From 1dda2f7ab706cf794d2c8f4e6b47b24caf2f1c78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Kr=C3=BCger?= Date: Wed, 31 Jul 2024 10:00:49 +0200 Subject: [PATCH] refactor(iroh-net): Move more server code behind `iroh-relay` feature flag (#2566) ## Description This moves more relay server code behind the `iroh-relay` feature flag. This is a continuation of #2516 Unfortunately I didn't quite catch "all server things". I'm fairly confident I do have all covered now, because this is extracted from a branch where server-side code wouldn't compile (to Wasm). Also: - Makes use of `MaybeTlsStream` instead of the `MaybeTlsStreamServer` alias. Using the original definition instead of the alias confuses rust-analyzer a lot less. And the aliasing back-and-forth was silly. ## Breaking Changes None ## Notes & open questions ## Change checklist - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - ~~[ ] Tests if relevant.~~ - [x] All breaking changes documented. --- iroh-net/src/magicsock/relay_actor.rs | 16 ++++++---------- iroh-net/src/relay.rs | 4 ++++ iroh-net/src/relay/client.rs | 16 ++-------------- iroh-net/src/relay/client_conn.rs | 2 +- iroh-net/src/relay/clients.rs | 3 +-- iroh-net/src/relay/codec.rs | 8 +++++++- iroh-net/src/relay/http.rs | 2 +- iroh-net/src/relay/http/client.rs | 4 ++-- iroh-net/src/relay/http/server.rs | 8 +++----- iroh-net/src/relay/iroh_relay.rs | 4 ++-- iroh-net/src/relay/server.rs | 3 +-- iroh-net/src/relay/types.rs | 5 +++++ 12 files changed, 35 insertions(+), 40 deletions(-) diff --git a/iroh-net/src/magicsock/relay_actor.rs b/iroh-net/src/magicsock/relay_actor.rs index ecae432cf3..93029de0ce 100644 --- a/iroh-net/src/magicsock/relay_actor.rs +++ b/iroh-net/src/magicsock/relay_actor.rs @@ -20,7 +20,7 @@ use tracing::{debug, info, info_span, trace, warn, Instrument}; use crate::{ key::{PublicKey, PUBLIC_KEY_LENGTH}, - relay::{self, http::ClientError, ReceivedMessage, RelayUrl, MAX_PACKET_SIZE}, + relay::{self, client::ReceivedMessage, http::ClientError, RelayUrl, MAX_PACKET_SIZE}, }; use super::{ActorMessage, MagicSock}; @@ -200,7 +200,7 @@ impl ActiveRelay { None => ReadResult::Break, } } - Ok((msg, conn_gen)) => { + Ok((msg, _conn_gen)) => { // reset self.backoff.reset(); let now = Instant::now(); @@ -214,11 +214,7 @@ impl ActiveRelay { } match msg { - relay::ReceivedMessage::ServerInfo { .. } => { - info!(%conn_gen, "connected"); - ReadResult::Continue - } - relay::ReceivedMessage::ReceivedPacket { source, data } => { + relay::client::ReceivedMessage::ReceivedPacket { source, data } => { trace!(len=%data.len(), "received msg"); // If this is a new sender we hadn't seen before, remember it and // register a route for this peer. @@ -248,7 +244,7 @@ impl ActiveRelay { ReadResult::Continue } - relay::ReceivedMessage::Ping(data) => { + relay::client::ReceivedMessage::Ping(data) => { // Best effort reply to the ping. let dc = self.relay_client.clone(); tokio::task::spawn(async move { @@ -258,8 +254,8 @@ impl ActiveRelay { }); ReadResult::Continue } - relay::ReceivedMessage::Health { .. } => ReadResult::Continue, - relay::ReceivedMessage::PeerGone(key) => { + relay::client::ReceivedMessage::Health { .. } => ReadResult::Continue, + relay::client::ReceivedMessage::PeerGone(key) => { self.relay_routes.retain(|peer| peer != &key); ReadResult::Continue } diff --git a/iroh-net/src/relay.rs b/iroh-net/src/relay.rs index 9c0d696efc..b9d9f1fb06 100644 --- a/iroh-net/src/relay.rs +++ b/iroh-net/src/relay.rs @@ -11,7 +11,9 @@ #![deny(missing_docs, rustdoc::broken_intra_doc_links)] pub(crate) mod client; +#[cfg(feature = "iroh-relay")] pub(crate) mod client_conn; +#[cfg(feature = "iroh-relay")] pub(crate) mod clients; pub(crate) mod codec; pub mod http; @@ -19,6 +21,7 @@ pub mod http; pub mod iroh_relay; mod map; mod metrics; +#[cfg(feature = "iroh-relay")] pub(crate) mod server; pub(crate) mod types; @@ -27,5 +30,6 @@ pub use self::codec::MAX_PACKET_SIZE; pub use self::http::Client as HttpClient; pub use self::map::{RelayMap, RelayMode, RelayNode}; pub use self::metrics::Metrics; +#[cfg(feature = "iroh-relay")] pub use self::server::{ClientConnHandler, MaybeTlsStream as MaybeTlsStreamServer, Server}; pub use iroh_base::node_addr::RelayUrl; diff --git a/iroh-net/src/relay/client.rs b/iroh-net/src/relay/client.rs index 173919d906..1fa34b1efd 100644 --- a/iroh-net/src/relay/client.rs +++ b/iroh-net/src/relay/client.rs @@ -439,7 +439,7 @@ impl ClientBuilder { } #[derive(derive_more::Debug, Clone)] -/// The type of message received by the [`Client`] from the [`super::server::Server`]. +/// The type of message received by the [`Client`] from a relay server. pub enum ReceivedMessage { /// Represents an incoming packet. ReceivedPacket { @@ -452,18 +452,6 @@ pub enum ReceivedMessage { /// Indicates that the client identified by the underlying public key had previously sent you a /// packet but has now disconnected from the server. PeerGone(PublicKey), - /// Sent by the server upon first connect. - ServerInfo { - /// How many bytes per second the server says it will accept, including all framing bytes. - /// - /// Zero means unspecified. There might be a limit, but the client need not try to respect it. - token_bucket_bytes_per_second: usize, - /// How many bytes the server will allow in one burst, temporarily violating - /// `token_bucket_bytes_per_second`. - /// - /// Zero means unspecified. There might be a limit, but the [`Client`] need not try to respect it. - token_bucket_bytes_burst: usize, - }, /// Request from a client or server to reply to the /// other side with a [`ReceivedMessage::Pong`] with the given payload. Ping([u8; 8]), @@ -471,7 +459,7 @@ pub enum ReceivedMessage { /// with the payload sent previously in the ping. Pong([u8; 8]), /// A one-way empty message from server to client, just to - /// keep the connection alive. It's like a [ReceivedMessage::Ping], but doesn't solicit + /// keep the connection alive. It's like a [`ReceivedMessage::Ping`], but doesn't solicit /// a reply from the client. KeepAlive, /// A one-way message from server to client, declaring the connection health state. diff --git a/iroh-net/src/relay/client_conn.rs b/iroh-net/src/relay/client_conn.rs index 3d5de5cae4..c81b92c967 100644 --- a/iroh-net/src/relay/client_conn.rs +++ b/iroh-net/src/relay/client_conn.rs @@ -453,7 +453,7 @@ impl ClientConnIo { mod tests { use crate::key::SecretKey; use crate::relay::codec::{recv_frame, DerpCodec, FrameType}; - use crate::relay::MaybeTlsStreamServer as MaybeTlsStream; + use crate::relay::server::MaybeTlsStream; use super::*; diff --git a/iroh-net/src/relay/clients.rs b/iroh-net/src/relay/clients.rs index 32c76a01cf..9f77418332 100644 --- a/iroh-net/src/relay/clients.rs +++ b/iroh-net/src/relay/clients.rs @@ -262,8 +262,7 @@ mod tests { key::SecretKey, relay::{ codec::{recv_frame, DerpCodec, Frame, FrameType}, - server::RelayIo, - MaybeTlsStreamServer as MaybeTlsStream, + server::{MaybeTlsStream, RelayIo}, }, }; diff --git a/iroh-net/src/relay/codec.rs b/iroh-net/src/relay/codec.rs index 66186ed6ad..a35293f60a 100644 --- a/iroh-net/src/relay/codec.rs +++ b/iroh-net/src/relay/codec.rs @@ -1,7 +1,8 @@ use std::time::Duration; -use anyhow::{bail, ensure, Context}; +use anyhow::{bail, ensure}; use bytes::{Buf, BufMut, Bytes, BytesMut}; +#[cfg(feature = "iroh-relay")] use futures_lite::{Stream, StreamExt}; use futures_sink::Sink; use futures_util::SinkExt; @@ -21,8 +22,10 @@ const MAX_FRAME_SIZE: usize = 1024 * 1024; /// The Relay magic number, sent in the FrameType::ClientInfo frame upon initial connection. const MAGIC: &str = "RELAY🔑"; +#[cfg(feature = "iroh-relay")] pub(super) const KEEP_ALIVE: Duration = Duration::from_secs(60); // TODO: what should this be? +#[cfg(feature = "iroh-relay")] pub(super) const SERVER_CHANNEL_SIZE: usize = 1024 * 100; /// The number of packets buffered for sending per client pub(super) const PER_CLIENT_SEND_QUEUE_DEPTH: usize = 512; //32; @@ -155,9 +158,11 @@ pub(crate) async fn send_client_key + Unp /// Reads the `FrameType::ClientInfo` frame from the client (its proof of identity) /// upon it's initial connection. +#[cfg(feature = "iroh-relay")] pub(super) async fn recv_client_key> + Unpin>( stream: S, ) -> anyhow::Result<(PublicKey, ClientInfo)> { + use anyhow::Context; // the client is untrusted at this point, limit the input size even smaller than our usual // maximum frame size, and give a timeout @@ -523,6 +528,7 @@ impl Encoder for DerpCodec { /// Receives the next frame and matches the frame type. If the correct type is found returns the content, /// otherwise an error. +#[cfg(feature = "iroh-relay")] pub(super) async fn recv_frame> + Unpin>( frame_type: FrameType, mut stream: S, diff --git a/iroh-net/src/relay/http.rs b/iroh-net/src/relay/http.rs index ac3daf1de0..f7e4365f1b 100644 --- a/iroh-net/src/relay/http.rs +++ b/iroh-net/src/relay/http.rs @@ -75,7 +75,7 @@ mod tests { use tracing_subscriber::{prelude::*, EnvFilter}; use crate::key::{PublicKey, SecretKey}; - use crate::relay::ReceivedMessage; + use crate::relay::client::ReceivedMessage; pub(crate) fn make_tls_config() -> TlsConfig { let subject_alt_names = vec!["localhost".to_string()]; diff --git a/iroh-net/src/relay/http/client.rs b/iroh-net/src/relay/http/client.rs index aee444c633..97d3303184 100644 --- a/iroh-net/src/relay/http/client.rs +++ b/iroh-net/src/relay/http/client.rs @@ -35,7 +35,7 @@ use crate::relay::http::RELAY_PATH; use crate::relay::RelayUrl; use crate::relay::{ client::Client as RelayClient, client::ClientBuilder as RelayClientBuilder, - client::ClientReceiver as RelayClientReceiver, ReceivedMessage, + client::ClientReceiver as RelayClientReceiver, client::ReceivedMessage, }; use crate::util::chain; use crate::util::AbortingJoinHandle; @@ -367,7 +367,7 @@ impl ClientBuilder { ) } - /// The expected [`PublicKey`] of the [`super::server::Server`] we are connecting to. + /// The expected [`PublicKey`] of the relay server we are connecting to. pub fn server_public_key(mut self, server_public_key: PublicKey) -> Self { self.server_public_key = Some(server_public_key); self diff --git a/iroh-net/src/relay/http/server.rs b/iroh-net/src/relay/http/server.rs index d94fa59ac1..b0d6af86c6 100644 --- a/iroh-net/src/relay/http/server.rs +++ b/iroh-net/src/relay/http/server.rs @@ -25,7 +25,6 @@ use tungstenite::handshake::derive_accept_key; use crate::key::SecretKey; use crate::relay::http::SUPPORTED_WEBSOCKET_VERSION; use crate::relay::server::{ClientConnHandler, MaybeTlsStream}; -use crate::relay::MaybeTlsStreamServer; use super::{Protocol, LEGACY_RELAY_PATH, RELAY_PATH}; @@ -609,8 +608,7 @@ impl RelayService { Some(tls_config) => self.tls_serve_connection(stream, tls_config).await, None => { debug!("HTTP: serve connection"); - self.serve_connection(MaybeTlsStreamServer::Plain(stream)) - .await + self.serve_connection(MaybeTlsStream::Plain(stream)).await } } } @@ -629,7 +627,7 @@ impl RelayService { .into_stream(config) .await .context("TLS[acme] handshake")?; - self.serve_connection(MaybeTlsStreamServer::Tls(tls_stream)) + self.serve_connection(MaybeTlsStream::Tls(tls_stream)) .await .context("TLS[acme] serve connection")?; } @@ -637,7 +635,7 @@ impl RelayService { TlsAcceptor::Manual(a) => { debug!("TLS[manual]: accept"); let tls_stream = a.accept(stream).await.context("TLS[manual] accept")?; - self.serve_connection(MaybeTlsStreamServer::Tls(tls_stream)) + self.serve_connection(MaybeTlsStream::Tls(tls_stream)) .await .context("TLS[manual] serve connection")?; } diff --git a/iroh-net/src/relay/iroh_relay.rs b/iroh-net/src/relay/iroh_relay.rs index f7f0f3d8b1..4ada7965a0 100644 --- a/iroh-net/src/relay/iroh_relay.rs +++ b/iroh-net/src/relay/iroh_relay.rs @@ -608,7 +608,7 @@ async fn run_captive_portal_service(http_listener: TcpListener) -> Result<()> { let handler = CaptivePortalService; tasks.spawn(async move { - let stream = relay::MaybeTlsStreamServer::Plain(stream); + let stream = relay::server::MaybeTlsStream::Plain(stream); let stream = hyper_util::rt::TokioIo::new(stream); if let Err(err) = hyper::server::conn::http1::Builder::new() .serve_connection(stream, handler) @@ -714,7 +714,7 @@ mod tests { use crate::relay::http::{ClientBuilder, Protocol, HTTP_UPGRADE_PROTOCOL}; - use self::relay::ReceivedMessage; + use self::relay::client::ReceivedMessage; use super::*; diff --git a/iroh-net/src/relay/server.rs b/iroh-net/src/relay/server.rs index 4ce80a3e6f..865a82a2c0 100644 --- a/iroh-net/src/relay/server.rs +++ b/iroh-net/src/relay/server.rs @@ -554,11 +554,10 @@ mod tests { use super::*; use crate::relay::{ - client::{ClientBuilder, ConnReader, ConnWriter}, + client::{ClientBuilder, ConnReader, ConnWriter, ReceivedMessage}, codec::{recv_frame, FrameType}, http::streams::{MaybeTlsStreamReader, MaybeTlsStreamWriter}, types::ClientInfo, - ReceivedMessage, }; use tokio_util::codec::{FramedRead, FramedWrite}; use tracing_subscriber::{prelude::*, EnvFilter}; diff --git a/iroh-net/src/relay/types.rs b/iroh-net/src/relay/types.rs index b332182d50..27445202df 100644 --- a/iroh-net/src/relay/types.rs +++ b/iroh-net/src/relay/types.rs @@ -1,11 +1,14 @@ use std::num::NonZeroU32; use anyhow::{bail, Context, Result}; +#[cfg(feature = "iroh-relay")] use bytes::Bytes; use postcard::experimental::max_size::MaxSize; use serde::{Deserialize, Serialize}; +#[cfg(feature = "iroh-relay")] use super::client_conn::ClientConnBuilder; +#[cfg(feature = "iroh-relay")] use crate::key::PublicKey; pub(crate) struct RateLimiter { @@ -44,6 +47,7 @@ impl RateLimiter { /// A request to write a dataframe to a Client #[derive(Debug, Clone)] +#[cfg(feature = "iroh-relay")] pub(crate) struct Packet { /// The sender of the packet pub(crate) src: PublicKey, @@ -57,6 +61,7 @@ pub(crate) struct ClientInfo { pub(crate) version: usize, } +#[cfg(feature = "iroh-relay")] #[derive(derive_more::Debug)] pub(crate) enum ServerMessage { SendPacket((PublicKey, Packet)),