From 03b44227bb098f77d3433dff63a12a67b0ac4cda Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Fri, 28 Nov 2025 13:56:26 +0000 Subject: [PATCH] deploy: 16bd0556c04607614760d0eadce7e2c2b8fec9ca --- .../iroh/endpoint/enum.DirectAddrType.html | 12 +- pr/3381/docs/iroh/endpoint/enum.Source.html | 12 +- .../docs/iroh/endpoint/struct.DirectAddr.html | 12 +- .../docs/iroh/endpoint/struct.PathInfo.html | 18 +- .../iroh/endpoint/struct.PathInfoList.html | 14 +- .../client/struct.ClientBuilder.html | 4 +- .../iroh_relay/dns/struct.DnsResolver.html | 8 +- .../endpoint_info/enum.DecodingError.html | 4 +- .../docs/iroh_relay/endpoint_info/index.html | 10 +- .../endpoint_info/struct.EndpointData.html | 18 +- .../endpoint_info/struct.EndpointInfo.html | 28 +- .../endpoint_info/trait.EndpointIdExt.html | 10 +- pr/3381/docs/iroh_relay/index.html | 2 +- .../protos/relay/enum.ClientToRelayMsg.html | 4 +- .../iroh_relay/protos/relay/enum.Error.html | 6 +- .../protos/relay/enum.RelayToClientMsg.html | 8 +- .../iroh_relay/server/enum.AccessConfig.html | 6 +- .../docs/iroh_relay/server/struct.Server.html | 4 +- .../docs/iroh_relay/struct.RelayConfig.html | 6 +- pr/3381/docs/iroh_relay/struct.RelayMap.html | 14 +- .../docs/search.index/path/8e8aa4077d4b.js | 1 - .../docs/search.index/path/cd9abbec06ea.js | 1 + pr/3381/docs/search.index/root.js | 2 +- pr/3381/docs/src/iroh/magicsock.rs.html | 2853 ++++++++--------- .../src/iroh/magicsock/remote_map.rs.html | 437 ++- .../magicsock/remote_map/remote_state.rs.html | 2425 +++++++------- .../src/iroh/magicsock/transports.rs.html | 131 +- .../trait.impl/core/convert/trait.From.js | 4 +- .../iter/traits/collect/trait.FromIterator.js | 4 +- 29 files changed, 3028 insertions(+), 3030 deletions(-) delete mode 100644 pr/3381/docs/search.index/path/8e8aa4077d4b.js create mode 100644 pr/3381/docs/search.index/path/cd9abbec06ea.js diff --git a/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html index cd2c999609..4b25bf7396 100644 --- a/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

DirectAddrType

Enum DirectAddrType 

Source
pub enum DirectAddrType {
+DirectAddrType in iroh::endpoint - Rust

DirectAddrType

Enum DirectAddrType 

Source
pub enum DirectAddrType {
     Unknown,
     Local,
     Qad,
@@ -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 endpoint. This indicates a situation like this, which still uses QAD to discover the public address.

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

Returns a duplicate 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 duplicate 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/3381/docs/iroh/endpoint/enum.Source.html b/pr/3381/docs/iroh/endpoint/enum.Source.html index 603e361bdf..b51d925531 100644 --- a/pr/3381/docs/iroh/endpoint/enum.Source.html +++ b/pr/3381/docs/iroh/endpoint/enum.Source.html @@ -1,4 +1,4 @@ -Source in iroh::endpoint - Rust

Source

Enum Source 

Source
pub enum Source {
+Source in iroh::endpoint - Rust

Source

Enum Source 

Source
pub enum Source {
     Udp,
     Relay,
     App,
@@ -39,12 +39,12 @@ address through multiple means.

Currently this means the path was in uses as PathId::ZERO when the a connection was added to the RemoteStateActor.

Fields

§_0: Private

private marker

-

Trait Implementations§

Source§

impl Clone for Source

Source§

fn clone(&self) -> Source

Returns a duplicate 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 duplicate 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/3381/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html index 867cc22a32..64fd67bd6d 100644 --- a/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html @@ -1,4 +1,4 @@ -DirectAddr in iroh::endpoint - Rust

DirectAddr

Struct DirectAddr 

Source
pub struct DirectAddr {
+DirectAddr in iroh::endpoint - Rust

DirectAddr

Struct DirectAddr 

Source
pub struct DirectAddr {
     pub addr: SocketAddr,
     pub typ: DirectAddrType,
 }
Expand description

A direct address on which an iroh-endpoint might be contactable.

@@ -9,16 +9,16 @@ iroh endpoint, see 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 duplicate 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 duplicate 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/3381/docs/iroh/endpoint/struct.PathInfo.html b/pr/3381/docs/iroh/endpoint/struct.PathInfo.html index 14fae744b1..c01b694d46 100644 --- a/pr/3381/docs/iroh/endpoint/struct.PathInfo.html +++ b/pr/3381/docs/iroh/endpoint/struct.PathInfo.html @@ -1,12 +1,12 @@ -PathInfo in iroh::endpoint - Rust

PathInfo

Struct PathInfo 

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

Information about a network path used by a Connection.

-

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

-
Source

pub fn is_selected(&self) -> bool

Returns true if this path is currently the main transmission path for this Connection.

-
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

-
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

-
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

-
Source

pub fn rtt(&self) -> Duration

Current best estimate of this paths’s latency (round-trip-time)

-

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

Returns a duplicate 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 PathInfo

Source§

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

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

impl PartialEq for PathInfo

Source§

fn eq(&self, other: &Self) -> 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 PathInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +PathInfo in iroh::endpoint - Rust

PathInfo

Struct PathInfo 

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

Information about a network path used by a Connection.

+

Implementations§

Source§

impl PathInfo

Source

pub fn remote_addr(&self) -> &TransportAddr

The remote transport address used by this network path.

+
Source

pub fn is_selected(&self) -> bool

Returns true if this path is currently the main transmission path for this Connection.

+
Source

pub fn is_ip(&self) -> bool

Whether this is an IP transport address.

+
Source

pub fn is_relay(&self) -> bool

Whether this is a transport address via a relay server.

+
Source

pub fn stats(&self) -> PathStats

Returns stats for this transmission path.

+
Source

pub fn rtt(&self) -> Duration

Current best estimate of this paths’s latency (round-trip-time)

+

Trait Implementations§

Source§

impl Clone for PathInfo

Source§

fn clone(&self) -> PathInfo

Returns a duplicate 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 PathInfo

Source§

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

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

impl PartialEq for PathInfo

Source§

fn eq(&self, other: &Self) -> 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 PathInfo

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/3381/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3381/docs/iroh/endpoint/struct.PathInfoList.html index 4418f2b674..d6aaf4918b 100644 --- a/pr/3381/docs/iroh/endpoint/struct.PathInfoList.html +++ b/pr/3381/docs/iroh/endpoint/struct.PathInfoList.html @@ -1,11 +1,11 @@ -PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

Source
pub struct PathInfoList(/* private fields */);
Expand description

List of PathInfo for the network paths of a Connection.

+PathInfoList in iroh::endpoint - Rust

PathInfoList

Struct PathInfoList 

Source
pub struct PathInfoList(/* private fields */);
Expand description

List of PathInfo for the network paths of a Connection.

This struct implements IntoIterator.

-

Implementations§

Source§

impl PathInfoList

Source

pub fn iter(&self) -> impl Iterator<Item = &PathInfo>

Returns an iterator over the path infos.

-
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

-
Source

pub fn len(&self) -> usize

Returns the number of paths.

-

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

Returns a duplicate 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 PathInfoList

Source§

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

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

impl IntoIterator for PathInfoList
where - SmallVec<[PathInfo; 4]>: IntoIterator,

Source§

type Item = <SmallVec<[PathInfo; 4]> as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <SmallVec<[PathInfo; 4]> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

fn eq(&self, other: &PathInfoList) -> 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 PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Implementations§

Source§

impl PathInfoList

Source

pub fn iter(&self) -> impl Iterator<Item = &PathInfo>

Returns an iterator over the path infos.

+
Source

pub fn is_empty(&self) -> bool

Returns true if the list is empty.

+
Source

pub fn len(&self) -> usize

Returns the number of paths.

+

Trait Implementations§

Source§

impl Clone for PathInfoList

Source§

fn clone(&self) -> PathInfoList

Returns a duplicate 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 PathInfoList

Source§

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

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

impl IntoIterator for PathInfoList
where + SmallVec<[PathInfo; 4]>: IntoIterator,

Source§

type Item = <SmallVec<[PathInfo; 4]> as IntoIterator>::Item

The type of the elements being iterated over.
Source§

type IntoIter = <SmallVec<[PathInfo; 4]> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for PathInfoList

Source§

fn eq(&self, other: &PathInfoList) -> 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 PathInfoList

Source§

impl StructuralPartialEq for PathInfoList

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/3381/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html index 822f6eb175..c66fab1488 100644 --- a/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html +++ b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html @@ -1,7 +1,7 @@ ClientBuilder in iroh_relay::client - Rust

ClientBuilder

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 address_family_selector<S>(self, selector: S) -> Self
where diff --git a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html index 919979e1b3..246ff55953 100644 --- a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html +++ b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html @@ -73,9 +73,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in summary of all errors otherwise.

Source

pub async fn lookup_endpoint_by_id( &self, - endpoint_id: &EndpointId, + endpoint_id: &EndpointId, origin: &str, -) -> Result<EndpointInfo, LookupError>

Looks up endpoint info by [EndpointId] and origin domain name.

+) -> Result<EndpointInfo, LookupError>

Looks up endpoint info by EndpointId and origin domain name.

To lookup endpoints that published their endpoint info to the DNS servers run by n0, pass N0_DNS_ENDPOINT_ORIGIN_PROD as origin.

Source

pub async fn lookup_endpoint_by_domain_name( @@ -93,10 +93,10 @@ at T+0ms, T+200ms and T+300ms. The result of the first successful call is return summary of all errors otherwise.

Source

pub async fn lookup_endpoint_by_id_staggered( &self, - endpoint_id: &EndpointId, + endpoint_id: &EndpointId, origin: &str, delays_ms: &[u64], -) -> Result<EndpointInfo, StaggeredError<LookupError>>

Looks up endpoint info by [EndpointId] and origin domain name.

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

Looks up endpoint info by EndpointId 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 diff --git a/pr/3381/docs/iroh_relay/endpoint_info/enum.DecodingError.html b/pr/3381/docs/iroh_relay/endpoint_info/enum.DecodingError.html index 86d2c6a6b7..daa76b8135 100644 --- a/pr/3381/docs/iroh_relay/endpoint_info/enum.DecodingError.html +++ b/pr/3381/docs/iroh_relay/endpoint_info/enum.DecodingError.html @@ -8,12 +8,12 @@ meta: Meta, }, InvalidKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, }

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.
§

InvalidEncodingZ32

Fields

§source: Z32Error
§meta: Meta

Captured call-site metadata

§

InvalidLength

Fields

§len: usize
§meta: Meta

Captured call-site metadata

-
§

InvalidKey

Fields

§source: KeyParsingError
§meta: Meta

Captured call-site metadata

+
§

InvalidKey

Fields

§meta: Meta

Captured call-site metadata

Trait Implementations§

Source§

impl Debug for DecodingError

Source§

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

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

impl Display for DecodingError

Source§

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

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

impl Error for DecodingError

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<DecodingError> for AnyError

Source§

fn from(value: DecodingError) -> AnyError

Converts to this type from the input type.
Source§

impl From<DecodingError> for ParseError

Source§

fn from(source: DecodingError) -> Self

Converts to this type from the input type.
Source§

impl StackError for DecodingError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

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/3381/docs/iroh_relay/endpoint_info/index.html b/pr/3381/docs/iroh_relay/endpoint_info/index.html index 4a43824b7c..9de61c4142 100644 --- a/pr/3381/docs/iroh_relay/endpoint_info/index.html +++ b/pr/3381/docs/iroh_relay/endpoint_info/index.html @@ -1,5 +1,5 @@ -iroh_relay::endpoint_info - Rust

Module endpoint_info

Module endpoint_info 

Source
Expand description

Support for handling DNS resource records for dialing by [EndpointId].

-

Dialing by [EndpointId] is supported by iroh endpoints publishing Pkarr records to DNS +iroh_relay::endpoint_info - Rust

Module endpoint_info

Module endpoint_info 

Source
Expand description

Support for handling DNS resource records for dialing by EndpointId.

+

Dialing by EndpointId is supported by iroh endpoints 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-endpoint-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-endpoint-id> is the z-base-32 encoding of the [EndpointId].

    +

    <z32-endpoint-id> is the z-base-32 encoding of the EndpointId.

  • <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 endpoint.

      +

      relay=<url>: The home RelayUrl of this endpoint.

    • addr=<addr> <addr>: A space-separated list of sockets addresses for this iroh endpoint. Each address is an IPv4 or IPv6 address with a port.

    -
  • Structs§

    EndpointData
    Data about an endpoint that may be published to and resolved from discovery services.
    EndpointInfo
    Information about an endpoint that may be published to and resolved from discovery services.
    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    EndpointIdExt
    Extension methods for [EndpointId] to encode to and decode from [z32], +

    Structs§

    EndpointData
    Data about an endpoint that may be published to and resolved from discovery services.
    EndpointInfo
    Information about an endpoint that may be published to and resolved from discovery services.
    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    EndpointIdExt
    Extension methods for EndpointId 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/3381/docs/iroh_relay/endpoint_info/struct.EndpointData.html b/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointData.html index 2d50b3f754..b6e5f6b39f 100644 --- a/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointData.html +++ b/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointData.html @@ -1,23 +1,23 @@ EndpointData in iroh_relay::endpoint_info - Rust

    EndpointData

    Struct EndpointData 

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

    Data about an endpoint 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 endpoint’s [EndpointId], only the data about a certain -endpoint. See EndpointInfo for a struct that contains a [EndpointId] with associated EndpointData.

    -

    Implementations§

    Source§

    impl EndpointData

    Source

    pub fn new(addrs: impl IntoIterator<Item = TransportAddr>) -> Self

    Creates a new EndpointData 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 endpoint data.

    +

    This struct does not include the endpoint’s EndpointId, only the data about a certain +endpoint. See EndpointInfo for a struct that contains a EndpointId with associated EndpointData.

    +

    Implementations§

    Source§

    impl EndpointData

    Source

    pub fn new(addrs: impl IntoIterator<Item = TransportAddr>) -> Self

    Creates a new EndpointData 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 endpoint data.

    Source

    pub fn with_ip_addrs(self, addresses: BTreeSet<SocketAddr>) -> Self

    Sets the direct addresses and returns the updated endpoint data.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated endpoint data.

    -
    Source

    pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the relay URL of the endpoint.

    +
    Source

    pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

    pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr>

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    +
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    +
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointData

    Source§

    fn clone(&self) -> EndpointData

    Returns a duplicate 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 EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

    fn eq(&self, other: &EndpointData) -> 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 EndpointData

    Source§

    fn clone(&self) -> EndpointData

    Returns a duplicate 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 EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

    fn eq(&self, other: &EndpointData) -> 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 EndpointData

    Source§

    impl StructuralPartialEq for EndpointData

    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/3381/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html b/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html index 7bdb2a8793..c6a136c7d7 100644 --- a/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html +++ b/pr/3381/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html @@ -1,17 +1,17 @@ EndpointInfo in iroh_relay::endpoint_info - Rust

    EndpointInfo

    Struct EndpointInfo 

    Source
    pub struct EndpointInfo {
    -    pub endpoint_id: EndpointId,
    +    pub endpoint_id: EndpointId,
         pub data: EndpointData,
     }
    Expand description

    Information about an endpoint that may be published to and resolved from discovery services.

    -

    This struct couples a [EndpointId] with its associated EndpointData.

    -

    Fields§

    §endpoint_id: EndpointId

    The [EndpointId] of the endpoint this is about.

    +

    This struct couples a EndpointId with its associated EndpointData.

    +

    Fields§

    §endpoint_id: EndpointId

    The EndpointId of the endpoint this is about.

    §data: EndpointData

    The information published about the endpoint.

    -

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    -
    Source

    pub fn from_parts(endpoint_id: EndpointId, data: EndpointData) -> Self

    Creates a new EndpointInfo from its parts.

    -
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated endpoint info.

    +

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    +
    Source

    pub fn from_parts(endpoint_id: EndpointId, data: EndpointData) -> Self

    Creates a new EndpointInfo from its parts.

    +
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated endpoint info.

    Source

    pub fn with_ip_addrs(self, addrs: BTreeSet<SocketAddr>) -> Self

    Sets the IP based addresses and returns the updated endpoint info.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated endpoint info.

    -
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

    Converts into a [EndpointAddr] by cloning the needed fields.

    -
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a [EndpointAddr] without cloning.

    +
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

    Converts into a EndpointAddr by cloning the needed fields.

    +
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a EndpointAddr without cloning.

    Source

    pub fn from_txt_lookup( domain_name: String, lookup: impl Iterator<Item = TxtRecordData>, @@ -21,21 +21,21 @@ ) -> Result<Self, ParseError>

    Parses a EndpointInfo 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 = EndpointData>§

    Source

    pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the relay URL of the endpoint.

    +

    Methods from Deref<Target = EndpointData>§

    Source

    pub fn relay_urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

    pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr>

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    +
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    +
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

    Returns a duplicate 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 EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

    fn eq(&self, other: &EndpointInfo) -> 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 EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

    Returns a duplicate 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 EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

    fn eq(&self, other: &EndpointInfo) -> 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 EndpointInfo

    Source§

    impl StructuralPartialEq for EndpointInfo

    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/3381/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html b/pr/3381/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html index 2cfafe8d14..103efb1882 100644 --- a/pr/3381/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html +++ b/pr/3381/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html @@ -1,9 +1,9 @@ EndpointIdExt in iroh_relay::endpoint_info - Rust

    EndpointIdExt

    Trait EndpointIdExt 

    Source
    pub trait EndpointIdExt {
         // Required methods
         fn to_z32(&self) -> String;
    -    fn from_z32(s: &str) -> Result<EndpointId, DecodingError>;
    -}
    Expand description

    Extension methods for [EndpointId] to encode to and decode from [z32], + fn from_z32(s: &str) -> Result<EndpointId, DecodingError>; +}

    Expand description

    Extension methods for EndpointId 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 [EndpointId] in z-base-32 encoding.

    -
    Source

    fn from_z32(s: &str) -> Result<EndpointId, DecodingError>

    Parses a [EndpointId] 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 EndpointIdExt for EndpointId

    Source§

    fn to_z32(&self) -> String

    Source§

    fn from_z32(s: &str) -> Result<EndpointId, DecodingError>

    Implementors§

    \ No newline at end of file +

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a EndpointId in z-base-32 encoding.

    +
    Source

    fn from_z32(s: &str) -> Result<EndpointId, DecodingError>

    Parses a EndpointId 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 EndpointIdExt for EndpointId

    Implementors§

    \ No newline at end of file diff --git a/pr/3381/docs/iroh_relay/index.html b/pr/3381/docs/iroh_relay/index.html index 9fd890b801..d16544ab4a 100644 --- a/pr/3381/docs/iroh_relay/index.html +++ b/pr/3381/docs/iroh_relay/index.html @@ -25,6 +25,6 @@ Tailscale.

    QAD 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
    endpoint_info
    Support for handling DNS resource records for dialing by [EndpointId].
    http
    HTTP-specific constants for the relay server and client.
    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
    endpoint_info
    Support for handling DNS resource records for dialing by EndpointId.
    http
    HTTP-specific constants for the relay server and client.
    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.
    RelayConfig
    Information on a specific relay server.
    RelayMap
    List of relay server configurations to be used in an iroh endpoint.
    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/3381/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html b/pr/3381/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html index c1f432fee0..e07e71e1c5 100644 --- a/pr/3381/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html +++ b/pr/3381/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html @@ -2,7 +2,7 @@ Ping([u8; 8]), Pong([u8; 8]), Datagrams { - dst_endpoint_id: EndpointId, + dst_endpoint_id: EndpointId, datagrams: Datagrams, }, }
    Expand description

    Messages that clients send to relays.

    @@ -11,7 +11,7 @@ other side with a §

    Pong([u8; 8])

    Reply to a RelayToClientMsg::Ping from a server with the payload sent previously in the ping.

    §

    Datagrams

    Request from the client to relay datagrams to given remote endpoint.

    -

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    +

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    §datagrams: Datagrams

    The datagrams and related metadata to relay.

    Trait Implementations§

    Source§

    impl Clone for ClientToRelayMsg

    Source§

    fn clone(&self) -> ClientToRelayMsg

    Returns a duplicate 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 ClientToRelayMsg

    Source§

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

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

    impl PartialEq for ClientToRelayMsg

    Source§

    fn eq(&self, other: &ClientToRelayMsg) -> 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 Sink<ClientToRelayMsg> 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/3381/docs/iroh_relay/protos/relay/enum.Error.html b/pr/3381/docs/iroh_relay/protos/relay/enum.Error.html index 9412db9658..27fca77b09 100644 --- a/pr/3381/docs/iroh_relay/protos/relay/enum.Error.html +++ b/pr/3381/docs/iroh_relay/protos/relay/enum.Error.html @@ -17,7 +17,7 @@ meta: Meta, }, InvalidPublicKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, InvalidFrame { @@ -39,12 +39,12 @@

    §

    FrameTooLarge

    Fields

    §frame_len: usize
    §meta: Meta

    Captured call-site metadata

    §

    SerDe

    Fields

    §source: Error
    §meta: Meta

    Captured call-site metadata

    §

    FrameTypeError

    Fields

    §meta: Meta

    Captured call-site metadata

    -
    §

    InvalidPublicKey

    Fields

    §source: KeyParsingError
    §meta: Meta

    Captured call-site metadata

    +
    §

    InvalidPublicKey

    Fields

    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrame

    Fields

    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrameType

    Fields

    §frame_type: FrameType
    §meta: Meta

    Captured call-site metadata

    §

    InvalidProtocolMessageEncoding

    Fields

    §source: Utf8Error
    §meta: Meta

    Captured call-site metadata

    §

    TooSmall

    Fields

    §meta: Meta

    Captured call-site metadata

    -

    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, f: &mut Formatter<'_>) -> Result

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

    impl Error for Error

    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<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

    fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

    Returns this error as a std error reference.
    Source§

    fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

    Returns the next source in the chain, if any.
    Source§

    fn meta(&self) -> Option<&Meta>

    Returns metadata captured at creation time, if available.
    Source§

    fn source(&self) -> Option<ErrorRef<'_>>

    Returns the next source in the chain, if any.
    Source§

    fn is_transparent(&self) -> bool

    Returns whether this error is transparent and should be skipped in reports.
    §

    fn as_ref(&self) -> ErrorRef<'_>

    Returns this error as an [ErrorRef]. Read more
    §

    fn stack(&self) -> Chain<'_>

    Returns an iterator over this error followed by its sources.
    §

    fn sources(&self) -> Chain<'_>

    Returns an iterator over sources of this error (skipping self).
    §

    fn report(&self) -> Report<'_>

    Returns a [Report] to output the error with configurable formatting.

    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 +

    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, f: &mut Formatter<'_>) -> Result

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

    impl Error for Error

    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<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

    fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

    Returns this error as a std error reference.
    Source§

    fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

    Returns the next source in the chain, if any.
    Source§

    fn meta(&self) -> Option<&Meta>

    Returns metadata captured at creation time, if available.
    Source§

    fn source(&self) -> Option<ErrorRef<'_>>

    Returns the next source in the chain, if any.
    Source§

    fn is_transparent(&self) -> bool

    Returns whether this error is transparent and should be skipped in reports.
    §

    fn as_ref(&self) -> ErrorRef<'_>

    Returns this error as an [ErrorRef]. Read more
    §

    fn stack(&self) -> Chain<'_>

    Returns an iterator over this error followed by its sources.
    §

    fn sources(&self) -> Chain<'_>

    Returns an iterator over sources of this error (skipping self).
    §

    fn report(&self) -> Report<'_>

    Returns a [Report] to output the error with configurable formatting.

    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 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/3381/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3381/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html index d3ffa9e17e..7858ef2c19 100644 --- a/pr/3381/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html +++ b/pr/3381/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html @@ -1,9 +1,9 @@ RelayToClientMsg in iroh_relay::protos::relay - Rust

    RelayToClientMsg

    Enum RelayToClientMsg 

    Source
    pub enum RelayToClientMsg {
         Datagrams {
    -        remote_endpoint_id: EndpointId,
    +        remote_endpoint_id: EndpointId,
             datagrams: Datagrams,
         },
    -    EndpointGone(EndpointId),
    +    EndpointGone(EndpointId),
         Health {
             problem: String,
         },
    @@ -15,9 +15,9 @@
         Pong([u8; 8]),
     }
    Expand description

    The messages that a relay sends to clients or the clients receive from the relay.

    Variants§

    §

    Datagrams

    Represents datagrams sent from relays (originally sent to them by another client).

    -

    Fields

    §remote_endpoint_id: EndpointId

    The [EndpointId] of the original sender.

    +

    Fields

    §remote_endpoint_id: EndpointId

    The EndpointId of the original sender.

    §datagrams: Datagrams

    The datagrams and related metadata.

    -
    §

    EndpointGone(EndpointId)

    Indicates that the client identified by the underlying public key had previously sent you a +

    §

    EndpointGone(EndpointId)

    Indicates that the client identified by the underlying public key had previously sent you a packet but has now disconnected from the relay.

    §

    Health

    A one-way message from relay to client, declaring the connection health state.

    Fields

    §problem: String

    If set, is a description of why the connection is unhealthy.

    diff --git a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html index 0c86262eed..28681a8228 100644 --- a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html +++ b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html @@ -1,10 +1,10 @@ AccessConfig in iroh_relay::server - Rust

    AccessConfig

    Enum AccessConfig 

    Source
    pub enum AccessConfig {
         Everyone,
    -    Restricted(Box<dyn Fn(EndpointId) -> Boxed<Access> + Send + Sync + 'static>),
    +    Restricted(Box<dyn Fn(EndpointId) -> Boxed<Access> + Send + Sync + 'static>),
     }
    Available on crate feature server only.
    Expand description

    Controls which endpoints are allowed to use the relay.

    Variants§

    §

    Everyone

    Everyone

    -
    §

    Restricted(Box<dyn Fn(EndpointId) -> Boxed<Access> + Send + Sync + 'static>)

    Only endpoints for which the function returns Access::Allow.

    -

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, endpoint: EndpointId) -> bool

    Is this endpoint allowed?

    +
    §

    Restricted(Box<dyn Fn(EndpointId) -> Boxed<Access> + Send + Sync + 'static>)

    Only endpoints for which the function returns Access::Allow.

    +

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, endpoint: EndpointId) -> bool

    Is this endpoint 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/3381/docs/iroh_relay/server/struct.Server.html b/pr/3381/docs/iroh_relay/server/struct.Server.html index 735121f652..2d8987915e 100644 --- a/pr/3381/docs/iroh_relay/server/struct.Server.html +++ b/pr/3381/docs/iroh_relay/server/struct.Server.html @@ -17,9 +17,9 @@ case there is an error in the server before it is shut down.

    Source

    pub fn http_addr(&self) -> Option<SocketAddr>

    The socket address the HTTP server is listening on.

    Source

    pub fn quic_addr(&self) -> Option<SocketAddr>

    The socket address the QUIC 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/3381/docs/iroh_relay/struct.RelayConfig.html b/pr/3381/docs/iroh_relay/struct.RelayConfig.html index 90f09dfa2e..4ba3e30d09 100644 --- a/pr/3381/docs/iroh_relay/struct.RelayConfig.html +++ b/pr/3381/docs/iroh_relay/struct.RelayConfig.html @@ -1,14 +1,14 @@ RelayConfig in iroh_relay - Rust

    RelayConfig

    Struct RelayConfig 

    Source
    pub struct RelayConfig {
    -    pub url: RelayUrl,
    +    pub url: RelayUrl,
         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.

    §quic: Option<RelayQuicConfig>

    Configuration to speak to the QUIC endpoint on the relay server.

    When None, we will not attempt to do QUIC address discovery with this relay server.

    Trait Implementations§

    Source§

    impl Clone for RelayConfig

    Source§

    fn clone(&self) -> RelayConfig

    Returns a duplicate 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 RelayConfig

    Source§

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

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

    impl<'de> Deserialize<'de> for RelayConfig

    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 RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayConfig>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

    fn cmp(&self, other: &RelayConfig) -> 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 RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayConfig>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

    fn cmp(&self, other: &RelayConfig) -> 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 RelayConfig

    Source§

    fn eq(&self, other: &RelayConfig) -> 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/3381/docs/iroh_relay/struct.RelayMap.html b/pr/3381/docs/iroh_relay/struct.RelayMap.html index 4e43ef401d..3a6131c7c6 100644 --- a/pr/3381/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3381/docs/iroh_relay/struct.RelayMap.html @@ -8,28 +8,28 @@ or by creating an empty relay map with let relay2 = RelayUrl::from_str("https://relay2.example.org").unwrap(); let map = RelayMap::from_iter(vec![relay1, relay2]);

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn empty() -> Self

    Creates an empty relay map.

    Source

    pub fn urls<T>(&self) -> T
    where - T: FromIterator<RelayUrl>,

    Returns the URLs of all servers in this relay map.

    + T: FromIterator<RelayUrl>,

    Returns the URLs of all servers in this relay map.

    This function is generic over the container to collect into. If you simply want a list of URLs, call this with map.urls::<Vec<_>>() to get a Vec<RelayUrl>.

    Source

    pub fn relays<T>(&self) -> T

    Returns a list with the RelayConfig for each relay in this relay map.

    This function is generic over the container to collect into. If you simply want a list of URLs, call this with map.relays::<Vec<_>>() to get a Vec<RelayConfig>.

    -
    Source

    pub fn contains(&self, url: &RelayUrl) -> bool

    Returns true if a relay with url is contained in this this relay map.

    -
    Source

    pub fn get(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Returns the config for a relay.

    +
    Source

    pub fn contains(&self, url: &RelayUrl) -> bool

    Returns true if a relay with url is contained in this this relay map.

    +
    Source

    pub fn get(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Returns the config for a relay.

    Source

    pub fn len(&self) -> usize

    Returns the number of relays in this relay map.

    Source

    pub fn is_empty(&self) -> bool

    Returns true if this relay map is empty.

    Source

    pub fn insert( &self, - url: RelayUrl, + url: RelayUrl, endpoint: Arc<RelayConfig>, ) -> Option<Arc<RelayConfig>>

    Inserts a new relay into the relay map.

    -
    Source

    pub fn remove(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Removes an existing relay by its URL.

    +
    Source

    pub fn remove(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Removes an existing relay by its URL.

    Source

    pub fn extend(&self, other: &RelayMap)

    Extends this RelayMap with another one.

    -

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

    Returns a duplicate 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<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> 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 duplicate 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<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> 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 RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    -
    Source§

    impl FromIterator<Arc<RelayConfig>> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = Arc<RelayConfig>>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayConfig>>(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<Arc<RelayConfig>> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = Arc<RelayConfig>>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayConfig>>(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 RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    Source§

    impl PartialEq for RelayMap

    Source§

    fn eq(&self, other: &Self) -> 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/3381/docs/search.index/path/8e8aa4077d4b.js b/pr/3381/docs/search.index/path/8e8aa4077d4b.js deleted file mode 100644 index 11d9967ec6..0000000000 --- a/pr/3381/docs/search.index/path/8e8aa4077d4b.js +++ /dev/null @@ -1 +0,0 @@ -rd_("f[1,\"\"]0Al[10,\"core::cmp\",\"core::cmp\"]Al[10,\"core::ops\",\"core::ops\"]Ce[5,\"clap_builder::util::id\",\"clap_builder::util::id\"]Bd[15,\"iroh_relay::client::DialError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Cg[5,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Eg[5,\"tower_http::follow_redirect::policy::or\",\"tower_http::follow_redirect::policy::or\"]77Ei[5,\"tower_http::follow_redirect::policy::and\",\"tower_http::follow_redirect::policy::and\"]A`[10,\"core::any\"]Ao[5,\"alloc::sync\",\"alloc::sync\"]Ba[5,\"alloc::boxed\",\"alloc::boxed\"]Cb[10,\"bytes::buf::buf_impl\",\"bytes::buf::buf_impl\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]9Am[5,\"n0_watcher\",\"n0_watcher\"]Am[5,\"iroh_bench\",\"iroh_bench\"]Bg[5,\"iroh_bench::s2n\",\"iroh_bench::s2n\"]A`[10,\"core::cmp\"]Ak[5,\"core::pin\",\"core::pin\"]Bg[15,\"iroh_relay::client::ConnectError\"]o[5,\"url\",\"url\"]Am[5,\"alloc::vec\",\"alloc::vec\"]Al[2,\"iroh::discovery::pkarr\"]j[2,\"iroh\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]00Ao[2,\"iroh::net_report::options\"]o[2,\"iroh_base\"]f[0,\"\"]A`[2,\"iroh_bench\"]4Ak[2,\"iroh_dns_server::http\"]555Ak[10,\"clap_builder::derive\"]>Af[10,\"core::ops::drop\"]Ad[10,\"core::convert\"]Aa[10,\"core::hash\"]1g[17,\"\"]Ci[5,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Be[5,\"n0_error::meta\",\"n0_error::meta\"]Cc[5,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Dg[5,\"hickory_proto::rr::domain::name\",\"hickory_proto::rr::domain::name\"]Ak[5,\"std::path\",\"std::path\"]Am[15,\"iroh::endpoint::Source\"]Bi[6,\"core::task::poll\",\"core::task::poll\"]Bb[10,\"core::marker\",\"core::marker\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]Ac[10,\"futures_sink\"]2Bf[15,\"iroh::discovery::DiscoveryError\"]Bj[15,\"iroh::discovery::IntoDiscoveryError\"]Bb[15,\"iroh::protocol::AcceptError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ah[10,\"ppv_lite86::types\"]f[1,\"\"]f[3,\"\"]Ah[2,\"iroh_relay::client\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]A`[2,\"iroh_bench\"]4Ae[2,\"iroh::discovery\"]Ad[2,\"iroh::defaults\"]4Bk[2,\"iroh_quinn_proto::connection::streams\"]88Bd[10,\"core::convert\",\"core::convert\"]Ca[8,\"futures_lite::future\",\"futures_lite::future\"]Ca[8,\"futures_lite::stream\",\"futures_lite::stream\"]Ba[5,\"bytes::bytes\",\"bytes::bytes\"]Ad[5,\"iroh::endpoint\"]Ab[10,\"core::clone\"]Cg[6,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Ao[10,\"iroh_quinn_proto::coding\"]A`[10,\"core::fmt\"]Ag[10,\"core::ops::deref\"]Ak[5,\"core::fmt\",\"core::fmt\"]Ab[10,\"core::error\"]Be[5,\"std::io::error\",\"std::io::error\"]Bc[6,\"rustls::error\",\"rustls::error\"]Ba[8,\"clap_builder\",\"clap_builder\"]Bi[5,\"signature::error\",\"signature::error\"]Af[2,\"iroh_relay::quic\"]Bc[2,\"iroh_relay::protos::handshake\"]Ao[2,\"iroh_relay::protos::relay\"]Ba[5,\"hyper::error\",\"hyper::error\"]Ee[6,\"iroh_quinn_proto::transport_parameters\",\"iroh_quinn_proto::transport_parameters\"]Be[5,\"reqwest::error\",\"reqwest::error\"]Bg[6,\"postcard::error\",\"postcard::error\"]Cg[6,\"tokio_websockets::error\",\"tokio_websockets::error\"]Bi[6,\"iroh_relay::quic\",\"iroh_relay::quic\"]Dc[6,\"iroh_relay::protos::handshake\",\"iroh_relay::protos::handshake\"]Ck[6,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ca[6,\"iroh::net_report\",\"iroh::net_report::probes\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bb[10,\"core::marker\",\"core::marker\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]Am[5,\"n0_watcher\",\"n0_watcher\"]2g[17,\"\"]f[1,\"\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ad[2,\"iroh::endpoint\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_bench\"]45Ae[2,\"iroh_dns_server\"]1Bb[2,\"iroh_quinn_proto::connection\"]177Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ac[10,\"core::borrow\"]C`[10,\"bytes::buf::buf_mut\",\"bytes::buf::buf_mut\"]Bc[5,\"pkarr::client\",\"pkarr::client\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ba[5,\"async_compat\",\"async_compat\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Cb[10,\"core::future::future\",\"core::future::future\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]An[10,\"core::hash\",\"core::hash\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Bm[6,\"core::net::ip_addr\",\"core::net::ip_addr\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Bh[10,\"reloadable_core\",\"reloadable_core\"]Be[15,\"iroh_relay::server::CertConfig\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Ad[5,\"iroh::endpoint\"]Ba[6,\"core::option\",\"core::option\"]g[17,\"\"]E`[10,\"tower_http::follow_redirect::policy\",\"tower_http::follow_redirect::policy\"]Ch[10,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Co[5,\"hickory_proto::rr::resource\",\"hickory_proto::rr::resource\"]Bl[15,\"iroh::endpoint::AfterHandshakeOutcome\"]Ca[5,\"iroh::net_report\",\"iroh::net_report::report\"]Ak[8,\"core::fmt\",\"core::fmt\"]Ba[6,\"core::result\",\"core::result\"]Be[8,\"std::io::error\",\"std::io::error\"]Ai[8,\"n0_error\",\"n0_error\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Cg[5,\"iroh_dns_server::server\",\"iroh_dns_server::server\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ad[2,\"iroh::endpoint\"]Cb[6,\"iroh::endpoint\",\"iroh::magicsock::remote_map\"]Ak[10,\"futures_core::stream\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Bc[5,\"alloc::string\",\"alloc::string\"]Ak[5,\"core::any\",\"core::any\"]Ci[5,\"iroh_quinn_proto::varint\",\"iroh_quinn_proto::varint\"]Ad[5,\"iroh::endpoint\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]A`[2,\"iroh_relay\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh_dns_server\"]1Af[2,\"iroh::net_report\"]40412Ae[10,\"iroh::endpoint\"]Bg[8,\"iroh_relay::dns\",\"iroh_relay::dns\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]De[5,\"clap_builder::builder::command\",\"clap_builder::builder::command\"]Bc[15,\"iroh::endpoint::ConnectError\"]An[15,\"iroh_relay::quic::Error\"]Bi[5,\"core::task::wake\",\"core::task::wake\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ad[10,\"core::default\"]A`[10,\"core::fmt\"]Bm[5,\"tokio::time::error\",\"tokio::time::error\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Bc[10,\"axum_core::extract::from_ref\"]Ah[10,\"core::str::traits\"]Ak[5,\"std::time\",\"std::time\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Cb[5,\"iroh::net_report\",\"iroh::net_report::metrics\"]Ci[5,\"iroh_dns_server::metrics\",\"iroh_dns_server::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ad[5,\"iroh::endpoint\"]Cg[5,\"iroh::net_report\",\"iroh::net_report::options::imp\"]Ak[5,\"std::path\",\"std::path\"]Bk[5,\"dyn_clone::sealed\",\"dyn_clone::sealed\"]Bo[5,\"tokio::io::read_buf\",\"tokio::io::read_buf\"]Eg[5,\"hickory_server::server::request_handler\",\"hickory_server::server::request_handler\"]B`[15,\"iroh_relay::dns::DnsError\"]Al[10,\"reqwest::dns::resolve\"]Cg[5,\"tokio::runtime::runtime\",\"tokio::runtime::runtime\"]Cj[10,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Bd[15,\"iroh_relay::client::DialError\"]4Ad[10,\"alloc::borrow\"]Ad[10,\"core::convert\"]0Bg[15,\"iroh_relay::client::ConnectError\"]k[10,\"iroh\"]>j[2,\"iroh\"]Af[2,\"iroh::net_report\"]Ah[2,\"iroh_relay::server\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]Ad[2,\"iroh::endpoint\"]Ad[2,\"iroh::defaults\"]Bb[2,\"iroh_quinn_proto::connection\"]5Ad[5,\"iroh::endpoint\"]Bc[5,\"n0_error::any\",\"n0_error::any\"]Ce[5,\"iroh_dns_server::state\",\"iroh_dns_server::state\"]De[5,\"alloc::collections::btree::set\",\"alloc::collections::btree::set\"]Ch[6,\"iroh_dns_server::http\",\"iroh_dns_server::http::tls\"]Am[6,\"iroh_bench\",\"iroh_bench\"]Ag[10,\"core::ops::deref\"]Ae[2,\"iroh_relay::dns\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]Am[5,\"core::time\",\"core::time\"]A`[10,\"dyn_clone\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]Ca[5,\"iroh_quinn::endpoint\",\"iroh_quinn::endpoint\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Bg[6,\"n0_error::error\",\"n0_error::error\"]3Ca[5,\"iroh_quinn::incoming\",\"iroh_quinn::incoming\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[5,\"core::net::ip_addr\",\"core::net::ip_addr\"]0Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Am[10,\"iroh_metrics::iterable\"]Db[10,\"core::iter::traits::iterator\",\"core::iter::traits::iterator\"]Am[15,\"iroh::endpoint::Source\"]An[10,\"n0_watcher\",\"n0_watcher\"]Ak[6,\"core::cmp\",\"core::cmp\"]D`[5,\"iroh::endpoint\",\"iroh::magicsock::remote_map::remote_state\"]Bd[15,\"iroh_relay::client::RecvError\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Ca[5,\"iroh_base::relay_url\",\"iroh_base::relay_url\"]2Bf[5,\"iroh_base\",\"iroh_base::relay_url\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Bh[10,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ad[5,\"iroh::endpoint\"]Ad[10,\"alloc::string\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]3Ae[5,\"iroh::discovery\"]1o[6,\"z32\",\"z32\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]1A`[2,\"iroh_quinn\"]2Ah[2,\"iroh_relay::server\"]B`[2,\"iroh::net_report::defaults\"]:Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Ci[5,\"tokio_rustls_acme::state\",\"tokio_rustls_acme::state\"]Ad[2,\"iroh::endpoint\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Al[10,\"tokio::io::async_read\"]2Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Ac[10,\"core::borrow\"]Ac[10,\"async_compat\"]Al[10,\"rand_core\",\"rand_core\"]Cb[15,\"iroh_relay::protos::relay::ClientToRelayMsg\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Ck[5,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ah[2,\"iroh_relay::client\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Am[15,\"iroh::endpoint::Source\"]B`[15,\"iroh::endpoint::BindError\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]0Ak[5,\"core::fmt\",\"core::fmt\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]Bg[15,\"iroh_relay::client::ConnectError\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ba[5,\"hdrhistogram\",\"hdrhistogram\"]Co[5,\"tokio::runtime::task::error\",\"tokio::runtime::task::error\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::discovery::DiscoveryError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]A`[10,\"core::cmp\"]Ad[5,\"iroh::endpoint\"]An[10,\"crossbeam_epoch::atomic\"]Bj[10,\"tower_http::follow_redirect::policy\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]j[5,\"iroh\"]B`[5,\"iroh_base\",\"iroh_base::key\"];Ad[6,\"iroh::endpoint\"]Ck[5,\"hickory_proto::rr::rr_set\",\"hickory_proto::rr::rr_set\"]Ck[5,\"tokio::sync::watch::error\",\"tokio::sync::watch::error\"]Ah[2,\"iroh_relay::client\"]Cc[6,\"iroh_relay::client\",\"iroh_relay::client::conn\"]Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Cc[8,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Be[5,\"iroh_base::key\",\"iroh_base::key\"]9843Af[10,\"serde_core::ser\"]:9Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ak[10,\"futures_core::future\"]Ak[10,\"futures_core::stream\"]Bi[5,\"core::str::error\",\"core::str::error\"]An[15,\"iroh_relay::quic::Error\"]Bg[15,\"iroh_relay::client::ConnectError\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Bn[5,\"iroh_dns_server\",\"iroh_dns_server::store\"]Bb[2,\"iroh_quinn_proto::connection\"]j[2,\"iroh\"]Ah[2,\"iroh_relay::protos\"]f[3,\"\"]2f[1,\"\"]A`[2,\"iroh_relay\"]o[2,\"iroh_base\"]Af[2,\"iroh::net_report\"]An[2,\"iroh_quinn_proto::config\"]Em[5,\"clap_builder::parser::matches::arg_matches\",\"clap_builder::parser::matches::arg_matches\"]Am[10,\"tokio::io::async_write\"]Ah[2,\"iroh_relay::server\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Aa[10,\"equivalent\"]Bc[15,\"iroh::endpoint::ConnectError\"]Bb[15,\"iroh::protocol::AcceptError\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Am[15,\"iroh::endpoint::Source\"]Cm[5,\"iroh::endpoint::connection\",\"iroh::endpoint::connection\"]43An[15,\"iroh_relay::quic::Error\"]Ce[5,\"iroh_quinn::connection\",\"iroh_quinn::connection\"]4Ae[10,\"iroh::endpoint\"]Bf[5,\"iroh::endpoint\",\"iroh::magicsock\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]Ak[8,\"iroh\",\"iroh_base::key\"]B`[8,\"iroh_base\",\"iroh_base::key\"]Be[8,\"iroh_base::key\",\"iroh_base::key\"]A`[10,\"hashbrown\"]?Ad[5,\"iroh::endpoint\"]Bm[5,\"http::header::name\",\"http::header::name\"]Cc[5,\"iroh_dns_server::http\",\"iroh_dns_server::http\"]0B`[10,\"core::future::into_future\"]Bi[15,\"iroh::endpoint_info::DecodingError\"]Bo[15,\"iroh_relay::endpoint_info::DecodingError\"]Bd[15,\"iroh_relay::client::DialError\"]B`[15,\"iroh::endpoint::BindError\"]Bm[5,\"iroh_metrics::base\",\"iroh_metrics::base\"]B`[15,\"iroh_relay::dns::DnsError\"]Bm[8,\"core::num::nonzero\",\"core::num::nonzero\"]Bb[15,\"iroh::protocol::AcceptError\"]Ae[2,\"iroh::discovery\"]Ao[6,\"url::parser\",\"url::parser\"]Bc[15,\"iroh_relay::dns::LookupError\"]Ao[2,\"iroh_relay::endpoint_info\"]Ae[6,\"iroh::discovery\"]Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]A`[10,\"core::cmp\"]Al[2,\"iroh::discovery::pkarr\"]Ce[6,\"iroh::discovery::pkarr\",\"iroh::discovery::pkarr\"]Bi[5,\"iroh_relay::quic\",\"iroh_relay::quic\"]Cd[5,\"iroh::net_report\",\"iroh::net_report::reportgen\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]De[6,\"hickory_proto::rr::record_type\",\"hickory_proto::rr::record_type\"]Ad[5,\"iroh::endpoint\"]Ad[6,\"iroh::endpoint\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]22Bh[10,\"serde_core::ser\",\"serde_core::ser\"]Ce[6,\"core::net::socket_addr\",\"core::net::socket_addr\"]Ah[2,\"iroh_relay::server\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Af[10,\"n0_error::error\"]Ba[5,\"http::status\",\"http::status\"]Ak[10,\"clap_builder::derive\"]Cj[10,\"iroh_quinn_proto::config\",\"iroh_quinn_proto::config\"]9Af[2,\"iroh_quinn_proto\"]Ad[2,\"iroh::endpoint\"]1A`[2,\"iroh_quinn\"]f[3,\"\"]00j[2,\"iroh\"]Ae[2,\"iroh::magicsock\"]10Ad[2,\"iroh::protocol\"]Be[6,\"iroh::protocol\",\"iroh::protocol\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Am[15,\"iroh::endpoint::Source\"]Co[5,\"rustls::server::server_conn\",\"rustls::server::server_conn\"]Am[5,\"iroh_bench\",\"iroh_bench\"]Ad[5,\"iroh::endpoint\"]Bc[5,\"data_encoding\",\"data_encoding\"]Ae[10,\"serde_core::de\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]o[5,\"iroh::dns\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]Bd[15,\"iroh_relay::client::SendError\"]Bo[5,\"http::header::value\",\"http::header::value\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]0Cc[5,\"iroh_dns_server::http\",\"iroh_dns_server::http\"]Do[5,\"iroh_quinn_proto::config::transport\",\"iroh_quinn_proto::config::transport\"]Be[15,\"iroh_relay::server::CertConfig\"]Ae[2,\"iroh_relay::dns\"]9B`[15,\"iroh_relay::dns::DnsError\"]Bg[15,\"iroh_relay::client::ConnectError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[5,\"iroh_relay\",\"iroh_relay::ping_tracker\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]6Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Bd[15,\"iroh_relay::client::RecvError\"]Bd[15,\"iroh_relay::client::SendError\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]B`[15,\"iroh::endpoint::AlpnError\"]Ci[5,\"ring::error::unspecified\",\"ring::error::unspecified\"]A`[2,\"iroh_quinn\"]0Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ce[5,\"rustls::crypto::signer\",\"rustls::crypto::signer\"]Co[5,\"rustls::client::client_conn\",\"rustls::client::client_conn\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ad[5,\"iroh::endpoint\"]Ad[2,\"iroh::endpoint\"]Ah[2,\"iroh_relay::client\"]Cm[6,\"iroh_quinn_proto::endpoint\",\"iroh_quinn_proto::endpoint\"]Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Ci[5,\"iroh_quinn_proto::shared\",\"iroh_quinn_proto::shared\"]Bf[10,\"serde_core::de\",\"serde_core::de\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ca[5,\"iroh::discovery::dns\",\"iroh::discovery::dns\"]Ci[5,\"iroh_base::endpoint_addr\",\"iroh_base::endpoint_addr\"]j[5,\"iroh\"]Bj[5,\"iroh_base\",\"iroh_base::endpoint_addr\"]Ae[5,\"iroh::discovery\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]10Bb[10,\"core::iter::traits::collect\"]Am[10,\"iroh_metrics::iterable\"]D`[10,\"core::iter::traits::collect\",\"core::iter::traits::collect\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Cg[5,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Bc[15,\"iroh_relay::dns::LookupError\"]Ai[10,\"iroh_metrics::base\"]D`[5,\"iroh::endpoint\",\"iroh::magicsock::remote_map::remote_state\"]Bd[15,\"iroh_relay::client::DialError\"]Ad[5,\"iroh::endpoint\"]Ac[5,\"iroh::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Cg[5,\"hickory_resolver::error\",\"hickory_resolver::error\"]Do[5,\"iroh_quinn_proto::connection::paths\",\"iroh_quinn_proto::connection::paths\"]Co[5,\"rustls::server::server_conn\",\"rustls::server::server_conn\"]5Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ca[5,\"pkarr::signed_packet\",\"pkarr::signed_packet\"]Ce[5,\"core::net::socket_addr\",\"core::net::socket_addr\"]0Ad[6,\"iroh::endpoint\"]A`[2,\"iroh_relay\"]Ba[2,\"iroh::magicsock::remote_map\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ab[10,\"core::clone\"]Bb[15,\"iroh::discovery::ParseError\"]Ai[2,\"iroh::endpoint_info\"]Ao[2,\"iroh_relay::endpoint_info\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ai[6,\"iroh::endpoint_info\"]Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Bg[5,\"iroh::discovery\",\"iroh::discovery\"]5421Bm[10,\"iroh::endpoint\",\"iroh::endpoint::hooks\"]Aj[10,\"iroh::endpoint_info\"]Cl[10,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Bi[15,\"iroh::endpoint_info::DecodingError\"]Bo[15,\"iroh_relay::endpoint_info::DecodingError\"]Cc[5,\"iroh::discovery::mdns\",\"iroh::discovery::mdns\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Ce[5,\"iroh::discovery::pkarr\",\"iroh::discovery::pkarr\"]Bi[6,\"rustls_pki_types\",\"rustls_pki_types\"]Eo[6,\"iroh_quinn_proto::connection::streams::recv\",\"iroh_quinn_proto::connection::streams::recv\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Ci[6,\"iroh_base::endpoint_addr\",\"iroh_base::endpoint_addr\"]j[6,\"iroh\"]Bj[6,\"iroh_base\",\"iroh_base::endpoint_addr\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ca[15,\"iroh_relay::protos::common::FrameTypeError\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Ci[5,\"iroh_quinn_proto::coding\",\"iroh_quinn_proto::coding\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]o[2,\"iroh_base\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]Ak[2,\"iroh_dns_server::http\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Bi[5,\"rustls_pki_types\",\"rustls_pki_types\"]Ak[10,\"clap_builder::derive\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bf[6,\"iroh::endpoint\",\"iroh::magicsock\"]Ae[2,\"iroh::discovery\"]Bg[6,\"iroh::discovery\",\"iroh::discovery\"]Ak[2,\"iroh::discovery::mdns\"]Cc[6,\"iroh::discovery::mdns\",\"iroh::discovery::mdns\"]D`[5,\"iroh::test_utils\",\"iroh::test_utils::dns_and_pkarr_servers\"]B`[2,\"iroh_relay::protos::common\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]Af[10,\"core::ops::drop\"]Ad[10,\"core::convert\"]Aa[10,\"core::hash\"]1g[17,\"\"]Ci[5,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Be[5,\"n0_error::meta\",\"n0_error::meta\"]Cc[5,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Dg[5,\"hickory_proto::rr::domain::name\",\"hickory_proto::rr::domain::name\"]Ak[5,\"std::path\",\"std::path\"]Am[15,\"iroh::endpoint::Source\"]Bi[6,\"core::task::poll\",\"core::task::poll\"]Bb[10,\"core::marker\",\"core::marker\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]Ac[10,\"futures_sink\"]2Bf[15,\"iroh::discovery::DiscoveryError\"]Bj[15,\"iroh::discovery::IntoDiscoveryError\"]Bb[15,\"iroh::protocol::AcceptError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ah[10,\"ppv_lite86::types\"]f[1,\"\"]f[3,\"\"]Ah[2,\"iroh_relay::client\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]A`[2,\"iroh_bench\"]4Ae[2,\"iroh::discovery\"]Ad[2,\"iroh::defaults\"]4Bk[2,\"iroh_quinn_proto::connection::streams\"]88Ad[10,\"core::convert\"]Ca[8,\"futures_lite::future\",\"futures_lite::future\"]Ca[8,\"futures_lite::stream\",\"futures_lite::stream\"]Ba[5,\"bytes::bytes\",\"bytes::bytes\"]Ad[5,\"iroh::endpoint\"]Ab[10,\"core::clone\"]Cg[6,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Ao[10,\"iroh_quinn_proto::coding\"]A`[10,\"core::fmt\"]Ag[10,\"core::ops::deref\"]Ak[5,\"core::fmt\",\"core::fmt\"]Ab[10,\"core::error\"]Be[5,\"std::io::error\",\"std::io::error\"]Bc[6,\"rustls::error\",\"rustls::error\"]Ba[8,\"clap_builder\",\"clap_builder\"]Bi[5,\"signature::error\",\"signature::error\"]Af[2,\"iroh_relay::quic\"]Bc[2,\"iroh_relay::protos::handshake\"]Ao[2,\"iroh_relay::protos::relay\"]Ba[5,\"hyper::error\",\"hyper::error\"]Ee[6,\"iroh_quinn_proto::transport_parameters\",\"iroh_quinn_proto::transport_parameters\"]Be[5,\"reqwest::error\",\"reqwest::error\"]Bg[6,\"postcard::error\",\"postcard::error\"]Cg[6,\"tokio_websockets::error\",\"tokio_websockets::error\"]Bi[6,\"iroh_relay::quic\",\"iroh_relay::quic\"]Dc[6,\"iroh_relay::protos::handshake\",\"iroh_relay::protos::handshake\"]Ck[6,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ca[6,\"iroh::net_report\",\"iroh::net_report::probes\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bb[10,\"core::marker\",\"core::marker\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]Am[5,\"n0_watcher\",\"n0_watcher\"]2g[17,\"\"]f[1,\"\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ad[2,\"iroh::endpoint\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_bench\"]45Ae[2,\"iroh_dns_server\"]1Bb[2,\"iroh_quinn_proto::connection\"]177Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ac[10,\"core::borrow\"]C`[10,\"bytes::buf::buf_mut\",\"bytes::buf::buf_mut\"]Bc[5,\"pkarr::client\",\"pkarr::client\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ba[5,\"async_compat\",\"async_compat\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Cb[10,\"core::future::future\",\"core::future::future\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]An[10,\"core::hash\",\"core::hash\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Bm[6,\"core::net::ip_addr\",\"core::net::ip_addr\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Bh[10,\"reloadable_core\",\"reloadable_core\"]Be[15,\"iroh_relay::server::CertConfig\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Ad[5,\"iroh::endpoint\"]Ba[6,\"core::option\",\"core::option\"]g[17,\"\"]E`[10,\"tower_http::follow_redirect::policy\",\"tower_http::follow_redirect::policy\"]Ch[10,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Co[5,\"hickory_proto::rr::resource\",\"hickory_proto::rr::resource\"]Bl[15,\"iroh::endpoint::AfterHandshakeOutcome\"]Ca[5,\"iroh::net_report\",\"iroh::net_report::report\"]Ak[8,\"core::fmt\",\"core::fmt\"]Ba[6,\"core::result\",\"core::result\"]Be[8,\"std::io::error\",\"std::io::error\"]Ai[8,\"n0_error\",\"n0_error\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Cg[5,\"iroh_dns_server::server\",\"iroh_dns_server::server\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ad[2,\"iroh::endpoint\"]Cb[6,\"iroh::endpoint\",\"iroh::magicsock::remote_map\"]Ak[10,\"futures_core::stream\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Bc[5,\"alloc::string\",\"alloc::string\"]Ak[5,\"core::any\",\"core::any\"]Ci[5,\"iroh_quinn_proto::varint\",\"iroh_quinn_proto::varint\"]Ad[5,\"iroh::endpoint\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]A`[2,\"iroh_relay\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh_dns_server\"]1Af[2,\"iroh::net_report\"]40412Ae[10,\"iroh::endpoint\"]Bg[8,\"iroh_relay::dns\",\"iroh_relay::dns\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]De[5,\"clap_builder::builder::command\",\"clap_builder::builder::command\"]Bc[15,\"iroh::endpoint::ConnectError\"]An[15,\"iroh_relay::quic::Error\"]Bi[5,\"core::task::wake\",\"core::task::wake\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ad[10,\"core::default\"]A`[10,\"core::fmt\"]Bm[5,\"tokio::time::error\",\"tokio::time::error\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Bc[10,\"axum_core::extract::from_ref\"]Ah[10,\"core::str::traits\"]Ak[5,\"std::time\",\"std::time\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Cb[5,\"iroh::net_report\",\"iroh::net_report::metrics\"]Ci[5,\"iroh_dns_server::metrics\",\"iroh_dns_server::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ad[5,\"iroh::endpoint\"]Cg[5,\"iroh::net_report\",\"iroh::net_report::options::imp\"]Ak[5,\"std::path\",\"std::path\"]Bk[5,\"dyn_clone::sealed\",\"dyn_clone::sealed\"]Bo[5,\"tokio::io::read_buf\",\"tokio::io::read_buf\"]Eg[5,\"hickory_server::server::request_handler\",\"hickory_server::server::request_handler\"]B`[15,\"iroh_relay::dns::DnsError\"]Al[10,\"reqwest::dns::resolve\"]Cg[5,\"tokio::runtime::runtime\",\"tokio::runtime::runtime\"]Cj[10,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Bd[15,\"iroh_relay::client::DialError\"]4Ad[10,\"alloc::borrow\"]Ad[10,\"core::convert\"]0Bg[15,\"iroh_relay::client::ConnectError\"]k[10,\"iroh\"]>j[2,\"iroh\"]Af[2,\"iroh::net_report\"]Ah[2,\"iroh_relay::server\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]Ad[2,\"iroh::endpoint\"]Ad[2,\"iroh::defaults\"]Bb[2,\"iroh_quinn_proto::connection\"]5Ad[5,\"iroh::endpoint\"]Bc[5,\"n0_error::any\",\"n0_error::any\"]Ce[5,\"iroh_dns_server::state\",\"iroh_dns_server::state\"]De[5,\"alloc::collections::btree::set\",\"alloc::collections::btree::set\"]Ch[6,\"iroh_dns_server::http\",\"iroh_dns_server::http::tls\"]Am[6,\"iroh_bench\",\"iroh_bench\"]Ag[10,\"core::ops::deref\"]Ae[2,\"iroh_relay::dns\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]Am[5,\"core::time\",\"core::time\"]A`[10,\"dyn_clone\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]Ca[5,\"iroh_quinn::endpoint\",\"iroh_quinn::endpoint\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Bg[6,\"n0_error::error\",\"n0_error::error\"]3Ca[5,\"iroh_quinn::incoming\",\"iroh_quinn::incoming\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[5,\"core::net::ip_addr\",\"core::net::ip_addr\"]0Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Am[10,\"iroh_metrics::iterable\"]Db[10,\"core::iter::traits::iterator\",\"core::iter::traits::iterator\"]Am[15,\"iroh::endpoint::Source\"]An[10,\"n0_watcher\",\"n0_watcher\"]Ak[6,\"core::cmp\",\"core::cmp\"]D`[5,\"iroh::endpoint\",\"iroh::magicsock::remote_map::remote_state\"]Bd[15,\"iroh_relay::client::RecvError\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Ca[5,\"iroh_base::relay_url\",\"iroh_base::relay_url\"]2Bf[5,\"iroh_base\",\"iroh_base::relay_url\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Bh[10,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ad[5,\"iroh::endpoint\"]Ad[10,\"alloc::string\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]3Ae[5,\"iroh::discovery\"]1o[6,\"z32\",\"z32\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]1A`[2,\"iroh_quinn\"]2Ah[2,\"iroh_relay::server\"]B`[2,\"iroh::net_report::defaults\"]:Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Ci[5,\"tokio_rustls_acme::state\",\"tokio_rustls_acme::state\"]Ad[2,\"iroh::endpoint\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Al[10,\"tokio::io::async_read\"]2Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Ac[10,\"core::borrow\"]Ac[10,\"async_compat\"]Al[10,\"rand_core\",\"rand_core\"]Cb[15,\"iroh_relay::protos::relay::ClientToRelayMsg\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Ck[5,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ah[2,\"iroh_relay::client\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Am[15,\"iroh::endpoint::Source\"]B`[15,\"iroh::endpoint::BindError\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]0Ak[5,\"core::fmt\",\"core::fmt\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]Bg[15,\"iroh_relay::client::ConnectError\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ba[5,\"hdrhistogram\",\"hdrhistogram\"]Co[5,\"tokio::runtime::task::error\",\"tokio::runtime::task::error\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::discovery::DiscoveryError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]A`[10,\"core::cmp\"]Ad[5,\"iroh::endpoint\"]An[10,\"crossbeam_epoch::atomic\"]Bj[10,\"tower_http::follow_redirect::policy\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]j[5,\"iroh\"]B`[5,\"iroh_base\",\"iroh_base::key\"];Ad[6,\"iroh::endpoint\"]Ck[5,\"hickory_proto::rr::rr_set\",\"hickory_proto::rr::rr_set\"]Ck[5,\"tokio::sync::watch::error\",\"tokio::sync::watch::error\"]Ah[2,\"iroh_relay::client\"]Cc[6,\"iroh_relay::client\",\"iroh_relay::client::conn\"]Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Cc[8,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Be[5,\"iroh_base::key\",\"iroh_base::key\"]9843Af[10,\"serde_core::ser\"]:9Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ak[10,\"futures_core::future\"]Ak[10,\"futures_core::stream\"]Bi[5,\"core::str::error\",\"core::str::error\"]An[15,\"iroh_relay::quic::Error\"]Bg[15,\"iroh_relay::client::ConnectError\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Bn[5,\"iroh_dns_server\",\"iroh_dns_server::store\"]Bb[2,\"iroh_quinn_proto::connection\"]j[2,\"iroh\"]Ah[2,\"iroh_relay::protos\"]f[3,\"\"]2f[1,\"\"]A`[2,\"iroh_relay\"]o[2,\"iroh_base\"]Af[2,\"iroh::net_report\"]An[2,\"iroh_quinn_proto::config\"]Em[5,\"clap_builder::parser::matches::arg_matches\",\"clap_builder::parser::matches::arg_matches\"]Am[10,\"tokio::io::async_write\"]Ah[2,\"iroh_relay::server\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Aa[10,\"equivalent\"]Bc[15,\"iroh::endpoint::ConnectError\"]Bb[15,\"iroh::protocol::AcceptError\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Am[15,\"iroh::endpoint::Source\"]Cm[5,\"iroh::endpoint::connection\",\"iroh::endpoint::connection\"]43An[15,\"iroh_relay::quic::Error\"]Ce[5,\"iroh_quinn::connection\",\"iroh_quinn::connection\"]4Ae[10,\"iroh::endpoint\"]Bf[5,\"iroh::endpoint\",\"iroh::magicsock\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]Ak[8,\"iroh\",\"iroh_base::key\"]B`[8,\"iroh_base\",\"iroh_base::key\"]Be[8,\"iroh_base::key\",\"iroh_base::key\"]A`[10,\"hashbrown\"]?Ad[5,\"iroh::endpoint\"]Bm[5,\"http::header::name\",\"http::header::name\"]Cc[5,\"iroh_dns_server::http\",\"iroh_dns_server::http\"]0B`[10,\"core::future::into_future\"]Bi[15,\"iroh::endpoint_info::DecodingError\"]Bo[15,\"iroh_relay::endpoint_info::DecodingError\"]Bd[15,\"iroh_relay::client::DialError\"]B`[15,\"iroh::endpoint::BindError\"]Bm[5,\"iroh_metrics::base\",\"iroh_metrics::base\"]B`[15,\"iroh_relay::dns::DnsError\"]Bm[8,\"core::num::nonzero\",\"core::num::nonzero\"]Bb[15,\"iroh::protocol::AcceptError\"]Ae[2,\"iroh::discovery\"]Ao[6,\"url::parser\",\"url::parser\"]Bc[15,\"iroh_relay::dns::LookupError\"]Ao[2,\"iroh_relay::endpoint_info\"]Ae[6,\"iroh::discovery\"]Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]A`[10,\"core::cmp\"]Al[2,\"iroh::discovery::pkarr\"]Ce[6,\"iroh::discovery::pkarr\",\"iroh::discovery::pkarr\"]Bi[5,\"iroh_relay::quic\",\"iroh_relay::quic\"]Cd[5,\"iroh::net_report\",\"iroh::net_report::reportgen\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]De[6,\"hickory_proto::rr::record_type\",\"hickory_proto::rr::record_type\"]Ad[5,\"iroh::endpoint\"]Ad[6,\"iroh::endpoint\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]22Bh[10,\"serde_core::ser\",\"serde_core::ser\"]Ce[6,\"core::net::socket_addr\",\"core::net::socket_addr\"]Ah[2,\"iroh_relay::server\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Af[10,\"n0_error::error\"]Ba[5,\"http::status\",\"http::status\"]Ak[10,\"clap_builder::derive\"]Cj[10,\"iroh_quinn_proto::config\",\"iroh_quinn_proto::config\"]9Af[2,\"iroh_quinn_proto\"]Ad[2,\"iroh::endpoint\"]1A`[2,\"iroh_quinn\"]f[3,\"\"]00j[2,\"iroh\"]Ae[2,\"iroh::magicsock\"]10Ad[2,\"iroh::protocol\"]Be[6,\"iroh::protocol\",\"iroh::protocol\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Am[15,\"iroh::endpoint::Source\"]Co[5,\"rustls::server::server_conn\",\"rustls::server::server_conn\"]Am[5,\"iroh_bench\",\"iroh_bench\"]Ad[5,\"iroh::endpoint\"]Bc[5,\"data_encoding\",\"data_encoding\"]Ae[10,\"serde_core::de\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]o[5,\"iroh::dns\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]Bd[15,\"iroh_relay::client::SendError\"]Bo[5,\"http::header::value\",\"http::header::value\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]0Cc[5,\"iroh_dns_server::http\",\"iroh_dns_server::http\"]Do[5,\"iroh_quinn_proto::config::transport\",\"iroh_quinn_proto::config::transport\"]Be[15,\"iroh_relay::server::CertConfig\"]Ae[2,\"iroh_relay::dns\"]9B`[15,\"iroh_relay::dns::DnsError\"]Bg[15,\"iroh_relay::client::ConnectError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[5,\"iroh_relay\",\"iroh_relay::ping_tracker\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]6Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Bd[15,\"iroh_relay::client::RecvError\"]Bd[15,\"iroh_relay::client::SendError\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]B`[15,\"iroh::endpoint::AlpnError\"]Ci[5,\"ring::error::unspecified\",\"ring::error::unspecified\"]A`[2,\"iroh_quinn\"]0Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ce[5,\"rustls::crypto::signer\",\"rustls::crypto::signer\"]Co[5,\"rustls::client::client_conn\",\"rustls::client::client_conn\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ad[5,\"iroh::endpoint\"]Ad[2,\"iroh::endpoint\"]Ah[2,\"iroh_relay::client\"]Cm[6,\"iroh_quinn_proto::endpoint\",\"iroh_quinn_proto::endpoint\"]Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Ci[5,\"iroh_quinn_proto::shared\",\"iroh_quinn_proto::shared\"]Bf[10,\"serde_core::de\",\"serde_core::de\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ca[5,\"iroh::discovery::dns\",\"iroh::discovery::dns\"]Ci[5,\"iroh_base::endpoint_addr\",\"iroh_base::endpoint_addr\"]j[5,\"iroh\"]Bj[5,\"iroh_base\",\"iroh_base::endpoint_addr\"]Ae[5,\"iroh::discovery\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]10Bb[10,\"core::iter::traits::collect\"]Am[10,\"iroh_metrics::iterable\"]D`[10,\"core::iter::traits::collect\",\"core::iter::traits::collect\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Cg[5,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Bc[15,\"iroh_relay::dns::LookupError\"]Ai[10,\"iroh_metrics::base\"]D`[5,\"iroh::endpoint\",\"iroh::magicsock::remote_map::remote_state\"]Bd[15,\"iroh_relay::client::DialError\"]Ad[5,\"iroh::endpoint\"]Ac[5,\"iroh::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Cg[5,\"hickory_resolver::error\",\"hickory_resolver::error\"]Do[5,\"iroh_quinn_proto::connection::paths\",\"iroh_quinn_proto::connection::paths\"]Co[5,\"rustls::server::server_conn\",\"rustls::server::server_conn\"]5Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ca[5,\"pkarr::signed_packet\",\"pkarr::signed_packet\"]Ce[5,\"core::net::socket_addr\",\"core::net::socket_addr\"]0Ad[6,\"iroh::endpoint\"]A`[2,\"iroh_relay\"]Ba[2,\"iroh::magicsock::remote_map\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ab[10,\"core::clone\"]Bb[15,\"iroh::discovery::ParseError\"]Ai[2,\"iroh::endpoint_info\"]Ao[2,\"iroh_relay::endpoint_info\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ai[6,\"iroh::endpoint_info\"]Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Bg[5,\"iroh::discovery\",\"iroh::discovery\"]5421Bm[10,\"iroh::endpoint\",\"iroh::endpoint::hooks\"]Aj[10,\"iroh::endpoint_info\"]Cl[10,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Bi[15,\"iroh::endpoint_info::DecodingError\"]Bo[15,\"iroh_relay::endpoint_info::DecodingError\"]Cc[5,\"iroh::discovery::mdns\",\"iroh::discovery::mdns\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Ce[5,\"iroh::discovery::pkarr\",\"iroh::discovery::pkarr\"]Bi[6,\"rustls_pki_types\",\"rustls_pki_types\"]Eo[6,\"iroh_quinn_proto::connection::streams::recv\",\"iroh_quinn_proto::connection::streams::recv\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Ci[6,\"iroh_base::endpoint_addr\",\"iroh_base::endpoint_addr\"]j[6,\"iroh\"]Bj[6,\"iroh_base\",\"iroh_base::endpoint_addr\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ca[15,\"iroh_relay::protos::common::FrameTypeError\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Ci[5,\"iroh_quinn_proto::coding\",\"iroh_quinn_proto::coding\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]o[2,\"iroh_base\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]Ak[2,\"iroh_dns_server::http\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Bi[5,\"rustls_pki_types\",\"rustls_pki_types\"]Ak[10,\"clap_builder::derive\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bf[6,\"iroh::endpoint\",\"iroh::magicsock\"]Ae[2,\"iroh::discovery\"]Bg[6,\"iroh::discovery\",\"iroh::discovery\"]Ak[2,\"iroh::discovery::mdns\"]Cc[6,\"iroh::discovery::mdns\",\"iroh::discovery::mdns\"]D`[5,\"iroh::test_utils\",\"iroh::test_utils::dns_and_pkarr_servers\"]B`[2,\"iroh_relay::protos::common\"]Bk[15,\"iroh_relay::protos::handshake::Error\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]850 secret_key.public(), 851 metrics.magicsock.clone(), 852 direct_addrs.addrs.watch(), -853 transports.create_sender(), -854 discovery.clone(), -855 ) -856 }; -857 -858 let msock = Arc::new(MagicSock { -859 public_key: secret_key.public(), -860 closing: AtomicBool::new(false), -861 closed: AtomicBool::new(false), -862 actor_sender: actor_sender.clone(), -863 ipv6_reported, -864 remote_map, -865 discovery, -866 relay_map: relay_map.clone(), -867 discovery_user_data: RwLock::new(discovery_user_data), -868 direct_addrs, -869 net_report: Watchable::new((None, UpdateReason::None)), -870 #[cfg(not(wasm_browser))] -871 dns_resolver: dns_resolver.clone(), -872 metrics: metrics.clone(), -873 local_addrs_watch: transports.local_addrs_watch(), -874 #[cfg(not(wasm_browser))] -875 ip_bind_addrs: transports.ip_bind_addrs(), -876 hooks, -877 }); -878 -879 let mut endpoint_config = quinn::EndpointConfig::default(); -880 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit -881 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -882 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -883 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore -884 // the packet if grease_quic_bit is set to false. -885 endpoint_config.grease_quic_bit(false); -886 -887 let local_addrs_watch = transports.local_addrs_watch(); -888 let network_change_sender = transports.create_network_change_sender(); -889 -890 let endpoint = quinn::Endpoint::new_with_abstract_socket( -891 endpoint_config, -892 Some(server_config), -893 Box::new(MagicTransport::new(msock.clone(), transports)), -894 #[cfg(not(wasm_browser))] -895 Arc::new(quinn::TokioRuntime), -896 #[cfg(wasm_browser)] -897 Arc::new(crate::web_runtime::WebRuntime), -898 ) -899 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; -900 -901 let network_monitor = netmon::Monitor::new() -902 .await -903 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; -904 -905 let qad_endpoint = endpoint.clone(); -906 -907 #[cfg(any(test, feature = "test-utils"))] -908 let client_config = if insecure_skip_relay_cert_verify { -909 iroh_relay::client::make_dangerous_client_config() -910 } else { -911 default_quic_client_config() -912 }; -913 #[cfg(not(any(test, feature = "test-utils")))] -914 let client_config = default_quic_client_config(); -915 -916 let net_report_config = net_report::Options::default(); -917 #[cfg(not(wasm_browser))] -918 let net_report_config = net_report_config.quic_config(Some(QuicConfig { -919 ep: qad_endpoint, -920 client_config, -921 ipv4: true, -922 ipv6, -923 })); -924 -925 #[cfg(any(test, feature = "test-utils"))] -926 let net_report_config = -927 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); -928 -929 let net_reporter = net_report::Client::new( -930 #[cfg(not(wasm_browser))] -931 dns_resolver, -932 relay_map.clone(), -933 net_report_config, -934 metrics.net_report.clone(), -935 ); -936 -937 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -938 let direct_addr_update_state = DirectAddrUpdateState::new( -939 msock.clone(), -940 #[cfg(not(wasm_browser))] -941 port_mapper, -942 Arc::new(AsyncMutex::new(net_reporter)), -943 relay_map, -944 direct_addr_done_tx, -945 ); -946 -947 let netmon_watcher = network_monitor.interface_state(); -948 -949 #[cfg_attr(not(wasm_browser), allow(unused_mut))] -950 let mut actor = Actor { -951 msg_receiver: actor_receiver, -952 msock: msock.clone(), -953 periodic_re_stun_timer: new_re_stun_timer(false), -954 network_monitor, -955 netmon_watcher, -956 direct_addr_update_state, -957 network_change_sender, -958 direct_addr_done_rx, -959 }; -960 // Initialize addresses -961 #[cfg(not(wasm_browser))] -962 actor.update_direct_addresses(None); -963 -964 let actor_task = task::spawn( -965 actor -966 .run(shutdown_token.child_token(), local_addrs_watch) -967 .instrument(info_span!("actor")), -968 ); -969 -970 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); -971 -972 Ok(Handle { -973 msock, -974 actor_task, -975 endpoint, -976 shutdown_token, -977 }) -978 } -979 -980 /// The underlying [`quinn::Endpoint`] -981 pub fn endpoint(&self) -> &quinn::Endpoint { -982 &self.endpoint -983 } -984 -985 /// Closes the connection. -986 /// -987 /// Only the first close does anything. Any later closes return nil. Polling the socket -988 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely -989 /// after this call. -990 /// -991 /// [`Poll::Pending`]: std::task::Poll::Pending -992 #[instrument(skip_all)] -993 pub(crate) async fn close(&self) { -994 trace!(me = ?self.public_key, "magicsock closing..."); -995 // Initiate closing all connections, and refuse future connections. -996 self.endpoint.close(0u16.into(), b""); -997 -998 // In the history of this code, this call had been -999 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1000 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1001 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1002 // and finally added back in together with this comment. -1003 // So before removing this call, please consider carefully. -1004 // Among other things, this call tries its best to make sure that any queued close frames -1005 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -1006 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -1007 // This allows the other endpoints for these connections to be notified to release -1008 // their resources, or - depending on the protocol - that all data was received. -1009 // With the current quinn API, this is the only way to ensure protocol code can use -1010 // connection close codes, and close the endpoint properly. -1011 // If this call is skipped, then connections that protocols close just shortly before the -1012 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -1013 self.endpoint.wait_idle().await; -1014 -1015 if self.msock.is_closed() { -1016 return; -1017 } -1018 self.msock.closing.store(true, Ordering::Relaxed); -1019 self.shutdown_token.cancel(); -1020 -1021 // MutexGuard is not held across await points -1022 let task = self.actor_task.lock().expect("poisoned").take(); -1023 if let Some(task) = task { -1024 // give the tasks a moment to shutdown cleanly -1025 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1026 if let Err(err) = task.await { -1027 warn!("unexpected error in task shutdown: {:?}", err); -1028 } -1029 }) -1030 .await; -1031 match shutdown_done { -1032 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1033 Err(time::Elapsed { .. }) => { -1034 // Dropping the task will abort itt -1035 warn!("tasks didn't finish in time, aborting"); -1036 } -1037 } -1038 } -1039 -1040 self.msock.closed.store(true, Ordering::SeqCst); -1041 -1042 trace!("magicsock closed"); -1043 } -1044} -1045 -1046fn default_quic_client_config() -> rustls::ClientConfig { -1047 // create a client config for the endpoint to use for QUIC address discovery -1048 let root_store = -1049 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -1050 rustls::client::ClientConfig::builder_with_provider(Arc::new( -1051 rustls::crypto::ring::default_provider(), -1052 )) -1053 .with_safe_default_protocol_versions() -1054 .expect("ring supports these") -1055 .with_root_certificates(root_store) -1056 .with_no_client_auth() -1057} -1058 -1059#[derive(Debug)] -1060#[allow(clippy::enum_variant_names)] -1061enum ActorMessage { -1062 NetworkChange, -1063 RelayMapChange, -1064 #[cfg(test)] -1065 ForceNetworkChange(bool), -1066} -1067 -1068struct Actor { -1069 msock: Arc<MagicSock>, -1070 msg_receiver: mpsc::Receiver<ActorMessage>, -1071 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. -1072 periodic_re_stun_timer: time::Interval, -1073 -1074 network_monitor: netmon::Monitor, -1075 netmon_watcher: n0_watcher::Direct<netmon::State>, -1076 network_change_sender: transports::NetworkChangeSender, -1077 /// Indicates the direct addr update state. -1078 direct_addr_update_state: DirectAddrUpdateState, -1079 direct_addr_done_rx: mpsc::Receiver<()>, -1080} -1081 -1082impl Actor { -1083 async fn run( -1084 mut self, -1085 shutdown_token: CancellationToken, -1086 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1087 ) { -1088 // Setup network monitoring -1089 let mut current_netmon_state = self.netmon_watcher.get(); -1090 -1091 #[cfg(not(wasm_browser))] -1092 let mut portmap_watcher = self -1093 .direct_addr_update_state -1094 .port_mapper -1095 .watch_external_address(); -1096 -1097 let mut receiver_closed = false; -1098 #[cfg_attr(wasm_browser, allow(unused_mut))] -1099 let mut portmap_watcher_closed = false; -1100 -1101 let mut net_report_watcher = self.msock.net_report.watch(); -1102 -1103 // ensure we are doing an initial publish of our addresses -1104 self.msock.publish_my_addr(); -1105 -1106 // Interval timer to remove closed `RemoteStateActor` handles from the endpoint map. -1107 let mut remote_map_gc = time::interval(remote_map::REMOTE_MAP_GC_INTERVAL); -1108 -1109 loop { -1110 self.msock.metrics.magicsock.actor_tick_main.inc(); -1111 #[cfg(not(wasm_browser))] -1112 let portmap_watcher_changed = portmap_watcher.changed(); -1113 #[cfg(wasm_browser)] -1114 let portmap_watcher_changed = n0_future::future::pending(); -1115 -1116 tokio::select! { -1117 _ = shutdown_token.cancelled() => { -1118 debug!("shutting down"); -1119 return; -1120 } -1121 msg = self.msg_receiver.recv(), if !receiver_closed => { -1122 let Some(msg) = msg else { -1123 trace!("tick: magicsock receiver closed"); -1124 self.msock.metrics.magicsock.actor_tick_other.inc(); -1125 -1126 receiver_closed = true; -1127 continue; -1128 }; -1129 -1130 trace!(?msg, "tick: msg"); -1131 self.msock.metrics.magicsock.actor_tick_msg.inc(); -1132 self.handle_actor_message(msg).await; -1133 } -1134 tick = self.periodic_re_stun_timer.tick() => { -1135 trace!("tick: re_stun {:?}", tick); -1136 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); -1137 self.re_stun(UpdateReason::Periodic); -1138 } -1139 new_addr = watcher.updated() => { -1140 match new_addr { -1141 Ok(addrs) => { -1142 if !addrs.is_empty() { -1143 trace!(?addrs, "local addrs"); -1144 self.msock.publish_my_addr(); -1145 } -1146 } -1147 Err(_) => { -1148 warn!("local addr watcher stopped"); -1149 } -1150 } -1151 } -1152 report = net_report_watcher.updated() => { -1153 match report { -1154 Ok((report, _)) => { -1155 self.handle_net_report_report(report); -1156 #[cfg(not(wasm_browser))] -1157 { -1158 self.periodic_re_stun_timer = new_re_stun_timer(true); -1159 } -1160 } -1161 Err(_) => { -1162 warn!("net report watcher stopped"); -1163 } -1164 } -1165 } -1166 reason = self.direct_addr_done_rx.recv() => { -1167 match reason { -1168 Some(()) => { -1169 // check if a new run needs to be scheduled -1170 let state = self.netmon_watcher.get(); -1171 self.direct_addr_update_state.try_run(state.into()); -1172 } -1173 None => { -1174 warn!("direct addr watcher died"); -1175 } -1176 } -1177 } -1178 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1179 #[cfg(not(wasm_browser))] -1180 { -1181 if change.is_err() { -1182 trace!("tick: portmap watcher closed"); -1183 self.msock.metrics.magicsock.actor_tick_other.inc(); -1184 -1185 portmap_watcher_closed = true; -1186 continue; -1187 } -1188 -1189 trace!("tick: portmap changed"); -1190 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); -1191 let new_external_address = *portmap_watcher.borrow(); -1192 debug!("external address updated: {new_external_address:?}"); -1193 self.re_stun(UpdateReason::PortmapUpdated); -1194 } -1195 #[cfg(wasm_browser)] -1196 let _unused_in_browsers = change; -1197 }, -1198 state = self.netmon_watcher.updated() => { -1199 let Ok(state) = state else { -1200 trace!("tick: link change receiver closed"); -1201 self.msock.metrics.magicsock.actor_tick_other.inc(); -1202 continue; -1203 }; -1204 let is_major = state.is_major_change(&current_netmon_state); -1205 event!( -1206 target: "iroh::_events::link_change", -1207 Level::DEBUG, -1208 ?state, -1209 is_major -1210 ); -1211 current_netmon_state = state; -1212 self.msock.metrics.magicsock.actor_link_change.inc(); -1213 self.handle_network_change(is_major).await; -1214 } -1215 _ = remote_map_gc.tick() => { -1216 self.msock.remote_map.remove_closed_remote_state_actors(); -1217 } -1218 } -1219 } -1220 } -1221 -1222 async fn handle_network_change(&mut self, is_major: bool) { -1223 debug!(is_major, "link change detected"); -1224 -1225 if is_major { -1226 if let Err(err) = self.network_change_sender.rebind() { -1227 warn!("failed to rebind transports: {err:?}"); -1228 } -1229 -1230 #[cfg(not(wasm_browser))] -1231 self.msock.dns_resolver.reset().await; -1232 self.re_stun(UpdateReason::LinkChangeMajor); -1233 } else { -1234 self.re_stun(UpdateReason::LinkChangeMinor); -1235 } -1236 } -1237 -1238 fn handle_relay_map_change(&mut self) { -1239 self.re_stun(UpdateReason::RelayMapChange); -1240 } -1241 -1242 fn re_stun(&mut self, why: UpdateReason) { -1243 let state = self.netmon_watcher.get(); -1244 self.direct_addr_update_state -1245 .schedule_run(why, state.into()); -1246 } -1247 -1248 /// Processes an incoming actor message. -1249 /// -1250 /// Returns `true` if it was a shutdown. -1251 async fn handle_actor_message(&mut self, msg: ActorMessage) { -1252 match msg { -1253 ActorMessage::NetworkChange => { -1254 self.network_monitor.network_change().await.ok(); -1255 } -1256 ActorMessage::RelayMapChange => { -1257 self.handle_relay_map_change(); -1258 } -1259 #[cfg(test)] -1260 ActorMessage::ForceNetworkChange(is_major) => { -1261 self.handle_network_change(is_major).await; -1262 } -1263 } -1264 } -1265 -1266 /// Updates the direct addresses of this magic socket. -1267 /// -1268 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of -1269 /// direct addresses from: -1270 /// -1271 /// - The portmapper. -1272 /// - A net_report report. -1273 /// - The local interfaces IP addresses. -1274 #[cfg(not(wasm_browser))] -1275 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1276 let portmap_watcher = self -1277 .direct_addr_update_state -1278 .port_mapper -1279 .watch_external_address(); -1280 -1281 // We only want to have one DirectAddr for each SocketAddr we have. So we store -1282 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -1283 // DirectAddr from each entry. -1284 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -1285 -1286 // First add PortMapper provided addresses. -1287 let maybe_port_mapped = *portmap_watcher.borrow(); -1288 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -1289 addrs -1290 .entry(portmap_ext) -1291 .or_insert(DirectAddrType::Portmapped); -1292 } -1293 -1294 // Next add STUN addresses from the net_report report. -1295 if let Some(net_report_report) = net_report_report { -1296 if let Some(global_v4) = net_report_report.global_v4 { -1297 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); -1298 -1299 // If they're behind a hard NAT and are using a fixed -1300 // port locally, assume they might've added a static -1301 // port mapping on their router to the same explicit -1302 // port that we are running with. Worst case it's an invalid candidate mapping. -1303 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { -1304 if addr.port() != 0 { -1305 Some(addr.port()) -1306 } else { -1307 None -1308 } -1309 }); -1310 -1311 if let Some(port) = port { -1312 if net_report_report -1313 .mapping_varies_by_dest() -1314 .unwrap_or_default() -1315 { -1316 let mut addr = global_v4; -1317 addr.set_port(port); -1318 addrs -1319 .entry(addr.into()) -1320 .or_insert(DirectAddrType::Qad4LocalPort); -1321 } -1322 } -1323 } -1324 if let Some(global_v6) = net_report_report.global_v6 { -1325 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); -1326 } -1327 } -1328 -1329 self.collect_local_addresses(&mut addrs); -1330 -1331 // Finally create and store store all these direct addresses and send any -1332 // queued call-me-maybe messages. -1333 self.msock.store_direct_addresses( -1334 addrs -1335 .iter() -1336 .map(|(addr, typ)| DirectAddr { -1337 addr: *addr, -1338 typ: *typ, -1339 }) -1340 .collect(), -1341 ); -1342 } -1343 -1344 #[cfg(not(wasm_browser))] -1345 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { -1346 // Matches the addresses that have been bound vs the requested ones. -1347 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -1348 .msock -1349 .ip_bind_addrs() -1350 .iter() -1351 .copied() -1352 .zip(self.msock.ip_local_addrs()) -1353 .collect(); -1354 -1355 // Do we listen on any IPv4 unspecified address? -1356 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -1357 if a.is_ipv4() && a.ip().is_unspecified() { -1358 Some(a.port()) -1359 } else { -1360 None -1361 } -1362 }); -1363 // Do we listen on any IPv6 unspecified address? -1364 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -1365 if a.is_ipv6() && a.ip().is_unspecified() { -1366 Some(a.port()) -1367 } else { -1368 None -1369 } -1370 }); -1371 -1372 // If a socket is bound to the unspecified address, create SocketAddrs for -1373 // each local IP address by pairing it with the port the socket is bound on. -1374 if local_addrs -1375 .iter() -1376 .any(|(_, local)| local.ip().is_unspecified()) -1377 { -1378 let LocalAddresses { -1379 regular: mut ips, -1380 loopback, -1381 } = self.netmon_watcher.get().local_addresses; -1382 if ips.is_empty() && addrs.is_empty() { -1383 // Include loopback addresses only if there are no other interfaces -1384 // or public addresses, this allows testing offline. -1385 ips = loopback; -1386 } -1387 -1388 for ip in ips { -1389 let port_if_unspecified = match ip { -1390 IpAddr::V4(_) => has_ipv4_unspecified, -1391 IpAddr::V6(_) => has_ipv6_unspecified, -1392 }; -1393 if let Some(port) = port_if_unspecified { -1394 let addr = SocketAddr::new(ip, port); -1395 addrs.entry(addr).or_insert(DirectAddrType::Local); -1396 } -1397 } -1398 } -1399 -1400 // If a socket is bound to a specific address, add it. -1401 for (bound, local) in local_addrs { -1402 if !bound.ip().is_unspecified() { -1403 addrs.entry(local).or_insert(DirectAddrType::Local); -1404 } -1405 } -1406 } -1407 -1408 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -1409 if let Some(ref mut r) = report { -1410 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -1411 if r.preferred_relay.is_none() { -1412 if let Some(my_relay) = self.msock.my_relay() { -1413 r.preferred_relay.replace(my_relay); -1414 } -1415 } -1416 -1417 // Notify all transports -1418 self.network_change_sender.on_network_change(r); -1419 } -1420 -1421 #[cfg(not(wasm_browser))] -1422 self.update_direct_addresses(report.as_ref()); -1423 } -1424} -1425 -1426fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -1427 // Pick a random duration between 20 and 26 seconds (just under 30s, -1428 // a common UDP NAT timeout on Linux,etc) -1429 let mut rng = rand::rng(); -1430 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); -1431 if initial_delay { -1432 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -1433 time::interval_at(time::Instant::now() + d, d) -1434 } else { -1435 debug!( -1436 "scheduling periodic_stun to run immediately and in {}s", -1437 d.as_secs() -1438 ); -1439 time::interval(d) -1440 } -1441} -1442 -1443/// The discovered direct addresses of this [`MagicSock`]. -1444/// -1445/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. -1446/// They include all locally bound ones as well as those discovered by other mechanisms like -1447/// QAD. -1448#[derive(derive_more::Debug, Clone, Default)] -1449struct DiscoveredDirectAddrs { -1450 /// The last set of discovered direct addresses. -1451 addrs: Watchable<BTreeSet<DirectAddr>>, -1452 -1453 /// The last time the direct addresses were updated, even if there was no change. -1454 /// -1455 /// This is only ever None at startup. -1456 updated_at: Arc<RwLock<Option<Instant>>>, -1457} -1458 -1459impl DiscoveredDirectAddrs { -1460 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -1461 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -1462 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -1463 let updated = self.addrs.set(addrs).is_ok(); -1464 if updated { -1465 event!( -1466 target: "iroh::_events::direct_addrs", -1467 Level::DEBUG, -1468 addrs = ?self.addrs.get(), -1469 ); -1470 } -1471 updated -1472 } -1473 -1474 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { -1475 self.addrs.get().into_iter().map(|da| da.addr) -1476 } -1477} -1478 -1479/// A *direct address* on which an iroh-endpoint might be contactable. -1480/// -1481/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be -1482/// contacted. These can come from various sources depending on the network topology of the -1483/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. -1484/// -1485/// This is essentially a combination of our local addresses combined with any reflexive -1486/// transport addresses we discovered using QAD. -1487#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -1488pub struct DirectAddr { -1489 /// The address. -1490 pub addr: SocketAddr, -1491 /// The origin of this direct address. -1492 pub typ: DirectAddrType, -1493} -1494 -1495/// The type of direct address. -1496/// -1497/// These are the various sources or origins from which an iroh endpoint might have found a -1498/// possible [`DirectAddr`]. -1499#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -1500pub enum DirectAddrType { -1501 /// Not yet determined.. -1502 Unknown, -1503 /// A locally bound socket address. -1504 Local, -1505 /// Public internet address discovered via QAD. -1506 /// -1507 /// When possible an iroh endpoint will perform QAD to discover which is the address -1508 /// from which it sends data on the public internet. This can be different from locally -1509 /// bound addresses when the endpoint is on a local network which performs NAT or similar. -1510 Qad, -1511 /// An address assigned by the router using port mapping. -1512 /// -1513 /// When possible an iroh endpoint will request a port mapping from the local router to -1514 /// get a publicly routable direct address. -1515 Portmapped, -1516 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -1517 /// -1518 /// It is possible to configure iroh to bound to a specific port and independently -1519 /// configure the router to forward this port to the iroh endpoint. This indicates a -1520 /// situation like this, which still uses QAD to discover the public address. -1521 Qad4LocalPort, -1522} -1523 -1524impl Display for DirectAddrType { -1525 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -1526 match self { -1527 DirectAddrType::Unknown => write!(f, "?"), -1528 DirectAddrType::Local => write!(f, "local"), -1529 DirectAddrType::Qad => write!(f, "qad"), -1530 DirectAddrType::Portmapped => write!(f, "portmap"), -1531 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -1532 } -1533 } -1534} -1535 -1536#[cfg(test)] -1537mod tests { -1538 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; -1539 -1540 use data_encoding::HEXLOWER; -1541 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; -1542 use n0_error::{Result, StackResultExt, StdResultExt}; -1543 use n0_future::{MergeBounded, StreamExt, time}; -1544 use n0_watcher::Watcher; -1545 use quinn::ServerConfig; -1546 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; -1547 use tokio_util::task::AbortOnDropHandle; -1548 use tracing::{Instrument, error, info, info_span, instrument}; -1549 use tracing_test::traced_test; -1550 -1551 use super::Options; -1552 use crate::{ -1553 Endpoint, RelayMode, SecretKey, -1554 discovery::static_provider::StaticProvider, -1555 dns::DnsResolver, -1556 magicsock::{ -1557 Handle, MagicSock, TransportConfig, -1558 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, -1559 }, -1560 tls::{self, DEFAULT_MAX_TLS_TICKETS}, -1561 }; -1562 -1563 const ALPN: &[u8] = b"n0/test/1"; -1564 -1565 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { -1566 let secret_key = SecretKey::generate(rng); -1567 let server_config = make_default_server_config(&secret_key); -1568 Options { -1569 transports: vec![ -1570 TransportConfig::default_ipv4(), -1571 TransportConfig::default_ipv6(), -1572 ], -1573 secret_key, -1574 proxy_url: None, -1575 dns_resolver: DnsResolver::new(), -1576 server_config, -1577 #[cfg(any(test, feature = "test-utils"))] -1578 insecure_skip_relay_cert_verify: false, -1579 #[cfg(any(test, feature = "test-utils"))] -1580 discovery_user_data: None, -1581 metrics: Default::default(), -1582 hooks: Default::default(), -1583 } -1584 } -1585 -1586 /// Generate a server config with no ALPNS and a default transport configuration -1587 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { -1588 let quic_server_config = -1589 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -1590 .make_server_config(vec![], false); -1591 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -1592 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -1593 server_config -1594 } -1595 -1596 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1597 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { -1598 info!("accepting conn"); -1599 let conn = ep.accept().await.expect("no conn"); -1600 -1601 info!("accepting"); -1602 let conn = conn.await.context("accepting")?; -1603 info!("accepting bi"); -1604 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; -1605 -1606 info!("reading"); -1607 let val = recv_bi -1608 .read_to_end(usize::MAX) -1609 .await -1610 .std_context("read to end")?; -1611 -1612 info!("replying"); -1613 for chunk in val.chunks(12) { -1614 send_bi.write_all(chunk).await.std_context("write all")?; -1615 } -1616 -1617 info!("finishing"); -1618 send_bi.finish().std_context("finish")?; -1619 send_bi.stopped().await.std_context("stopped")?; -1620 -1621 let stats = conn.stats(); -1622 info!("stats: {:#?}", stats); -1623 // TODO: ensure panics in this function are reported ok -1624 if matches!(loss, ExpectedLoss::AlmostNone) { -1625 for info in conn.paths().get().iter() { -1626 assert!( -1627 info.stats().lost_packets < 10, -1628 "[receiver] path {:?} should not loose many packets", -1629 info.remote_addr() -1630 ); -1631 } -1632 } -1633 -1634 info!("close"); -1635 conn.close(0u32.into(), b"done"); -1636 info!("wait idle"); -1637 ep.endpoint().wait_idle().await; -1638 -1639 Ok(()) -1640 } -1641 -1642 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1643 async fn echo_sender( -1644 ep: Endpoint, -1645 dest_id: EndpointId, -1646 msg: &[u8], -1647 loss: ExpectedLoss, -1648 ) -> Result { -1649 info!("connecting to {}", dest_id.fmt_short()); -1650 let dest = EndpointAddr::new(dest_id); -1651 let conn = ep.connect(dest, ALPN).await?; -1652 -1653 info!("opening bi"); -1654 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; -1655 -1656 info!("writing message"); -1657 send_bi.write_all(msg).await.std_context("write all")?; -1658 -1659 info!("finishing"); -1660 send_bi.finish().std_context("finish")?; -1661 send_bi.stopped().await.std_context("stopped")?; -1662 -1663 info!("reading_to_end"); -1664 let val = recv_bi -1665 .read_to_end(usize::MAX) -1666 .await -1667 .std_context("read to end")?; -1668 assert_eq!( -1669 val, -1670 msg, -1671 "[sender] expected {}, got {}", -1672 HEXLOWER.encode(msg), -1673 HEXLOWER.encode(&val) -1674 ); -1675 -1676 let stats = conn.stats(); -1677 info!("stats: {:#?}", stats); -1678 if matches!(loss, ExpectedLoss::AlmostNone) { -1679 for info in conn.paths().get() { -1680 assert!( -1681 info.stats().lost_packets < 10, -1682 "[sender] path {:?} should not loose many packets", -1683 info.remote_addr() -1684 ); -1685 } -1686 } -1687 -1688 info!("close"); -1689 conn.close(0u32.into(), b"done"); -1690 info!("wait idle"); -1691 ep.endpoint().wait_idle().await; -1692 Ok(()) -1693 } -1694 -1695 #[derive(Debug, Copy, Clone)] -1696 enum ExpectedLoss { -1697 AlmostNone, -1698 YeahSure, -1699 } -1700 -1701 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -1702 async fn run_roundtrip( -1703 sender: Endpoint, -1704 receiver: Endpoint, -1705 payload: &[u8], -1706 loss: ExpectedLoss, -1707 ) { -1708 let send_endpoint_id = sender.id(); -1709 let recv_endpoint_id = receiver.id(); -1710 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); -1711 -1712 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); -1713 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; -1714 let sender_is_err = match sender_res { -1715 Ok(()) => false, -1716 Err(err) => { -1717 eprintln!("[sender] Error:\n{err:#?}"); -1718 true -1719 } -1720 }; -1721 let receiver_is_err = match receiver_task.await { -1722 Ok(Ok(())) => false, -1723 Ok(Err(err)) => { -1724 eprintln!("[receiver] Error:\n{err:#?}"); -1725 true -1726 } -1727 Err(joinerr) => { -1728 if joinerr.is_panic() { -1729 std::panic::resume_unwind(joinerr.into_panic()); -1730 } else { -1731 eprintln!("[receiver] Error:\n{joinerr:#?}"); -1732 } -1733 true -1734 } -1735 }; -1736 if sender_is_err || receiver_is_err { -1737 panic!("Sender or receiver errored"); -1738 } -1739 } -1740 -1741 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. -1742 /// -1743 /// The endpoints do not use a relay server but can connect to each other via local -1744 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if -1745 /// the endpoints rebind. -1746 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { -1747 let discovery = StaticProvider::new(); -1748 let ep1 = Endpoint::builder() -1749 .relay_mode(RelayMode::Disabled) -1750 .alpns(vec![ALPN.to_vec()]) -1751 .discovery(discovery.clone()) -1752 .bind() -1753 .await -1754 .unwrap(); -1755 let ep2 = Endpoint::builder() -1756 .relay_mode(RelayMode::Disabled) -1757 .alpns(vec![ALPN.to_vec()]) -1758 .discovery(discovery.clone()) -1759 .bind() -1760 .await -1761 .unwrap(); -1762 discovery.add_endpoint_info(ep1.addr()); -1763 discovery.add_endpoint_info(ep2.addr()); -1764 -1765 let ep1_addr_stream = ep1.watch_addr().stream(); -1766 let ep2_addr_stream = ep2.watch_addr().stream(); -1767 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); -1768 let task = tokio::spawn(async move { -1769 while let Some(addr) = addr_stream.next().await { -1770 discovery.add_endpoint_info(addr); -1771 } -1772 }); -1773 -1774 (AbortOnDropHandle::new(task), ep1, ep2) -1775 } -1776 -1777 #[tokio::test(flavor = "multi_thread")] -1778 #[traced_test] -1779 async fn test_two_devices_roundtrip_quinn_magic() -> Result { -1780 let (_guard, m1, m2) = endpoint_pair().await; -1781 -1782 for i in 0..5 { -1783 info!("\n-- round {i}"); -1784 run_roundtrip( -1785 m1.clone(), -1786 m2.clone(), -1787 b"hello m1", -1788 ExpectedLoss::AlmostNone, -1789 ) -1790 .await; -1791 run_roundtrip( -1792 m2.clone(), -1793 m1.clone(), -1794 b"hello m2", -1795 ExpectedLoss::AlmostNone, -1796 ) -1797 .await; -1798 -1799 info!("\n-- larger data"); -1800 let mut data = vec![0u8; 10 * 1024]; -1801 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1802 rng.fill_bytes(&mut data); -1803 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; -1804 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; -1805 } -1806 -1807 Ok(()) -1808 } -1809 -1810 #[tokio::test] -1811 #[traced_test] -1812 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { -1813 let (_guard, m1, m2) = endpoint_pair().await; -1814 -1815 println!("Net change"); -1816 m1.magic_sock().force_network_change(true).await; -1817 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -1818 -1819 let _handle = AbortOnDropHandle::new(tokio::spawn({ -1820 let endpoint = m2.clone(); -1821 async move { -1822 while let Some(incoming) = endpoint.accept().await { -1823 println!("Incoming first conn!"); -1824 let conn = incoming.await.anyerr()?; -1825 conn.closed().await; -1826 } -1827 -1828 n0_error::Ok(()) -1829 } -1830 })); -1831 -1832 println!("first conn!"); -1833 let conn = m1.connect(m2.addr(), ALPN).await?; -1834 println!("Closing first conn"); -1835 conn.close(0u32.into(), b"bye lolz"); -1836 conn.closed().await; -1837 println!("Closed first conn"); -1838 -1839 Ok(()) -1840 } -1841 -1842 #[tokio::test(flavor = "multi_thread")] -1843 #[traced_test] -1844 async fn test_two_devices_roundtrip_network_change() -> Result { -1845 time::timeout( -1846 Duration::from_secs(90), -1847 test_two_devices_roundtrip_network_change_impl(), -1848 ) -1849 .await -1850 .std_context("timeout")? -1851 } -1852 -1853 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly -1854 /// with (simulated) network changes. -1855 async fn test_two_devices_roundtrip_network_change_impl() -> Result { -1856 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1857 let (_guard, m1, m2) = endpoint_pair().await; -1858 -1859 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { -1860 let delay = rng.random_range(10..=500); -1861 Duration::from_millis(delay) -1862 }; -1863 let rounds = 5; -1864 -1865 // Regular network changes to m1 only. -1866 let m1_network_change_guard = { -1867 let m1 = m1.clone(); -1868 let mut rng = rng.clone(); -1869 let task = tokio::spawn(async move { -1870 loop { -1871 println!("[m1] network change"); -1872 m1.magic_sock().force_network_change(true).await; -1873 time::sleep(offset(&mut rng)).await; -1874 } -1875 }); -1876 AbortOnDropHandle::new(task) -1877 }; -1878 -1879 for i in 0..rounds { -1880 println!("-- [m1 changes] round {}", i + 1); -1881 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -1882 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -1883 -1884 println!("-- [m1 changes] larger data"); -1885 let mut data = vec![0u8; 10 * 1024]; -1886 rng.fill_bytes(&mut data); -1887 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -1888 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -1889 } -1890 -1891 std::mem::drop(m1_network_change_guard); -1892 -1893 // Regular network changes to m2 only. -1894 let m2_network_change_guard = { -1895 let m2 = m2.clone(); -1896 let mut rng = rng.clone(); -1897 let task = tokio::spawn(async move { -1898 loop { -1899 println!("[m2] network change"); -1900 m2.magic_sock().force_network_change(true).await; -1901 time::sleep(offset(&mut rng)).await; -1902 } -1903 }); -1904 AbortOnDropHandle::new(task) -1905 }; -1906 -1907 for i in 0..rounds { -1908 println!("-- [m2 changes] round {}", i + 1); -1909 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -1910 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -1911 -1912 println!("-- [m2 changes] larger data"); -1913 let mut data = vec![0u8; 10 * 1024]; -1914 rng.fill_bytes(&mut data); -1915 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -1916 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -1917 } -1918 -1919 std::mem::drop(m2_network_change_guard); -1920 -1921 // Regular network changes to both m1 and m2 only. -1922 let m1_m2_network_change_guard = { -1923 let m1 = m1.clone(); -1924 let m2 = m2.clone(); -1925 let mut rng = rng.clone(); -1926 let task = tokio::spawn(async move { -1927 println!("-- [m1] network change"); -1928 m1.magic_sock().force_network_change(true).await; -1929 println!("-- [m2] network change"); -1930 m2.magic_sock().force_network_change(true).await; -1931 time::sleep(offset(&mut rng)).await; -1932 }); -1933 AbortOnDropHandle::new(task) -1934 }; -1935 -1936 for i in 0..rounds { -1937 println!("-- [m1 & m2 changes] round {}", i + 1); -1938 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -1939 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -1940 -1941 println!("-- [m1 & m2 changes] larger data"); -1942 let mut data = vec![0u8; 10 * 1024]; -1943 rng.fill_bytes(&mut data); -1944 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -1945 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -1946 } -1947 -1948 std::mem::drop(m1_m2_network_change_guard); -1949 Ok(()) -1950 } -1951 -1952 #[tokio::test(flavor = "multi_thread")] -1953 #[traced_test] -1954 async fn test_two_devices_setup_teardown() -> Result { -1955 for i in 0..10 { -1956 info!("-- round {i}"); -1957 info!("setting up magic stack"); -1958 let (_guard, m1, m2) = endpoint_pair().await; -1959 -1960 info!("closing endpoints"); -1961 let msock1 = m1.magic_sock(); -1962 let msock2 = m2.magic_sock(); -1963 m1.close().await; -1964 m2.close().await; -1965 -1966 assert!(msock1.msock.is_closed()); -1967 assert!(msock2.msock.is_closed()); -1968 } -1969 Ok(()) -1970 } -1971 -1972 #[tokio::test] -1973 #[traced_test] -1974 async fn test_direct_addresses() { -1975 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1976 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); -1977 -1978 // See if we can get endpoints. -1979 let eps0 = ms.ip_addrs().get(); -1980 println!("{eps0:?}"); -1981 assert!(!eps0.is_empty()); -1982 -1983 // Getting the endpoints again immediately should give the same results. -1984 let eps1 = ms.ip_addrs().get(); -1985 println!("{eps1:?}"); -1986 assert_eq!(eps0, eps1); -1987 } -1988 -1989 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. -1990 /// -1991 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -1992 /// connections using [`ALPN`]. -1993 /// -1994 /// Use [`magicsock_connect`] to establish connections. -1995 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] -1996 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { -1997 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -1998 .make_server_config(vec![ALPN.to_vec()], true); -1999 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -2000 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -2001 -2002 let dns_resolver = DnsResolver::new(); -2003 let opts = Options { -2004 transports: vec![ -2005 TransportConfig::default_ipv4(), -2006 TransportConfig::default_ipv6(), -2007 ], -2008 secret_key: secret_key.clone(), -2009 discovery_user_data: None, -2010 dns_resolver, -2011 proxy_url: None, -2012 server_config, -2013 insecure_skip_relay_cert_verify: false, -2014 metrics: Default::default(), -2015 hooks: Default::default(), -2016 }; -2017 let msock = MagicSock::spawn(opts).await?; -2018 Ok(msock) -2019 } -2020 -2021 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2022 /// -2023 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2024 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2025 async fn magicsock_connect( -2026 ep: &quinn::Endpoint, -2027 ep_secret_key: SecretKey, -2028 addr: EndpointIdMappedAddr, -2029 endpoint_id: EndpointId, -2030 ) -> Result<quinn::Connection> { -2031 // Endpoint::connect sets this, do the same to have similar behaviour. -2032 let mut transport_config = quinn::TransportConfig::default(); -2033 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -2034 -2035 magicsock_connect_with_transport_config( -2036 ep, -2037 ep_secret_key, -2038 addr, -2039 endpoint_id, -2040 Arc::new(transport_config), -2041 ) -2042 .await -2043 } -2044 -2045 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2046 /// -2047 /// This version allows customising the transport config. -2048 /// -2049 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2050 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2051 async fn magicsock_connect_with_transport_config( -2052 ep: &quinn::Endpoint, -2053 ep_secret_key: SecretKey, -2054 mapped_addr: EndpointIdMappedAddr, -2055 endpoint_id: EndpointId, -2056 transport_config: Arc<quinn::TransportConfig>, -2057 ) -> Result<quinn::Connection> { -2058 let alpns = vec![ALPN.to_vec()]; -2059 let quic_client_config = -2060 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2061 .make_client_config(alpns, true); -2062 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -2063 client_config.transport_config(transport_config); -2064 let connect = ep -2065 .connect_with( -2066 client_config, -2067 mapped_addr.private_socket_addr(), -2068 &tls::name::encode(endpoint_id), -2069 ) -2070 .std_context("connect")?; -2071 let connection = connect.await.anyerr()?; -2072 Ok(connection) -2073 } -2074 -2075 #[tokio::test] -2076 #[traced_test] -2077 async fn test_try_send_no_send_addr() { -2078 // Regression test: if there is no send_addr we should keep being able to use the -2079 // Endpoint. -2080 -2081 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2082 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2083 let endpoint_id_2 = secret_key_2.public(); -2084 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); -2085 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); -2086 -2087 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2088 -2089 // Generate an address not present in the RemoteMap. -2090 let bad_addr = EndpointIdMappedAddr::generate(); -2091 -2092 // 500ms is rather fast here. Running this locally it should always be the correct -2093 // timeout. If this is too slow however the test will not become flaky as we are -2094 // expecting the timeout, we might just get the timeout for the wrong reason. But -2095 // this speeds up the test. -2096 let res = tokio::time::timeout( -2097 Duration::from_millis(500), -2098 magicsock_connect( -2099 msock_1.endpoint(), -2100 secret_key_1.clone(), -2101 bad_addr, -2102 endpoint_id_missing_endpoint, -2103 ), -2104 ) -2105 .await; -2106 assert!(res.is_err(), "expecting timeout"); -2107 -2108 // Now check we can still create another connection with this endpoint. -2109 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2110 -2111 // This needs an accept task -2112 let accept_task = tokio::spawn({ -2113 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2114 let incoming = ep.accept().await.std_context("no incoming")?; -2115 let _conn = incoming -2116 .accept() -2117 .std_context("accept")? -2118 .await -2119 .std_context("accepting")?; -2120 -2121 // Keep this connection alive for a while -2122 tokio::time::sleep(Duration::from_secs(10)).await; -2123 info!("accept finished"); -2124 Ok(()) -2125 } -2126 let ep = msock_2.endpoint().clone(); -2127 async move { -2128 if let Err(err) = accept(ep).await { -2129 error!("{err:#}"); -2130 } -2131 } -2132 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) -2133 }); -2134 let _accept_task = AbortOnDropHandle::new(accept_task); -2135 -2136 let addrs = msock_2 -2137 .ip_addrs() -2138 .get() -2139 .into_iter() -2140 .map(|x| TransportAddr::Ip(x.addr)); -2141 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); -2142 let addr = msock_1 -2143 .resolve_remote(endpoint_addr_2) -2144 .await -2145 .unwrap() -2146 .unwrap(); -2147 let res = tokio::time::timeout( -2148 Duration::from_secs(10), -2149 magicsock_connect( -2150 msock_1.endpoint(), -2151 secret_key_1.clone(), -2152 addr, -2153 endpoint_id_2, -2154 ), -2155 ) -2156 .await -2157 .expect("timeout while connecting"); -2158 -2159 // aka assert!(res.is_ok()) but with nicer error reporting. -2160 res.unwrap(); -2161 -2162 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -2163 // much internal state for now. -2164 } -2165 -2166 #[tokio::test] -2167 #[traced_test] -2168 async fn test_try_send_no_udp_addr_or_relay_url() { -2169 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -2170 // behaviour of MagicSock::try_send. -2171 -2172 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2173 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2174 let endpoint_id_2 = secret_key_2.public(); -2175 -2176 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2177 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2178 let ep_2 = msock_2.endpoint().clone(); -2179 -2180 // We need a task to accept the connection. -2181 let accept_task = tokio::spawn({ -2182 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2183 let incoming = ep.accept().await.std_context("no incoming")?; -2184 let conn = incoming -2185 .accept() -2186 .std_context("accept")? -2187 .await -2188 .std_context("connecting")?; -2189 let mut stream = conn.accept_uni().await.std_context("accept uni")?; -2190 stream -2191 .read_to_end(1 << 16) -2192 .await -2193 .std_context("read to end")?; -2194 info!("accept finished"); -2195 Ok(()) -2196 } -2197 async move { -2198 if let Err(err) = accept(ep_2).await { -2199 error!("{err:#}"); -2200 } -2201 } -2202 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) -2203 }); -2204 let _accept_task = AbortOnDropHandle::new(accept_task); -2205 -2206 // Add an entry in the RemoteMap of ep_1 with an invalid socket address -2207 let empty_addr_2 = EndpointAddr::from_parts( -2208 endpoint_id_2, -2209 [TransportAddr::Ip( -2210 // Reserved IP range for documentation (unreachable) -2211 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), -2212 )], -2213 ); -2214 let addr_2 = msock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); -2215 -2216 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -2217 // not take forever. You need to check the log output to verify this is really -2218 // triggering the correct error. -2219 // In test_try_send_no_send_addr() above you may have noticed we used -2220 // tokio::time::timeout() on the connection attempt instead. Here however we want -2221 // Quinn itself to have fully given up on the connection attempt because we will -2222 // later connect to **the same** endpoint. If Quinn did not give up on the connection -2223 // we'd close it on drop, and the retransmits of the close packets would interfere -2224 // with the next handshake, closing it during the handshake. This makes the test a -2225 // little slower though. -2226 let mut transport_config = quinn::TransportConfig::default(); -2227 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -2228 let res = magicsock_connect_with_transport_config( -2229 msock_1.endpoint(), -2230 secret_key_1.clone(), -2231 addr_2, -2232 endpoint_id_2, -2233 Arc::new(transport_config), -2234 ) -2235 .await; -2236 assert!(res.is_err(), "expected timeout"); -2237 info!("first connect timed out as expected"); -2238 -2239 // Provide correct addressing information -2240 let correct_addr_2 = EndpointAddr::from_parts( -2241 endpoint_id_2, -2242 msock_2 -2243 .ip_addrs() -2244 .get() -2245 .into_iter() -2246 .map(|x| TransportAddr::Ip(x.addr)), -2247 ); -2248 let addr_2a = msock_1 -2249 .resolve_remote(correct_addr_2) -2250 .await -2251 .unwrap() -2252 .unwrap(); -2253 assert_eq!(addr_2, addr_2a); -2254 -2255 // We can now connect -2256 tokio::time::timeout(Duration::from_secs(10), async move { -2257 info!("establishing new connection"); -2258 let conn = magicsock_connect( -2259 msock_1.endpoint(), -2260 secret_key_1.clone(), -2261 addr_2, -2262 endpoint_id_2, -2263 ) -2264 .await -2265 .unwrap(); -2266 info!("have connection"); -2267 let mut stream = conn.open_uni().await.unwrap(); -2268 stream.write_all(b"hello").await.unwrap(); -2269 stream.finish().unwrap(); -2270 stream.stopped().await.unwrap(); -2271 info!("finished stream"); -2272 }) -2273 .await -2274 .expect("connection timed out"); -2275 -2276 // TODO: could remove the addresses again, send, add it back and see it recover. -2277 // But we don't have that much private access to the RemoteMap. This will do for now. -2278 } -2279}
    \ No newline at end of file +853 discovery.clone(), +854 ) +855 }; +856 +857 let msock = Arc::new(MagicSock { +858 public_key: secret_key.public(), +859 closing: AtomicBool::new(false), +860 closed: AtomicBool::new(false), +861 actor_sender: actor_sender.clone(), +862 ipv6_reported, +863 remote_map, +864 discovery, +865 relay_map: relay_map.clone(), +866 discovery_user_data: RwLock::new(discovery_user_data), +867 direct_addrs, +868 net_report: Watchable::new((None, UpdateReason::None)), +869 #[cfg(not(wasm_browser))] +870 dns_resolver: dns_resolver.clone(), +871 metrics: metrics.clone(), +872 local_addrs_watch: transports.local_addrs_watch(), +873 #[cfg(not(wasm_browser))] +874 ip_bind_addrs: transports.ip_bind_addrs(), +875 hooks, +876 }); +877 +878 let mut endpoint_config = quinn::EndpointConfig::default(); +879 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit +880 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +881 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +882 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore +883 // the packet if grease_quic_bit is set to false. +884 endpoint_config.grease_quic_bit(false); +885 +886 let local_addrs_watch = transports.local_addrs_watch(); +887 let network_change_sender = transports.create_network_change_sender(); +888 +889 let endpoint = quinn::Endpoint::new_with_abstract_socket( +890 endpoint_config, +891 Some(server_config), +892 Box::new(MagicTransport::new(msock.clone(), transports)), +893 #[cfg(not(wasm_browser))] +894 Arc::new(quinn::TokioRuntime), +895 #[cfg(wasm_browser)] +896 Arc::new(crate::web_runtime::WebRuntime), +897 ) +898 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; +899 +900 let network_monitor = netmon::Monitor::new() +901 .await +902 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; +903 +904 let qad_endpoint = endpoint.clone(); +905 +906 #[cfg(any(test, feature = "test-utils"))] +907 let client_config = if insecure_skip_relay_cert_verify { +908 iroh_relay::client::make_dangerous_client_config() +909 } else { +910 default_quic_client_config() +911 }; +912 #[cfg(not(any(test, feature = "test-utils")))] +913 let client_config = default_quic_client_config(); +914 +915 let net_report_config = net_report::Options::default(); +916 #[cfg(not(wasm_browser))] +917 let net_report_config = net_report_config.quic_config(Some(QuicConfig { +918 ep: qad_endpoint, +919 client_config, +920 ipv4: true, +921 ipv6, +922 })); +923 +924 #[cfg(any(test, feature = "test-utils"))] +925 let net_report_config = +926 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); +927 +928 let net_reporter = net_report::Client::new( +929 #[cfg(not(wasm_browser))] +930 dns_resolver, +931 relay_map.clone(), +932 net_report_config, +933 metrics.net_report.clone(), +934 ); +935 +936 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +937 let direct_addr_update_state = DirectAddrUpdateState::new( +938 msock.clone(), +939 #[cfg(not(wasm_browser))] +940 port_mapper, +941 Arc::new(AsyncMutex::new(net_reporter)), +942 relay_map, +943 direct_addr_done_tx, +944 ); +945 +946 let netmon_watcher = network_monitor.interface_state(); +947 +948 #[cfg_attr(not(wasm_browser), allow(unused_mut))] +949 let mut actor = Actor { +950 msg_receiver: actor_receiver, +951 msock: msock.clone(), +952 periodic_re_stun_timer: new_re_stun_timer(false), +953 network_monitor, +954 netmon_watcher, +955 direct_addr_update_state, +956 network_change_sender, +957 direct_addr_done_rx, +958 }; +959 // Initialize addresses +960 #[cfg(not(wasm_browser))] +961 actor.update_direct_addresses(None); +962 +963 let actor_task = task::spawn( +964 actor +965 .run(shutdown_token.child_token(), local_addrs_watch) +966 .instrument(info_span!("actor")), +967 ); +968 +969 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); +970 +971 Ok(Handle { +972 msock, +973 actor_task, +974 endpoint, +975 shutdown_token, +976 }) +977 } +978 +979 /// The underlying [`quinn::Endpoint`] +980 pub fn endpoint(&self) -> &quinn::Endpoint { +981 &self.endpoint +982 } +983 +984 /// Closes the connection. +985 /// +986 /// Only the first close does anything. Any later closes return nil. Polling the socket +987 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely +988 /// after this call. +989 /// +990 /// [`Poll::Pending`]: std::task::Poll::Pending +991 #[instrument(skip_all)] +992 pub(crate) async fn close(&self) { +993 trace!(me = ?self.public_key, "magicsock closing..."); +994 // Initiate closing all connections, and refuse future connections. +995 self.endpoint.close(0u16.into(), b""); +996 +997 // In the history of this code, this call had been +998 // - removed: https://github.com/n0-computer/iroh/pull/1753 +999 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1000 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1001 // and finally added back in together with this comment. +1002 // So before removing this call, please consider carefully. +1003 // Among other things, this call tries its best to make sure that any queued close frames +1004 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1005 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1006 // This allows the other endpoints for these connections to be notified to release +1007 // their resources, or - depending on the protocol - that all data was received. +1008 // With the current quinn API, this is the only way to ensure protocol code can use +1009 // connection close codes, and close the endpoint properly. +1010 // If this call is skipped, then connections that protocols close just shortly before the +1011 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1012 self.endpoint.wait_idle().await; +1013 +1014 if self.msock.is_closed() { +1015 return; +1016 } +1017 self.msock.closing.store(true, Ordering::Relaxed); +1018 self.shutdown_token.cancel(); +1019 +1020 // MutexGuard is not held across await points +1021 let task = self.actor_task.lock().expect("poisoned").take(); +1022 if let Some(task) = task { +1023 // give the tasks a moment to shutdown cleanly +1024 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1025 if let Err(err) = task.await { +1026 warn!("unexpected error in task shutdown: {:?}", err); +1027 } +1028 }) +1029 .await; +1030 match shutdown_done { +1031 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1032 Err(time::Elapsed { .. }) => { +1033 // Dropping the task will abort itt +1034 warn!("tasks didn't finish in time, aborting"); +1035 } +1036 } +1037 } +1038 +1039 self.msock.closed.store(true, Ordering::SeqCst); +1040 +1041 trace!("magicsock closed"); +1042 } +1043} +1044 +1045fn default_quic_client_config() -> rustls::ClientConfig { +1046 // create a client config for the endpoint to use for QUIC address discovery +1047 let root_store = +1048 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +1049 rustls::client::ClientConfig::builder_with_provider(Arc::new( +1050 rustls::crypto::ring::default_provider(), +1051 )) +1052 .with_safe_default_protocol_versions() +1053 .expect("ring supports these") +1054 .with_root_certificates(root_store) +1055 .with_no_client_auth() +1056} +1057 +1058#[derive(Debug)] +1059#[allow(clippy::enum_variant_names)] +1060enum ActorMessage { +1061 NetworkChange, +1062 RelayMapChange, +1063 #[cfg(test)] +1064 ForceNetworkChange(bool), +1065} +1066 +1067struct Actor { +1068 msock: Arc<MagicSock>, +1069 msg_receiver: mpsc::Receiver<ActorMessage>, +1070 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. +1071 periodic_re_stun_timer: time::Interval, +1072 +1073 network_monitor: netmon::Monitor, +1074 netmon_watcher: n0_watcher::Direct<netmon::State>, +1075 network_change_sender: transports::NetworkChangeSender, +1076 /// Indicates the direct addr update state. +1077 direct_addr_update_state: DirectAddrUpdateState, +1078 direct_addr_done_rx: mpsc::Receiver<()>, +1079} +1080 +1081impl Actor { +1082 async fn run( +1083 mut self, +1084 shutdown_token: CancellationToken, +1085 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1086 ) { +1087 // Setup network monitoring +1088 let mut current_netmon_state = self.netmon_watcher.get(); +1089 +1090 #[cfg(not(wasm_browser))] +1091 let mut portmap_watcher = self +1092 .direct_addr_update_state +1093 .port_mapper +1094 .watch_external_address(); +1095 +1096 let mut receiver_closed = false; +1097 #[cfg_attr(wasm_browser, allow(unused_mut))] +1098 let mut portmap_watcher_closed = false; +1099 +1100 let mut net_report_watcher = self.msock.net_report.watch(); +1101 +1102 // ensure we are doing an initial publish of our addresses +1103 self.msock.publish_my_addr(); +1104 +1105 // Interval timer to remove closed `RemoteStateActor` handles from the endpoint map. +1106 let mut remote_map_gc = time::interval(remote_map::REMOTE_MAP_GC_INTERVAL); +1107 +1108 loop { +1109 self.msock.metrics.magicsock.actor_tick_main.inc(); +1110 #[cfg(not(wasm_browser))] +1111 let portmap_watcher_changed = portmap_watcher.changed(); +1112 #[cfg(wasm_browser)] +1113 let portmap_watcher_changed = n0_future::future::pending(); +1114 +1115 tokio::select! { +1116 _ = shutdown_token.cancelled() => { +1117 debug!("shutting down"); +1118 return; +1119 } +1120 msg = self.msg_receiver.recv(), if !receiver_closed => { +1121 let Some(msg) = msg else { +1122 trace!("tick: magicsock receiver closed"); +1123 self.msock.metrics.magicsock.actor_tick_other.inc(); +1124 +1125 receiver_closed = true; +1126 continue; +1127 }; +1128 +1129 trace!(?msg, "tick: msg"); +1130 self.msock.metrics.magicsock.actor_tick_msg.inc(); +1131 self.handle_actor_message(msg).await; +1132 } +1133 tick = self.periodic_re_stun_timer.tick() => { +1134 trace!("tick: re_stun {:?}", tick); +1135 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); +1136 self.re_stun(UpdateReason::Periodic); +1137 } +1138 new_addr = watcher.updated() => { +1139 match new_addr { +1140 Ok(addrs) => { +1141 if !addrs.is_empty() { +1142 trace!(?addrs, "local addrs"); +1143 self.msock.publish_my_addr(); +1144 } +1145 } +1146 Err(_) => { +1147 warn!("local addr watcher stopped"); +1148 } +1149 } +1150 } +1151 report = net_report_watcher.updated() => { +1152 match report { +1153 Ok((report, _)) => { +1154 self.handle_net_report_report(report); +1155 #[cfg(not(wasm_browser))] +1156 { +1157 self.periodic_re_stun_timer = new_re_stun_timer(true); +1158 } +1159 } +1160 Err(_) => { +1161 warn!("net report watcher stopped"); +1162 } +1163 } +1164 } +1165 reason = self.direct_addr_done_rx.recv() => { +1166 match reason { +1167 Some(()) => { +1168 // check if a new run needs to be scheduled +1169 let state = self.netmon_watcher.get(); +1170 self.direct_addr_update_state.try_run(state.into()); +1171 } +1172 None => { +1173 warn!("direct addr watcher died"); +1174 } +1175 } +1176 } +1177 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1178 #[cfg(not(wasm_browser))] +1179 { +1180 if change.is_err() { +1181 trace!("tick: portmap watcher closed"); +1182 self.msock.metrics.magicsock.actor_tick_other.inc(); +1183 +1184 portmap_watcher_closed = true; +1185 continue; +1186 } +1187 +1188 trace!("tick: portmap changed"); +1189 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); +1190 let new_external_address = *portmap_watcher.borrow(); +1191 debug!("external address updated: {new_external_address:?}"); +1192 self.re_stun(UpdateReason::PortmapUpdated); +1193 } +1194 #[cfg(wasm_browser)] +1195 let _unused_in_browsers = change; +1196 }, +1197 state = self.netmon_watcher.updated() => { +1198 let Ok(state) = state else { +1199 trace!("tick: link change receiver closed"); +1200 self.msock.metrics.magicsock.actor_tick_other.inc(); +1201 continue; +1202 }; +1203 let is_major = state.is_major_change(&current_netmon_state); +1204 event!( +1205 target: "iroh::_events::link_change", +1206 Level::DEBUG, +1207 ?state, +1208 is_major +1209 ); +1210 current_netmon_state = state; +1211 self.msock.metrics.magicsock.actor_link_change.inc(); +1212 self.handle_network_change(is_major).await; +1213 } +1214 _ = remote_map_gc.tick() => { +1215 self.msock.remote_map.remove_closed_remote_state_actors(); +1216 } +1217 } +1218 } +1219 } +1220 +1221 async fn handle_network_change(&mut self, is_major: bool) { +1222 debug!(is_major, "link change detected"); +1223 +1224 if is_major { +1225 if let Err(err) = self.network_change_sender.rebind() { +1226 warn!("failed to rebind transports: {err:?}"); +1227 } +1228 +1229 #[cfg(not(wasm_browser))] +1230 self.msock.dns_resolver.reset().await; +1231 self.re_stun(UpdateReason::LinkChangeMajor); +1232 } else { +1233 self.re_stun(UpdateReason::LinkChangeMinor); +1234 } +1235 } +1236 +1237 fn handle_relay_map_change(&mut self) { +1238 self.re_stun(UpdateReason::RelayMapChange); +1239 } +1240 +1241 fn re_stun(&mut self, why: UpdateReason) { +1242 let state = self.netmon_watcher.get(); +1243 self.direct_addr_update_state +1244 .schedule_run(why, state.into()); +1245 } +1246 +1247 /// Processes an incoming actor message. +1248 /// +1249 /// Returns `true` if it was a shutdown. +1250 async fn handle_actor_message(&mut self, msg: ActorMessage) { +1251 match msg { +1252 ActorMessage::NetworkChange => { +1253 self.network_monitor.network_change().await.ok(); +1254 } +1255 ActorMessage::RelayMapChange => { +1256 self.handle_relay_map_change(); +1257 } +1258 #[cfg(test)] +1259 ActorMessage::ForceNetworkChange(is_major) => { +1260 self.handle_network_change(is_major).await; +1261 } +1262 } +1263 } +1264 +1265 /// Updates the direct addresses of this magic socket. +1266 /// +1267 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of +1268 /// direct addresses from: +1269 /// +1270 /// - The portmapper. +1271 /// - A net_report report. +1272 /// - The local interfaces IP addresses. +1273 #[cfg(not(wasm_browser))] +1274 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +1275 let portmap_watcher = self +1276 .direct_addr_update_state +1277 .port_mapper +1278 .watch_external_address(); +1279 +1280 // We only want to have one DirectAddr for each SocketAddr we have. So we store +1281 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +1282 // DirectAddr from each entry. +1283 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +1284 +1285 // First add PortMapper provided addresses. +1286 let maybe_port_mapped = *portmap_watcher.borrow(); +1287 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +1288 addrs +1289 .entry(portmap_ext) +1290 .or_insert(DirectAddrType::Portmapped); +1291 } +1292 +1293 // Next add STUN addresses from the net_report report. +1294 if let Some(net_report_report) = net_report_report { +1295 if let Some(global_v4) = net_report_report.global_v4 { +1296 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); +1297 +1298 // If they're behind a hard NAT and are using a fixed +1299 // port locally, assume they might've added a static +1300 // port mapping on their router to the same explicit +1301 // port that we are running with. Worst case it's an invalid candidate mapping. +1302 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { +1303 if addr.port() != 0 { +1304 Some(addr.port()) +1305 } else { +1306 None +1307 } +1308 }); +1309 +1310 if let Some(port) = port { +1311 if net_report_report +1312 .mapping_varies_by_dest() +1313 .unwrap_or_default() +1314 { +1315 let mut addr = global_v4; +1316 addr.set_port(port); +1317 addrs +1318 .entry(addr.into()) +1319 .or_insert(DirectAddrType::Qad4LocalPort); +1320 } +1321 } +1322 } +1323 if let Some(global_v6) = net_report_report.global_v6 { +1324 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); +1325 } +1326 } +1327 +1328 self.collect_local_addresses(&mut addrs); +1329 +1330 // Finally create and store store all these direct addresses and send any +1331 // queued call-me-maybe messages. +1332 self.msock.store_direct_addresses( +1333 addrs +1334 .iter() +1335 .map(|(addr, typ)| DirectAddr { +1336 addr: *addr, +1337 typ: *typ, +1338 }) +1339 .collect(), +1340 ); +1341 } +1342 +1343 #[cfg(not(wasm_browser))] +1344 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { +1345 // Matches the addresses that have been bound vs the requested ones. +1346 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +1347 .msock +1348 .ip_bind_addrs() +1349 .iter() +1350 .copied() +1351 .zip(self.msock.ip_local_addrs()) +1352 .collect(); +1353 +1354 // Do we listen on any IPv4 unspecified address? +1355 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +1356 if a.is_ipv4() && a.ip().is_unspecified() { +1357 Some(a.port()) +1358 } else { +1359 None +1360 } +1361 }); +1362 // Do we listen on any IPv6 unspecified address? +1363 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +1364 if a.is_ipv6() && a.ip().is_unspecified() { +1365 Some(a.port()) +1366 } else { +1367 None +1368 } +1369 }); +1370 +1371 // If a socket is bound to the unspecified address, create SocketAddrs for +1372 // each local IP address by pairing it with the port the socket is bound on. +1373 if local_addrs +1374 .iter() +1375 .any(|(_, local)| local.ip().is_unspecified()) +1376 { +1377 let LocalAddresses { +1378 regular: mut ips, +1379 loopback, +1380 } = self.netmon_watcher.get().local_addresses; +1381 if ips.is_empty() && addrs.is_empty() { +1382 // Include loopback addresses only if there are no other interfaces +1383 // or public addresses, this allows testing offline. +1384 ips = loopback; +1385 } +1386 +1387 for ip in ips { +1388 let port_if_unspecified = match ip { +1389 IpAddr::V4(_) => has_ipv4_unspecified, +1390 IpAddr::V6(_) => has_ipv6_unspecified, +1391 }; +1392 if let Some(port) = port_if_unspecified { +1393 let addr = SocketAddr::new(ip, port); +1394 addrs.entry(addr).or_insert(DirectAddrType::Local); +1395 } +1396 } +1397 } +1398 +1399 // If a socket is bound to a specific address, add it. +1400 for (bound, local) in local_addrs { +1401 if !bound.ip().is_unspecified() { +1402 addrs.entry(local).or_insert(DirectAddrType::Local); +1403 } +1404 } +1405 } +1406 +1407 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +1408 if let Some(ref mut r) = report { +1409 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +1410 if r.preferred_relay.is_none() { +1411 if let Some(my_relay) = self.msock.my_relay() { +1412 r.preferred_relay.replace(my_relay); +1413 } +1414 } +1415 +1416 // Notify all transports +1417 self.network_change_sender.on_network_change(r); +1418 } +1419 +1420 #[cfg(not(wasm_browser))] +1421 self.update_direct_addresses(report.as_ref()); +1422 } +1423} +1424 +1425fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +1426 // Pick a random duration between 20 and 26 seconds (just under 30s, +1427 // a common UDP NAT timeout on Linux,etc) +1428 let mut rng = rand::rng(); +1429 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); +1430 if initial_delay { +1431 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +1432 time::interval_at(time::Instant::now() + d, d) +1433 } else { +1434 debug!( +1435 "scheduling periodic_stun to run immediately and in {}s", +1436 d.as_secs() +1437 ); +1438 time::interval(d) +1439 } +1440} +1441 +1442/// The discovered direct addresses of this [`MagicSock`]. +1443/// +1444/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. +1445/// They include all locally bound ones as well as those discovered by other mechanisms like +1446/// QAD. +1447#[derive(derive_more::Debug, Clone, Default)] +1448struct DiscoveredDirectAddrs { +1449 /// The last set of discovered direct addresses. +1450 addrs: Watchable<BTreeSet<DirectAddr>>, +1451 +1452 /// The last time the direct addresses were updated, even if there was no change. +1453 /// +1454 /// This is only ever None at startup. +1455 updated_at: Arc<RwLock<Option<Instant>>>, +1456} +1457 +1458impl DiscoveredDirectAddrs { +1459 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +1460 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +1461 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +1462 let updated = self.addrs.set(addrs).is_ok(); +1463 if updated { +1464 event!( +1465 target: "iroh::_events::direct_addrs", +1466 Level::DEBUG, +1467 addrs = ?self.addrs.get(), +1468 ); +1469 } +1470 updated +1471 } +1472 +1473 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { +1474 self.addrs.get().into_iter().map(|da| da.addr) +1475 } +1476} +1477 +1478/// A *direct address* on which an iroh-endpoint might be contactable. +1479/// +1480/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be +1481/// contacted. These can come from various sources depending on the network topology of the +1482/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. +1483/// +1484/// This is essentially a combination of our local addresses combined with any reflexive +1485/// transport addresses we discovered using QAD. +1486#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +1487pub struct DirectAddr { +1488 /// The address. +1489 pub addr: SocketAddr, +1490 /// The origin of this direct address. +1491 pub typ: DirectAddrType, +1492} +1493 +1494/// The type of direct address. +1495/// +1496/// These are the various sources or origins from which an iroh endpoint might have found a +1497/// possible [`DirectAddr`]. +1498#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +1499pub enum DirectAddrType { +1500 /// Not yet determined.. +1501 Unknown, +1502 /// A locally bound socket address. +1503 Local, +1504 /// Public internet address discovered via QAD. +1505 /// +1506 /// When possible an iroh endpoint will perform QAD to discover which is the address +1507 /// from which it sends data on the public internet. This can be different from locally +1508 /// bound addresses when the endpoint is on a local network which performs NAT or similar. +1509 Qad, +1510 /// An address assigned by the router using port mapping. +1511 /// +1512 /// When possible an iroh endpoint will request a port mapping from the local router to +1513 /// get a publicly routable direct address. +1514 Portmapped, +1515 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +1516 /// +1517 /// It is possible to configure iroh to bound to a specific port and independently +1518 /// configure the router to forward this port to the iroh endpoint. This indicates a +1519 /// situation like this, which still uses QAD to discover the public address. +1520 Qad4LocalPort, +1521} +1522 +1523impl Display for DirectAddrType { +1524 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +1525 match self { +1526 DirectAddrType::Unknown => write!(f, "?"), +1527 DirectAddrType::Local => write!(f, "local"), +1528 DirectAddrType::Qad => write!(f, "qad"), +1529 DirectAddrType::Portmapped => write!(f, "portmap"), +1530 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +1531 } +1532 } +1533} +1534 +1535#[cfg(test)] +1536mod tests { +1537 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; +1538 +1539 use data_encoding::HEXLOWER; +1540 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; +1541 use n0_error::{Result, StackResultExt, StdResultExt}; +1542 use n0_future::{MergeBounded, StreamExt, time}; +1543 use n0_watcher::Watcher; +1544 use quinn::ServerConfig; +1545 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; +1546 use tokio_util::task::AbortOnDropHandle; +1547 use tracing::{Instrument, error, info, info_span, instrument}; +1548 use tracing_test::traced_test; +1549 +1550 use super::Options; +1551 use crate::{ +1552 Endpoint, RelayMode, SecretKey, +1553 discovery::static_provider::StaticProvider, +1554 dns::DnsResolver, +1555 magicsock::{ +1556 Handle, MagicSock, TransportConfig, +1557 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, +1558 }, +1559 tls::{self, DEFAULT_MAX_TLS_TICKETS}, +1560 }; +1561 +1562 const ALPN: &[u8] = b"n0/test/1"; +1563 +1564 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { +1565 let secret_key = SecretKey::generate(rng); +1566 let server_config = make_default_server_config(&secret_key); +1567 Options { +1568 transports: vec![ +1569 TransportConfig::default_ipv4(), +1570 TransportConfig::default_ipv6(), +1571 ], +1572 secret_key, +1573 proxy_url: None, +1574 dns_resolver: DnsResolver::new(), +1575 server_config, +1576 #[cfg(any(test, feature = "test-utils"))] +1577 insecure_skip_relay_cert_verify: false, +1578 #[cfg(any(test, feature = "test-utils"))] +1579 discovery_user_data: None, +1580 metrics: Default::default(), +1581 hooks: Default::default(), +1582 } +1583 } +1584 +1585 /// Generate a server config with no ALPNS and a default transport configuration +1586 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { +1587 let quic_server_config = +1588 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +1589 .make_server_config(vec![], false); +1590 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +1591 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +1592 server_config +1593 } +1594 +1595 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1596 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { +1597 info!("accepting conn"); +1598 let conn = ep.accept().await.expect("no conn"); +1599 +1600 info!("accepting"); +1601 let conn = conn.await.context("accepting")?; +1602 info!("accepting bi"); +1603 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; +1604 +1605 info!("reading"); +1606 let val = recv_bi +1607 .read_to_end(usize::MAX) +1608 .await +1609 .std_context("read to end")?; +1610 +1611 info!("replying"); +1612 for chunk in val.chunks(12) { +1613 send_bi.write_all(chunk).await.std_context("write all")?; +1614 } +1615 +1616 info!("finishing"); +1617 send_bi.finish().std_context("finish")?; +1618 send_bi.stopped().await.std_context("stopped")?; +1619 +1620 let stats = conn.stats(); +1621 info!("stats: {:#?}", stats); +1622 // TODO: ensure panics in this function are reported ok +1623 if matches!(loss, ExpectedLoss::AlmostNone) { +1624 for info in conn.paths().get().iter() { +1625 assert!( +1626 info.stats().lost_packets < 10, +1627 "[receiver] path {:?} should not loose many packets", +1628 info.remote_addr() +1629 ); +1630 } +1631 } +1632 +1633 info!("close"); +1634 conn.close(0u32.into(), b"done"); +1635 info!("wait idle"); +1636 ep.endpoint().wait_idle().await; +1637 +1638 Ok(()) +1639 } +1640 +1641 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1642 async fn echo_sender( +1643 ep: Endpoint, +1644 dest_id: EndpointId, +1645 msg: &[u8], +1646 loss: ExpectedLoss, +1647 ) -> Result { +1648 info!("connecting to {}", dest_id.fmt_short()); +1649 let dest = EndpointAddr::new(dest_id); +1650 let conn = ep.connect(dest, ALPN).await?; +1651 +1652 info!("opening bi"); +1653 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; +1654 +1655 info!("writing message"); +1656 send_bi.write_all(msg).await.std_context("write all")?; +1657 +1658 info!("finishing"); +1659 send_bi.finish().std_context("finish")?; +1660 send_bi.stopped().await.std_context("stopped")?; +1661 +1662 info!("reading_to_end"); +1663 let val = recv_bi +1664 .read_to_end(usize::MAX) +1665 .await +1666 .std_context("read to end")?; +1667 assert_eq!( +1668 val, +1669 msg, +1670 "[sender] expected {}, got {}", +1671 HEXLOWER.encode(msg), +1672 HEXLOWER.encode(&val) +1673 ); +1674 +1675 let stats = conn.stats(); +1676 info!("stats: {:#?}", stats); +1677 if matches!(loss, ExpectedLoss::AlmostNone) { +1678 for info in conn.paths().get() { +1679 assert!( +1680 info.stats().lost_packets < 10, +1681 "[sender] path {:?} should not loose many packets", +1682 info.remote_addr() +1683 ); +1684 } +1685 } +1686 +1687 info!("close"); +1688 conn.close(0u32.into(), b"done"); +1689 info!("wait idle"); +1690 ep.endpoint().wait_idle().await; +1691 Ok(()) +1692 } +1693 +1694 #[derive(Debug, Copy, Clone)] +1695 enum ExpectedLoss { +1696 AlmostNone, +1697 YeahSure, +1698 } +1699 +1700 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +1701 async fn run_roundtrip( +1702 sender: Endpoint, +1703 receiver: Endpoint, +1704 payload: &[u8], +1705 loss: ExpectedLoss, +1706 ) { +1707 let send_endpoint_id = sender.id(); +1708 let recv_endpoint_id = receiver.id(); +1709 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); +1710 +1711 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); +1712 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; +1713 let sender_is_err = match sender_res { +1714 Ok(()) => false, +1715 Err(err) => { +1716 eprintln!("[sender] Error:\n{err:#?}"); +1717 true +1718 } +1719 }; +1720 let receiver_is_err = match receiver_task.await { +1721 Ok(Ok(())) => false, +1722 Ok(Err(err)) => { +1723 eprintln!("[receiver] Error:\n{err:#?}"); +1724 true +1725 } +1726 Err(joinerr) => { +1727 if joinerr.is_panic() { +1728 std::panic::resume_unwind(joinerr.into_panic()); +1729 } else { +1730 eprintln!("[receiver] Error:\n{joinerr:#?}"); +1731 } +1732 true +1733 } +1734 }; +1735 if sender_is_err || receiver_is_err { +1736 panic!("Sender or receiver errored"); +1737 } +1738 } +1739 +1740 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. +1741 /// +1742 /// The endpoints do not use a relay server but can connect to each other via local +1743 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if +1744 /// the endpoints rebind. +1745 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { +1746 let discovery = StaticProvider::new(); +1747 let ep1 = Endpoint::builder() +1748 .relay_mode(RelayMode::Disabled) +1749 .alpns(vec![ALPN.to_vec()]) +1750 .discovery(discovery.clone()) +1751 .bind() +1752 .await +1753 .unwrap(); +1754 let ep2 = Endpoint::builder() +1755 .relay_mode(RelayMode::Disabled) +1756 .alpns(vec![ALPN.to_vec()]) +1757 .discovery(discovery.clone()) +1758 .bind() +1759 .await +1760 .unwrap(); +1761 discovery.add_endpoint_info(ep1.addr()); +1762 discovery.add_endpoint_info(ep2.addr()); +1763 +1764 let ep1_addr_stream = ep1.watch_addr().stream(); +1765 let ep2_addr_stream = ep2.watch_addr().stream(); +1766 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); +1767 let task = tokio::spawn(async move { +1768 while let Some(addr) = addr_stream.next().await { +1769 discovery.add_endpoint_info(addr); +1770 } +1771 }); +1772 +1773 (AbortOnDropHandle::new(task), ep1, ep2) +1774 } +1775 +1776 #[tokio::test(flavor = "multi_thread")] +1777 #[traced_test] +1778 async fn test_two_devices_roundtrip_quinn_magic() -> Result { +1779 let (_guard, m1, m2) = endpoint_pair().await; +1780 +1781 for i in 0..5 { +1782 info!("\n-- round {i}"); +1783 run_roundtrip( +1784 m1.clone(), +1785 m2.clone(), +1786 b"hello m1", +1787 ExpectedLoss::AlmostNone, +1788 ) +1789 .await; +1790 run_roundtrip( +1791 m2.clone(), +1792 m1.clone(), +1793 b"hello m2", +1794 ExpectedLoss::AlmostNone, +1795 ) +1796 .await; +1797 +1798 info!("\n-- larger data"); +1799 let mut data = vec![0u8; 10 * 1024]; +1800 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1801 rng.fill_bytes(&mut data); +1802 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; +1803 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; +1804 } +1805 +1806 Ok(()) +1807 } +1808 +1809 #[tokio::test] +1810 #[traced_test] +1811 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { +1812 let (_guard, m1, m2) = endpoint_pair().await; +1813 +1814 println!("Net change"); +1815 m1.magic_sock().force_network_change(true).await; +1816 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +1817 +1818 let _handle = AbortOnDropHandle::new(tokio::spawn({ +1819 let endpoint = m2.clone(); +1820 async move { +1821 while let Some(incoming) = endpoint.accept().await { +1822 println!("Incoming first conn!"); +1823 let conn = incoming.await.anyerr()?; +1824 conn.closed().await; +1825 } +1826 +1827 n0_error::Ok(()) +1828 } +1829 })); +1830 +1831 println!("first conn!"); +1832 let conn = m1.connect(m2.addr(), ALPN).await?; +1833 println!("Closing first conn"); +1834 conn.close(0u32.into(), b"bye lolz"); +1835 conn.closed().await; +1836 println!("Closed first conn"); +1837 +1838 Ok(()) +1839 } +1840 +1841 #[tokio::test(flavor = "multi_thread")] +1842 #[traced_test] +1843 async fn test_two_devices_roundtrip_network_change() -> Result { +1844 time::timeout( +1845 Duration::from_secs(90), +1846 test_two_devices_roundtrip_network_change_impl(), +1847 ) +1848 .await +1849 .std_context("timeout")? +1850 } +1851 +1852 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly +1853 /// with (simulated) network changes. +1854 async fn test_two_devices_roundtrip_network_change_impl() -> Result { +1855 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1856 let (_guard, m1, m2) = endpoint_pair().await; +1857 +1858 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { +1859 let delay = rng.random_range(10..=500); +1860 Duration::from_millis(delay) +1861 }; +1862 let rounds = 5; +1863 +1864 // Regular network changes to m1 only. +1865 let m1_network_change_guard = { +1866 let m1 = m1.clone(); +1867 let mut rng = rng.clone(); +1868 let task = tokio::spawn(async move { +1869 loop { +1870 println!("[m1] network change"); +1871 m1.magic_sock().force_network_change(true).await; +1872 time::sleep(offset(&mut rng)).await; +1873 } +1874 }); +1875 AbortOnDropHandle::new(task) +1876 }; +1877 +1878 for i in 0..rounds { +1879 println!("-- [m1 changes] round {}", i + 1); +1880 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +1881 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +1882 +1883 println!("-- [m1 changes] larger data"); +1884 let mut data = vec![0u8; 10 * 1024]; +1885 rng.fill_bytes(&mut data); +1886 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +1887 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +1888 } +1889 +1890 std::mem::drop(m1_network_change_guard); +1891 +1892 // Regular network changes to m2 only. +1893 let m2_network_change_guard = { +1894 let m2 = m2.clone(); +1895 let mut rng = rng.clone(); +1896 let task = tokio::spawn(async move { +1897 loop { +1898 println!("[m2] network change"); +1899 m2.magic_sock().force_network_change(true).await; +1900 time::sleep(offset(&mut rng)).await; +1901 } +1902 }); +1903 AbortOnDropHandle::new(task) +1904 }; +1905 +1906 for i in 0..rounds { +1907 println!("-- [m2 changes] round {}", i + 1); +1908 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +1909 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +1910 +1911 println!("-- [m2 changes] larger data"); +1912 let mut data = vec![0u8; 10 * 1024]; +1913 rng.fill_bytes(&mut data); +1914 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +1915 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +1916 } +1917 +1918 std::mem::drop(m2_network_change_guard); +1919 +1920 // Regular network changes to both m1 and m2 only. +1921 let m1_m2_network_change_guard = { +1922 let m1 = m1.clone(); +1923 let m2 = m2.clone(); +1924 let mut rng = rng.clone(); +1925 let task = tokio::spawn(async move { +1926 println!("-- [m1] network change"); +1927 m1.magic_sock().force_network_change(true).await; +1928 println!("-- [m2] network change"); +1929 m2.magic_sock().force_network_change(true).await; +1930 time::sleep(offset(&mut rng)).await; +1931 }); +1932 AbortOnDropHandle::new(task) +1933 }; +1934 +1935 for i in 0..rounds { +1936 println!("-- [m1 & m2 changes] round {}", i + 1); +1937 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +1938 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +1939 +1940 println!("-- [m1 & m2 changes] larger data"); +1941 let mut data = vec![0u8; 10 * 1024]; +1942 rng.fill_bytes(&mut data); +1943 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +1944 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +1945 } +1946 +1947 std::mem::drop(m1_m2_network_change_guard); +1948 Ok(()) +1949 } +1950 +1951 #[tokio::test(flavor = "multi_thread")] +1952 #[traced_test] +1953 async fn test_two_devices_setup_teardown() -> Result { +1954 for i in 0..10 { +1955 info!("-- round {i}"); +1956 info!("setting up magic stack"); +1957 let (_guard, m1, m2) = endpoint_pair().await; +1958 +1959 info!("closing endpoints"); +1960 let msock1 = m1.magic_sock(); +1961 let msock2 = m2.magic_sock(); +1962 m1.close().await; +1963 m2.close().await; +1964 +1965 assert!(msock1.msock.is_closed()); +1966 assert!(msock2.msock.is_closed()); +1967 } +1968 Ok(()) +1969 } +1970 +1971 #[tokio::test] +1972 #[traced_test] +1973 async fn test_direct_addresses() { +1974 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1975 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); +1976 +1977 // See if we can get endpoints. +1978 let eps0 = ms.ip_addrs().get(); +1979 println!("{eps0:?}"); +1980 assert!(!eps0.is_empty()); +1981 +1982 // Getting the endpoints again immediately should give the same results. +1983 let eps1 = ms.ip_addrs().get(); +1984 println!("{eps1:?}"); +1985 assert_eq!(eps0, eps1); +1986 } +1987 +1988 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. +1989 /// +1990 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +1991 /// connections using [`ALPN`]. +1992 /// +1993 /// Use [`magicsock_connect`] to establish connections. +1994 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] +1995 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { +1996 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +1997 .make_server_config(vec![ALPN.to_vec()], true); +1998 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +1999 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +2000 +2001 let dns_resolver = DnsResolver::new(); +2002 let opts = Options { +2003 transports: vec![ +2004 TransportConfig::default_ipv4(), +2005 TransportConfig::default_ipv6(), +2006 ], +2007 secret_key: secret_key.clone(), +2008 discovery_user_data: None, +2009 dns_resolver, +2010 proxy_url: None, +2011 server_config, +2012 insecure_skip_relay_cert_verify: false, +2013 metrics: Default::default(), +2014 hooks: Default::default(), +2015 }; +2016 let msock = MagicSock::spawn(opts).await?; +2017 Ok(msock) +2018 } +2019 +2020 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2021 /// +2022 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2023 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2024 async fn magicsock_connect( +2025 ep: &quinn::Endpoint, +2026 ep_secret_key: SecretKey, +2027 addr: EndpointIdMappedAddr, +2028 endpoint_id: EndpointId, +2029 ) -> Result<quinn::Connection> { +2030 // Endpoint::connect sets this, do the same to have similar behaviour. +2031 let mut transport_config = quinn::TransportConfig::default(); +2032 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2033 +2034 magicsock_connect_with_transport_config( +2035 ep, +2036 ep_secret_key, +2037 addr, +2038 endpoint_id, +2039 Arc::new(transport_config), +2040 ) +2041 .await +2042 } +2043 +2044 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2045 /// +2046 /// This version allows customising the transport config. +2047 /// +2048 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2049 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2050 async fn magicsock_connect_with_transport_config( +2051 ep: &quinn::Endpoint, +2052 ep_secret_key: SecretKey, +2053 mapped_addr: EndpointIdMappedAddr, +2054 endpoint_id: EndpointId, +2055 transport_config: Arc<quinn::TransportConfig>, +2056 ) -> Result<quinn::Connection> { +2057 let alpns = vec![ALPN.to_vec()]; +2058 let quic_client_config = +2059 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2060 .make_client_config(alpns, true); +2061 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +2062 client_config.transport_config(transport_config); +2063 let connect = ep +2064 .connect_with( +2065 client_config, +2066 mapped_addr.private_socket_addr(), +2067 &tls::name::encode(endpoint_id), +2068 ) +2069 .std_context("connect")?; +2070 let connection = connect.await.anyerr()?; +2071 Ok(connection) +2072 } +2073 +2074 #[tokio::test] +2075 #[traced_test] +2076 async fn test_try_send_no_send_addr() { +2077 // Regression test: if there is no send_addr we should keep being able to use the +2078 // Endpoint. +2079 +2080 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2081 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2082 let endpoint_id_2 = secret_key_2.public(); +2083 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); +2084 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); +2085 +2086 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2087 +2088 // Generate an address not present in the RemoteMap. +2089 let bad_addr = EndpointIdMappedAddr::generate(); +2090 +2091 // 500ms is rather fast here. Running this locally it should always be the correct +2092 // timeout. If this is too slow however the test will not become flaky as we are +2093 // expecting the timeout, we might just get the timeout for the wrong reason. But +2094 // this speeds up the test. +2095 let res = tokio::time::timeout( +2096 Duration::from_millis(500), +2097 magicsock_connect( +2098 msock_1.endpoint(), +2099 secret_key_1.clone(), +2100 bad_addr, +2101 endpoint_id_missing_endpoint, +2102 ), +2103 ) +2104 .await; +2105 assert!(res.is_err(), "expecting timeout"); +2106 +2107 // Now check we can still create another connection with this endpoint. +2108 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2109 +2110 // This needs an accept task +2111 let accept_task = tokio::spawn({ +2112 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2113 let incoming = ep.accept().await.std_context("no incoming")?; +2114 let _conn = incoming +2115 .accept() +2116 .std_context("accept")? +2117 .await +2118 .std_context("accepting")?; +2119 +2120 // Keep this connection alive for a while +2121 tokio::time::sleep(Duration::from_secs(10)).await; +2122 info!("accept finished"); +2123 Ok(()) +2124 } +2125 let ep = msock_2.endpoint().clone(); +2126 async move { +2127 if let Err(err) = accept(ep).await { +2128 error!("{err:#}"); +2129 } +2130 } +2131 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) +2132 }); +2133 let _accept_task = AbortOnDropHandle::new(accept_task); +2134 +2135 let addrs = msock_2 +2136 .ip_addrs() +2137 .get() +2138 .into_iter() +2139 .map(|x| TransportAddr::Ip(x.addr)); +2140 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); +2141 let addr = msock_1 +2142 .resolve_remote(endpoint_addr_2) +2143 .await +2144 .unwrap() +2145 .unwrap(); +2146 let res = tokio::time::timeout( +2147 Duration::from_secs(10), +2148 magicsock_connect( +2149 msock_1.endpoint(), +2150 secret_key_1.clone(), +2151 addr, +2152 endpoint_id_2, +2153 ), +2154 ) +2155 .await +2156 .expect("timeout while connecting"); +2157 +2158 // aka assert!(res.is_ok()) but with nicer error reporting. +2159 res.unwrap(); +2160 +2161 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +2162 // much internal state for now. +2163 } +2164 +2165 #[tokio::test] +2166 #[traced_test] +2167 async fn test_try_send_no_udp_addr_or_relay_url() { +2168 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +2169 // behaviour of MagicSock::try_send. +2170 +2171 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2172 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2173 let endpoint_id_2 = secret_key_2.public(); +2174 +2175 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2176 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2177 let ep_2 = msock_2.endpoint().clone(); +2178 +2179 // We need a task to accept the connection. +2180 let accept_task = tokio::spawn({ +2181 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2182 let incoming = ep.accept().await.std_context("no incoming")?; +2183 let conn = incoming +2184 .accept() +2185 .std_context("accept")? +2186 .await +2187 .std_context("connecting")?; +2188 let mut stream = conn.accept_uni().await.std_context("accept uni")?; +2189 stream +2190 .read_to_end(1 << 16) +2191 .await +2192 .std_context("read to end")?; +2193 info!("accept finished"); +2194 Ok(()) +2195 } +2196 async move { +2197 if let Err(err) = accept(ep_2).await { +2198 error!("{err:#}"); +2199 } +2200 } +2201 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) +2202 }); +2203 let _accept_task = AbortOnDropHandle::new(accept_task); +2204 +2205 // Add an entry in the RemoteMap of ep_1 with an invalid socket address +2206 let empty_addr_2 = EndpointAddr::from_parts( +2207 endpoint_id_2, +2208 [TransportAddr::Ip( +2209 // Reserved IP range for documentation (unreachable) +2210 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), +2211 )], +2212 ); +2213 let addr_2 = msock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); +2214 +2215 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +2216 // not take forever. You need to check the log output to verify this is really +2217 // triggering the correct error. +2218 // In test_try_send_no_send_addr() above you may have noticed we used +2219 // tokio::time::timeout() on the connection attempt instead. Here however we want +2220 // Quinn itself to have fully given up on the connection attempt because we will +2221 // later connect to **the same** endpoint. If Quinn did not give up on the connection +2222 // we'd close it on drop, and the retransmits of the close packets would interfere +2223 // with the next handshake, closing it during the handshake. This makes the test a +2224 // little slower though. +2225 let mut transport_config = quinn::TransportConfig::default(); +2226 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +2227 let res = magicsock_connect_with_transport_config( +2228 msock_1.endpoint(), +2229 secret_key_1.clone(), +2230 addr_2, +2231 endpoint_id_2, +2232 Arc::new(transport_config), +2233 ) +2234 .await; +2235 assert!(res.is_err(), "expected timeout"); +2236 info!("first connect timed out as expected"); +2237 +2238 // Provide correct addressing information +2239 let correct_addr_2 = EndpointAddr::from_parts( +2240 endpoint_id_2, +2241 msock_2 +2242 .ip_addrs() +2243 .get() +2244 .into_iter() +2245 .map(|x| TransportAddr::Ip(x.addr)), +2246 ); +2247 let addr_2a = msock_1 +2248 .resolve_remote(correct_addr_2) +2249 .await +2250 .unwrap() +2251 .unwrap(); +2252 assert_eq!(addr_2, addr_2a); +2253 +2254 // We can now connect +2255 tokio::time::timeout(Duration::from_secs(10), async move { +2256 info!("establishing new connection"); +2257 let conn = magicsock_connect( +2258 msock_1.endpoint(), +2259 secret_key_1.clone(), +2260 addr_2, +2261 endpoint_id_2, +2262 ) +2263 .await +2264 .unwrap(); +2265 info!("have connection"); +2266 let mut stream = conn.open_uni().await.unwrap(); +2267 stream.write_all(b"hello").await.unwrap(); +2268 stream.finish().unwrap(); +2269 stream.stopped().await.unwrap(); +2270 info!("finished stream"); +2271 }) +2272 .await +2273 .expect("connection timed out"); +2274 +2275 // TODO: could remove the addresses again, send, add it back and see it recover. +2276 // But we don't have that much private access to the RemoteMap. This will do for now. +2277 } +2278}
    \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/remote_map.rs.html b/pr/3381/docs/src/iroh/magicsock/remote_map.rs.html index c52798d402..5e72b5152b 100644 --- a/pr/3381/docs/src/iroh/magicsock/remote_map.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/remote_map.rs.html @@ -18,227 +18,222 @@ 18use super::{ 19 DirectAddr, MagicsockMetrics, 20 mapped_addrs::{AddrMap, EndpointIdMappedAddr, RelayMappedAddr}, -21 transports::TransportsSender, -22}; -23use crate::discovery::ConcurrentDiscovery; -24 -25mod remote_state; -26 -27/// Interval in which handles to closed [`RemoteStateActor`]s should be removed. -28pub(super) const REMOTE_MAP_GC_INTERVAL: Duration = Duration::from_secs(60); -29 -30// TODO: use this -31// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced -32// /// periodically via [`NodeMap::prune_inactive`]. -33// const MAX_INACTIVE_NODES: usize = 30; -34 -35/// Map containing all the state for endpoints. -36/// -37/// - Has actors which each manage all the connection state for a remote endpoint. -38/// -39/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6 -40/// addressing space that is used by Quinn. -41#[derive(Debug)] -42pub(crate) struct RemoteMap { -43 // -44 // State we keep about remote endpoints. -45 // -46 /// The actors tracking each remote endpoint. -47 actor_handles: Mutex<FxHashMap<EndpointId, RemoteStateHandle>>, -48 /// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s. -49 pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>, -50 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. -51 pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -52 -53 // -54 // State needed to start a new RemoteStateHandle. -55 // -56 /// The endpoint ID of the local endpoint. -57 local_endpoint_id: EndpointId, -58 metrics: Arc<MagicsockMetrics>, -59 /// The "direct" addresses known for our local endpoint -60 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -61 sender: TransportsSender, -62 discovery: ConcurrentDiscovery, -63} -64 -65impl RemoteMap { -66 /// Creates a new [`RemoteMap`]. -67 pub(super) fn new( -68 local_endpoint_id: EndpointId, -69 metrics: Arc<MagicsockMetrics>, -70 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -71 sender: TransportsSender, -72 discovery: ConcurrentDiscovery, -73 ) -> Self { -74 Self { -75 actor_handles: Mutex::new(FxHashMap::default()), -76 endpoint_mapped_addrs: Default::default(), -77 relay_mapped_addrs: Default::default(), -78 local_endpoint_id, -79 metrics, -80 local_direct_addrs, -81 sender, -82 discovery, -83 } +21}; +22use crate::discovery::ConcurrentDiscovery; +23 +24mod remote_state; +25 +26/// Interval in which handles to closed [`RemoteStateActor`]s should be removed. +27pub(super) const REMOTE_MAP_GC_INTERVAL: Duration = Duration::from_secs(60); +28 +29// TODO: use this +30// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced +31// /// periodically via [`NodeMap::prune_inactive`]. +32// const MAX_INACTIVE_NODES: usize = 30; +33 +34/// Map containing all the state for endpoints. +35/// +36/// - Has actors which each manage all the connection state for a remote endpoint. +37/// +38/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6 +39/// addressing space that is used by Quinn. +40#[derive(Debug)] +41pub(crate) struct RemoteMap { +42 // +43 // State we keep about remote endpoints. +44 // +45 /// The actors tracking each remote endpoint. +46 actor_handles: Mutex<FxHashMap<EndpointId, RemoteStateHandle>>, +47 /// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s. +48 pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>, +49 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. +50 pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +51 +52 // +53 // State needed to start a new RemoteStateHandle. +54 // +55 /// The endpoint ID of the local endpoint. +56 local_endpoint_id: EndpointId, +57 metrics: Arc<MagicsockMetrics>, +58 /// The "direct" addresses known for our local endpoint +59 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +60 discovery: ConcurrentDiscovery, +61} +62 +63impl RemoteMap { +64 /// Creates a new [`RemoteMap`]. +65 pub(super) fn new( +66 local_endpoint_id: EndpointId, +67 metrics: Arc<MagicsockMetrics>, +68 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +69 discovery: ConcurrentDiscovery, +70 ) -> Self { +71 Self { +72 actor_handles: Mutex::new(FxHashMap::default()), +73 endpoint_mapped_addrs: Default::default(), +74 relay_mapped_addrs: Default::default(), +75 local_endpoint_id, +76 metrics, +77 local_direct_addrs, +78 discovery, +79 } +80 } +81 +82 pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr { +83 self.endpoint_mapped_addrs.get(&eid) 84 } 85 -86 pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr { -87 self.endpoint_mapped_addrs.get(&eid) -88 } -89 -90 /// Removes the handles for terminated [`RemoteStateActor`]s from the endpoint map. -91 /// -92 /// This should be called periodically to remove handles to endpoint state actors -93 /// that have shutdown after their idle timeout expired. -94 pub(super) fn remove_closed_remote_state_actors(&self) { -95 let mut handles = self.actor_handles.lock().expect("poisoned"); -96 handles.retain(|_eid, handle| !handle.sender.is_closed()) -97 } -98 -99 /// Returns the sender for the [`RemoteStateActor`]. -100 /// -101 /// If needed a new actor is started on demand. -102 /// -103 /// [`RemoteStateActor`]: remote_state::RemoteStateActor -104 pub(super) fn remote_state_actor(&self, eid: EndpointId) -> mpsc::Sender<RemoteStateMessage> { -105 let mut handles = self.actor_handles.lock().expect("poisoned"); -106 match handles.entry(eid) { -107 hash_map::Entry::Occupied(mut entry) => { -108 if let Some(sender) = entry.get().sender.get() { -109 sender -110 } else { -111 // The actor is dead: Start a new actor. -112 let (handle, sender) = self.start_remote_state_actor(eid); -113 entry.insert(handle); -114 sender -115 } -116 } -117 hash_map::Entry::Vacant(entry) => { -118 let (handle, sender) = self.start_remote_state_actor(eid); -119 entry.insert(handle); -120 sender -121 } -122 } -123 } -124 -125 /// Starts a new remote state actor and returns a handle and a sender. -126 /// -127 /// The handle is not inserted into the endpoint map, this must be done by the caller of this function. -128 fn start_remote_state_actor( -129 &self, -130 eid: EndpointId, -131 ) -> (RemoteStateHandle, mpsc::Sender<RemoteStateMessage>) { -132 // Ensure there is a RemoteMappedAddr for this EndpointId. -133 self.endpoint_mapped_addrs.get(&eid); -134 let handle = RemoteStateActor::new( -135 eid, -136 self.local_endpoint_id, -137 self.local_direct_addrs.clone(), -138 self.relay_mapped_addrs.clone(), -139 self.metrics.clone(), -140 self.sender.clone(), -141 self.discovery.clone(), -142 ) -143 .start(); -144 let sender = handle.sender.get().expect("just created"); -145 (handle, sender) -146 } -147} -148 -149/// The origin or *source* through which an address associated with a remote endpoint -150/// was discovered. -151/// -152/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the -153/// [`Source`]s of the endpoint itself. -154/// -155/// A [`Source`] helps track how and where an address was learned. Multiple -156/// sources can be associated with a single address, if we have discovered this -157/// address through multiple means. -158#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] -159#[strum(serialize_all = "kebab-case")] -160#[allow(private_interfaces)] -161pub enum Source { -162 /// An endpoint communicated with us first via UDP. -163 Udp, -164 /// An endpoint communicated with us first via relay. -165 Relay, -166 /// Application layer added the address directly. -167 App, -168 /// The address was discovered by a discovery service. -169 #[strum(serialize = "{name}")] -170 Discovery { -171 /// The name of the discovery service that discovered the address. -172 name: String, -173 }, -174 /// Application layer with a specific name added the endpoint directly. -175 #[strum(serialize = "{name}")] -176 NamedApp { -177 /// The name of the application that added the endpoint -178 name: String, -179 }, -180 /// The address was advertised by a call-me-maybe DISCO message. -181 #[strum(serialize = "CallMeMaybe")] -182 CallMeMaybe { -183 /// private marker -184 _0: Private, -185 }, -186 /// We received a ping on the path. -187 #[strum(serialize = "Ping")] -188 Ping { -189 /// private marker -190 _0: Private, -191 }, -192 /// We established a connection on this address. -193 /// -194 /// Currently this means the path was in uses as [`PathId::ZERO`] when the a connection -195 /// was added to the `RemoteStateActor`. -196 /// -197 /// [`PathId::ZERO`]: quinn_proto::PathId::ZERO -198 #[strum(serialize = "Connection")] -199 Connection { -200 /// private marker -201 _0: Private, -202 }, -203} -204 -205/// Helper to ensure certain `Source` variants can not be constructed externally. -206#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Hash)] -207struct Private; -208 -209/// An (Ip, Port) pair. -210/// -211/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket -212/// addresses include fields that can't be assumed consistent even within a single connection. -213#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] -214#[display("{}", SocketAddr::from(*self))] -215pub struct IpPort { -216 ip: IpAddr, -217 port: u16, -218} -219 -220impl From<SocketAddr> for IpPort { -221 fn from(socket_addr: SocketAddr) -> Self { -222 Self { -223 ip: socket_addr.ip(), -224 port: socket_addr.port(), -225 } -226 } -227} -228 -229impl From<IpPort> for SocketAddr { -230 fn from(ip_port: IpPort) -> Self { -231 let IpPort { ip, port } = ip_port; -232 (ip, port).into() -233 } -234} +86 /// Removes the handles for terminated [`RemoteStateActor`]s from the endpoint map. +87 /// +88 /// This should be called periodically to remove handles to endpoint state actors +89 /// that have shutdown after their idle timeout expired. +90 pub(super) fn remove_closed_remote_state_actors(&self) { +91 let mut handles = self.actor_handles.lock().expect("poisoned"); +92 handles.retain(|_eid, handle| !handle.sender.is_closed()) +93 } +94 +95 /// Returns the sender for the [`RemoteStateActor`]. +96 /// +97 /// If needed a new actor is started on demand. +98 /// +99 /// [`RemoteStateActor`]: remote_state::RemoteStateActor +100 pub(super) fn remote_state_actor(&self, eid: EndpointId) -> mpsc::Sender<RemoteStateMessage> { +101 let mut handles = self.actor_handles.lock().expect("poisoned"); +102 match handles.entry(eid) { +103 hash_map::Entry::Occupied(mut entry) => { +104 if let Some(sender) = entry.get().sender.get() { +105 sender +106 } else { +107 // The actor is dead: Start a new actor. +108 let (handle, sender) = self.start_remote_state_actor(eid); +109 entry.insert(handle); +110 sender +111 } +112 } +113 hash_map::Entry::Vacant(entry) => { +114 let (handle, sender) = self.start_remote_state_actor(eid); +115 entry.insert(handle); +116 sender +117 } +118 } +119 } +120 +121 /// Starts a new remote state actor and returns a handle and a sender. +122 /// +123 /// The handle is not inserted into the endpoint map, this must be done by the caller of this function. +124 fn start_remote_state_actor( +125 &self, +126 eid: EndpointId, +127 ) -> (RemoteStateHandle, mpsc::Sender<RemoteStateMessage>) { +128 // Ensure there is a RemoteMappedAddr for this EndpointId. +129 self.endpoint_mapped_addrs.get(&eid); +130 let handle = RemoteStateActor::new( +131 eid, +132 self.local_endpoint_id, +133 self.local_direct_addrs.clone(), +134 self.relay_mapped_addrs.clone(), +135 self.metrics.clone(), +136 self.discovery.clone(), +137 ) +138 .start(); +139 let sender = handle.sender.get().expect("just created"); +140 (handle, sender) +141 } +142} +143 +144/// The origin or *source* through which an address associated with a remote endpoint +145/// was discovered. +146/// +147/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the +148/// [`Source`]s of the endpoint itself. +149/// +150/// A [`Source`] helps track how and where an address was learned. Multiple +151/// sources can be associated with a single address, if we have discovered this +152/// address through multiple means. +153#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] +154#[strum(serialize_all = "kebab-case")] +155#[allow(private_interfaces)] +156pub enum Source { +157 /// An endpoint communicated with us first via UDP. +158 Udp, +159 /// An endpoint communicated with us first via relay. +160 Relay, +161 /// Application layer added the address directly. +162 App, +163 /// The address was discovered by a discovery service. +164 #[strum(serialize = "{name}")] +165 Discovery { +166 /// The name of the discovery service that discovered the address. +167 name: String, +168 }, +169 /// Application layer with a specific name added the endpoint directly. +170 #[strum(serialize = "{name}")] +171 NamedApp { +172 /// The name of the application that added the endpoint +173 name: String, +174 }, +175 /// The address was advertised by a call-me-maybe DISCO message. +176 #[strum(serialize = "CallMeMaybe")] +177 CallMeMaybe { +178 /// private marker +179 _0: Private, +180 }, +181 /// We received a ping on the path. +182 #[strum(serialize = "Ping")] +183 Ping { +184 /// private marker +185 _0: Private, +186 }, +187 /// We established a connection on this address. +188 /// +189 /// Currently this means the path was in uses as [`PathId::ZERO`] when the a connection +190 /// was added to the `RemoteStateActor`. +191 /// +192 /// [`PathId::ZERO`]: quinn_proto::PathId::ZERO +193 #[strum(serialize = "Connection")] +194 Connection { +195 /// private marker +196 _0: Private, +197 }, +198} +199 +200/// Helper to ensure certain `Source` variants can not be constructed externally. +201#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Hash)] +202struct Private; +203 +204/// An (Ip, Port) pair. +205/// +206/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket +207/// addresses include fields that can't be assumed consistent even within a single connection. +208#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +209#[display("{}", SocketAddr::from(*self))] +210pub struct IpPort { +211 ip: IpAddr, +212 port: u16, +213} +214 +215impl From<SocketAddr> for IpPort { +216 fn from(socket_addr: SocketAddr) -> Self { +217 Self { +218 ip: socket_addr.ip(), +219 port: socket_addr.port(), +220 } +221 } +222} +223 +224impl From<IpPort> for SocketAddr { +225 fn from(ip_port: IpPort) -> Self { +226 let IpPort { ip, port } = ip_port; +227 (ip, port).into() +228 } +229} +230 +231impl IpPort { +232 pub fn ip(&self) -> &IpAddr { +233 &self.ip +234 } 235 -236impl IpPort { -237 pub fn ip(&self) -> &IpAddr { -238 &self.ip -239 } -240 -241 pub fn port(&self) -> u16 { -242 self.port -243 } -244}
    \ No newline at end of file +236 pub fn port(&self) -> u16 { +237 self.port +238 } +239} \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3381/docs/src/iroh/magicsock/remote_map/remote_state.rs.html index ac0d1ac1ad..47dc3b6ffd 100644 --- a/pr/3381/docs/src/iroh/magicsock/remote_map/remote_state.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/remote_map/remote_state.rs.html @@ -140,1220 +140,1221 @@ 140 // 141 /// Metrics. 142 metrics: Arc<MagicsockMetrics>, -143 sender: TransportsSender, -144 /// Our local addresses. -145 /// -146 /// These are our local addresses and any reflexive transport addresses. -147 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -148 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. -149 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -150 /// Discovery service, cloned from the magicsock. -151 discovery: ConcurrentDiscovery, -152 -153 // Internal state - Quinn Connections we are managing. -154 // -155 /// All connections we have to this remote endpoint. -156 connections: FxHashMap<ConnId, ConnectionState>, -157 /// Notifications when connections are closed. -158 connections_close: FuturesUnordered<OnClosed>, -159 /// Events emitted by Quinn about path changes, for all paths, all connections. -160 path_events: PathEvents, -161 /// A stream of events of announced NAT traversal candidate addresses for all connections. -162 addr_events: AddrEvents, -163 -164 // Internal state - Holepunching and path state. -165 // -166 /// All possible paths we are aware of. -167 /// -168 /// These paths might be entirely impossible to use, since they are added by discovery -169 /// mechanisms. The are only potentially usable. -170 paths: RemotePathState, -171 /// Information about the last holepunching attempt. -172 last_holepunch: Option<HolepunchAttempt>, -173 /// The path we currently consider the preferred path to the remote endpoint. -174 /// -175 /// **We expect this path to work.** If we become aware this path is broken then it is -176 /// set back to `None`. Having a selected path does not mean we may not be able to get -177 /// a better path: e.g. when the selected path is a relay path we still need to trigger -178 /// holepunching regularly. -179 /// -180 /// We only select a path once the path is functional in Quinn. -181 selected_path: Watchable<Option<transports::Addr>>, -182 /// Time at which we should schedule the next holepunch attempt. -183 scheduled_holepunch: Option<Instant>, -184 /// When to next attempt opening paths in [`Self::pending_open_paths`]. -185 scheduled_open_path: Option<Instant>, -186 /// Paths which we still need to open. -187 /// -188 /// They failed to open because we did not have enough CIDs issued by the remote. -189 pending_open_paths: VecDeque<transports::Addr>, -190 -191 // Internal state - Discovery -192 // -193 /// Stream of discovery results, or always pending if discovery is not running. -194 discovery_stream: DiscoveryStream, -195} -196 -197impl RemoteStateActor { -198 #[allow(clippy::too_many_arguments)] -199 pub(super) fn new( -200 endpoint_id: EndpointId, -201 local_endpoint_id: EndpointId, -202 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -203 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -204 metrics: Arc<MagicsockMetrics>, -205 sender: TransportsSender, -206 discovery: ConcurrentDiscovery, -207 ) -> Self { -208 Self { -209 endpoint_id, -210 local_endpoint_id, -211 metrics, -212 local_direct_addrs, -213 relay_mapped_addrs, -214 discovery, -215 connections: FxHashMap::default(), -216 connections_close: Default::default(), -217 path_events: Default::default(), -218 addr_events: Default::default(), -219 paths: Default::default(), -220 last_holepunch: None, -221 selected_path: Default::default(), -222 scheduled_holepunch: None, -223 scheduled_open_path: None, -224 pending_open_paths: VecDeque::new(), -225 sender, -226 discovery_stream: Either::Left(n0_future::stream::pending()), -227 } -228 } -229 -230 pub(super) fn start(self) -> RemoteStateHandle { -231 let (tx, rx) = guarded_channel(16); -232 let me = self.local_endpoint_id; -233 let endpoint_id = self.endpoint_id; -234 -235 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into -236 // here somehow. Instead we have no parent and explicitly set the me attribute. If -237 // we don't explicitly set a span we get the spans from whatever call happens to -238 // first create the actor, which is often very confusing as it then keeps those -239 // spans for all logging of the actor. -240 let task = task::spawn(self.run(rx).instrument(info_span!( -241 parent: None, -242 "RemoteStateActor", -243 me = %me.fmt_short(), -244 remote = %endpoint_id.fmt_short(), -245 ))); -246 RemoteStateHandle { -247 sender: tx, -248 _task: AbortOnDropHandle::new(task), -249 } -250 } -251 -252 /// Runs the main loop of the actor. -253 /// -254 /// Note that the actor uses async handlers for tasks from the main loop. The actor is -255 /// not processing items from the inbox while waiting on any async calls. So some -256 /// discipline is needed to not turn pending for a long time. -257 async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) { -258 trace!("actor started"); -259 let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT); -260 n0_future::pin!(idle_timeout); -261 loop { -262 let scheduled_path_open = match self.scheduled_open_path { -263 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -264 None => MaybeFuture::None, -265 }; -266 n0_future::pin!(scheduled_path_open); -267 let scheduled_hp = match self.scheduled_holepunch { -268 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -269 None => MaybeFuture::None, -270 }; -271 n0_future::pin!(scheduled_hp); -272 if !inbox.is_idle() || !self.connections.is_empty() { -273 idle_timeout -274 .as_mut() -275 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -276 } -277 tokio::select! { -278 biased; -279 msg = inbox.recv() => { -280 match msg { -281 Some(msg) => self.handle_message(msg).await, -282 None => break, -283 } +143 /// Our local addresses. +144 /// +145 /// These are our local addresses and any reflexive transport addresses. +146 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +147 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. +148 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +149 /// Discovery service, cloned from the magicsock. +150 discovery: ConcurrentDiscovery, +151 +152 // Internal state - Quinn Connections we are managing. +153 // +154 /// All connections we have to this remote endpoint. +155 connections: FxHashMap<ConnId, ConnectionState>, +156 /// Notifications when connections are closed. +157 connections_close: FuturesUnordered<OnClosed>, +158 /// Events emitted by Quinn about path changes, for all paths, all connections. +159 path_events: PathEvents, +160 /// A stream of events of announced NAT traversal candidate addresses for all connections. +161 addr_events: AddrEvents, +162 +163 // Internal state - Holepunching and path state. +164 // +165 /// All possible paths we are aware of. +166 /// +167 /// These paths might be entirely impossible to use, since they are added by discovery +168 /// mechanisms. The are only potentially usable. +169 paths: RemotePathState, +170 /// Information about the last holepunching attempt. +171 last_holepunch: Option<HolepunchAttempt>, +172 /// The path we currently consider the preferred path to the remote endpoint. +173 /// +174 /// **We expect this path to work.** If we become aware this path is broken then it is +175 /// set back to `None`. Having a selected path does not mean we may not be able to get +176 /// a better path: e.g. when the selected path is a relay path we still need to trigger +177 /// holepunching regularly. +178 /// +179 /// We only select a path once the path is functional in Quinn. +180 selected_path: Watchable<Option<transports::Addr>>, +181 /// Time at which we should schedule the next holepunch attempt. +182 scheduled_holepunch: Option<Instant>, +183 /// When to next attempt opening paths in [`Self::pending_open_paths`]. +184 scheduled_open_path: Option<Instant>, +185 /// Paths which we still need to open. +186 /// +187 /// They failed to open because we did not have enough CIDs issued by the remote. +188 pending_open_paths: VecDeque<transports::Addr>, +189 +190 // Internal state - Discovery +191 // +192 /// Stream of discovery results, or always pending if discovery is not running. +193 discovery_stream: DiscoveryStream, +194} +195 +196impl RemoteStateActor { +197 #[allow(clippy::too_many_arguments)] +198 pub(super) fn new( +199 endpoint_id: EndpointId, +200 local_endpoint_id: EndpointId, +201 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +202 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +203 metrics: Arc<MagicsockMetrics>, +204 discovery: ConcurrentDiscovery, +205 ) -> Self { +206 Self { +207 endpoint_id, +208 local_endpoint_id, +209 metrics, +210 local_direct_addrs, +211 relay_mapped_addrs, +212 discovery, +213 connections: FxHashMap::default(), +214 connections_close: Default::default(), +215 path_events: Default::default(), +216 addr_events: Default::default(), +217 paths: Default::default(), +218 last_holepunch: None, +219 selected_path: Default::default(), +220 scheduled_holepunch: None, +221 scheduled_open_path: None, +222 pending_open_paths: VecDeque::new(), +223 discovery_stream: Either::Left(n0_future::stream::pending()), +224 } +225 } +226 +227 pub(super) fn start(self) -> RemoteStateHandle { +228 let (tx, rx) = guarded_channel(16); +229 let me = self.local_endpoint_id; +230 let endpoint_id = self.endpoint_id; +231 +232 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into +233 // here somehow. Instead we have no parent and explicitly set the me attribute. If +234 // we don't explicitly set a span we get the spans from whatever call happens to +235 // first create the actor, which is often very confusing as it then keeps those +236 // spans for all logging of the actor. +237 let task = task::spawn(self.run(rx).instrument(info_span!( +238 parent: None, +239 "RemoteStateActor", +240 me = %me.fmt_short(), +241 remote = %endpoint_id.fmt_short(), +242 ))); +243 RemoteStateHandle { +244 sender: tx, +245 _task: AbortOnDropHandle::new(task), +246 } +247 } +248 +249 /// Runs the main loop of the actor. +250 /// +251 /// Note that the actor uses async handlers for tasks from the main loop. The actor is +252 /// not processing items from the inbox while waiting on any async calls. So some +253 /// discipline is needed to not turn pending for a long time. +254 async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) { +255 trace!("actor started"); +256 let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT); +257 n0_future::pin!(idle_timeout); +258 loop { +259 let scheduled_path_open = match self.scheduled_open_path { +260 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +261 None => MaybeFuture::None, +262 }; +263 n0_future::pin!(scheduled_path_open); +264 let scheduled_hp = match self.scheduled_holepunch { +265 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +266 None => MaybeFuture::None, +267 }; +268 n0_future::pin!(scheduled_hp); +269 if !inbox.is_idle() || !self.connections.is_empty() { +270 idle_timeout +271 .as_mut() +272 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +273 } +274 tokio::select! { +275 biased; +276 msg = inbox.recv() => { +277 match msg { +278 Some(msg) => self.handle_message(msg).await, +279 None => break, +280 } +281 } +282 Some((id, evt)) = self.path_events.next() => { +283 self.handle_path_event(id, evt); 284 } -285 Some((id, evt)) = self.path_events.next() => { -286 self.handle_path_event(id, evt); -287 } -288 Some((id, evt)) = self.addr_events.next() => { -289 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); -290 self.trigger_holepunching().await; -291 } -292 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { -293 self.connections.remove(&conn_id); -294 if self.connections.is_empty() { -295 trace!("last connection closed - clearing selected_path"); -296 self.selected_path.set(None).ok(); -297 } -298 } -299 res = self.local_direct_addrs.updated() => { -300 if let Err(n0_watcher::Disconnected) = res { -301 trace!("direct address watcher disconnected, shutting down"); -302 break; -303 } -304 self.local_addrs_updated(); -305 trace!("local addrs updated, triggering holepunching"); -306 self.trigger_holepunching().await; -307 } -308 _ = &mut scheduled_path_open => { -309 trace!("triggering scheduled path_open"); -310 self.scheduled_open_path = None; -311 let mut addrs = std::mem::take(&mut self.pending_open_paths); -312 while let Some(addr) = addrs.pop_front() { -313 self.open_path(&addr); -314 } -315 } -316 _ = &mut scheduled_hp => { -317 trace!("triggering scheduled holepunching"); -318 self.scheduled_holepunch = None; -319 self.trigger_holepunching().await; +285 Some((id, evt)) = self.addr_events.next() => { +286 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); +287 self.trigger_holepunching().await; +288 } +289 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { +290 self.connections.remove(&conn_id); +291 if self.connections.is_empty() { +292 trace!("last connection closed - clearing selected_path"); +293 self.selected_path.set(None).ok(); +294 } +295 } +296 res = self.local_direct_addrs.updated() => { +297 if let Err(n0_watcher::Disconnected) = res { +298 trace!("direct address watcher disconnected, shutting down"); +299 break; +300 } +301 self.local_addrs_updated(); +302 trace!("local addrs updated, triggering holepunching"); +303 self.trigger_holepunching().await; +304 } +305 _ = &mut scheduled_path_open => { +306 trace!("triggering scheduled path_open"); +307 self.scheduled_open_path = None; +308 let mut addrs = std::mem::take(&mut self.pending_open_paths); +309 while let Some(addr) = addrs.pop_front() { +310 self.open_path(&addr); +311 } +312 } +313 _ = &mut scheduled_hp => { +314 trace!("triggering scheduled holepunching"); +315 self.scheduled_holepunch = None; +316 self.trigger_holepunching().await; +317 } +318 item = self.discovery_stream.next() => { +319 self.handle_discovery_item(item); 320 } -321 item = self.discovery_stream.next() => { -322 self.handle_discovery_item(item); -323 } -324 _ = &mut idle_timeout => { -325 if self.connections.is_empty() && inbox.close_if_idle() { -326 trace!("idle timeout expired and still idle: terminate actor"); -327 break; -328 } else { -329 // Seems like we weren't really idle, so we reset -330 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -331 } -332 } -333 } -334 } -335 trace!("actor terminating"); -336 } -337 -338 /// Handles an actor message. -339 /// -340 /// Error returns are fatal and kill the actor. -341 #[instrument(skip(self))] -342 async fn handle_message(&mut self, msg: RemoteStateMessage) { -343 // trace!("handling message"); -344 match msg { -345 RemoteStateMessage::SendDatagram(transmit) => { -346 self.handle_msg_send_datagram(transmit).await; +321 _ = &mut idle_timeout => { +322 if self.connections.is_empty() && inbox.close_if_idle() { +323 trace!("idle timeout expired and still idle: terminate actor"); +324 break; +325 } else { +326 // Seems like we weren't really idle, so we reset +327 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +328 } +329 } +330 } +331 } +332 trace!("actor terminating"); +333 } +334 +335 /// Handles an actor message. +336 /// +337 /// Error returns are fatal and kill the actor. +338 #[instrument(skip(self))] +339 async fn handle_message(&mut self, msg: RemoteStateMessage) { +340 // trace!("handling message"); +341 match msg { +342 RemoteStateMessage::SendDatagram(sender, transmit) => { +343 self.handle_msg_send_datagram(sender, transmit).await; +344 } +345 RemoteStateMessage::AddConnection(handle, tx) => { +346 self.handle_msg_add_connection(handle, tx).await; 347 } -348 RemoteStateMessage::AddConnection(handle, tx) => { -349 self.handle_msg_add_connection(handle, tx).await; +348 RemoteStateMessage::ResolveRemote(addrs, tx) => { +349 self.handle_msg_resolve_remote(addrs, tx); 350 } -351 RemoteStateMessage::ResolveRemote(addrs, tx) => { -352 self.handle_msg_resolve_remote(addrs, tx); +351 RemoteStateMessage::Latency(tx) => { +352 self.handle_msg_latency(tx); 353 } -354 RemoteStateMessage::Latency(tx) => { -355 self.handle_msg_latency(tx); -356 } -357 } -358 } -359 -360 /// Handles [`RemoteStateMessage::SendDatagram`]. -361 async fn handle_msg_send_datagram(&mut self, transmit: OwnedTransmit) { -362 // Sending datagrams might fail, e.g. because we don't have the right transports set -363 // up to handle sending this owned transmit to. -364 // After all, we try every single path that we know (relay URL, IP address), even -365 // though we might not have a relay transport or ip-capable transport set up. -366 // So these errors must not be fatal for this actor (or even this operation). -367 -368 if let Some(addr) = self.selected_path.get() { -369 trace!(?addr, "sending datagram to selected path"); -370 -371 if let Err(err) = send_datagram(&mut self.sender, addr.clone(), transmit).await { -372 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); -373 } -374 } else { -375 trace!( -376 paths = ?self.paths.addrs().collect::<Vec<_>>(), -377 "sending datagram to all known paths", -378 ); -379 if self.paths.is_empty() { -380 warn!("Cannot send datagrams: No paths to remote endpoint known"); -381 } -382 -383 for addr in self.paths.addrs() { -384 // We never want to send to our local addresses. -385 // The local address set is updated in the main loop so we can use `peek` here. -386 if let transports::Addr::Ip(sockaddr) = addr -387 && self -388 .local_direct_addrs -389 .peek() -390 .iter() -391 .any(|a| a.addr == *sockaddr) -392 { -393 trace!(%sockaddr, "not sending datagram to our own address"); -394 } else if let Err(err) = -395 send_datagram(&mut self.sender, addr.clone(), transmit.clone()).await -396 { -397 debug!(?addr, "failed to send datagram: {err:#}"); -398 } -399 } -400 // This message is received *before* a connection is added. So we do -401 // not yet have a connection to holepunch. Instead we trigger -402 // holepunching when AddConnection is received. -403 } -404 } -405 -406 /// Handles [`RemoteStateMessage::AddConnection`]. -407 /// -408 /// Error returns are fatal and kill the actor. -409 async fn handle_msg_add_connection( -410 &mut self, -411 handle: WeakConnectionHandle, -412 tx: oneshot::Sender<PathsWatcher>, -413 ) { -414 let pub_open_paths = Watchable::default(); -415 if let Some(conn) = handle.upgrade() { -416 // Remove any conflicting stable_ids from the local state. -417 let conn_id = ConnId(conn.stable_id()); -418 self.connections.remove(&conn_id); -419 -420 // Hook up paths, NAT addresses and connection closed event streams. -421 self.path_events.push(Box::pin( -422 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), -423 )); -424 self.addr_events.push(Box::pin( -425 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), -426 )); -427 self.connections_close.push(OnClosed::new(&conn)); -428 -429 // Add local addrs to the connection -430 let local_addrs = self -431 .local_direct_addrs -432 .get() -433 .iter() -434 .map(|d| d.addr) -435 .collect::<BTreeSet<_>>(); -436 Self::set_local_addrs(&conn, &local_addrs); -437 -438 // Store the connection -439 let conn_state = self -440 .connections -441 .entry(conn_id) -442 .insert_entry(ConnectionState { -443 handle: handle.clone(), -444 pub_open_paths: pub_open_paths.clone(), -445 paths: Default::default(), -446 open_paths: Default::default(), -447 path_ids: Default::default(), -448 }) -449 .into_mut(); -450 -451 // Store PathId(0), set path_status and select best path, check if holepunching -452 // is needed. -453 if let Some(path) = conn.path(PathId::ZERO) -454 && let Ok(socketaddr) = path.remote_address() -455 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -456 { -457 trace!(?path_remote, "added new connection"); -458 let path_remote_is_ip = path_remote.is_ip(); -459 let status = match path_remote { -460 transports::Addr::Ip(_) => PathStatus::Available, -461 transports::Addr::Relay(_, _) => PathStatus::Backup, -462 }; -463 path.set_status(status).ok(); -464 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); -465 self.paths -466 .insert(path_remote, Source::Connection { _0: Private }); -467 self.select_path(); -468 -469 if path_remote_is_ip { -470 // We may have raced this with a relay address. Try and add any -471 // relay addresses we have back. -472 let relays = self -473 .paths -474 .addrs() -475 .filter(|a| a.is_relay()) -476 .cloned() -477 .collect::<Vec<_>>(); -478 for remote in relays { -479 self.open_path(&remote); -480 } -481 } -482 } -483 self.trigger_holepunching().await; -484 } -485 tx.send(PathsWatcher::new( -486 pub_open_paths.watch(), -487 self.selected_path.watch(), -488 handle, -489 )) -490 .ok(); -491 } -492 -493 /// Handles [`RemoteStateMessage::ResolveRemote`]. -494 fn handle_msg_resolve_remote( -495 &mut self, -496 addrs: BTreeSet<TransportAddr>, -497 tx: oneshot::Sender<Result<(), DiscoveryError>>, -498 ) { -499 let addrs = to_transports_addr(self.endpoint_id, addrs); -500 self.paths.insert_multiple(addrs, Source::App); -501 self.paths.resolve_remote(tx); -502 // Start discovery if we have no selected path. -503 self.trigger_discovery(); -504 } -505 -506 /// Handles [`RemoteStateMessage::Latency`]. -507 fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) { -508 let rtt = self.selected_path.get().and_then(|addr| { -509 for conn_state in self.connections.values() { -510 let Some(path_id) = conn_state.path_ids.get(&addr) else { -511 continue; -512 }; -513 if !conn_state.open_paths.contains_key(path_id) { -514 continue; -515 } -516 if let Some(rtt) = conn_state -517 .handle -518 .upgrade() -519 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt)) -520 { -521 return Some(rtt); -522 } -523 } -524 None -525 }); -526 tx.send(rtt).ok(); -527 } -528 -529 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { -530 match item { -531 None => { -532 self.discovery_stream = Either::Left(n0_future::stream::pending()); -533 self.paths.discovery_finished(Ok(())); -534 } -535 Some(Err(err)) => { -536 warn!("Discovery failed: {err:#}"); -537 self.discovery_stream = Either::Left(n0_future::stream::pending()); -538 self.paths.discovery_finished(Err(err)); -539 } -540 Some(Ok(item)) => { -541 if item.endpoint_id() != self.endpoint_id { -542 warn!(?item, "Discovery emitted item for wrong remote endpoint"); -543 } else { -544 let source = Source::Discovery { -545 name: item.provenance().to_string(), -546 }; -547 let addrs = -548 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); -549 self.paths.insert_multiple(addrs, source); -550 } -551 } -552 } -553 } -554 -555 /// Triggers discovery for the remote endpoint, if needed. -556 /// -557 /// Does not start discovery if we have a selected path or if discovery is currently running. -558 fn trigger_discovery(&mut self) { -559 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { -560 return; -561 } -562 match self.discovery.resolve(self.endpoint_id) { -563 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), -564 None => self.paths.discovery_finished(Ok(())), -565 } -566 } -567 -568 /// Sets the current local addresses to QNT's state to all connections -569 fn local_addrs_updated(&mut self) { -570 let local_addrs = self -571 .local_direct_addrs -572 .get() -573 .iter() -574 .map(|d| d.addr) -575 .collect::<BTreeSet<_>>(); -576 -577 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { -578 Self::set_local_addrs(&conn, &local_addrs); -579 } -580 // todo: trace -581 } -582 -583 /// Sets the current local addresses to QNT's state -584 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { -585 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { -586 Ok(addrs) => BTreeSet::from_iter(addrs), -587 Err(err) => { -588 warn!("failed to get local nat candidates: {err:#}"); -589 return; -590 } -591 }; -592 for addr in local_addrs.difference(&quinn_local_addrs) { -593 if let Err(err) = conn.add_nat_traversal_address(*addr) { -594 warn!("failed adding local addr: {err:#}",); -595 } -596 } -597 for addr in quinn_local_addrs.difference(local_addrs) { -598 if let Err(err) = conn.remove_nat_traversal_address(*addr) { -599 warn!("failed removing local addr: {err:#}"); -600 } -601 } -602 trace!(?local_addrs, "updated local QNT addresses"); -603 } -604 -605 /// Triggers holepunching to the remote endpoint. -606 /// -607 /// This will manage the entire process of holepunching with the remote endpoint. -608 /// -609 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a -610 /// client. -611 /// - Both endpoints may initiate holepunching if both have a client connection. -612 /// - Any opened paths are opened on all other connections without holepunching. -613 /// - If there are no changes in local or remote candidate addresses since the -614 /// last attempt **and** there was a recent attempt, a trigger_holepunching call -615 /// will be scheduled instead. -616 async fn trigger_holepunching(&mut self) { -617 if self.connections.is_empty() { -618 trace!("not holepunching: no connections"); -619 return; -620 } -621 -622 let Some(conn) = self -623 .connections -624 .iter() -625 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) -626 .filter(|(_, conn)| conn.side().is_client()) -627 .min_by_key(|(id, _)| *id) -628 .map(|(_, conn)| conn) -629 else { -630 trace!("not holepunching: no client connection"); -631 return; -632 }; -633 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { -634 Ok(addrs) => BTreeSet::from_iter(addrs), -635 Err(err) => { -636 warn!("failed to get nat candidate addresses: {err:#}"); -637 return; -638 } -639 }; -640 let local_candidates: BTreeSet<SocketAddr> = self -641 .local_direct_addrs -642 .get() -643 .iter() -644 .map(|daddr| daddr.addr) -645 .collect(); -646 let new_candidates = self -647 .last_holepunch -648 .as_ref() -649 .map(|last_hp| { -650 // Addrs are allowed to disappear, but if there are new ones we need to -651 // holepunch again. -652 trace!( -653 ?last_hp, -654 ?local_candidates, -655 ?remote_candidates, -656 "candidates to holepunch?" -657 ); -658 !remote_candidates.is_subset(&last_hp.remote_candidates) -659 || !local_candidates.is_subset(&last_hp.local_candidates) -660 }) -661 .unwrap_or(true); -662 if !new_candidates { -663 if let Some(ref last_hp) = self.last_holepunch { -664 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; -665 let now = Instant::now(); -666 if next_hp > now { -667 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); -668 self.scheduled_holepunch = Some(next_hp); -669 return; -670 } -671 } -672 } -673 -674 self.do_holepunching(conn).await; -675 } -676 -677 /// Unconditionally perform holepunching. -678 #[instrument(skip_all)] -679 async fn do_holepunching(&mut self, conn: quinn::Connection) { -680 self.metrics.nat_traversal.inc(); -681 let local_candidates = self -682 .local_direct_addrs -683 .get() -684 .iter() -685 .map(|daddr| daddr.addr) -686 .collect::<BTreeSet<_>>(); -687 match conn.initiate_nat_traversal_round() { -688 Ok(remote_candidates) => { -689 let remote_candidates = remote_candidates -690 .iter() -691 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) -692 .collect(); -693 event!( -694 target: "iroh::_events::qnt::init", -695 Level::DEBUG, -696 remote = %self.endpoint_id.fmt_short(), -697 ?local_candidates, -698 ?remote_candidates, -699 ); -700 self.last_holepunch = Some(HolepunchAttempt { -701 when: Instant::now(), -702 local_candidates, -703 remote_candidates, -704 }); -705 } -706 Err(err) => { -707 warn!("failed to initiate NAT traversal: {err:#}"); -708 } -709 } -710 } -711 -712 /// Open the path on all connections. -713 /// -714 /// This goes through all the connections for which we are the client, and makes sure -715 /// the path exists, or opens it. -716 #[instrument(level = "warn", skip(self))] -717 fn open_path(&mut self, open_addr: &transports::Addr) { -718 let path_status = match open_addr { -719 transports::Addr::Ip(_) => PathStatus::Available, -720 transports::Addr::Relay(_, _) => PathStatus::Backup, -721 }; -722 let quic_addr = match &open_addr { -723 transports::Addr::Ip(socket_addr) => *socket_addr, -724 transports::Addr::Relay(relay_url, eid) => self -725 .relay_mapped_addrs -726 .get(&(relay_url.clone(), *eid)) -727 .private_socket_addr(), -728 }; -729 -730 for (conn_id, conn_state) in self.connections.iter_mut() { -731 if conn_state.path_ids.contains_key(open_addr) { -732 continue; -733 } -734 let Some(conn) = conn_state.handle.upgrade() else { -735 continue; -736 }; -737 if conn.side().is_server() { -738 continue; -739 } -740 let fut = conn.open_path_ensure(quic_addr, path_status); -741 match fut.path_id() { -742 Some(path_id) => { -743 trace!(?conn_id, ?path_id, "opening new path"); -744 conn_state.add_path(open_addr.clone(), path_id); -745 } -746 None => { -747 let ret = now_or_never(fut); -748 match ret { -749 Some(Err(PathError::RemoteCidsExhausted)) => { -750 self.scheduled_open_path = -751 Some(Instant::now() + Duration::from_millis(333)); -752 self.pending_open_paths.push_back(open_addr.clone()); -753 trace!(?open_addr, "scheduling open_path"); -754 } -755 _ => warn!(?ret, "Opening path failed"), -756 } -757 } -758 } -759 } -760 } -761 -762 #[instrument(skip(self))] -763 fn handle_path_event( -764 &mut self, -765 conn_id: ConnId, -766 event: Result<PathEvent, BroadcastStreamRecvError>, -767 ) { -768 let Ok(event) = event else { -769 warn!("missed a PathEvent, RemoteStateActor lagging"); -770 // TODO: Is it possible to recover using the sync APIs to figure out what the -771 // state of the connection and it's paths are? -772 return; -773 }; -774 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -775 trace!("event for removed connection"); -776 return; -777 }; -778 let Some(conn) = conn_state.handle.upgrade() else { -779 trace!("event for closed connection"); -780 return; -781 }; -782 trace!("path event"); -783 match event { -784 PathEvent::Opened { id: path_id } => { -785 let Some(path) = conn.path(path_id) else { -786 trace!("path open event for unknown path"); -787 return; -788 }; -789 // TODO: We configure this as defaults when we setup the endpoint, do we -790 // really need to duplicate this? -791 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); -792 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); -793 -794 if let Ok(socketaddr) = path.remote_address() -795 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -796 { -797 event!( -798 target: "iroh::_events::path::open", -799 Level::DEBUG, -800 remote = %self.endpoint_id.fmt_short(), -801 ?path_remote, -802 ?conn_id, -803 ?path_id, -804 ); -805 conn_state.add_open_path(path_remote.clone(), path_id); -806 self.paths -807 .insert(path_remote, Source::Connection { _0: Private }); -808 } -809 -810 self.select_path(); -811 } -812 PathEvent::Abandoned { id, path_stats } => { -813 trace!(?path_stats, "path abandoned"); -814 // This is the last event for this path. -815 conn_state.remove_path(&id); -816 } -817 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { -818 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { -819 debug!("path not in path_id_map"); -820 return; -821 }; -822 event!( -823 target: "iroh::_events::path::closed", -824 Level::DEBUG, -825 remote = %self.endpoint_id.fmt_short(), -826 ?path_remote, -827 ?conn_id, -828 path_id = ?id, -829 ); -830 conn_state.remove_open_path(&id); -831 -832 // If one connection closes this path, close it on all connections. -833 for (conn_id, conn_state) in self.connections.iter_mut() { -834 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { -835 continue; -836 }; -837 let Some(conn) = conn_state.handle.upgrade() else { -838 continue; -839 }; -840 if let Some(path) = conn.path(*path_id) { -841 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); -842 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { -843 trace!( -844 ?path_remote, -845 ?conn_id, -846 ?path_id, -847 "path close failed: {err:#}" -848 ); -849 } -850 } -851 } -852 -853 // If the remote closed our selected path, select a new one. -854 self.select_path(); -855 } -856 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { -857 // Nothing to do for these events. -858 } -859 } -860 } -861 -862 /// Selects the path with the lowest RTT, prefers direct paths. -863 /// -864 /// If there are direct paths, this selects the direct path with the lowest RTT. If -865 /// there are only relay paths, the relay path with the lowest RTT is chosen. -866 /// -867 /// The selected path is added to any connections which do not yet have it. Any unused -868 /// direct paths are closed for all connections. -869 #[instrument(skip_all)] -870 fn select_path(&mut self) { -871 // Find the lowest RTT across all connections for each open path. The long way, so -872 // we get to log *all* RTTs. -873 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); -874 for conn_state in self.connections.values() { -875 let Some(conn) = conn_state.handle.upgrade() else { -876 continue; -877 }; -878 for (path_id, addr) in conn_state.open_paths.iter() { -879 if let Some(stats) = conn.path_stats(*path_id) { -880 all_path_rtts -881 .entry(addr.clone()) -882 .or_default() -883 .push(stats.rtt); -884 } -885 } -886 } -887 trace!(?all_path_rtts, "dumping all path RTTs"); -888 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts -889 .into_iter() -890 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -891 .collect(); -892 -893 // Find the fastest direct or relay path. -894 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); -895 let direct_path = path_rtts -896 .iter() -897 .filter(|(addr, _rtt)| addr.is_ip()) -898 .map(|(addr, rtt)| { -899 if addr.is_ipv4() { -900 (*rtt + IPV6_RTT_ADVANTAGE, addr) -901 } else { -902 (*rtt, addr) -903 } -904 }) -905 .min(); -906 let selected_path = direct_path.or_else(|| { -907 // Find the fasted relay path. -908 path_rtts -909 .iter() -910 .filter(|(addr, _rtt)| addr.is_relay()) -911 .map(|(addr, rtt)| (*rtt, addr)) -912 .min() -913 }); -914 if let Some((rtt, addr)) = selected_path { -915 let prev = self.selected_path.set(Some(addr.clone())); -916 if prev.is_ok() { -917 debug!(?addr, ?rtt, ?prev, "selected new path"); -918 } -919 self.open_path(addr); -920 self.close_redundant_paths(addr); -921 } -922 } -923 -924 /// Closes any direct paths not selected if we are the client. -925 /// -926 /// Makes sure not to close the last direct path. Relay paths are never closed -927 /// currently, because we only have one relay path at this time. -928 /// -929 /// Only the client closes paths, just like only the client opens paths. This is to -930 /// avoid the client and server selecting different paths and accidentally closing all -931 /// paths. -932 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { -933 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); -934 -935 for (conn_id, conn_state) in self.connections.iter() { -936 for (path_id, path_remote) in conn_state -937 .open_paths -938 .iter() -939 .filter(|(_, addr)| addr.is_ip()) -940 .filter(|(_, addr)| *addr != selected_path) -941 { -942 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { -943 continue; // Do not close the last direct path. -944 } -945 if let Some(path) = conn_state -946 .handle -947 .upgrade() -948 .filter(|conn| conn.side().is_client()) -949 .and_then(|conn| conn.path(*path_id)) -950 { -951 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); -952 match path.close(APPLICATION_ABANDON_PATH.into()) { -953 Err(quinn_proto::ClosePathError::LastOpenPath) => { -954 error!("could not close last open path"); -955 } -956 Err(quinn_proto::ClosePathError::ClosedPath) => { -957 // We already closed this. -958 } -959 Ok(_fut) => { -960 // We will handle the event in Self::handle_path_events. -961 } -962 } -963 } -964 } -965 } -966 } -967} -968 -969fn send_datagram<'a>( -970 sender: &'a mut TransportsSender, -971 dst: transports::Addr, -972 owned_transmit: OwnedTransmit, -973) -> impl Future<Output = n0_error::Result<()>> + 'a { -974 std::future::poll_fn(move |cx| { -975 let transmit = transports::Transmit { -976 ecn: owned_transmit.ecn, -977 contents: owned_transmit.contents.as_ref(), -978 segment_size: owned_transmit.segment_size, -979 }; -980 -981 Pin::new(&mut *sender) -982 .poll_send(cx, &dst, None, &transmit) -983 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) -984 }) -985} -986 -987/// Messages to send to the [`RemoteStateActor`]. -988#[derive(derive_more::Debug)] -989pub(crate) enum RemoteStateMessage { -990 /// Sends a datagram to all known paths. -991 /// -992 /// Used to send QUIC Initial packets. If there is no working direct path this will -993 /// trigger holepunching. -994 /// -995 /// This is not acceptable to use on the normal send path, as it is an async send -996 /// operation with a bunch more copying. So it should only be used for sending QUIC -997 /// Initial packets. -998 #[debug("SendDatagram(..)")] -999 SendDatagram(OwnedTransmit), -1000 /// Adds an active connection to this remote endpoint. -1001 /// -1002 /// The connection will now be managed by this actor. Holepunching will happen when -1003 /// needed, any new paths discovered via holepunching will be added. And closed paths -1004 /// will be removed etc. -1005 #[debug("AddConnection(..)")] -1006 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), -1007 /// Asks if there is any possible path that could be used. -1008 /// -1009 /// This adds the provided transport addresses to the list of potential paths for this remote -1010 /// and starts discovery if needed. -1011 /// -1012 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. -1013 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails -1014 /// or produces no results, -1015 #[debug("ResolveRemote(..)")] -1016 ResolveRemote( -1017 BTreeSet<TransportAddr>, -1018 oneshot::Sender<Result<(), DiscoveryError>>, -1019 ), -1020 /// Returns the current latency to the remote endpoint. -1021 /// -1022 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. -1023 #[debug("Latency(..)")] -1024 Latency(oneshot::Sender<Option<Duration>>), -1025} -1026 -1027/// A handle to a [`RemoteStateActor`]. -1028/// -1029/// Dropping this will stop the actor. The actor will also stop after an idle timeout -1030/// if it has no connections, an empty inbox, and no other senders than the one stored -1031/// in the endpoint map exist. -1032#[derive(Debug)] -1033pub(super) struct RemoteStateHandle { -1034 /// Sender for the channel into the [`RemoteStateActor`]. -1035 /// -1036 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver -1037 /// hasn't been closed. -1038 pub(super) sender: GuardedSender<RemoteStateMessage>, -1039 _task: AbortOnDropHandle<()>, -1040} -1041 -1042/// Information about a holepunch attempt. -1043/// -1044/// Addresses are always stored in canonical form. -1045#[derive(Debug)] -1046struct HolepunchAttempt { -1047 when: Instant, -1048 /// The set of local addresses which could take part in holepunching. -1049 /// -1050 /// This does not mean every address here participated in the holepunching. E.g. we -1051 /// could have tried only a sub-set of the addresses because a previous attempt already -1052 /// covered part of the range. -1053 /// -1054 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1055 /// do not want to compare the sources of these addresses. -1056 local_candidates: BTreeSet<SocketAddr>, -1057 /// The set of remote addresses which could take part in holepunching. -1058 /// -1059 /// Like [`Self::local_candidates`] we may not have used them. -1060 remote_candidates: BTreeSet<SocketAddr>, -1061} -1062 -1063/// Newtype to track Connections. -1064/// -1065/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid -1066/// for active connections. -1067#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -1068struct ConnId(usize); -1069 -1070/// State about one connection. -1071#[derive(Debug)] -1072struct ConnectionState { -1073 /// Weak handle to the connection. -1074 handle: WeakConnectionHandle, -1075 /// The information we publish to users about the paths used in this connection. -1076 pub_open_paths: Watchable<PathAddrList>, -1077 /// The paths that exist on this connection. -1078 /// -1079 /// This could be in any state, e.g. while still validating the path or already closed -1080 /// but not yet fully removed from the connection. This exists as long as Quinn knows -1081 /// about the [`PathId`]. -1082 paths: FxHashMap<PathId, transports::Addr>, -1083 /// The open paths on this connection, a subset of [`Self::paths`]. -1084 open_paths: FxHashMap<PathId, transports::Addr>, -1085 /// Reverse map of [`Self::paths]. -1086 path_ids: FxHashMap<transports::Addr, PathId>, -1087} -1088 -1089impl ConnectionState { -1090 /// Tracks a path for the connection. -1091 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { -1092 self.paths.insert(path_id, remote.clone()); -1093 self.path_ids.insert(remote, path_id); -1094 } -1095 -1096 /// Tracks an open path for the connection. -1097 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { -1098 self.paths.insert(path_id, remote.clone()); -1099 self.open_paths.insert(path_id, remote.clone()); -1100 self.path_ids.insert(remote, path_id); -1101 -1102 self.update_pub_path_info(); -1103 } -1104 -1105 /// Completely removes a path from this connection. -1106 fn remove_path(&mut self, path_id: &PathId) { -1107 if let Some(addr) = self.paths.remove(path_id) { -1108 self.path_ids.remove(&addr); -1109 } -1110 self.open_paths.remove(path_id); -1111 } -1112 -1113 /// Removes the path from the open paths. -1114 fn remove_open_path(&mut self, path_id: &PathId) { -1115 self.open_paths.remove(path_id); -1116 -1117 self.update_pub_path_info(); -1118 } -1119 -1120 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. -1121 /// -1122 /// [`Connection`]: crate::endpoint::Connection -1123 fn update_pub_path_info(&self) { -1124 let new = self -1125 .open_paths -1126 .iter() -1127 .map(|(path_id, remote)| { -1128 let remote = TransportAddr::from(remote.clone()); -1129 (remote, *path_id) -1130 }) -1131 .collect::<PathAddrList>(); -1132 -1133 self.pub_open_paths.set(new).ok(); -1134 } -1135} -1136 -1137/// Watcher for the open paths and selected transmission path in a connection. -1138/// -1139/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. -1140/// -1141/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the -1142/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with -1143/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. -1144/// -1145/// [`Connection`]: crate::endpoint::Connection -1146#[derive(Clone, derive_more::Debug)] -1147#[debug("PathsWatcher")] -1148#[allow(clippy::type_complexity)] -1149pub(crate) struct PathsWatcher( -1150 Box< -1151 n0_watcher::Map< -1152 n0_watcher::Tuple< -1153 n0_watcher::Direct<PathAddrList>, -1154 n0_watcher::Direct<Option<transports::Addr>>, -1155 >, -1156 PathInfoList, -1157 >, -1158 >, -1159); -1160 -1161impl n0_watcher::Watcher for PathsWatcher { -1162 type Value = PathInfoList; -1163 -1164 fn update(&mut self) -> bool { -1165 self.0.update() -1166 } -1167 -1168 fn peek(&self) -> &Self::Value { -1169 self.0.peek() -1170 } -1171 -1172 fn is_connected(&self) -> bool { -1173 self.0.is_connected() -1174 } -1175 -1176 fn poll_updated( -1177 &mut self, -1178 cx: &mut std::task::Context<'_>, -1179 ) -> Poll<Result<(), n0_watcher::Disconnected>> { -1180 self.0.poll_updated(cx) -1181 } -1182} -1183 -1184impl PathsWatcher { -1185 fn new( -1186 open_paths: n0_watcher::Direct<PathAddrList>, -1187 selected_path: n0_watcher::Direct<Option<transports::Addr>>, -1188 conn_handle: WeakConnectionHandle, -1189 ) -> Self { -1190 Self(Box::new(open_paths.or(selected_path).map( -1191 move |(open_paths, selected_path)| { -1192 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); -1193 let Some(conn) = conn_handle.upgrade() else { -1194 return PathInfoList(Default::default()); -1195 }; -1196 let list = open_paths -1197 .into_iter() -1198 .flat_map(move |(remote, path_id)| { -1199 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) -1200 }) -1201 .collect(); -1202 PathInfoList(list) -1203 }, -1204 ))) -1205 } -1206} -1207 -1208/// List of [`PathInfo`] for the network paths of a [`Connection`]. -1209/// -1210/// This struct implements [`IntoIterator`]. -1211/// -1212/// [`Connection`]: crate::endpoint::Connection -1213#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] -1214#[debug("{_0:?}")] -1215pub struct PathInfoList(SmallVec<[PathInfo; 4]>); -1216 -1217impl PathInfoList { -1218 /// Returns an iterator over the path infos. -1219 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { -1220 self.0.iter() -1221 } -1222 -1223 /// Returns `true` if the list is empty. -1224 pub fn is_empty(&self) -> bool { -1225 self.0.is_empty() -1226 } -1227 -1228 /// Returns the number of paths. -1229 pub fn len(&self) -> usize { -1230 self.0.len() -1231 } -1232} -1233 -1234/// Information about a network path used by a [`Connection`]. -1235/// -1236/// [`Connection`]: crate::endpoint::Connection -1237#[derive(derive_more::Debug, Clone)] -1238pub struct PathInfo { -1239 path_id: PathId, -1240 #[debug(skip)] -1241 handle: WeakConnectionHandle, -1242 stats: PathStats, -1243 remote: TransportAddr, -1244 is_selected: bool, -1245} -1246 -1247impl PartialEq for PathInfo { -1248 fn eq(&self, other: &Self) -> bool { -1249 self.path_id == other.path_id -1250 && self.remote == other.remote -1251 && self.is_selected == other.is_selected -1252 } -1253} -1254 -1255impl Eq for PathInfo {} -1256 -1257impl PathInfo { -1258 fn new( -1259 path_id: PathId, -1260 conn: &quinn::Connection, -1261 remote: TransportAddr, -1262 selected_path: Option<&TransportAddr>, -1263 ) -> Option<Self> { -1264 let stats = conn.path_stats(path_id)?; -1265 Some(Self { -1266 path_id, -1267 handle: conn.weak_handle(), -1268 is_selected: Some(&remote) == selected_path, -1269 remote, -1270 stats, -1271 }) -1272 } -1273 -1274 /// The remote transport address used by this network path. -1275 pub fn remote_addr(&self) -> &TransportAddr { -1276 &self.remote -1277 } -1278 -1279 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. -1280 /// -1281 /// [`Connection`]: crate::endpoint::Connection -1282 pub fn is_selected(&self) -> bool { -1283 self.is_selected -1284 } -1285 -1286 /// Whether this is an IP transport address. -1287 pub fn is_ip(&self) -> bool { -1288 self.remote.is_ip() -1289 } -1290 -1291 /// Whether this is a transport address via a relay server. -1292 pub fn is_relay(&self) -> bool { -1293 self.remote.is_relay() -1294 } -1295 -1296 /// Returns stats for this transmission path. -1297 pub fn stats(&self) -> PathStats { -1298 self.handle -1299 .upgrade() -1300 .and_then(|conn| conn.path_stats(self.path_id)) -1301 .unwrap_or(self.stats) -1302 } -1303 -1304 /// Current best estimate of this paths's latency (round-trip-time) -1305 pub fn rtt(&self) -> Duration { -1306 self.stats().rtt -1307 } -1308} -1309 -1310/// Poll a future once, like n0_future::future::poll_once but sync. -1311fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1312 let fut = std::pin::pin!(fut); -1313 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1314 Poll::Ready(res) => Some(res), -1315 Poll::Pending => None, -1316 } -1317} -1318 -1319/// Future that resolves to the `conn_id` once a connection is closed. -1320/// -1321/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive -1322/// while awaiting the future. -1323struct OnClosed { -1324 conn_id: ConnId, -1325 inner: quinn::OnClosed, -1326} -1327 -1328impl OnClosed { -1329 fn new(conn: &quinn::Connection) -> Self { -1330 Self { -1331 conn_id: ConnId(conn.stable_id()), -1332 inner: conn.on_closed(), -1333 } -1334 } -1335} -1336 -1337impl Future for OnClosed { -1338 type Output = ConnId; -1339 -1340 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1341 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1342 Poll::Ready(self.conn_id) -1343 } -1344} -1345 -1346/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. -1347fn to_transports_addr( -1348 endpoint_id: EndpointId, -1349 addrs: impl IntoIterator<Item = TransportAddr>, -1350) -> impl Iterator<Item = transports::Addr> { -1351 addrs.into_iter().filter_map(move |addr| match addr { -1352 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), -1353 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), -1354 _ => { -1355 warn!(?addr, "Unsupported TransportAddr"); -1356 None -1357 } -1358 }) -1359} \ No newline at end of file +354 } +355 } +356 +357 /// Handles [`RemoteStateMessage::SendDatagram`]. +358 async fn handle_msg_send_datagram( +359 &mut self, +360 mut sender: TransportsSender, +361 transmit: OwnedTransmit, +362 ) { +363 // Sending datagrams might fail, e.g. because we don't have the right transports set +364 // up to handle sending this owned transmit to. +365 // After all, we try every single path that we know (relay URL, IP address), even +366 // though we might not have a relay transport or ip-capable transport set up. +367 // So these errors must not be fatal for this actor (or even this operation). +368 +369 if let Some(addr) = self.selected_path.get() { +370 trace!(?addr, "sending datagram to selected path"); +371 +372 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { +373 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); +374 } +375 } else { +376 trace!( +377 paths = ?self.paths.addrs().collect::<Vec<_>>(), +378 "sending datagram to all known paths", +379 ); +380 if self.paths.is_empty() { +381 warn!("Cannot send datagrams: No paths to remote endpoint known"); +382 } +383 +384 for addr in self.paths.addrs() { +385 // We never want to send to our local addresses. +386 // The local address set is updated in the main loop so we can use `peek` here. +387 if let transports::Addr::Ip(sockaddr) = addr +388 && self +389 .local_direct_addrs +390 .peek() +391 .iter() +392 .any(|a| a.addr == *sockaddr) +393 { +394 trace!(%sockaddr, "not sending datagram to our own address"); +395 } else if let Err(err) = +396 send_datagram(&mut sender, addr.clone(), transmit.clone()).await +397 { +398 debug!(?addr, "failed to send datagram: {err:#}"); +399 } +400 } +401 // This message is received *before* a connection is added. So we do +402 // not yet have a connection to holepunch. Instead we trigger +403 // holepunching when AddConnection is received. +404 } +405 } +406 +407 /// Handles [`RemoteStateMessage::AddConnection`]. +408 /// +409 /// Error returns are fatal and kill the actor. +410 async fn handle_msg_add_connection( +411 &mut self, +412 handle: WeakConnectionHandle, +413 tx: oneshot::Sender<PathsWatcher>, +414 ) { +415 let pub_open_paths = Watchable::default(); +416 if let Some(conn) = handle.upgrade() { +417 // Remove any conflicting stable_ids from the local state. +418 let conn_id = ConnId(conn.stable_id()); +419 self.connections.remove(&conn_id); +420 +421 // Hook up paths, NAT addresses and connection closed event streams. +422 self.path_events.push(Box::pin( +423 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), +424 )); +425 self.addr_events.push(Box::pin( +426 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), +427 )); +428 self.connections_close.push(OnClosed::new(&conn)); +429 +430 // Add local addrs to the connection +431 let local_addrs = self +432 .local_direct_addrs +433 .get() +434 .iter() +435 .map(|d| d.addr) +436 .collect::<BTreeSet<_>>(); +437 Self::set_local_addrs(&conn, &local_addrs); +438 +439 // Store the connection +440 let conn_state = self +441 .connections +442 .entry(conn_id) +443 .insert_entry(ConnectionState { +444 handle: handle.clone(), +445 pub_open_paths: pub_open_paths.clone(), +446 paths: Default::default(), +447 open_paths: Default::default(), +448 path_ids: Default::default(), +449 }) +450 .into_mut(); +451 +452 // Store PathId(0), set path_status and select best path, check if holepunching +453 // is needed. +454 if let Some(path) = conn.path(PathId::ZERO) +455 && let Ok(socketaddr) = path.remote_address() +456 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +457 { +458 trace!(?path_remote, "added new connection"); +459 let path_remote_is_ip = path_remote.is_ip(); +460 let status = match path_remote { +461 transports::Addr::Ip(_) => PathStatus::Available, +462 transports::Addr::Relay(_, _) => PathStatus::Backup, +463 }; +464 path.set_status(status).ok(); +465 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); +466 self.paths +467 .insert(path_remote, Source::Connection { _0: Private }); +468 self.select_path(); +469 +470 if path_remote_is_ip { +471 // We may have raced this with a relay address. Try and add any +472 // relay addresses we have back. +473 let relays = self +474 .paths +475 .addrs() +476 .filter(|a| a.is_relay()) +477 .cloned() +478 .collect::<Vec<_>>(); +479 for remote in relays { +480 self.open_path(&remote); +481 } +482 } +483 } +484 self.trigger_holepunching().await; +485 } +486 tx.send(PathsWatcher::new( +487 pub_open_paths.watch(), +488 self.selected_path.watch(), +489 handle, +490 )) +491 .ok(); +492 } +493 +494 /// Handles [`RemoteStateMessage::ResolveRemote`]. +495 fn handle_msg_resolve_remote( +496 &mut self, +497 addrs: BTreeSet<TransportAddr>, +498 tx: oneshot::Sender<Result<(), DiscoveryError>>, +499 ) { +500 let addrs = to_transports_addr(self.endpoint_id, addrs); +501 self.paths.insert_multiple(addrs, Source::App); +502 self.paths.resolve_remote(tx); +503 // Start discovery if we have no selected path. +504 self.trigger_discovery(); +505 } +506 +507 /// Handles [`RemoteStateMessage::Latency`]. +508 fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) { +509 let rtt = self.selected_path.get().and_then(|addr| { +510 for conn_state in self.connections.values() { +511 let Some(path_id) = conn_state.path_ids.get(&addr) else { +512 continue; +513 }; +514 if !conn_state.open_paths.contains_key(path_id) { +515 continue; +516 } +517 if let Some(rtt) = conn_state +518 .handle +519 .upgrade() +520 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt)) +521 { +522 return Some(rtt); +523 } +524 } +525 None +526 }); +527 tx.send(rtt).ok(); +528 } +529 +530 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { +531 match item { +532 None => { +533 self.discovery_stream = Either::Left(n0_future::stream::pending()); +534 self.paths.discovery_finished(Ok(())); +535 } +536 Some(Err(err)) => { +537 warn!("Discovery failed: {err:#}"); +538 self.discovery_stream = Either::Left(n0_future::stream::pending()); +539 self.paths.discovery_finished(Err(err)); +540 } +541 Some(Ok(item)) => { +542 if item.endpoint_id() != self.endpoint_id { +543 warn!(?item, "Discovery emitted item for wrong remote endpoint"); +544 } else { +545 let source = Source::Discovery { +546 name: item.provenance().to_string(), +547 }; +548 let addrs = +549 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); +550 self.paths.insert_multiple(addrs, source); +551 } +552 } +553 } +554 } +555 +556 /// Triggers discovery for the remote endpoint, if needed. +557 /// +558 /// Does not start discovery if we have a selected path or if discovery is currently running. +559 fn trigger_discovery(&mut self) { +560 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { +561 return; +562 } +563 match self.discovery.resolve(self.endpoint_id) { +564 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), +565 None => self.paths.discovery_finished(Ok(())), +566 } +567 } +568 +569 /// Sets the current local addresses to QNT's state to all connections +570 fn local_addrs_updated(&mut self) { +571 let local_addrs = self +572 .local_direct_addrs +573 .get() +574 .iter() +575 .map(|d| d.addr) +576 .collect::<BTreeSet<_>>(); +577 +578 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { +579 Self::set_local_addrs(&conn, &local_addrs); +580 } +581 // todo: trace +582 } +583 +584 /// Sets the current local addresses to QNT's state +585 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { +586 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { +587 Ok(addrs) => BTreeSet::from_iter(addrs), +588 Err(err) => { +589 warn!("failed to get local nat candidates: {err:#}"); +590 return; +591 } +592 }; +593 for addr in local_addrs.difference(&quinn_local_addrs) { +594 if let Err(err) = conn.add_nat_traversal_address(*addr) { +595 warn!("failed adding local addr: {err:#}",); +596 } +597 } +598 for addr in quinn_local_addrs.difference(local_addrs) { +599 if let Err(err) = conn.remove_nat_traversal_address(*addr) { +600 warn!("failed removing local addr: {err:#}"); +601 } +602 } +603 trace!(?local_addrs, "updated local QNT addresses"); +604 } +605 +606 /// Triggers holepunching to the remote endpoint. +607 /// +608 /// This will manage the entire process of holepunching with the remote endpoint. +609 /// +610 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a +611 /// client. +612 /// - Both endpoints may initiate holepunching if both have a client connection. +613 /// - Any opened paths are opened on all other connections without holepunching. +614 /// - If there are no changes in local or remote candidate addresses since the +615 /// last attempt **and** there was a recent attempt, a trigger_holepunching call +616 /// will be scheduled instead. +617 async fn trigger_holepunching(&mut self) { +618 if self.connections.is_empty() { +619 trace!("not holepunching: no connections"); +620 return; +621 } +622 +623 let Some(conn) = self +624 .connections +625 .iter() +626 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) +627 .filter(|(_, conn)| conn.side().is_client()) +628 .min_by_key(|(id, _)| *id) +629 .map(|(_, conn)| conn) +630 else { +631 trace!("not holepunching: no client connection"); +632 return; +633 }; +634 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { +635 Ok(addrs) => BTreeSet::from_iter(addrs), +636 Err(err) => { +637 warn!("failed to get nat candidate addresses: {err:#}"); +638 return; +639 } +640 }; +641 let local_candidates: BTreeSet<SocketAddr> = self +642 .local_direct_addrs +643 .get() +644 .iter() +645 .map(|daddr| daddr.addr) +646 .collect(); +647 let new_candidates = self +648 .last_holepunch +649 .as_ref() +650 .map(|last_hp| { +651 // Addrs are allowed to disappear, but if there are new ones we need to +652 // holepunch again. +653 trace!( +654 ?last_hp, +655 ?local_candidates, +656 ?remote_candidates, +657 "candidates to holepunch?" +658 ); +659 !remote_candidates.is_subset(&last_hp.remote_candidates) +660 || !local_candidates.is_subset(&last_hp.local_candidates) +661 }) +662 .unwrap_or(true); +663 if !new_candidates { +664 if let Some(ref last_hp) = self.last_holepunch { +665 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; +666 let now = Instant::now(); +667 if next_hp > now { +668 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); +669 self.scheduled_holepunch = Some(next_hp); +670 return; +671 } +672 } +673 } +674 +675 self.do_holepunching(conn).await; +676 } +677 +678 /// Unconditionally perform holepunching. +679 #[instrument(skip_all)] +680 async fn do_holepunching(&mut self, conn: quinn::Connection) { +681 self.metrics.nat_traversal.inc(); +682 let local_candidates = self +683 .local_direct_addrs +684 .get() +685 .iter() +686 .map(|daddr| daddr.addr) +687 .collect::<BTreeSet<_>>(); +688 match conn.initiate_nat_traversal_round() { +689 Ok(remote_candidates) => { +690 let remote_candidates = remote_candidates +691 .iter() +692 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port())) +693 .collect(); +694 event!( +695 target: "iroh::_events::qnt::init", +696 Level::DEBUG, +697 remote = %self.endpoint_id.fmt_short(), +698 ?local_candidates, +699 ?remote_candidates, +700 ); +701 self.last_holepunch = Some(HolepunchAttempt { +702 when: Instant::now(), +703 local_candidates, +704 remote_candidates, +705 }); +706 } +707 Err(err) => { +708 warn!("failed to initiate NAT traversal: {err:#}"); +709 } +710 } +711 } +712 +713 /// Open the path on all connections. +714 /// +715 /// This goes through all the connections for which we are the client, and makes sure +716 /// the path exists, or opens it. +717 #[instrument(level = "warn", skip(self))] +718 fn open_path(&mut self, open_addr: &transports::Addr) { +719 let path_status = match open_addr { +720 transports::Addr::Ip(_) => PathStatus::Available, +721 transports::Addr::Relay(_, _) => PathStatus::Backup, +722 }; +723 let quic_addr = match &open_addr { +724 transports::Addr::Ip(socket_addr) => *socket_addr, +725 transports::Addr::Relay(relay_url, eid) => self +726 .relay_mapped_addrs +727 .get(&(relay_url.clone(), *eid)) +728 .private_socket_addr(), +729 }; +730 +731 for (conn_id, conn_state) in self.connections.iter_mut() { +732 if conn_state.path_ids.contains_key(open_addr) { +733 continue; +734 } +735 let Some(conn) = conn_state.handle.upgrade() else { +736 continue; +737 }; +738 if conn.side().is_server() { +739 continue; +740 } +741 let fut = conn.open_path_ensure(quic_addr, path_status); +742 match fut.path_id() { +743 Some(path_id) => { +744 trace!(?conn_id, ?path_id, "opening new path"); +745 conn_state.add_path(open_addr.clone(), path_id); +746 } +747 None => { +748 let ret = now_or_never(fut); +749 match ret { +750 Some(Err(PathError::RemoteCidsExhausted)) => { +751 self.scheduled_open_path = +752 Some(Instant::now() + Duration::from_millis(333)); +753 self.pending_open_paths.push_back(open_addr.clone()); +754 trace!(?open_addr, "scheduling open_path"); +755 } +756 _ => warn!(?ret, "Opening path failed"), +757 } +758 } +759 } +760 } +761 } +762 +763 #[instrument(skip(self))] +764 fn handle_path_event( +765 &mut self, +766 conn_id: ConnId, +767 event: Result<PathEvent, BroadcastStreamRecvError>, +768 ) { +769 let Ok(event) = event else { +770 warn!("missed a PathEvent, RemoteStateActor lagging"); +771 // TODO: Is it possible to recover using the sync APIs to figure out what the +772 // state of the connection and it's paths are? +773 return; +774 }; +775 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +776 trace!("event for removed connection"); +777 return; +778 }; +779 let Some(conn) = conn_state.handle.upgrade() else { +780 trace!("event for closed connection"); +781 return; +782 }; +783 trace!("path event"); +784 match event { +785 PathEvent::Opened { id: path_id } => { +786 let Some(path) = conn.path(path_id) else { +787 trace!("path open event for unknown path"); +788 return; +789 }; +790 // TODO: We configure this as defaults when we setup the endpoint, do we +791 // really need to duplicate this? +792 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); +793 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); +794 +795 if let Ok(socketaddr) = path.remote_address() +796 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +797 { +798 event!( +799 target: "iroh::_events::path::open", +800 Level::DEBUG, +801 remote = %self.endpoint_id.fmt_short(), +802 ?path_remote, +803 ?conn_id, +804 ?path_id, +805 ); +806 conn_state.add_open_path(path_remote.clone(), path_id); +807 self.paths +808 .insert(path_remote, Source::Connection { _0: Private }); +809 } +810 +811 self.select_path(); +812 } +813 PathEvent::Abandoned { id, path_stats } => { +814 trace!(?path_stats, "path abandoned"); +815 // This is the last event for this path. +816 conn_state.remove_path(&id); +817 } +818 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { +819 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { +820 debug!("path not in path_id_map"); +821 return; +822 }; +823 event!( +824 target: "iroh::_events::path::closed", +825 Level::DEBUG, +826 remote = %self.endpoint_id.fmt_short(), +827 ?path_remote, +828 ?conn_id, +829 path_id = ?id, +830 ); +831 conn_state.remove_open_path(&id); +832 +833 // If one connection closes this path, close it on all connections. +834 for (conn_id, conn_state) in self.connections.iter_mut() { +835 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { +836 continue; +837 }; +838 let Some(conn) = conn_state.handle.upgrade() else { +839 continue; +840 }; +841 if let Some(path) = conn.path(*path_id) { +842 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); +843 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { +844 trace!( +845 ?path_remote, +846 ?conn_id, +847 ?path_id, +848 "path close failed: {err:#}" +849 ); +850 } +851 } +852 } +853 +854 // If the remote closed our selected path, select a new one. +855 self.select_path(); +856 } +857 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { +858 // Nothing to do for these events. +859 } +860 } +861 } +862 +863 /// Selects the path with the lowest RTT, prefers direct paths. +864 /// +865 /// If there are direct paths, this selects the direct path with the lowest RTT. If +866 /// there are only relay paths, the relay path with the lowest RTT is chosen. +867 /// +868 /// The selected path is added to any connections which do not yet have it. Any unused +869 /// direct paths are closed for all connections. +870 #[instrument(skip_all)] +871 fn select_path(&mut self) { +872 // Find the lowest RTT across all connections for each open path. The long way, so +873 // we get to log *all* RTTs. +874 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); +875 for conn_state in self.connections.values() { +876 let Some(conn) = conn_state.handle.upgrade() else { +877 continue; +878 }; +879 for (path_id, addr) in conn_state.open_paths.iter() { +880 if let Some(stats) = conn.path_stats(*path_id) { +881 all_path_rtts +882 .entry(addr.clone()) +883 .or_default() +884 .push(stats.rtt); +885 } +886 } +887 } +888 trace!(?all_path_rtts, "dumping all path RTTs"); +889 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts +890 .into_iter() +891 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +892 .collect(); +893 +894 // Find the fastest direct or relay path. +895 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); +896 let direct_path = path_rtts +897 .iter() +898 .filter(|(addr, _rtt)| addr.is_ip()) +899 .map(|(addr, rtt)| { +900 if addr.is_ipv4() { +901 (*rtt + IPV6_RTT_ADVANTAGE, addr) +902 } else { +903 (*rtt, addr) +904 } +905 }) +906 .min(); +907 let selected_path = direct_path.or_else(|| { +908 // Find the fasted relay path. +909 path_rtts +910 .iter() +911 .filter(|(addr, _rtt)| addr.is_relay()) +912 .map(|(addr, rtt)| (*rtt, addr)) +913 .min() +914 }); +915 if let Some((rtt, addr)) = selected_path { +916 let prev = self.selected_path.set(Some(addr.clone())); +917 if prev.is_ok() { +918 debug!(?addr, ?rtt, ?prev, "selected new path"); +919 } +920 self.open_path(addr); +921 self.close_redundant_paths(addr); +922 } +923 } +924 +925 /// Closes any direct paths not selected if we are the client. +926 /// +927 /// Makes sure not to close the last direct path. Relay paths are never closed +928 /// currently, because we only have one relay path at this time. +929 /// +930 /// Only the client closes paths, just like only the client opens paths. This is to +931 /// avoid the client and server selecting different paths and accidentally closing all +932 /// paths. +933 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { +934 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); +935 +936 for (conn_id, conn_state) in self.connections.iter() { +937 for (path_id, path_remote) in conn_state +938 .open_paths +939 .iter() +940 .filter(|(_, addr)| addr.is_ip()) +941 .filter(|(_, addr)| *addr != selected_path) +942 { +943 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { +944 continue; // Do not close the last direct path. +945 } +946 if let Some(path) = conn_state +947 .handle +948 .upgrade() +949 .filter(|conn| conn.side().is_client()) +950 .and_then(|conn| conn.path(*path_id)) +951 { +952 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); +953 match path.close(APPLICATION_ABANDON_PATH.into()) { +954 Err(quinn_proto::ClosePathError::LastOpenPath) => { +955 error!("could not close last open path"); +956 } +957 Err(quinn_proto::ClosePathError::ClosedPath) => { +958 // We already closed this. +959 } +960 Ok(_fut) => { +961 // We will handle the event in Self::handle_path_events. +962 } +963 } +964 } +965 } +966 } +967 } +968} +969 +970fn send_datagram<'a>( +971 sender: &'a mut TransportsSender, +972 dst: transports::Addr, +973 owned_transmit: OwnedTransmit, +974) -> impl Future<Output = n0_error::Result<()>> + 'a { +975 std::future::poll_fn(move |cx| { +976 let transmit = transports::Transmit { +977 ecn: owned_transmit.ecn, +978 contents: owned_transmit.contents.as_ref(), +979 segment_size: owned_transmit.segment_size, +980 }; +981 +982 Pin::new(&mut *sender) +983 .poll_send(cx, &dst, None, &transmit) +984 .map(|res| res.with_context(|_| format!("failed to send datagram to {dst:?}"))) +985 }) +986} +987 +988/// Messages to send to the [`RemoteStateActor`]. +989#[derive(derive_more::Debug)] +990pub(crate) enum RemoteStateMessage { +991 /// Sends a datagram to all known paths. +992 /// +993 /// Used to send QUIC Initial packets. If there is no working direct path this will +994 /// trigger holepunching. +995 /// +996 /// This is not acceptable to use on the normal send path, as it is an async send +997 /// operation with a bunch more copying. So it should only be used for sending QUIC +998 /// Initial packets. +999 #[debug("SendDatagram(..)")] +1000 SendDatagram(TransportsSender, OwnedTransmit), +1001 /// Adds an active connection to this remote endpoint. +1002 /// +1003 /// The connection will now be managed by this actor. Holepunching will happen when +1004 /// needed, any new paths discovered via holepunching will be added. And closed paths +1005 /// will be removed etc. +1006 #[debug("AddConnection(..)")] +1007 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>), +1008 /// Asks if there is any possible path that could be used. +1009 /// +1010 /// This adds the provided transport addresses to the list of potential paths for this remote +1011 /// and starts discovery if needed. +1012 /// +1013 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths. +1014 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails +1015 /// or produces no results, +1016 #[debug("ResolveRemote(..)")] +1017 ResolveRemote( +1018 BTreeSet<TransportAddr>, +1019 oneshot::Sender<Result<(), DiscoveryError>>, +1020 ), +1021 /// Returns the current latency to the remote endpoint. +1022 /// +1023 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. +1024 #[debug("Latency(..)")] +1025 Latency(oneshot::Sender<Option<Duration>>), +1026} +1027 +1028/// A handle to a [`RemoteStateActor`]. +1029/// +1030/// Dropping this will stop the actor. The actor will also stop after an idle timeout +1031/// if it has no connections, an empty inbox, and no other senders than the one stored +1032/// in the endpoint map exist. +1033#[derive(Debug)] +1034pub(super) struct RemoteStateHandle { +1035 /// Sender for the channel into the [`RemoteStateActor`]. +1036 /// +1037 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver +1038 /// hasn't been closed. +1039 pub(super) sender: GuardedSender<RemoteStateMessage>, +1040 _task: AbortOnDropHandle<()>, +1041} +1042 +1043/// Information about a holepunch attempt. +1044/// +1045/// Addresses are always stored in canonical form. +1046#[derive(Debug)] +1047struct HolepunchAttempt { +1048 when: Instant, +1049 /// The set of local addresses which could take part in holepunching. +1050 /// +1051 /// This does not mean every address here participated in the holepunching. E.g. we +1052 /// could have tried only a sub-set of the addresses because a previous attempt already +1053 /// covered part of the range. +1054 /// +1055 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1056 /// do not want to compare the sources of these addresses. +1057 local_candidates: BTreeSet<SocketAddr>, +1058 /// The set of remote addresses which could take part in holepunching. +1059 /// +1060 /// Like [`Self::local_candidates`] we may not have used them. +1061 remote_candidates: BTreeSet<SocketAddr>, +1062} +1063 +1064/// Newtype to track Connections. +1065/// +1066/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid +1067/// for active connections. +1068#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +1069struct ConnId(usize); +1070 +1071/// State about one connection. +1072#[derive(Debug)] +1073struct ConnectionState { +1074 /// Weak handle to the connection. +1075 handle: WeakConnectionHandle, +1076 /// The information we publish to users about the paths used in this connection. +1077 pub_open_paths: Watchable<PathAddrList>, +1078 /// The paths that exist on this connection. +1079 /// +1080 /// This could be in any state, e.g. while still validating the path or already closed +1081 /// but not yet fully removed from the connection. This exists as long as Quinn knows +1082 /// about the [`PathId`]. +1083 paths: FxHashMap<PathId, transports::Addr>, +1084 /// The open paths on this connection, a subset of [`Self::paths`]. +1085 open_paths: FxHashMap<PathId, transports::Addr>, +1086 /// Reverse map of [`Self::paths]. +1087 path_ids: FxHashMap<transports::Addr, PathId>, +1088} +1089 +1090impl ConnectionState { +1091 /// Tracks a path for the connection. +1092 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { +1093 self.paths.insert(path_id, remote.clone()); +1094 self.path_ids.insert(remote, path_id); +1095 } +1096 +1097 /// Tracks an open path for the connection. +1098 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { +1099 self.paths.insert(path_id, remote.clone()); +1100 self.open_paths.insert(path_id, remote.clone()); +1101 self.path_ids.insert(remote, path_id); +1102 +1103 self.update_pub_path_info(); +1104 } +1105 +1106 /// Completely removes a path from this connection. +1107 fn remove_path(&mut self, path_id: &PathId) { +1108 if let Some(addr) = self.paths.remove(path_id) { +1109 self.path_ids.remove(&addr); +1110 } +1111 self.open_paths.remove(path_id); +1112 } +1113 +1114 /// Removes the path from the open paths. +1115 fn remove_open_path(&mut self, path_id: &PathId) { +1116 self.open_paths.remove(path_id); +1117 +1118 self.update_pub_path_info(); +1119 } +1120 +1121 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. +1122 /// +1123 /// [`Connection`]: crate::endpoint::Connection +1124 fn update_pub_path_info(&self) { +1125 let new = self +1126 .open_paths +1127 .iter() +1128 .map(|(path_id, remote)| { +1129 let remote = TransportAddr::from(remote.clone()); +1130 (remote, *path_id) +1131 }) +1132 .collect::<PathAddrList>(); +1133 +1134 self.pub_open_paths.set(new).ok(); +1135 } +1136} +1137 +1138/// Watcher for the open paths and selected transmission path in a connection. +1139/// +1140/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +1141/// +1142/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the +1143/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with +1144/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`]. +1145/// +1146/// [`Connection`]: crate::endpoint::Connection +1147#[derive(Clone, derive_more::Debug)] +1148#[debug("PathsWatcher")] +1149#[allow(clippy::type_complexity)] +1150pub(crate) struct PathsWatcher( +1151 Box< +1152 n0_watcher::Map< +1153 n0_watcher::Tuple< +1154 n0_watcher::Direct<PathAddrList>, +1155 n0_watcher::Direct<Option<transports::Addr>>, +1156 >, +1157 PathInfoList, +1158 >, +1159 >, +1160); +1161 +1162impl n0_watcher::Watcher for PathsWatcher { +1163 type Value = PathInfoList; +1164 +1165 fn update(&mut self) -> bool { +1166 self.0.update() +1167 } +1168 +1169 fn peek(&self) -> &Self::Value { +1170 self.0.peek() +1171 } +1172 +1173 fn is_connected(&self) -> bool { +1174 self.0.is_connected() +1175 } +1176 +1177 fn poll_updated( +1178 &mut self, +1179 cx: &mut std::task::Context<'_>, +1180 ) -> Poll<Result<(), n0_watcher::Disconnected>> { +1181 self.0.poll_updated(cx) +1182 } +1183} +1184 +1185impl PathsWatcher { +1186 fn new( +1187 open_paths: n0_watcher::Direct<PathAddrList>, +1188 selected_path: n0_watcher::Direct<Option<transports::Addr>>, +1189 conn_handle: WeakConnectionHandle, +1190 ) -> Self { +1191 Self(Box::new(open_paths.or(selected_path).map( +1192 move |(open_paths, selected_path)| { +1193 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); +1194 let Some(conn) = conn_handle.upgrade() else { +1195 return PathInfoList(Default::default()); +1196 }; +1197 let list = open_paths +1198 .into_iter() +1199 .flat_map(move |(remote, path_id)| { +1200 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) +1201 }) +1202 .collect(); +1203 PathInfoList(list) +1204 }, +1205 ))) +1206 } +1207} +1208 +1209/// List of [`PathInfo`] for the network paths of a [`Connection`]. +1210/// +1211/// This struct implements [`IntoIterator`]. +1212/// +1213/// [`Connection`]: crate::endpoint::Connection +1214#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] +1215#[debug("{_0:?}")] +1216pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1217 +1218impl PathInfoList { +1219 /// Returns an iterator over the path infos. +1220 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { +1221 self.0.iter() +1222 } +1223 +1224 /// Returns `true` if the list is empty. +1225 pub fn is_empty(&self) -> bool { +1226 self.0.is_empty() +1227 } +1228 +1229 /// Returns the number of paths. +1230 pub fn len(&self) -> usize { +1231 self.0.len() +1232 } +1233} +1234 +1235/// Information about a network path used by a [`Connection`]. +1236/// +1237/// [`Connection`]: crate::endpoint::Connection +1238#[derive(derive_more::Debug, Clone)] +1239pub struct PathInfo { +1240 path_id: PathId, +1241 #[debug(skip)] +1242 handle: WeakConnectionHandle, +1243 stats: PathStats, +1244 remote: TransportAddr, +1245 is_selected: bool, +1246} +1247 +1248impl PartialEq for PathInfo { +1249 fn eq(&self, other: &Self) -> bool { +1250 self.path_id == other.path_id +1251 && self.remote == other.remote +1252 && self.is_selected == other.is_selected +1253 } +1254} +1255 +1256impl Eq for PathInfo {} +1257 +1258impl PathInfo { +1259 fn new( +1260 path_id: PathId, +1261 conn: &quinn::Connection, +1262 remote: TransportAddr, +1263 selected_path: Option<&TransportAddr>, +1264 ) -> Option<Self> { +1265 let stats = conn.path_stats(path_id)?; +1266 Some(Self { +1267 path_id, +1268 handle: conn.weak_handle(), +1269 is_selected: Some(&remote) == selected_path, +1270 remote, +1271 stats, +1272 }) +1273 } +1274 +1275 /// The remote transport address used by this network path. +1276 pub fn remote_addr(&self) -> &TransportAddr { +1277 &self.remote +1278 } +1279 +1280 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. +1281 /// +1282 /// [`Connection`]: crate::endpoint::Connection +1283 pub fn is_selected(&self) -> bool { +1284 self.is_selected +1285 } +1286 +1287 /// Whether this is an IP transport address. +1288 pub fn is_ip(&self) -> bool { +1289 self.remote.is_ip() +1290 } +1291 +1292 /// Whether this is a transport address via a relay server. +1293 pub fn is_relay(&self) -> bool { +1294 self.remote.is_relay() +1295 } +1296 +1297 /// Returns stats for this transmission path. +1298 pub fn stats(&self) -> PathStats { +1299 self.handle +1300 .upgrade() +1301 .and_then(|conn| conn.path_stats(self.path_id)) +1302 .unwrap_or(self.stats) +1303 } +1304 +1305 /// Current best estimate of this paths's latency (round-trip-time) +1306 pub fn rtt(&self) -> Duration { +1307 self.stats().rtt +1308 } +1309} +1310 +1311/// Poll a future once, like n0_future::future::poll_once but sync. +1312fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1313 let fut = std::pin::pin!(fut); +1314 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1315 Poll::Ready(res) => Some(res), +1316 Poll::Pending => None, +1317 } +1318} +1319 +1320/// Future that resolves to the `conn_id` once a connection is closed. +1321/// +1322/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive +1323/// while awaiting the future. +1324struct OnClosed { +1325 conn_id: ConnId, +1326 inner: quinn::OnClosed, +1327} +1328 +1329impl OnClosed { +1330 fn new(conn: &quinn::Connection) -> Self { +1331 Self { +1332 conn_id: ConnId(conn.stable_id()), +1333 inner: conn.on_closed(), +1334 } +1335 } +1336} +1337 +1338impl Future for OnClosed { +1339 type Output = ConnId; +1340 +1341 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1342 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1343 Poll::Ready(self.conn_id) +1344 } +1345} +1346 +1347/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`]. +1348fn to_transports_addr( +1349 endpoint_id: EndpointId, +1350 addrs: impl IntoIterator<Item = TransportAddr>, +1351) -> impl Iterator<Item = transports::Addr> { +1352 addrs.into_iter().filter_map(move |addr| match addr { +1353 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))), +1354 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)), +1355 _ => { +1356 warn!(?addr, "Unsupported TransportAddr"); +1357 None +1358 } +1359 }) +1360} \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/transports.rs.html b/pr/3381/docs/src/iroh/magicsock/transports.rs.html index 4f4a0c5e53..298ede2264 100644 --- a/pr/3381/docs/src/iroh/magicsock/transports.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/transports.rs.html @@ -693,67 +693,70 @@ 693 694 let sender = self.msock.remote_map.remote_state_actor(node_id); 695 let transmit = OwnedTransmit::from(quinn_transmit); -696 return match sender.try_send(RemoteStateMessage::SendDatagram(transmit)) { -697 Ok(()) => { -698 trace!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), "sent transmit"); -699 Poll::Ready(Ok(())) -700 } -701 Err(err) => { -702 // We do not want to block the next send which might be on a -703 // different transport. Instead we let Quinn handle this as -704 // a lost datagram. -705 // TODO: Revisit this: we might want to do something better. -706 debug!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), -707 "RemoteStateActor inbox {err:#}, dropped transmit"); -708 Poll::Ready(Ok(())) -709 } -710 }; -711 } -712 MultipathMappedAddr::Relay(relay_mapped_addr) => { -713 match self -714 .msock -715 .remote_map -716 .relay_mapped_addrs -717 .lookup(&relay_mapped_addr) -718 { -719 Some((relay_url, endpoint_id)) => Addr::Relay(relay_url, endpoint_id), -720 None => { -721 error!("unknown RelayMappedAddr, dropped transmit"); -722 return Poll::Ready(Ok(())); -723 } -724 } -725 } -726 MultipathMappedAddr::Ip(socket_addr) => Addr::Ip(socket_addr), -727 }; -728 -729 let transmit = Transmit { -730 ecn: quinn_transmit.ecn, -731 contents: quinn_transmit.contents, -732 segment_size: quinn_transmit.segment_size, -733 }; -734 let this = self.project(); -735 -736 match this -737 .sender -738 .poll_send(cx, &transport_addr, quinn_transmit.src_ip, &transmit) -739 { -740 Poll::Ready(Ok(())) => Poll::Ready(Ok(())), -741 Poll::Ready(Err(ref err)) => { -742 warn!("dropped transmit: {err:#}"); -743 Poll::Ready(Ok(())) -744 } -745 Poll::Pending => { -746 // We do not want to block the next send which might be on a -747 // different transport. Instead we let Quinn handle this as a lost -748 // datagram. -749 // TODO: Revisit this: we might want to do something better. -750 trace!("transport pending, dropped transmit"); -751 Poll::Ready(Ok(())) -752 } -753 } -754 } -755 -756 fn max_transmit_segments(&self) -> usize { -757 self.sender.max_transmit_segments -758 } -759} \ No newline at end of file +696 return match sender.try_send(RemoteStateMessage::SendDatagram( +697 self.sender.clone(), +698 transmit, +699 )) { +700 Ok(()) => { +701 trace!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), "sent transmit"); +702 Poll::Ready(Ok(())) +703 } +704 Err(err) => { +705 // We do not want to block the next send which might be on a +706 // different transport. Instead we let Quinn handle this as +707 // a lost datagram. +708 // TODO: Revisit this: we might want to do something better. +709 debug!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), +710 "RemoteStateActor inbox {err:#}, dropped transmit"); +711 Poll::Ready(Ok(())) +712 } +713 }; +714 } +715 MultipathMappedAddr::Relay(relay_mapped_addr) => { +716 match self +717 .msock +718 .remote_map +719 .relay_mapped_addrs +720 .lookup(&relay_mapped_addr) +721 { +722 Some((relay_url, endpoint_id)) => Addr::Relay(relay_url, endpoint_id), +723 None => { +724 error!("unknown RelayMappedAddr, dropped transmit"); +725 return Poll::Ready(Ok(())); +726 } +727 } +728 } +729 MultipathMappedAddr::Ip(socket_addr) => Addr::Ip(socket_addr), +730 }; +731 +732 let transmit = Transmit { +733 ecn: quinn_transmit.ecn, +734 contents: quinn_transmit.contents, +735 segment_size: quinn_transmit.segment_size, +736 }; +737 let this = self.project(); +738 +739 match this +740 .sender +741 .poll_send(cx, &transport_addr, quinn_transmit.src_ip, &transmit) +742 { +743 Poll::Ready(Ok(())) => Poll::Ready(Ok(())), +744 Poll::Ready(Err(ref err)) => { +745 warn!("dropped transmit: {err:#}"); +746 Poll::Ready(Ok(())) +747 } +748 Poll::Pending => { +749 // We do not want to block the next send which might be on a +750 // different transport. Instead we let Quinn handle this as a lost +751 // datagram. +752 // TODO: Revisit this: we might want to do something better. +753 trace!("transport pending, dropped transmit"); +754 Poll::Ready(Ok(())) +755 } +756 } +757 } +758 +759 fn max_transmit_segments(&self) -> usize { +760 self.sender.max_transmit_segments +761 } +762} \ No newline at end of file diff --git a/pr/3381/docs/trait.impl/core/convert/trait.From.js b/pr/3381/docs/trait.impl/core/convert/trait.From.js index 5fe49b9492..49cde58576 100644 --- a/pr/3381/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3381/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<DiscoveryError> for ConnectWithOptsError"],["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<AnyError> for AcceptError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<KeyParsingError> for Error"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl From<DiscoveryError> for ConnectWithOptsError"],["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<AnyError> for AcceptError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<KeyParsingError> for Error"],["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[12661,3090,18835]} \ No newline at end of file +//{"start":57,"fragment_lengths":[12661,3090,19611]} \ No newline at end of file diff --git a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 53eb8f19b7..6823ee20ab 100644 --- a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[1940]} \ No newline at end of file +//{"start":57,"fragment_lengths":[2062]} \ No newline at end of file