From 95b8f71296c57c2fd4b8a402e99f06cb2da0d3ce Mon Sep 17 00:00:00 2001 From: Frando Date: Fri, 17 Jul 2026 12:21:31 +0000 Subject: [PATCH] deploy: c31b515d577f9c8e46d9cdc0c51949da89a29386 --- .../enum.AddressLookupFailed.html | 2 +- .../constant.ENV_FORCE_STAGING_RELAYS.html | 2 +- .../docs/iroh/endpoint/enum.ConnectError.html | 4 +- .../endpoint/enum.ConnectWithOptsError.html | 4 +- .../iroh/endpoint/enum.ConnectingError.html | 2 +- .../iroh/endpoint/enum.ConnectionError.html | 2 +- .../iroh/endpoint/enum.EndpointError.html | 4 +- .../iroh/endpoint/enum.QuicConnectError.html | 2 +- .../docs/iroh/endpoint/enum.RelayMode.html | 10 +- .../iroh/endpoint/fn.default_relay_mode.html | 2 +- .../iroh/endpoint/fn.force_staging_infra.html | 2 +- pr/4419/docs/iroh/endpoint/index.html | 2 +- .../docs/iroh/endpoint/struct.Builder.html | 58 +- .../iroh/endpoint/struct.ConnectOptions.html | 10 +- .../docs/iroh/endpoint/struct.Endpoint.html | 62 +- .../iroh/endpoint/struct.EndpointClosed.html | 8 +- .../iroh/endpoint/struct.RelayStatus.html | 12 +- pr/4419/docs/src/iroh/endpoint.rs.html | 7715 +++++++++-------- pr/4419/docs/src/iroh_dns_server/http.rs.html | 2 +- pr/4419/docs/src/iroh_relay/server.rs.html | 2 +- 20 files changed, 3954 insertions(+), 3953 deletions(-) diff --git a/pr/4419/docs/iroh/address_lookup/enum.AddressLookupFailed.html b/pr/4419/docs/iroh/address_lookup/enum.AddressLookupFailed.html index 6cc3564192..edf93b2faa 100644 --- a/pr/4419/docs/iroh/address_lookup/enum.AddressLookupFailed.html +++ b/pr/4419/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§

§

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 +

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/4419/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/4419/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html index 4a0a3d2ec2..3adef61640 100644 --- a/pr/4419/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.ConnectError.html b/pr/4419/docs/iroh/endpoint/enum.ConnectError.html index d6bc365dd4..5e4d551a4f 100644 --- a/pr/4419/docs/iroh/endpoint/enum.ConnectError.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/4419/docs/iroh/endpoint/enum.ConnectWithOptsError.html index 7c36f2edb9..1a54dee6b1 100644 --- a/pr/4419/docs/iroh/endpoint/enum.ConnectWithOptsError.html +++ b/pr/4419/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§

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/4419/docs/iroh/endpoint/enum.ConnectingError.html b/pr/4419/docs/iroh/endpoint/enum.ConnectingError.html index 7b532cb93f..f74b02a76d 100644 --- a/pr/4419/docs/iroh/endpoint/enum.ConnectingError.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.ConnectionError.html b/pr/4419/docs/iroh/endpoint/enum.ConnectionError.html index 7e2c82dd6e..2e5c568a89 100644 --- a/pr/4419/docs/iroh/endpoint/enum.ConnectionError.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.EndpointError.html b/pr/4419/docs/iroh/endpoint/enum.EndpointError.html index a95a890802..62bd01d393 100644 --- a/pr/4419/docs/iroh/endpoint/enum.EndpointError.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.QuicConnectError.html b/pr/4419/docs/iroh/endpoint/enum.QuicConnectError.html index c8520ee404..1d389d17fd 100644 --- a/pr/4419/docs/iroh/endpoint/enum.QuicConnectError.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/enum.RelayMode.html b/pr/4419/docs/iroh/endpoint/enum.RelayMode.html index 9d89a5ee0e..7726cf500a 100644 --- a/pr/4419/docs/iroh/endpoint/enum.RelayMode.html +++ b/pr/4419/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.link.".parse()?,
     "https://euw-1.relay.n0.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/4419/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/4419/docs/iroh/endpoint/fn.default_relay_mode.html index d05c6047a4..59a4d475b7 100644 --- a/pr/4419/docs/iroh/endpoint/fn.default_relay_mode.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/4419/docs/iroh/endpoint/fn.force_staging_infra.html index 0b5216893f..172cf42bc8 100644 --- a/pr/4419/docs/iroh/endpoint/fn.force_staging_infra.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/index.html b/pr/4419/docs/iroh/endpoint/index.html index 1f95501979..afd5909c2c 100644 --- a/pr/4419/docs/iroh/endpoint/index.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/struct.Builder.html b/pr/4419/docs/iroh/endpoint/struct.Builder.html index 591c2e7e29..766cb1bfc1 100644 --- a/pr/4419/docs/iroh/endpoint/struct.Builder.html +++ b/pr/4419/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 are 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,28 +208,28 @@ 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. Pass PortmapperConfig::Disabled to avoid gateway probing (e.g. if it triggers firewall prompts).

-
Source

pub fn net_report_config(self, config: NetReportConfig) -> Self

Configures the net report.

+
Source

pub fn net_report_config(self, config: NetReportConfig) -> Self

Configures the net report.

The net report component is responsible for figuring out if and how the endpoint is connected to the internet. It does this by doing various probes to the configured relay servers to get public addresses, NAT behaviour, and relay latencies. In addition it tries to detect captive portals.

Some non-essential features of the net report component can be disabled via this configuration.

-
Source

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

Available on crate feature unstable-custom-transports only.

Adds a custom transport to the 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 to the endpoint.

This API is unstable and gated behind the unstable-custom-transport feature. It is not covered by semantic versioning guarantees and may change in any release without a major version bump.

-
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 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/4419/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/4419/docs/iroh/endpoint/struct.ConnectOptions.html index 21bd281b50..9a89742106 100644 --- a/pr/4419/docs/iroh/endpoint/struct.ConnectOptions.html +++ b/pr/4419/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/4419/docs/iroh/endpoint/struct.Endpoint.html b/pr/4419/docs/iroh/endpoint/struct.Endpoint.html index f8b3ea0a34..095d199481 100644 --- a/pr/4419/docs/iroh/endpoint/struct.Endpoint.html +++ b/pr/4419/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 @@ -27,28 +27,28 @@ the error, and will then use Google’s fallback DNS servers. Note that if your compilation profile sets panic = "abort", this can’t work, and thus your app will panic if using a default DnsResolver without first initializing the JNI context.

-

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], @@ -68,7 +68,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], @@ -88,17 +88,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. @@ -108,7 +108,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};
@@ -151,7 +151,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.

@@ -180,7 +180,7 @@ connection is independent of the endpoint’s online status.

// 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( +endpoint.online().await;

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, @@ -192,7 +192,7 @@ 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 net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<>

Available on crate feature unstable-net-report only.

Returns a Watcher for any net report runs from this Endpoint.

+
Source

pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<>

Available on crate feature unstable-net-report only.

Returns a Watcher for any net report runs from this Endpoint.

This API is unstable and gated behind the unstable-net-report feature. It is not covered by semantic versioning guarantees and may change in any release @@ -219,25 +219,25 @@ task once the endpoint stops combine with

use iroh::{Endpoint, Watcher as _, endpoint::presets};
 
 let ep = Endpoint::bind(presets::N0).await.unwrap();
-let _report = ep.net_report().initialized().await;
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.

+let _report = ep.net_report().initialized().await;
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:

@@ -303,13 +303,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 @@ -318,14 +318,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.

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

\ No newline at end of file +1735 /// # } +1736 /// ``` +1737 pub fn closed(&self) -> EndpointClosed { +1738 EndpointClosed { +1739 inner: self.inner.closed(), +1740 } +1741 } +1742 +1743 /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. +1744 /// +1745 /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration +1746 /// for a connection accepted using the [`Incoming::accept_with`] method. +1747 pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder { +1748 let inner = self.inner.static_config.create_server_config(alpns); +1749 ServerConfigBuilder::new(inner, self.inner.static_config.transport_config.clone()) +1750 } +1751 +1752 // # Remaining private methods +1753 +1754 /// Translates a raw [`SocketAddr`] (which may be a synthetic mapped address) into +1755 /// a transport address. +1756 pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> crate::socket::transports::Addr { +1757 self.inner.to_transport_addr(addr) +1758 } +1759 +1760 #[cfg(all(test, with_crypto_provider))] +1761 pub(crate) fn inner(&self) -> Result<Arc<EndpointInner>, EndpointError> { +1762 if self.is_closed() { +1763 return Err(e!(EndpointError::Closed)); +1764 } +1765 Ok(self.inner.clone()) +1766 } +1767} +1768 +1769/// Options for the [`Endpoint::connect_with_opts`] function. +1770#[derive(Default, Debug, Clone)] +1771pub struct ConnectOptions { +1772 transport_config: Option<QuicTransportConfig>, +1773 additional_alpns: Vec<Vec<u8>>, +1774} +1775 +1776impl ConnectOptions { +1777 /// Initializes new connection options. +1778 /// +1779 /// By default, the connection will use the same options +1780 /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`]. +1781 pub fn new() -> Self { +1782 Self::default() +1783 } +1784 +1785 /// Sets the QUIC transport config options for this connection. +1786 pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self { +1787 self.transport_config = Some(transport_config); +1788 self +1789 } +1790 +1791 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in +1792 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. +1793 /// +1794 /// This allows connecting to servers that may only support older versions of your +1795 /// protocol. In this case, you would add the older [ALPN] identifiers with this +1796 /// function. +1797 /// +1798 /// You'll know the final negotiated [ALPN] identifier once your connection was +1799 /// established using [`Connection::alpn`], or even slightly earlier in the +1800 /// handshake by using [`Connecting::alpn`]. +1801 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this +1802 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. +1803 /// +1804 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the +1805 /// accept side that determines the protocol. +1806 /// +1807 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint +1808 /// builder's [`Builder::alpns`] function. +1809 /// +1810 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +1811 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { +1812 self.additional_alpns = alpns; +1813 self +1814 } +1815} +1816 +1817/// Future returned from [`Endpoint::closed`]. +1818#[derive(derive_more::Debug)] +1819#[pin_project] +1820#[debug("EndpointClosed")] +1821pub struct EndpointClosed { +1822 #[pin] +1823 inner: WaitForCancellationFutureOwned, +1824} +1825 +1826impl Future for EndpointClosed { +1827 type Output = (); +1828 +1829 fn poll( +1830 self: Pin<&mut Self>, +1831 cx: &mut std::task::Context<'_>, +1832 ) -> std::task::Poll<Self::Output> { +1833 let this = self.project(); +1834 this.inner.poll(cx) +1835 } +1836} +1837 +1838impl EndpointClosed { +1839 /// Runs a future to completion, or until the [`Endpoint`] is closed. +1840 /// +1841 /// Returns the output of `fut` if it completes before the endpoint closes, +1842 /// or `None` otherwise. +1843 pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output> { +1844 n0_future::future::or(async { Some(fut.await) }, async { +1845 self.await; +1846 None +1847 }) +1848 .await +1849 } +1850} +1851 +1852/// Read a proxy url from the environment, in this order +1853/// +1854/// - `HTTP_PROXY` +1855/// - `http_proxy` +1856/// - `HTTPS_PROXY` +1857/// - `https_proxy` +1858fn proxy_url_from_env() -> Option<Url> { +1859 if let Some(url) = std::env::var("HTTP_PROXY") +1860 .ok() +1861 .and_then(|s| s.parse::<Url>().ok()) +1862 { +1863 if is_cgi() { +1864 warn!("HTTP_PROXY environment variable ignored in CGI"); +1865 } else { +1866 return Some(url); +1867 } +1868 } +1869 if let Some(url) = std::env::var("http_proxy") +1870 .ok() +1871 .and_then(|s| s.parse::<Url>().ok()) +1872 { +1873 return Some(url); +1874 } +1875 if let Some(url) = std::env::var("HTTPS_PROXY") +1876 .ok() +1877 .and_then(|s| s.parse::<Url>().ok()) +1878 { +1879 return Some(url); +1880 } +1881 if let Some(url) = std::env::var("https_proxy") +1882 .ok() +1883 .and_then(|s| s.parse::<Url>().ok()) +1884 { +1885 return Some(url); +1886 } +1887 +1888 None +1889} +1890 +1891/// Connection status of a single home relay. +1892/// +1893/// Observed via [`Endpoint::home_relay_status`]. +1894#[derive(Debug, Clone, PartialEq, Eq)] +1895pub struct RelayStatus { +1896 url: RelayUrl, +1897 state: RelayConnectionState, +1898} +1899 +1900impl RelayStatus { +1901 pub(crate) fn new(url: RelayUrl, state: RelayConnectionState) -> Self { +1902 Self { url, state } +1903 } +1904 +1905 /// Returns the URL of the home relay. +1906 pub fn url(&self) -> &RelayUrl { +1907 &self.url +1908 } +1909 +1910 /// Returns `true` if the endpoint is connected to the relay. +1911 pub fn is_connected(&self) -> bool { +1912 self.state.is_connected() +1913 } +1914 +1915 /// Returns the most recent connection error, if the relay is currently +1916 /// disconnected. +1917 /// +1918 /// Returns `None` when the relay is connected, or when the endpoint has +1919 /// not yet observed a failed connection attempt. +1920 pub fn last_error(&self) -> Option<&AnyError> { +1921 self.state.last_error().map(Arc::as_ref) +1922 } +1923} +1924 +1925/// Configuration of the relay servers for an [`Endpoint`]. +1926#[derive(Debug, Clone, PartialEq, Eq)] +1927pub enum RelayMode { +1928 /// Disable relay servers completely. +1929 /// This means that neither listening nor dialing relays will be available. +1930 Disabled, +1931 /// Use the default relay map, with production relay servers from n0. +1932 /// +1933 /// See [`crate::defaults::prod`] for the severs used. +1934 Default, +1935 /// Use the staging relay servers from n0. +1936 Staging, +1937 /// Use a custom relay map. +1938 Custom(RelayMap), +1939} +1940 +1941impl RelayMode { +1942 /// Returns the relay map for this mode. +1943 pub fn relay_map(&self) -> RelayMap { +1944 match self { +1945 RelayMode::Disabled => RelayMap::empty(), +1946 RelayMode::Default => crate::defaults::prod::default_relay_map(), +1947 RelayMode::Staging => crate::defaults::staging::default_relay_map(), +1948 RelayMode::Custom(relay_map) => relay_map.clone(), +1949 } +1950 } +1951 +1952 /// Create a custom relay mode from a list of [`RelayUrl`]s. +1953 /// +1954 /// # Example +1955 /// +1956 /// ``` +1957 /// # fn main() -> n0_error::Result<()> { +1958 /// # use iroh::RelayMode; +1959 /// RelayMode::custom([ +1960 /// "https://use1-1.relay.n0.iroh.link.".parse()?, +1961 /// "https://euw-1.relay.n0.iroh.link.".parse()?, +1962 /// ]); +1963 /// # Ok(()) } +1964 /// ``` +1965 pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self { +1966 let m = RelayMap::from_iter(map); +1967 Self::Custom(m) +1968 } +1969} +1970 +1971/// Environment variable to force the use of staging relays. +1972pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; +1973 +1974/// Returns `true` if the use of staging relays is forced. +1975pub fn force_staging_infra() -> bool { +1976 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) +1977} +1978 +1979/// Returns the default relay mode. +1980/// +1981/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. +1982/// Otherwise, it will return `RelayMode::Default`. +1983pub fn default_relay_mode() -> RelayMode { +1984 // Use staging in testing +1985 match force_staging_infra() { +1986 true => RelayMode::Staging, +1987 false => RelayMode::Default, +1988 } +1989} +1990 +1991/// Check if we are being executed in a CGI context. +1992/// +1993/// If so, a malicious client can send the `Proxy:` header, and it will +1994/// be in the `HTTP_PROXY` env var. So we don't use it :) +1995fn is_cgi() -> bool { +1996 std::env::var_os("REQUEST_METHOD").is_some() +1997} +1998 +1999#[cfg(all(test, with_crypto_provider))] +2000mod tests { +2001 use std::{ +2002 collections::BTreeMap, +2003 io, +2004 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4}, +2005 str::FromStr, +2006 sync::Arc, +2007 time::{Duration, Instant}, +2008 }; +2009 +2010 use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; +2011 use iroh_dns::endpoint_info::UserData; +2012 use iroh_relay::{RelayConfig, RelayQuicConfig, server::Access, tls::CaTlsConfig}; +2013 use n0_error::{AnyError as Error, Result, StdResultExt}; +2014 use n0_future::{BufferedStreamExt, StreamExt, future::now_or_never, stream, time}; +2015 use n0_tracing_test::traced_test; +2016 use n0_watcher::Watcher; +2017 use noq::PathStats; +2018 use rand::{RngExt, SeedableRng}; +2019 use rand_chacha::ChaCha8Rng; +2020 use tokio::sync::oneshot; +2021 use tracing::{Instrument, debug_span, error_span, info, info_span, instrument}; +2022 +2023 use super::Endpoint; +2024 use crate::{ +2025 RelayMap, RelayMode, +2026 address_lookup::memory::MemoryLookup, +2027 endpoint::{ +2028 ApplicationClose, BindError, BindOpts, ConnectError, ConnectOptions, +2029 ConnectWithOptsError, Connection, ConnectionError, PathEvent, PathEventStream, presets, +2030 }, +2031 protocol::{AcceptError, ProtocolHandler, Router}, +2032 test_utils::{ +2033 QlogFileGroup, run_relay_server, run_relay_server_with, run_relay_server_with_access, +2034 }, +2035 }; +2036 +2037 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +2038 +2039 #[tokio::test] +2040 #[traced_test] +2041 async fn test_connect_self() -> Result { +2042 let ep = Endpoint::builder(presets::Minimal) +2043 .alpns(vec![TEST_ALPN.to_vec()]) +2044 .bind() +2045 .await +2046 .unwrap(); +2047 let my_addr = ep.addr(); +2048 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; +2049 assert!(res.is_err()); +2050 let err = res.err().unwrap(); +2051 assert!(err.to_string().starts_with("Connecting to ourself")); +2052 +2053 Ok(()) +2054 } +2055 +2056 #[tokio::test] +2057 #[traced_test] +2058 async fn endpoint_connect_close() -> Result { +2059 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2060 let (relay_map, relay_url, _guard) = run_relay_server().await?; +2061 let server_secret_key = SecretKey::from_bytes(&rng.random()); +2062 let server_peer_id = server_secret_key.public(); +2063 +2064 let qlog = QlogFileGroup::from_env("endpoint_connect_close"); +2065 +2066 // Wait for the endpoint to be started to make sure it's up before clients try to connect +2067 let ep = Endpoint::builder(presets::Minimal) +2068 .relay_mode(RelayMode::Custom(relay_map.clone())) +2069 .secret_key(server_secret_key) +2070 .transport_config(qlog.create("server")?) +2071 .alpns(vec![TEST_ALPN.to_vec()]) +2072 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2073 .bind() +2074 .await?; +2075 // Wait for the endpoint to be reachable via relay +2076 ep.online().await; +2077 +2078 let server = tokio::spawn( +2079 async move { +2080 info!("accepting connection"); +2081 let incoming = ep.accept().await.anyerr()?; +2082 let conn = incoming.await.anyerr()?; +2083 let mut stream = conn.accept_uni().await.anyerr()?; +2084 let mut buf = [0u8; 5]; +2085 stream.read_exact(&mut buf).await.anyerr()?; +2086 info!("Accepted 1 stream, received {buf:?}. Closing now."); +2087 // close the connection +2088 conn.close(7u8.into(), b"bye"); +2089 +2090 let res = conn.accept_uni().await; +2091 assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed); +2092 +2093 let res = stream.read_to_end(10).await; +2094 assert_eq!( +2095 res.unwrap_err(), +2096 noq::ReadToEndError::Read(noq::ReadError::ConnectionLost( +2097 ConnectionError::LocallyClosed +2098 )) +2099 ); +2100 info!("Closing the endpoint"); +2101 ep.close().await; +2102 info!("server test completed"); +2103 Ok::<_, Error>(()) +2104 } +2105 .instrument(info_span!("test-server")), +2106 ); +2107 +2108 let client = tokio::spawn( +2109 async move { +2110 let ep = Endpoint::builder(presets::Minimal) +2111 .relay_mode(RelayMode::Custom(relay_map)) +2112 .alpns(vec![TEST_ALPN.to_vec()]) +2113 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2114 .transport_config(qlog.create("client")?) +2115 .bind() +2116 .await?; +2117 info!("client connecting"); +2118 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); +2119 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; +2120 let mut stream = conn.open_uni().await.anyerr()?; +2121 +2122 // First write is accepted by server. We need this bit of synchronisation +2123 // because if the server closes after simply accepting the connection we can +2124 // not be sure our .open_uni() call would succeed as it may already receive +2125 // the error. +2126 stream.write_all(b"hello").await.anyerr()?; +2127 +2128 info!("waiting for closed"); +2129 // Remote now closes the connection, we should see an error sometime soon. +2130 let err = conn.closed().await; +2131 let expected_err = ConnectionError::ApplicationClosed(ApplicationClose { +2132 error_code: 7u8.into(), +2133 reason: b"bye".to_vec().into(), +2134 }); +2135 assert_eq!(err, expected_err); +2136 +2137 info!("opening new - expect it to fail"); +2138 let res = conn.open_uni().await; +2139 assert_eq!(res.unwrap_err(), expected_err); +2140 info!("Closing the client"); +2141 ep.close().await; +2142 info!("client test completed"); +2143 Ok::<_, Error>(()) +2144 } +2145 .instrument(info_span!("test-client")), +2146 ); +2147 +2148 let (server, client) = tokio::time::timeout( +2149 Duration::from_secs(30), +2150 n0_future::future::zip(server, client), +2151 ) +2152 .await +2153 .anyerr()?; +2154 server.anyerr()??; +2155 client.anyerr()??; +2156 Ok(()) +2157 } +2158 +2159 #[tokio::test] +2160 #[traced_test] +2161 async fn endpoint_relay_connect_loop() -> Result { +2162 let test_start = Instant::now(); +2163 let n_clients = 5; +2164 let n_chunks_per_client = 2; +2165 let chunk_size = 100; +2166 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +2167 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); +2168 let server_secret_key = SecretKey::from_bytes(&rng.random()); +2169 let server_endpoint_id = server_secret_key.public(); +2170 +2171 // Make sure the server is bound before having clients connect to it: +2172 let ep = Endpoint::builder(presets::Minimal) +2173 .relay_mode(RelayMode::Custom(relay_map.clone())) +2174 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2175 .secret_key(server_secret_key) +2176 .alpns(vec![TEST_ALPN.to_vec()]) +2177 .bind() +2178 .await?; +2179 // Also make sure the server has a working relay connection +2180 ep.online().await; +2181 +2182 info!(time = ?test_start.elapsed(), "test setup done"); +2183 +2184 // The server accepts the connections of the clients sequentially. +2185 let server = tokio::spawn( +2186 async move { +2187 let eps = ep.bound_sockets(); +2188 +2189 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); +2190 for i in 0..n_clients { +2191 let res = tokio::time::timeout(Duration::from_secs(5), async { +2192 let round_start = Instant::now(); +2193 info!("[server] round {i}"); +2194 let incoming = ep.accept().await.anyerr()?; +2195 let conn = incoming.await.anyerr()?; +2196 let endpoint_id = conn.remote_id(); +2197 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); +2198 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2199 let mut buf = vec![0u8; chunk_size]; +2200 for _i in 0..n_chunks_per_client { +2201 recv.read_exact(&mut buf).await.anyerr()?; +2202 send.write_all(&buf).await.anyerr()?; +2203 } +2204 info!(%i, peer = %endpoint_id.fmt_short(), "finishing"); +2205 send.finish().anyerr()?; +2206 conn.closed().await; // we're the last to send data, so we wait for the other side to close +2207 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); +2208 info!("[server] round {i} done in {:?}", round_start.elapsed()); +2209 Ok::<_, Error>(()) +2210 }) +2211 .await +2212 .std_context("timeout"); +2213 match res { +2214 Err(err) | Ok(Err(err)) => { +2215 // ensure we close the endpoint before returning early +2216 // on error +2217 ep.close().await; +2218 return Err(err); +2219 } +2220 _ => { +2221 // if this round went `Ok` don't close the endpoint yet +2222 } +2223 } +2224 } +2225 // close the endpoint before dropping the server task +2226 ep.close().await; +2227 Ok::<_, Error>(()) +2228 } +2229 .instrument(debug_span!("server")), +2230 ); +2231 +2232 let client = tokio::spawn(async move { +2233 for i in 0..n_clients { +2234 let round_start = Instant::now(); +2235 info!("[client] round {i}"); +2236 let client_secret_key = SecretKey::from_bytes(&rng.random()); +2237 let ep = Endpoint::builder(presets::Minimal) +2238 .relay_mode(RelayMode::Custom(relay_map.clone())) +2239 .alpns(vec![TEST_ALPN.to_vec()]) +2240 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2241 .secret_key(client_secret_key) +2242 .bind() +2243 .await?; +2244 let ep_1 = ep.clone(); +2245 let res = tokio::time::timeout( +2246 Duration::from_secs(5), +2247 async { +2248 info!("client binding"); +2249 let eps = ep.bound_sockets(); +2250 +2251 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); +2252 let endpoint_addr = +2253 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); +2254 info!(to = ?endpoint_addr, "client connecting"); +2255 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; +2256 info!("client connected"); +2257 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2258 +2259 for i in 0..n_chunks_per_client { +2260 let mut buf = vec![i; chunk_size]; +2261 send.write_all(&buf).await.anyerr()?; +2262 recv.read_exact(&mut buf).await.anyerr()?; +2263 assert_eq!(buf, vec![i; chunk_size]); +2264 } +2265 // we're the last to receive data, so we close +2266 conn.close(0u32.into(), b"bye!"); +2267 info!("client finished"); +2268 Ok::<_, Error>(()) +2269 } +2270 .instrument(debug_span!("client", %i)), +2271 ) +2272 .await +2273 .std_context("timeout"); +2274 ep_1.close().await; +2275 info!("client endpoint closed"); +2276 res??; +2277 info!("[client] round {i} done in {:?}", round_start.elapsed()); +2278 } +2279 Ok::<_, Error>(()) +2280 }); +2281 +2282 server.await.anyerr()??; +2283 client.await.anyerr()??; +2284 Ok(()) +2285 } +2286 +2287 #[tokio::test] +2288 #[traced_test] +2289 async fn endpoint_send_relay() -> Result { +2290 let (relay_map, _relay_url, _guard) = run_relay_server().await?; +2291 let client = Endpoint::builder(presets::Minimal) +2292 .relay_mode(RelayMode::Custom(relay_map.clone())) +2293 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2294 .bind() +2295 .await?; +2296 let server = Endpoint::builder(presets::Minimal) +2297 .relay_mode(RelayMode::Custom(relay_map)) +2298 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2299 .alpns(vec![TEST_ALPN.to_vec()]) +2300 .bind() +2301 .await?; +2302 +2303 let task = tokio::spawn({ +2304 let server = server.clone(); +2305 async move { +2306 let Some(conn) = server.accept().await else { +2307 n0_error::bail_any!("Expected an incoming connection"); +2308 }; +2309 let conn = conn.await.anyerr()?; +2310 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2311 let data = recv.read_to_end(1000).await.anyerr()?; +2312 send.write_all(&data).await.anyerr()?; +2313 send.finish().anyerr()?; +2314 conn.closed().await; +2315 +2316 Ok::<_, Error>(()) +2317 } +2318 }); +2319 +2320 let addr = server.addr(); +2321 let conn = client.connect(addr, TEST_ALPN).await?; +2322 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2323 send.write_all(b"Hello, world!").await.anyerr()?; +2324 send.finish().anyerr()?; +2325 let data = recv.read_to_end(1000).await.anyerr()?; +2326 conn.close(0u32.into(), b"bye!"); +2327 +2328 task.await.anyerr()??; +2329 +2330 client.close().await; +2331 server.close().await; +2332 +2333 assert_eq!(&data, b"Hello, world!"); +2334 +2335 Ok(()) +2336 } +2337 +2338 #[tokio::test] +2339 #[traced_test] +2340 async fn endpoint_two_direct_only() -> Result { +2341 // Connect two endpoints on the same network, without a relay server, without +2342 // Address Lookup. +2343 let ep1 = { +2344 let span = info_span!("server"); +2345 let _guard = span.enter(); +2346 Endpoint::builder(presets::N0) +2347 .alpns(vec![TEST_ALPN.to_vec()]) +2348 .relay_mode(RelayMode::Disabled) +2349 .bind() +2350 .await? +2351 }; +2352 let ep2 = { +2353 let span = info_span!("client"); +2354 let _guard = span.enter(); +2355 Endpoint::builder(presets::N0) +2356 .alpns(vec![TEST_ALPN.to_vec()]) +2357 .relay_mode(RelayMode::Disabled) +2358 .bind() +2359 .await? +2360 }; +2361 let ep1_nodeaddr = ep1.addr(); +2362 +2363 #[instrument(name = "client", skip_all)] +2364 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> { +2365 info!(me = %ep.id().fmt_short(), "client starting"); +2366 let conn = ep.connect(dst, TEST_ALPN).await?; +2367 let mut send = conn.open_uni().await.anyerr()?; +2368 send.write_all(b"hello").await.anyerr()?; +2369 send.finish().anyerr()?; +2370 Ok(conn.closed().await) +2371 } +2372 +2373 #[instrument(name = "server", skip_all)] +2374 async fn accept(ep: Endpoint, src: EndpointId) -> Result { +2375 info!(me = %ep.id().fmt_short(), "server starting"); +2376 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2377 let node_id = conn.remote_id(); +2378 assert_eq!(node_id, src); +2379 let mut recv = conn.accept_uni().await.anyerr()?; +2380 let msg = recv.read_to_end(100).await.anyerr()?; +2381 assert_eq!(msg, b"hello"); +2382 // Dropping the connection closes it just fine. +2383 Ok(()) +2384 } +2385 +2386 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); +2387 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); +2388 +2389 ep1_accept.await.anyerr()??; +2390 let conn_closed = dbg!(ep2_connect.await.anyerr()??); +2391 assert!(matches!( +2392 conn_closed, +2393 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2394 )); +2395 +2396 Ok(()) +2397 } +2398 +2399 #[tokio::test] +2400 #[traced_test] +2401 async fn endpoint_two_relay_only_becomes_direct() -> Result { +2402 // Connect two endpoints on the same network, via a relay server, without +2403 // Address Lookup. Wait until there is a direct connection. +2404 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2405 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2406 let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct")); +2407 +2408 #[instrument(name = "client", skip_all)] +2409 async fn connect( +2410 relay_map: RelayMap, +2411 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2412 qlog: Arc<QlogFileGroup>, +2413 ) -> Result<ConnectionError> { +2414 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2415 let secret = SecretKey::from_bytes(&rng.random()); +2416 let ep = Endpoint::builder(presets::N0) +2417 .secret_key(secret) +2418 .alpns(vec![TEST_ALPN.to_vec()]) +2419 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2420 .relay_mode(RelayMode::Custom(relay_map)) +2421 .transport_config(qlog.create("client")?) +2422 .bind() +2423 .await?; +2424 info!(me = %ep.id().fmt_short(), "client starting"); +2425 let dst = node_addr_rx.await.anyerr()?; +2426 +2427 info!(me = %ep.id().fmt_short(), "client connecting"); +2428 let conn = ep.connect(dst, TEST_ALPN).await?; +2429 let mut send = conn.open_uni().await.anyerr()?; +2430 send.write_all(b"hello").await.anyerr()?; +2431 let mut paths = conn.paths_stream(); +2432 info!("Waiting for direct connection"); +2433 while let Some(infos) = paths.next().await { +2434 info!(?infos, "new PathInfos"); +2435 if infos.iter().any(|info| info.is_ip()) { +2436 break; +2437 } +2438 } +2439 info!("Have direct connection"); +2440 #[cfg(feature = "metrics")] +2441 { +2442 // Validate holepunch metrics. +2443 assert_eq!(ep.metrics().socket.num_conns_opened.get(), 1); +2444 assert_eq!(ep.metrics().socket.num_conns_direct.get(), 1); +2445 } +2446 +2447 send.write_all(b"close please").await.anyerr()?; +2448 send.finish().anyerr()?; +2449 +2450 let res = conn.closed().await; +2451 ep.close().await; +2452 Ok(res) +2453 } +2454 +2455 #[instrument(name = "server", skip_all)] +2456 async fn accept( +2457 relay_map: RelayMap, +2458 node_addr_tx: oneshot::Sender<EndpointAddr>, +2459 qlog: Arc<QlogFileGroup>, +2460 ) -> Result { +2461 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +2462 let secret = SecretKey::from_bytes(&rng.random()); +2463 let ep = Endpoint::builder(presets::N0) +2464 .secret_key(secret) +2465 .alpns(vec![TEST_ALPN.to_vec()]) +2466 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2467 .transport_config(qlog.create("server")?) +2468 .relay_mode(RelayMode::Custom(relay_map)) +2469 .bind() +2470 .await?; +2471 ep.online().await; +2472 let mut node_addr = ep.addr(); +2473 node_addr.addrs.retain(|addr| addr.is_relay()); +2474 node_addr_tx.send(node_addr).unwrap(); +2475 +2476 info!(me = %ep.id().fmt_short(), "server starting"); +2477 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2478 // let node_id = conn.remote_node_id()?; +2479 // assert_eq!(node_id, src); +2480 let mut recv = conn.accept_uni().await.anyerr()?; +2481 let mut msg = [0u8; 5]; +2482 recv.read_exact(&mut msg).await.anyerr()?; +2483 assert_eq!(&msg, b"hello"); +2484 info!("received hello"); +2485 let msg = recv.read_to_end(100).await.anyerr()?; +2486 assert_eq!(msg, b"close please"); +2487 info!("received 'close please'"); +2488 // Closing the endpoint closes all connections. +2489 ep.close().await; +2490 Ok(()) +2491 } +2492 +2493 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone())); +2494 let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog)); +2495 +2496 server_task.await.anyerr()??; +2497 let conn_closed = dbg!(client_task.await.anyerr()??); +2498 assert!(matches!( +2499 conn_closed, +2500 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2501 )); +2502 +2503 Ok(()) +2504 } +2505 +2506 #[tokio::test] +2507 #[traced_test] +2508 async fn endpoint_two_relay_only_no_ip() -> Result { +2509 // Connect two endpoints on the same network, via a relay server, without +2510 // Address Lookup. +2511 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2512 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2513 +2514 #[instrument(name = "client", skip_all)] +2515 async fn connect( +2516 relay_map: RelayMap, +2517 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2518 ) -> Result<ConnectionError> { +2519 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2520 let secret = SecretKey::from_bytes(&rng.random()); +2521 let ep = Endpoint::builder(presets::N0) +2522 .secret_key(secret) +2523 .alpns(vec![TEST_ALPN.to_vec()]) +2524 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2525 .relay_mode(RelayMode::Custom(relay_map)) +2526 .clear_ip_transports() // disable direct +2527 .bind() +2528 .await?; +2529 info!(me = %ep.id().fmt_short(), "client starting"); +2530 let dst = node_addr_rx.await.anyerr()?; +2531 +2532 info!(me = %ep.id().fmt_short(), "client connecting"); +2533 let conn = ep.connect(dst, TEST_ALPN).await?; +2534 let mut send = conn.open_uni().await.anyerr()?; +2535 send.write_all(b"hello").await.anyerr()?; +2536 let mut paths = conn.paths_stream(); +2537 info!("Waiting for connection"); +2538 'outer: while let Some(infos) = paths.next().await { +2539 info!(?infos, "new PathInfos"); +2540 for info in infos.iter() { +2541 if info.is_ip() { +2542 panic!("should not happen: {:?}", info); +2543 } +2544 if info.is_relay() { +2545 break 'outer; +2546 } +2547 } +2548 } +2549 info!("Have relay connection"); +2550 +2551 send.write_all(b"close please").await.anyerr()?; +2552 send.finish().anyerr()?; +2553 let res = conn.closed().await; +2554 ep.close().await; +2555 Ok(res) +2556 } +2557 +2558 #[instrument(name = "server", skip_all)] +2559 async fn accept( +2560 relay_map: RelayMap, +2561 node_addr_tx: oneshot::Sender<EndpointAddr>, +2562 ) -> Result { +2563 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +2564 let secret = SecretKey::from_bytes(&rng.random()); +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 .clear_ip_transports() +2571 .bind() +2572 .await?; +2573 ep.online().await; +2574 let node_addr = ep.addr(); +2575 node_addr_tx.send(node_addr).unwrap(); +2576 +2577 info!(me = %ep.id().fmt_short(), "server starting"); +2578 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2579 // let node_id = conn.remote_node_id()?; +2580 // assert_eq!(node_id, src); +2581 let mut recv = conn.accept_uni().await.anyerr()?; +2582 let mut msg = [0u8; 5]; +2583 recv.read_exact(&mut msg).await.anyerr()?; +2584 assert_eq!(&msg, b"hello"); +2585 info!("received hello"); +2586 let msg = recv.read_to_end(100).await.anyerr()?; +2587 assert_eq!(msg, b"close please"); +2588 info!("received 'close please'"); +2589 // Closing the endpoint closes all connections. +2590 ep.close().await; +2591 Ok(()) +2592 } +2593 +2594 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2595 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2596 +2597 server_task.await.anyerr()??; +2598 let conn_closed = dbg!(client_task.await.anyerr()??); +2599 assert!(matches!( +2600 conn_closed, +2601 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2602 )); +2603 +2604 Ok(()) +2605 } +2606 +2607 #[tokio::test] +2608 #[traced_test] +2609 async fn endpoint_two_direct_add_relay() -> Result { +2610 // Connect two endpoints on the same network, without relay server and without +2611 // Address Lookup. Add a relay connection later. +2612 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2613 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2614 +2615 #[instrument(name = "client", skip_all)] +2616 async fn connect( +2617 relay_map: RelayMap, +2618 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2619 ) -> Result<()> { +2620 let secret = SecretKey::from([0u8; 32]); +2621 let ep = Endpoint::builder(presets::N0) +2622 .secret_key(secret) +2623 .alpns(vec![TEST_ALPN.to_vec()]) +2624 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2625 .relay_mode(RelayMode::Custom(relay_map)) +2626 .bind() +2627 .await?; +2628 info!(me = %ep.id().fmt_short(), "client starting"); +2629 let dst = node_addr_rx.await.anyerr()?; +2630 +2631 info!(me = %ep.id().fmt_short(), "client connecting"); +2632 let conn = ep.connect(dst, TEST_ALPN).await?; +2633 info!(me = %ep.id().fmt_short(), "client connected"); +2634 +2635 // We should be connected via IP, because it is faster than the relay server. +2636 // TODO: Maybe not panic if this is not true? +2637 +2638 let path_info = conn.paths(); +2639 assert_eq!(path_info.len(), 1); +2640 assert!(path_info.iter().next().unwrap().is_ip()); +2641 +2642 let mut paths = conn.paths_stream(); +2643 time::timeout(Duration::from_secs(5), async move { +2644 while let Some(infos) = paths.next().await { +2645 info!(?infos, "new PathInfos"); +2646 if infos.iter().any(|info| info.is_relay()) { +2647 info!("client has a relay path"); +2648 break; +2649 } +2650 } +2651 }) +2652 .await +2653 .anyerr()?; +2654 +2655 // wait for the server to signal it has the relay connection +2656 let mut stream = conn.accept_uni().await.anyerr()?; +2657 stream.read_to_end(100).await.anyerr()?; +2658 +2659 info!("client closing"); +2660 conn.close(0u8.into(), b""); +2661 ep.close().await; +2662 Ok(()) +2663 } +2664 +2665 #[instrument(name = "server", skip_all)] +2666 async fn accept( +2667 relay_map: RelayMap, +2668 node_addr_tx: oneshot::Sender<EndpointAddr>, +2669 ) -> Result<ConnectionError> { +2670 let secret = SecretKey::from([1u8; 32]); +2671 let ep = Endpoint::builder(presets::N0) +2672 .secret_key(secret) +2673 .alpns(vec![TEST_ALPN.to_vec()]) +2674 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2675 .relay_mode(RelayMode::Custom(relay_map)) +2676 .bind() +2677 .await?; +2678 ep.online().await; +2679 let node_addr = ep.addr(); +2680 node_addr_tx.send(node_addr).unwrap(); +2681 +2682 info!(me = %ep.id().fmt_short(), "server starting"); +2683 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2684 info!(me = %ep.id().fmt_short(), "server accepted connection"); +2685 +2686 // Wait for a relay connection to be added. Client does all the asserting here, +2687 // we just want to wait so we get to see all the mechanics of the connection +2688 // being added on this side too. +2689 let mut paths = conn.paths_stream(); +2690 time::timeout(Duration::from_secs(5), async move { +2691 while let Some(infos) = paths.next().await { +2692 info!(?infos, "new PathInfos"); +2693 if infos.iter().any(|path| path.is_relay()) { +2694 info!("server has a relay path"); +2695 break; +2696 } +2697 } +2698 }) +2699 .await +2700 .anyerr()?; +2701 +2702 let mut stream = conn.open_uni().await.anyerr()?; +2703 stream.write_all(b"have relay").await.anyerr()?; +2704 stream.finish().anyerr()?; +2705 info!("waiting conn.closed()"); +2706 +2707 Ok(conn.closed().await) +2708 } +2709 +2710 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2711 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2712 +2713 client_task.await.anyerr()??; +2714 let conn_closed = dbg!(server_task.await.anyerr()??); +2715 assert!(matches!( +2716 conn_closed, +2717 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2718 )); +2719 +2720 Ok(()) +2721 } +2722 +2723 #[tokio::test] +2724 #[traced_test] +2725 async fn endpoint_relay_map_change() -> Result { +2726 let (relay_map, relay_url, _guard1) = run_relay_server().await?; +2727 let client = Endpoint::builder(presets::Minimal) +2728 .relay_mode(RelayMode::Custom(relay_map.clone())) +2729 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2730 .bind() +2731 .await?; +2732 let server = Endpoint::builder(presets::Minimal) +2733 .relay_mode(RelayMode::Custom(relay_map)) +2734 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2735 .alpns(vec![TEST_ALPN.to_vec()]) +2736 .bind() +2737 .await?; +2738 +2739 let task = tokio::spawn({ +2740 let server = server.clone(); +2741 async move { +2742 for i in 0..2 { +2743 println!("accept: round {i}"); +2744 let Some(conn) = server.accept().await else { +2745 n0_error::bail_any!("Expected an incoming connection"); +2746 }; +2747 let conn = conn.await.anyerr()?; +2748 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2749 let data = recv.read_to_end(1000).await.anyerr()?; +2750 send.write_all(&data).await.anyerr()?; +2751 send.finish().anyerr()?; +2752 conn.closed().await; +2753 } +2754 Ok::<_, Error>(()) +2755 } +2756 }); +2757 +2758 server.online().await; +2759 +2760 let mut addr = server.addr(); +2761 println!("round1: {:?}", addr); +2762 +2763 // remove direct addrs to force relay usage +2764 addr.addrs +2765 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2766 +2767 let conn = client.connect(addr, TEST_ALPN).await?; +2768 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2769 send.write_all(b"Hello, world!").await.anyerr()?; +2770 send.finish().anyerr()?; +2771 let data = recv.read_to_end(1000).await.anyerr()?; +2772 conn.close(0u32.into(), b"bye!"); +2773 +2774 assert_eq!(&data, b"Hello, world!"); +2775 +2776 // setup a second relay server +2777 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; +2778 let new_endpoint = new_relay_map +2779 .get(&new_relay_url) +2780 .expect("missing endpoint") +2781 .clone(); +2782 dbg!(&new_relay_map); +2783 +2784 let addr_watcher = server.watch_addr(); +2785 +2786 // add new new relay +2787 assert!( +2788 server +2789 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) +2790 .await +2791 .is_none() +2792 ); +2793 // remove the old relay +2794 assert!(server.remove_relay(&relay_url).await.is_some()); +2795 +2796 println!("------- changed ----- "); +2797 +2798 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { +2799 let mut stream = addr_watcher.stream(); +2800 while let Some(addr) = stream.next().await { +2801 if addr.relay_urls().next() != Some(&relay_url) { +2802 return addr; +2803 } +2804 } +2805 panic!("failed to change relay"); +2806 }) +2807 .await +2808 .anyerr()?; +2809 +2810 println!("round2: {:?}", addr); +2811 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); +2812 +2813 // remove direct addrs to force relay usage +2814 addr.addrs +2815 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2816 +2817 let conn = client.connect(addr, TEST_ALPN).await?; +2818 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2819 send.write_all(b"Hello, world!").await.anyerr()?; +2820 send.finish().anyerr()?; +2821 let data = recv.read_to_end(1000).await.anyerr()?; +2822 conn.close(0u32.into(), b"bye!"); +2823 +2824 task.await.anyerr()??; +2825 +2826 client.close().await; +2827 server.close().await; +2828 +2829 assert_eq!(&data, b"Hello, world!"); +2830 +2831 Ok(()) +2832 } +2833 +2834 #[tokio::test] +2835 #[traced_test] +2836 async fn endpoint_bidi_send_recv() -> Result { +2837 let disco = MemoryLookup::new(); +2838 let ep1 = Endpoint::builder(presets::Minimal) +2839 .address_lookup(disco.clone()) +2840 .alpns(vec![TEST_ALPN.to_vec()]) +2841 .bind() +2842 .await?; +2843 +2844 let ep2 = Endpoint::builder(presets::Minimal) +2845 .address_lookup(disco.clone()) +2846 .alpns(vec![TEST_ALPN.to_vec()]) +2847 .bind() +2848 .await?; +2849 +2850 disco.add_endpoint_info(ep1.addr()); +2851 disco.add_endpoint_info(ep2.addr()); +2852 +2853 let ep1_endpointid = ep1.id(); +2854 let ep2_endpointid = ep2.id(); +2855 eprintln!("endpoint id 1 {ep1_endpointid}"); +2856 eprintln!("endpoint id 2 {ep2_endpointid}"); +2857 +2858 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { +2859 let conn = ep.connect(dst, TEST_ALPN).await?; +2860 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2861 info!("sending hello"); +2862 send.write_all(b"hello").await.anyerr()?; +2863 send.finish().anyerr()?; +2864 info!("receiving world"); +2865 let m = recv.read_to_end(100).await.anyerr()?; +2866 assert_eq!(m, b"world"); +2867 conn.close(1u8.into(), b"done"); +2868 Ok(()) +2869 } +2870 +2871 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { +2872 let incoming = ep.accept().await.anyerr()?; +2873 let mut iconn = incoming.accept().anyerr()?; +2874 let alpn = iconn.alpn().await?; +2875 let conn = iconn.await.anyerr()?; +2876 let endpoint_id = conn.remote_id(); +2877 assert_eq!(endpoint_id, src); +2878 assert_eq!(alpn, TEST_ALPN); +2879 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2880 info!("receiving hello"); +2881 let m = recv.read_to_end(100).await.anyerr()?; +2882 assert_eq!(m, b"hello"); +2883 info!("sending hello"); +2884 send.write_all(b"world").await.anyerr()?; +2885 send.finish().anyerr()?; +2886 match conn.closed().await { +2887 ConnectionError::ApplicationClosed(closed) => { +2888 assert_eq!(closed.error_code, 1u8.into()); +2889 Ok(()) +2890 } +2891 _ => panic!("wrong close error"), +2892 } +2893 } +2894 +2895 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( +2896 info_span!( +2897 "p1_accept", +2898 ep1 = %ep1.id().fmt_short(), +2899 dst = %ep2_endpointid.fmt_short(), +2900 ), +2901 )); +2902 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( +2903 info_span!( +2904 "p2_accept", +2905 ep2 = %ep2.id().fmt_short(), +2906 dst = %ep1_endpointid.fmt_short(), +2907 ), +2908 )); +2909 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( +2910 info_span!( +2911 "p1_connect", +2912 ep1 = %ep1.id().fmt_short(), +2913 dst = %ep2_endpointid.fmt_short(), +2914 ), +2915 )); +2916 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( +2917 info_span!( +2918 "p2_connect", +2919 ep2 = %ep2.id().fmt_short(), +2920 dst = %ep1_endpointid.fmt_short(), +2921 ), +2922 )); +2923 +2924 p1_accept.await.anyerr()??; +2925 p2_accept.await.anyerr()??; +2926 p1_connect.await.anyerr()??; +2927 p2_connect.await.anyerr()??; +2928 +2929 Ok(()) +2930 } +2931 +2932 /// Regression test: Don't fail connections with dead relays on Windows. +2933 /// +2934 /// A single client connecting to a single server over a usable direct path +2935 /// must succeed even when both are configured with an unreachable home relay +2936 /// (`https://127.0.0.1:1`, nothing listening). The dead relay should be irrelevant: +2937 /// the direct path works and the connection comes up in milliseconds. +2938 /// +2939 /// This was broken on Windows because QaD sends over the same socket to the dead +2940 /// relay, and the socket would return recv errors on the next recv to report ICMP +2941 /// errors for the previous send. We now skip over these errors, implemented in +2942 /// https://github.com/n0-computer/net-tools/pull/166, so this no longer fails. +2943 #[tokio::test] +2944 async fn endpoint_unreachable_relay_direct_connect_succeeds() -> Result { +2945 // The relay url and its QADv4 probe must both hit closed ports, so the relay is +2946 // unreachable and the probe draws the ICMP port-unreachable the Windows socket +2947 // reports on its next recv. Claim an ephemeral port, then close it: it's now free, +2948 // so nothing answers. There's nothing stopping the kernel from reusing a port +2949 // right away, but on most machines that's unlikely. The url is dialed over TCP +2950 // (HTTPS), the probe over UDP, so claim each with the matching socket type. +2951 let closed_tcp_port = { +2952 let sock = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind"); +2953 sock.local_addr().expect("local addr").port() +2954 }; +2955 let closed_udp_port = { +2956 let sock = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind"); +2957 sock.local_addr().expect("local addr").port() +2958 }; +2959 let dead_relay: RelayUrl = format!("https://127.0.0.1:{closed_tcp_port}") +2960 .parse() +2961 .expect("valid relay url"); +2962 let dead_relay_config = RelayConfig::new( +2963 dead_relay.clone(), +2964 Some(RelayQuicConfig::new(closed_udp_port)), +2965 ); +2966 +2967 let bind_endpoint = async || { +2968 Endpoint::builder(presets::Minimal) +2969 // Use the broken relay to trigger the ICMP errors from the QaD sends. +2970 .relay_mode(RelayMode::Custom(RelayMap::from_iter([ +2971 dead_relay_config.clone() +2972 ]))) +2973 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +2974 .alpns(vec![TEST_ALPN.to_vec()]) +2975 // Bind on IPv4 only to ensure a single socket to not have spurious polls. +2976 .bind_addr((Ipv4Addr::LOCALHOST, 0)) +2977 .expect("valid addr") +2978 .bind() +2979 .await +2980 }; +2981 +2982 let server = bind_endpoint().await?; +2983 let server_addr = server.addr().with_relay_url(dead_relay.clone()); +2984 let client = bind_endpoint().await?; +2985 +2986 // Server accepts the incoming connection and holds it open until the test ends. +2987 let accept = tokio::spawn(async move { +2988 let incoming = server.accept().await.anyerr()?; +2989 let conn = incoming.await.anyerr()?; +2990 conn.closed().await; +2991 server.close().await; +2992 n0_error::Ok(()) +2993 }); +2994 +2995 // The connect must complete over the direct loopback path despite the dead relay. +2996 let _conn = tokio::time::timeout( +2997 Duration::from_secs(10), +2998 client.connect(server_addr, TEST_ALPN), +2999 ) +3000 .await +3001 .expect("connection should succeed")?; +3002 client.close().await; +3003 accept.await.anyerr()??; +3004 Ok(()) +3005 } +3006 +3007 #[tokio::test] +3008 #[traced_test] +3009 async fn test_direct_addresses_no_qad_relay() -> Result { +3010 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +3011 +3012 let ep = Endpoint::builder(presets::Minimal) +3013 .relay_mode(RelayMode::Custom(relay_map)) +3014 .alpns(vec![TEST_ALPN.to_vec()]) +3015 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3016 .bind() +3017 .await?; +3018 +3019 assert!(ep.addr().ip_addrs().count() > 0); +3020 +3021 Ok(()) +3022 } +3023 +3024 /// Test that configured external addresses are included in the endpoint's +3025 /// direct addresses, both when set via builder and at runtime. +3026 #[tokio::test(flavor = "current_thread", start_paused = true)] +3027 #[traced_test] +3028 async fn test_external_addr() -> Result { +3029 let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345)); +3030 +3031 // Test builder-configured external address +3032 let ep = Endpoint::builder(presets::Minimal) +3033 .external_addr(configured_addr) +3034 .bind() +3035 .await?; +3036 +3037 let addr = ep.addr(); +3038 assert!( +3039 addr.ip_addrs().any(|a| *a == configured_addr), +3040 "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}" +3041 ); +3042 +3043 // Test runtime add +3044 let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321)); +3045 ep.add_external_addr(runtime_addr).await; +3046 tokio::time::sleep(Duration::from_millis(100)).await; +3047 +3048 let addr = ep.addr(); +3049 assert!( +3050 addr.ip_addrs().any(|a| *a == runtime_addr), +3051 "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}" +3052 ); +3053 +3054 // Test runtime remove +3055 let removed = ep.remove_external_addr(&runtime_addr).await; +3056 assert!(removed); +3057 tokio::time::sleep(Duration::from_millis(100)).await; +3058 +3059 let addr = ep.addr(); +3060 assert!( +3061 !addr.ip_addrs().any(|a| *a == runtime_addr), +3062 "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}" +3063 ); +3064 assert!( +3065 addr.ip_addrs().any(|a| *a == configured_addr), +3066 "builder-configured external addr should still be present: {addr:?}" +3067 ); +3068 +3069 ep.close().await; +3070 Ok(()) +3071 } +3072 +3073 #[tokio::test] +3074 #[traced_test] +3075 async fn graceful_close() -> Result { +3076 let client = Endpoint::bind(presets::Minimal).await?; +3077 let server = Endpoint::builder(presets::Minimal) +3078 .alpns(vec![TEST_ALPN.to_vec()]) +3079 .bind() +3080 .await?; +3081 let server_addr = server.addr(); +3082 let server_task = tokio::spawn(async move { +3083 let incoming = server.accept().await.anyerr()?; +3084 let conn = incoming.await.anyerr()?; +3085 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +3086 let msg = recv.read_to_end(1_000).await.anyerr()?; +3087 send.write_all(&msg).await.anyerr()?; +3088 send.finish().anyerr()?; +3089 let close_reason = conn.closed().await; +3090 Ok::<_, Error>(close_reason) +3091 }); +3092 +3093 let conn = client.connect(server_addr, TEST_ALPN).await?; +3094 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +3095 send.write_all(b"Hello, world!").await.anyerr()?; +3096 send.finish().anyerr()?; +3097 recv.read_to_end(1_000).await.anyerr()?; +3098 conn.close(42u32.into(), b"thanks, bye!"); +3099 client.close().await; +3100 +3101 let close_err = server_task.await.anyerr()??; +3102 let ConnectionError::ApplicationClosed(app_close) = close_err else { +3103 panic!("Unexpected close reason: {close_err:?}"); +3104 }; +3105 +3106 assert_eq!(app_close.error_code, 42u32.into()); +3107 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +3108 +3109 Ok(()) +3110 } +3111 +3112 #[cfg(feature = "metrics")] +3113 #[tokio::test] +3114 #[traced_test] +3115 async fn metrics_smoke() -> Result { +3116 use iroh_metrics::Registry; +3117 +3118 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +3119 let client = Endpoint::builder(presets::Minimal) +3120 .secret_key(secret_key) +3121 .bind() +3122 .await?; +3123 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +3124 let server = Endpoint::builder(presets::Minimal) +3125 .secret_key(secret_key) +3126 .alpns(vec![TEST_ALPN.to_vec()]) +3127 .bind() +3128 .await?; +3129 let server_addr = server.addr(); +3130 let server_task = tokio::task::spawn(async move { +3131 let conn = server.accept().await.anyerr()?.await.anyerr()?; +3132 let mut uni = conn.accept_uni().await.anyerr()?; +3133 uni.read_to_end(10).await.anyerr()?; +3134 drop(conn); +3135 Ok::<_, Error>(server) +3136 }); +3137 let conn = client.connect(server_addr, TEST_ALPN).await?; +3138 let mut uni = conn.open_uni().await.anyerr()?; +3139 uni.write_all(b"helloworld").await.anyerr()?; +3140 uni.finish().anyerr()?; +3141 conn.closed().await; +3142 drop(conn); +3143 let server = server_task.await.anyerr()??; +3144 +3145 let m = client.metrics(); +3146 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3147 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3148 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3149 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3150 assert!(m.socket.recv_datagrams.get() > 0); +3151 +3152 let m = server.metrics(); +3153 // assert_eq!(m.socket.num_direct_conns_added.get(), 1); +3154 // assert_eq!(m.socket.connection_became_direct.get(), 1); +3155 // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1); +3156 // assert_eq!(m.socket.connection_handshake_success.get(), 1); +3157 assert!(m.socket.recv_datagrams.get() > 0); +3158 +3159 // test openmetrics encoding with labeled subregistries per endpoint +3160 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +3161 let id = endpoint.id().fmt_short(); +3162 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); +3163 sub_registry.register_all(endpoint.metrics()); +3164 } +3165 let mut registry = Registry::default(); +3166 register_endpoint(&mut registry, &client); +3167 register_endpoint(&mut registry, &server); +3168 // let s = registry.encode_openmetrics_to_string().anyerr()?; +3169 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); +3170 // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); +3171 Ok(()) +3172 } +3173 +3174 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +3175 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +3176 async fn alpn_connection_test( +3177 accept_alpns: Vec<Vec<u8>>, +3178 primary_connect_alpn: &[u8], +3179 secondary_connect_alpns: Vec<Vec<u8>>, +3180 ) -> Result<Vec<u8>> { +3181 let client = Endpoint::bind(presets::Minimal).await?; +3182 let server = Endpoint::builder(presets::Minimal) +3183 .alpns(accept_alpns) +3184 .bind() +3185 .await?; +3186 let server_addr = server.addr(); +3187 let server_task = tokio::spawn({ +3188 let server = server.clone(); +3189 async move { +3190 let incoming = server.accept().await.anyerr()?; +3191 let conn = incoming.await.anyerr()?; +3192 conn.close(0u32.into(), b"bye!"); +3193 n0_error::Ok(conn.alpn().to_vec()) +3194 } +3195 }); +3196 +3197 let conn = client +3198 .connect_with_opts( +3199 server_addr, +3200 primary_connect_alpn, +3201 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +3202 ) +3203 .await?; +3204 let conn = conn.await.anyerr()?; +3205 let client_alpn = conn.alpn(); +3206 conn.closed().await; +3207 client.close().await; +3208 server.close().await; +3209 +3210 let server_alpn = server_task.await.anyerr()??; +3211 +3212 assert_eq!(client_alpn, server_alpn); +3213 +3214 Ok(server_alpn.to_vec()) +3215 } +3216 +3217 #[tokio::test] +3218 #[traced_test] +3219 async fn connect_multiple_alpn_negotiated() -> Result { +3220 const ALPN_ONE: &[u8] = b"alpn/1"; +3221 const ALPN_TWO: &[u8] = b"alpn/2"; +3222 +3223 assert_eq!( +3224 alpn_connection_test( +3225 // Prefer version 2 over version 1 on the accept side +3226 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3227 ALPN_TWO, +3228 vec![ALPN_ONE.to_vec()], +3229 ) +3230 .await?, +3231 ALPN_TWO.to_vec(), +3232 "accept side prefers version 2 over 1" +3233 ); +3234 +3235 assert_eq!( +3236 alpn_connection_test( +3237 // Only support the old version +3238 vec![ALPN_ONE.to_vec()], +3239 ALPN_TWO, +3240 vec![ALPN_ONE.to_vec()], +3241 ) +3242 .await?, +3243 ALPN_ONE.to_vec(), +3244 "accept side only supports the old version" +3245 ); +3246 +3247 assert_eq!( +3248 alpn_connection_test( +3249 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3250 ALPN_ONE, +3251 vec![ALPN_TWO.to_vec()], +3252 ) +3253 .await?, +3254 ALPN_TWO.to_vec(), +3255 "connect side ALPN order doesn't matter" +3256 ); +3257 +3258 assert_eq!( +3259 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +3260 .await?, +3261 ALPN_ONE.to_vec(), +3262 "connect side only supports the old version" +3263 ); +3264 +3265 Ok(()) +3266 } +3267 +3268 #[tokio::test] +3269 #[traced_test] +3270 #[cfg(feature = "unstable-net-report")] +3271 async fn watch_net_report() -> Result { +3272 let endpoint = Endpoint::builder(presets::Minimal) +3273 .relay_mode(RelayMode::Staging) +3274 .bind() +3275 .await?; +3276 +3277 // can get a first report +3278 endpoint.net_report().updated().await.anyerr()?; +3279 +3280 Ok(()) +3281 } +3282 +3283 /// Tests that initial connection establishment isn't extremely slow compared +3284 /// to subsequent connections. +3285 /// +3286 /// This is a time based test, but uses a very large ratio to reduce flakiness. +3287 /// It also does a number of connections to average out any anomalies. +3288 #[tokio::test] +3289 #[traced_test] +3290 async fn connect_multi_time() -> Result { +3291 let n = 32; +3292 +3293 const NOOP_ALPN: &[u8] = b"noop"; +3294 +3295 #[derive(Debug, Clone)] +3296 struct Noop; +3297 +3298 impl ProtocolHandler for Noop { +3299 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +3300 connection.closed().await; +3301 Ok(()) +3302 } +3303 } +3304 +3305 async fn noop_server() -> Result<(Router, EndpointAddr)> { +3306 let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?; +3307 let addr = endpoint.addr(); +3308 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); +3309 Ok((router, addr)) +3310 } +3311 +3312 let routers = stream::iter(0..n) +3313 .map(|_| noop_server()) +3314 .buffered_unordered(32) +3315 .collect::<Vec<_>>() +3316 .await +3317 .into_iter() +3318 .collect::<Result<Vec<_>, _>>() +3319 .anyerr()?; +3320 +3321 let addrs = routers +3322 .iter() +3323 .map(|(_, addr)| addr.clone()) +3324 .collect::<Vec<_>>(); +3325 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); +3326 let address_lookup = MemoryLookup::from_endpoint_info(addrs); +3327 let endpoint = Endpoint::builder(presets::Minimal) +3328 .address_lookup(address_lookup) +3329 .bind() +3330 .await +3331 .anyerr()?; +3332 // wait for the endpoint to be initialized. This should not be needed, +3333 // but we don't want to measure endpoint init time but connection time +3334 // from a fully initialized endpoint. +3335 endpoint.addr(); +3336 let t0 = Instant::now(); +3337 for id in &ids { +3338 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3339 conn.close(0u32.into(), b"done"); +3340 } +3341 let dt0 = t0.elapsed().as_secs_f64(); +3342 let t1 = Instant::now(); +3343 for id in &ids { +3344 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +3345 conn.close(0u32.into(), b"done"); +3346 } +3347 let dt1 = t1.elapsed().as_secs_f64(); +3348 +3349 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); +3350 Ok(()) +3351 } +3352 +3353 #[tokio::test] +3354 async fn test_custom_relay() -> Result { +3355 let _ep = Endpoint::builder(presets::Minimal) +3356 .relay_mode(RelayMode::custom([RelayUrl::from_str( +3357 "https://use1-1.relay.n0.iroh.link.", +3358 )?])) +3359 .bind() +3360 .await?; +3361 +3362 let relays = RelayMap::try_from_iter([ +3363 "https://use1-1.relay.n0.iroh.link/", +3364 "https://euc1-1.relay.n0.iroh.link/", +3365 ])?; +3366 let _ep = Endpoint::builder(presets::Minimal) +3367 .relay_mode(RelayMode::Custom(relays)) +3368 .bind() +3369 .await?; +3370 +3371 Ok(()) +3372 } +3373 +3374 /// Testing bind_addr: Clear IP transports and add single IPv4 bind +3375 #[tokio::test] +3376 #[traced_test] +3377 async fn test_bind_addr_clear() -> Result { +3378 let ep = Endpoint::builder(presets::Minimal) +3379 .clear_ip_transports() +3380 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3381 .bind() +3382 .await?; +3383 let bound_sockets = ep.bound_sockets(); +3384 assert_eq!(bound_sockets.len(), 1); +3385 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); +3386 ep.close().await; +3387 Ok(()) +3388 } +3389 +3390 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind +3391 /// +3392 /// This will bind two sockets: default wildcard bind for IPv6, and our +3393 /// manually-added IPv4 bind. +3394 #[tokio::test] +3395 #[traced_test] +3396 async fn test_bind_addr_no_clear() -> Result { +3397 let ep = Endpoint::builder(presets::Minimal) +3398 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +3399 .bind() +3400 .await?; +3401 let bound_sockets = ep.bound_sockets(); +3402 assert_eq!(bound_sockets.len(), 2); +3403 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3404 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3405 // Test that our manually added socket is there +3406 assert!( +3407 bound_sockets +3408 .iter() +3409 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3410 ); +3411 ep.close().await; +3412 Ok(()) +3413 } +3414 +3415 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. +3416 // +3417 // This replaces the default IPv4 bind added by the builder, +3418 // but keeps the default wildcard IPv6 bind. +3419 #[tokio::test] +3420 #[traced_test] +3421 async fn test_bind_addr_default() -> Result { +3422 let ep = Endpoint::builder(presets::Minimal) +3423 .bind_addr_with_opts( +3424 (Ipv4Addr::LOCALHOST, 0), +3425 BindOpts::default().set_is_default_route(true), +3426 )? +3427 .bind() +3428 .await?; +3429 let bound_sockets = ep.bound_sockets(); +3430 assert_eq!(bound_sockets.len(), 2); +3431 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +3432 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3433 assert!( +3434 bound_sockets +3435 .iter() +3436 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3437 ); +3438 ep.close().await; +3439 drop(ep); +3440 +3441 Ok(()) +3442 } +3443 +3444 /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len +3445 /// +3446 /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our +3447 /// manually-added IPv4 bind. +3448 #[tokio::test] +3449 #[traced_test] +3450 async fn test_bind_addr_nonzero_prefix() -> Result { +3451 let ep = Endpoint::builder(presets::Minimal) +3452 .bind_addr_with_opts( +3453 (Ipv4Addr::LOCALHOST, 0), +3454 BindOpts::default().set_prefix_len(32), +3455 )? +3456 .bind() +3457 .await?; +3458 let bound_sockets = ep.bound_sockets(); +3459 assert_eq!(bound_sockets.len(), 3); +3460 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); +3461 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +3462 // Test that the default wildcard socket is there +3463 assert!( +3464 bound_sockets +3465 .iter() +3466 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3467 ); +3468 // Test that our manually added socket is there +3469 assert!( +3470 bound_sockets +3471 .iter() +3472 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3473 ); +3474 ep.close().await; +3475 Ok(()) +3476 } +3477 +3478 /// Bind on an unusable port with the default opts. +3479 /// +3480 /// Binding the endpoint fails with an AddrInUse error. +3481 #[tokio::test] +3482 #[traced_test] +3483 async fn test_bind_addr_badport() -> Result { +3484 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3485 let port = socket.local_addr()?.port(); +3486 +3487 let res = Endpoint::builder(presets::Minimal) +3488 .clear_ip_transports() +3489 .bind_addr((Ipv4Addr::LOCALHOST, port))? +3490 .bind() +3491 .await; +3492 +3493 assert!(matches!( +3494 res, +3495 Err(BindError::Sockets { +3496 source: io_error, +3497 .. +3498 }) +3499 if io_error.kind() == io::ErrorKind::AddrInUse +3500 )); +3501 Ok(()) +3502 } +3503 +3504 /// Bind a non-default route on an unusable port, but set is_required = false. +3505 /// +3506 /// Binding the endpoint succeeds. +3507 #[tokio::test] +3508 #[traced_test] +3509 async fn test_bind_addr_badport_notrequired() -> Result { +3510 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3511 let port = socket.local_addr()?.port(); +3512 +3513 let ep = Endpoint::builder(presets::Minimal) +3514 .bind_addr_with_opts( +3515 (Ipv4Addr::LOCALHOST, port), +3516 BindOpts::default() +3517 .set_prefix_len(32) +3518 .set_is_required(false), +3519 )? +3520 .bind() +3521 .await?; +3522 let bound_sockets = ep.bound_sockets(); +3523 // just the default wildcard binds +3524 assert_eq!(bound_sockets.len(), 2); +3525 // our requested bind addr is not included because it failed to bind +3526 assert!( +3527 !bound_sockets +3528 .iter() +3529 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3530 ); +3531 Ok(()) +3532 } +3533 +3534 /// Bind on a default route on an unusable port, but set is_required = false. +3535 /// +3536 /// Binding the endpoint succeeds. +3537 #[tokio::test] +3538 #[traced_test] +3539 async fn test_bind_addr_badport_default_notrequired() -> Result { +3540 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3541 let port = socket.local_addr()?.port(); +3542 +3543 let ep = Endpoint::builder(presets::Minimal) +3544 .bind_addr_with_opts( +3545 (Ipv4Addr::LOCALHOST, port), +3546 BindOpts::default().set_is_required(false), +3547 )? +3548 .bind() +3549 .await?; +3550 let bound_sockets = ep.bound_sockets(); +3551 // just the IPv6 default, but no IPv4 bind at all because we replaced the default +3552 // with a bind with an unusable port and set it to not be required. +3553 assert_eq!(bound_sockets.len(), 1); +3554 assert!(bound_sockets[0].is_ipv6()); +3555 Ok(()) +3556 } +3557 +3558 /// Bind on an unusable port, with is_required = false, and no other transports. +3559 /// +3560 /// Binding the endpoint fails with "no valid address available". +3561 #[tokio::test] +3562 #[traced_test] +3563 async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result { +3564 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +3565 let port = socket.local_addr()?.port(); +3566 +3567 let res = Endpoint::builder(presets::Minimal) +3568 .clear_ip_transports() +3569 .bind_addr_with_opts( +3570 (Ipv4Addr::LOCALHOST, port), +3571 BindOpts::default().set_is_required(false), +3572 )? +3573 .bind() +3574 .await; +3575 +3576 assert!(matches!( +3577 res, +3578 Err(BindError::CreateQuicEndpoint { +3579 source: io_error, +3580 .. +3581 }) +3582 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" +3583 )); +3584 Ok(()) +3585 } +3586 +3587 /// Bind with prefix len 0 but set the route as non-default. +3588 #[tokio::test] +3589 #[traced_test] +3590 async fn test_bind_addr_prefix_len_0_not_default() -> Result { +3591 let ep = Endpoint::builder(presets::Minimal) +3592 .bind_addr_with_opts( +3593 (Ipv4Addr::LOCALHOST, 0), +3594 BindOpts::default().set_is_default_route(false), +3595 )? +3596 .bind() +3597 .await?; +3598 let bound_sockets = ep.bound_sockets(); +3599 // The two default wildcard binds plus our additional route (which does not replace the default route +3600 // because we set is_default_route to false explicitly). +3601 assert_eq!(bound_sockets.len(), 3); +3602 assert!( +3603 bound_sockets +3604 .iter() +3605 .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED)) +3606 ); +3607 assert!( +3608 bound_sockets +3609 .iter() +3610 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +3611 ); +3612 assert!( +3613 bound_sockets +3614 .iter() +3615 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +3616 ); +3617 Ok(()) +3618 } +3619 +3620 #[ignore = "flaky"] +3621 #[tokio::test] +3622 #[traced_test] +3623 async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result { +3624 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3625 let qlog = Arc::new(QlogFileGroup::from_env( +3626 "connect_via_relay_becomes_direct_and_sends_direct", +3627 )); +3628 let transfer_size = 1_000_000; +3629 +3630 async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> { +3631 let mut stats = BTreeMap::new(); +3632 while let Some(event) = events.next().await { +3633 if let PathEvent::Closed { +3634 remote_addr, +3635 last_stats, +3636 .. +3637 } = event +3638 { +3639 stats.insert(remote_addr, *last_stats); +3640 } +3641 } +3642 stats +3643 } +3644 +3645 let client = Endpoint::builder(presets::Minimal) +3646 .relay_mode(RelayMode::Custom(relay_map.clone())) +3647 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3648 .transport_config(qlog.create("client")?) +3649 .bind() +3650 .await?; +3651 let server = Endpoint::builder(presets::Minimal) +3652 .relay_mode(RelayMode::Custom(relay_map)) +3653 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3654 .transport_config(qlog.create("server")?) +3655 .alpns(vec![TEST_ALPN.to_vec()]) +3656 .bind() +3657 .await?; +3658 let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url); +3659 let server_task = tokio::spawn(async move { +3660 let incoming = server.accept().await.anyerr()?; +3661 let conn = incoming.await.anyerr()?; +3662 let stats_task = tokio::spawn(collect_stats(conn.path_events())); +3663 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +3664 let msg = recv.read_to_end(transfer_size).await.anyerr()?; +3665 send.write_all(&msg).await.anyerr()?; +3666 send.finish().anyerr()?; +3667 conn.closed().await; +3668 let stats = stats_task.await.expect("stats task panicked"); +3669 Ok::<_, Error>(stats) +3670 }); +3671 +3672 let conn = client.connect(server_addr, TEST_ALPN).await?; +3673 let client_stats_task = tokio::spawn(collect_stats(conn.path_events())); +3674 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +3675 send.write_all(&vec![42u8; transfer_size]).await.anyerr()?; +3676 send.finish().anyerr()?; +3677 recv.read_to_end(transfer_size).await.anyerr()?; +3678 conn.close(0u32.into(), b"thanks, bye!"); +3679 client.close().await; +3680 let client_stats = client_stats_task.await.expect("stats task panicked"); +3681 let server_stats = server_task.await.anyerr()??; +3682 +3683 info!("client stats: {client_stats:#?}"); +3684 info!("server stats: {server_stats:#?}"); +3685 +3686 let client_total_relay_tx = client_stats +3687 .iter() +3688 .filter(|(remote, _stats)| remote.is_relay()) +3689 .map(|(_, stats)| stats.udp_tx.bytes) +3690 .sum::<u64>(); +3691 let client_total_relay_rx = client_stats +3692 .iter() +3693 .filter(|(remote, _stats)| remote.is_relay()) +3694 .map(|(_, stats)| stats.udp_rx.bytes) +3695 .sum::<u64>(); +3696 let server_total_relay_tx = server_stats +3697 .iter() +3698 .filter(|(remote, _stats)| remote.is_relay()) +3699 .map(|(_, stats)| stats.udp_tx.bytes) +3700 .sum::<u64>(); +3701 let server_total_relay_rx = server_stats +3702 .iter() +3703 .filter(|(remote, _stats)| remote.is_relay()) +3704 .map(|(_, stats)| stats.udp_rx.bytes) +3705 .sum::<u64>(); +3706 +3707 info!(?client_total_relay_tx, "total"); +3708 info!(?client_total_relay_rx, "total"); +3709 info!(?server_total_relay_tx, "total"); +3710 info!(?server_total_relay_rx, "total"); +3711 +3712 // We should send/receive only the minorty of traffic via the relay. +3713 assert!(client_total_relay_tx < transfer_size as u64 / 2); +3714 assert!(client_total_relay_rx < transfer_size as u64 / 2); +3715 assert!(server_total_relay_tx < transfer_size as u64 / 2); +3716 assert!(server_total_relay_rx < transfer_size as u64 / 2); +3717 +3718 Ok(()) +3719 } +3720 +3721 /// Tests that correct logs are emitted when connecting two endpoints with same secret keys to a relay. +3722 #[tokio::test] +3723 #[traced_test] +3724 async fn same_endpoint_id_relay() -> Result { +3725 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +3726 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +3727 let secret_key = SecretKey::from_bytes(&rng.random()); +3728 +3729 let client = Endpoint::builder(presets::Minimal) +3730 .relay_mode(RelayMode::Custom(relay_map.clone())) +3731 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3732 .bind() +3733 .instrument(error_span!("ep-client")) +3734 .await?; +3735 +3736 info!("client {}", client.id()); +3737 +3738 // bind ep1 and wait until connected to relay. +3739 let ep1 = Endpoint::builder(presets::Minimal) +3740 .relay_mode(RelayMode::Custom(relay_map.clone())) +3741 .secret_key(secret_key.clone()) +3742 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3743 .alpns(vec![TEST_ALPN.to_vec()]) +3744 .bind() +3745 .instrument(error_span!("ep1")) +3746 .await?; +3747 info!("ep1 bound {:?}", ep1.id()); +3748 ep1.online().await; +3749 info!("ep1 online"); +3750 +3751 let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone()); +3752 +3753 tokio::try_join!( +3754 async { +3755 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3756 let reason = conn.closed().await; +3757 assert!(is_application_closed(&reason, 1)); +3758 n0_error::Ok(()) +3759 }, +3760 async { +3761 let conn = ep1.accept().await.unwrap().await?; +3762 conn.close(1u32.into(), b"bye"); +3763 n0_error::Ok(()) +3764 } +3765 )?; +3766 info!("client connected to ep1"); +3767 +3768 // now start second endpoint with same secret key +3769 let ep2 = Endpoint::builder(presets::Minimal) +3770 .relay_mode(RelayMode::Custom(relay_map)) +3771 .secret_key(secret_key.clone()) +3772 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +3773 .alpns(vec![TEST_ALPN.to_vec()]) +3774 .bind() +3775 .instrument(error_span!("ep2")) +3776 .await?; +3777 info!("ep2 bound {:?}", ep2.id()); +3778 ep2.online().await; +3779 println!("ep2 online"); +3780 +3781 // `online` does not mean that the connection to the home relay was *established*, +3782 // only that the home relay was *chosen* based on the net report probes. +3783 // We need to wait for the connection to be established though, to be sure that new packets +3784 // will be routed to the new endpoint and not to the old endpoint anymore. +3785 // We don't expose being connected to the home relay on the endpoint currently, +3786 // so we resort to log assertions. +3787 // TODO(Frando): Replace once we add a proper API for this. +3788 let expected_log_line = format!( +3789 "ep2:endpoint{{id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected", +3790 ep2.id().fmt_short() +3791 ); +3792 tokio::time::timeout(Duration::from_secs(5), async { +3793 while !logs_contain(&expected_log_line) { +3794 tokio::time::sleep(Duration::from_millis(10)).await +3795 } +3796 }) +3797 .await +3798 .std_context("relay connection did not establish in time")?; +3799 +3800 tokio::try_join!( +3801 async { +3802 let conn = client.connect(addr.clone(), TEST_ALPN).await?; +3803 let reason = conn.closed().await; +3804 assert!(is_application_closed(&reason, 1)); +3805 n0_error::Ok(()) +3806 }, +3807 async { +3808 let conn = ep2.accept().await.unwrap().await?; +3809 conn.close(1u32.into(), b"bye"); +3810 n0_error::Ok(()) +3811 } +3812 )?; +3813 println!("client connected to ep2"); +3814 +3815 // assert that ep1 did not receive a connection +3816 assert!(now_or_never(ep1.accept()).is_none()); +3817 +3818 // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2. +3819 logs_assert(|logs| { +3820 let expected_line = |line: &str| { +3821 line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received") +3822 }; +3823 let count_line_ep1 = logs +3824 .iter() +3825 .filter(|line| line.contains(":ep1:") && expected_line(line)) +3826 .count(); +3827 let count_line_ep2 = logs +3828 .iter() +3829 .filter(|line| line.contains(":ep2:") && expected_line(line)) +3830 .count(); +3831 if count_line_ep1 == 1 && count_line_ep2 == 0 { +3832 Ok(()) +3833 } else { +3834 Err("Logs don't match expectations".to_string()) +3835 } +3836 }); +3837 tokio::join!(ep1.close(), ep2.close(), client.close()); +3838 Ok(()) +3839 } +3840 +3841 fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool { +3842 matches!( +3843 close_reason, +3844 ConnectionError::ApplicationClosed(f) if f.error_code ==code.into() +3845 ) +3846 } +3847 +3848 #[tokio::test] +3849 #[traced_test] +3850 async fn test_closed_endpoint_behaviour() -> Result { +3851 // create endpoint +3852 // call endpoint.close +3853 // ensure methods behave in the expected way +3854 info!("Creating endpoint"); +3855 let ep = Endpoint::builder(presets::N0).bind().await?; +3856 let closed = ep.closed(); +3857 info!("Closing endpoint"); +3858 let now = Instant::now(); +3859 ep.close().await; +3860 info!("Endpoint closed in {:?}", now.elapsed()); +3861 +3862 // Assert that the `closed` cancellation token is now cancelled +3863 assert_eq!(now_or_never(closed), Some(())); +3864 +3865 info!("Set ALPNS fails silently"); +3866 ep.set_alpns(vec![b"test".into()]); +3867 +3868 info!("Insert Relay returns None"); +3869 let relay_config = crate::defaults::staging::default_na_east_relay(); +3870 assert!( +3871 ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config)) +3872 .await +3873 .is_none() +3874 ); +3875 +3876 info!("Remove Relay returns None"); +3877 assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none()); +3878 +3879 info!("Connecting"); +3880 let mut rng = ChaCha8Rng::seed_from_u64(41); +3881 let ep_id = SecretKey::from_bytes(&rng.random()).public(); +3882 +3883 // should likely be an error that states that the +3884 // endpoint is closed instead: +3885 if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err() +3886 { +3887 assert!(matches!( +3888 source, +3889 ConnectWithOptsError::EndpointClosed { .. } +3890 )); +3891 } else { +3892 panic!("unexpected error for connect"); +3893 } +3894 +3895 info!("Accepting!"); +3896 assert!(ep.accept().await.is_none()); +3897 +3898 // this should work +3899 info!("Addr: {:?}", ep.addr()); +3900 +3901 // create watchers to verify they terminate after the endpoint is dropped. +3902 let mut addrs = ep.watch_addr().stream(); +3903 +3904 #[cfg(feature = "unstable-net-report")] +3905 let mut net_reports = { +3906 let net_reports = ep.net_report().stream(); +3907 +3908 // returns None +3909 let net_report = ep.net_report().get(); +3910 info!("last Net report {net_report:?}"); +3911 net_reports +3912 }; +3913 +3914 // this should work +3915 let sockets = ep.bound_sockets(); +3916 info!("Sockets: {sockets:?}"); +3917 +3918 // these should return errors +3919 assert!(ep.dns_resolver().is_err()); +3920 assert!(ep.address_lookup().is_err()); +3921 +3922 #[cfg(feature = "metrics")] +3923 { +3924 // this should work +3925 let metrics = ep.metrics(); +3926 info!("Metrics: {metrics:?}"); +3927 } +3928 +3929 // this should return none +3930 assert!(ep.remote_info(ep_id).await.is_none()); +3931 +3932 // this should fail silently +3933 ep.network_change().await; +3934 +3935 // this should fail silently +3936 ep.set_user_data_for_address_lookup(Some( +3937 UserData::try_from("TEST".to_string()).expect("valid string"), +3938 )); +3939 drop(ep); +3940 // now that the endpoint is dropped, all watchers should terminate. +3941 tokio::time::timeout(Duration::from_secs(1), async { +3942 while let Some(addr) = addrs.next().await { +3943 info!("Addrs stream: {addr:?}"); +3944 } +3945 +3946 #[cfg(feature = "unstable-net-report")] +3947 while let Some(net_report) = net_reports.next().await { +3948 info!("Net report stream: {net_report:?}"); +3949 } +3950 }) +3951 .await +3952 .expect("watchers not closed"); +3953 +3954 info!("Done!"); +3955 Ok(()) +3956 } +3957 +3958 #[tokio::test] +3959 #[traced_test] +3960 async fn test_closed_endpoint_unpolled_accept_fut() -> Result { +3961 info!("Creating endpoint"); +3962 let ep = Endpoint::builder(presets::N0).bind().await?; +3963 +3964 info!("Get accept future"); +3965 let accept_fut = ep.accept(); +3966 +3967 info!("Closing endpoint"); +3968 let now = Instant::now(); +3969 tokio::time::timeout(Duration::from_secs(5), ep.close()) +3970 .await +3971 .expect("Endpoint closes in a reasonable time"); +3972 info!("Endpoint closed in {:?}", now.elapsed()); +3973 +3974 info!("Accept future returns None after the endpoint has closed"); +3975 let incoming = accept_fut.await; +3976 assert!(incoming.is_none()); +3977 Ok(()) +3978 } +3979 +3980 #[tokio::test] +3981 #[traced_test] +3982 async fn test_closed_endpoint_polled_accept_fut() -> Result { +3983 info!("Creating endpoint"); +3984 let ep = Endpoint::builder(presets::N0).bind().await?; +3985 +3986 info!("Run an accept task"); +3987 let ep2 = ep.clone(); +3988 let accept_task = tokio::spawn(async move { +3989 info!("Waiting on Accept"); +3990 let res = ep2.accept().await; +3991 info!("Accept await has returned"); +3992 res +3993 }); +3994 +3995 // Try to ensure the accept future is polled at least once. +3996 tokio::time::sleep(Duration::from_millis(10)).await; +3997 +3998 info!("Closing the endpoint"); +3999 tokio::time::timeout(Duration::from_secs(5), ep.close()) +4000 .await +4001 .expect("Endpoint closes in a reasonable time"); +4002 info!("Endpoint closed"); +4003 +4004 info!("Await the accept task"); +4005 let incoming = accept_task.await.expect("accept task panicked"); +4006 assert!(incoming.is_none()); +4007 +4008 Ok(()) +4009 } +4010 +4011 #[tokio::test] +4012 #[traced_test] +4013 async fn test_endpoint_online_add_relay() -> Result { +4014 let ep = Endpoint::builder(presets::Minimal) +4015 .relay_mode(RelayMode::Custom(RelayMap::empty())) +4016 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4017 .bind() +4018 .await?; +4019 // should not come online without relays. +4020 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +4021 assert!(res.is_err()); +4022 +4023 // should come online after a relay is added. +4024 let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?; +4025 ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap()) +4026 .await; +4027 let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await; +4028 assert!(res.is_ok()); +4029 +4030 // online should still return after endpoint close, if the endpoint was last online +4031 let ep_clone = ep.clone(); +4032 let task = tokio::task::spawn(async move { +4033 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +4034 }); +4035 ep.close().await; +4036 let res = task.await.unwrap(); +4037 assert!(res.is_ok()); +4038 Ok(()) +4039 } +4040 +4041 #[tokio::test] +4042 #[traced_test] +4043 async fn test_endpoint_online_close() -> Result { +4044 let ep = Endpoint::bind(presets::Minimal).await?; +4045 // should not come online without relays. +4046 let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await; +4047 assert!(res.is_err()); +4048 +4049 // online should remain pending after the endpoint is closed. +4050 let ep_clone = ep.clone(); +4051 let task = tokio::task::spawn(async move { +4052 tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await +4053 }); +4054 ep.close().await; +4055 let res = task.await.unwrap(); +4056 assert!(res.is_err()); +4057 Ok(()) +4058 } +4059 +4060 /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`] +4061 /// is admitted to a relay whose access control checks the token only when +4062 /// the token matches. +4063 #[tokio::test] +4064 #[traced_test] +4065 async fn test_endpoint_relay_auth_token() -> Result { +4066 const TOKEN: &str = "valid-token"; +4067 +4068 /// Admits a connection only if it carries the expected auth token. +4069 #[derive(Debug)] +4070 struct TokenAccess(&'static str); +4071 +4072 impl iroh_relay::server::AccessControl for TokenAccess { +4073 async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access { +4074 if request.auth_token().as_deref() == Some(self.0) { +4075 Access::Allow +4076 } else { +4077 Access::Deny { reason: None } +4078 } +4079 } +4080 } +4081 +4082 let access = Arc::new(TokenAccess(TOKEN)); +4083 let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?; +4084 +4085 // Wrong token: the connection attempt fails and last_error reports +4086 // the relay-side denial. +4087 let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None) +4088 .with_auth_token("wrong-token") +4089 .into(); +4090 let bad_ep = Endpoint::builder(presets::Minimal) +4091 .relay_mode(RelayMode::Custom(bad_map)) +4092 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4093 .bind() +4094 .await?; +4095 let mut stream = bad_ep.home_relay_status().stream(); +4096 let auth_err: String = tokio::time::timeout(Duration::from_secs(5), async { +4097 while let Some(status) = stream.next().await { +4098 if let Some(err) = status.iter().filter_map(|s| s.last_error()).next() { +4099 return format!("{err:#}"); +4100 } +4101 } +4102 panic!("home relay stream ended"); +4103 }) +4104 .await +4105 .std_context("waiting for auth error")?; +4106 assert!( +4107 auth_err.contains("not authorized"), +4108 "expected 'not authorized' in error, got: {auth_err}" +4109 ); +4110 +4111 // Correct token: the endpoint reaches the connected state. +4112 let good_map: RelayMap = RelayConfig::new(relay_url, None) +4113 .with_auth_token(TOKEN) +4114 .into(); +4115 let good_ep = Endpoint::builder(presets::Minimal) +4116 .relay_mode(RelayMode::Custom(good_map)) +4117 .ca_tls_config(CaTlsConfig::insecure_skip_verify()) +4118 .bind() +4119 .await?; +4120 tokio::time::timeout(Duration::from_secs(5), good_ep.online()) +4121 .await +4122 .std_context("waiting for endpoint to come online")?; +4123 +4124 Ok(()) +4125 } +4126}
\ No newline at end of file diff --git a/pr/4419/docs/src/iroh_dns_server/http.rs.html b/pr/4419/docs/src/iroh_dns_server/http.rs.html index 9457efa381..1aade09891 100644 --- a/pr/4419/docs/src/iroh_dns_server/http.rs.html +++ b/pr/4419/docs/src/iroh_dns_server/http.rs.html @@ -217,7 +217,7 @@ 217 Json(Health { 218 status: "ok", 219 version: env!("CARGO_PKG_VERSION"), -220 git_hash: option_env!("VERGEN_GIT_SHA").unwrap_or("unknown"), +220 git_hash: "unknown", 221 }) 222} 223 diff --git a/pr/4419/docs/src/iroh_relay/server.rs.html b/pr/4419/docs/src/iroh_relay/server.rs.html index a4087feaf9..c955955029 100644 --- a/pr/4419/docs/src/iroh_relay/server.rs.html +++ b/pr/4419/docs/src/iroh_relay/server.rs.html @@ -1098,7 +1098,7 @@ 1098 let health = Health { 1099 status: "ok", 1100 version: env!("CARGO_PKG_VERSION"), -1101 git_hash: option_env!("VERGEN_GIT_SHA").unwrap_or("unknown"), +1101 git_hash: "unknown", 1102 }; 1103 let body = serde_json::to_string(&health).unwrap_or_else(|_| r#"{"status":"error"}"#.into()); 1104 let body: BytesBody = Box::new(Full::from(body));