From ef0a2b3c749e596482fa9bf5dea70bf009d587d8 Mon Sep 17 00:00:00 2001 From: Frando Date: Thu, 26 Feb 2026 10:39:51 +0000 Subject: [PATCH] deploy: 085e2be0c634eeba80db46f731c4ee932ca691dd --- .../iroh/endpoint/enum.DirectAddrType.html | 12 +- .../docs/iroh/endpoint/struct.DirectAddr.html | 12 +- .../client/struct.ClientBuilder.html | 4 +- .../iroh_relay/dns/struct.DnsResolver.html | 8 +- .../endpoint_info/enum.DecodingError.html | 4 +- .../docs/iroh_relay/endpoint_info/index.html | 10 +- .../endpoint_info/struct.EndpointData.html | 18 +- .../endpoint_info/struct.EndpointInfo.html | 28 +- .../endpoint_info/trait.EndpointIdExt.html | 10 +- pr/3973/docs/iroh_relay/enum.KeyCache.html | 6 +- pr/3973/docs/iroh_relay/index.html | 2 +- .../struct.SuccessfulAuthentication.html | 6 +- .../protos/relay/enum.ClientToRelayMsg.html | 4 +- .../iroh_relay/protos/relay/enum.Error.html | 6 +- .../protos/relay/enum.RelayToClientMsg.html | 8 +- .../server/client/struct.Config.html | 4 +- .../iroh_relay/server/enum.AccessConfig.html | 6 +- .../docs/iroh_relay/server/struct.Server.html | 4 +- .../docs/iroh_relay/struct.RelayConfig.html | 6 +- pr/3973/docs/iroh_relay/struct.RelayMap.html | 16 +- pr/3973/docs/src/iroh/socket.rs.html | 3041 +++++++++-------- .../trait.impl/core/convert/trait.From.js | 4 +- .../iter/traits/collect/trait.FromIterator.js | 4 +- 23 files changed, 1612 insertions(+), 1611 deletions(-) diff --git a/pr/3973/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3973/docs/iroh/endpoint/enum.DirectAddrType.html index 79f3e0bfe0..43019c117b 100644 --- a/pr/3973/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3973/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

DirectAddrType

Enum DirectAddrType 

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

DirectAddrType

Enum DirectAddrType 

Source
pub enum DirectAddrType {
     Unknown,
     Local,
     Qad,
@@ -20,16 +20,16 @@ get a publicly routable direct address.

It is possible to configure iroh to bound to a specific port and independently configure the router to forward this port to the iroh endpoint. This indicates a situation like this, which still uses QAD to discover the public address.

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the + Self: Sized,
Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3973/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3973/docs/iroh/endpoint/struct.DirectAddr.html index bca82df971..1124dd122e 100644 --- a/pr/3973/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3973/docs/iroh/endpoint/struct.DirectAddr.html @@ -1,4 +1,4 @@ -DirectAddr in iroh::endpoint - Rust

DirectAddr

Struct DirectAddr 

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

DirectAddr

Struct DirectAddr 

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

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

@@ -9,16 +9,16 @@ iroh endpoint, see Fields§

§addr: SocketAddr

The address.

§typ: DirectAddrType

The origin of this direct address.

-

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddr

Source§

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

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

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

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

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the + Self: Sized,
Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddr

Source§

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

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

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

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

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

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

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3973/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3973/docs/iroh_relay/client/struct.ClientBuilder.html index 92667c6174..61b3ea0ab6 100644 --- a/pr/3973/docs/iroh_relay/client/struct.ClientBuilder.html +++ b/pr/3973/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 tls_client_config(self, tls_config: ClientConfig) -> Self

Sets a custom TLS config.

diff --git a/pr/3973/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3973/docs/iroh_relay/dns/struct.DnsResolver.html index c8235b0c6f..2337881b28 100644 --- a/pr/3973/docs/iroh_relay/dns/struct.DnsResolver.html +++ b/pr/3973/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/3973/docs/iroh_relay/endpoint_info/enum.DecodingError.html b/pr/3973/docs/iroh_relay/endpoint_info/enum.DecodingError.html index b83bc53fd5..1f33659ac4 100644 --- a/pr/3973/docs/iroh_relay/endpoint_info/enum.DecodingError.html +++ b/pr/3973/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/3973/docs/iroh_relay/endpoint_info/index.html b/pr/3973/docs/iroh_relay/endpoint_info/index.html index 5a81f61597..681ff99294 100644 --- a/pr/3973/docs/iroh_relay/endpoint_info/index.html +++ b/pr/3973/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/3973/docs/iroh_relay/endpoint_info/struct.EndpointData.html b/pr/3973/docs/iroh_relay/endpoint_info/struct.EndpointData.html index 4cb39187f1..6bc21021fd 100644 --- a/pr/3973/docs/iroh_relay/endpoint_info/struct.EndpointData.html +++ b/pr/3973/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/3973/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html b/pr/3973/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html index 895bfe4f7c..efa713a389 100644 --- a/pr/3973/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html +++ b/pr/3973/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/3973/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html b/pr/3973/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html index 0bd49dc493..c26b97e4bd 100644 --- a/pr/3973/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html +++ b/pr/3973/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/3973/docs/iroh_relay/enum.KeyCache.html b/pr/3973/docs/iroh_relay/enum.KeyCache.html index 854c0161ff..0f3da2bdd0 100644 --- a/pr/3973/docs/iroh_relay/enum.KeyCache.html +++ b/pr/3973/docs/iroh_relay/enum.KeyCache.html @@ -1,20 +1,20 @@ KeyCache in iroh_relay - Rust

    KeyCache

    Enum KeyCache 

    Source
    pub enum KeyCache {
         Disabled,
    -    Shared(Arc<Mutex<LruCache<PublicKey, ()>>>),
    +    Shared(Arc<Mutex<LruCache<PublicKey, ()>>>),
     }
    Expand description

    A cache for public keys.

    This is used solely to make parsing public keys from byte slices more efficient for the very common case where a large number of identical keys are being parsed, like in the relay server.

    The cache stores only successful parse results.

    Variants§

    §

    Disabled

    The key cache is disabled.

    -
    §

    Shared(Arc<Mutex<LruCache<PublicKey, ()>>>)

    The key cache is enabled with a fixed capacity. It is shared between +

    §

    Shared(Arc<Mutex<LruCache<PublicKey, ()>>>)

    The key cache is enabled with a fixed capacity. It is shared between multiple threads.

    Implementations§

    Source§

    impl KeyCache

    Source

    pub fn new(capacity: usize) -> Self

    Create a new key cache with the given capacity.

    If the capacity is zero, the cache is disabled and has zero overhead.

    Source

    pub fn key_from_slice( &self, slice: &[u8], -) -> Result<PublicKey, <PublicKey as TryFrom<&'static [u8]>>::Error>

    Get a key from a slice of bytes.

    +) -> Result<PublicKey, <PublicKey as TryFrom<&'static [u8]>>::Error>

    Get a key from a slice of bytes.

    Trait Implementations§

    Source§

    impl Clone for KeyCache

    Source§

    fn clone(&self) -> KeyCache

    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 KeyCache

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3973/docs/iroh_relay/index.html b/pr/3973/docs/iroh_relay/index.html index 4e42fef21c..8d18e43b14 100644 --- a/pr/3973/docs/iroh_relay/index.html +++ b/pr/3973/docs/iroh_relay/index.html @@ -25,7 +25,7 @@ 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.
    tls
    TLS verification configuration for iroh and iroh-relay.

    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.

    Enums§

    KeyCache
    A cache for public keys.

    Traits§

    ExportKeyingMaterial
    This trait allows anything that ends up potentially wrapping a TLS stream use the underlying export_keying_material diff --git a/pr/3973/docs/iroh_relay/protos/handshake/struct.SuccessfulAuthentication.html b/pr/3973/docs/iroh_relay/protos/handshake/struct.SuccessfulAuthentication.html index 792f4ea6d7..6bf4bfd38d 100644 --- a/pr/3973/docs/iroh_relay/protos/handshake/struct.SuccessfulAuthentication.html +++ b/pr/3973/docs/iroh_relay/protos/handshake/struct.SuccessfulAuthentication.html @@ -1,5 +1,5 @@ SuccessfulAuthentication in iroh_relay::protos::handshake - Rust

    SuccessfulAuthentication

    Struct SuccessfulAuthentication 

    Source
    pub struct SuccessfulAuthentication {
    -    pub client_key: PublicKey,
    +    pub client_key: PublicKey,
         pub mechanism: Mechanism,
     }
    Available on crate feature server only.
    Expand description

    This represents successful authentication for the client with the client_key public key via the authentication Mechanism mechanism.

    @@ -8,13 +8,13 @@ Result of a successful authentication handshake.

    This struct represents a client that has successfully authenticated itself to the relay server. The authorization must still be confirmed by calling Self::authorize_if to complete the protocol and notify the client of success or failure.

    -

    Fields§

    §client_key: PublicKey

    The authenticated client’s public key.

    +

    Fields§

    §client_key: PublicKey

    The authenticated client’s public key.

    §mechanism: Mechanism

    The authentication mechanism that was used.

    Implementations§

    Source§

    impl SuccessfulAuthentication

    Source

    pub async fn authorize_if( self, is_authorized: bool, io: &mut (impl BytesStreamSink + ExportKeyingMaterial), -) -> Result<PublicKey, Error>

    Completes the authorization protocol by notifying the client of success or failure.

    +) -> Result<PublicKey, Error>

    Completes the authorization protocol by notifying the client of success or failure.

    After a client has been successfully authenticated via serverside, the server must decide whether to authorize the client (allow access) or deny it. This method sends the authorization decision to the client and completes the handshake protocol.

    diff --git a/pr/3973/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html b/pr/3973/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html index c864cce80c..0c25cf9d54 100644 --- a/pr/3973/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html +++ b/pr/3973/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/3973/docs/iroh_relay/protos/relay/enum.Error.html b/pr/3973/docs/iroh_relay/protos/relay/enum.Error.html index 8e8006fed3..83d9df5b82 100644 --- a/pr/3973/docs/iroh_relay/protos/relay/enum.Error.html +++ b/pr/3973/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<Error> for RecvError

    Available on crate feature server only.
    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<Error> for RecvError

    Available on crate feature server only.
    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/3973/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3973/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html index b596a8eb85..75ed075f07 100644 --- a/pr/3973/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html +++ b/pr/3973/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/3973/docs/iroh_relay/server/client/struct.Config.html b/pr/3973/docs/iroh_relay/server/client/struct.Config.html index 3cf98c513e..9dc00f4d95 100644 --- a/pr/3973/docs/iroh_relay/server/client/struct.Config.html +++ b/pr/3973/docs/iroh_relay/server/client/struct.Config.html @@ -1,11 +1,11 @@ Config in iroh_relay::server::client - Rust

    Config

    Struct Config 

    Source
    pub struct Config<S> {
    -    pub endpoint_id: EndpointId,
    +    pub endpoint_id: EndpointId,
         pub stream: RelayedStream<S>,
         pub write_timeout: Duration,
         pub channel_capacity: usize,
     }
    Available on crate feature server only.
    Expand description

    Configuration for a Client.

    Generic over the stream type to support different WebSocket implementations.

    -

    Fields§

    §endpoint_id: EndpointId

    The endpoint ID of the client

    +

    Fields§

    §endpoint_id: EndpointId

    The endpoint ID of the client

    §stream: RelayedStream<S>

    The relayed stream connection

    §write_timeout: Duration

    Write timeout for the client connection

    §channel_capacity: usize

    Channel capacity for internal message queues

    diff --git a/pr/3973/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3973/docs/iroh_relay/server/enum.AccessConfig.html index 7247015baa..faa1d5a168 100644 --- a/pr/3973/docs/iroh_relay/server/enum.AccessConfig.html +++ b/pr/3973/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/3973/docs/iroh_relay/server/struct.Server.html b/pr/3973/docs/iroh_relay/server/struct.Server.html index ecde229cce..bac2e044e6 100644 --- a/pr/3973/docs/iroh_relay/server/struct.Server.html +++ b/pr/3973/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/3973/docs/iroh_relay/struct.RelayConfig.html b/pr/3973/docs/iroh_relay/struct.RelayConfig.html index bfa8ba30f7..03589f1728 100644 --- a/pr/3973/docs/iroh_relay/struct.RelayConfig.html +++ b/pr/3973/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/3973/docs/iroh_relay/struct.RelayMap.html b/pr/3973/docs/iroh_relay/struct.RelayMap.html index 360af04caf..4d3d55ed46 100644 --- a/pr/3973/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3973/docs/iroh_relay/struct.RelayMap.html @@ -9,34 +9,34 @@ or by creating an empty relay map with 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 try_from_iter<'a, T: IntoIterator<Item = &'a str>>( urls: T, -) -> Result<Self, RelayUrlParseError>

    Creates a RelayMap from an iterator.

    +) -> Result<Self, RelayUrlParseError>

    Creates a RelayMap from an iterator.

    The conversion from a URL to a RelayConfig is done the same as when parsing it directly, which means it is assumed to run QUIC on default settings as defined in RelayQuicConfig::default.

    §Example
    let map =
         RelayMap::try_from_iter(["https://relay_0.cool.com", "https://relay_1.cool.com"]).unwrap();
    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/3973/docs/src/iroh/socket.rs.html b/pr/3973/docs/src/iroh/socket.rs.html index ba690e1b30..c08f81e03d 100644 --- a/pr/3973/docs/src/iroh/socket.rs.html +++ b/pr/3973/docs/src/iroh/socket.rs.html @@ -869,1523 +869,1524 @@ 869 .await 870 .map_err(|err| e!(BindError::CreateNetmonMonitor, err))?; 871 -872 let net_report_config = net_report::Options::new(tls_config.clone()); -873 -874 #[cfg(not(wasm_browser))] -875 let net_report_config = { -876 // Set a `QuicConfig` for address discovery (QAD), but only if we have IP transports. -877 // -878 // If there are no IP transports configured, then we don't set a QuicConfig. -879 // If we would, the `quinn::Endpoint` passed along will not have IP connectivity, -880 // and the QAD probes that connect to the relay's QUIC endpoints would time out -881 // because all outgoing packets to IP destinations would be dropped. -882 let qad_config = has_ip_transports.then(|| QuicConfig { -883 ep: endpoint.clone(), -884 client_config: tls_config.clone(), -885 ipv4: true, -886 ipv6: has_ipv6_transport, -887 }); -888 net_report_config.quic_config(qad_config) -889 }; -890 -891 let net_reporter = net_report::Client::new( -892 #[cfg(not(wasm_browser))] -893 dns_resolver, -894 relay_map.clone(), -895 net_report_config, -896 metrics.net_report.clone(), -897 ); -898 -899 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -900 let direct_addr_update_state = DirectAddrUpdateState::new( -901 sock.clone(), -902 #[cfg(not(wasm_browser))] -903 port_mapper, -904 Arc::new(AsyncMutex::new(net_reporter)), -905 relay_map, -906 direct_addr_done_tx, -907 sock.shutdown.at_close_start.child_token(), -908 ); -909 -910 let netmon_watcher = network_monitor.interface_state(); -911 -912 #[cfg_attr(not(wasm_browser), allow(unused_mut))] -913 let mut actor = Actor { -914 sock: sock.clone(), -915 remote_map, -916 periodic_re_stun_timer: new_re_stun_timer(false), -917 network_monitor, -918 netmon_watcher, -919 direct_addr_update_state, -920 network_change_sender, -921 direct_addr_done_rx, -922 }; -923 // Initialize addresses -924 #[cfg(not(wasm_browser))] -925 actor.update_direct_addresses(None); -926 -927 let actor_task = task::spawn( -928 actor -929 .run( -930 actor_receiver, -931 shutdown_token.child_token(), -932 local_addrs_watch, -933 ) -934 .instrument(info_span!("actor")), -935 ); -936 -937 let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task))); -938 -939 Ok(EndpointInner { -940 sock, -941 actor_sender, -942 actor_task, -943 endpoint, -944 runtime, -945 static_config, -946 }) -947 } -948 -949 /// Returns a reference to the underlying [`quinn::Endpoint`]. -950 pub(crate) fn quinn_endpoint(&self) -> &quinn::Endpoint { -951 &self.endpoint -952 } -953 -954 /// Closes the connection. -955 /// -956 /// Only the first close does anything. Any later closes return nil. Polling the socket -957 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely -958 /// after this call. -959 /// -960 /// [`Poll::Pending`]: std::task::Poll::Pending -961 #[instrument(skip_all)] -962 pub(crate) async fn close(&self) { -963 if self.sock.is_closed() || self.sock.is_closing() { -964 return; -965 } -966 trace!(me = ?self.public_key, "socket closing..."); -967 -968 // Cancel at_close_start token, which cancels running netreports. -969 self.sock.shutdown.at_close_start.cancel(); -970 -971 // Remove address lookup services -972 self.sock.address_lookup().clear(); -973 -974 // Initiate closing all connections, and refuse future connections. -975 self.quinn_endpoint().close(0u16.into(), b""); -976 -977 // In the history of this code, this call had been -978 // - removed: https://github.com/n0-computer/iroh/pull/1753 -979 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -980 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -981 // and finally added back in together with this comment. -982 // So before removing this call, please consider carefully. -983 // Among other things, this call tries its best to make sure that any queued close frames -984 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -985 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -986 // This allows the other endpoints for these connections to be notified to release -987 // their resources, or - depending on the protocol - that all data was received. -988 // With the current quinn API, this is the only way to ensure protocol code can use -989 // connection close codes, and close the endpoint properly. -990 // If this call is skipped, then connections that protocols close just shortly before the -991 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -992 trace!("wait_idle start"); -993 self.quinn_endpoint().wait_idle().await; -994 trace!("wait_idle done"); -995 -996 // Start cancellation of all actors. -997 self.sock.shutdown.at_endpoint_closed.cancel(); -998 -999 // MutexGuard is not held across await points -1000 let task = self.actor_task.lock().expect("poisoned").take(); -1001 if let Some(task) = task { -1002 // give the tasks a moment to shutdown cleanly -1003 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1004 if let Err(err) = task.await { -1005 warn!("unexpected error in task shutdown: {:?}", err); -1006 } -1007 }) -1008 .await; -1009 match shutdown_done { -1010 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1011 Err(time::Elapsed { .. }) => { -1012 // Dropping the task will abort it -1013 warn!("tasks didn't finish in time, aborting"); -1014 } -1015 } -1016 } -1017 -1018 // Waits for the EndpointDriver and all ConnectionDrivers to shut down -1019 // Expects that the `quinn::Endpoint` has been closed before this call, -1020 // otherwise, the runtime will never shutdown. -1021 self.runtime.shutdown().await; -1022 -1023 self.sock.shutdown.closed.store(true, Ordering::SeqCst); -1024 -1025 trace!("socket closed"); -1026 } -1027 -1028 /// Aborts the endpoint ungracefully: -1029 /// -1030 /// - Calls cancellation token that stops running net reports -1031 /// - Removes all address lookup services -1032 /// - Calls cancellation token that stops all the Socket actors -1033 /// - Aborts the runtime -1034 /// - Drops the actor task -1035 /// - Sets the `Socket::is_closed` state to true -1036 /// -1037 /// This does not wait for any current connections or tasks to close gracefully. -1038 /// -1039 /// This should only be called in the `iroh::Endpoint` `Drop` impl when the -1040 /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`. -1041 #[instrument(skip_all)] -1042 pub(crate) fn abort(&self) { -1043 if self.sock.is_closed() || self.sock.is_closing() { -1044 return; -1045 } -1046 trace!(me = ?self.public_key, "aborting socket..."); -1047 -1048 // Cancel at_close_start token, which cancels running netreports. -1049 self.sock.shutdown.at_close_start.cancel(); -1050 -1051 self.sock.address_lookup().clear(); -1052 -1053 // Cancel all actors. -1054 self.sock.shutdown.at_endpoint_closed.cancel(); -1055 -1056 // Aborts all tasks, not waiting for any to close gracefully. -1057 self.runtime.abort(); -1058 -1059 self.actor_task.lock().expect("poisoned").take(); -1060 -1061 self.sock.shutdown.closed.store(true, Ordering::SeqCst); -1062 trace!("socket closed"); -1063 } -1064 -1065 pub(crate) async fn insert_relay( -1066 &self, -1067 relay: RelayUrl, -1068 endpoint: Arc<RelayConfig>, -1069 ) -> Option<Arc<RelayConfig>> { -1070 let res = self.relay_map.insert(relay, endpoint); -1071 self.actor_sender -1072 .send(ActorMessage::RelayMapChange) -1073 .await -1074 .ok(); -1075 res -1076 } -1077 -1078 pub(crate) async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { -1079 let res = self.relay_map.remove(relay); -1080 self.actor_sender -1081 .send(ActorMessage::RelayMapChange) -1082 .await -1083 .ok(); -1084 res -1085 } -1086 -1087 /// Call to notify the system of potential network changes. -1088 pub(crate) async fn network_change(&self) { -1089 self.actor_sender -1090 .send(ActorMessage::NetworkChange) -1091 .await -1092 .ok(); -1093 } -1094 -1095 #[cfg(test)] -1096 async fn force_network_change(&self, is_major: bool) { -1097 self.actor_sender -1098 .send(ActorMessage::ForceNetworkChange(is_major)) -1099 .await -1100 .ok(); -1101 } -1102 -1103 /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`]. -1104 /// -1105 /// This starts a `RemoteStateActor` for the remote if not running already, and then checks -1106 /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for -1107 /// at least one result to arrive. -1108 /// -1109 /// Returns `Ok(Ok(EndpointIdMappedAddr))` if there is a known path or Address Lookup produced -1110 /// at least one result. This does not mean there is a working path, only that we have at least -1111 /// one transport address we can try to connect to. -1112 /// -1113 /// Returns `Ok(Err(address_lookup_error))` if there are no known paths to the remote and Address Lookup -1114 /// failed or produced no results. This means that we don't have any transport address for -1115 /// the remote, thus there is no point in trying to connect over the quinn endpoint. -1116 /// -1117 /// Returns `Err(RemoteStateActorStoppedError)` if the `RemoteStateActor` for the remote has stopped, -1118 /// which may never happen and thus is a bug if it does. -1119 pub(crate) async fn resolve_remote( -1120 &self, -1121 addr: EndpointAddr, -1122 ) -> Result<Result<EndpointIdMappedAddr, AddressLookupError>, RemoteStateActorStoppedError> -1123 { -1124 let (tx, rx) = oneshot::channel(); -1125 self.actor_sender -1126 .send(ActorMessage::ResolveRemote(addr, tx)) -1127 .await -1128 .ok(); -1129 rx.await.map_err(|_| RemoteStateActorStoppedError::new())? -1130 } -1131 -1132 /// Fetches the [`RemoteInfo`] about a remote from the `RemoteStateActor`. -1133 /// -1134 /// Returns `None` if no actor is running for the remote. -1135 pub(crate) async fn remote_info(&self, id: EndpointId) -> Option<RemoteInfo> { -1136 let (tx, rx) = oneshot::channel(); -1137 self.actor_sender -1138 .send(ActorMessage::RemoteInfo(id, tx)) -1139 .await -1140 .ok()?; -1141 rx.await.ok() -1142 } -1143 -1144 /// Registers the connection in the `RemoteStateActor`. -1145 /// -1146 /// The actor is responsible for holepunching and opening additional paths to this -1147 /// connection. -1148 /// -1149 /// Returns a future that resolves to [`PathWatchable`]. -1150 /// -1151 /// The returned future is `'static`, so it can be stored without being liftetime-bound to `&self`. -1152 pub(crate) fn register_connection( -1153 &self, -1154 remote: EndpointId, -1155 conn: WeakConnectionHandle, -1156 ) -> impl Future<Output = Result<PathWatchable, RemoteStateActorStoppedError>> + Send + 'static -1157 { -1158 let (tx, rx) = oneshot::channel(); -1159 let sender = self.actor_sender.clone(); -1160 async move { -1161 sender -1162 .send(ActorMessage::AddConnection(remote, conn, tx)) -1163 .await -1164 .map_err(|_| RemoteStateActorStoppedError::new())?; -1165 rx.await.map_err(|_| RemoteStateActorStoppedError::new()) -1166 } -1167 } -1168} -1169 -1170#[derive(derive_more::Debug)] -1171#[allow(clippy::enum_variant_names)] -1172enum ActorMessage { -1173 NetworkChange, -1174 RelayMapChange, -1175 #[debug("ResolveRemote(..)")] -1176 ResolveRemote( -1177 EndpointAddr, -1178 oneshot::Sender< -1179 Result<Result<EndpointIdMappedAddr, AddressLookupError>, RemoteStateActorStoppedError>, -1180 >, -1181 ), -1182 #[debug("AddConnection(..)")] -1183 AddConnection( -1184 EndpointId, -1185 WeakConnectionHandle, -1186 oneshot::Sender<PathWatchable>, -1187 ), -1188 #[debug("RemoteInfo(..)")] -1189 RemoteInfo(EndpointId, oneshot::Sender<RemoteInfo>), -1190 #[cfg(test)] -1191 ForceNetworkChange(bool), -1192} -1193 -1194struct Actor { -1195 sock: Arc<Socket>, -1196 /// Tracks the networkmap endpoint entity for each endpoint discovery key. -1197 remote_map: RemoteMap, -1198 /// When set, is an AfterFunc timer that will call Socket::do_periodic_stun. -1199 periodic_re_stun_timer: time::Interval, -1200 -1201 network_monitor: netmon::Monitor, -1202 netmon_watcher: n0_watcher::Direct<netmon::State>, -1203 network_change_sender: transports::NetworkChangeSender, -1204 /// Indicates the direct addr update state. -1205 direct_addr_update_state: DirectAddrUpdateState, -1206 direct_addr_done_rx: mpsc::Receiver<()>, -1207} -1208 -1209impl Actor { -1210 async fn run( -1211 mut self, -1212 mut msg_receiver: mpsc::Receiver<ActorMessage>, -1213 shutdown_token: CancellationToken, -1214 mut local_addrs_watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1215 ) { -1216 // Setup network monitoring -1217 let mut current_netmon_state = self.netmon_watcher.get(); -1218 -1219 #[cfg(not(wasm_browser))] -1220 let mut portmap_watcher = self -1221 .direct_addr_update_state -1222 .port_mapper -1223 .watch_external_address(); -1224 -1225 let mut receiver_closed = false; -1226 #[cfg_attr(wasm_browser, allow(unused_mut))] -1227 let mut portmap_watcher_closed = false; -1228 -1229 let mut net_report_watcher = self.sock.net_report.watch(); -1230 -1231 // ensure we are doing an initial publish of our addresses -1232 self.sock.publish_my_addr(); -1233 -1234 while !shutdown_token.is_cancelled() { -1235 self.sock.metrics.socket.actor_tick_main.inc(); -1236 #[cfg(not(wasm_browser))] -1237 let portmap_watcher_changed = portmap_watcher.changed(); -1238 #[cfg(wasm_browser)] -1239 let portmap_watcher_changed = n0_future::future::pending(); -1240 -1241 tokio::select! { -1242 _ = shutdown_token.cancelled() => { -1243 debug!("tick: shutting down"); -1244 return; -1245 } -1246 msg = msg_receiver.recv(), if !receiver_closed => { -1247 let Some(msg) = msg else { -1248 trace!("tick: socket receiver closed"); -1249 self.sock.metrics.socket.actor_tick_other.inc(); -1250 -1251 receiver_closed = true; -1252 continue; -1253 }; -1254 -1255 trace!(?msg, "tick: msg"); -1256 self.sock.metrics.socket.actor_tick_msg.inc(); -1257 self.handle_actor_message(msg).await; -1258 } -1259 tick = self.periodic_re_stun_timer.tick() => { -1260 trace!("tick: re_stun {:?}", tick); -1261 self.sock.metrics.socket.actor_tick_re_stun.inc(); -1262 self.re_stun(UpdateReason::Periodic); -1263 } -1264 new_addr = local_addrs_watcher.updated() => { -1265 match new_addr { -1266 Ok(addrs) => { -1267 if !addrs.is_empty() { -1268 trace!(?addrs, "local addrs"); -1269 self.sock.publish_my_addr(); -1270 } -1271 } -1272 Err(_) => { -1273 warn!("local addr watcher stopped"); -1274 } -1275 } -1276 } -1277 report = net_report_watcher.updated() => { -1278 match report { -1279 Ok((report, _)) => { -1280 self.handle_net_report_report(report); -1281 #[cfg(not(wasm_browser))] -1282 { -1283 self.periodic_re_stun_timer = new_re_stun_timer(true); -1284 } -1285 } -1286 Err(_) => { -1287 warn!("net report watcher stopped"); -1288 } -1289 } -1290 } -1291 reason = self.direct_addr_done_rx.recv() => { -1292 match reason { -1293 Some(()) => { -1294 // check if a new run needs to be scheduled -1295 let state = self.netmon_watcher.get(); -1296 self.direct_addr_update_state.try_run(state.into()); -1297 } -1298 None => { -1299 warn!("direct addr watcher died"); -1300 } -1301 } -1302 } -1303 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1304 #[cfg(not(wasm_browser))] -1305 { -1306 if change.is_err() { -1307 trace!("tick: portmap watcher closed"); -1308 self.sock.metrics.socket.actor_tick_other.inc(); -1309 -1310 portmap_watcher_closed = true; -1311 continue; -1312 } -1313 -1314 trace!("tick: portmap changed"); -1315 self.sock.metrics.socket.actor_tick_portmap_changed.inc(); -1316 let new_external_address = *portmap_watcher.borrow(); -1317 debug!("external address updated: {new_external_address:?}"); -1318 self.re_stun(UpdateReason::PortmapUpdated); -1319 } -1320 #[cfg(wasm_browser)] -1321 let _unused_in_browsers = change; -1322 }, -1323 state = self.netmon_watcher.updated() => { -1324 let Ok(state) = state else { -1325 trace!("tick: link change receiver closed"); -1326 self.sock.metrics.socket.actor_tick_other.inc(); -1327 continue; -1328 }; -1329 let is_major = state.is_major_change(&current_netmon_state); -1330 event!( -1331 target: "iroh::_events::link_change", -1332 Level::DEBUG, -1333 ?state, -1334 is_major -1335 ); -1336 current_netmon_state = state; -1337 self.sock.metrics.socket.actor_link_change.inc(); -1338 self.handle_network_change(is_major).await; -1339 } -1340 eid = poll_fn(|cx| self.remote_map.poll_cleanup(cx)) => { -1341 trace!(%eid, "cleaned up RemoteStateActor"); -1342 } -1343 else => { -1344 trace!("tick: else"); -1345 } -1346 } -1347 } -1348 } -1349 -1350 async fn handle_network_change(&mut self, is_major: bool) { -1351 debug!(is_major, "link change detected"); -1352 -1353 if is_major { -1354 if let Err(err) = self.network_change_sender.rebind() { -1355 warn!("failed to rebind transports: {err:?}"); -1356 } -1357 -1358 #[cfg(not(wasm_browser))] -1359 self.sock.dns_resolver.reset().await; -1360 self.re_stun(UpdateReason::LinkChangeMajor); -1361 } else { -1362 self.re_stun(UpdateReason::LinkChangeMinor); -1363 } -1364 -1365 self.remote_map.on_network_change(is_major); -1366 } -1367 -1368 fn handle_relay_map_change(&mut self) { -1369 self.re_stun(UpdateReason::RelayMapChange); -1370 } -1371 -1372 fn re_stun(&mut self, why: UpdateReason) { -1373 let state = self.netmon_watcher.get(); -1374 self.direct_addr_update_state -1375 .schedule_run(why, state.into()); -1376 } -1377 -1378 /// Processes an incoming actor message. -1379 /// -1380 /// Returns `true` if it was a shutdown. -1381 async fn handle_actor_message(&mut self, msg: ActorMessage) { -1382 match msg { -1383 ActorMessage::NetworkChange => { -1384 self.network_monitor.network_change().await.ok(); -1385 } -1386 ActorMessage::RelayMapChange => { -1387 self.handle_relay_map_change(); -1388 } -1389 ActorMessage::ResolveRemote(addr, tx) => { -1390 tx.send(self.remote_map.resolve_remote(addr).await).ok(); -1391 } -1392 ActorMessage::RemoteInfo(id, tx) => { -1393 if let Some(info) = self.remote_map.remote_info(id).await { -1394 tx.send(info).ok(); -1395 } -1396 } -1397 ActorMessage::AddConnection(remote, conn, tx) => { -1398 if let Some(watcher) = self.remote_map.add_connection(remote, conn).await { -1399 tx.send(watcher).ok(); -1400 } -1401 } -1402 #[cfg(test)] -1403 ActorMessage::ForceNetworkChange(is_major) => { -1404 self.handle_network_change(is_major).await; -1405 } -1406 } -1407 } -1408 -1409 /// Updates the direct addresses of this socket. -1410 /// -1411 /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of -1412 /// direct addresses from: -1413 /// -1414 /// - The portmapper. -1415 /// - A net_report report. -1416 /// - The local interfaces IP addresses. -1417 #[cfg(not(wasm_browser))] -1418 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1419 let portmap_watcher = self -1420 .direct_addr_update_state -1421 .port_mapper -1422 .watch_external_address(); -1423 -1424 // We only want to have one DirectAddr for each SocketAddr we have. So we store -1425 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -1426 // DirectAddr from each entry. -1427 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -1428 -1429 // First add PortMapper provided addresses. -1430 let maybe_port_mapped = *portmap_watcher.borrow(); -1431 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -1432 addrs -1433 .entry(portmap_ext) -1434 .or_insert(DirectAddrType::Portmapped); -1435 } -1436 -1437 // Next add STUN addresses from the net_report report. -1438 if let Some(net_report_report) = net_report_report { -1439 if let Some(global_v4) = net_report_report.global_v4 { -1440 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); -1441 -1442 // If they're behind a hard NAT and are using a fixed -1443 // port locally, assume they might've added a static -1444 // port mapping on their router to the same explicit -1445 // port that we are running with. Worst case it's an invalid candidate mapping. -1446 let port = self.sock.ip_bind_addrs().iter().find_map(|addr| { -1447 if addr.port() != 0 { -1448 Some(addr.port()) -1449 } else { -1450 None -1451 } -1452 }); -1453 -1454 if let Some(port) = port -1455 && net_report_report -1456 .mapping_varies_by_dest() -1457 .unwrap_or_default() -1458 { -1459 let mut addr = global_v4; -1460 addr.set_port(port); -1461 addrs -1462 .entry(addr.into()) -1463 .or_insert(DirectAddrType::Qad4LocalPort); -1464 } -1465 } -1466 if let Some(global_v6) = net_report_report.global_v6 { -1467 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); -1468 } -1469 } -1470 -1471 self.collect_local_addresses(&mut addrs); -1472 -1473 // Finally create and store store all these direct addresses and send any -1474 // queued call-me-maybe messages. -1475 self.sock.store_direct_addresses( -1476 addrs -1477 .iter() -1478 .map(|(addr, typ)| DirectAddr { -1479 addr: *addr, -1480 typ: *typ, -1481 }) -1482 .collect(), -1483 ); -1484 } -1485 -1486 #[cfg(not(wasm_browser))] -1487 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { -1488 // Matches the addresses that have been bound vs the requested ones. -1489 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -1490 .sock -1491 .ip_bind_addrs() -1492 .iter() -1493 .copied() -1494 .zip(self.sock.ip_local_addrs()) -1495 .collect(); -1496 -1497 // Do we listen on any IPv4 unspecified address? -1498 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -1499 if a.is_ipv4() && a.ip().is_unspecified() { -1500 Some(a.port()) -1501 } else { -1502 None -1503 } -1504 }); -1505 // Do we listen on any IPv6 unspecified address? -1506 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -1507 if a.is_ipv6() && a.ip().is_unspecified() { -1508 Some(a.port()) -1509 } else { -1510 None -1511 } -1512 }); -1513 -1514 // If a socket is bound to the unspecified address, create SocketAddrs for -1515 // each local IP address by pairing it with the port the socket is bound on. -1516 if local_addrs -1517 .iter() -1518 .any(|(_, local)| local.ip().is_unspecified()) -1519 { -1520 let LocalAddresses { -1521 regular: mut ips, -1522 loopback, -1523 } = self.netmon_watcher.get().local_addresses; -1524 if ips.is_empty() && addrs.is_empty() { -1525 // Include loopback addresses only if there are no other interfaces -1526 // or public addresses, this allows testing offline. -1527 ips = loopback; -1528 } -1529 -1530 for ip in ips { -1531 let port_if_unspecified = match ip { -1532 IpAddr::V4(_) => has_ipv4_unspecified, -1533 IpAddr::V6(_) => has_ipv6_unspecified, -1534 }; -1535 if let Some(port) = port_if_unspecified { -1536 let addr = SocketAddr::new(ip, port); -1537 addrs.entry(addr).or_insert(DirectAddrType::Local); -1538 } -1539 } -1540 } -1541 -1542 // If a socket is bound to a specific address, add it. -1543 for (bound, local) in local_addrs { -1544 if !bound.ip().is_unspecified() { -1545 addrs.entry(local).or_insert(DirectAddrType::Local); -1546 } -1547 } -1548 } -1549 -1550 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -1551 if let Some(ref mut r) = report { -1552 self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -1553 if r.preferred_relay.is_none() -1554 && let Some(my_relay) = self.sock.my_relay() -1555 { -1556 r.preferred_relay.replace(my_relay); -1557 } -1558 -1559 // Notify all transports -1560 self.network_change_sender.on_network_change(r); -1561 } -1562 -1563 #[cfg(not(wasm_browser))] -1564 self.update_direct_addresses(report.as_ref()); -1565 } -1566} -1567 -1568fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -1569 // Pick a random duration between 20 and 26 seconds (just under 30s, -1570 // a common UDP NAT timeout on Linux,etc) -1571 let mut rng = rand::rng(); -1572 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); -1573 if initial_delay { -1574 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -1575 time::interval_at(time::Instant::now() + d, d) -1576 } else { -1577 debug!( -1578 "scheduling periodic_stun to run immediately and in {}s", -1579 d.as_secs() -1580 ); -1581 time::interval(d) -1582 } -1583} -1584 -1585/// The discovered direct addresses of this [`Socket`]. -1586/// -1587/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself. -1588/// They include all locally bound ones as well as those discovered by other mechanisms like -1589/// QAD. -1590#[derive(derive_more::Debug, Clone, Default)] -1591struct DiscoveredDirectAddrs { -1592 /// The last set of discovered direct addresses. -1593 addrs: Watchable<BTreeSet<DirectAddr>>, -1594 -1595 /// The last time the direct addresses were updated, even if there was no change. -1596 /// -1597 /// This is only ever None at startup. -1598 updated_at: Arc<RwLock<Option<Instant>>>, -1599} -1600 -1601impl DiscoveredDirectAddrs { -1602 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -1603 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -1604 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -1605 let updated = self.addrs.set(addrs).is_ok(); -1606 if updated { -1607 event!( -1608 target: "iroh::_events::direct_addrs", -1609 Level::DEBUG, -1610 addrs = ?self.addrs.get(), -1611 ); -1612 } -1613 updated -1614 } -1615 -1616 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { -1617 self.addrs.get().into_iter().map(|da| da.addr) -1618 } -1619} -1620 -1621/// A *direct address* on which an iroh-endpoint might be contactable. -1622/// -1623/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be -1624/// contacted. These can come from various sources depending on the network topology of the -1625/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. -1626/// -1627/// This is essentially a combination of our local addresses combined with any reflexive -1628/// transport addresses we discovered using QAD. -1629#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -1630pub struct DirectAddr { -1631 /// The address. -1632 pub addr: SocketAddr, -1633 /// The origin of this direct address. -1634 pub typ: DirectAddrType, -1635} -1636 -1637/// The type of direct address. -1638/// -1639/// These are the various sources or origins from which an iroh endpoint might have found a -1640/// possible [`DirectAddr`]. -1641#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -1642pub enum DirectAddrType { -1643 /// Not yet determined.. -1644 Unknown, -1645 /// A locally bound socket address. -1646 Local, -1647 /// Public internet address discovered via QAD. -1648 /// -1649 /// When possible an iroh endpoint will perform QAD to discover which is the address -1650 /// from which it sends data on the public internet. This can be different from locally -1651 /// bound addresses when the endpoint is on a local network which performs NAT or similar. -1652 Qad, -1653 /// An address assigned by the router using port mapping. -1654 /// -1655 /// When possible an iroh endpoint will request a port mapping from the local router to -1656 /// get a publicly routable direct address. -1657 Portmapped, -1658 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -1659 /// -1660 /// It is possible to configure iroh to bound to a specific port and independently -1661 /// configure the router to forward this port to the iroh endpoint. This indicates a -1662 /// situation like this, which still uses QAD to discover the public address. -1663 Qad4LocalPort, -1664} -1665 -1666impl Display for DirectAddrType { -1667 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -1668 match self { -1669 DirectAddrType::Unknown => write!(f, "?"), -1670 DirectAddrType::Local => write!(f, "local"), -1671 DirectAddrType::Qad => write!(f, "qad"), -1672 DirectAddrType::Portmapped => write!(f, "portmap"), -1673 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -1674 } -1675 } -1676} -1677 -1678#[cfg(test)] -1679mod tests { -1680 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; -1681 -1682 use data_encoding::HEXLOWER; -1683 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; -1684 use iroh_relay::tls::{CaRootConfig, default_provider}; -1685 use n0_error::{Result, StackResultExt, StdResultExt}; -1686 use n0_future::{MergeBounded, StreamExt, time}; -1687 use n0_tracing_test::traced_test; -1688 use n0_watcher::Watcher; -1689 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; -1690 use tokio_util::task::AbortOnDropHandle; -1691 use tracing::{Instrument, error, info, info_span, instrument}; -1692 -1693 use super::Options; -1694 use crate::{ -1695 Endpoint, RelayMode, SecretKey, -1696 address_lookup::memory::MemoryLookup, -1697 dns::DnsResolver, -1698 endpoint::QuicTransportConfig, -1699 socket::{ -1700 EndpointInner, Socket, StaticConfig, TransportConfig, -1701 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, -1702 }, -1703 tls::{self, DEFAULT_MAX_TLS_TICKETS}, -1704 }; -1705 -1706 const ALPN: &[u8] = b"n0/test/1"; -1707 -1708 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { -1709 let secret_key = SecretKey::generate(rng); -1710 let static_config = StaticConfig { -1711 tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), -1712 transport_config: QuicTransportConfig::default(), -1713 keylog: false, -1714 }; -1715 let server_config = static_config.create_server_config(vec![]); -1716 Options { -1717 transports: vec![ -1718 TransportConfig::default_ipv4(), -1719 TransportConfig::default_ipv6(), -1720 ], -1721 secret_key, -1722 proxy_url: None, -1723 dns_resolver: DnsResolver::new(), -1724 server_config, -1725 tls_config: CaRootConfig::default() -1726 .build_client_config(default_provider()) -1727 .unwrap(), -1728 #[cfg(any(test, feature = "test-utils"))] -1729 address_lookup_user_data: None, -1730 metrics: Default::default(), -1731 hooks: Default::default(), -1732 static_config, -1733 } -1734 } -1735 -1736 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1737 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { -1738 info!("accepting conn"); -1739 let conn = ep.accept().await.expect("no conn"); -1740 -1741 info!("accepting"); -1742 let conn = conn.await.context("accepting")?; -1743 info!("accepting bi"); -1744 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; -1745 -1746 info!("reading"); -1747 let val = recv_bi -1748 .read_to_end(usize::MAX) -1749 .await -1750 .std_context("read to end")?; -1751 -1752 info!("replying"); -1753 for chunk in val.chunks(12) { -1754 send_bi.write_all(chunk).await.std_context("write all")?; -1755 } -1756 -1757 info!("finishing"); -1758 send_bi.finish().std_context("finish")?; -1759 send_bi.stopped().await.std_context("stopped")?; -1760 -1761 let stats = conn.stats(); -1762 info!("stats: {:#?}", stats); -1763 if matches!(loss, ExpectedLoss::AlmostNone) { -1764 for info in conn.paths().get().iter() { -1765 assert!( -1766 info.stats().unwrap().lost_packets < 10, -1767 "[receiver] path {:?} should not loose many packets", -1768 info.remote_addr() -1769 ); -1770 } -1771 } -1772 -1773 conn.closed().await; -1774 info!("closed"); -1775 ep.inner()?.quinn_endpoint().wait_idle().await; -1776 info!("idle"); -1777 -1778 Ok(()) -1779 } -1780 -1781 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1782 async fn echo_sender( -1783 ep: Endpoint, -1784 dest_id: EndpointId, -1785 msg: &[u8], -1786 loss: ExpectedLoss, -1787 ) -> Result { -1788 info!("connecting to {}", dest_id.fmt_short()); -1789 let dest = EndpointAddr::new(dest_id); -1790 let conn = ep.connect(dest, ALPN).await?; -1791 -1792 info!("opening bi"); -1793 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; -1794 -1795 info!("writing message"); -1796 send_bi.write_all(msg).await.std_context("write all")?; -1797 -1798 info!("finishing"); -1799 send_bi.finish().std_context("finish")?; -1800 send_bi.stopped().await.std_context("stopped")?; -1801 -1802 info!("reading_to_end"); -1803 let val = recv_bi -1804 .read_to_end(usize::MAX) -1805 .await -1806 .std_context("read to end")?; -1807 assert_eq!( -1808 val, -1809 msg, -1810 "[sender] expected {}, got {}", -1811 HEXLOWER.encode(msg), -1812 HEXLOWER.encode(&val) -1813 ); -1814 -1815 let stats = conn.stats(); -1816 info!("stats: {:#?}", stats); -1817 if matches!(loss, ExpectedLoss::AlmostNone) { -1818 for info in conn.paths().get().iter() { -1819 assert!( -1820 info.stats().unwrap().lost_packets < 10, -1821 "[sender] path {:?} should not loose many packets", -1822 info.remote_addr() -1823 ); -1824 } -1825 } -1826 -1827 conn.close(0u32.into(), b"done"); -1828 info!("closed"); -1829 ep.inner()?.quinn_endpoint().wait_idle().await; -1830 info!("idle"); -1831 Ok(()) -1832 } -1833 -1834 #[derive(Debug, Copy, Clone)] -1835 enum ExpectedLoss { -1836 AlmostNone, -1837 YeahSure, -1838 } -1839 -1840 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -1841 async fn run_roundtrip( -1842 sender: Endpoint, -1843 receiver: Endpoint, -1844 payload: &[u8], -1845 loss: ExpectedLoss, -1846 ) -> Result<()> { -1847 tokio::time::timeout(Duration::from_secs(4), async move { -1848 let send_endpoint_id = sender.id(); -1849 let recv_endpoint_id = receiver.id(); -1850 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); -1851 -1852 let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss))); -1853 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; -1854 let sender_is_err = match sender_res { -1855 Ok(()) => false, -1856 Err(err) => { -1857 error!("[sender] Error:\n{err:#?}"); -1858 true -1859 } -1860 }; -1861 let receiver_is_err = match receiver_task.await { -1862 Ok(Ok(())) => false, -1863 Ok(Err(err)) => { -1864 error!("[receiver] Error:\n{err:#?}"); -1865 true -1866 } -1867 Err(joinerr) => { -1868 if joinerr.is_panic() { -1869 std::panic::resume_unwind(joinerr.into_panic()); -1870 } else { -1871 error!("[receiver] Error:\n{joinerr:#?}"); -1872 } -1873 true -1874 } -1875 }; -1876 if sender_is_err || receiver_is_err { -1877 panic!("Sender or receiver errored"); -1878 } -1879 }) -1880 .await -1881 .std_context("timeout")?; -1882 Ok(()) -1883 } -1884 -1885 /// Returns a pair of endpoints with a shared [`MemoryLookup`]. -1886 /// -1887 /// The endpoints do not use a relay server but can connect to each other via local -1888 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if -1889 /// the endpoints rebind. -1890 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { -1891 let address_lookup = MemoryLookup::new(); -1892 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) -1893 .alpns(vec![ALPN.to_vec()]) -1894 .address_lookup(address_lookup.clone()) -1895 .bind() -1896 .await -1897 .unwrap(); -1898 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) -1899 .alpns(vec![ALPN.to_vec()]) -1900 .address_lookup(address_lookup.clone()) -1901 .bind() -1902 .await -1903 .unwrap(); -1904 address_lookup.add_endpoint_info(ep1.addr()); -1905 address_lookup.add_endpoint_info(ep2.addr()); -1906 -1907 let ep1_addr_stream = ep1.watch_addr().stream(); -1908 let ep2_addr_stream = ep2.watch_addr().stream(); -1909 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); -1910 let task = tokio::spawn(async move { -1911 while let Some(addr) = addr_stream.next().await { -1912 address_lookup.add_endpoint_info(addr); -1913 } -1914 }); -1915 -1916 (AbortOnDropHandle::new(task), ep1, ep2) -1917 } -1918 -1919 #[tokio::test(flavor = "multi_thread")] -1920 #[traced_test] -1921 async fn test_two_devices_roundtrip_quinn_small() -> Result { -1922 let (_guard, m1, m2) = endpoint_pair().await; -1923 -1924 run_roundtrip( -1925 m1.clone(), -1926 m2.clone(), -1927 b"hello m1", -1928 ExpectedLoss::AlmostNone, -1929 ) -1930 .await?; -1931 run_roundtrip( -1932 m2.clone(), -1933 m1.clone(), -1934 b"hello m2", -1935 ExpectedLoss::AlmostNone, -1936 ) -1937 .await?; -1938 Ok(()) -1939 } -1940 -1941 #[tokio::test(flavor = "multi_thread")] -1942 #[traced_test] -1943 async fn test_two_devices_roundtrip_quinn_large() -> Result { -1944 let (_guard, m1, m2) = endpoint_pair().await; -1945 let mut data = vec![0u8; 10 * 1024]; -1946 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1947 rng.fill_bytes(&mut data); -1948 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?; -1949 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?; -1950 -1951 Ok(()) -1952 } -1953 -1954 #[tokio::test] -1955 #[traced_test] -1956 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { -1957 let (_guard, m1, m2) = endpoint_pair().await; -1958 -1959 println!("Net change"); -1960 m1.inner()?.force_network_change(true).await; -1961 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -1962 -1963 let _handle = AbortOnDropHandle::new(tokio::spawn({ -1964 let endpoint = m2.clone(); -1965 async move { -1966 while let Some(incoming) = endpoint.accept().await { -1967 println!("Incoming first conn!"); -1968 let conn = incoming.await.anyerr()?; -1969 conn.closed().await; -1970 } -1971 -1972 n0_error::Ok(()) -1973 } -1974 })); -1975 -1976 println!("first conn!"); -1977 let conn = m1.connect(m2.addr(), ALPN).await?; -1978 println!("Closing first conn"); -1979 conn.close(0u32.into(), b"bye lolz"); -1980 conn.closed().await; -1981 println!("Closed first conn"); -1982 -1983 Ok(()) -1984 } -1985 -1986 fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration { -1987 let delay = rng.random_range(1..=5); -1988 Duration::from_millis(delay * 50) -1989 } -1990 -1991 /// Same structure as `test_two_devices_roundtrip_quinn`, but interrupts regularly -1992 /// with (simulated) network changes. -1993 /// Regular network changes to m1 only. -1994 #[tokio::test(flavor = "multi_thread")] -1995 #[traced_test] -1996 async fn test_two_devices_roundtrip_network_change_only_a() -> Result { -1997 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1998 let (_guard, m1, m2) = endpoint_pair().await; -1999 -2000 let _network_change_guard = { -2001 let m1 = m1.clone(); -2002 let mut rng = rng.clone(); -2003 let task = tokio::spawn(async move { -2004 loop { -2005 info!("[m1] network change"); -2006 m1.inner() -2007 .expect("haven't closed the endpoint yet") -2008 .force_network_change(true) -2009 .await; -2010 time::sleep(offset(&mut rng)).await; -2011 } -2012 }); -2013 AbortOnDropHandle::new(task) -2014 }; -2015 -2016 let mut data = vec![0u8; 10 * 1024]; -2017 rng.fill_bytes(&mut data); -2018 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; -2019 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; -2020 -2021 Ok(()) -2022 } -2023 -2024 /// Regular network changes to both m1 and m2. -2025 #[tokio::test(flavor = "multi_thread")] -2026 #[traced_test] -2027 async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result { -2028 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2029 let (_guard, m1, m2) = endpoint_pair().await; -2030 -2031 let _network_change_guard = { -2032 let m1 = m1.clone(); -2033 let m2 = m2.clone(); -2034 let mut rng = rng.clone(); -2035 let task = tokio::spawn(async move { -2036 info!("-- [m1] network change"); -2037 m1.inner() -2038 .expect("haven't closed the endpoint yet") -2039 .force_network_change(true) -2040 .await; -2041 info!("-- [m2] network change"); -2042 m2.inner() -2043 .expect("haven't closed the endpoint yet") -2044 .force_network_change(true) -2045 .await; -2046 time::sleep(offset(&mut rng)).await; -2047 }); -2048 AbortOnDropHandle::new(task) -2049 }; -2050 -2051 let mut data = vec![0u8; 10 * 1024]; -2052 rng.fill_bytes(&mut data); -2053 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; -2054 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; -2055 -2056 Ok(()) -2057 } -2058 -2059 #[tokio::test(flavor = "multi_thread")] -2060 #[traced_test] -2061 async fn test_two_devices_setup_teardown() -> Result { -2062 for i in 0..10 { -2063 info!("-- round {i}"); -2064 info!("setting up stack"); -2065 let (_guard, m1, m2) = endpoint_pair().await; -2066 -2067 info!("closing endpoints"); -2068 let sock1 = m1.inner()?; -2069 let sock2 = m2.inner()?; -2070 m1.close().await; -2071 m2.close().await; -2072 -2073 assert!(sock1.is_closed()); -2074 assert!(sock2.is_closed()); -2075 } -2076 Ok(()) -2077 } -2078 -2079 #[tokio::test] -2080 #[traced_test] -2081 async fn test_direct_addresses() { -2082 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2083 let sock = EndpointInner::new(default_options(&mut rng)).await.unwrap(); -2084 -2085 // See if we can get endpoints. -2086 let eps0 = sock.ip_addrs().get(); -2087 info!("{eps0:?}"); -2088 assert!(!eps0.is_empty()); -2089 -2090 // Getting the endpoints again immediately should give the same results. -2091 let eps1 = sock.ip_addrs().get(); -2092 info!("{eps1:?}"); -2093 assert_eq!(eps0, eps1); -2094 } -2095 -2096 /// Creates a new [`quinn::Endpoint`] hooked up to a [`Socket`]. -2097 /// -2098 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -2099 /// connections using [`ALPN`]. -2100 /// -2101 /// Use [`socket_connect`] to establish connections. -2102 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] -2103 async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> { -2104 let static_config = StaticConfig { -2105 tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), -2106 transport_config: QuicTransportConfig::default(), -2107 keylog: true, -2108 }; -2109 let server_config = static_config.create_server_config(vec![ALPN.to_vec()]); -2110 -2111 let dns_resolver = DnsResolver::new(); -2112 let opts = Options { -2113 transports: vec![ -2114 TransportConfig::default_ipv4(), -2115 TransportConfig::default_ipv6(), -2116 ], -2117 secret_key: secret_key.clone(), -2118 address_lookup_user_data: None, -2119 dns_resolver, -2120 proxy_url: None, -2121 server_config, -2122 tls_config: CaRootConfig::default() -2123 .build_client_config(default_provider()) -2124 .unwrap(), -2125 metrics: Default::default(), -2126 hooks: Default::default(), -2127 static_config, -2128 }; -2129 let sock = Socket::spawn(opts).await?; -2130 Ok(sock) -2131 } -2132 -2133 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. -2134 /// -2135 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2136 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2137 async fn socket_connect( -2138 ep: quinn::Endpoint, -2139 ep_secret_key: SecretKey, -2140 addr: EndpointIdMappedAddr, -2141 endpoint_id: EndpointId, -2142 ) -> Result<quinn::Connection> { -2143 // Endpoint::connect sets this, do the same to have similar behaviour. -2144 let mut transport_config = quinn::TransportConfig::default(); -2145 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -2146 -2147 socket_connect_with_transport_config( -2148 ep, -2149 ep_secret_key, -2150 addr, -2151 endpoint_id, -2152 Arc::new(transport_config), -2153 ) -2154 .await -2155 } -2156 -2157 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. -2158 /// -2159 /// This version allows customising the transport config. -2160 /// -2161 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2162 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2163 async fn socket_connect_with_transport_config( -2164 ep: quinn::Endpoint, -2165 ep_secret_key: SecretKey, -2166 mapped_addr: EndpointIdMappedAddr, -2167 endpoint_id: EndpointId, -2168 transport_config: Arc<quinn::TransportConfig>, -2169 ) -> Result<quinn::Connection> { -2170 let alpns = vec![ALPN.to_vec()]; -2171 let quic_client_config = -2172 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2173 .make_client_config(alpns, true); -2174 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -2175 client_config.transport_config(transport_config); -2176 let connect = ep -2177 .connect_with( -2178 client_config, -2179 mapped_addr.private_socket_addr(), -2180 &tls::name::encode(endpoint_id), -2181 ) -2182 .std_context("connect")?; -2183 let connection = connect.await.anyerr()?; -2184 Ok(connection) -2185 } -2186 -2187 #[tokio::test] -2188 #[traced_test] -2189 async fn test_try_send_no_send_addr() { -2190 // Regression test: if there is no send_addr we should keep being able to use the -2191 // Endpoint. -2192 -2193 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2194 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2195 let endpoint_id_2 = secret_key_2.public(); -2196 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); -2197 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); -2198 -2199 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); -2200 -2201 // Generate an address not present in the RemoteMap. -2202 let bad_addr = EndpointIdMappedAddr::generate(); -2203 -2204 // 500ms is rather fast here. Running this locally it should always be the correct -2205 // timeout. If this is too slow however the test will not become flaky as we are -2206 // expecting the timeout, we might just get the timeout for the wrong reason. But -2207 // this speeds up the test. -2208 let res = tokio::time::timeout( -2209 Duration::from_millis(500), -2210 socket_connect( -2211 sock_1.quinn_endpoint().clone(), -2212 secret_key_1.clone(), -2213 bad_addr, -2214 endpoint_id_missing_endpoint, -2215 ), -2216 ) -2217 .await; -2218 assert!(res.is_err(), "expecting timeout"); -2219 -2220 // Now check we can still create another connection with this endpoint. -2221 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); -2222 -2223 // This needs an accept task -2224 let accept_task = tokio::spawn({ -2225 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2226 let incoming = ep.accept().await.std_context("no incoming")?; -2227 let _conn = incoming -2228 .accept() -2229 .std_context("accept")? -2230 .await -2231 .std_context("accepting")?; -2232 -2233 // Keep this connection alive for a while -2234 tokio::time::sleep(Duration::from_secs(10)).await; -2235 info!("accept finished"); -2236 Ok(()) -2237 } -2238 let ep = sock_2.quinn_endpoint().clone(); -2239 async move { -2240 if let Err(err) = accept(ep).await { -2241 error!("{err:#}"); -2242 } -2243 } -2244 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) -2245 }); -2246 let _accept_task = AbortOnDropHandle::new(accept_task); -2247 -2248 let addrs = sock_2 -2249 .ip_addrs() -2250 .get() -2251 .into_iter() -2252 .map(|x| TransportAddr::Ip(x.addr)); -2253 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); -2254 let addr = sock_1 -2255 .resolve_remote(endpoint_addr_2) -2256 .await -2257 .unwrap() -2258 .unwrap(); -2259 let res = tokio::time::timeout( -2260 Duration::from_secs(10), -2261 socket_connect( -2262 sock_1.quinn_endpoint().clone(), -2263 secret_key_1.clone(), -2264 addr, -2265 endpoint_id_2, -2266 ), -2267 ) -2268 .await -2269 .expect("timeout while connecting"); -2270 -2271 // aka assert!(res.is_ok()) but with nicer error reporting. -2272 res.unwrap(); -2273 -2274 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -2275 // much internal state for now. -2276 } -2277 -2278 #[tokio::test] -2279 #[traced_test] -2280 async fn test_try_send_no_udp_addr_or_relay_url() { -2281 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -2282 // behaviour of Socket::try_send. -2283 -2284 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2285 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2286 let endpoint_id_2 = secret_key_2.public(); -2287 -2288 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); -2289 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); -2290 let ep_2 = sock_2.quinn_endpoint().clone(); -2291 -2292 // We need a task to accept the connection. -2293 let accept_task = tokio::spawn({ -2294 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2295 let incoming = ep.accept().await.std_context("no incoming")?; -2296 let conn = incoming -2297 .accept() -2298 .std_context("accept")? -2299 .await -2300 .std_context("connecting")?; -2301 let mut stream = conn.accept_uni().await.std_context("accept uni")?; -2302 stream -2303 .read_to_end(1 << 16) -2304 .await -2305 .std_context("read to end")?; -2306 info!("accept finished"); -2307 Ok(()) -2308 } -2309 async move { -2310 if let Err(err) = accept(ep_2).await { -2311 error!("{err:#}"); -2312 } -2313 } -2314 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) -2315 }); -2316 let _accept_task = AbortOnDropHandle::new(accept_task); -2317 -2318 // Add an entry in the RemoteMap of ep_1 with an invalid socket address -2319 let empty_addr_2 = EndpointAddr::from_parts( -2320 endpoint_id_2, -2321 [TransportAddr::Ip( -2322 // Reserved IP range for documentation (unreachable) -2323 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), -2324 )], -2325 ); -2326 let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); -2327 -2328 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -2329 // not take forever. You need to check the log output to verify this is really -2330 // triggering the correct error. -2331 // In test_try_send_no_send_addr() above you may have noticed we used -2332 // tokio::time::timeout() on the connection attempt instead. Here however we want -2333 // Quinn itself to have fully given up on the connection attempt because we will -2334 // later connect to **the same** endpoint. If Quinn did not give up on the connection -2335 // we'd close it on drop, and the retransmits of the close packets would interfere -2336 // with the next handshake, closing it during the handshake. This makes the test a -2337 // little slower though. -2338 let mut transport_config = quinn::TransportConfig::default(); -2339 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -2340 let res = socket_connect_with_transport_config( -2341 sock_1.quinn_endpoint().clone(), -2342 secret_key_1.clone(), -2343 addr_2, -2344 endpoint_id_2, -2345 Arc::new(transport_config), -2346 ) -2347 .await; -2348 assert!(res.is_err(), "expected timeout"); -2349 info!("first connect timed out as expected"); -2350 -2351 // Provide correct addressing information -2352 let correct_addr_2 = EndpointAddr::from_parts( -2353 endpoint_id_2, -2354 sock_2 -2355 .ip_addrs() -2356 .get() -2357 .into_iter() -2358 .map(|x| TransportAddr::Ip(x.addr)), -2359 ); -2360 let addr_2a = sock_1 -2361 .resolve_remote(correct_addr_2) -2362 .await -2363 .unwrap() -2364 .unwrap(); -2365 assert_eq!(addr_2, addr_2a); -2366 -2367 // We can now connect -2368 tokio::time::timeout(Duration::from_secs(10), async move { -2369 info!("establishing new connection"); -2370 let conn = socket_connect( -2371 sock_1.quinn_endpoint().clone(), -2372 secret_key_1.clone(), -2373 addr_2, -2374 endpoint_id_2, -2375 ) -2376 .await -2377 .unwrap(); -2378 info!("have connection"); -2379 let mut stream = conn.open_uni().await.unwrap(); -2380 stream.write_all(b"hello").await.unwrap(); -2381 stream.finish().unwrap(); -2382 stream.stopped().await.unwrap(); -2383 info!("finished stream"); -2384 }) -2385 .await -2386 .expect("connection timed out"); -2387 -2388 // TODO: could remove the addresses again, send, add it back and see it recover. -2389 // But we don't have that much private access to the RemoteMap. This will do for now. -2390 } -2391}
    \ No newline at end of file +872 #[cfg(not(wasm_browser))] +873 let net_report_config = { +874 // Set a `QuicConfig` for address discovery (QAD), but only if we have IP transports. +875 // +876 // If there are no IP transports configured, then we don't set a QuicConfig. +877 // If we would, the `quinn::Endpoint` passed along will not have IP connectivity, +878 // and the QAD probes that connect to the relay's QUIC endpoints would time out +879 // because all outgoing packets to IP destinations would be dropped. +880 let qad_config = has_ip_transports.then(|| QuicConfig { +881 ep: endpoint.clone(), +882 client_config: tls_config.clone(), +883 ipv4: true, +884 ipv6: has_ipv6_transport, +885 }); +886 net_report::Options::new(tls_config.clone()).quic_config(qad_config) +887 }; +888 +889 #[cfg(wasm_browser)] +890 let net_report_config = net_report::Options::default(); +891 +892 let net_reporter = net_report::Client::new( +893 #[cfg(not(wasm_browser))] +894 dns_resolver, +895 relay_map.clone(), +896 net_report_config, +897 metrics.net_report.clone(), +898 ); +899 +900 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +901 let direct_addr_update_state = DirectAddrUpdateState::new( +902 sock.clone(), +903 #[cfg(not(wasm_browser))] +904 port_mapper, +905 Arc::new(AsyncMutex::new(net_reporter)), +906 relay_map, +907 direct_addr_done_tx, +908 sock.shutdown.at_close_start.child_token(), +909 ); +910 +911 let netmon_watcher = network_monitor.interface_state(); +912 +913 #[cfg_attr(not(wasm_browser), allow(unused_mut))] +914 let mut actor = Actor { +915 sock: sock.clone(), +916 remote_map, +917 periodic_re_stun_timer: new_re_stun_timer(false), +918 network_monitor, +919 netmon_watcher, +920 direct_addr_update_state, +921 network_change_sender, +922 direct_addr_done_rx, +923 }; +924 // Initialize addresses +925 #[cfg(not(wasm_browser))] +926 actor.update_direct_addresses(None); +927 +928 let actor_task = task::spawn( +929 actor +930 .run( +931 actor_receiver, +932 shutdown_token.child_token(), +933 local_addrs_watch, +934 ) +935 .instrument(info_span!("actor")), +936 ); +937 +938 let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task))); +939 +940 Ok(EndpointInner { +941 sock, +942 actor_sender, +943 actor_task, +944 endpoint, +945 runtime, +946 static_config, +947 }) +948 } +949 +950 /// Returns a reference to the underlying [`quinn::Endpoint`]. +951 pub(crate) fn quinn_endpoint(&self) -> &quinn::Endpoint { +952 &self.endpoint +953 } +954 +955 /// Closes the connection. +956 /// +957 /// Only the first close does anything. Any later closes return nil. Polling the socket +958 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely +959 /// after this call. +960 /// +961 /// [`Poll::Pending`]: std::task::Poll::Pending +962 #[instrument(skip_all)] +963 pub(crate) async fn close(&self) { +964 if self.sock.is_closed() || self.sock.is_closing() { +965 return; +966 } +967 trace!(me = ?self.public_key, "socket closing..."); +968 +969 // Cancel at_close_start token, which cancels running netreports. +970 self.sock.shutdown.at_close_start.cancel(); +971 +972 // Remove address lookup services +973 self.sock.address_lookup().clear(); +974 +975 // Initiate closing all connections, and refuse future connections. +976 self.quinn_endpoint().close(0u16.into(), b""); +977 +978 // In the history of this code, this call had been +979 // - removed: https://github.com/n0-computer/iroh/pull/1753 +980 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +981 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +982 // and finally added back in together with this comment. +983 // So before removing this call, please consider carefully. +984 // Among other things, this call tries its best to make sure that any queued close frames +985 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +986 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +987 // This allows the other endpoints for these connections to be notified to release +988 // their resources, or - depending on the protocol - that all data was received. +989 // With the current quinn API, this is the only way to ensure protocol code can use +990 // connection close codes, and close the endpoint properly. +991 // If this call is skipped, then connections that protocols close just shortly before the +992 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +993 trace!("wait_idle start"); +994 self.quinn_endpoint().wait_idle().await; +995 trace!("wait_idle done"); +996 +997 // Start cancellation of all actors. +998 self.sock.shutdown.at_endpoint_closed.cancel(); +999 +1000 // MutexGuard is not held across await points +1001 let task = self.actor_task.lock().expect("poisoned").take(); +1002 if let Some(task) = task { +1003 // give the tasks a moment to shutdown cleanly +1004 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1005 if let Err(err) = task.await { +1006 warn!("unexpected error in task shutdown: {:?}", err); +1007 } +1008 }) +1009 .await; +1010 match shutdown_done { +1011 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1012 Err(time::Elapsed { .. }) => { +1013 // Dropping the task will abort it +1014 warn!("tasks didn't finish in time, aborting"); +1015 } +1016 } +1017 } +1018 +1019 // Waits for the EndpointDriver and all ConnectionDrivers to shut down +1020 // Expects that the `quinn::Endpoint` has been closed before this call, +1021 // otherwise, the runtime will never shutdown. +1022 self.runtime.shutdown().await; +1023 +1024 self.sock.shutdown.closed.store(true, Ordering::SeqCst); +1025 +1026 trace!("socket closed"); +1027 } +1028 +1029 /// Aborts the endpoint ungracefully: +1030 /// +1031 /// - Calls cancellation token that stops running net reports +1032 /// - Removes all address lookup services +1033 /// - Calls cancellation token that stops all the Socket actors +1034 /// - Aborts the runtime +1035 /// - Drops the actor task +1036 /// - Sets the `Socket::is_closed` state to true +1037 /// +1038 /// This does not wait for any current connections or tasks to close gracefully. +1039 /// +1040 /// This should only be called in the `iroh::Endpoint` `Drop` impl when the +1041 /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`. +1042 #[instrument(skip_all)] +1043 pub(crate) fn abort(&self) { +1044 if self.sock.is_closed() || self.sock.is_closing() { +1045 return; +1046 } +1047 trace!(me = ?self.public_key, "aborting socket..."); +1048 +1049 // Cancel at_close_start token, which cancels running netreports. +1050 self.sock.shutdown.at_close_start.cancel(); +1051 +1052 self.sock.address_lookup().clear(); +1053 +1054 // Cancel all actors. +1055 self.sock.shutdown.at_endpoint_closed.cancel(); +1056 +1057 // Aborts all tasks, not waiting for any to close gracefully. +1058 self.runtime.abort(); +1059 +1060 self.actor_task.lock().expect("poisoned").take(); +1061 +1062 self.sock.shutdown.closed.store(true, Ordering::SeqCst); +1063 trace!("socket closed"); +1064 } +1065 +1066 pub(crate) async fn insert_relay( +1067 &self, +1068 relay: RelayUrl, +1069 endpoint: Arc<RelayConfig>, +1070 ) -> Option<Arc<RelayConfig>> { +1071 let res = self.relay_map.insert(relay, endpoint); +1072 self.actor_sender +1073 .send(ActorMessage::RelayMapChange) +1074 .await +1075 .ok(); +1076 res +1077 } +1078 +1079 pub(crate) async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { +1080 let res = self.relay_map.remove(relay); +1081 self.actor_sender +1082 .send(ActorMessage::RelayMapChange) +1083 .await +1084 .ok(); +1085 res +1086 } +1087 +1088 /// Call to notify the system of potential network changes. +1089 pub(crate) async fn network_change(&self) { +1090 self.actor_sender +1091 .send(ActorMessage::NetworkChange) +1092 .await +1093 .ok(); +1094 } +1095 +1096 #[cfg(test)] +1097 async fn force_network_change(&self, is_major: bool) { +1098 self.actor_sender +1099 .send(ActorMessage::ForceNetworkChange(is_major)) +1100 .await +1101 .ok(); +1102 } +1103 +1104 /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`]. +1105 /// +1106 /// This starts a `RemoteStateActor` for the remote if not running already, and then checks +1107 /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for +1108 /// at least one result to arrive. +1109 /// +1110 /// Returns `Ok(Ok(EndpointIdMappedAddr))` if there is a known path or Address Lookup produced +1111 /// at least one result. This does not mean there is a working path, only that we have at least +1112 /// one transport address we can try to connect to. +1113 /// +1114 /// Returns `Ok(Err(address_lookup_error))` if there are no known paths to the remote and Address Lookup +1115 /// failed or produced no results. This means that we don't have any transport address for +1116 /// the remote, thus there is no point in trying to connect over the quinn endpoint. +1117 /// +1118 /// Returns `Err(RemoteStateActorStoppedError)` if the `RemoteStateActor` for the remote has stopped, +1119 /// which may never happen and thus is a bug if it does. +1120 pub(crate) async fn resolve_remote( +1121 &self, +1122 addr: EndpointAddr, +1123 ) -> Result<Result<EndpointIdMappedAddr, AddressLookupError>, RemoteStateActorStoppedError> +1124 { +1125 let (tx, rx) = oneshot::channel(); +1126 self.actor_sender +1127 .send(ActorMessage::ResolveRemote(addr, tx)) +1128 .await +1129 .ok(); +1130 rx.await.map_err(|_| RemoteStateActorStoppedError::new())? +1131 } +1132 +1133 /// Fetches the [`RemoteInfo`] about a remote from the `RemoteStateActor`. +1134 /// +1135 /// Returns `None` if no actor is running for the remote. +1136 pub(crate) async fn remote_info(&self, id: EndpointId) -> Option<RemoteInfo> { +1137 let (tx, rx) = oneshot::channel(); +1138 self.actor_sender +1139 .send(ActorMessage::RemoteInfo(id, tx)) +1140 .await +1141 .ok()?; +1142 rx.await.ok() +1143 } +1144 +1145 /// Registers the connection in the `RemoteStateActor`. +1146 /// +1147 /// The actor is responsible for holepunching and opening additional paths to this +1148 /// connection. +1149 /// +1150 /// Returns a future that resolves to [`PathWatchable`]. +1151 /// +1152 /// The returned future is `'static`, so it can be stored without being liftetime-bound to `&self`. +1153 pub(crate) fn register_connection( +1154 &self, +1155 remote: EndpointId, +1156 conn: WeakConnectionHandle, +1157 ) -> impl Future<Output = Result<PathWatchable, RemoteStateActorStoppedError>> + Send + 'static +1158 { +1159 let (tx, rx) = oneshot::channel(); +1160 let sender = self.actor_sender.clone(); +1161 async move { +1162 sender +1163 .send(ActorMessage::AddConnection(remote, conn, tx)) +1164 .await +1165 .map_err(|_| RemoteStateActorStoppedError::new())?; +1166 rx.await.map_err(|_| RemoteStateActorStoppedError::new()) +1167 } +1168 } +1169} +1170 +1171#[derive(derive_more::Debug)] +1172#[allow(clippy::enum_variant_names)] +1173enum ActorMessage { +1174 NetworkChange, +1175 RelayMapChange, +1176 #[debug("ResolveRemote(..)")] +1177 ResolveRemote( +1178 EndpointAddr, +1179 oneshot::Sender< +1180 Result<Result<EndpointIdMappedAddr, AddressLookupError>, RemoteStateActorStoppedError>, +1181 >, +1182 ), +1183 #[debug("AddConnection(..)")] +1184 AddConnection( +1185 EndpointId, +1186 WeakConnectionHandle, +1187 oneshot::Sender<PathWatchable>, +1188 ), +1189 #[debug("RemoteInfo(..)")] +1190 RemoteInfo(EndpointId, oneshot::Sender<RemoteInfo>), +1191 #[cfg(test)] +1192 ForceNetworkChange(bool), +1193} +1194 +1195struct Actor { +1196 sock: Arc<Socket>, +1197 /// Tracks the networkmap endpoint entity for each endpoint discovery key. +1198 remote_map: RemoteMap, +1199 /// When set, is an AfterFunc timer that will call Socket::do_periodic_stun. +1200 periodic_re_stun_timer: time::Interval, +1201 +1202 network_monitor: netmon::Monitor, +1203 netmon_watcher: n0_watcher::Direct<netmon::State>, +1204 network_change_sender: transports::NetworkChangeSender, +1205 /// Indicates the direct addr update state. +1206 direct_addr_update_state: DirectAddrUpdateState, +1207 direct_addr_done_rx: mpsc::Receiver<()>, +1208} +1209 +1210impl Actor { +1211 async fn run( +1212 mut self, +1213 mut msg_receiver: mpsc::Receiver<ActorMessage>, +1214 shutdown_token: CancellationToken, +1215 mut local_addrs_watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1216 ) { +1217 // Setup network monitoring +1218 let mut current_netmon_state = self.netmon_watcher.get(); +1219 +1220 #[cfg(not(wasm_browser))] +1221 let mut portmap_watcher = self +1222 .direct_addr_update_state +1223 .port_mapper +1224 .watch_external_address(); +1225 +1226 let mut receiver_closed = false; +1227 #[cfg_attr(wasm_browser, allow(unused_mut))] +1228 let mut portmap_watcher_closed = false; +1229 +1230 let mut net_report_watcher = self.sock.net_report.watch(); +1231 +1232 // ensure we are doing an initial publish of our addresses +1233 self.sock.publish_my_addr(); +1234 +1235 while !shutdown_token.is_cancelled() { +1236 self.sock.metrics.socket.actor_tick_main.inc(); +1237 #[cfg(not(wasm_browser))] +1238 let portmap_watcher_changed = portmap_watcher.changed(); +1239 #[cfg(wasm_browser)] +1240 let portmap_watcher_changed = n0_future::future::pending(); +1241 +1242 tokio::select! { +1243 _ = shutdown_token.cancelled() => { +1244 debug!("tick: shutting down"); +1245 return; +1246 } +1247 msg = msg_receiver.recv(), if !receiver_closed => { +1248 let Some(msg) = msg else { +1249 trace!("tick: socket receiver closed"); +1250 self.sock.metrics.socket.actor_tick_other.inc(); +1251 +1252 receiver_closed = true; +1253 continue; +1254 }; +1255 +1256 trace!(?msg, "tick: msg"); +1257 self.sock.metrics.socket.actor_tick_msg.inc(); +1258 self.handle_actor_message(msg).await; +1259 } +1260 tick = self.periodic_re_stun_timer.tick() => { +1261 trace!("tick: re_stun {:?}", tick); +1262 self.sock.metrics.socket.actor_tick_re_stun.inc(); +1263 self.re_stun(UpdateReason::Periodic); +1264 } +1265 new_addr = local_addrs_watcher.updated() => { +1266 match new_addr { +1267 Ok(addrs) => { +1268 if !addrs.is_empty() { +1269 trace!(?addrs, "local addrs"); +1270 self.sock.publish_my_addr(); +1271 } +1272 } +1273 Err(_) => { +1274 warn!("local addr watcher stopped"); +1275 } +1276 } +1277 } +1278 report = net_report_watcher.updated() => { +1279 match report { +1280 Ok((report, _)) => { +1281 self.handle_net_report_report(report); +1282 #[cfg(not(wasm_browser))] +1283 { +1284 self.periodic_re_stun_timer = new_re_stun_timer(true); +1285 } +1286 } +1287 Err(_) => { +1288 warn!("net report watcher stopped"); +1289 } +1290 } +1291 } +1292 reason = self.direct_addr_done_rx.recv() => { +1293 match reason { +1294 Some(()) => { +1295 // check if a new run needs to be scheduled +1296 let state = self.netmon_watcher.get(); +1297 self.direct_addr_update_state.try_run(state.into()); +1298 } +1299 None => { +1300 warn!("direct addr watcher died"); +1301 } +1302 } +1303 } +1304 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1305 #[cfg(not(wasm_browser))] +1306 { +1307 if change.is_err() { +1308 trace!("tick: portmap watcher closed"); +1309 self.sock.metrics.socket.actor_tick_other.inc(); +1310 +1311 portmap_watcher_closed = true; +1312 continue; +1313 } +1314 +1315 trace!("tick: portmap changed"); +1316 self.sock.metrics.socket.actor_tick_portmap_changed.inc(); +1317 let new_external_address = *portmap_watcher.borrow(); +1318 debug!("external address updated: {new_external_address:?}"); +1319 self.re_stun(UpdateReason::PortmapUpdated); +1320 } +1321 #[cfg(wasm_browser)] +1322 let _unused_in_browsers = change; +1323 }, +1324 state = self.netmon_watcher.updated() => { +1325 let Ok(state) = state else { +1326 trace!("tick: link change receiver closed"); +1327 self.sock.metrics.socket.actor_tick_other.inc(); +1328 continue; +1329 }; +1330 let is_major = state.is_major_change(&current_netmon_state); +1331 event!( +1332 target: "iroh::_events::link_change", +1333 Level::DEBUG, +1334 ?state, +1335 is_major +1336 ); +1337 current_netmon_state = state; +1338 self.sock.metrics.socket.actor_link_change.inc(); +1339 self.handle_network_change(is_major).await; +1340 } +1341 eid = poll_fn(|cx| self.remote_map.poll_cleanup(cx)) => { +1342 trace!(%eid, "cleaned up RemoteStateActor"); +1343 } +1344 else => { +1345 trace!("tick: else"); +1346 } +1347 } +1348 } +1349 } +1350 +1351 async fn handle_network_change(&mut self, is_major: bool) { +1352 debug!(is_major, "link change detected"); +1353 +1354 if is_major { +1355 if let Err(err) = self.network_change_sender.rebind() { +1356 warn!("failed to rebind transports: {err:?}"); +1357 } +1358 +1359 #[cfg(not(wasm_browser))] +1360 self.sock.dns_resolver.reset().await; +1361 self.re_stun(UpdateReason::LinkChangeMajor); +1362 } else { +1363 self.re_stun(UpdateReason::LinkChangeMinor); +1364 } +1365 +1366 self.remote_map.on_network_change(is_major); +1367 } +1368 +1369 fn handle_relay_map_change(&mut self) { +1370 self.re_stun(UpdateReason::RelayMapChange); +1371 } +1372 +1373 fn re_stun(&mut self, why: UpdateReason) { +1374 let state = self.netmon_watcher.get(); +1375 self.direct_addr_update_state +1376 .schedule_run(why, state.into()); +1377 } +1378 +1379 /// Processes an incoming actor message. +1380 /// +1381 /// Returns `true` if it was a shutdown. +1382 async fn handle_actor_message(&mut self, msg: ActorMessage) { +1383 match msg { +1384 ActorMessage::NetworkChange => { +1385 self.network_monitor.network_change().await.ok(); +1386 } +1387 ActorMessage::RelayMapChange => { +1388 self.handle_relay_map_change(); +1389 } +1390 ActorMessage::ResolveRemote(addr, tx) => { +1391 tx.send(self.remote_map.resolve_remote(addr).await).ok(); +1392 } +1393 ActorMessage::RemoteInfo(id, tx) => { +1394 if let Some(info) = self.remote_map.remote_info(id).await { +1395 tx.send(info).ok(); +1396 } +1397 } +1398 ActorMessage::AddConnection(remote, conn, tx) => { +1399 if let Some(watcher) = self.remote_map.add_connection(remote, conn).await { +1400 tx.send(watcher).ok(); +1401 } +1402 } +1403 #[cfg(test)] +1404 ActorMessage::ForceNetworkChange(is_major) => { +1405 self.handle_network_change(is_major).await; +1406 } +1407 } +1408 } +1409 +1410 /// Updates the direct addresses of this socket. +1411 /// +1412 /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of +1413 /// direct addresses from: +1414 /// +1415 /// - The portmapper. +1416 /// - A net_report report. +1417 /// - The local interfaces IP addresses. +1418 #[cfg(not(wasm_browser))] +1419 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +1420 let portmap_watcher = self +1421 .direct_addr_update_state +1422 .port_mapper +1423 .watch_external_address(); +1424 +1425 // We only want to have one DirectAddr for each SocketAddr we have. So we store +1426 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +1427 // DirectAddr from each entry. +1428 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +1429 +1430 // First add PortMapper provided addresses. +1431 let maybe_port_mapped = *portmap_watcher.borrow(); +1432 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +1433 addrs +1434 .entry(portmap_ext) +1435 .or_insert(DirectAddrType::Portmapped); +1436 } +1437 +1438 // Next add STUN addresses from the net_report report. +1439 if let Some(net_report_report) = net_report_report { +1440 if let Some(global_v4) = net_report_report.global_v4 { +1441 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); +1442 +1443 // If they're behind a hard NAT and are using a fixed +1444 // port locally, assume they might've added a static +1445 // port mapping on their router to the same explicit +1446 // port that we are running with. Worst case it's an invalid candidate mapping. +1447 let port = self.sock.ip_bind_addrs().iter().find_map(|addr| { +1448 if addr.port() != 0 { +1449 Some(addr.port()) +1450 } else { +1451 None +1452 } +1453 }); +1454 +1455 if let Some(port) = port +1456 && net_report_report +1457 .mapping_varies_by_dest() +1458 .unwrap_or_default() +1459 { +1460 let mut addr = global_v4; +1461 addr.set_port(port); +1462 addrs +1463 .entry(addr.into()) +1464 .or_insert(DirectAddrType::Qad4LocalPort); +1465 } +1466 } +1467 if let Some(global_v6) = net_report_report.global_v6 { +1468 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); +1469 } +1470 } +1471 +1472 self.collect_local_addresses(&mut addrs); +1473 +1474 // Finally create and store store all these direct addresses and send any +1475 // queued call-me-maybe messages. +1476 self.sock.store_direct_addresses( +1477 addrs +1478 .iter() +1479 .map(|(addr, typ)| DirectAddr { +1480 addr: *addr, +1481 typ: *typ, +1482 }) +1483 .collect(), +1484 ); +1485 } +1486 +1487 #[cfg(not(wasm_browser))] +1488 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { +1489 // Matches the addresses that have been bound vs the requested ones. +1490 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +1491 .sock +1492 .ip_bind_addrs() +1493 .iter() +1494 .copied() +1495 .zip(self.sock.ip_local_addrs()) +1496 .collect(); +1497 +1498 // Do we listen on any IPv4 unspecified address? +1499 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +1500 if a.is_ipv4() && a.ip().is_unspecified() { +1501 Some(a.port()) +1502 } else { +1503 None +1504 } +1505 }); +1506 // Do we listen on any IPv6 unspecified address? +1507 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +1508 if a.is_ipv6() && a.ip().is_unspecified() { +1509 Some(a.port()) +1510 } else { +1511 None +1512 } +1513 }); +1514 +1515 // If a socket is bound to the unspecified address, create SocketAddrs for +1516 // each local IP address by pairing it with the port the socket is bound on. +1517 if local_addrs +1518 .iter() +1519 .any(|(_, local)| local.ip().is_unspecified()) +1520 { +1521 let LocalAddresses { +1522 regular: mut ips, +1523 loopback, +1524 } = self.netmon_watcher.get().local_addresses; +1525 if ips.is_empty() && addrs.is_empty() { +1526 // Include loopback addresses only if there are no other interfaces +1527 // or public addresses, this allows testing offline. +1528 ips = loopback; +1529 } +1530 +1531 for ip in ips { +1532 let port_if_unspecified = match ip { +1533 IpAddr::V4(_) => has_ipv4_unspecified, +1534 IpAddr::V6(_) => has_ipv6_unspecified, +1535 }; +1536 if let Some(port) = port_if_unspecified { +1537 let addr = SocketAddr::new(ip, port); +1538 addrs.entry(addr).or_insert(DirectAddrType::Local); +1539 } +1540 } +1541 } +1542 +1543 // If a socket is bound to a specific address, add it. +1544 for (bound, local) in local_addrs { +1545 if !bound.ip().is_unspecified() { +1546 addrs.entry(local).or_insert(DirectAddrType::Local); +1547 } +1548 } +1549 } +1550 +1551 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +1552 if let Some(ref mut r) = report { +1553 self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +1554 if r.preferred_relay.is_none() +1555 && let Some(my_relay) = self.sock.my_relay() +1556 { +1557 r.preferred_relay.replace(my_relay); +1558 } +1559 +1560 // Notify all transports +1561 self.network_change_sender.on_network_change(r); +1562 } +1563 +1564 #[cfg(not(wasm_browser))] +1565 self.update_direct_addresses(report.as_ref()); +1566 } +1567} +1568 +1569fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +1570 // Pick a random duration between 20 and 26 seconds (just under 30s, +1571 // a common UDP NAT timeout on Linux,etc) +1572 let mut rng = rand::rng(); +1573 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); +1574 if initial_delay { +1575 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +1576 time::interval_at(time::Instant::now() + d, d) +1577 } else { +1578 debug!( +1579 "scheduling periodic_stun to run immediately and in {}s", +1580 d.as_secs() +1581 ); +1582 time::interval(d) +1583 } +1584} +1585 +1586/// The discovered direct addresses of this [`Socket`]. +1587/// +1588/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself. +1589/// They include all locally bound ones as well as those discovered by other mechanisms like +1590/// QAD. +1591#[derive(derive_more::Debug, Clone, Default)] +1592struct DiscoveredDirectAddrs { +1593 /// The last set of discovered direct addresses. +1594 addrs: Watchable<BTreeSet<DirectAddr>>, +1595 +1596 /// The last time the direct addresses were updated, even if there was no change. +1597 /// +1598 /// This is only ever None at startup. +1599 updated_at: Arc<RwLock<Option<Instant>>>, +1600} +1601 +1602impl DiscoveredDirectAddrs { +1603 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +1604 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +1605 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +1606 let updated = self.addrs.set(addrs).is_ok(); +1607 if updated { +1608 event!( +1609 target: "iroh::_events::direct_addrs", +1610 Level::DEBUG, +1611 addrs = ?self.addrs.get(), +1612 ); +1613 } +1614 updated +1615 } +1616 +1617 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { +1618 self.addrs.get().into_iter().map(|da| da.addr) +1619 } +1620} +1621 +1622/// A *direct address* on which an iroh-endpoint might be contactable. +1623/// +1624/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be +1625/// contacted. These can come from various sources depending on the network topology of the +1626/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. +1627/// +1628/// This is essentially a combination of our local addresses combined with any reflexive +1629/// transport addresses we discovered using QAD. +1630#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +1631pub struct DirectAddr { +1632 /// The address. +1633 pub addr: SocketAddr, +1634 /// The origin of this direct address. +1635 pub typ: DirectAddrType, +1636} +1637 +1638/// The type of direct address. +1639/// +1640/// These are the various sources or origins from which an iroh endpoint might have found a +1641/// possible [`DirectAddr`]. +1642#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +1643pub enum DirectAddrType { +1644 /// Not yet determined.. +1645 Unknown, +1646 /// A locally bound socket address. +1647 Local, +1648 /// Public internet address discovered via QAD. +1649 /// +1650 /// When possible an iroh endpoint will perform QAD to discover which is the address +1651 /// from which it sends data on the public internet. This can be different from locally +1652 /// bound addresses when the endpoint is on a local network which performs NAT or similar. +1653 Qad, +1654 /// An address assigned by the router using port mapping. +1655 /// +1656 /// When possible an iroh endpoint will request a port mapping from the local router to +1657 /// get a publicly routable direct address. +1658 Portmapped, +1659 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +1660 /// +1661 /// It is possible to configure iroh to bound to a specific port and independently +1662 /// configure the router to forward this port to the iroh endpoint. This indicates a +1663 /// situation like this, which still uses QAD to discover the public address. +1664 Qad4LocalPort, +1665} +1666 +1667impl Display for DirectAddrType { +1668 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +1669 match self { +1670 DirectAddrType::Unknown => write!(f, "?"), +1671 DirectAddrType::Local => write!(f, "local"), +1672 DirectAddrType::Qad => write!(f, "qad"), +1673 DirectAddrType::Portmapped => write!(f, "portmap"), +1674 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +1675 } +1676 } +1677} +1678 +1679#[cfg(test)] +1680mod tests { +1681 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; +1682 +1683 use data_encoding::HEXLOWER; +1684 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; +1685 use iroh_relay::tls::{CaRootConfig, default_provider}; +1686 use n0_error::{Result, StackResultExt, StdResultExt}; +1687 use n0_future::{MergeBounded, StreamExt, time}; +1688 use n0_tracing_test::traced_test; +1689 use n0_watcher::Watcher; +1690 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; +1691 use tokio_util::task::AbortOnDropHandle; +1692 use tracing::{Instrument, error, info, info_span, instrument}; +1693 +1694 use super::Options; +1695 use crate::{ +1696 Endpoint, RelayMode, SecretKey, +1697 address_lookup::memory::MemoryLookup, +1698 dns::DnsResolver, +1699 endpoint::QuicTransportConfig, +1700 socket::{ +1701 EndpointInner, Socket, StaticConfig, TransportConfig, +1702 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, +1703 }, +1704 tls::{self, DEFAULT_MAX_TLS_TICKETS}, +1705 }; +1706 +1707 const ALPN: &[u8] = b"n0/test/1"; +1708 +1709 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { +1710 let secret_key = SecretKey::generate(rng); +1711 let static_config = StaticConfig { +1712 tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), +1713 transport_config: QuicTransportConfig::default(), +1714 keylog: false, +1715 }; +1716 let server_config = static_config.create_server_config(vec![]); +1717 Options { +1718 transports: vec![ +1719 TransportConfig::default_ipv4(), +1720 TransportConfig::default_ipv6(), +1721 ], +1722 secret_key, +1723 proxy_url: None, +1724 dns_resolver: DnsResolver::new(), +1725 server_config, +1726 tls_config: CaRootConfig::default() +1727 .build_client_config(default_provider()) +1728 .unwrap(), +1729 #[cfg(any(test, feature = "test-utils"))] +1730 address_lookup_user_data: None, +1731 metrics: Default::default(), +1732 hooks: Default::default(), +1733 static_config, +1734 } +1735 } +1736 +1737 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1738 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { +1739 info!("accepting conn"); +1740 let conn = ep.accept().await.expect("no conn"); +1741 +1742 info!("accepting"); +1743 let conn = conn.await.context("accepting")?; +1744 info!("accepting bi"); +1745 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; +1746 +1747 info!("reading"); +1748 let val = recv_bi +1749 .read_to_end(usize::MAX) +1750 .await +1751 .std_context("read to end")?; +1752 +1753 info!("replying"); +1754 for chunk in val.chunks(12) { +1755 send_bi.write_all(chunk).await.std_context("write all")?; +1756 } +1757 +1758 info!("finishing"); +1759 send_bi.finish().std_context("finish")?; +1760 send_bi.stopped().await.std_context("stopped")?; +1761 +1762 let stats = conn.stats(); +1763 info!("stats: {:#?}", stats); +1764 if matches!(loss, ExpectedLoss::AlmostNone) { +1765 for info in conn.paths().get().iter() { +1766 assert!( +1767 info.stats().unwrap().lost_packets < 10, +1768 "[receiver] path {:?} should not loose many packets", +1769 info.remote_addr() +1770 ); +1771 } +1772 } +1773 +1774 conn.closed().await; +1775 info!("closed"); +1776 ep.inner()?.quinn_endpoint().wait_idle().await; +1777 info!("idle"); +1778 +1779 Ok(()) +1780 } +1781 +1782 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1783 async fn echo_sender( +1784 ep: Endpoint, +1785 dest_id: EndpointId, +1786 msg: &[u8], +1787 loss: ExpectedLoss, +1788 ) -> Result { +1789 info!("connecting to {}", dest_id.fmt_short()); +1790 let dest = EndpointAddr::new(dest_id); +1791 let conn = ep.connect(dest, ALPN).await?; +1792 +1793 info!("opening bi"); +1794 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; +1795 +1796 info!("writing message"); +1797 send_bi.write_all(msg).await.std_context("write all")?; +1798 +1799 info!("finishing"); +1800 send_bi.finish().std_context("finish")?; +1801 send_bi.stopped().await.std_context("stopped")?; +1802 +1803 info!("reading_to_end"); +1804 let val = recv_bi +1805 .read_to_end(usize::MAX) +1806 .await +1807 .std_context("read to end")?; +1808 assert_eq!( +1809 val, +1810 msg, +1811 "[sender] expected {}, got {}", +1812 HEXLOWER.encode(msg), +1813 HEXLOWER.encode(&val) +1814 ); +1815 +1816 let stats = conn.stats(); +1817 info!("stats: {:#?}", stats); +1818 if matches!(loss, ExpectedLoss::AlmostNone) { +1819 for info in conn.paths().get().iter() { +1820 assert!( +1821 info.stats().unwrap().lost_packets < 10, +1822 "[sender] path {:?} should not loose many packets", +1823 info.remote_addr() +1824 ); +1825 } +1826 } +1827 +1828 conn.close(0u32.into(), b"done"); +1829 info!("closed"); +1830 ep.inner()?.quinn_endpoint().wait_idle().await; +1831 info!("idle"); +1832 Ok(()) +1833 } +1834 +1835 #[derive(Debug, Copy, Clone)] +1836 enum ExpectedLoss { +1837 AlmostNone, +1838 YeahSure, +1839 } +1840 +1841 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +1842 async fn run_roundtrip( +1843 sender: Endpoint, +1844 receiver: Endpoint, +1845 payload: &[u8], +1846 loss: ExpectedLoss, +1847 ) -> Result<()> { +1848 tokio::time::timeout(Duration::from_secs(4), async move { +1849 let send_endpoint_id = sender.id(); +1850 let recv_endpoint_id = receiver.id(); +1851 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); +1852 +1853 let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss))); +1854 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; +1855 let sender_is_err = match sender_res { +1856 Ok(()) => false, +1857 Err(err) => { +1858 error!("[sender] Error:\n{err:#?}"); +1859 true +1860 } +1861 }; +1862 let receiver_is_err = match receiver_task.await { +1863 Ok(Ok(())) => false, +1864 Ok(Err(err)) => { +1865 error!("[receiver] Error:\n{err:#?}"); +1866 true +1867 } +1868 Err(joinerr) => { +1869 if joinerr.is_panic() { +1870 std::panic::resume_unwind(joinerr.into_panic()); +1871 } else { +1872 error!("[receiver] Error:\n{joinerr:#?}"); +1873 } +1874 true +1875 } +1876 }; +1877 if sender_is_err || receiver_is_err { +1878 panic!("Sender or receiver errored"); +1879 } +1880 }) +1881 .await +1882 .std_context("timeout")?; +1883 Ok(()) +1884 } +1885 +1886 /// Returns a pair of endpoints with a shared [`MemoryLookup`]. +1887 /// +1888 /// The endpoints do not use a relay server but can connect to each other via local +1889 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if +1890 /// the endpoints rebind. +1891 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { +1892 let address_lookup = MemoryLookup::new(); +1893 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) +1894 .alpns(vec![ALPN.to_vec()]) +1895 .address_lookup(address_lookup.clone()) +1896 .bind() +1897 .await +1898 .unwrap(); +1899 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) +1900 .alpns(vec![ALPN.to_vec()]) +1901 .address_lookup(address_lookup.clone()) +1902 .bind() +1903 .await +1904 .unwrap(); +1905 address_lookup.add_endpoint_info(ep1.addr()); +1906 address_lookup.add_endpoint_info(ep2.addr()); +1907 +1908 let ep1_addr_stream = ep1.watch_addr().stream(); +1909 let ep2_addr_stream = ep2.watch_addr().stream(); +1910 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); +1911 let task = tokio::spawn(async move { +1912 while let Some(addr) = addr_stream.next().await { +1913 address_lookup.add_endpoint_info(addr); +1914 } +1915 }); +1916 +1917 (AbortOnDropHandle::new(task), ep1, ep2) +1918 } +1919 +1920 #[tokio::test(flavor = "multi_thread")] +1921 #[traced_test] +1922 async fn test_two_devices_roundtrip_quinn_small() -> Result { +1923 let (_guard, m1, m2) = endpoint_pair().await; +1924 +1925 run_roundtrip( +1926 m1.clone(), +1927 m2.clone(), +1928 b"hello m1", +1929 ExpectedLoss::AlmostNone, +1930 ) +1931 .await?; +1932 run_roundtrip( +1933 m2.clone(), +1934 m1.clone(), +1935 b"hello m2", +1936 ExpectedLoss::AlmostNone, +1937 ) +1938 .await?; +1939 Ok(()) +1940 } +1941 +1942 #[tokio::test(flavor = "multi_thread")] +1943 #[traced_test] +1944 async fn test_two_devices_roundtrip_quinn_large() -> Result { +1945 let (_guard, m1, m2) = endpoint_pair().await; +1946 let mut data = vec![0u8; 10 * 1024]; +1947 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1948 rng.fill_bytes(&mut data); +1949 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?; +1950 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?; +1951 +1952 Ok(()) +1953 } +1954 +1955 #[tokio::test] +1956 #[traced_test] +1957 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { +1958 let (_guard, m1, m2) = endpoint_pair().await; +1959 +1960 println!("Net change"); +1961 m1.inner()?.force_network_change(true).await; +1962 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +1963 +1964 let _handle = AbortOnDropHandle::new(tokio::spawn({ +1965 let endpoint = m2.clone(); +1966 async move { +1967 while let Some(incoming) = endpoint.accept().await { +1968 println!("Incoming first conn!"); +1969 let conn = incoming.await.anyerr()?; +1970 conn.closed().await; +1971 } +1972 +1973 n0_error::Ok(()) +1974 } +1975 })); +1976 +1977 println!("first conn!"); +1978 let conn = m1.connect(m2.addr(), ALPN).await?; +1979 println!("Closing first conn"); +1980 conn.close(0u32.into(), b"bye lolz"); +1981 conn.closed().await; +1982 println!("Closed first conn"); +1983 +1984 Ok(()) +1985 } +1986 +1987 fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration { +1988 let delay = rng.random_range(1..=5); +1989 Duration::from_millis(delay * 50) +1990 } +1991 +1992 /// Same structure as `test_two_devices_roundtrip_quinn`, but interrupts regularly +1993 /// with (simulated) network changes. +1994 /// Regular network changes to m1 only. +1995 #[tokio::test(flavor = "multi_thread")] +1996 #[traced_test] +1997 async fn test_two_devices_roundtrip_network_change_only_a() -> Result { +1998 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1999 let (_guard, m1, m2) = endpoint_pair().await; +2000 +2001 let _network_change_guard = { +2002 let m1 = m1.clone(); +2003 let mut rng = rng.clone(); +2004 let task = tokio::spawn(async move { +2005 loop { +2006 info!("[m1] network change"); +2007 m1.inner() +2008 .expect("haven't closed the endpoint yet") +2009 .force_network_change(true) +2010 .await; +2011 time::sleep(offset(&mut rng)).await; +2012 } +2013 }); +2014 AbortOnDropHandle::new(task) +2015 }; +2016 +2017 let mut data = vec![0u8; 10 * 1024]; +2018 rng.fill_bytes(&mut data); +2019 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; +2020 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; +2021 +2022 Ok(()) +2023 } +2024 +2025 /// Regular network changes to both m1 and m2. +2026 #[tokio::test(flavor = "multi_thread")] +2027 #[traced_test] +2028 async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result { +2029 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2030 let (_guard, m1, m2) = endpoint_pair().await; +2031 +2032 let _network_change_guard = { +2033 let m1 = m1.clone(); +2034 let m2 = m2.clone(); +2035 let mut rng = rng.clone(); +2036 let task = tokio::spawn(async move { +2037 info!("-- [m1] network change"); +2038 m1.inner() +2039 .expect("haven't closed the endpoint yet") +2040 .force_network_change(true) +2041 .await; +2042 info!("-- [m2] network change"); +2043 m2.inner() +2044 .expect("haven't closed the endpoint yet") +2045 .force_network_change(true) +2046 .await; +2047 time::sleep(offset(&mut rng)).await; +2048 }); +2049 AbortOnDropHandle::new(task) +2050 }; +2051 +2052 let mut data = vec![0u8; 10 * 1024]; +2053 rng.fill_bytes(&mut data); +2054 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; +2055 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; +2056 +2057 Ok(()) +2058 } +2059 +2060 #[tokio::test(flavor = "multi_thread")] +2061 #[traced_test] +2062 async fn test_two_devices_setup_teardown() -> Result { +2063 for i in 0..10 { +2064 info!("-- round {i}"); +2065 info!("setting up stack"); +2066 let (_guard, m1, m2) = endpoint_pair().await; +2067 +2068 info!("closing endpoints"); +2069 let sock1 = m1.inner()?; +2070 let sock2 = m2.inner()?; +2071 m1.close().await; +2072 m2.close().await; +2073 +2074 assert!(sock1.is_closed()); +2075 assert!(sock2.is_closed()); +2076 } +2077 Ok(()) +2078 } +2079 +2080 #[tokio::test] +2081 #[traced_test] +2082 async fn test_direct_addresses() { +2083 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2084 let sock = EndpointInner::new(default_options(&mut rng)).await.unwrap(); +2085 +2086 // See if we can get endpoints. +2087 let eps0 = sock.ip_addrs().get(); +2088 info!("{eps0:?}"); +2089 assert!(!eps0.is_empty()); +2090 +2091 // Getting the endpoints again immediately should give the same results. +2092 let eps1 = sock.ip_addrs().get(); +2093 info!("{eps1:?}"); +2094 assert_eq!(eps0, eps1); +2095 } +2096 +2097 /// Creates a new [`quinn::Endpoint`] hooked up to a [`Socket`]. +2098 /// +2099 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +2100 /// connections using [`ALPN`]. +2101 /// +2102 /// Use [`socket_connect`] to establish connections. +2103 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] +2104 async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> { +2105 let static_config = StaticConfig { +2106 tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS), +2107 transport_config: QuicTransportConfig::default(), +2108 keylog: true, +2109 }; +2110 let server_config = static_config.create_server_config(vec![ALPN.to_vec()]); +2111 +2112 let dns_resolver = DnsResolver::new(); +2113 let opts = Options { +2114 transports: vec![ +2115 TransportConfig::default_ipv4(), +2116 TransportConfig::default_ipv6(), +2117 ], +2118 secret_key: secret_key.clone(), +2119 address_lookup_user_data: None, +2120 dns_resolver, +2121 proxy_url: None, +2122 server_config, +2123 tls_config: CaRootConfig::default() +2124 .build_client_config(default_provider()) +2125 .unwrap(), +2126 metrics: Default::default(), +2127 hooks: Default::default(), +2128 static_config, +2129 }; +2130 let sock = Socket::spawn(opts).await?; +2131 Ok(sock) +2132 } +2133 +2134 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. +2135 /// +2136 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2137 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2138 async fn socket_connect( +2139 ep: quinn::Endpoint, +2140 ep_secret_key: SecretKey, +2141 addr: EndpointIdMappedAddr, +2142 endpoint_id: EndpointId, +2143 ) -> Result<quinn::Connection> { +2144 // Endpoint::connect sets this, do the same to have similar behaviour. +2145 let mut transport_config = quinn::TransportConfig::default(); +2146 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2147 +2148 socket_connect_with_transport_config( +2149 ep, +2150 ep_secret_key, +2151 addr, +2152 endpoint_id, +2153 Arc::new(transport_config), +2154 ) +2155 .await +2156 } +2157 +2158 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. +2159 /// +2160 /// This version allows customising the transport config. +2161 /// +2162 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2163 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2164 async fn socket_connect_with_transport_config( +2165 ep: quinn::Endpoint, +2166 ep_secret_key: SecretKey, +2167 mapped_addr: EndpointIdMappedAddr, +2168 endpoint_id: EndpointId, +2169 transport_config: Arc<quinn::TransportConfig>, +2170 ) -> Result<quinn::Connection> { +2171 let alpns = vec![ALPN.to_vec()]; +2172 let quic_client_config = +2173 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2174 .make_client_config(alpns, true); +2175 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +2176 client_config.transport_config(transport_config); +2177 let connect = ep +2178 .connect_with( +2179 client_config, +2180 mapped_addr.private_socket_addr(), +2181 &tls::name::encode(endpoint_id), +2182 ) +2183 .std_context("connect")?; +2184 let connection = connect.await.anyerr()?; +2185 Ok(connection) +2186 } +2187 +2188 #[tokio::test] +2189 #[traced_test] +2190 async fn test_try_send_no_send_addr() { +2191 // Regression test: if there is no send_addr we should keep being able to use the +2192 // Endpoint. +2193 +2194 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2195 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2196 let endpoint_id_2 = secret_key_2.public(); +2197 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); +2198 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); +2199 +2200 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); +2201 +2202 // Generate an address not present in the RemoteMap. +2203 let bad_addr = EndpointIdMappedAddr::generate(); +2204 +2205 // 500ms is rather fast here. Running this locally it should always be the correct +2206 // timeout. If this is too slow however the test will not become flaky as we are +2207 // expecting the timeout, we might just get the timeout for the wrong reason. But +2208 // this speeds up the test. +2209 let res = tokio::time::timeout( +2210 Duration::from_millis(500), +2211 socket_connect( +2212 sock_1.quinn_endpoint().clone(), +2213 secret_key_1.clone(), +2214 bad_addr, +2215 endpoint_id_missing_endpoint, +2216 ), +2217 ) +2218 .await; +2219 assert!(res.is_err(), "expecting timeout"); +2220 +2221 // Now check we can still create another connection with this endpoint. +2222 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); +2223 +2224 // This needs an accept task +2225 let accept_task = tokio::spawn({ +2226 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2227 let incoming = ep.accept().await.std_context("no incoming")?; +2228 let _conn = incoming +2229 .accept() +2230 .std_context("accept")? +2231 .await +2232 .std_context("accepting")?; +2233 +2234 // Keep this connection alive for a while +2235 tokio::time::sleep(Duration::from_secs(10)).await; +2236 info!("accept finished"); +2237 Ok(()) +2238 } +2239 let ep = sock_2.quinn_endpoint().clone(); +2240 async move { +2241 if let Err(err) = accept(ep).await { +2242 error!("{err:#}"); +2243 } +2244 } +2245 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) +2246 }); +2247 let _accept_task = AbortOnDropHandle::new(accept_task); +2248 +2249 let addrs = sock_2 +2250 .ip_addrs() +2251 .get() +2252 .into_iter() +2253 .map(|x| TransportAddr::Ip(x.addr)); +2254 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); +2255 let addr = sock_1 +2256 .resolve_remote(endpoint_addr_2) +2257 .await +2258 .unwrap() +2259 .unwrap(); +2260 let res = tokio::time::timeout( +2261 Duration::from_secs(10), +2262 socket_connect( +2263 sock_1.quinn_endpoint().clone(), +2264 secret_key_1.clone(), +2265 addr, +2266 endpoint_id_2, +2267 ), +2268 ) +2269 .await +2270 .expect("timeout while connecting"); +2271 +2272 // aka assert!(res.is_ok()) but with nicer error reporting. +2273 res.unwrap(); +2274 +2275 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +2276 // much internal state for now. +2277 } +2278 +2279 #[tokio::test] +2280 #[traced_test] +2281 async fn test_try_send_no_udp_addr_or_relay_url() { +2282 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +2283 // behaviour of Socket::try_send. +2284 +2285 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2286 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2287 let endpoint_id_2 = secret_key_2.public(); +2288 +2289 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); +2290 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); +2291 let ep_2 = sock_2.quinn_endpoint().clone(); +2292 +2293 // We need a task to accept the connection. +2294 let accept_task = tokio::spawn({ +2295 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2296 let incoming = ep.accept().await.std_context("no incoming")?; +2297 let conn = incoming +2298 .accept() +2299 .std_context("accept")? +2300 .await +2301 .std_context("connecting")?; +2302 let mut stream = conn.accept_uni().await.std_context("accept uni")?; +2303 stream +2304 .read_to_end(1 << 16) +2305 .await +2306 .std_context("read to end")?; +2307 info!("accept finished"); +2308 Ok(()) +2309 } +2310 async move { +2311 if let Err(err) = accept(ep_2).await { +2312 error!("{err:#}"); +2313 } +2314 } +2315 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) +2316 }); +2317 let _accept_task = AbortOnDropHandle::new(accept_task); +2318 +2319 // Add an entry in the RemoteMap of ep_1 with an invalid socket address +2320 let empty_addr_2 = EndpointAddr::from_parts( +2321 endpoint_id_2, +2322 [TransportAddr::Ip( +2323 // Reserved IP range for documentation (unreachable) +2324 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), +2325 )], +2326 ); +2327 let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); +2328 +2329 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +2330 // not take forever. You need to check the log output to verify this is really +2331 // triggering the correct error. +2332 // In test_try_send_no_send_addr() above you may have noticed we used +2333 // tokio::time::timeout() on the connection attempt instead. Here however we want +2334 // Quinn itself to have fully given up on the connection attempt because we will +2335 // later connect to **the same** endpoint. If Quinn did not give up on the connection +2336 // we'd close it on drop, and the retransmits of the close packets would interfere +2337 // with the next handshake, closing it during the handshake. This makes the test a +2338 // little slower though. +2339 let mut transport_config = quinn::TransportConfig::default(); +2340 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +2341 let res = socket_connect_with_transport_config( +2342 sock_1.quinn_endpoint().clone(), +2343 secret_key_1.clone(), +2344 addr_2, +2345 endpoint_id_2, +2346 Arc::new(transport_config), +2347 ) +2348 .await; +2349 assert!(res.is_err(), "expected timeout"); +2350 info!("first connect timed out as expected"); +2351 +2352 // Provide correct addressing information +2353 let correct_addr_2 = EndpointAddr::from_parts( +2354 endpoint_id_2, +2355 sock_2 +2356 .ip_addrs() +2357 .get() +2358 .into_iter() +2359 .map(|x| TransportAddr::Ip(x.addr)), +2360 ); +2361 let addr_2a = sock_1 +2362 .resolve_remote(correct_addr_2) +2363 .await +2364 .unwrap() +2365 .unwrap(); +2366 assert_eq!(addr_2, addr_2a); +2367 +2368 // We can now connect +2369 tokio::time::timeout(Duration::from_secs(10), async move { +2370 info!("establishing new connection"); +2371 let conn = socket_connect( +2372 sock_1.quinn_endpoint().clone(), +2373 secret_key_1.clone(), +2374 addr_2, +2375 endpoint_id_2, +2376 ) +2377 .await +2378 .unwrap(); +2379 info!("have connection"); +2380 let mut stream = conn.open_uni().await.unwrap(); +2381 stream.write_all(b"hello").await.unwrap(); +2382 stream.finish().unwrap(); +2383 stream.stopped().await.unwrap(); +2384 info!("finished stream"); +2385 }) +2386 .await +2387 .expect("connection timed out"); +2388 +2389 // TODO: could remove the addresses again, send, add it back and see it recover. +2390 // But we don't have that much private access to the RemoteMap. This will do for now. +2391 } +2392}
    \ No newline at end of file diff --git a/pr/3973/docs/trait.impl/core/convert/trait.From.js b/pr/3973/docs/trait.impl/core/convert/trait.From.js index 2185d3c95e..6f0844ea34 100644 --- a/pr/3973/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3973/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<Infallible> for InvalidSocketAddr"],["impl From<Error> for ConnectWithOptsError"],["impl From<Error> for AnyError"],["impl From<IntoAddressLookupError> for BindError"],["impl From<IntoAddressLookupError> for AnyError"],["impl From<PkarrError> for Error"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<EndpointError> for IntoAddressLookupError"],["impl From<EndpointError> for AnyError"],["impl From<InvalidSocketAddr> for AnyError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<AddrParseError> for InvalidSocketAddr"],["impl From<Error> for AcceptError"],["impl From<PrefixLenError> for InvalidSocketAddr"],["impl From<Item> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<RetryError> for AnyError"],["impl From<TransportAddrInfo> for TransportAddr"],["impl From<AnyError> for IntoAddressLookupError"],["impl From<AnyError> for AcceptError"],["impl<T> From<T> for ConcurrentAddressLookup
    where\n T: IntoIterator<Item = Box<dyn AddressLookup>>,
    "],["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 AcceptError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<HandleFrameError> for RunError"],["impl From<HandleFrameError> for AnyError"],["impl From<RunError> for AnyError"],["impl From<WriteFrameError> for HandleFrameError"],["impl From<WriteFrameError> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<AcceptError> for ConnectionHandlerError"],["impl From<AcceptError> for AnyError"],["impl From<ConnectionHandlerError> for AnyError"],["impl From<ServeConnectionError> for AnyError"],["impl From<RecvError> for HandleFrameError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for WriteFrameError"],["impl From<SendError> 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<ForwardPacketError> for HandleFrameError"],["impl From<ForwardPacketError> for RunError"],["impl From<ForwardPacketError> for AnyError"],["impl From<InvalidBucketConfig> for AcceptError"],["impl From<InvalidBucketConfig> 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<Elapsed> for WriteFrameError"],["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<Error> for RecvError"],["impl From<Error> for SendError"],["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<Infallible> for InvalidSocketAddr"],["impl From<Error> for ConnectWithOptsError"],["impl From<Error> for AnyError"],["impl From<IntoAddressLookupError> for BindError"],["impl From<IntoAddressLookupError> for AnyError"],["impl From<PkarrError> for Error"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<EndpointError> for IntoAddressLookupError"],["impl From<EndpointError> for AnyError"],["impl From<InvalidSocketAddr> for AnyError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<AddrParseError> for InvalidSocketAddr"],["impl From<Error> for AcceptError"],["impl From<PrefixLenError> for InvalidSocketAddr"],["impl From<Item> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<RetryError> for AnyError"],["impl From<TransportAddrInfo> for TransportAddr"],["impl From<AnyError> for IntoAddressLookupError"],["impl From<AnyError> for AcceptError"],["impl<T> From<T> for ConcurrentAddressLookup
    where\n T: IntoIterator<Item = Box<dyn AddressLookup>>,
    "],["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 AcceptError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<HandleFrameError> for RunError"],["impl From<HandleFrameError> for AnyError"],["impl From<RunError> for AnyError"],["impl From<WriteFrameError> for HandleFrameError"],["impl From<WriteFrameError> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<AcceptError> for ConnectionHandlerError"],["impl From<AcceptError> for AnyError"],["impl From<ConnectionHandlerError> for AnyError"],["impl From<ServeConnectionError> for AnyError"],["impl From<RecvError> for HandleFrameError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for WriteFrameError"],["impl From<SendError> 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<ForwardPacketError> for HandleFrameError"],["impl From<ForwardPacketError> for RunError"],["impl From<ForwardPacketError> for AnyError"],["impl From<InvalidBucketConfig> for AcceptError"],["impl From<InvalidBucketConfig> 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<Elapsed> for WriteFrameError"],["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<Error> for RecvError"],["impl From<Error> for SendError"],["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":[16172,3090,27662]} \ No newline at end of file +//{"start":57,"fragment_lengths":[16172,3090,28438]} \ No newline at end of file diff --git a/pr/3973/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3973/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 53eb8f19b7..6823ee20ab 100644 --- a/pr/3973/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3973/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