From 80e87e46361678aa5ddb446f33d0f68f44de0444 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 18:38:54 +0000 Subject: [PATCH 1/2] Multipath: dial fallback, fixed-rate paths, in-order delivery For a dedicated link A with a lower-quality overflow link B: - Dial fallback: if the primary path does not answer the handshake within 3 s, try the extra paths' proxy addresses (priority order, paths without @LOCAL_IP to another remote), so the tunnel comes up while A is down; A then joins as an ordinary path. - Fixed-rate paths: --path .../rate=RATE and --primary-rate send on a path at a fixed rate (cc::FixedRate via noq's new per-path controller) instead of under BBRv3, whose probing and ProbeRTT dips moved traffic onto B. Its window (2 RTTs at the rate) still fills within a round trip when the link dies, so failover is unchanged. The client announces the rate (FRAME_PATH_RATE) and the proxy applies it up to --max-path-rate (off by default: such paths have no congestion control). - In-order delivery (--in-order-delivery, default on): flows that negotiate the rapidmasque-sequence header carry 4-byte sequence numbers (HTTP datagram context 2) and the receiver resequences them with a self-tuning hold time (reorder.rs), so TCP inside WireGuard does not see the reordering of spilled traffic as loss. Other MASQUE peers keep plain RFC 9298 datagrams. The default minimum MTU grows by the 4 bytes to 1356. noq is pinned to the per-path congestion controller branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012baC35vUbLPPhuK4pz4uRz --- AGENTS.md | 13 +++ Cargo.lock | 6 +- Cargo.toml | 4 +- README.md | 82 ++++++++++++-- src/cc.rs | 200 ++++++++++++++++++++++++++++++++- src/cli.rs | 34 +++++- src/client.rs | 284 +++++++++++++++++++++++++++++++++++++++------- src/dgram.rs | 67 ++++++++++- src/e2e_test.rs | 254 +++++++++++++++++++++++++++++++++++++++-- src/h3.rs | 90 +++++++++++++-- src/main.rs | 4 + src/quic.rs | 13 ++- src/ranking.rs | 25 ++++- src/reorder.rs | 293 ++++++++++++++++++++++++++++++++++++++++++++++++ src/server.rs | 81 ++++++++++--- src/stats.rs | 1 + 16 files changed, 1350 insertions(+), 101 deletions(-) create mode 100644 src/reorder.rs diff --git a/AGENTS.md b/AGENTS.md index 6e3ab53..d1e51a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,6 +95,19 @@ and documented in `README.md`. readiness on it and wait forever for a kqueue write event, silencing every connection on the socket. It looked like a routing-table bug; the smoke test's back-to-back multipath rounds reproduce it within a few rounds. +- Per-path congestion control: `/rate=RATE` (and `--primary-rate`) puts a + path on `cc::FixedRate` through noq's `Path::set_congestion_controller` + (losfair/noq fork); the client announces it with the `FRAME_PATH_RATE` + control frame and the server applies it up to `--max-path-rate`. The fixed + window (2 RTTs at the rate) is what still moves traffic off a dead path. +- In-order delivery: flows that negotiate the `rapidmasque-sequence` header + carry sequenced datagrams (`dgram::CONTEXT_ID_SEQUENCED_UDP`, 4-byte + sequence number) and the receiver resequences them per flow + (`reorder::Reorder`, self-tuning hold time). The 4 bytes are part of + `quic::WIREGUARD_1280_DATAGRAM`, hence the 1356-byte default minimum MTU. +- Dial fallback (`client::handshake_candidates`): the primary handshake gets + 3 s, then extra paths' remotes are tried (no `@LOCAL_IP`, other remote); + path 0 is then that extra path, and the primary is opened like any path. - Outgoing datagram queue management (always on, no flags; `quic::DATAGRAM_CODEL`) is noq's `TransportConfig::datagram_send_codel` (CoDel plus a hard `max_delay`, in the losfair/noq fork): the queue that builds up is noq's diff --git a/Cargo.lock b/Cargo.lock index db7ecdc..7947079 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -563,7 +563,7 @@ dependencies = [ [[package]] name = "noq" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6#cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6" +source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" dependencies = [ "bytes", "cfg_aliases", @@ -583,7 +583,7 @@ dependencies = [ [[package]] name = "noq-proto" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6#cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6" +source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" dependencies = [ "bytes", "derive_more", @@ -609,7 +609,7 @@ dependencies = [ [[package]] name = "noq-udp" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6#cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6" +source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" dependencies = [ "cfg_aliases", "libc", diff --git a/Cargo.toml b/Cargo.toml index 461d23c..3719250 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,10 +32,10 @@ tokio-stream = "0.1" # Pinned to the losfair/noq fork for per-path scheduling priority, the path # spill threshold and datagram queue management (not in upstream noq). Keep # both crates on the same commit. -noq = { git = "https://github.com/losfair/noq", rev = "cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6", default-features = false, features = ["runtime-tokio", "ring", "bloom", "tracing-log"] } +noq = { git = "https://github.com/losfair/noq", rev = "21d76fb4243cbe8cb82fcd7c1da04b8e441de59a", default-features = false, features = ["runtime-tokio", "ring", "bloom", "tracing-log"] } # Direct dep only for `coding::Encodable` (to read a `PathId` for the multipath # AEAD nonce); same commit as noq's own. -noq-proto = { git = "https://github.com/losfair/noq", rev = "cad1d3ae29ed1b99f01dfd4498e0bb7d892ef6f6", default-features = false, features = ["ring", "bloom", "tracing-log"] } +noq-proto = { git = "https://github.com/losfair/noq", rev = "21d76fb4243cbe8cb82fcd7c1da04b8e441de59a", default-features = false, features = ["ring", "bloom", "tracing-log"] } # BoringSSL: the TLS 1.3 handshake (via its QUIC API), ECH, and packet # protection (AEAD + header protection). boring 4 keeps the ECH code identical # to zeromasque's. diff --git a/README.md b/README.md index c6cebfd..ee36c48 100644 --- a/README.md +++ b/README.md @@ -225,7 +225,7 @@ rapidmasque client \ --path '203.0.113.8:4433@10.64.0.5/backup' ``` -A path spec is `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rtable=N]`: +A path spec is `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rate=RATE][/rtable=N]`: - `REMOTE_IP:PORT` - a proxy address. It may differ from the primary one (the proxy's IPv6 address, another address of the same host, ...); the server must @@ -238,12 +238,20 @@ A path spec is `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rtable=N]`: - `/priority=N` - scheduling priority, 0-255, lower is preferred (default 0). See [Path priority](#path-priority). The primary path's priority is `--primary-priority` (default 0). +- `/rate=RATE` - send on the path at a fixed rate (bits per second, e.g. + `48M`) instead of under congestion control, for a link of known, dedicated + capacity. See [Fixed-rate paths](#fixed-rate-paths). The primary path's is + `--primary-rate`. - `/rtable=N` - OpenBSD only: send the path through routing table `N` (rtable(4)). See [Routing tables](#routing-tables-openbsd). The primary path (`--proxy-addr`, or the resolved endpoint host) is the handshake path, path 0 (path IDs are never reused: a re-opened path gets a new -one). +one). If it gets no answer within 3 s, the client tries the handshake on the +extra paths' proxy addresses instead, in priority order (`/backup` paths +last; only paths without `@LOCAL_IP`, to another remote than the primary), so +the tunnel comes up even while the primary link is down; the primary path then +joins once it works. Extra paths are opened once the tunnel is up. They, and the primary path, are re-opened whenever they fail or are abandoned (quick retries backing off to every 5 s), so a flapping uplink rejoins automatically. Every path has its own @@ -293,6 +301,58 @@ hold-back off. Each side's flag governs what it sends. Paths with equal priority always share traffic, and `/backup` paths still only carry traffic when no non-backup path is usable. +#### Fixed-rate paths + +A link of known capacity that nothing else shares (a dedicated line) needs no +congestion control: `/rate=RATE` (or `--primary-rate` for the primary path) +sends on it at that fixed rate. Continuing the example above, with A a +dedicated 50 Mbit/s line: + +``` +rapidmasque client ... \ + --proxy-addr 203.0.113.7:4433 --primary-rate 48M \ + --path '198.51.100.9:4433/priority=1' +rapidmasque serve ... --max-path-rate 100M +``` + +- A then runs at a steady 48 Mbit/s: BBRv3 would keep probing above the line + rate and periodically cut its window to re-measure the RTT, and each probe + or cut moves traffic onto B. Set the rate a little below the line rate to + leave room for IP/UDP headers. +- Spill-over to B starts exactly when more than the fixed rate is offered + (the spill threshold applies as above), and stops when it is not. +- If A goes down, its window (about two round trips' worth at the fixed rate) + fills within a round trip and traffic moves to B right away, as it would + for a congestion-controlled path. Loss on A is not a congestion signal and + never slows it down. +- The rate applies in both directions: the client announces it to the proxy, + which applies it to what it sends on the path up to its `--max-path-rate` + (requests above it are capped). Without `--max-path-rate` the proxy ignores + such requests, since a fixed-rate path sends without congestion control. +- `/stats` shows each path's `fixed_rate_bps`. + +#### In-order delivery + +When traffic spills from a fast path onto a slower one (or a path with more +delay), datagrams of one flow arrive out of order. TCP inside the tunnel +(inside WireGuard, which passes reordering through) takes that as loss: +duplicate ACKs, spurious retransmissions and a lower sending rate. So by +default both ends deliver each flow's datagrams in order: + +- The client asks for it on each flow (a `rapidmasque-sequence` request + header) and a rapidmasque proxy agrees; both then number the datagrams they + send (a rapidmasque HTTP datagram context, 4 bytes per datagram). Other + MASQUE peers never agree, and the flow uses plain RFC 9298 datagrams. +- The receiver holds a datagram that arrives ahead of a gap until the gap + fills, or for a hold time after which it gives up on the missing one and + releases what it has, in order. The hold time follows how late datagrams + that fill a gap actually arrive (plus a quarter, up to 250 ms), and decays + while nothing arrives out of order; it starts at 10 ms. +- Datagrams that come in order are never held, so a flow on one path pays + nothing beyond the 4 bytes; a genuinely lost datagram delays the ones after + it by up to the hold time. +- `--in-order-delivery false` on the client turns it off for its flows. + #### Automatic path ranking The client ranks paths by measured loss by default (`--path-ranking auto`; @@ -535,7 +595,8 @@ pull request and publishes the report in the job summary. - `src/quic.rs` - noq transport config (multipath, idle/keepalive) + BoringSSL context setup, ECH install hooks. - `src/cc.rs` - congestion control choice: BBRv3 (default) or the no-op - controller. + controller, and the fixed-rate controller of `/rate=RATE` paths. +- `src/reorder.rs` - in-order delivery of a flow's sequenced datagrams. - `src/tls/` - BoringSSL as noq's TLS provider: the QUIC handshake session (`session.rs`) and packet/header protection with the multipath nonce (`keys.rs`). @@ -554,7 +615,9 @@ The client never exits: it redials the proxy indefinitely with capped exponential backoff (100 ms → 5 s), so a server restart, a dropped NAT mapping, or any transient failure recovers automatically. The local listen socket stays bound across reconnects, and flows reopen lazily as local datagrams arrive (apps -retransmit lost UDP and self-heal). A 1 s keepalive (ack-eliciting) on every +retransmit lost UDP and self-heal). With extra paths, a dial whose primary +path does not answer within 3 s falls back to the extra paths' proxy +addresses. A 1 s keepalive (ack-eliciting) on every path keeps idle NAT mappings warm and makes a dead path detectable within the 10 s idle timeout; with multipath, losing one path does not drop the tunnel. @@ -588,18 +651,19 @@ Measured over an emulated 270 ms RTT path, this takes a 2000 pkt/s (~19 Mbit/s) flow from ~40–60 % loss (erratic) to a stable ~3 %. Also keep the tunnelled interface's MTU low enough that an inner packet plus encapsulation fits one QUIC DATAGRAM (these cannot fragment). By default, QUIC packets start at exactly -1352 bytes of UDP payload, which leaves the 1314 bytes of datagram room that a +1356 bytes of UDP payload, which leaves the 1318 bytes of datagram room that a 1280-MTU inner tunnel such as WireGuard needs from the first packet; DPLPMTUD -can raise this to 1452 bytes, but it never drops below 1352 (black-hole +can raise this to 1452 bytes, but it never drops below 1356 (black-hole detection does not shrink it). The client<->proxy path must therefore carry -1380-byte IPv4 (1400-byte IPv6) packets; on a path that cannot, full-size +1384-byte IPv4 (1404-byte IPv6) packets; on a path that cannot, full-size packets are lost rather than the tunnel quietly narrowing below what a -1280-MTU inner tunnel needs. (The 1314 bytes assume the 8-byte connection IDs +1280-MTU inner tunnel needs, sequence number included (see in-order +delivery below). (The 1318 bytes assume the 8-byte connection IDs rapidmasque peers use; against a server issuing longer CIDs there is less room.) Use `--min-mtu BYTES` on `serve` and/or `client` to override the initial and -minimum QUIC packet size for what that side sends (default 1352, minimum +minimum QUIC packet size for what that side sends (default 1356, minimum 1200). The value counts UDP payload bytes, excluding IP and UDP headers. For example, `--min-mtu 1200` supports smaller outer paths, but may require a smaller tunnelled interface MTU until discovery finds more room. Discovery diff --git a/src/cc.rs b/src/cc.rs index f798c9b..817c0a7 100644 --- a/src/cc.rs +++ b/src/cc.rs @@ -17,9 +17,9 @@ use std::any::Any; use std::sync::Arc; -use std::time::Instant; +use std::time::{Duration, Instant}; -use noq::congestion::{Bbr3Config, Controller, ControllerFactory}; +use noq::congestion::{Bbr3Config, Controller, ControllerFactory, ControllerMetrics}; /// Window reported by [`NoCongestionControl`]. Above `u32::MAX`, noq's pacer /// never delays; kept well below `u64::MAX` so `in_flight + n` cannot overflow. @@ -96,10 +96,206 @@ impl ControllerFactory for NoCongestionControl { } } +/// A fixed-rate controller for a path of known, dedicated capacity +/// (`--path .../rate=RATE`, `--primary-rate`). +/// +/// It paces at the configured rate and never probes for more or backs off on +/// loss, so on a link that is not shared the path runs at a steady rate, and +/// the multipath scheduler knows exactly what the path can take: once more +/// than that is queued, traffic spills onto less preferred paths. Its window +/// still bounds what is in flight to about two round trips at that rate +/// (`WINDOW_RTTS`), so when the link goes down and acknowledgements stop, the +/// path fills its window within a round trip and the scheduler moves traffic +/// to the other paths, as it would for a congestion-controlled path. After +/// persistent congestion (every packet over several round trips lost) the +/// window drops to its minimum until something is acknowledged again. +#[derive(Clone, Debug)] +pub struct FixedRate { + /// Pacing rate, bytes per second of QUIC packets (UDP payload). + rate: u64, + mtu: u16, + min_rtt: Option, + collapsed: bool, +} + +/// In-flight bound, in round trips at the fixed rate. +const WINDOW_RTTS: u32 = 2; +/// Round-trip time assumed for the window until the path has a sample. +const FIXED_RATE_INITIAL_RTT: Duration = Duration::from_millis(100); +/// The window is never smaller than the fixed rate times this... +const FIXED_RATE_MIN_WINDOW_TIME: Duration = Duration::from_millis(20); +/// ...or this many full-size packets. +const FIXED_RATE_MIN_WINDOW_PACKETS: u64 = 4; + +impl FixedRate { + /// A controller pacing at `bits_per_second` (of UDP payload). + pub fn new(bits_per_second: u64, mtu: u16) -> Self { + Self { + rate: (bits_per_second / 8).max(1), + mtu, + min_rtt: None, + collapsed: false, + } + } + + fn min_window(&self) -> u64 { + FIXED_RATE_MIN_WINDOW_PACKETS * u64::from(self.mtu) + } +} + +impl Controller for FixedRate { + fn on_ack( + &mut self, + _now: Instant, + _sent: Instant, + _bytes: u64, + _pn: u64, + _app_limited: bool, + rtt: &noq_proto::RttEstimator, + ) { + self.min_rtt = Some(rtt.min()); + self.collapsed = false; + } + + /// Loss on a dedicated link is not a congestion signal; only persistent + /// congestion (the link is gone) shrinks the window. + fn on_congestion_event( + &mut self, + _now: Instant, + _sent: Instant, + is_persistent_congestion: bool, + _is_ecn: bool, + _lost_bytes: u64, + _largest_lost_pn: u64, + ) { + if is_persistent_congestion { + self.collapsed = true; + } + } + + fn on_mtu_update(&mut self, new_mtu: u16) { + self.mtu = new_mtu; + } + + fn window(&self) -> u64 { + if self.collapsed { + return self.min_window(); + } + let rtt = self.min_rtt.unwrap_or(FIXED_RATE_INITIAL_RTT) * WINDOW_RTTS; + let bytes_in = |d: Duration| (self.rate as f64 * d.as_secs_f64()) as u64; + bytes_in(rtt) + .max(bytes_in(FIXED_RATE_MIN_WINDOW_TIME)) + .max(self.min_window()) + } + + fn metrics(&self) -> ControllerMetrics { + let mut metrics = ControllerMetrics::default(); + metrics.congestion_window = self.window(); + metrics.pacing_rate = Some(self.rate); + metrics + } + + fn clone_box(&self) -> Box { + Box::new(self.clone()) + } + + fn initial_window(&self) -> u64 { + self.window() + } + + fn into_any(self: Box) -> Box { + self + } +} + +/// Builds [`FixedRate`] controllers for one path. +#[derive(Clone, Copy, Debug)] +pub struct FixedRateFactory { + /// Bits per second. + pub rate: u64, +} + +impl ControllerFactory for FixedRateFactory { + fn build(self: Arc, _now: Instant, current_mtu: u16) -> Box { + Box::new(FixedRate::new(self.rate, current_mtu)) + } +} + +/// Parse a rate in bits per second: a number with an optional decimal +/// `k`/`M`/`G` suffix (`50M` = 50,000,000), optionally followed by `bit/s` or +/// `bps`. +pub fn parse_rate(s: &str) -> Result { + let t = s.trim(); + let t = t + .strip_suffix("bit/s") + .or_else(|| t.strip_suffix("bps")) + .unwrap_or(t); + let (number, scale) = match t.char_indices().last() { + Some((i, 'k' | 'K')) => (&t[..i], 1e3), + Some((i, 'm' | 'M')) => (&t[..i], 1e6), + Some((i, 'g' | 'G')) => (&t[..i], 1e9), + _ => (t, 1.0), + }; + let value: f64 = number + .parse() + .map_err(|_| format!("invalid rate {s:?} (e.g. 48M, 500k, 1.5G)"))?; + let bits = value * scale; + if !(1000.0..1e15).contains(&bits) { + return Err(format!("rate {s:?} out of range (1k to 999T bit/s)")); + } + Ok(bits as u64) +} + +/// Format a rate in bits per second the way [`parse_rate`] reads it. +pub fn format_rate(bits: u64) -> String { + let (value, suffix) = if bits >= 1_000_000_000 && bits.is_multiple_of(1_000_000) { + (bits as f64 / 1e9, "G") + } else if bits >= 1_000_000 && bits.is_multiple_of(1_000) { + (bits as f64 / 1e6, "M") + } else if bits >= 1_000 { + (bits as f64 / 1e3, "k") + } else { + (bits as f64, "") + }; + format!("{value}{suffix}") +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn rates_parse_and_format() { + assert_eq!(parse_rate("48M"), Ok(48_000_000)); + assert_eq!(parse_rate("1.5G"), Ok(1_500_000_000)); + assert_eq!(parse_rate("500k"), Ok(500_000)); + assert_eq!(parse_rate("50Mbit/s"), Ok(50_000_000)); + assert_eq!(parse_rate("2000000"), Ok(2_000_000)); + assert!(parse_rate("fast").is_err()); + assert!(parse_rate("0").is_err()); + assert!(parse_rate("-5M").is_err()); + for bits in [48_000_000, 1_500_000_000, 500_000, 2_500, 1_000_000_000] { + assert_eq!(parse_rate(&format_rate(bits)), Ok(bits)); + } + assert_eq!(format_rate(48_000_000), "48M"); + } + + #[test] + fn fixed_rate_paces_and_bounds_the_window() { + let now = Instant::now(); + // 48 Mbit/s = 6 MB/s. + let mut cc = Arc::new(FixedRateFactory { rate: 48_000_000 }).build(now, 1400); + assert_eq!(cc.metrics().pacing_rate, Some(6_000_000)); + // Before an RTT sample: two 100 ms round trips. + assert_eq!(cc.window(), 1_200_000); + // Loss does not shrink it... + cc.on_congestion_event(now, now, false, false, 1400, 1); + assert_eq!(cc.window(), 1_200_000); + // ...persistent congestion does, until an acknowledgement. + cc.on_congestion_event(now, now, true, false, 1400, 2); + assert_eq!(cc.window(), 4 * 1400); + } + #[test] fn bbr3_initial_window_is_configurable() { let now = Instant::now(); diff --git a/src/cli.rs b/src/cli.rs index be0e237..c5d0767 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -63,6 +63,14 @@ pub struct ServeArgs { #[command(flatten)] pub transport: TransportArgs, + /// Largest fixed sending rate a client may ask for on a path + /// (`--path .../rate=RATE`, `--primary-rate` on the client), in bits per + /// second (e.g. `100M`); larger requests are capped to it. A fixed-rate + /// path is sent on without congestion control, so without this option + /// such requests are ignored and every path stays congestion-controlled. + #[arg(long, value_name = "RATE", value_parser = crate::cc::parse_rate)] + pub max_path_rate: Option, + /// Serve a JSON stats snapshot (connections, multipath paths, priorities, /// ranking, RTT, loss, traffic) over plain HTTP at `http://ADDR/stats`. /// Off by default. No TLS or authentication and it reveals peer @@ -92,17 +100,23 @@ pub struct ClientArgs { pub proxy_addr: Option, /// Open an additional QUIC multipath path, as - /// `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rtable=N]`. `REMOTE` is a proxy + /// `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rate=RATE][/rtable=N]`. `REMOTE` is a proxy /// address (it may differ from the primary one), `LOCAL_IP` pins the /// path's source address (e.g. a second uplink's address), and `/backup` /// makes it a standby path used only when no primary path works. /// `/priority=N` (0-255, default 0, lower is preferred) orders usable /// paths in both directions: traffic fills the preferred path first and /// spills onto the next ones (see `--path-spill-threshold-ms`); equal - /// priorities share traffic. `/rtable=N` (OpenBSD) sends the path through + /// priorities share traffic. `/rate=RATE` (bits per second, e.g. `48M`) + /// sends on the path at that fixed rate instead of under congestion + /// control, in both directions (the proxy needs `--max-path-rate`): for a + /// link of known, dedicated capacity, set a little below it to leave room + /// for IP/UDP headers. `/rtable=N` (OpenBSD) sends the path through /// routing table N (rtable(4)); such a path needs a remote, or remote and /// `@LOCAL_IP`, that no other path uses. Repeatable. Paths that fail are - /// retried while the tunnel is up. + /// retried while the tunnel is up. If the primary path cannot complete + /// the handshake, the client tries these paths' proxy addresses in + /// priority order. #[arg(long = "path", value_name = "SPEC")] pub paths: Vec, @@ -111,6 +125,20 @@ pub struct ClientArgs { #[arg(long, value_name = "N", default_value_t = 0)] pub primary_priority: u8, + /// Fixed sending rate for the primary path, in the same terms as + /// `--path .../rate=RATE`. + #[arg(long, value_name = "RATE", value_parser = crate::cc::parse_rate)] + pub primary_rate: Option, + + /// Deliver each flow's datagrams in order: datagrams that overtake others + /// (e.g. while traffic spills across paths with different delays) wait + /// for the ones before them, up to a hold time that follows the observed + /// reordering (at most 250 ms). Needs a rapidmasque proxy on the other + /// end and costs 4 bytes per datagram; the proxy does the same for its + /// replies. `false` sends plain RFC 9298 datagrams. + #[arg(long, value_name = "BOOL", default_value_t = true, action = clap::ArgAction::Set)] + pub in_order_delivery: bool, + /// OpenBSD routing table (rtable(4)) for the primary path and every /// `--path` without its own `/rtable=N`. Defaults to the process's table /// (see `route -T N exec`). diff --git a/src/client.rs b/src/client.rs index 2ae829d..2a11fbd 100644 --- a/src/client.rs +++ b/src/client.rs @@ -27,6 +27,7 @@ use crate::endpoint::Endpoint as ProxyEndpoint; use crate::h3::{self, FrameReader}; use crate::quic::{self, CAPSULE_PROTOCOL_TRUE, TransportOptions, Verify, send_datagram}; use crate::ranking::{self, PathPriorities, PathRanking, RankingConfig}; +use crate::reorder::Reorder; use crate::routed_socket; use crate::stats; use crate::tls::HandshakeData; @@ -49,9 +50,13 @@ const PATH_WARN_AFTER: u32 = 3; /// How long the primary path's maintainer waits for the handshake path to /// learn its source address (see [`primary_path_spec`]). const PRIMARY_LOCAL_IP_WAIT: Duration = Duration::from_secs(5); +/// How long a handshake path gets before the client tries the next candidate +/// (see [`handshake_candidates`]); the last candidate gets the full handshake +/// timeout. +const HANDSHAKE_FALLBACK_AFTER: Duration = Duration::from_secs(3); /// An extra multipath path: -/// `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rtable=N]`. +/// `REMOTE_IP:PORT[@LOCAL_IP][/backup][/priority=N][/rate=RATE][/rtable=N]`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PathSpec { pub remote: SocketAddr, @@ -59,10 +64,27 @@ pub struct PathSpec { pub backup: bool, /// Scheduling priority, lower is preferred (noq `Path::set_priority`). pub priority: u8, + /// Fixed sending rate (bits per second) in place of congestion control, + /// for a link of known, dedicated capacity (`crate::cc::FixedRate`). + pub rate: Option, /// OpenBSD routing table to send this path's packets through. pub rtable: Option, } +impl PathSpec { + /// A path to `remote` with `priority` and no other options. + pub fn to(remote: SocketAddr, priority: u8) -> Self { + Self { + remote, + local_ip: None, + backup: false, + priority, + rate: None, + rtable: None, + } + } +} + impl FromStr for PathSpec { type Err = String; @@ -72,6 +94,7 @@ impl FromStr for PathSpec { let mut backup = false; let mut priority = 0; let mut rtable = None; + let mut rate = None; for option in options { if option == "backup" { backup = true; @@ -84,9 +107,12 @@ impl FromStr for PathSpec { n.parse() .map_err(|e| format!("bad routing table {n:?}: {e}"))?, ); + } else if let Some(r) = option.strip_prefix("rate=") { + rate = Some(crate::cc::parse_rate(r)?); } else { return Err(format!( - "unknown path option {option:?} (expected backup, priority=N or rtable=N)" + "unknown path option {option:?} (expected backup, priority=N, rate=RATE \ + or rtable=N)" )); } } @@ -106,6 +132,7 @@ impl FromStr for PathSpec { local_ip, backup, priority, + rate, rtable, }) } @@ -123,6 +150,9 @@ impl fmt::Display for PathSpec { if self.priority != 0 { write!(f, "/priority={}", self.priority)?; } + if let Some(rate) = self.rate { + write!(f, "/rate={}", crate::cc::format_rate(rate))?; + } if let Some(rtable) = self.rtable { write!(f, "/rtable={rtable}")?; } @@ -142,6 +172,11 @@ pub struct ConnectParams { pub paths: Vec, /// Scheduling priority of the primary path (only used with `paths`). pub primary_priority: u8, + /// Fixed sending rate of the primary path (bits per second). + pub primary_rate: Option, + /// Ask the proxy for sequenced datagrams and deliver each flow in order + /// (`crate::reorder`). + pub in_order_delivery: bool, /// OpenBSD routing table of the client's main socket: the primary path /// and every path without its own `rtable`. pub rtable: Option, @@ -211,6 +246,29 @@ struct Dialed { endpoint: Endpoint, conn: Connection, proxy_addr: SocketAddr, + /// Where the handshake went: `proxy_addr`, or an extra path's proxy + /// address if the primary path did not answer. + handshake_addr: SocketAddr, +} + +/// Proxy addresses to try the handshake on, in order: the primary, then the +/// extra paths' remotes by priority (`/backup` paths last). Only paths +/// without `@LOCAL_IP` qualify, and only remotes other than the primary's: a +/// handshake cannot pick its source address, and the path it creates must not +/// be mistaken for another configured path (see [`primary_path_spec`]). +fn handshake_candidates(proxy_addr: SocketAddr, paths: &[PathSpec]) -> Vec { + let mut extra: Vec<&PathSpec> = paths + .iter() + .filter(|spec| spec.local_ip.is_none() && spec.remote != proxy_addr) + .collect(); + extra.sort_by_key(|spec| (spec.backup, spec.priority)); + let mut out = vec![proxy_addr]; + for spec in extra { + if !out.contains(&spec.remote) { + out.push(spec.remote); + } + } + out } async fn dial(p: &ConnectParams) -> Result { @@ -252,17 +310,44 @@ async fn dial(p: &ConnectParams) -> Result { } .context("creating QUIC endpoint")?; - log::info!("connecting to proxy {proxy_addr} (sni={server_name})"); - let conn = endpoint - .connect_with(config, proxy_addr, &server_name) - .map_err(|e| anyhow!("connect: {e}"))? - .await - .context("QUIC handshake")?; - Ok(Dialed { - endpoint, - conn, - proxy_addr, - }) + let candidates = handshake_candidates(proxy_addr, &p.paths); + let mut failure = None; + for (i, &remote) in candidates.iter().enumerate() { + log::info!("connecting to proxy {remote} (sni={server_name})"); + let connecting = endpoint + .connect_with(config.clone(), remote, &server_name) + .map_err(|e| anyhow!("connect: {e}"))?; + let result = if i + 1 == candidates.len() { + Ok(connecting.await) + } else { + tokio::time::timeout(HANDSHAKE_FALLBACK_AFTER, connecting).await + }; + match result { + Ok(Ok(conn)) => { + if remote != proxy_addr { + log::warn!( + "primary path to {proxy_addr} unavailable; tunnel established over \ + {remote}" + ); + } + return Ok(Dialed { + endpoint, + conn, + proxy_addr, + handshake_addr: remote, + }); + } + Ok(Err(e)) => { + log::warn!("QUIC handshake via {remote} failed: {e}"); + failure = Some(anyhow!(e).context("QUIC handshake")); + } + Err(_) => log::warn!( + "QUIC handshake via {remote}: no answer within {HANDSHAKE_FALLBACK_AFTER:?}; \ + trying the next path" + ), + } + } + Err(failure.unwrap_or_else(|| anyhow!("QUIC handshake: no path answered"))) } /// One local source's flow state. @@ -278,6 +363,28 @@ struct FlowState { established: bool, /// Datagrams buffered until the flow is established. pending: Vec, + /// Sequence number of the next datagram, if the proxy agreed to numbered + /// datagrams. + next_seq: Option, +} + +impl FlowState { + /// `data` as an HTTP datagram for flow `fid`, numbered if agreed. + fn encode(&mut self, fid: u64, data: &[u8]) -> Bytes { + let seq = self.next_seq; + if let Some(seq) = seq { + self.next_seq = Some(seq.wrapping_add(1)); + } + dgram::encode_udp(fid, seq, data).into() + } +} + +/// A flow as seen by datagrams arriving from the proxy. +struct TunnelFlow { + /// The local source the flow belongs to. + src: SocketAddr, + /// Puts numbered datagrams back in order, once the first arrives. + reorder: Option, } /// Progress reports from per-flow request tasks to the session loop. @@ -290,6 +397,8 @@ enum FlowEvent { Accepted { src: SocketAddr, token: u64, + /// The proxy numbers its datagrams and accepts numbered ones. + sequenced: bool, }, Closed { src: SocketAddr, @@ -309,6 +418,7 @@ async fn run_session( endpoint, conn, proxy_addr, + handshake_addr, } = match dial(p).await { Ok(d) => d, Err(e) => { @@ -340,7 +450,12 @@ async fn run_session( } }; let priorities = Arc::new(PathPriorities::default()); - tokio::spawn(h3::serve_uni_streams(conn.clone(), priorities.clone())); + // The proxy never asks this end for fixed path rates. + tokio::spawn(h3::serve_uni_streams( + conn.clone(), + priorities.clone(), + None, + )); tokio::spawn(quic::log_path_events(conn.clone())); if !p.paths.is_empty() && p.path_ranking == PathRanking::Auto && conn.is_multipath_enabled() { // Rank what we send, and ask the proxy to rank what it sends. @@ -354,9 +469,16 @@ async fn run_session( // away) while extra paths carry the tunnel, re-open it once it works. tokio::spawn({ let (conn, control, priorities) = (conn.clone(), control.clone(), priorities.clone()); - let (paths, priority) = (p.paths.clone(), p.primary_priority); + let (paths, priority, rate) = (p.paths.clone(), p.primary_priority, p.primary_rate); async move { - let primary = primary_path_spec(&conn, proxy_addr, &paths, priority).await; + let mut primary = if handshake_addr == proxy_addr { + primary_path_spec(&conn, proxy_addr, &paths, priority).await + } else { + // The handshake went over an extra path (path 0 is that + // path), so the primary is opened like any other path. + PathSpec::to(proxy_addr, priority) + }; + primary.rate = rate; maintain_path(conn, primary, control, priorities).await } }); @@ -368,6 +490,13 @@ async fn run_session( priorities.clone(), )); } + } else if let Some(rate) = p.primary_rate { + // A single path: give it its fixed rate here. + if priorities.set_rate(&conn, PathId::ZERO, rate) + && let Err(e) = control.send_path_rate(PathId::ZERO, rate).await + { + log::warn!("announcing the primary path's rate failed: {e:#}"); + } } log::info!( "tunnel established (ech={ech}, multipath={})", @@ -378,7 +507,8 @@ async fn run_session( let path: Arc = p.endpoint.path.as_str().into(); let (ev_tx, mut ev_rx) = mpsc::unbounded_channel::(); let mut by_addr: HashMap = HashMap::new(); - let mut flows: HashMap = HashMap::new(); + let mut flows: HashMap = HashMap::new(); + let mut ready: Vec = Vec::new(); let mut next_token = 0u64; let flow_count = Arc::new(AtomicUsize::new(0)); let _stats = p.stats.as_ref().map(|registry| { @@ -389,6 +519,7 @@ async fn run_session( serde_json::json!({ "endpoint": p.endpoint.authority, "proxy_addr": proxy_addr.to_string(), + "handshake_addr": handshake_addr.to_string(), "ech": ech, }), move || flow_count.load(Ordering::Relaxed), @@ -414,6 +545,7 @@ async fn run_session( path.clone(), src, next_token, + p.in_order_delivery, ev_tx.clone(), )); FlowState { @@ -421,12 +553,13 @@ async fn run_session( flow_id: None, established: false, pending: Vec::new(), + next_seq: None, } }); match (st.established, st.flow_id) { (true, Some(fid)) => { log::debug!("-> tunnel flow {fid}: {} bytes", data.len()); - send_datagram(&conn, fid, dgram::encode(fid, &data).into(), "local"); + send_datagram(&conn, fid, st.encode(fid, &data), "local"); } _ => { if st.pending.len() < MAX_PENDING { @@ -437,25 +570,42 @@ async fn run_session( } } datagram = conn.read_datagram() => match datagram { - Ok(d) => route_tunnel_datagram(lsock, &flows, &d).await, + Ok(d) => { + if let Some(src) = take_tunnel_datagram(&mut flows, d, &mut ready) { + deliver_local(lsock, src, &mut ready).await; + } + } Err(e) => break e.to_string(), }, + _ = sleep_until_opt(next_reorder_deadline(&flows)) => { + let now = std::time::Instant::now(); + for flow in flows.values_mut() { + if let Some(reorder) = flow.reorder.as_mut() { + reorder.on_timeout(now, &mut ready); + } + deliver_local(lsock, flow.src, &mut ready).await; + } + }, Some(ev) = ev_rx.recv() => match ev { FlowEvent::Opened { src, token, flow_id } => { if let Some(st) = by_addr.get_mut(&src).filter(|st| st.token == token) { st.flow_id = Some(flow_id); - flows.insert(flow_id, src); + flows.insert(flow_id, TunnelFlow { src, reorder: None }); log::info!("opened flow {flow_id} for local {src}"); } } - FlowEvent::Accepted { src, token } => { + FlowEvent::Accepted { src, token, sequenced } => { if let Some(st) = by_addr.get_mut(&src).filter(|st| st.token == token) && let Some(fid) = st.flow_id { // The server has created the flow; release buffered data. st.established = true; + if sequenced { + st.next_seq = Some(0); + } for data in std::mem::take(&mut st.pending) { - send_datagram(&conn, fid, dgram::encode(fid, &data).into(), "local"); + let datagram = st.encode(fid, &data); + send_datagram(&conn, fid, datagram, "local"); } } } @@ -484,6 +634,7 @@ async fn open_flow( path: Arc, src: SocketAddr, token: u64, + in_order: bool, events: mpsc::UnboundedSender, ) { let closed = |events: &mpsc::UnboundedSender| { @@ -503,14 +654,18 @@ async fn open_flow( flow_id, }); - let request = h3::headers_frame(&[ + let mut fields = vec![ (":method", "CONNECT"), (":protocol", "connect-udp"), (":scheme", "https"), - (":authority", &authority), - (":path", &path), + (":authority", &*authority), + (":path", &*path), ("capsule-protocol", CAPSULE_PROTOCOL_TRUE), - ]); + ]; + if in_order { + fields.push((dgram::SEQUENCE_HEADER, dgram::SEQUENCE_HEADER_ON)); + } + let request = h3::headers_frame(&fields); if let Err(e) = send.write_all(&request).await { log::warn!("send_request for {src} failed: {e}"); return closed(&events); @@ -522,8 +677,15 @@ async fn open_flow( Ok(Some(fields)) => match h3::status_of(&fields) { Some(s) if (100..200).contains(&s) => continue, // interim Some(s) if (200..300).contains(&s) => { - log::debug!("flow {flow_id} accepted (status {s})"); - let _ = events.send(FlowEvent::Accepted { src, token }); + let sequenced = in_order + && h3::header(&fields, dgram::SEQUENCE_HEADER) + == Some(dgram::SEQUENCE_HEADER_ON.as_bytes()); + log::debug!("flow {flow_id} accepted (status {s}, in order: {sequenced})"); + let _ = events.send(FlowEvent::Accepted { + src, + token, + sequenced, + }); break; } status => { @@ -547,18 +709,51 @@ async fn open_flow( drop(send); } -/// Forward a tunnelled datagram back to the local source for its flow. -async fn route_tunnel_datagram(lsock: &UdpSocket, flows: &HashMap, d: &[u8]) { - let Some(p) = dgram::decode(d) else { - return; - }; - if p.context_id != dgram::CONTEXT_ID_UDP { - return; +/// Take in a datagram from the proxy: its flow's payloads that are now +/// deliverable, in order, are appended to `ready`. Returns the flow's local +/// source. +fn take_tunnel_datagram( + flows: &mut HashMap, + d: Bytes, + ready: &mut Vec, +) -> Option { + let p = dgram::decode(&d)?; + let (seq, payload) = dgram::udp_payload(&p)?; + let flow = flows.get_mut(&p.flow_id)?; + let payload = d.slice_ref(payload); + match seq { + Some(seq) => { + let now = std::time::Instant::now(); + flow.reorder + .get_or_insert_with(|| Reorder::new(now)) + .push(seq, payload, now, ready); + } + None => ready.push(payload), } - if let Some(src) = flows.get(&p.flow_id) - && let Err(e) = lsock.send_to(p.payload, *src).await - { - log::debug!("send to local {src} failed: {e}"); + Some(flow.src) +} + +/// Send `ready` payloads to local source `src`. +async fn deliver_local(lsock: &UdpSocket, src: SocketAddr, ready: &mut Vec) { + for payload in ready.drain(..) { + if let Err(e) = lsock.send_to(&payload, src).await { + log::debug!("send to local {src} failed: {e}"); + } + } +} + +/// The earliest time a flow gives up waiting for a missing datagram. +fn next_reorder_deadline(flows: &HashMap) -> Option { + flows + .values() + .filter_map(|flow| flow.reorder.as_ref()?.deadline()) + .min() +} + +async fn sleep_until_opt(deadline: Option) { + match deadline { + Some(d) => tokio::time::sleep_until(d.into()).await, + None => std::future::pending().await, } } @@ -632,11 +827,8 @@ pub(crate) async fn primary_path_spec( None }; PathSpec { - remote: proxy_addr, local_ip, - backup: false, - priority, - rtable: None, + ..PathSpec::to(proxy_addr, priority) } } @@ -676,6 +868,12 @@ pub(crate) async fn maintain_path( if let Err(e) = control.send_path_priority(path.id(), spec.priority).await { log::debug!("multipath path {spec}: announcing priority: {e:#}"); } + if let Some(rate) = spec.rate + && priorities.set_rate(&conn, path.id(), rate) + && let Err(e) = control.send_path_rate(path.id(), rate).await + { + log::debug!("multipath path {spec}: announcing rate: {e:#}"); + } } failures = 0; delay = PATH_RETRY_MIN; diff --git a/src/dgram.rs b/src/dgram.rs index 55487ac..8030927 100644 --- a/src/dgram.rs +++ b/src/dgram.rs @@ -8,12 +8,28 @@ //! ``` //! //! The quarter-stream-id is `request_stream_id / 4` (RFC 9297 §2.1). Context-ID -//! `0` denotes a raw UDP payload (RFC 9298 §5); other contexts are reserved and +//! `0` denotes a raw UDP payload (RFC 9298 §5). +//! +//! rapidmasque extension: context ID [`CONTEXT_ID_SEQUENCED_UDP`] is a UDP +//! payload preceded by a 4-byte big-endian sequence number, per flow and +//! direction, so the receiver can put datagrams that took different paths +//! back in order (`crate::reorder`). A flow uses it only when both ends agreed +//! to on the request (the `rapidmasque-sequence` header); other contexts are //! dropped. use crate::varint; pub const CONTEXT_ID_UDP: u64 = 0; +/// Sequenced UDP payload (rapidmasque extension, client-allocated even ID). +pub const CONTEXT_ID_SEQUENCED_UDP: u64 = 2; +/// Bytes the sequence number adds to a datagram. +pub const SEQUENCE_LEN: usize = 4; +/// Request and response header that turns sequenced datagrams on for a flow: +/// a client that wants them sends it, and a proxy that agrees echoes it in its +/// 2xx response. Each end then numbers what it sends. +pub const SEQUENCE_HEADER: &str = "rapidmasque-sequence"; +/// [`SEQUENCE_HEADER`]'s value (a structured-field boolean). +pub const SEQUENCE_HEADER_ON: &str = "?1"; /// Encode a UDP payload as a CONNECT-UDP HTTP datagram for `flow_id`. pub fn encode(flow_id: u64, udp_payload: &[u8]) -> Vec { @@ -24,6 +40,39 @@ pub fn encode(flow_id: u64, udp_payload: &[u8]) -> Vec { out } +/// Encode a UDP payload for `flow_id` with sequence number `seq` +/// ([`CONTEXT_ID_SEQUENCED_UDP`]). +pub fn encode_sequenced(flow_id: u64, seq: u32, udp_payload: &[u8]) -> Vec { + let mut out = + Vec::with_capacity(varint::encoded_len(flow_id) + 1 + SEQUENCE_LEN + udp_payload.len()); + varint::encode(flow_id, &mut out); + varint::encode(CONTEXT_ID_SEQUENCED_UDP, &mut out); + out.extend_from_slice(&seq.to_be_bytes()); + out.extend_from_slice(udp_payload); + out +} + +/// Encode a UDP payload for `flow_id`, sequenced if `seq` is given. +pub fn encode_udp(flow_id: u64, seq: Option, udp_payload: &[u8]) -> Vec { + match seq { + Some(seq) => encode_sequenced(flow_id, seq, udp_payload), + None => encode(flow_id, udp_payload), + } +} + +/// A received UDP payload and its sequence number, if it carried one; `None` +/// for contexts other than UDP and sequenced UDP. +pub fn udp_payload<'a>(parsed: &Parsed<'a>) -> Option<(Option, &'a [u8])> { + match parsed.context_id { + CONTEXT_ID_UDP => Some((None, parsed.payload)), + CONTEXT_ID_SEQUENCED_UDP => { + let (seq, payload) = parsed.payload.split_first_chunk::()?; + Some((Some(u32::from_be_bytes(*seq)), payload)) + } + _ => None, + } +} + /// Parsed view of a received HTTP datagram. pub struct Parsed<'a> { pub flow_id: u64, @@ -55,6 +104,22 @@ mod tests { assert_eq!(p.payload, b"hello"); } + #[test] + fn sequenced_roundtrip() { + let d = encode_udp(9, Some(0xdead_beef), b"wg"); + assert_eq!(d.len(), 1 + 1 + SEQUENCE_LEN + 2); + let p = decode(&d).unwrap(); + assert_eq!(p.flow_id, 9); + assert_eq!(p.context_id, CONTEXT_ID_SEQUENCED_UDP); + assert_eq!(udp_payload(&p), Some((Some(0xdead_beef), &b"wg"[..]))); + // Plain UDP has no sequence number. + let d = encode_udp(9, None, b"wg"); + assert_eq!(udp_payload(&decode(&d).unwrap()), Some((None, &b"wg"[..]))); + // Truncated sequence numbers and unknown contexts are dropped. + assert_eq!(udp_payload(&decode(&[9, 2, 0, 0]).unwrap()), None); + assert_eq!(udp_payload(&decode(&[9, 4, 1]).unwrap()), None); + } + #[test] fn nonzero_flow_and_context() { let d = encode(7, b"x"); diff --git a/src/e2e_test.rs b/src/e2e_test.rs index dad54ae..0a08551 100644 --- a/src/e2e_test.rs +++ b/src/e2e_test.rs @@ -271,7 +271,11 @@ async fn path_priorities_apply_on_both_ends() { tokio::spawn(async move { let conn = server.accept().await.unwrap().await.unwrap(); let _control = h3::open_control(&conn).await.unwrap(); - tokio::spawn(h3::serve_uni_streams(conn.clone(), Default::default())); + tokio::spawn(h3::serve_uni_streams( + conn.clone(), + Default::default(), + None, + )); let _ = server_tx.send(conn.clone()); conn.closed().await; }); @@ -389,7 +393,7 @@ async fn lossy_path_is_demoted_and_recovers_on_both_ends() { let priorities = Arc::new(PathPriorities::default()); ranking::start(conn.clone(), priorities.clone(), config); let _control = h3::open_control(&conn).await.unwrap(); - tokio::spawn(h3::serve_uni_streams(conn.clone(), priorities)); + tokio::spawn(h3::serve_uni_streams(conn.clone(), priorities, None)); let _ = server_tx.send(conn.clone()); while let Ok(d) = conn.read_datagram().await { let _ = conn.send_datagram(d); @@ -750,10 +754,62 @@ struct Tunnel { /// connections in stats registries. async fn start_tunnel( fx: &Fixture, - paths: impl FnOnce(SocketAddr) -> Vec, + paths: impl FnOnce(SocketAddr) -> Vec + 'static, server_stats: Option>, client_stats: Option>, ) -> Tunnel { + start_tunnel_with( + fx, + TunnelConfig { + paths: Box::new(paths), + server_stats, + client_stats, + ..Default::default() + }, + ) + .await +} + +type BoxFuture = std::pin::Pin + Send>>; + +/// Options for [`start_tunnel_with`]. +struct TunnelConfig { + /// Extra paths, given the server's address. + paths: Box Vec>, + server_stats: Option>, + client_stats: Option>, + /// The client's primary path goes here instead of to the server, given + /// the server's address (e.g. a relay in front of it). + primary_via: Option BoxFuture>>, + primary_rate: Option, + max_path_rate: Option, + in_order_delivery: bool, +} + +impl Default for TunnelConfig { + fn default() -> Self { + Self { + paths: Box::new(|_| Vec::new()), + server_stats: None, + client_stats: None, + primary_via: None, + primary_rate: None, + max_path_rate: None, + in_order_delivery: true, + } + } +} + +async fn start_tunnel_with(fx: &Fixture, cfg: TunnelConfig) -> Tunnel { + let TunnelConfig { + paths, + server_stats, + client_stats, + primary_via, + primary_rate, + max_path_rate, + in_order_delivery, + } = cfg; let target = udp_echo().await; // Server: bind first to learn the port the rule's authority must carry. @@ -784,6 +840,7 @@ async fn start_tunnel( let state = Arc::new(ServerState { rules: ArcSwap::from_pointee(rules), stats: server_stats, + max_path_rate, }); tokio::spawn(server::run(endpoint, state)); @@ -791,7 +848,11 @@ async fn start_tunnel( let s = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); s.local_addr().unwrap() }; - let proxy_addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap(); + let server_addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap(); + let proxy_addr = match primary_via { + Some(via) => via(server_addr).await, + None => server_addr, + }; let opts = ProxyOptions { conn: ConnectParams { endpoint: ProxyEndpoint::parse(&format!("https://{HOST}:{port}/connect")).unwrap(), @@ -800,8 +861,10 @@ async fn start_tunnel( ca_file: Some(fx.cert.clone()), }, ech_config_list: Some(fx.ech_list.clone()), - paths: paths(proxy_addr), + paths: paths(server_addr), primary_priority: 0, + primary_rate, + in_order_delivery, rtable: None, path_ranking: Default::default(), stats: client_stats, @@ -994,9 +1057,9 @@ async fn no_congestion_control_never_limits_any_path() { } } -/// A WireGuard tunnel with MTU 1280 needs 1314-byte HTTP datagrams (1280-byte +/// A WireGuard tunnel with MTU 1280 needs 1318-byte HTTP datagrams (1280-byte /// inner packet + 32 bytes of WireGuard framing + 2 bytes of flow/context -/// prefix). That must fit from the first packet, not only once DPLPMTUD has +/// prefix + 4 bytes of sequence number). That must fit from the first packet, not only once DPLPMTUD has /// probed the path. #[tokio::test(flavor = "multi_thread")] async fn wireguard_1280_fits_right_after_handshake() { @@ -1088,3 +1151,180 @@ async fn idle_extra_path_stays_up_and_fits_wireguard() { "datagram room {room} with two paths" ); } + +/// With the primary proxy address dead, the client completes the handshake +/// over an extra path's proxy address and the tunnel works. +#[tokio::test(flavor = "multi_thread")] +async fn handshake_falls_back_to_an_extra_path() { + let fx = Fixture::new("fallback"); + // A bound socket nobody reads: the primary path's handshake gets no answer. + let blackhole = std::net::UdpSocket::bind("127.0.0.4:0").unwrap(); + let dead = blackhole.local_addr().unwrap(); + let tunnel = start_tunnel_with( + &fx, + TunnelConfig { + paths: Box::new(|server| vec![format!("{server}/priority=1").parse().unwrap()]), + primary_via: Some(Box::new(move |_| Box::pin(async move { dead }))), + ..Default::default() + }, + ) + .await; + // The fallback waits 3 s for the primary; roundtrip() keeps trying for 10. + tunnel.roundtrip().await; + drop(blackhole); +} + +/// The fixed-rate window for `rate` bits per second on a loopback path: the +/// 20 ms floor dominates two loopback round trips and four packets. +fn fixed_rate_window(rate: u64) -> u64 { + rate / 8 / 50 +} + +/// The first path's `field` in a stats registry's only connection. +fn first_path_stat(registry: &stats::Registry, field: &str) -> serde_json::Value { + registry.snapshot()["connections"][0]["paths"][0][field].clone() +} + +/// `--primary-rate` sends the primary path at a fixed rate on the client, and +/// on the proxy too, capped to its `--max-path-rate`. +#[tokio::test(flavor = "multi_thread")] +async fn fixed_rate_path_applies_on_both_ends_up_to_the_proxy_cap() { + let fx = Fixture::new("fixed-rate"); + let (server_stats, client_stats) = ( + stats::Registry::new("server"), + stats::Registry::new("client"), + ); + let tunnel = start_tunnel_with( + &fx, + TunnelConfig { + server_stats: Some(server_stats.clone()), + client_stats: Some(client_stats.clone()), + primary_rate: Some(8_000_000), + max_path_rate: Some(4_000_000), + ..Default::default() + }, + ) + .await; + tunnel.roundtrip().await; + + let expected = [(&client_stats, 8_000_000u64), (&server_stats, 4_000_000u64)]; + for _ in 0..50 { + let done = expected.iter().all(|(registry, rate)| { + first_path_stat(registry, "fixed_rate_bps") == *rate + && first_path_stat(registry, "cwnd") == fixed_rate_window(*rate) + }); + if done { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!( + "client path {:?}, server path {:?}", + client_stats.snapshot()["connections"][0]["paths"][0], + server_stats.snapshot()["connections"][0]["paths"][0] + ); +} + +/// A relay in front of `upstream` that swaps every two consecutive packets +/// from `upstream` (a held packet goes out after 5 ms without a successor). +async fn swapping_relay(upstream: SocketAddr) -> SocketAddr { + let sock = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let addr = sock.local_addr().unwrap(); + tokio::spawn(async move { + let mut buf = vec![0u8; 2048]; + let mut client = None; + let mut held: Option> = None; + loop { + let received = if held.is_some() { + match tokio::time::timeout(Duration::from_millis(5), sock.recv_from(&mut buf)).await + { + Ok(r) => r, + Err(_) => { + if let (Some(packet), Some(c)) = (held.take(), client) { + let _ = sock.send_to(&packet, c).await; + } + continue; + } + } + } else { + sock.recv_from(&mut buf).await + }; + let Ok((n, from)) = received else { return }; + if from != upstream { + client = Some(from); + let _ = sock.send_to(&buf[..n], upstream).await; + continue; + } + let Some(c) = client else { continue }; + match held.take() { + None => held = Some(buf[..n].to_vec()), + Some(first) => { + let _ = sock.send_to(&buf[..n], c).await; + let _ = sock.send_to(&first, c).await; + } + } + } + }); + addr +} + +/// Send `count` numbered datagrams through the tunnel, paced 2 ms apart, and +/// return the order their echoes came back in. +async fn echo_order(tunnel: &Tunnel, count: u32) -> Vec { + let app = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let sender = { + let (app, listen) = (app.clone(), tunnel.listen); + tokio::spawn(async move { + for i in 0..count { + let mut payload = i.to_be_bytes().to_vec(); + payload.resize(1000, 0); + app.send_to(&payload, listen).await.unwrap(); + tokio::time::sleep(Duration::from_millis(2)).await; + } + }) + }; + let mut order = Vec::new(); + let mut buf = vec![0u8; 2048]; + while let Ok(Ok(n)) = tokio::time::timeout(Duration::from_millis(500), app.recv(&mut buf)).await + { + assert!(n >= 9 && buf.starts_with(b"echo:")); + order.push(u32::from_be_bytes(buf[5..9].try_into().unwrap())); + } + sender.await.unwrap(); + order +} + +/// Datagrams reordered on the way back arrive in order with in-order delivery +/// (the default), and out of order without it. +#[tokio::test(flavor = "multi_thread")] +async fn in_order_delivery_undoes_reordering() { + let fx = Fixture::new("in-order"); + let mut inversions = Vec::new(); + for in_order_delivery in [true, false] { + let tunnel = start_tunnel_with( + &fx, + TunnelConfig { + primary_via: Some(Box::new(|server| Box::pin(swapping_relay(server)))), + in_order_delivery, + ..Default::default() + }, + ) + .await; + tunnel.roundtrip().await; + // Warm up: the hold time learns how late the relay's swaps are. + echo_order(&tunnel, 50).await; + let order = echo_order(&tunnel, 200).await; + assert!(order.len() >= 190, "{} of 200 echoes", order.len()); + inversions.push(order.windows(2).filter(|w| w[1] < w[0]).count()); + } + // A swap delayed beyond the learned hold time (a busy test machine) is + // still delivered, late; allow a couple. + assert!( + inversions[0] <= 2, + "reordered with in-order delivery: {inversions:?}" + ); + assert!( + inversions[1] > 20, + "the relay did not reorder: {inversions:?}" + ); +} diff --git a/src/h3.rs b/src/h3.rs index 312ce71..69b3f68 100644 --- a/src/h3.rs +++ b/src/h3.rs @@ -10,8 +10,9 @@ //! //! Two extensions on the control stream: the client announces its multipath //! path priorities ([`FRAME_PATH_PRIORITY`]) so the proxy prefers the same -//! paths for the return direction, and asks the proxy to rank paths by loss -//! too ([`FRAME_PATH_RANKING`]). +//! paths for the return direction, asks the proxy to rank paths by loss too +//! ([`FRAME_PATH_RANKING`]), and announces paths that send at a fixed rate +//! ([`FRAME_PATH_RATE`]). use std::sync::Arc; @@ -39,6 +40,12 @@ pub const FRAME_PATH_PRIORITY: u64 = 0x726d_7070; /// Payload: mode varint, 1 = auto. "rmpr" in ASCII. pub const FRAME_PATH_RANKING: u64 = 0x726d_7072; const PATH_RANKING_AUTO: u64 = 1; +/// rapidmasque extension frame on the control stream: send on one multipath +/// path at a fixed rate instead of under congestion control (`/rate=RATE`, +/// `crate::cc::FixedRate`), so the peer does the same for what it sends on the +/// path. Payload: path ID varint, rate varint (bits per second). A proxy only +/// honours it up to its `--max-path-rate`. "rmpf" in ASCII. +pub const FRAME_PATH_RATE: u64 = 0x726d_7066; const STREAM_CONTROL: u64 = 0x00; const STREAM_PUSH: u64 = 0x01; @@ -89,6 +96,19 @@ impl Control { .context("writing PATH_PRIORITY") } + /// Tell the peer to send on `path_id` at a fixed `rate` (bits per second). + pub async fn send_path_rate(&self, path_id: PathId, rate: u64) -> Result<()> { + let mut payload = Vec::new(); + varint::encode(u64::from(crate::util::path_id_u32(path_id)), &mut payload); + varint::encode(rate, &mut payload); + self.0 + .lock() + .await + .write_all(&frame(FRAME_PATH_RATE, &payload)) + .await + .context("writing PATH_RATE") + } + /// Ask the peer to rank the paths it sends on by loss. pub async fn send_path_ranking(&self) -> Result<()> { let mut payload = Vec::new(); @@ -125,15 +145,30 @@ pub async fn open_control(conn: &Connection) -> Result { } /// Service the peer's unidirectional streams until the connection closes: -/// read its control stream (logging SETTINGS, applying path priorities), drain -/// QPACK streams, and refuse push and unknown stream types. -pub async fn serve_uni_streams(conn: Connection, priorities: Arc) { +/// read its control stream (logging SETTINGS, applying path priorities and, +/// up to `max_path_rate`, path rates), drain QPACK streams, and refuse push +/// and unknown stream types. +pub async fn serve_uni_streams( + conn: Connection, + priorities: Arc, + max_path_rate: Option, +) { while let Ok(recv) = conn.accept_uni().await { - tokio::spawn(serve_uni_stream(conn.clone(), priorities.clone(), recv)); + tokio::spawn(serve_uni_stream( + conn.clone(), + priorities.clone(), + max_path_rate, + recv, + )); } } -async fn serve_uni_stream(conn: Connection, priorities: Arc, recv: RecvStream) { +async fn serve_uni_stream( + conn: Connection, + priorities: Arc, + max_path_rate: Option, + recv: RecvStream, +) { let mut reader = FrameReader::new(recv); let ty = match reader.read_varint().await { Ok(Some(ty)) => ty, @@ -158,6 +193,9 @@ async fn serve_uni_stream(conn: Connection, priorities: Arc, rec Ok(Some((FRAME_PATH_PRIORITY, payload))) => { apply_path_priority(&conn, &priorities, &payload) } + Ok(Some((FRAME_PATH_RATE, payload))) => { + apply_path_rate(&conn, &priorities, max_path_rate, &payload) + } Ok(Some((FRAME_PATH_RANKING, payload))) => { if varint::decode(&payload).map(|(mode, _)| mode) == Some(PATH_RANKING_AUTO) { @@ -213,6 +251,44 @@ fn apply_path_priority(conn: &Connection, priorities: &PathPriorities, payload: priorities.set_base(conn, path_id, priority); } +fn parse_path_rate(payload: &[u8]) -> Option<(PathId, u64)> { + let (path_id, n) = varint::decode(payload)?; + let (rate, m) = varint::decode(&payload[n..])?; + if n + m != payload.len() || rate == 0 { + return None; + } + Some((PathId::from(u32::try_from(path_id).ok()?), rate)) +} + +fn apply_path_rate( + conn: &Connection, + priorities: &PathPriorities, + max_path_rate: Option, + payload: &[u8], +) { + let Some((path_id, requested)) = parse_path_rate(payload) else { + log::debug!("ignoring malformed PATH_RATE frame"); + return; + }; + let requested_text = crate::cc::format_rate(requested); + let Some(max) = max_path_rate else { + log::info!( + "path {path_id}: peer asked for a fixed rate of {requested_text}bit/s; ignored \ + (no --max-path-rate), the path stays congestion-controlled" + ); + return; + }; + let rate = requested.min(max); + if priorities.set_rate(conn, path_id, rate) { + log::info!( + "path {path_id}: fixed rate {}bit/s (peer asked for {requested_text}bit/s)", + crate::cc::format_rate(rate) + ); + } else { + log::debug!("path {path_id}: rate for a closed path ignored"); + } +} + fn parse_settings(mut payload: &[u8]) -> Option> { let mut out = Vec::new(); while !payload.is_empty() { diff --git a/src/main.rs b/src/main.rs index 15d6e06..a1a9ef0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod qpack_tables; mod quic; mod ranking; mod reload; +mod reorder; mod routed_socket; mod rules; mod server; @@ -99,6 +100,7 @@ fn serve(args: ServeArgs) -> Result<()> { let state = Arc::new(ServerState { rules: ArcSwap::from_pointee(rule_table), stats: stats_registry.clone(), + max_path_rate: args.max_path_rate, }); let reload_paths = ReloadPaths { cert: args.cert.clone(), @@ -163,6 +165,8 @@ fn client(args: ClientArgs) -> Result<()> { ech_config_list: load_ech_config(&args)?, paths: args.paths.clone(), primary_priority: args.primary_priority, + primary_rate: args.primary_rate, + in_order_delivery: args.in_order_delivery, rtable: args.rtable, path_ranking: args.path_ranking, stats: args.stats_listen.map(|_| stats::Registry::new("client")), diff --git a/src/quic.rs b/src/quic.rs index 21b8299..b092237 100644 --- a/src/quic.rs +++ b/src/quic.rs @@ -46,9 +46,10 @@ const DGRAM_RECV_BUFFER: usize = 8 * 1024 * 1024; /// HTTP datagram size for a full-size packet of a 1280-MTU WireGuard tunnel: a /// 1280-byte inner packet inside WireGuard is a 1312-byte UDP payload (16B /// header + 16B tag), plus our 2B HTTP-datagram prefix (quarter-stream ID + -/// context ID) = 1314B. It must fit in one QUIC DATAGRAM frame, which cannot -/// be fragmented. -pub(crate) const WIREGUARD_1280_DATAGRAM: usize = 1280 + 32 + 2; +/// context ID) and the 4B sequence number of in-order delivery +/// (`crate::reorder`) = 1318B. It must fit in one QUIC DATAGRAM frame, which +/// cannot be fragmented. +pub(crate) const WIREGUARD_1280_DATAGRAM: usize = 1280 + 32 + 2 + crate::dgram::SEQUENCE_LEN; /// noq's per-packet bound on DATAGRAM overhead (`Datagrams::max_size`): flags /// byte (1) + destination CID (8, noq's default CID length, which every @@ -58,17 +59,17 @@ pub(crate) const WIREGUARD_1280_DATAGRAM: usize = 1280 + 32 + 2; const DATAGRAM_OVERHEAD: usize = 1 + 8 + 4 + 16 + 9; /// Default initial and minimum outer (client<->proxy) QUIC packet size, i.e. UDP -/// payload bytes: exactly what a 1280-MTU WireGuard packet needs (1352). +/// payload bytes: exactly what a 1280-MTU WireGuard packet needs (1356). /// noq's default of 1200 leaves only 1162B, so until DPLPMTUD had probed the /// path upward (and indefinitely where probing never succeeds) every /// full-size packet would be dropped. It is also the floor: DPLPMTUD may raise /// the size (up to 1452) but its black-hole detection never lowers it below /// this, because shrinking would silently stop the tunnel from carrying /// full-size inner packets. The client<->proxy path must therefore carry -/// 1380-byte IPv4 / 1400-byte IPv6 packets; on a path that cannot, large +/// 1384-byte IPv4 / 1404-byte IPv6 packets; on a path that cannot, large /// packets are lost rather than the tunnel narrowing. Override with `--min-mtu`. pub(crate) const DEFAULT_MIN_MTU: u16 = (WIREGUARD_1280_DATAGRAM + DATAGRAM_OVERHEAD) as u16; -const _: () = assert!(DEFAULT_MIN_MTU == 1352); +const _: () = assert!(DEFAULT_MIN_MTU == 1356); /// Size requested (per direction) for every UDP socket's kernel buffers. /// diff --git a/src/ranking.rs b/src/ranking.rs index 58fdcde..5f276cb 100644 --- a/src/ranking.rs +++ b/src/ranking.rs @@ -112,6 +112,8 @@ pub struct PathEntry { pub demoted: bool, /// Smoothed loss rate of what this end sends on the path, once sampled. pub loss: Option, + /// Fixed sending rate (bits per second) in place of congestion control. + pub rate: Option, } impl PathEntry { @@ -133,6 +135,27 @@ impl PathPriorities { self.update(conn, path_id, |e| e.base = base); } + /// Send on a path at a fixed `rate` (bits per second) instead of under + /// congestion control (`crate::cc::FixedRate`). Returns `false` if the + /// path is gone. + pub fn set_rate(&self, conn: &Connection, path_id: PathId, rate: u64) -> bool { + let Some(path) = conn.path(path_id) else { + return false; + }; + let factory = Arc::new(crate::cc::FixedRateFactory { rate }); + if path.set_congestion_controller(factory).is_err() { + return false; + } + self.inner + .lock() + .unwrap() + .paths + .entry(path_id) + .or_default() + .rate = Some(rate); + true + } + /// Whether automatic ranking runs on this connection. pub fn ranking(&self) -> bool { self.inner.lock().unwrap().ranking @@ -610,7 +633,7 @@ mod tests { let entry = |base, demoted| PathEntry { base, demoted, - loss: None, + ..Default::default() }; assert_eq!(entry(3, true).effective(false), 3); assert_eq!(entry(0, false).effective(true), 0); diff --git a/src/reorder.rs b/src/reorder.rs new file mode 100644 index 0000000..76f8080 --- /dev/null +++ b/src/reorder.rs @@ -0,0 +1,293 @@ +//! In-order delivery of a flow's datagrams (`--in-order-delivery`). +//! +//! When the tunnel's preferred path is full, part of a flow spills onto a +//! slower path, and the far end receives its datagrams out of order. For TCP +//! inside the tunnel (e.g. inside WireGuard, which passes reordering through) +//! a datagram that arrives after its successors looks like loss: duplicate +//! ACKs, spurious retransmissions and a reduced sending rate. So the sender +//! numbers each flow's datagrams (`crate::dgram::encode_sequenced`) and the +//! receiver holds early arrivals until the gap before them fills, or gives up +//! on the gap after a hold time and releases what it has. +//! +//! The hold time tunes itself: it follows how late gap-filling datagrams +//! actually arrive (a quarter more, up to [`MAX_HOLD`]), and decays while +//! nothing arrives out of order, so a flow on one path, or a genuinely lost +//! datagram on a path that never reorders, delays its successors only +//! briefly. + +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +use bytes::Bytes; + +/// Hold time before any reordering has been seen. +const INITIAL_HOLD: Duration = Duration::from_millis(10); +/// The hold time never decays below this. +const MIN_HOLD: Duration = Duration::from_millis(2); +/// Nor grows above this: a datagram later than this is delivered when it +/// comes, out of order. +pub const MAX_HOLD: Duration = Duration::from_millis(250); +/// Without reordering for this long, the hold time halves. +const DECAY_AFTER: Duration = Duration::from_secs(10); +/// Datagrams buffered ahead of a gap, at most. A datagram further ahead than +/// this releases everything and restarts the sequence there. +const MAX_WINDOW: usize = 4096; + +/// Per-flow, per-direction reordering state. +#[derive(Debug)] +pub struct Reorder { + /// The sequence number delivered next (`None` before the first datagram). + next: Option, + /// Datagrams `next`, `next + 1`, ... that have arrived early; slot 0 is + /// always empty while anything is buffered. + window: VecDeque>, + /// When the current gap opened. + gap_since: Option, + hold: Duration, + last_reorder: Instant, + /// The last range given up on, `[start, end)`, and when its gap opened, + /// to learn from datagrams that arrive after it was skipped. + skipped: Option<(u32, u32, Instant)>, +} + +impl Reorder { + pub fn new(now: Instant) -> Self { + Self { + next: None, + window: VecDeque::new(), + gap_since: None, + hold: INITIAL_HOLD, + last_reorder: now, + skipped: None, + } + } + + /// Take in datagram `seq`; datagrams now deliverable, in order, are + /// appended to `out`. + pub fn push(&mut self, seq: u32, data: Bytes, now: Instant, out: &mut Vec) { + self.decay(now); + let next = *self.next.get_or_insert(seq); + let ahead = seq.wrapping_sub(next) as i32; + if ahead < 0 { + // Late: its gap was given up on already. Deliver it anyway (the + // tunnelled protocol handles duplicates and reordering), and wait + // longer next time. + if let Some((start, end, since)) = self.skipped + && seq.wrapping_sub(start) < end.wrapping_sub(start) + { + self.learn(now.saturating_duration_since(since), now); + } + out.push(data); + return; + } + let ahead = ahead as usize; + if ahead >= MAX_WINDOW { + // Far ahead (a long outage, or the peer restarted the flow): + // release everything and continue from here. + self.release_all(out); + out.push(data); + self.next = Some(seq.wrapping_add(1)); + return; + } + if ahead > 0 { + if self.window.len() <= ahead { + self.window.resize(ahead + 1, None); + } + if self.window[ahead].is_none() { + self.window[ahead] = Some(data); + } // else a duplicate + self.gap_since.get_or_insert(now); + return; + } + // The next datagram in order. + out.push(data); + self.window.pop_front(); + let mut next = next.wrapping_add(1); + while let Some(Some(_)) = self.window.front() { + out.push(self.window.pop_front().flatten().expect("checked")); + next = next.wrapping_add(1); + } + self.next = Some(next); + if let Some(since) = self.gap_since.take() { + self.learn(now.saturating_duration_since(since), now); + if !self.window.is_empty() { + // Another gap further on, opened no later than now. + self.gap_since = Some(now); + } + } + } + + /// When the current gap is given up on, if there is one. + pub fn deadline(&self) -> Option { + self.gap_since.map(|since| since + self.hold) + } + + /// Give up on the current gap if its hold time has passed: release every + /// buffered datagram, in order, to `out`. + pub fn on_timeout(&mut self, now: Instant, out: &mut Vec) { + if self.deadline().is_some_and(|deadline| deadline <= now) { + let since = self.gap_since.expect("deadline implies a gap"); + let start = self.next.expect("a gap implies a datagram"); + let end = start.wrapping_add(self.window.len() as u32); + self.skipped = Some((start, end, since)); + self.release_all(out); + } + } + + /// Current hold time. + #[cfg(test)] + pub fn hold(&self) -> Duration { + self.hold + } + + fn release_all(&mut self, out: &mut Vec) { + if let Some(next) = self.next.as_mut() { + *next = next.wrapping_add(self.window.len() as u32); + } + out.extend(self.window.drain(..).flatten()); + self.gap_since = None; + } + + /// A datagram arrived `delay` after its gap opened. + fn learn(&mut self, delay: Duration, now: Instant) { + self.hold = self.hold.max(delay * 5 / 4).min(MAX_HOLD); + self.last_reorder = now; + } + + fn decay(&mut self, now: Instant) { + if now.saturating_duration_since(self.last_reorder) >= DECAY_AFTER { + self.hold = (self.hold / 2).max(MIN_HOLD); + self.last_reorder = now; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn b(n: u32) -> Bytes { + Bytes::from(n.to_be_bytes().to_vec()) + } + + fn seqs(out: &[Bytes]) -> Vec { + out.iter() + .map(|d| u32::from_be_bytes(d[..].try_into().unwrap())) + .collect() + } + + /// Feed `order` at 1 ms intervals; returns delivered sequence numbers. + fn feed(r: &mut Reorder, start: Instant, order: &[u32]) -> Vec { + let mut out = Vec::new(); + for (i, &seq) in order.iter().enumerate() { + r.push( + seq, + b(seq), + start + Duration::from_millis(i as u64), + &mut out, + ); + } + seqs(&out) + } + + #[test] + fn in_order_passes_through() { + let t = Instant::now(); + let mut r = Reorder::new(t); + assert_eq!(feed(&mut r, t, &[5, 6, 7, 8]), vec![5, 6, 7, 8]); + assert_eq!(r.deadline(), None); + } + + #[test] + fn reordered_datagrams_come_out_in_order() { + let t = Instant::now(); + let mut r = Reorder::new(t); + // 3 and 4 overtake 2, which arrives 2 ms after its gap opened. + assert_eq!(feed(&mut r, t, &[0, 1, 3, 4, 2, 5]), vec![0, 1, 2, 3, 4, 5]); + assert_eq!(r.deadline(), None); + // Learned: hold at least 1.25 x 2 ms (but stays at the initial 10). + assert_eq!(r.hold(), INITIAL_HOLD); + } + + #[test] + fn hold_follows_observed_lateness() { + let t = Instant::now(); + let mut r = Reorder::new(t); + let mut out = Vec::new(); + r.push(0, b(0), t, &mut out); + r.push(2, b(2), t, &mut out); + // 1 arrives 40 ms late, within the hold? No: hold is 10 ms, so time + // out first... + r.on_timeout(t + Duration::from_millis(10), &mut out); + assert_eq!(seqs(&out), vec![0, 2]); + // ...then 1 turns up 40 ms after its gap opened: delivered late, and + // the hold grows to 50 ms. + r.push(1, b(1), t + Duration::from_millis(40), &mut out); + assert_eq!(seqs(&out), vec![0, 2, 1]); + assert_eq!(r.hold(), Duration::from_millis(50)); + + // Next time the same lateness is absorbed. + let t2 = t + Duration::from_millis(100); + r.push(4, b(4), t2, &mut out); + assert_eq!(r.deadline(), Some(t2 + Duration::from_millis(50))); + r.on_timeout(t2 + Duration::from_millis(40), &mut out); + r.push(3, b(3), t2 + Duration::from_millis(40), &mut out); + assert_eq!(seqs(&out), vec![0, 2, 1, 3, 4]); + } + + #[test] + fn lost_datagram_released_after_hold() { + let t = Instant::now(); + let mut r = Reorder::new(t); + let mut out = Vec::new(); + for seq in [0, 2, 3] { + r.push(seq, b(seq), t, &mut out); + } + assert_eq!(seqs(&out), vec![0]); + r.on_timeout(t + Duration::from_millis(9), &mut out); + assert_eq!(seqs(&out), vec![0], "not yet"); + r.on_timeout(t + INITIAL_HOLD, &mut out); + assert_eq!(seqs(&out), vec![0, 2, 3]); + r.push(4, b(4), t + INITIAL_HOLD, &mut out); + assert_eq!(seqs(&out), vec![0, 2, 3, 4]); + } + + #[test] + fn hold_is_capped_and_decays() { + let t = Instant::now(); + let mut r = Reorder::new(t); + let mut out = Vec::new(); + r.push(0, b(0), t, &mut out); + r.push(2, b(2), t, &mut out); + r.push(1, b(1), t + Duration::from_secs(1), &mut out); + assert_eq!(r.hold(), MAX_HOLD); + // Quiet for a while: halves on the next datagram. + r.push(3, b(3), t + Duration::from_secs(12), &mut out); + assert_eq!(r.hold(), MAX_HOLD / 2); + } + + #[test] + fn wraps_around() { + let t = Instant::now(); + let mut r = Reorder::new(t); + let order = [u32::MAX - 1, u32::MAX, 1, 0, 2]; + assert_eq!( + feed(&mut r, t, &order), + vec![u32::MAX - 1, u32::MAX, 0, 1, 2] + ); + } + + #[test] + fn duplicates_and_far_jumps() { + let t = Instant::now(); + let mut r = Reorder::new(t); + // A duplicate of a buffered datagram is dropped. + assert_eq!(feed(&mut r, t, &[0, 2, 2, 1]), vec![0, 1, 2]); + // Far ahead: release and restart there. + let mut out = Vec::new(); + r.push(5, b(5), t, &mut out); + r.push(100_000, b(100_000), t, &mut out); + r.push(100_001, b(100_001), t, &mut out); + assert_eq!(seqs(&out), vec![5, 100_000, 100_001]); + } +} diff --git a/src/server.rs b/src/server.rs index 4463640..1c11e48 100644 --- a/src/server.rs +++ b/src/server.rs @@ -24,6 +24,7 @@ use crate::dgram; use crate::h3::{self, FrameReader}; use crate::quic::{self, CAPSULE_PROTOCOL_TRUE}; use crate::ranking::PathPriorities; +use crate::reorder::Reorder; use crate::rules::RuleTable; use crate::stats; use crate::tls::HandshakeData; @@ -40,11 +41,14 @@ pub struct ServerState { pub rules: ArcSwap, /// Connections listed on the stats endpoint, if enabled. pub stats: Option>, + /// Largest fixed path rate a client may ask for (`--max-path-rate`). + pub max_path_rate: Option, } /// Client→target side of one active flow, as seen by the datagram dispatcher. struct FlowHandle { - to_target: mpsc::Sender, + /// Payloads with their sequence numbers, if the client numbers them. + to_target: mpsc::Sender<(Option, Bytes)>, activity: Arc, } @@ -105,7 +109,11 @@ async fn handle_connection(incoming: Incoming, state: Arc) -> Resul // Our control stream must stay open for the connection's lifetime. let _control = h3::open_control(&conn).await?; let priorities = Arc::new(PathPriorities::default()); - tokio::spawn(h3::serve_uni_streams(conn.clone(), priorities.clone())); + tokio::spawn(h3::serve_uni_streams( + conn.clone(), + priorities.clone(), + state.max_path_rate, + )); tokio::spawn(quic::log_path_events(conn.clone())); let flows: FlowMap = Arc::new(Mutex::new(HashMap::new())); @@ -155,20 +163,21 @@ async fn dispatch_datagrams(conn: Connection, flows: FlowMap) { let Some(parsed) = dgram::decode(&datagram) else { continue; }; - if parsed.context_id != dgram::CONTEXT_ID_UDP { - continue; // only raw UDP payloads are supported - } + // Only (sequenced) UDP payloads are supported. + let Some((seq, payload)) = dgram::udp_payload(&parsed) else { + continue; + }; let flows = flows.lock().unwrap(); match flows.get(&parsed.flow_id) { Some(flow) => { log::debug!( "client datagram flow {} -> target: {} bytes", parsed.flow_id, - parsed.payload.len() + payload.len() ); // Drop on full: UDP is lossy by contract. - let payload = datagram.slice_ref(parsed.payload); - let _ = flow.to_target.try_send(payload); + let payload = datagram.slice_ref(payload); + let _ = flow.to_target.try_send((seq, payload)); // Client→target traffic keeps the flow alive. flow.activity.touch(); } @@ -227,7 +236,7 @@ async fn handle_request( } }; - let (to_target_tx, to_target_rx) = mpsc::channel::(CHANNEL_CAP); + let (to_target_tx, to_target_rx) = mpsc::channel::<(Option, Bytes)>(CHANNEL_CAP); let activity = Arc::new(Activity::new()); flows.lock().unwrap().insert( flow_id, @@ -244,19 +253,27 @@ async fn handle_request( if let Some(mark) = rule.fwmark { extra.push_str(&format!(" fwmark {mark}")); } + if req.sequenced { + extra.push_str(" in order"); + } log::info!("CONNECT-UDP flow {flow_id} -> {}{extra}", rule.target); // Keep the stream open (no FIN) so datagrams keep flowing. - let response = h3::headers_frame(&[ + let mut fields = vec![ (":status", "200"), ("capsule-protocol", CAPSULE_PROTOCOL_TRUE), - ]); + ]; + if req.sequenced { + fields.push((dgram::SEQUENCE_HEADER, dgram::SEQUENCE_HEADER_ON)); + } + let response = h3::headers_frame(&fields); if let Err(e) = send.write_all(&response).await { log::warn!("failed to send CONNECT-UDP 200 response: {e}"); } else { relay_flow( &conn, flow_id, + req.sequenced, &target, to_target_rx, &mut send, @@ -271,32 +288,57 @@ async fn handle_request( /// Relay one flow until the client closes its request stream, the connection /// dies, or the flow idles out (which resets the stream so the client frees it -/// and reopens lazily on its next datagram). +/// and reopens lazily on its next datagram). With `sequenced`, replies carry +/// sequence numbers; numbered datagrams from the client are delivered to the +/// target in order (`crate::reorder`). #[allow(clippy::too_many_arguments)] async fn relay_flow( conn: &Connection, flow_id: u64, + sequenced: bool, target: &UdpSocket, - mut from_client: mpsc::Receiver, + mut from_client: mpsc::Receiver<(Option, Bytes)>, send: &mut SendStream, reader: &mut FrameReader, activity: &Activity, idle_timeout: Option, ) { let mut buf = vec![0u8; RECV_BUF]; + let mut next_seq = 0u32; + let mut reorder: Option = None; + let mut ready: Vec = Vec::new(); loop { + for payload in ready.drain(..) { + if let Err(e) = target.send(&payload).await { + log::debug!("send to target failed: {e}"); + } + } let deadline = idle_timeout.map(|d| activity.last() + d); + let reorder_deadline = reorder.as_ref().and_then(Reorder::deadline); tokio::select! { maybe = from_client.recv() => { - let Some(payload) = maybe else { break }; - if let Err(e) = target.send(&payload).await { - log::debug!("send to target failed: {e}"); + let Some((seq, payload)) = maybe else { break }; + match seq { + Some(seq) => reorder + .get_or_insert_with(|| Reorder::new(std::time::Instant::now())) + .push(seq, payload, std::time::Instant::now(), &mut ready), + None => ready.push(payload), + } + } + _ = sleep_until_opt(reorder_deadline.map(Instant::from_std)) => { + if let Some(reorder) = reorder.as_mut() { + reorder.on_timeout(std::time::Instant::now(), &mut ready); } } r = target.recv(&mut buf) => match r { Ok(n) => { activity.touch(); - let datagram = Bytes::from(dgram::encode(flow_id, &buf[..n])); + let seq = sequenced.then(|| { + let seq = next_seq; + next_seq = next_seq.wrapping_add(1); + seq + }); + let datagram = Bytes::from(dgram::encode_udp(flow_id, seq, &buf[..n])); if !quic::send_datagram(conn, flow_id, datagram, "reply") { break; } @@ -331,6 +373,9 @@ async fn sleep_until_opt(deadline: Option) { struct ConnectRequest { authority: String, path: String, + /// The client numbers its datagrams and wants ours numbered + /// ([`dgram::SEQUENCE_HEADER`]). + sequenced: bool, } impl ConnectRequest { @@ -351,6 +396,8 @@ impl ConnectRequest { Ok(Self { authority: text(":authority")?, path: text(":path")?, + sequenced: h3::header(fields, dgram::SEQUENCE_HEADER) + == Some(dgram::SEQUENCE_HEADER_ON.as_bytes()), }) } } diff --git a/src/stats.rs b/src/stats.rs index aa42e28..0dc7d78 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -148,6 +148,7 @@ fn connection_stats(entry: &Entry) -> Value { "base_priority": entry.base, "demoted": entry.demoted, "ranked_loss": entry.loss, + "fixed_rate_bps": entry.rate, "rtt_ms": millis(s.rtt), "cwnd": s.cwnd, "mtu": s.current_mtu, From f68464c230e717a41bf7c92f6d51f5571c188c17 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 18:42:03 +0000 Subject: [PATCH 2/2] Pin noq to the merged per-path congestion controller commit losfair/noq#5 merged as 38d92aa on dev (same tree as the pinned PR head 21d76fb). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012baC35vUbLPPhuK4pz4uRz --- Cargo.lock | 6 +++--- Cargo.toml | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7947079..3ee02a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -563,7 +563,7 @@ dependencies = [ [[package]] name = "noq" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" +source = "git+https://github.com/losfair/noq?rev=38d92aacf97a79083cb74fca0e6ba641c4f3ed7d#38d92aacf97a79083cb74fca0e6ba641c4f3ed7d" dependencies = [ "bytes", "cfg_aliases", @@ -583,7 +583,7 @@ dependencies = [ [[package]] name = "noq-proto" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" +source = "git+https://github.com/losfair/noq?rev=38d92aacf97a79083cb74fca0e6ba641c4f3ed7d#38d92aacf97a79083cb74fca0e6ba641c4f3ed7d" dependencies = [ "bytes", "derive_more", @@ -609,7 +609,7 @@ dependencies = [ [[package]] name = "noq-udp" version = "1.3.0" -source = "git+https://github.com/losfair/noq?rev=21d76fb4243cbe8cb82fcd7c1da04b8e441de59a#21d76fb4243cbe8cb82fcd7c1da04b8e441de59a" +source = "git+https://github.com/losfair/noq?rev=38d92aacf97a79083cb74fca0e6ba641c4f3ed7d#38d92aacf97a79083cb74fca0e6ba641c4f3ed7d" dependencies = [ "cfg_aliases", "libc", diff --git a/Cargo.toml b/Cargo.toml index 3719250..d4b696c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,10 +32,10 @@ tokio-stream = "0.1" # Pinned to the losfair/noq fork for per-path scheduling priority, the path # spill threshold and datagram queue management (not in upstream noq). Keep # both crates on the same commit. -noq = { git = "https://github.com/losfair/noq", rev = "21d76fb4243cbe8cb82fcd7c1da04b8e441de59a", default-features = false, features = ["runtime-tokio", "ring", "bloom", "tracing-log"] } +noq = { git = "https://github.com/losfair/noq", rev = "38d92aacf97a79083cb74fca0e6ba641c4f3ed7d", default-features = false, features = ["runtime-tokio", "ring", "bloom", "tracing-log"] } # Direct dep only for `coding::Encodable` (to read a `PathId` for the multipath # AEAD nonce); same commit as noq's own. -noq-proto = { git = "https://github.com/losfair/noq", rev = "21d76fb4243cbe8cb82fcd7c1da04b8e441de59a", default-features = false, features = ["ring", "bloom", "tracing-log"] } +noq-proto = { git = "https://github.com/losfair/noq", rev = "38d92aacf97a79083cb74fca0e6ba641c4f3ed7d", default-features = false, features = ["ring", "bloom", "tracing-log"] } # BoringSSL: the TLS 1.3 handshake (via its QUIC API), ECH, and packet # protection (AEAD + header protection). boring 4 keeps the ECH code identical # to zeromasque's.