diff --git a/pr/4324/docs/iroh/address_lookup/enum.AddressLookupBuilderError.html b/pr/4324/docs/iroh/address_lookup/enum.AddressLookupBuilderError.html index c2b710fb58..a5aaae4db5 100644 --- a/pr/4324/docs/iroh/address_lookup/enum.AddressLookupBuilderError.html +++ b/pr/4324/docs/iroh/address_lookup/enum.AddressLookupBuilderError.html @@ -19,7 +19,7 @@ provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, ) -> Self

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

-

Trait Implementations§

Source§

impl Debug for AddressLookupBuilderError

Source§

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

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

impl Display for AddressLookupBuilderError

Source§

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

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

impl Error for AddressLookupBuilderError

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

Source§

fn from(value: AddressLookupBuilderError) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddressLookupBuilderError> for BindError

Source§

fn from(source: AddressLookupBuilderError) -> Self

Converts to this type from the input type.
Source§

impl From<AnyError> for AddressLookupBuilderError

Source§

fn from(source: AnyError) -> Self

Converts to this type from the input type.
Source§

impl From<EndpointError> for AddressLookupBuilderError

Source§

fn from(source: EndpointError) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddressLookupBuilderError

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 AddressLookupBuilderError

§

impl !RefUnwindSafe for AddressLookupBuilderError

§

impl Send for AddressLookupBuilderError

§

impl Sync for AddressLookupBuilderError

§

impl Unpin for AddressLookupBuilderError

§

impl !UnwindSafe for AddressLookupBuilderError

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for AddressLookupBuilderError

Source§

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

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

impl Display for AddressLookupBuilderError

Source§

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

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

impl Error for AddressLookupBuilderError

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

Source§

fn from(value: AddressLookupBuilderError) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddressLookupBuilderError> for BindError

Source§

fn from(source: AddressLookupBuilderError) -> Self

Converts to this type from the input type.
Source§

impl From<AnyError> for AddressLookupBuilderError

Source§

fn from(source: AnyError) -> Self

Converts to this type from the input type.
Source§

impl From<EndpointError> for AddressLookupBuilderError

Source§

fn from(source: EndpointError) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddressLookupBuilderError

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 AddressLookupBuilderError

§

impl !RefUnwindSafe for AddressLookupBuilderError

§

impl Send for AddressLookupBuilderError

§

impl Sync for AddressLookupBuilderError

§

impl Unpin for AddressLookupBuilderError

§

impl !UnwindSafe for AddressLookupBuilderError

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/4324/docs/iroh/address_lookup/enum.AddressLookupFailed.html b/pr/4324/docs/iroh/address_lookup/enum.AddressLookupFailed.html index cdc2ef9ba7..ed9061bee2 100644 --- a/pr/4324/docs/iroh/address_lookup/enum.AddressLookupFailed.html +++ b/pr/4324/docs/iroh/address_lookup/enum.AddressLookupFailed.html @@ -9,7 +9,7 @@ }
Expand description

Variants (Non-exhaustive)§

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

NoServiceConfigured

Fields

§meta: Meta

Captured call-site metadata

§

NoResults

Fields

§errors: Vec<Error>
§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Clone for AddressLookupFailed

Source§

fn clone(&self) -> AddressLookupFailed

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 AddressLookupFailed

Source§

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

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

impl Display for AddressLookupFailed

Source§

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

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

impl Error for AddressLookupFailed

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

Source§

fn from(value: AddressLookupFailed) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddressLookupFailed> for ConnectWithOptsError

Source§

fn from(source: AddressLookupFailed) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddressLookupFailed

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 +

Trait Implementations§

Source§

impl Clone for AddressLookupFailed

Source§

fn clone(&self) -> AddressLookupFailed

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 AddressLookupFailed

Source§

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

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

impl Display for AddressLookupFailed

Source§

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

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

impl Error for AddressLookupFailed

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

Source§

fn from(value: AddressLookupFailed) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddressLookupFailed> for ConnectWithOptsError

Source§

fn from(source: AddressLookupFailed) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddressLookupFailed

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 AddressLookupFailed

§

impl !RefUnwindSafe for AddressLookupFailed

§

impl Send for AddressLookupFailed

§

impl Sync for AddressLookupFailed

§

impl Unpin for AddressLookupFailed

§

impl !UnwindSafe for AddressLookupFailed

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/4324/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/4324/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html index bc48689e2b..29daa10fb6 100644 --- a/pr/4324/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html +++ b/pr/4324/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html @@ -1,2 +1,2 @@ -ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

ENV_FORCE_STAGING_RELAYS

Constant ENV_FORCE_STAGING_RELAYS 

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

Environment variable to force the use of staging relays.

+ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

ENV_FORCE_STAGING_RELAYS

Constant ENV_FORCE_STAGING_RELAYS 

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

Environment variable to force the use of staging relays.

\ No newline at end of file diff --git a/pr/4324/docs/iroh/endpoint/enum.BindError.html b/pr/4324/docs/iroh/endpoint/enum.BindError.html index 877a268ab0..bf6ead45bf 100644 --- a/pr/4324/docs/iroh/endpoint/enum.BindError.html +++ b/pr/4324/docs/iroh/endpoint/enum.BindError.html @@ -1,4 +1,4 @@ -BindError in iroh::endpoint - Rust

BindError

Enum BindError 

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

BindError

Enum BindError 

Source
#[non_exhaustive]
pub enum BindError { Sockets { source: Error, meta: Meta, @@ -37,7 +37,7 @@
§

AddressLookup

Fields

§meta: Meta

Captured call-site metadata

§

InvalidCryptoProvider

Fields

§meta: Meta

Captured call-site metadata

§

TlsConfigError

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

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<AddressLookupBuilderError> for BindError

Source§

fn from(source: AddressLookupBuilderError) -> Self

Converts to this type from the input type.
Source§

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for BindError

Source§

fn from(source: TlsConfigError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

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 +

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

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<AddressLookupBuilderError> for BindError

Source§

fn from(source: AddressLookupBuilderError) -> Self

Converts to this type from the input type.
Source§

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for BindError

Source§

fn from(source: TlsConfigError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

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 BindError

§

impl !RefUnwindSafe for BindError

§

impl Send for BindError

§

impl Sync for BindError

§

impl Unpin for BindError

§

impl !UnwindSafe for BindError

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/4324/docs/iroh/endpoint/enum.ConnectError.html b/pr/4324/docs/iroh/endpoint/enum.ConnectError.html index 44098af8b1..b0bad65683 100644 --- a/pr/4324/docs/iroh/endpoint/enum.ConnectError.html +++ b/pr/4324/docs/iroh/endpoint/enum.ConnectError.html @@ -1,4 +1,4 @@ -ConnectError in iroh::endpoint - Rust

ConnectError

Enum ConnectError 

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

ConnectError

Enum ConnectError 

Source
#[non_exhaustive]
pub enum ConnectError { Connect { source: ConnectWithOptsError, meta: Meta, @@ -14,7 +14,7 @@ }

Variants (Non-exhaustive)§

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

Connect

Fields

§meta: Meta

Captured call-site metadata

§

Connecting

Fields

§meta: Meta

Captured call-site metadata

§

Connection

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

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

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

impl Display for ConnectError

Source§

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

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

impl Error for ConnectError

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

Source§

fn from(value: ConnectError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectError

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 +

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

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

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

impl Display for ConnectError

Source§

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

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

impl Error for ConnectError

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

Source§

fn from(value: ConnectError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectError

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 T: 'a,

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/4324/docs/iroh/endpoint/enum.ConnectWithOptsError.html index 007d56eb4f..703a03caf1 100644 --- a/pr/4324/docs/iroh/endpoint/enum.ConnectWithOptsError.html +++ b/pr/4324/docs/iroh/endpoint/enum.ConnectWithOptsError.html @@ -1,4 +1,4 @@ -ConnectWithOptsError in iroh::endpoint - Rust

ConnectWithOptsError

Enum ConnectWithOptsError 

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

ConnectWithOptsError

Enum ConnectWithOptsError 

Source
#[non_exhaustive]
pub enum ConnectWithOptsError { SelfConnect { meta: Meta, }, @@ -27,7 +27,7 @@
§meta: Meta

Captured call-site metadata

§

LocallyRejected

Fields

§meta: Meta

Captured call-site metadata

§

EndpointClosed

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

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

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

impl Display for ConnectWithOptsError

Source§

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

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

impl Error for ConnectWithOptsError

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<AddressLookupFailed> for ConnectWithOptsError

Source§

fn from(source: AddressLookupFailed) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for AnyError

Source§

fn from(value: ConnectWithOptsError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectWithOptsError

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 +

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

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

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

impl Display for ConnectWithOptsError

Source§

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

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

impl Error for ConnectWithOptsError

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<AddressLookupFailed> for ConnectWithOptsError

Source§

fn from(source: AddressLookupFailed) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for AnyError

Source§

fn from(value: ConnectWithOptsError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectWithOptsError

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 ConnectWithOptsError

§

impl !RefUnwindSafe for ConnectWithOptsError

§

impl Send for ConnectWithOptsError

§

impl Sync for ConnectWithOptsError

§

impl Unpin for ConnectWithOptsError

§

impl !UnwindSafe for ConnectWithOptsError

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/4324/docs/iroh/endpoint/enum.ConnectingError.html b/pr/4324/docs/iroh/endpoint/enum.ConnectingError.html index 9eaf54ccfe..f87f012158 100644 --- a/pr/4324/docs/iroh/endpoint/enum.ConnectingError.html +++ b/pr/4324/docs/iroh/endpoint/enum.ConnectingError.html @@ -19,7 +19,7 @@

§

InternalConsistencyError

Fields

§source: RemoteStateActorStoppedError

Private source type, cannot be created publicly.

§meta: Meta

Captured call-site metadata

§

LocallyRejected

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Clone for ConnectingError

Source§

fn clone(&self) -> ConnectingError

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 ConnectingError

Source§

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

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

impl Display for ConnectingError

Source§

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

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

impl Error for ConnectingError

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<AuthenticationError> for ConnectingError

Source§

fn from(source: AuthenticationError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AcceptError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AnyError

Source§

fn from(value: ConnectingError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectingError

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 ConnectingError

§

impl !RefUnwindSafe for ConnectingError

§

impl Send for ConnectingError

§

impl Sync for ConnectingError

§

impl Unpin for ConnectingError

§

impl !UnwindSafe for ConnectingError

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectingError

Source§

fn clone(&self) -> ConnectingError

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 ConnectingError

Source§

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

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

impl Display for ConnectingError

Source§

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

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

impl Error for ConnectingError

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<AuthenticationError> for ConnectingError

Source§

fn from(source: AuthenticationError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AcceptError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AnyError

Source§

fn from(value: ConnectingError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectingError

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 ConnectingError

§

impl !RefUnwindSafe for ConnectingError

§

impl Send for ConnectingError

§

impl Sync for ConnectingError

§

impl Unpin for ConnectingError

§

impl !UnwindSafe for ConnectingError

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/4324/docs/iroh/endpoint/enum.ConnectionError.html b/pr/4324/docs/iroh/endpoint/enum.ConnectionError.html index 80ca551d31..c6231a5dbb 100644 --- a/pr/4324/docs/iroh/endpoint/enum.ConnectionError.html +++ b/pr/4324/docs/iroh/endpoint/enum.ConnectionError.html @@ -21,7 +21,7 @@ and [TransportConfig::keep_alive_interval()].

§

LocallyClosed

The local application closed the connection

§

CidsExhausted

The connection could not be created because not enough of the CID space is available

Try using longer connection IDs.

-

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
§

impl From<CloseReason> for ConnectionError

§

fn from(value: CloseReason) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

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

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

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

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

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
§

impl From<CloseReason> for ConnectionError

§

fn from(value: CloseReason) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

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

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

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

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

impl Eq for ConnectionError

§

impl StructuralPartialEq for ConnectionError

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'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/4324/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/4324/docs/iroh/endpoint/enum.DirectAddrType.html index 1ed926bf8d..0fb8543f8f 100644 --- a/pr/4324/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/4324/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

DirectAddrType

Enum DirectAddrType 

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

DirectAddrType

Enum DirectAddrType 

Source
#[non_exhaustive]
pub enum DirectAddrType { Unknown, Local, Qad, @@ -22,16 +22,16 @@ get a publicly routable direct address.

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.

§

Config

An address explicitly provided by the user via configuration.

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

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

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

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

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

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

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

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

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

impl Ord for DirectAddrType

Source§

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

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

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

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

impl Ord for DirectAddrType

Source§

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

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

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

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

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

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

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

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

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

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

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

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

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

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

Tests less than or equal to (for self and other) and is used by the + Self: Sized,

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

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

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

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

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

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

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

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

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

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

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

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

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

§

impl Freeze for DirectAddrType

§

impl RefUnwindSafe for DirectAddrType

§

impl Send for DirectAddrType

§

impl Sync for DirectAddrType

§

impl Unpin for DirectAddrType

§

impl UnwindSafe for DirectAddrType

Blanket Implementations§

Source§

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

Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

§

impl Freeze for DirectAddrType

§

impl RefUnwindSafe for DirectAddrType

§

impl Send for DirectAddrType

§

impl Sync for DirectAddrType

§

impl Unpin for DirectAddrType

§

impl UnwindSafe for DirectAddrType

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/enum.EndpointError.html b/pr/4324/docs/iroh/endpoint/enum.EndpointError.html index 1d6e65d288..ffd375682a 100644 --- a/pr/4324/docs/iroh/endpoint/enum.EndpointError.html +++ b/pr/4324/docs/iroh/endpoint/enum.EndpointError.html @@ -1,9 +1,9 @@ -EndpointError in iroh::endpoint - Rust

EndpointError

Enum EndpointError 

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

EndpointError

Enum EndpointError 

Source
#[non_exhaustive]
pub enum EndpointError { Closed { 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.
§

Closed

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for EndpointError

Source§

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

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

impl Display for EndpointError

Source§

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

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

impl Error for EndpointError

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<EndpointError> for AddressLookupBuilderError

Source§

fn from(source: EndpointError) -> Self

Converts to this type from the input type.
Source§

impl From<EndpointError> for AnyError

Source§

fn from(value: EndpointError) -> AnyError

Converts to this type from the input type.
Source§

impl StackError for EndpointError

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 +

Trait Implementations§

Source§

impl Debug for EndpointError

Source§

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

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

impl Display for EndpointError

Source§

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

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

impl Error for EndpointError

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<EndpointError> for AddressLookupBuilderError

Source§

fn from(source: EndpointError) -> Self

Converts to this type from the input type.
Source§

impl From<EndpointError> for AnyError

Source§

fn from(value: EndpointError) -> AnyError

Converts to this type from the input type.
Source§

impl StackError for EndpointError

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 T: 'a,

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/enum.QuicConnectError.html b/pr/4324/docs/iroh/endpoint/enum.QuicConnectError.html index 0746247767..2bfbcc9ab4 100644 --- a/pr/4324/docs/iroh/endpoint/enum.QuicConnectError.html +++ b/pr/4324/docs/iroh/endpoint/enum.QuicConnectError.html @@ -18,7 +18,7 @@ Errors in the parameters being used to create a new connection

§

NoDefaultClientConfig

No default client configuration was set up

Use Endpoint::connect_with to specify a client configuration.

§

UnsupportedVersion

The local endpoint does not support the QUIC version specified in the client configuration

-

Trait Implementations§

§

impl Clone for ConnectError

§

fn clone(&self) -> ConnectError

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
§

impl Debug for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectError

1.30.0 · Source§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
§

impl From<UnsupportedVersion> for ConnectError

§

fn from(_: UnsupportedVersion) -> ConnectError

Converts to this type from the input type.
§

impl PartialEq for ConnectError

§

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

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

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

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

Trait Implementations§

§

impl Clone for ConnectError

§

fn clone(&self) -> ConnectError

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
§

impl Debug for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectError

1.30.0 · Source§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
§

impl From<UnsupportedVersion> for ConnectError

§

fn from(_: UnsupportedVersion) -> ConnectError

Converts to this type from the input type.
§

impl PartialEq for ConnectError

§

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

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

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

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

impl Eq for ConnectError

§

impl StructuralPartialEq for ConnectError

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/4324/docs/iroh/endpoint/enum.RelayMode.html b/pr/4324/docs/iroh/endpoint/enum.RelayMode.html index f227d6c745..876720a4a7 100644 --- a/pr/4324/docs/iroh/endpoint/enum.RelayMode.html +++ b/pr/4324/docs/iroh/endpoint/enum.RelayMode.html @@ -1,4 +1,4 @@ -RelayMode in iroh::endpoint - Rust

RelayMode

Enum RelayMode 

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

RelayMode

Enum RelayMode 

Source
pub enum RelayMode {
     Disabled,
     Default,
     Staging,
@@ -10,14 +10,14 @@ This means that neither listening nor dialing relays will be available.

See crate::defaults::prod for the severs used.

§

Staging

Use the staging relay servers from n0.

§

Custom(RelayMap)

Use a custom relay map.

-

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

-
Source

pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self

Create a custom relay mode from a list of RelayUrls.

+

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

+
Source

pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self

Create a custom relay mode from a list of RelayUrls.

§Example
RelayMode::custom([
     "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?,
     "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?,
-]);

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

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 RelayMode

Source§

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

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

impl From<RelayMode> for Option<TransportConfig>

Source§

fn from(mode: RelayMode) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RelayMode

Source§

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

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

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

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

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +]);

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

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 RelayMode

Source§

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

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

impl From<RelayMode> for Option<TransportConfig>

Source§

fn from(mode: RelayMode) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RelayMode

Source§

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

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

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

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

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/4324/docs/iroh/endpoint/fn.default_relay_mode.html index bbf883400d..8602b880d6 100644 --- a/pr/4324/docs/iroh/endpoint/fn.default_relay_mode.html +++ b/pr/4324/docs/iroh/endpoint/fn.default_relay_mode.html @@ -1,4 +1,4 @@ -default_relay_mode in iroh::endpoint - Rust

default_relay_mode

Function default_relay_mode 

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

+default_relay_mode in iroh::endpoint - Rust

default_relay_mode

Function default_relay_mode 

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

If the IROH_FORCE_STAGING_RELAYS environment variable is non empty, it will return RelayMode::Staging. Otherwise, it will return RelayMode::Default.

\ No newline at end of file diff --git a/pr/4324/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/4324/docs/iroh/endpoint/fn.force_staging_infra.html index 70bafd0f9d..d07d2f1834 100644 --- a/pr/4324/docs/iroh/endpoint/fn.force_staging_infra.html +++ b/pr/4324/docs/iroh/endpoint/fn.force_staging_infra.html @@ -1,2 +1,2 @@ -force_staging_infra in iroh::endpoint - Rust

force_staging_infra

Function force_staging_infra 

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

+force_staging_infra in iroh::endpoint - Rust

force_staging_infra

Function force_staging_infra 

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

\ No newline at end of file diff --git a/pr/4324/docs/iroh/endpoint/index.html b/pr/4324/docs/iroh/endpoint/index.html index 516a763f96..519f977373 100644 --- a/pr/4324/docs/iroh/endpoint/index.html +++ b/pr/4324/docs/iroh/endpoint/index.html @@ -1,4 +1,4 @@ -iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

The Endpoint allows establishing connections to other iroh endpoints.

+iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

The Endpoint allows establishing connections to other iroh endpoints.

The Endpoint is the main API interface to manage a local iroh endpoint. It allows connecting to and accepting connections from other endpoints. See the module docs for more details on how iroh connections work.

diff --git a/pr/4324/docs/iroh/endpoint/struct.Builder.html b/pr/4324/docs/iroh/endpoint/struct.Builder.html index 511c507d28..771ed9fb3a 100644 --- a/pr/4324/docs/iroh/endpoint/struct.Builder.html +++ b/pr/4324/docs/iroh/endpoint/struct.Builder.html @@ -2,12 +2,12 @@

By default the endpoint will generate a new random SecretKey, which will result in a new EndpointId.

To create the Endpoint call Builder::bind.

-

Implementations§

Source§

impl Builder

Source

pub fn new(preset: impl Preset) -> Self

Creates a new Builder using the given Preset.

+

Implementations§

Source§

impl Builder

Source

pub fn new(preset: impl Preset) -> Self

Creates a new Builder using the given Preset.

See presets for more.

Source

pub fn preset(self, preset: impl Preset) -> Self

Applies the given Preset.

Source

pub fn empty() -> Self

Creates an empty builder with no address lookup services, and RelayMode::Disabled.

-
Source

pub async fn bind(self) -> Result<Endpoint, BindError>

Binds the endpoint.

-
Source

pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr>
where +

Source

pub async fn bind(self) -> Result<Endpoint, BindError>

Binds the endpoint.

+
Source

pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr>

Available on non-wasm_browser only.

Binds an IP socket at the provided socket address.

This is an advanced API to tightly control the sockets used by the endpoint. Most @@ -48,7 +48,7 @@ port 0 in the socket address assigns a random free port.

.bind_addr("127.0.0.1:0")? .bind_addr("[::1]:0")? .bind() - .await?;
Source

pub fn bind_addr_with_opts<A>( + .await?;

Source

pub fn bind_addr_with_opts<A>( self, addr: A, opts: BindOpts, @@ -107,16 +107,16 @@ routing with the prefix length and default route as described above does not app .bind_addr_with_opts("127.0.0.1:0", BindOpts::default().set_prefix_len(24))? .bind_addr_with_opts("[::1]:0", BindOpts::default().set_prefix_len(48))? .bind() - .await?;

Source

pub fn clear_ip_transports(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports.

-
Source

pub fn clear_relay_transports(self) -> Self

Removes all relay based transports.

-
Source

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

Sets a secret key to authenticate with other peers.

+ .await?;
Source

pub fn clear_ip_transports(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports.

+
Source

pub fn clear_relay_transports(self) -> Self

Removes all relay based transports.

+
Source

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

Sets a secret key to authenticate with other peers.

This secret key’s public key will be the PublicKey of this endpoint and thus also its EndpointId

If not set, a new secret key will be generated.

-
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

+
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

Not setting this will still allow creating connections, but to accept incoming connections at least one ALPN must be set.

-
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

+
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

Relay servers are used to establish initial connection with another iroh endpoint. They also perform various functions related to hole punching, see the crate docs for more details.

@@ -124,11 +124,11 @@ for more details.

When using RelayMode::Custom, the provided relay_map must contain at least one configured relay endpoint. If an invalid RelayMap is provided bind will result in an error.

-
Source

pub fn clear_address_lookup(self) -> Self

Removes all Address Lookup services from the builder.

+
Source

pub fn clear_address_lookup(self) -> Self

Removes all Address Lookup services from the builder.

If no Address Lookup is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::address_lookup::AddressLookup trait for details.

-
Source

pub fn address_lookup(self, address_lookup: impl AddressLookupBuilder) -> Self

Adds an additional Address Lookup for this endpoint.

+
Source

pub fn address_lookup(self, address_lookup: impl AddressLookupBuilder) -> Self

Adds an additional Address Lookup for this endpoint.

Once the endpoint is created the provided AddressLookupBuilder::into_address_lookup will be called. This allows Address Lookup’s to finalize their configuration by e.g. using the secret key from the endpoint which can be needed to sign published information.

@@ -139,25 +139,25 @@ will be combined using an internal instance of the

If no Address Lookup is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::address_lookup::AddressLookup trait for details.

-
Source

pub fn addr_filter(self, filter: AddrFilter) -> Self

Sets the address filter applied to all address data before publishing.

+
Source

pub fn addr_filter(self, filter: AddrFilter) -> Self

Sets the address filter applied to all address data before publishing.

This filter is applied once, at the AddressLookupServices level, before distributing data to any individual address lookup service. This ensures consistent filtering regardless of how the services configured.

-
Source

pub fn clear_addr_filter(self) -> Self

Clears the address filter, allowing all addresses to be published.

+
Source

pub fn clear_addr_filter(self) -> Self

Clears the address filter, allowing all addresses to be published.

This removes any filter previously set via Self::addr_filter, including filters set by presets.

-
Source

pub fn user_data_for_address_lookup(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in Address Lookup’s for this node.

+
Source

pub fn user_data_for_address_lookup(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in Address Lookup’s for this node.

When using Address Lookup’s, this string of UserData will be published together with the endpoint’s addresses and relay URL. When other endpoints discover this endpoint, they retrieve the UserData in addition to the addressing info.

Iroh itself does not interpret the user-defined data in any way, it is purely left for applications to parse and use.

-
Source

pub fn external_addr(self, addr: SocketAddr) -> Self

Adds an external address on which this endpoint is directly reachable.

+
Source

pub fn external_addr(self, addr: SocketAddr) -> Self

Adds an external address on which this endpoint is directly reachable.

This address will be advertised to peers together with any discovered external addresses and will be used in NAT traversal and to establish direct connections.

Can be called multiple times. See also Endpoint::add_external_addr for adding addresses at runtime.

-
Source

pub fn transport_config(self, transport_config: QuicTransportConfig) -> Self

Sets a custom QuicTransportConfig for this endpoint.

+
Source

pub fn transport_config(self, transport_config: QuicTransportConfig) -> Self

Sets a custom QuicTransportConfig for this endpoint.

The transport config contains parameters governing the QUIC state machine.

If unset, the default config is used. Default values should be suitable for most internet applications. Applications protocols which forbid remotely-initiated @@ -165,38 +165,38 @@ streams should set max_concurrent_bidi_streams and max_concur zero.

Please be aware that changing some settings may have adverse effects on establishing and maintaining direct connections.

-
Source

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

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

+
Source

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

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

The DNS resolver is used to resolve relay hostnames, and endpoint addresses if crate::address_lookup::DnsAddressLookup is configured.

By default, a new DNS resolver is created which is configured to use the host system’s DNS configuration. You can pass a custom instance of DnsResolver here to use a differently configured DNS resolver for this endpoint, or to share a DnsResolver between multiple endpoints.

-
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

-
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

+
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

+
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

  • HTTP_PROXY
  • http_proxy
  • HTTPS_PROXY
  • https_proxy
-
Source

pub fn ca_tls_config(self, ca_tls_config: CaTlsConfig) -> Self

Sets the trusted CA root certificates for non-iroh TLS connections.

+
Source

pub fn ca_tls_config(self, ca_tls_config: CaTlsConfig) -> Self

Sets the trusted CA root certificates for non-iroh TLS connections.

These Certificate Authority roots are used as trust anchors for verifying the validity of TLS certificates presented by external services, such as iroh relays, pkarr servers, or DNS-over-HTTPS resolvers. They don’t need to be trusted for the integrity or authenticity of native iroh connections, which rely on iroh’s own cryptographic authentication mechanisms.

-
Source

pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self

👎Deprecated since 1.0.0: Renamed to ca_tls_config
Source

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

Enables saving the TLS pre-master key for connections.

+
Source

pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self

👎Deprecated since 1.0.0: Renamed to ca_tls_config
Source

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

Enables saving the TLS pre-master key for connections.

This key should normally remain secret but can be useful to debug networking issues by decrypting captured traffic.

If keylog is true then setting the SSLKEYLOGFILE environment variable to a filename will result in this file being used to log the TLS pre-master keys.

-
Source

pub fn max_tls_tickets(self, n: usize) -> Self

Set the maximum number of TLS tickets to cache.

+
Source

pub fn max_tls_tickets(self, n: usize) -> Self

Set the maximum number of TLS tickets to cache.

Set this to a larger value if you want to do 0rtt connections to a large number of clients.

The default is 256, taking about 150 KiB in memory.

-
Source

pub fn crypto_provider(self, crypto_provider: Arc<CryptoProvider>) -> Self

Specify the rustls cryptography to use for all TLS operations.

+
Source

pub fn crypto_provider(self, crypto_provider: Arc<CryptoProvider>) -> Self

Specify the rustls cryptography to use for all TLS operations.

This includes

  • TLS for encryption and authentication of iroh connections themselves, but also
  • @@ -208,17 +208,17 @@ number of clients.

    If either the tls-ring or tls-aws-lc-rs feature is set in iroh, this function doesn’t need to be called.

    If none of these features are set, then calling this function in the builder is mandatory.

    -
Source

pub fn hooks(self, hooks: impl EndpointHooks + 'static) -> Self

Install hooks onto the endpoint.

+
Source

pub fn hooks(self, hooks: impl EndpointHooks + 'static) -> Self

Install hooks onto the endpoint.

Endpoint hooks intercept the connection establishment process of an Endpoint.

You can install multiple EndpointHooks by calling this function multiple times. Order matters: hooks are invoked in the order they were installed onto the endpoint builder. Once a hook returns reject, further processing is aborted and other hooks won’t be invoked.

See EndpointHooks for details on the possible interception points in the connection lifecycle.

-
Source

pub fn portmapper_config(self, config: PortmapperConfig) -> Self

Configures the portmapper service (UPnP, PCP, NAT-PMP).

+
Source

pub fn portmapper_config(self, config: PortmapperConfig) -> Self

Configures the portmapper service (UPnP, PCP, NAT-PMP).

Defaults to PortmapperConfig::Enabled.

-
Source

pub fn add_custom_transport(self, factory: Arc<dyn CustomTransport>) -> Self

Available on crate feature unstable-custom-transports only.

Adds a custom transport

-
Source

pub fn path_selector(self, selector: Arc<dyn PathSelector>) -> Self

Available on crate feature unstable-custom-transports only.

Sets a custom PathSelector for this endpoint.

+
Source

pub fn add_custom_transport(self, factory: Arc<dyn CustomTransport>) -> Self

Available on crate feature unstable-custom-transports only.

Adds a custom transport

+
Source

pub fn path_selector(self, selector: Arc<dyn PathSelector>) -> Self

Available on crate feature unstable-custom-transports only.

Sets a custom PathSelector for this endpoint.

The path selector decides which path to use among the candidate paths to a remote endpoint. By default iroh uses a built-in selector that sorts paths by biased RTT (with IPv6 preferred over IPv4 and relay treated as backup) and is diff --git a/pr/4324/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/4324/docs/iroh/endpoint/struct.ConnectOptions.html index 1174a630d1..8520d53638 100644 --- a/pr/4324/docs/iroh/endpoint/struct.ConnectOptions.html +++ b/pr/4324/docs/iroh/endpoint/struct.ConnectOptions.html @@ -1,12 +1,12 @@ -ConnectOptions in iroh::endpoint - Rust

ConnectOptions

Struct ConnectOptions 

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

Options for the Endpoint::connect_with_opts function.

-

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

+ConnectOptions in iroh::endpoint - Rust

ConnectOptions

Struct ConnectOptions 

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

Options for the Endpoint::connect_with_opts function.

+

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

By default, the connection will use the same options as Endpoint::connect, e.g. a default QuicTransportConfig.

-
Source

pub fn with_transport_config( +

Source

pub fn with_transport_config( self, transport_config: QuicTransportConfig, ) -> Self

Sets the QUIC transport config options for this connection.

-
Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

Sets ALPN identifiers that should be signaled as supported on connection, in +

Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

Sets ALPN identifiers that should be signaled as supported on connection, in addition to the main ALPN identifier used in Endpoint::connect_with_opts.

This allows connecting to servers that may only support older versions of your protocol. In this case, you would add the older ALPN identifiers with this @@ -20,7 +20,7 @@ list or the main ALPN identifiers on the accept side, see the endpoint builder’s Builder::alpns function.

-

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

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

Source§

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

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

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

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

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

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

Source§

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

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

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

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

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/struct.DirectAddr.html b/pr/4324/docs/iroh/endpoint/struct.DirectAddr.html index 1d822b657b..5d502f8753 100644 --- a/pr/4324/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/4324/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§

§

impl Freeze for DirectAddr

§

impl RefUnwindSafe for DirectAddr

§

impl Send for DirectAddr

§

impl Sync for DirectAddr

§

impl Unpin for DirectAddr

§

impl UnwindSafe for DirectAddr

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/4324/docs/iroh/endpoint/struct.Endpoint.html b/pr/4324/docs/iroh/endpoint/struct.Endpoint.html index 0728bf2252..296c8301b2 100644 --- a/pr/4324/docs/iroh/endpoint/struct.Endpoint.html +++ b/pr/4324/docs/iroh/endpoint/struct.Endpoint.html @@ -1,4 +1,4 @@ -Endpoint in iroh::endpoint - Rust

Endpoint

Struct Endpoint 

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

Controls an iroh endpoint, establishing connections with other endpoints.

+Endpoint in iroh::endpoint - Rust

Endpoint

Struct Endpoint 

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

Controls an iroh endpoint, establishing connections with other endpoints.

This is the main API interface to create connections to, and accept connections from other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is used to make the connections reliable. See the [crate docs] for a more detailed @@ -22,28 +22,28 @@ through JNI, which needs a JVM context published to DnsResolver for the supported initialization paths.

-

Implementations§

Source§

impl Endpoint

Source

pub fn builder(preset: impl Preset) -> Builder

Returns the builder for an Endpoint, with the given Preset configuration.

-
Source

pub async fn bind(preset: impl Preset) -> Result<Self, BindError>

Constructs a default Endpoint using the provided Preset and binds it immediately.

-
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

+

Implementations§

Source§

impl Endpoint

Source

pub fn builder(preset: impl Preset) -> Builder

Returns the builder for an Endpoint, with the given Preset configuration.

+
Source

pub async fn bind(preset: impl Preset) -> Result<Self, BindError>

Constructs a default Endpoint using the provided Preset and binds it immediately.

+
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

This will only affect new incoming connections. Note that this overrides the current list of ALPNs.

If the endpoint is closed, this method will log a warning and ignore the request to set new ALPNs.

-
Source

pub async fn insert_relay( +

Source

pub async fn insert_relay( &self, relay: RelayUrl, config: Arc<RelayConfig>, ) -> Option<Arc<RelayConfig>>

Adds the provided configuration to the RelayMap.

Replacing and returning any existing configuration for RelayUrl.

Will also return None if the endpoint is closed.

-
Source

pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>>

Removes the configuration from the RelayMap for the provided RelayUrl.

+
Source

pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>>

Removes the configuration from the RelayMap for the provided RelayUrl.

Returns any existing configuration if it exists. Will also return None if the endpoint is closed.

-
Source

pub async fn add_external_addr(&self, addr: SocketAddr)

Adds an external address on which this endpoint is directly reachable.

+
Source

pub async fn add_external_addr(&self, addr: SocketAddr)

Adds an external address on which this endpoint is directly reachable.

This address will be advertised to peers together with any discovered external addresses and will be used in NAT traversal and to establish direct connections.

See also Builder::external_addr for setting addresses at build time.

-
Source

pub async fn remove_external_addr(&self, addr: &SocketAddr) -> bool

Removes a configured external address. Returns true if it was present.

-
Source

pub async fn connect( +

Source

pub async fn remove_external_addr(&self, addr: &SocketAddr) -> bool

Removes a configured external address. Returns true if it was present.

+
Source

pub async fn connect( &self, endpoint_addr: impl Into<EndpointAddr>, alpn: &[u8], @@ -63,7 +63,7 @@ connection attempt will fail with an error.

The alpn, or application-level protocol identifier, is also required. The remote endpoint must support this alpn, otherwise the connection attempt will fail with an error.

-

Source

pub async fn connect_with_opts( +

Source

pub async fn connect_with_opts( &self, endpoint_addr: impl Into<EndpointAddr>, alpn: &[u8], @@ -83,17 +83,17 @@ security concerns. establishing and maintaining direct connections. Carefully test settings you use and consider this currently as still rather experimental. -

Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

+
Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

Only connections with the ALPNs configured in Builder::alpns will be accepted. If multiple ALPNs have been configured the ALPN can be inspected before accepting the connection using Connecting::alpn.

The returned future will yield None if the endpoint is closed by calling Endpoint::close.

-
Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

-
Source

pub fn id(&self) -> EndpointId

Returns the endpoint id of this endpoint.

+
Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

+
Source

pub fn id(&self) -> EndpointId

Returns the endpoint id of this endpoint.

This ID is the unique addressing information of this endpoint and other peers must know it to be able to connect to this endpoint.

-
Source

pub fn addr(&self) -> EndpointAddr

Returns the current EndpointAddr. +

Source

pub fn addr(&self) -> EndpointAddr

Returns the current EndpointAddr. As long as the endpoint was able to bind to a network interface, some local addresses will be available.

The state of other fields depends on the state of networking and connectivity. @@ -103,7 +103,7 @@ to ensure that the EndpointAddr will contain enough information to to be dialable by a remote endpoint over the internet.

You can use the Endpoint::watch_addr method to get updates when the EndpointAddr changes.

-
Source

pub fn watch_addr(&self) -> impl Watcher<Value = EndpointAddr> + use<>

Available on non-wasm_browser only.

Returns a Watcher for the current EndpointAddr for this endpoint.

+
Source

pub fn watch_addr(&self) -> impl Watcher<Value = EndpointAddr> + use<>

Available on non-wasm_browser only.

Returns a Watcher for the current EndpointAddr for this endpoint.

The observed EndpointAddr will have the current RelayUrl and direct addresses.

use iroh::{Endpoint, Watcher, endpoint::presets};
@@ -146,7 +146,7 @@ tokio::spawn(endpoint_closed.run_until(async move {
 }));
 // Do fancy things, then close the endpoint.
 // Our task above will stop even if there are still clones of `Endpoint` alive somewhere.
-endpoint.close().await;
Source

pub async fn online(&self)

A convenience method that waits for the endpoint to be considered “online”.

+endpoint.close().await;
Source

pub async fn online(&self)

A convenience method that waits for the endpoint to be considered “online”.

This currently means at least one relay server has completed its connection handshake (i.e. the endpoint is registered and reachable via that relay). Merely selecting a relay URL is not sufficient.

@@ -179,7 +179,7 @@ let endpoint = Endpoint::bind().await; // After this await returns we have a connection to at least one relay // and holepunching should work as expected. endpoint.online().await; -}
Source

pub fn home_relay_status( +}

Source

pub fn home_relay_status( &self, ) -> impl Watcher<Value = Vec<RelayStatus>> + use<>

Returns a Watcher over the connection status of the endpoint’s home relays.

The watched value has one entry per home relay whose URL is known, @@ -191,25 +191,25 @@ See Endpoint is dropped. Closing the endpoint does not disconnect the watcher. To stop a task once the endpoint stops, combine with Self::closed.

-
Source

pub fn bound_sockets(&self) -> Vec<SocketAddr>

Available on non-wasm_browser only.

Returns the local socket addresses on which the underlying sockets are bound.

+
Source

pub fn bound_sockets(&self) -> Vec<SocketAddr>

Available on non-wasm_browser only.

Returns the local socket addresses on which the underlying sockets are bound.

The Endpoint always binds on an IPv4 address and also tries to bind on an IPv6 address if available.

-
Source

pub fn dns_resolver(&self) -> Result<&DnsResolver, EndpointError>

Available on non-wasm_browser only.

Returns the DNS resolver used in this Endpoint.

+
Source

pub fn dns_resolver(&self) -> Result<&DnsResolver, EndpointError>

Available on non-wasm_browser only.

Returns the DNS resolver used in this Endpoint.

§Errors

Returns an EndpointError::Closed error if the endpoint is closed.

See Builder::dns_resolver.

-
Source

pub fn tls_config(&self) -> &ClientConfig

Returns the [rustls::ClientConfig] used by the endpoint for connecting to external services.

+
Source

pub fn tls_config(&self) -> &ClientConfig

Returns the [rustls::ClientConfig] used by the endpoint for connecting to external services.

This might be useful for address lookup services or other functions that want to use the same trust anchors as iroh does for verifying the validity of TLS certificates presented by external services.

Note that this TLS config is unrelated to how iroh validates the authenticity of iroh connections itself.

The config is based on the trust anchors set via Builder::ca_tls_config.

-
Source

pub fn address_lookup(&self) -> Result<&AddressLookupServices, EndpointError>

Returns the Address Lookup service, if configured.

+
Source

pub fn address_lookup(&self) -> Result<&AddressLookupServices, EndpointError>

Returns the Address Lookup service, if configured.

§Errors

Returns a EndpointError::Closed error if the endpoint is closed.

See Builder::address_lookup.

-
Source

pub fn metrics(&self) -> &EndpointMetrics

Available on crate feature metrics only.

Returns metrics collected for this endpoint.

+
Source

pub fn metrics(&self) -> &EndpointMetrics

Available on crate feature metrics only.

Returns metrics collected for this endpoint.

The endpoint internally collects various metrics about its operation. The returned EndpointMetrics struct contains all of these metrics.

You can access individual metrics directly by using the public fields:

@@ -275,13 +275,13 @@ registry.write().unwrap().register_all(endpoint.metrics()); .std_context("text")?; assert!(res.contains(r#"TYPE socket_recv_datagrams counter"#)); -assert!(res.contains(r#"socket_recv_datagrams_total 0"#));
Source

pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo>

Returns addressing information about a recently used remote endpoint.

+assert!(res.contains(r#"socket_recv_datagrams_total 0"#));
Source

pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo>

Returns addressing information about a recently used remote endpoint.

The returned RemoteInfo contains a list of all transport addresses for the remote that we know about. This is a snapshot in time and not a watcher.

Returns None if the endpoint doesn’t have information about the remote or if the endpoint is closed. When remote endpoints are no longer used, our endpoint will keep information around for a little while, and then drop it. Afterwards, this will return None.

-
Source

pub async fn network_change(&self)

Notifies the system of potential network changes.

+
Source

pub async fn network_change(&self)

Notifies the system of potential network changes.

On many systems iroh is able to detect network changes by itself, however some systems like android do not expose this functionality to native code. Android does however provide this functionality to Java code. This @@ -290,14 +290,14 @@ this.

Even when the network did not change, or iroh was already able to detect the network change itself, there is no harm in calling this function.

If the endpoint is closed, this method will log a warning and ignore the request.

-
Source

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

Sets the initial user-defined data to be published in Address Lookups for this endpoint.

+
Source

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

Sets the initial user-defined data to be published in Address Lookups for this endpoint.

If the user-defined data passed to this function is different to the previous one, the endpoint will republish its endpoint info to the configured Address Lookups.

See also Builder::user_data_for_address_lookup for setting an initial value when building the endpoint.

If the endpoint is closed, this method will log a warning and ignore the request.

-
Source

pub async fn close(&self)

Closes the QUIC endpoint and the socket.

+
Source

pub async fn close(&self)

Closes the QUIC endpoint and the socket.

This will close any remaining open Connections with an error code of 0 and an empty reason. Though it is best practice to close those explicitly before with a custom error code and reason.

@@ -323,8 +323,8 @@ while TCP sockets usually get closed and drained by the operating system in the kernel during the “Time-Wait” period of the TCP socket.

Be aware however that the underlying UDP sockets are only closed once all clones of the the respective Endpoint are dropped.

-
Source

pub fn is_closed(&self) -> bool

Check if this endpoint is still alive, or already closed.

-
Source

pub fn closed(&self) -> EndpointClosed ⓘ

Returns a future that resolves once the endpoint closes.

+
Source

pub fn is_closed(&self) -> bool

Check if this endpoint is still alive, or already closed.

+
Source

pub fn closed(&self) -> EndpointClosed ⓘ

Returns a future that resolves once the endpoint closes.

The returned future does not contain a clone or reference to the Endpoint, so keeping the returned future alive does not prevent the endpoint from being dropped.

To run a task and stop it once the endpoint closes, you can use @@ -333,13 +333,13 @@ so keeping the returned future alive does not prevent the endpoint from being dr

let endpoint = Endpoint::bind(presets::N0).await?;
 tokio::spawn(endpoint.closed().run_until(async move {
     // the future will be aborted once the endpoint closes.
-}));
Source

pub fn create_server_config_builder( +}));

Source

pub fn create_server_config_builder( &self, alpns: Vec<Vec<u8>>, ) -> ServerConfigBuilder

Create a ServerConfigBuilder for this endpoint that includes the given alpns.

Use the ServerConfigBuilder to customize the ServerConfig connection configuration for a connection accepted using the Incoming::accept_with method.

-

Trait Implementations§

Source§

impl Clone for Endpoint

Source§

fn clone(&self) -> Endpoint

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 Endpoint

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Endpoint

§

impl !RefUnwindSafe for Endpoint

§

impl Send for Endpoint

§

impl Sync for Endpoint

§

impl Unpin for Endpoint

§

impl !UnwindSafe for Endpoint

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for Endpoint

Source§

fn clone(&self) -> Endpoint

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 Endpoint

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Endpoint

§

impl !RefUnwindSafe for Endpoint

§

impl Send for Endpoint

§

impl Sync for Endpoint

§

impl Unpin for Endpoint

§

impl !UnwindSafe for Endpoint

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/4324/docs/iroh/endpoint/struct.EndpointClosed.html b/pr/4324/docs/iroh/endpoint/struct.EndpointClosed.html index 596b8a08f0..c1f1d383f9 100644 --- a/pr/4324/docs/iroh/endpoint/struct.EndpointClosed.html +++ b/pr/4324/docs/iroh/endpoint/struct.EndpointClosed.html @@ -1,9 +1,9 @@ -EndpointClosed in iroh::endpoint - Rust

EndpointClosed

Struct EndpointClosed 

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

Future returned from Endpoint::closed.

-

Implementations§

Source§

impl EndpointClosed

Source

pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output>

Runs a future to completion, or until the Endpoint is closed.

+EndpointClosed in iroh::endpoint - Rust

EndpointClosed

Struct EndpointClosed 

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

Future returned from Endpoint::closed.

+

Implementations§

Source§

impl EndpointClosed

Source

pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output>

Runs a future to completion, or until the Endpoint is closed.

Returns the output of fut if it completes before the endpoint closes, or None otherwise.

-

Trait Implementations§

Source§

impl Debug for EndpointClosed

Source§

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

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

impl Future for EndpointClosed

Source§

type Output = ()

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for EndpointClosed
where +

Trait Implementations§

Source§

impl Debug for EndpointClosed

Source§

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

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

impl Future for EndpointClosed

Source§

type Output = ()

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for EndpointClosed
where PinnedFieldsOf<__EndpointClosed<'pin>>: Unpin,

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/4324/docs/iroh/endpoint/struct.RelayStatus.html b/pr/4324/docs/iroh/endpoint/struct.RelayStatus.html index 0344cdab17..d05a60975d 100644 --- a/pr/4324/docs/iroh/endpoint/struct.RelayStatus.html +++ b/pr/4324/docs/iroh/endpoint/struct.RelayStatus.html @@ -1,13 +1,13 @@ -RelayStatus in iroh::endpoint - Rust

RelayStatus

Struct RelayStatus 

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

Connection status of a single home relay.

+RelayStatus in iroh::endpoint - Rust

RelayStatus

Struct RelayStatus 

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

Connection status of a single home relay.

Observed via Endpoint::home_relay_status.

-

Implementations§

Source§

impl RelayStatus

Source

pub fn url(&self) -> &RelayUrl

Returns the URL of the home relay.

-
Source

pub fn is_connected(&self) -> bool

Returns true if the endpoint is connected to the relay.

-
Source

pub fn last_error(&self) -> Option<&AnyError>

Returns the most recent connection error, if the relay is currently +

Implementations§

Source§

impl RelayStatus

Source

pub fn url(&self) -> &RelayUrl

Returns the URL of the home relay.

+
Source

pub fn is_connected(&self) -> bool

Returns true if the endpoint is connected to the relay.

+
Source

pub fn last_error(&self) -> Option<&AnyError>

Returns the most recent connection error, if the relay is currently disconnected.

Returns None when the relay is connected, or when the endpoint has not yet observed a failed connection attempt.

-

Trait Implementations§

Source§

impl Clone for RelayStatus

Source§

fn clone(&self) -> RelayStatus

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 RelayStatus

Source§

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

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

impl PartialEq for RelayStatus

Source§

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

Source§

impl StructuralPartialEq for RelayStatus

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for RelayStatus

Source§

fn clone(&self) -> RelayStatus

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 RelayStatus

Source§

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

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

impl PartialEq for RelayStatus

Source§

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

Source§

impl StructuralPartialEq for RelayStatus

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/4324/docs/iroh/tls/enum.TlsConfigError.html b/pr/4324/docs/iroh/tls/enum.TlsConfigError.html index ee06c8b11b..f2c3e67f2a 100644 --- a/pr/4324/docs/iroh/tls/enum.TlsConfigError.html +++ b/pr/4324/docs/iroh/tls/enum.TlsConfigError.html @@ -9,7 +9,7 @@ }, }

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

CryptoProviderNoInitialCipherSuite

Fields

§source: NoInitialCipherSuite
§meta: Meta

Captured call-site metadata

§

CryptoProviderIncompatible

Fields

§source: Error
§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for TlsConfigError

Source§

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

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

impl Display for TlsConfigError

Source§

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

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

impl Error for TlsConfigError

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 TlsConfigError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<NoInitialCipherSuite> for TlsConfigError

Source§

fn from(source: NoInitialCipherSuite) -> Self

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for AnyError

Source§

fn from(value: TlsConfigError) -> AnyError

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for BindError

Source§

fn from(source: TlsConfigError) -> Self

Converts to this type from the input type.
Source§

impl StackError for TlsConfigError

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 +

Trait Implementations§

Source§

impl Debug for TlsConfigError

Source§

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

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

impl Display for TlsConfigError

Source§

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

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

impl Error for TlsConfigError

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 TlsConfigError

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<NoInitialCipherSuite> for TlsConfigError

Source§

fn from(source: NoInitialCipherSuite) -> Self

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for AnyError

Source§

fn from(value: TlsConfigError) -> AnyError

Converts to this type from the input type.
Source§

impl From<TlsConfigError> for BindError

Source§

fn from(source: TlsConfigError) -> Self

Converts to this type from the input type.
Source§

impl StackError for TlsConfigError

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 T: 'a,

§

fn implicit( diff --git a/pr/4324/docs/src/iroh/endpoint.rs.html b/pr/4324/docs/src/iroh/endpoint.rs.html index 98ec87b760..0e65b9b0ee 100644 --- a/pr/4324/docs/src/iroh/endpoint.rs.html +++ b/pr/4324/docs/src/iroh/endpoint.rs.html @@ -236,3751 +236,3752 @@ 236 tls_config, 237 transport_config: self.transport_config.clone(), 238 token_key, -239 }; -240 let server_config = static_config.create_server_config(self.alpn_protocols); -241 -242 #[cfg(not(wasm_browser))] -243 let dns_resolver = self.dns_resolver.unwrap_or_default(); -244 -245 let metrics = EndpointMetrics::default(); -246 -247 let tls_config = self -248 .ca_tls_config -249 .unwrap_or_default() -250 .client_config(crypto_provider) -251 .map_err(|err| e!(BindError::InvalidCaRootConfig, err))?; -252 -253 let sock_opts = socket::Options { -254 transports: self.transports, -255 secret_key, -256 address_lookup_user_data: self.address_lookup_user_data, -257 proxy_url: self.proxy_url, -258 #[cfg(not(wasm_browser))] -259 dns_resolver, -260 server_config, -261 tls_config, -262 metrics, -263 hooks: self.hooks, -264 path_selector: self.path_selector, -265 portmapper_config: self.portmapper_config, -266 static_config, -267 configured_addrs: self.configured_addrs, -268 }; -269 -270 let inner = socket::EndpointInner::bind(sock_opts) -271 .instrument(Span::current()) -272 .await?; -273 debug!( -274 id = %inner.static_config.tls_config.secret_key.public(), -275 iroh_version = %env!("CARGO_PKG_VERSION"), -276 "iroh endpoint bound" -277 ); -278 -279 let ep = Endpoint { -280 inner: Arc::new(inner), -281 }; -282 -283 // Add Address Lookup mechanisms -284 let address_lookup = ep.address_lookup().expect("just created the endpoint"); -285 if let Some(filter) = self.addr_filter { -286 address_lookup.set_addr_filter(filter); -287 } -288 for create_service in self.address_lookup { -289 let service = create_service.into_address_lookup(&ep)?; -290 address_lookup.add_boxed(service); -291 } -292 -293 Ok(ep) -294 } -295 -296 // # The very common methods everyone basically needs. -297 -298 /// Binds an IP socket at the provided socket address. -299 /// -300 /// This is an advanced API to tightly control the sockets used by the endpoint. Most -301 /// uses do not need to explicitly bind sockets. -302 /// -303 /// # Warning -304 /// -305 /// - The builder always comes pre-configured with an IPv4 socket to be bound on the -306 /// *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY` -307 /// special bind address and results in a socket listening on *all* interfaces -308 /// available. -309 /// -310 /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound -311 /// on the *unspecified* address: `[::]`. This bind is allowed to fail however. -312 /// -313 /// - Adding a bind address removes the pre-configured unspecified bind address for this -314 /// address family. Use [`Self::bind_addr_with_opts`] to bind additional addresses without -315 /// replacing the default bind address. -316 /// -317 /// - This should be called at most once for each address family: once for IPv4 and/or -318 /// once for IPv6. Calling it multiple times for the same address family will result -319 /// in undefined routing behaviour. To bind multiple sockets of the same address -320 /// family, use [`Self::bind_addr_with_opts`]. -321 /// -322 /// # Description -323 /// -324 /// Requests a socket to be bound on a specific address, with an implied netmask of -325 /// `/0`. This allows restricting binding to only one network interface for a given -326 /// address family. -327 /// -328 /// If the port specified is already in use, binding the endpoint will fail. Using -329 /// port `0` in the socket address assigns a random free port. -330 /// -331 /// # Example -332 /// -333 /// ```no_run -334 /// # #[cfg(with_crypto_provider)] -335 /// # { -336 /// # #[tokio::main] -337 /// # async fn main() -> n0_error::Result<()> { -338 /// # use iroh::{Endpoint, endpoint::presets}; -339 /// let endpoint = Endpoint::builder(presets::N0) -340 /// .clear_ip_transports() -341 /// .bind_addr("127.0.0.1:0")? -342 /// .bind_addr("[::1]:0")? -343 /// .bind() -344 /// .await?; -345 /// # Ok(()) } -346 /// # } -347 /// ``` -348 #[cfg(not(wasm_browser))] -349 pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr> -350 where -351 A: ToSocketAddr, -352 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, -353 { -354 self.bind_addr_with_opts(addr, BindOpts::default()) -355 } -356 -357 /// Binds an IP socket at the provided socket address. -358 /// -359 /// This is an advanced API to tightly control the sockets used by the endpoint. Most -360 /// uses do not need to explicitly bind sockets. -361 /// -362 /// # Warning -363 /// -364 /// - The builder always comes pre-configured with an IPv4 socket to be bound on the -365 /// *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY` -366 /// special bind address and results in a socket listening on *all* interfaces -367 /// available. -368 /// -369 /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound -370 /// on the *unspecified* address: `[::]`. This bind is allowed to fail however. -371 /// -372 /// # Description -373 /// -374 /// Requests a socket to be bound on a specific address. This allows restricting binding -375 /// to only one network interface for a given address family. -376 /// -377 /// [`BindOpts::set_prefix_len`] **should** be used to configure the netmask of the -378 /// network interface. This allows outgoing datagrams that start a new network flow to -379 /// be sent over the socket which is attached to the subnet of the destination -380 /// address. If multiple sockets are bound the standard routing-table semantics are -381 /// used: the socket attached to the subnet with the longest prefix matching the -382 /// destination is used. Practically this means the smallest subnets are at the top of -383 /// the routing table, and the first subnet containing the destination address is -384 /// chosen. -385 /// -386 /// If no socket is bound to a subnet that contains the destination address, the notion -387 /// of "default route" is used. At most one socket per address family may be marked as -388 /// the default route using [`BindOpts::set_is_default_route`], and this will be used -389 /// for destinations not contained by the subnets of the bound sockets. This network is -390 /// expected to have a default gateway configured. A socket with a prefix length of `/0` -391 /// will be set as a "default route" implicitly, unless [`BindOpts::set_is_default_route`] -392 /// is set to `false` explicitly. -393 /// -394 /// Be aware that using a subnet with a prefix length of `/0` will always contain all -395 /// destination addresses. It is valid to configure this, but no more than one such -396 /// socket should be bound or the routing will be non-deterministic. -397 /// -398 /// To use a subnet with a non-zero prefix length as the default route in addition to -399 /// being routed when its prefix matches, use [`BindOpts::set_is_default_route]. -400 /// Subnets with a prefix length of zero are always marked as default routes. -401 /// -402 /// Finally note that most outgoing datagrams are part of an existing network flow. That -403 /// is, they are in response to an incoming datagram. In this case the outgoing datagram -404 /// will be sent over the same socket as the incoming datagram was received on, and the -405 /// routing with the prefix length and default route as described above does not apply. -406 /// -407 /// Using port `0` in the socket address assigns a random free port. -408 /// -409 /// If the port specified is already in use, binding the endpoint will fail, unless -410 /// [`BindOpts::set_is_required`] is set to `false` -411 /// -412 /// # Example -413 /// ```no_run -414 /// # #[cfg(with_crypto_provider)] -415 /// # { -416 /// # #[tokio::main] -417 /// # async fn main() -> n0_error::Result<()> { -418 /// # use iroh::{Endpoint, endpoint::{BindOpts, presets}}; -419 /// let endpoint = Endpoint::builder(presets::N0) -420 /// .clear_ip_transports() -421 /// .bind_addr_with_opts("127.0.0.1:0", BindOpts::default().set_prefix_len(24))? -422 /// .bind_addr_with_opts("[::1]:0", BindOpts::default().set_prefix_len(48))? -423 /// .bind() -424 /// .await?; -425 /// # Ok(()) } -426 /// # } -427 /// ``` -428 #[cfg(not(wasm_browser))] -429 pub fn bind_addr_with_opts<A>( -430 mut self, -431 addr: A, -432 opts: BindOpts, -433 ) -> Result<Self, InvalidSocketAddr> -434 where -435 A: ToSocketAddr, -436 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, -437 { -438 let addr = addr.to_socket_addr().map_err(Into::into)?; -439 match addr { -440 SocketAddr::V4(addr) => { -441 if self -442 .transports -443 .iter() -444 .any(|t| t.is_ipv4_default() && t.is_user_defined()) -445 { -446 bail!(InvalidSocketAddr::DuplicateDefaultAddr); -447 } -448 -449 let ip_net = Ipv4Net::new(*addr.ip(), opts.prefix_len()) -450 .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?; -451 self.transports.push(TransportConfig::Ip { -452 config: IpConfig::V4 { -453 ip_net, -454 port: addr.port(), -455 is_required: opts.is_required(), -456 is_default: opts.is_default_route(), -457 }, -458 is_user_defined: true, -459 }); -460 } -461 SocketAddr::V6(addr) => { -462 if self -463 .transports -464 .iter() -465 .any(|t| t.is_ipv6_default() && t.is_user_defined()) -466 { -467 bail!(InvalidSocketAddr::DuplicateDefaultAddr); -468 } -469 -470 let ip_net = Ipv6Net::new(*addr.ip(), opts.prefix_len()) -471 .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?; -472 self.transports.push(TransportConfig::Ip { -473 config: IpConfig::V6 { -474 ip_net, -475 scope_id: addr.scope_id(), -476 port: addr.port(), -477 is_required: opts.is_required(), -478 is_default: opts.is_default_route(), -479 }, -480 is_user_defined: true, -481 }); -482 } -483 } -484 Ok(self) -485 } -486 -487 /// Removes all IP based transports. -488 #[cfg(not(wasm_browser))] -489 pub fn clear_ip_transports(mut self) -> Self { -490 self.transports -491 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); -492 self -493 } -494 -495 /// Removes all relay based transports. -496 pub fn clear_relay_transports(mut self) -> Self { -497 self.transports -498 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -499 self -500 } -501 -502 /// Sets a secret key to authenticate with other peers. -503 /// -504 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus -505 /// also its [`EndpointId`] -506 /// -507 /// If not set, a new secret key will be generated. -508 /// -509 /// [`PublicKey`]: iroh_base::PublicKey -510 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { -511 self.secret_key = Some(secret_key); -512 self -513 } -514 -515 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. -516 /// -517 /// Not setting this will still allow creating connections, but to accept incoming -518 /// connections at least one [ALPN] must be set. -519 /// -520 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -521 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { -522 self.alpn_protocols = alpn_protocols; -523 self -524 } -525 -526 // # Methods for common customisation items. -527 -528 /// Sets the relay servers to assist in establishing connectivity. -529 /// -530 /// Relay servers are used to establish initial connection with another iroh endpoint. -531 /// They also perform various functions related to hole punching, see the [crate docs] -532 /// for more details. -533 /// -534 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. -535 /// -536 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one -537 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] -538 /// will result in an error. -539 /// -540 /// [`bind`]: Builder::bind -541 /// [crate docs]: crate -542 /// [number 0]: https://n0.computer -543 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { -544 let transport: Option<_> = relay_mode.into(); -545 match transport { -546 Some(transport) => { -547 if let Some(og) = self -548 .transports -549 .iter_mut() -550 .find(|t| matches!(t, TransportConfig::Relay { .. })) -551 { -552 *og = transport; -553 } else { -554 self.transports.push(transport); -555 } -556 } -557 None => { -558 self.transports -559 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -560 } -561 } -562 self -563 } -564 -565 /// Removes all Address Lookup services from the builder. -566 /// -567 /// If no Address Lookup is set, connecting to an endpoint without providing its -568 /// direct addresses or relay URLs will fail. -569 /// -570 /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details. -571 pub fn clear_address_lookup(mut self) -> Self { -572 self.address_lookup.clear(); -573 self -574 } -575 -576 /// Adds an additional Address Lookup for this endpoint. -577 /// -578 /// Once the endpoint is created the provided [`AddressLookupBuilder::into_address_lookup`] will be -579 /// called. This allows Address Lookup's to finalize their configuration by e.g. using -580 /// the secret key from the endpoint which can be needed to sign published information. -581 /// -582 /// This method can be called multiple times and all the Address Lookup's passed in -583 /// will be combined using an internal instance of the -584 /// [`crate::address_lookup::AddressLookupServices`]. To clear all Address Lookup's, use -585 /// [`Self::clear_address_lookup`]. -586 /// -587 /// If no Address Lookup is set, connecting to an endpoint without providing its -588 /// direct addresses or relay URLs will fail. -589 /// -590 /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details. -591 pub fn address_lookup(mut self, address_lookup: impl AddressLookupBuilder) -> Self { -592 self.address_lookup.push(Box::new(address_lookup)); -593 self -594 } -595 -596 /// Sets the address filter applied to all address data before publishing. -597 /// -598 /// This filter is applied once, at the [`AddressLookupServices`] level, before -599 /// distributing data to any individual address lookup service. This ensures -600 /// consistent filtering regardless of how the services configured. -601 /// -602 /// [`AddressLookupServices`]: crate::address_lookup::AddressLookupServices -603 pub fn addr_filter(mut self, filter: AddrFilter) -> Self { -604 self.addr_filter = Some(filter); -605 self -606 } -607 -608 /// Clears the address filter, allowing all addresses to be published. -609 /// -610 /// This removes any filter previously set via [`Self::addr_filter`], including -611 /// filters set by presets. -612 pub fn clear_addr_filter(mut self) -> Self { -613 self.addr_filter = None; -614 self -615 } -616 -617 /// Sets the initial user-defined data to be published in Address Lookup's for this node. -618 /// -619 /// When using Address Lookup's, this string of [`UserData`] will be published together -620 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, -621 /// they retrieve the [`UserData`] in addition to the addressing info. -622 /// -623 /// Iroh itself does not interpret the user-defined data in any way, it is purely left -624 /// for applications to parse and use. -625 pub fn user_data_for_address_lookup(mut self, user_data: UserData) -> Self { -626 self.address_lookup_user_data = Some(user_data); -627 self -628 } -629 -630 /// Adds an external address on which this endpoint is directly reachable. -631 /// -632 /// This address will be advertised to peers together with any discovered external addresses -633 /// and will be used in NAT traversal and to establish direct connections. -634 /// -635 /// Can be called multiple times. See also [`Endpoint::add_external_addr`] for -636 /// adding addresses at runtime. -637 pub fn external_addr(mut self, addr: SocketAddr) -> Self { -638 self.configured_addrs.insert(addr); -639 self -640 } -641 -642 // # Methods for more specialist customisation. -643 -644 /// Sets a custom [`QuicTransportConfig`] for this endpoint. -645 /// -646 /// The transport config contains parameters governing the QUIC state machine. -647 /// -648 /// If unset, the default config is used. Default values should be suitable for most -649 /// internet applications. Applications protocols which forbid remotely-initiated -650 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to -651 /// zero. -652 /// -653 /// Please be aware that changing some settings may have adverse effects on establishing -654 /// and maintaining direct connections. -655 pub fn transport_config(mut self, transport_config: QuicTransportConfig) -> Self { -656 self.transport_config = transport_config; -657 self -658 } -659 -660 /// Optionally sets a custom DNS resolver to use for this endpoint. -661 /// -662 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if -663 /// [`crate::address_lookup::DnsAddressLookup`] is configured. -664 /// -665 /// By default, a new DNS resolver is created which is configured to use the -666 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] -667 /// here to use a differently configured DNS resolver for this endpoint, or to share -668 /// a [`DnsResolver`] between multiple endpoints. -669 #[cfg(not(wasm_browser))] -670 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -671 self.dns_resolver = Some(dns_resolver); -672 self -673 } -674 -675 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. -676 pub fn proxy_url(mut self, url: Url) -> Self { -677 self.proxy_url.replace(url); -678 self -679 } -680 -681 /// Sets the proxy url from the environment, in this order: -682 /// -683 /// - `HTTP_PROXY` -684 /// - `http_proxy` -685 /// - `HTTPS_PROXY` -686 /// - `https_proxy` -687 pub fn proxy_from_env(mut self) -> Self { -688 self.proxy_url = proxy_url_from_env(); -689 self -690 } -691 -692 /// Sets the trusted CA root certificates for non-iroh TLS connections. -693 /// -694 /// These Certificate Authority roots are used as trust anchors for verifying -695 /// the validity of TLS certificates presented by external services, such as -696 /// iroh relays, pkarr servers, or DNS-over-HTTPS resolvers. -697 /// They don't need to be trusted for the integrity or authenticity of native -698 /// iroh connections, which rely on iroh's own cryptographic authentication mechanisms. -699 pub fn ca_tls_config(mut self, ca_tls_config: CaTlsConfig) -> Self { -700 self.ca_tls_config = Some(ca_tls_config); -701 self -702 } -703 -704 /// Renamed to [`Builder::ca_tls_config`]. -705 #[deprecated(since = "1.0.0", note = "Renamed to `ca_tls_config`")] -706 pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self { -707 self.ca_tls_config(ca_roots_config) -708 } -709 -710 /// Enables saving the TLS pre-master key for connections. -711 /// -712 /// This key should normally remain secret but can be useful to debug networking issues -713 /// by decrypting captured traffic. -714 /// -715 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a -716 /// filename will result in this file being used to log the TLS pre-master keys. -717 pub fn keylog(mut self, keylog: bool) -> Self { -718 self.keylog = keylog; -719 self -720 } -721 -722 /// Set the maximum number of TLS tickets to cache. -723 /// -724 /// Set this to a larger value if you want to do 0rtt connections to a large -725 /// number of clients. -726 /// -727 /// The default is 256, taking about 150 KiB in memory. -728 pub fn max_tls_tickets(mut self, n: usize) -> Self { -729 self.max_tls_tickets = n; -730 self -731 } -732 -733 /// Specify the rustls cryptography to use for all TLS operations. -734 /// -735 /// This includes -736 /// - TLS for encryption and authentication of iroh connections themselves, but also -737 /// - HTTPS connections to relays -738 /// - Pkarr relay publishing HTTPS connections -739 /// - and any other Address Lookup services that decide to use [`Endpoint::tls_config`]. -740 /// -741 /// The two most common crypto providers in use today are `ring` as well as `aws-lc-rs`. -742 /// -743 /// If either the `tls-ring` or `tls-aws-lc-rs` feature is set in iroh, this function doesn't -744 /// need to be called. -745 /// -746 /// If none of these features are set, then calling this function in the builder is mandatory. -747 pub fn crypto_provider(mut self, crypto_provider: Arc<rustls::crypto::CryptoProvider>) -> Self { -748 self.crypto_provider = Some(crypto_provider); -749 self -750 } -751 -752 /// Install hooks onto the endpoint. -753 /// -754 /// Endpoint hooks intercept the connection establishment process of an [`Endpoint`]. -755 /// -756 /// You can install multiple [`EndpointHooks`] by calling this function multiple times. -757 /// Order matters: hooks are invoked in the order they were installed onto the endpoint -758 /// builder. Once a hook returns reject, further processing -759 /// is aborted and other hooks won't be invoked. -760 /// -761 /// See [`EndpointHooks`] for details on the possible interception points in the connection lifecycle. -762 pub fn hooks(mut self, hooks: impl EndpointHooks + 'static) -> Self { -763 self.hooks.push(hooks); -764 self -765 } -766 -767 /// Configures the portmapper service (UPnP, PCP, NAT-PMP). -768 /// -769 /// Defaults to [`PortmapperConfig::Enabled`]. -770 pub fn portmapper_config(mut self, config: PortmapperConfig) -> Self { -771 self.portmapper_config = config; -772 self -773 } -774 -775 /// Adds a custom transport -776 #[cfg(feature = "unstable-custom-transports")] -777 pub fn add_custom_transport(mut self, factory: Arc<dyn CustomTransport>) -> Self { -778 self.transports.push(TransportConfig::Custom(factory)); -779 self -780 } -781 -782 /// Sets a custom [`PathSelector`] for this endpoint. -783 /// -784 /// The path selector decides which path to use among the candidate paths to a -785 /// remote endpoint. By default iroh uses a built-in selector that sorts paths by -786 /// biased RTT (with IPv6 preferred over IPv4 and relay treated as backup) and is -787 /// sticky to avoid flapping. Pass a custom [`PathSelector`] here to override that -788 /// policy — for example, to make a custom transport always win over IP. -789 /// -790 /// Takes an `Arc<dyn PathSelector>` so the same selector instance can be shared -791 /// across multiple endpoints if desired. See `examples/custom-transport.rs` for -792 /// an example implementation. -793 /// -794 /// [`PathSelector`]: socket::remote_map::PathSelector -795 #[cfg(feature = "unstable-custom-transports")] -796 pub fn path_selector(mut self, selector: Arc<dyn PathSelector>) -> Self { -797 self.path_selector = selector; -798 self -799 } -800} -801 -802#[allow(missing_docs)] -803#[stack_error(derive, add_meta)] -804#[non_exhaustive] -805pub enum EndpointError { -806 #[error("Endpoint is closed")] -807 Closed, -808} -809 -810/// Controls an iroh endpoint, establishing connections with other endpoints. -811/// -812/// This is the main API interface to create connections to, and accept connections from -813/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is -814/// used to make the connections reliable. See the [crate docs] for a more detailed -815/// overview of iroh. -816/// -817/// It is recommended to only create a single instance per application. This ensures all -818/// the connections made share the same peer-to-peer connections to other iroh endpoints, -819/// while still remaining independent connections. This will result in more optimal network -820/// behaviour. -821/// -822/// The endpoint is created using the [`Builder`], which can be created using -823/// [`Endpoint::builder`]. -824/// -825/// Once an endpoint exists, new connections are typically created using the -826/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the -827/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to -828/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], -829/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. -830/// -831/// Note that due to the light-weight properties of streams a stream will only be accepted -832/// once the initiating peer has sent some data on it. -833/// -834/// # Usage on Android -835/// -836/// The endpoint's default [`DnsResolver`] reads the system DNS configuration -837/// through JNI, which needs a JVM context published to [`ndk_context`]. Apps -838/// must initialize that context before constructing the endpoint, or the -839/// resolver build panics. See [`DnsResolver`] for the supported -840/// initialization paths. -841/// -842/// [QUIC]: https://quicwg.org -843/// [`DnsResolver`]: crate::dns::DnsResolver -844/// [`ndk_context`]: https://docs.rs/ndk-context -845#[derive(Clone, Debug)] -846pub struct Endpoint { -847 inner: Arc<EndpointInner>, -848} -849 -850#[allow(missing_docs)] -851#[stack_error(derive, add_meta, from_sources)] -852#[non_exhaustive] -853#[allow(private_interfaces)] -854pub enum ConnectWithOptsError { -855 #[error("Connecting to ourself is not supported")] -856 SelfConnect, -857 #[error("No addressing information available")] -858 NoAddress { source: AddressLookupFailed }, -859 #[error("Unable to connect to remote")] -860 Noq { -861 #[error(std_err)] -862 source: QuicConnectError, -863 }, -864 #[error("Internal consistency error")] -865 InternalConsistencyError { -866 /// Private source type, cannot be created publicly. -867 source: RemoteStateActorStoppedError, -868 }, -869 #[error("Connection was rejected locally")] -870 LocallyRejected, -871 #[error("Endpoint is closed")] -872 EndpointClosed, -873} -874 -875#[allow(missing_docs)] -876#[stack_error(derive, add_meta, from_sources)] -877#[non_exhaustive] -878pub enum ConnectError { -879 #[error(transparent)] -880 Connect { source: ConnectWithOptsError }, -881 #[error(transparent)] -882 Connecting { source: ConnectingError }, -883 #[error(transparent)] -884 Connection { -885 #[error(std_err)] -886 source: ConnectionError, -887 }, -888} -889 -890impl Endpoint { -891 // The ordering of public methods is reflected directly in the documentation. This is -892 // roughly ordered by what is most commonly needed by users, but grouped in similar -893 // items. -894 -895 // # Methods relating to construction. -896 -897 /// Returns the builder for an [`Endpoint`], with the given [`Preset`] configuration. -898 pub fn builder(preset: impl Preset) -> Builder { -899 Builder::new(preset) -900 } -901 -902 /// Constructs a default [`Endpoint`] using the provided [`Preset`] and binds it immediately. -903 pub async fn bind(preset: impl Preset) -> Result<Self, BindError> { -904 Self::builder(preset).bind().await -905 } -906 -907 /// Sets the list of accepted ALPN protocols. -908 /// -909 /// This will only affect new incoming connections. -910 /// Note that this *overrides* the current list of ALPNs. -911 /// -912 /// If the endpoint is closed, this method will log a warning and ignore -913 /// the request to set new ALPNs. -914 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { -915 if self.is_closed() { -916 warn!("Attempting to set ALPNs for a closed endpoint. Ignoring."); -917 return; -918 } -919 let server_config = self.inner.static_config.create_server_config(alpns); -920 self.inner -921 .noq_endpoint() -922 .set_server_config(Some(server_config)); -923 } -924 -925 /// Adds the provided configuration to the [`RelayMap`]. -926 /// -927 /// Replacing and returning any existing configuration for [`RelayUrl`]. -928 /// -929 /// Will also return `None` if the endpoint is closed. -930 pub async fn insert_relay( -931 &self, -932 relay: RelayUrl, -933 config: Arc<RelayConfig>, -934 ) -> Option<Arc<RelayConfig>> { -935 if self.is_closed() { -936 return None; -937 } -938 self.inner.insert_relay(relay, config).await -939 } -940 -941 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. -942 /// -943 /// Returns any existing configuration if it exists. Will also return `None` if the endpoint is closed. -944 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { -945 if self.is_closed() { -946 return None; -947 } -948 self.inner.remove_relay(relay).await -949 } -950 -951 /// Adds an external address on which this endpoint is directly reachable. -952 /// -953 /// This address will be advertised to peers together with any discovered external addresses -954 /// and will be used in NAT traversal and to establish direct connections. -955 /// -956 /// See also [`Builder::external_addr`] for setting addresses at build time. -957 pub async fn add_external_addr(&self, addr: SocketAddr) { -958 if self.is_closed() { -959 warn!("Attempting to add external addr for a closed endpoint. Ignoring."); -960 return; -961 } -962 self.inner.add_external_addr(addr).await; -963 } -964 -965 /// Removes a configured external address. Returns `true` if it was present. -966 pub async fn remove_external_addr(&self, addr: &SocketAddr) -> bool { -967 if self.is_closed() { -968 return false; -969 } -970 self.inner.remove_external_addr(addr).await -971 } -972 -973 // # Methods for establishing connectivity. -974 -975 /// Connects to a remote [`Endpoint`]. -976 /// -977 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an -978 /// [`EndpointAddr`] or an [`EndpointId`]. -979 /// -980 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] -981 /// and direct addresses. If direct addresses are provided, they will be used to try and -982 /// establish a direct connection without involving a relay server. -983 /// -984 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it -985 /// may still be possible a connection can be established. This depends on which, if any, -986 /// [`crate::address_lookup::AddressLookup`]s were configured using [`Builder::address_lookup`]. The Address Lookup -987 /// service will also be used if the remote endpoint is not reachable on the provided direct -988 /// addresses and there is no [`RelayUrl`]. -989 /// -990 /// If addresses or relay servers are neither provided nor can be discovered, the -991 /// connection attempt will fail with an error. -992 /// -993 /// The `alpn`, or application-level protocol identifier, is also required. The remote -994 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with -995 /// an error. -996 /// -997 /// [`RelayUrl`]: crate::RelayUrl -998 pub async fn connect( -999 &self, -1000 endpoint_addr: impl Into<EndpointAddr>, -1001 alpn: &[u8], -1002 ) -> Result<Connection, ConnectError> { -1003 let endpoint_addr = endpoint_addr.into(); -1004 let remote = endpoint_addr.id; -1005 let connecting = self -1006 .connect_with_opts(endpoint_addr, alpn, Default::default()) -1007 .await?; -1008 let conn = connecting.await?; -1009 -1010 debug!( -1011 me = %self.id().fmt_short(), -1012 remote = %remote.fmt_short(), -1013 alpn = %String::from_utf8_lossy(alpn), -1014 "Connection established." -1015 ); -1016 Ok(conn) -1017 } -1018 -1019 /// Starts a connection attempt with a remote [`Endpoint`]. -1020 /// -1021 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more -1022 /// advanced connection setup with more customization in two aspects: -1023 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into -1024 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via -1025 /// [`Connecting::into_0rtt`]. -1026 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess -1027 /// security concerns. -1028 /// 2. The [`QuicTransportConfig`] for the connection can be modified via the provided -1029 /// [`ConnectOptions`]. -1030 /// **Note:** Please be aware that changing transport config settings may have adverse effects on -1031 /// establishing and maintaining direct connections. Carefully test settings you use and -1032 /// consider this currently as still rather experimental. -1033 #[instrument(name = "connect", skip_all, fields( -1034 me = %self.id().fmt_short(), -1035 remote = tracing::field::Empty, -1036 alpn = %String::from_utf8_lossy(alpn).to_string(), -1037 ))] -1038 pub async fn connect_with_opts( -1039 &self, -1040 endpoint_addr: impl Into<EndpointAddr>, -1041 alpn: &[u8], -1042 options: ConnectOptions, -1043 ) -> Result<Connecting, ConnectWithOptsError> { -1044 if self.is_closed() { -1045 return Err(e!(ConnectWithOptsError::EndpointClosed)); -1046 } -1047 -1048 let endpoint_addr: EndpointAddr = endpoint_addr.into(); -1049 let endpoint_id = endpoint_addr.id; -1050 -1051 Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short())); -1052 -1053 if let BeforeConnectOutcome::Reject = -1054 self.inner.hooks.before_connect(&endpoint_addr, alpn).await -1055 { -1056 return Err(e!(ConnectWithOptsError::LocallyRejected)); -1057 } -1058 -1059 // Connecting to ourselves is not supported. -1060 ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect); -1061 -1062 event!( -1063 target: "iroh::_events::conn::connecting", -1064 tracing::Level::DEBUG, -1065 remote_id = %endpoint_id.fmt_short(), -1066 alpn = %String::from_utf8_lossy(alpn), -1067 ); -1068 -1069 debug!( -1070 relay_url = ?endpoint_addr.relay_urls().next().cloned(), -1071 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(), -1072 "connecting", -1073 ); -1074 -1075 let mapped_addr = self.inner.resolve_remote(endpoint_addr).await??; -1076 -1077 let transport_config = options -1078 .transport_config -1079 .map(|cfg| cfg.to_inner_arc()) -1080 .unwrap_or(self.inner.static_config.transport_config.to_inner_arc()); -1081 -1082 // Start connecting via noq. This will time out after 10 seconds if no reachable -1083 // address is available. -1084 -1085 let mut alpn_protocols = vec![alpn.to_vec()]; -1086 alpn_protocols.extend(options.additional_alpns); -1087 let client_config = self -1088 .inner -1089 .static_config -1090 .create_client_config(alpn_protocols, transport_config.clone()); -1091 -1092 let dest_addr = mapped_addr.private_socket_addr(); -1093 let server_name = &tls::name::encode(endpoint_id); -1094 let connect = -1095 self.inner -1096 .noq_endpoint() -1097 .connect_with(client_config, dest_addr, server_name)?; -1098 -1099 Ok(Connecting::new(connect, self.clone(), endpoint_id)) -1100 } -1101 -1102 /// Accepts an incoming connection on the endpoint. -1103 /// -1104 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. -1105 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting -1106 /// the connection using [`Connecting::alpn`]. -1107 /// -1108 /// The returned future will yield `None` if the endpoint is closed by calling -1109 /// [`Endpoint::close`]. -1110 pub fn accept(&self) -> Accept<'_> { -1111 Accept { -1112 inner: self.inner.noq_endpoint().accept(), -1113 ep: self.clone(), -1114 } -1115 } -1116 -1117 // # Getter methods for properties of this Endpoint itself. -1118 -1119 /// Returns the secret_key of this endpoint. -1120 pub fn secret_key(&self) -> &SecretKey { -1121 &self.inner.static_config.tls_config.secret_key -1122 } -1123 -1124 /// Returns the endpoint id of this endpoint. -1125 /// -1126 /// This ID is the unique addressing information of this endpoint and other peers must know -1127 /// it to be able to connect to this endpoint. -1128 pub fn id(&self) -> EndpointId { -1129 self.inner.static_config.tls_config.secret_key.public() -1130 } -1131 -1132 /// Returns the current [`EndpointAddr`]. -1133 /// As long as the endpoint was able to bind to a network interface, some -1134 /// local addresses will be available. -1135 /// -1136 /// The state of other fields depends on the state of networking and connectivity. -1137 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered -1138 /// "online" (has contacted a relay server) before calling this method, if you want -1139 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint -1140 /// to be dialable by a remote endpoint over the internet. -1141 /// -1142 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` -1143 /// changes. -1144 pub fn addr(&self) -> EndpointAddr { -1145 self.watch_addr().get() -1146 } -1147 -1148 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -1149 /// -1150 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. -1151 /// -1152 /// ```no_run -1153 /// # #[cfg(with_crypto_provider)] -1154 /// # { -1155 /// # async fn wrapper() -> n0_error::Result<()> { -1156 /// use iroh::{Endpoint, Watcher, endpoint::presets}; -1157 /// -1158 /// let endpoint = Endpoint::builder(presets::N0) -1159 /// .alpns(vec![b"my-alpn".to_vec()]) -1160 /// .bind() -1161 /// .await?; -1162 /// let endpoint_addr = endpoint.watch_addr().get(); -1163 /// # let _ = endpoint_addr; -1164 /// # Ok(()) -1165 /// # } +239 token_store: Arc::new(noq::TokenMemoryCache::default()), +240 }; +241 let server_config = static_config.create_server_config(self.alpn_protocols); +242 +243 #[cfg(not(wasm_browser))] +244 let dns_resolver = self.dns_resolver.unwrap_or_default(); +245 +246 let metrics = EndpointMetrics::default(); +247 +248 let tls_config = self +249 .ca_tls_config +250 .unwrap_or_default() +251 .client_config(crypto_provider) +252 .map_err(|err| e!(BindError::InvalidCaRootConfig, err))?; +253 +254 let sock_opts = socket::Options { +255 transports: self.transports, +256 secret_key, +257 address_lookup_user_data: self.address_lookup_user_data, +258 proxy_url: self.proxy_url, +259 #[cfg(not(wasm_browser))] +260 dns_resolver, +261 server_config, +262 tls_config, +263 metrics, +264 hooks: self.hooks, +265 path_selector: self.path_selector, +266 portmapper_config: self.portmapper_config, +267 static_config, +268 configured_addrs: self.configured_addrs, +269 }; +270 +271 let inner = socket::EndpointInner::bind(sock_opts) +272 .instrument(Span::current()) +273 .await?; +274 debug!( +275 id = %inner.static_config.tls_config.secret_key.public(), +276 iroh_version = %env!("CARGO_PKG_VERSION"), +277 "iroh endpoint bound" +278 ); +279 +280 let ep = Endpoint { +281 inner: Arc::new(inner), +282 }; +283 +284 // Add Address Lookup mechanisms +285 let address_lookup = ep.address_lookup().expect("just created the endpoint"); +286 if let Some(filter) = self.addr_filter { +287 address_lookup.set_addr_filter(filter); +288 } +289 for create_service in self.address_lookup { +290 let service = create_service.into_address_lookup(&ep)?; +291 address_lookup.add_boxed(service); +292 } +293 +294 Ok(ep) +295 } +296 +297 // # The very common methods everyone basically needs. +298 +299 /// Binds an IP socket at the provided socket address. +300 /// +301 /// This is an advanced API to tightly control the sockets used by the endpoint. Most +302 /// uses do not need to explicitly bind sockets. +303 /// +304 /// # Warning +305 /// +306 /// - The builder always comes pre-configured with an IPv4 socket to be bound on the +307 /// *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY` +308 /// special bind address and results in a socket listening on *all* interfaces +309 /// available. +310 /// +311 /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound +312 /// on the *unspecified* address: `[::]`. This bind is allowed to fail however. +313 /// +314 /// - Adding a bind address removes the pre-configured unspecified bind address for this +315 /// address family. Use [`Self::bind_addr_with_opts`] to bind additional addresses without +316 /// replacing the default bind address. +317 /// +318 /// - This should be called at most once for each address family: once for IPv4 and/or +319 /// once for IPv6. Calling it multiple times for the same address family will result +320 /// in undefined routing behaviour. To bind multiple sockets of the same address +321 /// family, use [`Self::bind_addr_with_opts`]. +322 /// +323 /// # Description +324 /// +325 /// Requests a socket to be bound on a specific address, with an implied netmask of +326 /// `/0`. This allows restricting binding to only one network interface for a given +327 /// address family. +328 /// +329 /// If the port specified is already in use, binding the endpoint will fail. Using +330 /// port `0` in the socket address assigns a random free port. +331 /// +332 /// # Example +333 /// +334 /// ```no_run +335 /// # #[cfg(with_crypto_provider)] +336 /// # { +337 /// # #[tokio::main] +338 /// # async fn main() -> n0_error::Result<()> { +339 /// # use iroh::{Endpoint, endpoint::presets}; +340 /// let endpoint = Endpoint::builder(presets::N0) +341 /// .clear_ip_transports() +342 /// .bind_addr("127.0.0.1:0")? +343 /// .bind_addr("[::1]:0")? +344 /// .bind() +345 /// .await?; +346 /// # Ok(()) } +347 /// # } +348 /// ``` +349 #[cfg(not(wasm_browser))] +350 pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr> +351 where +352 A: ToSocketAddr, +353 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, +354 { +355 self.bind_addr_with_opts(addr, BindOpts::default()) +356 } +357 +358 /// Binds an IP socket at the provided socket address. +359 /// +360 /// This is an advanced API to tightly control the sockets used by the endpoint. Most +361 /// uses do not need to explicitly bind sockets. +362 /// +363 /// # Warning +364 /// +365 /// - The builder always comes pre-configured with an IPv4 socket to be bound on the +366 /// *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY` +367 /// special bind address and results in a socket listening on *all* interfaces +368 /// available. +369 /// +370 /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound +371 /// on the *unspecified* address: `[::]`. This bind is allowed to fail however. +372 /// +373 /// # Description +374 /// +375 /// Requests a socket to be bound on a specific address. This allows restricting binding +376 /// to only one network interface for a given address family. +377 /// +378 /// [`BindOpts::set_prefix_len`] **should** be used to configure the netmask of the +379 /// network interface. This allows outgoing datagrams that start a new network flow to +380 /// be sent over the socket which is attached to the subnet of the destination +381 /// address. If multiple sockets are bound the standard routing-table semantics are +382 /// used: the socket attached to the subnet with the longest prefix matching the +383 /// destination is used. Practically this means the smallest subnets are at the top of +384 /// the routing table, and the first subnet containing the destination address is +385 /// chosen. +386 /// +387 /// If no socket is bound to a subnet that contains the destination address, the notion +388 /// of "default route" is used. At most one socket per address family may be marked as +389 /// the default route using [`BindOpts::set_is_default_route`], and this will be used +390 /// for destinations not contained by the subnets of the bound sockets. This network is +391 /// expected to have a default gateway configured. A socket with a prefix length of `/0` +392 /// will be set as a "default route" implicitly, unless [`BindOpts::set_is_default_route`] +393 /// is set to `false` explicitly. +394 /// +395 /// Be aware that using a subnet with a prefix length of `/0` will always contain all +396 /// destination addresses. It is valid to configure this, but no more than one such +397 /// socket should be bound or the routing will be non-deterministic. +398 /// +399 /// To use a subnet with a non-zero prefix length as the default route in addition to +400 /// being routed when its prefix matches, use [`BindOpts::set_is_default_route]. +401 /// Subnets with a prefix length of zero are always marked as default routes. +402 /// +403 /// Finally note that most outgoing datagrams are part of an existing network flow. That +404 /// is, they are in response to an incoming datagram. In this case the outgoing datagram +405 /// will be sent over the same socket as the incoming datagram was received on, and the +406 /// routing with the prefix length and default route as described above does not apply. +407 /// +408 /// Using port `0` in the socket address assigns a random free port. +409 /// +410 /// If the port specified is already in use, binding the endpoint will fail, unless +411 /// [`BindOpts::set_is_required`] is set to `false` +412 /// +413 /// # Example +414 /// ```no_run +415 /// # #[cfg(with_crypto_provider)] +416 /// # { +417 /// # #[tokio::main] +418 /// # async fn main() -> n0_error::Result<()> { +419 /// # use iroh::{Endpoint, endpoint::{BindOpts, presets}}; +420 /// let endpoint = Endpoint::builder(presets::N0) +421 /// .clear_ip_transports() +422 /// .bind_addr_with_opts("127.0.0.1:0", BindOpts::default().set_prefix_len(24))? +423 /// .bind_addr_with_opts("[::1]:0", BindOpts::default().set_prefix_len(48))? +424 /// .bind() +425 /// .await?; +426 /// # Ok(()) } +427 /// # } +428 /// ``` +429 #[cfg(not(wasm_browser))] +430 pub fn bind_addr_with_opts<A>( +431 mut self, +432 addr: A, +433 opts: BindOpts, +434 ) -> Result<Self, InvalidSocketAddr> +435 where +436 A: ToSocketAddr, +437 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, +438 { +439 let addr = addr.to_socket_addr().map_err(Into::into)?; +440 match addr { +441 SocketAddr::V4(addr) => { +442 if self +443 .transports +444 .iter() +445 .any(|t| t.is_ipv4_default() && t.is_user_defined()) +446 { +447 bail!(InvalidSocketAddr::DuplicateDefaultAddr); +448 } +449 +450 let ip_net = Ipv4Net::new(*addr.ip(), opts.prefix_len()) +451 .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?; +452 self.transports.push(TransportConfig::Ip { +453 config: IpConfig::V4 { +454 ip_net, +455 port: addr.port(), +456 is_required: opts.is_required(), +457 is_default: opts.is_default_route(), +458 }, +459 is_user_defined: true, +460 }); +461 } +462 SocketAddr::V6(addr) => { +463 if self +464 .transports +465 .iter() +466 .any(|t| t.is_ipv6_default() && t.is_user_defined()) +467 { +468 bail!(InvalidSocketAddr::DuplicateDefaultAddr); +469 } +470 +471 let ip_net = Ipv6Net::new(*addr.ip(), opts.prefix_len()) +472 .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?; +473 self.transports.push(TransportConfig::Ip { +474 config: IpConfig::V6 { +475 ip_net, +476 scope_id: addr.scope_id(), +477 port: addr.port(), +478 is_required: opts.is_required(), +479 is_default: opts.is_default_route(), +480 }, +481 is_user_defined: true, +482 }); +483 } +484 } +485 Ok(self) +486 } +487 +488 /// Removes all IP based transports. +489 #[cfg(not(wasm_browser))] +490 pub fn clear_ip_transports(mut self) -> Self { +491 self.transports +492 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); +493 self +494 } +495 +496 /// Removes all relay based transports. +497 pub fn clear_relay_transports(mut self) -> Self { +498 self.transports +499 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +500 self +501 } +502 +503 /// Sets a secret key to authenticate with other peers. +504 /// +505 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus +506 /// also its [`EndpointId`] +507 /// +508 /// If not set, a new secret key will be generated. +509 /// +510 /// [`PublicKey`]: iroh_base::PublicKey +511 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { +512 self.secret_key = Some(secret_key); +513 self +514 } +515 +516 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. +517 /// +518 /// Not setting this will still allow creating connections, but to accept incoming +519 /// connections at least one [ALPN] must be set. +520 /// +521 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +522 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { +523 self.alpn_protocols = alpn_protocols; +524 self +525 } +526 +527 // # Methods for common customisation items. +528 +529 /// Sets the relay servers to assist in establishing connectivity. +530 /// +531 /// Relay servers are used to establish initial connection with another iroh endpoint. +532 /// They also perform various functions related to hole punching, see the [crate docs] +533 /// for more details. +534 /// +535 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. +536 /// +537 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one +538 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] +539 /// will result in an error. +540 /// +541 /// [`bind`]: Builder::bind +542 /// [crate docs]: crate +543 /// [number 0]: https://n0.computer +544 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { +545 let transport: Option<_> = relay_mode.into(); +546 match transport { +547 Some(transport) => { +548 if let Some(og) = self +549 .transports +550 .iter_mut() +551 .find(|t| matches!(t, TransportConfig::Relay { .. })) +552 { +553 *og = transport; +554 } else { +555 self.transports.push(transport); +556 } +557 } +558 None => { +559 self.transports +560 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +561 } +562 } +563 self +564 } +565 +566 /// Removes all Address Lookup services from the builder. +567 /// +568 /// If no Address Lookup is set, connecting to an endpoint without providing its +569 /// direct addresses or relay URLs will fail. +570 /// +571 /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details. +572 pub fn clear_address_lookup(mut self) -> Self { +573 self.address_lookup.clear(); +574 self +575 } +576 +577 /// Adds an additional Address Lookup for this endpoint. +578 /// +579 /// Once the endpoint is created the provided [`AddressLookupBuilder::into_address_lookup`] will be +580 /// called. This allows Address Lookup's to finalize their configuration by e.g. using +581 /// the secret key from the endpoint which can be needed to sign published information. +582 /// +583 /// This method can be called multiple times and all the Address Lookup's passed in +584 /// will be combined using an internal instance of the +585 /// [`crate::address_lookup::AddressLookupServices`]. To clear all Address Lookup's, use +586 /// [`Self::clear_address_lookup`]. +587 /// +588 /// If no Address Lookup is set, connecting to an endpoint without providing its +589 /// direct addresses or relay URLs will fail. +590 /// +591 /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details. +592 pub fn address_lookup(mut self, address_lookup: impl AddressLookupBuilder) -> Self { +593 self.address_lookup.push(Box::new(address_lookup)); +594 self +595 } +596 +597 /// Sets the address filter applied to all address data before publishing. +598 /// +599 /// This filter is applied once, at the [`AddressLookupServices`] level, before +600 /// distributing data to any individual address lookup service. This ensures +601 /// consistent filtering regardless of how the services configured. +602 /// +603 /// [`AddressLookupServices`]: crate::address_lookup::AddressLookupServices +604 pub fn addr_filter(mut self, filter: AddrFilter) -> Self { +605 self.addr_filter = Some(filter); +606 self +607 } +608 +609 /// Clears the address filter, allowing all addresses to be published. +610 /// +611 /// This removes any filter previously set via [`Self::addr_filter`], including +612 /// filters set by presets. +613 pub fn clear_addr_filter(mut self) -> Self { +614 self.addr_filter = None; +615 self +616 } +617 +618 /// Sets the initial user-defined data to be published in Address Lookup's for this node. +619 /// +620 /// When using Address Lookup's, this string of [`UserData`] will be published together +621 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, +622 /// they retrieve the [`UserData`] in addition to the addressing info. +623 /// +624 /// Iroh itself does not interpret the user-defined data in any way, it is purely left +625 /// for applications to parse and use. +626 pub fn user_data_for_address_lookup(mut self, user_data: UserData) -> Self { +627 self.address_lookup_user_data = Some(user_data); +628 self +629 } +630 +631 /// Adds an external address on which this endpoint is directly reachable. +632 /// +633 /// This address will be advertised to peers together with any discovered external addresses +634 /// and will be used in NAT traversal and to establish direct connections. +635 /// +636 /// Can be called multiple times. See also [`Endpoint::add_external_addr`] for +637 /// adding addresses at runtime. +638 pub fn external_addr(mut self, addr: SocketAddr) -> Self { +639 self.configured_addrs.insert(addr); +640 self +641 } +642 +643 // # Methods for more specialist customisation. +644 +645 /// Sets a custom [`QuicTransportConfig`] for this endpoint. +646 /// +647 /// The transport config contains parameters governing the QUIC state machine. +648 /// +649 /// If unset, the default config is used. Default values should be suitable for most +650 /// internet applications. Applications protocols which forbid remotely-initiated +651 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to +652 /// zero. +653 /// +654 /// Please be aware that changing some settings may have adverse effects on establishing +655 /// and maintaining direct connections. +656 pub fn transport_config(mut self, transport_config: QuicTransportConfig) -> Self { +657 self.transport_config = transport_config; +658 self +659 } +660 +661 /// Optionally sets a custom DNS resolver to use for this endpoint. +662 /// +663 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if +664 /// [`crate::address_lookup::DnsAddressLookup`] is configured. +665 /// +666 /// By default, a new DNS resolver is created which is configured to use the +667 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] +668 /// here to use a differently configured DNS resolver for this endpoint, or to share +669 /// a [`DnsResolver`] between multiple endpoints. +670 #[cfg(not(wasm_browser))] +671 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +672 self.dns_resolver = Some(dns_resolver); +673 self +674 } +675 +676 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. +677 pub fn proxy_url(mut self, url: Url) -> Self { +678 self.proxy_url.replace(url); +679 self +680 } +681 +682 /// Sets the proxy url from the environment, in this order: +683 /// +684 /// - `HTTP_PROXY` +685 /// - `http_proxy` +686 /// - `HTTPS_PROXY` +687 /// - `https_proxy` +688 pub fn proxy_from_env(mut self) -> Self { +689 self.proxy_url = proxy_url_from_env(); +690 self +691 } +692 +693 /// Sets the trusted CA root certificates for non-iroh TLS connections. +694 /// +695 /// These Certificate Authority roots are used as trust anchors for verifying +696 /// the validity of TLS certificates presented by external services, such as +697 /// iroh relays, pkarr servers, or DNS-over-HTTPS resolvers. +698 /// They don't need to be trusted for the integrity or authenticity of native +699 /// iroh connections, which rely on iroh's own cryptographic authentication mechanisms. +700 pub fn ca_tls_config(mut self, ca_tls_config: CaTlsConfig) -> Self { +701 self.ca_tls_config = Some(ca_tls_config); +702 self +703 } +704 +705 /// Renamed to [`Builder::ca_tls_config`]. +706 #[deprecated(since = "1.0.0", note = "Renamed to `ca_tls_config`")] +707 pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self { +708 self.ca_tls_config(ca_roots_config) +709 } +710 +711 /// Enables saving the TLS pre-master key for connections. +712 /// +713 /// This key should normally remain secret but can be useful to debug networking issues +714 /// by decrypting captured traffic. +715 /// +716 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a +717 /// filename will result in this file being used to log the TLS pre-master keys. +718 pub fn keylog(mut self, keylog: bool) -> Self { +719 self.keylog = keylog; +720 self +721 } +722 +723 /// Set the maximum number of TLS tickets to cache. +724 /// +725 /// Set this to a larger value if you want to do 0rtt connections to a large +726 /// number of clients. +727 /// +728 /// The default is 256, taking about 150 KiB in memory. +729 pub fn max_tls_tickets(mut self, n: usize) -> Self { +730 self.max_tls_tickets = n; +731 self +732 } +733 +734 /// Specify the rustls cryptography to use for all TLS operations. +735 /// +736 /// This includes +737 /// - TLS for encryption and authentication of iroh connections themselves, but also +738 /// - HTTPS connections to relays +739 /// - Pkarr relay publishing HTTPS connections +740 /// - and any other Address Lookup services that decide to use [`Endpoint::tls_config`]. +741 /// +742 /// The two most common crypto providers in use today are `ring` as well as `aws-lc-rs`. +743 /// +744 /// If either the `tls-ring` or `tls-aws-lc-rs` feature is set in iroh, this function doesn't +745 /// need to be called. +746 /// +747 /// If none of these features are set, then calling this function in the builder is mandatory. +748 pub fn crypto_provider(mut self, crypto_provider: Arc<rustls::crypto::CryptoProvider>) -> Self { +749 self.crypto_provider = Some(crypto_provider); +750 self +751 } +752 +753 /// Install hooks onto the endpoint. +754 /// +755 /// Endpoint hooks intercept the connection establishment process of an [`Endpoint`]. +756 /// +757 /// You can install multiple [`EndpointHooks`] by calling this function multiple times. +758 /// Order matters: hooks are invoked in the order they were installed onto the endpoint +759 /// builder. Once a hook returns reject, further processing +760 /// is aborted and other hooks won't be invoked. +761 /// +762 /// See [`EndpointHooks`] for details on the possible interception points in the connection lifecycle. +763 pub fn hooks(mut self, hooks: impl EndpointHooks + 'static) -> Self { +764 self.hooks.push(hooks); +765 self +766 } +767 +768 /// Configures the portmapper service (UPnP, PCP, NAT-PMP). +769 /// +770 /// Defaults to [`PortmapperConfig::Enabled`]. +771 pub fn portmapper_config(mut self, config: PortmapperConfig) -> Self { +772 self.portmapper_config = config; +773 self +774 } +775 +776 /// Adds a custom transport +777 #[cfg(feature = "unstable-custom-transports")] +778 pub fn add_custom_transport(mut self, factory: Arc<dyn CustomTransport>) -> Self { +779 self.transports.push(TransportConfig::Custom(factory)); +780 self +781 } +782 +783 /// Sets a custom [`PathSelector`] for this endpoint. +784 /// +785 /// The path selector decides which path to use among the candidate paths to a +786 /// remote endpoint. By default iroh uses a built-in selector that sorts paths by +787 /// biased RTT (with IPv6 preferred over IPv4 and relay treated as backup) and is +788 /// sticky to avoid flapping. Pass a custom [`PathSelector`] here to override that +789 /// policy — for example, to make a custom transport always win over IP. +790 /// +791 /// Takes an `Arc<dyn PathSelector>` so the same selector instance can be shared +792 /// across multiple endpoints if desired. See `examples/custom-transport.rs` for +793 /// an example implementation. +794 /// +795 /// [`PathSelector`]: socket::remote_map::PathSelector +796 #[cfg(feature = "unstable-custom-transports")] +797 pub fn path_selector(mut self, selector: Arc<dyn PathSelector>) -> Self { +798 self.path_selector = selector; +799 self +800 } +801} +802 +803#[allow(missing_docs)] +804#[stack_error(derive, add_meta)] +805#[non_exhaustive] +806pub enum EndpointError { +807 #[error("Endpoint is closed")] +808 Closed, +809} +810 +811/// Controls an iroh endpoint, establishing connections with other endpoints. +812/// +813/// This is the main API interface to create connections to, and accept connections from +814/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is +815/// used to make the connections reliable. See the [crate docs] for a more detailed +816/// overview of iroh. +817/// +818/// It is recommended to only create a single instance per application. This ensures all +819/// the connections made share the same peer-to-peer connections to other iroh endpoints, +820/// while still remaining independent connections. This will result in more optimal network +821/// behaviour. +822/// +823/// The endpoint is created using the [`Builder`], which can be created using +824/// [`Endpoint::builder`]. +825/// +826/// Once an endpoint exists, new connections are typically created using the +827/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the +828/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to +829/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], +830/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. +831/// +832/// Note that due to the light-weight properties of streams a stream will only be accepted +833/// once the initiating peer has sent some data on it. +834/// +835/// # Usage on Android +836/// +837/// The endpoint's default [`DnsResolver`] reads the system DNS configuration +838/// through JNI, which needs a JVM context published to [`ndk_context`]. Apps +839/// must initialize that context before constructing the endpoint, or the +840/// resolver build panics. See [`DnsResolver`] for the supported +841/// initialization paths. +842/// +843/// [QUIC]: https://quicwg.org +844/// [`DnsResolver`]: crate::dns::DnsResolver +845/// [`ndk_context`]: https://docs.rs/ndk-context +846#[derive(Clone, Debug)] +847pub struct Endpoint { +848 inner: Arc<EndpointInner>, +849} +850 +851#[allow(missing_docs)] +852#[stack_error(derive, add_meta, from_sources)] +853#[non_exhaustive] +854#[allow(private_interfaces)] +855pub enum ConnectWithOptsError { +856 #[error("Connecting to ourself is not supported")] +857 SelfConnect, +858 #[error("No addressing information available")] +859 NoAddress { source: AddressLookupFailed }, +860 #[error("Unable to connect to remote")] +861 Noq { +862 #[error(std_err)] +863 source: QuicConnectError, +864 }, +865 #[error("Internal consistency error")] +866 InternalConsistencyError { +867 /// Private source type, cannot be created publicly. +868 source: RemoteStateActorStoppedError, +869 }, +870 #[error("Connection was rejected locally")] +871 LocallyRejected, +872 #[error("Endpoint is closed")] +873 EndpointClosed, +874} +875 +876#[allow(missing_docs)] +877#[stack_error(derive, add_meta, from_sources)] +878#[non_exhaustive] +879pub enum ConnectError { +880 #[error(transparent)] +881 Connect { source: ConnectWithOptsError }, +882 #[error(transparent)] +883 Connecting { source: ConnectingError }, +884 #[error(transparent)] +885 Connection { +886 #[error(std_err)] +887 source: ConnectionError, +888 }, +889} +890 +891impl Endpoint { +892 // The ordering of public methods is reflected directly in the documentation. This is +893 // roughly ordered by what is most commonly needed by users, but grouped in similar +894 // items. +895 +896 // # Methods relating to construction. +897 +898 /// Returns the builder for an [`Endpoint`], with the given [`Preset`] configuration. +899 pub fn builder(preset: impl Preset) -> Builder { +900 Builder::new(preset) +901 } +902 +903 /// Constructs a default [`Endpoint`] using the provided [`Preset`] and binds it immediately. +904 pub async fn bind(preset: impl Preset) -> Result<Self, BindError> { +905 Self::builder(preset).bind().await +906 } +907 +908 /// Sets the list of accepted ALPN protocols. +909 /// +910 /// This will only affect new incoming connections. +911 /// Note that this *overrides* the current list of ALPNs. +912 /// +913 /// If the endpoint is closed, this method will log a warning and ignore +914 /// the request to set new ALPNs. +915 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { +916 if self.is_closed() { +917 warn!("Attempting to set ALPNs for a closed endpoint. Ignoring."); +918 return; +919 } +920 let server_config = self.inner.static_config.create_server_config(alpns); +921 self.inner +922 .noq_endpoint() +923 .set_server_config(Some(server_config)); +924 } +925 +926 /// Adds the provided configuration to the [`RelayMap`]. +927 /// +928 /// Replacing and returning any existing configuration for [`RelayUrl`]. +929 /// +930 /// Will also return `None` if the endpoint is closed. +931 pub async fn insert_relay( +932 &self, +933 relay: RelayUrl, +934 config: Arc<RelayConfig>, +935 ) -> Option<Arc<RelayConfig>> { +936 if self.is_closed() { +937 return None; +938 } +939 self.inner.insert_relay(relay, config).await +940 } +941 +942 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. +943 /// +944 /// Returns any existing configuration if it exists. Will also return `None` if the endpoint is closed. +945 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { +946 if self.is_closed() { +947 return None; +948 } +949 self.inner.remove_relay(relay).await +950 } +951 +952 /// Adds an external address on which this endpoint is directly reachable. +953 /// +954 /// This address will be advertised to peers together with any discovered external addresses +955 /// and will be used in NAT traversal and to establish direct connections. +956 /// +957 /// See also [`Builder::external_addr`] for setting addresses at build time. +958 pub async fn add_external_addr(&self, addr: SocketAddr) { +959 if self.is_closed() { +960 warn!("Attempting to add external addr for a closed endpoint. Ignoring."); +961 return; +962 } +963 self.inner.add_external_addr(addr).await; +964 } +965 +966 /// Removes a configured external address. Returns `true` if it was present. +967 pub async fn remove_external_addr(&self, addr: &SocketAddr) -> bool { +968 if self.is_closed() { +969 return false; +970 } +971 self.inner.remove_external_addr(addr).await +972 } +973 +974 // # Methods for establishing connectivity. +975 +976 /// Connects to a remote [`Endpoint`]. +977 /// +978 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an +979 /// [`EndpointAddr`] or an [`EndpointId`]. +980 /// +981 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] +982 /// and direct addresses. If direct addresses are provided, they will be used to try and +983 /// establish a direct connection without involving a relay server. +984 /// +985 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it +986 /// may still be possible a connection can be established. This depends on which, if any, +987 /// [`crate::address_lookup::AddressLookup`]s were configured using [`Builder::address_lookup`]. The Address Lookup +988 /// service will also be used if the remote endpoint is not reachable on the provided direct +989 /// addresses and there is no [`RelayUrl`]. +990 /// +991 /// If addresses or relay servers are neither provided nor can be discovered, the +992 /// connection attempt will fail with an error. +993 /// +994 /// The `alpn`, or application-level protocol identifier, is also required. The remote +995 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with +996 /// an error. +997 /// +998 /// [`RelayUrl`]: crate::RelayUrl +999 pub async fn connect( +1000 &self, +1001 endpoint_addr: impl Into<EndpointAddr>, +1002 alpn: &[u8], +1003 ) -> Result<Connection, ConnectError> { +1004 let endpoint_addr = endpoint_addr.into(); +1005 let remote = endpoint_addr.id; +1006 let connecting = self +1007 .connect_with_opts(endpoint_addr, alpn, Default::default()) +1008 .await?; +1009 let conn = connecting.await?; +1010 +1011 debug!( +1012 me = %self.id().fmt_short(), +1013 remote = %remote.fmt_short(), +1014 alpn = %String::from_utf8_lossy(alpn), +1015 "Connection established." +1016 ); +1017 Ok(conn) +1018 } +1019 +1020 /// Starts a connection attempt with a remote [`Endpoint`]. +1021 /// +1022 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more +1023 /// advanced connection setup with more customization in two aspects: +1024 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into +1025 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via +1026 /// [`Connecting::into_0rtt`]. +1027 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess +1028 /// security concerns. +1029 /// 2. The [`QuicTransportConfig`] for the connection can be modified via the provided +1030 /// [`ConnectOptions`]. +1031 /// **Note:** Please be aware that changing transport config settings may have adverse effects on +1032 /// establishing and maintaining direct connections. Carefully test settings you use and +1033 /// consider this currently as still rather experimental. +1034 #[instrument(name = "connect", skip_all, fields( +1035 me = %self.id().fmt_short(), +1036 remote = tracing::field::Empty, +1037 alpn = %String::from_utf8_lossy(alpn).to_string(), +1038 ))] +1039 pub async fn connect_with_opts( +1040 &self, +1041 endpoint_addr: impl Into<EndpointAddr>, +1042 alpn: &[u8], +1043 options: ConnectOptions, +1044 ) -> Result<Connecting, ConnectWithOptsError> { +1045 if self.is_closed() { +1046 return Err(e!(ConnectWithOptsError::EndpointClosed)); +1047 } +1048 +1049 let endpoint_addr: EndpointAddr = endpoint_addr.into(); +1050 let endpoint_id = endpoint_addr.id; +1051 +1052 Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short())); +1053 +1054 if let BeforeConnectOutcome::Reject = +1055 self.inner.hooks.before_connect(&endpoint_addr, alpn).await +1056 { +1057 return Err(e!(ConnectWithOptsError::LocallyRejected)); +1058 } +1059 +1060 // Connecting to ourselves is not supported. +1061 ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect); +1062 +1063 event!( +1064 target: "iroh::_events::conn::connecting", +1065 tracing::Level::DEBUG, +1066 remote_id = %endpoint_id.fmt_short(), +1067 alpn = %String::from_utf8_lossy(alpn), +1068 ); +1069 +1070 debug!( +1071 relay_url = ?endpoint_addr.relay_urls().next().cloned(), +1072 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(), +1073 "connecting", +1074 ); +1075 +1076 let mapped_addr = self.inner.resolve_remote(endpoint_addr).await??; +1077 +1078 let transport_config = options +1079 .transport_config +1080 .map(|cfg| cfg.to_inner_arc()) +1081 .unwrap_or(self.inner.static_config.transport_config.to_inner_arc()); +1082 +1083 // Start connecting via noq. This will time out after 10 seconds if no reachable +1084 // address is available. +1085 +1086 let mut alpn_protocols = vec![alpn.to_vec()]; +1087 alpn_protocols.extend(options.additional_alpns); +1088 let client_config = self +1089 .inner +1090 .static_config +1091 .create_client_config(alpn_protocols, transport_config.clone()); +1092 +1093 let dest_addr = mapped_addr.private_socket_addr(); +1094 let server_name = &tls::name::encode(endpoint_id); +1095 let connect = +1096 self.inner +1097 .noq_endpoint() +1098 .connect_with(client_config, dest_addr, server_name)?; +1099 +1100 Ok(Connecting::new(connect, self.clone(), endpoint_id)) +1101 } +1102 +1103 /// Accepts an incoming connection on the endpoint. +1104 /// +1105 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. +1106 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting +1107 /// the connection using [`Connecting::alpn`]. +1108 /// +1109 /// The returned future will yield `None` if the endpoint is closed by calling +1110 /// [`Endpoint::close`]. +1111 pub fn accept(&self) -> Accept<'_> { +1112 Accept { +1113 inner: self.inner.noq_endpoint().accept(), +1114 ep: self.clone(), +1115 } +1116 } +1117 +1118 // # Getter methods for properties of this Endpoint itself. +1119 +1120 /// Returns the secret_key of this endpoint. +1121 pub fn secret_key(&self) -> &SecretKey { +1122 &self.inner.static_config.tls_config.secret_key +1123 } +1124 +1125 /// Returns the endpoint id of this endpoint. +1126 /// +1127 /// This ID is the unique addressing information of this endpoint and other peers must know +1128 /// it to be able to connect to this endpoint. +1129 pub fn id(&self) -> EndpointId { +1130 self.inner.static_config.tls_config.secret_key.public() +1131 } +1132 +1133 /// Returns the current [`EndpointAddr`]. +1134 /// As long as the endpoint was able to bind to a network interface, some +1135 /// local addresses will be available. +1136 /// +1137 /// The state of other fields depends on the state of networking and connectivity. +1138 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered +1139 /// "online" (has contacted a relay server) before calling this method, if you want +1140 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint +1141 /// to be dialable by a remote endpoint over the internet. +1142 /// +1143 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` +1144 /// changes. +1145 pub fn addr(&self) -> EndpointAddr { +1146 self.watch_addr().get() +1147 } +1148 +1149 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. +1150 /// +1151 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. +1152 /// +1153 /// ```no_run +1154 /// # #[cfg(with_crypto_provider)] +1155 /// # { +1156 /// # async fn wrapper() -> n0_error::Result<()> { +1157 /// use iroh::{Endpoint, Watcher, endpoint::presets}; +1158 /// +1159 /// let endpoint = Endpoint::builder(presets::N0) +1160 /// .alpns(vec![b"my-alpn".to_vec()]) +1161 /// .bind() +1162 /// .await?; +1163 /// let endpoint_addr = endpoint.watch_addr().get(); +1164 /// # let _ = endpoint_addr; +1165 /// # Ok(()) 1166 /// # } -1167 /// ``` -1168 /// -1169 /// The [`Endpoint::online`] method can be used as a convenience method to -1170 /// understand if the endpoint has ever been considered "online". But after -1171 /// that initial call to [`Endpoint::online`], to understand if your -1172 /// endpoint is no longer able to be connected to by endpoints outside -1173 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. -1174 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints -1175 /// on the internet. -1176 /// -1177 /// The `EndpointAddr` will change as: -1178 /// - network conditions change -1179 /// - the endpoint connects to a relay server -1180 /// - the endpoint changes its preferred relay server -1181 /// - more addresses are discovered for this endpoint -1182 /// -1183 /// ## Closing behavior -1184 /// -1185 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] -1186 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created -1187 /// via [`Watcher::stream`] only terminates once the endpoint is fully dropped. To stop a task -1188 /// that loops over a watcher stream once the endpoint stops, combine with [`Self::closed`]: -1189 /// -1190 /// ```no_run -1191 /// # #[cfg(with_crypto_provider)] -1192 /// # { -1193 /// # use iroh::{Watcher, Endpoint, endpoint::presets}; -1194 /// # use n0_future::StreamExt; -1195 /// # use tracing::info; -1196 /// # async fn wrapper() -> n0_error::Result<()> { -1197 /// let endpoint = Endpoint::bind(presets::N0).await?; -1198 /// // We want to watch address changes in a different task, and stop our task -1199 /// // once the endpoint stops. -1200 /// let mut addr_stream = endpoint.watch_addr().stream(); -1201 /// let endpoint_closed = endpoint.closed(); -1202 /// tokio::spawn(endpoint_closed.run_until(async move { -1203 /// while let Some(addr) = addr_stream.next().await { -1204 /// info!("our address changed: {addr:?}"); -1205 /// } -1206 /// info!("endpoint closed"); -1207 /// })); -1208 /// // Do fancy things, then close the endpoint. -1209 /// // Our task above will stop even if there are still clones of `Endpoint` alive somewhere. -1210 /// endpoint.close().await; -1211 /// # Ok(()) -1212 /// # } +1167 /// # } +1168 /// ``` +1169 /// +1170 /// The [`Endpoint::online`] method can be used as a convenience method to +1171 /// understand if the endpoint has ever been considered "online". But after +1172 /// that initial call to [`Endpoint::online`], to understand if your +1173 /// endpoint is no longer able to be connected to by endpoints outside +1174 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. +1175 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints +1176 /// on the internet. +1177 /// +1178 /// The `EndpointAddr` will change as: +1179 /// - network conditions change +1180 /// - the endpoint connects to a relay server +1181 /// - the endpoint changes its preferred relay server +1182 /// - more addresses are discovered for this endpoint +1183 /// +1184 /// ## Closing behavior +1185 /// +1186 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] +1187 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created +1188 /// via [`Watcher::stream`] only terminates once the endpoint is fully dropped. To stop a task +1189 /// that loops over a watcher stream once the endpoint stops, combine with [`Self::closed`]: +1190 /// +1191 /// ```no_run +1192 /// # #[cfg(with_crypto_provider)] +1193 /// # { +1194 /// # use iroh::{Watcher, Endpoint, endpoint::presets}; +1195 /// # use n0_future::StreamExt; +1196 /// # use tracing::info; +1197 /// # async fn wrapper() -> n0_error::Result<()> { +1198 /// let endpoint = Endpoint::bind(presets::N0).await?; +1199 /// // We want to watch address changes in a different task, and stop our task +1200 /// // once the endpoint stops. +1201 /// let mut addr_stream = endpoint.watch_addr().stream(); +1202 /// let endpoint_closed = endpoint.closed(); +1203 /// tokio::spawn(endpoint_closed.run_until(async move { +1204 /// while let Some(addr) = addr_stream.next().await { +1205 /// info!("our address changed: {addr:?}"); +1206 /// } +1207 /// info!("endpoint closed"); +1208 /// })); +1209 /// // Do fancy things, then close the endpoint. +1210 /// // Our task above will stop even if there are still clones of `Endpoint` alive somewhere. +1211 /// endpoint.close().await; +1212 /// # Ok(()) 1213 /// # } -1214 /// ``` -1215 /// -1216 /// [`RelayUrl`]: crate::RelayUrl -1217 #[cfg(not(wasm_browser))] -1218 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -1219 let watch_addrs = self.inner.ip_addrs(); -1220 let watch_relay = self.inner.home_relay(); -1221 let endpoint_id = self.id(); -1222 -1223 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { -1224 EndpointAddr::from_parts( -1225 endpoint_id, -1226 relays -1227 .into_iter() -1228 .map(TransportAddr::Relay) -1229 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), -1230 ) -1231 }) -1232 } -1233 -1234 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -1235 /// -1236 /// When compiled to Wasm, this function returns a watcher that initializes -1237 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, -1238 /// as there are no APIs for directly using sockets in browsers. -1239 /// -1240 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] -1241 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created -1242 /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a -1243 /// task once the endpoint stops combine with [`Self::closed`]. -1244 #[cfg(wasm_browser)] -1245 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -1246 // In browsers, there will never be any direct addresses, so we wait -1247 // for the home relay instead. This makes the `EndpointAddr` have *some* way -1248 // of connecting to us. -1249 let watch_relay = self.inner.home_relay(); -1250 let endpoint_id = self.id(); -1251 watch_relay.map(move |mut relays| { -1252 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) -1253 }) -1254 } -1255 -1256 /// A convenience method that waits for the endpoint to be considered "online". -1257 /// -1258 /// This currently means at least one relay server has completed its -1259 /// connection handshake (i.e. the endpoint is registered and reachable -1260 /// via that relay). Merely selecting a relay URL is not sufficient. -1261 /// -1262 /// If no relays are configured, this will pend forever. -1263 /// -1264 /// This has no timeout, so if that is needed, you need to wrap it in a -1265 /// timeout. We recommend using a timeout close to -1266 /// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one -1267 /// [`crate::NetReport`] has been attempted. -1268 /// -1269 /// To understand if the endpoint has gone back "offline", -1270 /// you must use the [`Endpoint::watch_addr`] method, to -1271 /// get information on the current relay and direct address information. -1272 /// -1273 /// In the common case where the endpoint's configured relay servers are -1274 /// only accessible via a wide area network (WAN) connection, this method -1275 /// will await indefinitely when the endpoint has no WAN connection. If you're -1276 /// writing an app that's designed to work without a WAN connection, defer -1277 /// any calls to `online` as long as possible, or avoid calling `online` -1278 /// entirely. -1279 /// -1280 /// The online method does not interact with [`crate::address_lookup::AddressLookup`] -1281 /// services, which means that any Address Lookup that relies on a WAN -1282 /// connection is independent of the endpoint's online status. -1283 /// -1284 /// # Examples -1285 /// -1286 /// ```no run -1287 /// use iroh::Endpoint; -1288 /// -1289 /// #[tokio::main] -1290 /// async fn main() { -1291 /// // After this await returns, the endpoint is bound to a local socket. -1292 /// // It can be dialed, but almost certainly hasn't finished picking a -1293 /// // relay. -1294 /// let endpoint = Endpoint::bind().await; -1295 /// -1296 /// // After this await returns we have a connection to at least one relay -1297 /// // and holepunching should work as expected. -1298 /// endpoint.online().await; -1299 /// } -1300 /// ``` -1301 pub async fn online(&self) { -1302 let mut watcher = self.inner.home_relay_status(); -1303 let mut value = watcher.get(); -1304 loop { -1305 if value.into_iter().any(|status| status.is_connected()) { -1306 return; -1307 } -1308 value = match watcher.updated().await { -1309 Ok(value) => value, -1310 Err(_disconnected) => { -1311 std::future::pending::<()>().await; -1312 break; -1313 } -1314 } -1315 } -1316 } -1317 -1318 /// Returns a [`Watcher`] over the connection status of the endpoint's home relays. -1319 /// -1320 /// The watched value has one entry per home relay whose URL is known, -1321 /// and is empty when no relays are configured or before the endpoint has -1322 /// selected one the home relay from the list of configured relays. -1323 /// The watcher updates whenever any home relay's connection status changes. -1324 /// See [`RelayStatus`] for the information available on each entry. -1325 /// -1326 /// The returned watcher only becomes disconnected once the last clone of -1327 /// the [`Endpoint`] is dropped. Closing the endpoint does not disconnect -1328 /// the watcher. To stop a task once the endpoint stops, combine with -1329 /// [`Self::closed`]. -1330 pub fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> { -1331 self.inner.home_relay_status() -1332 } -1333 -1334 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. -1335 /// -1336 /// A `net-report` checks the network conditions of the [`Endpoint`], such as -1337 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT -1338 /// status, its latency to the relay servers, and its public addresses. -1339 /// -1340 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network -1341 /// conditions have changed. This [`Watcher`] will return the latest result -1342 /// of the `net-report`. -1343 /// -1344 /// When issuing the first call to this method the first report might -1345 /// still be underway, in this case the [`Watcher`] might not be initialized -1346 /// with [`Some`] value yet. Once the net-report has been successfully -1347 /// run, the [`Watcher`] will always return [`Some`] report immediately, which -1348 /// is the most recently run `net-report`. -1349 /// -1350 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] -1351 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created -1352 /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a -1353 /// task once the endpoint stops combine with [`Self::closed`]. -1354 /// -1355 /// # Examples -1356 /// -1357 /// To get the first report use [`Watcher::initialized`]: -1358 /// ```no_run -1359 /// # #[cfg(with_crypto_provider)] -1360 /// # { -1361 /// use iroh::{Endpoint, Watcher as _, endpoint::presets}; -1362 /// -1363 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -1364 /// # rt.block_on(async move { -1365 /// let ep = Endpoint::bind(presets::N0).await.unwrap(); -1366 /// let _report = ep.net_report().initialized().await; -1367 /// # }); -1368 /// # } -1369 /// ``` -1370 #[doc(hidden)] -1371 pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> { -1372 self.inner.net_report() -1373 } -1374 -1375 /// Returns the last [`NetReport`] generated by this endpoint. -1376 /// -1377 /// Returns `None` if no net report was ever generated. -1378 /// -1379 /// This method is hidden in the docs because it is not part of the public api -1380 #[doc(hidden)] -1381 pub fn last_net_report(&self) -> Option<NetReport> { -1382 self.inner.net_report().get() -1383 } -1384 -1385 /// Returns the local socket addresses on which the underlying sockets are bound. -1386 /// -1387 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 -1388 /// address if available. -1389 #[cfg(not(wasm_browser))] -1390 pub fn bound_sockets(&self) -> Vec<SocketAddr> { -1391 self.inner -1392 .local_addr() -1393 .into_iter() -1394 .filter_map(|addr| addr.into_socket_addr()) -1395 .collect() -1396 } -1397 -1398 // # Methods for less common getters. -1399 // -1400 // Partially they return things passed into the builder. -1401 -1402 /// Returns the DNS resolver used in this [`Endpoint`]. -1403 /// -1404 /// # Errors -1405 /// -1406 /// Returns an `EndpointError::Closed` error if the endpoint is closed. -1407 /// -1408 /// See [`Builder::dns_resolver`]. -1409 #[cfg(not(wasm_browser))] -1410 pub fn dns_resolver(&self) -> Result<&DnsResolver, EndpointError> { -1411 if self.is_closed() { -1412 return Err(e!(EndpointError::Closed)); -1413 } -1414 Ok(self.inner.dns_resolver()) -1415 } -1416 -1417 /// Returns the [`rustls::ClientConfig`] used by the endpoint for connecting to external services. -1418 /// -1419 /// This might be useful for address lookup services or other functions -1420 /// that want to use the same trust anchors as iroh does for verifying the -1421 /// validity of TLS certificates presented by external services. -1422 /// -1423 /// Note that this TLS config is unrelated to how iroh validates the authenticity -1424 /// of iroh connections itself. -1425 /// -1426 /// The config is based on the trust anchors set via [`Builder::ca_tls_config`]. -1427 pub fn tls_config(&self) -> &rustls::ClientConfig { -1428 &self.inner.tls_config -1429 } -1430 -1431 /// Returns the Address Lookup service, if configured. -1432 /// -1433 /// # Errors -1434 /// -1435 /// Returns a `EndpointError::Closed` error if the endpoint is closed. -1436 /// -1437 /// See [`Builder::address_lookup`]. -1438 pub fn address_lookup(&self) -> Result<&AddressLookupServices, EndpointError> { -1439 if self.is_closed() { -1440 return Err(e!(EndpointError::Closed)); -1441 } -1442 Ok(self.inner.address_lookup()) -1443 } -1444 -1445 /// Returns metrics collected for this endpoint. -1446 /// -1447 /// The endpoint internally collects various metrics about its operation. -1448 /// The returned [`EndpointMetrics`] struct contains all of these metrics. -1449 /// -1450 /// You can access individual metrics directly by using the public fields: -1451 /// ```rust -1452 /// # use std::collections::BTreeMap; -1453 /// # use iroh::endpoint::{Endpoint, presets}; -1454 /// # async fn wrapper() -> n0_error::Result<()> { -1455 /// let endpoint = Endpoint::bind(presets::N0).await?; -1456 /// assert_eq!(endpoint.metrics().socket.recv_datagrams.get(), 0); -1457 /// # Ok(()) -1458 /// # } -1459 /// ``` -1460 /// -1461 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field -1462 /// implements [`MetricsGroup`]. These traits provide methods to iterate over -1463 /// the groups in the set, and over the individual metrics in each group, without having -1464 /// to access each field manually. With these methods, it is straightforward to collect -1465 /// all metrics into a map or push their values to a metrics collector. -1466 /// -1467 /// For example, the following snippet collects all metrics into a map: -1468 /// ```rust -1469 /// # use std::collections::BTreeMap; -1470 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; -1471 /// # use iroh::endpoint::{Endpoint, presets}; -1472 /// # async fn wrapper() -> n0_error::Result<()> { -1473 /// let endpoint = Endpoint::bind(presets::N0).await?; -1474 /// let metrics: BTreeMap<String, MetricValue> = endpoint -1475 /// .metrics() -1476 /// .iter() -1477 /// .map(|(group, metric)| { -1478 /// let name = [group, metric.name()].join(":"); -1479 /// (name, metric.value()) -1480 /// }) -1481 /// .collect(); -1482 /// -1483 /// assert_eq!(metrics["socket:recv_datagrams"], MetricValue::Counter(0)); -1484 /// # Ok(()) -1485 /// # } -1486 /// ``` -1487 /// -1488 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. -1489 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the -1490 /// registry with [`Registry::register_all`], and encode the metrics to a string with -1491 /// [`encode_openmetrics_to_string`]: -1492 /// ```rust -1493 /// # use iroh_metrics::{Registry, MetricsSource}; -1494 /// # use iroh::endpoint::{Endpoint, presets}; -1495 /// # async fn wrapper() -> n0_error::Result<()> { -1496 /// let endpoint = Endpoint::bind(presets::N0).await?; -1497 /// let mut registry = Registry::default(); -1498 /// registry.register_all(endpoint.metrics()); -1499 /// let s = registry.encode_openmetrics_to_string()?; -1500 /// assert!(s.contains(r#"TYPE socket_recv_datagrams counter"#)); -1501 /// assert!(s.contains(r#"socket_recv_datagrams_total 0"#)); -1502 /// # Ok(()) -1503 /// # } -1504 /// ``` -1505 /// -1506 /// Through a registry, you can also add labels or prefixes to metrics with -1507 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. -1508 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services -1509 /// to serve the metrics with a HTTP server, dump them to a file, or push them -1510 /// to a Prometheus gateway. -1511 /// -1512 /// For example, the following snippet launches an HTTP server that serves the metrics in the -1513 /// OpenMetrics text format: -1514 /// ```no_run -1515 /// # use std::sync::{Arc, RwLock}; -1516 /// # use iroh_metrics::{Registry, MetricsSource}; -1517 /// # use iroh::endpoint::{Endpoint, presets}; -1518 /// # use n0_error::{StackResultExt, StdResultExt}; -1519 /// # async fn wrapper() -> n0_error::Result<()> { -1520 /// // Create a registry, wrapped in a read-write lock so that we can register and serve -1521 /// // the metrics independently. -1522 /// let registry = Arc::new(RwLock::new(Registry::default())); -1523 /// // Spawn an OpenMetrics HTTP server backed by the registry. -1524 /// let addr = "0.0.0.0:9100".parse().unwrap(); -1525 /// let metrics_server = iroh_metrics::service::MetricsServer::spawn(addr, registry.clone()) -1526 /// .await -1527 /// .std_context("spawn metrics server")?; -1528 /// -1529 /// // Spawn an endpoint and add the metrics to the registry. -1530 /// let endpoint = Endpoint::bind(presets::N0).await?; -1531 /// registry.write().unwrap().register_all(endpoint.metrics()); -1532 /// -1533 /// // Fetch the metrics via HTTP. -1534 /// let res = reqwest::get("http://localhost:9100/metrics") -1535 /// .await -1536 /// .std_context("get")? -1537 /// .text() -1538 /// .await -1539 /// .std_context("text")?; -1540 /// -1541 /// assert!(res.contains(r#"TYPE socket_recv_datagrams counter"#)); -1542 /// assert!(res.contains(r#"socket_recv_datagrams_total 0"#)); -1543 /// # metrics_server.shutdown().await; -1544 /// # Ok(()) -1545 /// # } -1546 /// ``` -1547 /// -1548 /// [`Registry`]: iroh_metrics::Registry -1549 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all -1550 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label -1551 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix -1552 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string -1553 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup -1554 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet -1555 #[cfg(feature = "metrics")] -1556 pub fn metrics(&self) -> &EndpointMetrics { -1557 &self.inner.metrics -1558 } -1559 -1560 /// Returns addressing information about a recently used remote endpoint. -1561 /// -1562 /// The returned [`RemoteInfo`] contains a list of all transport addresses for the remote -1563 /// that we know about. This is a snapshot in time and not a watcher. -1564 /// -1565 /// Returns `None` if the endpoint doesn't have information about the remote or if the endpoint is closed. -1566 /// When remote endpoints are no longer used, our endpoint will keep information around -1567 /// for a little while, and then drop it. Afterwards, this will return `None`. -1568 pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo> { -1569 if self.is_closed() { -1570 return None; -1571 } -1572 self.inner.remote_info(endpoint_id).await -1573 } -1574 -1575 // # Methods for less common state updates. -1576 -1577 /// Notifies the system of potential network changes. -1578 /// -1579 /// On many systems iroh is able to detect network changes by itself, however -1580 /// some systems like android do not expose this functionality to native code. -1581 /// Android does however provide this functionality to Java code. This -1582 /// function allows for notifying iroh of any potential network changes like -1583 /// this. -1584 /// -1585 /// Even when the network did not change, or iroh was already able to detect -1586 /// the network change itself, there is no harm in calling this function. -1587 /// -1588 /// If the endpoint is closed, this method will log a warning and ignore the request. -1589 pub async fn network_change(&self) { -1590 if self.is_closed() { -1591 debug!("Attempting to notify a closed endpoint about a network change. Ignoring."); -1592 return; -1593 } -1594 self.inner.network_change().await; -1595 } -1596 -1597 // # Methods to update internal state. -1598 -1599 /// Sets the initial user-defined data to be published in Address Lookups for this endpoint. -1600 /// -1601 /// If the user-defined data passed to this function is different to the previous one, -1602 /// the endpoint will republish its endpoint info to the configured Address Lookups. -1603 /// -1604 /// See also [`Builder::user_data_for_address_lookup`] for setting an initial value when -1605 /// building the endpoint. -1606 /// -1607 /// If the endpoint is closed, this method will log a warning and ignore the -1608 /// request. -1609 pub fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) { -1610 if self.is_closed() { -1611 warn!("Attempting to set user data for a closed endpoint. Ignoring."); -1612 return; -1613 } -1614 self.inner.set_user_data_for_address_lookup(user_data); -1615 } -1616 -1617 // # Methods for terminating the endpoint. -1618 -1619 /// Closes the QUIC endpoint and the socket. -1620 /// -1621 /// This will close any remaining open [`Connection`]s with an error code -1622 /// of `0` and an empty reason. Though it is best practice to close those -1623 /// explicitly before with a custom error code and reason. -1624 /// -1625 /// It will then make a best effort to wait for all close notifications to be -1626 /// acknowledged by the peers, re-transmitting them if needed. This ensures the -1627 /// peers are aware of the closed connections instead of having to wait for a timeout -1628 /// on the connection. Once all connections are closed or timed out, the future -1629 /// finishes. -1630 /// -1631 /// The maximum time-out that this future will wait for depends on QUIC transport -1632 /// configurations of non-drained connections at the time of calling, and their current -1633 /// estimates of round trip time. With default parameters and a conservative estimate -1634 /// of round trip time, this call's future should take 3 seconds to resolve in cases of -1635 /// bad connectivity or failed connections. In the usual case, this call's future should -1636 /// return much more quickly. -1637 /// -1638 /// It is highly recommended you *do* wait for this close call to finish, if possible. -1639 /// Not doing so will make connections that were still open while closing the endpoint -1640 /// time out on the remote end. Thus remote ends will assume connections to have failed -1641 /// even if all application data was transmitted successfully. -1642 /// -1643 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait -1644 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP -1645 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, -1646 /// while TCP sockets usually get closed and drained by the operating system in the -1647 /// kernel during the "Time-Wait" period of the TCP socket. -1648 /// -1649 /// Be aware however that the underlying UDP sockets are only closed once all clones of -1650 /// the the respective [`Endpoint`] are dropped. -1651 pub async fn close(&self) { -1652 self.inner.close().await; -1653 } -1654 -1655 /// Check if this endpoint is still alive, or already closed. -1656 pub fn is_closed(&self) -> bool { -1657 self.inner.is_closed() -1658 } -1659 -1660 /// Returns a future that resolves once the endpoint closes. -1661 /// -1662 /// The returned future does not contain a clone or reference to the [`Endpoint`], -1663 /// so keeping the returned future alive does not prevent the endpoint from being dropped. -1664 /// -1665 /// To run a task and stop it once the endpoint closes, you can use -1666 /// [`EndpointClosed::run_until`]: -1667 /// ```no_run -1668 /// # #[cfg(with_crypto_provider)] -1669 /// # { -1670 /// # use iroh::endpoint::{Endpoint, presets}; -1671 /// # async fn wrapper() -> n0_error::Result<()> { -1672 /// let endpoint = Endpoint::bind(presets::N0).await?; -1673 /// tokio::spawn(endpoint.closed().run_until(async move { -1674 /// // the future will be aborted once the endpoint closes. -1675 /// })); -1676 /// # Ok(()) -1677 /// # } +1214 /// # } +1215 /// ``` +1216 /// +1217 /// [`RelayUrl`]: crate::RelayUrl +1218 #[cfg(not(wasm_browser))] +1219 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +1220 let watch_addrs = self.inner.ip_addrs(); +1221 let watch_relay = self.inner.home_relay(); +1222 let endpoint_id = self.id(); +1223 +1224 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { +1225 EndpointAddr::from_parts( +1226 endpoint_id, +1227 relays +1228 .into_iter() +1229 .map(TransportAddr::Relay) +1230 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), +1231 ) +1232 }) +1233 } +1234 +1235 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. +1236 /// +1237 /// When compiled to Wasm, this function returns a watcher that initializes +1238 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, +1239 /// as there are no APIs for directly using sockets in browsers. +1240 /// +1241 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] +1242 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created +1243 /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a +1244 /// task once the endpoint stops combine with [`Self::closed`]. +1245 #[cfg(wasm_browser)] +1246 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +1247 // In browsers, there will never be any direct addresses, so we wait +1248 // for the home relay instead. This makes the `EndpointAddr` have *some* way +1249 // of connecting to us. +1250 let watch_relay = self.inner.home_relay(); +1251 let endpoint_id = self.id(); +1252 watch_relay.map(move |mut relays| { +1253 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) +1254 }) +1255 } +1256 +1257 /// A convenience method that waits for the endpoint to be considered "online". +1258 /// +1259 /// This currently means at least one relay server has completed its +1260 /// connection handshake (i.e. the endpoint is registered and reachable +1261 /// via that relay). Merely selecting a relay URL is not sufficient. +1262 /// +1263 /// If no relays are configured, this will pend forever. +1264 /// +1265 /// This has no timeout, so if that is needed, you need to wrap it in a +1266 /// timeout. We recommend using a timeout close to +1267 /// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one +1268 /// [`crate::NetReport`] has been attempted. +1269 /// +1270 /// To understand if the endpoint has gone back "offline", +1271 /// you must use the [`Endpoint::watch_addr`] method, to +1272 /// get information on the current relay and direct address information. +1273 /// +1274 /// In the common case where the endpoint's configured relay servers are +1275 /// only accessible via a wide area network (WAN) connection, this method +1276 /// will await indefinitely when the endpoint has no WAN connection. If you're +1277 /// writing an app that's designed to work without a WAN connection, defer +1278 /// any calls to `online` as long as possible, or avoid calling `online` +1279 /// entirely. +1280 /// +1281 /// The online method does not interact with [`crate::address_lookup::AddressLookup`] +1282 /// services, which means that any Address Lookup that relies on a WAN +1283 /// connection is independent of the endpoint's online status. +1284 /// +1285 /// # Examples +1286 /// +1287 /// ```no run +1288 /// use iroh::Endpoint; +1289 /// +1290 /// #[tokio::main] +1291 /// async fn main() { +1292 /// // After this await returns, the endpoint is bound to a local socket. +1293 /// // It can be dialed, but almost certainly hasn't finished picking a +1294 /// // relay. +1295 /// let endpoint = Endpoint::bind().await; +1296 /// +1297 /// // After this await returns we have a connection to at least one relay +1298 /// // and holepunching should work as expected. +1299 /// endpoint.online().await; +1300 /// } +1301 /// ``` +1302 pub async fn online(&self) { +1303 let mut watcher = self.inner.home_relay_status(); +1304 let mut value = watcher.get(); +1305 loop { +1306 if value.into_iter().any(|status| status.is_connected()) { +1307 return; +1308 } +1309 value = match watcher.updated().await { +1310 Ok(value) => value, +1311 Err(_disconnected) => { +1312 std::future::pending::<()>().await; +1313 break; +1314 } +1315 } +1316 } +1317 } +1318 +1319 /// Returns a [`Watcher`] over the connection status of the endpoint's home relays. +1320 /// +1321 /// The watched value has one entry per home relay whose URL is known, +1322 /// and is empty when no relays are configured or before the endpoint has +1323 /// selected one the home relay from the list of configured relays. +1324 /// The watcher updates whenever any home relay's connection status changes. +1325 /// See [`RelayStatus`] for the information available on each entry. +1326 /// +1327 /// The returned watcher only becomes disconnected once the last clone of +1328 /// the [`Endpoint`] is dropped. Closing the endpoint does not disconnect +1329 /// the watcher. To stop a task once the endpoint stops, combine with +1330 /// [`Self::closed`]. +1331 pub fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> { +1332 self.inner.home_relay_status() +1333 } +1334 +1335 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. +1336 /// +1337 /// A `net-report` checks the network conditions of the [`Endpoint`], such as +1338 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT +1339 /// status, its latency to the relay servers, and its public addresses. +1340 /// +1341 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network +1342 /// conditions have changed. This [`Watcher`] will return the latest result +1343 /// of the `net-report`. +1344 /// +1345 /// When issuing the first call to this method the first report might +1346 /// still be underway, in this case the [`Watcher`] might not be initialized +1347 /// with [`Some`] value yet. Once the net-report has been successfully +1348 /// run, the [`Watcher`] will always return [`Some`] report immediately, which +1349 /// is the most recently run `net-report`. +1350 /// +1351 /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`] +1352 /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created +1353 /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a +1354 /// task once the endpoint stops combine with [`Self::closed`]. +1355 /// +1356 /// # Examples +1357 /// +1358 /// To get the first report use [`Watcher::initialized`]: +1359 /// ```no_run +1360 /// # #[cfg(with_crypto_provider)] +1361 /// # { +1362 /// use iroh::{Endpoint, Watcher as _, endpoint::presets}; +1363 /// +1364 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +1365 /// # rt.block_on(async move { +1366 /// let ep = Endpoint::bind(presets::N0).await.unwrap(); +1367 /// let _report = ep.net_report().initialized().await; +1368 /// # }); +1369 /// # } +1370 /// ``` +1371 #[doc(hidden)] +1372 pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> { +1373 self.inner.net_report() +1374 } +1375 +1376 /// Returns the last [`NetReport`] generated by this endpoint. +1377 /// +1378 /// Returns `None` if no net report was ever generated. +1379 /// +1380 /// This method is hidden in the docs because it is not part of the public api +1381 #[doc(hidden)] +1382 pub fn last_net_report(&self) -> Option<NetReport> { +1383 self.inner.net_report().get() +1384 } +1385 +1386 /// Returns the local socket addresses on which the underlying sockets are bound. +1387 /// +1388 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 +1389 /// address if available. +1390 #[cfg(not(wasm_browser))] +1391 pub fn bound_sockets(&self) -> Vec<SocketAddr> { +1392 self.inner +1393 .local_addr() +1394 .into_iter() +1395 .filter_map(|addr| addr.into_socket_addr()) +1396 .collect() +1397 } +1398 +1399 // # Methods for less common getters. +1400 // +1401 // Partially they return things passed into the builder. +1402 +1403 /// Returns the DNS resolver used in this [`Endpoint`]. +1404 /// +1405 /// # Errors +1406 /// +1407 /// Returns an `EndpointError::Closed` error if the endpoint is closed. +1408 /// +1409 /// See [`Builder::dns_resolver`]. +1410 #[cfg(not(wasm_browser))] +1411 pub fn dns_resolver(&self) -> Result<&DnsResolver, EndpointError> { +1412 if self.is_closed() { +1413 return Err(e!(EndpointError::Closed)); +1414 } +1415 Ok(self.inner.dns_resolver()) +1416 } +1417 +1418 /// Returns the [`rustls::ClientConfig`] used by the endpoint for connecting to external services. +1419 /// +1420 /// This might be useful for address lookup services or other functions +1421 /// that want to use the same trust anchors as iroh does for verifying the +1422 /// validity of TLS certificates presented by external services. +1423 /// +1424 /// Note that this TLS config is unrelated to how iroh validates the authenticity +1425 /// of iroh connections itself. +1426 /// +1427 /// The config is based on the trust anchors set via [`Builder::ca_tls_config`]. +1428 pub fn tls_config(&self) -> &rustls::ClientConfig { +1429 &self.inner.tls_config +1430 } +1431 +1432 /// Returns the Address Lookup service, if configured. +1433 /// +1434 /// # Errors +1435 /// +1436 /// Returns a `EndpointError::Closed` error if the endpoint is closed. +1437 /// +1438 /// See [`Builder::address_lookup`]. +1439 pub fn address_lookup(&self) -> Result<&AddressLookupServices, EndpointError> { +1440 if self.is_closed() { +1441 return Err(e!(EndpointError::Closed)); +1442 } +1443 Ok(self.inner.address_lookup()) +1444 } +1445 +1446 /// Returns metrics collected for this endpoint. +1447 /// +1448 /// The endpoint internally collects various metrics about its operation. +1449 /// The returned [`EndpointMetrics`] struct contains all of these metrics. +1450 /// +1451 /// You can access individual metrics directly by using the public fields: +1452 /// ```rust +1453 /// # use std::collections::BTreeMap; +1454 /// # use iroh::endpoint::{Endpoint, presets}; +1455 /// # async fn wrapper() -> n0_error::Result<()> { +1456 /// let endpoint = Endpoint::bind(presets::N0).await?; +1457 /// assert_eq!(endpoint.metrics().socket.recv_datagrams.get(), 0); +1458 /// # Ok(()) +1459 /// # } +1460 /// ``` +1461 /// +1462 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field +1463 /// implements [`MetricsGroup`]. These traits provide methods to iterate over +1464 /// the groups in the set, and over the individual metrics in each group, without having +1465 /// to access each field manually. With these methods, it is straightforward to collect +1466 /// all metrics into a map or push their values to a metrics collector. +1467 /// +1468 /// For example, the following snippet collects all metrics into a map: +1469 /// ```rust +1470 /// # use std::collections::BTreeMap; +1471 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; +1472 /// # use iroh::endpoint::{Endpoint, presets}; +1473 /// # async fn wrapper() -> n0_error::Result<()> { +1474 /// let endpoint = Endpoint::bind(presets::N0).await?; +1475 /// let metrics: BTreeMap<String, MetricValue> = endpoint +1476 /// .metrics() +1477 /// .iter() +1478 /// .map(|(group, metric)| { +1479 /// let name = [group, metric.name()].join(":"); +1480 /// (name, metric.value()) +1481 /// }) +1482 /// .collect(); +1483 /// +1484 /// assert_eq!(metrics["socket:recv_datagrams"], MetricValue::Counter(0)); +1485 /// # Ok(()) +1486 /// # } +1487 /// ``` +1488 /// +1489 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. +1490 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the +1491 /// registry with [`Registry::register_all`], and encode the metrics to a string with +1492 /// [`encode_openmetrics_to_string`]: +1493 /// ```rust +1494 /// # use iroh_metrics::{Registry, MetricsSource}; +1495 /// # use iroh::endpoint::{Endpoint, presets}; +1496 /// # async fn wrapper() -> n0_error::Result<()> { +1497 /// let endpoint = Endpoint::bind(presets::N0).await?; +1498 /// let mut registry = Registry::default(); +1499 /// registry.register_all(endpoint.metrics()); +1500 /// let s = registry.encode_openmetrics_to_string()?; +1501 /// assert!(s.contains(r#"TYPE socket_recv_datagrams counter"#)); +1502 /// assert!(s.contains(r#"socket_recv_datagrams_total 0"#)); +1503 /// # Ok(()) +1504 /// # } +1505 /// ``` +1506 /// +1507 /// Through a registry, you can also add labels or prefixes to metrics with +1508 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. +1509 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services +1510 /// to serve the metrics with a HTTP server, dump them to a file, or push them +1511 /// to a Prometheus gateway. +1512 /// +1513 /// For example, the following snippet launches an HTTP server that serves the metrics in the +1514 /// OpenMetrics text format: +1515 /// ```no_run +1516 /// # use std::sync::{Arc, RwLock}; +1517 /// # use iroh_metrics::{Registry, MetricsSource}; +1518 /// # use iroh::endpoint::{Endpoint, presets}; +1519 /// # use n0_error::{StackResultExt, StdResultExt}; +1520 /// # async fn wrapper() -> n0_error::Result<()> { +1521 /// // Create a registry, wrapped in a read-write lock so that we can register and serve +1522 /// // the metrics independently. +1523 /// let registry = Arc::new(RwLock::new(Registry::default())); +1524 /// // Spawn an OpenMetrics HTTP server backed by the registry. +1525 /// let addr = "0.0.0.0:9100".parse().unwrap(); +1526 /// let metrics_server = iroh_metrics::service::MetricsServer::spawn(addr, registry.clone()) +1527 /// .await +1528 /// .std_context("spawn metrics server")?; +1529 /// +1530 /// // Spawn an endpoint and add the metrics to the registry. +1531 /// let endpoint = Endpoint::bind(presets::N0).await?; +1532 /// registry.write().unwrap().register_all(endpoint.metrics()); +1533 /// +1534 /// // Fetch the metrics via HTTP. +1535 /// let res = reqwest::get("http://localhost:9100/metrics") +1536 /// .await +1537 /// .std_context("get")? +1538 /// .text() +1539 /// .await +1540 /// .std_context("text")?; +1541 /// +1542 /// assert!(res.contains(r#"TYPE socket_recv_datagrams counter"#)); +1543 /// assert!(res.contains(r#"socket_recv_datagrams_total 0"#)); +1544 /// # metrics_server.shutdown().await; +1545 /// # Ok(()) +1546 /// # } +1547 /// ``` +1548 /// +1549 /// [`Registry`]: iroh_metrics::Registry +1550 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all +1551 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label +1552 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix +1553 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string +1554 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup +1555 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet +1556 #[cfg(feature = "metrics")] +1557 pub fn metrics(&self) -> &EndpointMetrics { +1558 &self.inner.metrics +1559 } +1560 +1561 /// Returns addressing information about a recently used remote endpoint. +1562 /// +1563 /// The returned [`RemoteInfo`] contains a list of all transport addresses for the remote +1564 /// that we know about. This is a snapshot in time and not a watcher. +1565 /// +1566 /// Returns `None` if the endpoint doesn't have information about the remote or if the endpoint is closed. +1567 /// When remote endpoints are no longer used, our endpoint will keep information around +1568 /// for a little while, and then drop it. Afterwards, this will return `None`. +1569 pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo> { +1570 if self.is_closed() { +1571 return None; +1572 } +1573 self.inner.remote_info(endpoint_id).await +1574 } +1575 +1576 // # Methods for less common state updates. +1577 +1578 /// Notifies the system of potential network changes. +1579 /// +1580 /// On many systems iroh is able to detect network changes by itself, however +1581 /// some systems like android do not expose this functionality to native code. +1582 /// Android does however provide this functionality to Java code. This +1583 /// function allows for notifying iroh of any potential network changes like +1584 /// this. +1585 /// +1586 /// Even when the network did not change, or iroh was already able to detect +1587 /// the network change itself, there is no harm in calling this function. +1588 /// +1589 /// If the endpoint is closed, this method will log a warning and ignore the request. +1590 pub async fn network_change(&self) { +1591 if self.is_closed() { +1592 debug!("Attempting to notify a closed endpoint about a network change. Ignoring."); +1593 return; +1594 } +1595 self.inner.network_change().await; +1596 } +1597 +1598 // # Methods to update internal state. +1599 +1600 /// Sets the initial user-defined data to be published in Address Lookups for this endpoint. +1601 /// +1602 /// If the user-defined data passed to this function is different to the previous one, +1603 /// the endpoint will republish its endpoint info to the configured Address Lookups. +1604 /// +1605 /// See also [`Builder::user_data_for_address_lookup`] for setting an initial value when +1606 /// building the endpoint. +1607 /// +1608 /// If the endpoint is closed, this method will log a warning and ignore the +1609 /// request. +1610 pub fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) { +1611 if self.is_closed() { +1612 warn!("Attempting to set user data for a closed endpoint. Ignoring."); +1613 return; +1614 } +1615 self.inner.set_user_data_for_address_lookup(user_data); +1616 } +1617 +1618 // # Methods for terminating the endpoint. +1619 +1620 /// Closes the QUIC endpoint and the socket. +1621 /// +1622 /// This will close any remaining open [`Connection`]s with an error code +1623 /// of `0` and an empty reason. Though it is best practice to close those +1624 /// explicitly before with a custom error code and reason. +1625 /// +1626 /// It will then make a best effort to wait for all close notifications to be +1627 /// acknowledged by the peers, re-transmitting them if needed. This ensures the +1628 /// peers are aware of the closed connections instead of having to wait for a timeout +1629 /// on the connection. Once all connections are closed or timed out, the future +1630 /// finishes. +1631 /// +1632 /// The maximum time-out that this future will wait for depends on QUIC transport +1633 /// configurations of non-drained connections at the time of calling, and their current +1634 /// estimates of round trip time. With default parameters and a conservative estimate +1635 /// of round trip time, this call's future should take 3 seconds to resolve in cases of +1636 /// bad connectivity or failed connections. In the usual case, this call's future should +1637 /// return much more quickly. +1638 /// +1639 /// It is highly recommended you *do* wait for this close call to finish, if possible. +1640 /// Not doing so will make connections that were still open while closing the endpoint +1641 /// time out on the remote end. Thus remote ends will assume connections to have failed +1642 /// even if all application data was transmitted successfully. +1643 /// +1644 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait +1645 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP +1646 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, +1647 /// while TCP sockets usually get closed and drained by the operating system in the +1648 /// kernel during the "Time-Wait" period of the TCP socket. +1649 /// +1650 /// Be aware however that the underlying UDP sockets are only closed once all clones of +1651 /// the the respective [`Endpoint`] are dropped. +1652 pub async fn close(&self) { +1653 self.inner.close().await; +1654 } +1655 +1656 /// Check if this endpoint is still alive, or already closed. +1657 pub fn is_closed(&self) -> bool { +1658 self.inner.is_closed() +1659 } +1660 +1661 /// Returns a future that resolves once the endpoint closes. +1662 /// +1663 /// The returned future does not contain a clone or reference to the [`Endpoint`], +1664 /// so keeping the returned future alive does not prevent the endpoint from being dropped. +1665 /// +1666 /// To run a task and stop it once the endpoint closes, you can use +1667 /// [`EndpointClosed::run_until`]: +1668 /// ```no_run +1669 /// # #[cfg(with_crypto_provider)] +1670 /// # { +1671 /// # use iroh::endpoint::{Endpoint, presets}; +1672 /// # async fn wrapper() -> n0_error::Result<()> { +1673 /// let endpoint = Endpoint::bind(presets::N0).await?; +1674 /// tokio::spawn(endpoint.closed().run_until(async move { +1675 /// // the future will be aborted once the endpoint closes. +1676 /// })); +1677 /// # Ok(()) 1678 /// # } -1679 /// ``` -1680 pub fn closed(&self) -> EndpointClosed { -1681 EndpointClosed { -1682 inner: self.inner.closed(), -1683 } -1684 } -1685 -1686 /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. -1687 /// -1688 /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration -1689 /// for a connection accepted using the [`Incoming::accept_with`] method. -1690 pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder { -1691 let inner = self.inner.static_config.create_server_config(alpns); -1692 ServerConfigBuilder::new(inner, self.inner.static_config.transport_config.clone()) -1693 } -1694 -1695 // # Remaining private methods -1696 -1697 /// Translates a raw [`SocketAddr`] (which may be a synthetic mapped address) into -1698 /// a transport address. -1699 pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> crate::socket::transports::Addr { -1700 self.inner.to_transport_addr(addr) -1701 } -1702 -1703 #[cfg(all(test, with_crypto_provider))] -1704 pub(crate) fn inner(&self) -> Result<Arc<EndpointInner>, EndpointError> { -1705 if self.is_closed() { -1706 return Err(e!(EndpointError::Closed)); -1707 } -1708 Ok(self.inner.clone()) -1709 } -1710} -1711 -1712/// Options for the [`Endpoint::connect_with_opts`] function. -1713#[derive(Default, Debug, Clone)] -1714pub struct ConnectOptions { -1715 transport_config: Option<QuicTransportConfig>, -1716 additional_alpns: Vec<Vec<u8>>, -1717} -1718 -1719impl ConnectOptions { -1720 /// Initializes new connection options. -1721 /// -1722 /// By default, the connection will use the same options -1723 /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`]. -1724 pub fn new() -> Self { -1725 Self::default() -1726 } -1727 -1728 /// Sets the QUIC transport config options for this connection. -1729 pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self { -1730 self.transport_config = Some(transport_config); -1731 self -1732 } -1733 -1734 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in -1735 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. -1736 /// -1737 /// This allows connecting to servers that may only support older versions of your -1738 /// protocol. In this case, you would add the older [ALPN] identifiers with this -1739 /// function. -1740 /// -1741 /// You'll know the final negotiated [ALPN] identifier once your connection was -1742 /// established using [`Connection::alpn`], or even slightly earlier in the -1743 /// handshake by using [`Connecting::alpn`]. -1744 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this -1745 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. -1746 /// -1747 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the -1748 /// accept side that determines the protocol. -1749 /// -1750 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint -1751 /// builder's [`Builder::alpns`] function. -1752 /// -1753 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -1754 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { -1755 self.additional_alpns = alpns; -1756 self -1757 } -1758} -1759 -1760/// Future returned from [`Endpoint::closed`]. -1761#[derive(derive_more::Debug)] -1762#[pin_project] -1763#[debug("EndpointClosed")] -1764pub struct EndpointClosed { -1765 #[pin] -1766 inner: WaitForCancellationFutureOwned, -1767} -1768 -1769impl Future for EndpointClosed { -1770 type Output = (); -1771 -1772 fn poll( -1773 self: Pin<&mut Self>, -1774 cx: &mut std::task::Context<'_>, -1775 ) -> std::task::Poll<Self::Output> { -1776 let this = self.project(); -1777 this.inner.poll(cx) -1778 } -1779} -1780 -1781impl EndpointClosed { -1782 /// Runs a future to completion, or until the [`Endpoint`] is closed. -1783 /// -1784 /// Returns the output of `fut` if it completes before the endpoint closes, -1785 /// or `None` otherwise. -1786 pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output> { -1787 n0_future::future::or(async { Some(fut.await) }, async { -1788 self.await; -1789 None -1790 }) -1791 .await -1792 } -1793} -1794 -1795/// Read a proxy url from the environment, in this order -1796/// -1797/// - `HTTP_PROXY` -1798/// - `http_proxy` -1799/// - `HTTPS_PROXY` -1800/// - `https_proxy` -1801fn proxy_url_from_env() -> Option<Url> { -1802 if let Some(url) = std::env::var("HTTP_PROXY") -1803 .ok() -1804 .and_then(|s| s.parse::<Url>().ok()) -1805 { -1806 if is_cgi() { -1807 warn!("HTTP_PROXY environment variable ignored in CGI"); -1808 } else { -1809 return Some(url); -1810 } -1811 } -1812 if let Some(url) = std::env::var("http_proxy") -1813 .ok() -1814 .and_then(|s| s.parse::<Url>().ok()) -1815 { -1816 return Some(url); -1817 } -1818 if let Some(url) = std::env::var("HTTPS_PROXY") -1819 .ok() -1820 .and_then(|s| s.parse::<Url>().ok()) -1821 { -1822 return Some(url); -1823 } -1824 if let Some(url) = std::env::var("https_proxy") -1825 .ok() -1826 .and_then(|s| s.parse::<Url>().ok()) -1827 { -1828 return Some(url); -1829 } -1830 -1831 None -1832} -1833 -1834/// Connection status of a single home relay. -1835/// -1836/// Observed via [`Endpoint::home_relay_status`]. -1837#[derive(Debug, Clone, PartialEq, Eq)] -1838pub struct RelayStatus { -1839 url: RelayUrl, -1840 state: RelayConnectionState, -1841} -1842 -1843impl RelayStatus { -1844 pub(crate) fn new(url: RelayUrl, state: RelayConnectionState) -> Self { -1845 Self { url, state } -1846 } -1847 -1848 /// Returns the URL of the home relay. -1849 pub fn url(&self) -> &RelayUrl { -1850 &self.url -1851 } -1852 -1853 /// Returns `true` if the endpoint is connected to the relay. -1854 pub fn is_connected(&self) -> bool { -1855 self.state.is_connected() -1856 } -1857 -1858 /// Returns the most recent connection error, if the relay is currently -1859 /// disconnected. -1860 /// -1861 /// Returns `None` when the relay is connected, or when the endpoint has -1862 /// not yet observed a failed connection attempt. -1863 pub fn last_error(&self) -> Option<&AnyError> { -1864 self.state.last_error().map(Arc::as_ref) -1865 } -1866} -1867 -1868/// Configuration of the relay servers for an [`Endpoint`]. -1869#[derive(Debug, Clone, PartialEq, Eq)] -1870pub enum RelayMode { -1871 /// Disable relay servers completely. -1872 /// This means that neither listening nor dialing relays will be available. -1873 Disabled, -1874 /// Use the default relay map, with production relay servers from n0. -1875 /// -1876 /// See [`crate::defaults::prod`] for the severs used. -1877 Default, -1878 /// Use the staging relay servers from n0. -1879 Staging, -1880 /// Use a custom relay map. -1881 Custom(RelayMap), -1882} -1883 -1884impl RelayMode { -1885 /// Returns the relay map for this mode. -1886 pub fn relay_map(&self) -> RelayMap { -1887 match self { -1888 RelayMode::Disabled => RelayMap::empty(), -1889 RelayMode::Default => crate::defaults::prod::default_relay_map(), -1890 RelayMode::Staging => crate::defaults::staging::default_relay_map(), -1891 RelayMode::Custom(relay_map) => relay_map.clone(), -1892 } -1893 } -1894 -1895 /// Create a custom relay mode from a list of [`RelayUrl`]s. -1896 /// -1897 /// # Example -1898 /// -1899 /// ``` -1900 /// # fn main() -> n0_error::Result<()> { -1901 /// # use iroh::RelayMode; -1902 /// RelayMode::custom([ -1903 /// "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?, -1904 /// "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?, -1905 /// ]); -1906 /// # Ok(()) } -1907 /// ``` -1908 pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self { -1909 let m = RelayMap::from_iter(map); -1910 Self::Custom(m) -1911 } -1912} -1913 -1914/// Environment variable to force the use of staging relays. -1915pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; -1916 -1917/// Returns `true` if the use of staging relays is forced. -1918pub fn force_staging_infra() -> bool { -1919 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) -1920} -1921 -1922/// Returns the default relay mode. -1923/// -1924/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. -1925/// Otherwise, it will return `RelayMode::Default`. -1926pub fn default_relay_mode() -> RelayMode { -1927 // Use staging in testing -1928 match force_staging_infra() { -1929 true => RelayMode::Staging, -1930 false => RelayMode::Default, -1931 } -1932} -1933 -1934/// Check if we are being executed in a CGI context. -1935/// -1936/// If so, a malicious client can send the `Proxy:` header, and it will -1937/// be in the `HTTP_PROXY` env var. So we don't use it :) -1938fn is_cgi() -> bool { -1939 std::env::var_os("REQUEST_METHOD").is_some() -1940} -1941 -1942#[cfg(all(test, with_crypto_provider))] -1943mod tests { -1944 use std::{ -1945 collections::BTreeMap, -1946 io, -1947 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4}, -1948 str::FromStr, -1949 sync::Arc, -1950 time::{Duration, Instant}, -1951 }; -1952 -1953 use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; -1954 use iroh_dns::endpoint_info::UserData; -1955 use iroh_relay::{RelayConfig, server::Access, tls::CaTlsConfig}; -1956 use n0_error::{AnyError as Error, Result, StdResultExt}; -1957 use n0_future::{BufferedStreamExt, StreamExt, future::now_or_never, stream, time}; -1958 use n0_tracing_test::traced_test; -1959 use n0_watcher::Watcher; -1960 use noq::PathStats; -1961 use rand::{RngExt, SeedableRng}; -1962 use rand_chacha::ChaCha8Rng; -1963 use tokio::sync::oneshot; -1964 use tracing::{Instrument, debug_span, error_span, info, info_span, instrument}; -1965 -1966 use super::Endpoint; -1967 use crate::{ -1968 RelayMap, RelayMode, -1969 address_lookup::memory::MemoryLookup, -1970 endpoint::{ -1971 ApplicationClose, BindError, BindOpts, ConnectError, ConnectOptions, -1972 ConnectWithOptsError, Connection, ConnectionError, PathEvent, PathEventStream, presets, -1973 }, -1974 protocol::{AcceptError, ProtocolHandler, Router}, -1975 test_utils::{ -1976 QlogFileGroup, run_relay_server, run_relay_server_with, run_relay_server_with_access, -1977 }, -1978 }; -1979 -1980 const TEST_ALPN: &[u8] = b"n0/iroh/test"; -1981 -1982 #[tokio::test] -1983 #[traced_test] -1984 async fn test_connect_self() -> Result { -1985 let ep = Endpoint::builder(presets::Minimal) -1986 .alpns(vec![TEST_ALPN.to_vec()]) -1987 .bind() -1988 .await -1989 .unwrap(); -1990 let my_addr = ep.addr(); -1991 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; -1992 assert!(res.is_err()); -1993 let err = res.err().unwrap(); -1994 assert!(err.to_string().starts_with("Connecting to ourself")); -1995 -1996 Ok(()) -1997 } -1998 -1999 #[tokio::test] -2000 #[traced_test] -2001 async fn endpoint_connect_close() -> Result { -2002 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2003 let (relay_map, relay_url, _guard) = run_relay_server().await?; -2004 let server_secret_key = SecretKey::from_bytes(&rng.random()); -2005 let server_peer_id = server_secret_key.public(); -2006 -2007 let qlog = QlogFileGroup::from_env("endpoint_connect_close"); -2008 -2009 // Wait for the endpoint to be started to make sure it's up before clients try to connect -2010 let ep = Endpoint::builder(presets::Minimal) -2011 .relay_mode(RelayMode::Custom(relay_map.clone())) -2012 .secret_key(server_secret_key) -2013 .transport_config(qlog.create("server")?) -2014 .alpns(vec![TEST_ALPN.to_vec()]) -2015 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2016 .bind() -2017 .await?; -2018 // Wait for the endpoint to be reachable via relay -2019 ep.online().await; -2020 -2021 let server = tokio::spawn( -2022 async move { -2023 info!("accepting connection"); -2024 let incoming = ep.accept().await.anyerr()?; -2025 let conn = incoming.await.anyerr()?; -2026 let mut stream = conn.accept_uni().await.anyerr()?; -2027 let mut buf = [0u8; 5]; -2028 stream.read_exact(&mut buf).await.anyerr()?; -2029 info!("Accepted 1 stream, received {buf:?}. Closing now."); -2030 // close the connection -2031 conn.close(7u8.into(), b"bye"); -2032 -2033 let res = conn.accept_uni().await; -2034 assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed); -2035 -2036 let res = stream.read_to_end(10).await; -2037 assert_eq!( -2038 res.unwrap_err(), -2039 noq::ReadToEndError::Read(noq::ReadError::ConnectionLost( -2040 ConnectionError::LocallyClosed -2041 )) -2042 ); -2043 info!("Closing the endpoint"); -2044 ep.close().await; -2045 info!("server test completed"); -2046 Ok::<_, Error>(()) -2047 } -2048 .instrument(info_span!("test-server")), -2049 ); -2050 -2051 let client = tokio::spawn( -2052 async move { -2053 let ep = Endpoint::builder(presets::Minimal) -2054 .relay_mode(RelayMode::Custom(relay_map)) -2055 .alpns(vec![TEST_ALPN.to_vec()]) -2056 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2057 .transport_config(qlog.create("client")?) -2058 .bind() -2059 .await?; -2060 info!("client connecting"); -2061 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); -2062 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; -2063 let mut stream = conn.open_uni().await.anyerr()?; -2064 -2065 // First write is accepted by server. We need this bit of synchronisation -2066 // because if the server closes after simply accepting the connection we can -2067 // not be sure our .open_uni() call would succeed as it may already receive -2068 // the error. -2069 stream.write_all(b"hello").await.anyerr()?; -2070 -2071 info!("waiting for closed"); -2072 // Remote now closes the connection, we should see an error sometime soon. -2073 let err = conn.closed().await; -2074 let expected_err = ConnectionError::ApplicationClosed(ApplicationClose { -2075 error_code: 7u8.into(), -2076 reason: b"bye".to_vec().into(), -2077 }); -2078 assert_eq!(err, expected_err); -2079 -2080 info!("opening new - expect it to fail"); -2081 let res = conn.open_uni().await; -2082 assert_eq!(res.unwrap_err(), expected_err); -2083 info!("Closing the client"); -2084 ep.close().await; -2085 info!("client test completed"); -2086 Ok::<_, Error>(()) -2087 } -2088 .instrument(info_span!("test-client")), -2089 ); -2090 -2091 let (server, client) = tokio::time::timeout( -2092 Duration::from_secs(30), -2093 n0_future::future::zip(server, client), -2094 ) -2095 .await -2096 .anyerr()?; -2097 server.anyerr()??; -2098 client.anyerr()??; -2099 Ok(()) -2100 } -2101 -2102 #[tokio::test] -2103 #[traced_test] -2104 async fn endpoint_relay_connect_loop() -> Result { -2105 let test_start = Instant::now(); -2106 let n_clients = 5; -2107 let n_chunks_per_client = 2; -2108 let chunk_size = 100; -2109 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); -2110 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); -2111 let server_secret_key = SecretKey::from_bytes(&rng.random()); -2112 let server_endpoint_id = server_secret_key.public(); -2113 -2114 // Make sure the server is bound before having clients connect to it: -2115 let ep = Endpoint::builder(presets::Minimal) -2116 .relay_mode(RelayMode::Custom(relay_map.clone())) -2117 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2118 .secret_key(server_secret_key) -2119 .alpns(vec![TEST_ALPN.to_vec()]) -2120 .bind() -2121 .await?; -2122 // Also make sure the server has a working relay connection -2123 ep.online().await; -2124 -2125 info!(time = ?test_start.elapsed(), "test setup done"); -2126 -2127 // The server accepts the connections of the clients sequentially. -2128 let server = tokio::spawn( -2129 async move { -2130 let eps = ep.bound_sockets(); -2131 -2132 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); -2133 for i in 0..n_clients { -2134 let res = tokio::time::timeout(Duration::from_secs(5), async { -2135 let round_start = Instant::now(); -2136 info!("[server] round {i}"); -2137 let incoming = ep.accept().await.anyerr()?; -2138 let conn = incoming.await.anyerr()?; -2139 let endpoint_id = conn.remote_id(); -2140 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); -2141 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2142 let mut buf = vec![0u8; chunk_size]; -2143 for _i in 0..n_chunks_per_client { -2144 recv.read_exact(&mut buf).await.anyerr()?; -2145 send.write_all(&buf).await.anyerr()?; -2146 } -2147 info!(%i, peer = %endpoint_id.fmt_short(), "finishing"); -2148 send.finish().anyerr()?; -2149 conn.closed().await; // we're the last to send data, so we wait for the other side to close -2150 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); -2151 info!("[server] round {i} done in {:?}", round_start.elapsed()); -2152 Ok::<_, Error>(()) -2153 }) -2154 .await -2155 .std_context("timeout"); -2156 match res { -2157 Err(err) | Ok(Err(err)) => { -2158 // ensure we close the endpoint before returning early -2159 // on error -2160 ep.close().await; -2161 return Err(err); -2162 } -2163 _ => { -2164 // if this round went `Ok` don't close the endpoint yet -2165 } -2166 } -2167 } -2168 // close the endpoint before dropping the server task -2169 ep.close().await; -2170 Ok::<_, Error>(()) -2171 } -2172 .instrument(debug_span!("server")), -2173 ); -2174 -2175 let client = tokio::spawn(async move { -2176 for i in 0..n_clients { -2177 let round_start = Instant::now(); -2178 info!("[client] round {i}"); -2179 let client_secret_key = SecretKey::from_bytes(&rng.random()); -2180 let ep = Endpoint::builder(presets::Minimal) -2181 .relay_mode(RelayMode::Custom(relay_map.clone())) -2182 .alpns(vec![TEST_ALPN.to_vec()]) -2183 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2184 .secret_key(client_secret_key) -2185 .bind() -2186 .await?; -2187 let ep_1 = ep.clone(); -2188 let res = tokio::time::timeout( -2189 Duration::from_secs(5), -2190 async { -2191 info!("client binding"); -2192 let eps = ep.bound_sockets(); -2193 -2194 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); -2195 let endpoint_addr = -2196 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); -2197 info!(to = ?endpoint_addr, "client connecting"); -2198 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; -2199 info!("client connected"); -2200 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2201 -2202 for i in 0..n_chunks_per_client { -2203 let mut buf = vec![i; chunk_size]; -2204 send.write_all(&buf).await.anyerr()?; -2205 recv.read_exact(&mut buf).await.anyerr()?; -2206 assert_eq!(buf, vec![i; chunk_size]); -2207 } -2208 // we're the last to receive data, so we close -2209 conn.close(0u32.into(), b"bye!"); -2210 info!("client finished"); -2211 Ok::<_, Error>(()) -2212 } -2213 .instrument(debug_span!("client", %i)), -2214 ) -2215 .await -2216 .std_context("timeout"); -2217 ep_1.close().await; -2218 info!("client endpoint closed"); -2219 res??; -2220 info!("[client] round {i} done in {:?}", round_start.elapsed()); -2221 } -2222 Ok::<_, Error>(()) -2223 }); -2224 -2225 server.await.anyerr()??; -2226 client.await.anyerr()??; -2227 Ok(()) -2228 } -2229 -2230 #[tokio::test] -2231 #[traced_test] -2232 async fn endpoint_send_relay() -> Result { -2233 let (relay_map, _relay_url, _guard) = run_relay_server().await?; -2234 let client = Endpoint::builder(presets::Minimal) -2235 .relay_mode(RelayMode::Custom(relay_map.clone())) -2236 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2237 .bind() -2238 .await?; -2239 let server = Endpoint::builder(presets::Minimal) -2240 .relay_mode(RelayMode::Custom(relay_map)) -2241 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2242 .alpns(vec![TEST_ALPN.to_vec()]) -2243 .bind() -2244 .await?; -2245 -2246 let task = tokio::spawn({ -2247 let server = server.clone(); -2248 async move { -2249 let Some(conn) = server.accept().await else { -2250 n0_error::bail_any!("Expected an incoming connection"); -2251 }; -2252 let conn = conn.await.anyerr()?; -2253 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2254 let data = recv.read_to_end(1000).await.anyerr()?; -2255 send.write_all(&data).await.anyerr()?; -2256 send.finish().anyerr()?; -2257 conn.closed().await; -2258 -2259 Ok::<_, Error>(()) -2260 } -2261 }); -2262 -2263 let addr = server.addr(); -2264 let conn = client.connect(addr, TEST_ALPN).await?; -2265 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2266 send.write_all(b"Hello, world!").await.anyerr()?; -2267 send.finish().anyerr()?; -2268 let data = recv.read_to_end(1000).await.anyerr()?; -2269 conn.close(0u32.into(), b"bye!"); -2270 -2271 task.await.anyerr()??; -2272 -2273 client.close().await; -2274 server.close().await; -2275 -2276 assert_eq!(&data, b"Hello, world!"); -2277 -2278 Ok(()) -2279 } -2280 -2281 #[tokio::test] -2282 #[traced_test] -2283 async fn endpoint_two_direct_only() -> Result { -2284 // Connect two endpoints on the same network, without a relay server, without -2285 // Address Lookup. -2286 let ep1 = { -2287 let span = info_span!("server"); -2288 let _guard = span.enter(); -2289 Endpoint::builder(presets::N0) -2290 .alpns(vec![TEST_ALPN.to_vec()]) -2291 .relay_mode(RelayMode::Disabled) -2292 .bind() -2293 .await? -2294 }; -2295 let ep2 = { -2296 let span = info_span!("client"); -2297 let _guard = span.enter(); -2298 Endpoint::builder(presets::N0) -2299 .alpns(vec![TEST_ALPN.to_vec()]) -2300 .relay_mode(RelayMode::Disabled) -2301 .bind() -2302 .await? -2303 }; -2304 let ep1_nodeaddr = ep1.addr(); -2305 -2306 #[instrument(name = "client", skip_all)] -2307 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> { -2308 info!(me = %ep.id().fmt_short(), "client starting"); -2309 let conn = ep.connect(dst, TEST_ALPN).await?; -2310 let mut send = conn.open_uni().await.anyerr()?; -2311 send.write_all(b"hello").await.anyerr()?; -2312 send.finish().anyerr()?; -2313 Ok(conn.closed().await) -2314 } -2315 -2316 #[instrument(name = "server", skip_all)] -2317 async fn accept(ep: Endpoint, src: EndpointId) -> Result { -2318 info!(me = %ep.id().fmt_short(), "server starting"); -2319 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2320 let node_id = conn.remote_id(); -2321 assert_eq!(node_id, src); -2322 let mut recv = conn.accept_uni().await.anyerr()?; -2323 let msg = recv.read_to_end(100).await.anyerr()?; -2324 assert_eq!(msg, b"hello"); -2325 // Dropping the connection closes it just fine. -2326 Ok(()) -2327 } -2328 -2329 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); -2330 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); -2331 -2332 ep1_accept.await.anyerr()??; -2333 let conn_closed = dbg!(ep2_connect.await.anyerr()??); -2334 assert!(matches!( -2335 conn_closed, -2336 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2337 )); -2338 -2339 Ok(()) -2340 } -2341 -2342 #[tokio::test] -2343 #[traced_test] -2344 async fn endpoint_two_relay_only_becomes_direct() -> Result { -2345 // Connect two endpoints on the same network, via a relay server, without -2346 // Address Lookup. Wait until there is a direct connection. -2347 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -2348 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -2349 let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct")); -2350 -2351 #[instrument(name = "client", skip_all)] -2352 async fn connect( -2353 relay_map: RelayMap, -2354 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2355 qlog: Arc<QlogFileGroup>, -2356 ) -> Result<ConnectionError> { -2357 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2358 let secret = SecretKey::from_bytes(&rng.random()); -2359 let ep = Endpoint::builder(presets::N0) -2360 .secret_key(secret) -2361 .alpns(vec![TEST_ALPN.to_vec()]) -2362 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2363 .relay_mode(RelayMode::Custom(relay_map)) -2364 .transport_config(qlog.create("client")?) -2365 .bind() -2366 .await?; -2367 info!(me = %ep.id().fmt_short(), "client starting"); -2368 let dst = node_addr_rx.await.anyerr()?; -2369 -2370 info!(me = %ep.id().fmt_short(), "client connecting"); -2371 let conn = ep.connect(dst, TEST_ALPN).await?; -2372 let mut send = conn.open_uni().await.anyerr()?; -2373 send.write_all(b"hello").await.anyerr()?; -2374 let mut paths = conn.paths_stream(); -2375 info!("Waiting for direct connection"); -2376 while let Some(infos) = paths.next().await { -2377 info!(?infos, "new PathInfos"); -2378 if infos.iter().any(|info| info.is_ip()) { -2379 break; -2380 } -2381 } -2382 info!("Have direct connection"); -2383 #[cfg(feature = "metrics")] -2384 { -2385 // Validate holepunch metrics. -2386 assert_eq!(ep.metrics().socket.num_conns_opened.get(), 1); -2387 assert_eq!(ep.metrics().socket.num_conns_direct.get(), 1); -2388 } -2389 -2390 send.write_all(b"close please").await.anyerr()?; -2391 send.finish().anyerr()?; -2392 -2393 let res = conn.closed().await; -2394 ep.close().await; -2395 Ok(res) -2396 } -2397 -2398 #[instrument(name = "server", skip_all)] -2399 async fn accept( -2400 relay_map: RelayMap, -2401 node_addr_tx: oneshot::Sender<EndpointAddr>, -2402 qlog: Arc<QlogFileGroup>, -2403 ) -> Result { -2404 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -2405 let secret = SecretKey::from_bytes(&rng.random()); -2406 let ep = Endpoint::builder(presets::N0) -2407 .secret_key(secret) -2408 .alpns(vec![TEST_ALPN.to_vec()]) -2409 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2410 .transport_config(qlog.create("server")?) -2411 .relay_mode(RelayMode::Custom(relay_map)) -2412 .bind() -2413 .await?; -2414 ep.online().await; -2415 let mut node_addr = ep.addr(); -2416 node_addr.addrs.retain(|addr| addr.is_relay()); -2417 node_addr_tx.send(node_addr).unwrap(); -2418 -2419 info!(me = %ep.id().fmt_short(), "server starting"); -2420 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2421 // let node_id = conn.remote_node_id()?; -2422 // assert_eq!(node_id, src); -2423 let mut recv = conn.accept_uni().await.anyerr()?; -2424 let mut msg = [0u8; 5]; -2425 recv.read_exact(&mut msg).await.anyerr()?; -2426 assert_eq!(&msg, b"hello"); -2427 info!("received hello"); -2428 let msg = recv.read_to_end(100).await.anyerr()?; -2429 assert_eq!(msg, b"close please"); -2430 info!("received 'close please'"); -2431 // Closing the endpoint closes all connections. -2432 ep.close().await; -2433 Ok(()) -2434 } -2435 -2436 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone())); -2437 let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog)); -2438 -2439 server_task.await.anyerr()??; -2440 let conn_closed = dbg!(client_task.await.anyerr()??); -2441 assert!(matches!( -2442 conn_closed, -2443 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2444 )); -2445 -2446 Ok(()) -2447 } -2448 -2449 #[tokio::test] -2450 #[traced_test] -2451 async fn endpoint_two_relay_only_no_ip() -> Result { -2452 // Connect two endpoints on the same network, via a relay server, without -2453 // Address Lookup. -2454 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -2455 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -2456 -2457 #[instrument(name = "client", skip_all)] -2458 async fn connect( -2459 relay_map: RelayMap, -2460 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2461 ) -> Result<ConnectionError> { -2462 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2463 let secret = SecretKey::from_bytes(&rng.random()); -2464 let ep = Endpoint::builder(presets::N0) -2465 .secret_key(secret) -2466 .alpns(vec![TEST_ALPN.to_vec()]) -2467 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2468 .relay_mode(RelayMode::Custom(relay_map)) -2469 .clear_ip_transports() // disable direct -2470 .bind() -2471 .await?; -2472 info!(me = %ep.id().fmt_short(), "client starting"); -2473 let dst = node_addr_rx.await.anyerr()?; -2474 -2475 info!(me = %ep.id().fmt_short(), "client connecting"); -2476 let conn = ep.connect(dst, TEST_ALPN).await?; -2477 let mut send = conn.open_uni().await.anyerr()?; -2478 send.write_all(b"hello").await.anyerr()?; -2479 let mut paths = conn.paths_stream(); -2480 info!("Waiting for connection"); -2481 'outer: while let Some(infos) = paths.next().await { -2482 info!(?infos, "new PathInfos"); -2483 for info in infos.iter() { -2484 if info.is_ip() { -2485 panic!("should not happen: {:?}", info); -2486 } -2487 if info.is_relay() { -2488 break 'outer; -2489 } -2490 } -2491 } -2492 info!("Have relay connection"); -2493 -2494 send.write_all(b"close please").await.anyerr()?; -2495 send.finish().anyerr()?; -2496 let res = conn.closed().await; -2497 ep.close().await; -2498 Ok(res) -2499 } -2500 -2501 #[instrument(name = "server", skip_all)] -2502 async fn accept( -2503 relay_map: RelayMap, -2504 node_addr_tx: oneshot::Sender<EndpointAddr>, -2505 ) -> Result { -2506 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -2507 let secret = SecretKey::from_bytes(&rng.random()); -2508 let ep = Endpoint::builder(presets::N0) -2509 .secret_key(secret) -2510 .alpns(vec![TEST_ALPN.to_vec()]) -2511 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2512 .relay_mode(RelayMode::Custom(relay_map)) -2513 .clear_ip_transports() -2514 .bind() -2515 .await?; -2516 ep.online().await; -2517 let node_addr = ep.addr(); -2518 node_addr_tx.send(node_addr).unwrap(); -2519 -2520 info!(me = %ep.id().fmt_short(), "server starting"); -2521 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2522 // let node_id = conn.remote_node_id()?; -2523 // assert_eq!(node_id, src); -2524 let mut recv = conn.accept_uni().await.anyerr()?; -2525 let mut msg = [0u8; 5]; -2526 recv.read_exact(&mut msg).await.anyerr()?; -2527 assert_eq!(&msg, b"hello"); -2528 info!("received hello"); -2529 let msg = recv.read_to_end(100).await.anyerr()?; -2530 assert_eq!(msg, b"close please"); -2531 info!("received 'close please'"); -2532 // Closing the endpoint closes all connections. -2533 ep.close().await; -2534 Ok(()) -2535 } -2536 -2537 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -2538 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -2539 -2540 server_task.await.anyerr()??; -2541 let conn_closed = dbg!(client_task.await.anyerr()??); -2542 assert!(matches!( -2543 conn_closed, -2544 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2545 )); -2546 -2547 Ok(()) -2548 } -2549 -2550 #[tokio::test] -2551 #[traced_test] -2552 async fn endpoint_two_direct_add_relay() -> Result { -2553 // Connect two endpoints on the same network, without relay server and without -2554 // Address Lookup. Add a relay connection later. -2555 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -2556 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -2557 -2558 #[instrument(name = "client", skip_all)] -2559 async fn connect( -2560 relay_map: RelayMap, -2561 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2562 ) -> Result<()> { -2563 let secret = SecretKey::from([0u8; 32]); -2564 let ep = Endpoint::builder(presets::N0) -2565 .secret_key(secret) -2566 .alpns(vec![TEST_ALPN.to_vec()]) -2567 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2568 .relay_mode(RelayMode::Custom(relay_map)) -2569 .bind() -2570 .await?; -2571 info!(me = %ep.id().fmt_short(), "client starting"); -2572 let dst = node_addr_rx.await.anyerr()?; -2573 -2574 info!(me = %ep.id().fmt_short(), "client connecting"); -2575 let conn = ep.connect(dst, TEST_ALPN).await?; -2576 info!(me = %ep.id().fmt_short(), "client connected"); -2577 -2578 // We should be connected via IP, because it is faster than the relay server. -2579 // TODO: Maybe not panic if this is not true? -2580 -2581 let path_info = conn.paths(); -2582 assert_eq!(path_info.len(), 1); -2583 assert!(path_info.iter().next().unwrap().is_ip()); -2584 -2585 let mut paths = conn.paths_stream(); -2586 time::timeout(Duration::from_secs(5), async move { -2587 while let Some(infos) = paths.next().await { -2588 info!(?infos, "new PathInfos"); -2589 if infos.iter().any(|info| info.is_relay()) { -2590 info!("client has a relay path"); -2591 break; -2592 } -2593 } -2594 }) -2595 .await -2596 .anyerr()?; -2597 -2598 // wait for the server to signal it has the relay connection -2599 let mut stream = conn.accept_uni().await.anyerr()?; -2600 stream.read_to_end(100).await.anyerr()?; -2601 -2602 info!("client closing"); -2603 conn.close(0u8.into(), b""); -2604 ep.close().await; -2605 Ok(()) -2606 } -2607 -2608 #[instrument(name = "server", skip_all)] -2609 async fn accept( -2610 relay_map: RelayMap, -2611 node_addr_tx: oneshot::Sender<EndpointAddr>, -2612 ) -> Result<ConnectionError> { -2613 let secret = SecretKey::from([1u8; 32]); -2614 let ep = Endpoint::builder(presets::N0) -2615 .secret_key(secret) -2616 .alpns(vec![TEST_ALPN.to_vec()]) -2617 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2618 .relay_mode(RelayMode::Custom(relay_map)) -2619 .bind() -2620 .await?; -2621 ep.online().await; -2622 let node_addr = ep.addr(); -2623 node_addr_tx.send(node_addr).unwrap(); -2624 -2625 info!(me = %ep.id().fmt_short(), "server starting"); -2626 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2627 info!(me = %ep.id().fmt_short(), "server accepted connection"); -2628 -2629 // Wait for a relay connection to be added. Client does all the asserting here, -2630 // we just want to wait so we get to see all the mechanics of the connection -2631 // being added on this side too. -2632 let mut paths = conn.paths_stream(); -2633 time::timeout(Duration::from_secs(5), async move { -2634 while let Some(infos) = paths.next().await { -2635 info!(?infos, "new PathInfos"); -2636 if infos.iter().any(|path| path.is_relay()) { -2637 info!("server has a relay path"); -2638 break; -2639 } -2640 } -2641 }) -2642 .await -2643 .anyerr()?; -2644 -2645 let mut stream = conn.open_uni().await.anyerr()?; -2646 stream.write_all(b"have relay").await.anyerr()?; -2647 stream.finish().anyerr()?; -2648 info!("waiting conn.closed()"); -2649 -2650 Ok(conn.closed().await) -2651 } -2652 -2653 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -2654 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -2655 -2656 client_task.await.anyerr()??; -2657 let conn_closed = dbg!(server_task.await.anyerr()??); -2658 assert!(matches!( -2659 conn_closed, -2660 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2661 )); -2662 -2663 Ok(()) -2664 } -2665 -2666 #[tokio::test] -2667 #[traced_test] -2668 async fn endpoint_relay_map_change() -> Result { -2669 let (relay_map, relay_url, _guard1) = run_relay_server().await?; -2670 let client = Endpoint::builder(presets::Minimal) -2671 .relay_mode(RelayMode::Custom(relay_map.clone())) -2672 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2673 .bind() -2674 .await?; -2675 let server = Endpoint::builder(presets::Minimal) -2676 .relay_mode(RelayMode::Custom(relay_map)) -2677 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2678 .alpns(vec![TEST_ALPN.to_vec()]) -2679 .bind() -2680 .await?; -2681 -2682 let task = tokio::spawn({ -2683 let server = server.clone(); -2684 async move { -2685 for i in 0..2 { -2686 println!("accept: round {i}"); -2687 let Some(conn) = server.accept().await else { -2688 n0_error::bail_any!("Expected an incoming connection"); -2689 }; -2690 let conn = conn.await.anyerr()?; -2691 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2692 let data = recv.read_to_end(1000).await.anyerr()?; -2693 send.write_all(&data).await.anyerr()?; -2694 send.finish().anyerr()?; -2695 conn.closed().await; -2696 } -2697 Ok::<_, Error>(()) -2698 } -2699 }); -2700 -2701 server.online().await; -2702 -2703 let mut addr = server.addr(); -2704 println!("round1: {:?}", addr); -2705 -2706 // remove direct addrs to force relay usage -2707 addr.addrs -2708 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2709 -2710 let conn = client.connect(addr, TEST_ALPN).await?; -2711 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2712 send.write_all(b"Hello, world!").await.anyerr()?; -2713 send.finish().anyerr()?; -2714 let data = recv.read_to_end(1000).await.anyerr()?; -2715 conn.close(0u32.into(), b"bye!"); -2716 -2717 assert_eq!(&data, b"Hello, world!"); -2718 -2719 // setup a second relay server -2720 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; -2721 let new_endpoint = new_relay_map -2722 .get(&new_relay_url) -2723 .expect("missing endpoint") -2724 .clone(); -2725 dbg!(&new_relay_map); -2726 -2727 let addr_watcher = server.watch_addr(); -2728 -2729 // add new new relay -2730 assert!( -2731 server -2732 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) -2733 .await -2734 .is_none() -2735 ); -2736 // remove the old relay -2737 assert!(server.remove_relay(&relay_url).await.is_some()); -2738 -2739 println!("------- changed ----- "); -2740 -2741 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { -2742 let mut stream = addr_watcher.stream(); -2743 while let Some(addr) = stream.next().await { -2744 if addr.relay_urls().next() != Some(&relay_url) { -2745 return addr; -2746 } -2747 } -2748 panic!("failed to change relay"); -2749 }) -2750 .await -2751 .anyerr()?; -2752 -2753 println!("round2: {:?}", addr); -2754 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); -2755 -2756 // remove direct addrs to force relay usage -2757 addr.addrs -2758 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2759 -2760 let conn = client.connect(addr, TEST_ALPN).await?; -2761 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2762 send.write_all(b"Hello, world!").await.anyerr()?; -2763 send.finish().anyerr()?; -2764 let data = recv.read_to_end(1000).await.anyerr()?; -2765 conn.close(0u32.into(), b"bye!"); -2766 -2767 task.await.anyerr()??; -2768 -2769 client.close().await; -2770 server.close().await; -2771 -2772 assert_eq!(&data, b"Hello, world!"); -2773 -2774 Ok(()) -2775 } -2776 -2777 #[tokio::test] -2778 #[traced_test] -2779 async fn endpoint_bidi_send_recv() -> Result { -2780 let disco = MemoryLookup::new(); -2781 let ep1 = Endpoint::builder(presets::Minimal) -2782 .address_lookup(disco.clone()) -2783 .alpns(vec![TEST_ALPN.to_vec()]) -2784 .bind() -2785 .await?; -2786 -2787 let ep2 = Endpoint::builder(presets::Minimal) -2788 .address_lookup(disco.clone()) -2789 .alpns(vec![TEST_ALPN.to_vec()]) -2790 .bind() -2791 .await?; -2792 -2793 disco.add_endpoint_info(ep1.addr()); -2794 disco.add_endpoint_info(ep2.addr()); -2795 -2796 let ep1_endpointid = ep1.id(); -2797 let ep2_endpointid = ep2.id(); -2798 eprintln!("endpoint id 1 {ep1_endpointid}"); -2799 eprintln!("endpoint id 2 {ep2_endpointid}"); -2800 -2801 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { -2802 let conn = ep.connect(dst, TEST_ALPN).await?; -2803 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2804 info!("sending hello"); -2805 send.write_all(b"hello").await.anyerr()?; -2806 send.finish().anyerr()?; -2807 info!("receiving world"); -2808 let m = recv.read_to_end(100).await.anyerr()?; -2809 assert_eq!(m, b"world"); -2810 conn.close(1u8.into(), b"done"); -2811 Ok(()) -2812 } -2813 -2814 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { -2815 let incoming = ep.accept().await.anyerr()?; -2816 let mut iconn = incoming.accept().anyerr()?; -2817 let alpn = iconn.alpn().await?; -2818 let conn = iconn.await.anyerr()?; -2819 let endpoint_id = conn.remote_id(); -2820 assert_eq!(endpoint_id, src); -2821 assert_eq!(alpn, TEST_ALPN); -2822 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2823 info!("receiving hello"); -2824 let m = recv.read_to_end(100).await.anyerr()?; -2825 assert_eq!(m, b"hello"); -2826 info!("sending hello"); -2827 send.write_all(b"world").await.anyerr()?; -2828 send.finish().anyerr()?; -2829 match conn.closed().await { -2830 ConnectionError::ApplicationClosed(closed) => { -2831 assert_eq!(closed.error_code, 1u8.into()); -2832 Ok(()) -2833 } -2834 _ => panic!("wrong close error"), -2835 } -2836 } -2837 -2838 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( -2839 info_span!( -2840 "p1_accept", -2841 ep1 = %ep1.id().fmt_short(), -2842 dst = %ep2_endpointid.fmt_short(), -2843 ), -2844 )); -2845 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( -2846 info_span!( -2847 "p2_accept", -2848 ep2 = %ep2.id().fmt_short(), -2849 dst = %ep1_endpointid.fmt_short(), -2850 ), -2851 )); -2852 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( -2853 info_span!( -2854 "p1_connect", -2855 ep1 = %ep1.id().fmt_short(), -2856 dst = %ep2_endpointid.fmt_short(), -2857 ), -2858 )); -2859 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( -2860 info_span!( -2861 "p2_connect", -2862 ep2 = %ep2.id().fmt_short(), -2863 dst = %ep1_endpointid.fmt_short(), -2864 ), -2865 )); -2866 -2867 p1_accept.await.anyerr()??; -2868 p2_accept.await.anyerr()??; -2869 p1_connect.await.anyerr()??; -2870 p2_connect.await.anyerr()??; -2871 -2872 Ok(()) -2873 } -2874 -2875 #[tokio::test] -2876 #[traced_test] -2877 async fn test_direct_addresses_no_qad_relay() -> Result { -2878 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); -2879 -2880 let ep = Endpoint::builder(presets::Minimal) -2881 .relay_mode(RelayMode::Custom(relay_map)) -2882 .alpns(vec![TEST_ALPN.to_vec()]) -2883 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -2884 .bind() -2885 .await?; -2886 -2887 assert!(ep.addr().ip_addrs().count() > 0); -2888 -2889 Ok(()) -2890 } -2891 -2892 /// Test that configured external addresses are included in the endpoint's -2893 /// direct addresses, both when set via builder and at runtime. -2894 #[tokio::test(flavor = "current_thread", start_paused = true)] -2895 #[traced_test] -2896 async fn test_external_addr() -> Result { -2897 let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345)); -2898 -2899 // Test builder-configured external address -2900 let ep = Endpoint::builder(presets::Minimal) -2901 .external_addr(configured_addr) -2902 .bind() -2903 .await?; -2904 -2905 let addr = ep.addr(); -2906 assert!( -2907 addr.ip_addrs().any(|a| *a == configured_addr), -2908 "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}" -2909 ); -2910 -2911 // Test runtime add -2912 let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321)); -2913 ep.add_external_addr(runtime_addr).await; -2914 tokio::time::sleep(Duration::from_millis(100)).await; -2915 -2916 let addr = ep.addr(); -2917 assert!( -2918 addr.ip_addrs().any(|a| *a == runtime_addr), -2919 "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}" -2920 ); -2921 -2922 // Test runtime remove -2923 let removed = ep.remove_external_addr(&runtime_addr).await; -2924 assert!(removed); -2925 tokio::time::sleep(Duration::from_millis(100)).await; -2926 -2927 let addr = ep.addr(); -2928 assert!( -2929 !addr.ip_addrs().any(|a| *a == runtime_addr), -2930 "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}" -2931 ); -2932 assert!( -2933 addr.ip_addrs().any(|a| *a == configured_addr), -2934 "builder-configured external addr should still be present: {addr:?}" -2935 ); -2936 -2937 ep.close().await; -2938 Ok(()) -2939 } -2940 -2941 #[tokio::test] -2942 #[traced_test] -2943 async fn graceful_close() -> Result { -2944 let client = Endpoint::bind(presets::Minimal).await?; -2945 let server = Endpoint::builder(presets::Minimal) -2946 .alpns(vec![TEST_ALPN.to_vec()]) -2947 .bind() -2948 .await?; -2949 let server_addr = server.addr(); -2950 let server_task = tokio::spawn(async move { -2951 let incoming = server.accept().await.anyerr()?; -2952 let conn = incoming.await.anyerr()?; -2953 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2954 let msg = recv.read_to_end(1_000).await.anyerr()?; -2955 send.write_all(&msg).await.anyerr()?; -2956 send.finish().anyerr()?; -2957 let close_reason = conn.closed().await; -2958 Ok::<_, Error>(close_reason) -2959 }); -2960 -2961 let conn = client.connect(server_addr, TEST_ALPN).await?; -2962 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2963 send.write_all(b"Hello, world!").await.anyerr()?; -2964 send.finish().anyerr()?; -2965 recv.read_to_end(1_000).await.anyerr()?; -2966 conn.close(42u32.into(), b"thanks, bye!"); -2967 client.close().await; -2968 -2969 let close_err = server_task.await.anyerr()??; -2970 let ConnectionError::ApplicationClosed(app_close) = close_err else { -2971 panic!("Unexpected close reason: {close_err:?}"); -2972 }; -2973 -2974 assert_eq!(app_close.error_code, 42u32.into()); -2975 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); -2976 -2977 Ok(()) -2978 } -2979 -2980 #[cfg(feature = "metrics")] -2981 #[tokio::test] -2982 #[traced_test] -2983 async fn metrics_smoke() -> Result { -2984 use iroh_metrics::Registry; -2985 -2986 let secret_key = SecretKey::from_bytes(&[0u8; 32]); -2987 let client = Endpoint::builder(presets::Minimal) -2988 .secret_key(secret_key) -2989 .bind() -2990 .await?; -2991 let secret_key = SecretKey::from_bytes(&[1u8; 32]); -2992 let server = Endpoint::builder(presets::Minimal) -2993 .secret_key(secret_key) -2994 .alpns(vec![TEST_ALPN.to_vec()]) -2995 .bind() -2996 .await?; -2997 let server_addr = server.addr(); -2998 let server_task = tokio::task::spawn(async move { -2999 let conn = server.accept().await.anyerr()?.await.anyerr()?; -3000 let mut uni = conn.accept_uni().await.anyerr()?; -3001 uni.read_to_end(10).await.anyerr()?; -3002 drop(conn); -3003 Ok::<_, Error>(server) -3004 }); -3005 let conn = client.connect(server_addr, TEST_ALPN).await?; -3006 let mut uni = conn.open_uni().await.anyerr()?; -3007 uni.write_all(b"helloworld").await.anyerr()?; -3008 uni.finish().anyerr()?; -3009 conn.closed().await; -3010 drop(conn); -3011 let server = server_task.await.anyerr()??; -3012 -3013 let m = client.metrics(); -3014 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); -3015 // assert_eq!(m.socket.connection_became_direct.get(), 1); -3016 // assert_eq!(m.socket.connection_handshake_success.get(), 1); -3017 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); -3018 assert!(m.socket.recv_datagrams.get() > 0); -3019 -3020 let m = server.metrics(); -3021 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); -3022 // assert_eq!(m.socket.connection_became_direct.get(), 1); -3023 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); -3024 // assert_eq!(m.socket.connection_handshake_success.get(), 1); -3025 assert!(m.socket.recv_datagrams.get() > 0); -3026 -3027 // test openmetrics encoding with labeled subregistries per endpoint -3028 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { -3029 let id = endpoint.id().fmt_short(); -3030 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); -3031 sub_registry.register_all(endpoint.metrics()); -3032 } -3033 let mut registry = Registry::default(); -3034 register_endpoint(&mut registry, &client); -3035 register_endpoint(&mut registry, &server); -3036 // let s = registry.encode_openmetrics_to_string().anyerr()?; -3037 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); -3038 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); -3039 Ok(()) -3040 } -3041 -3042 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` -3043 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. -3044 async fn alpn_connection_test( -3045 accept_alpns: Vec<Vec<u8>>, -3046 primary_connect_alpn: &[u8], -3047 secondary_connect_alpns: Vec<Vec<u8>>, -3048 ) -> Result<Vec<u8>> { -3049 let client = Endpoint::bind(presets::Minimal).await?; -3050 let server = Endpoint::builder(presets::Minimal) -3051 .alpns(accept_alpns) -3052 .bind() -3053 .await?; -3054 let server_addr = server.addr(); -3055 let server_task = tokio::spawn({ -3056 let server = server.clone(); -3057 async move { -3058 let incoming = server.accept().await.anyerr()?; -3059 let conn = incoming.await.anyerr()?; -3060 conn.close(0u32.into(), b"bye!"); -3061 n0_error::Ok(conn.alpn().to_vec()) -3062 } -3063 }); -3064 -3065 let conn = client -3066 .connect_with_opts( -3067 server_addr, -3068 primary_connect_alpn, -3069 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), -3070 ) -3071 .await?; -3072 let conn = conn.await.anyerr()?; -3073 let client_alpn = conn.alpn(); -3074 conn.closed().await; -3075 client.close().await; -3076 server.close().await; -3077 -3078 let server_alpn = server_task.await.anyerr()??; -3079 -3080 assert_eq!(client_alpn, server_alpn); -3081 -3082 Ok(server_alpn.to_vec()) -3083 } -3084 -3085 #[tokio::test] -3086 #[traced_test] -3087 async fn connect_multiple_alpn_negotiated() -> Result { -3088 const ALPN_ONE: &[u8] = b"alpn/1"; -3089 const ALPN_TWO: &[u8] = b"alpn/2"; -3090 -3091 assert_eq!( -3092 alpn_connection_test( -3093 // Prefer version 2 over version 1 on the accept side -3094 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3095 ALPN_TWO, -3096 vec![ALPN_ONE.to_vec()], -3097 ) -3098 .await?, -3099 ALPN_TWO.to_vec(), -3100 "accept side prefers version 2 over 1" -3101 ); -3102 -3103 assert_eq!( -3104 alpn_connection_test( -3105 // Only support the old version -3106 vec![ALPN_ONE.to_vec()], -3107 ALPN_TWO, -3108 vec![ALPN_ONE.to_vec()], -3109 ) -3110 .await?, -3111 ALPN_ONE.to_vec(), -3112 "accept side only supports the old version" -3113 ); -3114 -3115 assert_eq!( -3116 alpn_connection_test( -3117 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3118 ALPN_ONE, -3119 vec![ALPN_TWO.to_vec()], -3120 ) -3121 .await?, -3122 ALPN_TWO.to_vec(), -3123 "connect side ALPN order doesn't matter" -3124 ); -3125 -3126 assert_eq!( -3127 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) -3128 .await?, -3129 ALPN_ONE.to_vec(), -3130 "connect side only supports the old version" -3131 ); -3132 -3133 Ok(()) -3134 } -3135 -3136 #[tokio::test] -3137 #[traced_test] -3138 async fn watch_net_report() -> Result { -3139 let endpoint = Endpoint::builder(presets::Minimal) -3140 .relay_mode(RelayMode::Staging) -3141 .bind() -3142 .await?; -3143 -3144 // can get a first report -3145 endpoint.net_report().updated().await.anyerr()?; -3146 -3147 Ok(()) -3148 } -3149 -3150 /// Tests that initial connection establishment isn't extremely slow compared -3151 /// to subsequent connections. -3152 /// -3153 /// This is a time based test, but uses a very large ratio to reduce flakiness. -3154 /// It also does a number of connections to average out any anomalies. -3155 #[tokio::test] -3156 #[traced_test] -3157 async fn connect_multi_time() -> Result { -3158 let n = 32; -3159 -3160 const NOOP_ALPN: &[u8] = b"noop"; -3161 -3162 #[derive(Debug, Clone)] -3163 struct Noop; -3164 -3165 impl ProtocolHandler for Noop { -3166 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { -3167 connection.closed().await; -3168 Ok(()) -3169 } -3170 } -3171 -3172 async fn noop_server() -> Result<(Router, EndpointAddr)> { -3173 let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?; -3174 let addr = endpoint.addr(); -3175 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); -3176 Ok((router, addr)) -3177 } -3178 -3179 let routers = stream::iter(0..n) -3180 .map(|_| noop_server()) -3181 .buffered_unordered(32) -3182 .collect::<Vec<_>>() -3183 .await -3184 .into_iter() -3185 .collect::<Result<Vec<_>, _>>() -3186 .anyerr()?; -3187 -3188 let addrs = routers -3189 .iter() -3190 .map(|(_, addr)| addr.clone()) -3191 .collect::<Vec<_>>(); -3192 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); -3193 let address_lookup = MemoryLookup::from_endpoint_info(addrs); -3194 let endpoint = Endpoint::builder(presets::Minimal) -3195 .address_lookup(address_lookup) -3196 .bind() -3197 .await -3198 .anyerr()?; -3199 // wait for the endpoint to be initialized. This should not be needed, -3200 // but we don't want to measure endpoint init time but connection time -3201 // from a fully initialized endpoint. -3202 endpoint.addr(); -3203 let t0 = Instant::now(); -3204 for id in &ids { -3205 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -3206 conn.close(0u32.into(), b"done"); -3207 } -3208 let dt0 = t0.elapsed().as_secs_f64(); -3209 let t1 = Instant::now(); -3210 for id in &ids { -3211 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -3212 conn.close(0u32.into(), b"done"); -3213 } -3214 let dt1 = t1.elapsed().as_secs_f64(); -3215 -3216 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); -3217 Ok(()) -3218 } -3219 -3220 #[tokio::test] -3221 async fn test_custom_relay() -> Result { -3222 let _ep = Endpoint::builder(presets::Minimal) -3223 .relay_mode(RelayMode::custom([RelayUrl::from_str( -3224 "https://use1-1.relay.n0.iroh-canary.iroh.link.", -3225 )?])) -3226 .bind() -3227 .await?; -3228 -3229 let relays = RelayMap::try_from_iter([ -3230 "https://use1-1.relay.n0.iroh.iroh.link/", -3231 "https://euc1-1.relay.n0.iroh.iroh.link/", -3232 ])?; -3233 let _ep = Endpoint::builder(presets::Minimal) -3234 .relay_mode(RelayMode::Custom(relays)) -3235 .bind() -3236 .await?; -3237 -3238 Ok(()) -3239 } -3240 -3241 /// Testing bind_addr: Clear IP transports and add single IPv4 bind -3242 #[tokio::test] -3243 #[traced_test] -3244 async fn test_bind_addr_clear() -> Result { -3245 let ep = Endpoint::builder(presets::Minimal) -3246 .clear_ip_transports() -3247 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -3248 .bind() -3249 .await?; -3250 let bound_sockets = ep.bound_sockets(); -3251 assert_eq!(bound_sockets.len(), 1); -3252 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); -3253 ep.close().await; -3254 Ok(()) -3255 } -3256 -3257 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind -3258 /// -3259 /// This will bind two sockets: default wildcard bind for IPv6, and our -3260 /// manually-added IPv4 bind. -3261 #[tokio::test] -3262 #[traced_test] -3263 async fn test_bind_addr_no_clear() -> Result { -3264 let ep = Endpoint::builder(presets::Minimal) -3265 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -3266 .bind() -3267 .await?; -3268 let bound_sockets = ep.bound_sockets(); -3269 assert_eq!(bound_sockets.len(), 2); -3270 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); -3271 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3272 // Test that our manually added socket is there -3273 assert!( -3274 bound_sockets -3275 .iter() -3276 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3277 ); -3278 ep.close().await; -3279 Ok(()) -3280 } -3281 -3282 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. -3283 // -3284 // This replaces the default IPv4 bind added by the builder, -3285 // but keeps the default wildcard IPv6 bind. -3286 #[tokio::test] -3287 #[traced_test] -3288 async fn test_bind_addr_default() -> Result { -3289 let ep = Endpoint::builder(presets::Minimal) -3290 .bind_addr_with_opts( -3291 (Ipv4Addr::LOCALHOST, 0), -3292 BindOpts::default().set_is_default_route(true), -3293 )? -3294 .bind() -3295 .await?; -3296 let bound_sockets = ep.bound_sockets(); -3297 assert_eq!(bound_sockets.len(), 2); -3298 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); -3299 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3300 assert!( -3301 bound_sockets -3302 .iter() -3303 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3304 ); -3305 ep.close().await; -3306 drop(ep); -3307 -3308 Ok(()) -3309 } -3310 -3311 /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len -3312 /// -3313 /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our -3314 /// manually-added IPv4 bind. -3315 #[tokio::test] -3316 #[traced_test] -3317 async fn test_bind_addr_nonzero_prefix() -> Result { -3318 let ep = Endpoint::builder(presets::Minimal) -3319 .bind_addr_with_opts( -3320 (Ipv4Addr::LOCALHOST, 0), -3321 BindOpts::default().set_prefix_len(32), -3322 )? -3323 .bind() -3324 .await?; -3325 let bound_sockets = ep.bound_sockets(); -3326 assert_eq!(bound_sockets.len(), 3); -3327 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); -3328 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -3329 // Test that the default wildcard socket is there -3330 assert!( -3331 bound_sockets -3332 .iter() -3333 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) -3334 ); -3335 // Test that our manually added socket is there -3336 assert!( -3337 bound_sockets -3338 .iter() -3339 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3340 ); -3341 ep.close().await; -3342 Ok(()) -3343 } -3344 -3345 /// Bind on an unusable port with the default opts. -3346 /// -3347 /// Binding the endpoint fails with an AddrInUse error. -3348 #[tokio::test] -3349 #[traced_test] -3350 async fn test_bind_addr_badport() -> Result { -3351 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3352 let port = socket.local_addr()?.port(); -3353 -3354 let res = Endpoint::builder(presets::Minimal) -3355 .clear_ip_transports() -3356 .bind_addr((Ipv4Addr::LOCALHOST, port))? -3357 .bind() -3358 .await; -3359 -3360 assert!(matches!( -3361 res, -3362 Err(BindError::Sockets { -3363 source: io_error, -3364 .. -3365 }) -3366 if io_error.kind() == io::ErrorKind::AddrInUse -3367 )); -3368 Ok(()) -3369 } -3370 -3371 /// Bind a non-default route on an unusable port, but set is_required = false. -3372 /// -3373 /// Binding the endpoint succeeds. -3374 #[tokio::test] -3375 #[traced_test] -3376 async fn test_bind_addr_badport_notrequired() -> Result { -3377 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3378 let port = socket.local_addr()?.port(); -3379 -3380 let ep = Endpoint::builder(presets::Minimal) -3381 .bind_addr_with_opts( -3382 (Ipv4Addr::LOCALHOST, port), -3383 BindOpts::default() -3384 .set_prefix_len(32) -3385 .set_is_required(false), -3386 )? -3387 .bind() -3388 .await?; -3389 let bound_sockets = ep.bound_sockets(); -3390 // just the default wildcard binds -3391 assert_eq!(bound_sockets.len(), 2); -3392 // our requested bind addr is not included because it failed to bind -3393 assert!( -3394 !bound_sockets -3395 .iter() -3396 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3397 ); -3398 Ok(()) -3399 } -3400 -3401 /// Bind on a default route on an unusable port, but set is_required = false. -3402 /// -3403 /// Binding the endpoint succeeds. -3404 #[tokio::test] -3405 #[traced_test] -3406 async fn test_bind_addr_badport_default_notrequired() -> Result { -3407 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3408 let port = socket.local_addr()?.port(); -3409 -3410 let ep = Endpoint::builder(presets::Minimal) -3411 .bind_addr_with_opts( -3412 (Ipv4Addr::LOCALHOST, port), -3413 BindOpts::default().set_is_required(false), -3414 )? -3415 .bind() -3416 .await?; -3417 let bound_sockets = ep.bound_sockets(); -3418 // just the IPv6 default, but no IPv4 bind at all because we replaced the default -3419 // with a bind with an unusable port and set it to not be required. -3420 assert_eq!(bound_sockets.len(), 1); -3421 assert!(bound_sockets[0].is_ipv6()); -3422 Ok(()) -3423 } -3424 -3425 /// Bind on an unusable port, with is_required = false, and no other transports. -3426 /// -3427 /// Binding the endpoint fails with "no valid address available". -3428 #[tokio::test] -3429 #[traced_test] -3430 async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result { -3431 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -3432 let port = socket.local_addr()?.port(); -3433 -3434 let res = Endpoint::builder(presets::Minimal) -3435 .clear_ip_transports() -3436 .bind_addr_with_opts( -3437 (Ipv4Addr::LOCALHOST, port), -3438 BindOpts::default().set_is_required(false), -3439 )? -3440 .bind() -3441 .await; -3442 -3443 assert!(matches!( -3444 res, -3445 Err(BindError::CreateQuicEndpoint { -3446 source: io_error, -3447 .. -3448 }) -3449 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" -3450 )); -3451 Ok(()) -3452 } -3453 -3454 /// Bind with prefix len 0 but set the route as non-default. -3455 #[tokio::test] -3456 #[traced_test] -3457 async fn test_bind_addr_prefix_len_0_not_default() -> Result { -3458 let ep = Endpoint::builder(presets::Minimal) -3459 .bind_addr_with_opts( -3460 (Ipv4Addr::LOCALHOST, 0), -3461 BindOpts::default().set_is_default_route(false), -3462 )? -3463 .bind() -3464 .await?; -3465 let bound_sockets = ep.bound_sockets(); -3466 // The two default wildcard binds plus our additional route (which does not replace the default route -3467 // because we set is_default_route to false explicitly). -3468 assert_eq!(bound_sockets.len(), 3); -3469 assert!( -3470 bound_sockets -3471 .iter() -3472 .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED)) -3473 ); -3474 assert!( -3475 bound_sockets -3476 .iter() -3477 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) -3478 ); -3479 assert!( -3480 bound_sockets -3481 .iter() -3482 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -3483 ); -3484 Ok(()) -3485 } -3486 -3487 #[ignore = "flaky"] -3488 #[tokio::test] -3489 #[traced_test] -3490 async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result { -3491 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -3492 let qlog = Arc::new(QlogFileGroup::from_env( -3493 "connect_via_relay_becomes_direct_and_sends_direct", -3494 )); -3495 let transfer_size = 1_000_000; -3496 -3497 async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> { -3498 let mut stats = BTreeMap::new(); -3499 while let Some(event) = events.next().await { -3500 if let PathEvent::Closed { -3501 remote_addr, -3502 last_stats, -3503 .. -3504 } = event -3505 { -3506 stats.insert(remote_addr, *last_stats); -3507 } -3508 } -3509 stats -3510 } -3511 -3512 let client = Endpoint::builder(presets::Minimal) -3513 .relay_mode(RelayMode::Custom(relay_map.clone())) -3514 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3515 .transport_config(qlog.create("client")?) -3516 .bind() -3517 .await?; -3518 let server = Endpoint::builder(presets::Minimal) -3519 .relay_mode(RelayMode::Custom(relay_map)) -3520 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3521 .transport_config(qlog.create("server")?) -3522 .alpns(vec![TEST_ALPN.to_vec()]) -3523 .bind() -3524 .await?; -3525 let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url); -3526 let server_task = tokio::spawn(async move { -3527 let incoming = server.accept().await.anyerr()?; -3528 let conn = incoming.await.anyerr()?; -3529 let stats_task = tokio::spawn(collect_stats(conn.path_events())); -3530 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -3531 let msg = recv.read_to_end(transfer_size).await.anyerr()?; -3532 send.write_all(&msg).await.anyerr()?; -3533 send.finish().anyerr()?; -3534 conn.closed().await; -3535 let stats = stats_task.await.expect("stats task panicked"); -3536 Ok::<_, Error>(stats) -3537 }); -3538 -3539 let conn = client.connect(server_addr, TEST_ALPN).await?; -3540 let client_stats_task = tokio::spawn(collect_stats(conn.path_events())); -3541 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -3542 send.write_all(&vec![42u8; transfer_size]).await.anyerr()?; -3543 send.finish().anyerr()?; -3544 recv.read_to_end(transfer_size).await.anyerr()?; -3545 conn.close(0u32.into(), b"thanks, bye!"); -3546 client.close().await; -3547 let client_stats = client_stats_task.await.expect("stats task panicked"); -3548 let server_stats = server_task.await.anyerr()??; -3549 -3550 info!("client stats: {client_stats:#?}"); -3551 info!("server stats: {server_stats:#?}"); -3552 -3553 let client_total_relay_tx = client_stats -3554 .iter() -3555 .filter(|(remote, _stats)| remote.is_relay()) -3556 .map(|(_, stats)| stats.udp_tx.bytes) -3557 .sum::<u64>(); -3558 let client_total_relay_rx = client_stats -3559 .iter() -3560 .filter(|(remote, _stats)| remote.is_relay()) -3561 .map(|(_, stats)| stats.udp_rx.bytes) -3562 .sum::<u64>(); -3563 let server_total_relay_tx = server_stats -3564 .iter() -3565 .filter(|(remote, _stats)| remote.is_relay()) -3566 .map(|(_, stats)| stats.udp_tx.bytes) -3567 .sum::<u64>(); -3568 let server_total_relay_rx = server_stats -3569 .iter() -3570 .filter(|(remote, _stats)| remote.is_relay()) -3571 .map(|(_, stats)| stats.udp_rx.bytes) -3572 .sum::<u64>(); -3573 -3574 info!(?client_total_relay_tx, "total"); -3575 info!(?client_total_relay_rx, "total"); -3576 info!(?server_total_relay_tx, "total"); -3577 info!(?server_total_relay_rx, "total"); -3578 -3579 // We should send/receive only the minorty of traffic via the relay. -3580 assert!(client_total_relay_tx < transfer_size as u64 / 2); -3581 assert!(client_total_relay_rx < transfer_size as u64 / 2); -3582 assert!(server_total_relay_tx < transfer_size as u64 / 2); -3583 assert!(server_total_relay_rx < transfer_size as u64 / 2); -3584 -3585 Ok(()) -3586 } -3587 -3588 /// Tests that correct logs are emitted when connecting two endpoints with same secret keys to a relay. -3589 #[tokio::test] -3590 #[traced_test] -3591 async fn same_endpoint_id_relay() -> Result { -3592 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -3593 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -3594 let secret_key = SecretKey::from_bytes(&rng.random()); -3595 -3596 let client = Endpoint::builder(presets::Minimal) -3597 .relay_mode(RelayMode::Custom(relay_map.clone())) -3598 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3599 .bind() -3600 .instrument(error_span!("ep-client")) -3601 .await?; -3602 -3603 info!("client {}", client.id()); -3604 -3605 // bind ep1 and wait until connected to relay. -3606 let ep1 = Endpoint::builder(presets::Minimal) -3607 .relay_mode(RelayMode::Custom(relay_map.clone())) -3608 .secret_key(secret_key.clone()) -3609 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3610 .alpns(vec![TEST_ALPN.to_vec()]) -3611 .bind() -3612 .instrument(error_span!("ep1")) -3613 .await?; -3614 info!("ep1 bound {:?}", ep1.id()); -3615 ep1.online().await; -3616 info!("ep1 online"); -3617 -3618 let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone()); -3619 -3620 tokio::try_join!( -3621 async { -3622 let conn = client.connect(addr.clone(), TEST_ALPN).await?; -3623 let reason = conn.closed().await; -3624 assert!(is_application_closed(&reason, 1)); -3625 n0_error::Ok(()) -3626 }, -3627 async { -3628 let conn = ep1.accept().await.unwrap().await?; -3629 conn.close(1u32.into(), b"bye"); -3630 n0_error::Ok(()) -3631 } -3632 )?; -3633 info!("client connected to ep1"); -3634 -3635 // now start second endpoint with same secret key -3636 let ep2 = Endpoint::builder(presets::Minimal) -3637 .relay_mode(RelayMode::Custom(relay_map)) -3638 .secret_key(secret_key.clone()) -3639 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3640 .alpns(vec![TEST_ALPN.to_vec()]) -3641 .bind() -3642 .instrument(error_span!("ep2")) -3643 .await?; -3644 info!("ep2 bound {:?}", ep2.id()); -3645 ep2.online().await; -3646 println!("ep2 online"); -3647 -3648 // `online` does not mean that the connection to the home relay was *established*, -3649 // only that the home relay was *chosen* based on the net report probes. -3650 // We need to wait for the connection to be established though, to be sure that new packets -3651 // will be routed to the new endpoint and not to the old endpoint anymore. -3652 // We don't expose being connected to the home relay on the endpoint currently, -3653 // so we resort to log assertions. -3654 // TODO(Frando): Replace once we add a proper API for this. -3655 let expected_log_line = format!( -3656 "ep2:endpoint{{id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected", -3657 ep2.id().fmt_short() -3658 ); -3659 tokio::time::timeout(Duration::from_secs(5), async { -3660 while !logs_contain(&expected_log_line) { -3661 tokio::time::sleep(Duration::from_millis(10)).await -3662 } -3663 }) -3664 .await -3665 .std_context("relay connection did not establish in time")?; -3666 -3667 tokio::try_join!( -3668 async { -3669 let conn = client.connect(addr.clone(), TEST_ALPN).await?; -3670 let reason = conn.closed().await; -3671 assert!(is_application_closed(&reason, 1)); -3672 n0_error::Ok(()) -3673 }, -3674 async { -3675 let conn = ep2.accept().await.unwrap().await?; -3676 conn.close(1u32.into(), b"bye"); -3677 n0_error::Ok(()) -3678 } -3679 )?; -3680 println!("client connected to ep2"); -3681 -3682 // assert that ep1 did not receive a connection -3683 assert!(now_or_never(ep1.accept()).is_none()); -3684 -3685 // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2. -3686 logs_assert(|logs| { -3687 let expected_line = |line: &str| { -3688 line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received") -3689 }; -3690 let count_line_ep1 = logs -3691 .iter() -3692 .filter(|line| line.contains(":ep1:") && expected_line(line)) -3693 .count(); -3694 let count_line_ep2 = logs -3695 .iter() -3696 .filter(|line| line.contains(":ep2:") && expected_line(line)) -3697 .count(); -3698 if count_line_ep1 == 1 && count_line_ep2 == 0 { -3699 Ok(()) -3700 } else { -3701 Err("Logs don't match expectations".to_string()) -3702 } -3703 }); -3704 tokio::join!(ep1.close(), ep2.close(), client.close()); -3705 Ok(()) -3706 } -3707 -3708 fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool { -3709 matches!( -3710 close_reason, -3711 ConnectionError::ApplicationClosed(f) if f.error_code ==code.into() -3712 ) -3713 } -3714 -3715 #[tokio::test] -3716 #[traced_test] -3717 async fn test_closed_endpoint_behaviour() -> Result { -3718 // create endpoint -3719 // call endpoint.close -3720 // ensure methods behave in the expected way -3721 info!("Creating endpoint"); -3722 let ep = Endpoint::builder(presets::N0).bind().await?; -3723 let closed = ep.closed(); -3724 info!("Closing endpoint"); -3725 let now = Instant::now(); -3726 ep.close().await; -3727 info!("Endpoint closed in {:?}", now.elapsed()); -3728 -3729 // Assert that the `closed` cancellation token is now cancelled -3730 assert_eq!(now_or_never(closed), Some(())); -3731 -3732 info!("Set ALPNS fails silently"); -3733 ep.set_alpns(vec![b"test".into()]); -3734 -3735 info!("Insert Relay returns None"); -3736 let relay_config = crate::defaults::staging::default_na_east_relay(); -3737 assert!( -3738 ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) -3739 .await -3740 .is_none() -3741 ); -3742 -3743 info!("Remove Relay returns None"); -3744 assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); -3745 -3746 info!("Connecting"); -3747 let mut rng = ChaCha8Rng::seed_from_u64(41); -3748 let ep_id = SecretKey::from_bytes(&rng.random()).public(); -3749 -3750 // should likely be an error that states that the -3751 // endpoint is closed instead: -3752 if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() -3753 { -3754 assert!(matches!( -3755 source, -3756 ConnectWithOptsError::EndpointClosed { .. } -3757 )); -3758 } else { -3759 panic!("unexpected error for connect"); -3760 } -3761 -3762 info!("Accepting!"); -3763 assert!(ep.accept().await.is_none()); -3764 -3765 // this should work -3766 info!("Addr: {:?}", ep.addr()); -3767 -3768 // create watchers to verify they terminate after the endpoint is dropped. -3769 let mut addrs = ep.watch_addr().stream(); -3770 let mut net_reports = ep.net_report().stream(); -3771 -3772 // returns None -3773 let net_report = ep.last_net_report(); -3774 info!("last Net report {net_report:?}"); -3775 -3776 // this should work -3777 let sockets = ep.bound_sockets(); -3778 info!("Sockets: {sockets:?}"); -3779 -3780 // these should return errors -3781 assert!(ep.dns_resolver().is_err()); -3782 assert!(ep.address_lookup().is_err()); -3783 -3784 #[cfg(feature = "metrics")] -3785 { -3786 // this should work -3787 let metrics = ep.metrics(); -3788 info!("Metrics: {metrics:?}"); -3789 } -3790 -3791 // this should return none -3792 assert!(ep.remote_info(ep_id).await.is_none()); -3793 -3794 // this should fail silently -3795 ep.network_change().await; -3796 -3797 // this should fail silently -3798 ep.set_user_data_for_address_lookup(Some( -3799 UserData::try_from("TEST".to_string()).expect("valid string"), -3800 )); -3801 drop(ep); -3802 // now that the endpoint is dropped, all watchers should terminate. -3803 tokio::time::timeout(Duration::from_secs(1), async { -3804 while let Some(addr) = addrs.next().await { -3805 info!("Addrs stream: {addr:?}"); -3806 } -3807 while let Some(net_report) = net_reports.next().await { -3808 info!("Net report stream: {net_report:?}"); -3809 } -3810 }) -3811 .await -3812 .expect("watchers not closed"); -3813 -3814 info!("Done!"); -3815 Ok(()) -3816 } -3817 -3818 #[tokio::test] -3819 #[traced_test] -3820 async fn test_closed_endpoint_unpolled_accept_fut() -> Result { -3821 info!("Creating endpoint"); -3822 let ep = Endpoint::builder(presets::N0).bind().await?; -3823 -3824 info!("Get accept future"); -3825 let accept_fut = ep.accept(); -3826 -3827 info!("Closing endpoint"); -3828 let now = Instant::now(); -3829 tokio::time::timeout(Duration::from_secs(5), ep.close()) -3830 .await -3831 .expect("Endpoint closes in a reasonable time"); -3832 info!("Endpoint closed in {:?}", now.elapsed()); -3833 -3834 info!("Accept future returns None after the endpoint has closed"); -3835 let incoming = accept_fut.await; -3836 assert!(incoming.is_none()); -3837 Ok(()) -3838 } -3839 -3840 #[tokio::test] -3841 #[traced_test] -3842 async fn test_closed_endpoint_polled_accept_fut() -> Result { -3843 info!("Creating endpoint"); -3844 let ep = Endpoint::builder(presets::N0).bind().await?; -3845 -3846 info!("Run an accept task"); -3847 let ep2 = ep.clone(); -3848 let accept_task = tokio::spawn(async move { -3849 info!("Waiting on Accept"); -3850 let res = ep2.accept().await; -3851 info!("Accept await has returned"); -3852 res -3853 }); -3854 -3855 // Try to ensure the accept future is polled at least once. -3856 tokio::time::sleep(Duration::from_millis(10)).await; -3857 -3858 info!("Closing the endpoint"); -3859 tokio::time::timeout(Duration::from_secs(5), ep.close()) -3860 .await -3861 .expect("Endpoint closes in a reasonable time"); -3862 info!("Endpoint closed"); -3863 -3864 info!("Await the accept task"); -3865 let incoming = accept_task.await.expect("accept task panicked"); -3866 assert!(incoming.is_none()); -3867 -3868 Ok(()) -3869 } -3870 -3871 #[tokio::test] -3872 #[traced_test] -3873 async fn test_endpoint_online_add_relay() -> Result { -3874 let ep = Endpoint::builder(presets::Minimal) -3875 .relay_mode(RelayMode::Custom(RelayMap::empty())) -3876 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3877 .bind() -3878 .await?; -3879 // should not come online without relays. -3880 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; -3881 assert!(res.is_err()); -3882 -3883 // should come online after a relay is added. -3884 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; -3885 ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap()) -3886 .await; -3887 let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await; -3888 assert!(res.is_ok()); -3889 -3890 // online should still return after endpoint close, if the endpoint was last online -3891 let ep_clone = ep.clone(); -3892 let task = tokio::task::spawn(async move { -3893 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await -3894 }); -3895 ep.close().await; -3896 let res = task.await.unwrap(); -3897 assert!(res.is_ok()); -3898 Ok(()) -3899 } -3900 -3901 #[tokio::test] -3902 #[traced_test] -3903 async fn test_endpoint_online_close() -> Result { -3904 let ep = Endpoint::bind(presets::Minimal).await?; -3905 // should not come online without relays. -3906 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; -3907 assert!(res.is_err()); -3908 -3909 // online should remain pending after the endpoint is closed. -3910 let ep_clone = ep.clone(); -3911 let task = tokio::task::spawn(async move { -3912 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await -3913 }); -3914 ep.close().await; -3915 let res = task.await.unwrap(); -3916 assert!(res.is_err()); -3917 Ok(()) -3918 } -3919 -3920 /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] -3921 /// is admitted to a relay whose access control checks the token only when -3922 /// the token matches. -3923 #[tokio::test] -3924 #[traced_test] -3925 async fn test_endpoint_relay_auth_token() -> Result { -3926 const TOKEN: &str = "valid-token"; -3927 -3928 /// Admits a connection only if it carries the expected auth token. -3929 #[derive(Debug)] -3930 struct TokenAccess(&'static str); -3931 -3932 impl iroh_relay::server::AccessControl for TokenAccess { -3933 async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { -3934 if request.auth_token().as_deref() == Some(self.0) { -3935 Access::Allow -3936 } else { -3937 Access::Deny { reason: None } -3938 } -3939 } -3940 } -3941 -3942 let access = Arc::new(TokenAccess(TOKEN)); -3943 let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; -3944 -3945 // Wrong token: the connection attempt fails and last_error reports -3946 // the relay-side denial. -3947 let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None) -3948 .with_auth_token("wrong-token") -3949 .into(); -3950 let bad_ep = Endpoint::builder(presets::Minimal) -3951 .relay_mode(RelayMode::Custom(bad_map)) -3952 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3953 .bind() -3954 .await?; -3955 let mut stream = bad_ep.home_relay_status().stream(); -3956 let auth_err: String = tokio::time::timeout(Duration::from_secs(5), async { -3957 while let Some(status) = stream.next().await { -3958 if let Some(err) = status.iter().filter_map(|s| s.last_error()).next() { -3959 return format!("{err:#}"); -3960 } -3961 } -3962 panic!("home relay stream ended"); -3963 }) -3964 .await -3965 .std_context("waiting for auth error")?; -3966 assert!( -3967 auth_err.contains("not authorized"), -3968 "expected 'not authorized' in error, got: {auth_err}" -3969 ); -3970 -3971 // Correct token: the endpoint reaches the connected state. -3972 let good_map: RelayMap = RelayConfig::new(relay_url, None) -3973 .with_auth_token(TOKEN) -3974 .into(); -3975 let good_ep = Endpoint::builder(presets::Minimal) -3976 .relay_mode(RelayMode::Custom(good_map)) -3977 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) -3978 .bind() -3979 .await?; -3980 tokio::time::timeout(Duration::from_secs(5), good_ep.online()) -3981 .await -3982 .std_context("waiting for endpoint to come online")?; -3983 -3984 Ok(()) -3985 } -3986}

\ No newline at end of file +1679 /// # } +1680 /// ``` +1681 pub fn closed(&self) -> EndpointClosed { +1682 EndpointClosed { +1683 inner: self.inner.closed(), +1684 } +1685 } +1686 +1687 /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. +1688 /// +1689 /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration +1690 /// for a connection accepted using the [`Incoming::accept_with`] method. +1691 pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder { +1692 let inner = self.inner.static_config.create_server_config(alpns); +1693 ServerConfigBuilder::new(inner, self.inner.static_config.transport_config.clone()) +1694 } +1695 +1696 // # Remaining private methods +1697 +1698 /// Translates a raw [`SocketAddr`] (which may be a synthetic mapped address) into +1699 /// a transport address. +1700 pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> crate::socket::transports::Addr { +1701 self.inner.to_transport_addr(addr) +1702 } +1703 +1704 #[cfg(all(test, with_crypto_provider))] +1705 pub(crate) fn inner(&self) -> Result<Arc<EndpointInner>, EndpointError> { +1706 if self.is_closed() { +1707 return Err(e!(EndpointError::Closed)); +1708 } +1709 Ok(self.inner.clone()) +1710 } +1711} +1712 +1713/// Options for the [`Endpoint::connect_with_opts`] function. +1714#[derive(Default, Debug, Clone)] +1715pub struct ConnectOptions { +1716 transport_config: Option<QuicTransportConfig>, +1717 additional_alpns: Vec<Vec<u8>>, +1718} +1719 +1720impl ConnectOptions { +1721 /// Initializes new connection options. +1722 /// +1723 /// By default, the connection will use the same options +1724 /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`]. +1725 pub fn new() -> Self { +1726 Self::default() +1727 } +1728 +1729 /// Sets the QUIC transport config options for this connection. +1730 pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self { +1731 self.transport_config = Some(transport_config); +1732 self +1733 } +1734 +1735 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in +1736 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. +1737 /// +1738 /// This allows connecting to servers that may only support older versions of your +1739 /// protocol. In this case, you would add the older [ALPN] identifiers with this +1740 /// function. +1741 /// +1742 /// You'll know the final negotiated [ALPN] identifier once your connection was +1743 /// established using [`Connection::alpn`], or even slightly earlier in the +1744 /// handshake by using [`Connecting::alpn`]. +1745 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this +1746 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. +1747 /// +1748 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the +1749 /// accept side that determines the protocol. +1750 /// +1751 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint +1752 /// builder's [`Builder::alpns`] function. +1753 /// +1754 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +1755 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { +1756 self.additional_alpns = alpns; +1757 self +1758 } +1759} +1760 +1761/// Future returned from [`Endpoint::closed`]. +1762#[derive(derive_more::Debug)] +1763#[pin_project] +1764#[debug("EndpointClosed")] +1765pub struct EndpointClosed { +1766 #[pin] +1767 inner: WaitForCancellationFutureOwned, +1768} +1769 +1770impl Future for EndpointClosed { +1771 type Output = (); +1772 +1773 fn poll( +1774 self: Pin<&mut Self>, +1775 cx: &mut std::task::Context<'_>, +1776 ) -> std::task::Poll<Self::Output> { +1777 let this = self.project(); +1778 this.inner.poll(cx) +1779 } +1780} +1781 +1782impl EndpointClosed { +1783 /// Runs a future to completion, or until the [`Endpoint`] is closed. +1784 /// +1785 /// Returns the output of `fut` if it completes before the endpoint closes, +1786 /// or `None` otherwise. +1787 pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output> { +1788 n0_future::future::or(async { Some(fut.await) }, async { +1789 self.await; +1790 None +1791 }) +1792 .await +1793 } +1794} +1795 +1796/// Read a proxy url from the environment, in this order +1797/// +1798/// - `HTTP_PROXY` +1799/// - `http_proxy` +1800/// - `HTTPS_PROXY` +1801/// - `https_proxy` +1802fn proxy_url_from_env() -> Option<Url> { +1803 if let Some(url) = std::env::var("HTTP_PROXY") +1804 .ok() +1805 .and_then(|s| s.parse::<Url>().ok()) +1806 { +1807 if is_cgi() { +1808 warn!("HTTP_PROXY environment variable ignored in CGI"); +1809 } else { +1810 return Some(url); +1811 } +1812 } +1813 if let Some(url) = std::env::var("http_proxy") +1814 .ok() +1815 .and_then(|s| s.parse::<Url>().ok()) +1816 { +1817 return Some(url); +1818 } +1819 if let Some(url) = std::env::var("HTTPS_PROXY") +1820 .ok() +1821 .and_then(|s| s.parse::<Url>().ok()) +1822 { +1823 return Some(url); +1824 } +1825 if let Some(url) = std::env::var("https_proxy") +1826 .ok() +1827 .and_then(|s| s.parse::<Url>().ok()) +1828 { +1829 return Some(url); +1830 } +1831 +1832 None +1833} +1834 +1835/// Connection status of a single home relay. +1836/// +1837/// Observed via [`Endpoint::home_relay_status`]. +1838#[derive(Debug, Clone, PartialEq, Eq)] +1839pub struct RelayStatus { +1840 url: RelayUrl, +1841 state: RelayConnectionState, +1842} +1843 +1844impl RelayStatus { +1845 pub(crate) fn new(url: RelayUrl, state: RelayConnectionState) -> Self { +1846 Self { url, state } +1847 } +1848 +1849 /// Returns the URL of the home relay. +1850 pub fn url(&self) -> &RelayUrl { +1851 &self.url +1852 } +1853 +1854 /// Returns `true` if the endpoint is connected to the relay. +1855 pub fn is_connected(&self) -> bool { +1856 self.state.is_connected() +1857 } +1858 +1859 /// Returns the most recent connection error, if the relay is currently +1860 /// disconnected. +1861 /// +1862 /// Returns `None` when the relay is connected, or when the endpoint has +1863 /// not yet observed a failed connection attempt. +1864 pub fn last_error(&self) -> Option<&AnyError> { +1865 self.state.last_error().map(Arc::as_ref) +1866 } +1867} +1868 +1869/// Configuration of the relay servers for an [`Endpoint`]. +1870#[derive(Debug, Clone, PartialEq, Eq)] +1871pub enum RelayMode { +1872 /// Disable relay servers completely. +1873 /// This means that neither listening nor dialing relays will be available. +1874 Disabled, +1875 /// Use the default relay map, with production relay servers from n0. +1876 /// +1877 /// See [`crate::defaults::prod`] for the severs used. +1878 Default, +1879 /// Use the staging relay servers from n0. +1880 Staging, +1881 /// Use a custom relay map. +1882 Custom(RelayMap), +1883} +1884 +1885impl RelayMode { +1886 /// Returns the relay map for this mode. +1887 pub fn relay_map(&self) -> RelayMap { +1888 match self { +1889 RelayMode::Disabled => RelayMap::empty(), +1890 RelayMode::Default => crate::defaults::prod::default_relay_map(), +1891 RelayMode::Staging => crate::defaults::staging::default_relay_map(), +1892 RelayMode::Custom(relay_map) => relay_map.clone(), +1893 } +1894 } +1895 +1896 /// Create a custom relay mode from a list of [`RelayUrl`]s. +1897 /// +1898 /// # Example +1899 /// +1900 /// ``` +1901 /// # fn main() -> n0_error::Result<()> { +1902 /// # use iroh::RelayMode; +1903 /// RelayMode::custom([ +1904 /// "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?, +1905 /// "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?, +1906 /// ]); +1907 /// # Ok(()) } +1908 /// ``` +1909 pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self { +1910 let m = RelayMap::from_iter(map); +1911 Self::Custom(m) +1912 } +1913} +1914 +1915/// Environment variable to force the use of staging relays. +1916pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; +1917 +1918/// Returns `true` if the use of staging relays is forced. +1919pub fn force_staging_infra() -> bool { +1920 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) +1921} +1922 +1923/// Returns the default relay mode. +1924/// +1925/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. +1926/// Otherwise, it will return `RelayMode::Default`. +1927pub fn default_relay_mode() -> RelayMode { +1928 // Use staging in testing +1929 match force_staging_infra() { +1930 true => RelayMode::Staging, +1931 false => RelayMode::Default, +1932 } +1933} +1934 +1935/// Check if we are being executed in a CGI context. +1936/// +1937/// If so, a malicious client can send the `Proxy:` header, and it will +1938/// be in the `HTTP_PROXY` env var. So we don't use it :) +1939fn is_cgi() -> bool { +1940 std::env::var_os("REQUEST_METHOD").is_some() +1941} +1942 +1943#[cfg(all(test, with_crypto_provider))] +1944mod tests { +1945 use std::{ +1946 collections::BTreeMap, +1947 io, +1948 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4}, +1949 str::FromStr, +1950 sync::Arc, +1951 time::{Duration, Instant}, +1952 }; +1953 +1954 use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; +1955 use iroh_dns::endpoint_info::UserData; +1956 use iroh_relay::{RelayConfig, server::Access, tls::CaTlsConfig}; +1957 use n0_error::{AnyError as Error, Result, StdResultExt}; +1958 use n0_future::{BufferedStreamExt, StreamExt, future::now_or_never, stream, time}; +1959 use n0_tracing_test::traced_test; +1960 use n0_watcher::Watcher; +1961 use noq::PathStats; +1962 use rand::{RngExt, SeedableRng}; +1963 use rand_chacha::ChaCha8Rng; +1964 use tokio::sync::oneshot; +1965 use tracing::{Instrument, debug_span, error_span, info, info_span, instrument}; +1966 +1967 use super::Endpoint; +1968 use crate::{ +1969 RelayMap, RelayMode, +1970 address_lookup::memory::MemoryLookup, +1971 endpoint::{ +1972 ApplicationClose, BindError, BindOpts, ConnectError, ConnectOptions, +1973 ConnectWithOptsError, Connection, ConnectionError, PathEvent, PathEventStream, presets, +1974 }, +1975 protocol::{AcceptError, ProtocolHandler, Router}, +1976 test_utils::{ +1977 QlogFileGroup, run_relay_server, run_relay_server_with, run_relay_server_with_access, +1978 }, +1979 }; +1980 +1981 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +1982 +1983 #[tokio::test] +1984 #[traced_test] +1985 async fn test_connect_self() -> Result { +1986 let ep = Endpoint::builder(presets::Minimal) +1987 .alpns(vec![TEST_ALPN.to_vec()]) +1988 .bind() +1989 .await +1990 .unwrap(); +1991 let my_addr = ep.addr(); +1992 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; +1993 assert!(res.is_err()); +1994 let err = res.err().unwrap(); +1995 assert!(err.to_string().starts_with("Connecting to ourself")); +1996 +1997 Ok(()) +1998 } +1999 +2000 #[tokio::test] +2001 #[traced_test] +2002 async fn endpoint_connect_close() -> Result { +2003 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2004 let (relay_map, relay_url, _guard) = run_relay_server().await?; +2005 let server_secret_key = SecretKey::from_bytes(&rng.random()); +2006 let server_peer_id = server_secret_key.public(); +2007 +2008 let qlog = QlogFileGroup::from_env("endpoint_connect_close"); +2009 +2010 // Wait for the endpoint to be started to make sure it's up before clients try to connect +2011 let ep = Endpoint::builder(presets::Minimal) +2012 .relay_mode(RelayMode::Custom(relay_map.clone())) +2013 .secret_key(server_secret_key) +2014 .transport_config(qlog.create("server")?) +2015 .alpns(vec![TEST_ALPN.to_vec()]) +2016 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2017 .bind() +2018 .await?; +2019 // Wait for the endpoint to be reachable via relay +2020 ep.online().await; +2021 +2022 let server = tokio::spawn( +2023 async move { +2024 info!("accepting connection"); +2025 let incoming = ep.accept().await.anyerr()?; +2026 let conn = incoming.await.anyerr()?; +2027 let mut stream = conn.accept_uni().await.anyerr()?; +2028 let mut buf = [0u8; 5]; +2029 stream.read_exact(&mut buf).await.anyerr()?; +2030 info!("Accepted 1 stream, received {buf:?}. Closing now."); +2031 // close the connection +2032 conn.close(7u8.into(), b"bye"); +2033 +2034 let res = conn.accept_uni().await; +2035 assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed); +2036 +2037 let res = stream.read_to_end(10).await; +2038 assert_eq!( +2039 res.unwrap_err(), +2040 noq::ReadToEndError::Read(noq::ReadError::ConnectionLost( +2041 ConnectionError::LocallyClosed +2042 )) +2043 ); +2044 info!("Closing the endpoint"); +2045 ep.close().await; +2046 info!("server test completed"); +2047 Ok::<_, Error>(()) +2048 } +2049 .instrument(info_span!("test-server")), +2050 ); +2051 +2052 let client = tokio::spawn( +2053 async move { +2054 let ep = Endpoint::builder(presets::Minimal) +2055 .relay_mode(RelayMode::Custom(relay_map)) +2056 .alpns(vec![TEST_ALPN.to_vec()]) +2057 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2058 .transport_config(qlog.create("client")?) +2059 .bind() +2060 .await?; +2061 info!("client connecting"); +2062 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); +2063 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; +2064 let mut stream = conn.open_uni().await.anyerr()?; +2065 +2066 // First write is accepted by server. We need this bit of synchronisation +2067 // because if the server closes after simply accepting the connection we can +2068 // not be sure our .open_uni() call would succeed as it may already receive +2069 // the error. +2070 stream.write_all(b"hello").await.anyerr()?; +2071 +2072 info!("waiting for closed"); +2073 // Remote now closes the connection, we should see an error sometime soon. +2074 let err = conn.closed().await; +2075 let expected_err = ConnectionError::ApplicationClosed(ApplicationClose { +2076 error_code: 7u8.into(), +2077 reason: b"bye".to_vec().into(), +2078 }); +2079 assert_eq!(err, expected_err); +2080 +2081 info!("opening new - expect it to fail"); +2082 let res = conn.open_uni().await; +2083 assert_eq!(res.unwrap_err(), expected_err); +2084 info!("Closing the client"); +2085 ep.close().await; +2086 info!("client test completed"); +2087 Ok::<_, Error>(()) +2088 } +2089 .instrument(info_span!("test-client")), +2090 ); +2091 +2092 let (server, client) = tokio::time::timeout( +2093 Duration::from_secs(30), +2094 n0_future::future::zip(server, client), +2095 ) +2096 .await +2097 .anyerr()?; +2098 server.anyerr()??; +2099 client.anyerr()??; +2100 Ok(()) +2101 } +2102 +2103 #[tokio::test] +2104 #[traced_test] +2105 async fn endpoint_relay_connect_loop() -> Result { +2106 let test_start = Instant::now(); +2107 let n_clients = 5; +2108 let n_chunks_per_client = 2; +2109 let chunk_size = 100; +2110 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +2111 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); +2112 let server_secret_key = SecretKey::from_bytes(&rng.random()); +2113 let server_endpoint_id = server_secret_key.public(); +2114 +2115 // Make sure the server is bound before having clients connect to it: +2116 let ep = Endpoint::builder(presets::Minimal) +2117 .relay_mode(RelayMode::Custom(relay_map.clone())) +2118 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2119 .secret_key(server_secret_key) +2120 .alpns(vec![TEST_ALPN.to_vec()]) +2121 .bind() +2122 .await?; +2123 // Also make sure the server has a working relay connection +2124 ep.online().await; +2125 +2126 info!(time = ?test_start.elapsed(), "test setup done"); +2127 +2128 // The server accepts the connections of the clients sequentially. +2129 let server = tokio::spawn( +2130 async move { +2131 let eps = ep.bound_sockets(); +2132 +2133 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); +2134 for i in 0..n_clients { +2135 let res = tokio::time::timeout(Duration::from_secs(5), async { +2136 let round_start = Instant::now(); +2137 info!("[server] round {i}"); +2138 let incoming = ep.accept().await.anyerr()?; +2139 let conn = incoming.await.anyerr()?; +2140 let endpoint_id = conn.remote_id(); +2141 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); +2142 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2143 let mut buf = vec![0u8; chunk_size]; +2144 for _i in 0..n_chunks_per_client { +2145 recv.read_exact(&mut buf).await.anyerr()?; +2146 send.write_all(&buf).await.anyerr()?; +2147 } +2148 info!(%i, peer = %endpoint_id.fmt_short(), "finishing"); +2149 send.finish().anyerr()?; +2150 conn.closed().await; // we're the last to send data, so we wait for the other side to close +2151 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); +2152 info!("[server] round {i} done in {:?}", round_start.elapsed()); +2153 Ok::<_, Error>(()) +2154 }) +2155 .await +2156 .std_context("timeout"); +2157 match res { +2158 Err(err) | Ok(Err(err)) => { +2159 // ensure we close the endpoint before returning early +2160 // on error +2161 ep.close().await; +2162 return Err(err); +2163 } +2164 _ => { +2165 // if this round went `Ok` don't close the endpoint yet +2166 } +2167 } +2168 } +2169 // close the endpoint before dropping the server task +2170 ep.close().await; +2171 Ok::<_, Error>(()) +2172 } +2173 .instrument(debug_span!("server")), +2174 ); +2175 +2176 let client = tokio::spawn(async move { +2177 for i in 0..n_clients { +2178 let round_start = Instant::now(); +2179 info!("[client] round {i}"); +2180 let client_secret_key = SecretKey::from_bytes(&rng.random()); +2181 let ep = Endpoint::builder(presets::Minimal) +2182 .relay_mode(RelayMode::Custom(relay_map.clone())) +2183 .alpns(vec![TEST_ALPN.to_vec()]) +2184 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2185 .secret_key(client_secret_key) +2186 .bind() +2187 .await?; +2188 let ep_1 = ep.clone(); +2189 let res = tokio::time::timeout( +2190 Duration::from_secs(5), +2191 async { +2192 info!("client binding"); +2193 let eps = ep.bound_sockets(); +2194 +2195 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); +2196 let endpoint_addr = +2197 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); +2198 info!(to = ?endpoint_addr, "client connecting"); +2199 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; +2200 info!("client connected"); +2201 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2202 +2203 for i in 0..n_chunks_per_client { +2204 let mut buf = vec![i; chunk_size]; +2205 send.write_all(&buf).await.anyerr()?; +2206 recv.read_exact(&mut buf).await.anyerr()?; +2207 assert_eq!(buf, vec![i; chunk_size]); +2208 } +2209 // we're the last to receive data, so we close +2210 conn.close(0u32.into(), b"bye!"); +2211 info!("client finished"); +2212 Ok::<_, Error>(()) +2213 } +2214 .instrument(debug_span!("client", %i)), +2215 ) +2216 .await +2217 .std_context("timeout"); +2218 ep_1.close().await; +2219 info!("client endpoint closed"); +2220 res??; +2221 info!("[client] round {i} done in {:?}", round_start.elapsed()); +2222 } +2223 Ok::<_, Error>(()) +2224 }); +2225 +2226 server.await.anyerr()??; +2227 client.await.anyerr()??; +2228 Ok(()) +2229 } +2230 +2231 #[tokio::test] +2232 #[traced_test] +2233 async fn endpoint_send_relay() -> Result { +2234 let (relay_map, _relay_url, _guard) = run_relay_server().await?; +2235 let client = Endpoint::builder(presets::Minimal) +2236 .relay_mode(RelayMode::Custom(relay_map.clone())) +2237 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2238 .bind() +2239 .await?; +2240 let server = Endpoint::builder(presets::Minimal) +2241 .relay_mode(RelayMode::Custom(relay_map)) +2242 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2243 .alpns(vec![TEST_ALPN.to_vec()]) +2244 .bind() +2245 .await?; +2246 +2247 let task = tokio::spawn({ +2248 let server = server.clone(); +2249 async move { +2250 let Some(conn) = server.accept().await else { +2251 n0_error::bail_any!("Expected an incoming connection"); +2252 }; +2253 let conn = conn.await.anyerr()?; +2254 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2255 let data = recv.read_to_end(1000).await.anyerr()?; +2256 send.write_all(&data).await.anyerr()?; +2257 send.finish().anyerr()?; +2258 conn.closed().await; +2259 +2260 Ok::<_, Error>(()) +2261 } +2262 }); +2263 +2264 let addr = server.addr(); +2265 let conn = client.connect(addr, TEST_ALPN).await?; +2266 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2267 send.write_all(b"Hello, world!").await.anyerr()?; +2268 send.finish().anyerr()?; +2269 let data = recv.read_to_end(1000).await.anyerr()?; +2270 conn.close(0u32.into(), b"bye!"); +2271 +2272 task.await.anyerr()??; +2273 +2274 client.close().await; +2275 server.close().await; +2276 +2277 assert_eq!(&data, b"Hello, world!"); +2278 +2279 Ok(()) +2280 } +2281 +2282 #[tokio::test] +2283 #[traced_test] +2284 async fn endpoint_two_direct_only() -> Result { +2285 // Connect two endpoints on the same network, without a relay server, without +2286 // Address Lookup. +2287 let ep1 = { +2288 let span = info_span!("server"); +2289 let _guard = span.enter(); +2290 Endpoint::builder(presets::N0) +2291 .alpns(vec![TEST_ALPN.to_vec()]) +2292 .relay_mode(RelayMode::Disabled) +2293 .bind() +2294 .await? +2295 }; +2296 let ep2 = { +2297 let span = info_span!("client"); +2298 let _guard = span.enter(); +2299 Endpoint::builder(presets::N0) +2300 .alpns(vec![TEST_ALPN.to_vec()]) +2301 .relay_mode(RelayMode::Disabled) +2302 .bind() +2303 .await? +2304 }; +2305 let ep1_nodeaddr = ep1.addr(); +2306 +2307 #[instrument(name = "client", skip_all)] +2308 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> { +2309 info!(me = %ep.id().fmt_short(), "client starting"); +2310 let conn = ep.connect(dst, TEST_ALPN).await?; +2311 let mut send = conn.open_uni().await.anyerr()?; +2312 send.write_all(b"hello").await.anyerr()?; +2313 send.finish().anyerr()?; +2314 Ok(conn.closed().await) +2315 } +2316 +2317 #[instrument(name = "server", skip_all)] +2318 async fn accept(ep: Endpoint, src: EndpointId) -> Result { +2319 info!(me = %ep.id().fmt_short(), "server starting"); +2320 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2321 let node_id = conn.remote_id(); +2322 assert_eq!(node_id, src); +2323 let mut recv = conn.accept_uni().await.anyerr()?; +2324 let msg = recv.read_to_end(100).await.anyerr()?; +2325 assert_eq!(msg, b"hello"); +2326 // Dropping the connection closes it just fine. +2327 Ok(()) +2328 } +2329 +2330 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); +2331 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); +2332 +2333 ep1_accept.await.anyerr()??; +2334 let conn_closed = dbg!(ep2_connect.await.anyerr()??); +2335 assert!(matches!( +2336 conn_closed, +2337 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2338 )); +2339 +2340 Ok(()) +2341 } +2342 +2343 #[tokio::test] +2344 #[traced_test] +2345 async fn endpoint_two_relay_only_becomes_direct() -> Result { +2346 // Connect two endpoints on the same network, via a relay server, without +2347 // Address Lookup. Wait until there is a direct connection. +2348 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2349 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2350 let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct")); +2351 +2352 #[instrument(name = "client", skip_all)] +2353 async fn connect( +2354 relay_map: RelayMap, +2355 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2356 qlog: Arc<QlogFileGroup>, +2357 ) -> Result<ConnectionError> { +2358 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2359 let secret = SecretKey::from_bytes(&rng.random()); +2360 let ep = Endpoint::builder(presets::N0) +2361 .secret_key(secret) +2362 .alpns(vec![TEST_ALPN.to_vec()]) +2363 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2364 .relay_mode(RelayMode::Custom(relay_map)) +2365 .transport_config(qlog.create("client")?) +2366 .bind() +2367 .await?; +2368 info!(me = %ep.id().fmt_short(), "client starting"); +2369 let dst = node_addr_rx.await.anyerr()?; +2370 +2371 info!(me = %ep.id().fmt_short(), "client connecting"); +2372 let conn = ep.connect(dst, TEST_ALPN).await?; +2373 let mut send = conn.open_uni().await.anyerr()?; +2374 send.write_all(b"hello").await.anyerr()?; +2375 let mut paths = conn.paths_stream(); +2376 info!("Waiting for direct connection"); +2377 while let Some(infos) = paths.next().await { +2378 info!(?infos, "new PathInfos"); +2379 if infos.iter().any(|info| info.is_ip()) { +2380 break; +2381 } +2382 } +2383 info!("Have direct connection"); +2384 #[cfg(feature = "metrics")] +2385 { +2386 // Validate holepunch metrics. +2387 assert_eq!(ep.metrics().socket.num_conns_opened.get(), 1); +2388 assert_eq!(ep.metrics().socket.num_conns_direct.get(), 1); +2389 } +2390 +2391 send.write_all(b"close please").await.anyerr()?; +2392 send.finish().anyerr()?; +2393 +2394 let res = conn.closed().await; +2395 ep.close().await; +2396 Ok(res) +2397 } +2398 +2399 #[instrument(name = "server", skip_all)] +2400 async fn accept( +2401 relay_map: RelayMap, +2402 node_addr_tx: oneshot::Sender<EndpointAddr>, +2403 qlog: Arc<QlogFileGroup>, +2404 ) -> Result { +2405 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +2406 let secret = SecretKey::from_bytes(&rng.random()); +2407 let ep = Endpoint::builder(presets::N0) +2408 .secret_key(secret) +2409 .alpns(vec![TEST_ALPN.to_vec()]) +2410 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2411 .transport_config(qlog.create("server")?) +2412 .relay_mode(RelayMode::Custom(relay_map)) +2413 .bind() +2414 .await?; +2415 ep.online().await; +2416 let mut node_addr = ep.addr(); +2417 node_addr.addrs.retain(|addr| addr.is_relay()); +2418 node_addr_tx.send(node_addr).unwrap(); +2419 +2420 info!(me = %ep.id().fmt_short(), "server starting"); +2421 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2422 // let node_id = conn.remote_node_id()?; +2423 // assert_eq!(node_id, src); +2424 let mut recv = conn.accept_uni().await.anyerr()?; +2425 let mut msg = [0u8; 5]; +2426 recv.read_exact(&mut msg).await.anyerr()?; +2427 assert_eq!(&msg, b"hello"); +2428 info!("received hello"); +2429 let msg = recv.read_to_end(100).await.anyerr()?; +2430 assert_eq!(msg, b"close please"); +2431 info!("received 'close please'"); +2432 // Closing the endpoint closes all connections. +2433 ep.close().await; +2434 Ok(()) +2435 } +2436 +2437 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone())); +2438 let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog)); +2439 +2440 server_task.await.anyerr()??; +2441 let conn_closed = dbg!(client_task.await.anyerr()??); +2442 assert!(matches!( +2443 conn_closed, +2444 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2445 )); +2446 +2447 Ok(()) +2448 } +2449 +2450 #[tokio::test] +2451 #[traced_test] +2452 async fn endpoint_two_relay_only_no_ip() -> Result { +2453 // Connect two endpoints on the same network, via a relay server, without +2454 // Address Lookup. +2455 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2456 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2457 +2458 #[instrument(name = "client", skip_all)] +2459 async fn connect( +2460 relay_map: RelayMap, +2461 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2462 ) -> Result<ConnectionError> { +2463 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2464 let secret = SecretKey::from_bytes(&rng.random()); +2465 let ep = Endpoint::builder(presets::N0) +2466 .secret_key(secret) +2467 .alpns(vec![TEST_ALPN.to_vec()]) +2468 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2469 .relay_mode(RelayMode::Custom(relay_map)) +2470 .clear_ip_transports() // disable direct +2471 .bind() +2472 .await?; +2473 info!(me = %ep.id().fmt_short(), "client starting"); +2474 let dst = node_addr_rx.await.anyerr()?; +2475 +2476 info!(me = %ep.id().fmt_short(), "client connecting"); +2477 let conn = ep.connect(dst, TEST_ALPN).await?; +2478 let mut send = conn.open_uni().await.anyerr()?; +2479 send.write_all(b"hello").await.anyerr()?; +2480 let mut paths = conn.paths_stream(); +2481 info!("Waiting for connection"); +2482 'outer: while let Some(infos) = paths.next().await { +2483 info!(?infos, "new PathInfos"); +2484 for info in infos.iter() { +2485 if info.is_ip() { +2486 panic!("should not happen: {:?}", info); +2487 } +2488 if info.is_relay() { +2489 break 'outer; +2490 } +2491 } +2492 } +2493 info!("Have relay connection"); +2494 +2495 send.write_all(b"close please").await.anyerr()?; +2496 send.finish().anyerr()?; +2497 let res = conn.closed().await; +2498 ep.close().await; +2499 Ok(res) +2500 } +2501 +2502 #[instrument(name = "server", skip_all)] +2503 async fn accept( +2504 relay_map: RelayMap, +2505 node_addr_tx: oneshot::Sender<EndpointAddr>, +2506 ) -> Result { +2507 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +2508 let secret = SecretKey::from_bytes(&rng.random()); +2509 let ep = Endpoint::builder(presets::N0) +2510 .secret_key(secret) +2511 .alpns(vec![TEST_ALPN.to_vec()]) +2512 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2513 .relay_mode(RelayMode::Custom(relay_map)) +2514 .clear_ip_transports() +2515 .bind() +2516 .await?; +2517 ep.online().await; +2518 let node_addr = ep.addr(); +2519 node_addr_tx.send(node_addr).unwrap(); +2520 +2521 info!(me = %ep.id().fmt_short(), "server starting"); +2522 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2523 // let node_id = conn.remote_node_id()?; +2524 // assert_eq!(node_id, src); +2525 let mut recv = conn.accept_uni().await.anyerr()?; +2526 let mut msg = [0u8; 5]; +2527 recv.read_exact(&mut msg).await.anyerr()?; +2528 assert_eq!(&msg, b"hello"); +2529 info!("received hello"); +2530 let msg = recv.read_to_end(100).await.anyerr()?; +2531 assert_eq!(msg, b"close please"); +2532 info!("received 'close please'"); +2533 // Closing the endpoint closes all connections. +2534 ep.close().await; +2535 Ok(()) +2536 } +2537 +2538 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2539 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2540 +2541 server_task.await.anyerr()??; +2542 let conn_closed = dbg!(client_task.await.anyerr()??); +2543 assert!(matches!( +2544 conn_closed, +2545 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2546 )); +2547 +2548 Ok(()) +2549 } +2550 +2551 #[tokio::test] +2552 #[traced_test] +2553 async fn endpoint_two_direct_add_relay() -> Result { +2554 // Connect two endpoints on the same network, without relay server and without +2555 // Address Lookup. Add a relay connection later. +2556 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2557 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2558 +2559 #[instrument(name = "client", skip_all)] +2560 async fn connect( +2561 relay_map: RelayMap, +2562 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2563 ) -> Result<()> { +2564 let secret = SecretKey::from([0u8; 32]); +2565 let ep = Endpoint::builder(presets::N0) +2566 .secret_key(secret) +2567 .alpns(vec![TEST_ALPN.to_vec()]) +2568 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2569 .relay_mode(RelayMode::Custom(relay_map)) +2570 .bind() +2571 .await?; +2572 info!(me = %ep.id().fmt_short(), "client starting"); +2573 let dst = node_addr_rx.await.anyerr()?; +2574 +2575 info!(me = %ep.id().fmt_short(), "client connecting"); +2576 let conn = ep.connect(dst, TEST_ALPN).await?; +2577 info!(me = %ep.id().fmt_short(), "client connected"); +2578 +2579 // We should be connected via IP, because it is faster than the relay server. +2580 // TODO: Maybe not panic if this is not true? +2581 +2582 let path_info = conn.paths(); +2583 assert_eq!(path_info.len(), 1); +2584 assert!(path_info.iter().next().unwrap().is_ip()); +2585 +2586 let mut paths = conn.paths_stream(); +2587 time::timeout(Duration::from_secs(5), async move { +2588 while let Some(infos) = paths.next().await { +2589 info!(?infos, "new PathInfos"); +2590 if infos.iter().any(|info| info.is_relay()) { +2591 info!("client has a relay path"); +2592 break; +2593 } +2594 } +2595 }) +2596 .await +2597 .anyerr()?; +2598 +2599 // wait for the server to signal it has the relay connection +2600 let mut stream = conn.accept_uni().await.anyerr()?; +2601 stream.read_to_end(100).await.anyerr()?; +2602 +2603 info!("client closing"); +2604 conn.close(0u8.into(), b""); +2605 ep.close().await; +2606 Ok(()) +2607 } +2608 +2609 #[instrument(name = "server", skip_all)] +2610 async fn accept( +2611 relay_map: RelayMap, +2612 node_addr_tx: oneshot::Sender<EndpointAddr>, +2613 ) -> Result<ConnectionError> { +2614 let secret = SecretKey::from([1u8; 32]); +2615 let ep = Endpoint::builder(presets::N0) +2616 .secret_key(secret) +2617 .alpns(vec![TEST_ALPN.to_vec()]) +2618 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2619 .relay_mode(RelayMode::Custom(relay_map)) +2620 .bind() +2621 .await?; +2622 ep.online().await; +2623 let node_addr = ep.addr(); +2624 node_addr_tx.send(node_addr).unwrap(); +2625 +2626 info!(me = %ep.id().fmt_short(), "server starting"); +2627 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2628 info!(me = %ep.id().fmt_short(), "server accepted connection"); +2629 +2630 // Wait for a relay connection to be added. Client does all the asserting here, +2631 // we just want to wait so we get to see all the mechanics of the connection +2632 // being added on this side too. +2633 let mut paths = conn.paths_stream(); +2634 time::timeout(Duration::from_secs(5), async move { +2635 while let Some(infos) = paths.next().await { +2636 info!(?infos, "new PathInfos"); +2637 if infos.iter().any(|path| path.is_relay()) { +2638 info!("server has a relay path"); +2639 break; +2640 } +2641 } +2642 }) +2643 .await +2644 .anyerr()?; +2645 +2646 let mut stream = conn.open_uni().await.anyerr()?; +2647 stream.write_all(b"have relay").await.anyerr()?; +2648 stream.finish().anyerr()?; +2649 info!("waiting conn.closed()"); +2650 +2651 Ok(conn.closed().await) +2652 } +2653 +2654 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2655 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2656 +2657 client_task.await.anyerr()??; +2658 let conn_closed = dbg!(server_task.await.anyerr()??); +2659 assert!(matches!( +2660 conn_closed, +2661 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2662 )); +2663 +2664 Ok(()) +2665 } +2666 +2667 #[tokio::test] +2668 #[traced_test] +2669 async fn endpoint_relay_map_change() -> Result { +2670 let (relay_map, relay_url, _guard1) = run_relay_server().await?; +2671 let client = Endpoint::builder(presets::Minimal) +2672 .relay_mode(RelayMode::Custom(relay_map.clone())) +2673 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2674 .bind() +2675 .await?; +2676 let server = Endpoint::builder(presets::Minimal) +2677 .relay_mode(RelayMode::Custom(relay_map)) +2678 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2679 .alpns(vec![TEST_ALPN.to_vec()]) +2680 .bind() +2681 .await?; +2682 +2683 let task = tokio::spawn({ +2684 let server = server.clone(); +2685 async move { +2686 for i in 0..2 { +2687 println!("accept: round {i}"); +2688 let Some(conn) = server.accept().await else { +2689 n0_error::bail_any!("Expected an incoming connection"); +2690 }; +2691 let conn = conn.await.anyerr()?; +2692 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2693 let data = recv.read_to_end(1000).await.anyerr()?; +2694 send.write_all(&data).await.anyerr()?; +2695 send.finish().anyerr()?; +2696 conn.closed().await; +2697 } +2698 Ok::<_, Error>(()) +2699 } +2700 }); +2701 +2702 server.online().await; +2703 +2704 let mut addr = server.addr(); +2705 println!("round1: {:?}", addr); +2706 +2707 // remove direct addrs to force relay usage +2708 addr.addrs +2709 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2710 +2711 let conn = client.connect(addr, TEST_ALPN).await?; +2712 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2713 send.write_all(b"Hello, world!").await.anyerr()?; +2714 send.finish().anyerr()?; +2715 let data = recv.read_to_end(1000).await.anyerr()?; +2716 conn.close(0u32.into(), b"bye!"); +2717 +2718 assert_eq!(&data, b"Hello, world!"); +2719 +2720 // setup a second relay server +2721 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; +2722 let new_endpoint = new_relay_map +2723 .get(&new_relay_url) +2724 .expect("missing endpoint") +2725 .clone(); +2726 dbg!(&new_relay_map); +2727 +2728 let addr_watcher = server.watch_addr(); +2729 +2730 // add new new relay +2731 assert!( +2732 server +2733 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) +2734 .await +2735 .is_none() +2736 ); +2737 // remove the old relay +2738 assert!(server.remove_relay(&relay_url).await.is_some()); +2739 +2740 println!("------- changed ----- "); +2741 +2742 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { +2743 let mut stream = addr_watcher.stream(); +2744 while let Some(addr) = stream.next().await { +2745 if addr.relay_urls().next() != Some(&relay_url) { +2746 return addr; +2747 } +2748 } +2749 panic!("failed to change relay"); +2750 }) +2751 .await +2752 .anyerr()?; +2753 +2754 println!("round2: {:?}", addr); +2755 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); +2756 +2757 // remove direct addrs to force relay usage +2758 addr.addrs +2759 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2760 +2761 let conn = client.connect(addr, TEST_ALPN).await?; +2762 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2763 send.write_all(b"Hello, world!").await.anyerr()?; +2764 send.finish().anyerr()?; +2765 let data = recv.read_to_end(1000).await.anyerr()?; +2766 conn.close(0u32.into(), b"bye!"); +2767 +2768 task.await.anyerr()??; +2769 +2770 client.close().await; +2771 server.close().await; +2772 +2773 assert_eq!(&data, b"Hello, world!"); +2774 +2775 Ok(()) +2776 } +2777 +2778 #[tokio::test] +2779 #[traced_test] +2780 async fn endpoint_bidi_send_recv() -> Result { +2781 let disco = MemoryLookup::new(); +2782 let ep1 = Endpoint::builder(presets::Minimal) +2783 .address_lookup(disco.clone()) +2784 .alpns(vec![TEST_ALPN.to_vec()]) +2785 .bind() +2786 .await?; +2787 +2788 let ep2 = Endpoint::builder(presets::Minimal) +2789 .address_lookup(disco.clone()) +2790 .alpns(vec![TEST_ALPN.to_vec()]) +2791 .bind() +2792 .await?; +2793 +2794 disco.add_endpoint_info(ep1.addr()); +2795 disco.add_endpoint_info(ep2.addr()); +2796 +2797 let ep1_endpointid = ep1.id(); +2798 let ep2_endpointid = ep2.id(); +2799 eprintln!("endpoint id 1 {ep1_endpointid}"); +2800 eprintln!("endpoint id 2 {ep2_endpointid}"); +2801 +2802 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { +2803 let conn = ep.connect(dst, TEST_ALPN).await?; +2804 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2805 info!("sending hello"); +2806 send.write_all(b"hello").await.anyerr()?; +2807 send.finish().anyerr()?; +2808 info!("receiving world"); +2809 let m = recv.read_to_end(100).await.anyerr()?; +2810 assert_eq!(m, b"world"); +2811 conn.close(1u8.into(), b"done"); +2812 Ok(()) +2813 } +2814 +2815 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { +2816 let incoming = ep.accept().await.anyerr()?; +2817 let mut iconn = incoming.accept().anyerr()?; +2818 let alpn = iconn.alpn().await?; +2819 let conn = iconn.await.anyerr()?; +2820 let endpoint_id = conn.remote_id(); +2821 assert_eq!(endpoint_id, src); +2822 assert_eq!(alpn, TEST_ALPN); +2823 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2824 info!("receiving hello"); +2825 let m = recv.read_to_end(100).await.anyerr()?; +2826 assert_eq!(m, b"hello"); +2827 info!("sending hello"); +2828 send.write_all(b"world").await.anyerr()?; +2829 send.finish().anyerr()?; +2830 match conn.closed().await { +2831 ConnectionError::ApplicationClosed(closed) => { +2832 assert_eq!(closed.error_code, 1u8.into()); +2833 Ok(()) +2834 } +2835 _ => panic!("wrong close error"), +2836 } +2837 } +2838 +2839 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( +2840 info_span!( +2841 "p1_accept", +2842 ep1 = %ep1.id().fmt_short(), +2843 dst = %ep2_endpointid.fmt_short(), +2844 ), +2845 )); +2846 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( +2847 info_span!( +2848 "p2_accept", +2849 ep2 = %ep2.id().fmt_short(), +2850 dst = %ep1_endpointid.fmt_short(), +2851 ), +2852 )); +2853 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( +2854 info_span!( +2855 "p1_connect", +2856 ep1 = %ep1.id().fmt_short(), +2857 dst = %ep2_endpointid.fmt_short(), +2858 ), +2859 )); +2860 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( +2861 info_span!( +2862 "p2_connect", +2863 ep2 = %ep2.id().fmt_short(), +2864 dst = %ep1_endpointid.fmt_short(), +2865 ), +2866 )); +2867 +2868 p1_accept.await.anyerr()??; +2869 p2_accept.await.anyerr()??; +2870 p1_connect.await.anyerr()??; +2871 p2_connect.await.anyerr()??; +2872 +2873 Ok(()) +2874 } +2875 +2876 #[tokio::test] +2877 #[traced_test] +2878 async fn test_direct_addresses_no_qad_relay() -> Result { +2879 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +2880 +2881 let ep = Endpoint::builder(presets::Minimal) +2882 .relay_mode(RelayMode::Custom(relay_map)) +2883 .alpns(vec![TEST_ALPN.to_vec()]) +2884 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2885 .bind() +2886 .await?; +2887 +2888 assert!(ep.addr().ip_addrs().count() > 0); +2889 +2890 Ok(()) +2891 } +2892 +2893 /// Test that configured external addresses are included in the endpoint's +2894 /// direct addresses, both when set via builder and at runtime. +2895 #[tokio::test(flavor = "current_thread", start_paused = true)] +2896 #[traced_test] +2897 async fn test_external_addr() -> Result { +2898 let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345)); +2899 +2900 // Test builder-configured external address +2901 let ep = Endpoint::builder(presets::Minimal) +2902 .external_addr(configured_addr) +2903 .bind() +2904 .await?; +2905 +2906 let addr = ep.addr(); +2907 assert!( +2908 addr.ip_addrs().any(|a| *a == configured_addr), +2909 "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}" +2910 ); +2911 +2912 // Test runtime add +2913 let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321)); +2914 ep.add_external_addr(runtime_addr).await; +2915 tokio::time::sleep(Duration::from_millis(100)).await; +2916 +2917 let addr = ep.addr(); +2918 assert!( +2919 addr.ip_addrs().any(|a| *a == runtime_addr), +2920 "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}" +2921 ); +2922 +2923 // Test runtime remove +2924 let removed = ep.remove_external_addr(&runtime_addr).await; +2925 assert!(removed); +2926 tokio::time::sleep(Duration::from_millis(100)).await; +2927 +2928 let addr = ep.addr(); +2929 assert!( +2930 !addr.ip_addrs().any(|a| *a == runtime_addr), +2931 "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}" +2932 ); +2933 assert!( +2934 addr.ip_addrs().any(|a| *a == configured_addr), +2935 "builder-configured external addr should still be present: {addr:?}" +2936 ); +2937 +2938 ep.close().await; +2939 Ok(()) +2940 } +2941 +2942 #[tokio::test] +2943 #[traced_test] +2944 async fn graceful_close() -> Result { +2945 let client = Endpoint::bind(presets::Minimal).await?; +2946 let server = Endpoint::builder(presets::Minimal) +2947 .alpns(vec![TEST_ALPN.to_vec()]) +2948 .bind() +2949 .await?; +2950 let server_addr = server.addr(); +2951 let server_task = tokio::spawn(async move { +2952 let incoming = server.accept().await.anyerr()?; +2953 let conn = incoming.await.anyerr()?; +2954 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2955 let msg = recv.read_to_end(1_000).await.anyerr()?; +2956 send.write_all(&msg).await.anyerr()?; +2957 send.finish().anyerr()?; +2958 let close_reason = conn.closed().await; +2959 Ok::<_, Error>(close_reason) +2960 }); +2961 +2962 let conn = client.connect(server_addr, TEST_ALPN).await?; +2963 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2964 send.write_all(b"Hello, world!").await.anyerr()?; +2965 send.finish().anyerr()?; +2966 recv.read_to_end(1_000).await.anyerr()?; +2967 conn.close(42u32.into(), b"thanks, bye!"); +2968 client.close().await; +2969 +2970 let close_err = server_task.await.anyerr()??; +2971 let ConnectionError::ApplicationClosed(app_close) = close_err else { +2972 panic!("Unexpected close reason: {close_err:?}"); +2973 }; +2974 +2975 assert_eq!(app_close.error_code, 42u32.into()); +2976 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +2977 +2978 Ok(()) +2979 } +2980 +2981 #[cfg(feature = "metrics")] +2982 #[tokio::test] +2983 #[traced_test] +2984 async fn metrics_smoke() -> Result { +2985 use iroh_metrics::Registry; +2986 +2987 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +2988 let client = Endpoint::builder(presets::Minimal) +2989 .secret_key(secret_key) +2990 .bind() +2991 .await?; +2992 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +2993 let server = Endpoint::builder(presets::Minimal) +2994 .secret_key(secret_key) +2995 .alpns(vec![TEST_ALPN.to_vec()]) +2996 .bind() +2997 .await?; +2998 let server_addr = server.addr(); +2999 let server_task = tokio::task::spawn(async move { +3000 let conn = server.accept().await.anyerr()?.await.anyerr()?; +3001 let mut uni = conn.accept_uni().await.anyerr()?; +3002 uni.read_to_end(10).await.anyerr()?; +3003 drop(conn); +3004 Ok::<_, Error>(server) +3005 }); +3006 let conn = client.connect(server_addr, TEST_ALPN).await?; +3007 let mut uni = conn.open_uni().await.anyerr()?; +3008 uni.write_all(b"helloworld").await.anyerr()?; +3009 uni.finish().anyerr()?; +3010 conn.closed().await; +3011 drop(conn); +3012 let server = server_task.await.anyerr()??; +3013 +3014 let m = client.metrics(); +3015 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3016 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3017 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3018 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3019 assert!(m.socket.recv_datagrams.get() > 0); +3020 +3021 let m = server.metrics(); +3022 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3023 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3024 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3025 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3026 assert!(m.socket.recv_datagrams.get() > 0); +3027 +3028 // test openmetrics encoding with labeled subregistries per endpoint +3029 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +3030 let id = endpoint.id().fmt_short(); +3031 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); +3032 sub_registry.register_all(endpoint.metrics()); +3033 } +3034 let mut registry = Registry::default(); +3035 register_endpoint(&mut registry, &client); +3036 register_endpoint(&mut registry, &server); +3037 // let s = registry.encode_openmetrics_to_string().anyerr()?; +3038 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); +3039 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); +3040 Ok(()) +3041 } +3042 +3043 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +3044 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +3045 async fn alpn_connection_test( +3046 accept_alpns: Vec<Vec<u8>>, +3047 primary_connect_alpn: &[u8], +3048 secondary_connect_alpns: Vec<Vec<u8>>, +3049 ) -> Result<Vec<u8>> { +3050 let client = Endpoint::bind(presets::Minimal).await?; +3051 let server = Endpoint::builder(presets::Minimal) +3052 .alpns(accept_alpns) +3053 .bind() +3054 .await?; +3055 let server_addr = server.addr(); +3056 let server_task = tokio::spawn({ +3057 let server = server.clone(); +3058 async move { +3059 let incoming = server.accept().await.anyerr()?; +3060 let conn = incoming.await.anyerr()?; +3061 conn.close(0u32.into(), b"bye!"); +3062 n0_error::Ok(conn.alpn().to_vec()) +3063 } +3064 }); +3065 +3066 let conn = client +3067 .connect_with_opts( +3068 server_addr, +3069 primary_connect_alpn, +3070 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +3071 ) +3072 .await?; +3073 let conn = conn.await.anyerr()?; +3074 let client_alpn = conn.alpn(); +3075 conn.closed().await; +3076 client.close().await; +3077 server.close().await; +3078 +3079 let server_alpn = server_task.await.anyerr()??; +3080 +3081 assert_eq!(client_alpn, server_alpn); +3082 +3083 Ok(server_alpn.to_vec()) +3084 } +3085 +3086 #[tokio::test] +3087 #[traced_test] +3088 async fn connect_multiple_alpn_negotiated() -> Result { +3089 const ALPN_ONE: &[u8] = b"alpn/1"; +3090 const ALPN_TWO: &[u8] = b"alpn/2"; +3091 +3092 assert_eq!( +3093 alpn_connection_test( +3094 // Prefer version 2 over version 1 on the accept side +3095 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3096 ALPN_TWO, +3097 vec![ALPN_ONE.to_vec()], +3098 ) +3099 .await?, +3100 ALPN_TWO.to_vec(), +3101 "accept side prefers version 2 over 1" +3102 ); +3103 +3104 assert_eq!( +3105 alpn_connection_test( +3106 // Only support the old version +3107 vec![ALPN_ONE.to_vec()], +3108 ALPN_TWO, +3109 vec![ALPN_ONE.to_vec()], +3110 ) +3111 .await?, +3112 ALPN_ONE.to_vec(), +3113 "accept side only supports the old version" +3114 ); +3115 +3116 assert_eq!( +3117 alpn_connection_test( +3118 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3119 ALPN_ONE, +3120 vec![ALPN_TWO.to_vec()], +3121 ) +3122 .await?, +3123 ALPN_TWO.to_vec(), +3124 "connect side ALPN order doesn't matter" +3125 ); +3126 +3127 assert_eq!( +3128 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +3129 .await?, +3130 ALPN_ONE.to_vec(), +3131 "connect side only supports the old version" +3132 ); +3133 +3134 Ok(()) +3135 } +3136 +3137 #[tokio::test] +3138 #[traced_test] +3139 async fn watch_net_report() -> Result { +3140 let endpoint = Endpoint::builder(presets::Minimal) +3141 .relay_mode(RelayMode::Staging) +3142 .bind() +3143 .await?; +3144 +3145 // can get a first report +3146 endpoint.net_report().updated().await.anyerr()?; +3147 +3148 Ok(()) +3149 } +3150 +3151 /// Tests that initial connection establishment isn't extremely slow compared +3152 /// to subsequent connections. +3153 /// +3154 /// This is a time based test, but uses a very large ratio to reduce flakiness. +3155 /// It also does a number of connections to average out any anomalies. +3156 #[tokio::test] +3157 #[traced_test] +3158 async fn connect_multi_time() -> Result { +3159 let n = 32; +3160 +3161 const NOOP_ALPN: &[u8] = b"noop"; +3162 +3163 #[derive(Debug, Clone)] +3164 struct Noop; +3165 +3166 impl ProtocolHandler for Noop { +3167 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +3168 connection.closed().await; +3169 Ok(()) +3170 } +3171 } +3172 +3173 async fn noop_server() -> Result<(Router, EndpointAddr)> { +3174 let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?; +3175 let addr = endpoint.addr(); +3176 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); +3177 Ok((router, addr)) +3178 } +3179 +3180 let routers = stream::iter(0..n) +3181 .map(|_| noop_server()) +3182 .buffered_unordered(32) +3183 .collect::<Vec<_>>() +3184 .await +3185 .into_iter() +3186 .collect::<Result<Vec<_>, _>>() +3187 .anyerr()?; +3188 +3189 let addrs = routers +3190 .iter() +3191 .map(|(_, addr)| addr.clone()) +3192 .collect::<Vec<_>>(); +3193 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); +3194 let address_lookup = MemoryLookup::from_endpoint_info(addrs); +3195 let endpoint = Endpoint::builder(presets::Minimal) +3196 .address_lookup(address_lookup) +3197 .bind() +3198 .await +3199 .anyerr()?; +3200 // wait for the endpoint to be initialized. This should not be needed, +3201 // but we don't want to measure endpoint init time but connection time +3202 // from a fully initialized endpoint. +3203 endpoint.addr(); +3204 let t0 = Instant::now(); +3205 for id in &ids { +3206 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3207 conn.close(0u32.into(), b"done"); +3208 } +3209 let dt0 = t0.elapsed().as_secs_f64(); +3210 let t1 = Instant::now(); +3211 for id in &ids { +3212 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3213 conn.close(0u32.into(), b"done"); +3214 } +3215 let dt1 = t1.elapsed().as_secs_f64(); +3216 +3217 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); +3218 Ok(()) +3219 } +3220 +3221 #[tokio::test] +3222 async fn test_custom_relay() -> Result { +3223 let _ep = Endpoint::builder(presets::Minimal) +3224 .relay_mode(RelayMode::custom([RelayUrl::from_str( +3225 "https://use1-1.relay.n0.iroh-canary.iroh.link.", +3226 )?])) +3227 .bind() +3228 .await?; +3229 +3230 let relays = RelayMap::try_from_iter([ +3231 "https://use1-1.relay.n0.iroh.iroh.link/", +3232 "https://euc1-1.relay.n0.iroh.iroh.link/", +3233 ])?; +3234 let _ep = Endpoint::builder(presets::Minimal) +3235 .relay_mode(RelayMode::Custom(relays)) +3236 .bind() +3237 .await?; +3238 +3239 Ok(()) +3240 } +3241 +3242 /// Testing bind_addr: Clear IP transports and add single IPv4 bind +3243 #[tokio::test] +3244 #[traced_test] +3245 async fn test_bind_addr_clear() -> Result { +3246 let ep = Endpoint::builder(presets::Minimal) +3247 .clear_ip_transports() +3248 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3249 .bind() +3250 .await?; +3251 let bound_sockets = ep.bound_sockets(); +3252 assert_eq!(bound_sockets.len(), 1); +3253 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); +3254 ep.close().await; +3255 Ok(()) +3256 } +3257 +3258 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind +3259 /// +3260 /// This will bind two sockets: default wildcard bind for IPv6, and our +3261 /// manually-added IPv4 bind. +3262 #[tokio::test] +3263 #[traced_test] +3264 async fn test_bind_addr_no_clear() -> Result { +3265 let ep = Endpoint::builder(presets::Minimal) +3266 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3267 .bind() +3268 .await?; +3269 let bound_sockets = ep.bound_sockets(); +3270 assert_eq!(bound_sockets.len(), 2); +3271 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3272 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3273 // Test that our manually added socket is there +3274 assert!( +3275 bound_sockets +3276 .iter() +3277 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3278 ); +3279 ep.close().await; +3280 Ok(()) +3281 } +3282 +3283 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. +3284 // +3285 // This replaces the default IPv4 bind added by the builder, +3286 // but keeps the default wildcard IPv6 bind. +3287 #[tokio::test] +3288 #[traced_test] +3289 async fn test_bind_addr_default() -> Result { +3290 let ep = Endpoint::builder(presets::Minimal) +3291 .bind_addr_with_opts( +3292 (Ipv4Addr::LOCALHOST, 0), +3293 BindOpts::default().set_is_default_route(true), +3294 )? +3295 .bind() +3296 .await?; +3297 let bound_sockets = ep.bound_sockets(); +3298 assert_eq!(bound_sockets.len(), 2); +3299 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3300 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3301 assert!( +3302 bound_sockets +3303 .iter() +3304 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3305 ); +3306 ep.close().await; +3307 drop(ep); +3308 +3309 Ok(()) +3310 } +3311 +3312 /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len +3313 /// +3314 /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our +3315 /// manually-added IPv4 bind. +3316 #[tokio::test] +3317 #[traced_test] +3318 async fn test_bind_addr_nonzero_prefix() -> Result { +3319 let ep = Endpoint::builder(presets::Minimal) +3320 .bind_addr_with_opts( +3321 (Ipv4Addr::LOCALHOST, 0), +3322 BindOpts::default().set_prefix_len(32), +3323 )? +3324 .bind() +3325 .await?; +3326 let bound_sockets = ep.bound_sockets(); +3327 assert_eq!(bound_sockets.len(), 3); +3328 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); +3329 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3330 // Test that the default wildcard socket is there +3331 assert!( +3332 bound_sockets +3333 .iter() +3334 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3335 ); +3336 // Test that our manually added socket is there +3337 assert!( +3338 bound_sockets +3339 .iter() +3340 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3341 ); +3342 ep.close().await; +3343 Ok(()) +3344 } +3345 +3346 /// Bind on an unusable port with the default opts. +3347 /// +3348 /// Binding the endpoint fails with an AddrInUse error. +3349 #[tokio::test] +3350 #[traced_test] +3351 async fn test_bind_addr_badport() -> Result { +3352 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3353 let port = socket.local_addr()?.port(); +3354 +3355 let res = Endpoint::builder(presets::Minimal) +3356 .clear_ip_transports() +3357 .bind_addr((Ipv4Addr::LOCALHOST, port))? +3358 .bind() +3359 .await; +3360 +3361 assert!(matches!( +3362 res, +3363 Err(BindError::Sockets { +3364 source: io_error, +3365 .. +3366 }) +3367 if io_error.kind() == io::ErrorKind::AddrInUse +3368 )); +3369 Ok(()) +3370 } +3371 +3372 /// Bind a non-default route on an unusable port, but set is_required = false. +3373 /// +3374 /// Binding the endpoint succeeds. +3375 #[tokio::test] +3376 #[traced_test] +3377 async fn test_bind_addr_badport_notrequired() -> Result { +3378 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3379 let port = socket.local_addr()?.port(); +3380 +3381 let ep = Endpoint::builder(presets::Minimal) +3382 .bind_addr_with_opts( +3383 (Ipv4Addr::LOCALHOST, port), +3384 BindOpts::default() +3385 .set_prefix_len(32) +3386 .set_is_required(false), +3387 )? +3388 .bind() +3389 .await?; +3390 let bound_sockets = ep.bound_sockets(); +3391 // just the default wildcard binds +3392 assert_eq!(bound_sockets.len(), 2); +3393 // our requested bind addr is not included because it failed to bind +3394 assert!( +3395 !bound_sockets +3396 .iter() +3397 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3398 ); +3399 Ok(()) +3400 } +3401 +3402 /// Bind on a default route on an unusable port, but set is_required = false. +3403 /// +3404 /// Binding the endpoint succeeds. +3405 #[tokio::test] +3406 #[traced_test] +3407 async fn test_bind_addr_badport_default_notrequired() -> Result { +3408 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3409 let port = socket.local_addr()?.port(); +3410 +3411 let ep = Endpoint::builder(presets::Minimal) +3412 .bind_addr_with_opts( +3413 (Ipv4Addr::LOCALHOST, port), +3414 BindOpts::default().set_is_required(false), +3415 )? +3416 .bind() +3417 .await?; +3418 let bound_sockets = ep.bound_sockets(); +3419 // just the IPv6 default, but no IPv4 bind at all because we replaced the default +3420 // with a bind with an unusable port and set it to not be required. +3421 assert_eq!(bound_sockets.len(), 1); +3422 assert!(bound_sockets[0].is_ipv6()); +3423 Ok(()) +3424 } +3425 +3426 /// Bind on an unusable port, with is_required = false, and no other transports. +3427 /// +3428 /// Binding the endpoint fails with "no valid address available". +3429 #[tokio::test] +3430 #[traced_test] +3431 async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result { +3432 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3433 let port = socket.local_addr()?.port(); +3434 +3435 let res = Endpoint::builder(presets::Minimal) +3436 .clear_ip_transports() +3437 .bind_addr_with_opts( +3438 (Ipv4Addr::LOCALHOST, port), +3439 BindOpts::default().set_is_required(false), +3440 )? +3441 .bind() +3442 .await; +3443 +3444 assert!(matches!( +3445 res, +3446 Err(BindError::CreateQuicEndpoint { +3447 source: io_error, +3448 .. +3449 }) +3450 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" +3451 )); +3452 Ok(()) +3453 } +3454 +3455 /// Bind with prefix len 0 but set the route as non-default. +3456 #[tokio::test] +3457 #[traced_test] +3458 async fn test_bind_addr_prefix_len_0_not_default() -> Result { +3459 let ep = Endpoint::builder(presets::Minimal) +3460 .bind_addr_with_opts( +3461 (Ipv4Addr::LOCALHOST, 0), +3462 BindOpts::default().set_is_default_route(false), +3463 )? +3464 .bind() +3465 .await?; +3466 let bound_sockets = ep.bound_sockets(); +3467 // The two default wildcard binds plus our additional route (which does not replace the default route +3468 // because we set is_default_route to false explicitly). +3469 assert_eq!(bound_sockets.len(), 3); +3470 assert!( +3471 bound_sockets +3472 .iter() +3473 .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED)) +3474 ); +3475 assert!( +3476 bound_sockets +3477 .iter() +3478 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3479 ); +3480 assert!( +3481 bound_sockets +3482 .iter() +3483 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3484 ); +3485 Ok(()) +3486 } +3487 +3488 #[ignore = "flaky"] +3489 #[tokio::test] +3490 #[traced_test] +3491 async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result { +3492 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3493 let qlog = Arc::new(QlogFileGroup::from_env( +3494 "connect_via_relay_becomes_direct_and_sends_direct", +3495 )); +3496 let transfer_size = 1_000_000; +3497 +3498 async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> { +3499 let mut stats = BTreeMap::new(); +3500 while let Some(event) = events.next().await { +3501 if let PathEvent::Closed { +3502 remote_addr, +3503 last_stats, +3504 .. +3505 } = event +3506 { +3507 stats.insert(remote_addr, *last_stats); +3508 } +3509 } +3510 stats +3511 } +3512 +3513 let client = Endpoint::builder(presets::Minimal) +3514 .relay_mode(RelayMode::Custom(relay_map.clone())) +3515 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3516 .transport_config(qlog.create("client")?) +3517 .bind() +3518 .await?; +3519 let server = Endpoint::builder(presets::Minimal) +3520 .relay_mode(RelayMode::Custom(relay_map)) +3521 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3522 .transport_config(qlog.create("server")?) +3523 .alpns(vec![TEST_ALPN.to_vec()]) +3524 .bind() +3525 .await?; +3526 let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url); +3527 let server_task = tokio::spawn(async move { +3528 let incoming = server.accept().await.anyerr()?; +3529 let conn = incoming.await.anyerr()?; +3530 let stats_task = tokio::spawn(collect_stats(conn.path_events())); +3531 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +3532 let msg = recv.read_to_end(transfer_size).await.anyerr()?; +3533 send.write_all(&msg).await.anyerr()?; +3534 send.finish().anyerr()?; +3535 conn.closed().await; +3536 let stats = stats_task.await.expect("stats task panicked"); +3537 Ok::<_, Error>(stats) +3538 }); +3539 +3540 let conn = client.connect(server_addr, TEST_ALPN).await?; +3541 let client_stats_task = tokio::spawn(collect_stats(conn.path_events())); +3542 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +3543 send.write_all(&vec![42u8; transfer_size]).await.anyerr()?; +3544 send.finish().anyerr()?; +3545 recv.read_to_end(transfer_size).await.anyerr()?; +3546 conn.close(0u32.into(), b"thanks, bye!"); +3547 client.close().await; +3548 let client_stats = client_stats_task.await.expect("stats task panicked"); +3549 let server_stats = server_task.await.anyerr()??; +3550 +3551 info!("client stats: {client_stats:#?}"); +3552 info!("server stats: {server_stats:#?}"); +3553 +3554 let client_total_relay_tx = client_stats +3555 .iter() +3556 .filter(|(remote, _stats)| remote.is_relay()) +3557 .map(|(_, stats)| stats.udp_tx.bytes) +3558 .sum::<u64>(); +3559 let client_total_relay_rx = client_stats +3560 .iter() +3561 .filter(|(remote, _stats)| remote.is_relay()) +3562 .map(|(_, stats)| stats.udp_rx.bytes) +3563 .sum::<u64>(); +3564 let server_total_relay_tx = server_stats +3565 .iter() +3566 .filter(|(remote, _stats)| remote.is_relay()) +3567 .map(|(_, stats)| stats.udp_tx.bytes) +3568 .sum::<u64>(); +3569 let server_total_relay_rx = server_stats +3570 .iter() +3571 .filter(|(remote, _stats)| remote.is_relay()) +3572 .map(|(_, stats)| stats.udp_rx.bytes) +3573 .sum::<u64>(); +3574 +3575 info!(?client_total_relay_tx, "total"); +3576 info!(?client_total_relay_rx, "total"); +3577 info!(?server_total_relay_tx, "total"); +3578 info!(?server_total_relay_rx, "total"); +3579 +3580 // We should send/receive only the minorty of traffic via the relay. +3581 assert!(client_total_relay_tx < transfer_size as u64 / 2); +3582 assert!(client_total_relay_rx < transfer_size as u64 / 2); +3583 assert!(server_total_relay_tx < transfer_size as u64 / 2); +3584 assert!(server_total_relay_rx < transfer_size as u64 / 2); +3585 +3586 Ok(()) +3587 } +3588 +3589 /// Tests that correct logs are emitted when connecting two endpoints with same secret keys to a relay. +3590 #[tokio::test] +3591 #[traced_test] +3592 async fn same_endpoint_id_relay() -> Result { +3593 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3594 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +3595 let secret_key = SecretKey::from_bytes(&rng.random()); +3596 +3597 let client = Endpoint::builder(presets::Minimal) +3598 .relay_mode(RelayMode::Custom(relay_map.clone())) +3599 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3600 .bind() +3601 .instrument(error_span!("ep-client")) +3602 .await?; +3603 +3604 info!("client {}", client.id()); +3605 +3606 // bind ep1 and wait until connected to relay. +3607 let ep1 = Endpoint::builder(presets::Minimal) +3608 .relay_mode(RelayMode::Custom(relay_map.clone())) +3609 .secret_key(secret_key.clone()) +3610 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3611 .alpns(vec![TEST_ALPN.to_vec()]) +3612 .bind() +3613 .instrument(error_span!("ep1")) +3614 .await?; +3615 info!("ep1 bound {:?}", ep1.id()); +3616 ep1.online().await; +3617 info!("ep1 online"); +3618 +3619 let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone()); +3620 +3621 tokio::try_join!( +3622 async { +3623 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3624 let reason = conn.closed().await; +3625 assert!(is_application_closed(&reason, 1)); +3626 n0_error::Ok(()) +3627 }, +3628 async { +3629 let conn = ep1.accept().await.unwrap().await?; +3630 conn.close(1u32.into(), b"bye"); +3631 n0_error::Ok(()) +3632 } +3633 )?; +3634 info!("client connected to ep1"); +3635 +3636 // now start second endpoint with same secret key +3637 let ep2 = Endpoint::builder(presets::Minimal) +3638 .relay_mode(RelayMode::Custom(relay_map)) +3639 .secret_key(secret_key.clone()) +3640 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3641 .alpns(vec![TEST_ALPN.to_vec()]) +3642 .bind() +3643 .instrument(error_span!("ep2")) +3644 .await?; +3645 info!("ep2 bound {:?}", ep2.id()); +3646 ep2.online().await; +3647 println!("ep2 online"); +3648 +3649 // `online` does not mean that the connection to the home relay was *established*, +3650 // only that the home relay was *chosen* based on the net report probes. +3651 // We need to wait for the connection to be established though, to be sure that new packets +3652 // will be routed to the new endpoint and not to the old endpoint anymore. +3653 // We don't expose being connected to the home relay on the endpoint currently, +3654 // so we resort to log assertions. +3655 // TODO(Frando): Replace once we add a proper API for this. +3656 let expected_log_line = format!( +3657 "ep2:endpoint{{id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected", +3658 ep2.id().fmt_short() +3659 ); +3660 tokio::time::timeout(Duration::from_secs(5), async { +3661 while !logs_contain(&expected_log_line) { +3662 tokio::time::sleep(Duration::from_millis(10)).await +3663 } +3664 }) +3665 .await +3666 .std_context("relay connection did not establish in time")?; +3667 +3668 tokio::try_join!( +3669 async { +3670 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3671 let reason = conn.closed().await; +3672 assert!(is_application_closed(&reason, 1)); +3673 n0_error::Ok(()) +3674 }, +3675 async { +3676 let conn = ep2.accept().await.unwrap().await?; +3677 conn.close(1u32.into(), b"bye"); +3678 n0_error::Ok(()) +3679 } +3680 )?; +3681 println!("client connected to ep2"); +3682 +3683 // assert that ep1 did not receive a connection +3684 assert!(now_or_never(ep1.accept()).is_none()); +3685 +3686 // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2. +3687 logs_assert(|logs| { +3688 let expected_line = |line: &str| { +3689 line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received") +3690 }; +3691 let count_line_ep1 = logs +3692 .iter() +3693 .filter(|line| line.contains(":ep1:") && expected_line(line)) +3694 .count(); +3695 let count_line_ep2 = logs +3696 .iter() +3697 .filter(|line| line.contains(":ep2:") && expected_line(line)) +3698 .count(); +3699 if count_line_ep1 == 1 && count_line_ep2 == 0 { +3700 Ok(()) +3701 } else { +3702 Err("Logs don't match expectations".to_string()) +3703 } +3704 }); +3705 tokio::join!(ep1.close(), ep2.close(), client.close()); +3706 Ok(()) +3707 } +3708 +3709 fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool { +3710 matches!( +3711 close_reason, +3712 ConnectionError::ApplicationClosed(f) if f.error_code ==code.into() +3713 ) +3714 } +3715 +3716 #[tokio::test] +3717 #[traced_test] +3718 async fn test_closed_endpoint_behaviour() -> Result { +3719 // create endpoint +3720 // call endpoint.close +3721 // ensure methods behave in the expected way +3722 info!("Creating endpoint"); +3723 let ep = Endpoint::builder(presets::N0).bind().await?; +3724 let closed = ep.closed(); +3725 info!("Closing endpoint"); +3726 let now = Instant::now(); +3727 ep.close().await; +3728 info!("Endpoint closed in {:?}", now.elapsed()); +3729 +3730 // Assert that the `closed` cancellation token is now cancelled +3731 assert_eq!(now_or_never(closed), Some(())); +3732 +3733 info!("Set ALPNS fails silently"); +3734 ep.set_alpns(vec![b"test".into()]); +3735 +3736 info!("Insert Relay returns None"); +3737 let relay_config = crate::defaults::staging::default_na_east_relay(); +3738 assert!( +3739 ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) +3740 .await +3741 .is_none() +3742 ); +3743 +3744 info!("Remove Relay returns None"); +3745 assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); +3746 +3747 info!("Connecting"); +3748 let mut rng = ChaCha8Rng::seed_from_u64(41); +3749 let ep_id = SecretKey::from_bytes(&rng.random()).public(); +3750 +3751 // should likely be an error that states that the +3752 // endpoint is closed instead: +3753 if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() +3754 { +3755 assert!(matches!( +3756 source, +3757 ConnectWithOptsError::EndpointClosed { .. } +3758 )); +3759 } else { +3760 panic!("unexpected error for connect"); +3761 } +3762 +3763 info!("Accepting!"); +3764 assert!(ep.accept().await.is_none()); +3765 +3766 // this should work +3767 info!("Addr: {:?}", ep.addr()); +3768 +3769 // create watchers to verify they terminate after the endpoint is dropped. +3770 let mut addrs = ep.watch_addr().stream(); +3771 let mut net_reports = ep.net_report().stream(); +3772 +3773 // returns None +3774 let net_report = ep.last_net_report(); +3775 info!("last Net report {net_report:?}"); +3776 +3777 // this should work +3778 let sockets = ep.bound_sockets(); +3779 info!("Sockets: {sockets:?}"); +3780 +3781 // these should return errors +3782 assert!(ep.dns_resolver().is_err()); +3783 assert!(ep.address_lookup().is_err()); +3784 +3785 #[cfg(feature = "metrics")] +3786 { +3787 // this should work +3788 let metrics = ep.metrics(); +3789 info!("Metrics: {metrics:?}"); +3790 } +3791 +3792 // this should return none +3793 assert!(ep.remote_info(ep_id).await.is_none()); +3794 +3795 // this should fail silently +3796 ep.network_change().await; +3797 +3798 // this should fail silently +3799 ep.set_user_data_for_address_lookup(Some( +3800 UserData::try_from("TEST".to_string()).expect("valid string"), +3801 )); +3802 drop(ep); +3803 // now that the endpoint is dropped, all watchers should terminate. +3804 tokio::time::timeout(Duration::from_secs(1), async { +3805 while let Some(addr) = addrs.next().await { +3806 info!("Addrs stream: {addr:?}"); +3807 } +3808 while let Some(net_report) = net_reports.next().await { +3809 info!("Net report stream: {net_report:?}"); +3810 } +3811 }) +3812 .await +3813 .expect("watchers not closed"); +3814 +3815 info!("Done!"); +3816 Ok(()) +3817 } +3818 +3819 #[tokio::test] +3820 #[traced_test] +3821 async fn test_closed_endpoint_unpolled_accept_fut() -> Result { +3822 info!("Creating endpoint"); +3823 let ep = Endpoint::builder(presets::N0).bind().await?; +3824 +3825 info!("Get accept future"); +3826 let accept_fut = ep.accept(); +3827 +3828 info!("Closing endpoint"); +3829 let now = Instant::now(); +3830 tokio::time::timeout(Duration::from_secs(5), ep.close()) +3831 .await +3832 .expect("Endpoint closes in a reasonable time"); +3833 info!("Endpoint closed in {:?}", now.elapsed()); +3834 +3835 info!("Accept future returns None after the endpoint has closed"); +3836 let incoming = accept_fut.await; +3837 assert!(incoming.is_none()); +3838 Ok(()) +3839 } +3840 +3841 #[tokio::test] +3842 #[traced_test] +3843 async fn test_closed_endpoint_polled_accept_fut() -> Result { +3844 info!("Creating endpoint"); +3845 let ep = Endpoint::builder(presets::N0).bind().await?; +3846 +3847 info!("Run an accept task"); +3848 let ep2 = ep.clone(); +3849 let accept_task = tokio::spawn(async move { +3850 info!("Waiting on Accept"); +3851 let res = ep2.accept().await; +3852 info!("Accept await has returned"); +3853 res +3854 }); +3855 +3856 // Try to ensure the accept future is polled at least once. +3857 tokio::time::sleep(Duration::from_millis(10)).await; +3858 +3859 info!("Closing the endpoint"); +3860 tokio::time::timeout(Duration::from_secs(5), ep.close()) +3861 .await +3862 .expect("Endpoint closes in a reasonable time"); +3863 info!("Endpoint closed"); +3864 +3865 info!("Await the accept task"); +3866 let incoming = accept_task.await.expect("accept task panicked"); +3867 assert!(incoming.is_none()); +3868 +3869 Ok(()) +3870 } +3871 +3872 #[tokio::test] +3873 #[traced_test] +3874 async fn test_endpoint_online_add_relay() -> Result { +3875 let ep = Endpoint::builder(presets::Minimal) +3876 .relay_mode(RelayMode::Custom(RelayMap::empty())) +3877 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3878 .bind() +3879 .await?; +3880 // should not come online without relays. +3881 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +3882 assert!(res.is_err()); +3883 +3884 // should come online after a relay is added. +3885 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3886 ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap()) +3887 .await; +3888 let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await; +3889 assert!(res.is_ok()); +3890 +3891 // online should still return after endpoint close, if the endpoint was last online +3892 let ep_clone = ep.clone(); +3893 let task = tokio::task::spawn(async move { +3894 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +3895 }); +3896 ep.close().await; +3897 let res = task.await.unwrap(); +3898 assert!(res.is_ok()); +3899 Ok(()) +3900 } +3901 +3902 #[tokio::test] +3903 #[traced_test] +3904 async fn test_endpoint_online_close() -> Result { +3905 let ep = Endpoint::bind(presets::Minimal).await?; +3906 // should not come online without relays. +3907 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +3908 assert!(res.is_err()); +3909 +3910 // online should remain pending after the endpoint is closed. +3911 let ep_clone = ep.clone(); +3912 let task = tokio::task::spawn(async move { +3913 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +3914 }); +3915 ep.close().await; +3916 let res = task.await.unwrap(); +3917 assert!(res.is_err()); +3918 Ok(()) +3919 } +3920 +3921 /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] +3922 /// is admitted to a relay whose access control checks the token only when +3923 /// the token matches. +3924 #[tokio::test] +3925 #[traced_test] +3926 async fn test_endpoint_relay_auth_token() -> Result { +3927 const TOKEN: &str = "valid-token"; +3928 +3929 /// Admits a connection only if it carries the expected auth token. +3930 #[derive(Debug)] +3931 struct TokenAccess(&'static str); +3932 +3933 impl iroh_relay::server::AccessControl for TokenAccess { +3934 async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { +3935 if request.auth_token().as_deref() == Some(self.0) { +3936 Access::Allow +3937 } else { +3938 Access::Deny { reason: None } +3939 } +3940 } +3941 } +3942 +3943 let access = Arc::new(TokenAccess(TOKEN)); +3944 let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; +3945 +3946 // Wrong token: the connection attempt fails and last_error reports +3947 // the relay-side denial. +3948 let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None) +3949 .with_auth_token("wrong-token") +3950 .into(); +3951 let bad_ep = Endpoint::builder(presets::Minimal) +3952 .relay_mode(RelayMode::Custom(bad_map)) +3953 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3954 .bind() +3955 .await?; +3956 let mut stream = bad_ep.home_relay_status().stream(); +3957 let auth_err: String = tokio::time::timeout(Duration::from_secs(5), async { +3958 while let Some(status) = stream.next().await { +3959 if let Some(err) = status.iter().filter_map(|s| s.last_error()).next() { +3960 return format!("{err:#}"); +3961 } +3962 } +3963 panic!("home relay stream ended"); +3964 }) +3965 .await +3966 .std_context("waiting for auth error")?; +3967 assert!( +3968 auth_err.contains("not authorized"), +3969 "expected 'not authorized' in error, got: {auth_err}" +3970 ); +3971 +3972 // Correct token: the endpoint reaches the connected state. +3973 let good_map: RelayMap = RelayConfig::new(relay_url, None) +3974 .with_auth_token(TOKEN) +3975 .into(); +3976 let good_ep = Endpoint::builder(presets::Minimal) +3977 .relay_mode(RelayMode::Custom(good_map)) +3978 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3979 .bind() +3980 .await?; +3981 tokio::time::timeout(Duration::from_secs(5), good_ep.online()) +3982 .await +3983 .std_context("waiting for endpoint to come online")?; +3984 +3985 Ok(()) +3986 } +3987}
\ No newline at end of file diff --git a/pr/4324/docs/src/iroh/socket.rs.html b/pr/4324/docs/src/iroh/socket.rs.html index b265e47cb5..f358b64e46 100644 --- a/pr/4324/docs/src/iroh/socket.rs.html +++ b/pr/4324/docs/src/iroh/socket.rs.html @@ -42,7 +42,7 @@ 42 ip::LocalAddresses, 43}; 44use noq::{ -45 NetworkChangeHint, +45 NetworkChangeHint, TokenStore, 46 crypto::rustls::{QuicClientConfig, QuicServerConfig}, 47}; 48use rand::RngExt; @@ -238,2622 +238,2627 @@ 238 pub(crate) client_config: QuicClientConfig, 239 #[debug("Arc<RustlsTokenKey>")] 240 pub(crate) token_key: Arc<RustlsTokenKey>, -241 pub(crate) transport_config: QuicTransportConfig, -242} -243 -244impl StaticConfig { -245 /// Create a [`noq_proto::ServerConfig`] with the specified ALPN protocols. -246 pub(crate) fn create_server_config( -247 &self, -248 alpn_protocols: Vec<Vec<u8>>, -249 ) -> noq_proto::ServerConfig { -250 let mut quic_server_config = self.server_config.clone(); -251 quic_server_config.set_alpn_protocols(alpn_protocols); -252 let mut inner = -253 noq::ServerConfig::new(Arc::new(quic_server_config), self.token_key.clone()); -254 inner.transport_config(self.transport_config.to_inner_arc()); -255 inner -256 } -257 -258 /// Create a [`noq_proto::ClientConfig`] with the specified ALPN protocols. -259 pub(crate) fn create_client_config( -260 &self, -261 alpn_protocols: Vec<Vec<u8>>, -262 transport_config: Arc<noq::TransportConfig>, -263 ) -> noq_proto::ClientConfig { -264 let mut quic_client_config = self.client_config.clone(); -265 quic_client_config.set_alpn_protocols(alpn_protocols); -266 let mut inner = noq::ClientConfig::new(Arc::new(quic_client_config)); -267 inner.transport_config(transport_config); -268 inner -269 } -270} -271 -272/// This coordinates the shutdown of the [`Socket`] and all its tasks. -273/// -274/// It also tightly binds to the [`EndpointInner`] and [`Actor`] closing as that is where -275/// most of the logic lives. -276#[derive(Debug)] -277struct ShutdownState { -278 /// Token that is cancelled at the moment [`crate::Endpoint::close`] is called. -279 /// -280 /// Currently cancelled from [`EndpointInner::close`]. -281 at_close_start: CancellationToken, -282 /// Token that is cancelled once the [`noq::Endpoint`] is drained. -283 /// -284 /// Only 100ms after this is cancelled will the [`Actor`] task be cancelled, it should -285 /// have exited already by then as it is considered an error if it was still running. -286 at_endpoint_closed: CancellationToken, -287 /// Set if the endpoint is closed and all tasks are stopped. -288 /// -289 /// This is only set once both [`Self::at_close_start`] and [`Self::at_endpoint_closed`] -290 /// are cancelled **and** the [`Actor`] task is no longer running. -291 closed: AtomicBool, -292} -293 -294impl Default for ShutdownState { -295 fn default() -> Self { -296 Self { -297 at_close_start: CancellationToken::new(), -298 at_endpoint_closed: CancellationToken::new(), -299 closed: AtomicBool::new(false), -300 } -301 } -302} -303 -304impl ShutdownState { -305 /// Whether the endpoint has started closing, or is already closed. -306 /// -307 /// This is true once [`crate::Endpoint::close`] is called, and remains true forever -308 /// after. Tasks might still be shutting down. -309 fn is_closing(&self) -> bool { -310 self.at_close_start.is_cancelled() -311 } -312 -313 /// Whether the endpoint is fully closed and all tasks stopped. -314 /// -315 /// The endpoint will be drained, all transports and sockets will be closed. -316 fn is_closed(&self) -> bool { -317 self.closed.load(Ordering::Relaxed) -318 } -319} -320 -321/// Iroh connectivity layer. -322/// -323/// This is responsible for routing packets to endpoints based on endpoint IDs, it will initially -324/// route packets via a relay and transparently try and establish an endpoint-to-endpoint -325/// connection and upgrade to it. It will also keep looking for better connections as the -326/// network details of both endpoints change. -327/// -328/// It is usually only necessary to use a single [`Socket`] instance in an application, it -329/// means any QUIC endpoints on top will be sharing as much information about endpoints as -330/// possible. -331#[derive(Debug)] -332pub(crate) struct Socket { -333 /// Read-only view of the per-remote `RemoteStateActor` inboxes. -334 /// -335 /// Lets callers send to an existing `RemoteStateActor` without going through -336 /// the socket actor. +241 #[debug("Arc<dyn TokenStore>")] +242 pub(crate) token_store: Arc<dyn TokenStore>, +243 pub(crate) transport_config: QuicTransportConfig, +244} +245 +246impl StaticConfig { +247 /// Create a [`noq_proto::ServerConfig`] with the specified ALPN protocols. +248 pub(crate) fn create_server_config( +249 &self, +250 alpn_protocols: Vec<Vec<u8>>, +251 ) -> noq_proto::ServerConfig { +252 let mut quic_server_config = self.server_config.clone(); +253 quic_server_config.set_alpn_protocols(alpn_protocols); +254 let mut inner = +255 noq::ServerConfig::new(Arc::new(quic_server_config), self.token_key.clone()); +256 inner.transport_config(self.transport_config.to_inner_arc()); +257 inner +258 } +259 +260 /// Create a [`noq_proto::ClientConfig`] with the specified ALPN protocols. +261 pub(crate) fn create_client_config( +262 &self, +263 alpn_protocols: Vec<Vec<u8>>, +264 transport_config: Arc<noq::TransportConfig>, +265 ) -> noq_proto::ClientConfig { +266 let mut quic_client_config = self.client_config.clone(); +267 quic_client_config.set_alpn_protocols(alpn_protocols); +268 let mut inner = noq::ClientConfig::new(Arc::new(quic_client_config)); +269 inner.transport_config(transport_config); +270 inner.token_store(self.token_store.clone()); +271 inner +272 } +273} +274 +275/// This coordinates the shutdown of the [`Socket`] and all its tasks. +276/// +277/// It also tightly binds to the [`EndpointInner`] and [`Actor`] closing as that is where +278/// most of the logic lives. +279#[derive(Debug)] +280struct ShutdownState { +281 /// Token that is cancelled at the moment [`crate::Endpoint::close`] is called. +282 /// +283 /// Currently cancelled from [`EndpointInner::close`]. +284 at_close_start: CancellationToken, +285 /// Token that is cancelled once the [`noq::Endpoint`] is drained. +286 /// +287 /// Only 100ms after this is cancelled will the [`Actor`] task be cancelled, it should +288 /// have exited already by then as it is considered an error if it was still running. +289 at_endpoint_closed: CancellationToken, +290 /// Set if the endpoint is closed and all tasks are stopped. +291 /// +292 /// This is only set once both [`Self::at_close_start`] and [`Self::at_endpoint_closed`] +293 /// are cancelled **and** the [`Actor`] task is no longer running. +294 closed: AtomicBool, +295} +296 +297impl Default for ShutdownState { +298 fn default() -> Self { +299 Self { +300 at_close_start: CancellationToken::new(), +301 at_endpoint_closed: CancellationToken::new(), +302 closed: AtomicBool::new(false), +303 } +304 } +305} +306 +307impl ShutdownState { +308 /// Whether the endpoint has started closing, or is already closed. +309 /// +310 /// This is true once [`crate::Endpoint::close`] is called, and remains true forever +311 /// after. Tasks might still be shutting down. +312 fn is_closing(&self) -> bool { +313 self.at_close_start.is_cancelled() +314 } +315 +316 /// Whether the endpoint is fully closed and all tasks stopped. +317 /// +318 /// The endpoint will be drained, all transports and sockets will be closed. +319 fn is_closed(&self) -> bool { +320 self.closed.load(Ordering::Relaxed) +321 } +322} +323 +324/// Iroh connectivity layer. +325/// +326/// This is responsible for routing packets to endpoints based on endpoint IDs, it will initially +327/// route packets via a relay and transparently try and establish an endpoint-to-endpoint +328/// connection and upgrade to it. It will also keep looking for better connections as the +329/// network details of both endpoints change. +330/// +331/// It is usually only necessary to use a single [`Socket`] instance in an application, it +332/// means any QUIC endpoints on top will be sharing as much information about endpoints as +333/// possible. +334#[derive(Debug)] +335pub(crate) struct Socket { +336 /// Read-only view of the per-remote `RemoteStateActor` inboxes. 337 /// -338 /// A missing entry means no actor is running for that remote. Spawning new -339 /// `RemoteStateActor`s must go through the socket actor channel. -340 remote_actors: ReadOnlyMap<EndpointId, mpsc::Sender<RemoteStateMessage>>, -341 -342 // - Shutdown Management -343 shutdown: ShutdownState, +338 /// Lets callers send to an existing `RemoteStateActor` without going through +339 /// the socket actor. +340 /// +341 /// A missing entry means no actor is running for that remote. Spawning new +342 /// `RemoteStateActor`s must go through the socket actor channel. +343 remote_actors: ReadOnlyMap<EndpointId, mpsc::Sender<RemoteStateMessage>>, 344 -345 // - Networking Info -346 /// Our discovered direct addresses. -347 direct_addrs: DiscoveredDirectAddrs, -348 /// Our latest net-report -349 net_report: Watchable<(Option<Report>, UpdateReason)>, -350 /// If the last net_report report, reports IPv6 to be available. -351 ipv6_reported: Arc<AtomicBool>, -352 /// Maps for resolving mapped addrs to/from IP and relay addresses. -353 mapped_addrs: MappedAddrs, -354 -355 /// Local addresses -356 local_addrs_watch: LocalAddrsWatch, -357 home_relay_watch: HomeRelayWatcher, -358 /// Currently bound IP addresses of all sockets -359 #[cfg(not(wasm_browser))] -360 ip_bind_addrs: Vec<SocketAddr>, -361 /// The DNS resolver to be used in this socket. +345 // - Shutdown Management +346 shutdown: ShutdownState, +347 +348 // - Networking Info +349 /// Our discovered direct addresses. +350 direct_addrs: DiscoveredDirectAddrs, +351 /// Our latest net-report +352 net_report: Watchable<(Option<Report>, UpdateReason)>, +353 /// If the last net_report report, reports IPv6 to be available. +354 ipv6_reported: Arc<AtomicBool>, +355 /// Maps for resolving mapped addrs to/from IP and relay addresses. +356 mapped_addrs: MappedAddrs, +357 +358 /// Local addresses +359 local_addrs_watch: LocalAddrsWatch, +360 home_relay_watch: HomeRelayWatcher, +361 /// Currently bound IP addresses of all sockets 362 #[cfg(not(wasm_browser))] -363 dns_resolver: DnsResolver, -364 relay_map: RelayMap, -365 -366 /// Optional Address Lookup -367 address_lookup: address_lookup::AddressLookupServices, -368 /// Optional user-defined discover data. -369 address_lookup_user_data: RwLock<Option<UserData>>, -370 /// Explicitly configured external addresses to advertise. -371 configured_addrs: RwLock<BTreeSet<SocketAddr>>, -372 -373 pub(crate) tls_config: rustls::ClientConfig, -374 -375 /// Metrics -376 pub(crate) metrics: EndpointMetrics, -377 pub(crate) hooks: EndpointHooksList, -378 /// Tracing span for this endpoint. -379 pub(crate) span: Span, -380} -381 -382impl Socket { -383 /// Returns the relay endpoint we are connected to, that has the best latency. -384 /// -385 /// If `None`, then we are not connected to any relay endpoints. -386 pub(crate) fn my_relay(&self) -> Option<RelayUrl> { -387 self.local_addr().into_iter().find_map(|a| { -388 if let transports::Addr::Relay(url, _) = a { -389 Some(url) -390 } else { -391 None -392 } -393 }) -394 } -395 -396 /// Whether the iroh endpoint is closed and all its actors stopped. -397 pub(crate) fn is_closed(&self) -> bool { -398 self.shutdown.is_closed() -399 } -400 -401 /// Whether [`crate::Endpoint::close`] has been called. -402 fn is_closing(&self) -> bool { -403 self.shutdown.is_closing() -404 } -405 -406 /// Returns a future that resolves once endpoint shutdown has started. -407 pub(crate) fn closed(&self) -> WaitForCancellationFutureOwned { -408 self.shutdown.at_close_start.clone().cancelled_owned() -409 } -410 -411 /// Get the cached version of addresses. -412 pub(crate) fn local_addr(&self) -> Vec<transports::Addr> { -413 self.local_addrs_watch.clone().get() -414 } -415 -416 #[cfg(not(wasm_browser))] -417 fn ip_bind_addrs(&self) -> &[SocketAddr] { -418 &self.ip_bind_addrs -419 } -420 -421 fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> + use<> { -422 self.local_addr() -423 .into_iter() -424 .filter_map(|addr| addr.into_socket_addr()) -425 } -426 -427 /// Tries to send a [`RemoteStateMessage`] to the `RemoteStateActor` for given [`EndpointId`]. -428 /// -429 /// Returns an error if there currently is no remote state actor running for this, or when it -430 /// is currently shutting down. -431 pub(crate) fn try_send_remote_state_msg( -432 &self, -433 endpoint_id: EndpointId, -434 message: RemoteStateMessage, -435 ) -> Result<(), RemoteStateMessage> { -436 let Some(sender) = self.remote_actors.get(&endpoint_id) else { -437 return Err(message); -438 }; -439 sender.try_send(message).map_err(|err| err.into_inner()) -440 } -441 -442 /// Returns a [`Watcher`] for this socket's direct addresses. -443 /// -444 /// The [`Socket`] continuously monitors the direct addresses, the network addresses -445 /// it might be able to be contacted on, for changes. Whenever changes are detected -446 /// this [`Watcher`] will yield a new list of addresses. -447 /// -448 /// Upon the first creation on the [`Socket`] it may not yet have completed a first -449 /// net report to discover IP addresses, in this case the current item in this [`Watcher`] will be -450 /// [`None`]. Once the first set of ip addresses are discovered the [`Watcher`] will -451 /// store [`Some`] set of addresses. -452 /// -453 /// To get the current direct addresses, use [`Watcher::initialized`]. -454 /// -455 /// [`Watcher`]: n0_watcher::Watcher -456 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized -457 pub(crate) fn ip_addrs(&self) -> n0_watcher::Direct<BTreeSet<DirectAddr>> { -458 self.direct_addrs.addrs.watch() -459 } -460 -461 /// Returns a [`Watcher`] for this socket's net-report. -462 /// -463 /// The [`Socket`] continuously monitors the network conditions for changes. -464 /// Whenever changes are detected this [`Watcher`] will yield a new report. +363 ip_bind_addrs: Vec<SocketAddr>, +364 /// The DNS resolver to be used in this socket. +365 #[cfg(not(wasm_browser))] +366 dns_resolver: DnsResolver, +367 relay_map: RelayMap, +368 +369 /// Optional Address Lookup +370 address_lookup: address_lookup::AddressLookupServices, +371 /// Optional user-defined discover data. +372 address_lookup_user_data: RwLock<Option<UserData>>, +373 /// Explicitly configured external addresses to advertise. +374 configured_addrs: RwLock<BTreeSet<SocketAddr>>, +375 +376 pub(crate) tls_config: rustls::ClientConfig, +377 +378 /// Metrics +379 pub(crate) metrics: EndpointMetrics, +380 pub(crate) hooks: EndpointHooksList, +381 /// Tracing span for this endpoint. +382 pub(crate) span: Span, +383} +384 +385impl Socket { +386 /// Returns the relay endpoint we are connected to, that has the best latency. +387 /// +388 /// If `None`, then we are not connected to any relay endpoints. +389 pub(crate) fn my_relay(&self) -> Option<RelayUrl> { +390 self.local_addr().into_iter().find_map(|a| { +391 if let transports::Addr::Relay(url, _) = a { +392 Some(url) +393 } else { +394 None +395 } +396 }) +397 } +398 +399 /// Whether the iroh endpoint is closed and all its actors stopped. +400 pub(crate) fn is_closed(&self) -> bool { +401 self.shutdown.is_closed() +402 } +403 +404 /// Whether [`crate::Endpoint::close`] has been called. +405 fn is_closing(&self) -> bool { +406 self.shutdown.is_closing() +407 } +408 +409 /// Returns a future that resolves once endpoint shutdown has started. +410 pub(crate) fn closed(&self) -> WaitForCancellationFutureOwned { +411 self.shutdown.at_close_start.clone().cancelled_owned() +412 } +413 +414 /// Get the cached version of addresses. +415 pub(crate) fn local_addr(&self) -> Vec<transports::Addr> { +416 self.local_addrs_watch.clone().get() +417 } +418 +419 #[cfg(not(wasm_browser))] +420 fn ip_bind_addrs(&self) -> &[SocketAddr] { +421 &self.ip_bind_addrs +422 } +423 +424 fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> + use<> { +425 self.local_addr() +426 .into_iter() +427 .filter_map(|addr| addr.into_socket_addr()) +428 } +429 +430 /// Tries to send a [`RemoteStateMessage`] to the `RemoteStateActor` for given [`EndpointId`]. +431 /// +432 /// Returns an error if there currently is no remote state actor running for this, or when it +433 /// is currently shutting down. +434 pub(crate) fn try_send_remote_state_msg( +435 &self, +436 endpoint_id: EndpointId, +437 message: RemoteStateMessage, +438 ) -> Result<(), RemoteStateMessage> { +439 let Some(sender) = self.remote_actors.get(&endpoint_id) else { +440 return Err(message); +441 }; +442 sender.try_send(message).map_err(|err| err.into_inner()) +443 } +444 +445 /// Returns a [`Watcher`] for this socket's direct addresses. +446 /// +447 /// The [`Socket`] continuously monitors the direct addresses, the network addresses +448 /// it might be able to be contacted on, for changes. Whenever changes are detected +449 /// this [`Watcher`] will yield a new list of addresses. +450 /// +451 /// Upon the first creation on the [`Socket`] it may not yet have completed a first +452 /// net report to discover IP addresses, in this case the current item in this [`Watcher`] will be +453 /// [`None`]. Once the first set of ip addresses are discovered the [`Watcher`] will +454 /// store [`Some`] set of addresses. +455 /// +456 /// To get the current direct addresses, use [`Watcher::initialized`]. +457 /// +458 /// [`Watcher`]: n0_watcher::Watcher +459 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +460 pub(crate) fn ip_addrs(&self) -> n0_watcher::Direct<BTreeSet<DirectAddr>> { +461 self.direct_addrs.addrs.watch() +462 } +463 +464 /// Returns a [`Watcher`] for this socket's net-report. 465 /// -466 /// Upon the first creation on the [`Socket`] it may not yet have completed -467 /// a first net-report. In this case, the current item in this [`Watcher`] will -468 /// be [`None`]. Once the first report has been run, the [`Watcher`] will -469 /// store [`Some`] report. -470 /// -471 /// To get the current `net-report`, use [`Watcher::initialized`]. -472 /// -473 /// [`Watcher`]: n0_watcher::Watcher -474 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized -475 pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> { -476 self.net_report.watch().map(|(r, _)| r) -477 } -478 -479 /// Watch for changes to the home relay. -480 /// -481 /// Note that this can be used to wait for the initial home relay to be known using -482 /// [`Watcher::initialized`]. -483 pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> + use<> { -484 self.local_addrs_watch.clone().map(|addrs| { -485 addrs -486 .into_iter() -487 .filter_map(|addr| { -488 if let transports::Addr::Relay(url, _) = addr { -489 Some(url) -490 } else { -491 None -492 } -493 }) -494 .collect() -495 }) -496 } -497 -498 pub(crate) fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> { -499 self.home_relay_watch.clone() -500 } -501 -502 /// Stores a new set of direct addresses. -503 /// -504 /// If the direct addresses have changed from the previous set, they are published to -505 /// the address lookup system. -506 fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { -507 let updated = self.direct_addrs.update(addrs); -508 if updated { -509 self.publish_my_addr(); -510 } -511 } -512 -513 /// Get a reference to the DNS resolver used in this [`Socket`]. -514 #[cfg(not(wasm_browser))] -515 pub(crate) fn dns_resolver(&self) -> &DnsResolver { -516 &self.dns_resolver -517 } -518 -519 /// Translates a raw [`SocketAddr`] (which may be a synthetic mapped address) into -520 /// a [`transports::Addr`]. -521 /// -522 /// For regular IP addresses this returns `Addr::Ip`. For synthetic relay-mapped -523 /// IPv6 addresses this performs a reverse lookup and returns `Addr::Relay`. +466 /// The [`Socket`] continuously monitors the network conditions for changes. +467 /// Whenever changes are detected this [`Watcher`] will yield a new report. +468 /// +469 /// Upon the first creation on the [`Socket`] it may not yet have completed +470 /// a first net-report. In this case, the current item in this [`Watcher`] will +471 /// be [`None`]. Once the first report has been run, the [`Watcher`] will +472 /// store [`Some`] report. +473 /// +474 /// To get the current `net-report`, use [`Watcher::initialized`]. +475 /// +476 /// [`Watcher`]: n0_watcher::Watcher +477 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +478 pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> { +479 self.net_report.watch().map(|(r, _)| r) +480 } +481 +482 /// Watch for changes to the home relay. +483 /// +484 /// Note that this can be used to wait for the initial home relay to be known using +485 /// [`Watcher::initialized`]. +486 pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> + use<> { +487 self.local_addrs_watch.clone().map(|addrs| { +488 addrs +489 .into_iter() +490 .filter_map(|addr| { +491 if let transports::Addr::Relay(url, _) = addr { +492 Some(url) +493 } else { +494 None +495 } +496 }) +497 .collect() +498 }) +499 } +500 +501 pub(crate) fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> { +502 self.home_relay_watch.clone() +503 } +504 +505 /// Stores a new set of direct addresses. +506 /// +507 /// If the direct addresses have changed from the previous set, they are published to +508 /// the address lookup system. +509 fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { +510 let updated = self.direct_addrs.update(addrs); +511 if updated { +512 self.publish_my_addr(); +513 } +514 } +515 +516 /// Get a reference to the DNS resolver used in this [`Socket`]. +517 #[cfg(not(wasm_browser))] +518 pub(crate) fn dns_resolver(&self) -> &DnsResolver { +519 &self.dns_resolver +520 } +521 +522 /// Translates a raw [`SocketAddr`] (which may be a synthetic mapped address) into +523 /// a [`transports::Addr`]. 524 /// -525 /// This lookup only makes sense for a remote address of the -526 /// underlying QUIC connection. +525 /// For regular IP addresses this returns `Addr::Ip`. For synthetic relay-mapped +526 /// IPv6 addresses this performs a reverse lookup and returns `Addr::Relay`. 527 /// -528 /// If you call this with a mapped address for which no mapping exists, -529 /// it will return the address as an `Addr::Ip`. -530 pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> transports::Addr { -531 remote_map::to_transport_addr( -532 addr, -533 &self.mapped_addrs.relay_addrs, -534 &self.mapped_addrs.custom_addrs, -535 ) -536 .unwrap_or(transports::Addr::Ip(addr)) -537 } -538 -539 pub(crate) fn to_local_transport_addr( -540 &self, -541 local_ip: Option<IpAddr>, -542 remote_addr: SocketAddr, -543 ) -> LocalTransportAddr { -544 let remote_addr = self.to_transport_addr(remote_addr); -545 LocalTransportAddr::from_noq_local_ip( -546 local_ip, -547 &remote_addr, -548 &self.mapped_addrs.custom_addrs, -549 ) -550 } -551 -552 /// Reference to the internal Address Lookup -553 pub(crate) fn address_lookup(&self) -> &address_lookup::AddressLookupServices { -554 &self.address_lookup -555 } -556 -557 /// Updates the user-defined Address Lookup data for this endpoint. -558 pub(crate) fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) { -559 let mut guard = self -560 .address_lookup_user_data -561 .write() -562 .expect("lock poisened"); -563 if *guard != user_data { -564 *guard = user_data; -565 drop(guard); -566 self.publish_my_addr(); -567 } -568 } -569 -570 /// Process datagrams received from all the transports. -571 /// -572 /// All the `bufs` and `metas` should have initialized packets in them. -573 /// -574 /// This fixes up the datagrams to use the correct [`MultipathMappedAddr`] and extracts -575 /// DISCO packets, processing them inside the socket. +528 /// This lookup only makes sense for a remote address of the +529 /// underlying QUIC connection. +530 /// +531 /// If you call this with a mapped address for which no mapping exists, +532 /// it will return the address as an `Addr::Ip`. +533 pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> transports::Addr { +534 remote_map::to_transport_addr( +535 addr, +536 &self.mapped_addrs.relay_addrs, +537 &self.mapped_addrs.custom_addrs, +538 ) +539 .unwrap_or(transports::Addr::Ip(addr)) +540 } +541 +542 pub(crate) fn to_local_transport_addr( +543 &self, +544 local_ip: Option<IpAddr>, +545 remote_addr: SocketAddr, +546 ) -> LocalTransportAddr { +547 let remote_addr = self.to_transport_addr(remote_addr); +548 LocalTransportAddr::from_noq_local_ip( +549 local_ip, +550 &remote_addr, +551 &self.mapped_addrs.custom_addrs, +552 ) +553 } +554 +555 /// Reference to the internal Address Lookup +556 pub(crate) fn address_lookup(&self) -> &address_lookup::AddressLookupServices { +557 &self.address_lookup +558 } +559 +560 /// Updates the user-defined Address Lookup data for this endpoint. +561 pub(crate) fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) { +562 let mut guard = self +563 .address_lookup_user_data +564 .write() +565 .expect("lock poisened"); +566 if *guard != user_data { +567 *guard = user_data; +568 drop(guard); +569 self.publish_my_addr(); +570 } +571 } +572 +573 /// Process datagrams received from all the transports. +574 /// +575 /// All the `bufs` and `metas` should have initialized packets in them. 576 /// -577 /// [`MultipathMappedAddr`]: mapped_addrs::MultipathMappedAddr -578 fn process_datagrams( -579 &self, -580 bufs: &mut [io::IoSliceMut<'_>], -581 metas: &mut [noq_udp::RecvMeta], -582 recv_infos: &[transports::RecvInfo], -583 ) { -584 assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); -585 assert_eq!( -586 bufs.len(), -587 recv_infos.len(), -588 "non matching bufs & recv_infos" -589 ); -590 -591 // zip is slow :( -592 for i in 0..metas.len() { -593 let noq_meta = &mut metas[i]; -594 let recv_info = &recv_infos[i]; -595 let remote_addr = recv_info.remote(); -596 let datagram_count = if noq_meta.stride == 0 { -597 if noq_meta.len > 0 { -598 warn!( -599 src = ?remote_addr, -600 len = noq_meta.len, -601 "received datagram with stride=0 but len>0", -602 ); -603 // fix the weird len -604 noq_meta.len = 0; -605 } -606 // one empty datagram -607 1 -608 } else { -609 noq_meta.len.div_ceil(noq_meta.stride) -610 }; -611 self.metrics -612 .socket -613 .recv_datagrams -614 .inc_by(datagram_count as _); -615 if noq_meta.len > noq_meta.stride { -616 trace!( -617 src = ?remote_addr, -618 len = noq_meta.len, -619 stride = %noq_meta.stride, -620 datagram_count, -621 "GRO datagram received", -622 ); -623 self.metrics.socket.recv_gro_datagrams.inc(); -624 } else { -625 trace!(src = ?remote_addr, len = noq_meta.len, "datagram received"); -626 } -627 match remote_addr { -628 transports::Addr::Ip(SocketAddr::V4(..)) => { -629 self.metrics.socket.recv_data_ipv4.inc_by(noq_meta.len as _); -630 } -631 transports::Addr::Ip(SocketAddr::V6(..)) => { -632 self.metrics.socket.recv_data_ipv6.inc_by(noq_meta.len as _); +577 /// This fixes up the datagrams to use the correct [`MultipathMappedAddr`] and extracts +578 /// DISCO packets, processing them inside the socket. +579 /// +580 /// [`MultipathMappedAddr`]: mapped_addrs::MultipathMappedAddr +581 fn process_datagrams( +582 &self, +583 bufs: &mut [io::IoSliceMut<'_>], +584 metas: &mut [noq_udp::RecvMeta], +585 recv_infos: &[transports::RecvInfo], +586 ) { +587 assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); +588 assert_eq!( +589 bufs.len(), +590 recv_infos.len(), +591 "non matching bufs & recv_infos" +592 ); +593 +594 // zip is slow :( +595 for i in 0..metas.len() { +596 let noq_meta = &mut metas[i]; +597 let recv_info = &recv_infos[i]; +598 let remote_addr = recv_info.remote(); +599 let datagram_count = if noq_meta.stride == 0 { +600 if noq_meta.len > 0 { +601 warn!( +602 src = ?remote_addr, +603 len = noq_meta.len, +604 "received datagram with stride=0 but len>0", +605 ); +606 // fix the weird len +607 noq_meta.len = 0; +608 } +609 // one empty datagram +610 1 +611 } else { +612 noq_meta.len.div_ceil(noq_meta.stride) +613 }; +614 self.metrics +615 .socket +616 .recv_datagrams +617 .inc_by(datagram_count as _); +618 if noq_meta.len > noq_meta.stride { +619 trace!( +620 src = ?remote_addr, +621 len = noq_meta.len, +622 stride = %noq_meta.stride, +623 datagram_count, +624 "GRO datagram received", +625 ); +626 self.metrics.socket.recv_gro_datagrams.inc(); +627 } else { +628 trace!(src = ?remote_addr, len = noq_meta.len, "datagram received"); +629 } +630 match remote_addr { +631 transports::Addr::Ip(SocketAddr::V4(..)) => { +632 self.metrics.socket.recv_data_ipv4.inc_by(noq_meta.len as _); 633 } -634 transports::Addr::Relay(src_url, src_node) => { -635 self.metrics -636 .socket -637 .recv_data_relay -638 .inc_by(noq_meta.len as _); -639 -640 // Fill in the correct mapped address -641 let mapped_addr = self -642 .mapped_addrs -643 .relay_addrs -644 .get(&(src_url.clone(), *src_node)); -645 noq_meta.addr = mapped_addr.private_socket_addr(); -646 } -647 transports::Addr::Custom(remote) => { -648 self.metrics -649 .socket -650 .recv_data_custom -651 .inc_by(noq_meta.len as _); -652 // Fill in the correct mapped address -653 let mapped_addr = self.mapped_addrs.custom_addrs.get(remote); -654 noq_meta.addr = mapped_addr.private_socket_addr(); -655 if let Some(local) = recv_info.local() { -656 let local_mapped = self.mapped_addrs.custom_addrs.get(local); -657 noq_meta.dst_ip = Some(local_mapped.private_socket_addr().ip()); -658 } -659 } -660 } -661 } -662 } -663 -664 /// Publishes our address to an address lookup service, if configured. -665 /// -666 /// Called whenever our addresses or home relay endpoint changes. -667 fn publish_my_addr(&self) { -668 let relay_url = self.my_relay(); -669 let mut addrs: Vec<_> = self -670 .direct_addrs -671 .sockaddrs() -672 .map(TransportAddr::Ip) -673 .collect(); -674 -675 let user_data = self -676 .address_lookup_user_data -677 .read() -678 .expect("lock poisened") -679 .clone(); -680 if relay_url.is_none() && addrs.is_empty() && user_data.is_none() { -681 // do not bother publishing if we don't have any information -682 return; -683 } -684 if let Some(url) = relay_url { -685 addrs.push(TransportAddr::Relay(url)); +634 transports::Addr::Ip(SocketAddr::V6(..)) => { +635 self.metrics.socket.recv_data_ipv6.inc_by(noq_meta.len as _); +636 } +637 transports::Addr::Relay(src_url, src_node) => { +638 self.metrics +639 .socket +640 .recv_data_relay +641 .inc_by(noq_meta.len as _); +642 +643 // Fill in the correct mapped address +644 let mapped_addr = self +645 .mapped_addrs +646 .relay_addrs +647 .get(&(src_url.clone(), *src_node)); +648 noq_meta.addr = mapped_addr.private_socket_addr(); +649 } +650 transports::Addr::Custom(remote) => { +651 self.metrics +652 .socket +653 .recv_data_custom +654 .inc_by(noq_meta.len as _); +655 // Fill in the correct mapped address +656 let mapped_addr = self.mapped_addrs.custom_addrs.get(remote); +657 noq_meta.addr = mapped_addr.private_socket_addr(); +658 if let Some(local) = recv_info.local() { +659 let local_mapped = self.mapped_addrs.custom_addrs.get(local); +660 noq_meta.dst_ip = Some(local_mapped.private_socket_addr().ip()); +661 } +662 } +663 } +664 } +665 } +666 +667 /// Publishes our address to an address lookup service, if configured. +668 /// +669 /// Called whenever our addresses or home relay endpoint changes. +670 fn publish_my_addr(&self) { +671 let relay_url = self.my_relay(); +672 let mut addrs: Vec<_> = self +673 .direct_addrs +674 .sockaddrs() +675 .map(TransportAddr::Ip) +676 .collect(); +677 +678 let user_data = self +679 .address_lookup_user_data +680 .read() +681 .expect("lock poisened") +682 .clone(); +683 if relay_url.is_none() && addrs.is_empty() && user_data.is_none() { +684 // do not bother publishing if we don't have any information +685 return; 686 } -687 -688 let mut data = EndpointData::new(addrs); -689 data.set_user_data(user_data); -690 self.address_lookup.publish(&data); -691 } -692} -693 -694/// Manages currently running [`crate::NetReport`] to learn this endpoint's IP addresses. -695/// -696/// Invariants: -697/// - only one direct addr update must be running at a time -698/// - if an update is scheduled while another one is running, remember that -699/// and start a new one when the current one has finished -700#[derive(Debug)] -701struct DirectAddrUpdateState { -702 /// If set, start a new update as soon as the current one is finished. -703 want_update: Option<UpdateReason>, -704 sock: Arc<Socket>, -705 port_mapper: portmapper::Client, -706 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. -707 net_reporter: Arc<AsyncMutex<net_report::Client>>, -708 relay_map: RelayMap, -709 run_done: mpsc::Sender<()>, -710 shutdown_token: CancellationToken, -711} -712 -713#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] -714enum UpdateReason { -715 /// Initial state -716 #[default] -717 None, -718 Periodic, -719 PortmapUpdated, -720 LinkChangeMajor, -721 LinkChangeMinor, -722 RelayMapChange, -723} -724 -725impl UpdateReason { -726 fn is_major(self) -> bool { -727 matches!(self, Self::LinkChangeMajor | Self::RelayMapChange) -728 } -729} -730 -731impl DirectAddrUpdateState { -732 fn new( -733 sock: Arc<Socket>, -734 port_mapper: portmapper::Client, -735 net_reporter: Arc<AsyncMutex<net_report::Client>>, -736 relay_map: RelayMap, -737 run_done: mpsc::Sender<()>, -738 shutdown_token: CancellationToken, -739 ) -> Self { -740 DirectAddrUpdateState { -741 want_update: Default::default(), -742 port_mapper, -743 net_reporter, -744 sock, -745 relay_map, -746 run_done, -747 shutdown_token, -748 } -749 } -750 -751 /// Schedules a new run, either starting it immediately if none is running or -752 /// scheduling it for later. -753 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) { -754 match self.net_reporter.clone().try_lock_owned() { -755 Ok(net_reporter) => { -756 self.run(why, if_state, net_reporter); -757 } -758 Err(_) => { -759 let _ = self.want_update.insert(why); +687 if let Some(url) = relay_url { +688 addrs.push(TransportAddr::Relay(url)); +689 } +690 +691 let mut data = EndpointData::new(addrs); +692 data.set_user_data(user_data); +693 self.address_lookup.publish(&data); +694 } +695} +696 +697/// Manages currently running [`crate::NetReport`] to learn this endpoint's IP addresses. +698/// +699/// Invariants: +700/// - only one direct addr update must be running at a time +701/// - if an update is scheduled while another one is running, remember that +702/// and start a new one when the current one has finished +703#[derive(Debug)] +704struct DirectAddrUpdateState { +705 /// If set, start a new update as soon as the current one is finished. +706 want_update: Option<UpdateReason>, +707 sock: Arc<Socket>, +708 port_mapper: portmapper::Client, +709 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. +710 net_reporter: Arc<AsyncMutex<net_report::Client>>, +711 relay_map: RelayMap, +712 run_done: mpsc::Sender<()>, +713 shutdown_token: CancellationToken, +714} +715 +716#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] +717enum UpdateReason { +718 /// Initial state +719 #[default] +720 None, +721 Periodic, +722 PortmapUpdated, +723 LinkChangeMajor, +724 LinkChangeMinor, +725 RelayMapChange, +726} +727 +728impl UpdateReason { +729 fn is_major(self) -> bool { +730 matches!(self, Self::LinkChangeMajor | Self::RelayMapChange) +731 } +732} +733 +734impl DirectAddrUpdateState { +735 fn new( +736 sock: Arc<Socket>, +737 port_mapper: portmapper::Client, +738 net_reporter: Arc<AsyncMutex<net_report::Client>>, +739 relay_map: RelayMap, +740 run_done: mpsc::Sender<()>, +741 shutdown_token: CancellationToken, +742 ) -> Self { +743 DirectAddrUpdateState { +744 want_update: Default::default(), +745 port_mapper, +746 net_reporter, +747 sock, +748 relay_map, +749 run_done, +750 shutdown_token, +751 } +752 } +753 +754 /// Schedules a new run, either starting it immediately if none is running or +755 /// scheduling it for later. +756 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) { +757 match self.net_reporter.clone().try_lock_owned() { +758 Ok(net_reporter) => { +759 self.run(why, if_state, net_reporter); 760 } -761 } -762 } -763 -764 /// If another run is needed, triggers this run, otherwise does nothing. -765 fn try_run(&mut self, if_state: IfStateDetails) { -766 match self.net_reporter.clone().try_lock_owned() { -767 Ok(net_reporter) => { -768 if let Some(why) = self.want_update.take() { -769 self.run(why, if_state, net_reporter); -770 } -771 } -772 Err(_) => { -773 // do nothing -774 } -775 } -776 } -777 -778 /// Trigger a new run. -779 fn run( -780 &mut self, -781 why: UpdateReason, -782 if_state: IfStateDetails, -783 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>, -784 ) { -785 debug!("starting direct addr update ({:?})", why); -786 // Don't start a net report probe if we know -787 // we are shutting down -788 if self.shutdown_token.is_cancelled() { -789 debug!("skipping net_report, socket is shutting down"); -790 // deactivate portmapper -791 self.port_mapper.deactivate(); -792 return; -793 } -794 if self.relay_map.is_empty() { -795 debug!("skipping net_report, empty RelayMap"); -796 self.sock.net_report.set((None, why)).ok(); -797 return; -798 } -799 -800 self.sock.metrics.net_report.portmap_attempts.inc(); -801 self.port_mapper.procure_mapping(); +761 Err(_) => { +762 let _ = self.want_update.insert(why); +763 } +764 } +765 } +766 +767 /// If another run is needed, triggers this run, otherwise does nothing. +768 fn try_run(&mut self, if_state: IfStateDetails) { +769 match self.net_reporter.clone().try_lock_owned() { +770 Ok(net_reporter) => { +771 if let Some(why) = self.want_update.take() { +772 self.run(why, if_state, net_reporter); +773 } +774 } +775 Err(_) => { +776 // do nothing +777 } +778 } +779 } +780 +781 /// Trigger a new run. +782 fn run( +783 &mut self, +784 why: UpdateReason, +785 if_state: IfStateDetails, +786 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>, +787 ) { +788 debug!("starting direct addr update ({:?})", why); +789 // Don't start a net report probe if we know +790 // we are shutting down +791 if self.shutdown_token.is_cancelled() { +792 debug!("skipping net_report, socket is shutting down"); +793 // deactivate portmapper +794 self.port_mapper.deactivate(); +795 return; +796 } +797 if self.relay_map.is_empty() { +798 debug!("skipping net_report, empty RelayMap"); +799 self.sock.net_report.set((None, why)).ok(); +800 return; +801 } 802 -803 trace!("requesting net_report report"); -804 let sock = self.sock.clone(); +803 self.sock.metrics.net_report.portmap_attempts.inc(); +804 self.port_mapper.procure_mapping(); 805 -806 let run_done = self.run_done.clone(); -807 -808 // Ensure that reports are cancelled when we shutdown -809 let token = self.shutdown_token.child_token(); -810 let inner_token = token.child_token(); -811 task::spawn( -812 async move { -813 let fut = token.run_until_cancelled(time::timeout( -814 NET_REPORT_TIMEOUT, -815 net_reporter.get_report(if_state, why.is_major(), inner_token), -816 )); -817 -818 match fut.await { -819 Some(Ok(report)) => { -820 sock.net_report.set((Some(report), why)).ok(); -821 } -822 Some(Err(time::Elapsed { .. })) => { -823 warn!("net_report report timed out"); +806 trace!("requesting net_report report"); +807 let sock = self.sock.clone(); +808 +809 let run_done = self.run_done.clone(); +810 +811 // Ensure that reports are cancelled when we shutdown +812 let token = self.shutdown_token.child_token(); +813 let inner_token = token.child_token(); +814 task::spawn( +815 async move { +816 let fut = token.run_until_cancelled(time::timeout( +817 NET_REPORT_TIMEOUT, +818 net_reporter.get_report(if_state, why.is_major(), inner_token), +819 )); +820 +821 match fut.await { +822 Some(Ok(report)) => { +823 sock.net_report.set((Some(report), why)).ok(); 824 } -825 None => { -826 trace!("net_report cancelled"); +825 Some(Err(time::Elapsed { .. })) => { +826 warn!("net_report report timed out"); 827 } -828 } -829 -830 // mark run as finished -831 debug!("direct addr update done ({:?})", why); -832 run_done.send(()).await.ok(); -833 } -834 .instrument(tracing::Span::current()), -835 ); -836 } -837} -838 -839#[allow(missing_docs)] -840#[stack_error(derive, add_meta)] -841#[non_exhaustive] -842pub enum BindError { -843 #[error("Failed to bind sockets")] -844 Sockets { source: io::Error }, -845 #[error("Failed to create internal QUIC endpoint")] -846 CreateQuicEndpoint { source: io::Error }, -847 #[error("Failed to create netmon monitor")] -848 CreateNetmonMonitor { source: AnyError }, -849 #[error("Invalid transport configuration")] -850 InvalidTransportConfig, -851 #[error("Invalid CA root configuration")] -852 InvalidCaRootConfig { source: io::Error }, -853 #[error("Failed to create an address lookup service")] -854 AddressLookup { -855 #[error(from)] -856 source: crate::address_lookup::AddressLookupBuilderError, -857 }, -858 #[error("Missing or incompatible rustls crypto provider configured")] -859 InvalidCryptoProvider, -860 #[error("Error constructing TLS configuration")] -861 TlsConfigError { -862 #[error(from)] -863 source: tls::TlsConfigError, -864 }, -865} -866 -867impl EndpointInner { -868 /// Creates a [`EndpointInner`]. -869 pub(crate) async fn bind(opts: Options) -> Result<Self, BindError> { -870 // Use the current span as the main span for all tasks spawned in this endpoint. -871 // `EndpointInner::bind` is not public and only called from `crate::endpoint::Builder::bind`, -872 // which instruments the call with a span created for this purpose. -873 let span = tracing::Span::current(); -874 -875 let Options { -876 secret_key, -877 transports: transport_configs, -878 address_lookup_user_data, -879 #[cfg(not(wasm_browser))] -880 dns_resolver, -881 proxy_url, -882 server_config, -883 tls_config, -884 metrics, -885 hooks, -886 path_selector, -887 portmapper_config, -888 static_config, -889 configured_addrs, -890 } = opts; -891 -892 let address_lookup = address_lookup::AddressLookupServices::default(); -893 let port_mapper = portmapper::create_client(&portmapper_config); +828 None => { +829 trace!("net_report cancelled"); +830 } +831 } +832 +833 // mark run as finished +834 debug!("direct addr update done ({:?})", why); +835 run_done.send(()).await.ok(); +836 } +837 .instrument(tracing::Span::current()), +838 ); +839 } +840} +841 +842#[allow(missing_docs)] +843#[stack_error(derive, add_meta)] +844#[non_exhaustive] +845pub enum BindError { +846 #[error("Failed to bind sockets")] +847 Sockets { source: io::Error }, +848 #[error("Failed to create internal QUIC endpoint")] +849 CreateQuicEndpoint { source: io::Error }, +850 #[error("Failed to create netmon monitor")] +851 CreateNetmonMonitor { source: AnyError }, +852 #[error("Invalid transport configuration")] +853 InvalidTransportConfig, +854 #[error("Invalid CA root configuration")] +855 InvalidCaRootConfig { source: io::Error }, +856 #[error("Failed to create an address lookup service")] +857 AddressLookup { +858 #[error(from)] +859 source: crate::address_lookup::AddressLookupBuilderError, +860 }, +861 #[error("Missing or incompatible rustls crypto provider configured")] +862 InvalidCryptoProvider, +863 #[error("Error constructing TLS configuration")] +864 TlsConfigError { +865 #[error(from)] +866 source: tls::TlsConfigError, +867 }, +868} +869 +870impl EndpointInner { +871 /// Creates a [`EndpointInner`]. +872 pub(crate) async fn bind(opts: Options) -> Result<Self, BindError> { +873 // Use the current span as the main span for all tasks spawned in this endpoint. +874 // `EndpointInner::bind` is not public and only called from `crate::endpoint::Builder::bind`, +875 // which instruments the call with a span created for this purpose. +876 let span = tracing::Span::current(); +877 +878 let Options { +879 secret_key, +880 transports: transport_configs, +881 address_lookup_user_data, +882 #[cfg(not(wasm_browser))] +883 dns_resolver, +884 proxy_url, +885 server_config, +886 tls_config, +887 metrics, +888 hooks, +889 path_selector, +890 portmapper_config, +891 static_config, +892 configured_addrs, +893 } = opts; 894 -895 let relay_transport_configs: Vec<_> = transport_configs -896 .iter() -897 .filter(|t| matches!(t, TransportConfig::Relay { .. })) -898 .collect(); -899 -900 // Currently we only support a single relay transport -901 if relay_transport_configs.len() > 1 { -902 bail!(BindError::InvalidTransportConfig); -903 } -904 let relay_map = relay_transport_configs -905 .iter() -906 .filter_map(|t| { -907 #[allow(irrefutable_let_patterns)] -908 if let TransportConfig::Relay { relay_map, .. } = t { -909 Some(relay_map.clone()) -910 } else { -911 None -912 } -913 }) -914 .next() -915 .unwrap_or_else(RelayMap::empty); -916 -917 let ipv6_reported = Arc::new(AtomicBool::new(false)); -918 -919 let relay_actor_config = RelayActorConfig { -920 my_relay: HomeRelayWatch::default(), -921 secret_key: secret_key.clone(), -922 #[cfg(not(wasm_browser))] -923 dns_resolver: dns_resolver.clone(), -924 proxy_url: proxy_url.clone(), -925 ipv6_reported: ipv6_reported.clone(), -926 tls_config: tls_config.clone(), -927 metrics: metrics.socket.clone(), -928 relay_map: relay_map.clone(), -929 }; -930 -931 let shutdown_state = ShutdownState::default(); -932 let shutdown_token = shutdown_state.at_endpoint_closed.child_token(); +895 let address_lookup = address_lookup::AddressLookupServices::default(); +896 let port_mapper = portmapper::create_client(&portmapper_config); +897 +898 let relay_transport_configs: Vec<_> = transport_configs +899 .iter() +900 .filter(|t| matches!(t, TransportConfig::Relay { .. })) +901 .collect(); +902 +903 // Currently we only support a single relay transport +904 if relay_transport_configs.len() > 1 { +905 bail!(BindError::InvalidTransportConfig); +906 } +907 let relay_map = relay_transport_configs +908 .iter() +909 .filter_map(|t| { +910 #[allow(irrefutable_let_patterns)] +911 if let TransportConfig::Relay { relay_map, .. } = t { +912 Some(relay_map.clone()) +913 } else { +914 None +915 } +916 }) +917 .next() +918 .unwrap_or_else(RelayMap::empty); +919 +920 let ipv6_reported = Arc::new(AtomicBool::new(false)); +921 +922 let relay_actor_config = RelayActorConfig { +923 my_relay: HomeRelayWatch::default(), +924 secret_key: secret_key.clone(), +925 #[cfg(not(wasm_browser))] +926 dns_resolver: dns_resolver.clone(), +927 proxy_url: proxy_url.clone(), +928 ipv6_reported: ipv6_reported.clone(), +929 tls_config: tls_config.clone(), +930 metrics: metrics.socket.clone(), +931 relay_map: relay_map.clone(), +932 }; 933 -934 let transports = Transports::bind( -935 &transport_configs, -936 relay_actor_config, -937 &metrics, -938 shutdown_token.child_token(), -939 ) -940 .map_err(|err| e!(BindError::Sockets, err))?; -941 -942 if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { -943 if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { -944 Some(addr.port()) -945 } else { -946 None -947 } -948 }) { -949 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails -950 match v4_port.try_into() { -951 Ok(non_zero_port) => { -952 port_mapper.update_local_port(non_zero_port); -953 } -954 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), -955 } -956 } -957 -958 let (actor_sender, actor_receiver) = mpsc::channel(256); -959 -960 #[cfg(not(wasm_browser))] -961 let has_ipv6_transport = transports -962 .ip_bind_addrs() -963 .into_iter() -964 .any(|addr| addr.is_ipv6()); -965 -966 #[cfg(not(wasm_browser))] -967 let has_ip_transports = !transports.ip_bind_addrs().is_empty(); +934 let shutdown_state = ShutdownState::default(); +935 let shutdown_token = shutdown_state.at_endpoint_closed.child_token(); +936 +937 let transports = Transports::bind( +938 &transport_configs, +939 relay_actor_config, +940 &metrics, +941 shutdown_token.child_token(), +942 ) +943 .map_err(|err| e!(BindError::Sockets, err))?; +944 +945 if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { +946 if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { +947 Some(addr.port()) +948 } else { +949 None +950 } +951 }) { +952 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails +953 match v4_port.try_into() { +954 Ok(non_zero_port) => { +955 port_mapper.update_local_port(non_zero_port); +956 } +957 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), +958 } +959 } +960 +961 let (actor_sender, actor_receiver) = mpsc::channel(256); +962 +963 #[cfg(not(wasm_browser))] +964 let has_ipv6_transport = transports +965 .ip_bind_addrs() +966 .into_iter() +967 .any(|addr| addr.is_ipv6()); 968 -969 let direct_addrs = DiscoveredDirectAddrs::default(); -970 -971 let remote_map = { -972 RemoteMap::new( -973 metrics.socket.clone(), -974 direct_addrs.addrs.watch(), -975 address_lookup.clone(), -976 shutdown_token.child_token(), -977 path_selector, -978 span.clone(), -979 ) -980 }; -981 -982 let home_relay_watch = transports.home_relay_watch(); -983 -984 let sock = Arc::new(Socket { -985 remote_actors: remote_map.senders(), -986 shutdown: shutdown_state, -987 ipv6_reported, -988 mapped_addrs: remote_map.mapped_addrs.clone(), -989 address_lookup, -990 relay_map: relay_map.clone(), -991 address_lookup_user_data: RwLock::new(address_lookup_user_data), -992 configured_addrs: RwLock::new(configured_addrs), -993 direct_addrs, -994 net_report: Watchable::new((None, UpdateReason::None)), -995 #[cfg(not(wasm_browser))] -996 dns_resolver: dns_resolver.clone(), -997 metrics: metrics.clone(), -998 local_addrs_watch: transports.local_addrs_watch(), -999 home_relay_watch, -1000 #[cfg(not(wasm_browser))] -1001 ip_bind_addrs: transports.ip_bind_addrs(), -1002 tls_config: tls_config.clone(), -1003 hooks, -1004 span: span.clone(), -1005 }); -1006 -1007 let mut endpoint_config = -1008 noq::EndpointConfig::new(Arc::new(Blake3HmacKey::new(&mut rand::rng()))); -1009 // Setting this to false means that noq will ignore packets that have the QUIC fixed bit -1010 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -1011 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -1012 // through to noq. We set the first byte of the packet to zero, which makes noq ignore -1013 // the packet if grease_quic_bit is set to false. -1014 endpoint_config.grease_quic_bit(false); -1015 -1016 let local_addrs_watch = transports.local_addrs_watch(); -1017 let transports_network_change = transports.create_network_change_sender(); +969 #[cfg(not(wasm_browser))] +970 let has_ip_transports = !transports.ip_bind_addrs().is_empty(); +971 +972 let direct_addrs = DiscoveredDirectAddrs::default(); +973 +974 let remote_map = { +975 RemoteMap::new( +976 metrics.socket.clone(), +977 direct_addrs.addrs.watch(), +978 address_lookup.clone(), +979 shutdown_token.child_token(), +980 path_selector, +981 span.clone(), +982 ) +983 }; +984 +985 let home_relay_watch = transports.home_relay_watch(); +986 +987 let sock = Arc::new(Socket { +988 remote_actors: remote_map.senders(), +989 shutdown: shutdown_state, +990 ipv6_reported, +991 mapped_addrs: remote_map.mapped_addrs.clone(), +992 address_lookup, +993 relay_map: relay_map.clone(), +994 address_lookup_user_data: RwLock::new(address_lookup_user_data), +995 configured_addrs: RwLock::new(configured_addrs), +996 direct_addrs, +997 net_report: Watchable::new((None, UpdateReason::None)), +998 #[cfg(not(wasm_browser))] +999 dns_resolver: dns_resolver.clone(), +1000 metrics: metrics.clone(), +1001 local_addrs_watch: transports.local_addrs_watch(), +1002 home_relay_watch, +1003 #[cfg(not(wasm_browser))] +1004 ip_bind_addrs: transports.ip_bind_addrs(), +1005 tls_config: tls_config.clone(), +1006 hooks, +1007 span: span.clone(), +1008 }); +1009 +1010 let mut endpoint_config = +1011 noq::EndpointConfig::new(Arc::new(Blake3HmacKey::new(&mut rand::rng()))); +1012 // Setting this to false means that noq will ignore packets that have the QUIC fixed bit +1013 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +1014 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +1015 // through to noq. We set the first byte of the packet to zero, which makes noq ignore +1016 // the packet if grease_quic_bit is set to false. +1017 endpoint_config.grease_quic_bit(false); 1018 -1019 let runtime = Arc::new(Runtime::new(secret_key.public())); -1020 -1021 let endpoint = noq::Endpoint::new_with_abstract_socket( -1022 endpoint_config, -1023 Some(server_config), -1024 Box::new(Transport::new(sock.clone(), transports)), -1025 runtime.clone(), -1026 ) -1027 .map_err(|err| e!(BindError::CreateQuicEndpoint, err))?; -1028 -1029 let network_monitor = netmon::Monitor::new() -1030 .await -1031 .map_err(|err| e!(BindError::CreateNetmonMonitor, anyerr!(err)))?; -1032 -1033 #[cfg(not(wasm_browser))] -1034 let net_report_config = { -1035 // Set a `QuicConfig` for address discovery (QAD), but only if we have IP transports. -1036 // -1037 // If there are no IP transports configured, then we don't set a QuicConfig. -1038 // If we would, the `noq::Endpoint` passed along will not have IP connectivity, -1039 // and the QAD probes that connect to the relay's QUIC endpoints would time out -1040 // because all outgoing packets to IP destinations would be dropped. -1041 let qad_config = has_ip_transports.then(|| QuicConfig { -1042 ep: endpoint.clone(), -1043 client_config: tls_config.clone(), -1044 ipv4: true, -1045 ipv6: has_ipv6_transport, -1046 }); -1047 net_report::Options::new(tls_config.clone()).quic_config(qad_config) -1048 }; -1049 -1050 #[cfg(wasm_browser)] -1051 let net_report_config = net_report::Options::default(); +1019 let local_addrs_watch = transports.local_addrs_watch(); +1020 let transports_network_change = transports.create_network_change_sender(); +1021 +1022 let runtime = Arc::new(Runtime::new(secret_key.public())); +1023 +1024 let endpoint = noq::Endpoint::new_with_abstract_socket( +1025 endpoint_config, +1026 Some(server_config), +1027 Box::new(Transport::new(sock.clone(), transports)), +1028 runtime.clone(), +1029 ) +1030 .map_err(|err| e!(BindError::CreateQuicEndpoint, err))?; +1031 +1032 let network_monitor = netmon::Monitor::new() +1033 .await +1034 .map_err(|err| e!(BindError::CreateNetmonMonitor, anyerr!(err)))?; +1035 +1036 #[cfg(not(wasm_browser))] +1037 let net_report_config = { +1038 // Set a `QuicConfig` for address discovery (QAD), but only if we have IP transports. +1039 // +1040 // If there are no IP transports configured, then we don't set a QuicConfig. +1041 // If we would, the `noq::Endpoint` passed along will not have IP connectivity, +1042 // and the QAD probes that connect to the relay's QUIC endpoints would time out +1043 // because all outgoing packets to IP destinations would be dropped. +1044 let qad_config = has_ip_transports.then(|| QuicConfig { +1045 ep: endpoint.clone(), +1046 client_config: tls_config.clone(), +1047 ipv4: true, +1048 ipv6: has_ipv6_transport, +1049 }); +1050 net_report::Options::new(tls_config.clone()).quic_config(qad_config) +1051 }; 1052 -1053 let net_reporter = net_report::Client::new( -1054 #[cfg(not(wasm_browser))] -1055 dns_resolver, -1056 relay_map.clone(), -1057 net_report_config, -1058 metrics.net_report.clone(), -1059 ); -1060 -1061 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -1062 let direct_addr_update_state = DirectAddrUpdateState::new( -1063 sock.clone(), -1064 port_mapper, -1065 Arc::new(AsyncMutex::new(net_reporter)), -1066 relay_map, -1067 direct_addr_done_tx, -1068 sock.shutdown.at_close_start.child_token(), -1069 ); -1070 -1071 let local_interfaces_watcher = network_monitor.interface_state(); -1072 -1073 #[cfg_attr(not(wasm_browser), allow(unused_mut))] -1074 let mut actor = Actor { -1075 endpoint: endpoint.clone(), -1076 sock: sock.clone(), -1077 remote_map, -1078 periodic_re_stun_timer: new_re_stun_timer(false), -1079 network_monitor, -1080 local_interfaces_watcher, -1081 direct_addr_update_state, -1082 transports_network_change, -1083 direct_addr_done_rx, -1084 call_notify_quic_network_change: None, -1085 }; -1086 // Initialize addresses -1087 #[cfg(not(wasm_browser))] -1088 actor.update_direct_addresses(None); -1089 -1090 let actor_task = task::spawn( -1091 actor -1092 .run( -1093 actor_receiver, -1094 shutdown_token.child_token(), -1095 local_addrs_watch, -1096 ) -1097 .instrument(info_span!(parent: span, "actor")), -1098 ); -1099 -1100 let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task))); -1101 -1102 Ok(EndpointInner { -1103 sock, -1104 actor_sender, -1105 actor_task, -1106 endpoint, -1107 runtime, -1108 static_config, -1109 }) -1110 } -1111 -1112 /// Returns a reference to the underlying [`noq::Endpoint`]. -1113 pub(crate) fn noq_endpoint(&self) -> &noq::Endpoint { -1114 &self.endpoint -1115 } -1116 -1117 /// Closes the iroh endpoint. -1118 /// -1119 /// Only the first close does anything. Any later closes return nil. Polling the socket -1120 /// ([`noq::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely -1121 /// after this call. -1122 /// -1123 /// [`Poll::Pending`]: std::task::Poll::Pending -1124 #[instrument(skip_all, parent = self.sock.span.clone())] -1125 pub(crate) async fn close(&self) { -1126 if self.sock.is_closed() || self.sock.is_closing() { -1127 return; -1128 } -1129 trace!("socket closing..."); -1130 -1131 // Cancel at_close_start token, which cancels running netreports. -1132 self.sock.shutdown.at_close_start.cancel(); +1053 #[cfg(wasm_browser)] +1054 let net_report_config = net_report::Options::default(); +1055 +1056 let net_reporter = net_report::Client::new( +1057 #[cfg(not(wasm_browser))] +1058 dns_resolver, +1059 relay_map.clone(), +1060 net_report_config, +1061 metrics.net_report.clone(), +1062 ); +1063 +1064 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +1065 let direct_addr_update_state = DirectAddrUpdateState::new( +1066 sock.clone(), +1067 port_mapper, +1068 Arc::new(AsyncMutex::new(net_reporter)), +1069 relay_map, +1070 direct_addr_done_tx, +1071 sock.shutdown.at_close_start.child_token(), +1072 ); +1073 +1074 let local_interfaces_watcher = network_monitor.interface_state(); +1075 +1076 #[cfg_attr(not(wasm_browser), allow(unused_mut))] +1077 let mut actor = Actor { +1078 endpoint: endpoint.clone(), +1079 sock: sock.clone(), +1080 remote_map, +1081 periodic_re_stun_timer: new_re_stun_timer(false), +1082 network_monitor, +1083 local_interfaces_watcher, +1084 direct_addr_update_state, +1085 transports_network_change, +1086 direct_addr_done_rx, +1087 call_notify_quic_network_change: None, +1088 }; +1089 // Initialize addresses +1090 #[cfg(not(wasm_browser))] +1091 actor.update_direct_addresses(None); +1092 +1093 let actor_task = task::spawn( +1094 actor +1095 .run( +1096 actor_receiver, +1097 shutdown_token.child_token(), +1098 local_addrs_watch, +1099 ) +1100 .instrument(info_span!(parent: span, "actor")), +1101 ); +1102 +1103 let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task))); +1104 +1105 Ok(EndpointInner { +1106 sock, +1107 actor_sender, +1108 actor_task, +1109 endpoint, +1110 runtime, +1111 static_config, +1112 }) +1113 } +1114 +1115 /// Returns a reference to the underlying [`noq::Endpoint`]. +1116 pub(crate) fn noq_endpoint(&self) -> &noq::Endpoint { +1117 &self.endpoint +1118 } +1119 +1120 /// Closes the iroh endpoint. +1121 /// +1122 /// Only the first close does anything. Any later closes return nil. Polling the socket +1123 /// ([`noq::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely +1124 /// after this call. +1125 /// +1126 /// [`Poll::Pending`]: std::task::Poll::Pending +1127 #[instrument(skip_all, parent = self.sock.span.clone())] +1128 pub(crate) async fn close(&self) { +1129 if self.sock.is_closed() || self.sock.is_closing() { +1130 return; +1131 } +1132 trace!("socket closing..."); 1133 -1134 // Remove address lookup services -1135 self.sock.address_lookup().clear(); +1134 // Cancel at_close_start token, which cancels running netreports. +1135 self.sock.shutdown.at_close_start.cancel(); 1136 -1137 // Initiate closing all connections, and refuse future connections. -1138 self.noq_endpoint().close(0u16.into(), b""); +1137 // Remove address lookup services +1138 self.sock.address_lookup().clear(); 1139 -1140 // In the history of this code, this call had been -1141 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1142 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1143 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1144 // and finally added back in together with this comment. -1145 // So before removing this call, please consider carefully. -1146 // Among other things, this call tries its best to make sure that any queued close frames -1147 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -1148 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -1149 // This allows the other endpoints for these connections to be notified to release -1150 // their resources, or - depending on the protocol - that all data was received. -1151 // With the current noq API, this is the only way to ensure protocol code can use -1152 // connection close codes, and close the endpoint properly. -1153 // If this call is skipped, then connections that protocols close just shortly before the -1154 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -1155 trace!("wait_all_draining start"); -1156 self.noq_endpoint().wait_all_draining().await; -1157 trace!("wait_all_draining done"); -1158 -1159 // Start cancellation of all actors. -1160 self.sock.shutdown.at_endpoint_closed.cancel(); +1140 // Initiate closing all connections, and refuse future connections. +1141 self.noq_endpoint().close(0u16.into(), b""); +1142 +1143 // In the history of this code, this call had been +1144 // - removed: https://github.com/n0-computer/iroh/pull/1753 +1145 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1146 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1147 // and finally added back in together with this comment. +1148 // So before removing this call, please consider carefully. +1149 // Among other things, this call tries its best to make sure that any queued close frames +1150 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1151 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1152 // This allows the other endpoints for these connections to be notified to release +1153 // their resources, or - depending on the protocol - that all data was received. +1154 // With the current noq API, this is the only way to ensure protocol code can use +1155 // connection close codes, and close the endpoint properly. +1156 // If this call is skipped, then connections that protocols close just shortly before the +1157 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1158 trace!("wait_all_draining start"); +1159 self.noq_endpoint().wait_all_draining().await; +1160 trace!("wait_all_draining done"); 1161 -1162 // MutexGuard is not held across await points -1163 let task = self.actor_task.lock().expect("poisoned").take(); -1164 if let Some(task) = task { -1165 // give the tasks a moment to shutdown cleanly -1166 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1167 if let Err(err) = task.await { -1168 warn!("unexpected error in task shutdown: {:?}", err); -1169 } -1170 }) -1171 .await; -1172 match shutdown_done { -1173 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1174 Err(time::Elapsed { .. }) => { -1175 // Dropping the task will abort it -1176 warn!("tasks didn't finish in time, aborting"); -1177 } -1178 } -1179 } -1180 -1181 // Waits for the EndpointDriver and all ConnectionDrivers to shut down -1182 // Expects that the `noq::Endpoint` has been closed before this call, -1183 // otherwise, the runtime will never shutdown. -1184 self.runtime.shutdown().await; -1185 -1186 self.sock.shutdown.closed.store(true, Ordering::SeqCst); -1187 -1188 trace!("socket closed"); -1189 } +1162 // Start cancellation of all actors. +1163 self.sock.shutdown.at_endpoint_closed.cancel(); +1164 +1165 // MutexGuard is not held across await points +1166 let task = self.actor_task.lock().expect("poisoned").take(); +1167 if let Some(task) = task { +1168 // give the tasks a moment to shutdown cleanly +1169 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1170 if let Err(err) = task.await { +1171 warn!("unexpected error in task shutdown: {:?}", err); +1172 } +1173 }) +1174 .await; +1175 match shutdown_done { +1176 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1177 Err(time::Elapsed { .. }) => { +1178 // Dropping the task will abort it +1179 warn!("tasks didn't finish in time, aborting"); +1180 } +1181 } +1182 } +1183 +1184 // Waits for the EndpointDriver and all ConnectionDrivers to shut down +1185 // Expects that the `noq::Endpoint` has been closed before this call, +1186 // otherwise, the runtime will never shutdown. +1187 self.runtime.shutdown().await; +1188 +1189 self.sock.shutdown.closed.store(true, Ordering::SeqCst); 1190 -1191 /// Aborts the endpoint ungracefully: -1192 /// -1193 /// - Calls cancellation token that stops running net reports -1194 /// - Removes all address lookup services -1195 /// - Calls cancellation token that stops all the Socket actors -1196 /// - Aborts the runtime -1197 /// - Drops the actor task -1198 /// - Sets the `Socket::is_closed` state to true -1199 /// -1200 /// This does not wait for any current connections or tasks to close gracefully. -1201 /// -1202 /// This should only be called in the `iroh::Endpoint` `Drop` impl when the -1203 /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`. -1204 #[instrument(skip_all, parent = self.sock.span.clone())] -1205 pub(crate) fn abort(&self) { -1206 if self.sock.is_closed() || self.sock.is_closing() { -1207 return; -1208 } -1209 trace!("socket aborting..."); -1210 -1211 // Cancel at_close_start token, which cancels running netreports. -1212 self.sock.shutdown.at_close_start.cancel(); +1191 trace!("socket closed"); +1192 } +1193 +1194 /// Aborts the endpoint ungracefully: +1195 /// +1196 /// - Calls cancellation token that stops running net reports +1197 /// - Removes all address lookup services +1198 /// - Calls cancellation token that stops all the Socket actors +1199 /// - Aborts the runtime +1200 /// - Drops the actor task +1201 /// - Sets the `Socket::is_closed` state to true +1202 /// +1203 /// This does not wait for any current connections or tasks to close gracefully. +1204 /// +1205 /// This should only be called in the `iroh::Endpoint` `Drop` impl when the +1206 /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`. +1207 #[instrument(skip_all, parent = self.sock.span.clone())] +1208 pub(crate) fn abort(&self) { +1209 if self.sock.is_closed() || self.sock.is_closing() { +1210 return; +1211 } +1212 trace!("socket aborting..."); 1213 -1214 self.sock.address_lookup().clear(); -1215 -1216 // Cancel all actors. -1217 self.sock.shutdown.at_endpoint_closed.cancel(); +1214 // Cancel at_close_start token, which cancels running netreports. +1215 self.sock.shutdown.at_close_start.cancel(); +1216 +1217 self.sock.address_lookup().clear(); 1218 -1219 // Aborts all tasks, not waiting for any to close gracefully. -1220 self.runtime.abort(); +1219 // Cancel all actors. +1220 self.sock.shutdown.at_endpoint_closed.cancel(); 1221 -1222 self.actor_task.lock().expect("poisoned").take(); -1223 -1224 self.sock.shutdown.closed.store(true, Ordering::SeqCst); -1225 trace!("socket closed"); -1226 } -1227 -1228 pub(crate) async fn insert_relay( -1229 &self, -1230 relay: RelayUrl, -1231 endpoint: Arc<RelayConfig>, -1232 ) -> Option<Arc<RelayConfig>> { -1233 let res = self.relay_map.insert(relay, endpoint); -1234 self.actor_sender -1235 .send(ActorMessage::RelayMapChange) -1236 .await -1237 .ok(); -1238 res -1239 } -1240 -1241 pub(crate) async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { -1242 let res = self.relay_map.remove(relay); -1243 self.actor_sender -1244 .send(ActorMessage::RelayMapChange) -1245 .await -1246 .ok(); -1247 res -1248 } -1249 -1250 /// Adds an external address to advertise to peers. -1251 pub(crate) async fn add_external_addr(&self, addr: SocketAddr) { -1252 self.sock -1253 .configured_addrs -1254 .write() -1255 .expect("poisoned") -1256 .insert(addr); -1257 self.actor_sender -1258 .send(ActorMessage::DirectAddrRefresh) -1259 .await -1260 .ok(); -1261 } -1262 -1263 /// Removes a configured external address. Returns `true` if it was present. -1264 pub(crate) async fn remove_external_addr(&self, addr: &SocketAddr) -> bool { -1265 let removed = self -1266 .sock -1267 .configured_addrs -1268 .write() -1269 .expect("poisoned") -1270 .remove(addr); -1271 if removed { -1272 self.actor_sender -1273 .send(ActorMessage::DirectAddrRefresh) -1274 .await -1275 .ok(); -1276 } -1277 removed -1278 } -1279 -1280 /// Call to notify the system of potential network changes. -1281 pub(crate) async fn network_change(&self) { -1282 self.actor_sender -1283 .send(ActorMessage::NetworkChange) -1284 .await -1285 .ok(); -1286 } -1287 -1288 #[cfg(all(test, with_crypto_provider))] -1289 async fn force_network_change(&self, is_major: bool) { -1290 self.actor_sender -1291 .send(ActorMessage::ForceNetworkChange(is_major)) -1292 .await -1293 .ok(); -1294 } -1295 -1296 /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`]. -1297 /// -1298 /// This starts a `RemoteStateActor` for the remote if not running already, and then checks -1299 /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for -1300 /// at least one result to arrive. -1301 /// -1302 /// Returns `Ok(Ok(EndpointIdMappedAddr))` if there is a known path or Address Lookup produced -1303 /// at least one result. This does not mean there is a working path, only that we have at least -1304 /// one transport address we can try to connect to. -1305 /// -1306 /// Returns `Ok(Err(address_lookup_error))` if there are no known paths to the remote and Address Lookup -1307 /// failed or produced no results. This means that we don't have any transport address for -1308 /// the remote, thus there is no point in trying to connect over the noq endpoint. -1309 /// -1310 /// Returns `Err(RemoteStateActorStoppedError)` if the `RemoteStateActor` for the remote has stopped, -1311 /// which may never happen and thus is a bug if it does. -1312 pub(crate) async fn resolve_remote( -1313 &self, -1314 addr: EndpointAddr, -1315 ) -> Result<Result<EndpointIdMappedAddr, AddressLookupFailed>, RemoteStateActorStoppedError> -1316 { -1317 let (tx, rx) = oneshot::channel(); -1318 let remote_id = addr.id; -1319 self.actor_sender -1320 .send(ActorMessage::ResolveRemote(addr, tx)) -1321 .await -1322 .ok(); -1323 let reply = rx.await.map_err(|_| RemoteStateActorStoppedError::new())?; -1324 match reply { -1325 Ok(()) => Ok(Ok(self.mapped_addrs.endpoint_addrs.get(&remote_id))), -1326 Err(err) => Ok(Err(err)), -1327 } -1328 } -1329 -1330 /// Fetches the [`RemoteInfo`] about a remote from the `RemoteStateActor`. -1331 /// -1332 /// Returns `None` if no actor is running for the remote. -1333 pub(crate) async fn remote_info(&self, id: EndpointId) -> Option<RemoteInfo> { -1334 let (tx, rx) = oneshot::channel(); -1335 self.remote_actors -1336 .get(&id)? -1337 .send(RemoteStateMessage::RemoteInfo(tx)) -1338 .await -1339 .ok()?; -1340 rx.await.ok() -1341 } -1342 -1343 /// Registers the connection in the `RemoteStateActor`. -1344 /// -1345 /// The actor is responsible for holepunching and opening additional paths to this -1346 /// connection. +1222 // Aborts all tasks, not waiting for any to close gracefully. +1223 self.runtime.abort(); +1224 +1225 self.actor_task.lock().expect("poisoned").take(); +1226 +1227 self.sock.shutdown.closed.store(true, Ordering::SeqCst); +1228 trace!("socket closed"); +1229 } +1230 +1231 pub(crate) async fn insert_relay( +1232 &self, +1233 relay: RelayUrl, +1234 endpoint: Arc<RelayConfig>, +1235 ) -> Option<Arc<RelayConfig>> { +1236 let res = self.relay_map.insert(relay, endpoint); +1237 self.actor_sender +1238 .send(ActorMessage::RelayMapChange) +1239 .await +1240 .ok(); +1241 res +1242 } +1243 +1244 pub(crate) async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { +1245 let res = self.relay_map.remove(relay); +1246 self.actor_sender +1247 .send(ActorMessage::RelayMapChange) +1248 .await +1249 .ok(); +1250 res +1251 } +1252 +1253 /// Adds an external address to advertise to peers. +1254 pub(crate) async fn add_external_addr(&self, addr: SocketAddr) { +1255 self.sock +1256 .configured_addrs +1257 .write() +1258 .expect("poisoned") +1259 .insert(addr); +1260 self.actor_sender +1261 .send(ActorMessage::DirectAddrRefresh) +1262 .await +1263 .ok(); +1264 } +1265 +1266 /// Removes a configured external address. Returns `true` if it was present. +1267 pub(crate) async fn remove_external_addr(&self, addr: &SocketAddr) -> bool { +1268 let removed = self +1269 .sock +1270 .configured_addrs +1271 .write() +1272 .expect("poisoned") +1273 .remove(addr); +1274 if removed { +1275 self.actor_sender +1276 .send(ActorMessage::DirectAddrRefresh) +1277 .await +1278 .ok(); +1279 } +1280 removed +1281 } +1282 +1283 /// Call to notify the system of potential network changes. +1284 pub(crate) async fn network_change(&self) { +1285 self.actor_sender +1286 .send(ActorMessage::NetworkChange) +1287 .await +1288 .ok(); +1289 } +1290 +1291 #[cfg(all(test, with_crypto_provider))] +1292 async fn force_network_change(&self, is_major: bool) { +1293 self.actor_sender +1294 .send(ActorMessage::ForceNetworkChange(is_major)) +1295 .await +1296 .ok(); +1297 } +1298 +1299 /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`]. +1300 /// +1301 /// This starts a `RemoteStateActor` for the remote if not running already, and then checks +1302 /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for +1303 /// at least one result to arrive. +1304 /// +1305 /// Returns `Ok(Ok(EndpointIdMappedAddr))` if there is a known path or Address Lookup produced +1306 /// at least one result. This does not mean there is a working path, only that we have at least +1307 /// one transport address we can try to connect to. +1308 /// +1309 /// Returns `Ok(Err(address_lookup_error))` if there are no known paths to the remote and Address Lookup +1310 /// failed or produced no results. This means that we don't have any transport address for +1311 /// the remote, thus there is no point in trying to connect over the noq endpoint. +1312 /// +1313 /// Returns `Err(RemoteStateActorStoppedError)` if the `RemoteStateActor` for the remote has stopped, +1314 /// which may never happen and thus is a bug if it does. +1315 pub(crate) async fn resolve_remote( +1316 &self, +1317 addr: EndpointAddr, +1318 ) -> Result<Result<EndpointIdMappedAddr, AddressLookupFailed>, RemoteStateActorStoppedError> +1319 { +1320 let (tx, rx) = oneshot::channel(); +1321 let remote_id = addr.id; +1322 self.actor_sender +1323 .send(ActorMessage::ResolveRemote(addr, tx)) +1324 .await +1325 .ok(); +1326 let reply = rx.await.map_err(|_| RemoteStateActorStoppedError::new())?; +1327 match reply { +1328 Ok(()) => Ok(Ok(self.mapped_addrs.endpoint_addrs.get(&remote_id))), +1329 Err(err) => Ok(Err(err)), +1330 } +1331 } +1332 +1333 /// Fetches the [`RemoteInfo`] about a remote from the `RemoteStateActor`. +1334 /// +1335 /// Returns `None` if no actor is running for the remote. +1336 pub(crate) async fn remote_info(&self, id: EndpointId) -> Option<RemoteInfo> { +1337 let (tx, rx) = oneshot::channel(); +1338 self.remote_actors +1339 .get(&id)? +1340 .send(RemoteStateMessage::RemoteInfo(tx)) +1341 .await +1342 .ok()?; +1343 rx.await.ok() +1344 } +1345 +1346 /// Registers the connection in the `RemoteStateActor`. 1347 /// -1348 /// Returns a future that resolves to a [`PathStateReceiver`] for the new connection. -1349 /// -1350 /// The returned future is `'static`, so it can be stored without being lifetime-bound to `&self`. -1351 pub(crate) fn register_connection( -1352 &self, -1353 remote: EndpointId, -1354 conn: noq::Connection, -1355 ) -> impl Future<Output = Result<PathStateReceiver, RemoteStateActorStoppedError>> + Send + 'static -1356 { -1357 let (tx, rx) = oneshot::channel(); -1358 let sender = self.actor_sender.clone(); -1359 async move { -1360 sender -1361 .send(ActorMessage::AddConnection(remote, conn, tx)) -1362 .await -1363 .map_err(|_| RemoteStateActorStoppedError::new())?; -1364 rx.await.map_err(|_| RemoteStateActorStoppedError::new()) -1365 } -1366 } -1367} -1368 -1369#[derive(derive_more::Debug)] -1370#[allow(clippy::enum_variant_names)] -1371enum ActorMessage { -1372 NetworkChange, -1373 RelayMapChange, -1374 #[debug("ResolveRemote(..)")] -1375 ResolveRemote( -1376 EndpointAddr, -1377 oneshot::Sender<Result<(), AddressLookupFailed>>, -1378 ), -1379 #[debug("AddConnection(..)")] -1380 AddConnection( -1381 EndpointId, -1382 noq::Connection, -1383 oneshot::Sender<PathStateReceiver>, -1384 ), -1385 /// Re-evaluate direct addresses, e.g. after configured external addresses changed. -1386 DirectAddrRefresh, -1387 #[cfg(all(test, with_crypto_provider))] -1388 ForceNetworkChange(bool), -1389} -1390 -1391/// State for polling until a default route is available after a network change. -1392/// -1393/// When a network change is detected but no default route exists yet (e.g., -1394/// interface just came up but gateway not assigned), we poll with exponential -1395/// backoff until the gateway appears. This avoids the fixed 2s delay that was -1396/// too slow for interface recovery scenarios. -1397struct PendingNetworkChangeNotify { -1398 /// Next time to check for default route. -1399 next_check: Instant, -1400 /// Current backoff interval. -1401 interval: Duration, -1402 /// Whether this was a major change. -1403 is_major: bool, -1404 /// When we started polling (to enforce a max wait). -1405 started: Instant, -1406} -1407 -1408impl PendingNetworkChangeNotify { -1409 const INITIAL_INTERVAL: Duration = Duration::from_millis(100); -1410 const MAX_INTERVAL: Duration = Duration::from_secs(1); -1411 const MAX_WAIT: Duration = Duration::from_secs(5); -1412 -1413 fn new(is_major: bool) -> Self { -1414 Self { -1415 next_check: Instant::now() + Self::INITIAL_INTERVAL, -1416 interval: Self::INITIAL_INTERVAL, -1417 is_major, -1418 started: Instant::now(), -1419 } -1420 } -1421 -1422 /// Advance to the next check interval (exponential backoff, capped). -1423 fn advance(&mut self) { -1424 self.interval = (self.interval * 2).min(Self::MAX_INTERVAL); -1425 self.next_check = Instant::now() + self.interval; -1426 } -1427 -1428 /// Whether we've exceeded the maximum wait time. -1429 fn expired(&self) -> bool { -1430 self.started.elapsed() >= Self::MAX_WAIT -1431 } -1432} -1433 -1434struct Actor { -1435 /// A clone of the quinn Endpoint. -1436 /// -1437 /// The task of this actor is currently owned by the [`crate::Endpoint`] and wrapped in -1438 /// an [`AbortOnDropHandle`]. When [`crate::Endpoint::close`] is called various -1439 /// subsystems are being stopped. Then, when [`ShutdownState::at_endpoint_closed`] is -1440 /// called by [`crate::Endpoint::close`], this actor itself is stopped via it's -1441 /// [`CancellationToken`] and we will drop this clone of the endpoint. The endpoint is -1442 /// then finally dropped when the [`crate::Endpoint`] itself is dropped. -1443 /// -1444 /// All of this to say: keeping the quinn endpoint alive here does not impact the -1445 /// lifetime of it since it's lifetime is shorter than that one that's stored in the -1446 /// [`crate::Endpoint`]. -1447 endpoint: noq::Endpoint, -1448 /// Shared state between an awful lot of iroh subsystems. -1449 /// -1450 /// In particular both the [`EndpointInner`] as well as this actor itself have a -1451 /// copy. But also other subsystems that consequently have access to way to much state. -1452 sock: Arc<Socket>, -1453 /// Tracks the networkmap endpoint entity for each endpoint discovery key. -1454 remote_map: RemoteMap, -1455 /// When set, is an AfterFunc timer that will call Socket::do_periodic_stun. -1456 periodic_re_stun_timer: time::Interval, -1457 /// An actor watching the local network interfaces. -1458 /// -1459 /// The monitored changes are emitted via [`Self::local_interfaces_watcher`]. -1460 network_monitor: netmon::Monitor, -1461 /// Watcher for changes to the local network interfaces, IP addresses and routes. -1462 local_interfaces_watcher: n0_watcher::Direct<netmon::State>, -1463 transports_network_change: transports::NetworkChangeSender, -1464 /// Indicates the direct addr update state. -1465 direct_addr_update_state: DirectAddrUpdateState, -1466 direct_addr_done_rx: mpsc::Receiver<()>, -1467 /// Polling state for [`Actor::notify_quic_network_change`]. -1468 /// -1469 /// When a network change is detected but no default route is available yet, -1470 /// we poll with exponential backoff (100ms, 200ms, 400ms, 800ms, 1s, 1s, ...) -1471 /// until the gateway appears. Once it does, we notify immediately. -1472 /// After 5s total we notify anyway even without a gateway. -1473 call_notify_quic_network_change: Option<PendingNetworkChangeNotify>, -1474} -1475 -1476impl Actor { -1477 async fn run( -1478 mut self, -1479 mut msg_receiver: mpsc::Receiver<ActorMessage>, -1480 shutdown_token: CancellationToken, -1481 mut local_addrs_watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1482 ) { -1483 // Setup network monitoring -1484 let mut current_netmon_state = self.local_interfaces_watcher.get(); -1485 -1486 let mut portmap_watcher = self -1487 .direct_addr_update_state -1488 .port_mapper -1489 .watch_external_address(); -1490 -1491 let mut receiver_closed = false; -1492 let mut portmap_watcher_closed = false; +1348 /// The actor is responsible for holepunching and opening additional paths to this +1349 /// connection. +1350 /// +1351 /// Returns a future that resolves to a [`PathStateReceiver`] for the new connection. +1352 /// +1353 /// The returned future is `'static`, so it can be stored without being lifetime-bound to `&self`. +1354 pub(crate) fn register_connection( +1355 &self, +1356 remote: EndpointId, +1357 conn: noq::Connection, +1358 ) -> impl Future<Output = Result<PathStateReceiver, RemoteStateActorStoppedError>> + Send + 'static +1359 { +1360 let (tx, rx) = oneshot::channel(); +1361 let sender = self.actor_sender.clone(); +1362 async move { +1363 sender +1364 .send(ActorMessage::AddConnection(remote, conn, tx)) +1365 .await +1366 .map_err(|_| RemoteStateActorStoppedError::new())?; +1367 rx.await.map_err(|_| RemoteStateActorStoppedError::new()) +1368 } +1369 } +1370} +1371 +1372#[derive(derive_more::Debug)] +1373#[allow(clippy::enum_variant_names)] +1374enum ActorMessage { +1375 NetworkChange, +1376 RelayMapChange, +1377 #[debug("ResolveRemote(..)")] +1378 ResolveRemote( +1379 EndpointAddr, +1380 oneshot::Sender<Result<(), AddressLookupFailed>>, +1381 ), +1382 #[debug("AddConnection(..)")] +1383 AddConnection( +1384 EndpointId, +1385 noq::Connection, +1386 oneshot::Sender<PathStateReceiver>, +1387 ), +1388 /// Re-evaluate direct addresses, e.g. after configured external addresses changed. +1389 DirectAddrRefresh, +1390 #[cfg(all(test, with_crypto_provider))] +1391 ForceNetworkChange(bool), +1392} +1393 +1394/// State for polling until a default route is available after a network change. +1395/// +1396/// When a network change is detected but no default route exists yet (e.g., +1397/// interface just came up but gateway not assigned), we poll with exponential +1398/// backoff until the gateway appears. This avoids the fixed 2s delay that was +1399/// too slow for interface recovery scenarios. +1400struct PendingNetworkChangeNotify { +1401 /// Next time to check for default route. +1402 next_check: Instant, +1403 /// Current backoff interval. +1404 interval: Duration, +1405 /// Whether this was a major change. +1406 is_major: bool, +1407 /// When we started polling (to enforce a max wait). +1408 started: Instant, +1409} +1410 +1411impl PendingNetworkChangeNotify { +1412 const INITIAL_INTERVAL: Duration = Duration::from_millis(100); +1413 const MAX_INTERVAL: Duration = Duration::from_secs(1); +1414 const MAX_WAIT: Duration = Duration::from_secs(5); +1415 +1416 fn new(is_major: bool) -> Self { +1417 Self { +1418 next_check: Instant::now() + Self::INITIAL_INTERVAL, +1419 interval: Self::INITIAL_INTERVAL, +1420 is_major, +1421 started: Instant::now(), +1422 } +1423 } +1424 +1425 /// Advance to the next check interval (exponential backoff, capped). +1426 fn advance(&mut self) { +1427 self.interval = (self.interval * 2).min(Self::MAX_INTERVAL); +1428 self.next_check = Instant::now() + self.interval; +1429 } +1430 +1431 /// Whether we've exceeded the maximum wait time. +1432 fn expired(&self) -> bool { +1433 self.started.elapsed() >= Self::MAX_WAIT +1434 } +1435} +1436 +1437struct Actor { +1438 /// A clone of the quinn Endpoint. +1439 /// +1440 /// The task of this actor is currently owned by the [`crate::Endpoint`] and wrapped in +1441 /// an [`AbortOnDropHandle`]. When [`crate::Endpoint::close`] is called various +1442 /// subsystems are being stopped. Then, when [`ShutdownState::at_endpoint_closed`] is +1443 /// called by [`crate::Endpoint::close`], this actor itself is stopped via it's +1444 /// [`CancellationToken`] and we will drop this clone of the endpoint. The endpoint is +1445 /// then finally dropped when the [`crate::Endpoint`] itself is dropped. +1446 /// +1447 /// All of this to say: keeping the quinn endpoint alive here does not impact the +1448 /// lifetime of it since it's lifetime is shorter than that one that's stored in the +1449 /// [`crate::Endpoint`]. +1450 endpoint: noq::Endpoint, +1451 /// Shared state between an awful lot of iroh subsystems. +1452 /// +1453 /// In particular both the [`EndpointInner`] as well as this actor itself have a +1454 /// copy. But also other subsystems that consequently have access to way to much state. +1455 sock: Arc<Socket>, +1456 /// Tracks the networkmap endpoint entity for each endpoint discovery key. +1457 remote_map: RemoteMap, +1458 /// When set, is an AfterFunc timer that will call Socket::do_periodic_stun. +1459 periodic_re_stun_timer: time::Interval, +1460 /// An actor watching the local network interfaces. +1461 /// +1462 /// The monitored changes are emitted via [`Self::local_interfaces_watcher`]. +1463 network_monitor: netmon::Monitor, +1464 /// Watcher for changes to the local network interfaces, IP addresses and routes. +1465 local_interfaces_watcher: n0_watcher::Direct<netmon::State>, +1466 transports_network_change: transports::NetworkChangeSender, +1467 /// Indicates the direct addr update state. +1468 direct_addr_update_state: DirectAddrUpdateState, +1469 direct_addr_done_rx: mpsc::Receiver<()>, +1470 /// Polling state for [`Actor::notify_quic_network_change`]. +1471 /// +1472 /// When a network change is detected but no default route is available yet, +1473 /// we poll with exponential backoff (100ms, 200ms, 400ms, 800ms, 1s, 1s, ...) +1474 /// until the gateway appears. Once it does, we notify immediately. +1475 /// After 5s total we notify anyway even without a gateway. +1476 call_notify_quic_network_change: Option<PendingNetworkChangeNotify>, +1477} +1478 +1479impl Actor { +1480 async fn run( +1481 mut self, +1482 mut msg_receiver: mpsc::Receiver<ActorMessage>, +1483 shutdown_token: CancellationToken, +1484 mut local_addrs_watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1485 ) { +1486 // Setup network monitoring +1487 let mut current_netmon_state = self.local_interfaces_watcher.get(); +1488 +1489 let mut portmap_watcher = self +1490 .direct_addr_update_state +1491 .port_mapper +1492 .watch_external_address(); 1493 -1494 let mut net_report_watcher = self.sock.net_report.watch(); -1495 -1496 // ensure we are doing an initial publish of our addresses -1497 self.sock.publish_my_addr(); +1494 let mut receiver_closed = false; +1495 let mut portmap_watcher_closed = false; +1496 +1497 let mut net_report_watcher = self.sock.net_report.watch(); 1498 -1499 while !shutdown_token.is_cancelled() { -1500 self.sock.metrics.socket.actor_tick_main.inc(); -1501 let portmap_watcher_changed = portmap_watcher.changed(); -1502 -1503 let notify_quic_network_change = match &self.call_notify_quic_network_change { -1504 Some(pending) => { -1505 MaybeFuture::Some(n0_future::time::sleep_until(pending.next_check)) -1506 } -1507 None => MaybeFuture::None, -1508 }; -1509 n0_future::pin!(notify_quic_network_change); -1510 -1511 tokio::select! { -1512 _ = shutdown_token.cancelled() => { -1513 debug!("tick: shutting down"); -1514 return; -1515 } -1516 msg = msg_receiver.recv(), if !receiver_closed => { -1517 let Some(msg) = msg else { -1518 trace!("tick: socket receiver closed"); -1519 self.sock.metrics.socket.actor_tick_other.inc(); -1520 receiver_closed = true; -1521 continue; -1522 }; -1523 -1524 trace!(?msg, "tick: msg"); -1525 self.sock.metrics.socket.actor_tick_msg.inc(); -1526 self.handle_actor_message(msg).await; -1527 } -1528 tick = self.periodic_re_stun_timer.tick() => { -1529 trace!("tick: re_stun {:?}", tick); -1530 self.sock.metrics.socket.actor_tick_re_stun.inc(); -1531 self.re_stun(UpdateReason::Periodic); -1532 } -1533 new_addr = local_addrs_watcher.updated() => { -1534 match new_addr { -1535 Ok(addrs) => { -1536 if !addrs.is_empty() { -1537 trace!(?addrs, "local addrs"); -1538 self.sock.publish_my_addr(); -1539 } -1540 } -1541 Err(_) => { -1542 warn!("local addr watcher stopped"); +1499 // ensure we are doing an initial publish of our addresses +1500 self.sock.publish_my_addr(); +1501 +1502 while !shutdown_token.is_cancelled() { +1503 self.sock.metrics.socket.actor_tick_main.inc(); +1504 let portmap_watcher_changed = portmap_watcher.changed(); +1505 +1506 let notify_quic_network_change = match &self.call_notify_quic_network_change { +1507 Some(pending) => { +1508 MaybeFuture::Some(n0_future::time::sleep_until(pending.next_check)) +1509 } +1510 None => MaybeFuture::None, +1511 }; +1512 n0_future::pin!(notify_quic_network_change); +1513 +1514 tokio::select! { +1515 _ = shutdown_token.cancelled() => { +1516 debug!("tick: shutting down"); +1517 return; +1518 } +1519 msg = msg_receiver.recv(), if !receiver_closed => { +1520 let Some(msg) = msg else { +1521 trace!("tick: socket receiver closed"); +1522 self.sock.metrics.socket.actor_tick_other.inc(); +1523 receiver_closed = true; +1524 continue; +1525 }; +1526 +1527 trace!(?msg, "tick: msg"); +1528 self.sock.metrics.socket.actor_tick_msg.inc(); +1529 self.handle_actor_message(msg).await; +1530 } +1531 tick = self.periodic_re_stun_timer.tick() => { +1532 trace!("tick: re_stun {:?}", tick); +1533 self.sock.metrics.socket.actor_tick_re_stun.inc(); +1534 self.re_stun(UpdateReason::Periodic); +1535 } +1536 new_addr = local_addrs_watcher.updated() => { +1537 match new_addr { +1538 Ok(addrs) => { +1539 if !addrs.is_empty() { +1540 trace!(?addrs, "local addrs"); +1541 self.sock.publish_my_addr(); +1542 } 1543 } -1544 } -1545 } -1546 report = net_report_watcher.updated() => { -1547 match report { -1548 Ok((report, _)) => { -1549 self.handle_net_report_report(report); -1550 #[cfg(not(wasm_browser))] -1551 { -1552 self.periodic_re_stun_timer = new_re_stun_timer(true); -1553 } -1554 } -1555 Err(_) => { -1556 warn!("net report watcher stopped"); +1544 Err(_) => { +1545 warn!("local addr watcher stopped"); +1546 } +1547 } +1548 } +1549 report = net_report_watcher.updated() => { +1550 match report { +1551 Ok((report, _)) => { +1552 self.handle_net_report_report(report); +1553 #[cfg(not(wasm_browser))] +1554 { +1555 self.periodic_re_stun_timer = new_re_stun_timer(true); +1556 } 1557 } -1558 } -1559 } -1560 reason = self.direct_addr_done_rx.recv() => { -1561 match reason { -1562 Some(()) => { -1563 // check if a new run needs to be scheduled -1564 let state = self.local_interfaces_watcher.get(); -1565 self.direct_addr_update_state.try_run(state.into()); -1566 } -1567 None => { -1568 warn!("direct addr watcher died"); +1558 Err(_) => { +1559 warn!("net report watcher stopped"); +1560 } +1561 } +1562 } +1563 reason = self.direct_addr_done_rx.recv() => { +1564 match reason { +1565 Some(()) => { +1566 // check if a new run needs to be scheduled +1567 let state = self.local_interfaces_watcher.get(); +1568 self.direct_addr_update_state.try_run(state.into()); 1569 } -1570 } -1571 } -1572 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1573 if change.is_err() { -1574 trace!("tick: portmap watcher closed"); -1575 self.sock.metrics.socket.actor_tick_other.inc(); -1576 -1577 portmap_watcher_closed = true; -1578 continue; -1579 } -1580 -1581 trace!("tick: portmap changed"); -1582 self.sock.metrics.socket.actor_tick_portmap_changed.inc(); -1583 let new_external_address = *portmap_watcher.borrow(); -1584 if new_external_address.is_some() { -1585 self.sock.metrics.net_report.portmap_external_address_updated.inc(); -1586 } -1587 debug!("external address updated: {new_external_address:?}"); -1588 self.re_stun(UpdateReason::PortmapUpdated); -1589 }, -1590 state = self.local_interfaces_watcher.updated() => { -1591 let Ok(state) = state else { -1592 trace!("tick: link change receiver closed"); -1593 self.sock.metrics.socket.actor_tick_other.inc(); -1594 continue; -1595 }; -1596 let is_major = state.is_major_change(&current_netmon_state); -1597 event!( -1598 target: "iroh::_events::link_change", -1599 Level::DEBUG, -1600 ?state, -1601 is_major -1602 ); -1603 current_netmon_state = state; -1604 self.sock.metrics.socket.actor_link_change.inc(); -1605 self.handle_network_change(is_major); -1606 } -1607 _remote_id = self.remote_map.cleanup() => {}, -1608 _ = &mut notify_quic_network_change => { -1609 let has_network = self.has_usable_network(); -1610 let Some(pending) = self.call_notify_quic_network_change.as_mut() else { -1611 continue; -1612 }; -1613 if has_network || pending.expired() { -1614 // Gateway appeared or we've waited long enough, notify now. -1615 let is_major = pending.is_major; -1616 self.call_notify_quic_network_change = None; -1617 self.notify_quic_network_change(is_major); -1618 } else { -1619 // No gateway yet, back off and try again. -1620 trace!( -1621 interval = ?pending.interval, -1622 elapsed = ?pending.started.elapsed(), -1623 "no default route yet, retrying" -1624 ); -1625 pending.advance(); -1626 } -1627 } -1628 else => { -1629 trace!("tick: else"); +1570 None => { +1571 warn!("direct addr watcher died"); +1572 } +1573 } +1574 } +1575 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1576 if change.is_err() { +1577 trace!("tick: portmap watcher closed"); +1578 self.sock.metrics.socket.actor_tick_other.inc(); +1579 +1580 portmap_watcher_closed = true; +1581 continue; +1582 } +1583 +1584 trace!("tick: portmap changed"); +1585 self.sock.metrics.socket.actor_tick_portmap_changed.inc(); +1586 let new_external_address = *portmap_watcher.borrow(); +1587 if new_external_address.is_some() { +1588 self.sock.metrics.net_report.portmap_external_address_updated.inc(); +1589 } +1590 debug!("external address updated: {new_external_address:?}"); +1591 self.re_stun(UpdateReason::PortmapUpdated); +1592 }, +1593 state = self.local_interfaces_watcher.updated() => { +1594 let Ok(state) = state else { +1595 trace!("tick: link change receiver closed"); +1596 self.sock.metrics.socket.actor_tick_other.inc(); +1597 continue; +1598 }; +1599 let is_major = state.is_major_change(&current_netmon_state); +1600 event!( +1601 target: "iroh::_events::link_change", +1602 Level::DEBUG, +1603 ?state, +1604 is_major +1605 ); +1606 current_netmon_state = state; +1607 self.sock.metrics.socket.actor_link_change.inc(); +1608 self.handle_network_change(is_major); +1609 } +1610 _remote_id = self.remote_map.cleanup() => {}, +1611 _ = &mut notify_quic_network_change => { +1612 let has_network = self.has_usable_network(); +1613 let Some(pending) = self.call_notify_quic_network_change.as_mut() else { +1614 continue; +1615 }; +1616 if has_network || pending.expired() { +1617 // Gateway appeared or we've waited long enough, notify now. +1618 let is_major = pending.is_major; +1619 self.call_notify_quic_network_change = None; +1620 self.notify_quic_network_change(is_major); +1621 } else { +1622 // No gateway yet, back off and try again. +1623 trace!( +1624 interval = ?pending.interval, +1625 elapsed = ?pending.started.elapsed(), +1626 "no default route yet, retrying" +1627 ); +1628 pending.advance(); +1629 } 1630 } -1631 } -1632 } -1633 } -1634 -1635 /// Whether the local network has a default route and at least one IP address. -1636 fn has_usable_network(&mut self) -> bool { -1637 #[cfg(target_family = "wasm")] -1638 { -1639 true -1640 } -1641 #[cfg(not(target_family = "wasm"))] -1642 { -1643 let interfaces = self.local_interfaces_watcher.get(); -1644 interfaces.default_route_interface.is_some() -1645 && (interfaces.have_v4 || interfaces.have_v6) -1646 } -1647 } -1648 -1649 /// Handles a change detected in the local network conditions. -1650 /// -1651 /// This is triggered when the netmon actor detects a change in the local network -1652 /// interfaces, assigned IP addresses and routes. -1653 fn handle_network_change(&mut self, is_major: bool) { -1654 debug!(is_major, "link change detected"); -1655 -1656 if is_major { -1657 if let Err(err) = self.transports_network_change.rebind() { -1658 warn!("failed to rebind transports: {err:?}"); -1659 } -1660 self.transports_network_change.check_relay_connection(); -1661 -1662 #[cfg(not(wasm_browser))] -1663 self.sock.dns_resolver.reset(); -1664 self.re_stun(UpdateReason::LinkChangeMajor); -1665 } else { -1666 self.re_stun(UpdateReason::LinkChangeMinor); -1667 } -1668 -1669 if self.has_usable_network() { -1670 // This is considered a usable network change, propagate it to the QUIC stack -1671 // right away. -1672 self.call_notify_quic_network_change = None; -1673 self.notify_quic_network_change(is_major); -1674 } else { -1675 // No default route yet (e.g., interface just came up but gateway not -1676 // assigned). Poll with exponential backoff until the gateway appears. -1677 match &mut self.call_notify_quic_network_change { -1678 Some(pending) => { -1679 // Update is_major if this change is more severe. -1680 pending.is_major |= is_major; -1681 } -1682 None => { -1683 self.call_notify_quic_network_change = -1684 Some(PendingNetworkChangeNotify::new(is_major)); -1685 } -1686 } -1687 } -1688 } -1689 -1690 /// Notifies the QUIC stack of the network change we observed. -1691 /// -1692 /// This is decoupled from receiving the network change, because we try to debounce -1693 /// network changes as they often arrive in groups. -1694 fn notify_quic_network_change(&mut self, is_major: bool) { -1695 #[derive(Debug)] -1696 struct Hint { -1697 local_addrs: FxHashSet<IpAddr>, -1698 } -1699 -1700 impl NetworkChangeHint for Hint { -1701 fn is_path_recoverable( -1702 &self, -1703 _path_id: noq::PathId, -1704 network_path: noq_proto::FourTuple, -1705 ) -> bool { -1706 match MultipathMappedAddr::from(network_path.remote()) { -1707 MultipathMappedAddr::Mixed(_) => { -1708 // This address is only ever used to send an Initial packet to, it -1709 // should never appear as an established path. -1710 error!("A mixed address can not be used for network changes"); -1711 false -1712 } -1713 MultipathMappedAddr::Relay(_) => { -1714 // We pretend the relay path is never affected by link changes. The -1715 // relay actor transparently reconnects and the addresses never -1716 // change. -1717 true -1718 } -1719 MultipathMappedAddr::Ip(_) => { -1720 // If we no longer have a valid interface to send from for a local -1721 // IP then it can not be recovered. -1722 match network_path.local_ip() { -1723 Some(local_ip) => self.local_addrs.contains(&local_ip), -1724 None => true, -1725 } -1726 } -1727 MultipathMappedAddr::Custom(_) => { -1728 // Assume it is unrecoverable for now -1729 false -1730 } -1731 } -1732 } -1733 } -1734 -1735 let hint = Hint { -1736 #[cfg(not(wasm_browser))] -1737 local_addrs: { -1738 let interfaces = self.local_interfaces_watcher.get(); -1739 interfaces -1740 .local_addresses -1741 .regular -1742 .iter() -1743 .chain(interfaces.local_addresses.loopback.iter()) -1744 .copied() -1745 .collect() -1746 }, -1747 #[cfg(wasm_browser)] -1748 local_addrs: Default::default(), -1749 }; -1750 -1751 self.endpoint.handle_network_change(Some(Arc::new(hint))); -1752 self.remote_map.on_network_change(is_major); -1753 } -1754 -1755 fn handle_relay_map_change(&mut self) { -1756 self.re_stun(UpdateReason::RelayMapChange); -1757 } -1758 -1759 fn re_stun(&mut self, why: UpdateReason) { -1760 let state = self.local_interfaces_watcher.get(); -1761 self.direct_addr_update_state -1762 .schedule_run(why, state.into()); -1763 } -1764 -1765 /// Processes an incoming actor message. -1766 /// -1767 /// Returns `true` if it was a shutdown. -1768 async fn handle_actor_message(&mut self, msg: ActorMessage) { -1769 match msg { -1770 ActorMessage::NetworkChange => { -1771 self.network_monitor.network_change().await.ok(); -1772 } -1773 ActorMessage::RelayMapChange => { -1774 self.handle_relay_map_change(); +1631 else => { +1632 trace!("tick: else"); +1633 } +1634 } +1635 } +1636 } +1637 +1638 /// Whether the local network has a default route and at least one IP address. +1639 fn has_usable_network(&mut self) -> bool { +1640 #[cfg(target_family = "wasm")] +1641 { +1642 true +1643 } +1644 #[cfg(not(target_family = "wasm"))] +1645 { +1646 let interfaces = self.local_interfaces_watcher.get(); +1647 interfaces.default_route_interface.is_some() +1648 && (interfaces.have_v4 || interfaces.have_v6) +1649 } +1650 } +1651 +1652 /// Handles a change detected in the local network conditions. +1653 /// +1654 /// This is triggered when the netmon actor detects a change in the local network +1655 /// interfaces, assigned IP addresses and routes. +1656 fn handle_network_change(&mut self, is_major: bool) { +1657 debug!(is_major, "link change detected"); +1658 +1659 if is_major { +1660 if let Err(err) = self.transports_network_change.rebind() { +1661 warn!("failed to rebind transports: {err:?}"); +1662 } +1663 self.transports_network_change.check_relay_connection(); +1664 +1665 #[cfg(not(wasm_browser))] +1666 self.sock.dns_resolver.reset(); +1667 self.re_stun(UpdateReason::LinkChangeMajor); +1668 } else { +1669 self.re_stun(UpdateReason::LinkChangeMinor); +1670 } +1671 +1672 if self.has_usable_network() { +1673 // This is considered a usable network change, propagate it to the QUIC stack +1674 // right away. +1675 self.call_notify_quic_network_change = None; +1676 self.notify_quic_network_change(is_major); +1677 } else { +1678 // No default route yet (e.g., interface just came up but gateway not +1679 // assigned). Poll with exponential backoff until the gateway appears. +1680 match &mut self.call_notify_quic_network_change { +1681 Some(pending) => { +1682 // Update is_major if this change is more severe. +1683 pending.is_major |= is_major; +1684 } +1685 None => { +1686 self.call_notify_quic_network_change = +1687 Some(PendingNetworkChangeNotify::new(is_major)); +1688 } +1689 } +1690 } +1691 } +1692 +1693 /// Notifies the QUIC stack of the network change we observed. +1694 /// +1695 /// This is decoupled from receiving the network change, because we try to debounce +1696 /// network changes as they often arrive in groups. +1697 fn notify_quic_network_change(&mut self, is_major: bool) { +1698 #[derive(Debug)] +1699 struct Hint { +1700 local_addrs: FxHashSet<IpAddr>, +1701 } +1702 +1703 impl NetworkChangeHint for Hint { +1704 fn is_path_recoverable( +1705 &self, +1706 _path_id: noq::PathId, +1707 network_path: noq_proto::FourTuple, +1708 ) -> bool { +1709 match MultipathMappedAddr::from(network_path.remote()) { +1710 MultipathMappedAddr::Mixed(_) => { +1711 // This address is only ever used to send an Initial packet to, it +1712 // should never appear as an established path. +1713 error!("A mixed address can not be used for network changes"); +1714 false +1715 } +1716 MultipathMappedAddr::Relay(_) => { +1717 // We pretend the relay path is never affected by link changes. The +1718 // relay actor transparently reconnects and the addresses never +1719 // change. +1720 true +1721 } +1722 MultipathMappedAddr::Ip(_) => { +1723 // If we no longer have a valid interface to send from for a local +1724 // IP then it can not be recovered. +1725 match network_path.local_ip() { +1726 Some(local_ip) => self.local_addrs.contains(&local_ip), +1727 None => true, +1728 } +1729 } +1730 MultipathMappedAddr::Custom(_) => { +1731 // Assume it is unrecoverable for now +1732 false +1733 } +1734 } +1735 } +1736 } +1737 +1738 let hint = Hint { +1739 #[cfg(not(wasm_browser))] +1740 local_addrs: { +1741 let interfaces = self.local_interfaces_watcher.get(); +1742 interfaces +1743 .local_addresses +1744 .regular +1745 .iter() +1746 .chain(interfaces.local_addresses.loopback.iter()) +1747 .copied() +1748 .collect() +1749 }, +1750 #[cfg(wasm_browser)] +1751 local_addrs: Default::default(), +1752 }; +1753 +1754 self.endpoint.handle_network_change(Some(Arc::new(hint))); +1755 self.remote_map.on_network_change(is_major); +1756 } +1757 +1758 fn handle_relay_map_change(&mut self) { +1759 self.re_stun(UpdateReason::RelayMapChange); +1760 } +1761 +1762 fn re_stun(&mut self, why: UpdateReason) { +1763 let state = self.local_interfaces_watcher.get(); +1764 self.direct_addr_update_state +1765 .schedule_run(why, state.into()); +1766 } +1767 +1768 /// Processes an incoming actor message. +1769 /// +1770 /// Returns `true` if it was a shutdown. +1771 async fn handle_actor_message(&mut self, msg: ActorMessage) { +1772 match msg { +1773 ActorMessage::NetworkChange => { +1774 self.network_monitor.network_change().await.ok(); 1775 } -1776 ActorMessage::ResolveRemote(addr, tx) => { -1777 self.remote_map.resolve_remote(addr, tx).await; +1776 ActorMessage::RelayMapChange => { +1777 self.handle_relay_map_change(); 1778 } -1779 ActorMessage::AddConnection(remote, conn, tx) => { -1780 self.remote_map.add_connection(remote, conn, tx).await; +1779 ActorMessage::ResolveRemote(addr, tx) => { +1780 self.remote_map.resolve_remote(addr, tx).await; 1781 } -1782 ActorMessage::DirectAddrRefresh => { -1783 #[cfg(not(wasm_browser))] -1784 { -1785 let (report, _reason) = self.sock.net_report.get(); -1786 self.update_direct_addresses(report.as_ref()); -1787 } -1788 } -1789 #[cfg(all(test, with_crypto_provider))] -1790 ActorMessage::ForceNetworkChange(is_major) => { -1791 self.handle_network_change(is_major); -1792 } -1793 } -1794 } -1795 -1796 /// Updates the direct addresses of this socket. -1797 /// -1798 /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of -1799 /// direct addresses from: +1782 ActorMessage::AddConnection(remote, conn, tx) => { +1783 self.remote_map.add_connection(remote, conn, tx).await; +1784 } +1785 ActorMessage::DirectAddrRefresh => { +1786 #[cfg(not(wasm_browser))] +1787 { +1788 let (report, _reason) = self.sock.net_report.get(); +1789 self.update_direct_addresses(report.as_ref()); +1790 } +1791 } +1792 #[cfg(all(test, with_crypto_provider))] +1793 ActorMessage::ForceNetworkChange(is_major) => { +1794 self.handle_network_change(is_major); +1795 } +1796 } +1797 } +1798 +1799 /// Updates the direct addresses of this socket. 1800 /// -1801 /// - The portmapper. -1802 /// - A net_report report. -1803 /// - The local interfaces IP addresses. -1804 /// - User configured addresses. -1805 #[cfg(not(wasm_browser))] -1806 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1807 // We only want to have one DirectAddr for each SocketAddr we have. So we store -1808 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -1809 // DirectAddr from each entry. -1810 let mut addrs: BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)> = -1811 BTreeMap::new(); -1812 -1813 // First add PortMapper provided addresses. -1814 let portmap_watcher = self -1815 .direct_addr_update_state -1816 .port_mapper -1817 .watch_external_address(); -1818 let maybe_port_mapped = *portmap_watcher.borrow(); -1819 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -1820 addrs -1821 .entry(portmap_ext) -1822 .or_insert((DirectAddrType::Portmapped, None)); -1823 } -1824 -1825 // Next add STUN addresses from the net_report report. -1826 if let Some(net_report_report) = net_report_report { -1827 if let Some(global_v4) = net_report_report.global_v4 { -1828 addrs -1829 .entry(global_v4.into()) -1830 .or_insert((DirectAddrType::Qad, None)); -1831 -1832 // If they're behind a hard NAT and are using a fixed -1833 // port locally, assume they might've added a static -1834 // port mapping on their router to the same explicit -1835 // port that we are running with. Worst case it's an invalid candidate mapping. -1836 let port = self.sock.ip_bind_addrs().iter().find_map(|addr| { -1837 if addr.port() != 0 { -1838 Some(addr.port()) -1839 } else { -1840 None -1841 } -1842 }); -1843 -1844 if let Some(port) = port -1845 && net_report_report -1846 .mapping_varies_by_dest() -1847 .unwrap_or_default() -1848 { -1849 let mut addr = global_v4; -1850 addr.set_port(port); -1851 addrs -1852 .entry(addr.into()) -1853 .or_insert((DirectAddrType::Qad4LocalPort, None)); -1854 } -1855 } -1856 if let Some(global_v6) = net_report_report.global_v6 { -1857 addrs -1858 .entry(global_v6.into()) -1859 .or_insert((DirectAddrType::Qad, None)); -1860 } -1861 } -1862 -1863 self.collect_local_addresses(&mut addrs); -1864 -1865 // Add configured external addresses. -1866 for addr in self.sock.configured_addrs.read().expect("poisoned").iter() { -1867 addrs.entry(*addr).or_insert((DirectAddrType::Config, None)); -1868 } -1869 -1870 // Finally create and store store all these direct addresses -1871 let stored_addrs = addrs -1872 .into_iter() -1873 .filter_map(|(addr, (typ, flags))| { -1874 // Filter out deprecated IPs -1875 let is_deprecated = flags.map(|f| f.deprecated).unwrap_or(false); -1876 if is_deprecated { -1877 return None; -1878 } -1879 Some(DirectAddr { addr, typ }) -1880 }) -1881 .collect(); -1882 self.sock.store_direct_addresses(stored_addrs); -1883 } -1884 -1885 #[cfg(not(wasm_browser))] -1886 fn collect_local_addresses( -1887 &mut self, -1888 addrs: &mut BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)>, -1889 ) { -1890 let netmon_state = self.local_interfaces_watcher.get(); -1891 -1892 // Matches the addresses that have been bound vs the requested ones. -1893 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -1894 .sock -1895 .ip_bind_addrs() -1896 .iter() -1897 .copied() -1898 .zip(self.sock.ip_local_addrs()) -1899 .collect(); -1900 -1901 // Do we listen on any IPv4 unspecified address? -1902 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -1903 if a.is_ipv4() && a.ip().is_unspecified() { -1904 Some(a.port()) -1905 } else { -1906 None -1907 } -1908 }); -1909 // Do we listen on any IPv6 unspecified address? -1910 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -1911 if a.is_ipv6() && a.ip().is_unspecified() { -1912 Some(a.port()) -1913 } else { -1914 None -1915 } -1916 }); -1917 -1918 // If a socket is bound to the unspecified address, create SocketAddrs for -1919 // each local IP address by pairing it with the port the socket is bound on. -1920 if local_addrs -1921 .iter() -1922 .any(|(_, local)| local.ip().is_unspecified()) -1923 { -1924 let LocalAddresses { -1925 regular: mut ips, -1926 loopback, -1927 } = self.local_interfaces_watcher.get().local_addresses; -1928 if ips.is_empty() && addrs.is_empty() { -1929 // Include loopback addresses only if there are no other interfaces -1930 // or public addresses, this allows testing offline. -1931 ips = loopback; -1932 } -1933 -1934 for ip in ips { -1935 let port_if_unspecified = match ip { -1936 IpAddr::V4(_) => has_ipv4_unspecified, -1937 IpAddr::V6(_) => has_ipv6_unspecified, -1938 }; -1939 if let Some(port) = port_if_unspecified { -1940 let addr = SocketAddr::new(ip, port); -1941 let flags = find_flags(&netmon_state, ip); -1942 addrs.entry(addr).or_insert((DirectAddrType::Local, flags)); -1943 } -1944 } -1945 } -1946 -1947 // If a socket is bound to a specific address, add it. -1948 for (bound, local) in local_addrs { -1949 if !bound.ip().is_unspecified() { -1950 let flags = find_flags(&netmon_state, local.ip()); -1951 addrs.entry(local).or_insert((DirectAddrType::Local, flags)); -1952 } -1953 } -1954 } -1955 -1956 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -1957 if let Some(ref mut r) = report { -1958 self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -1959 if r.preferred_relay.is_none() -1960 && let Some(my_relay) = self.sock.my_relay() -1961 { -1962 r.preferred_relay.replace(my_relay); -1963 } -1964 -1965 // Notify all transports -1966 self.transports_network_change.on_network_change(r); -1967 } -1968 -1969 #[cfg(not(wasm_browser))] -1970 self.update_direct_addresses(report.as_ref()); -1971 } -1972} -1973 -1974#[cfg(not(wasm_browser))] -1975fn find_flags(state: &netmon::State, ip: IpAddr) -> Option<Ipv6AddrFlags> { -1976 if ip.is_ipv6() { -1977 state -1978 .interfaces -1979 .values() -1980 .flat_map(|i| i.addrs()) -1981 .find_map(|addr| match addr { -1982 IpNet::V4(_) => None, -1983 IpNet::V6 { net, flags, .. } => { -1984 if net.addr() == ip { -1985 Some(flags) -1986 } else { -1987 None -1988 } -1989 } -1990 }) -1991 } else { -1992 None -1993 } -1994} -1995 -1996fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -1997 // Pick a random duration between 20 and 26 seconds (just under 30s, -1998 // a common UDP NAT timeout on Linux,etc) -1999 let mut rng = rand::rng(); -2000 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); -2001 if initial_delay { -2002 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -2003 time::interval_at(time::Instant::now() + d, d) -2004 } else { -2005 debug!( -2006 "scheduling periodic_stun to run immediately and in {}s", -2007 d.as_secs() -2008 ); -2009 time::interval(d) -2010 } -2011} -2012 -2013/// The discovered direct addresses of this [`Socket`]. -2014/// -2015/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself. -2016/// They include all locally bound ones as well as those discovered by other mechanisms like -2017/// QAD. -2018#[derive(derive_more::Debug, Clone, Default)] -2019struct DiscoveredDirectAddrs { -2020 /// The last set of discovered direct addresses. -2021 addrs: Watchable<BTreeSet<DirectAddr>>, -2022 -2023 /// The last time the direct addresses were updated, even if there was no change. -2024 /// -2025 /// This is only ever None at startup. -2026 updated_at: Arc<RwLock<Option<Instant>>>, -2027} -2028 -2029impl DiscoveredDirectAddrs { -2030 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -2031 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -2032 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -2033 let updated = self.addrs.set(addrs).is_ok(); -2034 if updated { -2035 event!( -2036 target: "iroh::_events::direct_addrs", -2037 Level::DEBUG, -2038 addrs = ?self.addrs.get(), -2039 ); -2040 } -2041 updated -2042 } -2043 -2044 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { -2045 self.addrs.get().into_iter().map(|da| da.addr) -2046 } -2047} -2048 -2049/// A *direct address* on which an iroh-endpoint might be contactable. -2050/// -2051/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be -2052/// contacted. These can come from various sources depending on the network topology of the -2053/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. -2054/// -2055/// This is essentially a combination of our local addresses combined with any reflexive -2056/// transport addresses we discovered using QAD. -2057#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -2058pub struct DirectAddr { -2059 /// The address. -2060 pub addr: SocketAddr, -2061 /// The origin of this direct address. -2062 pub typ: DirectAddrType, -2063} -2064 -2065/// The type of direct address. -2066/// -2067/// These are the various sources or origins from which an iroh endpoint might have found a -2068/// possible [`DirectAddr`]. -2069#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -2070#[non_exhaustive] -2071pub enum DirectAddrType { -2072 /// Not yet determined.. -2073 Unknown, -2074 /// A locally bound socket address. -2075 Local, -2076 /// Public internet address discovered via QAD. -2077 /// -2078 /// When possible an iroh endpoint will perform QAD to discover which is the address -2079 /// from which it sends data on the public internet. This can be different from locally -2080 /// bound addresses when the endpoint is on a local network which performs NAT or similar. -2081 Qad, -2082 /// An address assigned by the router using port mapping. -2083 /// -2084 /// When possible an iroh endpoint will request a port mapping from the local router to -2085 /// get a publicly routable direct address. -2086 Portmapped, -2087 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -2088 /// -2089 /// It is possible to configure iroh to bound to a specific port and independently -2090 /// configure the router to forward this port to the iroh endpoint. This indicates a -2091 /// situation like this, which still uses QAD to discover the public address. -2092 Qad4LocalPort, -2093 /// An address explicitly provided by the user via configuration. -2094 Config, -2095} -2096 -2097impl Display for DirectAddrType { -2098 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -2099 match self { -2100 DirectAddrType::Unknown => write!(f, "?"), -2101 DirectAddrType::Local => write!(f, "local"), -2102 DirectAddrType::Qad => write!(f, "qad"), -2103 DirectAddrType::Portmapped => write!(f, "portmap"), -2104 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -2105 DirectAddrType::Config => write!(f, "config"), -2106 } -2107 } -2108} -2109 -2110#[cfg(all(test, with_crypto_provider))] -2111mod tests { -2112 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; -2113 -2114 use data_encoding::HEXLOWER; -2115 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; -2116 use iroh_relay::tls::{CaTlsConfig, default_provider}; -2117 use n0_error::{Result, StackResultExt, StdResultExt}; -2118 use n0_future::{MergeBounded, StreamExt, time}; -2119 use n0_tracing_test::traced_test; -2120 use n0_watcher::Watcher; -2121 use rand::{CryptoRng, Rng, RngExt, SeedableRng}; -2122 use tokio_util::task::AbortOnDropHandle; -2123 use tracing::{Instrument, error, info, info_span, instrument}; -2124 -2125 use super::Options; -2126 use crate::{ -2127 Endpoint, SecretKey, -2128 address_lookup::memory::MemoryLookup, -2129 dns::DnsResolver, -2130 endpoint::{QuicTransportConfig, presets}, -2131 socket::{ -2132 EndpointInner, StaticConfig, TransportConfig, -2133 biased_rtt_path_selector::BiasedRttPathSelector, -2134 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, -2135 }, -2136 tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey}, -2137 }; -2138 -2139 const ALPN: &[u8] = b"n0/test/1"; -2140 -2141 fn default_options(rng: &mut impl CryptoRng) -> Options { -2142 let crypto_provider = default_provider(); -2143 let secret_key = SecretKey::from_bytes(&rng.random()); -2144 let tls_config = tls::TlsConfig::new( -2145 secret_key.clone(), -2146 DEFAULT_MAX_TLS_TICKETS, -2147 crypto_provider.clone(), -2148 ); -2149 let static_config = StaticConfig { -2150 server_config: tls_config.make_server_config(false).unwrap(), -2151 client_config: tls_config.make_client_config(false).unwrap(), -2152 tls_config, -2153 token_key: Arc::new(RustlsTokenKey::new(rng, &crypto_provider).unwrap()), -2154 transport_config: QuicTransportConfig::default(), -2155 }; -2156 let server_config = static_config.create_server_config(vec![]); -2157 Options { -2158 transports: vec![ -2159 TransportConfig::default_ipv4(), -2160 TransportConfig::default_ipv6(), -2161 ], -2162 secret_key, -2163 proxy_url: None, -2164 dns_resolver: DnsResolver::new(), -2165 server_config, -2166 tls_config: CaTlsConfig::default() -2167 .client_config(crypto_provider.clone()) -2168 .unwrap(), -2169 #[cfg(any(test, feature = "test-utils"))] -2170 address_lookup_user_data: None, -2171 metrics: Default::default(), -2172 hooks: Default::default(), -2173 path_selector: Arc::new(BiasedRttPathSelector::default()), -2174 portmapper_config: Default::default(), -2175 static_config, -2176 configured_addrs: Default::default(), -2177 } -2178 } -2179 -2180 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -2181 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { -2182 info!("accepting conn"); -2183 let conn = ep.accept().await.expect("no conn"); -2184 -2185 info!("accepting"); -2186 let conn = conn.await.context("accepting")?; -2187 info!("accepting bi"); -2188 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; -2189 -2190 info!("reading"); -2191 let val = recv_bi -2192 .read_to_end(usize::MAX) -2193 .await -2194 .std_context("read to end")?; -2195 -2196 info!("replying"); -2197 for chunk in val.chunks(12) { -2198 send_bi.write_all(chunk).await.std_context("write all")?; -2199 } -2200 -2201 info!("finishing"); -2202 send_bi.finish().std_context("finish")?; -2203 -2204 let stats = conn.stats(); -2205 info!("stats: {:#?}", stats); -2206 if matches!(loss, ExpectedLoss::AlmostNone) { -2207 for info in conn.paths().iter() { -2208 assert!( -2209 info.stats().lost_packets < 10, -2210 "[receiver] path {:?} should not loose many packets", -2211 info.remote_addr() -2212 ); -2213 } -2214 } -2215 -2216 conn.closed().await; -2217 info!("closed"); -2218 ep.inner()?.noq_endpoint().wait_idle().await; -2219 info!("idle"); -2220 -2221 Ok(()) -2222 } -2223 -2224 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -2225 async fn echo_sender( -2226 ep: Endpoint, -2227 dest_id: EndpointId, -2228 msg: &[u8], -2229 loss: ExpectedLoss, -2230 ) -> Result { -2231 info!("connecting to {}", dest_id.fmt_short()); -2232 let dest = EndpointAddr::new(dest_id); -2233 let conn = ep.connect(dest, ALPN).await?; -2234 -2235 info!("opening bi"); -2236 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; -2237 -2238 info!("writing message"); -2239 send_bi.write_all(msg).await.std_context("write all")?; -2240 -2241 info!("finishing"); -2242 send_bi.finish().std_context("finish")?; -2243 -2244 info!("reading_to_end"); -2245 let val = recv_bi -2246 .read_to_end(usize::MAX) -2247 .await -2248 .std_context("read to end")?; -2249 assert_eq!( -2250 val, -2251 msg, -2252 "[sender] expected {}, got {}", -2253 HEXLOWER.encode(msg), -2254 HEXLOWER.encode(&val) -2255 ); -2256 -2257 let stats = conn.stats(); -2258 info!("stats: {:#?}", stats); -2259 if matches!(loss, ExpectedLoss::AlmostNone) { -2260 for info in conn.paths().iter() { -2261 assert!( -2262 info.stats().lost_packets < 10, -2263 "[sender] path {:?} should not loose many packets", -2264 info.remote_addr() -2265 ); -2266 } -2267 } -2268 -2269 conn.close(0u32.into(), b"done"); -2270 info!("closed"); -2271 ep.inner()?.noq_endpoint().wait_idle().await; -2272 info!("idle"); -2273 Ok(()) -2274 } -2275 -2276 #[derive(Debug, Copy, Clone)] -2277 enum ExpectedLoss { -2278 AlmostNone, -2279 YeahSure, -2280 } -2281 -2282 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -2283 async fn run_roundtrip( -2284 sender: Endpoint, -2285 receiver: Endpoint, -2286 payload: &[u8], -2287 loss: ExpectedLoss, -2288 ) -> Result<()> { -2289 tokio::time::timeout(Duration::from_secs(4), async move { -2290 let send_endpoint_id = sender.id(); -2291 let recv_endpoint_id = receiver.id(); -2292 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); -2293 -2294 let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss))); -2295 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; -2296 let sender_is_err = match sender_res { -2297 Ok(()) => false, -2298 Err(err) => { -2299 error!("[sender] Error:\n{err:#?}"); -2300 true -2301 } -2302 }; -2303 let receiver_is_err = match receiver_task.await { -2304 Ok(Ok(())) => false, -2305 Ok(Err(err)) => { -2306 error!("[receiver] Error:\n{err:#?}"); -2307 true -2308 } -2309 Err(joinerr) => { -2310 if joinerr.is_panic() { -2311 std::panic::resume_unwind(joinerr.into_panic()); -2312 } else { -2313 error!("[receiver] Error:\n{joinerr:#?}"); -2314 } -2315 true -2316 } -2317 }; -2318 if sender_is_err || receiver_is_err { -2319 panic!("Sender or receiver errored"); -2320 } -2321 }) -2322 .await -2323 .std_context("timeout")?; -2324 Ok(()) -2325 } -2326 -2327 /// Returns a pair of endpoints with a shared [`MemoryLookup`]. -2328 /// -2329 /// The endpoints do not use a relay server but can connect to each other via local -2330 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if -2331 /// the endpoints rebind. -2332 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { -2333 let address_lookup = MemoryLookup::new(); -2334 let ep1 = Endpoint::builder(presets::Minimal) -2335 .alpns(vec![ALPN.to_vec()]) -2336 .address_lookup(address_lookup.clone()) -2337 .bind() -2338 .await -2339 .unwrap(); -2340 let ep2 = Endpoint::builder(presets::Minimal) -2341 .alpns(vec![ALPN.to_vec()]) -2342 .address_lookup(address_lookup.clone()) -2343 .bind() -2344 .await -2345 .unwrap(); -2346 address_lookup.add_endpoint_info(ep1.addr()); -2347 address_lookup.add_endpoint_info(ep2.addr()); -2348 -2349 let ep1_addr_stream = ep1.watch_addr().stream(); -2350 let ep2_addr_stream = ep2.watch_addr().stream(); -2351 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); -2352 let task = tokio::spawn(async move { -2353 while let Some(addr) = addr_stream.next().await { -2354 address_lookup.add_endpoint_info(addr); -2355 } -2356 }); -2357 -2358 (AbortOnDropHandle::new(task), ep1, ep2) -2359 } -2360 -2361 #[tokio::test(flavor = "multi_thread")] -2362 #[traced_test] -2363 async fn test_two_devices_roundtrip_noq_small() -> Result { -2364 let (_guard, m1, m2) = endpoint_pair().await; -2365 -2366 run_roundtrip( -2367 m1.clone(), -2368 m2.clone(), -2369 b"hello m1", -2370 ExpectedLoss::AlmostNone, -2371 ) -2372 .await?; -2373 run_roundtrip( -2374 m2.clone(), -2375 m1.clone(), -2376 b"hello m2", -2377 ExpectedLoss::AlmostNone, -2378 ) -2379 .await?; -2380 Ok(()) -2381 } -2382 -2383 #[tokio::test(flavor = "multi_thread")] -2384 #[traced_test] -2385 async fn test_two_devices_roundtrip_noq_large() -> Result { -2386 let (_guard, m1, m2) = endpoint_pair().await; -2387 let mut data = vec![0u8; 10 * 1024]; -2388 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2389 rng.fill_bytes(&mut data); -2390 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?; -2391 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?; -2392 -2393 Ok(()) -2394 } -2395 -2396 // EADDRINUSE on the GitHub Android emulator persists past -2397 // `force_network_change()`, so the rebind fails and connect() never -2398 // wakes the connection driver. Passes locally. -2399 #[cfg_attr( -2400 target_os = "android", -2401 ignore = "rebind flakes against the GitHub Android emulator" -2402 )] -2403 #[tokio::test] -2404 #[traced_test] -2405 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { -2406 let (_guard, m1, m2) = endpoint_pair().await; -2407 -2408 println!("Net change"); -2409 m1.inner()?.force_network_change(true).await; -2410 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +1801 /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of +1802 /// direct addresses from: +1803 /// +1804 /// - The portmapper. +1805 /// - A net_report report. +1806 /// - The local interfaces IP addresses. +1807 /// - User configured addresses. +1808 #[cfg(not(wasm_browser))] +1809 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +1810 // We only want to have one DirectAddr for each SocketAddr we have. So we store +1811 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +1812 // DirectAddr from each entry. +1813 let mut addrs: BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)> = +1814 BTreeMap::new(); +1815 +1816 // First add PortMapper provided addresses. +1817 let portmap_watcher = self +1818 .direct_addr_update_state +1819 .port_mapper +1820 .watch_external_address(); +1821 let maybe_port_mapped = *portmap_watcher.borrow(); +1822 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +1823 addrs +1824 .entry(portmap_ext) +1825 .or_insert((DirectAddrType::Portmapped, None)); +1826 } +1827 +1828 // Next add STUN addresses from the net_report report. +1829 if let Some(net_report_report) = net_report_report { +1830 if let Some(global_v4) = net_report_report.global_v4 { +1831 addrs +1832 .entry(global_v4.into()) +1833 .or_insert((DirectAddrType::Qad, None)); +1834 +1835 // If they're behind a hard NAT and are using a fixed +1836 // port locally, assume they might've added a static +1837 // port mapping on their router to the same explicit +1838 // port that we are running with. Worst case it's an invalid candidate mapping. +1839 let port = self.sock.ip_bind_addrs().iter().find_map(|addr| { +1840 if addr.port() != 0 { +1841 Some(addr.port()) +1842 } else { +1843 None +1844 } +1845 }); +1846 +1847 if let Some(port) = port +1848 && net_report_report +1849 .mapping_varies_by_dest() +1850 .unwrap_or_default() +1851 { +1852 let mut addr = global_v4; +1853 addr.set_port(port); +1854 addrs +1855 .entry(addr.into()) +1856 .or_insert((DirectAddrType::Qad4LocalPort, None)); +1857 } +1858 } +1859 if let Some(global_v6) = net_report_report.global_v6 { +1860 addrs +1861 .entry(global_v6.into()) +1862 .or_insert((DirectAddrType::Qad, None)); +1863 } +1864 } +1865 +1866 self.collect_local_addresses(&mut addrs); +1867 +1868 // Add configured external addresses. +1869 for addr in self.sock.configured_addrs.read().expect("poisoned").iter() { +1870 addrs.entry(*addr).or_insert((DirectAddrType::Config, None)); +1871 } +1872 +1873 // Finally create and store store all these direct addresses +1874 let stored_addrs = addrs +1875 .into_iter() +1876 .filter_map(|(addr, (typ, flags))| { +1877 // Filter out deprecated IPs +1878 let is_deprecated = flags.map(|f| f.deprecated).unwrap_or(false); +1879 if is_deprecated { +1880 return None; +1881 } +1882 Some(DirectAddr { addr, typ }) +1883 }) +1884 .collect(); +1885 self.sock.store_direct_addresses(stored_addrs); +1886 } +1887 +1888 #[cfg(not(wasm_browser))] +1889 fn collect_local_addresses( +1890 &mut self, +1891 addrs: &mut BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)>, +1892 ) { +1893 let netmon_state = self.local_interfaces_watcher.get(); +1894 +1895 // Matches the addresses that have been bound vs the requested ones. +1896 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +1897 .sock +1898 .ip_bind_addrs() +1899 .iter() +1900 .copied() +1901 .zip(self.sock.ip_local_addrs()) +1902 .collect(); +1903 +1904 // Do we listen on any IPv4 unspecified address? +1905 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +1906 if a.is_ipv4() && a.ip().is_unspecified() { +1907 Some(a.port()) +1908 } else { +1909 None +1910 } +1911 }); +1912 // Do we listen on any IPv6 unspecified address? +1913 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +1914 if a.is_ipv6() && a.ip().is_unspecified() { +1915 Some(a.port()) +1916 } else { +1917 None +1918 } +1919 }); +1920 +1921 // If a socket is bound to the unspecified address, create SocketAddrs for +1922 // each local IP address by pairing it with the port the socket is bound on. +1923 if local_addrs +1924 .iter() +1925 .any(|(_, local)| local.ip().is_unspecified()) +1926 { +1927 let LocalAddresses { +1928 regular: mut ips, +1929 loopback, +1930 } = self.local_interfaces_watcher.get().local_addresses; +1931 if ips.is_empty() && addrs.is_empty() { +1932 // Include loopback addresses only if there are no other interfaces +1933 // or public addresses, this allows testing offline. +1934 ips = loopback; +1935 } +1936 +1937 for ip in ips { +1938 let port_if_unspecified = match ip { +1939 IpAddr::V4(_) => has_ipv4_unspecified, +1940 IpAddr::V6(_) => has_ipv6_unspecified, +1941 }; +1942 if let Some(port) = port_if_unspecified { +1943 let addr = SocketAddr::new(ip, port); +1944 let flags = find_flags(&netmon_state, ip); +1945 addrs.entry(addr).or_insert((DirectAddrType::Local, flags)); +1946 } +1947 } +1948 } +1949 +1950 // If a socket is bound to a specific address, add it. +1951 for (bound, local) in local_addrs { +1952 if !bound.ip().is_unspecified() { +1953 let flags = find_flags(&netmon_state, local.ip()); +1954 addrs.entry(local).or_insert((DirectAddrType::Local, flags)); +1955 } +1956 } +1957 } +1958 +1959 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +1960 if let Some(ref mut r) = report { +1961 self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +1962 if r.preferred_relay.is_none() +1963 && let Some(my_relay) = self.sock.my_relay() +1964 { +1965 r.preferred_relay.replace(my_relay); +1966 } +1967 +1968 // Notify all transports +1969 self.transports_network_change.on_network_change(r); +1970 } +1971 +1972 #[cfg(not(wasm_browser))] +1973 self.update_direct_addresses(report.as_ref()); +1974 } +1975} +1976 +1977#[cfg(not(wasm_browser))] +1978fn find_flags(state: &netmon::State, ip: IpAddr) -> Option<Ipv6AddrFlags> { +1979 if ip.is_ipv6() { +1980 state +1981 .interfaces +1982 .values() +1983 .flat_map(|i| i.addrs()) +1984 .find_map(|addr| match addr { +1985 IpNet::V4(_) => None, +1986 IpNet::V6 { net, flags, .. } => { +1987 if net.addr() == ip { +1988 Some(flags) +1989 } else { +1990 None +1991 } +1992 } +1993 }) +1994 } else { +1995 None +1996 } +1997} +1998 +1999fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +2000 // Pick a random duration between 20 and 26 seconds (just under 30s, +2001 // a common UDP NAT timeout on Linux,etc) +2002 let mut rng = rand::rng(); +2003 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); +2004 if initial_delay { +2005 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +2006 time::interval_at(time::Instant::now() + d, d) +2007 } else { +2008 debug!( +2009 "scheduling periodic_stun to run immediately and in {}s", +2010 d.as_secs() +2011 ); +2012 time::interval(d) +2013 } +2014} +2015 +2016/// The discovered direct addresses of this [`Socket`]. +2017/// +2018/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself. +2019/// They include all locally bound ones as well as those discovered by other mechanisms like +2020/// QAD. +2021#[derive(derive_more::Debug, Clone, Default)] +2022struct DiscoveredDirectAddrs { +2023 /// The last set of discovered direct addresses. +2024 addrs: Watchable<BTreeSet<DirectAddr>>, +2025 +2026 /// The last time the direct addresses were updated, even if there was no change. +2027 /// +2028 /// This is only ever None at startup. +2029 updated_at: Arc<RwLock<Option<Instant>>>, +2030} +2031 +2032impl DiscoveredDirectAddrs { +2033 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +2034 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +2035 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +2036 let updated = self.addrs.set(addrs).is_ok(); +2037 if updated { +2038 event!( +2039 target: "iroh::_events::direct_addrs", +2040 Level::DEBUG, +2041 addrs = ?self.addrs.get(), +2042 ); +2043 } +2044 updated +2045 } +2046 +2047 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { +2048 self.addrs.get().into_iter().map(|da| da.addr) +2049 } +2050} +2051 +2052/// A *direct address* on which an iroh-endpoint might be contactable. +2053/// +2054/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be +2055/// contacted. These can come from various sources depending on the network topology of the +2056/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. +2057/// +2058/// This is essentially a combination of our local addresses combined with any reflexive +2059/// transport addresses we discovered using QAD. +2060#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +2061pub struct DirectAddr { +2062 /// The address. +2063 pub addr: SocketAddr, +2064 /// The origin of this direct address. +2065 pub typ: DirectAddrType, +2066} +2067 +2068/// The type of direct address. +2069/// +2070/// These are the various sources or origins from which an iroh endpoint might have found a +2071/// possible [`DirectAddr`]. +2072#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +2073#[non_exhaustive] +2074pub enum DirectAddrType { +2075 /// Not yet determined.. +2076 Unknown, +2077 /// A locally bound socket address. +2078 Local, +2079 /// Public internet address discovered via QAD. +2080 /// +2081 /// When possible an iroh endpoint will perform QAD to discover which is the address +2082 /// from which it sends data on the public internet. This can be different from locally +2083 /// bound addresses when the endpoint is on a local network which performs NAT or similar. +2084 Qad, +2085 /// An address assigned by the router using port mapping. +2086 /// +2087 /// When possible an iroh endpoint will request a port mapping from the local router to +2088 /// get a publicly routable direct address. +2089 Portmapped, +2090 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +2091 /// +2092 /// It is possible to configure iroh to bound to a specific port and independently +2093 /// configure the router to forward this port to the iroh endpoint. This indicates a +2094 /// situation like this, which still uses QAD to discover the public address. +2095 Qad4LocalPort, +2096 /// An address explicitly provided by the user via configuration. +2097 Config, +2098} +2099 +2100impl Display for DirectAddrType { +2101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +2102 match self { +2103 DirectAddrType::Unknown => write!(f, "?"), +2104 DirectAddrType::Local => write!(f, "local"), +2105 DirectAddrType::Qad => write!(f, "qad"), +2106 DirectAddrType::Portmapped => write!(f, "portmap"), +2107 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +2108 DirectAddrType::Config => write!(f, "config"), +2109 } +2110 } +2111} +2112 +2113#[cfg(all(test, with_crypto_provider))] +2114mod tests { +2115 use std::{net::SocketAddrV4, sync::Arc, time::Duration}; +2116 +2117 use data_encoding::HEXLOWER; +2118 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; +2119 use iroh_relay::tls::{CaTlsConfig, default_provider}; +2120 use n0_error::{Result, StackResultExt, StdResultExt}; +2121 use n0_future::{MergeBounded, StreamExt, time}; +2122 use n0_tracing_test::traced_test; +2123 use n0_watcher::Watcher; +2124 use rand::{CryptoRng, Rng, RngExt, SeedableRng}; +2125 use tokio_util::task::AbortOnDropHandle; +2126 use tracing::{Instrument, error, info, info_span, instrument}; +2127 +2128 use super::Options; +2129 use crate::{ +2130 Endpoint, SecretKey, +2131 address_lookup::memory::MemoryLookup, +2132 dns::DnsResolver, +2133 endpoint::{QuicTransportConfig, presets}, +2134 socket::{ +2135 EndpointInner, StaticConfig, TransportConfig, +2136 biased_rtt_path_selector::BiasedRttPathSelector, +2137 mapped_addrs::{EndpointIdMappedAddr, MappedAddr}, +2138 }, +2139 tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey}, +2140 }; +2141 +2142 const ALPN: &[u8] = b"n0/test/1"; +2143 +2144 fn default_options(rng: &mut impl CryptoRng) -> Options { +2145 let crypto_provider = default_provider(); +2146 let secret_key = SecretKey::from_bytes(&rng.random()); +2147 let tls_config = tls::TlsConfig::new( +2148 secret_key.clone(), +2149 DEFAULT_MAX_TLS_TICKETS, +2150 crypto_provider.clone(), +2151 ); +2152 let static_config = StaticConfig { +2153 server_config: tls_config.make_server_config(false).unwrap(), +2154 client_config: tls_config.make_client_config(false).unwrap(), +2155 tls_config, +2156 token_key: Arc::new(RustlsTokenKey::new(rng, &crypto_provider).unwrap()), +2157 token_store: Arc::new(noq::TokenMemoryCache::default()), +2158 transport_config: QuicTransportConfig::default(), +2159 }; +2160 let server_config = static_config.create_server_config(vec![]); +2161 Options { +2162 transports: vec![ +2163 TransportConfig::default_ipv4(), +2164 TransportConfig::default_ipv6(), +2165 ], +2166 secret_key, +2167 proxy_url: None, +2168 dns_resolver: DnsResolver::new(), +2169 server_config, +2170 tls_config: CaTlsConfig::default() +2171 .client_config(crypto_provider.clone()) +2172 .unwrap(), +2173 #[cfg(any(test, feature = "test-utils"))] +2174 address_lookup_user_data: None, +2175 metrics: Default::default(), +2176 hooks: Default::default(), +2177 path_selector: Arc::new(BiasedRttPathSelector::default()), +2178 portmapper_config: Default::default(), +2179 static_config, +2180 configured_addrs: Default::default(), +2181 } +2182 } +2183 +2184 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +2185 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { +2186 info!("accepting conn"); +2187 let conn = ep.accept().await.expect("no conn"); +2188 +2189 info!("accepting"); +2190 let conn = conn.await.context("accepting")?; +2191 info!("accepting bi"); +2192 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; +2193 +2194 info!("reading"); +2195 let val = recv_bi +2196 .read_to_end(usize::MAX) +2197 .await +2198 .std_context("read to end")?; +2199 +2200 info!("replying"); +2201 for chunk in val.chunks(12) { +2202 send_bi.write_all(chunk).await.std_context("write all")?; +2203 } +2204 +2205 info!("finishing"); +2206 send_bi.finish().std_context("finish")?; +2207 +2208 let stats = conn.stats(); +2209 info!("stats: {:#?}", stats); +2210 if matches!(loss, ExpectedLoss::AlmostNone) { +2211 for info in conn.paths().iter() { +2212 assert!( +2213 info.stats().lost_packets < 10, +2214 "[receiver] path {:?} should not loose many packets", +2215 info.remote_addr() +2216 ); +2217 } +2218 } +2219 +2220 conn.closed().await; +2221 info!("closed"); +2222 ep.inner()?.noq_endpoint().wait_idle().await; +2223 info!("idle"); +2224 +2225 Ok(()) +2226 } +2227 +2228 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +2229 async fn echo_sender( +2230 ep: Endpoint, +2231 dest_id: EndpointId, +2232 msg: &[u8], +2233 loss: ExpectedLoss, +2234 ) -> Result { +2235 info!("connecting to {}", dest_id.fmt_short()); +2236 let dest = EndpointAddr::new(dest_id); +2237 let conn = ep.connect(dest, ALPN).await?; +2238 +2239 info!("opening bi"); +2240 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; +2241 +2242 info!("writing message"); +2243 send_bi.write_all(msg).await.std_context("write all")?; +2244 +2245 info!("finishing"); +2246 send_bi.finish().std_context("finish")?; +2247 +2248 info!("reading_to_end"); +2249 let val = recv_bi +2250 .read_to_end(usize::MAX) +2251 .await +2252 .std_context("read to end")?; +2253 assert_eq!( +2254 val, +2255 msg, +2256 "[sender] expected {}, got {}", +2257 HEXLOWER.encode(msg), +2258 HEXLOWER.encode(&val) +2259 ); +2260 +2261 let stats = conn.stats(); +2262 info!("stats: {:#?}", stats); +2263 if matches!(loss, ExpectedLoss::AlmostNone) { +2264 for info in conn.paths().iter() { +2265 assert!( +2266 info.stats().lost_packets < 10, +2267 "[sender] path {:?} should not loose many packets", +2268 info.remote_addr() +2269 ); +2270 } +2271 } +2272 +2273 conn.close(0u32.into(), b"done"); +2274 info!("closed"); +2275 ep.inner()?.noq_endpoint().wait_idle().await; +2276 info!("idle"); +2277 Ok(()) +2278 } +2279 +2280 #[derive(Debug, Copy, Clone)] +2281 enum ExpectedLoss { +2282 AlmostNone, +2283 YeahSure, +2284 } +2285 +2286 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +2287 async fn run_roundtrip( +2288 sender: Endpoint, +2289 receiver: Endpoint, +2290 payload: &[u8], +2291 loss: ExpectedLoss, +2292 ) -> Result<()> { +2293 tokio::time::timeout(Duration::from_secs(4), async move { +2294 let send_endpoint_id = sender.id(); +2295 let recv_endpoint_id = receiver.id(); +2296 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); +2297 +2298 let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss))); +2299 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; +2300 let sender_is_err = match sender_res { +2301 Ok(()) => false, +2302 Err(err) => { +2303 error!("[sender] Error:\n{err:#?}"); +2304 true +2305 } +2306 }; +2307 let receiver_is_err = match receiver_task.await { +2308 Ok(Ok(())) => false, +2309 Ok(Err(err)) => { +2310 error!("[receiver] Error:\n{err:#?}"); +2311 true +2312 } +2313 Err(joinerr) => { +2314 if joinerr.is_panic() { +2315 std::panic::resume_unwind(joinerr.into_panic()); +2316 } else { +2317 error!("[receiver] Error:\n{joinerr:#?}"); +2318 } +2319 true +2320 } +2321 }; +2322 if sender_is_err || receiver_is_err { +2323 panic!("Sender or receiver errored"); +2324 } +2325 }) +2326 .await +2327 .std_context("timeout")?; +2328 Ok(()) +2329 } +2330 +2331 /// Returns a pair of endpoints with a shared [`MemoryLookup`]. +2332 /// +2333 /// The endpoints do not use a relay server but can connect to each other via local +2334 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if +2335 /// the endpoints rebind. +2336 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { +2337 let address_lookup = MemoryLookup::new(); +2338 let ep1 = Endpoint::builder(presets::Minimal) +2339 .alpns(vec![ALPN.to_vec()]) +2340 .address_lookup(address_lookup.clone()) +2341 .bind() +2342 .await +2343 .unwrap(); +2344 let ep2 = Endpoint::builder(presets::Minimal) +2345 .alpns(vec![ALPN.to_vec()]) +2346 .address_lookup(address_lookup.clone()) +2347 .bind() +2348 .await +2349 .unwrap(); +2350 address_lookup.add_endpoint_info(ep1.addr()); +2351 address_lookup.add_endpoint_info(ep2.addr()); +2352 +2353 let ep1_addr_stream = ep1.watch_addr().stream(); +2354 let ep2_addr_stream = ep2.watch_addr().stream(); +2355 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); +2356 let task = tokio::spawn(async move { +2357 while let Some(addr) = addr_stream.next().await { +2358 address_lookup.add_endpoint_info(addr); +2359 } +2360 }); +2361 +2362 (AbortOnDropHandle::new(task), ep1, ep2) +2363 } +2364 +2365 #[tokio::test(flavor = "multi_thread")] +2366 #[traced_test] +2367 async fn test_two_devices_roundtrip_noq_small() -> Result { +2368 let (_guard, m1, m2) = endpoint_pair().await; +2369 +2370 run_roundtrip( +2371 m1.clone(), +2372 m2.clone(), +2373 b"hello m1", +2374 ExpectedLoss::AlmostNone, +2375 ) +2376 .await?; +2377 run_roundtrip( +2378 m2.clone(), +2379 m1.clone(), +2380 b"hello m2", +2381 ExpectedLoss::AlmostNone, +2382 ) +2383 .await?; +2384 Ok(()) +2385 } +2386 +2387 #[tokio::test(flavor = "multi_thread")] +2388 #[traced_test] +2389 async fn test_two_devices_roundtrip_noq_large() -> Result { +2390 let (_guard, m1, m2) = endpoint_pair().await; +2391 let mut data = vec![0u8; 10 * 1024]; +2392 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2393 rng.fill_bytes(&mut data); +2394 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?; +2395 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?; +2396 +2397 Ok(()) +2398 } +2399 +2400 // EADDRINUSE on the GitHub Android emulator persists past +2401 // `force_network_change()`, so the rebind fails and connect() never +2402 // wakes the connection driver. Passes locally. +2403 #[cfg_attr( +2404 target_os = "android", +2405 ignore = "rebind flakes against the GitHub Android emulator" +2406 )] +2407 #[tokio::test] +2408 #[traced_test] +2409 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { +2410 let (_guard, m1, m2) = endpoint_pair().await; 2411 -2412 let _handle = AbortOnDropHandle::new(tokio::spawn({ -2413 let endpoint = m2.clone(); -2414 async move { -2415 while let Some(incoming) = endpoint.accept().await { -2416 println!("Incoming first conn!"); -2417 let conn = incoming.await.anyerr()?; -2418 conn.closed().await; -2419 } -2420 -2421 n0_error::Ok(()) -2422 } -2423 })); +2412 println!("Net change"); +2413 m1.inner()?.force_network_change(true).await; +2414 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +2415 +2416 let _handle = AbortOnDropHandle::new(tokio::spawn({ +2417 let endpoint = m2.clone(); +2418 async move { +2419 while let Some(incoming) = endpoint.accept().await { +2420 println!("Incoming first conn!"); +2421 let conn = incoming.await.anyerr()?; +2422 conn.closed().await; +2423 } 2424 -2425 println!("first conn!"); -2426 let conn = m1.connect(m2.addr(), ALPN).await?; -2427 println!("Closing first conn"); -2428 conn.close(0u32.into(), b"bye lolz"); -2429 conn.closed().await; -2430 println!("Closed first conn"); -2431 -2432 Ok(()) -2433 } -2434 -2435 fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration { -2436 let delay = rng.random_range(1..=5); -2437 Duration::from_millis(delay * 50) -2438 } -2439 -2440 /// Same structure as `test_two_devices_roundtrip_noq`, but interrupts regularly -2441 /// with (simulated) network changes. -2442 /// Regular network changes to m1 only. -2443 #[tokio::test(flavor = "multi_thread")] -2444 #[traced_test] -2445 async fn test_two_devices_roundtrip_network_change_only_a() -> Result { -2446 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2447 let (_guard, m1, m2) = endpoint_pair().await; -2448 -2449 let _network_change_guard = { -2450 let m1 = m1.clone(); -2451 let mut rng = rng.clone(); -2452 let task = tokio::spawn(async move { -2453 loop { -2454 info!("[m1] network change"); -2455 m1.inner() -2456 .expect("haven't closed the endpoint yet") -2457 .force_network_change(true) -2458 .await; -2459 time::sleep(offset(&mut rng)).await; -2460 } -2461 }); -2462 AbortOnDropHandle::new(task) -2463 }; -2464 -2465 let mut data = vec![0u8; 10 * 1024]; -2466 rng.fill_bytes(&mut data); -2467 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; -2468 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; -2469 -2470 Ok(()) -2471 } -2472 -2473 /// Regular network changes to both m1 and m2. -2474 #[tokio::test(flavor = "multi_thread")] -2475 #[traced_test] -2476 async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result { -2477 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2478 let (_guard, m1, m2) = endpoint_pair().await; -2479 -2480 let _network_change_guard = { -2481 let m1 = m1.clone(); -2482 let m2 = m2.clone(); -2483 let mut rng = rng.clone(); -2484 let task = tokio::spawn(async move { -2485 info!("-- [m1] network change"); -2486 m1.inner() -2487 .expect("haven't closed the endpoint yet") -2488 .force_network_change(true) -2489 .await; -2490 info!("-- [m2] network change"); -2491 m2.inner() -2492 .expect("haven't closed the endpoint yet") -2493 .force_network_change(true) -2494 .await; -2495 time::sleep(offset(&mut rng)).await; -2496 }); -2497 AbortOnDropHandle::new(task) -2498 }; -2499 -2500 let mut data = vec![0u8; 10 * 1024]; -2501 rng.fill_bytes(&mut data); -2502 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; -2503 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; -2504 -2505 Ok(()) -2506 } -2507 -2508 #[tokio::test(flavor = "multi_thread")] -2509 #[traced_test] -2510 async fn test_two_devices_setup_teardown() -> Result { -2511 for i in 0..10 { -2512 info!("-- round {i}"); -2513 info!("setting up stack"); -2514 let (_guard, m1, m2) = endpoint_pair().await; -2515 -2516 info!("closing endpoints"); -2517 let sock1 = m1.inner()?; -2518 let sock2 = m2.inner()?; -2519 m1.close().await; -2520 m2.close().await; -2521 -2522 assert!(sock1.is_closed()); -2523 assert!(sock2.is_closed()); -2524 } -2525 Ok(()) -2526 } -2527 -2528 #[tokio::test] -2529 #[traced_test] -2530 async fn test_direct_addresses() { -2531 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2532 let sock = EndpointInner::bind(default_options(&mut rng)) -2533 .await -2534 .unwrap(); -2535 -2536 // See if we can get endpoints. -2537 let eps0 = sock.ip_addrs().get(); -2538 info!("{eps0:?}"); -2539 assert!(!eps0.is_empty()); -2540 -2541 // Getting the endpoints again immediately should give the same results. -2542 let eps1 = sock.ip_addrs().get(); -2543 info!("{eps1:?}"); -2544 assert_eq!(eps0, eps1); -2545 } -2546 -2547 /// Creates a new [`noq::Endpoint`] hooked up to a [`Socket`]. -2548 /// -2549 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -2550 /// connections using [`ALPN`]. -2551 /// -2552 /// Use [`socket_connect`] to establish connections. -2553 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] -2554 async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> { -2555 let crypto_provider = default_provider(); -2556 let tls_config = tls::TlsConfig::new( -2557 secret_key.clone(), -2558 DEFAULT_MAX_TLS_TICKETS, -2559 crypto_provider.clone(), -2560 ); -2561 let keylog = true; -2562 let static_config = StaticConfig { -2563 server_config: tls_config.make_server_config(keylog).unwrap(), -2564 client_config: tls_config.make_client_config(keylog).unwrap(), -2565 tls_config, -2566 token_key: Arc::new(RustlsTokenKey::new(&mut rand::rng(), &crypto_provider).unwrap()), -2567 transport_config: QuicTransportConfig::default(), -2568 }; -2569 let server_config = static_config.create_server_config(vec![ALPN.to_vec()]); -2570 -2571 let dns_resolver = DnsResolver::new(); -2572 let opts = Options { -2573 transports: vec![ -2574 TransportConfig::default_ipv4(), -2575 TransportConfig::default_ipv6(), -2576 ], -2577 secret_key: secret_key.clone(), -2578 address_lookup_user_data: None, -2579 dns_resolver, -2580 proxy_url: None, -2581 server_config, -2582 tls_config: CaTlsConfig::default() -2583 .client_config(crypto_provider.clone()) -2584 .unwrap(), -2585 metrics: Default::default(), -2586 hooks: Default::default(), -2587 path_selector: Arc::new(BiasedRttPathSelector::default()), -2588 portmapper_config: Default::default(), -2589 static_config, -2590 configured_addrs: Default::default(), -2591 }; -2592 let sock = EndpointInner::bind(opts).await?; -2593 Ok(sock) -2594 } -2595 -2596 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. -2597 /// -2598 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2599 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2600 async fn socket_connect( -2601 ep: noq::Endpoint, -2602 ep_secret_key: SecretKey, -2603 addr: EndpointIdMappedAddr, -2604 endpoint_id: EndpointId, -2605 ) -> Result<noq::Connection> { -2606 // Endpoint::connect sets this, do the same to have similar behaviour. -2607 let mut transport_config = noq::TransportConfig::default(); -2608 transport_config.server_handshake_migration(true); -2609 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -2610 -2611 socket_connect_with_transport_config( -2612 ep, -2613 ep_secret_key, -2614 addr, -2615 endpoint_id, -2616 Arc::new(transport_config), -2617 ) -2618 .await -2619 } -2620 -2621 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. -2622 /// -2623 /// This version allows customising the transport config. -2624 /// -2625 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2626 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2627 async fn socket_connect_with_transport_config( -2628 ep: noq::Endpoint, -2629 ep_secret_key: SecretKey, -2630 mapped_addr: EndpointIdMappedAddr, -2631 endpoint_id: EndpointId, -2632 transport_config: Arc<noq::TransportConfig>, -2633 ) -> Result<noq::Connection> { -2634 let mut quic_client_config = tls::TlsConfig::new( -2635 ep_secret_key.clone(), -2636 DEFAULT_MAX_TLS_TICKETS, -2637 default_provider(), -2638 ) -2639 .make_client_config(true)?; -2640 quic_client_config.set_alpn_protocols(vec![ALPN.to_vec()]); -2641 let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config)); -2642 client_config.transport_config(transport_config); -2643 let connect = ep -2644 .connect_with( -2645 client_config, -2646 mapped_addr.private_socket_addr(), -2647 &tls::name::encode(endpoint_id), -2648 ) -2649 .std_context("connect")?; -2650 let connection = connect.await.anyerr()?; -2651 Ok(connection) -2652 } -2653 -2654 #[tokio::test] -2655 #[traced_test] -2656 async fn test_try_send_no_send_addr() { -2657 // Regression test: if there is no send_addr we should keep being able to use the -2658 // Endpoint. -2659 -2660 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2661 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2662 let endpoint_id_2 = secret_key_2.public(); -2663 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); -2664 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); -2665 -2666 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); -2667 -2668 // Generate an address not present in the RemoteMap. -2669 let bad_addr = EndpointIdMappedAddr::generate(); +2425 n0_error::Ok(()) +2426 } +2427 })); +2428 +2429 println!("first conn!"); +2430 let conn = m1.connect(m2.addr(), ALPN).await?; +2431 println!("Closing first conn"); +2432 conn.close(0u32.into(), b"bye lolz"); +2433 conn.closed().await; +2434 println!("Closed first conn"); +2435 +2436 Ok(()) +2437 } +2438 +2439 fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration { +2440 let delay = rng.random_range(1..=5); +2441 Duration::from_millis(delay * 50) +2442 } +2443 +2444 /// Same structure as `test_two_devices_roundtrip_noq`, but interrupts regularly +2445 /// with (simulated) network changes. +2446 /// Regular network changes to m1 only. +2447 #[tokio::test(flavor = "multi_thread")] +2448 #[traced_test] +2449 async fn test_two_devices_roundtrip_network_change_only_a() -> Result { +2450 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2451 let (_guard, m1, m2) = endpoint_pair().await; +2452 +2453 let _network_change_guard = { +2454 let m1 = m1.clone(); +2455 let mut rng = rng.clone(); +2456 let task = tokio::spawn(async move { +2457 loop { +2458 info!("[m1] network change"); +2459 m1.inner() +2460 .expect("haven't closed the endpoint yet") +2461 .force_network_change(true) +2462 .await; +2463 time::sleep(offset(&mut rng)).await; +2464 } +2465 }); +2466 AbortOnDropHandle::new(task) +2467 }; +2468 +2469 let mut data = vec![0u8; 10 * 1024]; +2470 rng.fill_bytes(&mut data); +2471 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; +2472 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; +2473 +2474 Ok(()) +2475 } +2476 +2477 /// Regular network changes to both m1 and m2. +2478 #[tokio::test(flavor = "multi_thread")] +2479 #[traced_test] +2480 async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result { +2481 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2482 let (_guard, m1, m2) = endpoint_pair().await; +2483 +2484 let _network_change_guard = { +2485 let m1 = m1.clone(); +2486 let m2 = m2.clone(); +2487 let mut rng = rng.clone(); +2488 let task = tokio::spawn(async move { +2489 info!("-- [m1] network change"); +2490 m1.inner() +2491 .expect("haven't closed the endpoint yet") +2492 .force_network_change(true) +2493 .await; +2494 info!("-- [m2] network change"); +2495 m2.inner() +2496 .expect("haven't closed the endpoint yet") +2497 .force_network_change(true) +2498 .await; +2499 time::sleep(offset(&mut rng)).await; +2500 }); +2501 AbortOnDropHandle::new(task) +2502 }; +2503 +2504 let mut data = vec![0u8; 10 * 1024]; +2505 rng.fill_bytes(&mut data); +2506 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?; +2507 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?; +2508 +2509 Ok(()) +2510 } +2511 +2512 #[tokio::test(flavor = "multi_thread")] +2513 #[traced_test] +2514 async fn test_two_devices_setup_teardown() -> Result { +2515 for i in 0..10 { +2516 info!("-- round {i}"); +2517 info!("setting up stack"); +2518 let (_guard, m1, m2) = endpoint_pair().await; +2519 +2520 info!("closing endpoints"); +2521 let sock1 = m1.inner()?; +2522 let sock2 = m2.inner()?; +2523 m1.close().await; +2524 m2.close().await; +2525 +2526 assert!(sock1.is_closed()); +2527 assert!(sock2.is_closed()); +2528 } +2529 Ok(()) +2530 } +2531 +2532 #[tokio::test] +2533 #[traced_test] +2534 async fn test_direct_addresses() { +2535 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2536 let sock = EndpointInner::bind(default_options(&mut rng)) +2537 .await +2538 .unwrap(); +2539 +2540 // See if we can get endpoints. +2541 let eps0 = sock.ip_addrs().get(); +2542 info!("{eps0:?}"); +2543 assert!(!eps0.is_empty()); +2544 +2545 // Getting the endpoints again immediately should give the same results. +2546 let eps1 = sock.ip_addrs().get(); +2547 info!("{eps1:?}"); +2548 assert_eq!(eps0, eps1); +2549 } +2550 +2551 /// Creates a new [`noq::Endpoint`] hooked up to a [`Socket`]. +2552 /// +2553 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +2554 /// connections using [`ALPN`]. +2555 /// +2556 /// Use [`socket_connect`] to establish connections. +2557 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] +2558 async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> { +2559 let crypto_provider = default_provider(); +2560 let tls_config = tls::TlsConfig::new( +2561 secret_key.clone(), +2562 DEFAULT_MAX_TLS_TICKETS, +2563 crypto_provider.clone(), +2564 ); +2565 let keylog = true; +2566 let static_config = StaticConfig { +2567 server_config: tls_config.make_server_config(keylog).unwrap(), +2568 client_config: tls_config.make_client_config(keylog).unwrap(), +2569 tls_config, +2570 token_key: Arc::new(RustlsTokenKey::new(&mut rand::rng(), &crypto_provider).unwrap()), +2571 token_store: Arc::new(noq::TokenMemoryCache::default()), +2572 transport_config: QuicTransportConfig::default(), +2573 }; +2574 let server_config = static_config.create_server_config(vec![ALPN.to_vec()]); +2575 +2576 let dns_resolver = DnsResolver::new(); +2577 let opts = Options { +2578 transports: vec![ +2579 TransportConfig::default_ipv4(), +2580 TransportConfig::default_ipv6(), +2581 ], +2582 secret_key: secret_key.clone(), +2583 address_lookup_user_data: None, +2584 dns_resolver, +2585 proxy_url: None, +2586 server_config, +2587 tls_config: CaTlsConfig::default() +2588 .client_config(crypto_provider.clone()) +2589 .unwrap(), +2590 metrics: Default::default(), +2591 hooks: Default::default(), +2592 path_selector: Arc::new(BiasedRttPathSelector::default()), +2593 portmapper_config: Default::default(), +2594 static_config, +2595 configured_addrs: Default::default(), +2596 }; +2597 let sock = EndpointInner::bind(opts).await?; +2598 Ok(sock) +2599 } +2600 +2601 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. +2602 /// +2603 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2604 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2605 async fn socket_connect( +2606 ep: noq::Endpoint, +2607 ep_secret_key: SecretKey, +2608 addr: EndpointIdMappedAddr, +2609 endpoint_id: EndpointId, +2610 ) -> Result<noq::Connection> { +2611 // Endpoint::connect sets this, do the same to have similar behaviour. +2612 let mut transport_config = noq::TransportConfig::default(); +2613 transport_config.server_handshake_migration(true); +2614 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2615 +2616 socket_connect_with_transport_config( +2617 ep, +2618 ep_secret_key, +2619 addr, +2620 endpoint_id, +2621 Arc::new(transport_config), +2622 ) +2623 .await +2624 } +2625 +2626 /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`. +2627 /// +2628 /// This version allows customising the transport config. +2629 /// +2630 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2631 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2632 async fn socket_connect_with_transport_config( +2633 ep: noq::Endpoint, +2634 ep_secret_key: SecretKey, +2635 mapped_addr: EndpointIdMappedAddr, +2636 endpoint_id: EndpointId, +2637 transport_config: Arc<noq::TransportConfig>, +2638 ) -> Result<noq::Connection> { +2639 let mut quic_client_config = tls::TlsConfig::new( +2640 ep_secret_key.clone(), +2641 DEFAULT_MAX_TLS_TICKETS, +2642 default_provider(), +2643 ) +2644 .make_client_config(true)?; +2645 quic_client_config.set_alpn_protocols(vec![ALPN.to_vec()]); +2646 let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config)); +2647 client_config.transport_config(transport_config); +2648 let connect = ep +2649 .connect_with( +2650 client_config, +2651 mapped_addr.private_socket_addr(), +2652 &tls::name::encode(endpoint_id), +2653 ) +2654 .std_context("connect")?; +2655 let connection = connect.await.anyerr()?; +2656 Ok(connection) +2657 } +2658 +2659 #[tokio::test] +2660 #[traced_test] +2661 async fn test_try_send_no_send_addr() { +2662 // Regression test: if there is no send_addr we should keep being able to use the +2663 // Endpoint. +2664 +2665 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2666 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2667 let endpoint_id_2 = secret_key_2.public(); +2668 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); +2669 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); 2670 -2671 // 500ms is rather fast here. Running this locally it should always be the correct -2672 // timeout. If this is too slow however the test will not become flaky as we are -2673 // expecting the timeout, we might just get the timeout for the wrong reason. But -2674 // this speeds up the test. -2675 let res = tokio::time::timeout( -2676 Duration::from_millis(500), -2677 socket_connect( -2678 sock_1.noq_endpoint().clone(), -2679 secret_key_1.clone(), -2680 bad_addr, -2681 endpoint_id_missing_endpoint, -2682 ), -2683 ) -2684 .await; -2685 assert!(res.is_err(), "expecting timeout"); -2686 -2687 // Now check we can still create another connection with this endpoint. -2688 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); -2689 -2690 // This needs an accept task -2691 let accept_task = tokio::spawn({ -2692 async fn accept(ep: noq::Endpoint) -> Result<()> { -2693 let incoming = ep.accept().await.std_context("no incoming")?; -2694 let _conn = incoming -2695 .accept() -2696 .std_context("accept")? -2697 .await -2698 .std_context("accepting")?; -2699 -2700 // Keep this connection alive for a while -2701 tokio::time::sleep(Duration::from_secs(10)).await; -2702 info!("accept finished"); -2703 Ok(()) -2704 } -2705 let ep = sock_2.noq_endpoint().clone(); -2706 async move { -2707 if let Err(err) = accept(ep).await { -2708 error!("{err:#}"); -2709 } -2710 } -2711 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) -2712 }); -2713 let _accept_task = AbortOnDropHandle::new(accept_task); -2714 -2715 let addrs = sock_2 -2716 .ip_addrs() -2717 .get() -2718 .into_iter() -2719 .map(|x| TransportAddr::Ip(x.addr)); -2720 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); -2721 let addr = sock_1 -2722 .resolve_remote(endpoint_addr_2) -2723 .await -2724 .unwrap() -2725 .unwrap(); -2726 let res = tokio::time::timeout( -2727 Duration::from_secs(10), -2728 socket_connect( -2729 sock_1.noq_endpoint().clone(), -2730 secret_key_1.clone(), -2731 addr, -2732 endpoint_id_2, -2733 ), -2734 ) -2735 .await -2736 .expect("timeout while connecting"); -2737 -2738 // aka assert!(res.is_ok()) but with nicer error reporting. -2739 res.unwrap(); -2740 -2741 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -2742 // much internal state for now. -2743 } -2744 -2745 #[tokio::test] -2746 #[traced_test] -2747 async fn test_try_send_no_udp_addr_or_relay_url() { -2748 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -2749 // behaviour of Socket::try_send. -2750 -2751 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2752 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2753 let endpoint_id_2 = secret_key_2.public(); -2754 -2755 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); -2756 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); -2757 let ep_2 = sock_2.noq_endpoint().clone(); -2758 -2759 // We need a task to accept the connection. -2760 let accept_task = tokio::spawn({ -2761 async fn accept(ep: noq::Endpoint) -> Result<()> { -2762 let incoming = ep.accept().await.std_context("no incoming")?; -2763 let conn = incoming -2764 .accept() -2765 .std_context("accept")? -2766 .await -2767 .std_context("connecting")?; -2768 let mut stream = conn.accept_uni().await.std_context("accept uni")?; -2769 stream -2770 .read_to_end(1 << 16) -2771 .await -2772 .std_context("read to end")?; -2773 info!("accept finished"); -2774 Ok(()) -2775 } -2776 async move { -2777 if let Err(err) = accept(ep_2).await { -2778 error!("{err:#}"); -2779 } +2671 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); +2672 +2673 // Generate an address not present in the RemoteMap. +2674 let bad_addr = EndpointIdMappedAddr::generate(); +2675 +2676 // 500ms is rather fast here. Running this locally it should always be the correct +2677 // timeout. If this is too slow however the test will not become flaky as we are +2678 // expecting the timeout, we might just get the timeout for the wrong reason. But +2679 // this speeds up the test. +2680 let res = tokio::time::timeout( +2681 Duration::from_millis(500), +2682 socket_connect( +2683 sock_1.noq_endpoint().clone(), +2684 secret_key_1.clone(), +2685 bad_addr, +2686 endpoint_id_missing_endpoint, +2687 ), +2688 ) +2689 .await; +2690 assert!(res.is_err(), "expecting timeout"); +2691 +2692 // Now check we can still create another connection with this endpoint. +2693 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); +2694 +2695 // This needs an accept task +2696 let accept_task = tokio::spawn({ +2697 async fn accept(ep: noq::Endpoint) -> Result<()> { +2698 let incoming = ep.accept().await.std_context("no incoming")?; +2699 let _conn = incoming +2700 .accept() +2701 .std_context("accept")? +2702 .await +2703 .std_context("accepting")?; +2704 +2705 // Keep this connection alive for a while +2706 tokio::time::sleep(Duration::from_secs(10)).await; +2707 info!("accept finished"); +2708 Ok(()) +2709 } +2710 let ep = sock_2.noq_endpoint().clone(); +2711 async move { +2712 if let Err(err) = accept(ep).await { +2713 error!("{err:#}"); +2714 } +2715 } +2716 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) +2717 }); +2718 let _accept_task = AbortOnDropHandle::new(accept_task); +2719 +2720 let addrs = sock_2 +2721 .ip_addrs() +2722 .get() +2723 .into_iter() +2724 .map(|x| TransportAddr::Ip(x.addr)); +2725 let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs); +2726 let addr = sock_1 +2727 .resolve_remote(endpoint_addr_2) +2728 .await +2729 .unwrap() +2730 .unwrap(); +2731 let res = tokio::time::timeout( +2732 Duration::from_secs(10), +2733 socket_connect( +2734 sock_1.noq_endpoint().clone(), +2735 secret_key_1.clone(), +2736 addr, +2737 endpoint_id_2, +2738 ), +2739 ) +2740 .await +2741 .expect("timeout while connecting"); +2742 +2743 // aka assert!(res.is_ok()) but with nicer error reporting. +2744 res.unwrap(); +2745 +2746 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +2747 // much internal state for now. +2748 } +2749 +2750 #[tokio::test] +2751 #[traced_test] +2752 async fn test_try_send_no_udp_addr_or_relay_url() { +2753 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +2754 // behaviour of Socket::try_send. +2755 +2756 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2757 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2758 let endpoint_id_2 = secret_key_2.public(); +2759 +2760 let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap(); +2761 let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap(); +2762 let ep_2 = sock_2.noq_endpoint().clone(); +2763 +2764 // We need a task to accept the connection. +2765 let accept_task = tokio::spawn({ +2766 async fn accept(ep: noq::Endpoint) -> Result<()> { +2767 let incoming = ep.accept().await.std_context("no incoming")?; +2768 let conn = incoming +2769 .accept() +2770 .std_context("accept")? +2771 .await +2772 .std_context("connecting")?; +2773 let mut stream = conn.accept_uni().await.std_context("accept uni")?; +2774 stream +2775 .read_to_end(1 << 16) +2776 .await +2777 .std_context("read to end")?; +2778 info!("accept finished"); +2779 Ok(()) 2780 } -2781 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) -2782 }); -2783 let _accept_task = AbortOnDropHandle::new(accept_task); -2784 -2785 // Add an entry in the RemoteMap of ep_1 with an invalid socket address -2786 let empty_addr_2 = EndpointAddr::from_parts( -2787 endpoint_id_2, -2788 [TransportAddr::Ip( -2789 // Reserved IP range for documentation (unreachable) -2790 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), -2791 )], -2792 ); -2793 let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); -2794 -2795 // Set a low max_idle_timeout so noq gives up on this quickly and our test does -2796 // not take forever. You need to check the log output to verify this is really -2797 // triggering the correct error. -2798 // In test_try_send_no_send_addr() above you may have noticed we used -2799 // tokio::time::timeout() on the connection attempt instead. Here however we want -2800 // Noq itself to have fully given up on the connection attempt because we will -2801 // later connect to **the same** endpoint. If Noq did not give up on the connection -2802 // we'd close it on drop, and the retransmits of the close packets would interfere -2803 // with the next handshake, closing it during the handshake. This makes the test a -2804 // little slower though. -2805 let mut transport_config = noq::TransportConfig::default(); -2806 transport_config.server_handshake_migration(true); -2807 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -2808 let res = socket_connect_with_transport_config( -2809 sock_1.noq_endpoint().clone(), -2810 secret_key_1.clone(), -2811 addr_2, -2812 endpoint_id_2, -2813 Arc::new(transport_config), -2814 ) -2815 .await; -2816 assert!(res.is_err(), "expected timeout"); -2817 info!("first connect timed out as expected"); -2818 -2819 // Provide correct addressing information -2820 let correct_addr_2 = EndpointAddr::from_parts( -2821 endpoint_id_2, -2822 sock_2 -2823 .ip_addrs() -2824 .get() -2825 .into_iter() -2826 .map(|x| TransportAddr::Ip(x.addr)), -2827 ); -2828 let addr_2a = sock_1 -2829 .resolve_remote(correct_addr_2) -2830 .await -2831 .unwrap() -2832 .unwrap(); -2833 assert_eq!(addr_2, addr_2a); -2834 -2835 // We can now connect -2836 tokio::time::timeout(Duration::from_secs(10), async move { -2837 info!("establishing new connection"); -2838 let conn = socket_connect( -2839 sock_1.noq_endpoint().clone(), -2840 secret_key_1.clone(), -2841 addr_2, -2842 endpoint_id_2, -2843 ) -2844 .await -2845 .unwrap(); -2846 info!("have connection"); -2847 let mut stream = conn.open_uni().await.unwrap(); -2848 stream.write_all(b"hello").await.unwrap(); -2849 stream.finish().unwrap(); -2850 stream.stopped().await.unwrap(); -2851 info!("finished stream"); -2852 }) -2853 .await -2854 .expect("connection timed out"); -2855 -2856 // TODO: could remove the addresses again, send, add it back and see it recover. -2857 // But we don't have that much private access to the RemoteMap. This will do for now. -2858 } -2859}

\ No newline at end of file +2781 async move { +2782 if let Err(err) = accept(ep_2).await { +2783 error!("{err:#}"); +2784 } +2785 } +2786 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) +2787 }); +2788 let _accept_task = AbortOnDropHandle::new(accept_task); +2789 +2790 // Add an entry in the RemoteMap of ep_1 with an invalid socket address +2791 let empty_addr_2 = EndpointAddr::from_parts( +2792 endpoint_id_2, +2793 [TransportAddr::Ip( +2794 // Reserved IP range for documentation (unreachable) +2795 SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(), +2796 )], +2797 ); +2798 let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap(); +2799 +2800 // Set a low max_idle_timeout so noq gives up on this quickly and our test does +2801 // not take forever. You need to check the log output to verify this is really +2802 // triggering the correct error. +2803 // In test_try_send_no_send_addr() above you may have noticed we used +2804 // tokio::time::timeout() on the connection attempt instead. Here however we want +2805 // Noq itself to have fully given up on the connection attempt because we will +2806 // later connect to **the same** endpoint. If Noq did not give up on the connection +2807 // we'd close it on drop, and the retransmits of the close packets would interfere +2808 // with the next handshake, closing it during the handshake. This makes the test a +2809 // little slower though. +2810 let mut transport_config = noq::TransportConfig::default(); +2811 transport_config.server_handshake_migration(true); +2812 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +2813 let res = socket_connect_with_transport_config( +2814 sock_1.noq_endpoint().clone(), +2815 secret_key_1.clone(), +2816 addr_2, +2817 endpoint_id_2, +2818 Arc::new(transport_config), +2819 ) +2820 .await; +2821 assert!(res.is_err(), "expected timeout"); +2822 info!("first connect timed out as expected"); +2823 +2824 // Provide correct addressing information +2825 let correct_addr_2 = EndpointAddr::from_parts( +2826 endpoint_id_2, +2827 sock_2 +2828 .ip_addrs() +2829 .get() +2830 .into_iter() +2831 .map(|x| TransportAddr::Ip(x.addr)), +2832 ); +2833 let addr_2a = sock_1 +2834 .resolve_remote(correct_addr_2) +2835 .await +2836 .unwrap() +2837 .unwrap(); +2838 assert_eq!(addr_2, addr_2a); +2839 +2840 // We can now connect +2841 tokio::time::timeout(Duration::from_secs(10), async move { +2842 info!("establishing new connection"); +2843 let conn = socket_connect( +2844 sock_1.noq_endpoint().clone(), +2845 secret_key_1.clone(), +2846 addr_2, +2847 endpoint_id_2, +2848 ) +2849 .await +2850 .unwrap(); +2851 info!("have connection"); +2852 let mut stream = conn.open_uni().await.unwrap(); +2853 stream.write_all(b"hello").await.unwrap(); +2854 stream.finish().unwrap(); +2855 stream.stopped().await.unwrap(); +2856 info!("finished stream"); +2857 }) +2858 .await +2859 .expect("connection timed out"); +2860 +2861 // TODO: could remove the addresses again, send, add it back and see it recover. +2862 // But we don't have that much private access to the RemoteMap. This will do for now. +2863 } +2864}

\ No newline at end of file