diff --git a/pr/3384/docs/iroh_relay/client/enum.ReceivedMessage.html b/pr/3384/docs/iroh_relay/client/enum.ReceivedMessage.html index 9885f77ffe..1e8f7d759d 100644 --- a/pr/3384/docs/iroh_relay/client/enum.ReceivedMessage.html +++ b/pr/3384/docs/iroh_relay/client/enum.ReceivedMessage.html @@ -1,4 +1,4 @@ -ReceivedMessage in iroh_relay::client - Rust

Enum ReceivedMessage

Source
pub enum ReceivedMessage {
+ReceivedMessage in iroh_relay::client - Rust

Enum ReceivedMessage

Source
pub enum ReceivedMessage {
     ReceivedPacket {
         remote_node_id: NodeId,
         data: Bytes,
@@ -40,7 +40,7 @@ It might be zero. It exists for the server to smear out the reconnects.

before giving up and proceeding with its normal connection failure logic. The interval between retries is undefined for now. A server should not send a TryFor duration more than a few seconds.

-

Trait Implementations§

Source§

impl Clone for ReceivedMessage

Source§

fn clone(&self) -> ReceivedMessage

Returns a copy 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 ReceivedMessage

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 ReceivedMessage

§

impl RefUnwindSafe for ReceivedMessage

§

impl Send for ReceivedMessage

§

impl Sync for ReceivedMessage

§

impl Unpin for ReceivedMessage

§

impl UnwindSafe for ReceivedMessage

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ReceivedMessage

Source§

fn clone(&self) -> ReceivedMessage

Returns a copy 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 ReceivedMessage

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 ReceivedMessage

§

impl RefUnwindSafe for ReceivedMessage

§

impl Send for ReceivedMessage

§

impl Sync for ReceivedMessage

§

impl Unpin for ReceivedMessage

§

impl UnwindSafe for ReceivedMessage

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/3384/docs/iroh_relay/client/enum.RecvError.html b/pr/3384/docs/iroh_relay/client/enum.RecvError.html index 488cd81b8f..d624d302d0 100644 --- a/pr/3384/docs/iroh_relay/client/enum.RecvError.html +++ b/pr/3384/docs/iroh_relay/client/enum.RecvError.html @@ -1,4 +1,4 @@ -RecvError in iroh_relay::client - Rust

Enum RecvError

Source
#[non_exhaustive]
pub enum RecvError { +RecvError in iroh_relay::client - Rust

Enum RecvError

Source
#[non_exhaustive]
pub enum RecvError { Io { source: Error, backtrace: Option<Backtrace>, @@ -30,11 +30,11 @@ span_trace: SpanTrace, }, }
Expand description

Errors when receiving messages from the relay server.

-

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

Io

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ProtocolSend

Fields

§source: SendError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ProtocolRecv

Fields

§source: RecvError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Websocket

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

InvalidProtocolMessageEncoding

Fields

§source: Utf8Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnexpectedFrame

Fields

§frame_type: FrameType
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for RecvError

Source§

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

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

impl Display for RecvError

Source§

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

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

impl Error for RecvError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for RecvError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

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

Io

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ProtocolSend

Fields

§source: SendError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ProtocolRecv

Fields

§source: RecvError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Websocket

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

InvalidProtocolMessageEncoding

Fields

§source: Utf8Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnexpectedFrame

Fields

§frame_type: FrameType
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for RecvError

Source§

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

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

impl Display for RecvError

Source§

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

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

impl Error for RecvError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for RecvError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<RecvError> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for RecvError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<RecvError> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for RecvError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.

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<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3384/docs/iroh_relay/client/enum.SendError.html b/pr/3384/docs/iroh_relay/client/enum.SendError.html index b15dd3517c..1d8e33e6b0 100644 --- a/pr/3384/docs/iroh_relay/client/enum.SendError.html +++ b/pr/3384/docs/iroh_relay/client/enum.SendError.html @@ -1,4 +1,4 @@ -SendError in iroh_relay::client - Rust

Enum SendError

Source
#[non_exhaustive]
pub enum SendError { +SendError in iroh_relay::client - Rust

Enum SendError

Source
#[non_exhaustive]
pub enum SendError { RelayIo { source: Error, backtrace: Option<Backtrace>, @@ -15,11 +15,11 @@ span_trace: SpanTrace, }, }
Expand description

Error for sending messages to the relay server.

-

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

RelayIo

Available on non-wasm_browser only.

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

WebsocketIo

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ExceedsMaxPacketSize

Fields

§size: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for SendError

Source§

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

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

impl Display for SendError

Source§

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

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

impl Error for SendError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for SendError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

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

RelayIo

Available on non-wasm_browser only.

Fields

§source: Error
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

WebsocketIo

Fields

§source: Error
Available on non-wasm_browser only.
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ExceedsMaxPacketSize

Fields

§size: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for SendError

Source§

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

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

impl Display for SendError

Source§

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

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

impl Error for SendError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for SendError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for SendError

Source§

fn from(error: ConnSendError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for SendError

Source§

fn from(error: ConnSendError) -> Self

Converts to this type from the input type.

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<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3384/docs/iroh_relay/client/enum.SendMessage.html b/pr/3384/docs/iroh_relay/client/enum.SendMessage.html index b77e679750..60fd49ffcd 100644 --- a/pr/3384/docs/iroh_relay/client/enum.SendMessage.html +++ b/pr/3384/docs/iroh_relay/client/enum.SendMessage.html @@ -1,4 +1,4 @@ -SendMessage in iroh_relay::client - Rust

Enum SendMessage

Source
pub enum SendMessage {
+SendMessage in iroh_relay::client - Rust

Enum SendMessage

Source
pub enum SendMessage {
     SendPacket(NodeId, Bytes),
     Ping([u8; 8]),
     Pong([u8; 8]),
@@ -6,7 +6,7 @@
 

Variants§

§

SendPacket(NodeId, Bytes)

Send a packet of data to the NodeId.

§

Ping([u8; 8])

Sends a ping message to the connected relay server.

§

Pong([u8; 8])

Sends a pong message to the connected relay server.

-

Trait Implementations§

Source§

impl Debug for SendMessage

Source§

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

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

impl Sink<SendMessage> for Client

Source§

type Error = SendError

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

fn poll_ready( +

Trait Implementations§

Source§

impl Debug for SendMessage

Source§

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

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

impl Sink<SendMessage> for Client

Source§

type Error = SendError

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

fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Attempts to prepare the Sink to receive a value. Read more
Source§

fn start_send( diff --git a/pr/3384/docs/iroh_relay/http/constant.RELAY_PATH.html b/pr/3384/docs/iroh_relay/http/constant.RELAY_PATH.html index d818ea4628..e189a01479 100644 --- a/pr/3384/docs/iroh_relay/http/constant.RELAY_PATH.html +++ b/pr/3384/docs/iroh_relay/http/constant.RELAY_PATH.html @@ -1,3 +1,3 @@ -RELAY_PATH in iroh_relay::http - Rust

Constant RELAY_PATH

Source
pub const RELAY_PATH: &str = "/relay";
Expand description

The HTTP path under which the relay accepts relaying connections +RELAY_PATH in iroh_relay::http - Rust

Constant RELAY_PATH

Source
pub const RELAY_PATH: &str = "/relay";
Expand description

The HTTP path under which the relay accepts relaying connections (over websockets and a custom upgrade protocol).

\ No newline at end of file diff --git a/pr/3384/docs/iroh_relay/http/constant.RELAY_PROBE_PATH.html b/pr/3384/docs/iroh_relay/http/constant.RELAY_PROBE_PATH.html index 88e38667e2..ad4d5270bc 100644 --- a/pr/3384/docs/iroh_relay/http/constant.RELAY_PROBE_PATH.html +++ b/pr/3384/docs/iroh_relay/http/constant.RELAY_PROBE_PATH.html @@ -1,2 +1,2 @@ -RELAY_PROBE_PATH in iroh_relay::http - Rust

Constant RELAY_PROBE_PATH

Source
pub const RELAY_PROBE_PATH: &str = "/ping";
Expand description

The HTTP path under which the relay allows doing latency queries for testing.

+RELAY_PROBE_PATH in iroh_relay::http - Rust

Constant RELAY_PROBE_PATH

Source
pub const RELAY_PROBE_PATH: &str = "/ping";
Expand description

The HTTP path under which the relay allows doing latency queries for testing.

\ No newline at end of file diff --git a/pr/3384/docs/iroh_relay/http/index.html b/pr/3384/docs/iroh_relay/http/index.html index 49d8506c27..0c84c80fab 100644 --- a/pr/3384/docs/iroh_relay/http/index.html +++ b/pr/3384/docs/iroh_relay/http/index.html @@ -1,3 +1,3 @@ -iroh_relay::http - Rust

Module http

Source
Expand description

HTTP-specific constants for the relay server and client.

+iroh_relay::http - Rust

Module http

Source
Expand description

HTTP-specific constants for the relay server and client.

Constants§

RELAY_PATH
The HTTP path under which the relay accepts relaying connections (over websockets and a custom upgrade protocol).
RELAY_PROBE_PATH
The HTTP path under which the relay allows doing latency queries for testing.
\ No newline at end of file diff --git a/pr/3384/docs/iroh_relay/protos/relay/enum.RecvError.html b/pr/3384/docs/iroh_relay/protos/relay/enum.RecvError.html index d10b7e20d7..4d13704006 100644 --- a/pr/3384/docs/iroh_relay/protos/relay/enum.RecvError.html +++ b/pr/3384/docs/iroh_relay/protos/relay/enum.RecvError.html @@ -48,7 +48,7 @@ Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for RecvError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Elapsed> for RecvError

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: SignatureError) -> Self

Converts to this type from the input type.
Source§

impl From<RecvError> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Elapsed> for RecvError

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for RecvError

Source§

fn from(error: SignatureError) -> Self

Converts to this type from the input type.
Source§

impl From<RecvError> for RecvError

Source§

fn from(error: RecvRelayError) -> Self

Converts to this type from the input type.

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<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3384/docs/iroh_relay/protos/relay/enum.SendError.html b/pr/3384/docs/iroh_relay/protos/relay/enum.SendError.html index 370eda8c62..06279906af 100644 --- a/pr/3384/docs/iroh_relay/protos/relay/enum.SendError.html +++ b/pr/3384/docs/iroh_relay/protos/relay/enum.SendError.html @@ -24,7 +24,7 @@ Self: Debug + Display,

Source§

fn description(&self) -> &str

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

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

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

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

Returns the lower-level source of this error, if any. Read more
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 ErrorCompat for SendError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Elapsed> for SendError

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for ConnectError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for RecvError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for SendError

Source§

fn from(error: ConnSendError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for SendError

§

impl !RefUnwindSafe for SendError

§

impl Send for SendError

§

impl Sync for SendError

§

impl Unpin for SendError

§

impl !UnwindSafe for SendError

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Elapsed> for SendError

Source§

fn from(error: Elapsed) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for SendError

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for ConnectError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for RecvError

Source§

fn from(error: SendRelayError) -> Self

Converts to this type from the input type.
Source§

impl From<SendError> for SendError

Source§

fn from(error: ConnSendError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for SendError

§

impl !RefUnwindSafe for SendError

§

impl Send for SendError

§

impl Sync for SendError

§

impl Unpin for SendError

§

impl !UnwindSafe for SendError

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<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3384/docs/src/iroh_relay/client.rs.html b/pr/3384/docs/src/iroh_relay/client.rs.html index 15cd00d4e9..7b3f328c70 100644 --- a/pr/3384/docs/src/iroh_relay/client.rs.html +++ b/pr/3384/docs/src/iroh_relay/client.rs.html @@ -290,7 +290,7 @@ 290 291 /// Establishes a new connection to the relay server. 292 #[cfg(wasm_browser)] -293 async fn connect(&self) -> Result<Client, ConnectError> { +293 pub async fn connect(&self) -> Result<Client, ConnectError> { 294 let mut dial_url = (*self.url).clone(); 295 dial_url.set_path(RELAY_PATH); 296 // The relay URL is exchanged with the http(s) scheme in tickets and similar. diff --git a/pr/3384/docs/src/iroh_relay/client/conn.rs.html b/pr/3384/docs/src/iroh_relay/client/conn.rs.html index 9fe2d43c79..fa24f50be2 100644 --- a/pr/3384/docs/src/iroh_relay/client/conn.rs.html +++ b/pr/3384/docs/src/iroh_relay/client/conn.rs.html @@ -9,347 +9,350 @@ 9 task::{ready, Context, Poll}, 10}; 11 -12use bytes::{Bytes, BytesMut}; -13use iroh_base::{NodeId, SecretKey}; -14use n0_future::{time::Duration, Sink, Stream}; -15use nested_enum_utils::common_fields; -16use snafu::{Backtrace, ResultExt, Snafu}; -17use tracing::debug; -18 -19use super::KeyCache; -20#[cfg(not(wasm_browser))] -21use crate::client::streams::{MaybeTlsStream, ProxyStream}; -22use crate::{ -23 protos::relay::{ -24 ClientInfo, Frame, RecvError as RecvRelayError, SendError as SendRelayError, -25 PROTOCOL_VERSION, -26 }, -27 MAX_PACKET_SIZE, -28}; -29 -30/// Error for sending messages to the relay server. -31#[common_fields({ -32 backtrace: Option<Backtrace>, -33 #[snafu(implicit)] -34 span_trace: n0_snafu::SpanTrace, -35})] -36#[allow(missing_docs)] -37#[derive(Debug, Snafu)] -38#[non_exhaustive] -39pub enum SendError { -40 #[cfg(not(wasm_browser))] -41 #[snafu(transparent)] -42 RelayIo { source: io::Error }, -43 #[snafu(transparent)] -44 WebsocketIo { -45 #[cfg(not(wasm_browser))] -46 source: tokio_websockets::Error, -47 #[cfg(wasm_browser)] -48 source: ws_stream_wasm::WsErr, -49 }, -50 #[snafu(display("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}"))] -51 ExceedsMaxPacketSize { size: usize }, -52} -53 -54/// Errors when receiving messages from the relay server. -55#[common_fields({ -56 backtrace: Option<Backtrace>, -57 #[snafu(implicit)] -58 span_trace: n0_snafu::SpanTrace, -59})] -60#[allow(missing_docs)] -61#[derive(Debug, Snafu)] -62#[non_exhaustive] -63pub enum RecvError { -64 #[snafu(transparent)] -65 Io { source: io::Error }, +12use bytes::Bytes; +13#[cfg(not(wasm_browser))] +14use bytes::BytesMut; +15use iroh_base::{NodeId, SecretKey}; +16use n0_future::{time::Duration, Sink, Stream}; +17use nested_enum_utils::common_fields; +18use snafu::{Backtrace, ResultExt, Snafu}; +19use tracing::{debug, warn}; +20 +21use super::KeyCache; +22#[cfg(not(wasm_browser))] +23use crate::client::streams::{MaybeTlsStream, ProxyStream}; +24use crate::{ +25 protos::relay::{ +26 ClientInfo, Frame, RecvError as RecvRelayError, SendError as SendRelayError, +27 PROTOCOL_VERSION, +28 }, +29 MAX_PACKET_SIZE, +30}; +31 +32/// Error for sending messages to the relay server. +33#[common_fields({ +34 backtrace: Option<Backtrace>, +35 #[snafu(implicit)] +36 span_trace: n0_snafu::SpanTrace, +37})] +38#[allow(missing_docs)] +39#[derive(Debug, Snafu)] +40#[non_exhaustive] +41pub enum SendError { +42 #[cfg(not(wasm_browser))] +43 #[snafu(transparent)] +44 RelayIo { source: io::Error }, +45 #[snafu(transparent)] +46 WebsocketIo { +47 #[cfg(not(wasm_browser))] +48 source: tokio_websockets::Error, +49 #[cfg(wasm_browser)] +50 source: ws_stream_wasm::WsErr, +51 }, +52 #[snafu(display("Exceeds max packet size ({MAX_PACKET_SIZE}): {size}"))] +53 ExceedsMaxPacketSize { size: usize }, +54} +55 +56/// Errors when receiving messages from the relay server. +57#[common_fields({ +58 backtrace: Option<Backtrace>, +59 #[snafu(implicit)] +60 span_trace: n0_snafu::SpanTrace, +61})] +62#[allow(missing_docs)] +63#[derive(Debug, Snafu)] +64#[non_exhaustive] +65pub enum RecvError { 66 #[snafu(transparent)] -67 ProtocolSend { source: SendRelayError }, +67 Io { source: io::Error }, 68 #[snafu(transparent)] -69 ProtocolRecv { source: RecvRelayError }, +69 ProtocolSend { source: SendRelayError }, 70 #[snafu(transparent)] -71 Websocket { -72 #[cfg(not(wasm_browser))] -73 source: tokio_websockets::Error, -74 #[cfg(wasm_browser)] -75 source: ws_stream_wasm::WsErr, -76 }, -77 #[snafu(display("invalid protocol message encoding"))] -78 InvalidProtocolMessageEncoding { source: Utf8Error }, -79 #[snafu(display("Unexpected frame received: {frame_type}"))] -80 UnexpectedFrame { -81 frame_type: crate::protos::relay::FrameType, -82 }, -83} -84 -85/// A connection to a relay server. -86/// -87/// This holds a connection to a relay server. It is: +71 ProtocolRecv { source: RecvRelayError }, +72 #[snafu(transparent)] +73 Websocket { +74 #[cfg(not(wasm_browser))] +75 source: tokio_websockets::Error, +76 #[cfg(wasm_browser)] +77 source: ws_stream_wasm::WsErr, +78 }, +79 #[snafu(display("invalid protocol message encoding"))] +80 InvalidProtocolMessageEncoding { source: Utf8Error }, +81 #[snafu(display("Unexpected frame received: {frame_type}"))] +82 UnexpectedFrame { +83 frame_type: crate::protos::relay::FrameType, +84 }, +85} +86 +87/// A connection to a relay server. 88/// -89/// - A [`Stream`] for [`ReceivedMessage`] to receive from the server. -90/// - A [`Sink`] for [`SendMessage`] to send to the server. -91/// - A [`Sink`] for [`Frame`] to send to the server. -92/// -93/// The [`Frame`] sink is a more internal interface, it allows performing the handshake. -94/// The [`SendMessage`] and [`ReceivedMessage`] are safer wrappers enforcing some protocol -95/// invariants. -96#[derive(derive_more::Debug)] -97pub(crate) struct Conn { -98 #[cfg(not(wasm_browser))] -99 #[debug("tokio_websockets::WebSocketStream")] -100 pub(crate) conn: tokio_websockets::WebSocketStream<MaybeTlsStream<ProxyStream>>, -101 #[cfg(wasm_browser)] -102 #[debug("WsStream")] -103 pub(crate) conn: ws_stream_wasm::WsStream, -104 pub(crate) key_cache: KeyCache, -105} -106 -107impl Conn { -108 /// Constructs a new websocket connection, including the initial server handshake. -109 pub(crate) async fn new( -110 #[cfg(not(wasm_browser))] conn: tokio_websockets::WebSocketStream< -111 MaybeTlsStream<ProxyStream>, -112 >, -113 #[cfg(wasm_browser)] conn: ws_stream_wasm::WsStream, -114 key_cache: KeyCache, -115 secret_key: &SecretKey, -116 ) -> Result<Self, SendRelayError> { -117 let mut conn = Self { conn, key_cache }; -118 -119 // exchange information with the server -120 server_handshake(&mut conn, secret_key).await?; -121 -122 Ok(conn) -123 } -124} -125 -126/// Sends the server handshake message. -127async fn server_handshake(writer: &mut Conn, secret_key: &SecretKey) -> Result<(), SendRelayError> { -128 debug!("server_handshake: started"); -129 let client_info = ClientInfo { -130 version: PROTOCOL_VERSION, -131 }; -132 debug!("server_handshake: sending client_key: {:?}", &client_info); -133 crate::protos::relay::send_client_key(&mut *writer, secret_key, &client_info).await?; -134 -135 debug!("server_handshake: done"); -136 Ok(()) -137} -138 -139impl Stream for Conn { -140 type Item = Result<ReceivedMessage, RecvError>; -141 -142 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { -143 match ready!(Pin::new(&mut self.conn).poll_next(cx)) { -144 #[cfg(not(wasm_browser))] -145 Some(Ok(msg)) => { -146 if msg.is_close() { -147 // Indicate the stream is done when we receive a close message. -148 // Note: We don't have to poll the stream to completion for it to close gracefully. -149 return Poll::Ready(None); -150 } -151 if !msg.is_binary() { -152 tracing::warn!(?msg, "Got websocket message of unsupported type, skipping."); -153 return Poll::Pending; -154 } -155 let frame = Frame::from_bytes(msg.into_payload().into(), &self.key_cache)?; -156 let message = ReceivedMessage::try_from(frame); -157 Poll::Ready(Some(message)) -158 } -159 #[cfg(wasm_browser)] -160 Some(ws_stream_wasm::WsMessage::Binary(vec)) => { -161 let frame = Frame::from_bytes(Bytes::from(vec), &self.key_cache)?; -162 Poll::Ready(Some(ReceivedMessage::try_from(frame))) -163 } -164 #[cfg(wasm_browser)] -165 Some(msg) => { -166 tracing::warn!(?msg, "Got websocket message of unsupported type, skipping."); -167 Poll::Pending -168 } -169 Some(Err(e)) => Poll::Ready(Some(Err(e.into()))), -170 None => Poll::Ready(None), -171 } -172 } -173} -174 -175impl Sink<Frame> for Conn { -176 type Error = SendError; +89/// This holds a connection to a relay server. It is: +90/// +91/// - A [`Stream`] for [`ReceivedMessage`] to receive from the server. +92/// - A [`Sink`] for [`SendMessage`] to send to the server. +93/// - A [`Sink`] for [`Frame`] to send to the server. +94/// +95/// The [`Frame`] sink is a more internal interface, it allows performing the handshake. +96/// The [`SendMessage`] and [`ReceivedMessage`] are safer wrappers enforcing some protocol +97/// invariants. +98#[derive(derive_more::Debug)] +99pub(crate) struct Conn { +100 #[cfg(not(wasm_browser))] +101 #[debug("tokio_websockets::WebSocketStream")] +102 pub(crate) conn: tokio_websockets::WebSocketStream<MaybeTlsStream<ProxyStream>>, +103 #[cfg(wasm_browser)] +104 #[debug("WsStream")] +105 pub(crate) conn: ws_stream_wasm::WsStream, +106 pub(crate) key_cache: KeyCache, +107} +108 +109impl Conn { +110 /// Constructs a new websocket connection, including the initial server handshake. +111 pub(crate) async fn new( +112 #[cfg(not(wasm_browser))] conn: tokio_websockets::WebSocketStream< +113 MaybeTlsStream<ProxyStream>, +114 >, +115 #[cfg(wasm_browser)] conn: ws_stream_wasm::WsStream, +116 key_cache: KeyCache, +117 secret_key: &SecretKey, +118 ) -> Result<Self, SendRelayError> { +119 let mut conn = Self { conn, key_cache }; +120 +121 // exchange information with the server +122 server_handshake(&mut conn, secret_key).await?; +123 +124 Ok(conn) +125 } +126} +127 +128/// Sends the server handshake message. +129async fn server_handshake(writer: &mut Conn, secret_key: &SecretKey) -> Result<(), SendRelayError> { +130 debug!("server_handshake: started"); +131 let client_info = ClientInfo { +132 version: PROTOCOL_VERSION, +133 }; +134 debug!("server_handshake: sending client_key: {:?}", &client_info); +135 crate::protos::relay::send_client_key(&mut *writer, secret_key, &client_info).await?; +136 +137 debug!("server_handshake: done"); +138 Ok(()) +139} +140 +141impl Stream for Conn { +142 type Item = Result<ReceivedMessage, RecvError>; +143 +144 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { +145 match ready!(Pin::new(&mut self.conn).poll_next(cx)) { +146 #[cfg(not(wasm_browser))] +147 Some(Ok(msg)) => { +148 if msg.is_close() { +149 // Indicate the stream is done when we receive a close message. +150 // Note: We don't have to poll the stream to completion for it to close gracefully. +151 return Poll::Ready(None); +152 } +153 if !msg.is_binary() { +154 warn!(?msg, "Got websocket message of unsupported type, skipping."); +155 return Poll::Pending; +156 } +157 let frame = Frame::from_bytes(msg.into_payload().into(), &self.key_cache)?; +158 let message = ReceivedMessage::try_from(frame); +159 Poll::Ready(Some(message)) +160 } +161 #[cfg(not(wasm_browser))] +162 Some(Err(e)) => Poll::Ready(Some(Err(e.into()))), +163 #[cfg(wasm_browser)] +164 Some(ws_stream_wasm::WsMessage::Binary(vec)) => { +165 let frame = Frame::from_bytes(Bytes::from(vec), &self.key_cache)?; +166 Poll::Ready(Some(ReceivedMessage::try_from(frame))) +167 } +168 #[cfg(wasm_browser)] +169 Some(msg) => { +170 warn!(?msg, "Got websocket message of unsupported type, skipping."); +171 Poll::Pending +172 } +173 None => Poll::Ready(None), +174 } +175 } +176} 177 -178 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -179 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) -180 } -181 -182 fn start_send(mut self: Pin<&mut Self>, frame: Frame) -> Result<(), Self::Error> { -183 if let Frame::SendPacket { dst_key: _, packet } = &frame { -184 if packet.len() > MAX_PACKET_SIZE { -185 return Err(ExceedsMaxPacketSizeSnafu { size: packet.len() }.build()); -186 } -187 } -188 -189 #[cfg(not(wasm_browser))] -190 let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( -191 frame.write_to(BytesMut::new()).freeze(), -192 )); -193 #[cfg(wasm_browser)] -194 let msg = ws_stream_wasm::WsMessage::Binary(frame.write_to(Vec::new())); -195 -196 Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) -197 } +178impl Sink<Frame> for Conn { +179 type Error = SendError; +180 +181 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +182 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) +183 } +184 +185 fn start_send(mut self: Pin<&mut Self>, frame: Frame) -> Result<(), Self::Error> { +186 if let Frame::SendPacket { dst_key: _, packet } = &frame { +187 if packet.len() > MAX_PACKET_SIZE { +188 return Err(ExceedsMaxPacketSizeSnafu { size: packet.len() }.build()); +189 } +190 } +191 +192 #[cfg(not(wasm_browser))] +193 let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( +194 frame.write_to(BytesMut::new()).freeze(), +195 )); +196 #[cfg(wasm_browser)] +197 let msg = ws_stream_wasm::WsMessage::Binary(frame.write_to(Vec::new())); 198 -199 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -200 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) -201 } -202 -203 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -204 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) -205 } -206} -207 -208impl Sink<SendMessage> for Conn { -209 type Error = SendError; +199 Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) +200 } +201 +202 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +203 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) +204 } +205 +206 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +207 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) +208 } +209} 210 -211 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -212 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) -213 } -214 -215 fn start_send(mut self: Pin<&mut Self>, item: SendMessage) -> Result<(), Self::Error> { -216 if let SendMessage::SendPacket(_, bytes) = &item { -217 let size = bytes.len(); -218 snafu::ensure!(size <= MAX_PACKET_SIZE, ExceedsMaxPacketSizeSnafu { size }); -219 } -220 -221 let frame = Frame::from(item); -222 #[cfg(not(wasm_browser))] -223 let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( -224 frame.write_to(BytesMut::new()).freeze(), -225 )); -226 #[cfg(wasm_browser)] -227 let msg = ws_stream_wasm::WsMessage::Binary(frame.write_to(Vec::new())); -228 -229 Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) -230 } +211impl Sink<SendMessage> for Conn { +212 type Error = SendError; +213 +214 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +215 Pin::new(&mut self.conn).poll_ready(cx).map_err(Into::into) +216 } +217 +218 fn start_send(mut self: Pin<&mut Self>, item: SendMessage) -> Result<(), Self::Error> { +219 if let SendMessage::SendPacket(_, bytes) = &item { +220 let size = bytes.len(); +221 snafu::ensure!(size <= MAX_PACKET_SIZE, ExceedsMaxPacketSizeSnafu { size }); +222 } +223 +224 let frame = Frame::from(item); +225 #[cfg(not(wasm_browser))] +226 let msg = tokio_websockets::Message::binary(tokio_websockets::Payload::from( +227 frame.write_to(BytesMut::new()).freeze(), +228 )); +229 #[cfg(wasm_browser)] +230 let msg = ws_stream_wasm::WsMessage::Binary(frame.write_to(Vec::new())); 231 -232 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -233 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) -234 } -235 -236 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -237 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) -238 } -239} -240 -241/// The messages received from a framed relay stream. -242/// -243/// This is a type-validated version of the `Frame`s on the `RelayCodec`. -244#[derive(derive_more::Debug, Clone)] -245pub enum ReceivedMessage { -246 /// Represents an incoming packet. -247 ReceivedPacket { -248 /// The [`NodeId`] of the packet sender. -249 remote_node_id: NodeId, -250 /// The received packet bytes. -251 #[debug(skip)] -252 data: Bytes, // TODO: ref -253 }, -254 /// Indicates that the client identified by the underlying public key had previously sent you a -255 /// packet but has now disconnected from the server. -256 NodeGone(NodeId), -257 /// Request from a client or server to reply to the -258 /// other side with a [`ReceivedMessage::Pong`] with the given payload. -259 Ping([u8; 8]), -260 /// Reply to a [`ReceivedMessage::Ping`] from a client or server -261 /// with the payload sent previously in the ping. -262 Pong([u8; 8]), -263 /// A one-way empty message from server to client, just to -264 /// keep the connection alive. It's like a [`ReceivedMessage::Ping`], but doesn't solicit -265 /// a reply from the client. -266 KeepAlive, -267 /// A one-way message from server to client, declaring the connection health state. -268 Health { -269 /// If set, is a description of why the connection is unhealthy. -270 /// -271 /// If `None` means the connection is healthy again. -272 /// -273 /// The default condition is healthy, so the server doesn't broadcast a [`ReceivedMessage::Health`] -274 /// until a problem exists. -275 problem: Option<String>, -276 }, -277 /// A one-way message from server to client, advertising that the server is restarting. -278 ServerRestarting { -279 /// An advisory duration that the client should wait before attempting to reconnect. -280 /// It might be zero. It exists for the server to smear out the reconnects. -281 reconnect_in: Duration, -282 /// An advisory duration for how long the client should attempt to reconnect -283 /// before giving up and proceeding with its normal connection failure logic. The interval -284 /// between retries is undefined for now. A server should not send a TryFor duration more -285 /// than a few seconds. -286 try_for: Duration, -287 }, -288} -289 -290impl TryFrom<Frame> for ReceivedMessage { -291 type Error = RecvError; +232 Pin::new(&mut self.conn).start_send(msg).map_err(Into::into) +233 } +234 +235 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +236 Pin::new(&mut self.conn).poll_flush(cx).map_err(Into::into) +237 } +238 +239 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +240 Pin::new(&mut self.conn).poll_close(cx).map_err(Into::into) +241 } +242} +243 +244/// The messages received from a framed relay stream. +245/// +246/// This is a type-validated version of the `Frame`s on the `RelayCodec`. +247#[derive(derive_more::Debug, Clone)] +248pub enum ReceivedMessage { +249 /// Represents an incoming packet. +250 ReceivedPacket { +251 /// The [`NodeId`] of the packet sender. +252 remote_node_id: NodeId, +253 /// The received packet bytes. +254 #[debug(skip)] +255 data: Bytes, // TODO: ref +256 }, +257 /// Indicates that the client identified by the underlying public key had previously sent you a +258 /// packet but has now disconnected from the server. +259 NodeGone(NodeId), +260 /// Request from a client or server to reply to the +261 /// other side with a [`ReceivedMessage::Pong`] with the given payload. +262 Ping([u8; 8]), +263 /// Reply to a [`ReceivedMessage::Ping`] from a client or server +264 /// with the payload sent previously in the ping. +265 Pong([u8; 8]), +266 /// A one-way empty message from server to client, just to +267 /// keep the connection alive. It's like a [`ReceivedMessage::Ping`], but doesn't solicit +268 /// a reply from the client. +269 KeepAlive, +270 /// A one-way message from server to client, declaring the connection health state. +271 Health { +272 /// If set, is a description of why the connection is unhealthy. +273 /// +274 /// If `None` means the connection is healthy again. +275 /// +276 /// The default condition is healthy, so the server doesn't broadcast a [`ReceivedMessage::Health`] +277 /// until a problem exists. +278 problem: Option<String>, +279 }, +280 /// A one-way message from server to client, advertising that the server is restarting. +281 ServerRestarting { +282 /// An advisory duration that the client should wait before attempting to reconnect. +283 /// It might be zero. It exists for the server to smear out the reconnects. +284 reconnect_in: Duration, +285 /// An advisory duration for how long the client should attempt to reconnect +286 /// before giving up and proceeding with its normal connection failure logic. The interval +287 /// between retries is undefined for now. A server should not send a TryFor duration more +288 /// than a few seconds. +289 try_for: Duration, +290 }, +291} 292 -293 fn try_from(frame: Frame) -> std::result::Result<Self, Self::Error> { -294 match frame { -295 Frame::KeepAlive => { -296 // A one-way keep-alive message that doesn't require an ack. -297 // This predated FrameType::Ping/FrameType::Pong. -298 Ok(ReceivedMessage::KeepAlive) -299 } -300 Frame::NodeGone { node_id } => Ok(ReceivedMessage::NodeGone(node_id)), -301 Frame::RecvPacket { src_key, content } => { -302 let packet = ReceivedMessage::ReceivedPacket { -303 remote_node_id: src_key, -304 data: content, -305 }; -306 Ok(packet) -307 } -308 Frame::Ping { data } => Ok(ReceivedMessage::Ping(data)), -309 Frame::Pong { data } => Ok(ReceivedMessage::Pong(data)), -310 Frame::Health { problem } => { -311 let problem = std::str::from_utf8(&problem) -312 .context(InvalidProtocolMessageEncodingSnafu)? -313 .to_owned(); -314 let problem = Some(problem); -315 Ok(ReceivedMessage::Health { problem }) -316 } -317 Frame::Restarting { -318 reconnect_in, -319 try_for, -320 } => { -321 let reconnect_in = Duration::from_millis(reconnect_in as u64); -322 let try_for = Duration::from_millis(try_for as u64); -323 Ok(ReceivedMessage::ServerRestarting { -324 reconnect_in, -325 try_for, -326 }) -327 } -328 _ => Err(UnexpectedFrameSnafu { -329 frame_type: frame.typ(), +293impl TryFrom<Frame> for ReceivedMessage { +294 type Error = RecvError; +295 +296 fn try_from(frame: Frame) -> std::result::Result<Self, Self::Error> { +297 match frame { +298 Frame::KeepAlive => { +299 // A one-way keep-alive message that doesn't require an ack. +300 // This predated FrameType::Ping/FrameType::Pong. +301 Ok(ReceivedMessage::KeepAlive) +302 } +303 Frame::NodeGone { node_id } => Ok(ReceivedMessage::NodeGone(node_id)), +304 Frame::RecvPacket { src_key, content } => { +305 let packet = ReceivedMessage::ReceivedPacket { +306 remote_node_id: src_key, +307 data: content, +308 }; +309 Ok(packet) +310 } +311 Frame::Ping { data } => Ok(ReceivedMessage::Ping(data)), +312 Frame::Pong { data } => Ok(ReceivedMessage::Pong(data)), +313 Frame::Health { problem } => { +314 let problem = std::str::from_utf8(&problem) +315 .context(InvalidProtocolMessageEncodingSnafu)? +316 .to_owned(); +317 let problem = Some(problem); +318 Ok(ReceivedMessage::Health { problem }) +319 } +320 Frame::Restarting { +321 reconnect_in, +322 try_for, +323 } => { +324 let reconnect_in = Duration::from_millis(reconnect_in as u64); +325 let try_for = Duration::from_millis(try_for as u64); +326 Ok(ReceivedMessage::ServerRestarting { +327 reconnect_in, +328 try_for, +329 }) 330 } -331 .build()), -332 } -333 } -334} -335 -336/// Messages we can send to a relay server. -337#[derive(Debug)] -338pub enum SendMessage { -339 /// Send a packet of data to the [`NodeId`]. -340 SendPacket(NodeId, Bytes), -341 /// Sends a ping message to the connected relay server. -342 Ping([u8; 8]), -343 /// Sends a pong message to the connected relay server. -344 Pong([u8; 8]), -345} -346 -347impl From<SendMessage> for Frame { -348 fn from(source: SendMessage) -> Self { -349 match source { -350 SendMessage::SendPacket(dst_key, packet) => Frame::SendPacket { dst_key, packet }, -351 SendMessage::Ping(data) => Frame::Ping { data }, -352 SendMessage::Pong(data) => Frame::Pong { data }, -353 } -354 } -355}
\ No newline at end of file +331 _ => Err(UnexpectedFrameSnafu { +332 frame_type: frame.typ(), +333 } +334 .build()), +335 } +336 } +337} +338 +339/// Messages we can send to a relay server. +340#[derive(Debug)] +341pub enum SendMessage { +342 /// Send a packet of data to the [`NodeId`]. +343 SendPacket(NodeId, Bytes), +344 /// Sends a ping message to the connected relay server. +345 Ping([u8; 8]), +346 /// Sends a pong message to the connected relay server. +347 Pong([u8; 8]), +348} +349 +350impl From<SendMessage> for Frame { +351 fn from(source: SendMessage) -> Self { +352 match source { +353 SendMessage::SendPacket(dst_key, packet) => Frame::SendPacket { dst_key, packet }, +354 SendMessage::Ping(data) => Frame::Ping { data }, +355 SendMessage::Pong(data) => Frame::Pong { data }, +356 } +357 } +358} \ No newline at end of file diff --git a/pr/3384/docs/src/iroh_relay/http.rs.html b/pr/3384/docs/src/iroh_relay/http.rs.html index 2b77808951..8a2dd50924 100644 --- a/pr/3384/docs/src/iroh_relay/http.rs.html +++ b/pr/3384/docs/src/iroh_relay/http.rs.html @@ -1,11 +1,12 @@ http.rs - source

iroh_relay/
http.rs

1//! HTTP-specific constants for the relay server and client.
 2
-3pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket";
-4#[cfg(feature = "server")] // only used in the server for now
-5pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13";
-6
-7/// The HTTP path under which the relay accepts relaying connections
-8/// (over websockets and a custom upgrade protocol).
-9pub const RELAY_PATH: &str = "/relay";
-10/// The HTTP path under which the relay allows doing latency queries for testing.
-11pub const RELAY_PROBE_PATH: &str = "/ping";
\ No newline at end of file +3#[cfg(not(wasm_browser))] +4pub(crate) const WEBSOCKET_UPGRADE_PROTOCOL: &str = "websocket"; +5#[cfg(feature = "server")] // only used in the server for now +6pub(crate) const SUPPORTED_WEBSOCKET_VERSION: &str = "13"; +7 +8/// The HTTP path under which the relay accepts relaying connections +9/// (over websockets and a custom upgrade protocol). +10pub const RELAY_PATH: &str = "/relay"; +11/// The HTTP path under which the relay allows doing latency queries for testing. +12pub const RELAY_PROBE_PATH: &str = "/ping"; \ No newline at end of file diff --git a/pr/3384/docs/src/iroh_relay/protos/relay.rs.html b/pr/3384/docs/src/iroh_relay/protos/relay.rs.html index 05afb5b993..736562a9b0 100644 --- a/pr/3384/docs/src/iroh_relay/protos/relay.rs.html +++ b/pr/3384/docs/src/iroh_relay/protos/relay.rs.html @@ -262,7 +262,7 @@ 262 } 263} 264 -265/// The frames in the [`RelayCodec`]. +265/// The relay protocol frames. 266#[derive(Debug, Clone, PartialEq, Eq)] 267pub(crate) enum Frame { 268 ClientInfo { diff --git a/pr/3384/docs/src/iroh_relay/server/http_server.rs.html b/pr/3384/docs/src/iroh_relay/server/http_server.rs.html index 033c9a8ba8..59430ac25e 100644 --- a/pr/3384/docs/src/iroh_relay/server/http_server.rs.html +++ b/pr/3384/docs/src/iroh_relay/server/http_server.rs.html @@ -24,1265 +24,1264 @@ 24use super::{clients::Clients, streams::StreamError, AccessConfig, SpawnError}; 25use crate::{ 26 defaults::{timeouts::SERVER_WRITE_TIMEOUT, DEFAULT_KEY_CACHE_CAPACITY}, -27 http::{RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION}, +27 http::{RELAY_PATH, SUPPORTED_WEBSOCKET_VERSION, WEBSOCKET_UPGRADE_PROTOCOL}, 28 protos::relay::{ 29 recv_client_key, Frame, MAX_FRAME_SIZE, PER_CLIENT_SEND_QUEUE_DEPTH, PROTOCOL_VERSION, 30 }, 31 server::{ 32 client::Config, 33 metrics::Metrics, -34 streams::{MaybeTlsStream, RelayedStream}, +34 streams::{MaybeTlsStream, RateLimited, RelayedStream}, 35 BindTcpListenerSnafu, ClientRateLimit, NoLocalAddrSnafu, 36 }, 37 KeyCache, 38}; -39use crate::{http::WEBSOCKET_UPGRADE_PROTOCOL, server::streams::RateLimited}; -40 -41type BytesBody = http_body_util::Full<hyper::body::Bytes>; -42type HyperError = Box<dyn std::error::Error + Send + Sync>; -43type HyperResult<T> = std::result::Result<T, HyperError>; -44type HyperHandler = Box< -45 dyn Fn(Request<Incoming>, ResponseBuilder) -> HyperResult<Response<BytesBody>> -46 + Send -47 + Sync -48 + 'static, -49>; -50 -51/// WebSocket GUID needed for accepting websocket connections, see RFC 6455 (<https://www.rfc-editor.org/rfc/rfc6455>) section 1.3 -52const SEC_WEBSOCKET_ACCEPT_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; -53 -54/// Derives the accept key for WebSocket handshake according to RFC 6455. -55/// Takes the client's Sec-WebSocket-Key value and returns the calculated accept key. -56fn derive_accept_key(client_key: &HeaderValue) -> String { -57 use sha1::Digest; -58 -59 let mut sha1 = sha1::Sha1::new(); -60 sha1.update(client_key.as_bytes()); -61 sha1.update(SEC_WEBSOCKET_ACCEPT_GUID); -62 data_encoding::BASE64.encode(&sha1.finalize()) -63} -64 -65/// Creates a new [`BytesBody`] with no content. -66fn body_empty() -> BytesBody { -67 http_body_util::Full::new(hyper::body::Bytes::new()) -68} -69 -70/// Creates a new [`BytesBody`] with given content. -71fn body_full(content: impl Into<hyper::body::Bytes>) -> BytesBody { -72 http_body_util::Full::new(content.into()) -73} -74 -75#[allow(clippy::result_large_err)] -76fn downcast_upgrade(upgraded: Upgraded) -> Result<(MaybeTlsStream, Bytes), ConnectionHandlerError> { -77 match upgraded.downcast::<hyper_util::rt::TokioIo<MaybeTlsStream>>() { -78 Ok(parts) => Ok((parts.io.into_inner(), parts.read_buf)), -79 Err(_) => Err(DowncastUpgradeSnafu.build()), -80 } -81} -82 -83/// The Relay HTTP server. -84/// -85/// A running HTTP server serving the relay endpoint and optionally a number of additional -86/// HTTP services added with [`ServerBuilder::request_handler`]. If configured using -87/// [`ServerBuilder::tls_config`] the server will handle TLS as well. -88/// -89/// Created using [`ServerBuilder::spawn`]. -90#[derive(Debug)] -91pub(super) struct Server { -92 addr: SocketAddr, -93 http_server_task: AbortOnDropHandle<()>, -94 cancel_server_loop: CancellationToken, -95} -96 -97impl Server { -98 /// Returns a handle for this server. -99 /// -100 /// The server runs in the background as several async tasks. This allows controlling -101 /// the server, in particular it allows gracefully shutting down the server. -102 pub(super) fn handle(&self) -> ServerHandle { -103 ServerHandle { -104 cancel_token: self.cancel_server_loop.clone(), -105 } -106 } -107 -108 /// Closes the underlying relay server and the HTTP(S) server tasks. -109 pub(super) fn shutdown(&self) { -110 self.cancel_server_loop.cancel(); -111 } -112 -113 /// Returns the [`AbortOnDropHandle`] for the supervisor task managing the server. -114 /// -115 /// This is the root of all the tasks for the server. Aborting it will abort all the -116 /// other tasks for the server. Awaiting it will complete when all the server tasks are -117 /// completed. -118 pub(super) fn task_handle(&mut self) -> &mut AbortOnDropHandle<()> { -119 &mut self.http_server_task -120 } -121 -122 /// Returns the local address of this server. -123 pub(super) fn addr(&self) -> SocketAddr { -124 self.addr -125 } -126} -127 -128/// A handle for the [`Server`]. -129/// -130/// This does not allow access to the task but can communicate with it. -131#[derive(Debug, Clone)] -132pub(super) struct ServerHandle { -133 cancel_token: CancellationToken, -134} -135 -136impl ServerHandle { -137 /// Gracefully shut down the server. -138 pub(super) fn shutdown(&self) { -139 self.cancel_token.cancel() -140 } -141} -142 -143/// Configuration to use for the TLS connection -144#[derive(Debug, Clone)] -145pub(super) struct TlsConfig { -146 /// The server config -147 pub(super) config: Arc<rustls::ServerConfig>, -148 /// The kind -149 pub(super) acceptor: TlsAcceptor, -150} -151 -152/// Errors when attempting to upgrade and -153#[common_fields({ -154 backtrace: Option<Backtrace>, -155})] -156#[allow(missing_docs)] -157#[derive(Debug, Snafu)] -158#[non_exhaustive] -159pub enum ServeConnectionError { -160 #[snafu(display("TLS[acme] handshake"))] -161 Handshake { -162 source: std::io::Error, -163 #[snafu(implicit)] -164 span_trace: n0_snafu::SpanTrace, -165 }, -166 #[snafu(display("TLS[acme] serve connection"))] -167 ServeConnection { -168 source: hyper::Error, -169 #[snafu(implicit)] -170 span_trace: n0_snafu::SpanTrace, -171 }, -172 #[snafu(display("TLS[manual] timeout"))] -173 Timeout { -174 source: Elapsed, -175 #[snafu(implicit)] -176 span_trace: n0_snafu::SpanTrace, -177 }, -178 #[snafu(display("TLS[manual] accept"))] -179 ManualAccept { -180 source: std::io::Error, -181 #[snafu(implicit)] -182 span_trace: n0_snafu::SpanTrace, -183 }, -184 #[snafu(display("TLS[acme] accept"))] -185 LetsEncryptAccept { -186 source: std::io::Error, -187 #[snafu(implicit)] -188 span_trace: n0_snafu::SpanTrace, -189 }, -190 #[snafu(display("HTTPS connection"))] -191 Https { -192 source: hyper::Error, -193 #[snafu(implicit)] -194 span_trace: n0_snafu::SpanTrace, -195 }, -196 #[snafu(display("HTTP connection"))] -197 Http { -198 source: hyper::Error, -199 #[snafu(implicit)] -200 span_trace: n0_snafu::SpanTrace, -201 }, -202} -203 -204/// Server accept errors. -205#[common_fields({ -206 backtrace: Option<Backtrace>, -207})] -208#[allow(missing_docs)] -209#[derive(Debug, Snafu)] -210#[non_exhaustive] -211pub enum AcceptError { -212 #[snafu(display("Unable to receive client information"))] -213 RecvClientKey { -214 #[allow(clippy::result_large_err)] -215 source: StreamError, -216 #[snafu(implicit)] -217 span_trace: n0_snafu::SpanTrace, -218 }, -219 #[snafu(display("Unexpected client version {version}, expected {expected_version}"))] -220 UnexpectedClientVersion { -221 version: usize, -222 expected_version: usize, -223 #[snafu(implicit)] -224 span_trace: n0_snafu::SpanTrace, -225 }, -226 #[snafu(transparent)] -227 Io { source: std::io::Error }, -228 #[snafu(display("Client not authenticated: {key:?}"))] -229 ClientNotAuthenticated { -230 key: PublicKey, -231 #[snafu(implicit)] -232 span_trace: n0_snafu::SpanTrace, -233 }, -234} -235 -236/// Server connection errors, includes errors that can happen on `accept`. -237#[common_fields({ -238 backtrace: Option<Backtrace>, -239})] -240#[allow(missing_docs)] -241#[derive(Debug, Snafu)] -242#[non_exhaustive] -243pub enum ConnectionHandlerError { -244 #[snafu(transparent)] -245 Accept { source: AcceptError }, -246 #[snafu(display("Could not downcast the upgraded connection to MaybeTlsStream"))] -247 DowncastUpgrade { -248 #[snafu(implicit)] -249 span_trace: n0_snafu::SpanTrace, -250 }, -251 #[snafu(display("Cannot deal with buffered data yet: {buf:?}"))] -252 BufferNotEmpty { -253 buf: Bytes, -254 #[snafu(implicit)] -255 span_trace: n0_snafu::SpanTrace, -256 }, -257} -258 -259/// Builder for the Relay HTTP Server. -260/// -261/// Defaults to handling relay requests on the "/relay" (and "/derp" for backwards compatibility) endpoint. -262/// Other HTTP endpoints can be added using [`ServerBuilder::request_handler`]. -263#[derive(derive_more::Debug)] -264pub(super) struct ServerBuilder { -265 /// The ip + port combination for this server. -266 addr: SocketAddr, -267 /// Optional tls configuration/TlsAcceptor combination. -268 /// -269 /// When `None`, the server will serve HTTP, otherwise it will serve HTTPS. -270 tls_config: Option<TlsConfig>, -271 /// A map of request handlers to routes. -272 /// -273 /// Used when certain routes in your server should be made available at the same port as -274 /// the relay server, and so must be handled along side requests to the relay endpoint. -275 handlers: Handlers, -276 /// Headers to use for HTTP responses. -277 headers: HeaderMap, -278 /// Rate-limiting configuration for an individual client connection. -279 /// -280 /// Rate-limiting is enforced on received traffic from individual clients. This -281 /// configuration applies to a single client connection. -282 client_rx_ratelimit: Option<ClientRateLimit>, -283 /// The capacity of the key cache. -284 key_cache_capacity: usize, -285 /// Access config for nodes. -286 access: AccessConfig, -287 metrics: Option<Arc<Metrics>>, -288} -289 -290impl ServerBuilder { -291 /// Creates a new [ServerBuilder]. -292 pub(super) fn new(addr: SocketAddr) -> Self { -293 Self { -294 addr, -295 tls_config: None, -296 handlers: Default::default(), -297 headers: HeaderMap::new(), -298 client_rx_ratelimit: None, -299 key_cache_capacity: DEFAULT_KEY_CACHE_CAPACITY, -300 access: AccessConfig::Everyone, -301 metrics: None, -302 } -303 } -304 -305 /// Sets the metrics collector. -306 pub(super) fn metrics(mut self, metrics: Arc<Metrics>) -> Self { -307 self.metrics = Some(metrics); -308 self -309 } -310 -311 /// Set the access configuration. -312 pub(super) fn access(mut self, access: AccessConfig) -> Self { -313 self.access = access; -314 self -315 } -316 -317 /// Serves all requests content using TLS. -318 pub(super) fn tls_config(mut self, config: Option<TlsConfig>) -> Self { -319 self.tls_config = config; -320 self -321 } -322 -323 /// Sets the per-client rate-limit configuration for incoming data. -324 /// -325 /// On each client connection the incoming data is rate-limited. By default -326 /// no rate limit is enforced. -327 pub(super) fn client_rx_ratelimit(mut self, config: ClientRateLimit) -> Self { -328 self.client_rx_ratelimit = Some(config); -329 self -330 } -331 -332 /// Adds a custom handler for a specific Method & URI. -333 pub(super) fn request_handler( -334 mut self, -335 method: Method, -336 uri_path: &'static str, -337 handler: HyperHandler, -338 ) -> Self { -339 self.handlers.insert((method, uri_path), handler); -340 self -341 } -342 -343 /// Adds HTTP headers to responses. -344 pub(super) fn headers(mut self, headers: HeaderMap) -> Self { -345 for (k, v) in headers.iter() { -346 self.headers.insert(k.clone(), v.clone()); -347 } -348 self -349 } -350 -351 /// Set the capacity of the cache for public keys. -352 pub fn key_cache_capacity(mut self, capacity: usize) -> Self { -353 self.key_cache_capacity = capacity; -354 self -355 } -356 -357 /// Builds and spawns an HTTP(S) Relay Server. -358 pub(super) async fn spawn(self) -> Result<Server, SpawnError> { -359 use snafu::ResultExt; -360 -361 let cancel_token = CancellationToken::new(); -362 -363 let service = RelayService::new( -364 self.handlers, -365 self.headers, -366 self.client_rx_ratelimit, -367 KeyCache::new(self.key_cache_capacity), -368 self.access, -369 self.metrics.unwrap_or_default(), -370 ); -371 -372 let addr = self.addr; -373 let tls_config = self.tls_config; -374 -375 // Bind a TCP listener on `addr` and handles content using HTTPS. -376 -377 let listener = TcpListener::bind(&addr) -378 .await -379 .map_err(|_| BindTcpListenerSnafu { addr }.build())?; -380 -381 let addr = listener.local_addr().context(NoLocalAddrSnafu)?; -382 let http_str = tls_config.as_ref().map_or("HTTP/WS", |_| "HTTPS/WSS"); -383 info!("[{http_str}] relay: serving on {addr}"); -384 -385 let cancel = cancel_token.clone(); -386 let task = tokio::task::spawn( -387 async move { -388 // create a join set to track all our connection tasks -389 let mut set = tokio::task::JoinSet::new(); -390 loop { -391 tokio::select! { -392 biased; -393 _ = cancel.cancelled() => { -394 break; -395 } -396 Some(res) = set.join_next() => { -397 if let Err(err) = res { -398 if err.is_panic() { -399 panic!("task panicked: {err:#?}"); -400 } -401 } -402 } -403 res = listener.accept() => match res { -404 Ok((stream, peer_addr)) => { -405 debug!("connection opened from {peer_addr}"); -406 let tls_config = tls_config.clone(); -407 let service = service.clone(); -408 // spawn a task to handle the connection -409 set.spawn(async move { -410 service -411 .handle_connection(stream, tls_config) -412 .await -413 }.instrument(info_span!("conn", peer = %peer_addr))); -414 } -415 Err(err) => { -416 error!("failed to accept connection: {err}"); -417 } -418 } -419 } -420 } -421 service.shutdown().await; -422 set.shutdown().await; -423 debug!("server has been shutdown."); -424 } -425 .instrument(info_span!("relay-http-serve")), -426 ); -427 -428 Ok(Server { -429 addr, -430 http_server_task: AbortOnDropHandle::new(task), -431 cancel_server_loop: cancel_token, -432 }) -433 } -434} -435 -436/// The hyper Service that serves the actual relay endpoints. -437#[derive(Clone, Debug)] -438struct RelayService(Arc<Inner>); -439 -440#[derive(Debug)] -441struct Inner { -442 handlers: Handlers, -443 headers: HeaderMap, -444 clients: Clients, -445 write_timeout: Duration, -446 rate_limit: Option<ClientRateLimit>, -447 key_cache: KeyCache, -448 access: AccessConfig, -449 metrics: Arc<Metrics>, -450} -451 -452impl RelayService { -453 /// Upgrades the HTTP connection to the relay protocol, runs relay client. -454 fn call_client_conn( -455 &self, -456 mut req: Request<Incoming>, -457 ) -> Pin<Box<dyn Future<Output = Result<Response<BytesBody>, hyper::Error>> + Send>> { -458 // TODO: soooo much cloning. See if there is an alternative -459 let this = self.clone(); -460 let mut builder = Response::builder(); -461 for (key, value) in self.0.headers.iter() { -462 builder = builder.header(key, value); -463 } -464 -465 async move { -466 { -467 // Send a 400 to any request that doesn't have an `Upgrade` header. -468 if req.headers().get(UPGRADE) -469 != Some(&HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL)) -470 { -471 return Ok(builder -472 .status(StatusCode::BAD_REQUEST) -473 .body(body_empty()) -474 .expect("valid body")); -475 }; -476 -477 let Some(key) = req.headers().get("Sec-WebSocket-Key").cloned() else { -478 warn!("missing header Sec-WebSocket-Key for websocket relay protocol"); -479 return Ok(builder -480 .status(StatusCode::BAD_REQUEST) -481 .body(body_empty()) -482 .expect("valid body")); -483 }; -484 -485 let Some(version) = req.headers().get("Sec-WebSocket-Version").cloned() else { -486 warn!("missing header Sec-WebSocket-Version for websocket relay protocol"); -487 return Ok(builder -488 .status(StatusCode::BAD_REQUEST) -489 .body(body_empty()) -490 .expect("valid body")); -491 }; -492 -493 if version.as_bytes() != SUPPORTED_WEBSOCKET_VERSION.as_bytes() { -494 warn!("invalid header Sec-WebSocket-Version: {:?}", version); -495 return Ok(builder -496 .status(StatusCode::BAD_REQUEST) -497 // It's convention to send back the version(s) we *do* support -498 .header("Sec-WebSocket-Version", SUPPORTED_WEBSOCKET_VERSION) -499 .body(body_empty()) -500 .expect("valid body")); -501 } -502 -503 debug!("upgrading connection"); -504 -505 // Setup a future that will eventually receive the upgraded -506 // connection and talk a new protocol, and spawn the future -507 // into the runtime. -508 // -509 // Note: This can't possibly be fulfilled until the 101 response -510 // is returned below, so it's better to spawn this future instead -511 // waiting for it to complete to then return a response. -512 tokio::task::spawn( -513 async move { -514 match hyper::upgrade::on(&mut req).await { -515 Ok(upgraded) => { -516 if let Err(err) = this.0.relay_connection_handler(upgraded).await { -517 warn!("error accepting upgraded connection: {err:#}",); -518 } else { -519 debug!("upgraded connection completed"); -520 }; -521 } -522 Err(err) => warn!("upgrade error: {err:#}"), -523 } -524 } -525 .instrument(debug_span!("handler")), -526 ); -527 -528 // Now return a 101 Response saying we agree to the upgrade to the -529 // websocket upgrade protocol -530 builder = builder.status(StatusCode::SWITCHING_PROTOCOLS).header( -531 UPGRADE, -532 HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL), -533 ); -534 -535 Ok(builder -536 .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key)) -537 .header(CONNECTION, "upgrade") -538 .body(body_full("switching to websocket protocol")) -539 .expect("valid body")) -540 } -541 } -542 .boxed() -543 } -544} -545 -546impl Service<Request<Incoming>> for RelayService { -547 type Response = Response<BytesBody>; -548 type Error = HyperError; -549 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; -550 -551 fn call(&self, req: Request<Incoming>) -> Self::Future { -552 // Create a client if the request hits the relay endpoint. -553 if matches!( -554 (req.method(), req.uri().path()), -555 (&hyper::Method::GET, RELAY_PATH) -556 ) { -557 let this = self.clone(); -558 return Box::pin(async move { this.call_client_conn(req).await.map_err(Into::into) }); -559 } -560 // Otherwise handle the relay connection as normal. -561 -562 // Check all other possible endpoints. -563 let uri = req.uri().clone(); -564 if let Some(res) = self.0.handlers.get(&(req.method().clone(), uri.path())) { -565 let f = res(req, self.0.default_response()); -566 return Box::pin(async move { f }); -567 } -568 // Otherwise return 404 -569 let res = self.0.not_found_fn(req, self.0.default_response()); -570 Box::pin(async move { res }) -571 } -572} -573 -574impl Inner { -575 fn default_response(&self) -> ResponseBuilder { -576 let mut response = Response::builder(); -577 for (key, value) in self.headers.iter() { -578 response = response.header(key.clone(), value.clone()); -579 } -580 response -581 } -582 -583 fn not_found_fn( -584 &self, -585 _req: Request<Incoming>, -586 mut res: ResponseBuilder, -587 ) -> HyperResult<Response<BytesBody>> { -588 for (k, v) in self.headers.iter() { -589 res = res.header(k.clone(), v.clone()); -590 } -591 let body = body_full("Not Found"); -592 let r = res.status(StatusCode::NOT_FOUND).body(body)?; -593 HyperResult::Ok(r) -594 } -595 -596 /// The server HTTP handler to do HTTP upgrades. -597 /// -598 /// This handler runs while doing the connection upgrade handshake. Once the connection -599 /// is upgraded it sends the stream to the relay server which takes it over. After -600 /// having sent off the connection this handler returns. -601 async fn relay_connection_handler( -602 &self, -603 upgraded: Upgraded, -604 ) -> Result<(), ConnectionHandlerError> { -605 debug!("relay_connection upgraded"); -606 let (io, read_buf) = downcast_upgrade(upgraded)?; -607 if !read_buf.is_empty() { -608 return Err(BufferNotEmptySnafu { buf: read_buf }.build()); -609 } -610 -611 self.accept(io).await?; -612 Ok(()) -613 } -614 -615 /// Adds a new connection to the server and serves it. -616 /// -617 /// Will error if it takes too long (10 sec) to write or read to the connection, if there is -618 /// some read or write error to the connection, if the server is meant to verify clients, -619 /// and is unable to verify this one, or if there is some issue communicating with the server. -620 /// -621 /// The provided [`AsyncRead`] and [`AsyncWrite`] must be already connected to the connection. -622 /// -623 /// [`AsyncRead`]: tokio::io::AsyncRead -624 /// [`AsyncWrite`]: tokio::io::AsyncWrite -625 async fn accept(&self, io: MaybeTlsStream) -> Result<(), AcceptError> { -626 use snafu::ResultExt; -627 -628 trace!("accept: start"); -629 -630 let io = RateLimited::from_cfg(self.rate_limit, io, self.metrics.clone()); -631 self.metrics.accepts.inc(); -632 // Create a server builder with default config -633 let websocket = tokio_websockets::ServerBuilder::new() -634 .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE))) -635 // Serve will create a WebSocketStream on an already upgraded connection -636 .serve(io); -637 let mut io = RelayedStream { -638 inner: websocket, -639 key_cache: self.key_cache.clone(), -640 }; -641 trace!("accept: recv client key"); -642 let (client_key, info) = recv_client_key(&mut io).await.context(RecvClientKeySnafu)?; -643 -644 trace!("accept: checking access: {:?}", self.access); -645 if !self.access.is_allowed(client_key).await { -646 io.send(Frame::Health { -647 problem: Bytes::from_static(b"not authenticated"), -648 }) -649 .await?; -650 io.flush().await?; -651 -652 return Err(ClientNotAuthenticatedSnafu { key: client_key }.build()); -653 } -654 -655 if info.version != PROTOCOL_VERSION { -656 return Err(UnexpectedClientVersionSnafu { -657 version: info.version, -658 expected_version: PROTOCOL_VERSION, -659 } -660 .build()); -661 } -662 -663 trace!("accept: build client conn"); -664 let client_conn_builder = Config { -665 node_id: client_key, -666 stream: io, -667 write_timeout: self.write_timeout, -668 channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH, -669 }; -670 trace!("accept: create client"); -671 let node_id = client_conn_builder.node_id; -672 trace!(node_id = node_id.fmt_short(), "create client"); -673 -674 // build and register client, starting up read & write loops for the client -675 // connection -676 self.clients -677 .register(client_conn_builder, self.metrics.clone()) -678 .await; -679 Ok(()) -680 } -681} -682 -683/// TLS Certificate Authority acceptor. -684#[derive(Clone, derive_more::Debug)] -685pub(super) enum TlsAcceptor { -686 /// Uses Let's Encrypt as the Certificate Authority. This is used in production. -687 LetsEncrypt(#[debug("tokio_rustls_acme::AcmeAcceptor")] AcmeAcceptor), -688 /// Manually added tls acceptor. Generally used for tests or for when we've passed in -689 /// a certificate via a file. -690 Manual(#[debug("tokio_rustls::TlsAcceptor")] tokio_rustls::TlsAcceptor), -691} -692 -693impl RelayService { -694 fn new( -695 handlers: Handlers, -696 headers: HeaderMap, -697 rate_limit: Option<ClientRateLimit>, -698 key_cache: KeyCache, -699 access: AccessConfig, -700 metrics: Arc<Metrics>, -701 ) -> Self { -702 Self(Arc::new(Inner { -703 handlers, -704 headers, -705 clients: Clients::default(), -706 write_timeout: SERVER_WRITE_TIMEOUT, -707 rate_limit, -708 key_cache, -709 access, -710 metrics, -711 })) -712 } -713 -714 async fn shutdown(&self) { -715 self.0.clients.shutdown().await; -716 } -717 -718 /// Handle the incoming connection. -719 /// -720 /// If a `tls_config` is given, will serve the connection using HTTPS. -721 async fn handle_connection(self, stream: TcpStream, tls_config: Option<TlsConfig>) { -722 let res = match tls_config { -723 Some(tls_config) => { -724 debug!("HTTPS: serve connection"); -725 self.tls_serve_connection(stream, tls_config).await -726 } -727 None => { -728 debug!("HTTP: serve connection"); -729 self.serve_connection(MaybeTlsStream::Plain(stream)) -730 .await -731 .context(HttpSnafu) -732 } -733 }; -734 match res { -735 Ok(()) => {} -736 Err(error) => match error { -737 ServeConnectionError::ManualAccept { source, .. } -738 | ServeConnectionError::LetsEncryptAccept { source, .. } -739 if source.kind() == std::io::ErrorKind::UnexpectedEof => -740 { -741 debug!(reason=?source, "peer disconnected"); -742 } -743 // From hyper: <https://github.com/hyperium/hyper/commit/271bba16672ff54a44e043c5cc1ae6b9345bb172> -744 // `hyper::Error::IncompleteMessage` is hyper's equivalent of UnexpectedEof -745 ServeConnectionError::Https { source, .. } -746 | ServeConnectionError::Http { source, .. } -747 if source.is_incomplete_message() => -748 { -749 debug!(reason=?source, "peer disconnected"); -750 } -751 _ => { -752 error!(?error, "failed to handle connection"); -753 } -754 }, -755 } -756 } -757 -758 /// Serve the tls connection -759 async fn tls_serve_connection( -760 self, -761 stream: TcpStream, -762 tls_config: TlsConfig, -763 ) -> Result<(), ServeConnectionError> { -764 let TlsConfig { acceptor, config } = tls_config; -765 match acceptor { -766 TlsAcceptor::LetsEncrypt(a) => { -767 match a.accept(stream).await.context(LetsEncryptAcceptSnafu)? { -768 None => { -769 info!("TLS[acme]: received TLS-ALPN-01 validation request"); -770 } -771 Some(start_handshake) => { -772 debug!("TLS[acme]: start handshake"); -773 let tls_stream = start_handshake -774 .into_stream(config) -775 .await -776 .context(HandshakeSnafu)?; -777 self.serve_connection(MaybeTlsStream::Tls(tls_stream)) -778 .await -779 .context(HttpsSnafu)?; -780 } -781 } -782 } -783 TlsAcceptor::Manual(a) => { -784 debug!("TLS[manual]: accept"); -785 let tls_stream = tokio::time::timeout(Duration::from_secs(30), a.accept(stream)) -786 .await -787 .context(TimeoutSnafu)? -788 .context(ManualAcceptSnafu)?; -789 -790 self.serve_connection(MaybeTlsStream::Tls(tls_stream)) -791 .await -792 .context(ServeConnectionSnafu)?; -793 } -794 } -795 Ok(()) -796 } -797 -798 /// Wrapper for the actual http connection (with upgrades) -799 async fn serve_connection<I>(self, io: I) -> Result<(), hyper::Error> -800 where -801 I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync + 'static, -802 { -803 hyper::server::conn::http1::Builder::new() -804 .serve_connection(hyper_util::rt::TokioIo::new(io), self) -805 .with_upgrades() -806 .await -807 } -808} -809 -810#[derive(Default)] -811struct Handlers(HashMap<(Method, &'static str), HyperHandler>); -812 -813impl std::fmt::Debug for Handlers { -814 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -815 let s = self.0.keys().fold(String::new(), |curr, next| { -816 let (method, uri) = next; -817 format!("{curr}\n({method},{uri}): Box<Fn(ResponseBuilder) -> Result<Response<Body>> + Send + Sync + 'static>") -818 }); -819 write!(f, "HashMap<{s}>") -820 } -821} -822 -823impl std::ops::Deref for Handlers { -824 type Target = HashMap<(Method, &'static str), HyperHandler>; -825 -826 fn deref(&self) -> &Self::Target { -827 &self.0 -828 } -829} -830 -831impl std::ops::DerefMut for Handlers { -832 fn deref_mut(&mut self) -> &mut Self::Target { -833 &mut self.0 -834 } -835} -836 -837#[cfg(test)] -838mod tests { -839 use std::sync::Arc; -840 -841 use bytes::Bytes; -842 use iroh_base::{PublicKey, SecretKey}; -843 use n0_future::{SinkExt, StreamExt}; -844 use n0_snafu::{Result, ResultExt}; -845 use reqwest::Url; -846 use snafu::whatever; -847 use tracing::info; -848 use tracing_test::traced_test; -849 -850 use super::*; -851 use crate::{ -852 client::{ -853 conn::{Conn, ReceivedMessage, SendMessage}, -854 Client, ClientBuilder, ConnectError, -855 }, -856 dns::DnsResolver, -857 }; -858 -859 pub(crate) fn make_tls_config() -> TlsConfig { -860 let subject_alt_names = vec!["localhost".to_string()]; -861 -862 let cert = rcgen::generate_simple_self_signed(subject_alt_names).unwrap(); -863 let rustls_certificate = cert.cert.der().clone(); -864 let rustls_key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()); -865 let config = rustls::ServerConfig::builder_with_provider(Arc::new( -866 rustls::crypto::ring::default_provider(), -867 )) -868 .with_safe_default_protocol_versions() -869 .expect("protocols supported by ring") -870 .with_no_client_auth() -871 .with_single_cert(vec![(rustls_certificate)], rustls_key.into()) -872 .expect("cert is right"); -873 -874 let config = Arc::new(config); -875 let acceptor = tokio_rustls::TlsAcceptor::from(config.clone()); -876 -877 TlsConfig { -878 config, -879 acceptor: TlsAcceptor::Manual(acceptor), -880 } -881 } -882 -883 #[tokio::test] -884 #[traced_test] -885 async fn test_http_clients_and_server() -> Result { -886 let a_key = SecretKey::generate(rand::thread_rng()); -887 let b_key = SecretKey::generate(rand::thread_rng()); -888 -889 // start server -890 let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()) -891 .spawn() -892 .await?; -893 -894 let addr = server.addr(); -895 -896 // get dial info -897 let port = addr.port(); -898 let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() { -899 ipv4_addr -900 } else { -901 whatever!("cannot get ipv4 addr from socket addr {addr:?}"); -902 }; -903 -904 info!("addr: {addr}:{port}"); -905 let relay_addr: Url = format!("http://{addr}:{port}").parse().unwrap(); -906 -907 // create clients -908 let (a_key, mut client_a) = create_test_client(a_key, relay_addr.clone()).await?; -909 info!("created client {a_key:?}"); -910 let (b_key, mut client_b) = create_test_client(b_key, relay_addr).await?; -911 info!("created client {b_key:?}"); -912 -913 info!("ping a"); -914 client_a.send(SendMessage::Ping([1u8; 8])).await?; -915 let pong = client_a.next().await.expect("eos")?; -916 assert!(matches!(pong, ReceivedMessage::Pong(_))); -917 -918 info!("ping b"); -919 client_b.send(SendMessage::Ping([2u8; 8])).await?; -920 let pong = client_b.next().await.expect("eos")?; -921 assert!(matches!(pong, ReceivedMessage::Pong(_))); -922 -923 info!("sending message from a to b"); -924 let msg = Bytes::from_static(b"hi there, client b!"); -925 client_a -926 .send(SendMessage::SendPacket(b_key, msg.clone())) -927 .await?; -928 info!("waiting for message from a on b"); -929 let (got_key, got_msg) = -930 process_msg(client_b.next().await).expect("expected message from client_a"); -931 assert_eq!(a_key, got_key); -932 assert_eq!(msg, got_msg); -933 -934 info!("sending message from b to a"); -935 let msg = Bytes::from_static(b"right back at ya, client b!"); -936 client_b -937 .send(SendMessage::SendPacket(a_key, msg.clone())) -938 .await?; -939 info!("waiting for message b on a"); -940 let (got_key, got_msg) = -941 process_msg(client_a.next().await).expect("expected message from client_b"); -942 assert_eq!(b_key, got_key); -943 assert_eq!(msg, got_msg); -944 -945 // Close before shutting down, otherwise we'll try to send close frames on broken pipes -946 client_a.close().await?; -947 client_b.close().await?; -948 server.shutdown(); -949 -950 Ok(()) -951 } -952 -953 async fn create_test_client( -954 key: SecretKey, -955 server_url: Url, -956 ) -> Result<(PublicKey, Client), ConnectError> { -957 let public_key = key.public(); -958 let client = -959 ClientBuilder::new(server_url, key, DnsResolver::new()).insecure_skip_cert_verify(true); -960 let client = client.connect().await?; -961 -962 Ok((public_key, client)) -963 } -964 -965 fn process_msg( -966 msg: Option<Result<ReceivedMessage, crate::client::RecvError>>, -967 ) -> Option<(PublicKey, Bytes)> { -968 match msg { -969 Some(Err(e)) => { -970 info!("client `recv` error {e}"); -971 None -972 } -973 Some(Ok(msg)) => { -974 info!("got message on: {msg:?}"); -975 if let ReceivedMessage::ReceivedPacket { -976 remote_node_id: source, -977 data, -978 } = msg -979 { -980 Some((source, data)) -981 } else { -982 None -983 } -984 } -985 None => { -986 info!("client end of stream"); -987 None -988 } -989 } -990 } -991 -992 #[tokio::test] -993 #[traced_test] -994 async fn test_https_clients_and_server() -> Result { -995 let a_key = SecretKey::generate(rand::thread_rng()); -996 let b_key = SecretKey::generate(rand::thread_rng()); -997 -998 // create tls_config -999 let tls_config = make_tls_config(); -1000 -1001 // start server -1002 let mut server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()) -1003 .tls_config(Some(tls_config)) -1004 .spawn() -1005 .await?; -1006 -1007 let addr = server.addr(); -1008 -1009 // get dial info -1010 let port = addr.port(); -1011 let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() { -1012 ipv4_addr -1013 } else { -1014 whatever!("cannot get ipv4 addr from socket addr {addr:?}"); -1015 }; -1016 -1017 info!("Relay listening on: {addr}:{port}"); -1018 -1019 let url: Url = format!("https://localhost:{port}").parse().unwrap(); -1020 -1021 // create clients -1022 let (a_key, mut client_a) = create_test_client(a_key, url.clone()).await?; -1023 info!("created client {a_key:?}"); -1024 let (b_key, mut client_b) = create_test_client(b_key, url).await?; -1025 info!("created client {b_key:?}"); -1026 -1027 info!("ping a"); -1028 client_a.send(SendMessage::Ping([1u8; 8])).await?; -1029 let pong = client_a.next().await.expect("eos")?; -1030 assert!(matches!(pong, ReceivedMessage::Pong(_))); -1031 -1032 info!("ping b"); -1033 client_b.send(SendMessage::Ping([2u8; 8])).await?; -1034 let pong = client_b.next().await.expect("eos")?; -1035 assert!(matches!(pong, ReceivedMessage::Pong(_))); -1036 -1037 info!("sending message from a to b"); -1038 let msg = Bytes::from_static(b"hi there, client b!"); -1039 client_a -1040 .send(SendMessage::SendPacket(b_key, msg.clone())) -1041 .await?; -1042 info!("waiting for message from a on b"); -1043 let (got_key, got_msg) = -1044 process_msg(client_b.next().await).expect("expected message from client_a"); -1045 assert_eq!(a_key, got_key); -1046 assert_eq!(msg, got_msg); -1047 -1048 info!("sending message from b to a"); -1049 let msg = Bytes::from_static(b"right back at ya, client b!"); -1050 client_b -1051 .send(SendMessage::SendPacket(a_key, msg.clone())) -1052 .await?; -1053 info!("waiting for message b on a"); -1054 let (got_key, got_msg) = -1055 process_msg(client_a.next().await).expect("expected message from client_b"); -1056 assert_eq!(b_key, got_key); -1057 assert_eq!(msg, got_msg); -1058 -1059 // Close before shutting down, otherwise we'll try to send close frames on broken pipes -1060 client_a.close().await?; -1061 client_b.close().await?; -1062 server.shutdown(); -1063 server.task_handle().await.context("join")?; -1064 -1065 Ok(()) -1066 } -1067 -1068 async fn make_test_client(client: tokio::io::DuplexStream, key: &SecretKey) -> Result<Conn> { -1069 let client = crate::client::streams::MaybeTlsStream::Test(client); -1070 let client = tokio_websockets::ClientBuilder::new().take_over(client); -1071 let client = Conn::new(client, KeyCache::test(), key).await?; -1072 Ok(client) -1073 } -1074 -1075 #[tokio::test] -1076 #[traced_test] -1077 async fn test_server_basic() -> Result { -1078 info!("Create the server."); -1079 let service = RelayService::new( +39 +40type BytesBody = http_body_util::Full<hyper::body::Bytes>; +41type HyperError = Box<dyn std::error::Error + Send + Sync>; +42type HyperResult<T> = std::result::Result<T, HyperError>; +43type HyperHandler = Box< +44 dyn Fn(Request<Incoming>, ResponseBuilder) -> HyperResult<Response<BytesBody>> +45 + Send +46 + Sync +47 + 'static, +48>; +49 +50/// WebSocket GUID needed for accepting websocket connections, see RFC 6455 (<https://www.rfc-editor.org/rfc/rfc6455>) section 1.3 +51const SEC_WEBSOCKET_ACCEPT_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +52 +53/// Derives the accept key for WebSocket handshake according to RFC 6455. +54/// Takes the client's Sec-WebSocket-Key value and returns the calculated accept key. +55fn derive_accept_key(client_key: &HeaderValue) -> String { +56 use sha1::Digest; +57 +58 let mut sha1 = sha1::Sha1::new(); +59 sha1.update(client_key.as_bytes()); +60 sha1.update(SEC_WEBSOCKET_ACCEPT_GUID); +61 data_encoding::BASE64.encode(&sha1.finalize()) +62} +63 +64/// Creates a new [`BytesBody`] with no content. +65fn body_empty() -> BytesBody { +66 http_body_util::Full::new(hyper::body::Bytes::new()) +67} +68 +69/// Creates a new [`BytesBody`] with given content. +70fn body_full(content: impl Into<hyper::body::Bytes>) -> BytesBody { +71 http_body_util::Full::new(content.into()) +72} +73 +74#[allow(clippy::result_large_err)] +75fn downcast_upgrade(upgraded: Upgraded) -> Result<(MaybeTlsStream, Bytes), ConnectionHandlerError> { +76 match upgraded.downcast::<hyper_util::rt::TokioIo<MaybeTlsStream>>() { +77 Ok(parts) => Ok((parts.io.into_inner(), parts.read_buf)), +78 Err(_) => Err(DowncastUpgradeSnafu.build()), +79 } +80} +81 +82/// The Relay HTTP server. +83/// +84/// A running HTTP server serving the relay endpoint and optionally a number of additional +85/// HTTP services added with [`ServerBuilder::request_handler`]. If configured using +86/// [`ServerBuilder::tls_config`] the server will handle TLS as well. +87/// +88/// Created using [`ServerBuilder::spawn`]. +89#[derive(Debug)] +90pub(super) struct Server { +91 addr: SocketAddr, +92 http_server_task: AbortOnDropHandle<()>, +93 cancel_server_loop: CancellationToken, +94} +95 +96impl Server { +97 /// Returns a handle for this server. +98 /// +99 /// The server runs in the background as several async tasks. This allows controlling +100 /// the server, in particular it allows gracefully shutting down the server. +101 pub(super) fn handle(&self) -> ServerHandle { +102 ServerHandle { +103 cancel_token: self.cancel_server_loop.clone(), +104 } +105 } +106 +107 /// Closes the underlying relay server and the HTTP(S) server tasks. +108 pub(super) fn shutdown(&self) { +109 self.cancel_server_loop.cancel(); +110 } +111 +112 /// Returns the [`AbortOnDropHandle`] for the supervisor task managing the server. +113 /// +114 /// This is the root of all the tasks for the server. Aborting it will abort all the +115 /// other tasks for the server. Awaiting it will complete when all the server tasks are +116 /// completed. +117 pub(super) fn task_handle(&mut self) -> &mut AbortOnDropHandle<()> { +118 &mut self.http_server_task +119 } +120 +121 /// Returns the local address of this server. +122 pub(super) fn addr(&self) -> SocketAddr { +123 self.addr +124 } +125} +126 +127/// A handle for the [`Server`]. +128/// +129/// This does not allow access to the task but can communicate with it. +130#[derive(Debug, Clone)] +131pub(super) struct ServerHandle { +132 cancel_token: CancellationToken, +133} +134 +135impl ServerHandle { +136 /// Gracefully shut down the server. +137 pub(super) fn shutdown(&self) { +138 self.cancel_token.cancel() +139 } +140} +141 +142/// Configuration to use for the TLS connection +143#[derive(Debug, Clone)] +144pub(super) struct TlsConfig { +145 /// The server config +146 pub(super) config: Arc<rustls::ServerConfig>, +147 /// The kind +148 pub(super) acceptor: TlsAcceptor, +149} +150 +151/// Errors when attempting to upgrade and +152#[common_fields({ +153 backtrace: Option<Backtrace>, +154})] +155#[allow(missing_docs)] +156#[derive(Debug, Snafu)] +157#[non_exhaustive] +158pub enum ServeConnectionError { +159 #[snafu(display("TLS[acme] handshake"))] +160 Handshake { +161 source: std::io::Error, +162 #[snafu(implicit)] +163 span_trace: n0_snafu::SpanTrace, +164 }, +165 #[snafu(display("TLS[acme] serve connection"))] +166 ServeConnection { +167 source: hyper::Error, +168 #[snafu(implicit)] +169 span_trace: n0_snafu::SpanTrace, +170 }, +171 #[snafu(display("TLS[manual] timeout"))] +172 Timeout { +173 source: Elapsed, +174 #[snafu(implicit)] +175 span_trace: n0_snafu::SpanTrace, +176 }, +177 #[snafu(display("TLS[manual] accept"))] +178 ManualAccept { +179 source: std::io::Error, +180 #[snafu(implicit)] +181 span_trace: n0_snafu::SpanTrace, +182 }, +183 #[snafu(display("TLS[acme] accept"))] +184 LetsEncryptAccept { +185 source: std::io::Error, +186 #[snafu(implicit)] +187 span_trace: n0_snafu::SpanTrace, +188 }, +189 #[snafu(display("HTTPS connection"))] +190 Https { +191 source: hyper::Error, +192 #[snafu(implicit)] +193 span_trace: n0_snafu::SpanTrace, +194 }, +195 #[snafu(display("HTTP connection"))] +196 Http { +197 source: hyper::Error, +198 #[snafu(implicit)] +199 span_trace: n0_snafu::SpanTrace, +200 }, +201} +202 +203/// Server accept errors. +204#[common_fields({ +205 backtrace: Option<Backtrace>, +206})] +207#[allow(missing_docs)] +208#[derive(Debug, Snafu)] +209#[non_exhaustive] +210pub enum AcceptError { +211 #[snafu(display("Unable to receive client information"))] +212 RecvClientKey { +213 #[allow(clippy::result_large_err)] +214 source: StreamError, +215 #[snafu(implicit)] +216 span_trace: n0_snafu::SpanTrace, +217 }, +218 #[snafu(display("Unexpected client version {version}, expected {expected_version}"))] +219 UnexpectedClientVersion { +220 version: usize, +221 expected_version: usize, +222 #[snafu(implicit)] +223 span_trace: n0_snafu::SpanTrace, +224 }, +225 #[snafu(transparent)] +226 Io { source: std::io::Error }, +227 #[snafu(display("Client not authenticated: {key:?}"))] +228 ClientNotAuthenticated { +229 key: PublicKey, +230 #[snafu(implicit)] +231 span_trace: n0_snafu::SpanTrace, +232 }, +233} +234 +235/// Server connection errors, includes errors that can happen on `accept`. +236#[common_fields({ +237 backtrace: Option<Backtrace>, +238})] +239#[allow(missing_docs)] +240#[derive(Debug, Snafu)] +241#[non_exhaustive] +242pub enum ConnectionHandlerError { +243 #[snafu(transparent)] +244 Accept { source: AcceptError }, +245 #[snafu(display("Could not downcast the upgraded connection to MaybeTlsStream"))] +246 DowncastUpgrade { +247 #[snafu(implicit)] +248 span_trace: n0_snafu::SpanTrace, +249 }, +250 #[snafu(display("Cannot deal with buffered data yet: {buf:?}"))] +251 BufferNotEmpty { +252 buf: Bytes, +253 #[snafu(implicit)] +254 span_trace: n0_snafu::SpanTrace, +255 }, +256} +257 +258/// Builder for the Relay HTTP Server. +259/// +260/// Defaults to handling relay requests on the "/relay" (and "/derp" for backwards compatibility) endpoint. +261/// Other HTTP endpoints can be added using [`ServerBuilder::request_handler`]. +262#[derive(derive_more::Debug)] +263pub(super) struct ServerBuilder { +264 /// The ip + port combination for this server. +265 addr: SocketAddr, +266 /// Optional tls configuration/TlsAcceptor combination. +267 /// +268 /// When `None`, the server will serve HTTP, otherwise it will serve HTTPS. +269 tls_config: Option<TlsConfig>, +270 /// A map of request handlers to routes. +271 /// +272 /// Used when certain routes in your server should be made available at the same port as +273 /// the relay server, and so must be handled along side requests to the relay endpoint. +274 handlers: Handlers, +275 /// Headers to use for HTTP responses. +276 headers: HeaderMap, +277 /// Rate-limiting configuration for an individual client connection. +278 /// +279 /// Rate-limiting is enforced on received traffic from individual clients. This +280 /// configuration applies to a single client connection. +281 client_rx_ratelimit: Option<ClientRateLimit>, +282 /// The capacity of the key cache. +283 key_cache_capacity: usize, +284 /// Access config for nodes. +285 access: AccessConfig, +286 metrics: Option<Arc<Metrics>>, +287} +288 +289impl ServerBuilder { +290 /// Creates a new [ServerBuilder]. +291 pub(super) fn new(addr: SocketAddr) -> Self { +292 Self { +293 addr, +294 tls_config: None, +295 handlers: Default::default(), +296 headers: HeaderMap::new(), +297 client_rx_ratelimit: None, +298 key_cache_capacity: DEFAULT_KEY_CACHE_CAPACITY, +299 access: AccessConfig::Everyone, +300 metrics: None, +301 } +302 } +303 +304 /// Sets the metrics collector. +305 pub(super) fn metrics(mut self, metrics: Arc<Metrics>) -> Self { +306 self.metrics = Some(metrics); +307 self +308 } +309 +310 /// Set the access configuration. +311 pub(super) fn access(mut self, access: AccessConfig) -> Self { +312 self.access = access; +313 self +314 } +315 +316 /// Serves all requests content using TLS. +317 pub(super) fn tls_config(mut self, config: Option<TlsConfig>) -> Self { +318 self.tls_config = config; +319 self +320 } +321 +322 /// Sets the per-client rate-limit configuration for incoming data. +323 /// +324 /// On each client connection the incoming data is rate-limited. By default +325 /// no rate limit is enforced. +326 pub(super) fn client_rx_ratelimit(mut self, config: ClientRateLimit) -> Self { +327 self.client_rx_ratelimit = Some(config); +328 self +329 } +330 +331 /// Adds a custom handler for a specific Method & URI. +332 pub(super) fn request_handler( +333 mut self, +334 method: Method, +335 uri_path: &'static str, +336 handler: HyperHandler, +337 ) -> Self { +338 self.handlers.insert((method, uri_path), handler); +339 self +340 } +341 +342 /// Adds HTTP headers to responses. +343 pub(super) fn headers(mut self, headers: HeaderMap) -> Self { +344 for (k, v) in headers.iter() { +345 self.headers.insert(k.clone(), v.clone()); +346 } +347 self +348 } +349 +350 /// Set the capacity of the cache for public keys. +351 pub fn key_cache_capacity(mut self, capacity: usize) -> Self { +352 self.key_cache_capacity = capacity; +353 self +354 } +355 +356 /// Builds and spawns an HTTP(S) Relay Server. +357 pub(super) async fn spawn(self) -> Result<Server, SpawnError> { +358 use snafu::ResultExt; +359 +360 let cancel_token = CancellationToken::new(); +361 +362 let service = RelayService::new( +363 self.handlers, +364 self.headers, +365 self.client_rx_ratelimit, +366 KeyCache::new(self.key_cache_capacity), +367 self.access, +368 self.metrics.unwrap_or_default(), +369 ); +370 +371 let addr = self.addr; +372 let tls_config = self.tls_config; +373 +374 // Bind a TCP listener on `addr` and handles content using HTTPS. +375 +376 let listener = TcpListener::bind(&addr) +377 .await +378 .map_err(|_| BindTcpListenerSnafu { addr }.build())?; +379 +380 let addr = listener.local_addr().context(NoLocalAddrSnafu)?; +381 let http_str = tls_config.as_ref().map_or("HTTP/WS", |_| "HTTPS/WSS"); +382 info!("[{http_str}] relay: serving on {addr}"); +383 +384 let cancel = cancel_token.clone(); +385 let task = tokio::task::spawn( +386 async move { +387 // create a join set to track all our connection tasks +388 let mut set = tokio::task::JoinSet::new(); +389 loop { +390 tokio::select! { +391 biased; +392 _ = cancel.cancelled() => { +393 break; +394 } +395 Some(res) = set.join_next() => { +396 if let Err(err) = res { +397 if err.is_panic() { +398 panic!("task panicked: {err:#?}"); +399 } +400 } +401 } +402 res = listener.accept() => match res { +403 Ok((stream, peer_addr)) => { +404 debug!("connection opened from {peer_addr}"); +405 let tls_config = tls_config.clone(); +406 let service = service.clone(); +407 // spawn a task to handle the connection +408 set.spawn(async move { +409 service +410 .handle_connection(stream, tls_config) +411 .await +412 }.instrument(info_span!("conn", peer = %peer_addr))); +413 } +414 Err(err) => { +415 error!("failed to accept connection: {err}"); +416 } +417 } +418 } +419 } +420 service.shutdown().await; +421 set.shutdown().await; +422 debug!("server has been shutdown."); +423 } +424 .instrument(info_span!("relay-http-serve")), +425 ); +426 +427 Ok(Server { +428 addr, +429 http_server_task: AbortOnDropHandle::new(task), +430 cancel_server_loop: cancel_token, +431 }) +432 } +433} +434 +435/// The hyper Service that serves the actual relay endpoints. +436#[derive(Clone, Debug)] +437struct RelayService(Arc<Inner>); +438 +439#[derive(Debug)] +440struct Inner { +441 handlers: Handlers, +442 headers: HeaderMap, +443 clients: Clients, +444 write_timeout: Duration, +445 rate_limit: Option<ClientRateLimit>, +446 key_cache: KeyCache, +447 access: AccessConfig, +448 metrics: Arc<Metrics>, +449} +450 +451impl RelayService { +452 /// Upgrades the HTTP connection to the relay protocol, runs relay client. +453 fn call_client_conn( +454 &self, +455 mut req: Request<Incoming>, +456 ) -> Pin<Box<dyn Future<Output = Result<Response<BytesBody>, hyper::Error>> + Send>> { +457 // TODO: soooo much cloning. See if there is an alternative +458 let this = self.clone(); +459 let mut builder = Response::builder(); +460 for (key, value) in self.0.headers.iter() { +461 builder = builder.header(key, value); +462 } +463 +464 async move { +465 { +466 // Send a 400 to any request that doesn't have an `Upgrade` header. +467 if req.headers().get(UPGRADE) +468 != Some(&HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL)) +469 { +470 return Ok(builder +471 .status(StatusCode::BAD_REQUEST) +472 .body(body_empty()) +473 .expect("valid body")); +474 }; +475 +476 let Some(key) = req.headers().get("Sec-WebSocket-Key").cloned() else { +477 warn!("missing header Sec-WebSocket-Key for websocket relay protocol"); +478 return Ok(builder +479 .status(StatusCode::BAD_REQUEST) +480 .body(body_empty()) +481 .expect("valid body")); +482 }; +483 +484 let Some(version) = req.headers().get("Sec-WebSocket-Version").cloned() else { +485 warn!("missing header Sec-WebSocket-Version for websocket relay protocol"); +486 return Ok(builder +487 .status(StatusCode::BAD_REQUEST) +488 .body(body_empty()) +489 .expect("valid body")); +490 }; +491 +492 if version.as_bytes() != SUPPORTED_WEBSOCKET_VERSION.as_bytes() { +493 warn!("invalid header Sec-WebSocket-Version: {:?}", version); +494 return Ok(builder +495 .status(StatusCode::BAD_REQUEST) +496 // It's convention to send back the version(s) we *do* support +497 .header("Sec-WebSocket-Version", SUPPORTED_WEBSOCKET_VERSION) +498 .body(body_empty()) +499 .expect("valid body")); +500 } +501 +502 debug!("upgrading connection"); +503 +504 // Setup a future that will eventually receive the upgraded +505 // connection and talk a new protocol, and spawn the future +506 // into the runtime. +507 // +508 // Note: This can't possibly be fulfilled until the 101 response +509 // is returned below, so it's better to spawn this future instead +510 // waiting for it to complete to then return a response. +511 tokio::task::spawn( +512 async move { +513 match hyper::upgrade::on(&mut req).await { +514 Ok(upgraded) => { +515 if let Err(err) = this.0.relay_connection_handler(upgraded).await { +516 warn!("error accepting upgraded connection: {err:#}",); +517 } else { +518 debug!("upgraded connection completed"); +519 }; +520 } +521 Err(err) => warn!("upgrade error: {err:#}"), +522 } +523 } +524 .instrument(debug_span!("handler")), +525 ); +526 +527 // Now return a 101 Response saying we agree to the upgrade to the +528 // websocket upgrade protocol +529 builder = builder.status(StatusCode::SWITCHING_PROTOCOLS).header( +530 UPGRADE, +531 HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL), +532 ); +533 +534 Ok(builder +535 .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key)) +536 .header(CONNECTION, "upgrade") +537 .body(body_full("switching to websocket protocol")) +538 .expect("valid body")) +539 } +540 } +541 .boxed() +542 } +543} +544 +545impl Service<Request<Incoming>> for RelayService { +546 type Response = Response<BytesBody>; +547 type Error = HyperError; +548 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; +549 +550 fn call(&self, req: Request<Incoming>) -> Self::Future { +551 // Create a client if the request hits the relay endpoint. +552 if matches!( +553 (req.method(), req.uri().path()), +554 (&hyper::Method::GET, RELAY_PATH) +555 ) { +556 let this = self.clone(); +557 return Box::pin(async move { this.call_client_conn(req).await.map_err(Into::into) }); +558 } +559 // Otherwise handle the relay connection as normal. +560 +561 // Check all other possible endpoints. +562 let uri = req.uri().clone(); +563 if let Some(res) = self.0.handlers.get(&(req.method().clone(), uri.path())) { +564 let f = res(req, self.0.default_response()); +565 return Box::pin(async move { f }); +566 } +567 // Otherwise return 404 +568 let res = self.0.not_found_fn(req, self.0.default_response()); +569 Box::pin(async move { res }) +570 } +571} +572 +573impl Inner { +574 fn default_response(&self) -> ResponseBuilder { +575 let mut response = Response::builder(); +576 for (key, value) in self.headers.iter() { +577 response = response.header(key.clone(), value.clone()); +578 } +579 response +580 } +581 +582 fn not_found_fn( +583 &self, +584 _req: Request<Incoming>, +585 mut res: ResponseBuilder, +586 ) -> HyperResult<Response<BytesBody>> { +587 for (k, v) in self.headers.iter() { +588 res = res.header(k.clone(), v.clone()); +589 } +590 let body = body_full("Not Found"); +591 let r = res.status(StatusCode::NOT_FOUND).body(body)?; +592 HyperResult::Ok(r) +593 } +594 +595 /// The server HTTP handler to do HTTP upgrades. +596 /// +597 /// This handler runs while doing the connection upgrade handshake. Once the connection +598 /// is upgraded it sends the stream to the relay server which takes it over. After +599 /// having sent off the connection this handler returns. +600 async fn relay_connection_handler( +601 &self, +602 upgraded: Upgraded, +603 ) -> Result<(), ConnectionHandlerError> { +604 debug!("relay_connection upgraded"); +605 let (io, read_buf) = downcast_upgrade(upgraded)?; +606 if !read_buf.is_empty() { +607 return Err(BufferNotEmptySnafu { buf: read_buf }.build()); +608 } +609 +610 self.accept(io).await?; +611 Ok(()) +612 } +613 +614 /// Adds a new connection to the server and serves it. +615 /// +616 /// Will error if it takes too long (10 sec) to write or read to the connection, if there is +617 /// some read or write error to the connection, if the server is meant to verify clients, +618 /// and is unable to verify this one, or if there is some issue communicating with the server. +619 /// +620 /// The provided [`AsyncRead`] and [`AsyncWrite`] must be already connected to the connection. +621 /// +622 /// [`AsyncRead`]: tokio::io::AsyncRead +623 /// [`AsyncWrite`]: tokio::io::AsyncWrite +624 async fn accept(&self, io: MaybeTlsStream) -> Result<(), AcceptError> { +625 use snafu::ResultExt; +626 +627 trace!("accept: start"); +628 +629 let io = RateLimited::from_cfg(self.rate_limit, io, self.metrics.clone()); +630 self.metrics.accepts.inc(); +631 // Create a server builder with default config +632 let websocket = tokio_websockets::ServerBuilder::new() +633 .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE))) +634 // Serve will create a WebSocketStream on an already upgraded connection +635 .serve(io); +636 let mut io = RelayedStream { +637 inner: websocket, +638 key_cache: self.key_cache.clone(), +639 }; +640 trace!("accept: recv client key"); +641 let (client_key, info) = recv_client_key(&mut io).await.context(RecvClientKeySnafu)?; +642 +643 trace!("accept: checking access: {:?}", self.access); +644 if !self.access.is_allowed(client_key).await { +645 io.send(Frame::Health { +646 problem: Bytes::from_static(b"not authenticated"), +647 }) +648 .await?; +649 io.flush().await?; +650 +651 return Err(ClientNotAuthenticatedSnafu { key: client_key }.build()); +652 } +653 +654 if info.version != PROTOCOL_VERSION { +655 return Err(UnexpectedClientVersionSnafu { +656 version: info.version, +657 expected_version: PROTOCOL_VERSION, +658 } +659 .build()); +660 } +661 +662 trace!("accept: build client conn"); +663 let client_conn_builder = Config { +664 node_id: client_key, +665 stream: io, +666 write_timeout: self.write_timeout, +667 channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH, +668 }; +669 trace!("accept: create client"); +670 let node_id = client_conn_builder.node_id; +671 trace!(node_id = node_id.fmt_short(), "create client"); +672 +673 // build and register client, starting up read & write loops for the client +674 // connection +675 self.clients +676 .register(client_conn_builder, self.metrics.clone()) +677 .await; +678 Ok(()) +679 } +680} +681 +682/// TLS Certificate Authority acceptor. +683#[derive(Clone, derive_more::Debug)] +684pub(super) enum TlsAcceptor { +685 /// Uses Let's Encrypt as the Certificate Authority. This is used in production. +686 LetsEncrypt(#[debug("tokio_rustls_acme::AcmeAcceptor")] AcmeAcceptor), +687 /// Manually added tls acceptor. Generally used for tests or for when we've passed in +688 /// a certificate via a file. +689 Manual(#[debug("tokio_rustls::TlsAcceptor")] tokio_rustls::TlsAcceptor), +690} +691 +692impl RelayService { +693 fn new( +694 handlers: Handlers, +695 headers: HeaderMap, +696 rate_limit: Option<ClientRateLimit>, +697 key_cache: KeyCache, +698 access: AccessConfig, +699 metrics: Arc<Metrics>, +700 ) -> Self { +701 Self(Arc::new(Inner { +702 handlers, +703 headers, +704 clients: Clients::default(), +705 write_timeout: SERVER_WRITE_TIMEOUT, +706 rate_limit, +707 key_cache, +708 access, +709 metrics, +710 })) +711 } +712 +713 async fn shutdown(&self) { +714 self.0.clients.shutdown().await; +715 } +716 +717 /// Handle the incoming connection. +718 /// +719 /// If a `tls_config` is given, will serve the connection using HTTPS. +720 async fn handle_connection(self, stream: TcpStream, tls_config: Option<TlsConfig>) { +721 let res = match tls_config { +722 Some(tls_config) => { +723 debug!("HTTPS: serve connection"); +724 self.tls_serve_connection(stream, tls_config).await +725 } +726 None => { +727 debug!("HTTP: serve connection"); +728 self.serve_connection(MaybeTlsStream::Plain(stream)) +729 .await +730 .context(HttpSnafu) +731 } +732 }; +733 match res { +734 Ok(()) => {} +735 Err(error) => match error { +736 ServeConnectionError::ManualAccept { source, .. } +737 | ServeConnectionError::LetsEncryptAccept { source, .. } +738 if source.kind() == std::io::ErrorKind::UnexpectedEof => +739 { +740 debug!(reason=?source, "peer disconnected"); +741 } +742 // From hyper: <https://github.com/hyperium/hyper/commit/271bba16672ff54a44e043c5cc1ae6b9345bb172> +743 // `hyper::Error::IncompleteMessage` is hyper's equivalent of UnexpectedEof +744 ServeConnectionError::Https { source, .. } +745 | ServeConnectionError::Http { source, .. } +746 if source.is_incomplete_message() => +747 { +748 debug!(reason=?source, "peer disconnected"); +749 } +750 _ => { +751 error!(?error, "failed to handle connection"); +752 } +753 }, +754 } +755 } +756 +757 /// Serve the tls connection +758 async fn tls_serve_connection( +759 self, +760 stream: TcpStream, +761 tls_config: TlsConfig, +762 ) -> Result<(), ServeConnectionError> { +763 let TlsConfig { acceptor, config } = tls_config; +764 match acceptor { +765 TlsAcceptor::LetsEncrypt(a) => { +766 match a.accept(stream).await.context(LetsEncryptAcceptSnafu)? { +767 None => { +768 info!("TLS[acme]: received TLS-ALPN-01 validation request"); +769 } +770 Some(start_handshake) => { +771 debug!("TLS[acme]: start handshake"); +772 let tls_stream = start_handshake +773 .into_stream(config) +774 .await +775 .context(HandshakeSnafu)?; +776 self.serve_connection(MaybeTlsStream::Tls(tls_stream)) +777 .await +778 .context(HttpsSnafu)?; +779 } +780 } +781 } +782 TlsAcceptor::Manual(a) => { +783 debug!("TLS[manual]: accept"); +784 let tls_stream = tokio::time::timeout(Duration::from_secs(30), a.accept(stream)) +785 .await +786 .context(TimeoutSnafu)? +787 .context(ManualAcceptSnafu)?; +788 +789 self.serve_connection(MaybeTlsStream::Tls(tls_stream)) +790 .await +791 .context(ServeConnectionSnafu)?; +792 } +793 } +794 Ok(()) +795 } +796 +797 /// Wrapper for the actual http connection (with upgrades) +798 async fn serve_connection<I>(self, io: I) -> Result<(), hyper::Error> +799 where +800 I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync + 'static, +801 { +802 hyper::server::conn::http1::Builder::new() +803 .serve_connection(hyper_util::rt::TokioIo::new(io), self) +804 .with_upgrades() +805 .await +806 } +807} +808 +809#[derive(Default)] +810struct Handlers(HashMap<(Method, &'static str), HyperHandler>); +811 +812impl std::fmt::Debug for Handlers { +813 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +814 let s = self.0.keys().fold(String::new(), |curr, next| { +815 let (method, uri) = next; +816 format!("{curr}\n({method},{uri}): Box<Fn(ResponseBuilder) -> Result<Response<Body>> + Send + Sync + 'static>") +817 }); +818 write!(f, "HashMap<{s}>") +819 } +820} +821 +822impl std::ops::Deref for Handlers { +823 type Target = HashMap<(Method, &'static str), HyperHandler>; +824 +825 fn deref(&self) -> &Self::Target { +826 &self.0 +827 } +828} +829 +830impl std::ops::DerefMut for Handlers { +831 fn deref_mut(&mut self) -> &mut Self::Target { +832 &mut self.0 +833 } +834} +835 +836#[cfg(test)] +837mod tests { +838 use std::sync::Arc; +839 +840 use bytes::Bytes; +841 use iroh_base::{PublicKey, SecretKey}; +842 use n0_future::{SinkExt, StreamExt}; +843 use n0_snafu::{Result, ResultExt}; +844 use reqwest::Url; +845 use snafu::whatever; +846 use tracing::info; +847 use tracing_test::traced_test; +848 +849 use super::*; +850 use crate::{ +851 client::{ +852 conn::{Conn, ReceivedMessage, SendMessage}, +853 Client, ClientBuilder, ConnectError, +854 }, +855 dns::DnsResolver, +856 }; +857 +858 pub(crate) fn make_tls_config() -> TlsConfig { +859 let subject_alt_names = vec!["localhost".to_string()]; +860 +861 let cert = rcgen::generate_simple_self_signed(subject_alt_names).unwrap(); +862 let rustls_certificate = cert.cert.der().clone(); +863 let rustls_key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()); +864 let config = rustls::ServerConfig::builder_with_provider(Arc::new( +865 rustls::crypto::ring::default_provider(), +866 )) +867 .with_safe_default_protocol_versions() +868 .expect("protocols supported by ring") +869 .with_no_client_auth() +870 .with_single_cert(vec![(rustls_certificate)], rustls_key.into()) +871 .expect("cert is right"); +872 +873 let config = Arc::new(config); +874 let acceptor = tokio_rustls::TlsAcceptor::from(config.clone()); +875 +876 TlsConfig { +877 config, +878 acceptor: TlsAcceptor::Manual(acceptor), +879 } +880 } +881 +882 #[tokio::test] +883 #[traced_test] +884 async fn test_http_clients_and_server() -> Result { +885 let a_key = SecretKey::generate(rand::thread_rng()); +886 let b_key = SecretKey::generate(rand::thread_rng()); +887 +888 // start server +889 let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()) +890 .spawn() +891 .await?; +892 +893 let addr = server.addr(); +894 +895 // get dial info +896 let port = addr.port(); +897 let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() { +898 ipv4_addr +899 } else { +900 whatever!("cannot get ipv4 addr from socket addr {addr:?}"); +901 }; +902 +903 info!("addr: {addr}:{port}"); +904 let relay_addr: Url = format!("http://{addr}:{port}").parse().unwrap(); +905 +906 // create clients +907 let (a_key, mut client_a) = create_test_client(a_key, relay_addr.clone()).await?; +908 info!("created client {a_key:?}"); +909 let (b_key, mut client_b) = create_test_client(b_key, relay_addr).await?; +910 info!("created client {b_key:?}"); +911 +912 info!("ping a"); +913 client_a.send(SendMessage::Ping([1u8; 8])).await?; +914 let pong = client_a.next().await.expect("eos")?; +915 assert!(matches!(pong, ReceivedMessage::Pong(_))); +916 +917 info!("ping b"); +918 client_b.send(SendMessage::Ping([2u8; 8])).await?; +919 let pong = client_b.next().await.expect("eos")?; +920 assert!(matches!(pong, ReceivedMessage::Pong(_))); +921 +922 info!("sending message from a to b"); +923 let msg = Bytes::from_static(b"hi there, client b!"); +924 client_a +925 .send(SendMessage::SendPacket(b_key, msg.clone())) +926 .await?; +927 info!("waiting for message from a on b"); +928 let (got_key, got_msg) = +929 process_msg(client_b.next().await).expect("expected message from client_a"); +930 assert_eq!(a_key, got_key); +931 assert_eq!(msg, got_msg); +932 +933 info!("sending message from b to a"); +934 let msg = Bytes::from_static(b"right back at ya, client b!"); +935 client_b +936 .send(SendMessage::SendPacket(a_key, msg.clone())) +937 .await?; +938 info!("waiting for message b on a"); +939 let (got_key, got_msg) = +940 process_msg(client_a.next().await).expect("expected message from client_b"); +941 assert_eq!(b_key, got_key); +942 assert_eq!(msg, got_msg); +943 +944 // Close before shutting down, otherwise we'll try to send close frames on broken pipes +945 client_a.close().await?; +946 client_b.close().await?; +947 server.shutdown(); +948 +949 Ok(()) +950 } +951 +952 async fn create_test_client( +953 key: SecretKey, +954 server_url: Url, +955 ) -> Result<(PublicKey, Client), ConnectError> { +956 let public_key = key.public(); +957 let client = +958 ClientBuilder::new(server_url, key, DnsResolver::new()).insecure_skip_cert_verify(true); +959 let client = client.connect().await?; +960 +961 Ok((public_key, client)) +962 } +963 +964 fn process_msg( +965 msg: Option<Result<ReceivedMessage, crate::client::RecvError>>, +966 ) -> Option<(PublicKey, Bytes)> { +967 match msg { +968 Some(Err(e)) => { +969 info!("client `recv` error {e}"); +970 None +971 } +972 Some(Ok(msg)) => { +973 info!("got message on: {msg:?}"); +974 if let ReceivedMessage::ReceivedPacket { +975 remote_node_id: source, +976 data, +977 } = msg +978 { +979 Some((source, data)) +980 } else { +981 None +982 } +983 } +984 None => { +985 info!("client end of stream"); +986 None +987 } +988 } +989 } +990 +991 #[tokio::test] +992 #[traced_test] +993 async fn test_https_clients_and_server() -> Result { +994 let a_key = SecretKey::generate(rand::thread_rng()); +995 let b_key = SecretKey::generate(rand::thread_rng()); +996 +997 // create tls_config +998 let tls_config = make_tls_config(); +999 +1000 // start server +1001 let mut server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()) +1002 .tls_config(Some(tls_config)) +1003 .spawn() +1004 .await?; +1005 +1006 let addr = server.addr(); +1007 +1008 // get dial info +1009 let port = addr.port(); +1010 let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() { +1011 ipv4_addr +1012 } else { +1013 whatever!("cannot get ipv4 addr from socket addr {addr:?}"); +1014 }; +1015 +1016 info!("Relay listening on: {addr}:{port}"); +1017 +1018 let url: Url = format!("https://localhost:{port}").parse().unwrap(); +1019 +1020 // create clients +1021 let (a_key, mut client_a) = create_test_client(a_key, url.clone()).await?; +1022 info!("created client {a_key:?}"); +1023 let (b_key, mut client_b) = create_test_client(b_key, url).await?; +1024 info!("created client {b_key:?}"); +1025 +1026 info!("ping a"); +1027 client_a.send(SendMessage::Ping([1u8; 8])).await?; +1028 let pong = client_a.next().await.expect("eos")?; +1029 assert!(matches!(pong, ReceivedMessage::Pong(_))); +1030 +1031 info!("ping b"); +1032 client_b.send(SendMessage::Ping([2u8; 8])).await?; +1033 let pong = client_b.next().await.expect("eos")?; +1034 assert!(matches!(pong, ReceivedMessage::Pong(_))); +1035 +1036 info!("sending message from a to b"); +1037 let msg = Bytes::from_static(b"hi there, client b!"); +1038 client_a +1039 .send(SendMessage::SendPacket(b_key, msg.clone())) +1040 .await?; +1041 info!("waiting for message from a on b"); +1042 let (got_key, got_msg) = +1043 process_msg(client_b.next().await).expect("expected message from client_a"); +1044 assert_eq!(a_key, got_key); +1045 assert_eq!(msg, got_msg); +1046 +1047 info!("sending message from b to a"); +1048 let msg = Bytes::from_static(b"right back at ya, client b!"); +1049 client_b +1050 .send(SendMessage::SendPacket(a_key, msg.clone())) +1051 .await?; +1052 info!("waiting for message b on a"); +1053 let (got_key, got_msg) = +1054 process_msg(client_a.next().await).expect("expected message from client_b"); +1055 assert_eq!(b_key, got_key); +1056 assert_eq!(msg, got_msg); +1057 +1058 // Close before shutting down, otherwise we'll try to send close frames on broken pipes +1059 client_a.close().await?; +1060 client_b.close().await?; +1061 server.shutdown(); +1062 server.task_handle().await.context("join")?; +1063 +1064 Ok(()) +1065 } +1066 +1067 async fn make_test_client(client: tokio::io::DuplexStream, key: &SecretKey) -> Result<Conn> { +1068 let client = crate::client::streams::MaybeTlsStream::Test(client); +1069 let client = tokio_websockets::ClientBuilder::new().take_over(client); +1070 let client = Conn::new(client, KeyCache::test(), key).await?; +1071 Ok(client) +1072 } +1073 +1074 #[tokio::test] +1075 #[traced_test] +1076 async fn test_server_basic() -> Result { +1077 info!("Create the server."); +1078 let service = RelayService::new( +1079 Default::default(), 1080 Default::default(), -1081 Default::default(), -1082 None, -1083 KeyCache::test(), -1084 AccessConfig::Everyone, -1085 Default::default(), -1086 ); -1087 -1088 info!("Create client A and connect it to the server."); -1089 let key_a = SecretKey::generate(rand::thread_rng()); -1090 let public_key_a = key_a.public(); -1091 let (client_a, rw_a) = tokio::io::duplex(10); -1092 let s = service.clone(); -1093 let handler_task = -1094 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); -1095 let mut client_a = make_test_client(client_a, &key_a).await?; -1096 handler_task.await.context("join")??; -1097 -1098 info!("Create client B and connect it to the server."); -1099 let key_b = SecretKey::generate(rand::thread_rng()); -1100 let public_key_b = key_b.public(); -1101 let (client_b, rw_b) = tokio::io::duplex(10); -1102 let s = service.clone(); -1103 let handler_task = -1104 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); -1105 let mut client_b = make_test_client(client_b, &key_b).await?; -1106 handler_task.await.context("join")??; -1107 -1108 info!("Send message from A to B."); -1109 let msg = Bytes::from_static(b"hello client b!!"); -1110 client_a -1111 .send(SendMessage::SendPacket(public_key_b, msg.clone())) -1112 .await?; -1113 match client_b.next().await.unwrap()? { -1114 ReceivedMessage::ReceivedPacket { -1115 remote_node_id, -1116 data, -1117 } => { -1118 assert_eq!(public_key_a, remote_node_id); -1119 assert_eq!(&msg[..], data); -1120 } -1121 msg => { -1122 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1123 } -1124 } -1125 -1126 info!("Send message from B to A."); -1127 let msg = Bytes::from_static(b"nice to meet you client a!!"); -1128 client_b -1129 .send(SendMessage::SendPacket(public_key_a, msg.clone())) -1130 .await?; -1131 match client_a.next().await.unwrap()? { -1132 ReceivedMessage::ReceivedPacket { -1133 remote_node_id, -1134 data, -1135 } => { -1136 assert_eq!(public_key_b, remote_node_id); -1137 assert_eq!(&msg[..], data); -1138 } -1139 msg => { -1140 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1141 } -1142 } -1143 -1144 info!("Close the server and clients"); -1145 service.shutdown().await; -1146 tokio::time::sleep(Duration::from_secs(1)).await; -1147 -1148 info!("Fail to send message from A to B."); -1149 let res = client_a -1150 .send(SendMessage::SendPacket( -1151 public_key_b, -1152 Bytes::from_static(b"try to send"), -1153 )) -1154 .await; -1155 assert!(res.is_err()); -1156 assert!(client_b.next().await.is_none()); -1157 Ok(()) -1158 } -1159 -1160 #[tokio::test] -1161 async fn test_server_replace_client() -> Result { -1162 info!("Create the server."); -1163 let service = RelayService::new( +1081 None, +1082 KeyCache::test(), +1083 AccessConfig::Everyone, +1084 Default::default(), +1085 ); +1086 +1087 info!("Create client A and connect it to the server."); +1088 let key_a = SecretKey::generate(rand::thread_rng()); +1089 let public_key_a = key_a.public(); +1090 let (client_a, rw_a) = tokio::io::duplex(10); +1091 let s = service.clone(); +1092 let handler_task = +1093 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); +1094 let mut client_a = make_test_client(client_a, &key_a).await?; +1095 handler_task.await.context("join")??; +1096 +1097 info!("Create client B and connect it to the server."); +1098 let key_b = SecretKey::generate(rand::thread_rng()); +1099 let public_key_b = key_b.public(); +1100 let (client_b, rw_b) = tokio::io::duplex(10); +1101 let s = service.clone(); +1102 let handler_task = +1103 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); +1104 let mut client_b = make_test_client(client_b, &key_b).await?; +1105 handler_task.await.context("join")??; +1106 +1107 info!("Send message from A to B."); +1108 let msg = Bytes::from_static(b"hello client b!!"); +1109 client_a +1110 .send(SendMessage::SendPacket(public_key_b, msg.clone())) +1111 .await?; +1112 match client_b.next().await.unwrap()? { +1113 ReceivedMessage::ReceivedPacket { +1114 remote_node_id, +1115 data, +1116 } => { +1117 assert_eq!(public_key_a, remote_node_id); +1118 assert_eq!(&msg[..], data); +1119 } +1120 msg => { +1121 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1122 } +1123 } +1124 +1125 info!("Send message from B to A."); +1126 let msg = Bytes::from_static(b"nice to meet you client a!!"); +1127 client_b +1128 .send(SendMessage::SendPacket(public_key_a, msg.clone())) +1129 .await?; +1130 match client_a.next().await.unwrap()? { +1131 ReceivedMessage::ReceivedPacket { +1132 remote_node_id, +1133 data, +1134 } => { +1135 assert_eq!(public_key_b, remote_node_id); +1136 assert_eq!(&msg[..], data); +1137 } +1138 msg => { +1139 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1140 } +1141 } +1142 +1143 info!("Close the server and clients"); +1144 service.shutdown().await; +1145 tokio::time::sleep(Duration::from_secs(1)).await; +1146 +1147 info!("Fail to send message from A to B."); +1148 let res = client_a +1149 .send(SendMessage::SendPacket( +1150 public_key_b, +1151 Bytes::from_static(b"try to send"), +1152 )) +1153 .await; +1154 assert!(res.is_err()); +1155 assert!(client_b.next().await.is_none()); +1156 Ok(()) +1157 } +1158 +1159 #[tokio::test] +1160 async fn test_server_replace_client() -> Result { +1161 info!("Create the server."); +1162 let service = RelayService::new( +1163 Default::default(), 1164 Default::default(), -1165 Default::default(), -1166 None, -1167 KeyCache::test(), -1168 AccessConfig::Everyone, -1169 Default::default(), -1170 ); -1171 -1172 info!("Create client A and connect it to the server."); -1173 let key_a = SecretKey::generate(rand::thread_rng()); -1174 let public_key_a = key_a.public(); -1175 let (client_a, rw_a) = tokio::io::duplex(10); -1176 let s = service.clone(); -1177 let handler_task = -1178 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); -1179 let mut client_a = make_test_client(client_a, &key_a).await?; -1180 handler_task.await.context("join")??; -1181 -1182 info!("Create client B and connect it to the server."); -1183 let key_b = SecretKey::generate(rand::thread_rng()); -1184 let public_key_b = key_b.public(); -1185 let (client_b, rw_b) = tokio::io::duplex(10); -1186 let s = service.clone(); -1187 let handler_task = -1188 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); -1189 let mut client_b = make_test_client(client_b, &key_b).await?; -1190 handler_task.await.context("join")??; -1191 -1192 info!("Send message from A to B."); -1193 let msg = Bytes::from_static(b"hello client b!!"); -1194 client_a -1195 .send(SendMessage::SendPacket(public_key_b, msg.clone())) -1196 .await?; -1197 match client_b.next().await.expect("eos")? { -1198 ReceivedMessage::ReceivedPacket { -1199 remote_node_id, -1200 data, -1201 } => { -1202 assert_eq!(public_key_a, remote_node_id); -1203 assert_eq!(&msg[..], data); -1204 } -1205 msg => { -1206 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1207 } -1208 } -1209 -1210 info!("Send message from B to A."); -1211 let msg = Bytes::from_static(b"nice to meet you client a!!"); -1212 client_b -1213 .send(SendMessage::SendPacket(public_key_a, msg.clone())) -1214 .await?; -1215 match client_a.next().await.expect("eos")? { -1216 ReceivedMessage::ReceivedPacket { -1217 remote_node_id, -1218 data, -1219 } => { -1220 assert_eq!(public_key_b, remote_node_id); -1221 assert_eq!(&msg[..], data); -1222 } -1223 msg => { -1224 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1225 } -1226 } -1227 -1228 info!("Create client B and connect it to the server"); -1229 let (new_client_b, new_rw_b) = tokio::io::duplex(10); -1230 let s = service.clone(); -1231 let handler_task = -1232 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(new_rw_b)).await }); -1233 let mut new_client_b = make_test_client(new_client_b, &key_b).await?; -1234 handler_task.await.context("join")??; -1235 -1236 // assert!(client_b.recv().await.is_err()); -1237 -1238 info!("Send message from A to B."); -1239 let msg = Bytes::from_static(b"are you still there, b?!"); -1240 client_a -1241 .send(SendMessage::SendPacket(public_key_b, msg.clone())) -1242 .await?; -1243 match new_client_b.next().await.expect("eos")? { -1244 ReceivedMessage::ReceivedPacket { -1245 remote_node_id, -1246 data, -1247 } => { -1248 assert_eq!(public_key_a, remote_node_id); -1249 assert_eq!(&msg[..], data); -1250 } -1251 msg => { -1252 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1253 } -1254 } -1255 -1256 info!("Send message from B to A."); -1257 let msg = Bytes::from_static(b"just had a spot of trouble but I'm back now,a!!"); -1258 new_client_b -1259 .send(SendMessage::SendPacket(public_key_a, msg.clone())) -1260 .await?; -1261 match client_a.next().await.expect("eos")? { -1262 ReceivedMessage::ReceivedPacket { -1263 remote_node_id, -1264 data, -1265 } => { -1266 assert_eq!(public_key_b, remote_node_id); -1267 assert_eq!(&msg[..], data); -1268 } -1269 msg => { -1270 whatever!("expected ReceivedPacket msg, got {msg:?}"); -1271 } -1272 } -1273 -1274 info!("Close the server and clients"); -1275 service.shutdown().await; -1276 -1277 info!("Sending message from A to B fails"); -1278 let res = client_a -1279 .send(SendMessage::SendPacket( -1280 public_key_b, -1281 Bytes::from_static(b"try to send"), -1282 )) -1283 .await; -1284 assert!(res.is_err()); -1285 assert!(new_client_b.next().await.is_none()); -1286 Ok(()) -1287 } -1288} \ No newline at end of file +1165 None, +1166 KeyCache::test(), +1167 AccessConfig::Everyone, +1168 Default::default(), +1169 ); +1170 +1171 info!("Create client A and connect it to the server."); +1172 let key_a = SecretKey::generate(rand::thread_rng()); +1173 let public_key_a = key_a.public(); +1174 let (client_a, rw_a) = tokio::io::duplex(10); +1175 let s = service.clone(); +1176 let handler_task = +1177 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_a)).await }); +1178 let mut client_a = make_test_client(client_a, &key_a).await?; +1179 handler_task.await.context("join")??; +1180 +1181 info!("Create client B and connect it to the server."); +1182 let key_b = SecretKey::generate(rand::thread_rng()); +1183 let public_key_b = key_b.public(); +1184 let (client_b, rw_b) = tokio::io::duplex(10); +1185 let s = service.clone(); +1186 let handler_task = +1187 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(rw_b)).await }); +1188 let mut client_b = make_test_client(client_b, &key_b).await?; +1189 handler_task.await.context("join")??; +1190 +1191 info!("Send message from A to B."); +1192 let msg = Bytes::from_static(b"hello client b!!"); +1193 client_a +1194 .send(SendMessage::SendPacket(public_key_b, msg.clone())) +1195 .await?; +1196 match client_b.next().await.expect("eos")? { +1197 ReceivedMessage::ReceivedPacket { +1198 remote_node_id, +1199 data, +1200 } => { +1201 assert_eq!(public_key_a, remote_node_id); +1202 assert_eq!(&msg[..], data); +1203 } +1204 msg => { +1205 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1206 } +1207 } +1208 +1209 info!("Send message from B to A."); +1210 let msg = Bytes::from_static(b"nice to meet you client a!!"); +1211 client_b +1212 .send(SendMessage::SendPacket(public_key_a, msg.clone())) +1213 .await?; +1214 match client_a.next().await.expect("eos")? { +1215 ReceivedMessage::ReceivedPacket { +1216 remote_node_id, +1217 data, +1218 } => { +1219 assert_eq!(public_key_b, remote_node_id); +1220 assert_eq!(&msg[..], data); +1221 } +1222 msg => { +1223 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1224 } +1225 } +1226 +1227 info!("Create client B and connect it to the server"); +1228 let (new_client_b, new_rw_b) = tokio::io::duplex(10); +1229 let s = service.clone(); +1230 let handler_task = +1231 tokio::spawn(async move { s.0.accept(MaybeTlsStream::Test(new_rw_b)).await }); +1232 let mut new_client_b = make_test_client(new_client_b, &key_b).await?; +1233 handler_task.await.context("join")??; +1234 +1235 // assert!(client_b.recv().await.is_err()); +1236 +1237 info!("Send message from A to B."); +1238 let msg = Bytes::from_static(b"are you still there, b?!"); +1239 client_a +1240 .send(SendMessage::SendPacket(public_key_b, msg.clone())) +1241 .await?; +1242 match new_client_b.next().await.expect("eos")? { +1243 ReceivedMessage::ReceivedPacket { +1244 remote_node_id, +1245 data, +1246 } => { +1247 assert_eq!(public_key_a, remote_node_id); +1248 assert_eq!(&msg[..], data); +1249 } +1250 msg => { +1251 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1252 } +1253 } +1254 +1255 info!("Send message from B to A."); +1256 let msg = Bytes::from_static(b"just had a spot of trouble but I'm back now,a!!"); +1257 new_client_b +1258 .send(SendMessage::SendPacket(public_key_a, msg.clone())) +1259 .await?; +1260 match client_a.next().await.expect("eos")? { +1261 ReceivedMessage::ReceivedPacket { +1262 remote_node_id, +1263 data, +1264 } => { +1265 assert_eq!(public_key_b, remote_node_id); +1266 assert_eq!(&msg[..], data); +1267 } +1268 msg => { +1269 whatever!("expected ReceivedPacket msg, got {msg:?}"); +1270 } +1271 } +1272 +1273 info!("Close the server and clients"); +1274 service.shutdown().await; +1275 +1276 info!("Sending message from A to B fails"); +1277 let res = client_a +1278 .send(SendMessage::SendPacket( +1279 public_key_b, +1280 Bytes::from_static(b"try to send"), +1281 )) +1282 .await; +1283 assert!(res.is_err()); +1284 assert!(new_client_b.next().await.is_none()); +1285 Ok(()) +1286 } +1287} \ No newline at end of file diff --git a/pr/3384/docs/src/iroh_relay/server/streams.rs.html b/pr/3384/docs/src/iroh_relay/server/streams.rs.html index 431dcaa0b1..f0fb47300d 100644 --- a/pr/3384/docs/src/iroh_relay/server/streams.rs.html +++ b/pr/3384/docs/src/iroh_relay/server/streams.rs.html @@ -13,471 +13,470 @@ 13use tokio_websockets::WebSocketStream; 14use tracing::instrument; 15 -16use crate::{ -17 protos::relay::{Frame, RecvError}, -18 KeyCache, -19}; -20 -21use super::{ClientRateLimit, Metrics}; -22 -23/// A Stream and Sink for [`Frame`]s connected to a single relay client. -24/// -25/// The stream receives message from the client while the sink sends them to the client. -26#[derive(Debug)] -27pub(crate) struct RelayedStream { -28 pub(crate) inner: WebSocketStream<RateLimited<MaybeTlsStream>>, -29 pub(crate) key_cache: KeyCache, -30} -31 -32#[cfg(test)] -33impl RelayedStream { -34 pub(crate) fn test_client(stream: tokio::io::DuplexStream) -> Self { -35 let stream = MaybeTlsStream::Test(stream); -36 let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); -37 Self { -38 inner: tokio_websockets::ClientBuilder::new() -39 .limits(Self::limits()) -40 .take_over(stream), -41 key_cache: KeyCache::test(), -42 } -43 } -44 -45 pub(crate) fn test_server(stream: tokio::io::DuplexStream) -> Self { -46 let stream = MaybeTlsStream::Test(stream); -47 let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); -48 Self { -49 inner: tokio_websockets::ServerBuilder::new() -50 .limits(Self::limits()) -51 .serve(stream), -52 key_cache: KeyCache::test(), -53 } -54 } -55 -56 pub(crate) fn test_server_limited( -57 stream: tokio::io::DuplexStream, -58 max_burst_bytes: u32, -59 bytes_per_second: u32, -60 ) -> Self { -61 let stream = MaybeTlsStream::Test(stream); -62 let stream = RateLimited::new( -63 stream, -64 max_burst_bytes, -65 bytes_per_second, -66 Arc::new(Metrics::default()), -67 ); -68 Self { -69 inner: tokio_websockets::ServerBuilder::new() -70 .limits(Self::limits()) -71 .serve(stream), -72 key_cache: KeyCache::test(), -73 } -74 } -75 -76 fn limits() -> tokio_websockets::Limits { -77 tokio_websockets::Limits::default() -78 .max_payload_len(Some(crate::protos::relay::MAX_FRAME_SIZE)) -79 } -80} -81 -82fn ws_to_io_err(e: tokio_websockets::Error) -> std::io::Error { -83 match e { -84 tokio_websockets::Error::Io(io_err) => io_err, -85 _ => std::io::Error::other(e.to_string()), -86 } -87} -88 -89impl Sink<Frame> for RelayedStream { -90 type Error = std::io::Error; -91 -92 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -93 Pin::new(&mut self.inner) -94 .poll_ready(cx) -95 .map_err(ws_to_io_err) -96 } -97 -98 fn start_send(mut self: Pin<&mut Self>, item: Frame) -> Result<(), Self::Error> { -99 Pin::new(&mut self.inner) -100 .start_send(tokio_websockets::Message::binary( -101 tokio_websockets::Payload::from(item.write_to(BytesMut::new()).freeze()), -102 )) -103 .map_err(ws_to_io_err) -104 } -105 -106 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -107 Pin::new(&mut self.inner) -108 .poll_flush(cx) -109 .map_err(ws_to_io_err) -110 } -111 -112 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { -113 Pin::new(&mut self.inner) -114 .poll_close(cx) -115 .map_err(ws_to_io_err) -116 } -117} -118 -119/// Relay stream errors -120#[derive(Debug, Snafu)] -121#[non_exhaustive] -122pub enum StreamError { -123 #[snafu(transparent)] -124 Proto { source: RecvError }, -125 #[snafu(transparent)] -126 Ws { source: tokio_websockets::Error }, -127} -128 -129impl Stream for RelayedStream { -130 type Item = Result<Frame, StreamError>; -131 -132 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { -133 match Pin::new(&mut self.inner).poll_next(cx) { -134 Poll::Ready(Some(Ok(msg))) => { -135 if msg.is_close() { -136 // Indicate the stream is done when we receive a close message. -137 // Note: We don't have to poll the stream to completion for it to close gracefully. -138 return Poll::Ready(None); -139 } -140 if !msg.is_binary() { -141 tracing::warn!(?msg, "Got websocket message of unsupported type, skipping."); -142 return Poll::Pending; -143 } -144 Poll::Ready(Some( -145 Frame::from_bytes(msg.into_payload().into(), &self.key_cache) -146 .map_err(Into::into), -147 )) -148 } -149 Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e.into()))), -150 Poll::Ready(None) => Poll::Ready(None), -151 Poll::Pending => Poll::Pending, -152 } -153 } -154} -155 -156/// The main underlying IO stream type used for the relay server. -157/// -158/// Allows choosing whether or not the underlying [`tokio::net::TcpStream`] is served over Tls -159#[derive(Debug)] -160#[allow(clippy::large_enum_variant)] -161pub enum MaybeTlsStream { -162 /// A plain non-Tls [`tokio::net::TcpStream`] -163 Plain(tokio::net::TcpStream), -164 /// A Tls wrapped [`tokio::net::TcpStream`] -165 Tls(tokio_rustls::server::TlsStream<tokio::net::TcpStream>), -166 /// An in-memory bidirectional pipe. -167 #[cfg(test)] -168 Test(tokio::io::DuplexStream), -169} -170 -171impl AsyncRead for MaybeTlsStream { -172 fn poll_read( -173 mut self: Pin<&mut Self>, -174 cx: &mut Context<'_>, -175 buf: &mut tokio::io::ReadBuf<'_>, -176 ) -> Poll<std::io::Result<()>> { -177 match &mut *self { -178 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_read(cx, buf), -179 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_read(cx, buf), -180 #[cfg(test)] -181 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_read(cx, buf), -182 } -183 } -184} -185 -186impl AsyncWrite for MaybeTlsStream { -187 fn poll_flush( -188 mut self: Pin<&mut Self>, -189 cx: &mut Context<'_>, -190 ) -> Poll<std::result::Result<(), std::io::Error>> { -191 match &mut *self { -192 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_flush(cx), -193 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_flush(cx), -194 #[cfg(test)] -195 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_flush(cx), -196 } -197 } -198 -199 fn poll_shutdown( -200 mut self: Pin<&mut Self>, -201 cx: &mut Context<'_>, -202 ) -> Poll<std::result::Result<(), std::io::Error>> { -203 match &mut *self { -204 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_shutdown(cx), -205 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_shutdown(cx), -206 #[cfg(test)] -207 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_shutdown(cx), -208 } -209 } -210 -211 fn poll_write( -212 mut self: Pin<&mut Self>, -213 cx: &mut Context<'_>, -214 buf: &[u8], -215 ) -> Poll<std::result::Result<usize, std::io::Error>> { -216 match &mut *self { -217 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_write(cx, buf), -218 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_write(cx, buf), -219 #[cfg(test)] -220 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_write(cx, buf), -221 } -222 } -223 -224 fn poll_write_vectored( -225 mut self: Pin<&mut Self>, -226 cx: &mut Context<'_>, -227 bufs: &[std::io::IoSlice<'_>], -228 ) -> Poll<std::result::Result<usize, std::io::Error>> { -229 match &mut *self { -230 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), -231 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), -232 #[cfg(test)] -233 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), -234 } -235 } -236} -237 -238/// Rate limiter for reading from a [`RelayedStream`]. -239/// -240/// The writes to the sink are not rate limited. -241/// -242/// This potentially buffers one frame if the rate limiter does not allows this frame. -243/// While the frame is buffered the undernlying stream is no longer polled. -244#[derive(Debug)] -245pub(crate) struct RateLimited<S> { -246 inner: S, -247 bucket: Option<Bucket>, -248 bucket_refilled: Option<Pin<Box<time::Sleep>>>, -249 /// Keeps track if this stream was ever rate-limited. -250 limited_once: bool, -251 metrics: Arc<Metrics>, -252} -253 -254#[derive(Debug)] -255struct Bucket { -256 // The current bucket fill -257 fill: i64, -258 // The maximum bucket fill -259 max: i64, -260 // The bucket's last fill time -261 last_fill: time::Instant, -262 // Interval length of one refill -263 refill_period: time::Duration, -264 // How much we re-fill per refill period -265 refill: i64, -266} -267 -268impl Bucket { -269 fn new(max: i64, bytes_per_second: i64, refill_period: time::Duration) -> Self { -270 // TODO(matheus23) convert to errors -271 debug_assert!(max > 0); -272 debug_assert!(bytes_per_second > 0); -273 debug_assert_ne!(refill_period.as_millis(), 0); -274 // milliseconds is the tokio timer resolution -275 Self { -276 fill: max, -277 max, -278 last_fill: time::Instant::now(), -279 refill_period, -280 refill: bytes_per_second * refill_period.as_millis() as i64 / 1000, -281 } -282 } -283 -284 fn update_state(&mut self) { -285 let now = time::Instant::now(); -286 let refill_periods = now.saturating_duration_since(self.last_fill).as_millis() as u32 -287 / self.refill_period.as_millis() as u32; -288 if refill_periods == 0 { -289 // Nothing to do - we won't refill yet -290 return; -291 } -292 -293 self.fill += refill_periods as i64 * self.refill; -294 self.fill = std::cmp::min(self.fill, self.max); -295 self.last_fill += self.refill_period * refill_periods; -296 } -297 -298 fn consume(&mut self, bytes: i64) -> Result<(), time::Instant> { -299 self.update_state(); -300 -301 self.fill -= bytes; -302 -303 if self.fill > 0 { -304 return Ok(()); -305 } -306 -307 let missing = -self.fill; -308 -309 let periods_needed = (missing / self.refill) + 1; -310 -311 Err(self.last_fill + periods_needed as u32 * self.refill_period) -312 } -313} -314 -315impl<S> RateLimited<S> { -316 pub(crate) fn from_cfg(cfg: Option<ClientRateLimit>, io: S, metrics: Arc<Metrics>) -> Self { -317 match cfg { -318 Some(cfg) => { -319 let bytes_per_second = cfg.bytes_per_second.into(); -320 let max_burst_bytes = cfg.max_burst_bytes.map_or(bytes_per_second / 10, u32::from); -321 Self::new(io, max_burst_bytes, bytes_per_second, metrics) -322 } -323 None => Self::unlimited(io, metrics), -324 } -325 } -326 -327 pub(crate) fn new( -328 inner: S, -329 max_burst_bytes: u32, -330 bytes_per_second: u32, -331 metrics: Arc<Metrics>, -332 ) -> Self { -333 Self { -334 inner, -335 bucket: Some(Bucket::new( -336 max_burst_bytes as i64, -337 bytes_per_second as i64, -338 time::Duration::from_millis(100), -339 )), -340 bucket_refilled: None, -341 limited_once: false, -342 metrics, -343 } -344 } -345 -346 pub(crate) fn unlimited(inner: S, metrics: Arc<Metrics>) -> Self { -347 Self { -348 inner, -349 bucket: None, -350 bucket_refilled: None, -351 limited_once: false, -352 metrics, -353 } -354 } -355} -356 -357impl<S> RateLimited<S> { -358 /// Records metrics about being rate-limited. -359 fn record_rate_limited(&mut self, bytes: usize) { -360 // TODO: add a label for the frame type. -361 self.metrics.bytes_rx_ratelimited_total.inc_by(bytes as u64); -362 if !self.limited_once { -363 self.metrics.conns_rx_ratelimited_total.inc(); -364 self.limited_once = true; -365 } -366 } -367} -368 -369impl<S: AsyncRead + Unpin> AsyncRead for RateLimited<S> { -370 #[instrument(name = "rate_limited_poll_read", skip_all)] -371 fn poll_read( -372 mut self: Pin<&mut Self>, -373 cx: &mut std::task::Context<'_>, -374 buf: &mut tokio::io::ReadBuf<'_>, -375 ) -> Poll<std::io::Result<()>> { -376 let this = &mut *self; -377 let Some(bucket) = &mut this.bucket else { -378 // If there is no rate-limiter, then directly poll the inner. -379 return Pin::new(&mut this.inner).poll_read(cx, buf); -380 }; -381 -382 // If we're currently limited, wait until we've got some bucket space again -383 if let Some(bucket_refilled) = &mut this.bucket_refilled { -384 ready!(bucket_refilled.poll(cx)); -385 this.bucket_refilled = None; -386 } -387 -388 // We're not currently limited, let's read -389 -390 // Poll inner for a new item. -391 let bytes_before = buf.remaining(); -392 ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?; -393 let bytes_read = bytes_before - buf.remaining(); -394 -395 // Record how much we've read, rate limit accordingly, if need be. -396 if let Err(refill_time) = bucket.consume(bytes_read as i64) { -397 this.record_rate_limited(bytes_read); -398 this.bucket_refilled = Some(Box::pin(time::sleep_until(refill_time))); -399 } -400 -401 Poll::Ready(Ok(())) -402 } -403} -404 -405impl<S: AsyncWrite + Unpin> AsyncWrite for RateLimited<S> { -406 fn poll_write( -407 mut self: Pin<&mut Self>, -408 cx: &mut std::task::Context<'_>, -409 buf: &[u8], -410 ) -> Poll<Result<usize, std::io::Error>> { -411 Pin::new(&mut self.inner).poll_write(cx, buf) -412 } -413 -414 fn poll_flush( -415 mut self: Pin<&mut Self>, -416 cx: &mut std::task::Context<'_>, -417 ) -> Poll<Result<(), std::io::Error>> { -418 Pin::new(&mut self.inner).poll_flush(cx) -419 } -420 -421 fn poll_shutdown( -422 mut self: Pin<&mut Self>, -423 cx: &mut std::task::Context<'_>, -424 ) -> Poll<Result<(), std::io::Error>> { -425 Pin::new(&mut self.inner).poll_shutdown(cx) -426 } -427} -428 -429#[cfg(test)] -430mod tests { -431 use std::sync::Arc; -432 -433 use n0_future::time; -434 use n0_snafu::{Result, ResultExt}; -435 use tokio::io::{AsyncReadExt, AsyncWriteExt}; -436 use tracing_test::traced_test; -437 -438 use crate::server::{streams::RateLimited, Metrics}; -439 -440 #[tokio::test(start_paused = true)] -441 #[traced_test] -442 async fn test_ratelimiter() -> Result { -443 let (read, mut write) = tokio::io::duplex(4096); -444 -445 let send_total = 10 * 1024 * 1024; // 10MiB -446 let send_data = vec![42u8; send_total]; -447 -448 let bytes_per_second = 12_345; -449 -450 let mut rate_limited = RateLimited::new( -451 read, -452 bytes_per_second / 10, -453 bytes_per_second, -454 Arc::new(Metrics::default()), -455 ); -456 -457 let before = time::Instant::now(); -458 n0_future::future::try_zip( -459 async { -460 let mut remaining = send_total; -461 let mut buf = [0u8; 4096]; -462 while remaining > 0 { -463 remaining -= rate_limited.read(&mut buf).await?; -464 } -465 Ok(()) -466 }, -467 async { -468 write.write_all(&send_data).await?; -469 write.flush().await -470 }, -471 ) -472 .await -473 .e()?; -474 -475 let duration = time::Instant::now().duration_since(before); -476 assert_ne!(duration.as_millis(), 0); -477 -478 let actual_bytes_per_second = send_total as f64 / duration.as_secs_f64(); -479 assert_eq!(actual_bytes_per_second.round() as u32, bytes_per_second); -480 -481 Ok(()) -482 } -483} \ No newline at end of file +16use super::{ClientRateLimit, Metrics}; +17use crate::{ +18 protos::relay::{Frame, RecvError}, +19 KeyCache, +20}; +21 +22/// A Stream and Sink for [`Frame`]s connected to a single relay client. +23/// +24/// The stream receives message from the client while the sink sends them to the client. +25#[derive(Debug)] +26pub(crate) struct RelayedStream { +27 pub(crate) inner: WebSocketStream<RateLimited<MaybeTlsStream>>, +28 pub(crate) key_cache: KeyCache, +29} +30 +31#[cfg(test)] +32impl RelayedStream { +33 pub(crate) fn test_client(stream: tokio::io::DuplexStream) -> Self { +34 let stream = MaybeTlsStream::Test(stream); +35 let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); +36 Self { +37 inner: tokio_websockets::ClientBuilder::new() +38 .limits(Self::limits()) +39 .take_over(stream), +40 key_cache: KeyCache::test(), +41 } +42 } +43 +44 pub(crate) fn test_server(stream: tokio::io::DuplexStream) -> Self { +45 let stream = MaybeTlsStream::Test(stream); +46 let stream = RateLimited::unlimited(stream, Arc::new(Metrics::default())); +47 Self { +48 inner: tokio_websockets::ServerBuilder::new() +49 .limits(Self::limits()) +50 .serve(stream), +51 key_cache: KeyCache::test(), +52 } +53 } +54 +55 pub(crate) fn test_server_limited( +56 stream: tokio::io::DuplexStream, +57 max_burst_bytes: u32, +58 bytes_per_second: u32, +59 ) -> Self { +60 let stream = MaybeTlsStream::Test(stream); +61 let stream = RateLimited::new( +62 stream, +63 max_burst_bytes, +64 bytes_per_second, +65 Arc::new(Metrics::default()), +66 ); +67 Self { +68 inner: tokio_websockets::ServerBuilder::new() +69 .limits(Self::limits()) +70 .serve(stream), +71 key_cache: KeyCache::test(), +72 } +73 } +74 +75 fn limits() -> tokio_websockets::Limits { +76 tokio_websockets::Limits::default() +77 .max_payload_len(Some(crate::protos::relay::MAX_FRAME_SIZE)) +78 } +79} +80 +81fn ws_to_io_err(e: tokio_websockets::Error) -> std::io::Error { +82 match e { +83 tokio_websockets::Error::Io(io_err) => io_err, +84 _ => std::io::Error::other(e.to_string()), +85 } +86} +87 +88impl Sink<Frame> for RelayedStream { +89 type Error = std::io::Error; +90 +91 fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +92 Pin::new(&mut self.inner) +93 .poll_ready(cx) +94 .map_err(ws_to_io_err) +95 } +96 +97 fn start_send(mut self: Pin<&mut Self>, item: Frame) -> Result<(), Self::Error> { +98 Pin::new(&mut self.inner) +99 .start_send(tokio_websockets::Message::binary( +100 tokio_websockets::Payload::from(item.write_to(BytesMut::new()).freeze()), +101 )) +102 .map_err(ws_to_io_err) +103 } +104 +105 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +106 Pin::new(&mut self.inner) +107 .poll_flush(cx) +108 .map_err(ws_to_io_err) +109 } +110 +111 fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { +112 Pin::new(&mut self.inner) +113 .poll_close(cx) +114 .map_err(ws_to_io_err) +115 } +116} +117 +118/// Relay stream errors +119#[derive(Debug, Snafu)] +120#[non_exhaustive] +121pub enum StreamError { +122 #[snafu(transparent)] +123 Proto { source: RecvError }, +124 #[snafu(transparent)] +125 Ws { source: tokio_websockets::Error }, +126} +127 +128impl Stream for RelayedStream { +129 type Item = Result<Frame, StreamError>; +130 +131 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { +132 match Pin::new(&mut self.inner).poll_next(cx) { +133 Poll::Ready(Some(Ok(msg))) => { +134 if msg.is_close() { +135 // Indicate the stream is done when we receive a close message. +136 // Note: We don't have to poll the stream to completion for it to close gracefully. +137 return Poll::Ready(None); +138 } +139 if !msg.is_binary() { +140 tracing::warn!(?msg, "Got websocket message of unsupported type, skipping."); +141 return Poll::Pending; +142 } +143 Poll::Ready(Some( +144 Frame::from_bytes(msg.into_payload().into(), &self.key_cache) +145 .map_err(Into::into), +146 )) +147 } +148 Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e.into()))), +149 Poll::Ready(None) => Poll::Ready(None), +150 Poll::Pending => Poll::Pending, +151 } +152 } +153} +154 +155/// The main underlying IO stream type used for the relay server. +156/// +157/// Allows choosing whether or not the underlying [`tokio::net::TcpStream`] is served over Tls +158#[derive(Debug)] +159#[allow(clippy::large_enum_variant)] +160pub enum MaybeTlsStream { +161 /// A plain non-Tls [`tokio::net::TcpStream`] +162 Plain(tokio::net::TcpStream), +163 /// A Tls wrapped [`tokio::net::TcpStream`] +164 Tls(tokio_rustls::server::TlsStream<tokio::net::TcpStream>), +165 /// An in-memory bidirectional pipe. +166 #[cfg(test)] +167 Test(tokio::io::DuplexStream), +168} +169 +170impl AsyncRead for MaybeTlsStream { +171 fn poll_read( +172 mut self: Pin<&mut Self>, +173 cx: &mut Context<'_>, +174 buf: &mut tokio::io::ReadBuf<'_>, +175 ) -> Poll<std::io::Result<()>> { +176 match &mut *self { +177 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_read(cx, buf), +178 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_read(cx, buf), +179 #[cfg(test)] +180 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_read(cx, buf), +181 } +182 } +183} +184 +185impl AsyncWrite for MaybeTlsStream { +186 fn poll_flush( +187 mut self: Pin<&mut Self>, +188 cx: &mut Context<'_>, +189 ) -> Poll<std::result::Result<(), std::io::Error>> { +190 match &mut *self { +191 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_flush(cx), +192 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_flush(cx), +193 #[cfg(test)] +194 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_flush(cx), +195 } +196 } +197 +198 fn poll_shutdown( +199 mut self: Pin<&mut Self>, +200 cx: &mut Context<'_>, +201 ) -> Poll<std::result::Result<(), std::io::Error>> { +202 match &mut *self { +203 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_shutdown(cx), +204 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_shutdown(cx), +205 #[cfg(test)] +206 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_shutdown(cx), +207 } +208 } +209 +210 fn poll_write( +211 mut self: Pin<&mut Self>, +212 cx: &mut Context<'_>, +213 buf: &[u8], +214 ) -> Poll<std::result::Result<usize, std::io::Error>> { +215 match &mut *self { +216 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_write(cx, buf), +217 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_write(cx, buf), +218 #[cfg(test)] +219 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_write(cx, buf), +220 } +221 } +222 +223 fn poll_write_vectored( +224 mut self: Pin<&mut Self>, +225 cx: &mut Context<'_>, +226 bufs: &[std::io::IoSlice<'_>], +227 ) -> Poll<std::result::Result<usize, std::io::Error>> { +228 match &mut *self { +229 MaybeTlsStream::Plain(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), +230 MaybeTlsStream::Tls(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), +231 #[cfg(test)] +232 MaybeTlsStream::Test(ref mut s) => Pin::new(s).poll_write_vectored(cx, bufs), +233 } +234 } +235} +236 +237/// Rate limiter for reading from a [`RelayedStream`]. +238/// +239/// The writes to the sink are not rate limited. +240/// +241/// This potentially buffers one frame if the rate limiter does not allows this frame. +242/// While the frame is buffered the undernlying stream is no longer polled. +243#[derive(Debug)] +244pub(crate) struct RateLimited<S> { +245 inner: S, +246 bucket: Option<Bucket>, +247 bucket_refilled: Option<Pin<Box<time::Sleep>>>, +248 /// Keeps track if this stream was ever rate-limited. +249 limited_once: bool, +250 metrics: Arc<Metrics>, +251} +252 +253#[derive(Debug)] +254struct Bucket { +255 // The current bucket fill +256 fill: i64, +257 // The maximum bucket fill +258 max: i64, +259 // The bucket's last fill time +260 last_fill: time::Instant, +261 // Interval length of one refill +262 refill_period: time::Duration, +263 // How much we re-fill per refill period +264 refill: i64, +265} +266 +267impl Bucket { +268 fn new(max: i64, bytes_per_second: i64, refill_period: time::Duration) -> Self { +269 // TODO(matheus23) convert to errors +270 debug_assert!(max > 0); +271 debug_assert!(bytes_per_second > 0); +272 debug_assert_ne!(refill_period.as_millis(), 0); +273 // milliseconds is the tokio timer resolution +274 Self { +275 fill: max, +276 max, +277 last_fill: time::Instant::now(), +278 refill_period, +279 refill: bytes_per_second * refill_period.as_millis() as i64 / 1000, +280 } +281 } +282 +283 fn update_state(&mut self) { +284 let now = time::Instant::now(); +285 let refill_periods = now.saturating_duration_since(self.last_fill).as_millis() as u32 +286 / self.refill_period.as_millis() as u32; +287 if refill_periods == 0 { +288 // Nothing to do - we won't refill yet +289 return; +290 } +291 +292 self.fill += refill_periods as i64 * self.refill; +293 self.fill = std::cmp::min(self.fill, self.max); +294 self.last_fill += self.refill_period * refill_periods; +295 } +296 +297 fn consume(&mut self, bytes: i64) -> Result<(), time::Instant> { +298 self.update_state(); +299 +300 self.fill -= bytes; +301 +302 if self.fill > 0 { +303 return Ok(()); +304 } +305 +306 let missing = -self.fill; +307 +308 let periods_needed = (missing / self.refill) + 1; +309 +310 Err(self.last_fill + periods_needed as u32 * self.refill_period) +311 } +312} +313 +314impl<S> RateLimited<S> { +315 pub(crate) fn from_cfg(cfg: Option<ClientRateLimit>, io: S, metrics: Arc<Metrics>) -> Self { +316 match cfg { +317 Some(cfg) => { +318 let bytes_per_second = cfg.bytes_per_second.into(); +319 let max_burst_bytes = cfg.max_burst_bytes.map_or(bytes_per_second / 10, u32::from); +320 Self::new(io, max_burst_bytes, bytes_per_second, metrics) +321 } +322 None => Self::unlimited(io, metrics), +323 } +324 } +325 +326 pub(crate) fn new( +327 inner: S, +328 max_burst_bytes: u32, +329 bytes_per_second: u32, +330 metrics: Arc<Metrics>, +331 ) -> Self { +332 Self { +333 inner, +334 bucket: Some(Bucket::new( +335 max_burst_bytes as i64, +336 bytes_per_second as i64, +337 time::Duration::from_millis(100), +338 )), +339 bucket_refilled: None, +340 limited_once: false, +341 metrics, +342 } +343 } +344 +345 pub(crate) fn unlimited(inner: S, metrics: Arc<Metrics>) -> Self { +346 Self { +347 inner, +348 bucket: None, +349 bucket_refilled: None, +350 limited_once: false, +351 metrics, +352 } +353 } +354} +355 +356impl<S> RateLimited<S> { +357 /// Records metrics about being rate-limited. +358 fn record_rate_limited(&mut self, bytes: usize) { +359 // TODO: add a label for the frame type. +360 self.metrics.bytes_rx_ratelimited_total.inc_by(bytes as u64); +361 if !self.limited_once { +362 self.metrics.conns_rx_ratelimited_total.inc(); +363 self.limited_once = true; +364 } +365 } +366} +367 +368impl<S: AsyncRead + Unpin> AsyncRead for RateLimited<S> { +369 #[instrument(name = "rate_limited_poll_read", skip_all)] +370 fn poll_read( +371 mut self: Pin<&mut Self>, +372 cx: &mut std::task::Context<'_>, +373 buf: &mut tokio::io::ReadBuf<'_>, +374 ) -> Poll<std::io::Result<()>> { +375 let this = &mut *self; +376 let Some(bucket) = &mut this.bucket else { +377 // If there is no rate-limiter, then directly poll the inner. +378 return Pin::new(&mut this.inner).poll_read(cx, buf); +379 }; +380 +381 // If we're currently limited, wait until we've got some bucket space again +382 if let Some(bucket_refilled) = &mut this.bucket_refilled { +383 ready!(bucket_refilled.poll(cx)); +384 this.bucket_refilled = None; +385 } +386 +387 // We're not currently limited, let's read +388 +389 // Poll inner for a new item. +390 let bytes_before = buf.remaining(); +391 ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?; +392 let bytes_read = bytes_before - buf.remaining(); +393 +394 // Record how much we've read, rate limit accordingly, if need be. +395 if let Err(refill_time) = bucket.consume(bytes_read as i64) { +396 this.record_rate_limited(bytes_read); +397 this.bucket_refilled = Some(Box::pin(time::sleep_until(refill_time))); +398 } +399 +400 Poll::Ready(Ok(())) +401 } +402} +403 +404impl<S: AsyncWrite + Unpin> AsyncWrite for RateLimited<S> { +405 fn poll_write( +406 mut self: Pin<&mut Self>, +407 cx: &mut std::task::Context<'_>, +408 buf: &[u8], +409 ) -> Poll<Result<usize, std::io::Error>> { +410 Pin::new(&mut self.inner).poll_write(cx, buf) +411 } +412 +413 fn poll_flush( +414 mut self: Pin<&mut Self>, +415 cx: &mut std::task::Context<'_>, +416 ) -> Poll<Result<(), std::io::Error>> { +417 Pin::new(&mut self.inner).poll_flush(cx) +418 } +419 +420 fn poll_shutdown( +421 mut self: Pin<&mut Self>, +422 cx: &mut std::task::Context<'_>, +423 ) -> Poll<Result<(), std::io::Error>> { +424 Pin::new(&mut self.inner).poll_shutdown(cx) +425 } +426} +427 +428#[cfg(test)] +429mod tests { +430 use std::sync::Arc; +431 +432 use n0_future::time; +433 use n0_snafu::{Result, ResultExt}; +434 use tokio::io::{AsyncReadExt, AsyncWriteExt}; +435 use tracing_test::traced_test; +436 +437 use crate::server::{streams::RateLimited, Metrics}; +438 +439 #[tokio::test(start_paused = true)] +440 #[traced_test] +441 async fn test_ratelimiter() -> Result { +442 let (read, mut write) = tokio::io::duplex(4096); +443 +444 let send_total = 10 * 1024 * 1024; // 10MiB +445 let send_data = vec![42u8; send_total]; +446 +447 let bytes_per_second = 12_345; +448 +449 let mut rate_limited = RateLimited::new( +450 read, +451 bytes_per_second / 10, +452 bytes_per_second, +453 Arc::new(Metrics::default()), +454 ); +455 +456 let before = time::Instant::now(); +457 n0_future::future::try_zip( +458 async { +459 let mut remaining = send_total; +460 let mut buf = [0u8; 4096]; +461 while remaining > 0 { +462 remaining -= rate_limited.read(&mut buf).await?; +463 } +464 Ok(()) +465 }, +466 async { +467 write.write_all(&send_data).await?; +468 write.flush().await +469 }, +470 ) +471 .await +472 .e()?; +473 +474 let duration = time::Instant::now().duration_since(before); +475 assert_ne!(duration.as_millis(), 0); +476 +477 let actual_bytes_per_second = send_total as f64 / duration.as_secs_f64(); +478 assert_eq!(actual_bytes_per_second.round() as u32, bytes_per_second); +479 +480 Ok(()) +481 } +482} \ No newline at end of file