diff --git a/pr/3651/docs/iroh/discovery/enum.IntoDiscoveryError.html b/pr/3651/docs/iroh/discovery/enum.IntoDiscoveryError.html index 09bf35edbc..1295bd83eb 100644 --- a/pr/3651/docs/iroh/discovery/enum.IntoDiscoveryError.html +++ b/pr/3651/docs/iroh/discovery/enum.IntoDiscoveryError.html @@ -14,7 +14,7 @@ provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, ) -> Self

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

-

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

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

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

impl Display for IntoDiscoveryError

Source§

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

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

impl Error for IntoDiscoveryError

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

Source§

fn from(value: IntoDiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for IntoDiscoveryError

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 IntoDiscoveryError

§

impl !RefUnwindSafe for IntoDiscoveryError

§

impl Send for IntoDiscoveryError

§

impl Sync for IntoDiscoveryError

§

impl Unpin for IntoDiscoveryError

§

impl !UnwindSafe for IntoDiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

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

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

impl Display for IntoDiscoveryError

Source§

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

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

impl Error for IntoDiscoveryError

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

Source§

fn from(value: IntoDiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for IntoDiscoveryError

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 IntoDiscoveryError

§

impl !RefUnwindSafe for IntoDiscoveryError

§

impl Send for IntoDiscoveryError

§

impl Sync for IntoDiscoveryError

§

impl Unpin for IntoDiscoveryError

§

impl !UnwindSafe for IntoDiscoveryError

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/3651/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/3651/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html index 6ee98a3c34..7f9b6cc36d 100644 --- a/pr/3651/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html +++ b/pr/3651/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/3651/docs/iroh/endpoint/enum.AddEndpointAddrError.html b/pr/3651/docs/iroh/endpoint/enum.AddEndpointAddrError.html index 89103c322f..dd7ffda71d 100644 --- a/pr/3651/docs/iroh/endpoint/enum.AddEndpointAddrError.html +++ b/pr/3651/docs/iroh/endpoint/enum.AddEndpointAddrError.html @@ -12,7 +12,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.
§

Empty

Fields

§meta: Meta

Captured call-site metadata

§

EmptyPruned

Fields

§pruned: usize
§meta: Meta

Captured call-site metadata

§

OwnAddress

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for AddEndpointAddrError

Source§

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

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

impl Display for AddEndpointAddrError

Source§

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

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

impl Error for AddEndpointAddrError

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

Source§

fn from(value: AddEndpointAddrError) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddEndpointAddrError> for ConnectWithOptsError

Source§

fn from(source: AddEndpointAddrError) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddEndpointAddrError

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 AddEndpointAddrError

Source§

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

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

impl Display for AddEndpointAddrError

Source§

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

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

impl Error for AddEndpointAddrError

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

Source§

fn from(value: AddEndpointAddrError) -> AnyError

Converts to this type from the input type.
Source§

impl From<AddEndpointAddrError> for ConnectWithOptsError

Source§

fn from(source: AddEndpointAddrError) -> Self

Converts to this type from the input type.
Source§

impl StackError for AddEndpointAddrError

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/3651/docs/iroh/endpoint/enum.BindError.html b/pr/3651/docs/iroh/endpoint/enum.BindError.html index be026bfa2a..d34fd05294 100644 --- a/pr/3651/docs/iroh/endpoint/enum.BindError.html +++ b/pr/3651/docs/iroh/endpoint/enum.BindError.html @@ -1,4 +1,4 @@ -BindError in iroh::endpoint - Rust

BindError

Enum BindError 

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

BindError

Enum BindError 

Source
#[non_exhaustive]
pub enum BindError { MagicSpawn { source: CreateHandleError, meta: Meta, @@ -9,7 +9,7 @@ }, }

Variants (Non-exhaustive)§

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

MagicSpawn

Fields

§source: CreateHandleError
§meta: Meta

Captured call-site metadata

§

Discovery

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

Source§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

Source§

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

Returns this error as a std error reference.
Source§

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

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

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

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

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

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

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

fn is_transparent(&self) -> bool

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

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

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

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

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

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

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

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

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

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

Source§

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

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

fn description(&self) -> &str

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

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

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

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

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

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

Source§

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

Returns this error as a std error reference.
Source§

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

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

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

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

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

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

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

fn is_transparent(&self) -> bool

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

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

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

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

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

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

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

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

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

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where 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/3651/docs/iroh/endpoint/enum.ConnectError.html b/pr/3651/docs/iroh/endpoint/enum.ConnectError.html index e387e4b4de..0cad540cf3 100644 --- a/pr/3651/docs/iroh/endpoint/enum.ConnectError.html +++ b/pr/3651/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/3651/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/3651/docs/iroh/endpoint/enum.ConnectWithOptsError.html index c51d59834b..2c11ad05f2 100644 --- a/pr/3651/docs/iroh/endpoint/enum.ConnectWithOptsError.html +++ b/pr/3651/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 { AddEndpointAddr { source: AddEndpointAddrError, meta: Meta, @@ -18,7 +18,7 @@

§

SelfConnect

Fields

§meta: Meta

Captured call-site metadata

§

NoAddress

Fields

§meta: Meta

Captured call-site metadata

§

Quinn

Fields

§source: ConnectError
§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<AddEndpointAddrError> for ConnectWithOptsError

Source§

fn from(source: AddEndpointAddrError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: ConnectError) -> 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 From<GetMappingAddressError> for ConnectWithOptsError

Source§

fn from(source: GetMappingAddressError) -> 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<AddEndpointAddrError> for ConnectWithOptsError

Source§

fn from(source: AddEndpointAddrError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: ConnectError) -> 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 From<GetMappingAddressError> for ConnectWithOptsError

Source§

fn from(source: GetMappingAddressError) -> 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/3651/docs/iroh/endpoint/enum.ConnectingError.html b/pr/3651/docs/iroh/endpoint/enum.ConnectingError.html index a142494729..b2001c1c18 100644 --- a/pr/3651/docs/iroh/endpoint/enum.ConnectingError.html +++ b/pr/3651/docs/iroh/endpoint/enum.ConnectingError.html @@ -9,7 +9,7 @@ }, }

Variants (Non-exhaustive)§

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

ConnectionError

Fields

§meta: Meta

Captured call-site metadata

§

HandshakeFailure

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

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§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

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§

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/3651/docs/iroh/endpoint/enum.ConnectionError.html b/pr/3651/docs/iroh/endpoint/enum.ConnectionError.html index a1c7ba5ec5..1bead2f5ad 100644 --- a/pr/3651/docs/iroh/endpoint/enum.ConnectionError.html +++ b/pr/3651/docs/iroh/endpoint/enum.ConnectionError.html @@ -20,7 +20,7 @@ and
§

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

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

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/3651/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3651/docs/iroh/endpoint/enum.DirectAddrType.html index 8674c5acb3..4582fcabbd 100644 --- a/pr/3651/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3651/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

DirectAddrType

Enum DirectAddrType 

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

DirectAddrType

Enum DirectAddrType 

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

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

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

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

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

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

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

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

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

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

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

impl Ord for DirectAddrType

Source§

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

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

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

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

impl Ord for DirectAddrType

Source§

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

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

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

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

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

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

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

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

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

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

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

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

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

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

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

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

impl PartialEq for DirectAddrType

Source§

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

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

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

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

impl PartialOrd for DirectAddrType

Source§

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

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

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

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

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

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

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

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

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

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

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3651/docs/iroh/endpoint/enum.GetMappingAddressError.html b/pr/3651/docs/iroh/endpoint/enum.GetMappingAddressError.html index d62a681b8e..d7b2d30ea0 100644 --- a/pr/3651/docs/iroh/endpoint/enum.GetMappingAddressError.html +++ b/pr/3651/docs/iroh/endpoint/enum.GetMappingAddressError.html @@ -1,4 +1,4 @@ -GetMappingAddressError in iroh::endpoint - Rust

GetMappingAddressError

Enum GetMappingAddressError 

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

GetMappingAddressError

Enum GetMappingAddressError 

Source
#[non_exhaustive]
pub enum GetMappingAddressError { DiscoveryStart { source: DiscoveryError, meta: Meta, @@ -13,7 +13,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.
§

DiscoveryStart

Fields

§meta: Meta

Captured call-site metadata

§

Discover

Fields

§meta: Meta

Captured call-site metadata

§

NoAddress

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for GetMappingAddressError

Source§

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

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

impl Display for GetMappingAddressError

Source§

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

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

impl Error for GetMappingAddressError

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

Source§

fn from(value: GetMappingAddressError) -> AnyError

Converts to this type from the input type.
Source§

impl From<GetMappingAddressError> for ConnectWithOptsError

Source§

fn from(source: GetMappingAddressError) -> Self

Converts to this type from the input type.
Source§

impl StackError for GetMappingAddressError

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 GetMappingAddressError

Source§

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

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

impl Display for GetMappingAddressError

Source§

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

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

impl Error for GetMappingAddressError

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

Source§

fn from(value: GetMappingAddressError) -> AnyError

Converts to this type from the input type.
Source§

impl From<GetMappingAddressError> for ConnectWithOptsError

Source§

fn from(source: GetMappingAddressError) -> Self

Converts to this type from the input type.
Source§

impl StackError for GetMappingAddressError

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/3651/docs/iroh/endpoint/enum.RelayMode.html b/pr/3651/docs/iroh/endpoint/enum.RelayMode.html index eae3665015..1b8e4be031 100644 --- a/pr/3651/docs/iroh/endpoint/enum.RelayMode.html +++ b/pr/3651/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,
@@ -9,9 +9,9 @@
 

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.

-

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 +

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

+

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/3651/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/3651/docs/iroh/endpoint/fn.default_relay_mode.html index 34b83de860..865aa157f1 100644 --- a/pr/3651/docs/iroh/endpoint/fn.default_relay_mode.html +++ b/pr/3651/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/3651/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/3651/docs/iroh/endpoint/fn.force_staging_infra.html index 528d846963..1d5f1283d1 100644 --- a/pr/3651/docs/iroh/endpoint/fn.force_staging_infra.html +++ b/pr/3651/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/3651/docs/iroh/endpoint/index.html b/pr/3651/docs/iroh/endpoint/index.html index 657d47cb6b..e959918d02 100644 --- a/pr/3651/docs/iroh/endpoint/index.html +++ b/pr/3651/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/3651/docs/iroh/endpoint/struct.Builder.html b/pr/3651/docs/iroh/endpoint/struct.Builder.html index 760b86c22a..f875347312 100644 --- a/pr/3651/docs/iroh/endpoint/struct.Builder.html +++ b/pr/3651/docs/iroh/endpoint/struct.Builder.html @@ -2,29 +2,29 @@

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<P: Preset>(preset: P) -> Self

Creates a new Builder using the given Preset.

+

Implementations§

Source§

impl Builder

Source

pub fn new<P: Preset>(preset: P) -> Self

Creates a new Builder using the given Preset.

See presets for more.

Source

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

Applies the given Preset.

-
Source

pub fn empty(relay_mode: RelayMode) -> Self

Creates an empty builder with no discovery services.

-
Source

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

Binds the magic endpoint.

-
Source

pub fn bind_addr_v4(self, bind_addr: SocketAddrV4) -> Self

Sets the IPv4 bind address.

+
Source

pub fn empty(relay_mode: RelayMode) -> Self

Creates an empty builder with no discovery services.

+
Source

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

Binds the magic endpoint.

+
Source

pub fn bind_addr_v4(self, bind_addr: SocketAddrV4) -> Self

Available on non-wasm_browser only.

Sets the IPv4 bind address.

Setting the port to 0 will use a random port. If the port specified is already in use, it will fallback to choosing a random port.

By default will use 0.0.0.0:0 to bind to.

-
Source

pub fn bind_addr_v6(self, bind_addr: SocketAddrV6) -> Self

Sets the IPv6 bind address.

+
Source

pub fn bind_addr_v6(self, bind_addr: SocketAddrV6) -> Self

Available on non-wasm_browser only.

Sets the IPv6 bind address.

Setting the port to 0 will use a random port. If the port specified is already in use, it will fallback to choosing a random port.

By default will use [::]:0 to bind to.

-
Source

pub fn disable_ip(self) -> Self

Removes all IP based transports

-
Source

pub fn disable_relay(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.

+
Source

pub fn disable_ip(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports

+
Source

pub fn disable_relay(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.

@@ -32,11 +32,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_discovery(self) -> Self

Removes all discovery services from the builder.

+
Source

pub fn clear_discovery(self) -> Self

Removes all discovery services from the builder.

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

See the documentation of the crate::discovery::Discovery trait for details.

-
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Adds a discovery mechanism for this endpoint.

+
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Adds a discovery mechanism for this endpoint.

The function discovery will be called on endpoint creation with the configured secret key of the endpoint. Discovery services that need to publish information need @@ -47,13 +47,13 @@ to use this secret key to sign the information.

direct addresses or relay URLs will fail.

To clear all discovery services, use Builder::clear_discovery.

See the documentation of the crate::discovery::Discovery trait for details.

-
Source

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

Sets the initial user-defined data to be published in discovery services for this node.

+
Source

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

Sets the initial user-defined data to be published in discovery services for this node.

When using discovery services, 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 transport_config(self, transport_config: TransportConfig) -> Self

Sets a custom quinn::TransportConfig for this endpoint.

+
Source

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

Sets a custom quinn::TransportConfig 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 @@ -61,31 +61,31 @@ 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::discovery::dns::DnsDiscovery 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 keylog(self, keylog: bool) -> Self

Enables saving the TLS pre-master key for connections.

+
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 insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate features test-utils only.

Skip verification of SSL certificates from relay servers

+
Source

pub fn insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate features test-utils only.

Skip verification of SSL certificates from relay servers

May only be used in tests.

-
Source

pub fn path_selection(self, path_selection: PathSelection) -> Self

Available on crate features test-utils only.

This implies we only use the relay to communicate +

Source

pub fn path_selection(self, path_selection: PathSelection) -> Self

Available on crate features test-utils only.

This implies we only use the relay to communicate and do not attempt to do any hole punching.

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

diff --git a/pr/3651/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/3651/docs/iroh/endpoint/struct.ConnectOptions.html index b78d899cc5..1942f4573f 100644 --- a/pr/3651/docs/iroh/endpoint/struct.ConnectOptions.html +++ b/pr/3651/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 TransportConfig.

-
Source

pub fn with_transport_config( +

Source

pub fn with_transport_config( self, transport_config: Arc<TransportConfig>, ) -> 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/3651/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3651/docs/iroh/endpoint/struct.DirectAddr.html index 7960cfb1ed..20daa3d883 100644 --- a/pr/3651/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3651/docs/iroh/endpoint/struct.DirectAddr.html @@ -1,4 +1,4 @@ -DirectAddr in iroh::endpoint - Rust

DirectAddr

Struct DirectAddr 

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

DirectAddr

Struct DirectAddr 

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

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

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

§addr: SocketAddr

The address.

§typ: DirectAddrType

The origin of this direct address.

-

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

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

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

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

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

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

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

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

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

impl Ord for DirectAddr

Source§

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

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

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

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

impl Ord for DirectAddr

Source§

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

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

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

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

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

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

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

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

impl PartialEq for DirectAddr

Source§

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

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

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

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

impl PartialOrd for DirectAddr

Source§

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

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

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

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

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

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

Restrict a value to a certain interval. Read more

Source§

impl PartialEq for DirectAddr

Source§

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

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

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

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

impl PartialOrd for DirectAddr

Source§

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

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

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

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

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

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

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

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

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

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

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3651/docs/iroh/endpoint/struct.Endpoint.html b/pr/3651/docs/iroh/endpoint/struct.Endpoint.html index 4edbbe7706..b38c4490e8 100644 --- a/pr/3651/docs/iroh/endpoint/struct.Endpoint.html +++ b/pr/3651/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 @@ -16,24 +16,24 @@ the peer are created using the Connection::open_uni and Connection::open_bi functions.

Note that due to the light-weight properties of streams a stream will only be accepted once the initiating peer has sent some data on it.

-

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

+

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

This uses the presets::N0 as the configuration.

-
Source

pub fn empty_builder(relay_mode: RelayMode) -> Builder

Returns the builder for an Endpoint, with an empty configuration.

+
Source

pub fn empty_builder(relay_mode: RelayMode) -> Builder

Returns the builder for an Endpoint, with an empty configuration.

See Builder::empty for details.

-
Source

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

Constructs a default Endpoint and binds it immediately.

+
Source

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

Constructs a default Endpoint and binds it immediately.

Uses the presets::N0 as configuration.

-
Source

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

Sets the list of accepted ALPN protocols.

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

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

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

-
Source

pub async fn connect( +

Source

pub async fn connect( &self, endpoint_addr: impl Into<EndpointAddr>, alpn: &[u8], @@ -53,7 +53,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], @@ -73,17 +73,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. @@ -93,7 +93,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};
@@ -117,7 +117,7 @@ on the internet.

  • the endpoint changes its preferred relay server
  • more addresses are discovered for this endpoint
  • -
    Source

    pub async fn online(&self)

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

    +
    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 was connected, and at least one local IP address is available. Event if no relays are configured, this will still wait for a relay connection.

    @@ -129,16 +129,16 @@ timeout. We recommend using a timeout close to

    To understand if the endpoint has gone back “offline”, you must use the Endpoint::watch_addr method, to get information on the current relay and direct address information.

    -
    Source

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

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

    +
    Source

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

    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 async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration>

    Returns the currently lowest latency for this endpoint.

    +
    Source

    pub async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration>

    Returns the currently lowest latency for this endpoint.

    Will return None if we do not have any address information for the given endpoint_id.

    -
    Source

    pub fn dns_resolver(&self) -> &DnsResolver

    Available on non-wasm_browser only.

    Returns the DNS resolver used in this Endpoint.

    +
    Source

    pub fn dns_resolver(&self) -> &DnsResolver

    Available on non-wasm_browser only.

    Returns the DNS resolver used in this Endpoint.

    See Builder::dns_resolver.

    -
    Source

    pub fn discovery(&self) -> &ConcurrentDiscovery

    Returns the discovery mechanism, if configured.

    +
    Source

    pub fn discovery(&self) -> &ConcurrentDiscovery

    Returns the discovery mechanism, if configured.

    See Builder::discovery.

    -
    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:

    @@ -208,7 +208,7 @@ registry.write().unwrap().register_all(endpoint.metrics()); .std_context("text")?; assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));

    Source

    pub async fn network_change(&self)

    Notifies the system of potential network changes.

    +assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
    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 @@ -216,12 +216,12 @@ function allows for notifying iroh of any potential network changes like 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.

    -
    Source

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

    Sets the initial user-defined data to be published in discovery services for this endpoint.

    +
    Source

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

    Sets the initial user-defined data to be published in discovery services 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 discovery services.

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

    -
    Source

    pub async fn close(&self)

    Closes the QUIC endpoint and the magic socket.

    +
    Source

    pub async fn close(&self)

    Closes the QUIC endpoint and the magic 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.

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

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

    -
    Source

    pub fn is_closed(&self) -> bool

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

    -

    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 +

    Source

    pub fn is_closed(&self) -> bool

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

    +

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

    ClientBuilder

    Struct ClientBuilder 

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

    Build a Client.

    Implementations§

    Source§

    impl ClientBuilder

    Source

    pub fn new( - url: impl Into<RelayUrl>, - secret_key: SecretKey, + url: impl Into<RelayUrl>, + secret_key: SecretKey, dns_resolver: DnsResolver, ) -> Self

    Create a new ClientBuilder

    Source

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

    Source

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

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

    +) -> Result<EndpointInfo, LookupError>

    Looks up endpoint info by EndpointId and origin domain name.

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

    Source

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

    Source

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

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

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

    Looks up endpoint info by EndpointId and origin domain name.

    From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a diff --git a/pr/3651/docs/iroh_relay/endpoint_info/enum.DecodingError.html b/pr/3651/docs/iroh_relay/endpoint_info/enum.DecodingError.html index 86d2c6a6b7..daa76b8135 100644 --- a/pr/3651/docs/iroh_relay/endpoint_info/enum.DecodingError.html +++ b/pr/3651/docs/iroh_relay/endpoint_info/enum.DecodingError.html @@ -8,12 +8,12 @@ meta: Meta, }, InvalidKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, }

    Variants (Non-exhaustive)§

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

    InvalidEncodingZ32

    Fields

    §source: Z32Error
    §meta: Meta

    Captured call-site metadata

    §

    InvalidLength

    Fields

    §len: usize
    §meta: Meta

    Captured call-site metadata

    -
    §

    InvalidKey

    Fields

    §source: KeyParsingError
    §meta: Meta

    Captured call-site metadata

    +
    §

    InvalidKey

    Fields

    §meta: Meta

    Captured call-site metadata

    Trait Implementations§

    Source§

    impl Debug for DecodingError

    Source§

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

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

    impl Display for DecodingError

    Source§

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

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

    impl Error for DecodingError

    Source§

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

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

    fn description(&self) -> &str

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

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

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

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

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

    impl From<DecodingError> for AnyError

    Source§

    fn from(value: DecodingError) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<DecodingError> for ParseError

    Source§

    fn from(source: DecodingError) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for DecodingError

    Source§

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

    Returns this error as a std error reference.
    Source§

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

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

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

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

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

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

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

    fn is_transparent(&self) -> bool

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

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

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

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

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

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

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

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

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

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3651/docs/iroh_relay/endpoint_info/index.html b/pr/3651/docs/iroh_relay/endpoint_info/index.html index 4a43824b7c..9de61c4142 100644 --- a/pr/3651/docs/iroh_relay/endpoint_info/index.html +++ b/pr/3651/docs/iroh_relay/endpoint_info/index.html @@ -1,5 +1,5 @@ -iroh_relay::endpoint_info - Rust

    Module endpoint_info

    Module endpoint_info 

    Source
    Expand description

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

    -

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

    Module endpoint_info

    Module endpoint_info 

    Source
    Expand description

    Support for handling DNS resource records for dialing by EndpointId.

    +

    Dialing by EndpointId is supported by iroh endpoints publishing Pkarr records to DNS servers or the Mainline DHT. This module supports creating and parsing these records.

    DNS records are published under the following names:

    _iroh.<z32-endpoint-id>.<origin-domain> TXT

    @@ -8,7 +8,7 @@ servers or the Mainline DHT. This module supports creating and parsing these re

    _iroh is the record name as defined by IROH_TXT_NAME.

  • -

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

    +

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

  • <origin-domain> is the domain name of the publishing DNS server, @@ -23,12 +23,12 @@ servers or the Mainline DHT. This module supports creating and parsing these re in RFC1464. The following attributes are defined:

    • -

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

      +

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

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

    -
  • Structs§

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

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

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

    Structs§

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

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    EndpointIdExt
    Extension methods for EndpointId to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.
    \ No newline at end of file diff --git a/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointData.html b/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointData.html index 2d50b3f754..b6e5f6b39f 100644 --- a/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointData.html +++ b/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointData.html @@ -1,23 +1,23 @@ EndpointData in iroh_relay::endpoint_info - Rust

    EndpointData

    Struct EndpointData 

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

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

    -

    This includes an optional [RelayUrl], a set of direct addresses, and the optional +

    This includes an optional RelayUrl, a set of direct addresses, and the optional UserData, a string that can be set by applications and is not parsed or used by iroh itself.

    -

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

    -

    Implementations§

    Source§

    impl EndpointData

    Source

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

    Creates a new EndpointData with a relay URL and a set of direct addresses.

    -
    Source

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

    Sets the relay URL and returns the updated endpoint data.

    +

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

    +

    Implementations§

    Source§

    impl EndpointData

    Source

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

    Creates a new EndpointData with a relay URL and a set of direct addresses.

    +
    Source

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

    Sets the relay URL and returns the updated endpoint data.

    Source

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

    Sets the direct addresses and returns the updated endpoint data.

    Source

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

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

    -
    Source

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

    Returns the relay URL of the endpoint.

    +
    Source

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

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

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

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

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

    Add addresses to the endpoint data.

    +
    Source

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

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

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

    Returns the full list of all known addresses

    +
    Source

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

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointData

    Source§

    fn clone(&self) -> EndpointData

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

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

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

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

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

    Trait Implementations§

    Source§

    impl Clone for EndpointData

    Source§

    fn clone(&self) -> EndpointData

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

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

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

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

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

    impl Eq for EndpointData

    Source§

    impl StructuralPartialEq for EndpointData

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html b/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html index 7bdb2a8793..c6a136c7d7 100644 --- a/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html +++ b/pr/3651/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html @@ -1,17 +1,17 @@ EndpointInfo in iroh_relay::endpoint_info - Rust

    EndpointInfo

    Struct EndpointInfo 

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

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

    -

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

    -

    Fields§

    §endpoint_id: EndpointId

    The [EndpointId] of the endpoint this is about.

    +

    This struct couples a EndpointId with its associated EndpointData.

    +

    Fields§

    §endpoint_id: EndpointId

    The EndpointId of the endpoint this is about.

    §data: EndpointData

    The information published about the endpoint.

    -

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    -
    Source

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

    Creates a new EndpointInfo from its parts.

    -
    Source

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

    Sets the relay URL and returns the updated endpoint info.

    +

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    +
    Source

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

    Creates a new EndpointInfo from its parts.

    +
    Source

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

    Sets the relay URL and returns the updated endpoint info.

    Source

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

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

    Source

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

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

    -
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

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

    -
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a [EndpointAddr] without cloning.

    +
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

    Converts into a EndpointAddr by cloning the needed fields.

    +
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a EndpointAddr without cloning.

    Source

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

    Parses a EndpointInfo from a [pkarr::SignedPacket].

    Source

    pub fn to_pkarr_signed_packet( &self, - secret_key: &SecretKey, + secret_key: &SecretKey, ttl: u32, ) -> Result<SignedPacket, EncodingError>

    Creates a [pkarr::SignedPacket].

    -

    This constructs a DNS packet and signs it with a [SecretKey].

    +

    This constructs a DNS packet and signs it with a SecretKey.

    Source

    pub fn to_txt_strings(&self) -> Vec<String>

    Converts into a list of {key}={value} strings.

    -

    Methods from Deref<Target = EndpointData>§

    Source

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

    Returns the relay URL of the endpoint.

    +

    Methods from Deref<Target = EndpointData>§

    Source

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

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

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

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

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

    Add addresses to the endpoint data.

    +
    Source

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

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

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

    Returns the full list of all known addresses

    +
    Source

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

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

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

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

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

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

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

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

    Trait Implementations§

    Source§

    impl Clone for EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

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

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

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

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

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

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

    impl Eq for EndpointInfo

    Source§

    impl StructuralPartialEq for EndpointInfo

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3651/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html b/pr/3651/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html index 2cfafe8d14..103efb1882 100644 --- a/pr/3651/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html +++ b/pr/3651/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html @@ -1,9 +1,9 @@ EndpointIdExt in iroh_relay::endpoint_info - Rust

    EndpointIdExt

    Trait EndpointIdExt 

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

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

    Expand description

    Extension methods for EndpointId to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.

    -

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a [EndpointId] in z-base-32 encoding.

    -
    Source

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

    Parses a [EndpointId] from z-base-32 encoding.

    -

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl EndpointIdExt for EndpointId

    Source§

    fn to_z32(&self) -> String

    Source§

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

    Implementors§

    \ No newline at end of file +

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a EndpointId in z-base-32 encoding.

    +
    Source

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

    Parses a EndpointId from z-base-32 encoding.

    +

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl EndpointIdExt for EndpointId

    Implementors§

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

    QAD support and expose metrics.

    -

    Re-exports§

    pub use protos::relay::MAX_PACKET_SIZE;

    Modules§

    client
    Exposes Client, which allows to establish connections to a relay server.
    defaults
    Default values used in the relay.
    dnsNon-wasm_browser
    DNS resolver
    endpoint_info
    Support for handling DNS resource records for dialing by [EndpointId].
    http
    HTTP-specific constants for the relay server and client.
    protos
    Protocols used by the iroh-relay
    quic
    Create a QUIC server that accepts connections +

    Re-exports§

    pub use protos::relay::MAX_PACKET_SIZE;

    Modules§

    client
    Exposes Client, which allows to establish connections to a relay server.
    defaults
    Default values used in the relay.
    dnsNon-wasm_browser
    DNS resolver
    endpoint_info
    Support for handling DNS resource records for dialing by EndpointId.
    http
    HTTP-specific constants for the relay server and client.
    protos
    Protocols used by the iroh-relay
    quic
    Create a QUIC server that accepts connections for QUIC address discovery.
    serverserver
    A fully-fledged iroh-relay server over HTTP or HTTPS.

    Structs§

    PingTracker
    Tracks pings on a single relay connection.
    RelayConfig
    Information on a specific relay server.
    RelayMap
    List of relay server configurations to be used in an iroh endpoint.
    RelayQuicConfig
    Configuration for speaking to the QUIC endpoint on the relay server to do QUIC address discovery.
    \ No newline at end of file diff --git a/pr/3651/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html b/pr/3651/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html index c1f432fee0..e07e71e1c5 100644 --- a/pr/3651/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html +++ b/pr/3651/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html @@ -2,7 +2,7 @@ Ping([u8; 8]), Pong([u8; 8]), Datagrams { - dst_endpoint_id: EndpointId, + dst_endpoint_id: EndpointId, datagrams: Datagrams, }, }
    Expand description

    Messages that clients send to relays.

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

    Pong([u8; 8])

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

    §

    Datagrams

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

    -

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    +

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    §datagrams: Datagrams

    The datagrams and related metadata to relay.

    Trait Implementations§

    Source§

    impl Clone for ClientToRelayMsg

    Source§

    fn clone(&self) -> ClientToRelayMsg

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for ClientToRelayMsg

    Source§

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

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

    impl PartialEq for ClientToRelayMsg

    Source§

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

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

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

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

    impl Sink<ClientToRelayMsg> for Client

    Source§

    type Error = SendError

    The type of value produced by the sink when an error occurs.
    Source§

    fn poll_ready( diff --git a/pr/3651/docs/iroh_relay/protos/relay/enum.Error.html b/pr/3651/docs/iroh_relay/protos/relay/enum.Error.html index 9412db9658..27fca77b09 100644 --- a/pr/3651/docs/iroh_relay/protos/relay/enum.Error.html +++ b/pr/3651/docs/iroh_relay/protos/relay/enum.Error.html @@ -17,7 +17,7 @@ meta: Meta, }, InvalidPublicKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, InvalidFrame { @@ -39,12 +39,12 @@

    §

    FrameTooLarge

    Fields

    §frame_len: usize
    §meta: Meta

    Captured call-site metadata

    §

    SerDe

    Fields

    §source: Error
    §meta: Meta

    Captured call-site metadata

    §

    FrameTypeError

    Fields

    §meta: Meta

    Captured call-site metadata

    -
    §

    InvalidPublicKey

    Fields

    §source: KeyParsingError
    §meta: Meta

    Captured call-site metadata

    +
    §

    InvalidPublicKey

    Fields

    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrame

    Fields

    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrameType

    Fields

    §frame_type: FrameType
    §meta: Meta

    Captured call-site metadata

    §

    InvalidProtocolMessageEncoding

    Fields

    §source: Utf8Error
    §meta: Meta

    Captured call-site metadata

    §

    TooSmall

    Fields

    §meta: Meta

    Captured call-site metadata

    -

    Trait Implementations§

    Source§

    impl Debug for Error

    Source§

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

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

    impl Display for Error

    Source§

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

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

    impl Error for Error

    Source§

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

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

    fn description(&self) -> &str

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

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

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

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

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

    impl From<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

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

    Returns this error as a std error reference.
    Source§

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

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

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

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

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

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

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

    fn is_transparent(&self) -> bool

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

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

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

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

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

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

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

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

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

    Auto Trait Implementations§

    §

    impl Freeze for Error

    §

    impl !RefUnwindSafe for Error

    §

    impl Send for Error

    §

    impl Sync for Error

    §

    impl Unpin for Error

    §

    impl !UnwindSafe for Error

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where +

    Trait Implementations§

    Source§

    impl Debug for Error

    Source§

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

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

    impl Display for Error

    Source§

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

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

    impl Error for Error

    Source§

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

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

    fn description(&self) -> &str

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

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

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

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

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

    impl From<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

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

    Returns this error as a std error reference.
    Source§

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

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

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

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

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

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

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

    fn is_transparent(&self) -> bool

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

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

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

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

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

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

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

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

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

    Auto Trait Implementations§

    §

    impl Freeze for Error

    §

    impl !RefUnwindSafe for Error

    §

    impl Send for Error

    §

    impl Sync for Error

    §

    impl Unpin for Error

    §

    impl !UnwindSafe for Error

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

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

    §

    fn implicit( diff --git a/pr/3651/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3651/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html index d3ffa9e17e..7858ef2c19 100644 --- a/pr/3651/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html +++ b/pr/3651/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html @@ -1,9 +1,9 @@ RelayToClientMsg in iroh_relay::protos::relay - Rust

    RelayToClientMsg

    Enum RelayToClientMsg 

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

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

    Variants§

    §

    Datagrams

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

    -

    Fields

    §remote_endpoint_id: EndpointId

    The [EndpointId] of the original sender.

    +

    Fields

    §remote_endpoint_id: EndpointId

    The EndpointId of the original sender.

    §datagrams: Datagrams

    The datagrams and related metadata.

    -
    §

    EndpointGone(EndpointId)

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

    §

    EndpointGone(EndpointId)

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

    §

    Health

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

    Fields

    §problem: String

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

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

    AccessConfig

    Enum AccessConfig 

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

    Controls which endpoints are allowed to use the relay.

    Variants§

    §

    Everyone

    Everyone

    -
    §

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

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

    -

    Implementations§

    Source§

    impl AccessConfig

    Source

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

    Is this endpoint allowed?

    +
    §

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

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

    +

    Implementations§

    Source§

    impl AccessConfig

    Source

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

    Is this endpoint allowed?

    Trait Implementations§

    Source§

    impl Debug for AccessConfig

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3651/docs/iroh_relay/server/struct.Server.html b/pr/3651/docs/iroh_relay/server/struct.Server.html index 735121f652..2d8987915e 100644 --- a/pr/3651/docs/iroh_relay/server/struct.Server.html +++ b/pr/3651/docs/iroh_relay/server/struct.Server.html @@ -17,9 +17,9 @@ case there is an error in the server before it is shut down.

    Source

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

    The socket address the HTTP server is listening on.

    Source

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

    The socket address the QUIC server is listening on.

    Source

    pub fn certificates(&self) -> Option<Vec<CertificateDer<'static>>>

    The certificates chain if configured with manual TLS certificates.

    -
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https [RelayUrl].

    +
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https RelayUrl.

    This uses Self::https_addr so it’s mostly useful for local development.

    -
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http [RelayUrl].

    +
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http RelayUrl.

    This uses Self::http_addr so it’s mostly useful for local development.

    Source

    pub fn metrics(&self) -> &RelayMetrics

    Returns the metrics collected in the relay server.

    Trait Implementations§

    Source§

    impl Debug for Server

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Server

    §

    impl RefUnwindSafe for Server

    §

    impl Send for Server

    §

    impl Sync for Server

    §

    impl Unpin for Server

    §

    impl UnwindSafe for Server

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where diff --git a/pr/3651/docs/iroh_relay/struct.RelayConfig.html b/pr/3651/docs/iroh_relay/struct.RelayConfig.html index 90f09dfa2e..4ba3e30d09 100644 --- a/pr/3651/docs/iroh_relay/struct.RelayConfig.html +++ b/pr/3651/docs/iroh_relay/struct.RelayConfig.html @@ -1,14 +1,14 @@ RelayConfig in iroh_relay - Rust

    RelayConfig

    Struct RelayConfig 

    Source
    pub struct RelayConfig {
    -    pub url: RelayUrl,
    +    pub url: RelayUrl,
         pub quic: Option<RelayQuicConfig>,
     }
    Expand description

    Information on a specific relay server.

    Includes the Url where it can be dialed.

    -

    Fields§

    §url: RelayUrl

    The [RelayUrl] where this relay server can be dialed.

    +

    Fields§

    §url: RelayUrl

    The RelayUrl where this relay server can be dialed.

    §quic: Option<RelayQuicConfig>

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

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

    Trait Implementations§

    Source§

    impl Clone for RelayConfig

    Source§

    fn clone(&self) -> RelayConfig

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayConfig

    Source§

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

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

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

    Source§

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

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

    impl Display for RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

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

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

    fn max(self, other: Self) -> Self
    where + __D: Deserializer<'de>,

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

    impl Display for RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

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

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

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

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

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

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

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

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

    impl PartialEq for RelayConfig

    Source§

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

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

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

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3651/docs/iroh_relay/struct.RelayMap.html b/pr/3651/docs/iroh_relay/struct.RelayMap.html index 4e43ef401d..3a6131c7c6 100644 --- a/pr/3651/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3651/docs/iroh_relay/struct.RelayMap.html @@ -8,28 +8,28 @@ or by creating an empty relay map with let relay2 = RelayUrl::from_str("https://relay2.example.org").unwrap(); let map = RelayMap::from_iter(vec![relay1, relay2]);

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn empty() -> Self

    Creates an empty relay map.

    Source

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

    Returns the URLs of all servers in this relay map.

    + T: FromIterator<RelayUrl>,

    Returns the URLs of all servers in this relay map.

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

    Source

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

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

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

    -
    Source

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

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

    -
    Source

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

    Returns the config for a relay.

    +
    Source

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

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

    +
    Source

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

    Returns the config for a relay.

    Source

    pub fn len(&self) -> usize

    Returns the number of relays in this relay map.

    Source

    pub fn is_empty(&self) -> bool

    Returns true if this relay map is empty.

    Source

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

    Inserts a new relay into the relay map.

    -
    Source

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

    Removes an existing relay by its URL.

    +
    Source

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

    Removes an existing relay by its URL.

    Source

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

    Extends this RelayMap with another one.

    -

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

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

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

    impl Display for RelayMap

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a [RelayUrl].

    +

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

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

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

    impl Display for RelayMap

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a RelayUrl.

    The RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    -
    Source§

    impl FromIterator<Arc<RelayConfig>> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

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

    Creates a RelayMap from an iterator of [RelayUrl].

    +
    Source§

    impl FromIterator<Arc<RelayConfig>> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

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

    Creates a RelayMap from an iterator of RelayUrl.

    The RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    Source§

    impl PartialEq for RelayMap

    Source§

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

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

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

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3651/docs/search.index/path/d0d8eb1807d8.js b/pr/3651/docs/search.index/path/d0d8eb1807d8.js new file mode 100644 index 0000000000..f8d00a0115 --- /dev/null +++ b/pr/3651/docs/search.index/path/d0d8eb1807d8.js @@ -0,0 +1 @@ +rd_("f[1,\"\"]0Al[10,\"core::cmp\",\"core::cmp\"]Al[10,\"core::ops\",\"core::ops\"]Ce[5,\"clap_builder::util::id\",\"clap_builder::util::id\"]Bd[15,\"iroh_relay::client::DialError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Cg[5,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Eg[5,\"tower_http::follow_redirect::policy::or\",\"tower_http::follow_redirect::policy::or\"]77Ei[5,\"tower_http::follow_redirect::policy::and\",\"tower_http::follow_redirect::policy::and\"]A`[10,\"core::any\"]Ao[5,\"alloc::sync\",\"alloc::sync\"]Ba[5,\"alloc::boxed\",\"alloc::boxed\"]Cb[10,\"bytes::buf::buf_impl\",\"bytes::buf::buf_impl\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]9Am[5,\"n0_watcher\",\"n0_watcher\"]Am[5,\"iroh_bench\",\"iroh_bench\"]Bg[5,\"iroh_bench::s2n\",\"iroh_bench::s2n\"]A`[10,\"core::cmp\"]Ak[5,\"core::pin\",\"core::pin\"]Bg[15,\"iroh_relay::client::ConnectError\"]o[5,\"url\",\"url\"]Am[5,\"alloc::vec\",\"alloc::vec\"]Al[2,\"iroh::discovery::pkarr\"]j[2,\"iroh\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]00Ao[2,\"iroh::net_report::options\"]o[2,\"iroh_base\"]f[0,\"\"]A`[2,\"iroh_bench\"]4Ak[2,\"iroh_dns_server::http\"]555Ak[10,\"clap_builder::derive\"]>Af[10,\"core::ops::drop\"]Ad[10,\"core::convert\"]Aa[10,\"core::hash\"]1g[17,\"\"]Ci[5,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Be[5,\"n0_error::meta\",\"n0_error::meta\"]Cc[5,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Dg[5,\"hickory_proto::rr::domain::name\",\"hickory_proto::rr::domain::name\"]Ak[5,\"std::path\",\"std::path\"]Am[15,\"iroh::endpoint::Source\"]Bi[6,\"core::task::poll\",\"core::task::poll\"]Bb[10,\"core::marker\",\"core::marker\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]Ac[10,\"futures_sink\"]2Bf[15,\"iroh::discovery::DiscoveryError\"]Bj[15,\"iroh::discovery::IntoDiscoveryError\"]Bb[15,\"iroh::protocol::AcceptError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ah[10,\"ppv_lite86::types\"]f[1,\"\"]f[3,\"\"]Ah[2,\"iroh_relay::client\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]A`[2,\"iroh_bench\"]4Ae[2,\"iroh::discovery\"]Ad[2,\"iroh::defaults\"]4Bk[2,\"iroh_quinn_proto::connection::streams\"]88Ad[10,\"core::convert\"]Ca[8,\"futures_lite::future\",\"futures_lite::future\"]Ca[8,\"futures_lite::stream\",\"futures_lite::stream\"]Ba[5,\"bytes::bytes\",\"bytes::bytes\"]Ad[5,\"iroh::endpoint\"]Ab[10,\"core::clone\"]Cg[6,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Ao[10,\"iroh_quinn_proto::coding\"]A`[10,\"core::fmt\"]Ag[10,\"core::ops::deref\"]Bk[15,\"iroh::endpoint::AddEndpointAddrError\"]Ak[5,\"core::fmt\",\"core::fmt\"]Ab[10,\"core::error\"]Be[5,\"std::io::error\",\"std::io::error\"]Bc[6,\"rustls::error\",\"rustls::error\"]Ba[8,\"clap_builder\",\"clap_builder\"]Bi[5,\"signature::error\",\"signature::error\"]Af[2,\"iroh_relay::quic\"]Bc[2,\"iroh_relay::protos::handshake\"]Ao[2,\"iroh_relay::protos::relay\"]Ba[5,\"hyper::error\",\"hyper::error\"]Ee[6,\"iroh_quinn_proto::transport_parameters\",\"iroh_quinn_proto::transport_parameters\"]Be[5,\"reqwest::error\",\"reqwest::error\"]Bg[6,\"postcard::error\",\"postcard::error\"]Cg[6,\"tokio_websockets::error\",\"tokio_websockets::error\"]Bi[6,\"iroh_relay::quic\",\"iroh_relay::quic\"]Dc[6,\"iroh_relay::protos::handshake\",\"iroh_relay::protos::handshake\"]Ck[6,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ca[6,\"iroh::net_report\",\"iroh::net_report::probes\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bb[10,\"core::marker\",\"core::marker\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]1g[17,\"\"]f[1,\"\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_bench\"]34Ae[2,\"iroh_dns_server\"]1Bb[2,\"iroh_quinn_proto::connection\"]166Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ac[10,\"core::borrow\"]C`[10,\"bytes::buf::buf_mut\",\"bytes::buf::buf_mut\"]Bc[5,\"pkarr::client\",\"pkarr::client\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ba[5,\"async_compat\",\"async_compat\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Cb[10,\"core::future::future\",\"core::future::future\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]An[10,\"core::hash\",\"core::hash\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Bm[6,\"core::net::ip_addr\",\"core::net::ip_addr\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Bh[10,\"reloadable_core\",\"reloadable_core\"]Be[15,\"iroh_relay::server::CertConfig\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Ad[5,\"iroh::endpoint\"]Ba[6,\"core::option\",\"core::option\"]g[17,\"\"]E`[10,\"tower_http::follow_redirect::policy\",\"tower_http::follow_redirect::policy\"]Ch[10,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Co[5,\"hickory_proto::rr::resource\",\"hickory_proto::rr::resource\"]Ca[5,\"iroh::net_report\",\"iroh::net_report::report\"]Ak[8,\"core::fmt\",\"core::fmt\"]Ba[6,\"core::result\",\"core::result\"]Be[8,\"std::io::error\",\"std::io::error\"]Ai[8,\"n0_error\",\"n0_error\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Cg[5,\"iroh_dns_server::server\",\"iroh_dns_server::server\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ad[2,\"iroh::endpoint\"]Cd[6,\"iroh::endpoint\",\"iroh::magicsock::endpoint_map\"]Ak[10,\"futures_core::stream\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Bc[5,\"alloc::string\",\"alloc::string\"]Ak[5,\"core::any\",\"core::any\"]Ci[5,\"iroh_quinn_proto::varint\",\"iroh_quinn_proto::varint\"]Ad[5,\"iroh::endpoint\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]A`[2,\"iroh_relay\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh_dns_server\"]1Af[2,\"iroh::net_report\"]40412Ae[10,\"iroh::endpoint\"]Bg[8,\"iroh_relay::dns\",\"iroh_relay::dns\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]De[5,\"clap_builder::builder::command\",\"clap_builder::builder::command\"]Bc[15,\"iroh::endpoint::ConnectError\"]An[15,\"iroh_relay::quic::Error\"]Bi[5,\"core::task::wake\",\"core::task::wake\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ad[10,\"core::default\"]A`[10,\"core::fmt\"]Bm[5,\"tokio::time::error\",\"tokio::time::error\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Bc[10,\"axum_core::extract::from_ref\"]Ah[10,\"core::str::traits\"]Ak[5,\"std::time\",\"std::time\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Cb[5,\"iroh::net_report\",\"iroh::net_report::metrics\"]Ci[5,\"iroh_dns_server::metrics\",\"iroh_dns_server::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ad[5,\"iroh::endpoint\"]Cg[5,\"iroh::net_report\",\"iroh::net_report::options::imp\"]Ak[5,\"std::path\",\"std::path\"]Bk[5,\"dyn_clone::sealed\",\"dyn_clone::sealed\"]Bo[5,\"tokio::io::read_buf\",\"tokio::io::read_buf\"]Eg[5,\"hickory_server::server::request_handler\",\"hickory_server::server::request_handler\"]B`[15,\"iroh_relay::dns::DnsError\"]Al[10,\"reqwest::dns::resolve\"]Cg[5,\"tokio::runtime::runtime\",\"tokio::runtime::runtime\"]Cj[10,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Bd[15,\"iroh_relay::client::DialError\"]4Ad[10,\"alloc::borrow\"]Ad[10,\"core::convert\"]0Bg[15,\"iroh_relay::client::ConnectError\"]k[10,\"iroh\"]>j[2,\"iroh\"]Af[2,\"iroh::net_report\"]Ah[2,\"iroh_relay::server\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]Ad[2,\"iroh::endpoint\"]Ad[2,\"iroh::defaults\"]Bb[2,\"iroh_quinn_proto::connection\"]5Ad[5,\"iroh::endpoint\"]Bc[5,\"n0_error::any\",\"n0_error::any\"]Ce[5,\"iroh_dns_server::state\",\"iroh_dns_server::state\"]De[5,\"alloc::collections::btree::set\",\"alloc::collections::btree::set\"]Ch[6,\"iroh_dns_server::http\",\"iroh_dns_server::http::tls\"]Am[6,\"iroh_bench\",\"iroh_bench\"]Ag[10,\"core::ops::deref\"]Bm[15,\"iroh::endpoint::GetMappingAddressError\"]Ae[2,\"iroh_relay::dns\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]Am[5,\"core::time\",\"core::time\"]A`[10,\"dyn_clone\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]Ca[5,\"iroh_quinn::endpoint\",\"iroh_quinn::endpoint\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Bg[6,\"n0_error::error\",\"n0_error::error\"]3Ca[5,\"iroh_quinn::incoming\",\"iroh_quinn::incoming\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[5,\"core::net::ip_addr\",\"core::net::ip_addr\"]0Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Am[10,\"iroh_metrics::iterable\"]Db[10,\"core::iter::traits::iterator\",\"core::iter::traits::iterator\"]Am[15,\"iroh::endpoint::Source\"]An[10,\"n0_watcher\",\"n0_watcher\"]Ak[6,\"core::cmp\",\"core::cmp\"]Dd[5,\"iroh::endpoint\",\"iroh::magicsock::endpoint_map::endpoint_state\"]Bd[15,\"iroh_relay::client::RecvError\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Ca[5,\"iroh_base::relay_url\",\"iroh_base::relay_url\"]2Bf[5,\"iroh_base\",\"iroh_base::relay_url\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Bh[10,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ad[5,\"iroh::endpoint\"]Ad[10,\"alloc::string\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]3Ae[5,\"iroh::discovery\"]1o[6,\"z32\",\"z32\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]1A`[2,\"iroh_quinn\"]2Ah[2,\"iroh_relay::server\"]B`[2,\"iroh::net_report::defaults\"]:Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Ci[5,\"tokio_rustls_acme::state\",\"tokio_rustls_acme::state\"]Ad[2,\"iroh::endpoint\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Al[10,\"tokio::io::async_read\"]2Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Ac[10,\"core::borrow\"]Ac[10,\"async_compat\"]Al[10,\"rand_core\",\"rand_core\"]Cb[15,\"iroh_relay::protos::relay::ClientToRelayMsg\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Ck[5,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ah[2,\"iroh_relay::client\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Am[15,\"iroh::endpoint::Source\"]B`[15,\"iroh::endpoint::BindError\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]0Ak[5,\"core::fmt\",\"core::fmt\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]Bg[15,\"iroh_relay::client::ConnectError\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ba[5,\"hdrhistogram\",\"hdrhistogram\"]Co[5,\"tokio::runtime::task::error\",\"tokio::runtime::task::error\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bm[15,\"iroh::endpoint::GetMappingAddressError\"]Bf[15,\"iroh::discovery::DiscoveryError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]A`[10,\"core::cmp\"]Ad[5,\"iroh::endpoint\"]An[10,\"crossbeam_epoch::atomic\"]Bj[10,\"tower_http::follow_redirect::policy\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]j[5,\"iroh\"]B`[5,\"iroh_base\",\"iroh_base::key\"]Af[10,\"core::ops::drop\"]Ad[10,\"core::convert\"]Aa[10,\"core::hash\"]1g[17,\"\"]Ci[5,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Be[5,\"n0_error::meta\",\"n0_error::meta\"]Cc[5,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Dg[5,\"hickory_proto::rr::domain::name\",\"hickory_proto::rr::domain::name\"]Ak[5,\"std::path\",\"std::path\"]Am[15,\"iroh::endpoint::Source\"]Bi[6,\"core::task::poll\",\"core::task::poll\"]Bb[10,\"core::marker\",\"core::marker\"]Bi[6,\"iroh_quinn_proto\",\"iroh_quinn_proto\"]Ac[10,\"futures_sink\"]2Bf[15,\"iroh::discovery::DiscoveryError\"]Bj[15,\"iroh::discovery::IntoDiscoveryError\"]Bb[15,\"iroh::protocol::AcceptError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ah[10,\"ppv_lite86::types\"]f[1,\"\"]f[3,\"\"]Ah[2,\"iroh_relay::client\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]A`[2,\"iroh_bench\"]4Ae[2,\"iroh::discovery\"]Ad[2,\"iroh::defaults\"]4Bk[2,\"iroh_quinn_proto::connection::streams\"]88Bd[10,\"core::convert\",\"core::convert\"]Ca[8,\"futures_lite::future\",\"futures_lite::future\"]Ca[8,\"futures_lite::stream\",\"futures_lite::stream\"]Ba[5,\"bytes::bytes\",\"bytes::bytes\"]Ad[5,\"iroh::endpoint\"]Ab[10,\"core::clone\"]Cg[6,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]Ao[10,\"iroh_quinn_proto::coding\"]A`[10,\"core::fmt\"]Ag[10,\"core::ops::deref\"]Bk[15,\"iroh::endpoint::AddEndpointAddrError\"]Ak[5,\"core::fmt\",\"core::fmt\"]Ab[10,\"core::error\"]Be[5,\"std::io::error\",\"std::io::error\"]Bc[6,\"rustls::error\",\"rustls::error\"]Ba[8,\"clap_builder\",\"clap_builder\"]Bi[5,\"signature::error\",\"signature::error\"]Af[2,\"iroh_relay::quic\"]Bc[2,\"iroh_relay::protos::handshake\"]Ao[2,\"iroh_relay::protos::relay\"]Ba[5,\"hyper::error\",\"hyper::error\"]Ee[6,\"iroh_quinn_proto::transport_parameters\",\"iroh_quinn_proto::transport_parameters\"]Be[5,\"reqwest::error\",\"reqwest::error\"]Bg[6,\"postcard::error\",\"postcard::error\"]Cg[6,\"tokio_websockets::error\",\"tokio_websockets::error\"]Bi[6,\"iroh_relay::quic\",\"iroh_relay::quic\"]Dc[6,\"iroh_relay::protos::handshake\",\"iroh_relay::protos::handshake\"]Ck[6,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ca[6,\"iroh::net_report\",\"iroh::net_report::probes\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bf[15,\"iroh::endpoint::TransportConfig\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bb[10,\"core::marker\",\"core::marker\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]1g[17,\"\"]f[1,\"\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_bench\"]34Ae[2,\"iroh_dns_server\"]1Bb[2,\"iroh_quinn_proto::connection\"]166Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ac[10,\"core::borrow\"]C`[10,\"bytes::buf::buf_mut\",\"bytes::buf::buf_mut\"]Bc[5,\"pkarr::client\",\"pkarr::client\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ba[5,\"async_compat\",\"async_compat\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Cb[10,\"core::future::future\",\"core::future::future\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]An[10,\"core::hash\",\"core::hash\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Bm[6,\"core::net::ip_addr\",\"core::net::ip_addr\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Bh[10,\"reloadable_core\",\"reloadable_core\"]Be[15,\"iroh_relay::server::CertConfig\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Ad[5,\"iroh::endpoint\"]Ba[6,\"core::option\",\"core::option\"]g[17,\"\"]E`[10,\"tower_http::follow_redirect::policy\",\"tower_http::follow_redirect::policy\"]Ch[10,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Co[5,\"hickory_proto::rr::resource\",\"hickory_proto::rr::resource\"]Ca[5,\"iroh::net_report\",\"iroh::net_report::report\"]Ak[8,\"core::fmt\",\"core::fmt\"]Ba[6,\"core::result\",\"core::result\"]Be[8,\"std::io::error\",\"std::io::error\"]Ai[8,\"n0_error\",\"n0_error\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Cg[5,\"iroh_dns_server::server\",\"iroh_dns_server::server\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ad[2,\"iroh::endpoint\"]Cd[6,\"iroh::endpoint\",\"iroh::magicsock::endpoint_map\"]Ak[10,\"futures_core::stream\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Bc[5,\"alloc::string\",\"alloc::string\"]Ak[5,\"core::any\",\"core::any\"]Ci[5,\"iroh_quinn_proto::varint\",\"iroh_quinn_proto::varint\"]Ad[5,\"iroh::endpoint\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]A`[2,\"iroh_relay\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh_dns_server\"]1Af[2,\"iroh::net_report\"]40412Ae[10,\"iroh::endpoint\"]Bg[8,\"iroh_relay::dns\",\"iroh_relay::dns\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]De[5,\"clap_builder::builder::command\",\"clap_builder::builder::command\"]Bc[15,\"iroh::endpoint::ConnectError\"]An[15,\"iroh_relay::quic::Error\"]Bi[5,\"core::task::wake\",\"core::task::wake\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ad[10,\"core::default\"]A`[10,\"core::fmt\"]Bm[5,\"tokio::time::error\",\"tokio::time::error\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Bc[10,\"axum_core::extract::from_ref\"]Ah[10,\"core::str::traits\"]Ak[5,\"std::time\",\"std::time\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Cb[5,\"iroh::net_report\",\"iroh::net_report::metrics\"]Ci[5,\"iroh_dns_server::metrics\",\"iroh_dns_server::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ad[5,\"iroh::endpoint\"]Cg[5,\"iroh::net_report\",\"iroh::net_report::options::imp\"]Ak[5,\"std::path\",\"std::path\"]Bk[5,\"dyn_clone::sealed\",\"dyn_clone::sealed\"]Bo[5,\"tokio::io::read_buf\",\"tokio::io::read_buf\"]Eg[5,\"hickory_server::server::request_handler\",\"hickory_server::server::request_handler\"]B`[15,\"iroh_relay::dns::DnsError\"]Al[10,\"reqwest::dns::resolve\"]Cg[5,\"tokio::runtime::runtime\",\"tokio::runtime::runtime\"]Cj[10,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Bd[15,\"iroh_relay::client::DialError\"]4Ad[10,\"alloc::borrow\"]Ad[10,\"core::convert\"]0Bg[15,\"iroh_relay::client::ConnectError\"]k[10,\"iroh\"]>j[2,\"iroh\"]Af[2,\"iroh::net_report\"]Ah[2,\"iroh_relay::server\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]Ad[2,\"iroh::endpoint\"]Ad[2,\"iroh::defaults\"]Bb[2,\"iroh_quinn_proto::connection\"]5Ad[5,\"iroh::endpoint\"]Bc[5,\"n0_error::any\",\"n0_error::any\"]Ce[5,\"iroh_dns_server::state\",\"iroh_dns_server::state\"]De[5,\"alloc::collections::btree::set\",\"alloc::collections::btree::set\"]Ch[6,\"iroh_dns_server::http\",\"iroh_dns_server::http::tls\"]Am[6,\"iroh_bench\",\"iroh_bench\"]Ag[10,\"core::ops::deref\"]Bm[15,\"iroh::endpoint::GetMappingAddressError\"]Ae[2,\"iroh_relay::dns\"]Bg[6,\"iroh_relay::dns\",\"iroh_relay::dns\"]Am[5,\"core::time\",\"core::time\"]A`[10,\"dyn_clone\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]Ca[5,\"iroh_quinn::endpoint\",\"iroh_quinn::endpoint\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Bg[6,\"n0_error::error\",\"n0_error::error\"]3Ca[5,\"iroh_quinn::incoming\",\"iroh_quinn::incoming\"]Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[5,\"core::net::ip_addr\",\"core::net::ip_addr\"]0Ck[6,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]Am[10,\"iroh_metrics::iterable\"]Db[10,\"core::iter::traits::iterator\",\"core::iter::traits::iterator\"]Am[15,\"iroh::endpoint::Source\"]An[10,\"n0_watcher\",\"n0_watcher\"]Ak[6,\"core::cmp\",\"core::cmp\"]Dd[5,\"iroh::endpoint\",\"iroh::magicsock::endpoint_map::endpoint_state\"]Bd[15,\"iroh_relay::client::RecvError\"]j[5,\"iroh\"]Bh[5,\"iroh_relay\",\"iroh_relay::relay_map\"]Ca[5,\"iroh_base::relay_url\",\"iroh_base::relay_url\"]2Bf[5,\"iroh_base\",\"iroh_base::relay_url\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Bh[10,\"iroh_relay::dns\",\"iroh_relay::dns\"]Ad[5,\"iroh::endpoint\"]Ad[10,\"alloc::string\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Ck[5,\"iroh_relay::endpoint_info\",\"iroh_relay::endpoint_info\"]3Ae[5,\"iroh::discovery\"]1o[6,\"z32\",\"z32\"]j[2,\"iroh\"]A`[2,\"iroh_relay\"]1A`[2,\"iroh_quinn\"]2Ah[2,\"iroh_relay::server\"]B`[2,\"iroh::net_report::defaults\"]:Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Ci[5,\"tokio_rustls_acme::state\",\"tokio_rustls_acme::state\"]Ad[2,\"iroh::endpoint\"]Ca[6,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Al[10,\"tokio::io::async_read\"]2Be[6,\"iroh::endpoint\",\"iroh::endpoint\"]Ac[10,\"core::borrow\"]Ac[10,\"async_compat\"]Al[10,\"rand_core\",\"rand_core\"]Cb[15,\"iroh_relay::protos::relay::ClientToRelayMsg\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Ck[5,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Ah[2,\"iroh_relay::client\"]Bm[6,\"iroh_relay::client\",\"iroh_relay::client\"]Am[15,\"iroh::endpoint::Source\"]B`[15,\"iroh::endpoint::BindError\"]Bh[10,\"iroh::discovery\",\"iroh::discovery\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]0Ak[5,\"core::fmt\",\"core::fmt\"]Cm[6,\"iroh_relay::protos::common\",\"iroh_relay::protos::common\"]Bg[15,\"iroh_relay::client::ConnectError\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ba[5,\"hdrhistogram\",\"hdrhistogram\"]Co[5,\"tokio::runtime::task::error\",\"tokio::runtime::task::error\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Be[15,\"iroh_relay::server::SpawnError\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bm[15,\"iroh::endpoint::GetMappingAddressError\"]Bf[15,\"iroh::discovery::DiscoveryError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]A`[10,\"core::cmp\"]Ad[5,\"iroh::endpoint\"]An[10,\"crossbeam_epoch::atomic\"]Bj[10,\"tower_http::follow_redirect::policy\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]j[5,\"iroh\"]B`[5,\"iroh_base\",\"iroh_base::key\"]156 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); 157 158 let mut transports = vec![ -159 TransportConfig::default_ipv4(), -160 TransportConfig::default_ipv6(), -161 ]; -162 if let Some(relay) = relay_mode.into() { -163 transports.push(relay); -164 } -165 Self { -166 secret_key: Default::default(), -167 alpn_protocols: Default::default(), -168 transport_config: quinn::TransportConfig::default(), -169 keylog: Default::default(), -170 discovery: Default::default(), -171 discovery_user_data: Default::default(), -172 proxy_url: None, -173 #[cfg(not(wasm_browser))] -174 dns_resolver: None, -175 #[cfg(any(test, feature = "test-utils"))] -176 insecure_skip_relay_cert_verify: false, +159 #[cfg(not(wasm_browser))] +160 TransportConfig::default_ipv4(), +161 #[cfg(not(wasm_browser))] +162 TransportConfig::default_ipv6(), +163 ]; +164 if let Some(relay) = relay_mode.into() { +165 transports.push(relay); +166 } +167 Self { +168 secret_key: Default::default(), +169 alpn_protocols: Default::default(), +170 transport_config: quinn::TransportConfig::default(), +171 keylog: Default::default(), +172 discovery: Default::default(), +173 discovery_user_data: Default::default(), +174 proxy_url: None, +175 #[cfg(not(wasm_browser))] +176 dns_resolver: None, 177 #[cfg(any(test, feature = "test-utils"))] -178 path_selection: PathSelection::default(), -179 max_tls_tickets: DEFAULT_MAX_TLS_TICKETS, -180 transports, -181 } -182 } -183 -184 // # The final constructor that everyone needs. +178 insecure_skip_relay_cert_verify: false, +179 #[cfg(any(test, feature = "test-utils"))] +180 path_selection: PathSelection::default(), +181 max_tls_tickets: DEFAULT_MAX_TLS_TICKETS, +182 transports, +183 } +184 } 185 -186 /// Binds the magic endpoint. -187 pub async fn bind(mut self) -> Result<Endpoint, BindError> { -188 let mut rng = rand::rng(); -189 let secret_key = self -190 .secret_key -191 .unwrap_or_else(move || SecretKey::generate(&mut rng)); -192 -193 // Override some transport config settings. -194 self.transport_config -195 .keep_alive_interval(Some(HEARTBEAT_INTERVAL)); -196 self.transport_config -197 .default_path_keep_alive_interval(Some(HEARTBEAT_INTERVAL)); +186 // # The final constructor that everyone needs. +187 +188 /// Binds the magic endpoint. +189 pub async fn bind(mut self) -> Result<Endpoint, BindError> { +190 let mut rng = rand::rng(); +191 let secret_key = self +192 .secret_key +193 .unwrap_or_else(move || SecretKey::generate(&mut rng)); +194 +195 // Override some transport config settings. +196 self.transport_config +197 .keep_alive_interval(Some(HEARTBEAT_INTERVAL)); 198 self.transport_config -199 .default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)); +199 .default_path_keep_alive_interval(Some(HEARTBEAT_INTERVAL)); 200 self.transport_config -201 .max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS); -202 -203 let static_config = StaticConfig { -204 transport_config: Arc::new(self.transport_config), -205 tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets), -206 keylog: self.keylog, -207 }; -208 let server_config = static_config.create_server_config(self.alpn_protocols); -209 -210 #[cfg(not(wasm_browser))] -211 let dns_resolver = self.dns_resolver.unwrap_or_default(); -212 -213 let metrics = EndpointMetrics::default(); +201 .default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)); +202 self.transport_config +203 .max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS); +204 +205 let static_config = StaticConfig { +206 transport_config: Arc::new(self.transport_config), +207 tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets), +208 keylog: self.keylog, +209 }; +210 let server_config = static_config.create_server_config(self.alpn_protocols); +211 +212 #[cfg(not(wasm_browser))] +213 let dns_resolver = self.dns_resolver.unwrap_or_default(); 214 -215 let msock_opts = magicsock::Options { -216 transports: self.transports, -217 secret_key, -218 discovery_user_data: self.discovery_user_data, -219 proxy_url: self.proxy_url, -220 #[cfg(not(wasm_browser))] -221 dns_resolver, -222 server_config, -223 #[cfg(any(test, feature = "test-utils"))] -224 insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify, -225 // #[cfg(any(test, feature = "test-utils"))] -226 // path_selection: self.path_selection, -227 metrics, -228 }; -229 -230 let msock = magicsock::MagicSock::spawn(msock_opts).await?; -231 trace!("created magicsock"); -232 debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created"); -233 -234 let ep = Endpoint { -235 msock, -236 static_config: Arc::new(static_config), -237 }; -238 -239 // Add discovery mechanisms -240 for create_service in self.discovery { -241 let service = create_service.into_discovery(&ep)?; -242 ep.discovery().add_boxed(service); -243 } -244 -245 Ok(ep) -246 } -247 -248 // # The very common methods everyone basically needs. +215 let metrics = EndpointMetrics::default(); +216 +217 let msock_opts = magicsock::Options { +218 transports: self.transports, +219 secret_key, +220 discovery_user_data: self.discovery_user_data, +221 proxy_url: self.proxy_url, +222 #[cfg(not(wasm_browser))] +223 dns_resolver, +224 server_config, +225 #[cfg(any(test, feature = "test-utils"))] +226 insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify, +227 // #[cfg(any(test, feature = "test-utils"))] +228 // path_selection: self.path_selection, +229 metrics, +230 }; +231 +232 let msock = magicsock::MagicSock::spawn(msock_opts).await?; +233 trace!("created magicsock"); +234 debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created"); +235 +236 let ep = Endpoint { +237 msock, +238 static_config: Arc::new(static_config), +239 }; +240 +241 // Add discovery mechanisms +242 for create_service in self.discovery { +243 let service = create_service.into_discovery(&ep)?; +244 ep.discovery().add_boxed(service); +245 } +246 +247 Ok(ep) +248 } 249 -250 /// Sets the IPv4 bind address. -251 /// -252 /// Setting the port to `0` will use a random port. -253 /// If the port specified is already in use, it will fallback to choosing a random port. -254 /// -255 /// By default will use `0.0.0.0:0` to bind to. -256 // TODO: update docs -257 pub fn bind_addr_v4(mut self, bind_addr: SocketAddrV4) -> Self { -258 self.transports.push(TransportConfig::Ip { -259 bind_addr: bind_addr.into(), -260 }); -261 self -262 } -263 -264 /// Sets the IPv6 bind address. -265 /// -266 /// Setting the port to `0` will use a random port. -267 /// If the port specified is already in use, it will fallback to choosing a random port. +250 // # The very common methods everyone basically needs. +251 +252 /// Sets the IPv4 bind address. +253 /// +254 /// Setting the port to `0` will use a random port. +255 /// If the port specified is already in use, it will fallback to choosing a random port. +256 /// +257 /// By default will use `0.0.0.0:0` to bind to. +258 // TODO: update docs +259 #[cfg(not(wasm_browser))] +260 pub fn bind_addr_v4(mut self, bind_addr: SocketAddrV4) -> Self { +261 self.transports.push(TransportConfig::Ip { +262 bind_addr: bind_addr.into(), +263 }); +264 self +265 } +266 +267 /// Sets the IPv6 bind address. 268 /// -269 /// By default will use `[::]:0` to bind to. -270 // TODO: update docs -271 pub fn bind_addr_v6(mut self, bind_addr: SocketAddrV6) -> Self { -272 self.transports.push(TransportConfig::Ip { -273 bind_addr: bind_addr.into(), -274 }); -275 self -276 } -277 -278 /// Removes all IP based transports -279 pub fn disable_ip(mut self) -> Self { -280 self.transports -281 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); -282 self -283 } -284 -285 /// Removes all relay based transports -286 pub fn disable_relay(mut self) -> Self { -287 self.transports -288 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -289 self -290 } -291 -292 /// Sets a secret key to authenticate with other peers. -293 /// -294 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus -295 /// also its [`EndpointId`] -296 /// -297 /// If not set, a new secret key will be generated. +269 /// Setting the port to `0` will use a random port. +270 /// If the port specified is already in use, it will fallback to choosing a random port. +271 /// +272 /// By default will use `[::]:0` to bind to. +273 // TODO: update docs +274 #[cfg(not(wasm_browser))] +275 pub fn bind_addr_v6(mut self, bind_addr: SocketAddrV6) -> Self { +276 self.transports.push(TransportConfig::Ip { +277 bind_addr: bind_addr.into(), +278 }); +279 self +280 } +281 +282 /// Removes all IP based transports +283 #[cfg(not(wasm_browser))] +284 pub fn disable_ip(mut self) -> Self { +285 self.transports +286 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); +287 self +288 } +289 +290 /// Removes all relay based transports +291 pub fn disable_relay(mut self) -> Self { +292 self.transports +293 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +294 self +295 } +296 +297 /// Sets a secret key to authenticate with other peers. 298 /// -299 /// [`PublicKey`]: iroh_base::PublicKey -300 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { -301 self.secret_key = Some(secret_key); -302 self -303 } -304 -305 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. -306 /// -307 /// Not setting this will still allow creating connections, but to accept incoming -308 /// connections at least one [ALPN] must be set. -309 /// -310 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -311 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { -312 self.alpn_protocols = alpn_protocols; -313 self -314 } -315 -316 // # Methods for common customisation items. -317 -318 /// Sets the relay servers to assist in establishing connectivity. -319 /// -320 /// Relay servers are used to establish initial connection with another iroh endpoint. -321 /// They also perform various functions related to hole punching, see the [crate docs] -322 /// for more details. -323 /// -324 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. -325 /// -326 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one -327 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] -328 /// will result in an error. -329 /// -330 /// [`bind`]: Builder::bind -331 /// [crate docs]: crate -332 /// [number 0]: https://n0.computer -333 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { -334 let transport: Option<_> = relay_mode.into(); -335 match transport { -336 Some(transport) => { -337 if let Some(og) = self -338 .transports -339 .iter_mut() -340 .find(|t| matches!(t, TransportConfig::Relay { .. })) -341 { -342 *og = transport; -343 } else { -344 self.transports.push(transport); -345 } -346 } -347 None => { -348 self.transports -349 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -350 } -351 } -352 self -353 } -354 -355 /// Removes all discovery services from the builder. -356 /// -357 /// If no discovery service is set, connecting to an endpoint without providing its -358 /// direct addresses or relay URLs will fail. -359 /// -360 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. -361 pub fn clear_discovery(mut self) -> Self { -362 self.discovery.clear(); -363 self -364 } -365 -366 /// Adds a discovery mechanism for this endpoint. -367 /// -368 /// The function `discovery` -369 /// will be called on endpoint creation with the configured secret key of -370 /// the endpoint. Discovery services that need to publish information need -371 /// to use this secret key to sign the information. +299 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus +300 /// also its [`EndpointId`] +301 /// +302 /// If not set, a new secret key will be generated. +303 /// +304 /// [`PublicKey`]: iroh_base::PublicKey +305 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { +306 self.secret_key = Some(secret_key); +307 self +308 } +309 +310 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. +311 /// +312 /// Not setting this will still allow creating connections, but to accept incoming +313 /// connections at least one [ALPN] must be set. +314 /// +315 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +316 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { +317 self.alpn_protocols = alpn_protocols; +318 self +319 } +320 +321 // # Methods for common customisation items. +322 +323 /// Sets the relay servers to assist in establishing connectivity. +324 /// +325 /// Relay servers are used to establish initial connection with another iroh endpoint. +326 /// They also perform various functions related to hole punching, see the [crate docs] +327 /// for more details. +328 /// +329 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. +330 /// +331 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one +332 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] +333 /// will result in an error. +334 /// +335 /// [`bind`]: Builder::bind +336 /// [crate docs]: crate +337 /// [number 0]: https://n0.computer +338 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { +339 let transport: Option<_> = relay_mode.into(); +340 match transport { +341 Some(transport) => { +342 if let Some(og) = self +343 .transports +344 .iter_mut() +345 .find(|t| matches!(t, TransportConfig::Relay { .. })) +346 { +347 *og = transport; +348 } else { +349 self.transports.push(transport); +350 } +351 } +352 None => { +353 self.transports +354 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +355 } +356 } +357 self +358 } +359 +360 /// Removes all discovery services from the builder. +361 /// +362 /// If no discovery service is set, connecting to an endpoint without providing its +363 /// direct addresses or relay URLs will fail. +364 /// +365 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. +366 pub fn clear_discovery(mut self) -> Self { +367 self.discovery.clear(); +368 self +369 } +370 +371 /// Adds a discovery mechanism for this endpoint. 372 /// -373 /// If you add multiple discovery services, they will be combined using a -374 /// [`crate::discovery::ConcurrentDiscovery`]. -375 /// -376 /// If no discovery service is set, connecting to an endpoint without providing its -377 /// direct addresses or relay URLs will fail. -378 /// -379 /// To clear all discovery services, use [`Builder::clear_discovery`]. +373 /// The function `discovery` +374 /// will be called on endpoint creation with the configured secret key of +375 /// the endpoint. Discovery services that need to publish information need +376 /// to use this secret key to sign the information. +377 /// +378 /// If you add multiple discovery services, they will be combined using a +379 /// [`crate::discovery::ConcurrentDiscovery`]. 380 /// -381 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. -382 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { -383 self.discovery.push(Box::new(discovery)); -384 self -385 } -386 -387 /// Sets the initial user-defined data to be published in discovery services for this node. -388 /// -389 /// When using discovery services, this string of [`UserData`] will be published together -390 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, -391 /// they retrieve the [`UserData`] in addition to the addressing info. -392 /// -393 /// Iroh itself does not interpret the user-defined data in any way, it is purely left -394 /// for applications to parse and use. -395 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { -396 self.discovery_user_data = Some(user_data); -397 self -398 } -399 -400 // # Methods for more specialist customisation. -401 -402 /// Sets a custom [`quinn::TransportConfig`] for this endpoint. -403 /// -404 /// The transport config contains parameters governing the QUIC state machine. -405 /// -406 /// If unset, the default config is used. Default values should be suitable for most -407 /// internet applications. Applications protocols which forbid remotely-initiated -408 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to -409 /// zero. +381 /// If no discovery service is set, connecting to an endpoint without providing its +382 /// direct addresses or relay URLs will fail. +383 /// +384 /// To clear all discovery services, use [`Builder::clear_discovery`]. +385 /// +386 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. +387 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { +388 self.discovery.push(Box::new(discovery)); +389 self +390 } +391 +392 /// Sets the initial user-defined data to be published in discovery services for this node. +393 /// +394 /// When using discovery services, this string of [`UserData`] will be published together +395 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, +396 /// they retrieve the [`UserData`] in addition to the addressing info. +397 /// +398 /// Iroh itself does not interpret the user-defined data in any way, it is purely left +399 /// for applications to parse and use. +400 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { +401 self.discovery_user_data = Some(user_data); +402 self +403 } +404 +405 // # Methods for more specialist customisation. +406 +407 /// Sets a custom [`quinn::TransportConfig`] for this endpoint. +408 /// +409 /// The transport config contains parameters governing the QUIC state machine. 410 /// -411 /// Please be aware that changing some settings may have adverse effects on establishing -412 /// and maintaining direct connections. -413 pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self { -414 self.transport_config = transport_config; -415 self -416 } -417 -418 /// Optionally sets a custom DNS resolver to use for this endpoint. -419 /// -420 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if -421 /// [`crate::discovery::dns::DnsDiscovery`] is configured. -422 /// -423 /// By default, a new DNS resolver is created which is configured to use the -424 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] -425 /// here to use a differently configured DNS resolver for this endpoint, or to share -426 /// a [`DnsResolver`] between multiple endpoints. -427 #[cfg(not(wasm_browser))] -428 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -429 self.dns_resolver = Some(dns_resolver); -430 self -431 } -432 -433 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. -434 pub fn proxy_url(mut self, url: Url) -> Self { -435 self.proxy_url.replace(url); -436 self -437 } -438 -439 /// Sets the proxy url from the environment, in this order: -440 /// -441 /// - `HTTP_PROXY` -442 /// - `http_proxy` -443 /// - `HTTPS_PROXY` -444 /// - `https_proxy` -445 pub fn proxy_from_env(mut self) -> Self { -446 self.proxy_url = proxy_url_from_env(); -447 self -448 } -449 -450 /// Enables saving the TLS pre-master key for connections. -451 /// -452 /// This key should normally remain secret but can be useful to debug networking issues -453 /// by decrypting captured traffic. -454 /// -455 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a -456 /// filename will result in this file being used to log the TLS pre-master keys. -457 pub fn keylog(mut self, keylog: bool) -> Self { -458 self.keylog = keylog; -459 self -460 } -461 -462 /// Skip verification of SSL certificates from relay servers -463 /// -464 /// May only be used in tests. -465 #[cfg(any(test, feature = "test-utils"))] -466 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { -467 self.insecure_skip_relay_cert_verify = skip_verify; -468 self -469 } -470 -471 /// This implies we only use the relay to communicate -472 /// and do not attempt to do any hole punching. -473 #[cfg(any(test, feature = "test-utils"))] -474 pub fn path_selection(mut self, path_selection: PathSelection) -> Self { -475 self.path_selection = path_selection; -476 self -477 } -478 -479 /// Set the maximum number of TLS tickets to cache. -480 /// -481 /// Set this to a larger value if you want to do 0rtt connections to a large -482 /// number of clients. -483 /// -484 /// The default is 256, taking about 150 KiB in memory. -485 pub fn max_tls_tickets(mut self, n: usize) -> Self { -486 self.max_tls_tickets = n; -487 self -488 } -489} -490 -491/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. -492#[derive(Debug)] -493struct StaticConfig { -494 tls_config: tls::TlsConfig, -495 transport_config: Arc<quinn::TransportConfig>, -496 keylog: bool, -497} -498 -499impl StaticConfig { -500 /// Create a [`quinn::ServerConfig`] with the specified ALPN protocols. -501 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig { -502 let quic_server_config = self -503 .tls_config -504 .make_server_config(alpn_protocols, self.keylog); -505 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -506 server_config.transport_config(self.transport_config.clone()); -507 -508 server_config -509 } -510} -511 -512/// Controls an iroh endpoint, establishing connections with other endpoints. -513/// -514/// This is the main API interface to create connections to, and accept connections from -515/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is -516/// used to make the connections reliable. See the [crate docs] for a more detailed -517/// overview of iroh. +411 /// If unset, the default config is used. Default values should be suitable for most +412 /// internet applications. Applications protocols which forbid remotely-initiated +413 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to +414 /// zero. +415 /// +416 /// Please be aware that changing some settings may have adverse effects on establishing +417 /// and maintaining direct connections. +418 pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self { +419 self.transport_config = transport_config; +420 self +421 } +422 +423 /// Optionally sets a custom DNS resolver to use for this endpoint. +424 /// +425 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if +426 /// [`crate::discovery::dns::DnsDiscovery`] is configured. +427 /// +428 /// By default, a new DNS resolver is created which is configured to use the +429 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] +430 /// here to use a differently configured DNS resolver for this endpoint, or to share +431 /// a [`DnsResolver`] between multiple endpoints. +432 #[cfg(not(wasm_browser))] +433 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +434 self.dns_resolver = Some(dns_resolver); +435 self +436 } +437 +438 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. +439 pub fn proxy_url(mut self, url: Url) -> Self { +440 self.proxy_url.replace(url); +441 self +442 } +443 +444 /// Sets the proxy url from the environment, in this order: +445 /// +446 /// - `HTTP_PROXY` +447 /// - `http_proxy` +448 /// - `HTTPS_PROXY` +449 /// - `https_proxy` +450 pub fn proxy_from_env(mut self) -> Self { +451 self.proxy_url = proxy_url_from_env(); +452 self +453 } +454 +455 /// Enables saving the TLS pre-master key for connections. +456 /// +457 /// This key should normally remain secret but can be useful to debug networking issues +458 /// by decrypting captured traffic. +459 /// +460 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a +461 /// filename will result in this file being used to log the TLS pre-master keys. +462 pub fn keylog(mut self, keylog: bool) -> Self { +463 self.keylog = keylog; +464 self +465 } +466 +467 /// Skip verification of SSL certificates from relay servers +468 /// +469 /// May only be used in tests. +470 #[cfg(any(test, feature = "test-utils"))] +471 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { +472 self.insecure_skip_relay_cert_verify = skip_verify; +473 self +474 } +475 +476 /// This implies we only use the relay to communicate +477 /// and do not attempt to do any hole punching. +478 #[cfg(any(test, feature = "test-utils"))] +479 pub fn path_selection(mut self, path_selection: PathSelection) -> Self { +480 self.path_selection = path_selection; +481 self +482 } +483 +484 /// Set the maximum number of TLS tickets to cache. +485 /// +486 /// Set this to a larger value if you want to do 0rtt connections to a large +487 /// number of clients. +488 /// +489 /// The default is 256, taking about 150 KiB in memory. +490 pub fn max_tls_tickets(mut self, n: usize) -> Self { +491 self.max_tls_tickets = n; +492 self +493 } +494} +495 +496/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. +497#[derive(Debug)] +498struct StaticConfig { +499 tls_config: tls::TlsConfig, +500 transport_config: Arc<quinn::TransportConfig>, +501 keylog: bool, +502} +503 +504impl StaticConfig { +505 /// Create a [`quinn::ServerConfig`] with the specified ALPN protocols. +506 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig { +507 let quic_server_config = self +508 .tls_config +509 .make_server_config(alpn_protocols, self.keylog); +510 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +511 server_config.transport_config(self.transport_config.clone()); +512 +513 server_config +514 } +515} +516 +517/// Controls an iroh endpoint, establishing connections with other endpoints. 518/// -519/// It is recommended to only create a single instance per application. This ensures all -520/// the connections made share the same peer-to-peer connections to other iroh endpoints, -521/// while still remaining independent connections. This will result in more optimal network -522/// behaviour. +519/// This is the main API interface to create connections to, and accept connections from +520/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is +521/// used to make the connections reliable. See the [crate docs] for a more detailed +522/// overview of iroh. 523/// -524/// The endpoint is created using the [`Builder`], which can be created using -525/// [`Endpoint::builder`]. -526/// -527/// Once an endpoint exists, new connections are typically created using the -528/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the -529/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to -530/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], -531/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. -532/// -533/// Note that due to the light-weight properties of streams a stream will only be accepted -534/// once the initiating peer has sent some data on it. -535/// -536/// [QUIC]: https://quicwg.org -537#[derive(Clone, Debug)] -538pub struct Endpoint { -539 /// Handle to the magicsocket/actor -540 pub(crate) msock: Handle, -541 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. -542 static_config: Arc<StaticConfig>, -543} -544 -545#[allow(missing_docs)] -546#[stack_error(derive, add_meta, from_sources)] -547#[non_exhaustive] -548pub enum ConnectWithOptsError { -549 #[error(transparent)] -550 AddEndpointAddr { source: AddEndpointAddrError }, -551 #[error("Connecting to ourself is not supported")] -552 SelfConnect, -553 #[error("No addressing information available")] -554 NoAddress { source: GetMappingAddressError }, -555 #[error("Unable to connect to remote")] -556 Quinn { -557 #[error(std_err)] -558 source: quinn_proto::ConnectError, -559 }, -560} -561 -562#[allow(missing_docs)] -563#[stack_error(derive, add_meta, from_sources)] -564#[non_exhaustive] -565pub enum ConnectError { -566 #[error(transparent)] -567 Connect { source: ConnectWithOptsError }, -568 #[error(transparent)] -569 Connecting { source: ConnectingError }, -570 #[error(transparent)] -571 Connection { -572 #[error(std_err)] -573 source: ConnectionError, -574 }, -575} -576 -577#[allow(missing_docs)] -578#[stack_error(derive, add_meta, from_sources)] -579#[non_exhaustive] -580pub enum BindError { -581 #[error(transparent)] -582 MagicSpawn { -583 source: magicsock::CreateHandleError, -584 }, -585 #[error(transparent)] -586 Discovery { -587 source: crate::discovery::IntoDiscoveryError, -588 }, -589} -590 -591#[allow(missing_docs)] -592#[stack_error(derive, add_meta)] -593#[non_exhaustive] -594pub enum GetMappingAddressError { -595 #[error("Discovery service required due to missing addressing information")] -596 DiscoveryStart { source: DiscoveryError }, -597 #[error("Discovery service failed")] -598 Discover { source: DiscoveryError }, -599 #[error("No addressing information found")] -600 NoAddress, -601} -602 -603impl Endpoint { -604 // The ordering of public methods is reflected directly in the documentation. This is -605 // roughly ordered by what is most commonly needed by users, but grouped in similar -606 // items. +524/// It is recommended to only create a single instance per application. This ensures all +525/// the connections made share the same peer-to-peer connections to other iroh endpoints, +526/// while still remaining independent connections. This will result in more optimal network +527/// behaviour. +528/// +529/// The endpoint is created using the [`Builder`], which can be created using +530/// [`Endpoint::builder`]. +531/// +532/// Once an endpoint exists, new connections are typically created using the +533/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the +534/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to +535/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], +536/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. +537/// +538/// Note that due to the light-weight properties of streams a stream will only be accepted +539/// once the initiating peer has sent some data on it. +540/// +541/// [QUIC]: https://quicwg.org +542#[derive(Clone, Debug)] +543pub struct Endpoint { +544 /// Handle to the magicsocket/actor +545 pub(crate) msock: Handle, +546 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. +547 static_config: Arc<StaticConfig>, +548} +549 +550#[allow(missing_docs)] +551#[stack_error(derive, add_meta, from_sources)] +552#[non_exhaustive] +553pub enum ConnectWithOptsError { +554 #[error(transparent)] +555 AddEndpointAddr { source: AddEndpointAddrError }, +556 #[error("Connecting to ourself is not supported")] +557 SelfConnect, +558 #[error("No addressing information available")] +559 NoAddress { source: GetMappingAddressError }, +560 #[error("Unable to connect to remote")] +561 Quinn { +562 #[error(std_err)] +563 source: quinn_proto::ConnectError, +564 }, +565} +566 +567#[allow(missing_docs)] +568#[stack_error(derive, add_meta, from_sources)] +569#[non_exhaustive] +570pub enum ConnectError { +571 #[error(transparent)] +572 Connect { source: ConnectWithOptsError }, +573 #[error(transparent)] +574 Connecting { source: ConnectingError }, +575 #[error(transparent)] +576 Connection { +577 #[error(std_err)] +578 source: ConnectionError, +579 }, +580} +581 +582#[allow(missing_docs)] +583#[stack_error(derive, add_meta, from_sources)] +584#[non_exhaustive] +585pub enum BindError { +586 #[error(transparent)] +587 MagicSpawn { +588 source: magicsock::CreateHandleError, +589 }, +590 #[error(transparent)] +591 Discovery { +592 source: crate::discovery::IntoDiscoveryError, +593 }, +594} +595 +596#[allow(missing_docs)] +597#[stack_error(derive, add_meta)] +598#[non_exhaustive] +599pub enum GetMappingAddressError { +600 #[error("Discovery service required due to missing addressing information")] +601 DiscoveryStart { source: DiscoveryError }, +602 #[error("Discovery service failed")] +603 Discover { source: DiscoveryError }, +604 #[error("No addressing information found")] +605 NoAddress, +606} 607 -608 // # Methods relating to construction. -609 -610 /// Returns the builder for an [`Endpoint`], with a production configuration. -611 /// -612 /// This uses the [`presets::N0`] as the configuration. -613 pub fn builder() -> Builder { -614 Builder::new(presets::N0) -615 } -616 -617 /// Returns the builder for an [`Endpoint`], with an empty configuration. -618 /// -619 /// See [`Builder::empty`] for details. -620 pub fn empty_builder(relay_mode: RelayMode) -> Builder { -621 Builder::empty(relay_mode) -622 } -623 -624 /// Constructs a default [`Endpoint`] and binds it immediately. -625 /// -626 /// Uses the [`presets::N0`] as configuration. -627 pub async fn bind() -> Result<Self, BindError> { -628 Self::builder().bind().await -629 } -630 -631 /// Sets the list of accepted ALPN protocols. -632 /// -633 /// This will only affect new incoming connections. -634 /// Note that this *overrides* the current list of ALPNs. -635 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { -636 let server_config = self.static_config.create_server_config(alpns); -637 self.msock.endpoint().set_server_config(Some(server_config)); -638 } -639 -640 /// Adds the provided configuration to the [`RelayMap`]. -641 /// -642 /// Replacing and returning any existing configuration for [`RelayUrl`]. -643 pub async fn insert_relay( -644 &self, -645 relay: RelayUrl, -646 config: Arc<RelayConfig>, -647 ) -> Option<Arc<RelayConfig>> { -648 self.msock.insert_relay(relay, config).await -649 } -650 -651 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. -652 /// -653 /// Returns any existing configuration. -654 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { -655 self.msock.remove_relay(relay).await -656 } -657 -658 // # Methods for establishing connectivity. -659 -660 /// Connects to a remote [`Endpoint`]. -661 /// -662 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an -663 /// [`EndpointAddr`] or an [`EndpointId`]. -664 /// -665 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] -666 /// and direct addresses. If direct addresses are provided, they will be used to try and -667 /// establish a direct connection without involving a relay server. -668 /// -669 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it -670 /// may still be possible a connection can be established. This depends on which, if any, -671 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery -672 /// service will also be used if the remote endpoint is not reachable on the provided direct -673 /// addresses and there is no [`RelayUrl`]. -674 /// -675 /// If addresses or relay servers are neither provided nor can be discovered, the -676 /// connection attempt will fail with an error. -677 /// -678 /// The `alpn`, or application-level protocol identifier, is also required. The remote -679 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with -680 /// an error. -681 /// -682 /// [`RelayUrl`]: crate::RelayUrl -683 pub async fn connect( -684 &self, -685 endpoint_addr: impl Into<EndpointAddr>, -686 alpn: &[u8], -687 ) -> Result<Connection, ConnectError> { -688 let endpoint_addr = endpoint_addr.into(); -689 let remote = endpoint_addr.id; -690 let connecting = self -691 .connect_with_opts(endpoint_addr, alpn, Default::default()) -692 .await?; -693 let conn = connecting.await?; -694 -695 debug!( -696 me = %self.id().fmt_short(), -697 remote = %remote.fmt_short(), -698 alpn = %String::from_utf8_lossy(alpn), -699 "Connection established." -700 ); -701 Ok(conn) -702 } -703 -704 /// Starts a connection attempt with a remote [`Endpoint`]. -705 /// -706 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more -707 /// advanced connection setup with more customization in two aspects: -708 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into -709 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via -710 /// [`Connecting::into_0rtt`]. -711 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess -712 /// security concerns. -713 /// 2. The [`TransportConfig`] for the connection can be modified via the provided -714 /// [`ConnectOptions`]. -715 /// **Note:** Please be aware that changing transport config settings may have adverse effects on -716 /// establishing and maintaining direct connections. Carefully test settings you use and -717 /// consider this currently as still rather experimental. -718 #[instrument(name = "connect", skip_all, fields( -719 me = %self.id().fmt_short(), -720 remote = tracing::field::Empty, -721 alpn = String::from_utf8_lossy(alpn).to_string(), -722 ))] -723 pub async fn connect_with_opts( -724 &self, -725 endpoint_addr: impl Into<EndpointAddr>, -726 alpn: &[u8], -727 options: ConnectOptions, -728 ) -> Result<Connecting, ConnectWithOptsError> { -729 let endpoint_addr: EndpointAddr = endpoint_addr.into(); -730 tracing::Span::current().record( -731 "remote", -732 tracing::field::display(endpoint_addr.id.fmt_short()), -733 ); -734 -735 // Connecting to ourselves is not supported. -736 ensure!( -737 endpoint_addr.id != self.id(), -738 ConnectWithOptsError::SelfConnect -739 ); -740 -741 if !endpoint_addr.is_empty() { -742 self.add_endpoint_addr(endpoint_addr.clone(), Source::App) -743 .await?; -744 } -745 let endpoint_id = endpoint_addr.id; -746 let ip_addresses: Vec<_> = endpoint_addr.ip_addrs().cloned().collect(); -747 let relay_url = endpoint_addr.relay_urls().next().cloned(); -748 trace!( -749 dst_endpoint_id = %endpoint_id.fmt_short(), -750 ?relay_url, -751 ?ip_addresses, -752 "connecting", -753 ); -754 -755 // When we start a connection we want to send the QUIC Initial packets on all the -756 // known paths for the remote endpoint. For this we use an EndpointIdMappedAddr as -757 // destination for Quinn. Start discovery for this endpoint if it's enabled and we have -758 // no valid or verified address information for this endpoint. Dropping the discovery -759 // cancels any still running task. -760 let (mapped_addr, _discovery_drop_guard) = self -761 .get_mapping_addr_and_maybe_start_discovery(endpoint_addr) -762 .await?; -763 -764 let transport_config = options -765 .transport_config -766 .unwrap_or(self.static_config.transport_config.clone()); -767 -768 // Start connecting via quinn. This will time out after 10 seconds if no reachable -769 // address is available. -770 -771 let client_config = { -772 let mut alpn_protocols = vec![alpn.to_vec()]; -773 alpn_protocols.extend(options.additional_alpns); -774 let quic_client_config = self -775 .static_config -776 .tls_config -777 .make_client_config(alpn_protocols, self.static_config.keylog); -778 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -779 client_config.transport_config(transport_config); -780 client_config -781 }; -782 -783 let dest_addr = mapped_addr.private_socket_addr(); -784 let server_name = &tls::name::encode(endpoint_id); -785 let connect = self -786 .msock -787 .endpoint() -788 .connect_with(client_config, dest_addr, server_name)?; -789 -790 Ok(Connecting::new( -791 connect, -792 self.clone(), -793 endpoint_id, -794 _discovery_drop_guard, -795 )) -796 } -797 -798 /// Accepts an incoming connection on the endpoint. -799 /// -800 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. -801 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting -802 /// the connection using [`Connecting::alpn`]. -803 /// -804 /// The returned future will yield `None` if the endpoint is closed by calling -805 /// [`Endpoint::close`]. -806 pub fn accept(&self) -> Accept<'_> { -807 Accept { -808 inner: self.msock.endpoint().accept(), -809 ep: self.clone(), -810 } -811 } -812 -813 // # Methods for manipulating the internal state about other endpoints. -814 -815 /// Informs this [`Endpoint`] about addresses of the iroh endpoint. -816 /// -817 /// This updates the local state for the remote endpoint. If the provided [`EndpointAddr`] -818 /// contains a [`RelayUrl`] this will be used as the new relay server for this endpoint. If -819 /// it contains any new IP endpoints they will also be stored and tried when next -820 /// connecting to this endpoint. Any address that matches this endpoint's direct addresses will be -821 /// silently ignored. -822 /// -823 /// The *source* is used for logging exclusively and will not be stored. -824 /// -825 /// # Using endpoint discovery instead -826 /// -827 /// It is strongly advised to use endpoint discovery using the [`StaticProvider`] instead. -828 /// This provides more flexibility and future proofing. +608impl Endpoint { +609 // The ordering of public methods is reflected directly in the documentation. This is +610 // roughly ordered by what is most commonly needed by users, but grouped in similar +611 // items. +612 +613 // # Methods relating to construction. +614 +615 /// Returns the builder for an [`Endpoint`], with a production configuration. +616 /// +617 /// This uses the [`presets::N0`] as the configuration. +618 pub fn builder() -> Builder { +619 Builder::new(presets::N0) +620 } +621 +622 /// Returns the builder for an [`Endpoint`], with an empty configuration. +623 /// +624 /// See [`Builder::empty`] for details. +625 pub fn empty_builder(relay_mode: RelayMode) -> Builder { +626 Builder::empty(relay_mode) +627 } +628 +629 /// Constructs a default [`Endpoint`] and binds it immediately. +630 /// +631 /// Uses the [`presets::N0`] as configuration. +632 pub async fn bind() -> Result<Self, BindError> { +633 Self::builder().bind().await +634 } +635 +636 /// Sets the list of accepted ALPN protocols. +637 /// +638 /// This will only affect new incoming connections. +639 /// Note that this *overrides* the current list of ALPNs. +640 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { +641 let server_config = self.static_config.create_server_config(alpns); +642 self.msock.endpoint().set_server_config(Some(server_config)); +643 } +644 +645 /// Adds the provided configuration to the [`RelayMap`]. +646 /// +647 /// Replacing and returning any existing configuration for [`RelayUrl`]. +648 pub async fn insert_relay( +649 &self, +650 relay: RelayUrl, +651 config: Arc<RelayConfig>, +652 ) -> Option<Arc<RelayConfig>> { +653 self.msock.insert_relay(relay, config).await +654 } +655 +656 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. +657 /// +658 /// Returns any existing configuration. +659 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { +660 self.msock.remove_relay(relay).await +661 } +662 +663 // # Methods for establishing connectivity. +664 +665 /// Connects to a remote [`Endpoint`]. +666 /// +667 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an +668 /// [`EndpointAddr`] or an [`EndpointId`]. +669 /// +670 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] +671 /// and direct addresses. If direct addresses are provided, they will be used to try and +672 /// establish a direct connection without involving a relay server. +673 /// +674 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it +675 /// may still be possible a connection can be established. This depends on which, if any, +676 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery +677 /// service will also be used if the remote endpoint is not reachable on the provided direct +678 /// addresses and there is no [`RelayUrl`]. +679 /// +680 /// If addresses or relay servers are neither provided nor can be discovered, the +681 /// connection attempt will fail with an error. +682 /// +683 /// The `alpn`, or application-level protocol identifier, is also required. The remote +684 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with +685 /// an error. +686 /// +687 /// [`RelayUrl`]: crate::RelayUrl +688 pub async fn connect( +689 &self, +690 endpoint_addr: impl Into<EndpointAddr>, +691 alpn: &[u8], +692 ) -> Result<Connection, ConnectError> { +693 let endpoint_addr = endpoint_addr.into(); +694 let remote = endpoint_addr.id; +695 let connecting = self +696 .connect_with_opts(endpoint_addr, alpn, Default::default()) +697 .await?; +698 let conn = connecting.await?; +699 +700 debug!( +701 me = %self.id().fmt_short(), +702 remote = %remote.fmt_short(), +703 alpn = %String::from_utf8_lossy(alpn), +704 "Connection established." +705 ); +706 Ok(conn) +707 } +708 +709 /// Starts a connection attempt with a remote [`Endpoint`]. +710 /// +711 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more +712 /// advanced connection setup with more customization in two aspects: +713 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into +714 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via +715 /// [`Connecting::into_0rtt`]. +716 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess +717 /// security concerns. +718 /// 2. The [`TransportConfig`] for the connection can be modified via the provided +719 /// [`ConnectOptions`]. +720 /// **Note:** Please be aware that changing transport config settings may have adverse effects on +721 /// establishing and maintaining direct connections. Carefully test settings you use and +722 /// consider this currently as still rather experimental. +723 #[instrument(name = "connect", skip_all, fields( +724 me = %self.id().fmt_short(), +725 remote = tracing::field::Empty, +726 alpn = String::from_utf8_lossy(alpn).to_string(), +727 ))] +728 pub async fn connect_with_opts( +729 &self, +730 endpoint_addr: impl Into<EndpointAddr>, +731 alpn: &[u8], +732 options: ConnectOptions, +733 ) -> Result<Connecting, ConnectWithOptsError> { +734 let endpoint_addr: EndpointAddr = endpoint_addr.into(); +735 tracing::Span::current().record( +736 "remote", +737 tracing::field::display(endpoint_addr.id.fmt_short()), +738 ); +739 +740 // Connecting to ourselves is not supported. +741 ensure!( +742 endpoint_addr.id != self.id(), +743 ConnectWithOptsError::SelfConnect +744 ); +745 +746 if !endpoint_addr.is_empty() { +747 self.add_endpoint_addr(endpoint_addr.clone(), Source::App) +748 .await?; +749 } +750 let endpoint_id = endpoint_addr.id; +751 let ip_addresses: Vec<_> = endpoint_addr.ip_addrs().cloned().collect(); +752 let relay_url = endpoint_addr.relay_urls().next().cloned(); +753 trace!( +754 dst_endpoint_id = %endpoint_id.fmt_short(), +755 ?relay_url, +756 ?ip_addresses, +757 "connecting", +758 ); +759 +760 // When we start a connection we want to send the QUIC Initial packets on all the +761 // known paths for the remote endpoint. For this we use an EndpointIdMappedAddr as +762 // destination for Quinn. Start discovery for this endpoint if it's enabled and we have +763 // no valid or verified address information for this endpoint. Dropping the discovery +764 // cancels any still running task. +765 let (mapped_addr, _discovery_drop_guard) = self +766 .get_mapping_addr_and_maybe_start_discovery(endpoint_addr) +767 .await?; +768 +769 let transport_config = options +770 .transport_config +771 .unwrap_or(self.static_config.transport_config.clone()); +772 +773 // Start connecting via quinn. This will time out after 10 seconds if no reachable +774 // address is available. +775 +776 let client_config = { +777 let mut alpn_protocols = vec![alpn.to_vec()]; +778 alpn_protocols.extend(options.additional_alpns); +779 let quic_client_config = self +780 .static_config +781 .tls_config +782 .make_client_config(alpn_protocols, self.static_config.keylog); +783 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +784 client_config.transport_config(transport_config); +785 client_config +786 }; +787 +788 let dest_addr = mapped_addr.private_socket_addr(); +789 let server_name = &tls::name::encode(endpoint_id); +790 let connect = self +791 .msock +792 .endpoint() +793 .connect_with(client_config, dest_addr, server_name)?; +794 +795 Ok(Connecting::new( +796 connect, +797 self.clone(), +798 endpoint_id, +799 _discovery_drop_guard, +800 )) +801 } +802 +803 /// Accepts an incoming connection on the endpoint. +804 /// +805 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. +806 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting +807 /// the connection using [`Connecting::alpn`]. +808 /// +809 /// The returned future will yield `None` if the endpoint is closed by calling +810 /// [`Endpoint::close`]. +811 pub fn accept(&self) -> Accept<'_> { +812 Accept { +813 inner: self.msock.endpoint().accept(), +814 ep: self.clone(), +815 } +816 } +817 +818 // # Methods for manipulating the internal state about other endpoints. +819 +820 /// Informs this [`Endpoint`] about addresses of the iroh endpoint. +821 /// +822 /// This updates the local state for the remote endpoint. If the provided [`EndpointAddr`] +823 /// contains a [`RelayUrl`] this will be used as the new relay server for this endpoint. If +824 /// it contains any new IP endpoints they will also be stored and tried when next +825 /// connecting to this endpoint. Any address that matches this endpoint's direct addresses will be +826 /// silently ignored. +827 /// +828 /// The *source* is used for logging exclusively and will not be stored. 829 /// -830 /// # Errors +830 /// # Using endpoint discovery instead 831 /// -832 /// Will return an error if we attempt to add our own [`EndpointId`] to the endpoint map or -833 /// if the direct addresses are a subset of ours. +832 /// It is strongly advised to use endpoint discovery using the [`StaticProvider`] instead. +833 /// This provides more flexibility and future proofing. 834 /// -835 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider -836 /// [`RelayUrl`]: crate::RelayUrl -837 pub(crate) async fn add_endpoint_addr( -838 &self, -839 endpoint_addr: EndpointAddr, -840 source: Source, -841 ) -> Result<(), AddEndpointAddrError> { -842 // Connecting to ourselves is not supported. -843 ensure!( -844 endpoint_addr.id != self.id(), -845 AddEndpointAddrError::OwnAddress -846 ); -847 self.msock.add_endpoint_addr(endpoint_addr, source).await -848 } -849 -850 // # Getter methods for properties of this Endpoint itself. -851 -852 /// Returns the secret_key of this endpoint. -853 pub fn secret_key(&self) -> &SecretKey { -854 &self.static_config.tls_config.secret_key -855 } +835 /// # Errors +836 /// +837 /// Will return an error if we attempt to add our own [`EndpointId`] to the endpoint map or +838 /// if the direct addresses are a subset of ours. +839 /// +840 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider +841 /// [`RelayUrl`]: crate::RelayUrl +842 pub(crate) async fn add_endpoint_addr( +843 &self, +844 endpoint_addr: EndpointAddr, +845 source: Source, +846 ) -> Result<(), AddEndpointAddrError> { +847 // Connecting to ourselves is not supported. +848 ensure!( +849 endpoint_addr.id != self.id(), +850 AddEndpointAddrError::OwnAddress +851 ); +852 self.msock.add_endpoint_addr(endpoint_addr, source).await +853 } +854 +855 // # Getter methods for properties of this Endpoint itself. 856 -857 /// Returns the endpoint id of this endpoint. -858 /// -859 /// This ID is the unique addressing information of this endpoint and other peers must know -860 /// it to be able to connect to this endpoint. -861 pub fn id(&self) -> EndpointId { -862 self.static_config.tls_config.secret_key.public() -863 } -864 -865 /// Returns the current [`EndpointAddr`]. -866 /// As long as the endpoint was able to bind to a network interface, some -867 /// local addresses will be available. -868 /// -869 /// The state of other fields depends on the state of networking and connectivity. -870 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered -871 /// "online" (has contacted a relay server) before calling this method, if you want -872 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint -873 /// to be dialable by a remote endpoint over the internet. -874 /// -875 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` -876 /// changes. -877 pub fn addr(&self) -> EndpointAddr { -878 self.watch_addr().get() -879 } -880 -881 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -882 /// -883 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. -884 /// -885 /// ```no_run -886 /// # async fn wrapper() -> n0_error::Result<()> { -887 /// use iroh::{Endpoint, Watcher}; -888 /// -889 /// let endpoint = Endpoint::builder() -890 /// .alpns(vec![b"my-alpn".to_vec()]) -891 /// .bind() -892 /// .await?; -893 /// let endpoint_addr = endpoint.watch_addr().get(); -894 /// # let _ = endpoint_addr; -895 /// # Ok(()) -896 /// # } -897 /// ``` -898 /// -899 /// The [`Endpoint::online`] method can be used as a convenience method to -900 /// understand if the endpoint has ever been considered "online". But after -901 /// that initial call to [`Endpoint::online`], to understand if your -902 /// endpoint is no longer able to be connected to by endpoints outside -903 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. -904 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints -905 /// on the internet. -906 /// -907 /// -908 /// The `EndpointAddr` will change as: -909 /// - network conditions change -910 /// - the endpoint connects to a relay server -911 /// - the endpoint changes its preferred relay server -912 /// - more addresses are discovered for this endpoint -913 /// -914 /// [`RelayUrl`]: crate::RelayUrl -915 #[cfg(not(wasm_browser))] -916 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -917 let watch_addrs = self.msock.ip_addrs(); -918 let watch_relay = self.msock.home_relay(); -919 let endpoint_id = self.id(); -920 -921 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { -922 EndpointAddr::from_parts( -923 endpoint_id, -924 relays -925 .into_iter() -926 .map(TransportAddr::Relay) -927 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), -928 ) -929 }) -930 } -931 -932 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -933 /// -934 /// When compiled to Wasm, this function returns a watcher that initializes -935 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, -936 /// as there are no APIs for directly using sockets in browsers. -937 #[cfg(wasm_browser)] -938 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -939 // In browsers, there will never be any direct addresses, so we wait -940 // for the home relay instead. This makes the `EndpointAddr` have *some* way -941 // of connecting to us. -942 let watch_relay = self.msock.home_relay(); -943 let endpoint_id = self.id(); -944 watch_relay.map(move |mut relays| { -945 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) -946 }) -947 } -948 -949 /// A convenience method that waits for the endpoint to be considered "online". -950 /// -951 /// This currently means at least one relay server was connected, -952 /// and at least one local IP address is available. -953 /// Event if no relays are configured, this will still wait for a relay connection. -954 /// -955 /// Once this has been resolved once, this will always immediately resolve. -956 /// -957 /// This has no timeout, so if that is needed, you need to wrap it in a -958 /// timeout. We recommend using a timeout close to -959 /// [`crate::net_report::TIMEOUT`], so you can be sure that at least one -960 /// [`crate::net_report::Report`] has been attempted. +857 /// Returns the secret_key of this endpoint. +858 pub fn secret_key(&self) -> &SecretKey { +859 &self.static_config.tls_config.secret_key +860 } +861 +862 /// Returns the endpoint id of this endpoint. +863 /// +864 /// This ID is the unique addressing information of this endpoint and other peers must know +865 /// it to be able to connect to this endpoint. +866 pub fn id(&self) -> EndpointId { +867 self.static_config.tls_config.secret_key.public() +868 } +869 +870 /// Returns the current [`EndpointAddr`]. +871 /// As long as the endpoint was able to bind to a network interface, some +872 /// local addresses will be available. +873 /// +874 /// The state of other fields depends on the state of networking and connectivity. +875 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered +876 /// "online" (has contacted a relay server) before calling this method, if you want +877 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint +878 /// to be dialable by a remote endpoint over the internet. +879 /// +880 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` +881 /// changes. +882 pub fn addr(&self) -> EndpointAddr { +883 self.watch_addr().get() +884 } +885 +886 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. +887 /// +888 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. +889 /// +890 /// ```no_run +891 /// # async fn wrapper() -> n0_error::Result<()> { +892 /// use iroh::{Endpoint, Watcher}; +893 /// +894 /// let endpoint = Endpoint::builder() +895 /// .alpns(vec![b"my-alpn".to_vec()]) +896 /// .bind() +897 /// .await?; +898 /// let endpoint_addr = endpoint.watch_addr().get(); +899 /// # let _ = endpoint_addr; +900 /// # Ok(()) +901 /// # } +902 /// ``` +903 /// +904 /// The [`Endpoint::online`] method can be used as a convenience method to +905 /// understand if the endpoint has ever been considered "online". But after +906 /// that initial call to [`Endpoint::online`], to understand if your +907 /// endpoint is no longer able to be connected to by endpoints outside +908 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. +909 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints +910 /// on the internet. +911 /// +912 /// +913 /// The `EndpointAddr` will change as: +914 /// - network conditions change +915 /// - the endpoint connects to a relay server +916 /// - the endpoint changes its preferred relay server +917 /// - more addresses are discovered for this endpoint +918 /// +919 /// [`RelayUrl`]: crate::RelayUrl +920 #[cfg(not(wasm_browser))] +921 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +922 let watch_addrs = self.msock.ip_addrs(); +923 let watch_relay = self.msock.home_relay(); +924 let endpoint_id = self.id(); +925 +926 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { +927 EndpointAddr::from_parts( +928 endpoint_id, +929 relays +930 .into_iter() +931 .map(TransportAddr::Relay) +932 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), +933 ) +934 }) +935 } +936 +937 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. +938 /// +939 /// When compiled to Wasm, this function returns a watcher that initializes +940 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, +941 /// as there are no APIs for directly using sockets in browsers. +942 #[cfg(wasm_browser)] +943 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +944 // In browsers, there will never be any direct addresses, so we wait +945 // for the home relay instead. This makes the `EndpointAddr` have *some* way +946 // of connecting to us. +947 let watch_relay = self.msock.home_relay(); +948 let endpoint_id = self.id(); +949 watch_relay.map(move |mut relays| { +950 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) +951 }) +952 } +953 +954 /// A convenience method that waits for the endpoint to be considered "online". +955 /// +956 /// This currently means at least one relay server was connected, +957 /// and at least one local IP address is available. +958 /// Event if no relays are configured, this will still wait for a relay connection. +959 /// +960 /// Once this has been resolved once, this will always immediately resolve. 961 /// -962 /// To understand if the endpoint has gone back "offline", -963 /// you must use the [`Endpoint::watch_addr`] method, to -964 /// get information on the current relay and direct address information. -965 pub async fn online(&self) { -966 self.msock.home_relay().initialized().await; -967 } -968 -969 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. -970 /// -971 /// A `net-report` checks the network conditions of the [`Endpoint`], such as -972 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT -973 /// status, its latency to the relay servers, and its public addresses. -974 /// -975 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network -976 /// conditions have changed. This [`Watcher`] will return the latest result -977 /// of the `net-report`. -978 /// -979 /// When issuing the first call to this method the first report might -980 /// still be underway, in this case the [`Watcher`] might not be initialized -981 /// with [`Some`] value yet. Once the net-report has been successfully -982 /// run, the [`Watcher`] will always return [`Some`] report immediately, which -983 /// is the most recently run `net-report`. -984 /// -985 /// # Examples -986 /// -987 /// To get the first report use [`Watcher::initialized`]: -988 /// ```no_run -989 /// use iroh::{Endpoint, Watcher as _}; -990 /// -991 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -992 /// # rt.block_on(async move { -993 /// let ep = Endpoint::bind().await.unwrap(); -994 /// let _report = ep.net_report().initialized().await; -995 /// # }); -996 /// ``` -997 #[doc(hidden)] -998 pub fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> { -999 self.msock.net_report() -1000 } -1001 -1002 /// Returns the local socket addresses on which the underlying sockets are bound. -1003 /// -1004 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 -1005 /// address if available. -1006 pub fn bound_sockets(&self) -> Vec<SocketAddr> { -1007 self.msock -1008 .local_addr() -1009 .into_iter() -1010 .filter_map(|addr| addr.into_socket_addr()) -1011 .collect() -1012 } -1013 -1014 // # Methods for less common getters. -1015 // -1016 // Partially they return things passed into the builder. -1017 -1018 /// Returns the currently lowest latency for this endpoint. -1019 /// -1020 /// Will return `None` if we do not have any address information for the given `endpoint_id`. -1021 pub async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration> { -1022 self.msock.latency(endpoint_id).await -1023 } -1024 -1025 /// Returns the DNS resolver used in this [`Endpoint`]. -1026 /// -1027 /// See [`Builder::dns_resolver`]. -1028 #[cfg(not(wasm_browser))] -1029 pub fn dns_resolver(&self) -> &DnsResolver { -1030 self.msock.dns_resolver() -1031 } -1032 -1033 /// Returns the discovery mechanism, if configured. -1034 /// -1035 /// See [`Builder::discovery`]. -1036 pub fn discovery(&self) -> &ConcurrentDiscovery { -1037 self.msock.discovery() -1038 } -1039 -1040 /// Returns metrics collected for this endpoint. -1041 /// -1042 /// The endpoint internally collects various metrics about its operation. -1043 /// The returned [`EndpointMetrics`] struct contains all of these metrics. -1044 /// -1045 /// You can access individual metrics directly by using the public fields: -1046 /// ```rust -1047 /// # use std::collections::BTreeMap; -1048 /// # use iroh::endpoint::Endpoint; -1049 /// # async fn wrapper() -> n0_error::Result<()> { -1050 /// let endpoint = Endpoint::bind().await?; -1051 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); -1052 /// # Ok(()) -1053 /// # } -1054 /// ``` -1055 /// -1056 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field -1057 /// implements [`MetricsGroup`]. These traits provide methods to iterate over -1058 /// the groups in the set, and over the individual metrics in each group, without having -1059 /// to access each field manually. With these methods, it is straightforward to collect -1060 /// all metrics into a map or push their values to a metrics collector. -1061 /// -1062 /// For example, the following snippet collects all metrics into a map: -1063 /// ```rust -1064 /// # use std::collections::BTreeMap; -1065 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; -1066 /// # use iroh::endpoint::Endpoint; -1067 /// # async fn wrapper() -> n0_error::Result<()> { -1068 /// let endpoint = Endpoint::bind().await?; -1069 /// let metrics: BTreeMap<String, MetricValue> = endpoint -1070 /// .metrics() -1071 /// .iter() -1072 /// .map(|(group, metric)| { -1073 /// let name = [group, metric.name()].join(":"); -1074 /// (name, metric.value()) -1075 /// }) -1076 /// .collect(); -1077 /// -1078 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); -1079 /// # Ok(()) -1080 /// # } -1081 /// ``` +962 /// This has no timeout, so if that is needed, you need to wrap it in a +963 /// timeout. We recommend using a timeout close to +964 /// [`crate::net_report::TIMEOUT`], so you can be sure that at least one +965 /// [`crate::net_report::Report`] has been attempted. +966 /// +967 /// To understand if the endpoint has gone back "offline", +968 /// you must use the [`Endpoint::watch_addr`] method, to +969 /// get information on the current relay and direct address information. +970 pub async fn online(&self) { +971 self.msock.home_relay().initialized().await; +972 } +973 +974 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. +975 /// +976 /// A `net-report` checks the network conditions of the [`Endpoint`], such as +977 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT +978 /// status, its latency to the relay servers, and its public addresses. +979 /// +980 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network +981 /// conditions have changed. This [`Watcher`] will return the latest result +982 /// of the `net-report`. +983 /// +984 /// When issuing the first call to this method the first report might +985 /// still be underway, in this case the [`Watcher`] might not be initialized +986 /// with [`Some`] value yet. Once the net-report has been successfully +987 /// run, the [`Watcher`] will always return [`Some`] report immediately, which +988 /// is the most recently run `net-report`. +989 /// +990 /// # Examples +991 /// +992 /// To get the first report use [`Watcher::initialized`]: +993 /// ```no_run +994 /// use iroh::{Endpoint, Watcher as _}; +995 /// +996 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +997 /// # rt.block_on(async move { +998 /// let ep = Endpoint::bind().await.unwrap(); +999 /// let _report = ep.net_report().initialized().await; +1000 /// # }); +1001 /// ``` +1002 #[doc(hidden)] +1003 pub fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> { +1004 self.msock.net_report() +1005 } +1006 +1007 /// Returns the local socket addresses on which the underlying sockets are bound. +1008 /// +1009 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 +1010 /// address if available. +1011 pub fn bound_sockets(&self) -> Vec<SocketAddr> { +1012 self.msock +1013 .local_addr() +1014 .into_iter() +1015 .filter_map(|addr| addr.into_socket_addr()) +1016 .collect() +1017 } +1018 +1019 // # Methods for less common getters. +1020 // +1021 // Partially they return things passed into the builder. +1022 +1023 /// Returns the currently lowest latency for this endpoint. +1024 /// +1025 /// Will return `None` if we do not have any address information for the given `endpoint_id`. +1026 pub async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration> { +1027 self.msock.latency(endpoint_id).await +1028 } +1029 +1030 /// Returns the DNS resolver used in this [`Endpoint`]. +1031 /// +1032 /// See [`Builder::dns_resolver`]. +1033 #[cfg(not(wasm_browser))] +1034 pub fn dns_resolver(&self) -> &DnsResolver { +1035 self.msock.dns_resolver() +1036 } +1037 +1038 /// Returns the discovery mechanism, if configured. +1039 /// +1040 /// See [`Builder::discovery`]. +1041 pub fn discovery(&self) -> &ConcurrentDiscovery { +1042 self.msock.discovery() +1043 } +1044 +1045 /// Returns metrics collected for this endpoint. +1046 /// +1047 /// The endpoint internally collects various metrics about its operation. +1048 /// The returned [`EndpointMetrics`] struct contains all of these metrics. +1049 /// +1050 /// You can access individual metrics directly by using the public fields: +1051 /// ```rust +1052 /// # use std::collections::BTreeMap; +1053 /// # use iroh::endpoint::Endpoint; +1054 /// # async fn wrapper() -> n0_error::Result<()> { +1055 /// let endpoint = Endpoint::bind().await?; +1056 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); +1057 /// # Ok(()) +1058 /// # } +1059 /// ``` +1060 /// +1061 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field +1062 /// implements [`MetricsGroup`]. These traits provide methods to iterate over +1063 /// the groups in the set, and over the individual metrics in each group, without having +1064 /// to access each field manually. With these methods, it is straightforward to collect +1065 /// all metrics into a map or push their values to a metrics collector. +1066 /// +1067 /// For example, the following snippet collects all metrics into a map: +1068 /// ```rust +1069 /// # use std::collections::BTreeMap; +1070 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; +1071 /// # use iroh::endpoint::Endpoint; +1072 /// # async fn wrapper() -> n0_error::Result<()> { +1073 /// let endpoint = Endpoint::bind().await?; +1074 /// let metrics: BTreeMap<String, MetricValue> = endpoint +1075 /// .metrics() +1076 /// .iter() +1077 /// .map(|(group, metric)| { +1078 /// let name = [group, metric.name()].join(":"); +1079 /// (name, metric.value()) +1080 /// }) +1081 /// .collect(); 1082 /// -1083 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. -1084 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the -1085 /// registry with [`Registry::register_all`], and encode the metrics to a string with -1086 /// [`encode_openmetrics_to_string`]: -1087 /// ```rust -1088 /// # use iroh_metrics::{Registry, MetricsSource}; -1089 /// # use iroh::endpoint::Endpoint; -1090 /// # async fn wrapper() -> n0_error::Result<()> { -1091 /// let endpoint = Endpoint::bind().await?; -1092 /// let mut registry = Registry::default(); -1093 /// registry.register_all(endpoint.metrics()); -1094 /// let s = registry.encode_openmetrics_to_string()?; -1095 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1096 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); -1097 /// # Ok(()) -1098 /// # } -1099 /// ``` -1100 /// -1101 /// Through a registry, you can also add labels or prefixes to metrics with -1102 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. -1103 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services -1104 /// to serve the metrics with a HTTP server, dump them to a file, or push them -1105 /// to a Prometheus gateway. -1106 /// -1107 /// For example, the following snippet launches an HTTP server that serves the metrics in the -1108 /// OpenMetrics text format: -1109 /// ```no_run -1110 /// # use std::{sync::{Arc, RwLock}, time::Duration}; -1111 /// # use iroh_metrics::{Registry, MetricsSource}; -1112 /// # use iroh::endpoint::Endpoint; -1113 /// # use n0_error::{StackResultExt, StdResultExt}; -1114 /// # async fn wrapper() -> n0_error::Result<()> { -1115 /// // Create a registry, wrapped in a read-write lock so that we can register and serve -1116 /// // the metrics independently. -1117 /// let registry = Arc::new(RwLock::new(Registry::default())); -1118 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. -1119 /// let metrics_task = tokio::task::spawn({ -1120 /// let registry = registry.clone(); -1121 /// async move { -1122 /// let addr = "0.0.0.0:9100".parse().unwrap(); -1123 /// iroh_metrics::service::start_metrics_server(addr, registry).await -1124 /// } -1125 /// }); -1126 /// -1127 /// // Spawn an endpoint and add the metrics to the registry. -1128 /// let endpoint = Endpoint::bind().await?; -1129 /// registry.write().unwrap().register_all(endpoint.metrics()); -1130 /// -1131 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. -1132 /// tokio::time::sleep(Duration::from_millis(500)); -1133 /// let res = reqwest::get("http://localhost:9100/metrics") -1134 /// .await -1135 /// .std_context("get")? -1136 /// .text() -1137 /// .await -1138 /// .std_context("text")?; -1139 /// -1140 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1141 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); -1142 /// # metrics_task.abort(); -1143 /// # Ok(()) -1144 /// # } -1145 /// ``` -1146 /// -1147 /// [`Registry`]: iroh_metrics::Registry -1148 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all -1149 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label -1150 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix -1151 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string -1152 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup -1153 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet -1154 #[cfg(feature = "metrics")] -1155 pub fn metrics(&self) -> &EndpointMetrics { -1156 &self.msock.metrics -1157 } -1158 -1159 // # Methods for less common state updates. -1160 -1161 /// Notifies the system of potential network changes. -1162 /// -1163 /// On many systems iroh is able to detect network changes by itself, however -1164 /// some systems like android do not expose this functionality to native code. -1165 /// Android does however provide this functionality to Java code. This -1166 /// function allows for notifying iroh of any potential network changes like -1167 /// this. -1168 /// -1169 /// Even when the network did not change, or iroh was already able to detect -1170 /// the network change itself, there is no harm in calling this function. -1171 pub async fn network_change(&self) { -1172 self.msock.network_change().await; -1173 } -1174 -1175 // # Methods to update internal state. -1176 -1177 /// Sets the initial user-defined data to be published in discovery services for this endpoint. -1178 /// -1179 /// If the user-defined data passed to this function is different to the previous one, -1180 /// the endpoint will republish its endpoint info to the configured discovery services. -1181 /// -1182 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when -1183 /// building the endpoint. -1184 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { -1185 self.msock.set_user_data_for_discovery(user_data); -1186 } -1187 -1188 // # Methods for terminating the endpoint. -1189 -1190 /// Closes the QUIC endpoint and the magic socket. -1191 /// -1192 /// This will close any remaining open [`Connection`]s with an error code -1193 /// of `0` and an empty reason. Though it is best practice to close those -1194 /// explicitly before with a custom error code and reason. -1195 /// -1196 /// It will then make a best effort to wait for all close notifications to be -1197 /// acknowledged by the peers, re-transmitting them if needed. This ensures the -1198 /// peers are aware of the closed connections instead of having to wait for a timeout -1199 /// on the connection. Once all connections are closed or timed out, the future -1200 /// finishes. -1201 /// -1202 /// The maximum time-out that this future will wait for depends on QUIC transport -1203 /// configurations of non-drained connections at the time of calling, and their current -1204 /// estimates of round trip time. With default parameters and a conservative estimate -1205 /// of round trip time, this call's future should take 3 seconds to resolve in cases of -1206 /// bad connectivity or failed connections. In the usual case, this call's future should -1207 /// return much more quickly. -1208 /// -1209 /// It is highly recommended you *do* wait for this close call to finish, if possible. -1210 /// Not doing so will make connections that were still open while closing the endpoint -1211 /// time out on the remote end. Thus remote ends will assume connections to have failed -1212 /// even if all application data was transmitted successfully. +1083 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); +1084 /// # Ok(()) +1085 /// # } +1086 /// ``` +1087 /// +1088 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. +1089 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the +1090 /// registry with [`Registry::register_all`], and encode the metrics to a string with +1091 /// [`encode_openmetrics_to_string`]: +1092 /// ```rust +1093 /// # use iroh_metrics::{Registry, MetricsSource}; +1094 /// # use iroh::endpoint::Endpoint; +1095 /// # async fn wrapper() -> n0_error::Result<()> { +1096 /// let endpoint = Endpoint::bind().await?; +1097 /// let mut registry = Registry::default(); +1098 /// registry.register_all(endpoint.metrics()); +1099 /// let s = registry.encode_openmetrics_to_string()?; +1100 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1101 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); +1102 /// # Ok(()) +1103 /// # } +1104 /// ``` +1105 /// +1106 /// Through a registry, you can also add labels or prefixes to metrics with +1107 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. +1108 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services +1109 /// to serve the metrics with a HTTP server, dump them to a file, or push them +1110 /// to a Prometheus gateway. +1111 /// +1112 /// For example, the following snippet launches an HTTP server that serves the metrics in the +1113 /// OpenMetrics text format: +1114 /// ```no_run +1115 /// # use std::{sync::{Arc, RwLock}, time::Duration}; +1116 /// # use iroh_metrics::{Registry, MetricsSource}; +1117 /// # use iroh::endpoint::Endpoint; +1118 /// # use n0_error::{StackResultExt, StdResultExt}; +1119 /// # async fn wrapper() -> n0_error::Result<()> { +1120 /// // Create a registry, wrapped in a read-write lock so that we can register and serve +1121 /// // the metrics independently. +1122 /// let registry = Arc::new(RwLock::new(Registry::default())); +1123 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. +1124 /// let metrics_task = tokio::task::spawn({ +1125 /// let registry = registry.clone(); +1126 /// async move { +1127 /// let addr = "0.0.0.0:9100".parse().unwrap(); +1128 /// iroh_metrics::service::start_metrics_server(addr, registry).await +1129 /// } +1130 /// }); +1131 /// +1132 /// // Spawn an endpoint and add the metrics to the registry. +1133 /// let endpoint = Endpoint::bind().await?; +1134 /// registry.write().unwrap().register_all(endpoint.metrics()); +1135 /// +1136 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. +1137 /// tokio::time::sleep(Duration::from_millis(500)); +1138 /// let res = reqwest::get("http://localhost:9100/metrics") +1139 /// .await +1140 /// .std_context("get")? +1141 /// .text() +1142 /// .await +1143 /// .std_context("text")?; +1144 /// +1145 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1146 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); +1147 /// # metrics_task.abort(); +1148 /// # Ok(()) +1149 /// # } +1150 /// ``` +1151 /// +1152 /// [`Registry`]: iroh_metrics::Registry +1153 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all +1154 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label +1155 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix +1156 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string +1157 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup +1158 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet +1159 #[cfg(feature = "metrics")] +1160 pub fn metrics(&self) -> &EndpointMetrics { +1161 &self.msock.metrics +1162 } +1163 +1164 // # Methods for less common state updates. +1165 +1166 /// Notifies the system of potential network changes. +1167 /// +1168 /// On many systems iroh is able to detect network changes by itself, however +1169 /// some systems like android do not expose this functionality to native code. +1170 /// Android does however provide this functionality to Java code. This +1171 /// function allows for notifying iroh of any potential network changes like +1172 /// this. +1173 /// +1174 /// Even when the network did not change, or iroh was already able to detect +1175 /// the network change itself, there is no harm in calling this function. +1176 pub async fn network_change(&self) { +1177 self.msock.network_change().await; +1178 } +1179 +1180 // # Methods to update internal state. +1181 +1182 /// Sets the initial user-defined data to be published in discovery services for this endpoint. +1183 /// +1184 /// If the user-defined data passed to this function is different to the previous one, +1185 /// the endpoint will republish its endpoint info to the configured discovery services. +1186 /// +1187 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when +1188 /// building the endpoint. +1189 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { +1190 self.msock.set_user_data_for_discovery(user_data); +1191 } +1192 +1193 // # Methods for terminating the endpoint. +1194 +1195 /// Closes the QUIC endpoint and the magic socket. +1196 /// +1197 /// This will close any remaining open [`Connection`]s with an error code +1198 /// of `0` and an empty reason. Though it is best practice to close those +1199 /// explicitly before with a custom error code and reason. +1200 /// +1201 /// It will then make a best effort to wait for all close notifications to be +1202 /// acknowledged by the peers, re-transmitting them if needed. This ensures the +1203 /// peers are aware of the closed connections instead of having to wait for a timeout +1204 /// on the connection. Once all connections are closed or timed out, the future +1205 /// finishes. +1206 /// +1207 /// The maximum time-out that this future will wait for depends on QUIC transport +1208 /// configurations of non-drained connections at the time of calling, and their current +1209 /// estimates of round trip time. With default parameters and a conservative estimate +1210 /// of round trip time, this call's future should take 3 seconds to resolve in cases of +1211 /// bad connectivity or failed connections. In the usual case, this call's future should +1212 /// return much more quickly. 1213 /// -1214 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait -1215 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP -1216 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, -1217 /// while TCP sockets usually get closed and drained by the operating system in the -1218 /// kernel during the "Time-Wait" period of the TCP socket. -1219 /// -1220 /// Be aware however that the underlying UDP sockets are only closed once all clones of -1221 /// the the respective [`Endpoint`] are dropped. -1222 pub async fn close(&self) { -1223 if self.is_closed() { -1224 return; -1225 } -1226 -1227 tracing::debug!("Connections closed"); -1228 self.msock.close().await; -1229 } -1230 -1231 /// Check if this endpoint is still alive, or already closed. -1232 pub fn is_closed(&self) -> bool { -1233 self.msock.is_closed() +1214 /// It is highly recommended you *do* wait for this close call to finish, if possible. +1215 /// Not doing so will make connections that were still open while closing the endpoint +1216 /// time out on the remote end. Thus remote ends will assume connections to have failed +1217 /// even if all application data was transmitted successfully. +1218 /// +1219 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait +1220 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP +1221 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, +1222 /// while TCP sockets usually get closed and drained by the operating system in the +1223 /// kernel during the "Time-Wait" period of the TCP socket. +1224 /// +1225 /// Be aware however that the underlying UDP sockets are only closed once all clones of +1226 /// the the respective [`Endpoint`] are dropped. +1227 pub async fn close(&self) { +1228 if self.is_closed() { +1229 return; +1230 } +1231 +1232 tracing::debug!("Connections closed"); +1233 self.msock.close().await; 1234 } 1235 -1236 // # Remaining private methods -1237 -1238 /// Return the quic mapped address for this `endpoint_id` and possibly start discovery -1239 /// services if discovery is enabled on this magic endpoint. -1240 /// -1241 /// This will launch discovery in all cases except if: -1242 /// 1) we do not have discovery enabled -1243 /// 2) we have discovery enabled, but already have at least one verified, unexpired -1244 /// addresses for this `endpoint_id` +1236 /// Check if this endpoint is still alive, or already closed. +1237 pub fn is_closed(&self) -> bool { +1238 self.msock.is_closed() +1239 } +1240 +1241 // # Remaining private methods +1242 +1243 /// Return the quic mapped address for this `endpoint_id` and possibly start discovery +1244 /// services if discovery is enabled on this magic endpoint. 1245 /// -1246 /// # Errors -1247 /// -1248 /// This method may fail if we have no way of dialing the endpoint. This can occur if -1249 /// we were given no dialing information in the [`EndpointAddr`] and no discovery -1250 /// services were configured or if discovery failed to fetch any dialing information. -1251 async fn get_mapping_addr_and_maybe_start_discovery( -1252 &self, -1253 endpoint_addr: EndpointAddr, -1254 ) -> Result<(EndpointIdMappedAddr, Option<DiscoveryTask>), GetMappingAddressError> { -1255 let endpoint_id = endpoint_addr.id; -1256 -1257 // Only return a mapped addr if we have some way of dialing this endpoint, in other -1258 // words, we have either a relay URL or at least one direct address. -1259 let addr = if self.msock.has_send_address(endpoint_id).await { -1260 Some(self.msock.get_endpoint_mapped_addr(endpoint_id)) -1261 } else { -1262 None -1263 }; -1264 match addr { -1265 Some(maddr) => { -1266 // We have some way of dialing this endpoint, but that doesn't mean we can -1267 // connect to any of these addresses. Start discovery after a small delay. -1268 let discovery = -1269 DiscoveryTask::start_after_delay(self, endpoint_id, DISCOVERY_WAIT_PERIOD) -1270 .ok() -1271 .flatten(); -1272 Ok((maddr, discovery)) -1273 } -1274 -1275 None => { -1276 // We have no known addresses or relay URLs for this endpoint. -1277 // So, we start a discovery task and wait for the first result to arrive, and -1278 // only then continue, because otherwise we wouldn't have any -1279 // path to the remote endpoint. -1280 let res = DiscoveryTask::start(self.clone(), endpoint_id); -1281 let mut discovery = -1282 res.map_err(|err| e!(GetMappingAddressError::DiscoveryStart, err))?; -1283 discovery -1284 .first_arrived() -1285 .await -1286 .map_err(|err| e!(GetMappingAddressError::Discover, err))?; -1287 -1288 let addr = self.msock.get_endpoint_mapped_addr(endpoint_id); -1289 Ok((addr, Some(discovery))) -1290 } -1291 } -1292 } -1293 -1294 #[cfg(test)] -1295 pub(crate) fn magic_sock(&self) -> Handle { -1296 self.msock.clone() +1246 /// This will launch discovery in all cases except if: +1247 /// 1) we do not have discovery enabled +1248 /// 2) we have discovery enabled, but already have at least one verified, unexpired +1249 /// addresses for this `endpoint_id` +1250 /// +1251 /// # Errors +1252 /// +1253 /// This method may fail if we have no way of dialing the endpoint. This can occur if +1254 /// we were given no dialing information in the [`EndpointAddr`] and no discovery +1255 /// services were configured or if discovery failed to fetch any dialing information. +1256 async fn get_mapping_addr_and_maybe_start_discovery( +1257 &self, +1258 endpoint_addr: EndpointAddr, +1259 ) -> Result<(EndpointIdMappedAddr, Option<DiscoveryTask>), GetMappingAddressError> { +1260 let endpoint_id = endpoint_addr.id; +1261 +1262 // Only return a mapped addr if we have some way of dialing this endpoint, in other +1263 // words, we have either a relay URL or at least one direct address. +1264 let addr = if self.msock.has_send_address(endpoint_id).await { +1265 Some(self.msock.get_endpoint_mapped_addr(endpoint_id)) +1266 } else { +1267 None +1268 }; +1269 match addr { +1270 Some(maddr) => { +1271 // We have some way of dialing this endpoint, but that doesn't mean we can +1272 // connect to any of these addresses. Start discovery after a small delay. +1273 let discovery = +1274 DiscoveryTask::start_after_delay(self, endpoint_id, DISCOVERY_WAIT_PERIOD) +1275 .ok() +1276 .flatten(); +1277 Ok((maddr, discovery)) +1278 } +1279 +1280 None => { +1281 // We have no known addresses or relay URLs for this endpoint. +1282 // So, we start a discovery task and wait for the first result to arrive, and +1283 // only then continue, because otherwise we wouldn't have any +1284 // path to the remote endpoint. +1285 let res = DiscoveryTask::start(self.clone(), endpoint_id); +1286 let mut discovery = +1287 res.map_err(|err| e!(GetMappingAddressError::DiscoveryStart, err))?; +1288 discovery +1289 .first_arrived() +1290 .await +1291 .map_err(|err| e!(GetMappingAddressError::Discover, err))?; +1292 +1293 let addr = self.msock.get_endpoint_mapped_addr(endpoint_id); +1294 Ok((addr, Some(discovery))) +1295 } +1296 } 1297 } -1298 #[cfg(test)] -1299 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { -1300 self.msock.endpoint() -1301 } -1302} -1303 -1304/// Options for the [`Endpoint::connect_with_opts`] function. -1305#[derive(Default, Debug, Clone)] -1306pub struct ConnectOptions { -1307 transport_config: Option<Arc<quinn::TransportConfig>>, -1308 additional_alpns: Vec<Vec<u8>>, -1309} -1310 -1311impl ConnectOptions { -1312 /// Initializes new connection options. -1313 /// -1314 /// By default, the connection will use the same options -1315 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`]. -1316 pub fn new() -> Self { -1317 Self::default() -1318 } -1319 -1320 /// Sets the QUIC transport config options for this connection. -1321 pub fn with_transport_config(mut self, transport_config: Arc<quinn::TransportConfig>) -> Self { -1322 self.transport_config = Some(transport_config); -1323 self -1324 } -1325 -1326 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in -1327 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. -1328 /// -1329 /// This allows connecting to servers that may only support older versions of your -1330 /// protocol. In this case, you would add the older [ALPN] identifiers with this -1331 /// function. -1332 /// -1333 /// You'll know the final negotiated [ALPN] identifier once your connection was -1334 /// established using [`Connection::alpn`], or even slightly earlier in the -1335 /// handshake by using [`Connecting::alpn`]. -1336 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this -1337 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. -1338 /// -1339 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the -1340 /// accept side that determines the protocol. -1341 /// -1342 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint -1343 /// builder's [`Builder::alpns`] function. -1344 /// -1345 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -1346 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { -1347 self.additional_alpns = alpns; -1348 self -1349 } -1350} -1351 -1352/// Read a proxy url from the environment, in this order -1353/// -1354/// - `HTTP_PROXY` -1355/// - `http_proxy` -1356/// - `HTTPS_PROXY` -1357/// - `https_proxy` -1358fn proxy_url_from_env() -> Option<Url> { -1359 if let Some(url) = std::env::var("HTTP_PROXY") -1360 .ok() -1361 .and_then(|s| s.parse::<Url>().ok()) -1362 { -1363 if is_cgi() { -1364 warn!("HTTP_PROXY environment variable ignored in CGI"); -1365 } else { -1366 return Some(url); -1367 } -1368 } -1369 if let Some(url) = std::env::var("http_proxy") -1370 .ok() -1371 .and_then(|s| s.parse::<Url>().ok()) -1372 { -1373 return Some(url); -1374 } -1375 if let Some(url) = std::env::var("HTTPS_PROXY") -1376 .ok() -1377 .and_then(|s| s.parse::<Url>().ok()) -1378 { -1379 return Some(url); -1380 } -1381 if let Some(url) = std::env::var("https_proxy") -1382 .ok() -1383 .and_then(|s| s.parse::<Url>().ok()) -1384 { -1385 return Some(url); -1386 } -1387 -1388 None -1389} -1390 -1391/// Configuration of the relay servers for an [`Endpoint`]. -1392#[derive(Debug, Clone, PartialEq, Eq)] -1393pub enum RelayMode { -1394 /// Disable relay servers completely. -1395 Disabled, -1396 /// Use the default relay map, with production relay servers from n0. -1397 /// -1398 /// See [`crate::defaults::prod`] for the severs used. -1399 Default, -1400 /// Use the staging relay servers from n0. -1401 Staging, -1402 /// Use a custom relay map. -1403 Custom(RelayMap), -1404} -1405 -1406impl RelayMode { -1407 /// Returns the relay map for this mode. -1408 pub fn relay_map(&self) -> RelayMap { -1409 match self { -1410 RelayMode::Disabled => RelayMap::empty(), -1411 RelayMode::Default => crate::defaults::prod::default_relay_map(), -1412 RelayMode::Staging => crate::defaults::staging::default_relay_map(), -1413 RelayMode::Custom(relay_map) => relay_map.clone(), -1414 } -1415 } -1416} -1417 -1418/// Environment variable to force the use of staging relays. -1419pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; -1420 -1421/// Returns `true` if the use of staging relays is forced. -1422pub fn force_staging_infra() -> bool { -1423 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) -1424} +1298 +1299 #[cfg(test)] +1300 pub(crate) fn magic_sock(&self) -> Handle { +1301 self.msock.clone() +1302 } +1303 #[cfg(test)] +1304 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { +1305 self.msock.endpoint() +1306 } +1307} +1308 +1309/// Options for the [`Endpoint::connect_with_opts`] function. +1310#[derive(Default, Debug, Clone)] +1311pub struct ConnectOptions { +1312 transport_config: Option<Arc<quinn::TransportConfig>>, +1313 additional_alpns: Vec<Vec<u8>>, +1314} +1315 +1316impl ConnectOptions { +1317 /// Initializes new connection options. +1318 /// +1319 /// By default, the connection will use the same options +1320 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`]. +1321 pub fn new() -> Self { +1322 Self::default() +1323 } +1324 +1325 /// Sets the QUIC transport config options for this connection. +1326 pub fn with_transport_config(mut self, transport_config: Arc<quinn::TransportConfig>) -> Self { +1327 self.transport_config = Some(transport_config); +1328 self +1329 } +1330 +1331 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in +1332 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. +1333 /// +1334 /// This allows connecting to servers that may only support older versions of your +1335 /// protocol. In this case, you would add the older [ALPN] identifiers with this +1336 /// function. +1337 /// +1338 /// You'll know the final negotiated [ALPN] identifier once your connection was +1339 /// established using [`Connection::alpn`], or even slightly earlier in the +1340 /// handshake by using [`Connecting::alpn`]. +1341 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this +1342 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. +1343 /// +1344 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the +1345 /// accept side that determines the protocol. +1346 /// +1347 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint +1348 /// builder's [`Builder::alpns`] function. +1349 /// +1350 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +1351 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { +1352 self.additional_alpns = alpns; +1353 self +1354 } +1355} +1356 +1357/// Read a proxy url from the environment, in this order +1358/// +1359/// - `HTTP_PROXY` +1360/// - `http_proxy` +1361/// - `HTTPS_PROXY` +1362/// - `https_proxy` +1363fn proxy_url_from_env() -> Option<Url> { +1364 if let Some(url) = std::env::var("HTTP_PROXY") +1365 .ok() +1366 .and_then(|s| s.parse::<Url>().ok()) +1367 { +1368 if is_cgi() { +1369 warn!("HTTP_PROXY environment variable ignored in CGI"); +1370 } else { +1371 return Some(url); +1372 } +1373 } +1374 if let Some(url) = std::env::var("http_proxy") +1375 .ok() +1376 .and_then(|s| s.parse::<Url>().ok()) +1377 { +1378 return Some(url); +1379 } +1380 if let Some(url) = std::env::var("HTTPS_PROXY") +1381 .ok() +1382 .and_then(|s| s.parse::<Url>().ok()) +1383 { +1384 return Some(url); +1385 } +1386 if let Some(url) = std::env::var("https_proxy") +1387 .ok() +1388 .and_then(|s| s.parse::<Url>().ok()) +1389 { +1390 return Some(url); +1391 } +1392 +1393 None +1394} +1395 +1396/// Configuration of the relay servers for an [`Endpoint`]. +1397#[derive(Debug, Clone, PartialEq, Eq)] +1398pub enum RelayMode { +1399 /// Disable relay servers completely. +1400 Disabled, +1401 /// Use the default relay map, with production relay servers from n0. +1402 /// +1403 /// See [`crate::defaults::prod`] for the severs used. +1404 Default, +1405 /// Use the staging relay servers from n0. +1406 Staging, +1407 /// Use a custom relay map. +1408 Custom(RelayMap), +1409} +1410 +1411impl RelayMode { +1412 /// Returns the relay map for this mode. +1413 pub fn relay_map(&self) -> RelayMap { +1414 match self { +1415 RelayMode::Disabled => RelayMap::empty(), +1416 RelayMode::Default => crate::defaults::prod::default_relay_map(), +1417 RelayMode::Staging => crate::defaults::staging::default_relay_map(), +1418 RelayMode::Custom(relay_map) => relay_map.clone(), +1419 } +1420 } +1421} +1422 +1423/// Environment variable to force the use of staging relays. +1424pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; 1425 -1426/// Returns the default relay mode. -1427/// -1428/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. -1429/// Otherwise, it will return `RelayMode::Default`. -1430pub fn default_relay_mode() -> RelayMode { -1431 // Use staging in testing -1432 match force_staging_infra() { -1433 true => RelayMode::Staging, -1434 false => RelayMode::Default, -1435 } -1436} -1437 -1438/// Check if we are being executed in a CGI context. -1439/// -1440/// If so, a malicious client can send the `Proxy:` header, and it will -1441/// be in the `HTTP_PROXY` env var. So we don't use it :) -1442fn is_cgi() -> bool { -1443 std::env::var_os("REQUEST_METHOD").is_some() -1444} -1445 -1446// TODO: These tests could still be flaky, lets fix that: -1447// https://github.com/n0-computer/iroh/issues/1183 -1448#[cfg(test)] -1449mod tests { -1450 use std::time::{Duration, Instant}; -1451 -1452 use iroh_base::{EndpointAddr, EndpointId, SecretKey, TransportAddr}; -1453 use n0_error::{AnyError as Error, Result, StdResultExt}; -1454 use n0_future::{BufferedStreamExt, StreamExt, stream, time}; -1455 use n0_watcher::Watcher; -1456 use quinn::ConnectionError; -1457 use rand::SeedableRng; -1458 use tokio::sync::oneshot; -1459 use tracing::{Instrument, error_span, info, info_span, instrument}; -1460 use tracing_test::traced_test; -1461 -1462 use super::Endpoint; -1463 use crate::{ -1464 RelayMap, RelayMode, -1465 discovery::static_provider::StaticProvider, -1466 endpoint::{ConnectOptions, Connection}, -1467 protocol::{AcceptError, ProtocolHandler, Router}, -1468 test_utils::{run_relay_server, run_relay_server_with}, -1469 }; -1470 -1471 const TEST_ALPN: &[u8] = b"n0/iroh/test"; -1472 -1473 #[tokio::test] -1474 #[traced_test] -1475 async fn test_connect_self() -> Result { -1476 let ep = Endpoint::empty_builder(RelayMode::Disabled) -1477 .alpns(vec![TEST_ALPN.to_vec()]) -1478 .bind() -1479 .await -1480 .unwrap(); -1481 let my_addr = ep.addr(); -1482 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; -1483 assert!(res.is_err()); -1484 let err = res.err().unwrap(); -1485 assert!(err.to_string().starts_with("Connecting to ourself")); -1486 -1487 Ok(()) -1488 } -1489 -1490 #[tokio::test] -1491 #[traced_test] -1492 async fn endpoint_connect_close() -> Result { -1493 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1494 let (relay_map, relay_url, _guard) = run_relay_server().await?; -1495 let server_secret_key = SecretKey::generate(&mut rng); -1496 let server_peer_id = server_secret_key.public(); -1497 -1498 // Wait for the endpoint to be started to make sure it's up before clients try to connect -1499 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1500 .secret_key(server_secret_key) -1501 .alpns(vec![TEST_ALPN.to_vec()]) -1502 .insecure_skip_relay_cert_verify(true) -1503 .bind() -1504 .await?; -1505 // Wait for the endpoint to be reachable via relay -1506 ep.online().await; -1507 -1508 let server = tokio::spawn( -1509 async move { -1510 info!("accepting connection"); -1511 let incoming = ep.accept().await.anyerr()?; -1512 let conn = incoming.await.anyerr()?; -1513 let mut stream = conn.accept_uni().await.anyerr()?; -1514 let mut buf = [0u8; 5]; -1515 stream.read_exact(&mut buf).await.anyerr()?; -1516 info!("Accepted 1 stream, received {buf:?}. Closing now."); -1517 // close the connection -1518 conn.close(7u8.into(), b"bye"); -1519 -1520 let res = conn.accept_uni().await; -1521 assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed); -1522 -1523 let res = stream.read_to_end(10).await; -1524 assert_eq!( -1525 res.unwrap_err(), -1526 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( -1527 quinn::ConnectionError::LocallyClosed -1528 )) -1529 ); -1530 info!("server test completed"); -1531 Ok::<_, Error>(()) -1532 } -1533 .instrument(info_span!("test-server")), -1534 ); -1535 -1536 let client = tokio::spawn( -1537 async move { -1538 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -1539 .alpns(vec![TEST_ALPN.to_vec()]) -1540 .insecure_skip_relay_cert_verify(true) -1541 .bind() -1542 .await?; -1543 info!("client connecting"); -1544 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); -1545 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; -1546 let mut stream = conn.open_uni().await.anyerr()?; -1547 -1548 // First write is accepted by server. We need this bit of synchronisation -1549 // because if the server closes after simply accepting the connection we can -1550 // not be sure our .open_uni() call would succeed as it may already receive -1551 // the error. -1552 stream.write_all(b"hello").await.anyerr()?; -1553 -1554 info!("waiting for closed"); -1555 // Remote now closes the connection, we should see an error sometime soon. -1556 let err = conn.closed().await; -1557 let expected_err = -1558 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose { -1559 error_code: 7u8.into(), -1560 reason: b"bye".to_vec().into(), -1561 }); -1562 assert_eq!(err, expected_err); -1563 -1564 info!("opening new - expect it to fail"); -1565 let res = conn.open_uni().await; -1566 assert_eq!(res.unwrap_err(), expected_err); -1567 info!("client test completed"); -1568 Ok::<_, Error>(()) -1569 } -1570 .instrument(info_span!("test-client")), -1571 ); -1572 -1573 let (server, client) = tokio::time::timeout( -1574 Duration::from_secs(30), -1575 n0_future::future::zip(server, client), -1576 ) -1577 .await -1578 .anyerr()?; -1579 server.anyerr()??; -1580 client.anyerr()??; -1581 Ok(()) -1582 } -1583 -1584 #[tokio::test] -1585 #[traced_test] -1586 async fn endpoint_relay_connect_loop() -> Result { -1587 let test_start = Instant::now(); -1588 let n_clients = 5; -1589 let n_chunks_per_client = 2; -1590 let chunk_size = 10; -1591 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); -1592 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); -1593 let server_secret_key = SecretKey::generate(&mut rng); -1594 let server_endpoint_id = server_secret_key.public(); -1595 -1596 // Make sure the server is bound before having clients connect to it: -1597 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1598 .insecure_skip_relay_cert_verify(true) -1599 .secret_key(server_secret_key) -1600 .alpns(vec![TEST_ALPN.to_vec()]) -1601 .bind() -1602 .await?; -1603 // Also make sure the server has a working relay connection -1604 ep.online().await; -1605 -1606 info!(time = ?test_start.elapsed(), "test setup done"); -1607 -1608 // The server accepts the connections of the clients sequentially. -1609 let server = tokio::spawn( -1610 async move { -1611 let eps = ep.bound_sockets(); +1426/// Returns `true` if the use of staging relays is forced. +1427pub fn force_staging_infra() -> bool { +1428 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) +1429} +1430 +1431/// Returns the default relay mode. +1432/// +1433/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. +1434/// Otherwise, it will return `RelayMode::Default`. +1435pub fn default_relay_mode() -> RelayMode { +1436 // Use staging in testing +1437 match force_staging_infra() { +1438 true => RelayMode::Staging, +1439 false => RelayMode::Default, +1440 } +1441} +1442 +1443/// Check if we are being executed in a CGI context. +1444/// +1445/// If so, a malicious client can send the `Proxy:` header, and it will +1446/// be in the `HTTP_PROXY` env var. So we don't use it :) +1447fn is_cgi() -> bool { +1448 std::env::var_os("REQUEST_METHOD").is_some() +1449} +1450 +1451// TODO: These tests could still be flaky, lets fix that: +1452// https://github.com/n0-computer/iroh/issues/1183 +1453#[cfg(test)] +1454mod tests { +1455 use std::time::{Duration, Instant}; +1456 +1457 use iroh_base::{EndpointAddr, EndpointId, SecretKey, TransportAddr}; +1458 use n0_error::{AnyError as Error, Result, StdResultExt}; +1459 use n0_future::{BufferedStreamExt, StreamExt, stream, time}; +1460 use n0_watcher::Watcher; +1461 use quinn::ConnectionError; +1462 use rand::SeedableRng; +1463 use tokio::sync::oneshot; +1464 use tracing::{Instrument, error_span, info, info_span, instrument}; +1465 use tracing_test::traced_test; +1466 +1467 use super::Endpoint; +1468 use crate::{ +1469 RelayMap, RelayMode, +1470 discovery::static_provider::StaticProvider, +1471 endpoint::{ConnectOptions, Connection}, +1472 protocol::{AcceptError, ProtocolHandler, Router}, +1473 test_utils::{run_relay_server, run_relay_server_with}, +1474 }; +1475 +1476 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +1477 +1478 #[tokio::test] +1479 #[traced_test] +1480 async fn test_connect_self() -> Result { +1481 let ep = Endpoint::empty_builder(RelayMode::Disabled) +1482 .alpns(vec![TEST_ALPN.to_vec()]) +1483 .bind() +1484 .await +1485 .unwrap(); +1486 let my_addr = ep.addr(); +1487 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; +1488 assert!(res.is_err()); +1489 let err = res.err().unwrap(); +1490 assert!(err.to_string().starts_with("Connecting to ourself")); +1491 +1492 Ok(()) +1493 } +1494 +1495 #[tokio::test] +1496 #[traced_test] +1497 async fn endpoint_connect_close() -> Result { +1498 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1499 let (relay_map, relay_url, _guard) = run_relay_server().await?; +1500 let server_secret_key = SecretKey::generate(&mut rng); +1501 let server_peer_id = server_secret_key.public(); +1502 +1503 // Wait for the endpoint to be started to make sure it's up before clients try to connect +1504 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1505 .secret_key(server_secret_key) +1506 .alpns(vec![TEST_ALPN.to_vec()]) +1507 .insecure_skip_relay_cert_verify(true) +1508 .bind() +1509 .await?; +1510 // Wait for the endpoint to be reachable via relay +1511 ep.online().await; +1512 +1513 let server = tokio::spawn( +1514 async move { +1515 info!("accepting connection"); +1516 let incoming = ep.accept().await.anyerr()?; +1517 let conn = incoming.await.anyerr()?; +1518 let mut stream = conn.accept_uni().await.anyerr()?; +1519 let mut buf = [0u8; 5]; +1520 stream.read_exact(&mut buf).await.anyerr()?; +1521 info!("Accepted 1 stream, received {buf:?}. Closing now."); +1522 // close the connection +1523 conn.close(7u8.into(), b"bye"); +1524 +1525 let res = conn.accept_uni().await; +1526 assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed); +1527 +1528 let res = stream.read_to_end(10).await; +1529 assert_eq!( +1530 res.unwrap_err(), +1531 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( +1532 quinn::ConnectionError::LocallyClosed +1533 )) +1534 ); +1535 info!("server test completed"); +1536 Ok::<_, Error>(()) +1537 } +1538 .instrument(info_span!("test-server")), +1539 ); +1540 +1541 let client = tokio::spawn( +1542 async move { +1543 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +1544 .alpns(vec![TEST_ALPN.to_vec()]) +1545 .insecure_skip_relay_cert_verify(true) +1546 .bind() +1547 .await?; +1548 info!("client connecting"); +1549 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); +1550 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; +1551 let mut stream = conn.open_uni().await.anyerr()?; +1552 +1553 // First write is accepted by server. We need this bit of synchronisation +1554 // because if the server closes after simply accepting the connection we can +1555 // not be sure our .open_uni() call would succeed as it may already receive +1556 // the error. +1557 stream.write_all(b"hello").await.anyerr()?; +1558 +1559 info!("waiting for closed"); +1560 // Remote now closes the connection, we should see an error sometime soon. +1561 let err = conn.closed().await; +1562 let expected_err = +1563 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose { +1564 error_code: 7u8.into(), +1565 reason: b"bye".to_vec().into(), +1566 }); +1567 assert_eq!(err, expected_err); +1568 +1569 info!("opening new - expect it to fail"); +1570 let res = conn.open_uni().await; +1571 assert_eq!(res.unwrap_err(), expected_err); +1572 info!("client test completed"); +1573 Ok::<_, Error>(()) +1574 } +1575 .instrument(info_span!("test-client")), +1576 ); +1577 +1578 let (server, client) = tokio::time::timeout( +1579 Duration::from_secs(30), +1580 n0_future::future::zip(server, client), +1581 ) +1582 .await +1583 .anyerr()?; +1584 server.anyerr()??; +1585 client.anyerr()??; +1586 Ok(()) +1587 } +1588 +1589 #[tokio::test] +1590 #[traced_test] +1591 async fn endpoint_relay_connect_loop() -> Result { +1592 let test_start = Instant::now(); +1593 let n_clients = 5; +1594 let n_chunks_per_client = 2; +1595 let chunk_size = 10; +1596 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +1597 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); +1598 let server_secret_key = SecretKey::generate(&mut rng); +1599 let server_endpoint_id = server_secret_key.public(); +1600 +1601 // Make sure the server is bound before having clients connect to it: +1602 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1603 .insecure_skip_relay_cert_verify(true) +1604 .secret_key(server_secret_key) +1605 .alpns(vec![TEST_ALPN.to_vec()]) +1606 .bind() +1607 .await?; +1608 // Also make sure the server has a working relay connection +1609 ep.online().await; +1610 +1611 info!(time = ?test_start.elapsed(), "test setup done"); 1612 -1613 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); -1614 for i in 0..n_clients { -1615 let round_start = Instant::now(); -1616 info!("[server] round {i}"); -1617 let incoming = ep.accept().await.anyerr()?; -1618 let conn = incoming.await.anyerr()?; -1619 let endpoint_id = conn.remote_id(); -1620 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); -1621 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -1622 let mut buf = vec![0u8; chunk_size]; -1623 for _i in 0..n_chunks_per_client { -1624 recv.read_exact(&mut buf).await.anyerr()?; -1625 send.write_all(&buf).await.anyerr()?; -1626 } -1627 send.finish().anyerr()?; -1628 conn.closed().await; // we're the last to send data, so we wait for the other side to close -1629 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); -1630 info!("[server] round {i} done in {:?}", round_start.elapsed()); -1631 } -1632 Ok::<_, Error>(()) -1633 } -1634 .instrument(error_span!("server")), -1635 ); -1636 -1637 let start = Instant::now(); -1638 -1639 for i in 0..n_clients { -1640 let round_start = Instant::now(); -1641 info!("[client] round {i}"); -1642 let client_secret_key = SecretKey::generate(&mut rng); -1643 async { -1644 info!("client binding"); -1645 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1646 .alpns(vec![TEST_ALPN.to_vec()]) -1647 .insecure_skip_relay_cert_verify(true) -1648 .secret_key(client_secret_key) -1649 .bind() -1650 .await?; -1651 let eps = ep.bound_sockets(); -1652 -1653 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); -1654 let endpoint_addr = -1655 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); -1656 info!(to = ?endpoint_addr, "client connecting"); -1657 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; -1658 info!("client connected"); -1659 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -1660 -1661 for i in 0..n_chunks_per_client { -1662 let mut buf = vec![i; chunk_size]; -1663 send.write_all(&buf).await.anyerr()?; -1664 recv.read_exact(&mut buf).await.anyerr()?; -1665 assert_eq!(buf, vec![i; chunk_size]); -1666 } -1667 // we're the last to receive data, so we close -1668 conn.close(0u32.into(), b"bye!"); -1669 info!("client finished"); -1670 ep.close().await; -1671 info!("client closed"); -1672 Ok::<_, Error>(()) -1673 } -1674 .instrument(error_span!("client", %i)) -1675 .await?; -1676 info!("[client] round {i} done in {:?}", round_start.elapsed()); -1677 } -1678 -1679 server.await.anyerr()??; -1680 -1681 // We appear to have seen this being very slow at times. So ensure we fail if this -1682 // test is too slow. We're only making two connections transferring very little -1683 // data, this really shouldn't take long. -1684 if start.elapsed() > Duration::from_secs(15) { -1685 panic!("Test too slow, something went wrong"); -1686 } -1687 -1688 Ok(()) -1689 } -1690 -1691 #[tokio::test] -1692 #[traced_test] -1693 async fn endpoint_send_relay() -> Result { -1694 let (relay_map, _relay_url, _guard) = run_relay_server().await?; -1695 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1696 .insecure_skip_relay_cert_verify(true) -1697 .bind() -1698 .await?; -1699 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -1700 .insecure_skip_relay_cert_verify(true) -1701 .alpns(vec![TEST_ALPN.to_vec()]) +1613 // The server accepts the connections of the clients sequentially. +1614 let server = tokio::spawn( +1615 async move { +1616 let eps = ep.bound_sockets(); +1617 +1618 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); +1619 for i in 0..n_clients { +1620 let round_start = Instant::now(); +1621 info!("[server] round {i}"); +1622 let incoming = ep.accept().await.anyerr()?; +1623 let conn = incoming.await.anyerr()?; +1624 let endpoint_id = conn.remote_id(); +1625 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); +1626 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +1627 let mut buf = vec![0u8; chunk_size]; +1628 for _i in 0..n_chunks_per_client { +1629 recv.read_exact(&mut buf).await.anyerr()?; +1630 send.write_all(&buf).await.anyerr()?; +1631 } +1632 send.finish().anyerr()?; +1633 conn.closed().await; // we're the last to send data, so we wait for the other side to close +1634 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); +1635 info!("[server] round {i} done in {:?}", round_start.elapsed()); +1636 } +1637 Ok::<_, Error>(()) +1638 } +1639 .instrument(error_span!("server")), +1640 ); +1641 +1642 let start = Instant::now(); +1643 +1644 for i in 0..n_clients { +1645 let round_start = Instant::now(); +1646 info!("[client] round {i}"); +1647 let client_secret_key = SecretKey::generate(&mut rng); +1648 async { +1649 info!("client binding"); +1650 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1651 .alpns(vec![TEST_ALPN.to_vec()]) +1652 .insecure_skip_relay_cert_verify(true) +1653 .secret_key(client_secret_key) +1654 .bind() +1655 .await?; +1656 let eps = ep.bound_sockets(); +1657 +1658 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); +1659 let endpoint_addr = +1660 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); +1661 info!(to = ?endpoint_addr, "client connecting"); +1662 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; +1663 info!("client connected"); +1664 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +1665 +1666 for i in 0..n_chunks_per_client { +1667 let mut buf = vec![i; chunk_size]; +1668 send.write_all(&buf).await.anyerr()?; +1669 recv.read_exact(&mut buf).await.anyerr()?; +1670 assert_eq!(buf, vec![i; chunk_size]); +1671 } +1672 // we're the last to receive data, so we close +1673 conn.close(0u32.into(), b"bye!"); +1674 info!("client finished"); +1675 ep.close().await; +1676 info!("client closed"); +1677 Ok::<_, Error>(()) +1678 } +1679 .instrument(error_span!("client", %i)) +1680 .await?; +1681 info!("[client] round {i} done in {:?}", round_start.elapsed()); +1682 } +1683 +1684 server.await.anyerr()??; +1685 +1686 // We appear to have seen this being very slow at times. So ensure we fail if this +1687 // test is too slow. We're only making two connections transferring very little +1688 // data, this really shouldn't take long. +1689 if start.elapsed() > Duration::from_secs(15) { +1690 panic!("Test too slow, something went wrong"); +1691 } +1692 +1693 Ok(()) +1694 } +1695 +1696 #[tokio::test] +1697 #[traced_test] +1698 async fn endpoint_send_relay() -> Result { +1699 let (relay_map, _relay_url, _guard) = run_relay_server().await?; +1700 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1701 .insecure_skip_relay_cert_verify(true) 1702 .bind() 1703 .await?; -1704 -1705 let task = tokio::spawn({ -1706 let server = server.clone(); -1707 async move { -1708 let Some(conn) = server.accept().await else { -1709 n0_error::bail_any!("Expected an incoming connection"); -1710 }; -1711 let conn = conn.await.anyerr()?; -1712 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -1713 let data = recv.read_to_end(1000).await.anyerr()?; -1714 send.write_all(&data).await.anyerr()?; -1715 send.finish().anyerr()?; -1716 conn.closed().await; -1717 -1718 Ok::<_, Error>(()) -1719 } -1720 }); -1721 -1722 let addr = server.addr(); -1723 let conn = client.connect(addr, TEST_ALPN).await?; -1724 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -1725 send.write_all(b"Hello, world!").await.anyerr()?; -1726 send.finish().anyerr()?; -1727 let data = recv.read_to_end(1000).await.anyerr()?; -1728 conn.close(0u32.into(), b"bye!"); -1729 -1730 task.await.anyerr()??; -1731 -1732 client.close().await; -1733 server.close().await; +1704 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +1705 .insecure_skip_relay_cert_verify(true) +1706 .alpns(vec![TEST_ALPN.to_vec()]) +1707 .bind() +1708 .await?; +1709 +1710 let task = tokio::spawn({ +1711 let server = server.clone(); +1712 async move { +1713 let Some(conn) = server.accept().await else { +1714 n0_error::bail_any!("Expected an incoming connection"); +1715 }; +1716 let conn = conn.await.anyerr()?; +1717 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +1718 let data = recv.read_to_end(1000).await.anyerr()?; +1719 send.write_all(&data).await.anyerr()?; +1720 send.finish().anyerr()?; +1721 conn.closed().await; +1722 +1723 Ok::<_, Error>(()) +1724 } +1725 }); +1726 +1727 let addr = server.addr(); +1728 let conn = client.connect(addr, TEST_ALPN).await?; +1729 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +1730 send.write_all(b"Hello, world!").await.anyerr()?; +1731 send.finish().anyerr()?; +1732 let data = recv.read_to_end(1000).await.anyerr()?; +1733 conn.close(0u32.into(), b"bye!"); 1734 -1735 assert_eq!(&data, b"Hello, world!"); +1735 task.await.anyerr()??; 1736 -1737 Ok(()) -1738 } +1737 client.close().await; +1738 server.close().await; 1739 -1740 #[tokio::test] -1741 #[traced_test] -1742 async fn endpoint_two_direct_only() -> Result { -1743 // Connect two endpoints on the same network, without a relay server, without -1744 // discovery. -1745 let ep1 = { -1746 let span = info_span!("server"); -1747 let _guard = span.enter(); -1748 Endpoint::builder() -1749 .alpns(vec![TEST_ALPN.to_vec()]) -1750 .relay_mode(RelayMode::Disabled) -1751 .bind() -1752 .await? -1753 }; -1754 let ep2 = { -1755 let span = info_span!("client"); -1756 let _guard = span.enter(); -1757 Endpoint::builder() -1758 .alpns(vec![TEST_ALPN.to_vec()]) -1759 .relay_mode(RelayMode::Disabled) -1760 .bind() -1761 .await? -1762 }; -1763 let ep1_nodeaddr = ep1.addr(); -1764 -1765 #[instrument(name = "client", skip_all)] -1766 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<quinn::ConnectionError> { -1767 info!(me = %ep.id().fmt_short(), "client starting"); -1768 let conn = ep.connect(dst, TEST_ALPN).await?; -1769 let mut send = conn.open_uni().await.anyerr()?; -1770 send.write_all(b"hello").await.anyerr()?; -1771 send.finish().anyerr()?; -1772 Ok(conn.closed().await) -1773 } -1774 -1775 #[instrument(name = "server", skip_all)] -1776 async fn accept(ep: Endpoint, src: EndpointId) -> Result { -1777 info!(me = %ep.id().fmt_short(), "server starting"); -1778 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -1779 let node_id = conn.remote_id(); -1780 assert_eq!(node_id, src); -1781 let mut recv = conn.accept_uni().await.anyerr()?; -1782 let msg = recv.read_to_end(100).await.anyerr()?; -1783 assert_eq!(msg, b"hello"); -1784 // Dropping the connection closes it just fine. -1785 Ok(()) -1786 } -1787 -1788 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); -1789 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); -1790 -1791 ep1_accept.await.anyerr()??; -1792 let conn_closed = dbg!(ep2_connect.await.anyerr()??); -1793 assert!(matches!( -1794 conn_closed, -1795 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) -1796 )); -1797 -1798 Ok(()) -1799 } -1800 -1801 #[tokio::test] -1802 #[traced_test] -1803 async fn endpoint_two_relay_only_becomes_direct() -> Result { -1804 // Connect two endpoints on the same network, via a relay server, without -1805 // discovery. Wait until there is a direct connection. -1806 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -1807 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -1808 -1809 #[instrument(name = "client", skip_all)] -1810 async fn connect( -1811 relay_map: RelayMap, -1812 node_addr_rx: oneshot::Receiver<EndpointAddr>, -1813 ) -> Result<quinn::ConnectionError> { -1814 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1815 let secret = SecretKey::generate(&mut rng); -1816 let ep = Endpoint::builder() -1817 .secret_key(secret) -1818 .alpns(vec![TEST_ALPN.to_vec()]) -1819 .insecure_skip_relay_cert_verify(true) -1820 .relay_mode(RelayMode::Custom(relay_map)) -1821 .bind() -1822 .await?; -1823 info!(me = %ep.id().fmt_short(), "client starting"); -1824 let dst = node_addr_rx.await.anyerr()?; -1825 -1826 info!(me = %ep.id().fmt_short(), "client connecting"); -1827 let conn = ep.connect(dst, TEST_ALPN).await?; -1828 let mut send = conn.open_uni().await.anyerr()?; -1829 send.write_all(b"hello").await.anyerr()?; -1830 let mut paths = conn.paths().stream(); -1831 info!("Waiting for direct connection"); -1832 while let Some(infos) = paths.next().await { -1833 info!(?infos, "new PathInfos"); -1834 if infos.iter().any(|info| info.is_ip()) { -1835 break; -1836 } -1837 } -1838 info!("Have direct connection"); -1839 send.write_all(b"close please").await.anyerr()?; -1840 send.finish().anyerr()?; -1841 Ok(conn.closed().await) -1842 } -1843 -1844 #[instrument(name = "server", skip_all)] -1845 async fn accept( -1846 relay_map: RelayMap, -1847 node_addr_tx: oneshot::Sender<EndpointAddr>, -1848 ) -> Result { -1849 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -1850 let secret = SecretKey::generate(&mut rng); -1851 let ep = Endpoint::builder() -1852 .secret_key(secret) -1853 .alpns(vec![TEST_ALPN.to_vec()]) -1854 .insecure_skip_relay_cert_verify(true) -1855 .relay_mode(RelayMode::Custom(relay_map)) -1856 .bind() -1857 .await?; -1858 ep.online().await; -1859 let mut node_addr = ep.addr(); -1860 node_addr.addrs.retain(|addr| addr.is_relay()); -1861 node_addr_tx.send(node_addr).unwrap(); -1862 -1863 info!(me = %ep.id().fmt_short(), "server starting"); -1864 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -1865 // let node_id = conn.remote_node_id()?; -1866 // assert_eq!(node_id, src); -1867 let mut recv = conn.accept_uni().await.anyerr()?; -1868 let mut msg = [0u8; 5]; -1869 recv.read_exact(&mut msg).await.anyerr()?; -1870 assert_eq!(&msg, b"hello"); -1871 info!("received hello"); -1872 let msg = recv.read_to_end(100).await.anyerr()?; -1873 assert_eq!(msg, b"close please"); -1874 info!("received 'close please'"); -1875 // Dropping the connection closes it just fine. -1876 Ok(()) -1877 } -1878 -1879 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -1880 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -1881 -1882 server_task.await.anyerr()??; -1883 let conn_closed = dbg!(client_task.await.anyerr()??); -1884 assert!(matches!( -1885 conn_closed, -1886 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) -1887 )); -1888 -1889 Ok(()) -1890 } -1891 -1892 #[tokio::test] -1893 #[traced_test] -1894 async fn endpoint_two_relay_only_no_ip() -> Result { -1895 // Connect two endpoints on the same network, via a relay server, without -1896 // discovery. -1897 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -1898 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -1899 -1900 #[instrument(name = "client", skip_all)] -1901 async fn connect( -1902 relay_map: RelayMap, -1903 node_addr_rx: oneshot::Receiver<EndpointAddr>, -1904 ) -> Result<quinn::ConnectionError> { -1905 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1906 let secret = SecretKey::generate(&mut rng); -1907 let ep = Endpoint::builder() -1908 .secret_key(secret) -1909 .alpns(vec![TEST_ALPN.to_vec()]) -1910 .insecure_skip_relay_cert_verify(true) -1911 .relay_mode(RelayMode::Custom(relay_map)) -1912 .disable_ip() // disable direct -1913 .bind() -1914 .await?; -1915 info!(me = %ep.id().fmt_short(), "client starting"); -1916 let dst = node_addr_rx.await.anyerr()?; -1917 -1918 info!(me = %ep.id().fmt_short(), "client connecting"); -1919 let conn = ep.connect(dst, TEST_ALPN).await?; -1920 let mut send = conn.open_uni().await.anyerr()?; -1921 send.write_all(b"hello").await.anyerr()?; -1922 let mut paths = conn.paths().stream(); -1923 info!("Waiting for connection"); -1924 'outer: while let Some(infos) = paths.next().await { -1925 info!(?infos, "new PathInfos"); -1926 for info in infos { -1927 if info.is_ip() { -1928 panic!("should not happen: {:?}", info); -1929 } -1930 if info.is_relay() { -1931 break 'outer; -1932 } -1933 } -1934 } -1935 info!("Have relay connection"); -1936 send.write_all(b"close please").await.anyerr()?; -1937 send.finish().anyerr()?; -1938 Ok(conn.closed().await) -1939 } -1940 -1941 #[instrument(name = "server", skip_all)] -1942 async fn accept( -1943 relay_map: RelayMap, -1944 node_addr_tx: oneshot::Sender<EndpointAddr>, -1945 ) -> Result { -1946 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -1947 let secret = SecretKey::generate(&mut rng); -1948 let ep = Endpoint::builder() -1949 .secret_key(secret) -1950 .alpns(vec![TEST_ALPN.to_vec()]) -1951 .insecure_skip_relay_cert_verify(true) -1952 .relay_mode(RelayMode::Custom(relay_map)) -1953 .disable_ip() -1954 .bind() -1955 .await?; -1956 ep.online().await; -1957 let node_addr = ep.addr(); -1958 node_addr_tx.send(node_addr).unwrap(); -1959 -1960 info!(me = %ep.id().fmt_short(), "server starting"); -1961 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -1962 // let node_id = conn.remote_node_id()?; -1963 // assert_eq!(node_id, src); -1964 let mut recv = conn.accept_uni().await.anyerr()?; -1965 let mut msg = [0u8; 5]; -1966 recv.read_exact(&mut msg).await.anyerr()?; -1967 assert_eq!(&msg, b"hello"); -1968 info!("received hello"); -1969 let msg = recv.read_to_end(100).await.anyerr()?; -1970 assert_eq!(msg, b"close please"); -1971 info!("received 'close please'"); -1972 // Dropping the connection closes it just fine. -1973 Ok(()) -1974 } -1975 -1976 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -1977 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -1978 -1979 server_task.await.anyerr()??; -1980 let conn_closed = dbg!(client_task.await.anyerr()??); -1981 assert!(matches!( -1982 conn_closed, -1983 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) -1984 )); -1985 -1986 Ok(()) -1987 } -1988 -1989 #[tokio::test] -1990 #[traced_test] -1991 async fn endpoint_two_direct_add_relay() -> Result { -1992 // Connect two endpoints on the same network, without relay server and without -1993 // discovery. Add a relay connection later. -1994 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -1995 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -1996 -1997 #[instrument(name = "client", skip_all)] -1998 async fn connect( -1999 relay_map: RelayMap, -2000 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2001 ) -> Result<()> { -2002 let secret = SecretKey::from([0u8; 32]); -2003 let ep = Endpoint::builder() -2004 .secret_key(secret) -2005 .alpns(vec![TEST_ALPN.to_vec()]) -2006 .insecure_skip_relay_cert_verify(true) -2007 .relay_mode(RelayMode::Custom(relay_map)) -2008 .bind() -2009 .await?; -2010 info!(me = %ep.id().fmt_short(), "client starting"); -2011 let dst = node_addr_rx.await.anyerr()?; -2012 -2013 info!(me = %ep.id().fmt_short(), "client connecting"); -2014 let conn = ep.connect(dst, TEST_ALPN).await?; -2015 -2016 // We should be connected via IP, because it is faster than the relay server. -2017 // TODO: Maybe not panic if this is not true? -2018 let path_info = conn.paths().get(); -2019 assert_eq!(path_info.len(), 1); -2020 assert!(path_info.iter().next().unwrap().is_ip()); -2021 -2022 let mut paths = conn.paths().stream(); -2023 time::timeout(Duration::from_secs(5), async move { -2024 while let Some(infos) = paths.next().await { -2025 info!(?infos, "new PathInfos"); -2026 if infos.iter().any(|info| info.is_relay()) { -2027 break; -2028 } -2029 } -2030 }) -2031 .await -2032 .anyerr()?; -2033 -2034 // wait for the server to signal it has the relay connection -2035 let mut stream = conn.accept_uni().await.anyerr()?; -2036 stream.read_to_end(100).await.anyerr()?; -2037 -2038 info!("client closing"); -2039 conn.close(0u8.into(), b""); -2040 ep.close().await; -2041 Ok(()) -2042 } -2043 -2044 #[instrument(name = "server", skip_all)] -2045 async fn accept( -2046 relay_map: RelayMap, -2047 node_addr_tx: oneshot::Sender<EndpointAddr>, -2048 ) -> Result<quinn::ConnectionError> { -2049 let secret = SecretKey::from([1u8; 32]); -2050 let ep = Endpoint::builder() -2051 .secret_key(secret) -2052 .alpns(vec![TEST_ALPN.to_vec()]) -2053 .insecure_skip_relay_cert_verify(true) -2054 .relay_mode(RelayMode::Custom(relay_map)) -2055 .bind() -2056 .await?; -2057 ep.online().await; -2058 let node_addr = ep.addr(); -2059 node_addr_tx.send(node_addr).unwrap(); -2060 -2061 info!(me = %ep.id().fmt_short(), "server starting"); -2062 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2063 -2064 // Wait for a relay connection to be added. Client does all the asserting here, -2065 // we just want to wait so we get to see all the mechanics of the connection -2066 // being added on this side too. -2067 let mut paths = conn.paths().stream(); -2068 time::timeout(Duration::from_secs(5), async move { -2069 while let Some(infos) = paths.next().await { -2070 info!(?infos, "new PathInfos"); -2071 if infos.iter().any(|path| path.is_relay()) { -2072 break; -2073 } -2074 } -2075 }) -2076 .await -2077 .anyerr()?; -2078 -2079 let mut stream = conn.open_uni().await.anyerr()?; -2080 stream.write_all(b"have relay").await.anyerr()?; -2081 -2082 Ok(conn.closed().await) -2083 } -2084 -2085 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -2086 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -2087 -2088 client_task.await.anyerr()??; -2089 let conn_closed = dbg!(server_task.await.anyerr()??); -2090 assert!(matches!( -2091 conn_closed, -2092 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) -2093 )); -2094 -2095 Ok(()) -2096 } -2097 -2098 #[tokio::test] -2099 #[traced_test] -2100 async fn endpoint_relay_map_change() -> Result { -2101 let (relay_map, relay_url, _guard1) = run_relay_server().await?; -2102 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -2103 .insecure_skip_relay_cert_verify(true) -2104 .bind() -2105 .await?; -2106 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -2107 .insecure_skip_relay_cert_verify(true) -2108 .alpns(vec![TEST_ALPN.to_vec()]) +1740 assert_eq!(&data, b"Hello, world!"); +1741 +1742 Ok(()) +1743 } +1744 +1745 #[tokio::test] +1746 #[traced_test] +1747 async fn endpoint_two_direct_only() -> Result { +1748 // Connect two endpoints on the same network, without a relay server, without +1749 // discovery. +1750 let ep1 = { +1751 let span = info_span!("server"); +1752 let _guard = span.enter(); +1753 Endpoint::builder() +1754 .alpns(vec![TEST_ALPN.to_vec()]) +1755 .relay_mode(RelayMode::Disabled) +1756 .bind() +1757 .await? +1758 }; +1759 let ep2 = { +1760 let span = info_span!("client"); +1761 let _guard = span.enter(); +1762 Endpoint::builder() +1763 .alpns(vec![TEST_ALPN.to_vec()]) +1764 .relay_mode(RelayMode::Disabled) +1765 .bind() +1766 .await? +1767 }; +1768 let ep1_nodeaddr = ep1.addr(); +1769 +1770 #[instrument(name = "client", skip_all)] +1771 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<quinn::ConnectionError> { +1772 info!(me = %ep.id().fmt_short(), "client starting"); +1773 let conn = ep.connect(dst, TEST_ALPN).await?; +1774 let mut send = conn.open_uni().await.anyerr()?; +1775 send.write_all(b"hello").await.anyerr()?; +1776 send.finish().anyerr()?; +1777 Ok(conn.closed().await) +1778 } +1779 +1780 #[instrument(name = "server", skip_all)] +1781 async fn accept(ep: Endpoint, src: EndpointId) -> Result { +1782 info!(me = %ep.id().fmt_short(), "server starting"); +1783 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +1784 let node_id = conn.remote_id(); +1785 assert_eq!(node_id, src); +1786 let mut recv = conn.accept_uni().await.anyerr()?; +1787 let msg = recv.read_to_end(100).await.anyerr()?; +1788 assert_eq!(msg, b"hello"); +1789 // Dropping the connection closes it just fine. +1790 Ok(()) +1791 } +1792 +1793 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); +1794 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); +1795 +1796 ep1_accept.await.anyerr()??; +1797 let conn_closed = dbg!(ep2_connect.await.anyerr()??); +1798 assert!(matches!( +1799 conn_closed, +1800 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) +1801 )); +1802 +1803 Ok(()) +1804 } +1805 +1806 #[tokio::test] +1807 #[traced_test] +1808 async fn endpoint_two_relay_only_becomes_direct() -> Result { +1809 // Connect two endpoints on the same network, via a relay server, without +1810 // discovery. Wait until there is a direct connection. +1811 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +1812 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +1813 +1814 #[instrument(name = "client", skip_all)] +1815 async fn connect( +1816 relay_map: RelayMap, +1817 node_addr_rx: oneshot::Receiver<EndpointAddr>, +1818 ) -> Result<quinn::ConnectionError> { +1819 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1820 let secret = SecretKey::generate(&mut rng); +1821 let ep = Endpoint::builder() +1822 .secret_key(secret) +1823 .alpns(vec![TEST_ALPN.to_vec()]) +1824 .insecure_skip_relay_cert_verify(true) +1825 .relay_mode(RelayMode::Custom(relay_map)) +1826 .bind() +1827 .await?; +1828 info!(me = %ep.id().fmt_short(), "client starting"); +1829 let dst = node_addr_rx.await.anyerr()?; +1830 +1831 info!(me = %ep.id().fmt_short(), "client connecting"); +1832 let conn = ep.connect(dst, TEST_ALPN).await?; +1833 let mut send = conn.open_uni().await.anyerr()?; +1834 send.write_all(b"hello").await.anyerr()?; +1835 let mut paths = conn.paths().stream(); +1836 info!("Waiting for direct connection"); +1837 while let Some(infos) = paths.next().await { +1838 info!(?infos, "new PathInfos"); +1839 if infos.iter().any(|info| info.is_ip()) { +1840 break; +1841 } +1842 } +1843 info!("Have direct connection"); +1844 send.write_all(b"close please").await.anyerr()?; +1845 send.finish().anyerr()?; +1846 Ok(conn.closed().await) +1847 } +1848 +1849 #[instrument(name = "server", skip_all)] +1850 async fn accept( +1851 relay_map: RelayMap, +1852 node_addr_tx: oneshot::Sender<EndpointAddr>, +1853 ) -> Result { +1854 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +1855 let secret = SecretKey::generate(&mut rng); +1856 let ep = Endpoint::builder() +1857 .secret_key(secret) +1858 .alpns(vec![TEST_ALPN.to_vec()]) +1859 .insecure_skip_relay_cert_verify(true) +1860 .relay_mode(RelayMode::Custom(relay_map)) +1861 .bind() +1862 .await?; +1863 ep.online().await; +1864 let mut node_addr = ep.addr(); +1865 node_addr.addrs.retain(|addr| addr.is_relay()); +1866 node_addr_tx.send(node_addr).unwrap(); +1867 +1868 info!(me = %ep.id().fmt_short(), "server starting"); +1869 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +1870 // let node_id = conn.remote_node_id()?; +1871 // assert_eq!(node_id, src); +1872 let mut recv = conn.accept_uni().await.anyerr()?; +1873 let mut msg = [0u8; 5]; +1874 recv.read_exact(&mut msg).await.anyerr()?; +1875 assert_eq!(&msg, b"hello"); +1876 info!("received hello"); +1877 let msg = recv.read_to_end(100).await.anyerr()?; +1878 assert_eq!(msg, b"close please"); +1879 info!("received 'close please'"); +1880 // Dropping the connection closes it just fine. +1881 Ok(()) +1882 } +1883 +1884 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +1885 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +1886 +1887 server_task.await.anyerr()??; +1888 let conn_closed = dbg!(client_task.await.anyerr()??); +1889 assert!(matches!( +1890 conn_closed, +1891 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) +1892 )); +1893 +1894 Ok(()) +1895 } +1896 +1897 #[tokio::test] +1898 #[traced_test] +1899 async fn endpoint_two_relay_only_no_ip() -> Result { +1900 // Connect two endpoints on the same network, via a relay server, without +1901 // discovery. +1902 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +1903 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +1904 +1905 #[instrument(name = "client", skip_all)] +1906 async fn connect( +1907 relay_map: RelayMap, +1908 node_addr_rx: oneshot::Receiver<EndpointAddr>, +1909 ) -> Result<quinn::ConnectionError> { +1910 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1911 let secret = SecretKey::generate(&mut rng); +1912 let ep = Endpoint::builder() +1913 .secret_key(secret) +1914 .alpns(vec![TEST_ALPN.to_vec()]) +1915 .insecure_skip_relay_cert_verify(true) +1916 .relay_mode(RelayMode::Custom(relay_map)) +1917 .disable_ip() // disable direct +1918 .bind() +1919 .await?; +1920 info!(me = %ep.id().fmt_short(), "client starting"); +1921 let dst = node_addr_rx.await.anyerr()?; +1922 +1923 info!(me = %ep.id().fmt_short(), "client connecting"); +1924 let conn = ep.connect(dst, TEST_ALPN).await?; +1925 let mut send = conn.open_uni().await.anyerr()?; +1926 send.write_all(b"hello").await.anyerr()?; +1927 let mut paths = conn.paths().stream(); +1928 info!("Waiting for connection"); +1929 'outer: while let Some(infos) = paths.next().await { +1930 info!(?infos, "new PathInfos"); +1931 for info in infos { +1932 if info.is_ip() { +1933 panic!("should not happen: {:?}", info); +1934 } +1935 if info.is_relay() { +1936 break 'outer; +1937 } +1938 } +1939 } +1940 info!("Have relay connection"); +1941 send.write_all(b"close please").await.anyerr()?; +1942 send.finish().anyerr()?; +1943 Ok(conn.closed().await) +1944 } +1945 +1946 #[instrument(name = "server", skip_all)] +1947 async fn accept( +1948 relay_map: RelayMap, +1949 node_addr_tx: oneshot::Sender<EndpointAddr>, +1950 ) -> Result { +1951 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +1952 let secret = SecretKey::generate(&mut rng); +1953 let ep = Endpoint::builder() +1954 .secret_key(secret) +1955 .alpns(vec![TEST_ALPN.to_vec()]) +1956 .insecure_skip_relay_cert_verify(true) +1957 .relay_mode(RelayMode::Custom(relay_map)) +1958 .disable_ip() +1959 .bind() +1960 .await?; +1961 ep.online().await; +1962 let node_addr = ep.addr(); +1963 node_addr_tx.send(node_addr).unwrap(); +1964 +1965 info!(me = %ep.id().fmt_short(), "server starting"); +1966 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +1967 // let node_id = conn.remote_node_id()?; +1968 // assert_eq!(node_id, src); +1969 let mut recv = conn.accept_uni().await.anyerr()?; +1970 let mut msg = [0u8; 5]; +1971 recv.read_exact(&mut msg).await.anyerr()?; +1972 assert_eq!(&msg, b"hello"); +1973 info!("received hello"); +1974 let msg = recv.read_to_end(100).await.anyerr()?; +1975 assert_eq!(msg, b"close please"); +1976 info!("received 'close please'"); +1977 // Dropping the connection closes it just fine. +1978 Ok(()) +1979 } +1980 +1981 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +1982 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +1983 +1984 server_task.await.anyerr()??; +1985 let conn_closed = dbg!(client_task.await.anyerr()??); +1986 assert!(matches!( +1987 conn_closed, +1988 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) +1989 )); +1990 +1991 Ok(()) +1992 } +1993 +1994 #[tokio::test] +1995 #[traced_test] +1996 async fn endpoint_two_direct_add_relay() -> Result { +1997 // Connect two endpoints on the same network, without relay server and without +1998 // discovery. Add a relay connection later. +1999 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2000 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2001 +2002 #[instrument(name = "client", skip_all)] +2003 async fn connect( +2004 relay_map: RelayMap, +2005 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2006 ) -> Result<()> { +2007 let secret = SecretKey::from([0u8; 32]); +2008 let ep = Endpoint::builder() +2009 .secret_key(secret) +2010 .alpns(vec![TEST_ALPN.to_vec()]) +2011 .insecure_skip_relay_cert_verify(true) +2012 .relay_mode(RelayMode::Custom(relay_map)) +2013 .bind() +2014 .await?; +2015 info!(me = %ep.id().fmt_short(), "client starting"); +2016 let dst = node_addr_rx.await.anyerr()?; +2017 +2018 info!(me = %ep.id().fmt_short(), "client connecting"); +2019 let conn = ep.connect(dst, TEST_ALPN).await?; +2020 +2021 // We should be connected via IP, because it is faster than the relay server. +2022 // TODO: Maybe not panic if this is not true? +2023 let path_info = conn.paths().get(); +2024 assert_eq!(path_info.len(), 1); +2025 assert!(path_info.iter().next().unwrap().is_ip()); +2026 +2027 let mut paths = conn.paths().stream(); +2028 time::timeout(Duration::from_secs(5), async move { +2029 while let Some(infos) = paths.next().await { +2030 info!(?infos, "new PathInfos"); +2031 if infos.iter().any(|info| info.is_relay()) { +2032 break; +2033 } +2034 } +2035 }) +2036 .await +2037 .anyerr()?; +2038 +2039 // wait for the server to signal it has the relay connection +2040 let mut stream = conn.accept_uni().await.anyerr()?; +2041 stream.read_to_end(100).await.anyerr()?; +2042 +2043 info!("client closing"); +2044 conn.close(0u8.into(), b""); +2045 ep.close().await; +2046 Ok(()) +2047 } +2048 +2049 #[instrument(name = "server", skip_all)] +2050 async fn accept( +2051 relay_map: RelayMap, +2052 node_addr_tx: oneshot::Sender<EndpointAddr>, +2053 ) -> Result<quinn::ConnectionError> { +2054 let secret = SecretKey::from([1u8; 32]); +2055 let ep = Endpoint::builder() +2056 .secret_key(secret) +2057 .alpns(vec![TEST_ALPN.to_vec()]) +2058 .insecure_skip_relay_cert_verify(true) +2059 .relay_mode(RelayMode::Custom(relay_map)) +2060 .bind() +2061 .await?; +2062 ep.online().await; +2063 let node_addr = ep.addr(); +2064 node_addr_tx.send(node_addr).unwrap(); +2065 +2066 info!(me = %ep.id().fmt_short(), "server starting"); +2067 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2068 +2069 // Wait for a relay connection to be added. Client does all the asserting here, +2070 // we just want to wait so we get to see all the mechanics of the connection +2071 // being added on this side too. +2072 let mut paths = conn.paths().stream(); +2073 time::timeout(Duration::from_secs(5), async move { +2074 while let Some(infos) = paths.next().await { +2075 info!(?infos, "new PathInfos"); +2076 if infos.iter().any(|path| path.is_relay()) { +2077 break; +2078 } +2079 } +2080 }) +2081 .await +2082 .anyerr()?; +2083 +2084 let mut stream = conn.open_uni().await.anyerr()?; +2085 stream.write_all(b"have relay").await.anyerr()?; +2086 +2087 Ok(conn.closed().await) +2088 } +2089 +2090 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2091 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2092 +2093 client_task.await.anyerr()??; +2094 let conn_closed = dbg!(server_task.await.anyerr()??); +2095 assert!(matches!( +2096 conn_closed, +2097 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. }) +2098 )); +2099 +2100 Ok(()) +2101 } +2102 +2103 #[tokio::test] +2104 #[traced_test] +2105 async fn endpoint_relay_map_change() -> Result { +2106 let (relay_map, relay_url, _guard1) = run_relay_server().await?; +2107 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +2108 .insecure_skip_relay_cert_verify(true) 2109 .bind() 2110 .await?; -2111 -2112 let task = tokio::spawn({ -2113 let server = server.clone(); -2114 async move { -2115 for i in 0..2 { -2116 println!("accept: round {i}"); -2117 let Some(conn) = server.accept().await else { -2118 n0_error::bail_any!("Expected an incoming connection"); -2119 }; -2120 let conn = conn.await.anyerr()?; -2121 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2122 let data = recv.read_to_end(1000).await.anyerr()?; -2123 send.write_all(&data).await.anyerr()?; -2124 send.finish().anyerr()?; -2125 conn.closed().await; -2126 } -2127 Ok::<_, Error>(()) -2128 } -2129 }); -2130 -2131 server.online().await; -2132 -2133 let mut addr = server.addr(); -2134 println!("round1: {:?}", addr); +2111 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +2112 .insecure_skip_relay_cert_verify(true) +2113 .alpns(vec![TEST_ALPN.to_vec()]) +2114 .bind() +2115 .await?; +2116 +2117 let task = tokio::spawn({ +2118 let server = server.clone(); +2119 async move { +2120 for i in 0..2 { +2121 println!("accept: round {i}"); +2122 let Some(conn) = server.accept().await else { +2123 n0_error::bail_any!("Expected an incoming connection"); +2124 }; +2125 let conn = conn.await.anyerr()?; +2126 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2127 let data = recv.read_to_end(1000).await.anyerr()?; +2128 send.write_all(&data).await.anyerr()?; +2129 send.finish().anyerr()?; +2130 conn.closed().await; +2131 } +2132 Ok::<_, Error>(()) +2133 } +2134 }); 2135 -2136 // remove direct addrs to force relay usage -2137 addr.addrs -2138 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2139 -2140 let conn = client.connect(addr, TEST_ALPN).await?; -2141 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2142 send.write_all(b"Hello, world!").await.anyerr()?; -2143 send.finish().anyerr()?; -2144 let data = recv.read_to_end(1000).await.anyerr()?; -2145 conn.close(0u32.into(), b"bye!"); -2146 -2147 assert_eq!(&data, b"Hello, world!"); -2148 -2149 // setup a second relay server -2150 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; -2151 let new_endpoint = new_relay_map -2152 .get(&new_relay_url) -2153 .expect("missing endpoint") -2154 .clone(); -2155 dbg!(&new_relay_map); -2156 -2157 let addr_watcher = server.watch_addr(); -2158 -2159 // add new new relay -2160 assert!( -2161 server -2162 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) -2163 .await -2164 .is_none() -2165 ); -2166 // remove the old relay -2167 assert!(server.remove_relay(&relay_url).await.is_some()); -2168 -2169 println!("------- changed ----- "); -2170 -2171 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { -2172 let mut stream = addr_watcher.stream(); -2173 while let Some(addr) = stream.next().await { -2174 if addr.relay_urls().next() != Some(&relay_url) { -2175 return addr; -2176 } -2177 } -2178 panic!("failed to change relay"); -2179 }) -2180 .await -2181 .anyerr()?; -2182 -2183 println!("round2: {:?}", addr); -2184 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); -2185 -2186 // remove direct addrs to force relay usage -2187 addr.addrs -2188 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2189 -2190 let conn = client.connect(addr, TEST_ALPN).await?; -2191 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2192 send.write_all(b"Hello, world!").await.anyerr()?; -2193 send.finish().anyerr()?; -2194 let data = recv.read_to_end(1000).await.anyerr()?; -2195 conn.close(0u32.into(), b"bye!"); -2196 -2197 task.await.anyerr()??; -2198 -2199 client.close().await; -2200 server.close().await; +2136 server.online().await; +2137 +2138 let mut addr = server.addr(); +2139 println!("round1: {:?}", addr); +2140 +2141 // remove direct addrs to force relay usage +2142 addr.addrs +2143 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2144 +2145 let conn = client.connect(addr, TEST_ALPN).await?; +2146 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2147 send.write_all(b"Hello, world!").await.anyerr()?; +2148 send.finish().anyerr()?; +2149 let data = recv.read_to_end(1000).await.anyerr()?; +2150 conn.close(0u32.into(), b"bye!"); +2151 +2152 assert_eq!(&data, b"Hello, world!"); +2153 +2154 // setup a second relay server +2155 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; +2156 let new_endpoint = new_relay_map +2157 .get(&new_relay_url) +2158 .expect("missing endpoint") +2159 .clone(); +2160 dbg!(&new_relay_map); +2161 +2162 let addr_watcher = server.watch_addr(); +2163 +2164 // add new new relay +2165 assert!( +2166 server +2167 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) +2168 .await +2169 .is_none() +2170 ); +2171 // remove the old relay +2172 assert!(server.remove_relay(&relay_url).await.is_some()); +2173 +2174 println!("------- changed ----- "); +2175 +2176 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { +2177 let mut stream = addr_watcher.stream(); +2178 while let Some(addr) = stream.next().await { +2179 if addr.relay_urls().next() != Some(&relay_url) { +2180 return addr; +2181 } +2182 } +2183 panic!("failed to change relay"); +2184 }) +2185 .await +2186 .anyerr()?; +2187 +2188 println!("round2: {:?}", addr); +2189 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); +2190 +2191 // remove direct addrs to force relay usage +2192 addr.addrs +2193 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2194 +2195 let conn = client.connect(addr, TEST_ALPN).await?; +2196 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2197 send.write_all(b"Hello, world!").await.anyerr()?; +2198 send.finish().anyerr()?; +2199 let data = recv.read_to_end(1000).await.anyerr()?; +2200 conn.close(0u32.into(), b"bye!"); 2201 -2202 assert_eq!(&data, b"Hello, world!"); +2202 task.await.anyerr()??; 2203 -2204 Ok(()) -2205 } +2204 client.close().await; +2205 server.close().await; 2206 -2207 #[tokio::test] -2208 #[traced_test] -2209 async fn endpoint_bidi_send_recv() -> Result { -2210 let disco = StaticProvider::new(); -2211 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) -2212 .discovery(disco.clone()) -2213 .alpns(vec![TEST_ALPN.to_vec()]) -2214 .bind() -2215 .await?; -2216 -2217 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) -2218 .discovery(disco.clone()) -2219 .alpns(vec![TEST_ALPN.to_vec()]) -2220 .bind() -2221 .await?; -2222 -2223 disco.add_endpoint_info(ep1.addr()); -2224 disco.add_endpoint_info(ep2.addr()); -2225 -2226 let ep1_endpointid = ep1.id(); -2227 let ep2_endpointid = ep2.id(); -2228 eprintln!("endpoint id 1 {ep1_endpointid}"); -2229 eprintln!("endpoint id 2 {ep2_endpointid}"); +2207 assert_eq!(&data, b"Hello, world!"); +2208 +2209 Ok(()) +2210 } +2211 +2212 #[tokio::test] +2213 #[traced_test] +2214 async fn endpoint_bidi_send_recv() -> Result { +2215 let disco = StaticProvider::new(); +2216 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) +2217 .discovery(disco.clone()) +2218 .alpns(vec![TEST_ALPN.to_vec()]) +2219 .bind() +2220 .await?; +2221 +2222 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) +2223 .discovery(disco.clone()) +2224 .alpns(vec![TEST_ALPN.to_vec()]) +2225 .bind() +2226 .await?; +2227 +2228 disco.add_endpoint_info(ep1.addr()); +2229 disco.add_endpoint_info(ep2.addr()); 2230 -2231 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { -2232 let conn = ep.connect(dst, TEST_ALPN).await?; -2233 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2234 info!("sending hello"); -2235 send.write_all(b"hello").await.anyerr()?; -2236 send.finish().anyerr()?; -2237 info!("receiving world"); -2238 let m = recv.read_to_end(100).await.anyerr()?; -2239 assert_eq!(m, b"world"); -2240 conn.close(1u8.into(), b"done"); -2241 Ok(()) -2242 } -2243 -2244 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { -2245 let incoming = ep.accept().await.anyerr()?; -2246 let mut iconn = incoming.accept().anyerr()?; -2247 let alpn = iconn.alpn().await?; -2248 let conn = iconn.await.anyerr()?; -2249 let endpoint_id = conn.remote_id(); -2250 assert_eq!(endpoint_id, src); -2251 assert_eq!(alpn, TEST_ALPN); -2252 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2253 info!("receiving hello"); -2254 let m = recv.read_to_end(100).await.anyerr()?; -2255 assert_eq!(m, b"hello"); -2256 info!("sending hello"); -2257 send.write_all(b"world").await.anyerr()?; -2258 send.finish().anyerr()?; -2259 match conn.closed().await { -2260 ConnectionError::ApplicationClosed(closed) => { -2261 assert_eq!(closed.error_code, 1u8.into()); -2262 Ok(()) -2263 } -2264 _ => panic!("wrong close error"), -2265 } -2266 } -2267 -2268 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( -2269 info_span!( -2270 "p1_accept", -2271 ep1 = %ep1.id().fmt_short(), -2272 dst = %ep2_endpointid.fmt_short(), -2273 ), -2274 )); -2275 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( -2276 info_span!( -2277 "p2_accept", -2278 ep2 = %ep2.id().fmt_short(), -2279 dst = %ep1_endpointid.fmt_short(), -2280 ), -2281 )); -2282 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( -2283 info_span!( -2284 "p1_connect", -2285 ep1 = %ep1.id().fmt_short(), -2286 dst = %ep2_endpointid.fmt_short(), -2287 ), -2288 )); -2289 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( -2290 info_span!( -2291 "p2_connect", -2292 ep2 = %ep2.id().fmt_short(), -2293 dst = %ep1_endpointid.fmt_short(), -2294 ), -2295 )); -2296 -2297 p1_accept.await.anyerr()??; -2298 p2_accept.await.anyerr()??; -2299 p1_connect.await.anyerr()??; -2300 p2_connect.await.anyerr()??; +2231 let ep1_endpointid = ep1.id(); +2232 let ep2_endpointid = ep2.id(); +2233 eprintln!("endpoint id 1 {ep1_endpointid}"); +2234 eprintln!("endpoint id 2 {ep2_endpointid}"); +2235 +2236 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { +2237 let conn = ep.connect(dst, TEST_ALPN).await?; +2238 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2239 info!("sending hello"); +2240 send.write_all(b"hello").await.anyerr()?; +2241 send.finish().anyerr()?; +2242 info!("receiving world"); +2243 let m = recv.read_to_end(100).await.anyerr()?; +2244 assert_eq!(m, b"world"); +2245 conn.close(1u8.into(), b"done"); +2246 Ok(()) +2247 } +2248 +2249 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { +2250 let incoming = ep.accept().await.anyerr()?; +2251 let mut iconn = incoming.accept().anyerr()?; +2252 let alpn = iconn.alpn().await?; +2253 let conn = iconn.await.anyerr()?; +2254 let endpoint_id = conn.remote_id(); +2255 assert_eq!(endpoint_id, src); +2256 assert_eq!(alpn, TEST_ALPN); +2257 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2258 info!("receiving hello"); +2259 let m = recv.read_to_end(100).await.anyerr()?; +2260 assert_eq!(m, b"hello"); +2261 info!("sending hello"); +2262 send.write_all(b"world").await.anyerr()?; +2263 send.finish().anyerr()?; +2264 match conn.closed().await { +2265 ConnectionError::ApplicationClosed(closed) => { +2266 assert_eq!(closed.error_code, 1u8.into()); +2267 Ok(()) +2268 } +2269 _ => panic!("wrong close error"), +2270 } +2271 } +2272 +2273 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( +2274 info_span!( +2275 "p1_accept", +2276 ep1 = %ep1.id().fmt_short(), +2277 dst = %ep2_endpointid.fmt_short(), +2278 ), +2279 )); +2280 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( +2281 info_span!( +2282 "p2_accept", +2283 ep2 = %ep2.id().fmt_short(), +2284 dst = %ep1_endpointid.fmt_short(), +2285 ), +2286 )); +2287 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( +2288 info_span!( +2289 "p1_connect", +2290 ep1 = %ep1.id().fmt_short(), +2291 dst = %ep2_endpointid.fmt_short(), +2292 ), +2293 )); +2294 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( +2295 info_span!( +2296 "p2_connect", +2297 ep2 = %ep2.id().fmt_short(), +2298 dst = %ep1_endpointid.fmt_short(), +2299 ), +2300 )); 2301 -2302 Ok(()) -2303 } -2304 -2305 #[tokio::test] -2306 #[traced_test] -2307 async fn test_direct_addresses_no_qad_relay() -> Result { -2308 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +2302 p1_accept.await.anyerr()??; +2303 p2_accept.await.anyerr()??; +2304 p1_connect.await.anyerr()??; +2305 p2_connect.await.anyerr()??; +2306 +2307 Ok(()) +2308 } 2309 -2310 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -2311 .alpns(vec![TEST_ALPN.to_vec()]) -2312 .insecure_skip_relay_cert_verify(true) -2313 .bind() -2314 .await?; -2315 -2316 assert!(ep.addr().ip_addrs().count() > 0); -2317 -2318 Ok(()) -2319 } +2310 #[tokio::test] +2311 #[traced_test] +2312 async fn test_direct_addresses_no_qad_relay() -> Result { +2313 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +2314 +2315 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +2316 .alpns(vec![TEST_ALPN.to_vec()]) +2317 .insecure_skip_relay_cert_verify(true) +2318 .bind() +2319 .await?; 2320 -2321 #[cfg_attr(target_os = "windows", ignore = "flaky")] -2322 #[tokio::test] -2323 #[traced_test] -2324 async fn graceful_close() -> Result { -2325 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; -2326 let server = Endpoint::empty_builder(RelayMode::Disabled) -2327 .alpns(vec![TEST_ALPN.to_vec()]) -2328 .bind() -2329 .await?; -2330 let server_addr = server.addr(); -2331 let server_task = tokio::spawn(async move { -2332 let incoming = server.accept().await.anyerr()?; -2333 let conn = incoming.await.anyerr()?; -2334 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2335 let msg = recv.read_to_end(1_000).await.anyerr()?; -2336 send.write_all(&msg).await.anyerr()?; -2337 send.finish().anyerr()?; -2338 let close_reason = conn.closed().await; -2339 Ok::<_, Error>(close_reason) -2340 }); -2341 -2342 let conn = client.connect(server_addr, TEST_ALPN).await?; -2343 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2344 send.write_all(b"Hello, world!").await.anyerr()?; -2345 send.finish().anyerr()?; -2346 recv.read_to_end(1_000).await.anyerr()?; -2347 conn.close(42u32.into(), b"thanks, bye!"); -2348 client.close().await; -2349 -2350 let close_err = server_task.await.anyerr()??; -2351 let ConnectionError::ApplicationClosed(app_close) = close_err else { -2352 panic!("Unexpected close reason: {close_err:?}"); -2353 }; +2321 assert!(ep.addr().ip_addrs().count() > 0); +2322 +2323 Ok(()) +2324 } +2325 +2326 #[cfg_attr(target_os = "windows", ignore = "flaky")] +2327 #[tokio::test] +2328 #[traced_test] +2329 async fn graceful_close() -> Result { +2330 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; +2331 let server = Endpoint::empty_builder(RelayMode::Disabled) +2332 .alpns(vec![TEST_ALPN.to_vec()]) +2333 .bind() +2334 .await?; +2335 let server_addr = server.addr(); +2336 let server_task = tokio::spawn(async move { +2337 let incoming = server.accept().await.anyerr()?; +2338 let conn = incoming.await.anyerr()?; +2339 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2340 let msg = recv.read_to_end(1_000).await.anyerr()?; +2341 send.write_all(&msg).await.anyerr()?; +2342 send.finish().anyerr()?; +2343 let close_reason = conn.closed().await; +2344 Ok::<_, Error>(close_reason) +2345 }); +2346 +2347 let conn = client.connect(server_addr, TEST_ALPN).await?; +2348 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2349 send.write_all(b"Hello, world!").await.anyerr()?; +2350 send.finish().anyerr()?; +2351 recv.read_to_end(1_000).await.anyerr()?; +2352 conn.close(42u32.into(), b"thanks, bye!"); +2353 client.close().await; 2354 -2355 assert_eq!(app_close.error_code, 42u32.into()); -2356 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); -2357 -2358 Ok(()) -2359 } -2360 -2361 #[cfg(feature = "metrics")] -2362 #[tokio::test] -2363 #[traced_test] -2364 async fn metrics_smoke() -> Result { -2365 use iroh_metrics::{MetricsSource, Registry}; -2366 -2367 let secret_key = SecretKey::from_bytes(&[0u8; 32]); -2368 let client = Endpoint::empty_builder(RelayMode::Disabled) -2369 .secret_key(secret_key) -2370 .bind() -2371 .await?; -2372 let secret_key = SecretKey::from_bytes(&[1u8; 32]); -2373 let server = Endpoint::empty_builder(RelayMode::Disabled) +2355 let close_err = server_task.await.anyerr()??; +2356 let ConnectionError::ApplicationClosed(app_close) = close_err else { +2357 panic!("Unexpected close reason: {close_err:?}"); +2358 }; +2359 +2360 assert_eq!(app_close.error_code, 42u32.into()); +2361 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +2362 +2363 Ok(()) +2364 } +2365 +2366 #[cfg(feature = "metrics")] +2367 #[tokio::test] +2368 #[traced_test] +2369 async fn metrics_smoke() -> Result { +2370 use iroh_metrics::{MetricsSource, Registry}; +2371 +2372 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +2373 let client = Endpoint::empty_builder(RelayMode::Disabled) 2374 .secret_key(secret_key) -2375 .alpns(vec![TEST_ALPN.to_vec()]) -2376 .bind() -2377 .await?; -2378 let server_addr = server.addr(); -2379 let server_task = tokio::task::spawn(async move { -2380 let conn = server.accept().await.anyerr()?.await.anyerr()?; -2381 let mut uni = conn.accept_uni().await.anyerr()?; -2382 uni.read_to_end(10).await.anyerr()?; -2383 drop(conn); -2384 Ok::<_, Error>(server) -2385 }); -2386 let conn = client.connect(server_addr, TEST_ALPN).await?; -2387 let mut uni = conn.open_uni().await.anyerr()?; -2388 uni.write_all(b"helloworld").await.anyerr()?; -2389 uni.finish().anyerr()?; -2390 conn.closed().await; -2391 drop(conn); -2392 let server = server_task.await.anyerr()??; -2393 -2394 let m = client.metrics(); -2395 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -2396 assert_eq!(m.magicsock.connection_became_direct.get(), 1); -2397 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -2398 assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); -2399 assert!(m.magicsock.recv_datagrams.get() > 0); -2400 -2401 let m = server.metrics(); -2402 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -2403 assert_eq!(m.magicsock.connection_became_direct.get(), 1); -2404 assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); -2405 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -2406 assert!(m.magicsock.recv_datagrams.get() > 0); -2407 -2408 // test openmetrics encoding with labeled subregistries per endpoint -2409 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { -2410 let id = endpoint.id().fmt_short(); -2411 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); -2412 sub_registry.register_all(endpoint.metrics()); -2413 } -2414 let mut registry = Registry::default(); -2415 register_endpoint(&mut registry, &client); -2416 register_endpoint(&mut registry, &server); -2417 let s = registry.encode_openmetrics_to_string().anyerr()?; -2418 assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); -2419 assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); -2420 Ok(()) -2421 } -2422 -2423 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` -2424 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. -2425 async fn alpn_connection_test( -2426 accept_alpns: Vec<Vec<u8>>, -2427 primary_connect_alpn: &[u8], -2428 secondary_connect_alpns: Vec<Vec<u8>>, -2429 ) -> Result<Vec<u8>> { -2430 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; -2431 let server = Endpoint::empty_builder(RelayMode::Disabled) -2432 .alpns(accept_alpns) -2433 .bind() -2434 .await?; -2435 let server_addr = server.addr(); -2436 let server_task = tokio::spawn({ -2437 let server = server.clone(); -2438 async move { -2439 let incoming = server.accept().await.anyerr()?; -2440 let conn = incoming.await.anyerr()?; -2441 conn.close(0u32.into(), b"bye!"); -2442 n0_error::Ok(conn.alpn().to_vec()) -2443 } -2444 }); -2445 -2446 let conn = client -2447 .connect_with_opts( -2448 server_addr, -2449 primary_connect_alpn, -2450 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), -2451 ) -2452 .await?; -2453 let conn = conn.await.anyerr()?; -2454 let client_alpn = conn.alpn(); -2455 conn.closed().await; -2456 client.close().await; -2457 server.close().await; -2458 -2459 let server_alpn = server_task.await.anyerr()??; -2460 -2461 assert_eq!(client_alpn, server_alpn); -2462 -2463 Ok(server_alpn.to_vec()) -2464 } +2375 .bind() +2376 .await?; +2377 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +2378 let server = Endpoint::empty_builder(RelayMode::Disabled) +2379 .secret_key(secret_key) +2380 .alpns(vec![TEST_ALPN.to_vec()]) +2381 .bind() +2382 .await?; +2383 let server_addr = server.addr(); +2384 let server_task = tokio::task::spawn(async move { +2385 let conn = server.accept().await.anyerr()?.await.anyerr()?; +2386 let mut uni = conn.accept_uni().await.anyerr()?; +2387 uni.read_to_end(10).await.anyerr()?; +2388 drop(conn); +2389 Ok::<_, Error>(server) +2390 }); +2391 let conn = client.connect(server_addr, TEST_ALPN).await?; +2392 let mut uni = conn.open_uni().await.anyerr()?; +2393 uni.write_all(b"helloworld").await.anyerr()?; +2394 uni.finish().anyerr()?; +2395 conn.closed().await; +2396 drop(conn); +2397 let server = server_task.await.anyerr()??; +2398 +2399 let m = client.metrics(); +2400 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +2401 assert_eq!(m.magicsock.connection_became_direct.get(), 1); +2402 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +2403 assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); +2404 assert!(m.magicsock.recv_datagrams.get() > 0); +2405 +2406 let m = server.metrics(); +2407 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +2408 assert_eq!(m.magicsock.connection_became_direct.get(), 1); +2409 assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); +2410 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +2411 assert!(m.magicsock.recv_datagrams.get() > 0); +2412 +2413 // test openmetrics encoding with labeled subregistries per endpoint +2414 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +2415 let id = endpoint.id().fmt_short(); +2416 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); +2417 sub_registry.register_all(endpoint.metrics()); +2418 } +2419 let mut registry = Registry::default(); +2420 register_endpoint(&mut registry, &client); +2421 register_endpoint(&mut registry, &server); +2422 let s = registry.encode_openmetrics_to_string().anyerr()?; +2423 assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); +2424 assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); +2425 Ok(()) +2426 } +2427 +2428 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +2429 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +2430 async fn alpn_connection_test( +2431 accept_alpns: Vec<Vec<u8>>, +2432 primary_connect_alpn: &[u8], +2433 secondary_connect_alpns: Vec<Vec<u8>>, +2434 ) -> Result<Vec<u8>> { +2435 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; +2436 let server = Endpoint::empty_builder(RelayMode::Disabled) +2437 .alpns(accept_alpns) +2438 .bind() +2439 .await?; +2440 let server_addr = server.addr(); +2441 let server_task = tokio::spawn({ +2442 let server = server.clone(); +2443 async move { +2444 let incoming = server.accept().await.anyerr()?; +2445 let conn = incoming.await.anyerr()?; +2446 conn.close(0u32.into(), b"bye!"); +2447 n0_error::Ok(conn.alpn().to_vec()) +2448 } +2449 }); +2450 +2451 let conn = client +2452 .connect_with_opts( +2453 server_addr, +2454 primary_connect_alpn, +2455 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +2456 ) +2457 .await?; +2458 let conn = conn.await.anyerr()?; +2459 let client_alpn = conn.alpn(); +2460 conn.closed().await; +2461 client.close().await; +2462 server.close().await; +2463 +2464 let server_alpn = server_task.await.anyerr()??; 2465 -2466 #[tokio::test] -2467 #[traced_test] -2468 async fn connect_multiple_alpn_negotiated() -> Result { -2469 const ALPN_ONE: &[u8] = b"alpn/1"; -2470 const ALPN_TWO: &[u8] = b"alpn/2"; -2471 -2472 assert_eq!( -2473 alpn_connection_test( -2474 // Prefer version 2 over version 1 on the accept side -2475 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -2476 ALPN_TWO, -2477 vec![ALPN_ONE.to_vec()], -2478 ) -2479 .await?, -2480 ALPN_TWO.to_vec(), -2481 "accept side prefers version 2 over 1" -2482 ); -2483 -2484 assert_eq!( -2485 alpn_connection_test( -2486 // Only support the old version -2487 vec![ALPN_ONE.to_vec()], -2488 ALPN_TWO, -2489 vec![ALPN_ONE.to_vec()], -2490 ) -2491 .await?, -2492 ALPN_ONE.to_vec(), -2493 "accept side only supports the old version" -2494 ); -2495 -2496 assert_eq!( -2497 alpn_connection_test( -2498 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -2499 ALPN_ONE, -2500 vec![ALPN_TWO.to_vec()], -2501 ) -2502 .await?, -2503 ALPN_TWO.to_vec(), -2504 "connect side ALPN order doesn't matter" -2505 ); -2506 -2507 assert_eq!( -2508 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) -2509 .await?, -2510 ALPN_ONE.to_vec(), -2511 "connect side only supports the old version" -2512 ); -2513 -2514 Ok(()) -2515 } -2516 -2517 #[tokio::test] -2518 #[traced_test] -2519 async fn watch_net_report() -> Result { -2520 let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?; +2466 assert_eq!(client_alpn, server_alpn); +2467 +2468 Ok(server_alpn.to_vec()) +2469 } +2470 +2471 #[tokio::test] +2472 #[traced_test] +2473 async fn connect_multiple_alpn_negotiated() -> Result { +2474 const ALPN_ONE: &[u8] = b"alpn/1"; +2475 const ALPN_TWO: &[u8] = b"alpn/2"; +2476 +2477 assert_eq!( +2478 alpn_connection_test( +2479 // Prefer version 2 over version 1 on the accept side +2480 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +2481 ALPN_TWO, +2482 vec![ALPN_ONE.to_vec()], +2483 ) +2484 .await?, +2485 ALPN_TWO.to_vec(), +2486 "accept side prefers version 2 over 1" +2487 ); +2488 +2489 assert_eq!( +2490 alpn_connection_test( +2491 // Only support the old version +2492 vec![ALPN_ONE.to_vec()], +2493 ALPN_TWO, +2494 vec![ALPN_ONE.to_vec()], +2495 ) +2496 .await?, +2497 ALPN_ONE.to_vec(), +2498 "accept side only supports the old version" +2499 ); +2500 +2501 assert_eq!( +2502 alpn_connection_test( +2503 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +2504 ALPN_ONE, +2505 vec![ALPN_TWO.to_vec()], +2506 ) +2507 .await?, +2508 ALPN_TWO.to_vec(), +2509 "connect side ALPN order doesn't matter" +2510 ); +2511 +2512 assert_eq!( +2513 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +2514 .await?, +2515 ALPN_ONE.to_vec(), +2516 "connect side only supports the old version" +2517 ); +2518 +2519 Ok(()) +2520 } 2521 -2522 // can get a first report -2523 endpoint.net_report().updated().await.anyerr()?; -2524 -2525 Ok(()) -2526 } -2527 -2528 /// Tests that initial connection establishment isn't extremely slow compared -2529 /// to subsequent connections. -2530 /// -2531 /// This is a time based test, but uses a very large ratio to reduce flakiness. -2532 /// It also does a number of connections to average out any anomalies. -2533 #[tokio::test] -2534 #[traced_test] -2535 async fn connect_multi_time() -> Result { -2536 let n = 32; -2537 -2538 const NOOP_ALPN: &[u8] = b"noop"; -2539 -2540 #[derive(Debug, Clone)] -2541 struct Noop; +2522 #[tokio::test] +2523 #[traced_test] +2524 async fn watch_net_report() -> Result { +2525 let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?; +2526 +2527 // can get a first report +2528 endpoint.net_report().updated().await.anyerr()?; +2529 +2530 Ok(()) +2531 } +2532 +2533 /// Tests that initial connection establishment isn't extremely slow compared +2534 /// to subsequent connections. +2535 /// +2536 /// This is a time based test, but uses a very large ratio to reduce flakiness. +2537 /// It also does a number of connections to average out any anomalies. +2538 #[tokio::test] +2539 #[traced_test] +2540 async fn connect_multi_time() -> Result { +2541 let n = 32; 2542 -2543 impl ProtocolHandler for Noop { -2544 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { -2545 connection.closed().await; -2546 Ok(()) -2547 } -2548 } -2549 -2550 async fn noop_server() -> Result<(Router, EndpointAddr)> { -2551 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) -2552 .bind() -2553 .await -2554 .anyerr()?; -2555 let addr = endpoint.addr(); -2556 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); -2557 Ok((router, addr)) -2558 } -2559 -2560 let routers = stream::iter(0..n) -2561 .map(|_| noop_server()) -2562 .buffered_unordered(32) -2563 .collect::<Vec<_>>() -2564 .await -2565 .into_iter() -2566 .collect::<Result<Vec<_>, _>>() -2567 .anyerr()?; -2568 -2569 let addrs = routers -2570 .iter() -2571 .map(|(_, addr)| addr.clone()) -2572 .collect::<Vec<_>>(); -2573 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); -2574 let discovery = StaticProvider::from_endpoint_info(addrs); -2575 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) -2576 .discovery(discovery) -2577 .bind() -2578 .await -2579 .anyerr()?; -2580 // wait for the endpoint to be initialized. This should not be needed, -2581 // but we don't want to measure endpoint init time but connection time -2582 // from a fully initialized endpoint. -2583 endpoint.addr(); -2584 let t0 = Instant::now(); -2585 for id in &ids { -2586 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -2587 conn.close(0u32.into(), b"done"); -2588 } -2589 let dt0 = t0.elapsed().as_secs_f64(); -2590 let t1 = Instant::now(); -2591 for id in &ids { -2592 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -2593 conn.close(0u32.into(), b"done"); -2594 } -2595 let dt1 = t1.elapsed().as_secs_f64(); -2596 -2597 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); -2598 Ok(()) -2599 } -2600}
    \ No newline at end of file +2543 const NOOP_ALPN: &[u8] = b"noop"; +2544 +2545 #[derive(Debug, Clone)] +2546 struct Noop; +2547 +2548 impl ProtocolHandler for Noop { +2549 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +2550 connection.closed().await; +2551 Ok(()) +2552 } +2553 } +2554 +2555 async fn noop_server() -> Result<(Router, EndpointAddr)> { +2556 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) +2557 .bind() +2558 .await +2559 .anyerr()?; +2560 let addr = endpoint.addr(); +2561 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); +2562 Ok((router, addr)) +2563 } +2564 +2565 let routers = stream::iter(0..n) +2566 .map(|_| noop_server()) +2567 .buffered_unordered(32) +2568 .collect::<Vec<_>>() +2569 .await +2570 .into_iter() +2571 .collect::<Result<Vec<_>, _>>() +2572 .anyerr()?; +2573 +2574 let addrs = routers +2575 .iter() +2576 .map(|(_, addr)| addr.clone()) +2577 .collect::<Vec<_>>(); +2578 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); +2579 let discovery = StaticProvider::from_endpoint_info(addrs); +2580 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) +2581 .discovery(discovery) +2582 .bind() +2583 .await +2584 .anyerr()?; +2585 // wait for the endpoint to be initialized. This should not be needed, +2586 // but we don't want to measure endpoint init time but connection time +2587 // from a fully initialized endpoint. +2588 endpoint.addr(); +2589 let t0 = Instant::now(); +2590 for id in &ids { +2591 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +2592 conn.close(0u32.into(), b"done"); +2593 } +2594 let dt0 = t0.elapsed().as_secs_f64(); +2595 let t1 = Instant::now(); +2596 for id in &ids { +2597 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +2598 conn.close(0u32.into(), b"done"); +2599 } +2600 let dt1 = t1.elapsed().as_secs_f64(); +2601 +2602 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); +2603 Ok(()) +2604 } +2605}
    \ No newline at end of file diff --git a/pr/3651/docs/src/iroh/magicsock.rs.html b/pr/3651/docs/src/iroh/magicsock.rs.html index 2fe15869d4..51b2db1642 100644 --- a/pr/3651/docs/src/iroh/magicsock.rs.html +++ b/pr/3651/docs/src/iroh/magicsock.rs.html @@ -958,1645 +958,1646 @@ 958 let relay_map = relay_transport_configs 959 .iter() 960 .filter_map(|t| { -961 if let TransportConfig::Relay { relay_map } = t { -962 Some(relay_map.clone()) -963 } else { -964 None -965 } -966 }) -967 .next() -968 .unwrap_or_else(RelayMap::empty); -969 -970 let my_relay = Watchable::new(None); -971 let ipv6_reported = Arc::new(AtomicBool::new(false)); -972 -973 let relay_actor_config = RelayActorConfig { -974 my_relay: my_relay.clone(), -975 secret_key: secret_key.clone(), -976 #[cfg(not(wasm_browser))] -977 dns_resolver: dns_resolver.clone(), -978 proxy_url: proxy_url.clone(), -979 ipv6_reported: ipv6_reported.clone(), -980 #[cfg(any(test, feature = "test-utils"))] -981 insecure_skip_relay_cert_verify, -982 metrics: metrics.magicsock.clone(), -983 }; -984 let shutdown_token = CancellationToken::new(); -985 -986 let transports = Transports::bind( -987 &transport_configs, -988 relay_actor_config, -989 &metrics, -990 shutdown_token.child_token(), -991 ) -992 .map_err(|err| e!(CreateHandleError::BindSockets, err))?; -993 -994 #[cfg(not(wasm_browser))] -995 { -996 if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { -997 if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { -998 Some(addr.port()) -999 } else { -1000 None -1001 } -1002 }) { -1003 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails -1004 match v4_port.try_into() { -1005 Ok(non_zero_port) => { -1006 port_mapper.update_local_port(non_zero_port); -1007 } -1008 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), -1009 } -1010 } -1011 } -1012 -1013 let (actor_sender, actor_receiver) = mpsc::channel(256); -1014 -1015 #[cfg(not(wasm_browser))] -1016 let ipv6 = transports -1017 .ip_bind_addrs() -1018 .into_iter() -1019 .any(|addr| addr.is_ipv6()); -1020 -1021 let direct_addrs = DiscoveredDirectAddrs::default(); -1022 let (disco, disco_receiver) = DiscoState::new(&secret_key); -1023 -1024 let endpoint_map = { -1025 EndpointMap::new( -1026 secret_key.public(), -1027 // #[cfg(any(test, feature = "test-utils"))] -1028 // path_selection, -1029 metrics.magicsock.clone(), -1030 direct_addrs.addrs.watch(), -1031 disco.clone(), -1032 transports.create_sender(), -1033 ) -1034 }; -1035 -1036 let msock = Arc::new(MagicSock { -1037 public_key: secret_key.public(), -1038 closing: AtomicBool::new(false), -1039 closed: AtomicBool::new(false), -1040 disco, -1041 actor_sender: actor_sender.clone(), -1042 ipv6_reported, -1043 endpoint_map, -1044 discovery, -1045 relay_map: relay_map.clone(), -1046 discovery_user_data: RwLock::new(discovery_user_data), -1047 direct_addrs, -1048 net_report: Watchable::new((None, UpdateReason::None)), -1049 #[cfg(not(wasm_browser))] -1050 dns_resolver: dns_resolver.clone(), -1051 metrics: metrics.clone(), -1052 local_addrs_watch: transports.local_addrs_watch(), -1053 #[cfg(not(wasm_browser))] -1054 ip_bind_addrs: transports.ip_bind_addrs(), -1055 }); -1056 -1057 let mut endpoint_config = quinn::EndpointConfig::default(); -1058 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit -1059 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -1060 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -1061 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore -1062 // the packet if grease_quic_bit is set to false. -1063 endpoint_config.grease_quic_bit(false); -1064 -1065 let sender = transports.create_sender(); -1066 let local_addrs_watch = transports.local_addrs_watch(); -1067 let network_change_sender = transports.create_network_change_sender(); -1068 -1069 let endpoint = quinn::Endpoint::new_with_abstract_socket( -1070 endpoint_config, -1071 Some(server_config), -1072 Box::new(MagicTransport::new(msock.clone(), transports)), -1073 #[cfg(not(wasm_browser))] -1074 Arc::new(quinn::TokioRuntime), -1075 #[cfg(wasm_browser)] -1076 Arc::new(crate::web_runtime::WebRuntime), -1077 ) -1078 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; -1079 -1080 let network_monitor = netmon::Monitor::new() -1081 .await -1082 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; -1083 -1084 let qad_endpoint = endpoint.clone(); -1085 -1086 #[cfg(any(test, feature = "test-utils"))] -1087 let client_config = if insecure_skip_relay_cert_verify { -1088 iroh_relay::client::make_dangerous_client_config() -1089 } else { -1090 default_quic_client_config() -1091 }; -1092 #[cfg(not(any(test, feature = "test-utils")))] -1093 let client_config = default_quic_client_config(); -1094 -1095 let net_report_config = net_report::Options::default(); -1096 #[cfg(not(wasm_browser))] -1097 let net_report_config = net_report_config.quic_config(Some(QuicConfig { -1098 ep: qad_endpoint, -1099 client_config, -1100 ipv4: true, -1101 ipv6, -1102 })); -1103 -1104 #[cfg(any(test, feature = "test-utils"))] -1105 let net_report_config = -1106 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); -1107 -1108 let net_reporter = net_report::Client::new( -1109 #[cfg(not(wasm_browser))] -1110 dns_resolver, -1111 relay_map.clone(), -1112 net_report_config, -1113 metrics.net_report.clone(), -1114 ); -1115 -1116 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -1117 let direct_addr_update_state = DirectAddrUpdateState::new( -1118 msock.clone(), -1119 #[cfg(not(wasm_browser))] -1120 port_mapper, -1121 Arc::new(AsyncMutex::new(net_reporter)), -1122 relay_map, -1123 direct_addr_done_tx, -1124 ); -1125 -1126 let netmon_watcher = network_monitor.interface_state(); -1127 -1128 #[cfg_attr(not(wasm_browser), allow(unused_mut))] -1129 let mut actor = Actor { -1130 msg_receiver: actor_receiver, -1131 msock: msock.clone(), -1132 periodic_re_stun_timer: new_re_stun_timer(false), -1133 network_monitor, -1134 netmon_watcher, -1135 direct_addr_update_state, -1136 network_change_sender, -1137 direct_addr_done_rx, -1138 pending_call_me_maybes: Default::default(), -1139 disco_receiver, -1140 }; -1141 // Initialize addresses -1142 #[cfg(not(wasm_browser))] -1143 actor.update_direct_addresses(None); -1144 -1145 let actor_task = task::spawn( -1146 actor -1147 .run(shutdown_token.child_token(), local_addrs_watch, sender) -1148 .instrument(info_span!("actor")), -1149 ); -1150 -1151 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); -1152 -1153 Ok(Handle { -1154 msock, -1155 actor_task, -1156 endpoint, -1157 shutdown_token, -1158 }) -1159 } -1160 -1161 /// The underlying [`quinn::Endpoint`] -1162 pub fn endpoint(&self) -> &quinn::Endpoint { -1163 &self.endpoint -1164 } -1165 -1166 /// Closes the connection. -1167 /// -1168 /// Only the first close does anything. Any later closes return nil. Polling the socket -1169 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely -1170 /// after this call. -1171 /// -1172 /// [`Poll::Pending`]: std::task::Poll::Pending -1173 #[instrument(skip_all)] -1174 pub(crate) async fn close(&self) { -1175 trace!(me = ?self.public_key, "magicsock closing..."); -1176 // Initiate closing all connections, and refuse future connections. -1177 self.endpoint.close(0u16.into(), b""); -1178 -1179 // In the history of this code, this call had been -1180 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1181 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1182 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1183 // and finally added back in together with this comment. -1184 // So before removing this call, please consider carefully. -1185 // Among other things, this call tries its best to make sure that any queued close frames -1186 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -1187 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -1188 // This allows the other endpoints for these connections to be notified to release -1189 // their resources, or - depending on the protocol - that all data was received. -1190 // With the current quinn API, this is the only way to ensure protocol code can use -1191 // connection close codes, and close the endpoint properly. -1192 // If this call is skipped, then connections that protocols close just shortly before the -1193 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -1194 self.endpoint.wait_idle().await; -1195 -1196 if self.msock.is_closed() { -1197 return; -1198 } -1199 self.msock.closing.store(true, Ordering::Relaxed); -1200 self.shutdown_token.cancel(); -1201 -1202 // MutexGuard is not held across await points -1203 let task = self.actor_task.lock().expect("poisoned").take(); -1204 if let Some(task) = task { -1205 // give the tasks a moment to shutdown cleanly -1206 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1207 if let Err(err) = task.await { -1208 warn!("unexpected error in task shutdown: {:?}", err); -1209 } -1210 }) -1211 .await; -1212 match shutdown_done { -1213 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1214 Err(time::Elapsed { .. }) => { -1215 // Dropping the task will abort itt -1216 warn!("tasks didn't finish in time, aborting"); -1217 } -1218 } -1219 } -1220 -1221 self.msock.closed.store(true, Ordering::SeqCst); -1222 -1223 trace!("magicsock closed"); -1224 } -1225} -1226 -1227fn default_quic_client_config() -> rustls::ClientConfig { -1228 // create a client config for the endpoint to use for QUIC address discovery -1229 let root_store = -1230 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -1231 rustls::client::ClientConfig::builder_with_provider(Arc::new( -1232 rustls::crypto::ring::default_provider(), -1233 )) -1234 .with_safe_default_protocol_versions() -1235 .expect("ring supports these") -1236 .with_root_certificates(root_store) -1237 .with_no_client_auth() -1238} -1239 -1240#[derive(Debug, Clone)] -1241struct DiscoState { -1242 /// The EndpointId/PublikeKey of this endpoint. -1243 this_id: EndpointId, -1244 /// Encryption key for this endpoint. -1245 secret_encryption_key: Arc<crypto_box::SecretKey>, -1246 /// The state for an active DiscoKey. -1247 secrets: Arc<Mutex<HashMap<PublicKey, SharedSecret>>>, -1248 /// Disco (ping) queue -1249 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, -1250} -1251 -1252impl DiscoState { -1253 fn new( -1254 secret_key: &SecretKey, -1255 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { -1256 let this_id = secret_key.public(); -1257 let secret_encryption_key = secret_ed_box(secret_key); -1258 let (disco_sender, disco_receiver) = mpsc::channel(256); -1259 -1260 ( -1261 Self { -1262 this_id, -1263 secret_encryption_key: Arc::new(secret_encryption_key), -1264 secrets: Default::default(), -1265 sender: disco_sender, -1266 }, -1267 disco_receiver, -1268 ) -1269 } -1270 -1271 fn try_send(&self, dst: SendAddr, dst_key: PublicKey, msg: disco::Message) -> bool { -1272 self.sender.try_send((dst, dst_key, msg)).is_ok() -1273 } -1274 -1275 fn encode_and_seal(&self, other_key: PublicKey, msg: &disco::Message) -> Bytes { -1276 let mut seal = msg.as_bytes(); -1277 self.get_secret(other_key, |secret| secret.seal(&mut seal)); -1278 disco::encode_message(&self.this_id, seal).into() -1279 } -1280 -1281 fn unseal_and_decode( -1282 &self, -1283 endpoint_key: PublicKey, -1284 sealed_box: &[u8], -1285 ) -> Result<disco::Message, DiscoBoxError> { -1286 let mut sealed_box = sealed_box.to_vec(); -1287 self.get_secret(endpoint_key, |secret| secret.open(&mut sealed_box)) -1288 .map_err(|source| e!(DiscoBoxError::Open { source }))?; -1289 disco::Message::from_bytes(&sealed_box) -1290 .map_err(|source| e!(DiscoBoxError::Parse { source })) -1291 } -1292 -1293 fn get_secret<F, T>(&self, endpoint_id: PublicKey, cb: F) -> T -1294 where -1295 F: FnOnce(&mut SharedSecret) -> T, -1296 { -1297 let mut inner = self.secrets.lock().expect("poisoned"); -1298 let x = inner.entry(endpoint_id).or_insert_with(|| { -1299 let public_key = public_ed_box(&endpoint_id); -1300 SharedSecret::new(&self.secret_encryption_key, &public_key) -1301 }); -1302 cb(x) -1303 } -1304} -1305 -1306#[allow(missing_docs)] -1307#[stack_error(derive, add_meta)] -1308#[non_exhaustive] -1309enum DiscoBoxError { -1310 #[error("Failed to open crypto box")] -1311 Open { source: DecryptionError }, -1312 #[error("Failed to parse disco message")] -1313 Parse { source: disco::ParseError }, -1314} -1315 -1316#[derive(Debug)] -1317#[allow(clippy::enum_variant_names)] -1318enum ActorMessage { -1319 NetworkChange, -1320 RelayMapChange, -1321 #[cfg(test)] -1322 ForceNetworkChange(bool), -1323} -1324 -1325struct Actor { -1326 msock: Arc<MagicSock>, -1327 msg_receiver: mpsc::Receiver<ActorMessage>, -1328 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. -1329 periodic_re_stun_timer: time::Interval, -1330 -1331 network_monitor: netmon::Monitor, -1332 netmon_watcher: n0_watcher::Direct<netmon::State>, -1333 network_change_sender: transports::NetworkChangeSender, -1334 /// Indicates the direct addr update state. -1335 direct_addr_update_state: DirectAddrUpdateState, -1336 direct_addr_done_rx: mpsc::Receiver<()>, -1337 -1338 /// List of CallMeMaybe disco messages that should be sent out after -1339 /// the next endpoint update completes -1340 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, -1341 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, -1342} -1343 -1344impl Actor { -1345 async fn run( -1346 mut self, -1347 shutdown_token: CancellationToken, -1348 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1349 sender: TransportsSender, -1350 ) { -1351 // Setup network monitoring -1352 let mut current_netmon_state = self.netmon_watcher.get(); -1353 -1354 #[cfg(not(wasm_browser))] -1355 let mut portmap_watcher = self -1356 .direct_addr_update_state -1357 .port_mapper -1358 .watch_external_address(); -1359 -1360 let mut receiver_closed = false; -1361 #[cfg_attr(wasm_browser, allow(unused_mut))] -1362 let mut portmap_watcher_closed = false; -1363 -1364 let mut net_report_watcher = self.msock.net_report.watch(); -1365 -1366 // ensure we are doing an initial publish of our addresses -1367 self.msock.publish_my_addr(); -1368 -1369 // Interval timer to remove closed `EndpointStateActor` handles from the endpoint map. -1370 let mut endpoint_map_gc = time::interval(endpoint_map::ENDPOINT_MAP_GC_INTERVAL); -1371 -1372 loop { -1373 self.msock.metrics.magicsock.actor_tick_main.inc(); -1374 #[cfg(not(wasm_browser))] -1375 let portmap_watcher_changed = portmap_watcher.changed(); -1376 #[cfg(wasm_browser)] -1377 let portmap_watcher_changed = n0_future::future::pending(); -1378 -1379 tokio::select! { -1380 _ = shutdown_token.cancelled() => { -1381 debug!("shutting down"); -1382 return; -1383 } -1384 msg = self.msg_receiver.recv(), if !receiver_closed => { -1385 let Some(msg) = msg else { -1386 trace!("tick: magicsock receiver closed"); -1387 self.msock.metrics.magicsock.actor_tick_other.inc(); -1388 -1389 receiver_closed = true; -1390 continue; -1391 }; -1392 -1393 trace!(?msg, "tick: msg"); -1394 self.msock.metrics.magicsock.actor_tick_msg.inc(); -1395 self.handle_actor_message(msg).await; -1396 } -1397 tick = self.periodic_re_stun_timer.tick() => { -1398 trace!("tick: re_stun {:?}", tick); -1399 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); -1400 self.re_stun(UpdateReason::Periodic); -1401 } -1402 new_addr = watcher.updated() => { -1403 match new_addr { -1404 Ok(addrs) => { -1405 if !addrs.is_empty() { -1406 trace!(?addrs, "local addrs"); -1407 self.msock.publish_my_addr(); -1408 } -1409 } -1410 Err(_) => { -1411 warn!("local addr watcher stopped"); -1412 } -1413 } -1414 } -1415 report = net_report_watcher.updated() => { -1416 match report { -1417 Ok((report, _)) => { -1418 self.handle_net_report_report(report); -1419 #[cfg(not(wasm_browser))] -1420 { -1421 self.periodic_re_stun_timer = new_re_stun_timer(true); -1422 } -1423 } -1424 Err(_) => { -1425 warn!("net report watcher stopped"); -1426 } -1427 } -1428 } -1429 reason = self.direct_addr_done_rx.recv() => { -1430 match reason { -1431 Some(()) => { -1432 // check if a new run needs to be scheduled -1433 let state = self.netmon_watcher.get(); -1434 self.direct_addr_update_state.try_run(state.into()); -1435 } -1436 None => { -1437 warn!("direct addr watcher died"); -1438 } -1439 } -1440 } -1441 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1442 #[cfg(not(wasm_browser))] -1443 { -1444 if change.is_err() { -1445 trace!("tick: portmap watcher closed"); -1446 self.msock.metrics.magicsock.actor_tick_other.inc(); -1447 -1448 portmap_watcher_closed = true; -1449 continue; -1450 } -1451 -1452 trace!("tick: portmap changed"); -1453 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); -1454 let new_external_address = *portmap_watcher.borrow(); -1455 debug!("external address updated: {new_external_address:?}"); -1456 self.re_stun(UpdateReason::PortmapUpdated); -1457 } -1458 #[cfg(wasm_browser)] -1459 let _unused_in_browsers = change; -1460 }, -1461 state = self.netmon_watcher.updated() => { -1462 let Ok(state) = state else { -1463 trace!("tick: link change receiver closed"); -1464 self.msock.metrics.magicsock.actor_tick_other.inc(); -1465 continue; -1466 }; -1467 let is_major = state.is_major_change(&current_netmon_state); -1468 event!( -1469 target: "iroh::_events::link_change", -1470 Level::DEBUG, -1471 ?state, -1472 is_major -1473 ); -1474 current_netmon_state = state; -1475 self.msock.metrics.magicsock.actor_link_change.inc(); -1476 self.handle_network_change(is_major).await; -1477 } -1478 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { -1479 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { -1480 warn!(%dst, endpoint = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); -1481 } -1482 } -1483 _ = endpoint_map_gc.tick() => { -1484 self.msock.endpoint_map.remove_closed_endpoint_state_actors(); -1485 } -1486 } -1487 } -1488 } -1489 -1490 async fn handle_network_change(&mut self, is_major: bool) { -1491 debug!(is_major, "link change detected"); -1492 -1493 if is_major { -1494 if let Err(err) = self.network_change_sender.rebind() { -1495 warn!("failed to rebind transports: {err:?}"); -1496 } -1497 -1498 #[cfg(not(wasm_browser))] -1499 self.msock.dns_resolver.reset().await; -1500 self.re_stun(UpdateReason::LinkChangeMajor); -1501 } else { -1502 self.re_stun(UpdateReason::LinkChangeMinor); -1503 } -1504 } -1505 -1506 fn handle_relay_map_change(&mut self) { -1507 self.re_stun(UpdateReason::RelayMapChange); -1508 } -1509 -1510 fn re_stun(&mut self, why: UpdateReason) { -1511 let state = self.netmon_watcher.get(); -1512 self.direct_addr_update_state -1513 .schedule_run(why, state.into()); -1514 } -1515 -1516 /// Processes an incoming actor message. -1517 /// -1518 /// Returns `true` if it was a shutdown. -1519 async fn handle_actor_message(&mut self, msg: ActorMessage) { -1520 match msg { -1521 ActorMessage::NetworkChange => { -1522 self.network_monitor.network_change().await.ok(); -1523 } -1524 ActorMessage::RelayMapChange => { -1525 self.handle_relay_map_change(); -1526 } -1527 #[cfg(test)] -1528 ActorMessage::ForceNetworkChange(is_major) => { -1529 self.handle_network_change(is_major).await; -1530 } -1531 } -1532 } -1533 -1534 /// Updates the direct addresses of this magic socket. -1535 /// -1536 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of -1537 /// direct addresses from: -1538 /// -1539 /// - The portmapper. -1540 /// - A net_report report. -1541 /// - The local interfaces IP addresses. -1542 #[cfg(not(wasm_browser))] -1543 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1544 let portmap_watcher = self -1545 .direct_addr_update_state -1546 .port_mapper -1547 .watch_external_address(); -1548 -1549 // We only want to have one DirectAddr for each SocketAddr we have. So we store -1550 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -1551 // DirectAddr from each entry. -1552 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -1553 -1554 // First add PortMapper provided addresses. -1555 let maybe_port_mapped = *portmap_watcher.borrow(); -1556 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -1557 addrs -1558 .entry(portmap_ext) -1559 .or_insert(DirectAddrType::Portmapped); -1560 } -1561 -1562 // Next add STUN addresses from the net_report report. -1563 if let Some(net_report_report) = net_report_report { -1564 if let Some(global_v4) = net_report_report.global_v4 { -1565 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); -1566 -1567 // If they're behind a hard NAT and are using a fixed -1568 // port locally, assume they might've added a static -1569 // port mapping on their router to the same explicit -1570 // port that we are running with. Worst case it's an invalid candidate mapping. -1571 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { -1572 if addr.port() != 0 { -1573 Some(addr.port()) -1574 } else { -1575 None -1576 } -1577 }); -1578 -1579 if let Some(port) = port { -1580 if net_report_report -1581 .mapping_varies_by_dest() -1582 .unwrap_or_default() -1583 { -1584 let mut addr = global_v4; -1585 addr.set_port(port); -1586 addrs -1587 .entry(addr.into()) -1588 .or_insert(DirectAddrType::Qad4LocalPort); -1589 } -1590 } -1591 } -1592 if let Some(global_v6) = net_report_report.global_v6 { -1593 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); -1594 } -1595 } -1596 -1597 self.collect_local_addresses(&mut addrs); -1598 -1599 // Finally create and store store all these direct addresses and send any -1600 // queued call-me-maybe messages. -1601 self.msock.store_direct_addresses( -1602 addrs -1603 .iter() -1604 .map(|(addr, typ)| DirectAddr { -1605 addr: *addr, -1606 typ: *typ, -1607 }) -1608 .collect(), -1609 ); -1610 self.send_queued_call_me_maybes(); -1611 } -1612 -1613 #[cfg(not(wasm_browser))] -1614 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { -1615 // Matches the addresses that have been bound vs the requested ones. -1616 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -1617 .msock -1618 .ip_bind_addrs() -1619 .iter() -1620 .copied() -1621 .zip(self.msock.ip_local_addrs()) -1622 .collect(); -1623 -1624 // Do we listen on any IPv4 unspecified address? -1625 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -1626 if a.is_ipv4() && a.ip().is_unspecified() { -1627 Some(a.port()) -1628 } else { -1629 None -1630 } -1631 }); -1632 // Do we listen on any IPv6 unspecified address? -1633 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -1634 if a.is_ipv6() && a.ip().is_unspecified() { -1635 Some(a.port()) -1636 } else { -1637 None -1638 } -1639 }); -1640 -1641 // If a socket is bound to the unspecified address, create SocketAddrs for -1642 // each local IP address by pairing it with the port the socket is bound on. -1643 if local_addrs -1644 .iter() -1645 .any(|(_, local)| local.ip().is_unspecified()) -1646 { -1647 let LocalAddresses { -1648 regular: mut ips, -1649 loopback, -1650 } = self.netmon_watcher.get().local_addresses; -1651 if ips.is_empty() && addrs.is_empty() { -1652 // Include loopback addresses only if there are no other interfaces -1653 // or public addresses, this allows testing offline. -1654 ips = loopback; -1655 } -1656 -1657 for ip in ips { -1658 let port_if_unspecified = match ip { -1659 IpAddr::V4(_) => has_ipv4_unspecified, -1660 IpAddr::V6(_) => has_ipv6_unspecified, -1661 }; -1662 if let Some(port) = port_if_unspecified { -1663 let addr = SocketAddr::new(ip, port); -1664 addrs.entry(addr).or_insert(DirectAddrType::Local); -1665 } -1666 } -1667 } -1668 -1669 // If a socket is bound to a specific address, add it. -1670 for (bound, local) in local_addrs { -1671 if !bound.ip().is_unspecified() { -1672 addrs.entry(local).or_insert(DirectAddrType::Local); -1673 } -1674 } -1675 } -1676 -1677 fn send_queued_call_me_maybes(&mut self) { -1678 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); -1679 let msg = disco::Message::CallMeMaybe(msg); -1680 // allocate, to minimize locking duration -1681 -1682 for (public_key, url) in self.pending_call_me_maybes.drain() { -1683 if !self -1684 .msock -1685 .disco -1686 .try_send(SendAddr::Relay(url), public_key, msg.clone()) -1687 { -1688 warn!(endpoint = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); -1689 } -1690 } -1691 } -1692 -1693 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -1694 if let Some(ref mut r) = report { -1695 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -1696 if r.preferred_relay.is_none() { -1697 if let Some(my_relay) = self.msock.my_relay() { -1698 r.preferred_relay.replace(my_relay); -1699 } -1700 } -1701 -1702 // Notify all transports -1703 self.network_change_sender.on_network_change(r); -1704 } -1705 -1706 #[cfg(not(wasm_browser))] -1707 self.update_direct_addresses(report.as_ref()); -1708 } -1709} -1710 -1711fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -1712 // Pick a random duration between 20 and 26 seconds (just under 30s, -1713 // a common UDP NAT timeout on Linux,etc) -1714 let mut rng = rand::rng(); -1715 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); -1716 if initial_delay { -1717 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -1718 time::interval_at(time::Instant::now() + d, d) -1719 } else { -1720 debug!( -1721 "scheduling periodic_stun to run immediately and in {}s", -1722 d.as_secs() -1723 ); -1724 time::interval(d) -1725 } -1726} -1727 -1728/// The discovered direct addresses of this [`MagicSock`]. -1729/// -1730/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. -1731/// They include all locally bound ones as well as those discovered by other mechanisms like -1732/// QAD. -1733#[derive(derive_more::Debug, Clone, Default)] -1734struct DiscoveredDirectAddrs { -1735 /// The last set of discovered direct addresses. -1736 addrs: Watchable<BTreeSet<DirectAddr>>, -1737 -1738 /// The last time the direct addresses were updated, even if there was no change. -1739 /// -1740 /// This is only ever None at startup. -1741 updated_at: Arc<RwLock<Option<Instant>>>, -1742} -1743 -1744impl DiscoveredDirectAddrs { -1745 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -1746 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -1747 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -1748 let updated = self.addrs.set(addrs).is_ok(); -1749 if updated { -1750 event!( -1751 target: "iroh::_events::direct_addrs", -1752 Level::DEBUG, -1753 addrs = ?self.addrs.get(), -1754 ); -1755 } -1756 updated -1757 } -1758 -1759 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { -1760 self.addrs.get().into_iter().map(|da| da.addr) -1761 } -1762 -1763 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { -1764 let my_numbers = self.addrs.get().into_iter().map(|da| da.addr).collect(); -1765 disco::CallMeMaybe { my_numbers } -1766 } -1767} -1768 -1769fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { -1770 match msg { -1771 disco::Message::Ping(_) => { -1772 metrics.sent_disco_ping.inc(); -1773 } -1774 disco::Message::Pong(_) => { -1775 metrics.sent_disco_pong.inc(); -1776 } -1777 disco::Message::CallMeMaybe(_) => { -1778 metrics.sent_disco_call_me_maybe.inc(); -1779 } -1780 } -1781} -1782 -1783/// A *direct address* on which an iroh-endpoint might be contactable. -1784/// -1785/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be -1786/// contacted. These can come from various sources depending on the network topology of the -1787/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. -1788/// -1789/// This is essentially a combination of our local addresses combined with any reflexive -1790/// transport addresses we discovered using QAD. -1791#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -1792pub struct DirectAddr { -1793 /// The address. -1794 pub addr: SocketAddr, -1795 /// The origin of this direct address. -1796 pub typ: DirectAddrType, -1797} -1798 -1799/// The type of direct address. -1800/// -1801/// These are the various sources or origins from which an iroh endpoint might have found a -1802/// possible [`DirectAddr`]. -1803#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -1804pub enum DirectAddrType { -1805 /// Not yet determined.. -1806 Unknown, -1807 /// A locally bound socket address. -1808 Local, -1809 /// Public internet address discovered via QAD. -1810 /// -1811 /// When possible an iroh endpoint will perform QAD to discover which is the address -1812 /// from which it sends data on the public internet. This can be different from locally -1813 /// bound addresses when the endpoint is on a local network which performs NAT or similar. -1814 Qad, -1815 /// An address assigned by the router using port mapping. -1816 /// -1817 /// When possible an iroh endpoint will request a port mapping from the local router to -1818 /// get a publicly routable direct address. -1819 Portmapped, -1820 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -1821 /// -1822 /// It is possible to configure iroh to bound to a specific port and independently -1823 /// configure the router to forward this port to the iroh endpoint. This indicates a -1824 /// situation like this, which still uses QAD to discover the public address. -1825 Qad4LocalPort, -1826} -1827 -1828impl Display for DirectAddrType { -1829 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -1830 match self { -1831 DirectAddrType::Unknown => write!(f, "?"), -1832 DirectAddrType::Local => write!(f, "local"), -1833 DirectAddrType::Qad => write!(f, "qad"), -1834 DirectAddrType::Portmapped => write!(f, "portmap"), -1835 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -1836 } -1837 } -1838} -1839 -1840#[cfg(test)] -1841mod tests { -1842 use std::{sync::Arc, time::Duration}; -1843 -1844 use data_encoding::HEXLOWER; -1845 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; -1846 use n0_error::{Result, StackResultExt, StdResultExt}; -1847 use n0_future::{MergeBounded, StreamExt, time}; -1848 use n0_watcher::Watcher; -1849 use quinn::ServerConfig; -1850 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; -1851 use tokio_util::task::AbortOnDropHandle; -1852 use tracing::{Instrument, error, info, info_span, instrument}; -1853 use tracing_test::traced_test; -1854 -1855 use super::{EndpointIdMappedAddr, Options, endpoint_map::Source, mapped_addrs::MappedAddr}; -1856 use crate::{ -1857 Endpoint, -1858 RelayMode, -1859 SecretKey, -1860 discovery::static_provider::StaticProvider, -1861 dns::DnsResolver, -1862 // endpoint::PathSelection, -1863 magicsock::{Handle, MagicSock, TransportConfig}, -1864 tls::{self, DEFAULT_MAX_TLS_TICKETS}, -1865 }; -1866 -1867 const ALPN: &[u8] = b"n0/test/1"; -1868 -1869 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { -1870 let secret_key = SecretKey::generate(rng); -1871 let server_config = make_default_server_config(&secret_key); -1872 Options { -1873 transports: vec![ -1874 TransportConfig::default_ipv4(), -1875 TransportConfig::default_ipv6(), -1876 ], -1877 secret_key, -1878 proxy_url: None, -1879 dns_resolver: DnsResolver::new(), -1880 server_config, -1881 #[cfg(any(test, feature = "test-utils"))] -1882 insecure_skip_relay_cert_verify: false, -1883 #[cfg(any(test, feature = "test-utils"))] -1884 // path_selection: PathSelection::default(), -1885 discovery_user_data: None, -1886 metrics: Default::default(), -1887 } -1888 } -1889 -1890 /// Generate a server config with no ALPNS and a default transport configuration -1891 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { -1892 let quic_server_config = -1893 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -1894 .make_server_config(vec![], false); -1895 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -1896 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -1897 server_config -1898 } -1899 -1900 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1901 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { -1902 info!("accepting conn"); -1903 let conn = ep.accept().await.expect("no conn"); -1904 -1905 info!("accepting"); -1906 let conn = conn.await.context("accepting")?; -1907 info!("accepting bi"); -1908 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; -1909 -1910 info!("reading"); -1911 let val = recv_bi -1912 .read_to_end(usize::MAX) -1913 .await -1914 .std_context("read to end")?; -1915 -1916 info!("replying"); -1917 for chunk in val.chunks(12) { -1918 send_bi.write_all(chunk).await.std_context("write all")?; -1919 } -1920 -1921 info!("finishing"); -1922 send_bi.finish().std_context("finish")?; -1923 send_bi.stopped().await.std_context("stopped")?; -1924 -1925 let stats = conn.stats(); -1926 info!("stats: {:#?}", stats); -1927 // TODO: ensure panics in this function are reported ok -1928 if matches!(loss, ExpectedLoss::AlmostNone) { -1929 for info in conn.paths().get().iter() { -1930 assert!( -1931 info.stats().lost_packets < 10, -1932 "[receiver] path {:?} should not loose many packets", -1933 info.remote_addr() -1934 ); -1935 } -1936 } -1937 -1938 info!("close"); -1939 conn.close(0u32.into(), b"done"); -1940 info!("wait idle"); -1941 ep.endpoint().wait_idle().await; -1942 -1943 Ok(()) -1944 } -1945 -1946 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] -1947 async fn echo_sender( -1948 ep: Endpoint, -1949 dest_id: EndpointId, -1950 msg: &[u8], -1951 loss: ExpectedLoss, -1952 ) -> Result { -1953 info!("connecting to {}", dest_id.fmt_short()); -1954 let dest = EndpointAddr::new(dest_id); -1955 let conn = ep.connect(dest, ALPN).await?; -1956 -1957 info!("opening bi"); -1958 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; -1959 -1960 info!("writing message"); -1961 send_bi.write_all(msg).await.std_context("write all")?; -1962 -1963 info!("finishing"); -1964 send_bi.finish().std_context("finish")?; -1965 send_bi.stopped().await.std_context("stopped")?; -1966 -1967 info!("reading_to_end"); -1968 let val = recv_bi -1969 .read_to_end(usize::MAX) -1970 .await -1971 .std_context("read to end")?; -1972 assert_eq!( -1973 val, -1974 msg, -1975 "[sender] expected {}, got {}", -1976 HEXLOWER.encode(msg), -1977 HEXLOWER.encode(&val) -1978 ); -1979 -1980 let stats = conn.stats(); -1981 info!("stats: {:#?}", stats); -1982 if matches!(loss, ExpectedLoss::AlmostNone) { -1983 for info in conn.paths().get() { -1984 assert!( -1985 info.stats().lost_packets < 10, -1986 "[sender] path {:?} should not loose many packets", -1987 info.remote_addr() -1988 ); -1989 } -1990 } -1991 -1992 info!("close"); -1993 conn.close(0u32.into(), b"done"); -1994 info!("wait idle"); -1995 ep.endpoint().wait_idle().await; -1996 Ok(()) -1997 } -1998 -1999 #[derive(Debug, Copy, Clone)] -2000 enum ExpectedLoss { -2001 AlmostNone, -2002 YeahSure, -2003 } -2004 -2005 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -2006 async fn run_roundtrip( -2007 sender: Endpoint, -2008 receiver: Endpoint, -2009 payload: &[u8], -2010 loss: ExpectedLoss, -2011 ) { -2012 let send_endpoint_id = sender.id(); -2013 let recv_endpoint_id = receiver.id(); -2014 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); -2015 -2016 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); -2017 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; -2018 let sender_is_err = match sender_res { -2019 Ok(()) => false, -2020 Err(err) => { -2021 eprintln!("[sender] Error:\n{err:#?}"); -2022 true -2023 } -2024 }; -2025 let receiver_is_err = match receiver_task.await { -2026 Ok(Ok(())) => false, -2027 Ok(Err(err)) => { -2028 eprintln!("[receiver] Error:\n{err:#?}"); -2029 true -2030 } -2031 Err(joinerr) => { -2032 if joinerr.is_panic() { -2033 std::panic::resume_unwind(joinerr.into_panic()); -2034 } else { -2035 eprintln!("[receiver] Error:\n{joinerr:#?}"); -2036 } -2037 true -2038 } -2039 }; -2040 if sender_is_err || receiver_is_err { -2041 panic!("Sender or receiver errored"); -2042 } -2043 } -2044 -2045 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. -2046 /// -2047 /// The endpoints do not use a relay server but can connect to each other via local -2048 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if -2049 /// the endpoints rebind. -2050 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { -2051 let discovery = StaticProvider::new(); -2052 let ep1 = Endpoint::builder() -2053 .relay_mode(RelayMode::Disabled) -2054 .alpns(vec![ALPN.to_vec()]) -2055 .discovery(discovery.clone()) -2056 .bind() -2057 .await -2058 .unwrap(); -2059 let ep2 = Endpoint::builder() -2060 .relay_mode(RelayMode::Disabled) -2061 .alpns(vec![ALPN.to_vec()]) -2062 .discovery(discovery.clone()) -2063 .bind() -2064 .await -2065 .unwrap(); -2066 discovery.add_endpoint_info(ep1.addr()); -2067 discovery.add_endpoint_info(ep2.addr()); -2068 -2069 let ep1_addr_stream = ep1.watch_addr().stream(); -2070 let ep2_addr_stream = ep2.watch_addr().stream(); -2071 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); -2072 let task = tokio::spawn(async move { -2073 loop { -2074 while let Some(addr) = addr_stream.next().await { -2075 discovery.add_endpoint_info(addr); -2076 } -2077 } -2078 }); -2079 -2080 (AbortOnDropHandle::new(task), ep1, ep2) -2081 } -2082 -2083 #[tokio::test(flavor = "multi_thread")] -2084 #[traced_test] -2085 async fn test_two_devices_roundtrip_quinn_magic() -> Result { -2086 let (_guard, m1, m2) = endpoint_pair().await; -2087 -2088 for i in 0..5 { -2089 info!("\n-- round {i}"); -2090 run_roundtrip( -2091 m1.clone(), -2092 m2.clone(), -2093 b"hello m1", -2094 ExpectedLoss::AlmostNone, -2095 ) -2096 .await; -2097 run_roundtrip( -2098 m2.clone(), -2099 m1.clone(), -2100 b"hello m2", -2101 ExpectedLoss::AlmostNone, -2102 ) -2103 .await; -2104 -2105 info!("\n-- larger data"); -2106 let mut data = vec![0u8; 10 * 1024]; -2107 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2108 rng.fill_bytes(&mut data); -2109 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; -2110 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; -2111 } -2112 -2113 Ok(()) -2114 } -2115 -2116 #[tokio::test] -2117 #[traced_test] -2118 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { -2119 let (_guard, m1, m2) = endpoint_pair().await; -2120 -2121 println!("Net change"); -2122 m1.magic_sock().force_network_change(true).await; -2123 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -2124 -2125 let _handle = AbortOnDropHandle::new(tokio::spawn({ -2126 let endpoint = m2.clone(); -2127 async move { -2128 while let Some(incoming) = endpoint.accept().await { -2129 println!("Incoming first conn!"); -2130 let conn = incoming.await.anyerr()?; -2131 conn.closed().await; -2132 } -2133 -2134 n0_error::Ok(()) -2135 } -2136 })); -2137 -2138 println!("first conn!"); -2139 let conn = m1.connect(m2.addr(), ALPN).await?; -2140 println!("Closing first conn"); -2141 conn.close(0u32.into(), b"bye lolz"); -2142 conn.closed().await; -2143 println!("Closed first conn"); -2144 -2145 Ok(()) -2146 } -2147 -2148 #[tokio::test(flavor = "multi_thread")] -2149 #[traced_test] -2150 async fn test_two_devices_roundtrip_network_change() -> Result { -2151 time::timeout( -2152 Duration::from_secs(90), -2153 test_two_devices_roundtrip_network_change_impl(), -2154 ) -2155 .await -2156 .std_context("timeout")? -2157 } -2158 -2159 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly -2160 /// with (simulated) network changes. -2161 async fn test_two_devices_roundtrip_network_change_impl() -> Result { -2162 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2163 let (_guard, m1, m2) = endpoint_pair().await; -2164 -2165 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { -2166 let delay = rng.random_range(10..=500); -2167 Duration::from_millis(delay) -2168 }; -2169 let rounds = 5; -2170 -2171 // Regular network changes to m1 only. -2172 let m1_network_change_guard = { -2173 let m1 = m1.clone(); -2174 let mut rng = rng.clone(); -2175 let task = tokio::spawn(async move { -2176 loop { -2177 println!("[m1] network change"); -2178 m1.magic_sock().force_network_change(true).await; -2179 time::sleep(offset(&mut rng)).await; -2180 } -2181 }); -2182 AbortOnDropHandle::new(task) -2183 }; -2184 -2185 for i in 0..rounds { -2186 println!("-- [m1 changes] round {}", i + 1); -2187 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2188 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2189 -2190 println!("-- [m1 changes] larger data"); -2191 let mut data = vec![0u8; 10 * 1024]; -2192 rng.fill_bytes(&mut data); -2193 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2194 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2195 } -2196 -2197 std::mem::drop(m1_network_change_guard); -2198 -2199 // Regular network changes to m2 only. -2200 let m2_network_change_guard = { -2201 let m2 = m2.clone(); -2202 let mut rng = rng.clone(); -2203 let task = tokio::spawn(async move { -2204 loop { -2205 println!("[m2] network change"); -2206 m2.magic_sock().force_network_change(true).await; -2207 time::sleep(offset(&mut rng)).await; -2208 } -2209 }); -2210 AbortOnDropHandle::new(task) -2211 }; -2212 -2213 for i in 0..rounds { -2214 println!("-- [m2 changes] round {}", i + 1); -2215 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2216 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2217 -2218 println!("-- [m2 changes] larger data"); -2219 let mut data = vec![0u8; 10 * 1024]; -2220 rng.fill_bytes(&mut data); -2221 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2222 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2223 } -2224 -2225 std::mem::drop(m2_network_change_guard); -2226 -2227 // Regular network changes to both m1 and m2 only. -2228 let m1_m2_network_change_guard = { -2229 let m1 = m1.clone(); -2230 let m2 = m2.clone(); -2231 let mut rng = rng.clone(); -2232 let task = tokio::spawn(async move { -2233 println!("-- [m1] network change"); -2234 m1.magic_sock().force_network_change(true).await; -2235 println!("-- [m2] network change"); -2236 m2.magic_sock().force_network_change(true).await; -2237 time::sleep(offset(&mut rng)).await; -2238 }); -2239 AbortOnDropHandle::new(task) -2240 }; -2241 -2242 for i in 0..rounds { -2243 println!("-- [m1 & m2 changes] round {}", i + 1); -2244 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2245 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2246 -2247 println!("-- [m1 & m2 changes] larger data"); -2248 let mut data = vec![0u8; 10 * 1024]; -2249 rng.fill_bytes(&mut data); -2250 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2251 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2252 } -2253 -2254 std::mem::drop(m1_m2_network_change_guard); -2255 Ok(()) -2256 } -2257 -2258 #[tokio::test(flavor = "multi_thread")] -2259 #[traced_test] -2260 async fn test_two_devices_setup_teardown() -> Result { -2261 for i in 0..10 { -2262 println!("-- round {i}"); -2263 println!("setting up magic stack"); -2264 let (_guard, m1, m2) = endpoint_pair().await; -2265 -2266 println!("closing endpoints"); -2267 let msock1 = m1.magic_sock(); -2268 let msock2 = m2.magic_sock(); -2269 m1.close().await; -2270 m2.close().await; -2271 -2272 assert!(msock1.msock.is_closed()); -2273 assert!(msock2.msock.is_closed()); -2274 } -2275 Ok(()) -2276 } -2277 -2278 #[tokio::test] -2279 #[traced_test] -2280 async fn test_direct_addresses() { -2281 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2282 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); -2283 -2284 // See if we can get endpoints. -2285 let eps0 = ms.ip_addrs().get(); -2286 println!("{eps0:?}"); -2287 assert!(!eps0.is_empty()); -2288 -2289 // Getting the endpoints again immediately should give the same results. -2290 let eps1 = ms.ip_addrs().get(); -2291 println!("{eps1:?}"); -2292 assert_eq!(eps0, eps1); -2293 } -2294 -2295 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. -2296 /// -2297 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -2298 /// connections using [`ALPN`]. -2299 /// -2300 /// Use [`magicsock_connect`] to establish connections. -2301 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] -2302 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { -2303 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2304 .make_server_config(vec![ALPN.to_vec()], true); -2305 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -2306 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -2307 -2308 let dns_resolver = DnsResolver::new(); -2309 let opts = Options { -2310 transports: vec![ -2311 TransportConfig::default_ipv4(), -2312 TransportConfig::default_ipv6(), -2313 ], -2314 secret_key: secret_key.clone(), -2315 discovery_user_data: None, -2316 dns_resolver, -2317 proxy_url: None, -2318 server_config, -2319 insecure_skip_relay_cert_verify: false, -2320 // path_selection: PathSelection::default(), -2321 metrics: Default::default(), -2322 }; -2323 let msock = MagicSock::spawn(opts).await?; -2324 Ok(msock) -2325 } -2326 -2327 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2328 /// -2329 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2330 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2331 async fn magicsock_connect( -2332 ep: &quinn::Endpoint, -2333 ep_secret_key: SecretKey, -2334 addr: EndpointIdMappedAddr, -2335 endpoint_id: EndpointId, -2336 ) -> Result<quinn::Connection> { -2337 // Endpoint::connect sets this, do the same to have similar behaviour. -2338 let mut transport_config = quinn::TransportConfig::default(); -2339 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -2340 -2341 magicsock_connect_with_transport_config( -2342 ep, -2343 ep_secret_key, -2344 addr, -2345 endpoint_id, -2346 Arc::new(transport_config), -2347 ) -2348 .await -2349 } -2350 -2351 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. -2352 /// -2353 /// This version allows customising the transport config. -2354 /// -2355 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. -2356 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] -2357 async fn magicsock_connect_with_transport_config( -2358 ep: &quinn::Endpoint, -2359 ep_secret_key: SecretKey, -2360 mapped_addr: EndpointIdMappedAddr, -2361 endpoint_id: EndpointId, -2362 transport_config: Arc<quinn::TransportConfig>, -2363 ) -> Result<quinn::Connection> { -2364 let alpns = vec![ALPN.to_vec()]; -2365 let quic_client_config = -2366 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) -2367 .make_client_config(alpns, true); -2368 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -2369 client_config.transport_config(transport_config); -2370 let connect = ep -2371 .connect_with( -2372 client_config, -2373 mapped_addr.private_socket_addr(), -2374 &tls::name::encode(endpoint_id), -2375 ) -2376 .std_context("connect")?; -2377 let connection = connect.await.anyerr()?; -2378 Ok(connection) -2379 } -2380 -2381 #[tokio::test] -2382 #[traced_test] -2383 async fn test_try_send_no_send_addr() { -2384 // Regression test: if there is no send_addr we should keep being able to use the -2385 // Endpoint. -2386 -2387 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2388 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2389 let endpoint_id_2 = secret_key_2.public(); -2390 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); -2391 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); -2392 -2393 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2394 -2395 // Generate an address not present in the EndpointMap. -2396 let bad_addr = EndpointIdMappedAddr::generate(); -2397 -2398 // 500ms is rather fast here. Running this locally it should always be the correct -2399 // timeout. If this is too slow however the test will not become flaky as we are -2400 // expecting the timeout, we might just get the timeout for the wrong reason. But -2401 // this speeds up the test. -2402 let res = tokio::time::timeout( -2403 Duration::from_millis(500), -2404 magicsock_connect( -2405 msock_1.endpoint(), -2406 secret_key_1.clone(), -2407 bad_addr, -2408 endpoint_id_missing_endpoint, -2409 ), -2410 ) -2411 .await; -2412 assert!(res.is_err(), "expecting timeout"); -2413 -2414 // Now check we can still create another connection with this endpoint. -2415 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2416 -2417 // This needs an accept task -2418 let accept_task = tokio::spawn({ -2419 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2420 let incoming = ep.accept().await.std_context("no incoming")?; -2421 let _conn = incoming -2422 .accept() -2423 .std_context("accept")? -2424 .await -2425 .std_context("accepting")?; -2426 -2427 // Keep this connection alive for a while -2428 tokio::time::sleep(Duration::from_secs(10)).await; -2429 info!("accept finished"); -2430 Ok(()) -2431 } -2432 let ep = msock_2.endpoint().clone(); -2433 async move { -2434 if let Err(err) = accept(ep).await { -2435 error!("{err:#}"); -2436 } -2437 } -2438 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) -2439 }); -2440 let _accept_task = AbortOnDropHandle::new(accept_task); -2441 -2442 let addrs = msock_2 -2443 .ip_addrs() -2444 .get() -2445 .into_iter() -2446 .map(|x| TransportAddr::Ip(x.addr)) -2447 .collect(); -2448 let endpoint_addr_2 = EndpointAddr { -2449 id: endpoint_id_2, -2450 addrs, -2451 }; -2452 msock_1 -2453 .add_endpoint_addr( -2454 endpoint_addr_2, -2455 Source::NamedApp { -2456 name: "test".into(), -2457 }, -2458 ) -2459 .await -2460 .unwrap(); -2461 let addr = msock_1.get_endpoint_mapped_addr(endpoint_id_2); -2462 let res = tokio::time::timeout( -2463 Duration::from_secs(10), -2464 magicsock_connect( -2465 msock_1.endpoint(), -2466 secret_key_1.clone(), -2467 addr, -2468 endpoint_id_2, -2469 ), -2470 ) -2471 .await -2472 .expect("timeout while connecting"); -2473 -2474 // aka assert!(res.is_ok()) but with nicer error reporting. -2475 res.unwrap(); -2476 -2477 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -2478 // much internal state for now. -2479 } -2480 -2481 #[tokio::test] -2482 #[traced_test] -2483 async fn test_try_send_no_udp_addr_or_relay_url() { -2484 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -2485 // behaviour of MagicSock::try_send. -2486 -2487 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -2488 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -2489 let endpoint_id_2 = secret_key_2.public(); -2490 -2491 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -2492 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -2493 let ep_2 = msock_2.endpoint().clone(); -2494 -2495 // We need a task to accept the connection. -2496 let accept_task = tokio::spawn({ -2497 async fn accept(ep: quinn::Endpoint) -> Result<()> { -2498 let incoming = ep.accept().await.std_context("no incoming")?; -2499 let conn = incoming -2500 .accept() -2501 .std_context("accept")? -2502 .await -2503 .std_context("connecting")?; -2504 let mut stream = conn.accept_uni().await.std_context("accept uni")?; -2505 stream -2506 .read_to_end(1 << 16) -2507 .await -2508 .std_context("read to end")?; -2509 info!("accept finished"); -2510 Ok(()) -2511 } -2512 async move { -2513 if let Err(err) = accept(ep_2).await { -2514 error!("{err:#}"); -2515 } -2516 } -2517 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) -2518 }); -2519 let _accept_task = AbortOnDropHandle::new(accept_task); -2520 -2521 // Add an empty entry in the EndpointMap of ep_1 -2522 msock_1 -2523 .endpoint_map -2524 .add_endpoint_addr( -2525 EndpointAddr { -2526 id: endpoint_id_2, -2527 addrs: Default::default(), -2528 }, -2529 Source::NamedApp { -2530 name: "test".into(), -2531 }, -2532 ) -2533 .await; -2534 let addr_2 = msock_1.get_endpoint_mapped_addr(endpoint_id_2); -2535 -2536 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -2537 // not take forever. You need to check the log output to verify this is really -2538 // triggering the correct error. -2539 // In test_try_send_no_send_addr() above you may have noticed we used -2540 // tokio::time::timeout() on the connection attempt instead. Here however we want -2541 // Quinn itself to have fully given up on the connection attempt because we will -2542 // later connect to **the same** endpoint. If Quinn did not give up on the connection -2543 // we'd close it on drop, and the retransmits of the close packets would interfere -2544 // with the next handshake, closing it during the handshake. This makes the test a -2545 // little slower though. -2546 let mut transport_config = quinn::TransportConfig::default(); -2547 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -2548 let res = magicsock_connect_with_transport_config( -2549 msock_1.endpoint(), -2550 secret_key_1.clone(), -2551 addr_2, -2552 endpoint_id_2, -2553 Arc::new(transport_config), -2554 ) -2555 .await; -2556 assert!(res.is_err(), "expected timeout"); -2557 info!("first connect timed out as expected"); -2558 -2559 // Provide correct addressing information -2560 msock_1 -2561 .endpoint_map -2562 .add_endpoint_addr( -2563 EndpointAddr { -2564 id: endpoint_id_2, -2565 addrs: msock_2 -2566 .ip_addrs() -2567 .get() -2568 .into_iter() -2569 .map(|x| TransportAddr::Ip(x.addr)) -2570 .collect(), -2571 }, -2572 Source::NamedApp { -2573 name: "test".into(), -2574 }, -2575 ) -2576 .await; -2577 -2578 // We can now connect -2579 tokio::time::timeout(Duration::from_secs(10), async move { -2580 info!("establishing new connection"); -2581 let conn = magicsock_connect( -2582 msock_1.endpoint(), -2583 secret_key_1.clone(), -2584 addr_2, -2585 endpoint_id_2, -2586 ) -2587 .await -2588 .unwrap(); -2589 info!("have connection"); -2590 let mut stream = conn.open_uni().await.unwrap(); -2591 stream.write_all(b"hello").await.unwrap(); -2592 stream.finish().unwrap(); -2593 stream.stopped().await.unwrap(); -2594 info!("finished stream"); -2595 }) -2596 .await -2597 .expect("connection timed out"); -2598 -2599 // TODO: could remove the addresses again, send, add it back and see it recover. -2600 // But we don't have that much private access to the EndpointMap. This will do for now. -2601 } -2602}
    \ No newline at end of file +961 #[allow(irrefutable_let_patterns)] +962 if let TransportConfig::Relay { relay_map } = t { +963 Some(relay_map.clone()) +964 } else { +965 None +966 } +967 }) +968 .next() +969 .unwrap_or_else(RelayMap::empty); +970 +971 let my_relay = Watchable::new(None); +972 let ipv6_reported = Arc::new(AtomicBool::new(false)); +973 +974 let relay_actor_config = RelayActorConfig { +975 my_relay: my_relay.clone(), +976 secret_key: secret_key.clone(), +977 #[cfg(not(wasm_browser))] +978 dns_resolver: dns_resolver.clone(), +979 proxy_url: proxy_url.clone(), +980 ipv6_reported: ipv6_reported.clone(), +981 #[cfg(any(test, feature = "test-utils"))] +982 insecure_skip_relay_cert_verify, +983 metrics: metrics.magicsock.clone(), +984 }; +985 let shutdown_token = CancellationToken::new(); +986 +987 let transports = Transports::bind( +988 &transport_configs, +989 relay_actor_config, +990 &metrics, +991 shutdown_token.child_token(), +992 ) +993 .map_err(|err| e!(CreateHandleError::BindSockets, err))?; +994 +995 #[cfg(not(wasm_browser))] +996 { +997 if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { +998 if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { +999 Some(addr.port()) +1000 } else { +1001 None +1002 } +1003 }) { +1004 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails +1005 match v4_port.try_into() { +1006 Ok(non_zero_port) => { +1007 port_mapper.update_local_port(non_zero_port); +1008 } +1009 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), +1010 } +1011 } +1012 } +1013 +1014 let (actor_sender, actor_receiver) = mpsc::channel(256); +1015 +1016 #[cfg(not(wasm_browser))] +1017 let ipv6 = transports +1018 .ip_bind_addrs() +1019 .into_iter() +1020 .any(|addr| addr.is_ipv6()); +1021 +1022 let direct_addrs = DiscoveredDirectAddrs::default(); +1023 let (disco, disco_receiver) = DiscoState::new(&secret_key); +1024 +1025 let endpoint_map = { +1026 EndpointMap::new( +1027 secret_key.public(), +1028 // #[cfg(any(test, feature = "test-utils"))] +1029 // path_selection, +1030 metrics.magicsock.clone(), +1031 direct_addrs.addrs.watch(), +1032 disco.clone(), +1033 transports.create_sender(), +1034 ) +1035 }; +1036 +1037 let msock = Arc::new(MagicSock { +1038 public_key: secret_key.public(), +1039 closing: AtomicBool::new(false), +1040 closed: AtomicBool::new(false), +1041 disco, +1042 actor_sender: actor_sender.clone(), +1043 ipv6_reported, +1044 endpoint_map, +1045 discovery, +1046 relay_map: relay_map.clone(), +1047 discovery_user_data: RwLock::new(discovery_user_data), +1048 direct_addrs, +1049 net_report: Watchable::new((None, UpdateReason::None)), +1050 #[cfg(not(wasm_browser))] +1051 dns_resolver: dns_resolver.clone(), +1052 metrics: metrics.clone(), +1053 local_addrs_watch: transports.local_addrs_watch(), +1054 #[cfg(not(wasm_browser))] +1055 ip_bind_addrs: transports.ip_bind_addrs(), +1056 }); +1057 +1058 let mut endpoint_config = quinn::EndpointConfig::default(); +1059 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit +1060 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +1061 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +1062 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore +1063 // the packet if grease_quic_bit is set to false. +1064 endpoint_config.grease_quic_bit(false); +1065 +1066 let sender = transports.create_sender(); +1067 let local_addrs_watch = transports.local_addrs_watch(); +1068 let network_change_sender = transports.create_network_change_sender(); +1069 +1070 let endpoint = quinn::Endpoint::new_with_abstract_socket( +1071 endpoint_config, +1072 Some(server_config), +1073 Box::new(MagicTransport::new(msock.clone(), transports)), +1074 #[cfg(not(wasm_browser))] +1075 Arc::new(quinn::TokioRuntime), +1076 #[cfg(wasm_browser)] +1077 Arc::new(crate::web_runtime::WebRuntime), +1078 ) +1079 .map_err(|err| e!(CreateHandleError::CreateQuinnEndpoint, err))?; +1080 +1081 let network_monitor = netmon::Monitor::new() +1082 .await +1083 .map_err(|err| e!(CreateHandleError::CreateNetmonMonitor, err))?; +1084 +1085 let qad_endpoint = endpoint.clone(); +1086 +1087 #[cfg(any(test, feature = "test-utils"))] +1088 let client_config = if insecure_skip_relay_cert_verify { +1089 iroh_relay::client::make_dangerous_client_config() +1090 } else { +1091 default_quic_client_config() +1092 }; +1093 #[cfg(not(any(test, feature = "test-utils")))] +1094 let client_config = default_quic_client_config(); +1095 +1096 let net_report_config = net_report::Options::default(); +1097 #[cfg(not(wasm_browser))] +1098 let net_report_config = net_report_config.quic_config(Some(QuicConfig { +1099 ep: qad_endpoint, +1100 client_config, +1101 ipv4: true, +1102 ipv6, +1103 })); +1104 +1105 #[cfg(any(test, feature = "test-utils"))] +1106 let net_report_config = +1107 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); +1108 +1109 let net_reporter = net_report::Client::new( +1110 #[cfg(not(wasm_browser))] +1111 dns_resolver, +1112 relay_map.clone(), +1113 net_report_config, +1114 metrics.net_report.clone(), +1115 ); +1116 +1117 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +1118 let direct_addr_update_state = DirectAddrUpdateState::new( +1119 msock.clone(), +1120 #[cfg(not(wasm_browser))] +1121 port_mapper, +1122 Arc::new(AsyncMutex::new(net_reporter)), +1123 relay_map, +1124 direct_addr_done_tx, +1125 ); +1126 +1127 let netmon_watcher = network_monitor.interface_state(); +1128 +1129 #[cfg_attr(not(wasm_browser), allow(unused_mut))] +1130 let mut actor = Actor { +1131 msg_receiver: actor_receiver, +1132 msock: msock.clone(), +1133 periodic_re_stun_timer: new_re_stun_timer(false), +1134 network_monitor, +1135 netmon_watcher, +1136 direct_addr_update_state, +1137 network_change_sender, +1138 direct_addr_done_rx, +1139 pending_call_me_maybes: Default::default(), +1140 disco_receiver, +1141 }; +1142 // Initialize addresses +1143 #[cfg(not(wasm_browser))] +1144 actor.update_direct_addresses(None); +1145 +1146 let actor_task = task::spawn( +1147 actor +1148 .run(shutdown_token.child_token(), local_addrs_watch, sender) +1149 .instrument(info_span!("actor")), +1150 ); +1151 +1152 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); +1153 +1154 Ok(Handle { +1155 msock, +1156 actor_task, +1157 endpoint, +1158 shutdown_token, +1159 }) +1160 } +1161 +1162 /// The underlying [`quinn::Endpoint`] +1163 pub fn endpoint(&self) -> &quinn::Endpoint { +1164 &self.endpoint +1165 } +1166 +1167 /// Closes the connection. +1168 /// +1169 /// Only the first close does anything. Any later closes return nil. Polling the socket +1170 /// ([`quinn::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely +1171 /// after this call. +1172 /// +1173 /// [`Poll::Pending`]: std::task::Poll::Pending +1174 #[instrument(skip_all)] +1175 pub(crate) async fn close(&self) { +1176 trace!(me = ?self.public_key, "magicsock closing..."); +1177 // Initiate closing all connections, and refuse future connections. +1178 self.endpoint.close(0u16.into(), b""); +1179 +1180 // In the history of this code, this call had been +1181 // - removed: https://github.com/n0-computer/iroh/pull/1753 +1182 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1183 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1184 // and finally added back in together with this comment. +1185 // So before removing this call, please consider carefully. +1186 // Among other things, this call tries its best to make sure that any queued close frames +1187 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1188 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1189 // This allows the other endpoints for these connections to be notified to release +1190 // their resources, or - depending on the protocol - that all data was received. +1191 // With the current quinn API, this is the only way to ensure protocol code can use +1192 // connection close codes, and close the endpoint properly. +1193 // If this call is skipped, then connections that protocols close just shortly before the +1194 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1195 self.endpoint.wait_idle().await; +1196 +1197 if self.msock.is_closed() { +1198 return; +1199 } +1200 self.msock.closing.store(true, Ordering::Relaxed); +1201 self.shutdown_token.cancel(); +1202 +1203 // MutexGuard is not held across await points +1204 let task = self.actor_task.lock().expect("poisoned").take(); +1205 if let Some(task) = task { +1206 // give the tasks a moment to shutdown cleanly +1207 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1208 if let Err(err) = task.await { +1209 warn!("unexpected error in task shutdown: {:?}", err); +1210 } +1211 }) +1212 .await; +1213 match shutdown_done { +1214 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1215 Err(time::Elapsed { .. }) => { +1216 // Dropping the task will abort itt +1217 warn!("tasks didn't finish in time, aborting"); +1218 } +1219 } +1220 } +1221 +1222 self.msock.closed.store(true, Ordering::SeqCst); +1223 +1224 trace!("magicsock closed"); +1225 } +1226} +1227 +1228fn default_quic_client_config() -> rustls::ClientConfig { +1229 // create a client config for the endpoint to use for QUIC address discovery +1230 let root_store = +1231 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +1232 rustls::client::ClientConfig::builder_with_provider(Arc::new( +1233 rustls::crypto::ring::default_provider(), +1234 )) +1235 .with_safe_default_protocol_versions() +1236 .expect("ring supports these") +1237 .with_root_certificates(root_store) +1238 .with_no_client_auth() +1239} +1240 +1241#[derive(Debug, Clone)] +1242struct DiscoState { +1243 /// The EndpointId/PublikeKey of this endpoint. +1244 this_id: EndpointId, +1245 /// Encryption key for this endpoint. +1246 secret_encryption_key: Arc<crypto_box::SecretKey>, +1247 /// The state for an active DiscoKey. +1248 secrets: Arc<Mutex<HashMap<PublicKey, SharedSecret>>>, +1249 /// Disco (ping) queue +1250 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, +1251} +1252 +1253impl DiscoState { +1254 fn new( +1255 secret_key: &SecretKey, +1256 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { +1257 let this_id = secret_key.public(); +1258 let secret_encryption_key = secret_ed_box(secret_key); +1259 let (disco_sender, disco_receiver) = mpsc::channel(256); +1260 +1261 ( +1262 Self { +1263 this_id, +1264 secret_encryption_key: Arc::new(secret_encryption_key), +1265 secrets: Default::default(), +1266 sender: disco_sender, +1267 }, +1268 disco_receiver, +1269 ) +1270 } +1271 +1272 fn try_send(&self, dst: SendAddr, dst_key: PublicKey, msg: disco::Message) -> bool { +1273 self.sender.try_send((dst, dst_key, msg)).is_ok() +1274 } +1275 +1276 fn encode_and_seal(&self, other_key: PublicKey, msg: &disco::Message) -> Bytes { +1277 let mut seal = msg.as_bytes(); +1278 self.get_secret(other_key, |secret| secret.seal(&mut seal)); +1279 disco::encode_message(&self.this_id, seal).into() +1280 } +1281 +1282 fn unseal_and_decode( +1283 &self, +1284 endpoint_key: PublicKey, +1285 sealed_box: &[u8], +1286 ) -> Result<disco::Message, DiscoBoxError> { +1287 let mut sealed_box = sealed_box.to_vec(); +1288 self.get_secret(endpoint_key, |secret| secret.open(&mut sealed_box)) +1289 .map_err(|source| e!(DiscoBoxError::Open { source }))?; +1290 disco::Message::from_bytes(&sealed_box) +1291 .map_err(|source| e!(DiscoBoxError::Parse { source })) +1292 } +1293 +1294 fn get_secret<F, T>(&self, endpoint_id: PublicKey, cb: F) -> T +1295 where +1296 F: FnOnce(&mut SharedSecret) -> T, +1297 { +1298 let mut inner = self.secrets.lock().expect("poisoned"); +1299 let x = inner.entry(endpoint_id).or_insert_with(|| { +1300 let public_key = public_ed_box(&endpoint_id); +1301 SharedSecret::new(&self.secret_encryption_key, &public_key) +1302 }); +1303 cb(x) +1304 } +1305} +1306 +1307#[allow(missing_docs)] +1308#[stack_error(derive, add_meta)] +1309#[non_exhaustive] +1310enum DiscoBoxError { +1311 #[error("Failed to open crypto box")] +1312 Open { source: DecryptionError }, +1313 #[error("Failed to parse disco message")] +1314 Parse { source: disco::ParseError }, +1315} +1316 +1317#[derive(Debug)] +1318#[allow(clippy::enum_variant_names)] +1319enum ActorMessage { +1320 NetworkChange, +1321 RelayMapChange, +1322 #[cfg(test)] +1323 ForceNetworkChange(bool), +1324} +1325 +1326struct Actor { +1327 msock: Arc<MagicSock>, +1328 msg_receiver: mpsc::Receiver<ActorMessage>, +1329 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. +1330 periodic_re_stun_timer: time::Interval, +1331 +1332 network_monitor: netmon::Monitor, +1333 netmon_watcher: n0_watcher::Direct<netmon::State>, +1334 network_change_sender: transports::NetworkChangeSender, +1335 /// Indicates the direct addr update state. +1336 direct_addr_update_state: DirectAddrUpdateState, +1337 direct_addr_done_rx: mpsc::Receiver<()>, +1338 +1339 /// List of CallMeMaybe disco messages that should be sent out after +1340 /// the next endpoint update completes +1341 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, +1342 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, +1343} +1344 +1345impl Actor { +1346 async fn run( +1347 mut self, +1348 shutdown_token: CancellationToken, +1349 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1350 sender: TransportsSender, +1351 ) { +1352 // Setup network monitoring +1353 let mut current_netmon_state = self.netmon_watcher.get(); +1354 +1355 #[cfg(not(wasm_browser))] +1356 let mut portmap_watcher = self +1357 .direct_addr_update_state +1358 .port_mapper +1359 .watch_external_address(); +1360 +1361 let mut receiver_closed = false; +1362 #[cfg_attr(wasm_browser, allow(unused_mut))] +1363 let mut portmap_watcher_closed = false; +1364 +1365 let mut net_report_watcher = self.msock.net_report.watch(); +1366 +1367 // ensure we are doing an initial publish of our addresses +1368 self.msock.publish_my_addr(); +1369 +1370 // Interval timer to remove closed `EndpointStateActor` handles from the endpoint map. +1371 let mut endpoint_map_gc = time::interval(endpoint_map::ENDPOINT_MAP_GC_INTERVAL); +1372 +1373 loop { +1374 self.msock.metrics.magicsock.actor_tick_main.inc(); +1375 #[cfg(not(wasm_browser))] +1376 let portmap_watcher_changed = portmap_watcher.changed(); +1377 #[cfg(wasm_browser)] +1378 let portmap_watcher_changed = n0_future::future::pending(); +1379 +1380 tokio::select! { +1381 _ = shutdown_token.cancelled() => { +1382 debug!("shutting down"); +1383 return; +1384 } +1385 msg = self.msg_receiver.recv(), if !receiver_closed => { +1386 let Some(msg) = msg else { +1387 trace!("tick: magicsock receiver closed"); +1388 self.msock.metrics.magicsock.actor_tick_other.inc(); +1389 +1390 receiver_closed = true; +1391 continue; +1392 }; +1393 +1394 trace!(?msg, "tick: msg"); +1395 self.msock.metrics.magicsock.actor_tick_msg.inc(); +1396 self.handle_actor_message(msg).await; +1397 } +1398 tick = self.periodic_re_stun_timer.tick() => { +1399 trace!("tick: re_stun {:?}", tick); +1400 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); +1401 self.re_stun(UpdateReason::Periodic); +1402 } +1403 new_addr = watcher.updated() => { +1404 match new_addr { +1405 Ok(addrs) => { +1406 if !addrs.is_empty() { +1407 trace!(?addrs, "local addrs"); +1408 self.msock.publish_my_addr(); +1409 } +1410 } +1411 Err(_) => { +1412 warn!("local addr watcher stopped"); +1413 } +1414 } +1415 } +1416 report = net_report_watcher.updated() => { +1417 match report { +1418 Ok((report, _)) => { +1419 self.handle_net_report_report(report); +1420 #[cfg(not(wasm_browser))] +1421 { +1422 self.periodic_re_stun_timer = new_re_stun_timer(true); +1423 } +1424 } +1425 Err(_) => { +1426 warn!("net report watcher stopped"); +1427 } +1428 } +1429 } +1430 reason = self.direct_addr_done_rx.recv() => { +1431 match reason { +1432 Some(()) => { +1433 // check if a new run needs to be scheduled +1434 let state = self.netmon_watcher.get(); +1435 self.direct_addr_update_state.try_run(state.into()); +1436 } +1437 None => { +1438 warn!("direct addr watcher died"); +1439 } +1440 } +1441 } +1442 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1443 #[cfg(not(wasm_browser))] +1444 { +1445 if change.is_err() { +1446 trace!("tick: portmap watcher closed"); +1447 self.msock.metrics.magicsock.actor_tick_other.inc(); +1448 +1449 portmap_watcher_closed = true; +1450 continue; +1451 } +1452 +1453 trace!("tick: portmap changed"); +1454 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); +1455 let new_external_address = *portmap_watcher.borrow(); +1456 debug!("external address updated: {new_external_address:?}"); +1457 self.re_stun(UpdateReason::PortmapUpdated); +1458 } +1459 #[cfg(wasm_browser)] +1460 let _unused_in_browsers = change; +1461 }, +1462 state = self.netmon_watcher.updated() => { +1463 let Ok(state) = state else { +1464 trace!("tick: link change receiver closed"); +1465 self.msock.metrics.magicsock.actor_tick_other.inc(); +1466 continue; +1467 }; +1468 let is_major = state.is_major_change(&current_netmon_state); +1469 event!( +1470 target: "iroh::_events::link_change", +1471 Level::DEBUG, +1472 ?state, +1473 is_major +1474 ); +1475 current_netmon_state = state; +1476 self.msock.metrics.magicsock.actor_link_change.inc(); +1477 self.handle_network_change(is_major).await; +1478 } +1479 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { +1480 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { +1481 warn!(%dst, endpoint = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); +1482 } +1483 } +1484 _ = endpoint_map_gc.tick() => { +1485 self.msock.endpoint_map.remove_closed_endpoint_state_actors(); +1486 } +1487 } +1488 } +1489 } +1490 +1491 async fn handle_network_change(&mut self, is_major: bool) { +1492 debug!(is_major, "link change detected"); +1493 +1494 if is_major { +1495 if let Err(err) = self.network_change_sender.rebind() { +1496 warn!("failed to rebind transports: {err:?}"); +1497 } +1498 +1499 #[cfg(not(wasm_browser))] +1500 self.msock.dns_resolver.reset().await; +1501 self.re_stun(UpdateReason::LinkChangeMajor); +1502 } else { +1503 self.re_stun(UpdateReason::LinkChangeMinor); +1504 } +1505 } +1506 +1507 fn handle_relay_map_change(&mut self) { +1508 self.re_stun(UpdateReason::RelayMapChange); +1509 } +1510 +1511 fn re_stun(&mut self, why: UpdateReason) { +1512 let state = self.netmon_watcher.get(); +1513 self.direct_addr_update_state +1514 .schedule_run(why, state.into()); +1515 } +1516 +1517 /// Processes an incoming actor message. +1518 /// +1519 /// Returns `true` if it was a shutdown. +1520 async fn handle_actor_message(&mut self, msg: ActorMessage) { +1521 match msg { +1522 ActorMessage::NetworkChange => { +1523 self.network_monitor.network_change().await.ok(); +1524 } +1525 ActorMessage::RelayMapChange => { +1526 self.handle_relay_map_change(); +1527 } +1528 #[cfg(test)] +1529 ActorMessage::ForceNetworkChange(is_major) => { +1530 self.handle_network_change(is_major).await; +1531 } +1532 } +1533 } +1534 +1535 /// Updates the direct addresses of this magic socket. +1536 /// +1537 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of +1538 /// direct addresses from: +1539 /// +1540 /// - The portmapper. +1541 /// - A net_report report. +1542 /// - The local interfaces IP addresses. +1543 #[cfg(not(wasm_browser))] +1544 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +1545 let portmap_watcher = self +1546 .direct_addr_update_state +1547 .port_mapper +1548 .watch_external_address(); +1549 +1550 // We only want to have one DirectAddr for each SocketAddr we have. So we store +1551 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +1552 // DirectAddr from each entry. +1553 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +1554 +1555 // First add PortMapper provided addresses. +1556 let maybe_port_mapped = *portmap_watcher.borrow(); +1557 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +1558 addrs +1559 .entry(portmap_ext) +1560 .or_insert(DirectAddrType::Portmapped); +1561 } +1562 +1563 // Next add STUN addresses from the net_report report. +1564 if let Some(net_report_report) = net_report_report { +1565 if let Some(global_v4) = net_report_report.global_v4 { +1566 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); +1567 +1568 // If they're behind a hard NAT and are using a fixed +1569 // port locally, assume they might've added a static +1570 // port mapping on their router to the same explicit +1571 // port that we are running with. Worst case it's an invalid candidate mapping. +1572 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { +1573 if addr.port() != 0 { +1574 Some(addr.port()) +1575 } else { +1576 None +1577 } +1578 }); +1579 +1580 if let Some(port) = port { +1581 if net_report_report +1582 .mapping_varies_by_dest() +1583 .unwrap_or_default() +1584 { +1585 let mut addr = global_v4; +1586 addr.set_port(port); +1587 addrs +1588 .entry(addr.into()) +1589 .or_insert(DirectAddrType::Qad4LocalPort); +1590 } +1591 } +1592 } +1593 if let Some(global_v6) = net_report_report.global_v6 { +1594 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); +1595 } +1596 } +1597 +1598 self.collect_local_addresses(&mut addrs); +1599 +1600 // Finally create and store store all these direct addresses and send any +1601 // queued call-me-maybe messages. +1602 self.msock.store_direct_addresses( +1603 addrs +1604 .iter() +1605 .map(|(addr, typ)| DirectAddr { +1606 addr: *addr, +1607 typ: *typ, +1608 }) +1609 .collect(), +1610 ); +1611 self.send_queued_call_me_maybes(); +1612 } +1613 +1614 #[cfg(not(wasm_browser))] +1615 fn collect_local_addresses(&mut self, addrs: &mut BTreeMap<SocketAddr, DirectAddrType>) { +1616 // Matches the addresses that have been bound vs the requested ones. +1617 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +1618 .msock +1619 .ip_bind_addrs() +1620 .iter() +1621 .copied() +1622 .zip(self.msock.ip_local_addrs()) +1623 .collect(); +1624 +1625 // Do we listen on any IPv4 unspecified address? +1626 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +1627 if a.is_ipv4() && a.ip().is_unspecified() { +1628 Some(a.port()) +1629 } else { +1630 None +1631 } +1632 }); +1633 // Do we listen on any IPv6 unspecified address? +1634 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +1635 if a.is_ipv6() && a.ip().is_unspecified() { +1636 Some(a.port()) +1637 } else { +1638 None +1639 } +1640 }); +1641 +1642 // If a socket is bound to the unspecified address, create SocketAddrs for +1643 // each local IP address by pairing it with the port the socket is bound on. +1644 if local_addrs +1645 .iter() +1646 .any(|(_, local)| local.ip().is_unspecified()) +1647 { +1648 let LocalAddresses { +1649 regular: mut ips, +1650 loopback, +1651 } = self.netmon_watcher.get().local_addresses; +1652 if ips.is_empty() && addrs.is_empty() { +1653 // Include loopback addresses only if there are no other interfaces +1654 // or public addresses, this allows testing offline. +1655 ips = loopback; +1656 } +1657 +1658 for ip in ips { +1659 let port_if_unspecified = match ip { +1660 IpAddr::V4(_) => has_ipv4_unspecified, +1661 IpAddr::V6(_) => has_ipv6_unspecified, +1662 }; +1663 if let Some(port) = port_if_unspecified { +1664 let addr = SocketAddr::new(ip, port); +1665 addrs.entry(addr).or_insert(DirectAddrType::Local); +1666 } +1667 } +1668 } +1669 +1670 // If a socket is bound to a specific address, add it. +1671 for (bound, local) in local_addrs { +1672 if !bound.ip().is_unspecified() { +1673 addrs.entry(local).or_insert(DirectAddrType::Local); +1674 } +1675 } +1676 } +1677 +1678 fn send_queued_call_me_maybes(&mut self) { +1679 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); +1680 let msg = disco::Message::CallMeMaybe(msg); +1681 // allocate, to minimize locking duration +1682 +1683 for (public_key, url) in self.pending_call_me_maybes.drain() { +1684 if !self +1685 .msock +1686 .disco +1687 .try_send(SendAddr::Relay(url), public_key, msg.clone()) +1688 { +1689 warn!(endpoint = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); +1690 } +1691 } +1692 } +1693 +1694 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +1695 if let Some(ref mut r) = report { +1696 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +1697 if r.preferred_relay.is_none() { +1698 if let Some(my_relay) = self.msock.my_relay() { +1699 r.preferred_relay.replace(my_relay); +1700 } +1701 } +1702 +1703 // Notify all transports +1704 self.network_change_sender.on_network_change(r); +1705 } +1706 +1707 #[cfg(not(wasm_browser))] +1708 self.update_direct_addresses(report.as_ref()); +1709 } +1710} +1711 +1712fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +1713 // Pick a random duration between 20 and 26 seconds (just under 30s, +1714 // a common UDP NAT timeout on Linux,etc) +1715 let mut rng = rand::rng(); +1716 let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26)); +1717 if initial_delay { +1718 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +1719 time::interval_at(time::Instant::now() + d, d) +1720 } else { +1721 debug!( +1722 "scheduling periodic_stun to run immediately and in {}s", +1723 d.as_secs() +1724 ); +1725 time::interval(d) +1726 } +1727} +1728 +1729/// The discovered direct addresses of this [`MagicSock`]. +1730/// +1731/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. +1732/// They include all locally bound ones as well as those discovered by other mechanisms like +1733/// QAD. +1734#[derive(derive_more::Debug, Clone, Default)] +1735struct DiscoveredDirectAddrs { +1736 /// The last set of discovered direct addresses. +1737 addrs: Watchable<BTreeSet<DirectAddr>>, +1738 +1739 /// The last time the direct addresses were updated, even if there was no change. +1740 /// +1741 /// This is only ever None at startup. +1742 updated_at: Arc<RwLock<Option<Instant>>>, +1743} +1744 +1745impl DiscoveredDirectAddrs { +1746 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +1747 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +1748 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +1749 let updated = self.addrs.set(addrs).is_ok(); +1750 if updated { +1751 event!( +1752 target: "iroh::_events::direct_addrs", +1753 Level::DEBUG, +1754 addrs = ?self.addrs.get(), +1755 ); +1756 } +1757 updated +1758 } +1759 +1760 fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> { +1761 self.addrs.get().into_iter().map(|da| da.addr) +1762 } +1763 +1764 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { +1765 let my_numbers = self.addrs.get().into_iter().map(|da| da.addr).collect(); +1766 disco::CallMeMaybe { my_numbers } +1767 } +1768} +1769 +1770fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { +1771 match msg { +1772 disco::Message::Ping(_) => { +1773 metrics.sent_disco_ping.inc(); +1774 } +1775 disco::Message::Pong(_) => { +1776 metrics.sent_disco_pong.inc(); +1777 } +1778 disco::Message::CallMeMaybe(_) => { +1779 metrics.sent_disco_call_me_maybe.inc(); +1780 } +1781 } +1782} +1783 +1784/// A *direct address* on which an iroh-endpoint might be contactable. +1785/// +1786/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be +1787/// contacted. These can come from various sources depending on the network topology of the +1788/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources. +1789/// +1790/// This is essentially a combination of our local addresses combined with any reflexive +1791/// transport addresses we discovered using QAD. +1792#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +1793pub struct DirectAddr { +1794 /// The address. +1795 pub addr: SocketAddr, +1796 /// The origin of this direct address. +1797 pub typ: DirectAddrType, +1798} +1799 +1800/// The type of direct address. +1801/// +1802/// These are the various sources or origins from which an iroh endpoint might have found a +1803/// possible [`DirectAddr`]. +1804#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +1805pub enum DirectAddrType { +1806 /// Not yet determined.. +1807 Unknown, +1808 /// A locally bound socket address. +1809 Local, +1810 /// Public internet address discovered via QAD. +1811 /// +1812 /// When possible an iroh endpoint will perform QAD to discover which is the address +1813 /// from which it sends data on the public internet. This can be different from locally +1814 /// bound addresses when the endpoint is on a local network which performs NAT or similar. +1815 Qad, +1816 /// An address assigned by the router using port mapping. +1817 /// +1818 /// When possible an iroh endpoint will request a port mapping from the local router to +1819 /// get a publicly routable direct address. +1820 Portmapped, +1821 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +1822 /// +1823 /// It is possible to configure iroh to bound to a specific port and independently +1824 /// configure the router to forward this port to the iroh endpoint. This indicates a +1825 /// situation like this, which still uses QAD to discover the public address. +1826 Qad4LocalPort, +1827} +1828 +1829impl Display for DirectAddrType { +1830 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +1831 match self { +1832 DirectAddrType::Unknown => write!(f, "?"), +1833 DirectAddrType::Local => write!(f, "local"), +1834 DirectAddrType::Qad => write!(f, "qad"), +1835 DirectAddrType::Portmapped => write!(f, "portmap"), +1836 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +1837 } +1838 } +1839} +1840 +1841#[cfg(test)] +1842mod tests { +1843 use std::{sync::Arc, time::Duration}; +1844 +1845 use data_encoding::HEXLOWER; +1846 use iroh_base::{EndpointAddr, EndpointId, TransportAddr}; +1847 use n0_error::{Result, StackResultExt, StdResultExt}; +1848 use n0_future::{MergeBounded, StreamExt, time}; +1849 use n0_watcher::Watcher; +1850 use quinn::ServerConfig; +1851 use rand::{CryptoRng, Rng, RngCore, SeedableRng}; +1852 use tokio_util::task::AbortOnDropHandle; +1853 use tracing::{Instrument, error, info, info_span, instrument}; +1854 use tracing_test::traced_test; +1855 +1856 use super::{EndpointIdMappedAddr, Options, endpoint_map::Source, mapped_addrs::MappedAddr}; +1857 use crate::{ +1858 Endpoint, +1859 RelayMode, +1860 SecretKey, +1861 discovery::static_provider::StaticProvider, +1862 dns::DnsResolver, +1863 // endpoint::PathSelection, +1864 magicsock::{Handle, MagicSock, TransportConfig}, +1865 tls::{self, DEFAULT_MAX_TLS_TICKETS}, +1866 }; +1867 +1868 const ALPN: &[u8] = b"n0/test/1"; +1869 +1870 fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options { +1871 let secret_key = SecretKey::generate(rng); +1872 let server_config = make_default_server_config(&secret_key); +1873 Options { +1874 transports: vec![ +1875 TransportConfig::default_ipv4(), +1876 TransportConfig::default_ipv6(), +1877 ], +1878 secret_key, +1879 proxy_url: None, +1880 dns_resolver: DnsResolver::new(), +1881 server_config, +1882 #[cfg(any(test, feature = "test-utils"))] +1883 insecure_skip_relay_cert_verify: false, +1884 #[cfg(any(test, feature = "test-utils"))] +1885 // path_selection: PathSelection::default(), +1886 discovery_user_data: None, +1887 metrics: Default::default(), +1888 } +1889 } +1890 +1891 /// Generate a server config with no ALPNS and a default transport configuration +1892 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { +1893 let quic_server_config = +1894 crate::tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +1895 .make_server_config(vec![], false); +1896 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +1897 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +1898 server_config +1899 } +1900 +1901 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1902 async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result { +1903 info!("accepting conn"); +1904 let conn = ep.accept().await.expect("no conn"); +1905 +1906 info!("accepting"); +1907 let conn = conn.await.context("accepting")?; +1908 info!("accepting bi"); +1909 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?; +1910 +1911 info!("reading"); +1912 let val = recv_bi +1913 .read_to_end(usize::MAX) +1914 .await +1915 .std_context("read to end")?; +1916 +1917 info!("replying"); +1918 for chunk in val.chunks(12) { +1919 send_bi.write_all(chunk).await.std_context("write all")?; +1920 } +1921 +1922 info!("finishing"); +1923 send_bi.finish().std_context("finish")?; +1924 send_bi.stopped().await.std_context("stopped")?; +1925 +1926 let stats = conn.stats(); +1927 info!("stats: {:#?}", stats); +1928 // TODO: ensure panics in this function are reported ok +1929 if matches!(loss, ExpectedLoss::AlmostNone) { +1930 for info in conn.paths().get().iter() { +1931 assert!( +1932 info.stats().lost_packets < 10, +1933 "[receiver] path {:?} should not loose many packets", +1934 info.remote_addr() +1935 ); +1936 } +1937 } +1938 +1939 info!("close"); +1940 conn.close(0u32.into(), b"done"); +1941 info!("wait idle"); +1942 ep.endpoint().wait_idle().await; +1943 +1944 Ok(()) +1945 } +1946 +1947 #[instrument(skip_all, fields(me = %ep.id().fmt_short()))] +1948 async fn echo_sender( +1949 ep: Endpoint, +1950 dest_id: EndpointId, +1951 msg: &[u8], +1952 loss: ExpectedLoss, +1953 ) -> Result { +1954 info!("connecting to {}", dest_id.fmt_short()); +1955 let dest = EndpointAddr::new(dest_id); +1956 let conn = ep.connect(dest, ALPN).await?; +1957 +1958 info!("opening bi"); +1959 let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?; +1960 +1961 info!("writing message"); +1962 send_bi.write_all(msg).await.std_context("write all")?; +1963 +1964 info!("finishing"); +1965 send_bi.finish().std_context("finish")?; +1966 send_bi.stopped().await.std_context("stopped")?; +1967 +1968 info!("reading_to_end"); +1969 let val = recv_bi +1970 .read_to_end(usize::MAX) +1971 .await +1972 .std_context("read to end")?; +1973 assert_eq!( +1974 val, +1975 msg, +1976 "[sender] expected {}, got {}", +1977 HEXLOWER.encode(msg), +1978 HEXLOWER.encode(&val) +1979 ); +1980 +1981 let stats = conn.stats(); +1982 info!("stats: {:#?}", stats); +1983 if matches!(loss, ExpectedLoss::AlmostNone) { +1984 for info in conn.paths().get() { +1985 assert!( +1986 info.stats().lost_packets < 10, +1987 "[sender] path {:?} should not loose many packets", +1988 info.remote_addr() +1989 ); +1990 } +1991 } +1992 +1993 info!("close"); +1994 conn.close(0u32.into(), b"done"); +1995 info!("wait idle"); +1996 ep.endpoint().wait_idle().await; +1997 Ok(()) +1998 } +1999 +2000 #[derive(Debug, Copy, Clone)] +2001 enum ExpectedLoss { +2002 AlmostNone, +2003 YeahSure, +2004 } +2005 +2006 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +2007 async fn run_roundtrip( +2008 sender: Endpoint, +2009 receiver: Endpoint, +2010 payload: &[u8], +2011 loss: ExpectedLoss, +2012 ) { +2013 let send_endpoint_id = sender.id(); +2014 let recv_endpoint_id = receiver.id(); +2015 info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}"); +2016 +2017 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); +2018 let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await; +2019 let sender_is_err = match sender_res { +2020 Ok(()) => false, +2021 Err(err) => { +2022 eprintln!("[sender] Error:\n{err:#?}"); +2023 true +2024 } +2025 }; +2026 let receiver_is_err = match receiver_task.await { +2027 Ok(Ok(())) => false, +2028 Ok(Err(err)) => { +2029 eprintln!("[receiver] Error:\n{err:#?}"); +2030 true +2031 } +2032 Err(joinerr) => { +2033 if joinerr.is_panic() { +2034 std::panic::resume_unwind(joinerr.into_panic()); +2035 } else { +2036 eprintln!("[receiver] Error:\n{joinerr:#?}"); +2037 } +2038 true +2039 } +2040 }; +2041 if sender_is_err || receiver_is_err { +2042 panic!("Sender or receiver errored"); +2043 } +2044 } +2045 +2046 /// Returns a pair of endpoints with a shared [`StaticDiscovery`]. +2047 /// +2048 /// The endpoints do not use a relay server but can connect to each other via local +2049 /// addresses. Dialing by [`EndpointId`] is possible, and the addresses get updated even if +2050 /// the endpoints rebind. +2051 async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) { +2052 let discovery = StaticProvider::new(); +2053 let ep1 = Endpoint::builder() +2054 .relay_mode(RelayMode::Disabled) +2055 .alpns(vec![ALPN.to_vec()]) +2056 .discovery(discovery.clone()) +2057 .bind() +2058 .await +2059 .unwrap(); +2060 let ep2 = Endpoint::builder() +2061 .relay_mode(RelayMode::Disabled) +2062 .alpns(vec![ALPN.to_vec()]) +2063 .discovery(discovery.clone()) +2064 .bind() +2065 .await +2066 .unwrap(); +2067 discovery.add_endpoint_info(ep1.addr()); +2068 discovery.add_endpoint_info(ep2.addr()); +2069 +2070 let ep1_addr_stream = ep1.watch_addr().stream(); +2071 let ep2_addr_stream = ep2.watch_addr().stream(); +2072 let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]); +2073 let task = tokio::spawn(async move { +2074 loop { +2075 while let Some(addr) = addr_stream.next().await { +2076 discovery.add_endpoint_info(addr); +2077 } +2078 } +2079 }); +2080 +2081 (AbortOnDropHandle::new(task), ep1, ep2) +2082 } +2083 +2084 #[tokio::test(flavor = "multi_thread")] +2085 #[traced_test] +2086 async fn test_two_devices_roundtrip_quinn_magic() -> Result { +2087 let (_guard, m1, m2) = endpoint_pair().await; +2088 +2089 for i in 0..5 { +2090 info!("\n-- round {i}"); +2091 run_roundtrip( +2092 m1.clone(), +2093 m2.clone(), +2094 b"hello m1", +2095 ExpectedLoss::AlmostNone, +2096 ) +2097 .await; +2098 run_roundtrip( +2099 m2.clone(), +2100 m1.clone(), +2101 b"hello m2", +2102 ExpectedLoss::AlmostNone, +2103 ) +2104 .await; +2105 +2106 info!("\n-- larger data"); +2107 let mut data = vec![0u8; 10 * 1024]; +2108 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2109 rng.fill_bytes(&mut data); +2110 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; +2111 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; +2112 } +2113 +2114 Ok(()) +2115 } +2116 +2117 #[tokio::test] +2118 #[traced_test] +2119 async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result { +2120 let (_guard, m1, m2) = endpoint_pair().await; +2121 +2122 println!("Net change"); +2123 m1.magic_sock().force_network_change(true).await; +2124 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +2125 +2126 let _handle = AbortOnDropHandle::new(tokio::spawn({ +2127 let endpoint = m2.clone(); +2128 async move { +2129 while let Some(incoming) = endpoint.accept().await { +2130 println!("Incoming first conn!"); +2131 let conn = incoming.await.anyerr()?; +2132 conn.closed().await; +2133 } +2134 +2135 n0_error::Ok(()) +2136 } +2137 })); +2138 +2139 println!("first conn!"); +2140 let conn = m1.connect(m2.addr(), ALPN).await?; +2141 println!("Closing first conn"); +2142 conn.close(0u32.into(), b"bye lolz"); +2143 conn.closed().await; +2144 println!("Closed first conn"); +2145 +2146 Ok(()) +2147 } +2148 +2149 #[tokio::test(flavor = "multi_thread")] +2150 #[traced_test] +2151 async fn test_two_devices_roundtrip_network_change() -> Result { +2152 time::timeout( +2153 Duration::from_secs(90), +2154 test_two_devices_roundtrip_network_change_impl(), +2155 ) +2156 .await +2157 .std_context("timeout")? +2158 } +2159 +2160 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly +2161 /// with (simulated) network changes. +2162 async fn test_two_devices_roundtrip_network_change_impl() -> Result { +2163 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2164 let (_guard, m1, m2) = endpoint_pair().await; +2165 +2166 let offset = |rng: &mut rand_chacha::ChaCha8Rng| { +2167 let delay = rng.random_range(10..=500); +2168 Duration::from_millis(delay) +2169 }; +2170 let rounds = 5; +2171 +2172 // Regular network changes to m1 only. +2173 let m1_network_change_guard = { +2174 let m1 = m1.clone(); +2175 let mut rng = rng.clone(); +2176 let task = tokio::spawn(async move { +2177 loop { +2178 println!("[m1] network change"); +2179 m1.magic_sock().force_network_change(true).await; +2180 time::sleep(offset(&mut rng)).await; +2181 } +2182 }); +2183 AbortOnDropHandle::new(task) +2184 }; +2185 +2186 for i in 0..rounds { +2187 println!("-- [m1 changes] round {}", i + 1); +2188 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2189 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2190 +2191 println!("-- [m1 changes] larger data"); +2192 let mut data = vec![0u8; 10 * 1024]; +2193 rng.fill_bytes(&mut data); +2194 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2195 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2196 } +2197 +2198 std::mem::drop(m1_network_change_guard); +2199 +2200 // Regular network changes to m2 only. +2201 let m2_network_change_guard = { +2202 let m2 = m2.clone(); +2203 let mut rng = rng.clone(); +2204 let task = tokio::spawn(async move { +2205 loop { +2206 println!("[m2] network change"); +2207 m2.magic_sock().force_network_change(true).await; +2208 time::sleep(offset(&mut rng)).await; +2209 } +2210 }); +2211 AbortOnDropHandle::new(task) +2212 }; +2213 +2214 for i in 0..rounds { +2215 println!("-- [m2 changes] round {}", i + 1); +2216 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2217 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2218 +2219 println!("-- [m2 changes] larger data"); +2220 let mut data = vec![0u8; 10 * 1024]; +2221 rng.fill_bytes(&mut data); +2222 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2223 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2224 } +2225 +2226 std::mem::drop(m2_network_change_guard); +2227 +2228 // Regular network changes to both m1 and m2 only. +2229 let m1_m2_network_change_guard = { +2230 let m1 = m1.clone(); +2231 let m2 = m2.clone(); +2232 let mut rng = rng.clone(); +2233 let task = tokio::spawn(async move { +2234 println!("-- [m1] network change"); +2235 m1.magic_sock().force_network_change(true).await; +2236 println!("-- [m2] network change"); +2237 m2.magic_sock().force_network_change(true).await; +2238 time::sleep(offset(&mut rng)).await; +2239 }); +2240 AbortOnDropHandle::new(task) +2241 }; +2242 +2243 for i in 0..rounds { +2244 println!("-- [m1 & m2 changes] round {}", i + 1); +2245 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2246 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2247 +2248 println!("-- [m1 & m2 changes] larger data"); +2249 let mut data = vec![0u8; 10 * 1024]; +2250 rng.fill_bytes(&mut data); +2251 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2252 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2253 } +2254 +2255 std::mem::drop(m1_m2_network_change_guard); +2256 Ok(()) +2257 } +2258 +2259 #[tokio::test(flavor = "multi_thread")] +2260 #[traced_test] +2261 async fn test_two_devices_setup_teardown() -> Result { +2262 for i in 0..10 { +2263 println!("-- round {i}"); +2264 println!("setting up magic stack"); +2265 let (_guard, m1, m2) = endpoint_pair().await; +2266 +2267 println!("closing endpoints"); +2268 let msock1 = m1.magic_sock(); +2269 let msock2 = m2.magic_sock(); +2270 m1.close().await; +2271 m2.close().await; +2272 +2273 assert!(msock1.msock.is_closed()); +2274 assert!(msock2.msock.is_closed()); +2275 } +2276 Ok(()) +2277 } +2278 +2279 #[tokio::test] +2280 #[traced_test] +2281 async fn test_direct_addresses() { +2282 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2283 let ms = Handle::new(default_options(&mut rng)).await.unwrap(); +2284 +2285 // See if we can get endpoints. +2286 let eps0 = ms.ip_addrs().get(); +2287 println!("{eps0:?}"); +2288 assert!(!eps0.is_empty()); +2289 +2290 // Getting the endpoints again immediately should give the same results. +2291 let eps1 = ms.ip_addrs().get(); +2292 println!("{eps1:?}"); +2293 assert_eq!(eps0, eps1); +2294 } +2295 +2296 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. +2297 /// +2298 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +2299 /// connections using [`ALPN`]. +2300 /// +2301 /// Use [`magicsock_connect`] to establish connections. +2302 #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))] +2303 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { +2304 let quic_server_config = tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2305 .make_server_config(vec![ALPN.to_vec()], true); +2306 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +2307 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +2308 +2309 let dns_resolver = DnsResolver::new(); +2310 let opts = Options { +2311 transports: vec![ +2312 TransportConfig::default_ipv4(), +2313 TransportConfig::default_ipv6(), +2314 ], +2315 secret_key: secret_key.clone(), +2316 discovery_user_data: None, +2317 dns_resolver, +2318 proxy_url: None, +2319 server_config, +2320 insecure_skip_relay_cert_verify: false, +2321 // path_selection: PathSelection::default(), +2322 metrics: Default::default(), +2323 }; +2324 let msock = MagicSock::spawn(opts).await?; +2325 Ok(msock) +2326 } +2327 +2328 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2329 /// +2330 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2331 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2332 async fn magicsock_connect( +2333 ep: &quinn::Endpoint, +2334 ep_secret_key: SecretKey, +2335 addr: EndpointIdMappedAddr, +2336 endpoint_id: EndpointId, +2337 ) -> Result<quinn::Connection> { +2338 // Endpoint::connect sets this, do the same to have similar behaviour. +2339 let mut transport_config = quinn::TransportConfig::default(); +2340 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2341 +2342 magicsock_connect_with_transport_config( +2343 ep, +2344 ep_secret_key, +2345 addr, +2346 endpoint_id, +2347 Arc::new(transport_config), +2348 ) +2349 .await +2350 } +2351 +2352 /// Connects from `ep` returned by [`magicsock_ep`] to the `endpoint_id`. +2353 /// +2354 /// This version allows customising the transport config. +2355 /// +2356 /// Uses [`ALPN`], `endpoint_id`, must match `addr`. +2357 #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))] +2358 async fn magicsock_connect_with_transport_config( +2359 ep: &quinn::Endpoint, +2360 ep_secret_key: SecretKey, +2361 mapped_addr: EndpointIdMappedAddr, +2362 endpoint_id: EndpointId, +2363 transport_config: Arc<quinn::TransportConfig>, +2364 ) -> Result<quinn::Connection> { +2365 let alpns = vec![ALPN.to_vec()]; +2366 let quic_client_config = +2367 tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS) +2368 .make_client_config(alpns, true); +2369 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +2370 client_config.transport_config(transport_config); +2371 let connect = ep +2372 .connect_with( +2373 client_config, +2374 mapped_addr.private_socket_addr(), +2375 &tls::name::encode(endpoint_id), +2376 ) +2377 .std_context("connect")?; +2378 let connection = connect.await.anyerr()?; +2379 Ok(connection) +2380 } +2381 +2382 #[tokio::test] +2383 #[traced_test] +2384 async fn test_try_send_no_send_addr() { +2385 // Regression test: if there is no send_addr we should keep being able to use the +2386 // Endpoint. +2387 +2388 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2389 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2390 let endpoint_id_2 = secret_key_2.public(); +2391 let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]); +2392 let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public(); +2393 +2394 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2395 +2396 // Generate an address not present in the EndpointMap. +2397 let bad_addr = EndpointIdMappedAddr::generate(); +2398 +2399 // 500ms is rather fast here. Running this locally it should always be the correct +2400 // timeout. If this is too slow however the test will not become flaky as we are +2401 // expecting the timeout, we might just get the timeout for the wrong reason. But +2402 // this speeds up the test. +2403 let res = tokio::time::timeout( +2404 Duration::from_millis(500), +2405 magicsock_connect( +2406 msock_1.endpoint(), +2407 secret_key_1.clone(), +2408 bad_addr, +2409 endpoint_id_missing_endpoint, +2410 ), +2411 ) +2412 .await; +2413 assert!(res.is_err(), "expecting timeout"); +2414 +2415 // Now check we can still create another connection with this endpoint. +2416 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2417 +2418 // This needs an accept task +2419 let accept_task = tokio::spawn({ +2420 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2421 let incoming = ep.accept().await.std_context("no incoming")?; +2422 let _conn = incoming +2423 .accept() +2424 .std_context("accept")? +2425 .await +2426 .std_context("accepting")?; +2427 +2428 // Keep this connection alive for a while +2429 tokio::time::sleep(Duration::from_secs(10)).await; +2430 info!("accept finished"); +2431 Ok(()) +2432 } +2433 let ep = msock_2.endpoint().clone(); +2434 async move { +2435 if let Err(err) = accept(ep).await { +2436 error!("{err:#}"); +2437 } +2438 } +2439 .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()")) +2440 }); +2441 let _accept_task = AbortOnDropHandle::new(accept_task); +2442 +2443 let addrs = msock_2 +2444 .ip_addrs() +2445 .get() +2446 .into_iter() +2447 .map(|x| TransportAddr::Ip(x.addr)) +2448 .collect(); +2449 let endpoint_addr_2 = EndpointAddr { +2450 id: endpoint_id_2, +2451 addrs, +2452 }; +2453 msock_1 +2454 .add_endpoint_addr( +2455 endpoint_addr_2, +2456 Source::NamedApp { +2457 name: "test".into(), +2458 }, +2459 ) +2460 .await +2461 .unwrap(); +2462 let addr = msock_1.get_endpoint_mapped_addr(endpoint_id_2); +2463 let res = tokio::time::timeout( +2464 Duration::from_secs(10), +2465 magicsock_connect( +2466 msock_1.endpoint(), +2467 secret_key_1.clone(), +2468 addr, +2469 endpoint_id_2, +2470 ), +2471 ) +2472 .await +2473 .expect("timeout while connecting"); +2474 +2475 // aka assert!(res.is_ok()) but with nicer error reporting. +2476 res.unwrap(); +2477 +2478 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +2479 // much internal state for now. +2480 } +2481 +2482 #[tokio::test] +2483 #[traced_test] +2484 async fn test_try_send_no_udp_addr_or_relay_url() { +2485 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +2486 // behaviour of MagicSock::try_send. +2487 +2488 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +2489 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +2490 let endpoint_id_2 = secret_key_2.public(); +2491 +2492 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +2493 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +2494 let ep_2 = msock_2.endpoint().clone(); +2495 +2496 // We need a task to accept the connection. +2497 let accept_task = tokio::spawn({ +2498 async fn accept(ep: quinn::Endpoint) -> Result<()> { +2499 let incoming = ep.accept().await.std_context("no incoming")?; +2500 let conn = incoming +2501 .accept() +2502 .std_context("accept")? +2503 .await +2504 .std_context("connecting")?; +2505 let mut stream = conn.accept_uni().await.std_context("accept uni")?; +2506 stream +2507 .read_to_end(1 << 16) +2508 .await +2509 .std_context("read to end")?; +2510 info!("accept finished"); +2511 Ok(()) +2512 } +2513 async move { +2514 if let Err(err) = accept(ep_2).await { +2515 error!("{err:#}"); +2516 } +2517 } +2518 .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short())) +2519 }); +2520 let _accept_task = AbortOnDropHandle::new(accept_task); +2521 +2522 // Add an empty entry in the EndpointMap of ep_1 +2523 msock_1 +2524 .endpoint_map +2525 .add_endpoint_addr( +2526 EndpointAddr { +2527 id: endpoint_id_2, +2528 addrs: Default::default(), +2529 }, +2530 Source::NamedApp { +2531 name: "test".into(), +2532 }, +2533 ) +2534 .await; +2535 let addr_2 = msock_1.get_endpoint_mapped_addr(endpoint_id_2); +2536 +2537 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +2538 // not take forever. You need to check the log output to verify this is really +2539 // triggering the correct error. +2540 // In test_try_send_no_send_addr() above you may have noticed we used +2541 // tokio::time::timeout() on the connection attempt instead. Here however we want +2542 // Quinn itself to have fully given up on the connection attempt because we will +2543 // later connect to **the same** endpoint. If Quinn did not give up on the connection +2544 // we'd close it on drop, and the retransmits of the close packets would interfere +2545 // with the next handshake, closing it during the handshake. This makes the test a +2546 // little slower though. +2547 let mut transport_config = quinn::TransportConfig::default(); +2548 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +2549 let res = magicsock_connect_with_transport_config( +2550 msock_1.endpoint(), +2551 secret_key_1.clone(), +2552 addr_2, +2553 endpoint_id_2, +2554 Arc::new(transport_config), +2555 ) +2556 .await; +2557 assert!(res.is_err(), "expected timeout"); +2558 info!("first connect timed out as expected"); +2559 +2560 // Provide correct addressing information +2561 msock_1 +2562 .endpoint_map +2563 .add_endpoint_addr( +2564 EndpointAddr { +2565 id: endpoint_id_2, +2566 addrs: msock_2 +2567 .ip_addrs() +2568 .get() +2569 .into_iter() +2570 .map(|x| TransportAddr::Ip(x.addr)) +2571 .collect(), +2572 }, +2573 Source::NamedApp { +2574 name: "test".into(), +2575 }, +2576 ) +2577 .await; +2578 +2579 // We can now connect +2580 tokio::time::timeout(Duration::from_secs(10), async move { +2581 info!("establishing new connection"); +2582 let conn = magicsock_connect( +2583 msock_1.endpoint(), +2584 secret_key_1.clone(), +2585 addr_2, +2586 endpoint_id_2, +2587 ) +2588 .await +2589 .unwrap(); +2590 info!("have connection"); +2591 let mut stream = conn.open_uni().await.unwrap(); +2592 stream.write_all(b"hello").await.unwrap(); +2593 stream.finish().unwrap(); +2594 stream.stopped().await.unwrap(); +2595 info!("finished stream"); +2596 }) +2597 .await +2598 .expect("connection timed out"); +2599 +2600 // TODO: could remove the addresses again, send, add it back and see it recover. +2601 // But we don't have that much private access to the EndpointMap. This will do for now. +2602 } +2603} \ No newline at end of file diff --git a/pr/3651/docs/trait.impl/core/convert/trait.From.js b/pr/3651/docs/trait.impl/core/convert/trait.From.js index cef0c25208..c34fe78235 100644 --- a/pr/3651/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3651/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AddEndpointAddrError> for ConnectWithOptsError"],["impl From<AddEndpointAddrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for AuthenticationError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<GetMappingAddressError> for ConnectWithOptsError"],["impl From<GetMappingAddressError> for AnyError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<AnyError> for AcceptError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<KeyParsingError> for Error"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AddEndpointAddrError> for ConnectWithOptsError"],["impl From<AddEndpointAddrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for AuthenticationError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<GetMappingAddressError> for ConnectWithOptsError"],["impl From<GetMappingAddressError> for AnyError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<AnyError> for AcceptError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<KeyParsingError> for Error"],["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[14207,3090,18835]} \ No newline at end of file +//{"start":57,"fragment_lengths":[14207,3090,19611]} \ No newline at end of file diff --git a/pr/3651/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3651/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 53eb8f19b7..6823ee20ab 100644 --- a/pr/3651/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3651/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[1940]} \ No newline at end of file +//{"start":57,"fragment_lengths":[2062]} \ No newline at end of file