From 2de56afdc67273058b8b614a6b7c11ba2bfe7c3e Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:31:46 -0600 Subject: [PATCH] fleet-proxy: CONNECT-UDP client shim + standalone endpoint bins (#6109) The spike follow-through, still dark: * udp_forward: the client shim the #6109 design note named -- plain local UDP in, one CONNECT-UDP session per (listen port, peer) out via UdpProxyClient, replies unwrapped back. Port sets (--ports 47998-48010, the Moonlight shape, port-preserving) and explicit --map rules; sessions lazy, idle out at the relay horizon, replaced when dead. * bin fleet-udp-forward: the shim's CLI. Nothing starts it unless a host deliberately does. * bin fleet-connect-udp: the endpoint standalone (connect_udp::run), for hosts where the session broker does not run -- the laptop serves fleet roles as fleet serve units. Refuses to start unless the loaded fleet config opts in ([proxy] connect_udp); binds connect_udp_listen (default loopback). * Both bins are required-features=[serve] so the connect-only variant keeps its mechanical incapability. No service wiring, no config changes, no consumer: the #5924 tailnet-direct streaming verdict stands until a cutover is called. --- pkgs/fleet/crates/fleet-proxy/Cargo.toml | 14 + .../fleet-proxy/src/bin/fleet-connect-udp.rs | 42 ++ .../fleet-proxy/src/bin/fleet-udp-forward.rs | 117 ++++++ .../crates/fleet-proxy/src/connect_udp.rs | 7 + pkgs/fleet/crates/fleet-proxy/src/lib.rs | 3 + .../crates/fleet-proxy/src/udp_forward.rs | 358 ++++++++++++++++++ 6 files changed, 541 insertions(+) create mode 100644 pkgs/fleet/crates/fleet-proxy/src/bin/fleet-connect-udp.rs create mode 100644 pkgs/fleet/crates/fleet-proxy/src/bin/fleet-udp-forward.rs create mode 100644 pkgs/fleet/crates/fleet-proxy/src/udp_forward.rs diff --git a/pkgs/fleet/crates/fleet-proxy/Cargo.toml b/pkgs/fleet/crates/fleet-proxy/Cargo.toml index cbcd91769d..b439363fae 100644 --- a/pkgs/fleet/crates/fleet-proxy/Cargo.toml +++ b/pkgs/fleet/crates/fleet-proxy/Cargo.toml @@ -14,6 +14,20 @@ serde = { workspace = true } serde_json = { workspace = true } libc = "0.2" + +# The CONNECT-UDP bins (#6109) ride on the serve-gated modules; +# required-features keeps the connect-only variant (§2's +# mechanical-incapability build) from trying to build them. +[[bin]] +name = "fleet-connect-udp" +path = "src/bin/fleet-connect-udp.rs" +required-features = ["serve"] + +[[bin]] +name = "fleet-udp-forward" +path = "src/bin/fleet-udp-forward.rs" +required-features = ["serve"] + [features] # The broker half. The connect variant compiles this crate without # it: a dropped-on-a-box artifact carries the client and nothing diff --git a/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-connect-udp.rs b/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-connect-udp.rs new file mode 100644 index 0000000000..1ed494dcf7 --- /dev/null +++ b/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-connect-udp.rs @@ -0,0 +1,42 @@ +//! fleet-connect-udp — the standalone CONNECT-UDP endpoint +//! (RFC 9298, #6109), for hosts where the session broker +//! (`fleet proxy serve`) doesn't run: the laptop serves its +//! fleet roles as `fleet serve ` units, so the endpoint +//! gets its own handler process there. +//! +//! Dark by construction, twice over: it refuses to start +//! unless the fleet config it loads opts in with +//! `[proxy] connect_udp = true` (fleet-config), and the +//! endpoint binds whatever `connect_udp_listen` says — the +//! default, and the only sanctioned posture pre-cutover, is +//! loopback. Which config loads is fleet-config's own +//! resolution ($FLEET_CONFIG, else ~/.config/fleet/fleet.toml), +//! so a host can stage this endpoint behind a dedicated config +//! file without touching the shared one. + +use std::process::ExitCode; + +fn main() -> ExitCode { + let config = match fleet_config::Config::load() { + Ok(c) => c, + Err(e) => { + eprintln!("fleet-connect-udp: cannot load fleet config: {e}"); + return ExitCode::FAILURE; + } + }; + if !config.connect_udp_enabled() { + eprintln!( + "fleet-connect-udp: [proxy] connect_udp is not enabled in the loaded \ + fleet config — the endpoint stays dark. Enable it deliberately, \ + loopback only, in the config this process loads." + ); + return ExitCode::from(fleet_proxy::EXIT_UNAVAILABLE as u8); + } + match fleet_proxy::connect_udp::run(&config) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("fleet-connect-udp: {e}"); + ExitCode::FAILURE + } + } +} diff --git a/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-udp-forward.rs b/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-udp-forward.rs new file mode 100644 index 0000000000..269ccbeac8 --- /dev/null +++ b/pkgs/fleet/crates/fleet-proxy/src/bin/fleet-udp-forward.rs @@ -0,0 +1,117 @@ +//! fleet-udp-forward — the CONNECT-UDP client shim (#6109): +//! local UDP in, CONNECT-UDP sessions out, replies back. The +//! piece a real consumer (Moonlight) needs in front of it, +//! since it speaks plain UDP and nothing else. +//! +//! Two ways to name the forwards: +//! +//! * `--target --ports ` — port-preserving over a +//! set (`47998-48010` is the Moonlight shape): local port P +//! forwards to :P. +//! * `--map =:` (repeatable) — explicit +//! one-off mappings. +//! +//! Everything binds `--bind` (default 127.0.0.1) and talks to +//! the CONNECT-UDP endpoint at `--proxy` (default +//! 127.0.0.1:3131). Config-gated in the only way a shim can +//! be: nothing runs it unless a host deliberately starts it. + +use std::net::{IpAddr, SocketAddr}; +use std::process::ExitCode; + +use fleet_proxy::EXIT_USAGE; +use fleet_proxy::udp_forward::{Forward, parse_map, parse_port_set}; + +const DEFAULT_PROXY: &str = "127.0.0.1:3131"; +const USAGE: &str = "usage: fleet-udp-forward [--proxy ] [--bind ] \ + (--map =:... | --target --ports )"; + +fn fail(msg: &str) -> ExitCode { + eprintln!("fleet-udp-forward: {msg}"); + eprintln!("{USAGE}"); + ExitCode::from(EXIT_USAGE as u8) +} + +fn take(args: &[String], i: &mut usize, flag: &str) -> Result { + *i += 1; + args.get(*i) + .cloned() + .ok_or_else(|| fail(&format!("{flag} needs a value"))) +} + +fn main() -> ExitCode { + let argv: Vec = std::env::args().skip(1).collect(); + let mut proxy = DEFAULT_PROXY.to_string(); + let mut bind: IpAddr = IpAddr::from([127, 0, 0, 1]); + let mut target: Option = None; + let mut ports: Option = None; + let mut maps: Vec = Vec::new(); + let mut i = 0; + while i < argv.len() { + match argv[i].as_str() { + "--proxy" => match take(&argv, &mut i, "--proxy") { + Ok(v) => proxy = v, + Err(c) => return c, + }, + "--bind" => match take(&argv, &mut i, "--bind") { + Ok(v) => match v.parse() { + Ok(ip) => bind = ip, + Err(_) => return fail(&format!("--bind {v:?} is not an IP address")), + }, + Err(c) => return c, + }, + "--target" => match take(&argv, &mut i, "--target") { + Ok(v) => target = Some(v), + Err(c) => return c, + }, + "--ports" => match take(&argv, &mut i, "--ports") { + Ok(v) => ports = Some(v), + Err(c) => return c, + }, + "--map" => match take(&argv, &mut i, "--map") { + Ok(v) => maps.push(v), + Err(c) => return c, + }, + "-h" | "--help" => { + println!("{USAGE}"); + return ExitCode::SUCCESS; + } + other => return fail(&format!("unknown argument {other:?}")), + } + i += 1; + } + + let mut forwards: Vec = Vec::new(); + for m in &maps { + match parse_map(m, bind) { + Ok(f) => forwards.push(f), + Err(e) => return fail(&e), + } + } + match (target, ports) { + (Some(host), Some(spec)) => match parse_port_set(&spec) { + Ok(ps) => { + for p in ps { + forwards.push(Forward { + listen: SocketAddr::new(bind, p), + target_host: host.clone(), + target_port: p, + }); + } + } + Err(e) => return fail(&e), + }, + (None, None) => {} + _ => return fail("--target and --ports must be given together"), + } + if forwards.is_empty() { + return fail("nothing to forward: give --map and/or --target + --ports"); + } + match fleet_proxy::udp_forward::run_forwards(&proxy, &forwards) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("fleet-udp-forward: {e}"); + ExitCode::FAILURE + } + } +} diff --git a/pkgs/fleet/crates/fleet-proxy/src/connect_udp.rs b/pkgs/fleet/crates/fleet-proxy/src/connect_udp.rs index 4d038cfa01..6fbd18a6ca 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/connect_udp.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/connect_udp.rs @@ -42,6 +42,13 @@ //! * A session with no datagrams in either direction for //! [`RELAY_IDLE_TIMEOUT`] closes. //! +//! The follow-up surface beside this module: `udp_forward` +//! (the client shim wrapping plain UDP into these sessions) +//! and two small bins — `fleet-connect-udp`, the standalone +//! endpoint for hosts where the broker doesn't run (the +//! laptop's dark deployment), and `fleet-udp-forward`, the +//! shim. Neither bin is wired into any service by the code. +//! //! There is deliberately **no target allowlist**: the listener //! binds loopback by default and is off unless configured, the //! same trust posture as the broker itself (a local capability, diff --git a/pkgs/fleet/crates/fleet-proxy/src/lib.rs b/pkgs/fleet/crates/fleet-proxy/src/lib.rs index c7f1123d82..931a41df63 100644 --- a/pkgs/fleet/crates/fleet-proxy/src/lib.rs +++ b/pkgs/fleet/crates/fleet-proxy/src/lib.rs @@ -40,6 +40,9 @@ pub mod serve; #[cfg(feature = "serve")] pub mod connect_udp; +#[cfg(feature = "serve")] +pub mod udp_forward; + /// Exit code for "the transport is down" — repo-queue's established /// 3 (§3's collision table: 3 means repair the transport, 69 means /// wrong build). The proxy client surface honors the same split. diff --git a/pkgs/fleet/crates/fleet-proxy/src/udp_forward.rs b/pkgs/fleet/crates/fleet-proxy/src/udp_forward.rs new file mode 100644 index 0000000000..16ae8087b2 --- /dev/null +++ b/pkgs/fleet/crates/fleet-proxy/src/udp_forward.rs @@ -0,0 +1,358 @@ +//! UDP forwarding shim — the client half of the CONNECT-UDP +//! capability (#6109), the follow-up the spike's design note +//! named. A real consumer does not speak CONNECT-UDP (Moonlight +//! certainly doesn't), so something on the client device has to +//! wrap its UDP into proxy sessions: this module is that +//! something, at spike grade. +//! +//! Plain local UDP sockets in; one CONNECT-UDP session per +//! (listen port, peer) out, opened lazily on the peer's first +//! datagram; replies unwrapped back to the peer. Sessions idle +//! out on the same horizon as the proxy's own relay +//! ([`PEER_IDLE_TIMEOUT`]), and a dead session is replaced on +//! the peer's next datagram — the shim is stateless forwarding, +//! not a tunnel endpoint with opinions. +//! +//! The two bins beside this module are the whole surface: +//! `fleet-connect-udp` serves the endpoint standalone (for hosts +//! where the broker proper doesn't run), and `fleet-udp-forward` +//! runs this shim. Neither is wired into any service by the +//! code; a host opts in deliberately, the same posture as the +//! endpoint itself. Nothing here changes the #5924 verdict: +//! streaming stays tailnet-direct until a cutover says otherwise. + +use std::collections::HashMap; +use std::io::ErrorKind; +use std::net::{IpAddr, SocketAddr, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crate::connect_udp::{MAX_DATAGRAM_BYTES, UdpProxyClient, UdpProxySender}; + +/// How long a peer session may sit with no datagrams in either +/// direction before the forwarder drops it. Matches the proxy +/// relay's own idle horizon: a peer silent longer than this +/// gets a fresh session on its next datagram either way. +pub const PEER_IDLE_TIMEOUT: Duration = Duration::from_secs(120); +/// Poll cadence for the forwarding loops: how often a blocked +/// read wakes to reap idle peers. +const POLL: Duration = Duration::from_millis(250); + +/// One forwarding rule: datagrams arriving on `listen` are +/// wrapped into CONNECT-UDP sessions to `target_host:target_port`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Forward { + pub listen: SocketAddr, + pub target_host: String, + pub target_port: u16, +} + +/// Parse a port set: `"47998"`, `"47998-48010"`, +/// `"47998,48000-48002"`. Ranges are inclusive; port 0 is not a +/// forwarding port. +pub fn parse_port_set(spec: &str) -> Result, String> { + let mut ports = Vec::new(); + for part in spec.split(',') { + let part = part.trim(); + if part.is_empty() { + return Err(format!("empty element in port set {spec:?}")); + } + match part.split_once('-') { + Some((a, b)) => { + let a: u16 = a + .parse() + .map_err(|_| format!("bad port {a:?} in port set {spec:?}"))?; + let b: u16 = b + .parse() + .map_err(|_| format!("bad port {b:?} in port set {spec:?}"))?; + if a == 0 || b < a { + return Err(format!("bad port range {part:?} in port set {spec:?}")); + } + ports.extend(a..=b); + } + None => { + let p: u16 = part + .parse() + .map_err(|_| format!("bad port {part:?} in port set {spec:?}"))?; + if p == 0 { + return Err("port 0 is not a forwarding port".to_string()); + } + ports.push(p); + } + } + } + if ports.is_empty() { + return Err(format!("port set {spec:?} names no ports")); + } + Ok(ports) +} + +/// Parse one `--map` value: `"=:"`, binding +/// the listen side on `bind`. +pub fn parse_map(spec: &str, bind: IpAddr) -> Result { + let (lport, target) = spec + .split_once('=') + .ok_or_else(|| format!("map {spec:?} is not =:"))?; + let lport: u16 = lport + .parse() + .map_err(|_| format!("map {spec:?} has a bad listen port"))?; + if lport == 0 { + return Err(format!("map {spec:?} listen port is 0")); + } + let (host, rport) = target + .rsplit_once(':') + .ok_or_else(|| format!("map {spec:?} target lacks a port"))?; + if host.is_empty() { + return Err(format!("map {spec:?} target has an empty host")); + } + let rport: u16 = rport + .parse() + .map_err(|_| format!("map {spec:?} has a bad target port"))?; + if rport == 0 { + return Err(format!("map {spec:?} target port is 0")); + } + Ok(Forward { + listen: SocketAddr::new(bind, lport), + target_host: host.to_string(), + target_port: rport, + }) +} + +/// One peer's live session: the send half, shared activity +/// clock, and the liveness flag the reply thread clears on its +/// way out. +struct Peer { + tx: Mutex, + last: Arc>, + alive: Arc, +} + +/// Open a session for `peer` and spawn its reply thread: +/// datagrams from the proxy go back out the listen socket to +/// the peer, verbatim. +fn open_peer( + proxy_addr: &str, + fwd: &Forward, + socket: &Arc, + peer: SocketAddr, +) -> std::io::Result { + let client = UdpProxyClient::connect(proxy_addr, &fwd.target_host, fwd.target_port)?; + let (tx, mut rx) = client.split(); + rx.set_read_timeout(Some(POLL))?; + let last = Arc::new(Mutex::new(Instant::now())); + let alive = Arc::new(AtomicBool::new(true)); + { + let socket = Arc::clone(socket); + let last = Arc::clone(&last); + let alive = Arc::clone(&alive); + std::thread::spawn(move || { + loop { + match rx.recv() { + Ok(d) => { + *last.lock().unwrap() = Instant::now(); + if socket.send_to(&d, peer).is_err() { + break; + } + } + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { + if !alive.load(Ordering::SeqCst) { + break; + } + } + Err(_) => break, + } + } + alive.store(false, Ordering::SeqCst); + }); + } + Ok(Peer { + tx: Mutex::new(tx), + last, + alive, + }) +} + +/// Drop peers that died (reply thread gone) or outlived the +/// idle horizon. Dropping a peer drops its send half; the reply +/// thread sees the liveness flag and exits, closing the +/// session. +fn reap(peers: &mut HashMap) { + peers.retain(|_, p| { + let keep = + p.alive.load(Ordering::SeqCst) && p.last.lock().unwrap().elapsed() <= PEER_IDLE_TIMEOUT; + if !keep { + p.alive.store(false, Ordering::SeqCst); + } + keep + }); +} + +/// The forwarding loop for one already-bound listen socket. +fn serve_socket(proxy_addr: &str, fwd: &Forward, socket: Arc) { + let mut peers: HashMap = HashMap::new(); + let mut buf = vec![0u8; MAX_DATAGRAM_BYTES]; + loop { + match socket.recv_from(&mut buf) { + Ok((n, peer_addr)) => { + let live = peers + .get(&peer_addr) + .map(|p| p.alive.load(Ordering::SeqCst)) + .unwrap_or(false); + if !live { + peers.remove(&peer_addr); + match open_peer(proxy_addr, fwd, &socket, peer_addr) { + Ok(p) => { + peers.insert(peer_addr, p); + } + Err(e) => { + eprintln!( + "fleet udp-forward: session to {}:{} for {peer_addr} via {proxy_addr} failed: {e}", + fwd.target_host, fwd.target_port + ); + continue; + } + } + } + let p = peers.get(&peer_addr).expect("peer just ensured"); + *p.last.lock().unwrap() = Instant::now(); + let sent = p.tx.lock().unwrap().send(&buf[..n]); + if sent.is_err() { + // Dead session: drop it; the peer's next + // datagram opens a fresh one. + p.alive.store(false, Ordering::SeqCst); + peers.remove(&peer_addr); + } + } + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { + reap(&mut peers); + } + Err(e) => { + eprintln!("fleet udp-forward: recv on {} failed: {e}", fwd.listen); + } + } + } +} + +/// Bind every forward's listen socket and serve them all, +/// one thread each. Bind failures surface before any thread +/// starts, so a misconfigured shim fails whole and loud. +pub fn run_forwards(proxy_addr: &str, forwards: &[Forward]) -> Result<(), String> { + use std::io::Write as _; + if forwards.is_empty() { + return Err("no forwards configured".to_string()); + } + let mut bound = Vec::new(); + for fwd in forwards { + let socket = UdpSocket::bind(fwd.listen) + .map_err(|e| format!("cannot bind UDP {}: {e}", fwd.listen))?; + socket + .set_read_timeout(Some(POLL)) + .map_err(|e| format!("cannot set read timeout on {}: {e}", fwd.listen))?; + println!( + "fleet udp-forward: udp:{} -> {}:{} via {proxy_addr}", + fwd.listen, fwd.target_host, fwd.target_port + ); + bound.push((fwd.clone(), Arc::new(socket))); + } + let _ = std::io::stdout().flush(); + let mut handles = Vec::new(); + for (fwd, socket) in bound { + let proxy_addr = proxy_addr.to_string(); + handles.push(std::thread::spawn(move || { + serve_socket(&proxy_addr, &fwd, socket); + })); + } + for h in handles { + let _ = h.join(); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn port_set_parsing() { + assert_eq!(parse_port_set("47998").unwrap(), vec![47998]); + assert_eq!( + parse_port_set("47998-48000").unwrap(), + vec![47998, 47999, 48000] + ); + assert_eq!( + parse_port_set("47998, 48010-48011").unwrap(), + vec![47998, 48010, 48011] + ); + assert!(parse_port_set("").is_err()); + assert!(parse_port_set("0").is_err()); + assert!(parse_port_set("48010-47998").is_err()); + assert!(parse_port_set("abc").is_err()); + assert!(parse_port_set("47998,,47999").is_err()); + } + + #[test] + fn map_parsing() { + let bind: IpAddr = "127.0.0.1".parse().unwrap(); + assert_eq!( + parse_map("47998=192.0.2.10:47999", bind).unwrap(), + Forward { + listen: "127.0.0.1:47998".parse().unwrap(), + target_host: "192.0.2.10".to_string(), + target_port: 47999, + } + ); + assert!(parse_map("47998", bind).is_err()); + assert!(parse_map("0=127.0.0.1:47999", bind).is_err()); + assert!(parse_map("47998=127.0.0.1", bind).is_err()); + assert!(parse_map("47998=127.0.0.1:0", bind).is_err()); + assert!(parse_map("47998=:47999", bind).is_err()); + } + + /// A loopback UDP echo server on an ephemeral port. + fn spawn_echo() -> u16 { + let sock = UdpSocket::bind("127.0.0.1:0").unwrap(); + let port = sock.local_addr().unwrap().port(); + std::thread::spawn(move || { + let mut buf = vec![0u8; MAX_DATAGRAM_BYTES]; + loop { + match sock.recv_from(&mut buf) { + Ok((n, from)) => { + let _ = sock.send_to(&buf[..n], from); + } + Err(_) => break, + } + } + }); + port + } + + #[test] + fn forward_round_trip() { + let echo_port = spawn_echo(); + let listener = crate::connect_udp::listen("127.0.0.1:0").unwrap(); + let proxy_addr = listener.local_addr().unwrap().to_string(); + std::thread::spawn(move || crate::connect_udp::serve(listener)); + + let sock = Arc::new(UdpSocket::bind("127.0.0.1:0").unwrap()); + let fwd_addr = sock.local_addr().unwrap(); + let fwd = Forward { + listen: fwd_addr, + target_host: "127.0.0.1".to_string(), + target_port: echo_port, + }; + std::thread::spawn(move || serve_socket(&proxy_addr, &fwd, sock)); + + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut buf = [0u8; 64]; + // First datagram opens the session; the second rides it. + for payload in [&b"hello"[..], b"again"] { + client.send_to(payload, fwd_addr).unwrap(); + let (n, _) = client.recv_from(&mut buf).unwrap(); + assert_eq!(&buf[..n], payload); + } + } +}