diff --git a/pr/3381/docs/iroh/endpoint/enum.ConnectionType.html b/pr/3381/docs/iroh/endpoint/enum.ConnectionType.html index 342f81d211..f0e4be04d7 100644 --- a/pr/3381/docs/iroh/endpoint/enum.ConnectionType.html +++ b/pr/3381/docs/iroh/endpoint/enum.ConnectionType.html @@ -1,4 +1,4 @@ -ConnectionType in iroh::endpoint - Rust

ConnectionType

Enum ConnectionType 

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

ConnectionType

Enum ConnectionType 

Source
pub enum ConnectionType {
     Direct(SocketAddr),
     Relay(RelayUrl),
     Mixed(SocketAddr, RelayUrl),
@@ -10,10 +10,10 @@
 

This is the case if we do have a UDP address, but are missing a recent confirmation that the address works.

§

None

We have no verified connection to this PublicKey

-

Trait Implementations§

Source§

impl Clone for ConnectionType

Source§

fn clone(&self) -> ConnectionType

Returns a 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 ConnectionType

Source§

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

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

impl Default for ConnectionType

Source§

fn default() -> ConnectionType

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

impl<'de> Deserialize<'de> for ConnectionType

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ConnectionType

Source§

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

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

impl PartialEq for ConnectionType

Source§

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

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

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

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

impl Serialize for ConnectionType

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ConnectionType

Source§

impl StructuralPartialEq for ConnectionType

Auto Trait Implementations§

§

impl Freeze for ConnectionType

§

impl RefUnwindSafe for ConnectionType

§

impl Send for ConnectionType

§

impl Sync for ConnectionType

§

impl Unpin for ConnectionType

§

impl UnwindSafe for ConnectionType

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectionType

Source§

fn clone(&self) -> ConnectionType

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 ConnectionType

Source§

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

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

impl Default for ConnectionType

Source§

fn default() -> ConnectionType

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

impl<'de> Deserialize<'de> for ConnectionType

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ConnectionType

Source§

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

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

impl PartialEq for ConnectionType

Source§

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

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

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

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

impl Serialize for ConnectionType

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ConnectionType

Source§

impl StructuralPartialEq for ConnectionType

Auto Trait Implementations§

§

impl Freeze for ConnectionType

§

impl RefUnwindSafe for ConnectionType

§

impl Send for ConnectionType

§

impl Sync for ConnectionType

§

impl Unpin for ConnectionType

§

impl UnwindSafe for ConnectionType

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.DirectAddrType.html b/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html index f48199daa4..7950534189 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§

§

impl Freeze for DirectAddrType

§

impl RefUnwindSafe for DirectAddrType

§

impl Send for DirectAddrType

§

impl Sync for DirectAddrType

§

impl Unpin for DirectAddrType

§

impl UnwindSafe for DirectAddrType

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§

§

impl Freeze for DirectAddrType

§

impl RefUnwindSafe for DirectAddrType

§

impl Send for DirectAddrType

§

impl Sync for DirectAddrType

§

impl Unpin for DirectAddrType

§

impl UnwindSafe for DirectAddrType

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 3917aad644..a17b7f2e30 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 {
     Saved,
     Udp,
     Relay,
@@ -32,12 +32,12 @@ address through multiple means.

§

Connection

We established a connection on this address.

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

-

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

§

impl Freeze for DirectAddr

§

impl RefUnwindSafe for DirectAddr

§

impl Send for DirectAddr

§

impl Sync for DirectAddr

§

impl Unpin for DirectAddr

§

impl UnwindSafe for DirectAddr

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§

§

impl Freeze for DirectAddr

§

impl RefUnwindSafe for DirectAddr

§

impl Send for DirectAddr

§

impl Sync for DirectAddr

§

impl Unpin for DirectAddr

§

impl UnwindSafe for DirectAddr

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 bc94628814..1304f9f186 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 0fda1124e2..b0fb15fd25 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/src/iroh/magicsock.rs.html b/pr/3381/docs/src/iroh/magicsock.rs.html index 5db957d3e5..334f7937dd 100644 --- a/pr/3381/docs/src/iroh/magicsock.rs.html +++ b/pr/3381/docs/src/iroh/magicsock.rs.html @@ -1011,1650 +1011,1649 @@ 1011 let (disco, disco_receiver) = DiscoState::new(&secret_key); 1012 1013 let endpoint_map = { -1014 let sender = transports.create_sender(); -1015 EndpointMap::new( -1016 secret_key.public(), -1017 // #[cfg(any(test, feature = "test-utils"))] -1018 // path_selection, -1019 metrics.magicsock.clone(), -1020 sender, -1021 direct_addrs.addrs.watch(), -1022 disco.clone(), -1023 ) -1024 }; -1025 -1026 let msock = Arc::new(MagicSock { -1027 public_key: secret_key.public(), -1028 closing: AtomicBool::new(false), -1029 closed: AtomicBool::new(false), -1030 disco, -1031 actor_sender: actor_sender.clone(), -1032 ipv6_reported, -1033 endpoint_map, -1034 discovery, -1035 relay_map: relay_map.clone(), -1036 discovery_user_data: RwLock::new(discovery_user_data), -1037 direct_addrs, -1038 net_report: Watchable::new((None, UpdateReason::None)), -1039 #[cfg(not(wasm_browser))] -1040 dns_resolver: dns_resolver.clone(), -1041 metrics: metrics.clone(), -1042 local_addrs_watch: transports.local_addrs_watch(), -1043 #[cfg(not(wasm_browser))] -1044 ip_bind_addrs: transports.ip_bind_addrs(), -1045 }); -1046 -1047 let mut endpoint_config = quinn::EndpointConfig::default(); -1048 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit -1049 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -1050 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -1051 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore -1052 // the packet if grease_quic_bit is set to false. -1053 endpoint_config.grease_quic_bit(false); -1054 -1055 let sender = transports.create_sender(); -1056 let local_addrs_watch = transports.local_addrs_watch(); -1057 let network_change_sender = transports.create_network_change_sender(); -1058 -1059 let endpoint = quinn::Endpoint::new_with_abstract_socket( -1060 endpoint_config, -1061 Some(server_config), -1062 Box::new(MagicTransport::new(msock.clone(), transports)), -1063 #[cfg(not(wasm_browser))] -1064 Arc::new(quinn::TokioRuntime), -1065 #[cfg(wasm_browser)] -1066 Arc::new(crate::web_runtime::WebRuntime), -1067 ) -1068 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; -1069 -1070 let network_monitor = netmon::Monitor::new() -1071 .await -1072 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; -1073 -1074 let qad_endpoint = endpoint.clone(); -1075 -1076 #[cfg(any(test, feature = "test-utils"))] -1077 let client_config = if insecure_skip_relay_cert_verify { -1078 iroh_relay::client::make_dangerous_client_config() -1079 } else { -1080 default_quic_client_config() -1081 }; -1082 #[cfg(not(any(test, feature = "test-utils")))] -1083 let client_config = default_quic_client_config(); -1084 -1085 let net_report_config = net_report::Options::default(); -1086 #[cfg(not(wasm_browser))] -1087 let net_report_config = net_report_config.quic_config(Some(QuicConfig { -1088 ep: qad_endpoint, -1089 client_config, -1090 ipv4: true, -1091 ipv6, -1092 })); -1093 -1094 #[cfg(any(test, feature = "test-utils"))] -1095 let net_report_config = -1096 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); -1097 -1098 let net_reporter = net_report::Client::new( -1099 #[cfg(not(wasm_browser))] -1100 dns_resolver, -1101 relay_map.clone(), -1102 net_report_config, -1103 metrics.net_report.clone(), -1104 ); -1105 -1106 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -1107 let direct_addr_update_state = DirectAddrUpdateState::new( -1108 msock.clone(), -1109 #[cfg(not(wasm_browser))] -1110 port_mapper, -1111 Arc::new(AsyncMutex::new(net_reporter)), -1112 relay_map, -1113 direct_addr_done_tx, -1114 ); -1115 -1116 let netmon_watcher = network_monitor.interface_state(); -1117 -1118 #[cfg_attr(not(wasm_browser), allow(unused_mut))] -1119 let mut actor = Actor { -1120 msg_receiver: actor_receiver, -1121 msock: msock.clone(), -1122 periodic_re_stun_timer: new_re_stun_timer(false), -1123 network_monitor, -1124 netmon_watcher, -1125 direct_addr_update_state, -1126 network_change_sender, -1127 direct_addr_done_rx, -1128 pending_call_me_maybes: Default::default(), -1129 disco_receiver, -1130 }; -1131 // Initialize addresses -1132 #[cfg(not(wasm_browser))] -1133 actor.update_direct_addresses(None); -1134 -1135 let actor_task = task::spawn( -1136 actor -1137 .run(shutdown_token.child_token(), local_addrs_watch, sender) -1138 .instrument(info_span!("actor")), -1139 ); -1140 -1141 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); -1142 -1143 Ok(Handle { -1144 msock, -1145 actor_task, -1146 endpoint, -1147 shutdown_token, -1148 }) -1149 } -1150 -1151 /// The underlying [`quinn::Endpoint`] -1152 pub fn endpoint(&self) -> &quinn::Endpoint { -1153 &self.endpoint -1154 } -1155 -1156 /// Closes the connection. -1157 /// -1158 /// Only the first close does anything. Any later closes return nil. Polling the socket -1159 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely -1160 /// after this call. -1161 /// -1162 /// [`Poll::Pending`]: std::task::Poll::Pending -1163 #[instrument(skip_all)] -1164 pub(crate) async fn close(&self) { -1165 trace!(me = ?self.public_key, "magicsock closing..."); -1166 // Initiate closing all connections, and refuse future connections. -1167 self.endpoint.close(0u16.into(), b""); -1168 -1169 // In the history of this code, this call had been -1170 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1171 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1172 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1173 // and finally added back in together with this comment. -1174 // So before removing this call, please consider carefully. -1175 // Among other things, this call tries its best to make sure that any queued close frames -1176 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -1177 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -1178 // This allows the other endpoints for these connections to be notified to release -1179 // their resources, or - depending on the protocol - that all data was received. -1180 // With the current quinn API, this is the only way to ensure protocol code can use -1181 // connection close codes, and close the endpoint properly. -1182 // If this call is skipped, then connections that protocols close just shortly before the -1183 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -1184 self.endpoint.wait_idle().await; -1185 -1186 if self.msock.is_closed() { -1187 return; -1188 } -1189 self.msock.closing.store(true, Ordering::Relaxed); -1190 self.shutdown_token.cancel(); -1191 -1192 // MutexGuard is not held across await points -1193 let task = self.actor_task.lock().expect("poisoned").take(); -1194 if let Some(task) = task { -1195 // give the tasks a moment to shutdown cleanly -1196 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1197 if let Err(err) = task.await { -1198 warn!("unexpected error in task shutdown: {:?}", err); -1199 } -1200 }) -1201 .await; -1202 match shutdown_done { -1203 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1204 Err(time::Elapsed { .. }) => { -1205 // Dropping the task will abort itt -1206 warn!("tasks didn't finish in time, aborting"); -1207 } -1208 } -1209 } -1210 -1211 self.msock.closed.store(true, Ordering::SeqCst); -1212 -1213 trace!("magicsock closed"); -1214 } -1215} -1216 -1217fn default_quic_client_config() -> rustls::ClientConfig { -1218 // create a client config for the endpoint to use for QUIC address discovery -1219 let root_store = -1220 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -1221 rustls::client::ClientConfig::builder_with_provider(Arc::new( -1222 rustls::crypto::ring::default_provider(), -1223 )) -1224 .with_safe_default_protocol_versions() -1225 .expect("ring supports these") -1226 .with_root_certificates(root_store) -1227 .with_no_client_auth() -1228} -1229 -1230#[derive(Debug, Clone)] -1231struct DiscoState { -1232 /// The EndpointId/PublikeKey of this endpoint. -1233 this_id: EndpointId, -1234 /// Encryption key for this endpoint. -1235 secret_encryption_key: Arc<crypto_box::SecretKey>, -1236 /// The state for an active DiscoKey. -1237 secrets: Arc<Mutex<HashMap<PublicKey, SharedSecret>>>, -1238 /// Disco (ping) queue -1239 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, -1240} -1241 -1242impl DiscoState { -1243 fn new( -1244 secret_key: &SecretKey, -1245 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { -1246 let this_id = secret_key.public(); -1247 let secret_encryption_key = secret_ed_box(secret_key); -1248 let (disco_sender, disco_receiver) = mpsc::channel(256); -1249 -1250 ( -1251 Self { -1252 this_id, -1253 secret_encryption_key: Arc::new(secret_encryption_key), -1254 secrets: Default::default(), -1255 sender: disco_sender, -1256 }, -1257 disco_receiver, -1258 ) -1259 } -1260 -1261 fn try_send(&self, dst: SendAddr, dst_key: PublicKey, msg: disco::Message) -> bool { -1262 self.sender.try_send((dst, dst_key, msg)).is_ok() -1263 } -1264 -1265 fn encode_and_seal(&self, other_key: PublicKey, msg: &disco::Message) -> Bytes { -1266 let mut seal = msg.as_bytes(); -1267 self.get_secret(other_key, |secret| secret.seal(&mut seal)); -1268 disco::encode_message(&self.this_id, seal).into() -1269 } -1270 -1271 fn unseal_and_decode( -1272 &self, -1273 endpoint_key: PublicKey, -1274 sealed_box: &[u8], -1275 ) -> Result<disco::Message, DiscoBoxError> { -1276 let mut sealed_box = sealed_box.to_vec(); -1277 self.get_secret(endpoint_key, |secret| secret.open(&mut sealed_box)) -1278 .map_err(|source| e!(DiscoBoxError::Open { source }))?; -1279 disco::Message::from_bytes(&sealed_box) -1280 .map_err(|source| e!(DiscoBoxError::Parse { source })) -1281 } -1282 -1283 fn get_secret<F, T>(&self, endpoint_id: PublicKey, cb: F) -> T -1284 where -1285 F: FnOnce(&mut SharedSecret) -> T, -1286 { -1287 let mut inner = self.secrets.lock().expect("poisoned"); -1288 let x = inner.entry(endpoint_id).or_insert_with(|| { -1289 let public_key = public_ed_box(&endpoint_id); -1290 SharedSecret::new(&self.secret_encryption_key, &public_key) -1291 }); -1292 cb(x) -1293 } -1294} -1295 -1296#[allow(missing_docs)] -1297#[stack_error(derive, add_meta)] -1298#[non_exhaustive] -1299enum DiscoBoxError { -1300 #[error("Failed to open crypto box")] -1301 Open { source: DecryptionError }, -1302 #[error("Failed to parse disco message")] -1303 Parse { source: disco::ParseError }, -1304} -1305 -1306#[derive(Debug)] -1307#[allow(clippy::enum_variant_names)] -1308enum ActorMessage { -1309 NetworkChange, -1310 RelayMapChange, -1311 #[cfg(test)] -1312 ForceNetworkChange(bool), -1313} -1314 -1315struct Actor { -1316 msock: Arc<MagicSock>, -1317 msg_receiver: mpsc::Receiver<ActorMessage>, -1318 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. -1319 periodic_re_stun_timer: time::Interval, -1320 -1321 network_monitor: netmon::Monitor, -1322 netmon_watcher: n0_watcher::Direct<netmon::State>, -1323 network_change_sender: transports::NetworkChangeSender, -1324 /// Indicates the direct addr update state. -1325 direct_addr_update_state: DirectAddrUpdateState, -1326 direct_addr_done_rx: mpsc::Receiver<()>, -1327 -1328 /// List of CallMeMaybe disco messages that should be sent out after -1329 /// the next endpoint update completes -1330 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, -1331 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, -1332} -1333 -1334#[cfg(not(wasm_browser))] -1335fn bind_ip( -1336 addr_v4: SocketAddrV4, -1337 addr_v6: Option<SocketAddrV6>, -1338 metrics: &EndpointMetrics, -1339) -> io::Result<(Vec<IpTransport>, portmapper::Client)> { -1340 let port_mapper = -1341 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); -1342 -1343 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); -1344 let ip4_port = v4.local_addr()?.port(); -1345 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); -1346 -1347 let addr_v6 = -1348 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); -1349 -1350 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { -1351 Ok(sock) => Some(Arc::new(sock)), -1352 Err(err) => { -1353 info!("bind ignoring IPv6 bind failure: {:?}", err); -1354 None -1355 } -1356 }; -1357 -1358 let port = v4.local_addr().map_or(0, |p| p.port()); -1359 -1360 let mut ip = vec![IpTransport::new( -1361 addr_v4.into(), -1362 v4, -1363 metrics.magicsock.clone(), -1364 )]; -1365 if let Some(v6) = v6 { -1366 ip.push(IpTransport::new( -1367 addr_v6.into(), -1368 v6, -1369 metrics.magicsock.clone(), -1370 )) -1371 } -1372 -1373 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails -1374 match port.try_into() { -1375 Ok(non_zero_port) => { -1376 port_mapper.update_local_port(non_zero_port); -1377 } -1378 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), -1379 } -1380 -1381 Ok((ip, port_mapper)) -1382} -1383 -1384impl Actor { -1385 async fn run( -1386 mut self, -1387 shutdown_token: CancellationToken, -1388 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1389 sender: TransportsSender, -1390 ) { -1391 // Setup network monitoring -1392 let mut current_netmon_state = self.netmon_watcher.get(); -1393 -1394 #[cfg(not(wasm_browser))] -1395 let mut portmap_watcher = self -1396 .direct_addr_update_state -1397 .port_mapper -1398 .watch_external_address(); -1399 -1400 let mut receiver_closed = false; -1401 #[cfg_attr(wasm_browser, allow(unused_mut))] -1402 let mut portmap_watcher_closed = false; -1403 -1404 let mut net_report_watcher = self.msock.net_report.watch(); -1405 -1406 // ensure we are doing an initial publish of our addresses -1407 self.msock.publish_my_addr(); -1408 -1409 loop { -1410 self.msock.metrics.magicsock.actor_tick_main.inc(); -1411 #[cfg(not(wasm_browser))] -1412 let portmap_watcher_changed = portmap_watcher.changed(); -1413 #[cfg(wasm_browser)] -1414 let portmap_watcher_changed = n0_future::future::pending(); -1415 -1416 tokio::select! { -1417 _ = shutdown_token.cancelled() => { -1418 debug!("shutting down"); -1419 return; -1420 } -1421 msg = self.msg_receiver.recv(), if !receiver_closed => { -1422 let Some(msg) = msg else { -1423 trace!("tick: magicsock receiver closed"); -1424 self.msock.metrics.magicsock.actor_tick_other.inc(); -1425 -1426 receiver_closed = true; -1427 continue; -1428 }; -1429 -1430 trace!(?msg, "tick: msg"); -1431 self.msock.metrics.magicsock.actor_tick_msg.inc(); -1432 self.handle_actor_message(msg).await; -1433 } -1434 tick = self.periodic_re_stun_timer.tick() => { -1435 trace!("tick: re_stun {:?}", tick); -1436 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); -1437 self.re_stun(UpdateReason::Periodic); -1438 } -1439 new_addr = watcher.updated() => { -1440 match new_addr { -1441 Ok(addrs) => { -1442 if !addrs.is_empty() { -1443 trace!(?addrs, "local addrs"); -1444 self.msock.publish_my_addr(); -1445 } -1446 } -1447 Err(_) => { -1448 warn!("local addr watcher stopped"); -1449 } -1450 } -1451 } -1452 report = net_report_watcher.updated() => { -1453 match report { -1454 Ok((report, _)) => { -1455 self.handle_net_report_report(report); -1456 #[cfg(not(wasm_browser))] -1457 { -1458 self.periodic_re_stun_timer = new_re_stun_timer(true); -1459 } -1460 } -1461 Err(_) => { -1462 warn!("net report watcher stopped"); -1463 } -1464 } -1465 } -1466 reason = self.direct_addr_done_rx.recv() => { -1467 match reason { -1468 Some(()) => { -1469 // check if a new run needs to be scheduled -1470 let state = self.netmon_watcher.get(); -1471 self.direct_addr_update_state.try_run(state.into()); -1472 } -1473 None => { -1474 warn!("direct addr watcher died"); -1475 } -1476 } -1477 } -1478 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1479 #[cfg(not(wasm_browser))] -1480 { -1481 if change.is_err() { -1482 trace!("tick: portmap watcher closed"); -1483 self.msock.metrics.magicsock.actor_tick_other.inc(); -1484 -1485 portmap_watcher_closed = true; -1486 continue; -1487 } -1488 -1489 trace!("tick: portmap changed"); -1490 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); -1491 let new_external_address = *portmap_watcher.borrow(); -1492 debug!("external address updated: {new_external_address:?}"); -1493 self.re_stun(UpdateReason::PortmapUpdated); -1494 } -1495 #[cfg(wasm_browser)] -1496 let _unused_in_browsers = change; -1497 }, -1498 state = self.netmon_watcher.updated() => { -1499 let Ok(state) = state else { -1500 trace!("tick: link change receiver closed"); -1501 self.msock.metrics.magicsock.actor_tick_other.inc(); -1502 continue; -1503 }; -1504 let is_major = state.is_major_change(&current_netmon_state); -1505 event!( -1506 target: "iroh::_events::link_change", -1507 Level::DEBUG, -1508 ?state, -1509 is_major -1510 ); -1511 current_netmon_state = state; -1512 self.msock.metrics.magicsock.actor_link_change.inc(); -1513 self.handle_network_change(is_major).await; -1514 } -1515 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { -1516 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { -1517 warn!(%dst, endpoint = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); -1518 } -1519 } -1520 } -1521 } -1522 } -1523 -1524 async fn handle_network_change(&mut self, is_major: bool) { -1525 debug!(is_major, "link change detected"); -1526 -1527 if is_major { -1528 if let Err(err) = self.network_change_sender.rebind() { -1529 warn!("failed to rebind transports: {err:?}"); -1530 } -1531 -1532 #[cfg(not(wasm_browser))] -1533 self.msock.dns_resolver.reset().await; -1534 self.re_stun(UpdateReason::LinkChangeMajor); -1535 } else { -1536 self.re_stun(UpdateReason::LinkChangeMinor); -1537 } -1538 } -1539 -1540 fn handle_relay_map_change(&mut self) { -1541 self.re_stun(UpdateReason::RelayMapChange); -1542 } -1543 -1544 fn re_stun(&mut self, why: UpdateReason) { -1545 let state = self.netmon_watcher.get(); -1546 self.direct_addr_update_state -1547 .schedule_run(why, state.into()); -1548 } -1549 -1550 /// Processes an incoming actor message. -1551 /// -1552 /// Returns `true` if it was a shutdown. -1553 async fn handle_actor_message(&mut self, msg: ActorMessage) { -1554 match msg { -1555 ActorMessage::NetworkChange => { -1556 self.network_monitor.network_change().await.ok(); -1557 } -1558 ActorMessage::RelayMapChange => { -1559 self.handle_relay_map_change(); -1560 } -1561 #[cfg(test)] -1562 ActorMessage::ForceNetworkChange(is_major) => { -1563 self.handle_network_change(is_major).await; -1564 } -1565 } -1566 } -1567 -1568 /// Updates the direct addresses of this magic socket. -1569 /// -1570 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of -1571 /// direct addresses from: -1572 /// -1573 /// - The portmapper. -1574 /// - A net_report report. -1575 /// - The local interfaces IP addresses. -1576 #[cfg(not(wasm_browser))] -1577 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1578 let portmap_watcher = self -1579 .direct_addr_update_state -1580 .port_mapper -1581 .watch_external_address(); -1582 -1583 // We only want to have one DirectAddr for each SocketAddr we have. So we store -1584 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -1585 // DirectAddr from each entry. -1586 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -1587 -1588 // First add PortMapper provided addresses. -1589 let maybe_port_mapped = *portmap_watcher.borrow(); -1590 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -1591 addrs -1592 .entry(portmap_ext) -1593 .or_insert(DirectAddrType::Portmapped); -1594 } -1595 -1596 // Next add STUN addresses from the net_report report. -1597 if let Some(net_report_report) = net_report_report { -1598 if let Some(global_v4) = net_report_report.global_v4 { -1599 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); -1600 -1601 // If they're behind a hard NAT and are using a fixed -1602 // port locally, assume they might've added a static -1603 // port mapping on their router to the same explicit -1604 // port that we are running with. Worst case it's an invalid candidate mapping. -1605 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { -1606 if addr.port() != 0 { -1607 Some(addr.port()) -1608 } else { -1609 None -1610 } -1611 }); -1612 -1613 if let Some(port) = port { -1614 if net_report_report -1615 .mapping_varies_by_dest() -1616 .unwrap_or_default() -1617 { -1618 let mut addr = global_v4; -1619 addr.set_port(port); -1620 addrs -1621 .entry(addr.into()) -1622 .or_insert(DirectAddrType::Qad4LocalPort); -1623 } -1624 } -1625 } -1626 if let Some(global_v6) = net_report_report.global_v6 { -1627 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); -1628 } -1629 } -1630 -1631 self.collect_local_addresses(&mut addrs); -1632 -1633 // Finally create and store store all these direct addresses and send any -1634 // queued call-me-maybe messages. -1635 self.msock.store_direct_addresses( -1636 addrs -1637 .iter() -1638 .map(|(addr, typ)| DirectAddr { -1639 addr: *addr, -1640 typ: *typ, -1641 }) -1642 .collect(), -1643 ); -1644 self.send_queued_call_me_maybes(); -1645 } -1646 -1647 #[cfg(not(wasm_browser))] -1648 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { -1649 // Matches the addresses that have been bound vs the requested ones. -1650 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -1651 .msock -1652 .ip_bind_addrs() -1653 .iter() -1654 .copied() -1655 .zip(self.msock.ip_local_addrs()) -1656 .collect(); -1657 -1658 // Do we listen on any IPv4 unspecified address? -1659 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -1660 if a.is_ipv4() && a.ip().is_unspecified() { -1661 Some(a.port()) -1662 } else { -1663 None -1664 } -1665 }); -1666 // Do we listen on any IPv6 unspecified address? -1667 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -1668 if a.is_ipv6() && a.ip().is_unspecified() { -1669 Some(a.port()) -1670 } else { -1671 None -1672 } -1673 }); -1674 -1675 // If a socket is bound to the unspecified address, create SocketAddrs for -1676 // each local IP address by pairing it with the port the socket is bound on. -1677 if local_addrs -1678 .iter() -1679 .any(|(_, local)| local.ip().is_unspecified()) -1680 { -1681 let LocalAddresses { -1682 regular: mut ips, -1683 loopback, -1684 } = self.netmon_watcher.get().local_addresses; -1685 if ips.is_empty() && addrs.is_empty() { -1686 // Include loopback addresses only if there are no other interfaces -1687 // or public addresses, this allows testing offline. -1688 ips = loopback; -1689 } -1690 -1691 for ip in ips { -1692 let port_if_unspecified = match ip { -1693 IpAddr::V4(_) => has_ipv4_unspecified, -1694 IpAddr::V6(_) => has_ipv6_unspecified, -1695 }; -1696 if let Some(port) = port_if_unspecified { -1697 let addr = SocketAddr::new(ip, port); -1698 addrs.entry(addr).or_insert(DirectAddrType::Local); -1699 } -1700 } -1701 } -1702 -1703 // If a socket is bound to a specific address, add it. -1704 for (bound, local) in local_addrs { -1705 if !bound.ip().is_unspecified() { -1706 addrs.entry(local).or_insert(DirectAddrType::Local); -1707 } -1708 } -1709 } -1710 -1711 fn send_queued_call_me_maybes(&mut self) { -1712 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); -1713 let msg = disco::Message::CallMeMaybe(msg); -1714 // allocate, to minimize locking duration -1715 -1716 for (public_key, url) in self.pending_call_me_maybes.drain() { -1717 if !self -1718 .msock -1719 .disco -1720 .try_send(SendAddr::Relay(url), public_key, msg.clone()) -1721 { -1722 warn!(endpoint = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); -1723 } -1724 } -1725 } -1726 -1727 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -1728 if let Some(ref mut r) = report { -1729 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -1730 if r.preferred_relay.is_none() { -1731 if let Some(my_relay) = self.msock.my_relay() { -1732 r.preferred_relay.replace(my_relay); -1733 } -1734 } -1735 -1736 // Notify all transports -1737 self.network_change_sender.on_network_change(r); -1738 } -1739 -1740 #[cfg(not(wasm_browser))] -1741 self.update_direct_addresses(report.as_ref()); -1742 } -1743} -1744 -1745fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -1746 // Pick a random duration between 20 and 26 seconds (just under 30s, -1747 // a common UDP NAT timeout on Linux,etc) -1748 let mut rng = rand::rng(); -1749 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); -1750 if initial_delay { -1751 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -1752 time::interval_at(time::Instant::now() + d, d) -1753 } else { -1754 debug!( -1755 "scheduling periodic_stun to run immediately and in {}s", -1756 d.as_secs() -1757 ); -1758 time::interval(d) -1759 } -1760} -1761 -1762#[cfg(not(wasm_browser))] -1763fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { -1764 debug!(%addr, "binding"); -1765 -1766 // First try binding a preferred port, if specified -1767 match UdpSocket::bind_full(addr) { -1768 Ok(socket) => { -1769 let local_addr = socket.local_addr()?; -1770 debug!(%addr, %local_addr, "successfully bound"); -1771 return Ok(socket); -1772 } -1773 Err(err) => { -1774 debug!(%addr, "failed to bind: {err:#}"); -1775 // If that was already the fallback port, then error out -1776 if addr.port() == 0 { -1777 return Err(err); -1778 } -1779 } -1780 } -1781 -1782 // Otherwise, try binding with port 0 -1783 addr.set_port(0); -1784 UdpSocket::bind_full(addr) -1785} -1786 -1787/// The discovered direct addresses of this [`MagicSock`]. -1788/// -1789/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. -1790/// They include all locally bound ones as well as those discovered by other mechanisms like -1791/// QAD. -1792#[derive(derive_more::Debug, Clone, Default)] -1793struct DiscoveredDirectAddrs { -1794 /// The last set of discovered direct addresses. -1795 addrs: Watchable<BTreeSet<DirectAddr>>, -1796 -1797 /// The last time the direct addresses were updated, even if there was no change. -1798 /// -1799 /// This is only ever None at startup. -1800 updated_at: Arc<RwLock<Option<Instant>>>, -1801} -1802 -1803impl DiscoveredDirectAddrs { -1804 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -1805 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -1806 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -1807 let updated = self.addrs.set(addrs).is_ok(); -1808 if updated { -1809 event!( -1810 target: "iroh::_events::direct_addrs", -1811 Level::DEBUG, -1812 addrs = ?self.addrs.get(), -1813 ); -1814 } -1815 updated -1816 } -1817 -1818 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { -1819 self.addrs.get().into_iter().map(|da| da.addr) -1820 } -1821 -1822 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { -1823 let my_numbers = self.addrs.get().into_iter().map(|da| da.addr).collect(); -1824 disco::CallMeMaybe { my_numbers } -1825 } -1826} -1827 -1828fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { -1829 match msg { -1830 disco::Message::Ping(_) => { -1831 metrics.sent_disco_ping.inc(); -1832 } -1833 disco::Message::Pong(_) => { -1834 metrics.sent_disco_pong.inc(); -1835 } -1836 disco::Message::CallMeMaybe(_) => { -1837 metrics.sent_disco_call_me_maybe.inc(); -1838 } -1839 } -1840} -1841 -1842/// A *direct address* on which an iroh-endpoint might be contactable. -1843/// -1844/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be -1845/// contacted. These can come from various sources depending on the network topology of the -1846/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. -1847/// -1848/// This is essentially a combination of our local addresses combined with any reflexive -1849/// transport addresses we discovered using QAD. -1850#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -1851pub struct DirectAddr { -1852 /// The address. -1853 pub addr: SocketAddr, -1854 /// The origin of this direct address. -1855 pub typ: DirectAddrType, -1856} -1857 -1858/// The type of direct address. -1859/// -1860/// These are the various sources or origins from which an iroh endpoint might have found a -1861/// possible [`DirectAddr`]. -1862#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -1863pub enum DirectAddrType { -1864 /// Not yet determined.. -1865 Unknown, -1866 /// A locally bound socket address. -1867 Local, -1868 /// Public internet address discovered via QAD. -1869 /// -1870 /// When possible an iroh endpoint will perform QAD to discover which is the address -1871 /// from which it sends data on the public internet. This can be different from locally -1872 /// bound addresses when the endpoint is on a local network which performs NAT or similar. -1873 Qad, -1874 /// An address assigned by the router using port mapping. -1875 /// -1876 /// When possible an iroh endpoint will request a port mapping from the local router to -1877 /// get a publicly routable direct address. -1878 Portmapped, -1879 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -1880 /// -1881 /// It is possible to configure iroh to bound to a specific port and independently -1882 /// configure the router to forward this port to the iroh endpoint. This indicates a -1883 /// situation like this, which still uses QAD to discover the public address. -1884 Qad4LocalPort, -1885} -1886 -1887impl Display for DirectAddrType { -1888 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -1889 match self { -1890 DirectAddrType::Unknown => write!(f, "?"), -1891 DirectAddrType::Local => write!(f, "local"), -1892 DirectAddrType::Qad => write!(f, "qad"), -1893 DirectAddrType::Portmapped => write!(f, "portmap"), -1894 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -1895 } -1896 } -1897} -1898 -1899#[cfg(test)] -1900mod tests { -1901 use std::{sync::Arc, time::Duration}; -1902 -1903 use data_encoding::HEXLOWER; -1904 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; -1905 use n0_error::{Result, StackResultExt, StdResultExt}; -1906 use n0_future::{MergeBounded, StreamExt, time}; -1907 use n0_watcher::Watcher; -1908 use quinn::ServerConfig; -1909 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; -1910 use tokio_util::task::AbortOnDropHandle; -1911 use tracing::{Instrument, error, info, info_span, instrument}; -1912 use tracing_test::traced_test; -1913 -1914 use super::{EndpointIdMappedAddr, Options, endpoint_map::Source, mapped_addrs::MappedAddr}; -1915 use crate::{ -1916 Endpoint, -1917 RelayMap, -1918 RelayMode, -1919 SecretKey, -1920 discovery::static_provider::StaticProvider, -1921 dns::DnsResolver, -1922 // endpoint::PathSelection, -1923 magicsock::{Handle, MagicSock}, -1924 tls::{self, DEFAULT_MAX_TLS_TICKETS}, -1925 }; -1926 -1927 const ALPN: &[u8] = b"n0/test/1"; -1928 -1929 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { -1930 let secret_key = SecretKey::generate(rng); -1931 let server_config = make_default_server_config(&secret_key); -1932 Options { -1933 addr_v4: None, -1934 addr_v6: None, -1935 secret_key, -1936 relay_map: RelayMap::empty(), -1937 proxy_url: None, -1938 dns_resolver: DnsResolver::new(), -1939 server_config, -1940 #[cfg(any(test, feature = "test-utils"))] -1941 insecure_skip_relay_cert_verify: false, -1942 #[cfg(any(test, feature = "test-utils"))] -1943 // path_selection: PathSelection::default(), -1944 discovery_user_data: None, -1945 metrics: Default::default(), -1946 } -1947 } -1948 -1949 /// Generate a server config with no ALPNS and a default transport configuration -1950 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { -1951 let quic_server_config = -1952 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -1953 .make_server_config(vec![], false); -1954 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -1955 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -1956 server_config -1957 } -1958 -1959 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1960 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { -1961 info!("accepting conn"); -1962 let conn = ep.accept().await.expect("no conn"); -1963 -1964 info!("accepting"); -1965 let conn = conn.await.context("accepting")?; -1966 info!("accepting bi"); -1967 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; -1968 -1969 info!("reading"); -1970 let val = recv_bi -1971 .read_to_end(usize::MAX) -1972 .await -1973 .std_context("read to end")?; -1974 -1975 info!("replying"); -1976 for chunk in val.chunks(12) { -1977 send_bi.write_all(chunk).await.std_context("write all")?; -1978 } -1979 -1980 info!("finishing"); -1981 send_bi.finish().std_context("finish")?; -1982 send_bi.stopped().await.std_context("stopped")?; -1983 -1984 let stats = conn.stats(); -1985 info!("stats: {:#?}", stats); -1986 // TODO: ensure panics in this function are reported ok -1987 if matches!(loss, ExpectedLoss::AlmostNone) { -1988 for info in conn.paths().get().iter() { -1989 assert!( -1990 info.stats().lost_packets < 10, -1991 "[receiver] path {:?} should not loose many packets", -1992 info.remote_addr() -1993 ); -1994 } -1995 } -1996 -1997 info!("close"); -1998 conn.close(0u32.into(), b"done"); -1999 info!("wait idle"); -2000 ep.endpoint().wait_idle().await; -2001 -2002 Ok(()) -2003 } -2004 -2005 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -2006 async fn echo_sender( -2007 ep: Endpoint, -2008 dest_id: EndpointId, -2009 msg: &[u8], -2010 loss: ExpectedLoss, -2011 ) -> Result { -2012 info!("connecting to {}", dest_id.fmt_short()); -2013 let dest = EndpointAddr::new(dest_id); -2014 let conn = ep.connect(dest, ALPN).await?; -2015 -2016 info!("opening bi"); -2017 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; -2018 -2019 info!("writing message"); -2020 send_bi.write_all(msg).await.std_context("write all")?; -2021 -2022 info!("finishing"); -2023 send_bi.finish().std_context("finish")?; -2024 send_bi.stopped().await.std_context("stopped")?; -2025 -2026 info!("reading_to_end"); -2027 let val = recv_bi -2028 .read_to_end(usize::MAX) -2029 .await -2030 .std_context("read to end")?; -2031 assert_eq!( -2032 val, -2033 msg, -2034 "[sender] expected {}, got {}", -2035 HEXLOWER.encode(msg), -2036 HEXLOWER.encode(&val) -2037 ); -2038 -2039 let stats = conn.stats(); -2040 info!("stats: {:#?}", stats); -2041 if matches!(loss, ExpectedLoss::AlmostNone) { -2042 for info in conn.paths().get() { -2043 assert!( -2044 info.stats().lost_packets < 10, -2045 "[sender] path {:?} should not loose many packets", -2046 info.remote_addr() -2047 ); -2048 } -2049 } -2050 -2051 info!("close"); -2052 conn.close(0u32.into(), b"done"); -2053 info!("wait idle"); -2054 ep.endpoint().wait_idle().await; -2055 Ok(()) -2056 } -2057 -2058 #[derive(Debug, Copy, Clone)] -2059 enum ExpectedLoss { -2060 AlmostNone, -2061 YeahSure, -2062 } -2063 -2064 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -2065 async fn run_roundtrip( -2066 sender: Endpoint, -2067 receiver: Endpoint, -2068 payload: &[u8], -2069 loss: ExpectedLoss, -2070 ) { -2071 let send_endpoint_id = sender.id(); -2072 let recv_endpoint_id = receiver.id(); -2073 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); -2074 -2075 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); -2076 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; -2077 let sender_is_err = match sender_res { -2078 Ok(()) => false, -2079 Err(err) => { -2080 eprintln!("[sender] Error:\n{err:#?}"); -2081 true -2082 } -2083 }; -2084 let receiver_is_err = match receiver_task.await { -2085 Ok(Ok(())) => false, -2086 Ok(Err(err)) => { -2087 eprintln!("[receiver] Error:\n{err:#?}"); -2088 true -2089 } -2090 Err(joinerr) => { -2091 if joinerr.is_panic() { -2092 std::panic::resume_unwind(joinerr.into_panic()); -2093 } else { -2094 eprintln!("[receiver] Error:\n{joinerr:#?}"); -2095 } -2096 true -2097 } -2098 }; -2099 if sender_is_err || receiver_is_err { -2100 panic!("Sender or receiver errored"); -2101 } -2102 } -2103 -2104 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. -2105 /// -2106 /// The endpoints do not use a relay server but can connect to each other via local -2107 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if -2108 /// the endpoints rebind. -2109 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { -2110 let discovery = StaticProvider::new(); -2111 let ep1 = Endpoint::builder() -2112 .relay_mode(RelayMode::Disabled) -2113 .alpns(vec![ALPN.to_vec()]) -2114 .discovery(discovery.clone()) -2115 .bind() -2116 .await -2117 .unwrap(); -2118 let ep2 = Endpoint::builder() -2119 .relay_mode(RelayMode::Disabled) -2120 .alpns(vec![ALPN.to_vec()]) -2121 .discovery(discovery.clone()) -2122 .bind() -2123 .await -2124 .unwrap(); -2125 discovery.add_endpoint_info(ep1.addr()); -2126 discovery.add_endpoint_info(ep2.addr()); -2127 -2128 let ep1_addr_stream = ep1.watch_addr().stream(); -2129 let ep2_addr_stream = ep2.watch_addr().stream(); -2130 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); -2131 let task = tokio::spawn(async move { -2132 loop { -2133 while let Some(addr) = addr_stream.next().await { -2134 discovery.add_endpoint_info(addr); -2135 } -2136 } -2137 }); -2138 -2139 (AbortOnDropHandle::new(task), ep1, ep2) -2140 } -2141 -2142 #[tokio::test(flavor = "multi_thread")] -2143 #[traced_test] -2144 async fn test_two_devices_roundtrip_quinn_magic() -> Result { -2145 let (_guard, m1, m2) = endpoint_pair().await; -2146 -2147 for i in 0..5 { -2148 info!("\n-- round {i}"); -2149 run_roundtrip( -2150 m1.clone(), -2151 m2.clone(), -2152 b"hello m1", -2153 ExpectedLoss::AlmostNone, -2154 ) -2155 .await; -2156 run_roundtrip( -2157 m2.clone(), -2158 m1.clone(), -2159 b"hello m2", -2160 ExpectedLoss::AlmostNone, -2161 ) -2162 .await; -2163 -2164 info!("\n-- larger data"); -2165 let mut data = vec![0u8; 10 * 1024]; -2166 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2167 rng.fill_bytes(&mut data); -2168 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; -2169 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; -2170 } -2171 -2172 Ok(()) -2173 } -2174 -2175 #[tokio::test] -2176 #[traced_test] -2177 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { -2178 let (_guard, m1, m2) = endpoint_pair().await; -2179 -2180 println!("Net change"); -2181 m1.magic_sock().force_network_change(true).await; -2182 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -2183 -2184 let _handle = AbortOnDropHandle::new(tokio::spawn({ -2185 let endpoint = m2.clone(); -2186 async move { -2187 while let Some(incoming) = endpoint.accept().await { -2188 println!("Incoming first conn!"); -2189 let conn = incoming.await.anyerr()?; -2190 conn.closed().await; -2191 } -2192 -2193 n0_error::Ok(()) -2194 } -2195 })); -2196 -2197 println!("first conn!"); -2198 let conn = m1.connect(m2.addr(), ALPN).await?; -2199 println!("Closing first conn"); -2200 conn.close(0u32.into(), b"bye lolz"); -2201 conn.closed().await; -2202 println!("Closed first conn"); -2203 -2204 Ok(()) -2205 } -2206 -2207 #[tokio::test(flavor = "multi_thread")] -2208 #[traced_test] -2209 async fn test_two_devices_roundtrip_network_change() -> Result { -2210 time::timeout( -2211 Duration::from_secs(90), -2212 test_two_devices_roundtrip_network_change_impl(), -2213 ) -2214 .await -2215 .std_context("timeout")? -2216 } -2217 -2218 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly -2219 /// with (simulated) network changes. -2220 async fn test_two_devices_roundtrip_network_change_impl() -> Result { -2221 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2222 let (_guard, m1, m2) = endpoint_pair().await; -2223 -2224 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { -2225 let delay = rng.random_range(10..=500); -2226 Duration::from_millis(delay) -2227 }; -2228 let rounds = 5; -2229 -2230 // Regular network changes to m1 only. -2231 let m1_network_change_guard = { -2232 let m1 = m1.clone(); -2233 let mut rng = rng.clone(); -2234 let task = tokio::spawn(async move { -2235 loop { -2236 println!("[m1] network change"); -2237 m1.magic_sock().force_network_change(true).await; -2238 time::sleep(offset(&mut rng)).await; -2239 } -2240 }); -2241 AbortOnDropHandle::new(task) -2242 }; -2243 -2244 for i in 0..rounds { -2245 println!("-- [m1 changes] round {}", i + 1); -2246 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2247 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2248 -2249 println!("-- [m1 changes] larger data"); -2250 let mut data = vec![0u8; 10 * 1024]; -2251 rng.fill_bytes(&mut data); -2252 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2253 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2254 } -2255 -2256 std::mem::drop(m1_network_change_guard); -2257 -2258 // Regular network changes to m2 only. -2259 let m2_network_change_guard = { -2260 let m2 = m2.clone(); -2261 let mut rng = rng.clone(); -2262 let task = tokio::spawn(async move { -2263 loop { -2264 println!("[m2] network change"); -2265 m2.magic_sock().force_network_change(true).await; -2266 time::sleep(offset(&mut rng)).await; -2267 } -2268 }); -2269 AbortOnDropHandle::new(task) -2270 }; -2271 -2272 for i in 0..rounds { -2273 println!("-- [m2 changes] round {}", i + 1); -2274 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2275 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2276 -2277 println!("-- [m2 changes] larger data"); -2278 let mut data = vec![0u8; 10 * 1024]; -2279 rng.fill_bytes(&mut data); -2280 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2281 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2282 } -2283 -2284 std::mem::drop(m2_network_change_guard); -2285 -2286 // Regular network changes to both m1 and m2 only. -2287 let m1_m2_network_change_guard = { -2288 let m1 = m1.clone(); -2289 let m2 = m2.clone(); -2290 let mut rng = rng.clone(); -2291 let task = tokio::spawn(async move { -2292 println!("-- [m1] network change"); -2293 m1.magic_sock().force_network_change(true).await; -2294 println!("-- [m2] network change"); -2295 m2.magic_sock().force_network_change(true).await; -2296 time::sleep(offset(&mut rng)).await; -2297 }); -2298 AbortOnDropHandle::new(task) -2299 }; -2300 -2301 for i in 0..rounds { -2302 println!("-- [m1 & m2 changes] round {}", i + 1); -2303 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2304 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2305 -2306 println!("-- [m1 & m2 changes] larger data"); -2307 let mut data = vec![0u8; 10 * 1024]; -2308 rng.fill_bytes(&mut data); -2309 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2310 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2311 } -2312 -2313 std::mem::drop(m1_m2_network_change_guard); -2314 Ok(()) -2315 } -2316 -2317 #[tokio::test(flavor = "multi_thread")] -2318 #[traced_test] -2319 async fn test_two_devices_setup_teardown() -> Result { -2320 for i in 0..10 { -2321 println!("-- round {i}"); -2322 println!("setting up magic stack"); -2323 let (_guard, m1, m2) = endpoint_pair().await; -2324 -2325 println!("closing endpoints"); -2326 let msock1 = m1.magic_sock(); -2327 let msock2 = m2.magic_sock(); -2328 m1.close().await; -2329 m2.close().await; -2330 -2331 assert!(msock1.msock.is_closed()); -2332 assert!(msock2.msock.is_closed()); -2333 } -2334 Ok(()) -2335 } -2336 -2337 #[tokio::test] -2338 #[traced_test] -2339 async fn test_direct_addresses() { -2340 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2341 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); -2342 -2343 // See if we can get endpoints. -2344 let eps0 = ms.ip_addrs().get(); -2345 println!("{eps0:?}"); -2346 assert!(!eps0.is_empty()); -2347 -2348 // Getting the endpoints again immediately should give the same results. -2349 let eps1 = ms.ip_addrs().get(); -2350 println!("{eps1:?}"); -2351 assert_eq!(eps0, eps1); -2352 } -2353 -2354 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. -2355 /// -2356 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -2357 /// connections using [`ALPN`]. -2358 /// -2359 /// Use [`magicsock_connect`] to establish connections. -2360 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] -2361 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { -2362 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2363 .make_server_config(vec![ALPN.to_vec()], true); -2364 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -2365 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -2366 -2367 let dns_resolver = DnsResolver::new(); -2368 let opts = Options { -2369 addr_v4: None, -2370 addr_v6: None, -2371 secret_key: secret_key.clone(), -2372 relay_map: RelayMap::empty(), -2373 discovery_user_data: None, -2374 dns_resolver, -2375 proxy_url: None, -2376 server_config, -2377 insecure_skip_relay_cert_verify: false, -2378 // path_selection: PathSelection::default(), -2379 metrics: Default::default(), -2380 }; -2381 let msock = MagicSock::spawn(opts).await?; -2382 Ok(msock) -2383 } -2384 -2385 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2386 /// -2387 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2388 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2389 async fn magicsock_connect( -2390 ep: &quinn::Endpoint, -2391 ep_secret_key: SecretKey, -2392 addr: EndpointIdMappedAddr, -2393 endpoint_id: EndpointId, -2394 ) -> Result<quinn::Connection> { -2395 // Endpoint::connect sets this, do the same to have similar behaviour. -2396 let mut transport_config = quinn::TransportConfig::default(); -2397 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -2398 -2399 magicsock_connect_with_transport_config( -2400 ep, -2401 ep_secret_key, -2402 addr, -2403 endpoint_id, -2404 Arc::new(transport_config), -2405 ) -2406 .await -2407 } -2408 -2409 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2410 /// -2411 /// This version allows customising the transport config. -2412 /// -2413 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2414 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2415 async fn magicsock_connect_with_transport_config( -2416 ep: &quinn::Endpoint, -2417 ep_secret_key: SecretKey, -2418 mapped_addr: EndpointIdMappedAddr, -2419 endpoint_id: EndpointId, -2420 transport_config: Arc<quinn::TransportConfig>, -2421 ) -> Result<quinn::Connection> { -2422 let alpns = vec![ALPN.to_vec()]; -2423 let quic_client_config = -2424 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2425 .make_client_config(alpns, true); -2426 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -2427 client_config.transport_config(transport_config); -2428 let connect = ep -2429 .connect_with( -2430 client_config, -2431 mapped_addr.private_socket_addr(), -2432 &tls::name::encode(endpoint_id), -2433 ) -2434 .std_context("connect")?; -2435 let connection = connect.await.anyerr()?; -2436 Ok(connection) -2437 } -2438 -2439 #[tokio::test] -2440 #[traced_test] -2441 async fn test_try_send_no_send_addr() { -2442 // Regression test: if there is no send_addr we should keep being able to use the -2443 // Endpoint. -2444 -2445 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2446 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2447 let endpoint_id_2 = secret_key_2.public(); -2448 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); -2449 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); -2450 -2451 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2452 -2453 // Generate an address not present in the EndpointMap. -2454 let bad_addr = EndpointIdMappedAddr::generate(); -2455 -2456 // 500ms is rather fast here. Running this locally it should always be the correct -2457 // timeout. If this is too slow however the test will not become flaky as we are -2458 // expecting the timeout, we might just get the timeout for the wrong reason. But -2459 // this speeds up the test. -2460 let res = tokio::time::timeout( -2461 Duration::from_millis(500), -2462 magicsock_connect( -2463 msock_1.endpoint(), -2464 secret_key_1.clone(), -2465 bad_addr, -2466 endpoint_id_missing_endpoint, -2467 ), -2468 ) -2469 .await; -2470 assert!(res.is_err(), "expecting timeout"); -2471 -2472 // Now check we can still create another connection with this endpoint. -2473 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2474 -2475 // This needs an accept task -2476 let accept_task = tokio::spawn({ -2477 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2478 let incoming = ep.accept().await.std_context("no incoming")?; -2479 let _conn = incoming -2480 .accept() -2481 .std_context("accept")? -2482 .await -2483 .std_context("accepting")?; -2484 -2485 // Keep this connection alive for a while -2486 tokio::time::sleep(Duration::from_secs(10)).await; -2487 info!("accept finished"); -2488 Ok(()) -2489 } -2490 let ep = msock_2.endpoint().clone(); -2491 async move { -2492 if let Err(err) = accept(ep).await { -2493 error!("{err:#}"); -2494 } -2495 } -2496 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) -2497 }); -2498 let _accept_task = AbortOnDropHandle::new(accept_task); -2499 -2500 let addrs = msock_2 -2501 .ip_addrs() -2502 .get() -2503 .into_iter() -2504 .map(|x| TransportAddr::Ip(x.addr)) -2505 .collect(); -2506 let endpoint_addr_2 = EndpointAddr { -2507 id: endpoint_id_2, -2508 addrs, -2509 }; -2510 msock_1 -2511 .add_endpoint_addr( -2512 endpoint_addr_2, -2513 Source::NamedApp { -2514 name: "test".into(), -2515 }, -2516 ) -2517 .await -2518 .unwrap(); -2519 let addr = msock_1.get_endpoint_mapped_addr(endpoint_id_2); -2520 let res = tokio::time::timeout( -2521 Duration::from_secs(10), -2522 magicsock_connect( -2523 msock_1.endpoint(), -2524 secret_key_1.clone(), -2525 addr, -2526 endpoint_id_2, -2527 ), -2528 ) -2529 .await -2530 .expect("timeout while connecting"); -2531 -2532 // aka assert!(res.is_ok()) but with nicer error reporting. -2533 res.unwrap(); -2534 -2535 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -2536 // much internal state for now. -2537 } -2538 -2539 #[tokio::test] -2540 #[traced_test] -2541 async fn test_try_send_no_udp_addr_or_relay_url() { -2542 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -2543 // behaviour of MagicSock::try_send. -2544 -2545 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2546 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2547 let endpoint_id_2 = secret_key_2.public(); -2548 -2549 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2550 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2551 let ep_2 = msock_2.endpoint().clone(); -2552 -2553 // We need a task to accept the connection. -2554 let accept_task = tokio::spawn({ -2555 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2556 let incoming = ep.accept().await.std_context("no incoming")?; -2557 let conn = incoming -2558 .accept() -2559 .std_context("accept")? -2560 .await -2561 .std_context("connecting")?; -2562 let mut stream = conn.accept_uni().await.std_context("accept uni")?; -2563 stream -2564 .read_to_end(1 << 16) -2565 .await -2566 .std_context("read to end")?; -2567 info!("accept finished"); -2568 Ok(()) -2569 } -2570 async move { -2571 if let Err(err) = accept(ep_2).await { -2572 error!("{err:#}"); -2573 } -2574 } -2575 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) -2576 }); -2577 let _accept_task = AbortOnDropHandle::new(accept_task); -2578 -2579 // Add an empty entry in the EndpointMap of ep_1 -2580 msock_1 -2581 .endpoint_map -2582 .add_endpoint_addr( -2583 EndpointAddr { -2584 id: endpoint_id_2, -2585 addrs: Default::default(), -2586 }, -2587 Source::NamedApp { -2588 name: "test".into(), -2589 }, -2590 ) -2591 .await; -2592 let addr_2 = msock_1.get_endpoint_mapped_addr(endpoint_id_2); -2593 -2594 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -2595 // not take forever. You need to check the log output to verify this is really -2596 // triggering the correct error. -2597 // In test_try_send_no_send_addr() above you may have noticed we used -2598 // tokio::time::timeout() on the connection attempt instead. Here however we want -2599 // Quinn itself to have fully given up on the connection attempt because we will -2600 // later connect to **the same** endpoint. If Quinn did not give up on the connection -2601 // we'd close it on drop, and the retransmits of the close packets would interfere -2602 // with the next handshake, closing it during the handshake. This makes the test a -2603 // little slower though. -2604 let mut transport_config = quinn::TransportConfig::default(); -2605 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -2606 let res = magicsock_connect_with_transport_config( -2607 msock_1.endpoint(), -2608 secret_key_1.clone(), -2609 addr_2, -2610 endpoint_id_2, -2611 Arc::new(transport_config), -2612 ) -2613 .await; -2614 assert!(res.is_err(), "expected timeout"); -2615 info!("first connect timed out as expected"); -2616 -2617 // Provide correct addressing information -2618 msock_1 -2619 .endpoint_map -2620 .add_endpoint_addr( -2621 EndpointAddr { -2622 id: endpoint_id_2, -2623 addrs: msock_2 -2624 .ip_addrs() -2625 .get() -2626 .into_iter() -2627 .map(|x| TransportAddr::Ip(x.addr)) -2628 .collect(), -2629 }, -2630 Source::NamedApp { -2631 name: "test".into(), -2632 }, -2633 ) -2634 .await; -2635 -2636 // We can now connect -2637 tokio::time::timeout(Duration::from_secs(10), async move { -2638 info!("establishing new connection"); -2639 let conn = magicsock_connect( -2640 msock_1.endpoint(), -2641 secret_key_1.clone(), -2642 addr_2, -2643 endpoint_id_2, -2644 ) -2645 .await -2646 .unwrap(); -2647 info!("have connection"); -2648 let mut stream = conn.open_uni().await.unwrap(); -2649 stream.write_all(b"hello").await.unwrap(); -2650 stream.finish().unwrap(); -2651 stream.stopped().await.unwrap(); -2652 info!("finished stream"); -2653 }) -2654 .await -2655 .expect("connection timed out"); -2656 -2657 // TODO: could remove the addresses again, send, add it back and see it recover. -2658 // But we don't have that much private access to the EndpointMap. This will do for now. -2659 } -2660}
    \ No newline at end of file +1014 EndpointMap::new( +1015 secret_key.public(), +1016 // #[cfg(any(test, feature = "test-utils"))] +1017 // path_selection, +1018 metrics.magicsock.clone(), +1019 direct_addrs.addrs.watch(), +1020 disco.clone(), +1021 transports.create_sender(), +1022 ) +1023 }; +1024 +1025 let msock = Arc::new(MagicSock { +1026 public_key: secret_key.public(), +1027 closing: AtomicBool::new(false), +1028 closed: AtomicBool::new(false), +1029 disco, +1030 actor_sender: actor_sender.clone(), +1031 ipv6_reported, +1032 endpoint_map, +1033 discovery, +1034 relay_map: relay_map.clone(), +1035 discovery_user_data: RwLock::new(discovery_user_data), +1036 direct_addrs, +1037 net_report: Watchable::new((None, UpdateReason::None)), +1038 #[cfg(not(wasm_browser))] +1039 dns_resolver: dns_resolver.clone(), +1040 metrics: metrics.clone(), +1041 local_addrs_watch: transports.local_addrs_watch(), +1042 #[cfg(not(wasm_browser))] +1043 ip_bind_addrs: transports.ip_bind_addrs(), +1044 }); +1045 +1046 let mut endpoint_config = quinn::EndpointConfig::default(); +1047 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit +1048 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +1049 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +1050 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore +1051 // the packet if grease_quic_bit is set to false. +1052 endpoint_config.grease_quic_bit(false); +1053 +1054 let sender = transports.create_sender(); +1055 let local_addrs_watch = transports.local_addrs_watch(); +1056 let network_change_sender = transports.create_network_change_sender(); +1057 +1058 let endpoint = quinn::Endpoint::new_with_abstract_socket( +1059 endpoint_config, +1060 Some(server_config), +1061 Box::new(MagicTransport::new(msock.clone(), transports)), +1062 #[cfg(not(wasm_browser))] +1063 Arc::new(quinn::TokioRuntime), +1064 #[cfg(wasm_browser)] +1065 Arc::new(crate::web_runtime::WebRuntime), +1066 ) +1067 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; +1068 +1069 let network_monitor = netmon::Monitor::new() +1070 .await +1071 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; +1072 +1073 let qad_endpoint = endpoint.clone(); +1074 +1075 #[cfg(any(test, feature = "test-utils"))] +1076 let client_config = if insecure_skip_relay_cert_verify { +1077 iroh_relay::client::make_dangerous_client_config() +1078 } else { +1079 default_quic_client_config() +1080 }; +1081 #[cfg(not(any(test, feature = "test-utils")))] +1082 let client_config = default_quic_client_config(); +1083 +1084 let net_report_config = net_report::Options::default(); +1085 #[cfg(not(wasm_browser))] +1086 let net_report_config = net_report_config.quic_config(Some(QuicConfig { +1087 ep: qad_endpoint, +1088 client_config, +1089 ipv4: true, +1090 ipv6, +1091 })); +1092 +1093 #[cfg(any(test, feature = "test-utils"))] +1094 let net_report_config = +1095 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); +1096 +1097 let net_reporter = net_report::Client::new( +1098 #[cfg(not(wasm_browser))] +1099 dns_resolver, +1100 relay_map.clone(), +1101 net_report_config, +1102 metrics.net_report.clone(), +1103 ); +1104 +1105 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +1106 let direct_addr_update_state = DirectAddrUpdateState::new( +1107 msock.clone(), +1108 #[cfg(not(wasm_browser))] +1109 port_mapper, +1110 Arc::new(AsyncMutex::new(net_reporter)), +1111 relay_map, +1112 direct_addr_done_tx, +1113 ); +1114 +1115 let netmon_watcher = network_monitor.interface_state(); +1116 +1117 #[cfg_attr(not(wasm_browser), allow(unused_mut))] +1118 let mut actor = Actor { +1119 msg_receiver: actor_receiver, +1120 msock: msock.clone(), +1121 periodic_re_stun_timer: new_re_stun_timer(false), +1122 network_monitor, +1123 netmon_watcher, +1124 direct_addr_update_state, +1125 network_change_sender, +1126 direct_addr_done_rx, +1127 pending_call_me_maybes: Default::default(), +1128 disco_receiver, +1129 }; +1130 // Initialize addresses +1131 #[cfg(not(wasm_browser))] +1132 actor.update_direct_addresses(None); +1133 +1134 let actor_task = task::spawn( +1135 actor +1136 .run(shutdown_token.child_token(), local_addrs_watch, sender) +1137 .instrument(info_span!("actor")), +1138 ); +1139 +1140 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); +1141 +1142 Ok(Handle { +1143 msock, +1144 actor_task, +1145 endpoint, +1146 shutdown_token, +1147 }) +1148 } +1149 +1150 /// The underlying [`quinn::Endpoint`] +1151 pub fn endpoint(&self) -> &quinn::Endpoint { +1152 &self.endpoint +1153 } +1154 +1155 /// Closes the connection. +1156 /// +1157 /// Only the first close does anything. Any later closes return nil. Polling the socket +1158 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely +1159 /// after this call. +1160 /// +1161 /// [`Poll::Pending`]: std::task::Poll::Pending +1162 #[instrument(skip_all)] +1163 pub(crate) async fn close(&self) { +1164 trace!(me = ?self.public_key, "magicsock closing..."); +1165 // Initiate closing all connections, and refuse future connections. +1166 self.endpoint.close(0u16.into(), b""); +1167 +1168 // In the history of this code, this call had been +1169 // - removed: https://github.com/n0-computer/iroh/pull/1753 +1170 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1171 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1172 // and finally added back in together with this comment. +1173 // So before removing this call, please consider carefully. +1174 // Among other things, this call tries its best to make sure that any queued close frames +1175 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1176 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1177 // This allows the other endpoints for these connections to be notified to release +1178 // their resources, or - depending on the protocol - that all data was received. +1179 // With the current quinn API, this is the only way to ensure protocol code can use +1180 // connection close codes, and close the endpoint properly. +1181 // If this call is skipped, then connections that protocols close just shortly before the +1182 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1183 self.endpoint.wait_idle().await; +1184 +1185 if self.msock.is_closed() { +1186 return; +1187 } +1188 self.msock.closing.store(true, Ordering::Relaxed); +1189 self.shutdown_token.cancel(); +1190 +1191 // MutexGuard is not held across await points +1192 let task = self.actor_task.lock().expect("poisoned").take(); +1193 if let Some(task) = task { +1194 // give the tasks a moment to shutdown cleanly +1195 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1196 if let Err(err) = task.await { +1197 warn!("unexpected error in task shutdown: {:?}", err); +1198 } +1199 }) +1200 .await; +1201 match shutdown_done { +1202 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1203 Err(time::Elapsed { .. }) => { +1204 // Dropping the task will abort itt +1205 warn!("tasks didn't finish in time, aborting"); +1206 } +1207 } +1208 } +1209 +1210 self.msock.closed.store(true, Ordering::SeqCst); +1211 +1212 trace!("magicsock closed"); +1213 } +1214} +1215 +1216fn default_quic_client_config() -> rustls::ClientConfig { +1217 // create a client config for the endpoint to use for QUIC address discovery +1218 let root_store = +1219 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +1220 rustls::client::ClientConfig::builder_with_provider(Arc::new( +1221 rustls::crypto::ring::default_provider(), +1222 )) +1223 .with_safe_default_protocol_versions() +1224 .expect("ring supports these") +1225 .with_root_certificates(root_store) +1226 .with_no_client_auth() +1227} +1228 +1229#[derive(Debug, Clone)] +1230struct DiscoState { +1231 /// The EndpointId/PublikeKey of this endpoint. +1232 this_id: EndpointId, +1233 /// Encryption key for this endpoint. +1234 secret_encryption_key: Arc<crypto_box::SecretKey>, +1235 /// The state for an active DiscoKey. +1236 secrets: Arc<Mutex<HashMap<PublicKey, SharedSecret>>>, +1237 /// Disco (ping) queue +1238 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, +1239} +1240 +1241impl DiscoState { +1242 fn new( +1243 secret_key: &SecretKey, +1244 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { +1245 let this_id = secret_key.public(); +1246 let secret_encryption_key = secret_ed_box(secret_key); +1247 let (disco_sender, disco_receiver) = mpsc::channel(256); +1248 +1249 ( +1250 Self { +1251 this_id, +1252 secret_encryption_key: Arc::new(secret_encryption_key), +1253 secrets: Default::default(), +1254 sender: disco_sender, +1255 }, +1256 disco_receiver, +1257 ) +1258 } +1259 +1260 fn try_send(&self, dst: SendAddr, dst_key: PublicKey, msg: disco::Message) -> bool { +1261 self.sender.try_send((dst, dst_key, msg)).is_ok() +1262 } +1263 +1264 fn encode_and_seal(&self, other_key: PublicKey, msg: &disco::Message) -> Bytes { +1265 let mut seal = msg.as_bytes(); +1266 self.get_secret(other_key, |secret| secret.seal(&mut seal)); +1267 disco::encode_message(&self.this_id, seal).into() +1268 } +1269 +1270 fn unseal_and_decode( +1271 &self, +1272 endpoint_key: PublicKey, +1273 sealed_box: &[u8], +1274 ) -> Result<disco::Message, DiscoBoxError> { +1275 let mut sealed_box = sealed_box.to_vec(); +1276 self.get_secret(endpoint_key, |secret| secret.open(&mut sealed_box)) +1277 .map_err(|source| e!(DiscoBoxError::Open { source }))?; +1278 disco::Message::from_bytes(&sealed_box) +1279 .map_err(|source| e!(DiscoBoxError::Parse { source })) +1280 } +1281 +1282 fn get_secret<F, T>(&self, endpoint_id: PublicKey, cb: F) -> T +1283 where +1284 F: FnOnce(&mut SharedSecret) -> T, +1285 { +1286 let mut inner = self.secrets.lock().expect("poisoned"); +1287 let x = inner.entry(endpoint_id).or_insert_with(|| { +1288 let public_key = public_ed_box(&endpoint_id); +1289 SharedSecret::new(&self.secret_encryption_key, &public_key) +1290 }); +1291 cb(x) +1292 } +1293} +1294 +1295#[allow(missing_docs)] +1296#[stack_error(derive, add_meta)] +1297#[non_exhaustive] +1298enum DiscoBoxError { +1299 #[error("Failed to open crypto box")] +1300 Open { source: DecryptionError }, +1301 #[error("Failed to parse disco message")] +1302 Parse { source: disco::ParseError }, +1303} +1304 +1305#[derive(Debug)] +1306#[allow(clippy::enum_variant_names)] +1307enum ActorMessage { +1308 NetworkChange, +1309 RelayMapChange, +1310 #[cfg(test)] +1311 ForceNetworkChange(bool), +1312} +1313 +1314struct Actor { +1315 msock: Arc<MagicSock>, +1316 msg_receiver: mpsc::Receiver<ActorMessage>, +1317 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. +1318 periodic_re_stun_timer: time::Interval, +1319 +1320 network_monitor: netmon::Monitor, +1321 netmon_watcher: n0_watcher::Direct<netmon::State>, +1322 network_change_sender: transports::NetworkChangeSender, +1323 /// Indicates the direct addr update state. +1324 direct_addr_update_state: DirectAddrUpdateState, +1325 direct_addr_done_rx: mpsc::Receiver<()>, +1326 +1327 /// List of CallMeMaybe disco messages that should be sent out after +1328 /// the next endpoint update completes +1329 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, +1330 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, +1331} +1332 +1333#[cfg(not(wasm_browser))] +1334fn bind_ip( +1335 addr_v4: SocketAddrV4, +1336 addr_v6: Option<SocketAddrV6>, +1337 metrics: &EndpointMetrics, +1338) -> io::Result<(Vec<IpTransport>, portmapper::Client)> { +1339 let port_mapper = +1340 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); +1341 +1342 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); +1343 let ip4_port = v4.local_addr()?.port(); +1344 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); +1345 +1346 let addr_v6 = +1347 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); +1348 +1349 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { +1350 Ok(sock) => Some(Arc::new(sock)), +1351 Err(err) => { +1352 info!("bind ignoring IPv6 bind failure: {:?}", err); +1353 None +1354 } +1355 }; +1356 +1357 let port = v4.local_addr().map_or(0, |p| p.port()); +1358 +1359 let mut ip = vec![IpTransport::new( +1360 addr_v4.into(), +1361 v4, +1362 metrics.magicsock.clone(), +1363 )]; +1364 if let Some(v6) = v6 { +1365 ip.push(IpTransport::new( +1366 addr_v6.into(), +1367 v6, +1368 metrics.magicsock.clone(), +1369 )) +1370 } +1371 +1372 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails +1373 match port.try_into() { +1374 Ok(non_zero_port) => { +1375 port_mapper.update_local_port(non_zero_port); +1376 } +1377 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), +1378 } +1379 +1380 Ok((ip, port_mapper)) +1381} +1382 +1383impl Actor { +1384 async fn run( +1385 mut self, +1386 shutdown_token: CancellationToken, +1387 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1388 sender: TransportsSender, +1389 ) { +1390 // Setup network monitoring +1391 let mut current_netmon_state = self.netmon_watcher.get(); +1392 +1393 #[cfg(not(wasm_browser))] +1394 let mut portmap_watcher = self +1395 .direct_addr_update_state +1396 .port_mapper +1397 .watch_external_address(); +1398 +1399 let mut receiver_closed = false; +1400 #[cfg_attr(wasm_browser, allow(unused_mut))] +1401 let mut portmap_watcher_closed = false; +1402 +1403 let mut net_report_watcher = self.msock.net_report.watch(); +1404 +1405 // ensure we are doing an initial publish of our addresses +1406 self.msock.publish_my_addr(); +1407 +1408 loop { +1409 self.msock.metrics.magicsock.actor_tick_main.inc(); +1410 #[cfg(not(wasm_browser))] +1411 let portmap_watcher_changed = portmap_watcher.changed(); +1412 #[cfg(wasm_browser)] +1413 let portmap_watcher_changed = n0_future::future::pending(); +1414 +1415 tokio::select! { +1416 _ = shutdown_token.cancelled() => { +1417 debug!("shutting down"); +1418 return; +1419 } +1420 msg = self.msg_receiver.recv(), if !receiver_closed => { +1421 let Some(msg) = msg else { +1422 trace!("tick: magicsock receiver closed"); +1423 self.msock.metrics.magicsock.actor_tick_other.inc(); +1424 +1425 receiver_closed = true; +1426 continue; +1427 }; +1428 +1429 trace!(?msg, "tick: msg"); +1430 self.msock.metrics.magicsock.actor_tick_msg.inc(); +1431 self.handle_actor_message(msg).await; +1432 } +1433 tick = self.periodic_re_stun_timer.tick() => { +1434 trace!("tick: re_stun {:?}", tick); +1435 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); +1436 self.re_stun(UpdateReason::Periodic); +1437 } +1438 new_addr = watcher.updated() => { +1439 match new_addr { +1440 Ok(addrs) => { +1441 if !addrs.is_empty() { +1442 trace!(?addrs, "local addrs"); +1443 self.msock.publish_my_addr(); +1444 } +1445 } +1446 Err(_) => { +1447 warn!("local addr watcher stopped"); +1448 } +1449 } +1450 } +1451 report = net_report_watcher.updated() => { +1452 match report { +1453 Ok((report, _)) => { +1454 self.handle_net_report_report(report); +1455 #[cfg(not(wasm_browser))] +1456 { +1457 self.periodic_re_stun_timer = new_re_stun_timer(true); +1458 } +1459 } +1460 Err(_) => { +1461 warn!("net report watcher stopped"); +1462 } +1463 } +1464 } +1465 reason = self.direct_addr_done_rx.recv() => { +1466 match reason { +1467 Some(()) => { +1468 // check if a new run needs to be scheduled +1469 let state = self.netmon_watcher.get(); +1470 self.direct_addr_update_state.try_run(state.into()); +1471 } +1472 None => { +1473 warn!("direct addr watcher died"); +1474 } +1475 } +1476 } +1477 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1478 #[cfg(not(wasm_browser))] +1479 { +1480 if change.is_err() { +1481 trace!("tick: portmap watcher closed"); +1482 self.msock.metrics.magicsock.actor_tick_other.inc(); +1483 +1484 portmap_watcher_closed = true; +1485 continue; +1486 } +1487 +1488 trace!("tick: portmap changed"); +1489 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); +1490 let new_external_address = *portmap_watcher.borrow(); +1491 debug!("external address updated: {new_external_address:?}"); +1492 self.re_stun(UpdateReason::PortmapUpdated); +1493 } +1494 #[cfg(wasm_browser)] +1495 let _unused_in_browsers = change; +1496 }, +1497 state = self.netmon_watcher.updated() => { +1498 let Ok(state) = state else { +1499 trace!("tick: link change receiver closed"); +1500 self.msock.metrics.magicsock.actor_tick_other.inc(); +1501 continue; +1502 }; +1503 let is_major = state.is_major_change(&current_netmon_state); +1504 event!( +1505 target: "iroh::_events::link_change", +1506 Level::DEBUG, +1507 ?state, +1508 is_major +1509 ); +1510 current_netmon_state = state; +1511 self.msock.metrics.magicsock.actor_link_change.inc(); +1512 self.handle_network_change(is_major).await; +1513 } +1514 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { +1515 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { +1516 warn!(%dst, endpoint = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); +1517 } +1518 } +1519 } +1520 } +1521 } +1522 +1523 async fn handle_network_change(&mut self, is_major: bool) { +1524 debug!(is_major, "link change detected"); +1525 +1526 if is_major { +1527 if let Err(err) = self.network_change_sender.rebind() { +1528 warn!("failed to rebind transports: {err:?}"); +1529 } +1530 +1531 #[cfg(not(wasm_browser))] +1532 self.msock.dns_resolver.reset().await; +1533 self.re_stun(UpdateReason::LinkChangeMajor); +1534 } else { +1535 self.re_stun(UpdateReason::LinkChangeMinor); +1536 } +1537 } +1538 +1539 fn handle_relay_map_change(&mut self) { +1540 self.re_stun(UpdateReason::RelayMapChange); +1541 } +1542 +1543 fn re_stun(&mut self, why: UpdateReason) { +1544 let state = self.netmon_watcher.get(); +1545 self.direct_addr_update_state +1546 .schedule_run(why, state.into()); +1547 } +1548 +1549 /// Processes an incoming actor message. +1550 /// +1551 /// Returns `true` if it was a shutdown. +1552 async fn handle_actor_message(&mut self, msg: ActorMessage) { +1553 match msg { +1554 ActorMessage::NetworkChange => { +1555 self.network_monitor.network_change().await.ok(); +1556 } +1557 ActorMessage::RelayMapChange => { +1558 self.handle_relay_map_change(); +1559 } +1560 #[cfg(test)] +1561 ActorMessage::ForceNetworkChange(is_major) => { +1562 self.handle_network_change(is_major).await; +1563 } +1564 } +1565 } +1566 +1567 /// Updates the direct addresses of this magic socket. +1568 /// +1569 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of +1570 /// direct addresses from: +1571 /// +1572 /// - The portmapper. +1573 /// - A net_report report. +1574 /// - The local interfaces IP addresses. +1575 #[cfg(not(wasm_browser))] +1576 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +1577 let portmap_watcher = self +1578 .direct_addr_update_state +1579 .port_mapper +1580 .watch_external_address(); +1581 +1582 // We only want to have one DirectAddr for each SocketAddr we have. So we store +1583 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +1584 // DirectAddr from each entry. +1585 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +1586 +1587 // First add PortMapper provided addresses. +1588 let maybe_port_mapped = *portmap_watcher.borrow(); +1589 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +1590 addrs +1591 .entry(portmap_ext) +1592 .or_insert(DirectAddrType::Portmapped); +1593 } +1594 +1595 // Next add STUN addresses from the net_report report. +1596 if let Some(net_report_report) = net_report_report { +1597 if let Some(global_v4) = net_report_report.global_v4 { +1598 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); +1599 +1600 // If they're behind a hard NAT and are using a fixed +1601 // port locally, assume they might've added a static +1602 // port mapping on their router to the same explicit +1603 // port that we are running with. Worst case it's an invalid candidate mapping. +1604 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { +1605 if addr.port() != 0 { +1606 Some(addr.port()) +1607 } else { +1608 None +1609 } +1610 }); +1611 +1612 if let Some(port) = port { +1613 if net_report_report +1614 .mapping_varies_by_dest() +1615 .unwrap_or_default() +1616 { +1617 let mut addr = global_v4; +1618 addr.set_port(port); +1619 addrs +1620 .entry(addr.into()) +1621 .or_insert(DirectAddrType::Qad4LocalPort); +1622 } +1623 } +1624 } +1625 if let Some(global_v6) = net_report_report.global_v6 { +1626 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); +1627 } +1628 } +1629 +1630 self.collect_local_addresses(&mut addrs); +1631 +1632 // Finally create and store store all these direct addresses and send any +1633 // queued call-me-maybe messages. +1634 self.msock.store_direct_addresses( +1635 addrs +1636 .iter() +1637 .map(|(addr, typ)| DirectAddr { +1638 addr: *addr, +1639 typ: *typ, +1640 }) +1641 .collect(), +1642 ); +1643 self.send_queued_call_me_maybes(); +1644 } +1645 +1646 #[cfg(not(wasm_browser))] +1647 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { +1648 // Matches the addresses that have been bound vs the requested ones. +1649 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +1650 .msock +1651 .ip_bind_addrs() +1652 .iter() +1653 .copied() +1654 .zip(self.msock.ip_local_addrs()) +1655 .collect(); +1656 +1657 // Do we listen on any IPv4 unspecified address? +1658 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +1659 if a.is_ipv4() && a.ip().is_unspecified() { +1660 Some(a.port()) +1661 } else { +1662 None +1663 } +1664 }); +1665 // Do we listen on any IPv6 unspecified address? +1666 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +1667 if a.is_ipv6() && a.ip().is_unspecified() { +1668 Some(a.port()) +1669 } else { +1670 None +1671 } +1672 }); +1673 +1674 // If a socket is bound to the unspecified address, create SocketAddrs for +1675 // each local IP address by pairing it with the port the socket is bound on. +1676 if local_addrs +1677 .iter() +1678 .any(|(_, local)| local.ip().is_unspecified()) +1679 { +1680 let LocalAddresses { +1681 regular: mut ips, +1682 loopback, +1683 } = self.netmon_watcher.get().local_addresses; +1684 if ips.is_empty() && addrs.is_empty() { +1685 // Include loopback addresses only if there are no other interfaces +1686 // or public addresses, this allows testing offline. +1687 ips = loopback; +1688 } +1689 +1690 for ip in ips { +1691 let port_if_unspecified = match ip { +1692 IpAddr::V4(_) => has_ipv4_unspecified, +1693 IpAddr::V6(_) => has_ipv6_unspecified, +1694 }; +1695 if let Some(port) = port_if_unspecified { +1696 let addr = SocketAddr::new(ip, port); +1697 addrs.entry(addr).or_insert(DirectAddrType::Local); +1698 } +1699 } +1700 } +1701 +1702 // If a socket is bound to a specific address, add it. +1703 for (bound, local) in local_addrs { +1704 if !bound.ip().is_unspecified() { +1705 addrs.entry(local).or_insert(DirectAddrType::Local); +1706 } +1707 } +1708 } +1709 +1710 fn send_queued_call_me_maybes(&mut self) { +1711 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); +1712 let msg = disco::Message::CallMeMaybe(msg); +1713 // allocate, to minimize locking duration +1714 +1715 for (public_key, url) in self.pending_call_me_maybes.drain() { +1716 if !self +1717 .msock +1718 .disco +1719 .try_send(SendAddr::Relay(url), public_key, msg.clone()) +1720 { +1721 warn!(endpoint = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); +1722 } +1723 } +1724 } +1725 +1726 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +1727 if let Some(ref mut r) = report { +1728 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +1729 if r.preferred_relay.is_none() { +1730 if let Some(my_relay) = self.msock.my_relay() { +1731 r.preferred_relay.replace(my_relay); +1732 } +1733 } +1734 +1735 // Notify all transports +1736 self.network_change_sender.on_network_change(r); +1737 } +1738 +1739 #[cfg(not(wasm_browser))] +1740 self.update_direct_addresses(report.as_ref()); +1741 } +1742} +1743 +1744fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +1745 // Pick a random duration between 20 and 26 seconds (just under 30s, +1746 // a common UDP NAT timeout on Linux,etc) +1747 let mut rng = rand::rng(); +1748 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); +1749 if initial_delay { +1750 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +1751 time::interval_at(time::Instant::now() + d, d) +1752 } else { +1753 debug!( +1754 "scheduling periodic_stun to run immediately and in {}s", +1755 d.as_secs() +1756 ); +1757 time::interval(d) +1758 } +1759} +1760 +1761#[cfg(not(wasm_browser))] +1762fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { +1763 debug!(%addr, "binding"); +1764 +1765 // First try binding a preferred port, if specified +1766 match UdpSocket::bind_full(addr) { +1767 Ok(socket) => { +1768 let local_addr = socket.local_addr()?; +1769 debug!(%addr, %local_addr, "successfully bound"); +1770 return Ok(socket); +1771 } +1772 Err(err) => { +1773 debug!(%addr, "failed to bind: {err:#}"); +1774 // If that was already the fallback port, then error out +1775 if addr.port() == 0 { +1776 return Err(err); +1777 } +1778 } +1779 } +1780 +1781 // Otherwise, try binding with port 0 +1782 addr.set_port(0); +1783 UdpSocket::bind_full(addr) +1784} +1785 +1786/// The discovered direct addresses of this [`MagicSock`]. +1787/// +1788/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. +1789/// They include all locally bound ones as well as those discovered by other mechanisms like +1790/// QAD. +1791#[derive(derive_more::Debug, Clone, Default)] +1792struct DiscoveredDirectAddrs { +1793 /// The last set of discovered direct addresses. +1794 addrs: Watchable<BTreeSet<DirectAddr>>, +1795 +1796 /// The last time the direct addresses were updated, even if there was no change. +1797 /// +1798 /// This is only ever None at startup. +1799 updated_at: Arc<RwLock<Option<Instant>>>, +1800} +1801 +1802impl DiscoveredDirectAddrs { +1803 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +1804 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +1805 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +1806 let updated = self.addrs.set(addrs).is_ok(); +1807 if updated { +1808 event!( +1809 target: "iroh::_events::direct_addrs", +1810 Level::DEBUG, +1811 addrs = ?self.addrs.get(), +1812 ); +1813 } +1814 updated +1815 } +1816 +1817 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { +1818 self.addrs.get().into_iter().map(|da| da.addr) +1819 } +1820 +1821 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { +1822 let my_numbers = self.addrs.get().into_iter().map(|da| da.addr).collect(); +1823 disco::CallMeMaybe { my_numbers } +1824 } +1825} +1826 +1827fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { +1828 match msg { +1829 disco::Message::Ping(_) => { +1830 metrics.sent_disco_ping.inc(); +1831 } +1832 disco::Message::Pong(_) => { +1833 metrics.sent_disco_pong.inc(); +1834 } +1835 disco::Message::CallMeMaybe(_) => { +1836 metrics.sent_disco_call_me_maybe.inc(); +1837 } +1838 } +1839} +1840 +1841/// A *direct address* on which an iroh-endpoint might be contactable. +1842/// +1843/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be +1844/// contacted. These can come from various sources depending on the network topology of the +1845/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. +1846/// +1847/// This is essentially a combination of our local addresses combined with any reflexive +1848/// transport addresses we discovered using QAD. +1849#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +1850pub struct DirectAddr { +1851 /// The address. +1852 pub addr: SocketAddr, +1853 /// The origin of this direct address. +1854 pub typ: DirectAddrType, +1855} +1856 +1857/// The type of direct address. +1858/// +1859/// These are the various sources or origins from which an iroh endpoint might have found a +1860/// possible [`DirectAddr`]. +1861#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +1862pub enum DirectAddrType { +1863 /// Not yet determined.. +1864 Unknown, +1865 /// A locally bound socket address. +1866 Local, +1867 /// Public internet address discovered via QAD. +1868 /// +1869 /// When possible an iroh endpoint will perform QAD to discover which is the address +1870 /// from which it sends data on the public internet. This can be different from locally +1871 /// bound addresses when the endpoint is on a local network which performs NAT or similar. +1872 Qad, +1873 /// An address assigned by the router using port mapping. +1874 /// +1875 /// When possible an iroh endpoint will request a port mapping from the local router to +1876 /// get a publicly routable direct address. +1877 Portmapped, +1878 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +1879 /// +1880 /// It is possible to configure iroh to bound to a specific port and independently +1881 /// configure the router to forward this port to the iroh endpoint. This indicates a +1882 /// situation like this, which still uses QAD to discover the public address. +1883 Qad4LocalPort, +1884} +1885 +1886impl Display for DirectAddrType { +1887 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +1888 match self { +1889 DirectAddrType::Unknown => write!(f, "?"), +1890 DirectAddrType::Local => write!(f, "local"), +1891 DirectAddrType::Qad => write!(f, "qad"), +1892 DirectAddrType::Portmapped => write!(f, "portmap"), +1893 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +1894 } +1895 } +1896} +1897 +1898#[cfg(test)] +1899mod tests { +1900 use std::{sync::Arc, time::Duration}; +1901 +1902 use data_encoding::HEXLOWER; +1903 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; +1904 use n0_error::{Result, StackResultExt, StdResultExt}; +1905 use n0_future::{MergeBounded, StreamExt, time}; +1906 use n0_watcher::Watcher; +1907 use quinn::ServerConfig; +1908 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; +1909 use tokio_util::task::AbortOnDropHandle; +1910 use tracing::{Instrument, error, info, info_span, instrument}; +1911 use tracing_test::traced_test; +1912 +1913 use super::{EndpointIdMappedAddr, Options, endpoint_map::Source, mapped_addrs::MappedAddr}; +1914 use crate::{ +1915 Endpoint, +1916 RelayMap, +1917 RelayMode, +1918 SecretKey, +1919 discovery::static_provider::StaticProvider, +1920 dns::DnsResolver, +1921 // endpoint::PathSelection, +1922 magicsock::{Handle, MagicSock}, +1923 tls::{self, DEFAULT_MAX_TLS_TICKETS}, +1924 }; +1925 +1926 const ALPN: &[u8] = b"n0/test/1"; +1927 +1928 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { +1929 let secret_key = SecretKey::generate(rng); +1930 let server_config = make_default_server_config(&secret_key); +1931 Options { +1932 addr_v4: None, +1933 addr_v6: None, +1934 secret_key, +1935 relay_map: RelayMap::empty(), +1936 proxy_url: None, +1937 dns_resolver: DnsResolver::new(), +1938 server_config, +1939 #[cfg(any(test, feature = "test-utils"))] +1940 insecure_skip_relay_cert_verify: false, +1941 #[cfg(any(test, feature = "test-utils"))] +1942 // path_selection: PathSelection::default(), +1943 discovery_user_data: None, +1944 metrics: Default::default(), +1945 } +1946 } +1947 +1948 /// Generate a server config with no ALPNS and a default transport configuration +1949 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { +1950 let quic_server_config = +1951 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +1952 .make_server_config(vec![], false); +1953 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +1954 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +1955 server_config +1956 } +1957 +1958 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1959 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { +1960 info!("accepting conn"); +1961 let conn = ep.accept().await.expect("no conn"); +1962 +1963 info!("accepting"); +1964 let conn = conn.await.context("accepting")?; +1965 info!("accepting bi"); +1966 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; +1967 +1968 info!("reading"); +1969 let val = recv_bi +1970 .read_to_end(usize::MAX) +1971 .await +1972 .std_context("read to end")?; +1973 +1974 info!("replying"); +1975 for chunk in val.chunks(12) { +1976 send_bi.write_all(chunk).await.std_context("write all")?; +1977 } +1978 +1979 info!("finishing"); +1980 send_bi.finish().std_context("finish")?; +1981 send_bi.stopped().await.std_context("stopped")?; +1982 +1983 let stats = conn.stats(); +1984 info!("stats: {:#?}", stats); +1985 // TODO: ensure panics in this function are reported ok +1986 if matches!(loss, ExpectedLoss::AlmostNone) { +1987 for info in conn.paths().get().iter() { +1988 assert!( +1989 info.stats().lost_packets < 10, +1990 "[receiver] path {:?} should not loose many packets", +1991 info.remote_addr() +1992 ); +1993 } +1994 } +1995 +1996 info!("close"); +1997 conn.close(0u32.into(), b"done"); +1998 info!("wait idle"); +1999 ep.endpoint().wait_idle().await; +2000 +2001 Ok(()) +2002 } +2003 +2004 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +2005 async fn echo_sender( +2006 ep: Endpoint, +2007 dest_id: EndpointId, +2008 msg: &[u8], +2009 loss: ExpectedLoss, +2010 ) -> Result { +2011 info!("connecting to {}", dest_id.fmt_short()); +2012 let dest = EndpointAddr::new(dest_id); +2013 let conn = ep.connect(dest, ALPN).await?; +2014 +2015 info!("opening bi"); +2016 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; +2017 +2018 info!("writing message"); +2019 send_bi.write_all(msg).await.std_context("write all")?; +2020 +2021 info!("finishing"); +2022 send_bi.finish().std_context("finish")?; +2023 send_bi.stopped().await.std_context("stopped")?; +2024 +2025 info!("reading_to_end"); +2026 let val = recv_bi +2027 .read_to_end(usize::MAX) +2028 .await +2029 .std_context("read to end")?; +2030 assert_eq!( +2031 val, +2032 msg, +2033 "[sender] expected {}, got {}", +2034 HEXLOWER.encode(msg), +2035 HEXLOWER.encode(&val) +2036 ); +2037 +2038 let stats = conn.stats(); +2039 info!("stats: {:#?}", stats); +2040 if matches!(loss, ExpectedLoss::AlmostNone) { +2041 for info in conn.paths().get() { +2042 assert!( +2043 info.stats().lost_packets < 10, +2044 "[sender] path {:?} should not loose many packets", +2045 info.remote_addr() +2046 ); +2047 } +2048 } +2049 +2050 info!("close"); +2051 conn.close(0u32.into(), b"done"); +2052 info!("wait idle"); +2053 ep.endpoint().wait_idle().await; +2054 Ok(()) +2055 } +2056 +2057 #[derive(Debug, Copy, Clone)] +2058 enum ExpectedLoss { +2059 AlmostNone, +2060 YeahSure, +2061 } +2062 +2063 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +2064 async fn run_roundtrip( +2065 sender: Endpoint, +2066 receiver: Endpoint, +2067 payload: &[u8], +2068 loss: ExpectedLoss, +2069 ) { +2070 let send_endpoint_id = sender.id(); +2071 let recv_endpoint_id = receiver.id(); +2072 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); +2073 +2074 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); +2075 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; +2076 let sender_is_err = match sender_res { +2077 Ok(()) => false, +2078 Err(err) => { +2079 eprintln!("[sender] Error:\n{err:#?}"); +2080 true +2081 } +2082 }; +2083 let receiver_is_err = match receiver_task.await { +2084 Ok(Ok(())) => false, +2085 Ok(Err(err)) => { +2086 eprintln!("[receiver] Error:\n{err:#?}"); +2087 true +2088 } +2089 Err(joinerr) => { +2090 if joinerr.is_panic() { +2091 std::panic::resume_unwind(joinerr.into_panic()); +2092 } else { +2093 eprintln!("[receiver] Error:\n{joinerr:#?}"); +2094 } +2095 true +2096 } +2097 }; +2098 if sender_is_err || receiver_is_err { +2099 panic!("Sender or receiver errored"); +2100 } +2101 } +2102 +2103 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. +2104 /// +2105 /// The endpoints do not use a relay server but can connect to each other via local +2106 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if +2107 /// the endpoints rebind. +2108 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { +2109 let discovery = StaticProvider::new(); +2110 let ep1 = Endpoint::builder() +2111 .relay_mode(RelayMode::Disabled) +2112 .alpns(vec![ALPN.to_vec()]) +2113 .discovery(discovery.clone()) +2114 .bind() +2115 .await +2116 .unwrap(); +2117 let ep2 = Endpoint::builder() +2118 .relay_mode(RelayMode::Disabled) +2119 .alpns(vec![ALPN.to_vec()]) +2120 .discovery(discovery.clone()) +2121 .bind() +2122 .await +2123 .unwrap(); +2124 discovery.add_endpoint_info(ep1.addr()); +2125 discovery.add_endpoint_info(ep2.addr()); +2126 +2127 let ep1_addr_stream = ep1.watch_addr().stream(); +2128 let ep2_addr_stream = ep2.watch_addr().stream(); +2129 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); +2130 let task = tokio::spawn(async move { +2131 loop { +2132 while let Some(addr) = addr_stream.next().await { +2133 discovery.add_endpoint_info(addr); +2134 } +2135 } +2136 }); +2137 +2138 (AbortOnDropHandle::new(task), ep1, ep2) +2139 } +2140 +2141 #[tokio::test(flavor = "multi_thread")] +2142 #[traced_test] +2143 async fn test_two_devices_roundtrip_quinn_magic() -> Result { +2144 let (_guard, m1, m2) = endpoint_pair().await; +2145 +2146 for i in 0..5 { +2147 info!("\n-- round {i}"); +2148 run_roundtrip( +2149 m1.clone(), +2150 m2.clone(), +2151 b"hello m1", +2152 ExpectedLoss::AlmostNone, +2153 ) +2154 .await; +2155 run_roundtrip( +2156 m2.clone(), +2157 m1.clone(), +2158 b"hello m2", +2159 ExpectedLoss::AlmostNone, +2160 ) +2161 .await; +2162 +2163 info!("\n-- larger data"); +2164 let mut data = vec![0u8; 10 * 1024]; +2165 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2166 rng.fill_bytes(&mut data); +2167 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; +2168 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; +2169 } +2170 +2171 Ok(()) +2172 } +2173 +2174 #[tokio::test] +2175 #[traced_test] +2176 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { +2177 let (_guard, m1, m2) = endpoint_pair().await; +2178 +2179 println!("Net change"); +2180 m1.magic_sock().force_network_change(true).await; +2181 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +2182 +2183 let _handle = AbortOnDropHandle::new(tokio::spawn({ +2184 let endpoint = m2.clone(); +2185 async move { +2186 while let Some(incoming) = endpoint.accept().await { +2187 println!("Incoming first conn!"); +2188 let conn = incoming.await.anyerr()?; +2189 conn.closed().await; +2190 } +2191 +2192 n0_error::Ok(()) +2193 } +2194 })); +2195 +2196 println!("first conn!"); +2197 let conn = m1.connect(m2.addr(), ALPN).await?; +2198 println!("Closing first conn"); +2199 conn.close(0u32.into(), b"bye lolz"); +2200 conn.closed().await; +2201 println!("Closed first conn"); +2202 +2203 Ok(()) +2204 } +2205 +2206 #[tokio::test(flavor = "multi_thread")] +2207 #[traced_test] +2208 async fn test_two_devices_roundtrip_network_change() -> Result { +2209 time::timeout( +2210 Duration::from_secs(90), +2211 test_two_devices_roundtrip_network_change_impl(), +2212 ) +2213 .await +2214 .std_context("timeout")? +2215 } +2216 +2217 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly +2218 /// with (simulated) network changes. +2219 async fn test_two_devices_roundtrip_network_change_impl() -> Result { +2220 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2221 let (_guard, m1, m2) = endpoint_pair().await; +2222 +2223 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { +2224 let delay = rng.random_range(10..=500); +2225 Duration::from_millis(delay) +2226 }; +2227 let rounds = 5; +2228 +2229 // Regular network changes to m1 only. +2230 let m1_network_change_guard = { +2231 let m1 = m1.clone(); +2232 let mut rng = rng.clone(); +2233 let task = tokio::spawn(async move { +2234 loop { +2235 println!("[m1] network change"); +2236 m1.magic_sock().force_network_change(true).await; +2237 time::sleep(offset(&mut rng)).await; +2238 } +2239 }); +2240 AbortOnDropHandle::new(task) +2241 }; +2242 +2243 for i in 0..rounds { +2244 println!("-- [m1 changes] round {}", i + 1); +2245 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2246 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2247 +2248 println!("-- [m1 changes] larger data"); +2249 let mut data = vec![0u8; 10 * 1024]; +2250 rng.fill_bytes(&mut data); +2251 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2252 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2253 } +2254 +2255 std::mem::drop(m1_network_change_guard); +2256 +2257 // Regular network changes to m2 only. +2258 let m2_network_change_guard = { +2259 let m2 = m2.clone(); +2260 let mut rng = rng.clone(); +2261 let task = tokio::spawn(async move { +2262 loop { +2263 println!("[m2] network change"); +2264 m2.magic_sock().force_network_change(true).await; +2265 time::sleep(offset(&mut rng)).await; +2266 } +2267 }); +2268 AbortOnDropHandle::new(task) +2269 }; +2270 +2271 for i in 0..rounds { +2272 println!("-- [m2 changes] round {}", i + 1); +2273 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2274 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2275 +2276 println!("-- [m2 changes] larger data"); +2277 let mut data = vec![0u8; 10 * 1024]; +2278 rng.fill_bytes(&mut data); +2279 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2280 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2281 } +2282 +2283 std::mem::drop(m2_network_change_guard); +2284 +2285 // Regular network changes to both m1 and m2 only. +2286 let m1_m2_network_change_guard = { +2287 let m1 = m1.clone(); +2288 let m2 = m2.clone(); +2289 let mut rng = rng.clone(); +2290 let task = tokio::spawn(async move { +2291 println!("-- [m1] network change"); +2292 m1.magic_sock().force_network_change(true).await; +2293 println!("-- [m2] network change"); +2294 m2.magic_sock().force_network_change(true).await; +2295 time::sleep(offset(&mut rng)).await; +2296 }); +2297 AbortOnDropHandle::new(task) +2298 }; +2299 +2300 for i in 0..rounds { +2301 println!("-- [m1 & m2 changes] round {}", i + 1); +2302 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2303 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2304 +2305 println!("-- [m1 & m2 changes] larger data"); +2306 let mut data = vec![0u8; 10 * 1024]; +2307 rng.fill_bytes(&mut data); +2308 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2309 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2310 } +2311 +2312 std::mem::drop(m1_m2_network_change_guard); +2313 Ok(()) +2314 } +2315 +2316 #[tokio::test(flavor = "multi_thread")] +2317 #[traced_test] +2318 async fn test_two_devices_setup_teardown() -> Result { +2319 for i in 0..10 { +2320 println!("-- round {i}"); +2321 println!("setting up magic stack"); +2322 let (_guard, m1, m2) = endpoint_pair().await; +2323 +2324 println!("closing endpoints"); +2325 let msock1 = m1.magic_sock(); +2326 let msock2 = m2.magic_sock(); +2327 m1.close().await; +2328 m2.close().await; +2329 +2330 assert!(msock1.msock.is_closed()); +2331 assert!(msock2.msock.is_closed()); +2332 } +2333 Ok(()) +2334 } +2335 +2336 #[tokio::test] +2337 #[traced_test] +2338 async fn test_direct_addresses() { +2339 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2340 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); +2341 +2342 // See if we can get endpoints. +2343 let eps0 = ms.ip_addrs().get(); +2344 println!("{eps0:?}"); +2345 assert!(!eps0.is_empty()); +2346 +2347 // Getting the endpoints again immediately should give the same results. +2348 let eps1 = ms.ip_addrs().get(); +2349 println!("{eps1:?}"); +2350 assert_eq!(eps0, eps1); +2351 } +2352 +2353 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. +2354 /// +2355 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +2356 /// connections using [`ALPN`]. +2357 /// +2358 /// Use [`magicsock_connect`] to establish connections. +2359 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] +2360 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { +2361 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2362 .make_server_config(vec![ALPN.to_vec()], true); +2363 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +2364 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +2365 +2366 let dns_resolver = DnsResolver::new(); +2367 let opts = Options { +2368 addr_v4: None, +2369 addr_v6: None, +2370 secret_key: secret_key.clone(), +2371 relay_map: RelayMap::empty(), +2372 discovery_user_data: None, +2373 dns_resolver, +2374 proxy_url: None, +2375 server_config, +2376 insecure_skip_relay_cert_verify: false, +2377 // path_selection: PathSelection::default(), +2378 metrics: Default::default(), +2379 }; +2380 let msock = MagicSock::spawn(opts).await?; +2381 Ok(msock) +2382 } +2383 +2384 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2385 /// +2386 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2387 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2388 async fn magicsock_connect( +2389 ep: &quinn::Endpoint, +2390 ep_secret_key: SecretKey, +2391 addr: EndpointIdMappedAddr, +2392 endpoint_id: EndpointId, +2393 ) -> Result<quinn::Connection> { +2394 // Endpoint::connect sets this, do the same to have similar behaviour. +2395 let mut transport_config = quinn::TransportConfig::default(); +2396 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2397 +2398 magicsock_connect_with_transport_config( +2399 ep, +2400 ep_secret_key, +2401 addr, +2402 endpoint_id, +2403 Arc::new(transport_config), +2404 ) +2405 .await +2406 } +2407 +2408 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2409 /// +2410 /// This version allows customising the transport config. +2411 /// +2412 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2413 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2414 async fn magicsock_connect_with_transport_config( +2415 ep: &quinn::Endpoint, +2416 ep_secret_key: SecretKey, +2417 mapped_addr: EndpointIdMappedAddr, +2418 endpoint_id: EndpointId, +2419 transport_config: Arc<quinn::TransportConfig>, +2420 ) -> Result<quinn::Connection> { +2421 let alpns = vec![ALPN.to_vec()]; +2422 let quic_client_config = +2423 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2424 .make_client_config(alpns, true); +2425 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +2426 client_config.transport_config(transport_config); +2427 let connect = ep +2428 .connect_with( +2429 client_config, +2430 mapped_addr.private_socket_addr(), +2431 &tls::name::encode(endpoint_id), +2432 ) +2433 .std_context("connect")?; +2434 let connection = connect.await.anyerr()?; +2435 Ok(connection) +2436 } +2437 +2438 #[tokio::test] +2439 #[traced_test] +2440 async fn test_try_send_no_send_addr() { +2441 // Regression test: if there is no send_addr we should keep being able to use the +2442 // Endpoint. +2443 +2444 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2445 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2446 let endpoint_id_2 = secret_key_2.public(); +2447 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); +2448 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); +2449 +2450 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2451 +2452 // Generate an address not present in the EndpointMap. +2453 let bad_addr = EndpointIdMappedAddr::generate(); +2454 +2455 // 500ms is rather fast here. Running this locally it should always be the correct +2456 // timeout. If this is too slow however the test will not become flaky as we are +2457 // expecting the timeout, we might just get the timeout for the wrong reason. But +2458 // this speeds up the test. +2459 let res = tokio::time::timeout( +2460 Duration::from_millis(500), +2461 magicsock_connect( +2462 msock_1.endpoint(), +2463 secret_key_1.clone(), +2464 bad_addr, +2465 endpoint_id_missing_endpoint, +2466 ), +2467 ) +2468 .await; +2469 assert!(res.is_err(), "expecting timeout"); +2470 +2471 // Now check we can still create another connection with this endpoint. +2472 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2473 +2474 // This needs an accept task +2475 let accept_task = tokio::spawn({ +2476 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2477 let incoming = ep.accept().await.std_context("no incoming")?; +2478 let _conn = incoming +2479 .accept() +2480 .std_context("accept")? +2481 .await +2482 .std_context("accepting")?; +2483 +2484 // Keep this connection alive for a while +2485 tokio::time::sleep(Duration::from_secs(10)).await; +2486 info!("accept finished"); +2487 Ok(()) +2488 } +2489 let ep = msock_2.endpoint().clone(); +2490 async move { +2491 if let Err(err) = accept(ep).await { +2492 error!("{err:#}"); +2493 } +2494 } +2495 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) +2496 }); +2497 let _accept_task = AbortOnDropHandle::new(accept_task); +2498 +2499 let addrs = msock_2 +2500 .ip_addrs() +2501 .get() +2502 .into_iter() +2503 .map(|x| TransportAddr::Ip(x.addr)) +2504 .collect(); +2505 let endpoint_addr_2 = EndpointAddr { +2506 id: endpoint_id_2, +2507 addrs, +2508 }; +2509 msock_1 +2510 .add_endpoint_addr( +2511 endpoint_addr_2, +2512 Source::NamedApp { +2513 name: "test".into(), +2514 }, +2515 ) +2516 .await +2517 .unwrap(); +2518 let addr = msock_1.get_endpoint_mapped_addr(endpoint_id_2); +2519 let res = tokio::time::timeout( +2520 Duration::from_secs(10), +2521 magicsock_connect( +2522 msock_1.endpoint(), +2523 secret_key_1.clone(), +2524 addr, +2525 endpoint_id_2, +2526 ), +2527 ) +2528 .await +2529 .expect("timeout while connecting"); +2530 +2531 // aka assert!(res.is_ok()) but with nicer error reporting. +2532 res.unwrap(); +2533 +2534 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +2535 // much internal state for now. +2536 } +2537 +2538 #[tokio::test] +2539 #[traced_test] +2540 async fn test_try_send_no_udp_addr_or_relay_url() { +2541 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +2542 // behaviour of MagicSock::try_send. +2543 +2544 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2545 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2546 let endpoint_id_2 = secret_key_2.public(); +2547 +2548 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2549 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2550 let ep_2 = msock_2.endpoint().clone(); +2551 +2552 // We need a task to accept the connection. +2553 let accept_task = tokio::spawn({ +2554 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2555 let incoming = ep.accept().await.std_context("no incoming")?; +2556 let conn = incoming +2557 .accept() +2558 .std_context("accept")? +2559 .await +2560 .std_context("connecting")?; +2561 let mut stream = conn.accept_uni().await.std_context("accept uni")?; +2562 stream +2563 .read_to_end(1 << 16) +2564 .await +2565 .std_context("read to end")?; +2566 info!("accept finished"); +2567 Ok(()) +2568 } +2569 async move { +2570 if let Err(err) = accept(ep_2).await { +2571 error!("{err:#}"); +2572 } +2573 } +2574 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) +2575 }); +2576 let _accept_task = AbortOnDropHandle::new(accept_task); +2577 +2578 // Add an empty entry in the EndpointMap of ep_1 +2579 msock_1 +2580 .endpoint_map +2581 .add_endpoint_addr( +2582 EndpointAddr { +2583 id: endpoint_id_2, +2584 addrs: Default::default(), +2585 }, +2586 Source::NamedApp { +2587 name: "test".into(), +2588 }, +2589 ) +2590 .await; +2591 let addr_2 = msock_1.get_endpoint_mapped_addr(endpoint_id_2); +2592 +2593 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +2594 // not take forever. You need to check the log output to verify this is really +2595 // triggering the correct error. +2596 // In test_try_send_no_send_addr() above you may have noticed we used +2597 // tokio::time::timeout() on the connection attempt instead. Here however we want +2598 // Quinn itself to have fully given up on the connection attempt because we will +2599 // later connect to **the same** endpoint. If Quinn did not give up on the connection +2600 // we'd close it on drop, and the retransmits of the close packets would interfere +2601 // with the next handshake, closing it during the handshake. This makes the test a +2602 // little slower though. +2603 let mut transport_config = quinn::TransportConfig::default(); +2604 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +2605 let res = magicsock_connect_with_transport_config( +2606 msock_1.endpoint(), +2607 secret_key_1.clone(), +2608 addr_2, +2609 endpoint_id_2, +2610 Arc::new(transport_config), +2611 ) +2612 .await; +2613 assert!(res.is_err(), "expected timeout"); +2614 info!("first connect timed out as expected"); +2615 +2616 // Provide correct addressing information +2617 msock_1 +2618 .endpoint_map +2619 .add_endpoint_addr( +2620 EndpointAddr { +2621 id: endpoint_id_2, +2622 addrs: msock_2 +2623 .ip_addrs() +2624 .get() +2625 .into_iter() +2626 .map(|x| TransportAddr::Ip(x.addr)) +2627 .collect(), +2628 }, +2629 Source::NamedApp { +2630 name: "test".into(), +2631 }, +2632 ) +2633 .await; +2634 +2635 // We can now connect +2636 tokio::time::timeout(Duration::from_secs(10), async move { +2637 info!("establishing new connection"); +2638 let conn = magicsock_connect( +2639 msock_1.endpoint(), +2640 secret_key_1.clone(), +2641 addr_2, +2642 endpoint_id_2, +2643 ) +2644 .await +2645 .unwrap(); +2646 info!("have connection"); +2647 let mut stream = conn.open_uni().await.unwrap(); +2648 stream.write_all(b"hello").await.unwrap(); +2649 stream.finish().unwrap(); +2650 stream.stopped().await.unwrap(); +2651 info!("finished stream"); +2652 }) +2653 .await +2654 .expect("connection timed out"); +2655 +2656 // TODO: could remove the addresses again, send, add it back and see it recover. +2657 // But we don't have that much private access to the EndpointMap. This will do for now. +2658 } +2659}
    \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/endpoint_map.rs.html b/pr/3381/docs/src/iroh/magicsock/endpoint_map.rs.html index 8dc82a4007..3030d6cb5a 100644 --- a/pr/3381/docs/src/iroh/magicsock/endpoint_map.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/endpoint_map.rs.html @@ -6,503 +6,428 @@ 6}; 7 8use iroh_base::{EndpointAddr, EndpointId, RelayUrl}; -9use n0_future::task::{self, AbortOnDropHandle}; -10use rustc_hash::FxHashMap; -11use serde::{Deserialize, Serialize}; -12use tokio::sync::mpsc; -13use tracing::{Instrument, info_span, trace, warn}; -14 -15use super::{ -16 DirectAddr, DiscoState, MagicsockMetrics, -17 mapped_addrs::{AddrMap, EndpointIdMappedAddr, RelayMappedAddr}, -18 transports::{self, OwnedTransmit, TransportsSender}, -19}; -20use crate::disco::{self}; -21// #[cfg(any(test, feature = "test-utils"))] -22// use crate::endpoint::PathSelection; -23 -24mod endpoint_state; -25mod path_state; -26 -27pub(super) use endpoint_state::EndpointStateMessage; -28pub(crate) use endpoint_state::PathsWatchable; -29pub use endpoint_state::{ConnectionType, PathInfo, PathInfoList}; -30use endpoint_state::{EndpointStateActor, EndpointStateHandle}; -31 -32// TODO: use this -33// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced -34// /// periodically via [`NodeMap::prune_inactive`]. -35// const MAX_INACTIVE_NODES: usize = 30; -36 -37/// Map containing all the state for endpoints. -38/// -39/// - Has actors which each manage all the connection state for a remote endpoint. -40/// -41/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6 -42/// addressing space that is used by Quinn. -43#[derive(Debug)] -44pub(crate) struct EndpointMap { -45 // -46 // State we keep about remote endpoints. -47 // -48 /// The actors tracking each remote endpoint. -49 actor_handles: Mutex<FxHashMap<EndpointId, EndpointStateHandle>>, -50 /// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s. -51 pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>, -52 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. -53 pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -54 -55 // -56 // State needed to start a new EndpointStateHandle. -57 // -58 /// The endpoint ID of the local endpoint. -59 local_endpoint_id: EndpointId, -60 metrics: Arc<MagicsockMetrics>, -61 /// Handle to an actor that can send over the transports. -62 transports_handle: TransportsSenderHandle, -63 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -64 disco: DiscoState, -65} -66 -67impl EndpointMap { -68 /// Creates a new [`EndpointMap`]. -69 pub(super) fn new( -70 local_endpoint_id: EndpointId, -71 // TODO: -72 // #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection, -73 metrics: Arc<MagicsockMetrics>, -74 sender: TransportsSender, -75 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -76 disco: DiscoState, -77 ) -> Self { -78 Self { -79 actor_handles: Mutex::new(FxHashMap::default()), -80 endpoint_mapped_addrs: Default::default(), -81 relay_mapped_addrs: Default::default(), -82 local_endpoint_id, -83 metrics, -84 transports_handle: TransportsSenderActor::new(sender).start(), -85 local_addrs, -86 disco, -87 } -88 } -89 -90 /// Adds addresses where an endpoint might be contactable. -91 pub(super) async fn add_endpoint_addr(&self, endpoint_addr: EndpointAddr, source: Source) { -92 for url in endpoint_addr.relay_urls() { -93 // Ensure we have a RelayMappedAddress. -94 self.relay_mapped_addrs -95 .get(&(url.clone(), endpoint_addr.id)); -96 } -97 let actor = self.endpoint_state_actor(endpoint_addr.id); -98 -99 // This only fails if the sender is closed. That means the EndpointStateActor has -100 // stopped, which only happens during shutdown. -101 actor -102 .send(EndpointStateMessage::AddEndpointAddr(endpoint_addr, source)) -103 .await -104 .ok(); -105 } -106 -107 pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr { -108 self.endpoint_mapped_addrs.get(&eid) -109 } -110 -111 /// Returns a [`n0_watcher::Direct`] for given endpoint's [`ConnectionType`]. -112 /// -113 /// # Errors -114 /// -115 /// Will return `None` if there is not an entry in the [`EndpointMap`] for -116 /// the `endpoint_id` -117 pub(super) fn conn_type( -118 &self, -119 _endpoint_id: EndpointId, -120 ) -> Option<n0_watcher::Direct<ConnectionType>> { -121 todo!(); -122 } -123 -124 /// Returns the sender for the [`EndpointStateActor`]. -125 /// -126 /// If needed a new actor is started on demand. -127 /// -128 /// [`EndpointStateActor`]: endpoint_state::EndpointStateActor -129 pub(super) fn endpoint_state_actor( -130 &self, -131 eid: EndpointId, -132 ) -> mpsc::Sender<EndpointStateMessage> { -133 let mut handles = self.actor_handles.lock().expect("poisoned"); -134 match handles.get(&eid) { -135 Some(handle) => handle.sender.clone(), -136 None => { -137 // Create a new EndpointStateActor and insert it into the endpoint map. -138 let sender = self.transports_handle.inbox.clone(); -139 let local_addrs = self.local_addrs.clone(); -140 let disco = self.disco.clone(); -141 let metrics = self.metrics.clone(); -142 let actor = EndpointStateActor::new( -143 eid, -144 self.local_endpoint_id, -145 sender, -146 local_addrs, -147 disco, -148 self.relay_mapped_addrs.clone(), -149 metrics, -150 ); -151 let handle = actor.start(); -152 let sender = handle.sender.clone(); -153 handles.insert(eid, handle); -154 -155 // Ensure there is a EndpointMappedAddr for this EndpointId. -156 self.endpoint_mapped_addrs.get(&eid); -157 sender -158 } -159 } -160 } -161 -162 pub(super) fn handle_ping(&self, msg: disco::Ping, sender: EndpointId, src: transports::Addr) { -163 if msg.endpoint_key != sender { -164 warn!("DISCO Ping EndpointId mismatch, ignoring ping"); -165 return; -166 } -167 let endpoint_state = self.endpoint_state_actor(sender); -168 if let Err(err) = endpoint_state.try_send(EndpointStateMessage::PingReceived(msg, src)) { -169 // TODO: This is really, really bad and will drop pings under load. But -170 // DISCO pings are going away with QUIC-NAT-TRAVERSAL so I don't care. -171 warn!("DISCO Ping dropped: {err:#}"); -172 } -173 } -174 -175 pub(super) fn handle_pong(&self, msg: disco::Pong, sender: EndpointId, src: transports::Addr) { -176 let actor = self.endpoint_state_actor(sender); -177 if let Err(err) = actor.try_send(EndpointStateMessage::PongReceived(msg, src)) { -178 // TODO: This is really, really bad and will drop pongs under load. But -179 // DISCO pongs are going away with QUIC-NAT-TRAVERSAL so I don't care. -180 warn!("DISCO Pong dropped: {err:#}"); -181 } -182 } -183 -184 pub(super) fn handle_call_me_maybe( -185 &self, -186 msg: disco::CallMeMaybe, -187 sender: EndpointId, -188 src: transports::Addr, -189 ) { -190 if !src.is_relay() { -191 warn!("DISCO CallMeMaybe packets should only come via relay"); -192 return; -193 } -194 let actor = self.endpoint_state_actor(sender); -195 if let Err(err) = actor.try_send(EndpointStateMessage::CallMeMaybeReceived(msg)) { -196 // TODO: This is bad and will drop call-me-maybe's under load. But -197 // DISCO CallMeMaybe going away with QUIC-NAT-TRAVERSAL so I don't care. -198 warn!("DISCO CallMeMaybe dropped: {err:#}"); -199 } -200 } -201} -202 -203/// The origin or *source* through which an address associated with a remote endpoint -204/// was discovered. -205/// -206/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the -207/// [`Source`]s of the endpoint itself. -208/// -209/// A [`Source`] helps track how and where an address was learned. Multiple -210/// sources can be associated with a single address, if we have discovered this -211/// address through multiple means. -212#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] -213#[strum(serialize_all = "kebab-case")] -214pub enum Source { -215 /// Address was loaded from the fs. -216 Saved, -217 /// An endpoint communicated with us first via UDP. -218 Udp, -219 /// An endpoint communicated with us first via relay. -220 Relay, -221 /// Application layer added the address directly. -222 App, -223 /// The address was discovered by a discovery service. -224 #[strum(serialize = "{name}")] -225 Discovery { -226 /// The name of the discovery service that discovered the address. -227 name: String, -228 }, -229 /// Application layer with a specific name added the endpoint directly. -230 #[strum(serialize = "{name}")] -231 NamedApp { -232 /// The name of the application that added the endpoint -233 name: String, -234 }, -235 /// The address was advertised by a call-me-maybe DISCO message. -236 CallMeMaybe, -237 /// We received a ping on the path. -238 Ping, -239 /// We established a connection on this address. -240 /// -241 /// Currently this means the path was in uses as [`PathId::ZERO`] when the a connection -242 /// was added to the `EndpointStateActor`. -243 /// -244 /// [`PathId::ZERO`]: quinn_proto::PathId::ZERO -245 Connection, -246} -247 -248/// An (Ip, Port) pair. -249/// -250/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket -251/// addresses include fields that can't be assumed consistent even within a single connection. -252#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] -253#[display("{}", SocketAddr::from(*self))] -254pub struct IpPort { -255 ip: IpAddr, -256 port: u16, -257} -258 -259impl From<SocketAddr> for IpPort { -260 fn from(socket_addr: SocketAddr) -> Self { -261 Self { -262 ip: socket_addr.ip(), -263 port: socket_addr.port(), -264 } -265 } -266} -267 -268impl From<IpPort> for SocketAddr { -269 fn from(ip_port: IpPort) -> Self { -270 let IpPort { ip, port } = ip_port; -271 (ip, port).into() -272 } -273} -274 -275impl IpPort { -276 pub fn ip(&self) -> &IpAddr { -277 &self.ip -278 } -279 -280 pub fn port(&self) -> u16 { -281 self.port -282 } -283} -284 -285/// An actor that can send datagrams onto iroh transports. -286/// -287/// The [`EndpointStateActor`]s want to be able to send datagrams. Because we can not create -288/// [`TransportsSender`]s on demand we must share one for the entire [`EndpointMap`], which -289/// lives in this actor. -290/// -291/// [`EndpointStateActor`]: endpoint_state::EndpointStateActor -292#[derive(Debug)] -293struct TransportsSenderActor { -294 sender: TransportsSender, -295} -296 -297impl TransportsSenderActor { -298 fn new(sender: TransportsSender) -> Self { -299 Self { sender } -300 } +9use rustc_hash::FxHashMap; +10use serde::{Deserialize, Serialize}; +11use tokio::sync::mpsc; +12use tracing::warn; +13 +14use super::{ +15 DirectAddr, DiscoState, MagicsockMetrics, +16 mapped_addrs::{AddrMap, EndpointIdMappedAddr, RelayMappedAddr}, +17 transports::{self, TransportsSender}, +18}; +19use crate::disco::{self}; +20// #[cfg(any(test, feature = "test-utils"))] +21// use crate::endpoint::PathSelection; +22 +23mod endpoint_state; +24mod path_state; +25 +26pub(super) use endpoint_state::EndpointStateMessage; +27pub(crate) use endpoint_state::PathsWatchable; +28pub use endpoint_state::{ConnectionType, PathInfo, PathInfoList}; +29use endpoint_state::{EndpointStateActor, EndpointStateHandle}; +30 +31// TODO: use this +32// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced +33// /// periodically via [`NodeMap::prune_inactive`]. +34// const MAX_INACTIVE_NODES: usize = 30; +35 +36/// Map containing all the state for endpoints. +37/// +38/// - Has actors which each manage all the connection state for a remote endpoint. +39/// +40/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6 +41/// addressing space that is used by Quinn. +42#[derive(Debug)] +43pub(crate) struct EndpointMap { +44 // +45 // State we keep about remote endpoints. +46 // +47 /// The actors tracking each remote endpoint. +48 actor_handles: Mutex<FxHashMap<EndpointId, EndpointStateHandle>>, +49 /// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s. +50 pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>, +51 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. +52 pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +53 +54 // +55 // State needed to start a new EndpointStateHandle. +56 // +57 /// The endpoint ID of the local endpoint. +58 local_endpoint_id: EndpointId, +59 metrics: Arc<MagicsockMetrics>, +60 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +61 disco: DiscoState, +62 sender: TransportsSender, +63} +64 +65impl EndpointMap { +66 /// Creates a new [`EndpointMap`]. +67 pub(super) fn new( +68 local_endpoint_id: EndpointId, +69 // TODO: +70 // #[cfg(any(test, feature = "test-utils"))] path_selection: PathSelection, +71 metrics: Arc<MagicsockMetrics>, +72 +73 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +74 disco: DiscoState, +75 sender: TransportsSender, +76 ) -> Self { +77 Self { +78 actor_handles: Mutex::new(FxHashMap::default()), +79 endpoint_mapped_addrs: Default::default(), +80 relay_mapped_addrs: Default::default(), +81 local_endpoint_id, +82 metrics, +83 local_addrs, +84 disco, +85 sender, +86 } +87 } +88 +89 /// Adds addresses where an endpoint might be contactable. +90 pub(super) async fn add_endpoint_addr(&self, endpoint_addr: EndpointAddr, source: Source) { +91 for url in endpoint_addr.relay_urls() { +92 // Ensure we have a RelayMappedAddress. +93 self.relay_mapped_addrs +94 .get(&(url.clone(), endpoint_addr.id)); +95 } +96 let actor = self.endpoint_state_actor(endpoint_addr.id); +97 +98 // This only fails if the sender is closed. That means the EndpointStateActor has +99 // stopped, which only happens during shutdown. +100 actor +101 .send(EndpointStateMessage::AddEndpointAddr(endpoint_addr, source)) +102 .await +103 .ok(); +104 } +105 +106 pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr { +107 self.endpoint_mapped_addrs.get(&eid) +108 } +109 +110 /// Returns a [`n0_watcher::Direct`] for given endpoint's [`ConnectionType`]. +111 /// +112 /// # Errors +113 /// +114 /// Will return `None` if there is not an entry in the [`EndpointMap`] for +115 /// the `endpoint_id` +116 pub(super) fn conn_type( +117 &self, +118 _endpoint_id: EndpointId, +119 ) -> Option<n0_watcher::Direct<ConnectionType>> { +120 todo!(); +121 } +122 +123 /// Returns the sender for the [`EndpointStateActor`]. +124 /// +125 /// If needed a new actor is started on demand. +126 /// +127 /// [`EndpointStateActor`]: endpoint_state::EndpointStateActor +128 pub(super) fn endpoint_state_actor( +129 &self, +130 eid: EndpointId, +131 ) -> mpsc::Sender<EndpointStateMessage> { +132 let mut handles = self.actor_handles.lock().expect("poisoned"); +133 match handles.get(&eid) { +134 Some(handle) => handle.sender.clone(), +135 None => { +136 // Create a new EndpointStateActor and insert it into the endpoint map. +137 let local_addrs = self.local_addrs.clone(); +138 let disco = self.disco.clone(); +139 let metrics = self.metrics.clone(); +140 let actor = EndpointStateActor::new( +141 eid, +142 self.local_endpoint_id, +143 local_addrs, +144 disco, +145 self.relay_mapped_addrs.clone(), +146 metrics, +147 self.sender.clone(), +148 ); +149 let handle = actor.start(); +150 let sender = handle.sender.clone(); +151 handles.insert(eid, handle); +152 +153 // Ensure there is a EndpointMappedAddr for this EndpointId. +154 self.endpoint_mapped_addrs.get(&eid); +155 sender +156 } +157 } +158 } +159 +160 pub(super) fn handle_ping(&self, msg: disco::Ping, sender: EndpointId, src: transports::Addr) { +161 if msg.endpoint_key != sender { +162 warn!("DISCO Ping EndpointId mismatch, ignoring ping"); +163 return; +164 } +165 let endpoint_state = self.endpoint_state_actor(sender); +166 if let Err(err) = endpoint_state.try_send(EndpointStateMessage::PingReceived(msg, src)) { +167 // TODO: This is really, really bad and will drop pings under load. But +168 // DISCO pings are going away with QUIC-NAT-TRAVERSAL so I don't care. +169 warn!("DISCO Ping dropped: {err:#}"); +170 } +171 } +172 +173 pub(super) fn handle_pong(&self, msg: disco::Pong, sender: EndpointId, src: transports::Addr) { +174 let actor = self.endpoint_state_actor(sender); +175 if let Err(err) = actor.try_send(EndpointStateMessage::PongReceived(msg, src)) { +176 // TODO: This is really, really bad and will drop pongs under load. But +177 // DISCO pongs are going away with QUIC-NAT-TRAVERSAL so I don't care. +178 warn!("DISCO Pong dropped: {err:#}"); +179 } +180 } +181 +182 pub(super) fn handle_call_me_maybe( +183 &self, +184 msg: disco::CallMeMaybe, +185 sender: EndpointId, +186 src: transports::Addr, +187 ) { +188 if !src.is_relay() { +189 warn!("DISCO CallMeMaybe packets should only come via relay"); +190 return; +191 } +192 let actor = self.endpoint_state_actor(sender); +193 if let Err(err) = actor.try_send(EndpointStateMessage::CallMeMaybeReceived(msg)) { +194 // TODO: This is bad and will drop call-me-maybe's under load. But +195 // DISCO CallMeMaybe going away with QUIC-NAT-TRAVERSAL so I don't care. +196 warn!("DISCO CallMeMaybe dropped: {err:#}"); +197 } +198 } +199} +200 +201/// The origin or *source* through which an address associated with a remote endpoint +202/// was discovered. +203/// +204/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the +205/// [`Source`]s of the endpoint itself. +206/// +207/// A [`Source`] helps track how and where an address was learned. Multiple +208/// sources can be associated with a single address, if we have discovered this +209/// address through multiple means. +210#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] +211#[strum(serialize_all = "kebab-case")] +212pub enum Source { +213 /// Address was loaded from the fs. +214 Saved, +215 /// An endpoint communicated with us first via UDP. +216 Udp, +217 /// An endpoint communicated with us first via relay. +218 Relay, +219 /// Application layer added the address directly. +220 App, +221 /// The address was discovered by a discovery service. +222 #[strum(serialize = "{name}")] +223 Discovery { +224 /// The name of the discovery service that discovered the address. +225 name: String, +226 }, +227 /// Application layer with a specific name added the endpoint directly. +228 #[strum(serialize = "{name}")] +229 NamedApp { +230 /// The name of the application that added the endpoint +231 name: String, +232 }, +233 /// The address was advertised by a call-me-maybe DISCO message. +234 CallMeMaybe, +235 /// We received a ping on the path. +236 Ping, +237 /// We established a connection on this address. +238 /// +239 /// Currently this means the path was in uses as [`PathId::ZERO`] when the a connection +240 /// was added to the `EndpointStateActor`. +241 /// +242 /// [`PathId::ZERO`]: quinn_proto::PathId::ZERO +243 Connection, +244} +245 +246/// An (Ip, Port) pair. +247/// +248/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket +249/// addresses include fields that can't be assumed consistent even within a single connection. +250#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +251#[display("{}", SocketAddr::from(*self))] +252pub struct IpPort { +253 ip: IpAddr, +254 port: u16, +255} +256 +257impl From<SocketAddr> for IpPort { +258 fn from(socket_addr: SocketAddr) -> Self { +259 Self { +260 ip: socket_addr.ip(), +261 port: socket_addr.port(), +262 } +263 } +264} +265 +266impl From<IpPort> for SocketAddr { +267 fn from(ip_port: IpPort) -> Self { +268 let IpPort { ip, port } = ip_port; +269 (ip, port).into() +270 } +271} +272 +273impl IpPort { +274 pub fn ip(&self) -> &IpAddr { +275 &self.ip +276 } +277 +278 pub fn port(&self) -> u16 { +279 self.port +280 } +281} +282 +283#[cfg(test)] +284mod tests { +285 +286 use tracing_test::traced_test; +287 +288 // use super::*; +289 +290 // impl NodeMap { +291 // async fn add_test_addr(&self, node_addr: NodeAddr) { +292 // self.add_node_addr( +293 // node_addr, +294 // Source::NamedApp { +295 // name: "test".into(), +296 // }, +297 // ) +298 // .await; +299 // } +300 // } 301 -302 fn start(self) -> TransportsSenderHandle { -303 // This actor gets an inbox size of exactly 1. This is the same as if they had the -304 // underlying sender directly: either you can send or not, or you await until you -305 // can. No need to introduce extra buffering. -306 let (tx, rx) = mpsc::channel(1); -307 -308 let task = task::spawn( -309 async move { -310 self.run(rx).await; -311 } -312 .instrument(info_span!("TransportsSenderActor")), -313 ); -314 TransportsSenderHandle { -315 inbox: tx, -316 _task: AbortOnDropHandle::new(task), -317 } -318 } -319 -320 async fn run(self, mut inbox: mpsc::Receiver<TransportsSenderMessage>) { -321 use TransportsSenderMessage::SendDatagram; -322 -323 while let Some(SendDatagram(dst, owned_transmit)) = inbox.recv().await { -324 let transmit = transports::Transmit { -325 ecn: owned_transmit.ecn, -326 contents: owned_transmit.contents.as_ref(), -327 segment_size: owned_transmit.segment_size, -328 }; -329 let len = transmit.contents.len(); -330 match self.sender.send(&dst, None, &transmit).await { -331 Ok(()) => {} -332 Err(err) => { -333 trace!(?dst, %len, "transmit failed to send: {err:#}"); -334 } -335 }; -336 } -337 trace!("actor terminating"); -338 } -339} -340 -341#[derive(Debug)] -342struct TransportsSenderHandle { -343 inbox: mpsc::Sender<TransportsSenderMessage>, -344 _task: AbortOnDropHandle<()>, -345} -346 -347#[derive(Debug)] -348enum TransportsSenderMessage { -349 SendDatagram(transports::Addr, OwnedTransmit), -350} +302 // fn addr(port: u16) -> SocketAddr { +303 // (std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), port).into() +304 // } +305 +306 #[tokio::test] +307 #[traced_test] +308 async fn test_prune_direct_addresses() { +309 panic!("support this again"); +310 // let transports = Transports::new(Vec::new(), Vec::new(), Arc::new(1200.into())); +311 // let direct_addrs = DiscoveredDirectAddrs::default(); +312 // let secret_key = SecretKey::generate(&mut rand::rngs::OsRng); +313 // let (disco, _) = DiscoState::new(&secret_key); +314 // let node_map = NodeMap::new( +315 // secret_key.public(), +316 // Default::default(), +317 // transports.create_sender(), +318 // direct_addrs.addrs.watch(), +319 // disco, +320 // ); +321 // let public_key = SecretKey::generate(rand::thread_rng()).public(); +322 // let id = node_map +323 // .inner +324 // .lock() +325 // .unwrap() +326 // .insert_node(Options { +327 // node_id: public_key, +328 // relay_url: None, +329 // active: false, +330 // source: Source::NamedApp { +331 // name: "test".into(), +332 // }, +333 // path_selection: PathSelection::default(), +334 // }) +335 // .id(); +336 +337 // const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST); +338 +339 // // add [`MAX_INACTIVE_DIRECT_ADDRESSES`] active direct addresses and double +340 // // [`MAX_INACTIVE_DIRECT_ADDRESSES`] that are inactive +341 +342 // info!("Adding active addresses"); +343 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { +344 // let addr = SocketAddr::new(LOCALHOST, 5000 + i as u16); +345 // let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); +346 // // add address +347 // node_map.add_test_addr(node_addr).await; +348 // // make it active +349 // node_map.inner.lock().unwrap().receive_udp(addr); +350 // } 351 -352impl From<(transports::Addr, OwnedTransmit)> for TransportsSenderMessage { -353 fn from(source: (transports::Addr, OwnedTransmit)) -> Self { -354 Self::SendDatagram(source.0, source.1) -355 } -356} -357 -358#[cfg(test)] -359mod tests { -360 -361 use tracing_test::traced_test; -362 -363 // use super::*; -364 -365 // impl NodeMap { -366 // async fn add_test_addr(&self, node_addr: NodeAddr) { -367 // self.add_node_addr( -368 // node_addr, -369 // Source::NamedApp { -370 // name: "test".into(), -371 // }, -372 // ) -373 // .await; -374 // } -375 // } -376 -377 // fn addr(port: u16) -> SocketAddr { -378 // (std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), port).into() -379 // } +352 // info!("Adding offline/inactive addresses"); +353 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES * 2 { +354 // let addr = SocketAddr::new(LOCALHOST, 6000 + i as u16); +355 // let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); +356 // node_map.add_test_addr(node_addr).await; +357 // } +358 +359 // let mut node_map_inner = node_map.inner.lock().unwrap(); +360 // let endpoint = node_map_inner.by_id.get_mut(&id).unwrap(); +361 +362 // info!("Adding alive addresses"); +363 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { +364 // let addr = SendAddr::Udp(SocketAddr::new(LOCALHOST, 7000 + i as u16)); +365 // let txid = stun_rs::TransactionId::from([i as u8; 12]); +366 // // Note that this already invokes .prune_direct_addresses() because these are +367 // // new UDP paths. +368 // // endpoint.handle_ping(addr, txid); +369 // } +370 +371 // info!("Pruning addresses"); +372 // endpoint.prune_direct_addresses(Instant::now()); +373 +374 // // Half the offline addresses should have been pruned. All the active and alive +375 // // addresses should have been kept. +376 // assert_eq!( +377 // endpoint.direct_addresses().count(), +378 // MAX_INACTIVE_DIRECT_ADDRESSES * 3 +379 // ); 380 -381 #[tokio::test] -382 #[traced_test] -383 async fn test_prune_direct_addresses() { -384 panic!("support this again"); -385 // let transports = Transports::new(Vec::new(), Vec::new(), Arc::new(1200.into())); -386 // let direct_addrs = DiscoveredDirectAddrs::default(); -387 // let secret_key = SecretKey::generate(&mut rand::rngs::OsRng); -388 // let (disco, _) = DiscoState::new(&secret_key); -389 // let node_map = NodeMap::new( -390 // secret_key.public(), -391 // Default::default(), -392 // transports.create_sender(), -393 // direct_addrs.addrs.watch(), -394 // disco, -395 // ); -396 // let public_key = SecretKey::generate(rand::thread_rng()).public(); -397 // let id = node_map -398 // .inner -399 // .lock() -400 // .unwrap() -401 // .insert_node(Options { -402 // node_id: public_key, -403 // relay_url: None, -404 // active: false, -405 // source: Source::NamedApp { -406 // name: "test".into(), -407 // }, -408 // path_selection: PathSelection::default(), -409 // }) -410 // .id(); -411 -412 // const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST); -413 -414 // // add [`MAX_INACTIVE_DIRECT_ADDRESSES`] active direct addresses and double -415 // // [`MAX_INACTIVE_DIRECT_ADDRESSES`] that are inactive -416 -417 // info!("Adding active addresses"); -418 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { -419 // let addr = SocketAddr::new(LOCALHOST, 5000 + i as u16); -420 // let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); -421 // // add address -422 // node_map.add_test_addr(node_addr).await; -423 // // make it active -424 // node_map.inner.lock().unwrap().receive_udp(addr); -425 // } -426 -427 // info!("Adding offline/inactive addresses"); -428 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES * 2 { -429 // let addr = SocketAddr::new(LOCALHOST, 6000 + i as u16); -430 // let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); -431 // node_map.add_test_addr(node_addr).await; -432 // } -433 -434 // let mut node_map_inner = node_map.inner.lock().unwrap(); -435 // let endpoint = node_map_inner.by_id.get_mut(&id).unwrap(); -436 -437 // info!("Adding alive addresses"); -438 // for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { -439 // let addr = SendAddr::Udp(SocketAddr::new(LOCALHOST, 7000 + i as u16)); -440 // let txid = stun_rs::TransactionId::from([i as u8; 12]); -441 // // Note that this already invokes .prune_direct_addresses() because these are -442 // // new UDP paths. -443 // // endpoint.handle_ping(addr, txid); -444 // } -445 -446 // info!("Pruning addresses"); -447 // endpoint.prune_direct_addresses(Instant::now()); -448 -449 // // Half the offline addresses should have been pruned. All the active and alive -450 // // addresses should have been kept. -451 // assert_eq!( -452 // endpoint.direct_addresses().count(), -453 // MAX_INACTIVE_DIRECT_ADDRESSES * 3 -454 // ); -455 -456 // // We should have both offline and alive addresses which are not active. -457 // assert_eq!( -458 // endpoint -459 // .direct_address_states() -460 // .filter(|(_addr, state)| !state.is_active()) -461 // .count(), -462 // MAX_INACTIVE_DIRECT_ADDRESSES * 2 -463 // ) -464 } -465 -466 #[tokio::test] -467 async fn test_prune_inactive() { -468 panic!("support this again"); -469 // let transports = Transports::new(Vec::new(), Vec::new(), Arc::new(1200.into())); -470 // let direct_addrs = DiscoveredDirectAddrs::default(); -471 // let secret_key = SecretKey::generate(&mut rand::rngs::OsRng); -472 // let (disco, _) = DiscoState::new(&secret_key); -473 // let node_map = NodeMap::new( -474 // secret_key.public(), -475 // Default::default(), -476 // transports.create_sender(), -477 // direct_addrs.addrs.watch(), -478 // disco, -479 // ); -480 // // add one active node and more than MAX_INACTIVE_NODES inactive nodes -481 // let active_node = SecretKey::generate(rand::thread_rng()).public(); -482 // let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 167); -483 // node_map -484 // .add_test_addr(NodeAddr::new(active_node).with_direct_addresses([addr])) -485 // .await; -486 // node_map -487 // .inner -488 // .lock() -489 // .unwrap() -490 // .receive_udp(addr) -491 // .expect("registered"); -492 -493 // for _ in 0..MAX_INACTIVE_NODES + 1 { -494 // let node = SecretKey::generate(rand::thread_rng()).public(); -495 // node_map.add_test_addr(NodeAddr::new(node)).await; -496 // } -497 -498 // assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 2); -499 // node_map.prune_inactive(); -500 // assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 1); -501 // node_map -502 // .inner -503 // .lock() -504 // .unwrap() -505 // .get(NodeStateKey::NodeId(active_node)) -506 // .expect("should not be pruned"); -507 } -508}
    \ No newline at end of file +381 // // We should have both offline and alive addresses which are not active. +382 // assert_eq!( +383 // endpoint +384 // .direct_address_states() +385 // .filter(|(_addr, state)| !state.is_active()) +386 // .count(), +387 // MAX_INACTIVE_DIRECT_ADDRESSES * 2 +388 // ) +389 } +390 +391 #[tokio::test] +392 async fn test_prune_inactive() { +393 panic!("support this again"); +394 // let transports = Transports::new(Vec::new(), Vec::new(), Arc::new(1200.into())); +395 // let direct_addrs = DiscoveredDirectAddrs::default(); +396 // let secret_key = SecretKey::generate(&mut rand::rngs::OsRng); +397 // let (disco, _) = DiscoState::new(&secret_key); +398 // let node_map = NodeMap::new( +399 // secret_key.public(), +400 // Default::default(), +401 // transports.create_sender(), +402 // direct_addrs.addrs.watch(), +403 // disco, +404 // ); +405 // // add one active node and more than MAX_INACTIVE_NODES inactive nodes +406 // let active_node = SecretKey::generate(rand::thread_rng()).public(); +407 // let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 167); +408 // node_map +409 // .add_test_addr(NodeAddr::new(active_node).with_direct_addresses([addr])) +410 // .await; +411 // node_map +412 // .inner +413 // .lock() +414 // .unwrap() +415 // .receive_udp(addr) +416 // .expect("registered"); +417 +418 // for _ in 0..MAX_INACTIVE_NODES + 1 { +419 // let node = SecretKey::generate(rand::thread_rng()).public(); +420 // node_map.add_test_addr(NodeAddr::new(node)).await; +421 // } +422 +423 // assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 2); +424 // node_map.prune_inactive(); +425 // assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 1); +426 // node_map +427 // .inner +428 // .lock() +429 // .unwrap() +430 // .get(NodeStateKey::NodeId(active_node)) +431 // .expect("should not be pruned"); +432 } +433} \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html b/pr/3381/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html index e23604f27d..8635a8753c 100644 --- a/pr/3381/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/endpoint_map/endpoint_state.rs.html @@ -7,1311 +7,1315 @@ 7}; 8 9use iroh_base::{EndpointAddr, EndpointId, RelayUrl, TransportAddr}; -10use n0_error::StdResultExt; -11use n0_future::{ -12 FuturesUnordered, MergeUnbounded, Stream, StreamExt, -13 task::{self, AbortOnDropHandle}, -14 time::{self, Duration, Instant}, -15}; -16use n0_watcher::{Watchable, Watcher}; -17use quinn::{PathStats, WeakConnectionHandle}; -18use quinn_proto::{PathError, PathEvent, PathId, PathStatus}; -19use rustc_hash::FxHashMap; -20use serde::{Deserialize, Serialize}; -21use smallvec::SmallVec; -22use tokio::sync::{mpsc, oneshot}; -23use tokio_stream::wrappers::{BroadcastStream, errors::BroadcastStreamRecvError}; -24use tracing::{Instrument, Level, debug, error, event, info_span, instrument, trace, warn}; -25 -26use super::{Source, TransportsSenderMessage, path_state::PathState}; -27// TODO: Use this -28// #[cfg(any(test, feature = "test-utils"))] -29// use crate::endpoint::PathSelection; -30use crate::{ -31 disco::{self}, -32 endpoint::DirectAddr, -33 magicsock::{ -34 DiscoState, HEARTBEAT_INTERVAL, MagicsockMetrics, PATH_MAX_IDLE_TIMEOUT, -35 mapped_addrs::{AddrMap, MappedAddr, RelayMappedAddr}, -36 transports::{self, OwnedTransmit}, -37 }, -38 util::MaybeFuture, -39}; -40 -41// TODO: use this -42// /// Number of addresses that are not active that we keep around per endpoint. -43// /// -44// /// See [`EndpointState::prune_direct_addresses`]. -45// pub(super) const MAX_INACTIVE_DIRECT_ADDRESSES: usize = 20; -46 -47// TODO: use this -48// /// How long since an endpoint path was last alive before it might be pruned. -49// const LAST_ALIVE_PRUNE_DURATION: Duration = Duration::from_secs(120); -50 -51// TODO: use this -52// /// The latency at or under which we don't try to upgrade to a better path. -53// const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(5); -54 -55// TODO: use this -56// /// How long since the last activity we try to keep an established endpoint peering alive. -57// /// -58// /// It's also the idle time at which we stop doing QAD queries to keep NAT mappings alive. -59// pub(super) const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45); -60 -61// TODO: use this -62// /// How often we try to upgrade to a better path. -63// /// -64// /// Even if we have some non-relay route that works. -65// const UPGRADE_INTERVAL: Duration = Duration::from_secs(60); -66 -67/// The value which we close paths. -68// TODO: Quinn should just do this. Also, I made this value up. -69const APPLICATION_ABANDON_PATH: u8 = 30; -70 -71/// A stream of events from all paths for all connections. -72/// -73/// The connection is identified using [`ConnId`]. The event `Err` variant happens when the -74/// actor has lagged processing the events, which is rather critical for us. -75type PathEvents = MergeUnbounded< -76 Pin< -77 Box<dyn Stream<Item = (ConnId, Result<PathEvent, BroadcastStreamRecvError>)> + Send + Sync>, -78 >, -79>; -80 -81/// List of addrs and path ids for open paths in a connection. -82pub(crate) type PathAddrList = SmallVec<[(TransportAddr, PathId); 4]>; -83 -84/// The state we need to know about a single remote endpoint. -85/// -86/// This actor manages all connections to the remote endpoint. It will trigger holepunching -87/// and select the best path etc. -88pub(super) struct EndpointStateActor { -89 /// The endpoint ID of the remote endpoint. -90 endpoint_id: EndpointId, -91 /// The endpoint ID of the local endpoint. -92 local_endpoint_id: EndpointId, -93 -94 // Hooks into the rest of the MagicSocket. -95 // -96 /// Metrics. -97 metrics: Arc<MagicsockMetrics>, -98 /// Allowing us to directly send datagrams. +10use n0_future::{ +11 FuturesUnordered, MergeUnbounded, Stream, StreamExt, +12 task::{self, AbortOnDropHandle}, +13 time::{self, Duration, Instant}, +14}; +15use n0_watcher::{Watchable, Watcher}; +16use quinn::{PathStats, WeakConnectionHandle}; +17use quinn_proto::{PathError, PathEvent, PathId, PathStatus}; +18use rustc_hash::FxHashMap; +19use serde::{Deserialize, Serialize}; +20use smallvec::SmallVec; +21use tokio::sync::{mpsc, oneshot}; +22use tokio_stream::wrappers::{BroadcastStream, errors::BroadcastStreamRecvError}; +23use tracing::{Instrument, Level, debug, error, event, info_span, instrument, trace, warn}; +24 +25use super::{Source, path_state::PathState}; +26// TODO: Use this +27// #[cfg(any(test, feature = "test-utils"))] +28// use crate::endpoint::PathSelection; +29use crate::{ +30 disco::{self}, +31 endpoint::DirectAddr, +32 magicsock::{ +33 DiscoState, HEARTBEAT_INTERVAL, MagicsockMetrics, PATH_MAX_IDLE_TIMEOUT, +34 mapped_addrs::{AddrMap, MappedAddr, RelayMappedAddr}, +35 transports::{self, OwnedTransmit, TransportsSender}, +36 }, +37 util::MaybeFuture, +38}; +39 +40// TODO: use this +41// /// Number of addresses that are not active that we keep around per endpoint. +42// /// +43// /// See [`EndpointState::prune_direct_addresses`]. +44// pub(super) const MAX_INACTIVE_DIRECT_ADDRESSES: usize = 20; +45 +46// TODO: use this +47// /// How long since an endpoint path was last alive before it might be pruned. +48// const LAST_ALIVE_PRUNE_DURATION: Duration = Duration::from_secs(120); +49 +50// TODO: use this +51// /// The latency at or under which we don't try to upgrade to a better path. +52// const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(5); +53 +54// TODO: use this +55// /// How long since the last activity we try to keep an established endpoint peering alive. +56// /// +57// /// It's also the idle time at which we stop doing QAD queries to keep NAT mappings alive. +58// pub(super) const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45); +59 +60// TODO: use this +61// /// How often we try to upgrade to a better path. +62// /// +63// /// Even if we have some non-relay route that works. +64// const UPGRADE_INTERVAL: Duration = Duration::from_secs(60); +65 +66/// The value which we close paths. +67// TODO: Quinn should just do this. Also, I made this value up. +68const APPLICATION_ABANDON_PATH: u8 = 30; +69 +70/// A stream of events from all paths for all connections. +71/// +72/// The connection is identified using [`ConnId`]. The event `Err` variant happens when the +73/// actor has lagged processing the events, which is rather critical for us. +74type PathEvents = MergeUnbounded< +75 Pin< +76 Box<dyn Stream<Item = (ConnId, Result<PathEvent, BroadcastStreamRecvError>)> + Send + Sync>, +77 >, +78>; +79 +80/// List of addrs and path ids for open paths in a connection. +81pub(crate) type PathAddrList = SmallVec<[(TransportAddr, PathId); 4]>; +82 +83/// The state we need to know about a single remote endpoint. +84/// +85/// This actor manages all connections to the remote endpoint. It will trigger holepunching +86/// and select the best path etc. +87pub(super) struct EndpointStateActor { +88 /// The endpoint ID of the remote endpoint. +89 endpoint_id: EndpointId, +90 /// The endpoint ID of the local endpoint. +91 local_endpoint_id: EndpointId, +92 +93 // Hooks into the rest of the MagicSocket. +94 // +95 /// Metrics. +96 metrics: Arc<MagicsockMetrics>, +97 sender: TransportsSender, +98 /// Our local addresses. 99 /// -100 /// Used for handling [`EndpointStateMessage::SendDatagram`] messages. -101 transports_sender: mpsc::Sender<TransportsSenderMessage>, -102 /// Our local addresses. -103 /// -104 /// These are our local addresses and any reflexive transport addresses. -105 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -106 /// Shared state to allow to encrypt DISCO messages to peers. -107 disco: DiscoState, -108 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. -109 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -110 -111 // Internal state - Quinn Connections we are managing. -112 // -113 /// All connections we have to this remote endpoint. -114 connections: FxHashMap<ConnId, ConnectionState>, -115 /// Notifications when connections are closed. -116 connections_close: FuturesUnordered<OnClosed>, -117 /// Events emitted by Quinn about path changes, for all paths, all connections. -118 path_events: PathEvents, -119 -120 // Internal state - Holepunching and path state. -121 // -122 /// All possible paths we are aware of. -123 /// -124 /// These paths might be entirely impossible to use, since they are added by discovery -125 /// mechanisms. The are only potentially usable. -126 paths: FxHashMap<transports::Addr, PathState>, -127 /// Information about the last holepunching attempt. -128 last_holepunch: Option<HolepunchAttempt>, -129 /// The path we currently consider the preferred path to the remote endpoint. -130 /// -131 /// **We expect this path to work.** If we become aware this path is broken then it is -132 /// set back to `None`. Having a selected path does not mean we may not be able to get -133 /// a better path: e.g. when the selected path is a relay path we still need to trigger -134 /// holepunching regularly. -135 /// -136 /// We only select a path once the path is functional in Quinn. -137 selected_path: Watchable<Option<transports::Addr>>, -138 /// Time at which we should schedule the next holepunch attempt. -139 scheduled_holepunch: Option<Instant>, -140 /// When to next attempt opening paths in [`Self::pending_open_paths`]. -141 scheduled_open_path: Option<Instant>, -142 /// Paths which we still need to open. -143 /// -144 /// They failed to open because we did not have enough CIDs issued by the remote. -145 pending_open_paths: VecDeque<transports::Addr>, -146} -147 -148impl EndpointStateActor { -149 pub(super) fn new( -150 endpoint_id: EndpointId, -151 local_endpoint_id: EndpointId, -152 transports_sender: mpsc::Sender<TransportsSenderMessage>, -153 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, -154 disco: DiscoState, -155 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, -156 metrics: Arc<MagicsockMetrics>, -157 ) -> Self { -158 Self { -159 endpoint_id, -160 local_endpoint_id, -161 metrics, -162 transports_sender, -163 local_addrs, -164 relay_mapped_addrs, -165 disco, -166 connections: FxHashMap::default(), -167 connections_close: Default::default(), -168 path_events: Default::default(), -169 paths: FxHashMap::default(), -170 last_holepunch: None, -171 selected_path: Default::default(), -172 scheduled_holepunch: None, -173 scheduled_open_path: None, -174 pending_open_paths: VecDeque::new(), -175 } -176 } -177 -178 pub(super) fn start(mut self) -> EndpointStateHandle { -179 let (tx, rx) = mpsc::channel(16); -180 let me = self.local_endpoint_id; -181 let endpoint_id = self.endpoint_id; -182 -183 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into -184 // here somehow. Instead we have no parent and explicitly set the me attribute. If -185 // we don't explicitly set a span we get the spans from whatever call happens to -186 // first create the actor, which is often very confusing as it then keeps those -187 // spans for all logging of the actor. -188 let task = task::spawn( -189 async move { -190 if let Err(err) = self.run(rx).await { -191 error!("actor failed: {err:#}"); -192 } -193 } -194 .instrument(info_span!( -195 parent: None, -196 "EndpointStateActor", -197 me = %me.fmt_short(), -198 remote = %endpoint_id.fmt_short(), -199 )), -200 ); -201 EndpointStateHandle { -202 sender: tx, -203 _task: AbortOnDropHandle::new(task), -204 } -205 } -206 -207 /// Runs the main loop of the actor. -208 /// -209 /// Note that the actor uses async handlers for tasks from the main loop. The actor is -210 /// not processing items from the inbox while waiting on any async calls. So some -211 /// discipline is needed to not turn pending for a long time. -212 async fn run( -213 &mut self, -214 mut inbox: mpsc::Receiver<EndpointStateMessage>, -215 ) -> n0_error::Result<()> { -216 trace!("actor started"); -217 loop { -218 let scheduled_path_open = match self.scheduled_open_path { -219 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -220 None => MaybeFuture::None, -221 }; -222 n0_future::pin!(scheduled_path_open); -223 let scheduled_hp = match self.scheduled_holepunch { -224 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -225 None => MaybeFuture::None, -226 }; -227 n0_future::pin!(scheduled_hp); -228 tokio::select! { -229 biased; -230 msg = inbox.recv() => { -231 match msg { -232 Some(msg) => self.handle_message(msg).await?, -233 None => break, -234 } -235 } -236 Some((id, evt)) = self.path_events.next() => { -237 self.handle_path_event(id, evt); -238 } -239 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { -240 self.connections.remove(&conn_id); +100 /// These are our local addresses and any reflexive transport addresses. +101 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +102 /// Shared state to allow to encrypt DISCO messages to peers. +103 disco: DiscoState, +104 /// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s. +105 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +106 +107 // Internal state - Quinn Connections we are managing. +108 // +109 /// All connections we have to this remote endpoint. +110 connections: FxHashMap<ConnId, ConnectionState>, +111 /// Notifications when connections are closed. +112 connections_close: FuturesUnordered<OnClosed>, +113 /// Events emitted by Quinn about path changes, for all paths, all connections. +114 path_events: PathEvents, +115 +116 // Internal state - Holepunching and path state. +117 // +118 /// All possible paths we are aware of. +119 /// +120 /// These paths might be entirely impossible to use, since they are added by discovery +121 /// mechanisms. The are only potentially usable. +122 paths: FxHashMap<transports::Addr, PathState>, +123 /// Information about the last holepunching attempt. +124 last_holepunch: Option<HolepunchAttempt>, +125 /// The path we currently consider the preferred path to the remote endpoint. +126 /// +127 /// **We expect this path to work.** If we become aware this path is broken then it is +128 /// set back to `None`. Having a selected path does not mean we may not be able to get +129 /// a better path: e.g. when the selected path is a relay path we still need to trigger +130 /// holepunching regularly. +131 /// +132 /// We only select a path once the path is functional in Quinn. +133 selected_path: Watchable<Option<transports::Addr>>, +134 /// Time at which we should schedule the next holepunch attempt. +135 scheduled_holepunch: Option<Instant>, +136 /// When to next attempt opening paths in [`Self::pending_open_paths`]. +137 scheduled_open_path: Option<Instant>, +138 /// Paths which we still need to open. +139 /// +140 /// They failed to open because we did not have enough CIDs issued by the remote. +141 pending_open_paths: VecDeque<transports::Addr>, +142} +143 +144impl EndpointStateActor { +145 pub(super) fn new( +146 endpoint_id: EndpointId, +147 local_endpoint_id: EndpointId, +148 local_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>, +149 disco: DiscoState, +150 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>, +151 metrics: Arc<MagicsockMetrics>, +152 sender: TransportsSender, +153 ) -> Self { +154 Self { +155 endpoint_id, +156 local_endpoint_id, +157 metrics, +158 local_addrs, +159 relay_mapped_addrs, +160 disco, +161 connections: FxHashMap::default(), +162 connections_close: Default::default(), +163 path_events: Default::default(), +164 paths: FxHashMap::default(), +165 last_holepunch: None, +166 selected_path: Default::default(), +167 scheduled_holepunch: None, +168 scheduled_open_path: None, +169 pending_open_paths: VecDeque::new(), +170 sender, +171 } +172 } +173 +174 pub(super) fn start(mut self) -> EndpointStateHandle { +175 let (tx, rx) = mpsc::channel(16); +176 let me = self.local_endpoint_id; +177 let endpoint_id = self.endpoint_id; +178 +179 // Ideally we'd use the endpoint span as parent. We'd have to plug that span into +180 // here somehow. Instead we have no parent and explicitly set the me attribute. If +181 // we don't explicitly set a span we get the spans from whatever call happens to +182 // first create the actor, which is often very confusing as it then keeps those +183 // spans for all logging of the actor. +184 let task = task::spawn( +185 async move { +186 if let Err(err) = self.run(rx).await { +187 error!("actor failed: {err:#}"); +188 } +189 } +190 .instrument(info_span!( +191 parent: None, +192 "EndpointStateActor", +193 me = %me.fmt_short(), +194 remote = %endpoint_id.fmt_short(), +195 )), +196 ); +197 EndpointStateHandle { +198 sender: tx, +199 _task: AbortOnDropHandle::new(task), +200 } +201 } +202 +203 /// Runs the main loop of the actor. +204 /// +205 /// Note that the actor uses async handlers for tasks from the main loop. The actor is +206 /// not processing items from the inbox while waiting on any async calls. So some +207 /// discipline is needed to not turn pending for a long time. +208 async fn run( +209 &mut self, +210 mut inbox: mpsc::Receiver<EndpointStateMessage>, +211 ) -> n0_error::Result<()> { +212 trace!("actor started"); +213 loop { +214 let scheduled_path_open = match self.scheduled_open_path { +215 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +216 None => MaybeFuture::None, +217 }; +218 n0_future::pin!(scheduled_path_open); +219 let scheduled_hp = match self.scheduled_holepunch { +220 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +221 None => MaybeFuture::None, +222 }; +223 n0_future::pin!(scheduled_hp); +224 tokio::select! { +225 biased; +226 msg = inbox.recv() => { +227 match msg { +228 Some(msg) => self.handle_message(msg).await?, +229 None => break, +230 } +231 } +232 Some((id, evt)) = self.path_events.next() => { +233 self.handle_path_event(id, evt); +234 } +235 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { +236 self.connections.remove(&conn_id); +237 } +238 _ = self.local_addrs.updated() => { +239 trace!("local addrs updated, triggering holepunching"); +240 self.trigger_holepunching().await; 241 } -242 _ = self.local_addrs.updated() => { -243 trace!("local addrs updated, triggering holepunching"); -244 self.trigger_holepunching().await; -245 } -246 _ = &mut scheduled_path_open => { -247 trace!("triggering scheduled path_open"); -248 self.scheduled_open_path = None; -249 let mut addrs = std::mem::take(&mut self.pending_open_paths); -250 while let Some(addr) = addrs.pop_front() { -251 self.open_path(&addr); -252 } -253 } -254 _ = &mut scheduled_hp => { -255 trace!("triggering scheduled holepunching"); -256 self.scheduled_holepunch = None; -257 self.trigger_holepunching().await; -258 } -259 } -260 } -261 trace!("actor terminating"); -262 Ok(()) -263 } -264 -265 /// Handles an actor message. -266 /// -267 /// Error returns are fatal and kill the actor. -268 #[instrument(skip(self))] -269 async fn handle_message(&mut self, msg: EndpointStateMessage) -> n0_error::Result<()> { -270 // trace!("handling message"); -271 match msg { -272 EndpointStateMessage::SendDatagram(transmit) => { -273 self.handle_msg_send_datagram(transmit).await?; -274 } -275 EndpointStateMessage::AddConnection(handle, tx) => { -276 self.handle_msg_add_connection(handle, tx).await; -277 } -278 EndpointStateMessage::AddEndpointAddr(addr, source) => { -279 self.handle_msg_add_endpoint_addr(addr, source); -280 } -281 EndpointStateMessage::CallMeMaybeReceived(msg) => { -282 self.handle_msg_call_me_maybe_received(msg).await; -283 } -284 EndpointStateMessage::PingReceived(ping, src) => { -285 self.handle_msg_ping_received(ping, src).await; -286 } -287 EndpointStateMessage::PongReceived(pong, src) => { -288 self.handle_msg_pong_received(pong, src); -289 } -290 EndpointStateMessage::CanSend(tx) => { -291 self.handle_msg_can_send(tx); -292 } -293 EndpointStateMessage::Latency(tx) => { -294 self.handle_msg_latency(tx); -295 } -296 } -297 Ok(()) -298 } -299 -300 /// Handles [`EndpointStateMessage::SendDatagram`]. -301 /// -302 /// Error returns are fatal and kill the actor. -303 async fn handle_msg_send_datagram(&mut self, transmit: OwnedTransmit) -> n0_error::Result<()> { -304 if let Some(addr) = self.selected_path.get() { -305 trace!(?addr, "sending datagram to selected path"); -306 self.transports_sender -307 .send((addr, transmit).into()) -308 .await -309 .std_context("TransportSenderActor stopped")?; -310 } else { -311 trace!( -312 paths = ?self.paths.keys().collect::<Vec<_>>(), -313 "sending datagram to all known paths", -314 ); -315 for addr in self.paths.keys() { -316 self.transports_sender -317 .send((addr.clone(), transmit.clone()).into()) -318 .await -319 .std_context("TransportSenerActor stopped")?; -320 } -321 // This message is received *before* a connection is added. So we do -322 // not yet have a connection to holepunch. Instead we trigger -323 // holepunching when AddConnection is received. -324 } -325 Ok(()) -326 } -327 -328 /// Handles [`EndpointStateMessage::AddConnection`]. -329 /// -330 /// Error returns are fatal and kill the actor. -331 async fn handle_msg_add_connection( -332 &mut self, -333 handle: WeakConnectionHandle, -334 tx: oneshot::Sender<PathsWatchable>, -335 ) { -336 let pub_open_paths = Watchable::default(); -337 if let Some(conn) = handle.upgrade() { -338 // Remove any conflicting stable_ids from the local state. -339 let conn_id = ConnId(conn.stable_id()); -340 self.connections.remove(&conn_id); -341 -342 // Store the connection and hook up paths events stream. -343 let events = BroadcastStream::new(conn.path_events()); -344 let stream = events.map(move |evt| (conn_id, evt)); -345 self.path_events.push(Box::pin(stream)); -346 self.connections_close.push(OnClosed::new(&conn)); -347 let conn_state = self -348 .connections -349 .entry(conn_id) -350 .insert_entry(ConnectionState { -351 handle: handle.clone(), -352 pub_open_paths: pub_open_paths.clone(), -353 paths: Default::default(), -354 open_paths: Default::default(), -355 path_ids: Default::default(), -356 }) -357 .into_mut(); -358 -359 // Store PathId(0), set path_status and select best path, check if holepunching -360 // is needed. -361 if let Some(path) = conn.path(PathId::ZERO) -362 && let Ok(socketaddr) = path.remote_address() -363 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -364 { -365 trace!(?path_remote, "added new connection"); -366 let path_remote_is_ip = path_remote.is_ip(); -367 let status = match path_remote { -368 transports::Addr::Ip(_) => PathStatus::Available, -369 transports::Addr::Relay(_, _) => PathStatus::Backup, -370 }; -371 path.set_status(status).ok(); -372 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); -373 self.paths -374 .entry(path_remote) -375 .or_default() -376 .sources -377 .insert(Source::Connection, Instant::now()); -378 self.select_path(); -379 -380 if path_remote_is_ip { -381 // We may have raced this with a relay address. Try and add any -382 // relay addresses we have back. -383 let relays = self -384 .paths -385 .keys() -386 .filter(|a| a.is_relay()) -387 .cloned() -388 .collect::<Vec<_>>(); -389 for remote in relays { -390 self.open_path(&remote); -391 } -392 } -393 } -394 self.trigger_holepunching().await; -395 } -396 tx.send(PathsWatchable { -397 open_paths: pub_open_paths, -398 selected_path: self.selected_path.clone(), -399 }) -400 .ok(); -401 } -402 -403 /// Handles [`EndpointStateMessage::AddEndpointAddr`]. -404 fn handle_msg_add_endpoint_addr(&mut self, addr: EndpointAddr, source: Source) { -405 for sockaddr in addr.ip_addrs() { -406 let addr = transports::Addr::from(sockaddr); -407 self.paths -408 .entry(addr) -409 .or_default() -410 .sources -411 .insert(source.clone(), Instant::now()); -412 } -413 for relay_url in addr.relay_urls() { -414 let addr = transports::Addr::from((relay_url.clone(), self.endpoint_id)); -415 self.paths -416 .entry(addr) -417 .or_default() -418 .sources -419 .insert(source.clone(), Instant::now()); -420 } -421 trace!("added addressing information"); -422 } -423 -424 /// Handles [`EndpointStateMessage::CallMeMaybeReceived`]. -425 async fn handle_msg_call_me_maybe_received(&mut self, msg: disco::CallMeMaybe) { -426 event!( -427 target: "iroh::_events::call_me_maybe::recv", -428 Level::DEBUG, -429 remote = %self.endpoint_id.fmt_short(), -430 addrs = ?msg.my_numbers, -431 ); -432 let now = Instant::now(); -433 for addr in msg.my_numbers { -434 let dst = transports::Addr::Ip(addr); -435 let ping = disco::Ping::new(self.local_endpoint_id); -436 -437 let path = self.paths.entry(dst.clone()).or_default(); -438 path.sources.insert(Source::CallMeMaybe, now); -439 path.ping_sent = Some(ping.tx_id); +242 _ = &mut scheduled_path_open => { +243 trace!("triggering scheduled path_open"); +244 self.scheduled_open_path = None; +245 let mut addrs = std::mem::take(&mut self.pending_open_paths); +246 while let Some(addr) = addrs.pop_front() { +247 self.open_path(&addr); +248 } +249 } +250 _ = &mut scheduled_hp => { +251 trace!("triggering scheduled holepunching"); +252 self.scheduled_holepunch = None; +253 self.trigger_holepunching().await; +254 } +255 } +256 } +257 trace!("actor terminating"); +258 Ok(()) +259 } +260 +261 /// Handles an actor message. +262 /// +263 /// Error returns are fatal and kill the actor. +264 #[instrument(skip(self))] +265 async fn handle_message(&mut self, msg: EndpointStateMessage) -> n0_error::Result<()> { +266 // trace!("handling message"); +267 match msg { +268 EndpointStateMessage::SendDatagram(transmit) => { +269 self.handle_msg_send_datagram(transmit).await?; +270 } +271 EndpointStateMessage::AddConnection(handle, tx) => { +272 self.handle_msg_add_connection(handle, tx).await; +273 } +274 EndpointStateMessage::AddEndpointAddr(addr, source) => { +275 self.handle_msg_add_endpoint_addr(addr, source); +276 } +277 EndpointStateMessage::CallMeMaybeReceived(msg) => { +278 self.handle_msg_call_me_maybe_received(msg).await; +279 } +280 EndpointStateMessage::PingReceived(ping, src) => { +281 self.handle_msg_ping_received(ping, src).await; +282 } +283 EndpointStateMessage::PongReceived(pong, src) => { +284 self.handle_msg_pong_received(pong, src); +285 } +286 EndpointStateMessage::CanSend(tx) => { +287 self.handle_msg_can_send(tx); +288 } +289 EndpointStateMessage::Latency(tx) => { +290 self.handle_msg_latency(tx); +291 } +292 } +293 Ok(()) +294 } +295 +296 async fn send_datagram( +297 &self, +298 dst: transports::Addr, +299 owned_transmit: OwnedTransmit, +300 ) -> n0_error::Result<()> { +301 let transmit = transports::Transmit { +302 ecn: owned_transmit.ecn, +303 contents: owned_transmit.contents.as_ref(), +304 segment_size: owned_transmit.segment_size, +305 }; +306 self.sender.send(&dst, None, &transmit).await?; +307 Ok(()) +308 } +309 +310 /// Handles [`EndpointStateMessage::SendDatagram`]. +311 /// +312 /// Error returns are fatal and kill the actor. +313 async fn handle_msg_send_datagram(&mut self, transmit: OwnedTransmit) -> n0_error::Result<()> { +314 if let Some(addr) = self.selected_path.get() { +315 trace!(?addr, "sending datagram to selected path"); +316 self.send_datagram(addr, transmit).await?; +317 } else { +318 trace!( +319 paths = ?self.paths.keys().collect::<Vec<_>>(), +320 "sending datagram to all known paths", +321 ); +322 for addr in self.paths.keys() { +323 self.send_datagram(addr.clone(), transmit.clone()).await?; +324 } +325 // This message is received *before* a connection is added. So we do +326 // not yet have a connection to holepunch. Instead we trigger +327 // holepunching when AddConnection is received. +328 } +329 Ok(()) +330 } +331 +332 /// Handles [`EndpointStateMessage::AddConnection`]. +333 /// +334 /// Error returns are fatal and kill the actor. +335 async fn handle_msg_add_connection( +336 &mut self, +337 handle: WeakConnectionHandle, +338 tx: oneshot::Sender<PathsWatchable>, +339 ) { +340 let pub_open_paths = Watchable::default(); +341 if let Some(conn) = handle.upgrade() { +342 // Remove any conflicting stable_ids from the local state. +343 let conn_id = ConnId(conn.stable_id()); +344 self.connections.remove(&conn_id); +345 +346 // Store the connection and hook up paths events stream. +347 let events = BroadcastStream::new(conn.path_events()); +348 let stream = events.map(move |evt| (conn_id, evt)); +349 self.path_events.push(Box::pin(stream)); +350 self.connections_close.push(OnClosed::new(&conn)); +351 let conn_state = self +352 .connections +353 .entry(conn_id) +354 .insert_entry(ConnectionState { +355 handle: handle.clone(), +356 pub_open_paths: pub_open_paths.clone(), +357 paths: Default::default(), +358 open_paths: Default::default(), +359 path_ids: Default::default(), +360 }) +361 .into_mut(); +362 +363 // Store PathId(0), set path_status and select best path, check if holepunching +364 // is needed. +365 if let Some(path) = conn.path(PathId::ZERO) +366 && let Ok(socketaddr) = path.remote_address() +367 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +368 { +369 trace!(?path_remote, "added new connection"); +370 let path_remote_is_ip = path_remote.is_ip(); +371 let status = match path_remote { +372 transports::Addr::Ip(_) => PathStatus::Available, +373 transports::Addr::Relay(_, _) => PathStatus::Backup, +374 }; +375 path.set_status(status).ok(); +376 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); +377 self.paths +378 .entry(path_remote) +379 .or_default() +380 .sources +381 .insert(Source::Connection, Instant::now()); +382 self.select_path(); +383 +384 if path_remote_is_ip { +385 // We may have raced this with a relay address. Try and add any +386 // relay addresses we have back. +387 let relays = self +388 .paths +389 .keys() +390 .filter(|a| a.is_relay()) +391 .cloned() +392 .collect::<Vec<_>>(); +393 for remote in relays { +394 self.open_path(&remote); +395 } +396 } +397 } +398 self.trigger_holepunching().await; +399 } +400 tx.send(PathsWatchable { +401 open_paths: pub_open_paths, +402 selected_path: self.selected_path.clone(), +403 }) +404 .ok(); +405 } +406 +407 /// Handles [`EndpointStateMessage::AddEndpointAddr`]. +408 fn handle_msg_add_endpoint_addr(&mut self, addr: EndpointAddr, source: Source) { +409 for sockaddr in addr.ip_addrs() { +410 let addr = transports::Addr::from(sockaddr); +411 self.paths +412 .entry(addr) +413 .or_default() +414 .sources +415 .insert(source.clone(), Instant::now()); +416 } +417 for relay_url in addr.relay_urls() { +418 let addr = transports::Addr::from((relay_url.clone(), self.endpoint_id)); +419 self.paths +420 .entry(addr) +421 .or_default() +422 .sources +423 .insert(source.clone(), Instant::now()); +424 } +425 trace!("added addressing information"); +426 } +427 +428 /// Handles [`EndpointStateMessage::CallMeMaybeReceived`]. +429 async fn handle_msg_call_me_maybe_received(&mut self, msg: disco::CallMeMaybe) { +430 event!( +431 target: "iroh::_events::call_me_maybe::recv", +432 Level::DEBUG, +433 remote = %self.endpoint_id.fmt_short(), +434 addrs = ?msg.my_numbers, +435 ); +436 let now = Instant::now(); +437 for addr in msg.my_numbers { +438 let dst = transports::Addr::Ip(addr); +439 let ping = disco::Ping::new(self.local_endpoint_id); 440 -441 event!( -442 target: "iroh::_events::ping::sent", -443 Level::DEBUG, -444 remote = %self.endpoint_id.fmt_short(), -445 ?dst, -446 ); -447 self.send_disco_message(dst, disco::Message::Ping(ping)) -448 .await; -449 } -450 } -451 -452 /// Handles [`EndpointStateMessage::PingReceived`]. -453 async fn handle_msg_ping_received(&mut self, ping: disco::Ping, src: transports::Addr) { -454 let transports::Addr::Ip(addr) = src else { -455 warn!("received ping via relay transport, ignored"); -456 return; -457 }; -458 event!( -459 target: "iroh::_events::ping::recv", -460 Level::DEBUG, -461 remote = %self.endpoint_id.fmt_short(), -462 ?src, -463 txn = ?ping.tx_id, -464 ); -465 let pong = disco::Pong { -466 tx_id: ping.tx_id, -467 ping_observed_addr: addr.into(), -468 }; -469 event!( -470 target: "iroh::_events::pong::sent", -471 Level::DEBUG, -472 remote = %self.endpoint_id.fmt_short(), -473 dst = ?src, -474 txn = ?pong.tx_id, -475 ); -476 self.send_disco_message(src.clone(), disco::Message::Pong(pong)) -477 .await; -478 -479 let path = self.paths.entry(src).or_default(); -480 path.sources.insert(Source::Ping, Instant::now()); -481 -482 trace!("ping received, triggering holepunching"); -483 self.trigger_holepunching().await; -484 } +441 let path = self.paths.entry(dst.clone()).or_default(); +442 path.sources.insert(Source::CallMeMaybe, now); +443 path.ping_sent = Some(ping.tx_id); +444 +445 event!( +446 target: "iroh::_events::ping::sent", +447 Level::DEBUG, +448 remote = %self.endpoint_id.fmt_short(), +449 ?dst, +450 ); +451 self.send_disco_message(dst, disco::Message::Ping(ping)) +452 .await; +453 } +454 } +455 +456 /// Handles [`EndpointStateMessage::PingReceived`]. +457 async fn handle_msg_ping_received(&mut self, ping: disco::Ping, src: transports::Addr) { +458 let transports::Addr::Ip(addr) = src else { +459 warn!("received ping via relay transport, ignored"); +460 return; +461 }; +462 event!( +463 target: "iroh::_events::ping::recv", +464 Level::DEBUG, +465 remote = %self.endpoint_id.fmt_short(), +466 ?src, +467 txn = ?ping.tx_id, +468 ); +469 let pong = disco::Pong { +470 tx_id: ping.tx_id, +471 ping_observed_addr: addr.into(), +472 }; +473 event!( +474 target: "iroh::_events::pong::sent", +475 Level::DEBUG, +476 remote = %self.endpoint_id.fmt_short(), +477 dst = ?src, +478 txn = ?pong.tx_id, +479 ); +480 self.send_disco_message(src.clone(), disco::Message::Pong(pong)) +481 .await; +482 +483 let path = self.paths.entry(src).or_default(); +484 path.sources.insert(Source::Ping, Instant::now()); 485 -486 /// Handles [`EndpointStateMessage::PongReceived`]. -487 fn handle_msg_pong_received(&mut self, pong: disco::Pong, src: transports::Addr) { -488 let Some(state) = self.paths.get(&src) else { -489 warn!(path = ?src, ?self.paths, "ignoring DISCO Pong for unknown path"); -490 return; -491 }; -492 if state.ping_sent != Some(pong.tx_id) { -493 debug!(path = ?src, ?state.ping_sent, pong_tx = ?pong.tx_id, -494 "ignoring unknown DISCO Pong for path"); -495 return; -496 } -497 event!( -498 target: "iroh::_events::pong::recv", -499 Level::DEBUG, -500 remote_endpoint = %self.endpoint_id.fmt_short(), -501 ?src, -502 txn = ?pong.tx_id, -503 ); -504 -505 self.open_path(&src); -506 } -507 -508 /// Handles [`EndpointStateMessage::CanSend`]. -509 fn handle_msg_can_send(&self, tx: oneshot::Sender<bool>) { -510 let can_send = !self.paths.is_empty(); -511 tx.send(can_send).ok(); -512 } -513 -514 /// Handles [`EndpointStateMessage::Latency`]. -515 fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) { -516 let rtt = self.selected_path.get().and_then(|addr| { -517 for conn_state in self.connections.values() { -518 let Some(path_id) = conn_state.path_ids.get(&addr) else { -519 continue; -520 }; -521 if !conn_state.open_paths.contains_key(path_id) { -522 continue; -523 } -524 if let Some(rtt) = conn_state -525 .handle -526 .upgrade() -527 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt)) -528 { -529 return Some(rtt); -530 } -531 } -532 None -533 }); -534 tx.send(rtt).ok(); -535 } -536 -537 /// Triggers holepunching to the remote endpoint. -538 /// -539 /// This will manage the entire process of holepunching with the remote endpoint. -540 /// -541 /// - If there already is a direct connection, nothing happens. -542 /// - If there is no relay address known, nothing happens. -543 /// - If there was a recent attempt, it will schedule holepunching instead. -544 /// - Unless there are new addresses to try. -545 /// - The scheduled attempt will only run if holepunching has not yet succeeded by -546 /// then. -547 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe -548 /// message. -549 /// - A DISCO call-me-maybe message advertising our own addresses will be sent. -550 /// -551 /// If a next trigger needs to be scheduled the delay until when to call this again is -552 /// returned. -553 async fn trigger_holepunching(&mut self) { -554 const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5); -555 -556 if self.connections.is_empty() { -557 trace!("not holepunching: no connections"); -558 return; -559 } -560 -561 if self -562 .selected_path -563 .get() -564 .map(|addr| addr.is_ip()) -565 .unwrap_or_default() -566 { -567 // TODO: We should ping this path to make sure it still works. Because we now -568 // know things could be broken. -569 trace!("not holepunching: already have a direct connection"); -570 // TODO: If the latency is kind of bad we should retry holepunching at times. -571 return; -572 } -573 -574 let remote_addrs: BTreeSet<SocketAddr> = self.remote_hp_addrs(); -575 let local_addrs: BTreeSet<SocketAddr> = self -576 .local_addrs -577 .get() -578 .iter() -579 .map(|daddr| daddr.addr) -580 .collect(); -581 let new_addrs = self -582 .last_holepunch -583 .as_ref() -584 .map(|last_hp| { -585 // Addrs are allowed to disappear, but if there are new ones we need to -586 // holepunch again. -587 trace!(?last_hp, ?local_addrs, ?remote_addrs, "addrs to holepunch?"); -588 !remote_addrs.is_subset(&last_hp.remote_addrs) -589 || !local_addrs.is_subset(&last_hp.local_addrs) -590 }) -591 .unwrap_or(true); -592 if !new_addrs { -593 if let Some(ref last_hp) = self.last_holepunch { -594 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; -595 let now = Instant::now(); -596 if next_hp > now { -597 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); -598 self.scheduled_holepunch = Some(next_hp); -599 return; -600 } -601 } -602 } -603 -604 self.do_holepunching().await; -605 } -606 -607 /// Returns the remote addresses to holepunch against. -608 fn remote_hp_addrs(&self) -> BTreeSet<SocketAddr> { -609 const CALL_ME_MAYBE_VALIDITY: Duration = Duration::from_secs(30); +486 trace!("ping received, triggering holepunching"); +487 self.trigger_holepunching().await; +488 } +489 +490 /// Handles [`EndpointStateMessage::PongReceived`]. +491 fn handle_msg_pong_received(&mut self, pong: disco::Pong, src: transports::Addr) { +492 let Some(state) = self.paths.get(&src) else { +493 warn!(path = ?src, ?self.paths, "ignoring DISCO Pong for unknown path"); +494 return; +495 }; +496 if state.ping_sent != Some(pong.tx_id) { +497 debug!(path = ?src, ?state.ping_sent, pong_tx = ?pong.tx_id, +498 "ignoring unknown DISCO Pong for path"); +499 return; +500 } +501 event!( +502 target: "iroh::_events::pong::recv", +503 Level::DEBUG, +504 remote_endpoint = %self.endpoint_id.fmt_short(), +505 ?src, +506 txn = ?pong.tx_id, +507 ); +508 +509 self.open_path(&src); +510 } +511 +512 /// Handles [`EndpointStateMessage::CanSend`]. +513 fn handle_msg_can_send(&self, tx: oneshot::Sender<bool>) { +514 let can_send = !self.paths.is_empty(); +515 tx.send(can_send).ok(); +516 } +517 +518 /// Handles [`EndpointStateMessage::Latency`]. +519 fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) { +520 let rtt = self.selected_path.get().and_then(|addr| { +521 for conn_state in self.connections.values() { +522 let Some(path_id) = conn_state.path_ids.get(&addr) else { +523 continue; +524 }; +525 if !conn_state.open_paths.contains_key(path_id) { +526 continue; +527 } +528 if let Some(rtt) = conn_state +529 .handle +530 .upgrade() +531 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt)) +532 { +533 return Some(rtt); +534 } +535 } +536 None +537 }); +538 tx.send(rtt).ok(); +539 } +540 +541 /// Triggers holepunching to the remote endpoint. +542 /// +543 /// This will manage the entire process of holepunching with the remote endpoint. +544 /// +545 /// - If there already is a direct connection, nothing happens. +546 /// - If there is no relay address known, nothing happens. +547 /// - If there was a recent attempt, it will schedule holepunching instead. +548 /// - Unless there are new addresses to try. +549 /// - The scheduled attempt will only run if holepunching has not yet succeeded by +550 /// then. +551 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe +552 /// message. +553 /// - A DISCO call-me-maybe message advertising our own addresses will be sent. +554 /// +555 /// If a next trigger needs to be scheduled the delay until when to call this again is +556 /// returned. +557 async fn trigger_holepunching(&mut self) { +558 const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5); +559 +560 if self.connections.is_empty() { +561 trace!("not holepunching: no connections"); +562 return; +563 } +564 +565 if self +566 .selected_path +567 .get() +568 .map(|addr| addr.is_ip()) +569 .unwrap_or_default() +570 { +571 // TODO: We should ping this path to make sure it still works. Because we now +572 // know things could be broken. +573 trace!("not holepunching: already have a direct connection"); +574 // TODO: If the latency is kind of bad we should retry holepunching at times. +575 return; +576 } +577 +578 let remote_addrs: BTreeSet<SocketAddr> = self.remote_hp_addrs(); +579 let local_addrs: BTreeSet<SocketAddr> = self +580 .local_addrs +581 .get() +582 .iter() +583 .map(|daddr| daddr.addr) +584 .collect(); +585 let new_addrs = self +586 .last_holepunch +587 .as_ref() +588 .map(|last_hp| { +589 // Addrs are allowed to disappear, but if there are new ones we need to +590 // holepunch again. +591 trace!(?last_hp, ?local_addrs, ?remote_addrs, "addrs to holepunch?"); +592 !remote_addrs.is_subset(&last_hp.remote_addrs) +593 || !local_addrs.is_subset(&last_hp.local_addrs) +594 }) +595 .unwrap_or(true); +596 if !new_addrs { +597 if let Some(ref last_hp) = self.last_holepunch { +598 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; +599 let now = Instant::now(); +600 if next_hp > now { +601 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); +602 self.scheduled_holepunch = Some(next_hp); +603 return; +604 } +605 } +606 } +607 +608 self.do_holepunching().await; +609 } 610 -611 self.paths -612 .iter() -613 .filter_map(|(addr, state)| match addr { -614 transports::Addr::Ip(socket_addr) => Some((socket_addr, state)), -615 transports::Addr::Relay(_, _) => None, -616 }) -617 .filter_map(|(addr, state)| { -618 if state -619 .sources -620 .get(&Source::CallMeMaybe) -621 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY) -622 .unwrap_or_default() -623 || state -624 .sources -625 .get(&Source::Ping) -626 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY) -627 .unwrap_or_default() -628 { -629 Some(*addr) -630 } else { -631 None -632 } -633 }) -634 .collect() -635 } -636 -637 /// Unconditionally perform holepunching. -638 /// -639 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe -640 /// message. -641 /// - A DISCO call-me-maybe message advertising our own addresses will be sent. -642 #[instrument(skip_all)] -643 async fn do_holepunching(&mut self) { -644 let Some(relay_addr) = self -645 .paths -646 .iter() -647 .filter_map(|(addr, _)| match addr { -648 transports::Addr::Ip(_) => None, -649 transports::Addr::Relay(_, _) => Some(addr), -650 }) -651 .next() -652 .cloned() -653 else { -654 warn!("holepunching requested but have no relay address"); -655 return; -656 }; -657 let remote_addrs = self.remote_hp_addrs(); -658 -659 // Send DISCO Ping messages to all CallMeMaybe-advertised paths. -660 for dst in remote_addrs.iter() { -661 let msg = disco::Ping::new(self.local_endpoint_id); -662 event!( -663 target: "iroh::_events::ping::sent", -664 Level::DEBUG, -665 remote = %self.endpoint_id.fmt_short(), -666 ?dst, -667 txn = ?msg.tx_id, -668 ); -669 let addr = transports::Addr::Ip(*dst); -670 self.paths.entry(addr.clone()).or_default().ping_sent = Some(msg.tx_id); -671 self.send_disco_message(addr, disco::Message::Ping(msg)) -672 .await; -673 } -674 -675 // Send the DISCO CallMeMaybe message over the relay. -676 let my_numbers: Vec<SocketAddr> = self -677 .local_addrs -678 .get() -679 .iter() -680 .map(|daddr| daddr.addr) -681 .collect(); -682 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect(); -683 let msg = disco::CallMeMaybe { my_numbers }; -684 event!( -685 target: "iroh::_events::call_me_maybe::sent", -686 Level::DEBUG, -687 remote = %self.endpoint_id.fmt_short(), -688 dst = ?relay_addr, -689 my_numbers = ?msg.my_numbers, -690 ); -691 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg)) -692 .await; -693 -694 self.last_holepunch = Some(HolepunchAttempt { -695 when: Instant::now(), -696 local_addrs, -697 remote_addrs, -698 }); -699 } -700 -701 /// Sends a DISCO message to the remote endpoint this actor manages. -702 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))] -703 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) { -704 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg); -705 let transmit = transports::OwnedTransmit { -706 ecn: None, -707 contents: pkt, -708 segment_size: None, -709 }; -710 let counter = match dst { -711 transports::Addr::Ip(_) => &self.metrics.send_disco_udp, -712 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay, +611 /// Returns the remote addresses to holepunch against. +612 fn remote_hp_addrs(&self) -> BTreeSet<SocketAddr> { +613 const CALL_ME_MAYBE_VALIDITY: Duration = Duration::from_secs(30); +614 +615 self.paths +616 .iter() +617 .filter_map(|(addr, state)| match addr { +618 transports::Addr::Ip(socket_addr) => Some((socket_addr, state)), +619 transports::Addr::Relay(_, _) => None, +620 }) +621 .filter_map(|(addr, state)| { +622 if state +623 .sources +624 .get(&Source::CallMeMaybe) +625 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY) +626 .unwrap_or_default() +627 || state +628 .sources +629 .get(&Source::Ping) +630 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY) +631 .unwrap_or_default() +632 { +633 Some(*addr) +634 } else { +635 None +636 } +637 }) +638 .collect() +639 } +640 +641 /// Unconditionally perform holepunching. +642 /// +643 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe +644 /// message. +645 /// - A DISCO call-me-maybe message advertising our own addresses will be sent. +646 #[instrument(skip_all)] +647 async fn do_holepunching(&mut self) { +648 let Some(relay_addr) = self +649 .paths +650 .iter() +651 .filter_map(|(addr, _)| match addr { +652 transports::Addr::Ip(_) => None, +653 transports::Addr::Relay(_, _) => Some(addr), +654 }) +655 .next() +656 .cloned() +657 else { +658 warn!("holepunching requested but have no relay address"); +659 return; +660 }; +661 let remote_addrs = self.remote_hp_addrs(); +662 +663 // Send DISCO Ping messages to all CallMeMaybe-advertised paths. +664 for dst in remote_addrs.iter() { +665 let msg = disco::Ping::new(self.local_endpoint_id); +666 event!( +667 target: "iroh::_events::ping::sent", +668 Level::DEBUG, +669 remote = %self.endpoint_id.fmt_short(), +670 ?dst, +671 txn = ?msg.tx_id, +672 ); +673 let addr = transports::Addr::Ip(*dst); +674 self.paths.entry(addr.clone()).or_default().ping_sent = Some(msg.tx_id); +675 self.send_disco_message(addr, disco::Message::Ping(msg)) +676 .await; +677 } +678 +679 // Send the DISCO CallMeMaybe message over the relay. +680 let my_numbers: Vec<SocketAddr> = self +681 .local_addrs +682 .get() +683 .iter() +684 .map(|daddr| daddr.addr) +685 .collect(); +686 let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect(); +687 let msg = disco::CallMeMaybe { my_numbers }; +688 event!( +689 target: "iroh::_events::call_me_maybe::sent", +690 Level::DEBUG, +691 remote = %self.endpoint_id.fmt_short(), +692 dst = ?relay_addr, +693 my_numbers = ?msg.my_numbers, +694 ); +695 self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg)) +696 .await; +697 +698 self.last_holepunch = Some(HolepunchAttempt { +699 when: Instant::now(), +700 local_addrs, +701 remote_addrs, +702 }); +703 } +704 +705 /// Sends a DISCO message to the remote endpoint this actor manages. +706 #[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))] +707 async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) { +708 let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg); +709 let transmit = transports::OwnedTransmit { +710 ecn: None, +711 contents: pkt, +712 segment_size: None, 713 }; -714 match self.transports_sender.send((dst, transmit).into()).await { -715 Ok(()) => { -716 trace!("sent"); -717 counter.inc(); -718 } -719 Err(err) => { -720 warn!("failed to send disco message: {err:#}"); -721 } -722 } -723 } -724 -725 /// Open the path on all connections. -726 /// -727 /// This goes through all the connections for which we are the client, and makes sure -728 /// the path exists, or opens it. -729 #[instrument(level = "warn", skip(self))] -730 fn open_path(&mut self, open_addr: &transports::Addr) { -731 let path_status = match open_addr { -732 transports::Addr::Ip(_) => PathStatus::Available, -733 transports::Addr::Relay(_, _) => PathStatus::Backup, -734 }; -735 let quic_addr = match &open_addr { -736 transports::Addr::Ip(socket_addr) => *socket_addr, -737 transports::Addr::Relay(relay_url, eid) => self -738 .relay_mapped_addrs -739 .get(&(relay_url.clone(), *eid)) -740 .private_socket_addr(), -741 }; -742 -743 for (conn_id, conn_state) in self.connections.iter_mut() { -744 if conn_state.path_ids.contains_key(open_addr) { -745 continue; -746 } -747 let Some(conn) = conn_state.handle.upgrade() else { -748 continue; -749 }; -750 if conn.side().is_server() { -751 continue; -752 } -753 let fut = conn.open_path_ensure(quic_addr, path_status); -754 match fut.path_id() { -755 Some(path_id) => { -756 trace!(?conn_id, ?path_id, "opening new path"); -757 conn_state.add_path(open_addr.clone(), path_id); -758 } -759 None => { -760 let ret = now_or_never(fut); -761 match ret { -762 Some(Err(PathError::RemoteCidsExhausted)) => { -763 self.scheduled_open_path = -764 Some(Instant::now() + Duration::from_millis(333)); -765 self.pending_open_paths.push_back(open_addr.clone()); -766 trace!(?open_addr, "scheduling open_path"); -767 } -768 _ => warn!(?ret, "Opening path failed"), -769 } -770 } -771 } -772 } -773 } -774 -775 #[instrument(skip(self))] -776 fn handle_path_event( -777 &mut self, -778 conn_id: ConnId, -779 event: Result<PathEvent, BroadcastStreamRecvError>, -780 ) { -781 let Ok(event) = event else { -782 warn!("missed a PathEvent, EndpointStateActor lagging"); -783 // TODO: Is it possible to recover using the sync APIs to figure out what the -784 // state of the connection and it's paths are? -785 return; -786 }; -787 let Some(conn_state) = self.connections.get_mut(&conn_id) else { -788 trace!("event for removed connection"); -789 return; +714 let counter = match dst { +715 transports::Addr::Ip(_) => &self.metrics.send_disco_udp, +716 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay, +717 }; +718 match self.send_datagram(dst, transmit).await { +719 Ok(()) => { +720 trace!("sent"); +721 counter.inc(); +722 } +723 Err(err) => { +724 warn!("failed to send disco message: {err:#}"); +725 } +726 } +727 } +728 +729 /// Open the path on all connections. +730 /// +731 /// This goes through all the connections for which we are the client, and makes sure +732 /// the path exists, or opens it. +733 #[instrument(level = "warn", skip(self))] +734 fn open_path(&mut self, open_addr: &transports::Addr) { +735 let path_status = match open_addr { +736 transports::Addr::Ip(_) => PathStatus::Available, +737 transports::Addr::Relay(_, _) => PathStatus::Backup, +738 }; +739 let quic_addr = match &open_addr { +740 transports::Addr::Ip(socket_addr) => *socket_addr, +741 transports::Addr::Relay(relay_url, eid) => self +742 .relay_mapped_addrs +743 .get(&(relay_url.clone(), *eid)) +744 .private_socket_addr(), +745 }; +746 +747 for (conn_id, conn_state) in self.connections.iter_mut() { +748 if conn_state.path_ids.contains_key(open_addr) { +749 continue; +750 } +751 let Some(conn) = conn_state.handle.upgrade() else { +752 continue; +753 }; +754 if conn.side().is_server() { +755 continue; +756 } +757 let fut = conn.open_path_ensure(quic_addr, path_status); +758 match fut.path_id() { +759 Some(path_id) => { +760 trace!(?conn_id, ?path_id, "opening new path"); +761 conn_state.add_path(open_addr.clone(), path_id); +762 } +763 None => { +764 let ret = now_or_never(fut); +765 match ret { +766 Some(Err(PathError::RemoteCidsExhausted)) => { +767 self.scheduled_open_path = +768 Some(Instant::now() + Duration::from_millis(333)); +769 self.pending_open_paths.push_back(open_addr.clone()); +770 trace!(?open_addr, "scheduling open_path"); +771 } +772 _ => warn!(?ret, "Opening path failed"), +773 } +774 } +775 } +776 } +777 } +778 +779 #[instrument(skip(self))] +780 fn handle_path_event( +781 &mut self, +782 conn_id: ConnId, +783 event: Result<PathEvent, BroadcastStreamRecvError>, +784 ) { +785 let Ok(event) = event else { +786 warn!("missed a PathEvent, EndpointStateActor lagging"); +787 // TODO: Is it possible to recover using the sync APIs to figure out what the +788 // state of the connection and it's paths are? +789 return; 790 }; -791 let Some(conn) = conn_state.handle.upgrade() else { -792 trace!("event for closed connection"); +791 let Some(conn_state) = self.connections.get_mut(&conn_id) else { +792 trace!("event for removed connection"); 793 return; 794 }; -795 trace!("path event"); -796 match event { -797 PathEvent::Opened { id: path_id } => { -798 let Some(path) = conn.path(path_id) else { -799 trace!("path open event for unknown path"); -800 return; -801 }; -802 // TODO: We configure this as defaults when we setup the endpoint, do we -803 // really need to duplicate this? -804 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); -805 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); -806 -807 if let Ok(socketaddr) = path.remote_address() -808 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -809 { -810 event!( -811 target: "iroh::_events::path::open", -812 Level::DEBUG, -813 remote = %self.endpoint_id.fmt_short(), -814 ?path_remote, -815 ?conn_id, -816 ?path_id, -817 ); -818 conn_state.add_open_path(path_remote.clone(), path_id); -819 self.paths -820 .entry(path_remote.clone()) -821 .or_default() -822 .sources -823 .insert(Source::Connection, Instant::now()); -824 } -825 -826 self.select_path(); -827 } -828 PathEvent::Abandoned { id, path_stats } => { -829 trace!(?path_stats, "path abandoned"); -830 // This is the last event for this path. -831 conn_state.remove_path(&id); -832 } -833 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { -834 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { -835 debug!("path not in path_id_map"); -836 return; -837 }; -838 event!( -839 target: "iroh::_events::path::closed", -840 Level::DEBUG, -841 remote = %self.endpoint_id.fmt_short(), -842 ?path_remote, -843 ?conn_id, -844 path_id = ?id, -845 ); -846 conn_state.remove_open_path(&id); -847 -848 // If one connection closes this path, close it on all connections. -849 for (conn_id, conn_state) in self.connections.iter_mut() { -850 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { -851 continue; -852 }; -853 let Some(conn) = conn_state.handle.upgrade() else { -854 continue; -855 }; -856 if let Some(path) = conn.path(*path_id) { -857 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); -858 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { -859 trace!( -860 ?path_remote, -861 ?conn_id, -862 ?path_id, -863 "path close failed: {err:#}" -864 ); -865 } -866 } -867 } -868 } -869 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { -870 // Nothing to do for these events. -871 } -872 } -873 } -874 -875 /// Selects the path with the lowest RTT, prefers direct paths. -876 /// -877 /// If there are direct paths, this selects the direct path with the lowest RTT. If -878 /// there are only relay paths, the relay path with the lowest RTT is chosen. -879 /// -880 /// The selected path is added to any connections which do not yet have it. Any unused -881 /// direct paths are closed for all connections. -882 #[instrument(skip_all)] -883 fn select_path(&mut self) { -884 // Find the lowest RTT across all connections for each open path. The long way, so -885 // we get to log *all* RTTs. -886 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); -887 for conn_state in self.connections.values() { -888 let Some(conn) = conn_state.handle.upgrade() else { -889 continue; -890 }; -891 for (path_id, addr) in conn_state.open_paths.iter() { -892 if let Some(stats) = conn.path_stats(*path_id) { -893 all_path_rtts -894 .entry(addr.clone()) -895 .or_default() -896 .push(stats.rtt); -897 } -898 } -899 } -900 trace!(?all_path_rtts, "dumping all path RTTs"); -901 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts -902 .into_iter() -903 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) -904 .collect(); -905 -906 // Find the fastest direct or relay path. -907 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); -908 let direct_path = path_rtts -909 .iter() -910 .filter(|(addr, _rtt)| addr.is_ip()) -911 .map(|(addr, rtt)| { -912 if addr.is_ipv4() { -913 (*rtt + IPV6_RTT_ADVANTAGE, addr) -914 } else { -915 (*rtt, addr) -916 } -917 }) -918 .min(); -919 let selected_path = direct_path.or_else(|| { -920 // Find the fasted relay path. -921 path_rtts -922 .iter() -923 .filter(|(addr, _rtt)| addr.is_relay()) -924 .map(|(addr, rtt)| (*rtt, addr)) -925 .min() -926 }); -927 if let Some((rtt, addr)) = selected_path { -928 let prev = self.selected_path.set(Some(addr.clone())); -929 if prev.is_ok() { -930 debug!(?addr, ?rtt, ?prev, "selected new path"); -931 } -932 self.open_path(addr); -933 self.close_redundant_paths(addr); -934 } -935 } -936 -937 /// Closes any direct paths not selected. -938 /// -939 /// Makes sure not to close the last direct path. Relay paths are never closed -940 /// currently, because we only have one relay path at this time. -941 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new -942 // paths and immediately call this. But the new paths are probably not yet open on -943 // all connections. -944 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { -945 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); -946 -947 for (conn_id, conn_state) in self.connections.iter() { -948 for (path_id, path_remote) in conn_state -949 .open_paths -950 .iter() -951 .filter(|(_, addr)| addr.is_ip()) -952 .filter(|(_, addr)| *addr != selected_path) -953 { -954 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { -955 continue; // Do not close the last direct path. -956 } -957 if let Some(path) = conn_state -958 .handle -959 .upgrade() -960 .and_then(|conn| conn.path(*path_id)) -961 { -962 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); -963 match path.close(APPLICATION_ABANDON_PATH.into()) { -964 Err(quinn_proto::ClosePathError::LastOpenPath) => { -965 error!("could not close last open path"); -966 } -967 Err(quinn_proto::ClosePathError::ClosedPath) => { -968 // We already closed this. -969 } -970 Ok(_fut) => { -971 // We will handle the event in Self::handle_path_events. -972 } -973 } -974 } -975 } -976 } -977 } -978} -979 -980/// Messages to send to the [`EndpointStateActor`]. -981#[derive(derive_more::Debug)] -982pub(crate) enum EndpointStateMessage { -983 /// Sends a datagram to all known paths. -984 /// -985 /// Used to send QUIC Initial packets. If there is no working direct path this will -986 /// trigger holepunching. -987 /// -988 /// This is not acceptable to use on the normal send path, as it is an async send -989 /// operation with a bunch more copying. So it should only be used for sending QUIC -990 /// Initial packets. -991 #[debug("SendDatagram(..)")] -992 SendDatagram(OwnedTransmit), -993 /// Adds an active connection to this remote endpoint. -994 /// -995 /// The connection will now be managed by this actor. Holepunching will happen when -996 /// needed, any new paths discovered via holepunching will be added. And closed paths -997 /// will be removed etc. -998 #[debug("AddConnection(..)")] -999 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatchable>), -1000 /// Adds a [`EndpointAddr`] with locations where the endpoint might be reachable. -1001 AddEndpointAddr(EndpointAddr, Source), -1002 /// Process a received DISCO CallMeMaybe message. -1003 CallMeMaybeReceived(disco::CallMeMaybe), -1004 /// Process a received DISCO Ping message. -1005 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)] -1006 PingReceived(disco::Ping, transports::Addr), -1007 /// Process a received DISCO Pong message. -1008 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)] -1009 PongReceived(disco::Pong, transports::Addr), -1010 /// Asks if there is any possible path that could be used. -1011 /// -1012 /// This does not mean there is any guarantee that the remote endpoint is reachable. -1013 #[debug("CanSend(..)")] -1014 CanSend(oneshot::Sender<bool>), -1015 /// Returns the current latency to the remote endpoint. -1016 /// -1017 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. -1018 #[debug("Latency(..)")] -1019 Latency(oneshot::Sender<Option<Duration>>), -1020} -1021 -1022/// A handle to a [`EndpointStateActor`]. -1023/// -1024/// Dropping this will stop the actor. -1025#[derive(Debug)] -1026pub(super) struct EndpointStateHandle { -1027 /// Sender for the channel into the [`EndpointStateActor`]. -1028 pub(super) sender: mpsc::Sender<EndpointStateMessage>, -1029 _task: AbortOnDropHandle<()>, -1030} -1031 -1032/// Information about a holepunch attempt. -1033#[derive(Debug)] -1034struct HolepunchAttempt { -1035 when: Instant, -1036 /// The set of local addresses which could take part in holepunching. -1037 /// -1038 /// This does not mean every address here participated in the holepunching. E.g. we -1039 /// could have tried only a sub-set of the addresses because a previous attempt already -1040 /// covered part of the range. +795 let Some(conn) = conn_state.handle.upgrade() else { +796 trace!("event for closed connection"); +797 return; +798 }; +799 trace!("path event"); +800 match event { +801 PathEvent::Opened { id: path_id } => { +802 let Some(path) = conn.path(path_id) else { +803 trace!("path open event for unknown path"); +804 return; +805 }; +806 // TODO: We configure this as defaults when we setup the endpoint, do we +807 // really need to duplicate this? +808 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); +809 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok(); +810 +811 if let Ok(socketaddr) = path.remote_address() +812 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +813 { +814 event!( +815 target: "iroh::_events::path::open", +816 Level::DEBUG, +817 remote = %self.endpoint_id.fmt_short(), +818 ?path_remote, +819 ?conn_id, +820 ?path_id, +821 ); +822 conn_state.add_open_path(path_remote.clone(), path_id); +823 self.paths +824 .entry(path_remote.clone()) +825 .or_default() +826 .sources +827 .insert(Source::Connection, Instant::now()); +828 } +829 +830 self.select_path(); +831 } +832 PathEvent::Abandoned { id, path_stats } => { +833 trace!(?path_stats, "path abandoned"); +834 // This is the last event for this path. +835 conn_state.remove_path(&id); +836 } +837 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => { +838 let Some(path_remote) = conn_state.paths.get(&id).cloned() else { +839 debug!("path not in path_id_map"); +840 return; +841 }; +842 event!( +843 target: "iroh::_events::path::closed", +844 Level::DEBUG, +845 remote = %self.endpoint_id.fmt_short(), +846 ?path_remote, +847 ?conn_id, +848 path_id = ?id, +849 ); +850 conn_state.remove_open_path(&id); +851 +852 // If one connection closes this path, close it on all connections. +853 for (conn_id, conn_state) in self.connections.iter_mut() { +854 let Some(path_id) = conn_state.path_ids.get(&path_remote) else { +855 continue; +856 }; +857 let Some(conn) = conn_state.handle.upgrade() else { +858 continue; +859 }; +860 if let Some(path) = conn.path(*path_id) { +861 trace!(?path_remote, ?conn_id, ?path_id, "closing path"); +862 if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) { +863 trace!( +864 ?path_remote, +865 ?conn_id, +866 ?path_id, +867 "path close failed: {err:#}" +868 ); +869 } +870 } +871 } +872 } +873 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => { +874 // Nothing to do for these events. +875 } +876 } +877 } +878 +879 /// Selects the path with the lowest RTT, prefers direct paths. +880 /// +881 /// If there are direct paths, this selects the direct path with the lowest RTT. If +882 /// there are only relay paths, the relay path with the lowest RTT is chosen. +883 /// +884 /// The selected path is added to any connections which do not yet have it. Any unused +885 /// direct paths are closed for all connections. +886 #[instrument(skip_all)] +887 fn select_path(&mut self) { +888 // Find the lowest RTT across all connections for each open path. The long way, so +889 // we get to log *all* RTTs. +890 let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default(); +891 for conn_state in self.connections.values() { +892 let Some(conn) = conn_state.handle.upgrade() else { +893 continue; +894 }; +895 for (path_id, addr) in conn_state.open_paths.iter() { +896 if let Some(stats) = conn.path_stats(*path_id) { +897 all_path_rtts +898 .entry(addr.clone()) +899 .or_default() +900 .push(stats.rtt); +901 } +902 } +903 } +904 trace!(?all_path_rtts, "dumping all path RTTs"); +905 let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts +906 .into_iter() +907 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt))) +908 .collect(); +909 +910 // Find the fastest direct or relay path. +911 const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3); +912 let direct_path = path_rtts +913 .iter() +914 .filter(|(addr, _rtt)| addr.is_ip()) +915 .map(|(addr, rtt)| { +916 if addr.is_ipv4() { +917 (*rtt + IPV6_RTT_ADVANTAGE, addr) +918 } else { +919 (*rtt, addr) +920 } +921 }) +922 .min(); +923 let selected_path = direct_path.or_else(|| { +924 // Find the fasted relay path. +925 path_rtts +926 .iter() +927 .filter(|(addr, _rtt)| addr.is_relay()) +928 .map(|(addr, rtt)| (*rtt, addr)) +929 .min() +930 }); +931 if let Some((rtt, addr)) = selected_path { +932 let prev = self.selected_path.set(Some(addr.clone())); +933 if prev.is_ok() { +934 debug!(?addr, ?rtt, ?prev, "selected new path"); +935 } +936 self.open_path(addr); +937 self.close_redundant_paths(addr); +938 } +939 } +940 +941 /// Closes any direct paths not selected. +942 /// +943 /// Makes sure not to close the last direct path. Relay paths are never closed +944 /// currently, because we only have one relay path at this time. +945 // TODO: Need to handle this on a timer as well probably. In .select_path() we open new +946 // paths and immediately call this. But the new paths are probably not yet open on +947 // all connections. +948 fn close_redundant_paths(&mut self, selected_path: &transports::Addr) { +949 debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),); +950 +951 for (conn_id, conn_state) in self.connections.iter() { +952 for (path_id, path_remote) in conn_state +953 .open_paths +954 .iter() +955 .filter(|(_, addr)| addr.is_ip()) +956 .filter(|(_, addr)| *addr != selected_path) +957 { +958 if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 { +959 continue; // Do not close the last direct path. +960 } +961 if let Some(path) = conn_state +962 .handle +963 .upgrade() +964 .and_then(|conn| conn.path(*path_id)) +965 { +966 trace!(?path_remote, ?conn_id, ?path_id, "closing direct path"); +967 match path.close(APPLICATION_ABANDON_PATH.into()) { +968 Err(quinn_proto::ClosePathError::LastOpenPath) => { +969 error!("could not close last open path"); +970 } +971 Err(quinn_proto::ClosePathError::ClosedPath) => { +972 // We already closed this. +973 } +974 Ok(_fut) => { +975 // We will handle the event in Self::handle_path_events. +976 } +977 } +978 } +979 } +980 } +981 } +982} +983 +984/// Messages to send to the [`EndpointStateActor`]. +985#[derive(derive_more::Debug)] +986pub(crate) enum EndpointStateMessage { +987 /// Sends a datagram to all known paths. +988 /// +989 /// Used to send QUIC Initial packets. If there is no working direct path this will +990 /// trigger holepunching. +991 /// +992 /// This is not acceptable to use on the normal send path, as it is an async send +993 /// operation with a bunch more copying. So it should only be used for sending QUIC +994 /// Initial packets. +995 #[debug("SendDatagram(..)")] +996 SendDatagram(OwnedTransmit), +997 /// Adds an active connection to this remote endpoint. +998 /// +999 /// The connection will now be managed by this actor. Holepunching will happen when +1000 /// needed, any new paths discovered via holepunching will be added. And closed paths +1001 /// will be removed etc. +1002 #[debug("AddConnection(..)")] +1003 AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatchable>), +1004 /// Adds a [`EndpointAddr`] with locations where the endpoint might be reachable. +1005 AddEndpointAddr(EndpointAddr, Source), +1006 /// Process a received DISCO CallMeMaybe message. +1007 CallMeMaybeReceived(disco::CallMeMaybe), +1008 /// Process a received DISCO Ping message. +1009 #[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)] +1010 PingReceived(disco::Ping, transports::Addr), +1011 /// Process a received DISCO Pong message. +1012 #[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)] +1013 PongReceived(disco::Pong, transports::Addr), +1014 /// Asks if there is any possible path that could be used. +1015 /// +1016 /// This does not mean there is any guarantee that the remote endpoint is reachable. +1017 #[debug("CanSend(..)")] +1018 CanSend(oneshot::Sender<bool>), +1019 /// Returns the current latency to the remote endpoint. +1020 /// +1021 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency. +1022 #[debug("Latency(..)")] +1023 Latency(oneshot::Sender<Option<Duration>>), +1024} +1025 +1026/// A handle to a [`EndpointStateActor`]. +1027/// +1028/// Dropping this will stop the actor. +1029#[derive(Debug)] +1030pub(super) struct EndpointStateHandle { +1031 /// Sender for the channel into the [`EndpointStateActor`]. +1032 pub(super) sender: mpsc::Sender<EndpointStateMessage>, +1033 _task: AbortOnDropHandle<()>, +1034} +1035 +1036/// Information about a holepunch attempt. +1037#[derive(Debug)] +1038struct HolepunchAttempt { +1039 when: Instant, +1040 /// The set of local addresses which could take part in holepunching. 1041 /// -1042 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we -1043 /// do not want to compare the sources of these addresses. -1044 local_addrs: BTreeSet<SocketAddr>, -1045 /// The set of remote addresses which could take part in holepunching. -1046 /// -1047 /// Like `local_addrs` we may not have used them. -1048 remote_addrs: BTreeSet<SocketAddr>, -1049} -1050 -1051/// The type of connection we have to the endpoint. -1052#[derive(derive_more::Display, Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -1053pub enum ConnectionType { -1054 /// Direct UDP connection -1055 #[display("direct({_0})")] -1056 Direct(SocketAddr), -1057 /// Relay connection over relay -1058 #[display("relay({_0})")] -1059 Relay(RelayUrl), -1060 /// Both a UDP and a relay connection are used. -1061 /// -1062 /// This is the case if we do have a UDP address, but are missing a recent confirmation that -1063 /// the address works. -1064 #[display("mixed(udp: {_0}, relay: {_1})")] -1065 Mixed(SocketAddr, RelayUrl), -1066 /// We have no verified connection to this PublicKey -1067 #[default] -1068 #[display("none")] -1069 None, -1070} -1071 -1072/// Newtype to track Connections. -1073/// -1074/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid -1075/// for active connections. -1076#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -1077struct ConnId(usize); -1078 -1079/// State about one connection. -1080#[derive(Debug)] -1081struct ConnectionState { -1082 /// Weak handle to the connection. -1083 handle: WeakConnectionHandle, -1084 /// The information we publish to users about the paths used in this connection. -1085 pub_open_paths: Watchable<PathAddrList>, -1086 /// The paths that exist on this connection. -1087 /// -1088 /// This could be in any state, e.g. while still validating the path or already closed -1089 /// but not yet fully removed from the connection. This exists as long as Quinn knows -1090 /// about the [`PathId`]. -1091 paths: FxHashMap<PathId, transports::Addr>, -1092 /// The open paths on this connection, a subset of [`Self::paths`]. -1093 open_paths: FxHashMap<PathId, transports::Addr>, -1094 /// Reverse map of [`Self::paths]. -1095 path_ids: FxHashMap<transports::Addr, PathId>, -1096} -1097 -1098impl ConnectionState { -1099 /// Tracks a path for the connection. -1100 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { -1101 self.paths.insert(path_id, remote.clone()); -1102 self.path_ids.insert(remote, path_id); -1103 } -1104 -1105 /// Tracks an open path for the connection. -1106 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { -1107 self.paths.insert(path_id, remote.clone()); -1108 self.open_paths.insert(path_id, remote.clone()); -1109 self.path_ids.insert(remote, path_id); -1110 -1111 self.update_pub_path_info(); -1112 } -1113 -1114 /// Completely removes a path from this connection. -1115 fn remove_path(&mut self, path_id: &PathId) { -1116 if let Some(addr) = self.paths.remove(path_id) { -1117 self.path_ids.remove(&addr); -1118 } -1119 self.open_paths.remove(path_id); -1120 } -1121 -1122 /// Removes the path from the open paths. -1123 fn remove_open_path(&mut self, path_id: &PathId) { -1124 self.open_paths.remove(path_id); +1042 /// This does not mean every address here participated in the holepunching. E.g. we +1043 /// could have tried only a sub-set of the addresses because a previous attempt already +1044 /// covered part of the range. +1045 /// +1046 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we +1047 /// do not want to compare the sources of these addresses. +1048 local_addrs: BTreeSet<SocketAddr>, +1049 /// The set of remote addresses which could take part in holepunching. +1050 /// +1051 /// Like `local_addrs` we may not have used them. +1052 remote_addrs: BTreeSet<SocketAddr>, +1053} +1054 +1055/// The type of connection we have to the endpoint. +1056#[derive(derive_more::Display, Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +1057pub enum ConnectionType { +1058 /// Direct UDP connection +1059 #[display("direct({_0})")] +1060 Direct(SocketAddr), +1061 /// Relay connection over relay +1062 #[display("relay({_0})")] +1063 Relay(RelayUrl), +1064 /// Both a UDP and a relay connection are used. +1065 /// +1066 /// This is the case if we do have a UDP address, but are missing a recent confirmation that +1067 /// the address works. +1068 #[display("mixed(udp: {_0}, relay: {_1})")] +1069 Mixed(SocketAddr, RelayUrl), +1070 /// We have no verified connection to this PublicKey +1071 #[default] +1072 #[display("none")] +1073 None, +1074} +1075 +1076/// Newtype to track Connections. +1077/// +1078/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid +1079/// for active connections. +1080#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +1081struct ConnId(usize); +1082 +1083/// State about one connection. +1084#[derive(Debug)] +1085struct ConnectionState { +1086 /// Weak handle to the connection. +1087 handle: WeakConnectionHandle, +1088 /// The information we publish to users about the paths used in this connection. +1089 pub_open_paths: Watchable<PathAddrList>, +1090 /// The paths that exist on this connection. +1091 /// +1092 /// This could be in any state, e.g. while still validating the path or already closed +1093 /// but not yet fully removed from the connection. This exists as long as Quinn knows +1094 /// about the [`PathId`]. +1095 paths: FxHashMap<PathId, transports::Addr>, +1096 /// The open paths on this connection, a subset of [`Self::paths`]. +1097 open_paths: FxHashMap<PathId, transports::Addr>, +1098 /// Reverse map of [`Self::paths]. +1099 path_ids: FxHashMap<transports::Addr, PathId>, +1100} +1101 +1102impl ConnectionState { +1103 /// Tracks a path for the connection. +1104 fn add_path(&mut self, remote: transports::Addr, path_id: PathId) { +1105 self.paths.insert(path_id, remote.clone()); +1106 self.path_ids.insert(remote, path_id); +1107 } +1108 +1109 /// Tracks an open path for the connection. +1110 fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) { +1111 self.paths.insert(path_id, remote.clone()); +1112 self.open_paths.insert(path_id, remote.clone()); +1113 self.path_ids.insert(remote, path_id); +1114 +1115 self.update_pub_path_info(); +1116 } +1117 +1118 /// Completely removes a path from this connection. +1119 fn remove_path(&mut self, path_id: &PathId) { +1120 if let Some(addr) = self.paths.remove(path_id) { +1121 self.path_ids.remove(&addr); +1122 } +1123 self.open_paths.remove(path_id); +1124 } 1125 -1126 self.update_pub_path_info(); -1127 } -1128 -1129 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. -1130 /// -1131 /// [`Connection`]: crate::endpoint::Connection -1132 fn update_pub_path_info(&self) { -1133 let new = self -1134 .open_paths -1135 .iter() -1136 .map(|(path_id, remote)| { -1137 let remote = TransportAddr::from(remote.clone()); -1138 (remote, *path_id) -1139 }) -1140 .collect::<PathAddrList>(); -1141 -1142 self.pub_open_paths.set(new).ok(); -1143 } -1144} +1126 /// Removes the path from the open paths. +1127 fn remove_open_path(&mut self, path_id: &PathId) { +1128 self.open_paths.remove(path_id); +1129 +1130 self.update_pub_path_info(); +1131 } +1132 +1133 /// Sets the new [`PathInfo`] structs for the public [`Connection`]. +1134 /// +1135 /// [`Connection`]: crate::endpoint::Connection +1136 fn update_pub_path_info(&self) { +1137 let new = self +1138 .open_paths +1139 .iter() +1140 .map(|(path_id, remote)| { +1141 let remote = TransportAddr::from(remote.clone()); +1142 (remote, *path_id) +1143 }) +1144 .collect::<PathAddrList>(); 1145 -1146/// Watchables for the open paths and selected transmission path in a connection. -1147/// -1148/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. -1149/// -1150/// [`Connection`]: crate::endpoint::Connection -1151#[derive(Debug, Default, Clone)] -1152pub(crate) struct PathsWatchable { -1153 /// Watchable for the open paths (in this connection). -1154 open_paths: Watchable<PathAddrList>, -1155 /// Watchable for the selected transmission path (global for this remote endpoint). -1156 selected_path: Watchable<Option<transports::Addr>>, -1157} -1158 -1159impl PathsWatchable { -1160 pub(crate) fn watch( -1161 &self, -1162 conn_handle: WeakConnectionHandle, -1163 ) -> impl Watcher<Value = PathInfoList> { -1164 let joined_watcher = (self.open_paths.watch(), self.selected_path.watch()); -1165 joined_watcher.map(move |(open_paths, selected_path)| { -1166 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); -1167 let Some(conn) = conn_handle.upgrade() else { -1168 return PathInfoList(Default::default()); -1169 }; -1170 let list = open_paths -1171 .into_iter() -1172 .flat_map(move |(remote, path_id)| { -1173 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) -1174 }) -1175 .collect(); -1176 PathInfoList(list) -1177 }) -1178 } -1179} -1180 -1181/// List of [`PathInfo`] for the network paths of a [`Connection`]. -1182/// -1183/// This struct implements [`IntoIterator`]. -1184/// -1185/// [`Connection`]: crate::endpoint::Connection -1186#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] -1187#[debug("{_0:?}")] -1188pub struct PathInfoList(SmallVec<[PathInfo; 4]>); -1189 -1190impl PathInfoList { -1191 /// Returns an iterator over the path infos. -1192 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { -1193 self.0.iter() -1194 } -1195 -1196 /// Returns `true` if the list is empty. -1197 pub fn is_empty(&self) -> bool { -1198 self.0.is_empty() -1199 } -1200 -1201 /// Returns the number of paths. -1202 pub fn len(&self) -> usize { -1203 self.0.len() -1204 } -1205} -1206 -1207/// Information about a network path used by a [`Connection`]. -1208/// -1209/// [`Connection`]: crate::endpoint::Connection -1210#[derive(derive_more::Debug, Clone)] -1211pub struct PathInfo { -1212 path_id: PathId, -1213 #[debug(skip)] -1214 handle: WeakConnectionHandle, -1215 stats: PathStats, -1216 remote: TransportAddr, -1217 is_selected: bool, -1218} -1219 -1220impl PartialEq for PathInfo { -1221 fn eq(&self, other: &Self) -> bool { -1222 self.path_id == other.path_id -1223 && self.remote == other.remote -1224 && self.is_selected == other.is_selected -1225 } -1226} -1227 -1228impl Eq for PathInfo {} -1229 -1230impl PathInfo { -1231 fn new( -1232 path_id: PathId, -1233 conn: &quinn::Connection, -1234 remote: TransportAddr, -1235 selected_path: Option<&TransportAddr>, -1236 ) -> Option<Self> { -1237 let stats = conn.path_stats(path_id)?; -1238 Some(Self { -1239 path_id, -1240 handle: conn.weak_handle(), -1241 is_selected: Some(&remote) == selected_path, -1242 remote, -1243 stats, -1244 }) -1245 } -1246 -1247 /// The remote transport address used by this network path. -1248 pub fn remote_addr(&self) -> &TransportAddr { -1249 &self.remote -1250 } -1251 -1252 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. -1253 /// -1254 /// [`Connection`]: crate::endpoint::Connection -1255 pub fn is_selected(&self) -> bool { -1256 self.is_selected -1257 } -1258 -1259 /// Whether this is an IP transport address. -1260 pub fn is_ip(&self) -> bool { -1261 self.remote.is_ip() -1262 } -1263 -1264 /// Whether this is a transport address via a relay server. -1265 pub fn is_relay(&self) -> bool { -1266 self.remote.is_relay() -1267 } -1268 -1269 /// Returns stats for this transmission path. -1270 pub fn stats(&self) -> PathStats { -1271 self.handle -1272 .upgrade() -1273 .and_then(|conn| conn.path_stats(self.path_id)) -1274 .unwrap_or(self.stats) -1275 } -1276 -1277 /// Current best estimate of this paths's latency (round-trip-time) -1278 pub fn rtt(&self) -> Duration { -1279 self.stats().rtt -1280 } -1281} -1282 -1283/// Poll a future once, like n0_future::future::poll_once but sync. -1284fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { -1285 let fut = std::pin::pin!(fut); -1286 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { -1287 Poll::Ready(res) => Some(res), -1288 Poll::Pending => None, -1289 } -1290} -1291 -1292/// Future that resolves to the `conn_id` once a connection is closed. -1293/// -1294/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive -1295/// while awaiting the future. -1296struct OnClosed { -1297 conn_id: ConnId, -1298 inner: quinn::OnClosed, -1299} -1300 -1301impl OnClosed { -1302 fn new(conn: &quinn::Connection) -> Self { -1303 Self { -1304 conn_id: ConnId(conn.stable_id()), -1305 inner: conn.on_closed(), -1306 } -1307 } -1308} -1309 -1310impl Future for OnClosed { -1311 type Output = ConnId; -1312 -1313 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1314 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); -1315 Poll::Ready(self.conn_id) -1316 } -1317} \ No newline at end of file +1146 self.pub_open_paths.set(new).ok(); +1147 } +1148} +1149 +1150/// Watchables for the open paths and selected transmission path in a connection. +1151/// +1152/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor. +1153/// +1154/// [`Connection`]: crate::endpoint::Connection +1155#[derive(Debug, Default, Clone)] +1156pub(crate) struct PathsWatchable { +1157 /// Watchable for the open paths (in this connection). +1158 open_paths: Watchable<PathAddrList>, +1159 /// Watchable for the selected transmission path (global for this remote endpoint). +1160 selected_path: Watchable<Option<transports::Addr>>, +1161} +1162 +1163impl PathsWatchable { +1164 pub(crate) fn watch( +1165 &self, +1166 conn_handle: WeakConnectionHandle, +1167 ) -> impl Watcher<Value = PathInfoList> { +1168 let joined_watcher = (self.open_paths.watch(), self.selected_path.watch()); +1169 joined_watcher.map(move |(open_paths, selected_path)| { +1170 let selected_path: Option<TransportAddr> = selected_path.map(Into::into); +1171 let Some(conn) = conn_handle.upgrade() else { +1172 return PathInfoList(Default::default()); +1173 }; +1174 let list = open_paths +1175 .into_iter() +1176 .flat_map(move |(remote, path_id)| { +1177 PathInfo::new(path_id, &conn, remote, selected_path.as_ref()) +1178 }) +1179 .collect(); +1180 PathInfoList(list) +1181 }) +1182 } +1183} +1184 +1185/// List of [`PathInfo`] for the network paths of a [`Connection`]. +1186/// +1187/// This struct implements [`IntoIterator`]. +1188/// +1189/// [`Connection`]: crate::endpoint::Connection +1190#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)] +1191#[debug("{_0:?}")] +1192pub struct PathInfoList(SmallVec<[PathInfo; 4]>); +1193 +1194impl PathInfoList { +1195 /// Returns an iterator over the path infos. +1196 pub fn iter(&self) -> impl Iterator<Item = &PathInfo> { +1197 self.0.iter() +1198 } +1199 +1200 /// Returns `true` if the list is empty. +1201 pub fn is_empty(&self) -> bool { +1202 self.0.is_empty() +1203 } +1204 +1205 /// Returns the number of paths. +1206 pub fn len(&self) -> usize { +1207 self.0.len() +1208 } +1209} +1210 +1211/// Information about a network path used by a [`Connection`]. +1212/// +1213/// [`Connection`]: crate::endpoint::Connection +1214#[derive(derive_more::Debug, Clone)] +1215pub struct PathInfo { +1216 path_id: PathId, +1217 #[debug(skip)] +1218 handle: WeakConnectionHandle, +1219 stats: PathStats, +1220 remote: TransportAddr, +1221 is_selected: bool, +1222} +1223 +1224impl PartialEq for PathInfo { +1225 fn eq(&self, other: &Self) -> bool { +1226 self.path_id == other.path_id +1227 && self.remote == other.remote +1228 && self.is_selected == other.is_selected +1229 } +1230} +1231 +1232impl Eq for PathInfo {} +1233 +1234impl PathInfo { +1235 fn new( +1236 path_id: PathId, +1237 conn: &quinn::Connection, +1238 remote: TransportAddr, +1239 selected_path: Option<&TransportAddr>, +1240 ) -> Option<Self> { +1241 let stats = conn.path_stats(path_id)?; +1242 Some(Self { +1243 path_id, +1244 handle: conn.weak_handle(), +1245 is_selected: Some(&remote) == selected_path, +1246 remote, +1247 stats, +1248 }) +1249 } +1250 +1251 /// The remote transport address used by this network path. +1252 pub fn remote_addr(&self) -> &TransportAddr { +1253 &self.remote +1254 } +1255 +1256 /// Returns `true` if this path is currently the main transmission path for this [`Connection`]. +1257 /// +1258 /// [`Connection`]: crate::endpoint::Connection +1259 pub fn is_selected(&self) -> bool { +1260 self.is_selected +1261 } +1262 +1263 /// Whether this is an IP transport address. +1264 pub fn is_ip(&self) -> bool { +1265 self.remote.is_ip() +1266 } +1267 +1268 /// Whether this is a transport address via a relay server. +1269 pub fn is_relay(&self) -> bool { +1270 self.remote.is_relay() +1271 } +1272 +1273 /// Returns stats for this transmission path. +1274 pub fn stats(&self) -> PathStats { +1275 self.handle +1276 .upgrade() +1277 .and_then(|conn| conn.path_stats(self.path_id)) +1278 .unwrap_or(self.stats) +1279 } +1280 +1281 /// Current best estimate of this paths's latency (round-trip-time) +1282 pub fn rtt(&self) -> Duration { +1283 self.stats().rtt +1284 } +1285} +1286 +1287/// Poll a future once, like n0_future::future::poll_once but sync. +1288fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> { +1289 let fut = std::pin::pin!(fut); +1290 match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) { +1291 Poll::Ready(res) => Some(res), +1292 Poll::Pending => None, +1293 } +1294} +1295 +1296/// Future that resolves to the `conn_id` once a connection is closed. +1297/// +1298/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive +1299/// while awaiting the future. +1300struct OnClosed { +1301 conn_id: ConnId, +1302 inner: quinn::OnClosed, +1303} +1304 +1305impl OnClosed { +1306 fn new(conn: &quinn::Connection) -> Self { +1307 Self { +1308 conn_id: ConnId(conn.stable_id()), +1309 inner: conn.on_closed(), +1310 } +1311 } +1312} +1313 +1314impl Future for OnClosed { +1315 type Output = ConnId; +1316 +1317 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1318 let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx)); +1319 Poll::Ready(self.conn_id) +1320 } +1321} \ 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 dda31e064b..6f5c3c8d66 100644 --- a/pr/3381/docs/src/iroh/magicsock/transports.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/transports.rs.html @@ -412,7 +412,7 @@ 412} 413 414/// A sender that sends to all our transports. -415#[derive(Debug)] +415#[derive(Debug, Clone)] 416pub(crate) struct TransportsSender { 417 #[cfg(not(wasm_browser))] 418 ip: Vec<IpSender>, @@ -602,131 +602,129 @@ 602/// This is special in that it handles [`MultipathMappedAddr::Mixed`] by delegating to the 603/// [`MagicSock`] which expands it back to one or more [`Addr`]s and sends it 604/// using the underlying [`Transports`]. -605// TODO: Can I just send the TransportsSender along in the NodeStateMessage::SendDatagram -606// message?? That way you don't have to hook up the sender into the NodeMap! -607#[derive(Debug)] -608#[pin_project::pin_project] -609pub(crate) struct MagicSender { -610 msock: Arc<MagicSock>, -611 #[pin] -612 sender: TransportsSender, -613} -614 -615impl MagicSender { -616 /// Extracts the right [`Addr`] from the [`quinn_udp::Transmit`]. -617 /// -618 /// Because Quinn does only know about IP transports we map other transports to private -619 /// IPv6 Unique Local Address ranges. This extracts the transport addresses out of the -620 /// transmit's destination. -621 fn mapped_addr(&self, transmit: &quinn_udp::Transmit) -> io::Result<MultipathMappedAddr> { -622 if self.msock.is_closed() { -623 return Err(io::Error::new( -624 io::ErrorKind::NotConnected, -625 "connection closed", -626 )); -627 } -628 -629 Ok(MultipathMappedAddr::from(transmit.destination)) -630 } -631} -632 -633impl quinn::UdpSender for MagicSender { -634 fn poll_send( -635 self: Pin<&mut Self>, -636 quinn_transmit: &quinn_udp::Transmit, -637 cx: &mut Context, -638 ) -> Poll<io::Result<()>> { -639 // On errors this methods prefers returning Ok(()) to Quinn. Returning an error -640 // should only happen if the error is permanent and fatal and it will never be -641 // possible to send anything again. Doing so kills the Quinn EndpointDriver. Most -642 // send errors are intermittent errors, returning Ok(()) in those cases will mean -643 // Quinn eventually considers the packets that had send errors as lost and will try -644 // and re-send them. -645 let mapped_addr = self.mapped_addr(quinn_transmit)?; -646 -647 let transport_addr = match mapped_addr { -648 MultipathMappedAddr::Mixed(mapped_addr) => { -649 let Some(node_id) = self -650 .msock -651 .endpoint_map -652 .endpoint_mapped_addrs -653 .lookup(&mapped_addr) -654 else { -655 error!(dst = ?mapped_addr, "unknown NodeIdMappedAddr, dropped transmit"); -656 return Poll::Ready(Ok(())); -657 }; -658 -659 // Note we drop the src_ip set in the Quinn Transmit. This is only the -660 // Initial packet we are sending, so we do not yet have an src address we -661 // need to respond from. -662 if let Some(src_ip) = quinn_transmit.src_ip { -663 warn!(dst = ?mapped_addr, ?src_ip, dst_node = %node_id.fmt_short(), -664 "oops, flub didn't think this would happen"); -665 } -666 -667 let sender = self.msock.endpoint_map.endpoint_state_actor(node_id); -668 let transmit = OwnedTransmit::from(quinn_transmit); -669 return match sender.try_send(EndpointStateMessage::SendDatagram(transmit)) { -670 Ok(()) => { -671 trace!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), "sent transmit"); -672 Poll::Ready(Ok(())) -673 } -674 Err(err) => { -675 // We do not want to block the next send which might be on a -676 // different transport. Instead we let Quinn handle this as -677 // a lost datagram. -678 // TODO: Revisit this: we might want to do something better. -679 debug!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), -680 "EndpointStateActor inbox {err:#}, dropped transmit"); -681 Poll::Ready(Ok(())) -682 } -683 }; -684 } -685 MultipathMappedAddr::Relay(relay_mapped_addr) => { -686 match self -687 .msock -688 .endpoint_map -689 .relay_mapped_addrs -690 .lookup(&relay_mapped_addr) -691 { -692 Some((relay_url, endpoint_id)) => Addr::Relay(relay_url, endpoint_id), -693 None => { -694 error!("unknown RelayMappedAddr, dropped transmit"); -695 return Poll::Ready(Ok(())); -696 } -697 } -698 } -699 MultipathMappedAddr::Ip(socket_addr) => Addr::Ip(socket_addr), -700 }; -701 -702 let transmit = Transmit { -703 ecn: quinn_transmit.ecn, -704 contents: quinn_transmit.contents, -705 segment_size: quinn_transmit.segment_size, -706 }; -707 let this = self.project(); -708 -709 match this -710 .sender -711 .inner_poll_send(cx, &transport_addr, quinn_transmit.src_ip, &transmit) -712 { -713 Poll::Ready(Ok(())) => Poll::Ready(Ok(())), -714 Poll::Ready(Err(ref err)) => { -715 warn!("dropped transmit: {err:#}"); -716 Poll::Ready(Ok(())) -717 } -718 Poll::Pending => { -719 // We do not want to block the next send which might be on a -720 // different transport. Instead we let Quinn handle this as a lost -721 // datagram. -722 // TODO: Revisit this: we might want to do something better. -723 trace!("transport pending, dropped transmit"); -724 Poll::Ready(Ok(())) -725 } -726 } -727 } -728 -729 fn max_transmit_segments(&self) -> usize { -730 self.sender.max_transmit_segments -731 } -732} \ No newline at end of file +605#[derive(Debug)] +606#[pin_project::pin_project] +607pub(crate) struct MagicSender { +608 msock: Arc<MagicSock>, +609 #[pin] +610 sender: TransportsSender, +611} +612 +613impl MagicSender { +614 /// Extracts the right [`Addr`] from the [`quinn_udp::Transmit`]. +615 /// +616 /// Because Quinn does only know about IP transports we map other transports to private +617 /// IPv6 Unique Local Address ranges. This extracts the transport addresses out of the +618 /// transmit's destination. +619 fn mapped_addr(&self, transmit: &quinn_udp::Transmit) -> io::Result<MultipathMappedAddr> { +620 if self.msock.is_closed() { +621 return Err(io::Error::new( +622 io::ErrorKind::NotConnected, +623 "connection closed", +624 )); +625 } +626 +627 Ok(MultipathMappedAddr::from(transmit.destination)) +628 } +629} +630 +631impl quinn::UdpSender for MagicSender { +632 fn poll_send( +633 self: Pin<&mut Self>, +634 quinn_transmit: &quinn_udp::Transmit, +635 cx: &mut Context, +636 ) -> Poll<io::Result<()>> { +637 // On errors this methods prefers returning Ok(()) to Quinn. Returning an error +638 // should only happen if the error is permanent and fatal and it will never be +639 // possible to send anything again. Doing so kills the Quinn EndpointDriver. Most +640 // send errors are intermittent errors, returning Ok(()) in those cases will mean +641 // Quinn eventually considers the packets that had send errors as lost and will try +642 // and re-send them. +643 let mapped_addr = self.mapped_addr(quinn_transmit)?; +644 +645 let transport_addr = match mapped_addr { +646 MultipathMappedAddr::Mixed(mapped_addr) => { +647 let Some(node_id) = self +648 .msock +649 .endpoint_map +650 .endpoint_mapped_addrs +651 .lookup(&mapped_addr) +652 else { +653 error!(dst = ?mapped_addr, "unknown NodeIdMappedAddr, dropped transmit"); +654 return Poll::Ready(Ok(())); +655 }; +656 +657 // Note we drop the src_ip set in the Quinn Transmit. This is only the +658 // Initial packet we are sending, so we do not yet have an src address we +659 // need to respond from. +660 if let Some(src_ip) = quinn_transmit.src_ip { +661 warn!(dst = ?mapped_addr, ?src_ip, dst_node = %node_id.fmt_short(), +662 "oops, flub didn't think this would happen"); +663 } +664 +665 let sender = self.msock.endpoint_map.endpoint_state_actor(node_id); +666 let transmit = OwnedTransmit::from(quinn_transmit); +667 return match sender.try_send(EndpointStateMessage::SendDatagram(transmit)) { +668 Ok(()) => { +669 trace!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), "sent transmit"); +670 Poll::Ready(Ok(())) +671 } +672 Err(err) => { +673 // We do not want to block the next send which might be on a +674 // different transport. Instead we let Quinn handle this as +675 // a lost datagram. +676 // TODO: Revisit this: we might want to do something better. +677 debug!(dst = ?mapped_addr, dst_node = %node_id.fmt_short(), +678 "EndpointStateActor inbox {err:#}, dropped transmit"); +679 Poll::Ready(Ok(())) +680 } +681 }; +682 } +683 MultipathMappedAddr::Relay(relay_mapped_addr) => { +684 match self +685 .msock +686 .endpoint_map +687 .relay_mapped_addrs +688 .lookup(&relay_mapped_addr) +689 { +690 Some((relay_url, endpoint_id)) => Addr::Relay(relay_url, endpoint_id), +691 None => { +692 error!("unknown RelayMappedAddr, dropped transmit"); +693 return Poll::Ready(Ok(())); +694 } +695 } +696 } +697 MultipathMappedAddr::Ip(socket_addr) => Addr::Ip(socket_addr), +698 }; +699 +700 let transmit = Transmit { +701 ecn: quinn_transmit.ecn, +702 contents: quinn_transmit.contents, +703 segment_size: quinn_transmit.segment_size, +704 }; +705 let this = self.project(); +706 +707 match this +708 .sender +709 .inner_poll_send(cx, &transport_addr, quinn_transmit.src_ip, &transmit) +710 { +711 Poll::Ready(Ok(())) => Poll::Ready(Ok(())), +712 Poll::Ready(Err(ref err)) => { +713 warn!("dropped transmit: {err:#}"); +714 Poll::Ready(Ok(())) +715 } +716 Poll::Pending => { +717 // We do not want to block the next send which might be on a +718 // different transport. Instead we let Quinn handle this as a lost +719 // datagram. +720 // TODO: Revisit this: we might want to do something better. +721 trace!("transport pending, dropped transmit"); +722 Poll::Ready(Ok(())) +723 } +724 } +725 } +726 +727 fn max_transmit_segments(&self) -> usize { +728 self.sender.max_transmit_segments +729 } +730} \ No newline at end of file diff --git a/pr/3381/docs/src/iroh/magicsock/transports/ip.rs.html b/pr/3381/docs/src/iroh/magicsock/transports/ip.rs.html index b9140c200b..d2b019e875 100644 --- a/pr/3381/docs/src/iroh/magicsock/transports/ip.rs.html +++ b/pr/3381/docs/src/iroh/magicsock/transports/ip.rs.html @@ -132,7 +132,7 @@ 132 } 133} 134 -135#[derive(Debug)] +135#[derive(Debug, Clone)] 136#[pin_project] 137pub(super) struct IpSender { 138 bind_addr: SocketAddr, 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 34a5306f46..0cebe6b8f8 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 AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AddEndpointAddrError> for ConnectWithOptsError"],["impl From<AddEndpointAddrError> 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 AuthenticationError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<GetMappingAddressError> for ConnectWithOptsError"],["impl From<GetMappingAddressError> for AnyError"],["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 AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AddEndpointAddrError> for ConnectWithOptsError"],["impl From<AddEndpointAddrError> 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 AuthenticationError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<GetMappingAddressError> for ConnectWithOptsError"],["impl From<GetMappingAddressError> for AnyError"],["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":[13657,3090,18835]} \ No newline at end of file +//{"start":57,"fragment_lengths":[13657,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