diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index f14b41c6..c86eeecc 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -17,9 +17,14 @@ clients. Design rationale lives in `` is 1–64 characters from `[A-Za-z0-9._-]`. The daemon keeps its socket, lock and log under `` (default `$HOME/.lithe-server`) in directories only the user can access, and rejects peers with another user -id. A session has one client at a time: a new connection replaces the -current one. A session without a client ends after its idle timeout. -Launchers serialize socket rechecking and daemon creation with a per-identity +id. A session has one client at a time: a new connection that presents the +session token (see below) replaces the current one. The idle timeout runs +only while the session has neither a client nor running processes or open +terminals; it is 10 minutes unless `server.hello` requests another with +`idleTimeoutSeconds`, at most 24 hours, and the latest request applies. A +connection the daemon cannot set up is closed without ending the session. +The daemon log is created `0600`, never through a symbolic link, and moves to +`.log.1` once it reaches 1 MiB. Launchers serialize socket rechecking and daemon creation with a per-identity `.start` advisory lock in the private `run/` directory, bounded by the existing startup deadline. The lock is released when its owning descriptor closes; its inode is retained so concurrent waiters cannot lock different files. This keeps @@ -35,7 +40,11 @@ a redundant launcher from restarting an explicitly closed session. 3. Closing the client-to-server stream is a disconnect. The server never listens on a network port; all traffic, including tunnels, -uses this stream. +uses this stream. Local port forwards are the client's: the reference client +listens on loopback addresses only, because a remote development server +usually has no authentication of its own, and bridges at most 64 connections +per forward, leaving further ones in the system's listen queue until one +ends. Other clients should keep both rules. ## Messages @@ -60,6 +69,12 @@ uses this stream. `terminal.write`, `terminal.resize`, `tunnel.write`, `tunnel.close`, `walk.cancel` — are applied in the order sent. Potentially blocking creation and teardown run on workers; other requests may complete in any order. +- At most 64 requests run on workers at once; a further one fails with + `BUSY` and changes nothing. When the host cannot start a thread that a + request or a new process, terminal, tunnel, watch or walk needs, the + request fails with `BUSY` the same way, before it has any effect. + `environment.resolve` instead falls back to the server's environment and + names the failure in `diagnostics`. - A `process.kill`, `terminal.close`, or `watch.stop` received while the same resource is starting records teardown before worker scheduling. The creating worker applies it after publication, even if the close worker is rejected as @@ -88,7 +103,7 @@ subscribe before creating the resource. | Method | Params | Result | | --- | --- | --- | -| `server.hello` | `protocolVersion`, `clientName`, `idleTimeoutSeconds?` | `protocolVersion`, `serverVersion`, `host`, `session` | +| `server.hello` | `protocolVersion`, `clientName`, `idleTimeoutSeconds?`, `sessionToken?` | `protocolVersion`, `serverVersion`, `host`, `session`; `INVALID_SESSION_TOKEN` closes the connection | | `server.resume` | `afterSeq?` | `truncated`; then every kept event after `afterSeq`, followed by live events | | `server.ack` | `seq` | `null`; events up to `seq` may be forgotten | | `server.shutdown` | — | `null`; the session ends | @@ -125,7 +140,7 @@ subscribe before creating the resource. | `terminal.resize` | `terminalId`, `columns`, `rows` | `null` | | `terminal.close` | `terminalId` | `null`; `SIGHUP` to its session, `SIGKILL` after 2 s | | `environment.resolve` | `refresh` | `environment`, `source`, `diagnostics?` | -| `tunnel.open` | `tunnelId`, `target` (`{kind: tcp, host, port}` / `{kind: unix, path}`) | `null`; `CONNECT_FAILED` on failure | +| `tunnel.open` | `tunnelId`, `target` (`{kind: tcp, host, port}` / `{kind: unix, path}`) | `null`; `CONNECT_FAILED` on failure; `BUSY` while the session has 256 open tunnels | | `tunnel.write` | `tunnelId`, `data` | `null`; `BUSY` when the peer stops reading | | `tunnel.shutdownWrite` | `tunnelId` | `null`; queued data is sent, then the write side is shut down; replies keep arriving | | `tunnel.close` | `tunnelId` | `null`; aborts both directions, queued data is discarded | @@ -229,7 +244,18 @@ changes were lost and the client must rescan the watched tree. ## Event delivery and persistent sessions `server.hello` returns `session` with `persistent`, `resumed`, -`nextResourceId` and `lastEventSeq`. The session keeps every event until the +`nextResourceId`, `lastEventSeq` and, for a persistent session, +`sessionToken`: 128 random bits, hex encoded, fixed for the whole session. +The first client of a persistent session is admitted whatever it presents; +every later `server.hello` must present that token as `sessionToken`. A +missing or different token fails with `INVALID_SESSION_TOKEN`, the server +closes that connection, and the attached client is not disturbed. The socket +already admits only the host account, so the token keeps other programs of +that account, or a second window reusing the key, from taking over the +session and its buffered output. Clients keep it in secret storage and never +log it; the server compares it in constant time. + +The session keeps every event until the client acknowledges it with `server.ack` (clients acknowledge periodically, for example every 256 events), up to 8 MiB; beyond that the oldest kept events are dropped. Written to a socket is not received: when a connection @@ -262,13 +288,15 @@ list. Clients branch on these facts, never on `os` alone, and check ## Error codes -`PROTOCOL_MISMATCH`, `INVALID_REQUEST`, `UNKNOWN_METHOD`, `INVALID_PATH`, +`PROTOCOL_MISMATCH`, `INVALID_SESSION_TOKEN`, `INVALID_REQUEST`, +`UNKNOWN_METHOD`, `INVALID_PATH`, `NOT_FOUND`, `PERMISSION_DENIED`, `ALREADY_EXISTS`, `NOT_A_DIRECTORY`, `IS_A_DIRECTORY`, `DIRECTORY_NOT_EMPTY`, `CONFLICT`, `TOO_LARGE`, `UNKNOWN_RESOURCE`, `RESOURCE_ID_IN_USE`, `SPAWN_FAILED`, `CONNECT_FAILED`, `BUSY`, `UNSUPPORTED`, `IO`. Clients additionally produce `TIMEOUT` and `DISCONNECTED` locally. Messages are for people; OS error numbers stay in -`details`. +`details`. `BUSY` always means a capacity limit that may clear: retrying +later is safe because the failed request changed nothing. ## Compatibility @@ -281,5 +309,11 @@ than reaching an older one. ## Server identity `lithe-remote-server --identity` prints one JSON line with `serverVersion`, -`protocolVersion` and `sha256` of the executable itself. Bootstrappers reuse an -installed server only when the hash matches the artifact they ship. +`protocolVersion` and `sha256` of the executable itself. A binary is never +trusted to report its own hash: bootstrappers reuse an installed server only +when the host's own `sha256sum` or `shasum` computes the hash of the artifact +they ship, and only from install directories that are not symbolic links, +belong to the remote user and are not writable by the group or other users. +On a host without a hash tool, a fresh upload is accepted when its size +matches and `--identity` reports the expected hash, and it is uploaded again +on every connection instead of being reused. diff --git a/rust/crates/remote/src/client/command.rs b/rust/crates/remote/src/client/command.rs index 3dd57c1e..c3f4ab55 100644 --- a/rust/crates/remote/src/client/command.rs +++ b/rust/crates/remote/src/client/command.rs @@ -2,7 +2,7 @@ //! Those tests drive real shells, so the module exists on Unix hosts only. use std::io::{self, Read}; -use std::process::{Command, Stdio}; +use std::process::{Child, Command, Stdio}; use std::sync::mpsc::{self, Receiver}; use std::sync::{Arc, Mutex}; use std::thread; @@ -49,8 +49,17 @@ pub fn run(argv: &[String], timeout: Duration) -> io::Result { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; - let stdout = capture(child.stdout.take()); - let stderr = capture(child.stderr.take()); + let captures = + capture(child.stdout.take()).and_then(|stdout| Ok((stdout, capture(child.stderr.take())?))); + let (stdout, stderr) = match captures { + Ok(captures) => captures, + Err(error) => { + // Without a reader the child could block on a full pipe; a + // started stdout reader ends once the child is gone. + stop(&mut child); + return Err(error); + } + }; let deadline = Instant::now() + timeout; let status = loop { @@ -58,16 +67,7 @@ pub fn run(argv: &[String], timeout: Duration) -> io::Result { break status; } if Instant::now() >= deadline { - crate::failure_log::kill( - "remote.client.operation_failed", - "process_kill", - child.kill(), - ); - crate::failure_log::io( - "remote.client.operation_failed", - "process_wait", - child.wait(), - ); + stop(&mut child); return Err(io::Error::new( io::ErrorKind::TimedOut, format!( @@ -112,28 +112,44 @@ impl Capture { } } -fn capture(pipe: Option) -> Capture { +/// Kills and reaps a child that will not be waited for normally. +fn stop(child: &mut Child) { + crate::failure_log::kill( + "remote.client.operation_failed", + "process_kill", + child.kill(), + ); + crate::failure_log::io( + "remote.client.operation_failed", + "process_wait", + child.wait(), + ); +} + +fn capture(pipe: Option) -> io::Result { let bytes = Arc::new(Mutex::new(Vec::new())); let (finished_sender, finished) = mpsc::channel(); let shared = Arc::clone(&bytes); - thread::spawn(move || { - if let Some(mut pipe) = pipe { - let mut buffer = [0_u8; 8192]; - loop { - match pipe.read(&mut buffer) { - Ok(0) | Err(_) => break, - Ok(read) => { - let mut captured = shared - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let room = CAPTURE_LIMIT_BYTES.saturating_sub(captured.len()); - captured.extend_from_slice(&buffer[..read.min(room)]); + thread::Builder::new() + .name("remote-command-output".into()) + .spawn(move || { + if let Some(mut pipe) = pipe { + let mut buffer = [0_u8; 8192]; + loop { + match pipe.read(&mut buffer) { + Ok(0) | Err(_) => break, + Ok(read) => { + let mut captured = shared + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let room = CAPTURE_LIMIT_BYTES.saturating_sub(captured.len()); + captured.extend_from_slice(&buffer[..read.min(room)]); + } } } } - } - // log-exempt: User cancellation: the command caller already stopped collecting output and no longer waits for the capture completion notification. - let _ = finished_sender.send(()); - }); - Capture { bytes, finished } + // log-exempt: User cancellation: the command caller already stopped collecting output and no longer waits for the capture completion notification. + let _ = finished_sender.send(()); + })?; + Ok(Capture { bytes, finished }) } diff --git a/rust/crates/remote/src/client/forward.rs b/rust/crates/remote/src/client/forward.rs index ed802c31..7db6a55d 100644 --- a/rust/crates/remote/src/client/forward.rs +++ b/rust/crates/remote/src/client/forward.rs @@ -5,6 +5,17 @@ //! `http://127.0.0.1:` in a browser reaches a server that only //! listens on the remote machine's loopback interface. //! +//! Forwards listen on loopback addresses only. A forward on every interface +//! would hand the remote service, often a development server without any +//! authentication, to everyone on the local network, so +//! [`PortForward::start`] refuses other addresses instead of leaving the +//! choice to each caller. +//! +//! One forward bridges at most 64 connections at once. Further connections +//! are accepted only when one of them ends: until then they wait in the +//! system's listen queue, as with a busy server, instead of costing threads +//! here and a tunnel on the remote, which limits tunnels per session. +//! //! Starting and removing a forward are recorded in the session's //! [`ConnectionLog`] with the local port and the number of accepted //! connections; the remote host and socket path are not recorded. @@ -16,15 +27,26 @@ use crate::protocol::methods::TunnelTarget; use std::io::{self, Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; const READ_CHUNK_BYTES: usize = 32 * 1024; +/// Most connections one forward bridges at once. +const MAX_CONNECTIONS: usize = 64; + /// Pause after a failed `accept`. const ACCEPT_FAILURE_BACKOFF: Duration = Duration::from_millis(200); +/// How often an acceptor waiting for a free connection slot checks whether +/// its forward is being removed. +const STOP_CHECK: Duration = Duration::from_millis(200); + +/// Bound for the connection that wakes the acceptor when the forward is +/// removed, so that removing a forward never hangs on its own listener. +const WAKEUP_TIMEOUT: Duration = Duration::from_secs(1); + /// How long a tunnel waits for remote data before checking whether the /// local side has gone away. Data ends the wait immediately. const IDLE_CHECK: Duration = Duration::from_secs(1); @@ -35,77 +57,47 @@ pub struct PortForward { local_address: SocketAddr, stopping: Arc, acceptor: Option>, - /// Local connections accepted so far. + /// Local connections handed to a bridge so far. accepted: Arc, started: Instant, log: ConnectionLog, } impl PortForward { - /// Starts forwarding `bind` to `target`. Use port 0 to let the system - /// choose a free local port, then read [`PortForward::local_address`]. + /// Starts forwarding `bind` to `target`. `bind` must be a loopback + /// address such as `127.0.0.1` or `::1`; any other address fails with + /// [`io::ErrorKind::InvalidInput`] before a socket is opened. Use port 0 + /// to let the system choose a free local port, then read + /// [`PortForward::local_address`]. pub fn start( session: Arc, bind: SocketAddr, target: TunnelTarget, ) -> io::Result { + if !bind.ip().is_loopback() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "port forwards listen on loopback addresses only", + )); + } let listener = TcpListener::bind(bind)?; let local_address = listener.local_addr()?; let stopping = Arc::new(AtomicBool::new(false)); let accepted = Arc::new(AtomicU64::new(0)); let log = session.connection_log().clone(); let started = Instant::now(); - let acceptor = { - let stopping = Arc::clone(&stopping); - let accepted = Arc::clone(&accepted); - let log = log.clone(); - let target = target.clone(); - thread::Builder::new() - .name("remote-forward".into()) - .spawn(move || { - for connection in listener.incoming() { - if stopping.load(Ordering::Acquire) { - return; - } - let connection = match connection { - Ok(connection) => connection, - Err(error) => { - forward_failed( - "remote.forward.accept_failed", - &log, - "accept", - &format!("{:?}", error.kind()), - "io", - &ACCEPT_LOG, - ); - // Failures such as EMFILE repeat immediately; - // pausing keeps the acceptor from spinning. - thread::sleep(ACCEPT_FAILURE_BACKOFF); - continue; - } - }; - accepted.fetch_add(1, Ordering::Relaxed); - let session = Arc::clone(&session); - let target = target.clone(); - let log = log.clone(); - thread::spawn(move || { - if let Err(error) = bridge(&session, connection, target) { - if let Some(category) = crate::failure_log::bridge_category(&error) - { - forward_failed( - "remote.forward.connection_failed", - &log, - "bridge", - &category, - "remote", - &BRIDGE_LOG, - ); - } - } - }); - } - })? + let acceptor = Acceptor { + listener, + session, + target: target.clone(), + stopping: Arc::clone(&stopping), + accepted: Arc::clone(&accepted), + log: log.clone(), + slots: Arc::new(Slots::new(MAX_CONNECTIONS)), }; + let acceptor = thread::Builder::new() + .name("remote-forward".into()) + .spawn(move || acceptor.run())?; log.forward_started(local_address, &target); Ok(Self { local_address, @@ -121,6 +113,25 @@ impl PortForward { pub fn local_address(&self) -> SocketAddr { self.local_address } + + /// Connects to the listener so that an acceptor waiting in `accept` + /// observes `stopping`, and returns whether joining the acceptor is + /// bounded. An acceptor waiting for a free slot needs no wakeup. + fn wake_acceptor(&self) -> bool { + match TcpStream::connect_timeout(&self.local_address, WAKEUP_TIMEOUT) { + Ok(_) => true, + // log-exempt: Expected absence: ConnectionRefused means the listener closed because its acceptor exited after the caller checked it. + Err(error) if error.kind() == io::ErrorKind::ConnectionRefused => true, + Err(error) => { + crate::failure_log::io::<()>( + "remote.client.operation_failed", + "acceptor_wakeup", + Err(error), + ); + false + } + } + } } impl Drop for PortForward { @@ -128,26 +139,21 @@ impl Drop for PortForward { /// until either side closes them. fn drop(&mut self) { self.stopping.store(true, Ordering::Release); - // The acceptor owns the listener. A refused wakeup means that owner - // already dropped it; otherwise the next accept result observes stopping. - match TcpStream::connect(self.local_address) { - Ok(_) => {} - // log-exempt: Expected absence: ConnectionRefused means the listener closed because its owning acceptor already exited. - Err(error) if error.kind() == io::ErrorKind::ConnectionRefused => {} - Err(error) => crate::failure_log::io::<()>( - "remote.client.operation_failed", - "acceptor_wakeup", - Err(error), - ), - } if let Some(acceptor) = self.acceptor.take() { - crate::failure_log::outcome( - "remote.client.operation_failed", - "forward_acceptor_join", - acceptor.join(), - "panic", - "thread", - ); + // Without a wakeup, for example when no descriptor is left for + // it, the acceptor may wait in `accept` until some connection + // arrives. It is then left to end on that connection, which + // keeps the listener open until it does, rather than blocking + // the caller. + if acceptor.is_finished() || self.wake_acceptor() { + crate::failure_log::outcome( + "remote.client.operation_failed", + "forward_acceptor_join", + acceptor.join(), + "panic", + "thread", + ); + } } self.log.forward_removed( self.local_address.port(), @@ -157,6 +163,131 @@ impl Drop for PortForward { } } +/// The thread that accepts local connections and starts their bridges. +struct Acceptor { + listener: TcpListener, + session: Arc, + target: TunnelTarget, + stopping: Arc, + accepted: Arc, + log: ConnectionLog, + slots: Arc, +} + +impl Acceptor { + fn run(self) { + loop { + // A connection is accepted only once it can be bridged. + let Some(slot) = self.slots.acquire(&self.stopping) else { + return; + }; + let connection = self.listener.accept(); + if self.stopping.load(Ordering::Acquire) { + return; + } + match connection { + Ok((connection, _)) => self.bridge(connection, slot), + Err(error) => { + forward_failed( + "remote.forward.accept_failed", + &self.log, + "accept", + &format!("{:?}", error.kind()), + "io", + &ACCEPT_LOG, + ); + // Failures such as EMFILE repeat immediately; pausing + // keeps the acceptor from spinning. + thread::sleep(ACCEPT_FAILURE_BACKOFF); + } + } + } + } + + fn bridge(&self, connection: TcpStream, slot: Slot) { + let session = Arc::clone(&self.session); + let target = self.target.clone(); + let log = self.log.clone(); + let spawned = thread::Builder::new() + .name("remote-forward-connection".into()) + .spawn(move || { + let _slot = slot; + if let Err(error) = bridge(&session, connection, target) { + if let Some(category) = crate::failure_log::bridge_category(&error) { + forward_failed( + "remote.forward.connection_failed", + &log, + "bridge", + &category, + "remote", + &BRIDGE_LOG, + ); + } + } + }); + match spawned { + Ok(_) => { + self.accepted.fetch_add(1, Ordering::Relaxed); + } + // The closure that never ran is dropped with the error, which + // closes the local connection and frees its slot. + Err(error) => forward_failed( + "remote.forward.connection_failed", + &self.log, + "spawn", + &format!("{:?}", error.kind()), + "io", + &BRIDGE_LOG, + ), + } + } +} + +/// The connections one forward is bridging, at most `limit` at once. +struct Slots { + limit: usize, + active: Mutex, + freed: Condvar, +} + +impl Slots { + fn new(limit: usize) -> Self { + Self { + limit, + active: Mutex::new(0), + freed: Condvar::new(), + } + } + + /// Waits for a free slot, or returns `None` once the forward stops. + fn acquire(self: &Arc, stopping: &AtomicBool) -> Option { + let mut active = self.active.lock().unwrap_or_else(PoisonError::into_inner); + while *active >= self.limit { + if stopping.load(Ordering::Acquire) { + return None; + } + active = self + .freed + .wait_timeout(active, STOP_CHECK) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + *active += 1; + Some(Slot(Arc::clone(self))) + } +} + +/// One bridged connection's slot, freed when its bridge ends, including when +/// the bridge thread never starts or panics. +struct Slot(Arc); + +impl Drop for Slot { + fn drop(&mut self) { + *self.0.active.lock().unwrap_or_else(PoisonError::into_inner) -= 1; + self.0.freed.notify_one(); + } +} + fn bridge( session: &RemoteSession, local: TcpStream, @@ -182,29 +313,37 @@ fn bridge( thread::scope(|scope| { let local_done_writer = Arc::clone(&local_done); let writer = tunnel.writer(); - scope.spawn(move || { - let mut buffer = vec![0_u8; READ_CHUNK_BYTES]; - let local_ended = loop { - match to_remote.read(&mut buffer) { - Ok(0) => break true, - Ok(read) => { - if writer.write(&buffer[..read]).is_err() { - break false; + let upload = thread::Builder::new() + .name("remote-forward-upload".into()) + .spawn_scoped(scope, move || { + let mut buffer = vec![0_u8; READ_CHUNK_BYTES]; + let local_ended = loop { + match to_remote.read(&mut buffer) { + Ok(0) => break true, + Ok(read) => { + if writer.write(&buffer[..read]).is_err() { + break false; + } } + Err(_) => break false, } - Err(_) => break false, + }; + local_done_writer.store(true, Ordering::Release); + if local_ended { + // The local client finished sending, as HTTP/1.0 clients + // and `nc -N` do, and now waits for the reply: pass the + // half-close on after the queued data, and keep receiving. + crate::failure_log::client("tunnel_half_close", writer.shutdown_write()); + } else { + crate::failure_log::client("tunnel_close", writer.close()); } - }; - local_done_writer.store(true, Ordering::Release); - if local_ended { - // The local client finished sending, as HTTP/1.0 clients and - // `nc -N` do, and now waits for the reply: pass the half-close - // on after the queued data, and keep receiving. - crate::failure_log::client("tunnel_half_close", writer.shutdown_write()); - } else { - crate::failure_log::client("tunnel_close", writer.close()); - } - }); + }); + if let Err(error) = upload { + crate::failure_log::client("tunnel_close", tunnel.close()); + // log-exempt: Same failure already recorded: the spawn error propagates to the bridge boundary and is recorded there, so closing the local connection afterwards is not recorded again. + let _ = to_local.shutdown(Shutdown::Both); + return Err(ClientError::Spawn(error)); + } loop { match tunnel.next_event(IDLE_CHECK) { Ok(Some(TunnelEvent::Data(bytes))) => { @@ -227,8 +366,8 @@ fn bridge( "socket_shutdown", to_local.shutdown(Shutdown::Both), ); - }); - Ok(()) + Ok(()) + }) } // Each forward failure family emits at most once per five seconds process-wide, @@ -280,3 +419,22 @@ mod failure_tests { )); } } + +#[cfg(test)] +mod slot_tests { + use super::Slots; + use std::sync::atomic::AtomicBool; + use std::sync::Arc; + + #[test] + fn a_full_forward_admits_a_connection_once_another_ends() { + let slots = Arc::new(Slots::new(2)); + let running = AtomicBool::new(false); + let first = slots.acquire(&running).unwrap(); + let _second = slots.acquire(&running).unwrap(); + // A stopping forward gives up instead of waiting for a free slot. + assert!(slots.acquire(&AtomicBool::new(true)).is_none()); + drop(first); + assert!(slots.acquire(&running).is_some()); + } +} diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index 2a8c5b25..389e9b05 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -416,7 +416,12 @@ impl RemoteSession { let stdout = child.stdout.take().expect("stdout is piped"); let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); if let Some(stderr) = child.stderr.take() { - keep_tail(stderr, Arc::clone(&stderr_tail)); + if let Err(error) = keep_tail(stderr, Arc::clone(&stderr_tail)) { + abandon(Some(child)); + let error = ClientError::Spawn(error); + log.connect_failed("connect", &error.failure_category(), "remote"); + return Err(error); + } } Self::establish( stdout, @@ -471,15 +476,18 @@ impl RemoteSession { let outgoing = Arc::new(Outgoing::default()); let next_request = Arc::new(AtomicU64::new(0)); let last_seq = Arc::new(AtomicU64::new(0)); - { + let writer = { let outgoing = Arc::clone(&outgoing); let pending = Arc::clone(&pending); thread::Builder::new() .name("remote-writer".into()) .spawn(move || write_loop(writer, &outgoing, &pending)) - .map_err(ClientError::Spawn)?; + }; + if let Err(error) = writer { + abandon(child); + return Err(ClientError::Spawn(error)); } - { + let reader = { let reader_context = ReaderContext { pending: Arc::clone(&pending), routes: Arc::clone(&routes), @@ -492,7 +500,13 @@ impl RemoteSession { thread::Builder::new() .name("remote-reader".into()) .spawn(move || read_loop(reader, reader_context, ready_sender)) - .map_err(ClientError::Spawn)?; + }; + if let Err(error) = reader { + // Ends the writer thread, which otherwise waits for requests + // that never come. + outgoing.close(); + abandon(child); + return Err(ClientError::Spawn(error)); } let mut session = Self { outgoing, @@ -730,18 +744,7 @@ impl Drop for RemoteSession { // is released when the transport is killed below. self.outgoing.close(); if !self.wait_for_transport_exit(SHUTDOWN_GRACE) { - if let Some(child) = lock(&self.child).as_mut() { - crate::failure_log::kill( - "remote.client.operation_failed", - "process_kill", - child.kill(), - ); - crate::failure_log::io( - "remote.client.operation_failed", - "process_wait", - child.wait(), - ); - } + abandon(lock(&self.child).take()); } } } @@ -912,21 +915,45 @@ fn close(pending: &Mutex) { } } -fn keep_tail(mut stderr: impl Read + Send + 'static, tail: Arc>>) { - thread::spawn(move || { - let mut buffer = [0_u8; 4096]; - loop { - match stderr.read(&mut buffer) { - Ok(0) | Err(_) => return, - Ok(read) => { - let mut tail = lock(&tail); - tail.extend(&buffer[..read]); - let excess = tail.len().saturating_sub(STDERR_TAIL_BYTES); - tail.drain(..excess); +fn keep_tail( + mut stderr: impl Read + Send + 'static, + tail: Arc>>, +) -> io::Result<()> { + thread::Builder::new() + .name("remote-stderr".into()) + .spawn(move || { + let mut buffer = [0_u8; 4096]; + loop { + match stderr.read(&mut buffer) { + Ok(0) | Err(_) => return, + Ok(read) => { + let mut tail = lock(&tail); + tail.extend(&buffer[..read]); + let excess = tail.len().saturating_sub(STDERR_TAIL_BYTES); + tail.drain(..excess); + } } } - } - }); + }) + .map(drop) +} + +/// Kills and reaps a transport process: one that outlived its session's +/// shutdown grace, or one that never became a session because no thread +/// could be started for it. Dropping a `Child` neither stops nor reaps it. +fn abandon(child: Option) { + if let Some(mut child) = child { + crate::failure_log::kill( + "remote.client.operation_failed", + "process_kill", + child.kill(), + ); + crate::failure_log::io( + "remote.client.operation_failed", + "process_wait", + child.wait(), + ); + } } fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { diff --git a/rust/crates/remote/src/protocol/message.rs b/rust/crates/remote/src/protocol/message.rs index d61e81c9..934c709f 100644 --- a/rust/crates/remote/src/protocol/message.rs +++ b/rust/crates/remote/src/protocol/message.rs @@ -112,7 +112,10 @@ pub enum ErrorCode { SpawnFailed, /// A tunnel could not connect to its remote target. ConnectFailed, - /// The server has too many requests in flight. + /// A capacity limit was reached, for now: too many requests in flight, + /// too many open tunnels, an input queue that is not being read, a + /// concurrent operation on the same upload, or a host that cannot start + /// another thread. Nothing was changed; the request may be retried. Busy, /// The operation is not available on this host. Unsupported, diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index fe7f6108..c54a6a21 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -303,14 +303,13 @@ fn dispatch_to_worker(context: &Context, id: u64, method: String, params: Value, return; } }; - let workers = &context.session.workers; - if !workers.try_acquire() { + let Some(slot) = WorkerSlot::acquire(&context.session) else { outbox.send(Message::failure( id, RemoteError::new(ErrorCode::Busy, "too many requests in flight"), )); return; - } + }; let worker_outbox = outbox.clone(); let worker_context = context.clone(); let spawned = thread::Builder::new() @@ -328,17 +327,37 @@ fn dispatch_to_worker(context: &Context, id: u64, method: String, params: Value, // up cancellation of an already-published resource. drop(order); worker_outbox.send(respond(id, reply)); - worker_context.session.workers.release(); + drop(slot); }); + // A closure that never ran is dropped with the error, and its slot with it. if let Err(error) = spawned { - workers.release(); outbox.send(Message::failure( id, - RemoteError::new(ErrorCode::Busy, format!("cannot start worker: {error}")), + crate::server::threads::unavailable(error), )); } } +/// One of the session's in-flight request slots. It is released when the +/// worker drops it, including while a panicking handler unwinds, so a failed +/// request cannot use up the limit for the rest of the session. +struct WorkerSlot(Arc); + +impl WorkerSlot { + fn acquire(session: &Arc) -> Option { + session + .workers + .try_acquire() + .then(|| Self(Arc::clone(session))) + } +} + +impl Drop for WorkerSlot { + fn drop(&mut self) { + self.0.workers.release(); + } +} + enum ResourceOrder { Start { guard: StartGuard, diff --git a/rust/crates/remote/src/server/connection/tests.rs b/rust/crates/remote/src/server/connection/tests.rs index 9500f9f2..897c48f5 100644 --- a/rust/crates/remote/src/server/connection/tests.rs +++ b/rust/crates/remote/src/server/connection/tests.rs @@ -325,3 +325,17 @@ fn pending_close_reports_the_creators_cleanup_failure_instead_of_success() { assert_eq!(close.wait(Duration::ZERO), Err(failure)); ResourceOrder::prepare(&session, methods::FS_CREATE_RUN_DIRECTORY, ¶ms).unwrap(); } + +#[test] +fn a_panicking_worker_gives_its_slot_back() { + let session = Session::new(false).unwrap(); + let _cleanup = Cleanup(Arc::clone(&session)); + let slot = WorkerSlot::acquire(&session).unwrap(); + assert_eq!(session.workers.drain(Duration::ZERO), 1); + let worker = thread::spawn(move || { + let _slot = slot; + panic!("a handler failed"); + }); + assert!(worker.join().is_err()); + assert_eq!(session.workers.drain(Duration::ZERO), 0); +} diff --git a/rust/crates/remote/src/server/daemon.rs b/rust/crates/remote/src/server/daemon.rs index 6b0e0b84..f81d3ec7 100644 --- a/rust/crates/remote/src/server/daemon.rs +++ b/rust/crates/remote/src/server/daemon.rs @@ -36,7 +36,7 @@ use std::os::unix::net::{UnixListener, UnixStream}; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; @@ -334,11 +334,13 @@ fn wait_for_socket(socket: &Path, deadline: Instant) -> io::Result { /// Copies bytes in both directions until the daemon closes the connection. fn relay(stream: UnixStream) -> io::Result<()> { let mut to_daemon = stream.try_clone()?; - thread::spawn(move || { - let _ = io::copy(&mut io::stdin().lock(), &mut to_daemon); - // End-of-file from the transport is the client's disconnect. - let _ = to_daemon.shutdown(std::net::Shutdown::Write); - }); + thread::Builder::new() + .name("remote-relay".into()) + .spawn(move || { + let _ = io::copy(&mut io::stdin().lock(), &mut to_daemon); + // End-of-file from the transport is the client's disconnect. + let _ = to_daemon.shutdown(std::net::Shutdown::Write); + })?; let mut from_daemon = stream; let mut stdout = io::stdout().lock(); let mut buffer = vec![0_u8; 64 * 1024]; @@ -385,7 +387,7 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { listener.set_nonblocking(true)?; let session = Session::new(true)?; - let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let shutdown = Arc::new(AtomicBool::new(false)); { // A client that reconnects right after `server.shutdown` must not // reach this ending session: the socket disappears before the @@ -400,7 +402,7 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { let attached = Arc::new(AtomicUsize::new(0)); // The attached connection's id and a copy of its socket, kept so that a // replacing connection can disconnect it. - let current: Arc>> = Arc::new(Mutex::new(None)); + let current: Current = Arc::new(Mutex::new(None)); let mut next_connection: u64 = 0; let mut idle_since = Instant::now(); let mut log_rotation_failed = false; @@ -412,58 +414,20 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { eprintln!("lithe-remote-server: rejected a connection from another user"); continue; } - stream.set_nonblocking(false)?; next_connection += 1; - let connection_id = next_connection; - let replacement = stream.try_clone()?; - let current = Arc::clone(¤t); - attached.fetch_add(1, Ordering::AcqRel); - let session = Arc::clone(&session); - let attached = Arc::clone(&attached); - let shutdown = Arc::clone(&shutdown); - thread::Builder::new() - .name("remote-connection".into()) - .spawn(move || { - let input = match stream.try_clone() { - Ok(input) => input, - Err(error) => { - eprintln!("lithe-remote-server: {error}"); - attached.fetch_sub(1, Ordering::AcqRel); - return; - } - }; - // An admitted client replaces the attached one, which - // may be half-dead after a network change and not yet - // noticed. A connection the session refuses leaves it - // alone, and its copy closes with the unused closure. - let attach = { - let current = Arc::clone(¤t); - move || { - if let Some((_, previous)) = crate::server::lock(¤t) - .replace((connection_id, replacement)) - { - // log-exempt: Expected absence: the replaced client may already have disconnected, which is why it is being replaced. - let _ = previous.shutdown(std::net::Shutdown::Both); - } - } - }; - let ended = connection::serve(&session, input, stream, attach); - // The copy kept for replacement is the last open - // descriptor of this socket. Closing it delivers - // end-of-file to the proxy, which would otherwise - // linger on the host after every disconnect. - // (`shutdown` is not enough: BSD rejects it with - // ENOTCONN once the peer has half-closed.) - let mut current = crate::server::lock(¤t); - if matches!(&*current, Some((id, _)) if *id == connection_id) { - current.take(); - } - drop(current); - if matches!(ended, Ok(Ended::Shutdown)) { - shutdown.store(true, Ordering::Release); - } - attached.fetch_sub(1, Ordering::AcqRel); - })?; + let connection = Connection { + id: next_connection, + session: Arc::clone(&session), + current: Arc::clone(¤t), + shutdown: Arc::clone(&shutdown), + attached: Attached::count(&attached), + }; + if let Err(error) = connection.start(stream) { + // The client sees its connection close and may connect + // again; one connection that cannot be set up must not + // end the session and the programs running in it. + eprintln!("lithe-remote-server: cannot serve a connection: {error}"); + } } Err(error) if error.kind() == io::ErrorKind::WouldBlock => { if attached.load(Ordering::Acquire) > 0 || session.keeps_programs() { @@ -501,6 +465,87 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { Ok(()) } +/// The attached connection's id and a copy of its socket. +type Current = Arc>>; + +/// One accepted connection, before its thread starts. +struct Connection { + id: u64, + session: Arc, + current: Current, + shutdown: Arc, + attached: Attached, +} + +impl Connection { + /// Serves the connection on its own thread. A failure drops everything, + /// which closes the socket and ends the connection's attached count. + fn start(self, stream: UnixStream) -> io::Result<()> { + stream.set_nonblocking(false)?; + let input = stream.try_clone()?; + let replacement = stream.try_clone()?; + thread::Builder::new() + .name("remote-connection".into()) + .spawn(move || { + let Self { + id, + session, + current, + shutdown, + attached, + } = self; + // An admitted client replaces the attached one, which may be + // half-dead after a network change and not yet noticed. A + // connection the session refuses leaves it alone, and its copy + // closes with the unused closure. + let attach = { + let current = Arc::clone(¤t); + move || { + if let Some((_, previous)) = + crate::server::lock(¤t).replace((id, replacement)) + { + // log-exempt: Expected absence: the replaced client may already have disconnected, which is why it is being replaced. + let _ = previous.shutdown(std::net::Shutdown::Both); + } + } + }; + let ended = connection::serve(&session, input, stream, attach); + // The copy kept for replacement is the last open descriptor of + // this socket. Closing it delivers end-of-file to the proxy, + // which would otherwise linger on the host after every + // disconnect. (`shutdown` is not enough: BSD rejects it with + // ENOTCONN once the peer has half-closed.) + let mut current = crate::server::lock(¤t); + if matches!(&*current, Some((attached_id, _)) if *attached_id == id) { + current.take(); + } + drop(current); + if matches!(ended, Ok(Ended::Shutdown)) { + shutdown.store(true, Ordering::Release); + } + drop(attached); + })?; + Ok(()) + } +} + +/// Counts a connection for the idle timer from accept until its thread ends. +/// Dropping it ends the count, including when the thread never started. +struct Attached(Arc); + +impl Attached { + fn count(attached: &Arc) -> Self { + attached.fetch_add(1, Ordering::AcqRel); + Self(Arc::clone(attached)) + } +} + +impl Drop for Attached { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} + /// Takes the exclusive lock for the key. Another daemon holding it is either /// serving the key, then this daemon is redundant and exits, or ending its /// session after removing the socket, then this daemon waits for it so the diff --git a/rust/crates/remote/src/server/mod.rs b/rust/crates/remote/src/server/mod.rs index 9714bb9a..f92deff6 100644 --- a/rust/crates/remote/src/server/mod.rs +++ b/rust/crates/remote/src/server/mod.rs @@ -33,6 +33,7 @@ mod run_directory; mod session; mod spawner; mod terminal; +mod threads; mod tunnel; mod upload; mod walk; diff --git a/rust/crates/remote/src/server/platform/linux_watch.rs b/rust/crates/remote/src/server/platform/linux_watch.rs index 28af5120..944a71cb 100644 --- a/rust/crates/remote/src/server/platform/linux_watch.rs +++ b/rust/crates/remote/src/server/platform/linux_watch.rs @@ -8,6 +8,9 @@ //! produce no events of their own. use crate::protocol::methods::{ChangeKind, WatchBackend}; +use crate::protocol::RemoteError; +use crate::server::fs::io_error; +use crate::server::threads::Parked; use crate::server::watch::{Excludes, RawEvent, Sink}; use std::collections::HashMap; use std::ffi::OsStr; @@ -16,7 +19,7 @@ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::thread::{self, JoinHandle}; +use std::thread::JoinHandle; pub(crate) const BACKEND: WatchBackend = WatchBackend::Inotify; @@ -62,45 +65,86 @@ impl Drop for Watcher { } } +/// Starts watching `root`. `requested` is the root as the client spelled it, +/// for error messages. pub(crate) fn start( root: PathBuf, + requested: &str, excludes: Arc, sink: Sink, -) -> io::Result<(Watcher, Option)> { - // SAFETY: inotify_init1 has no memory-safety preconditions. - let fd = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) }; - if fd == -1 { - return Err(io::Error::last_os_error()); - } - // SAFETY: the descriptor was just created and is owned here. - let inotify = unsafe { OwnedFd::from_raw_fd(fd) }; - let mut tree = Tree { - fd: inotify.as_raw_fd(), - root: root.clone(), - by_descriptor: HashMap::new(), - limit_reported: false, - excludes, - }; - let root_descriptor = tree.add(&root)?; - tree.add_below(&root, &sink, false); - let watched = tree.by_descriptor.len() as u64; - - let (stop_read, stop_write) = pipe()?; - let thread = thread::Builder::new() - .name("remote-inotify".into()) - .spawn(move || { - let _inotify = inotify; - tree.run(root_descriptor, stop_read, sink); - })?; +) -> Result<(Watcher, Option), RemoteError> { + // The thread starts before any directory is registered, so a host out of + // threads refuses the watch with nothing to release. + let thread = Parked::start("remote-inotify", Backend::run)?; + let (backend, stop) = + Backend::register(root, excludes, sink).map_err(|error| io_error(error, requested))?; + let watched = backend.tree.by_descriptor.len() as u64; Ok(( Watcher { - stop: Some(stop_write), - thread: Some(thread), + stop: Some(stop), + thread: Some(thread.run(backend)), }, Some(watched), )) } +/// What the backend thread owns while it runs. +struct Backend { + /// Kept open until the thread ends; closing it releases every + /// registration at once. + inotify: OwnedFd, + tree: Tree, + root_descriptor: i32, + stop: OwnedFd, + sink: Sink, +} + +impl Backend { + /// Registers `root` and every directory below it. Also returns the write + /// end of the stop pipe, which [`Watcher`] closes to stop the thread. + fn register(root: PathBuf, excludes: Arc, sink: Sink) -> io::Result<(Self, OwnedFd)> { + // SAFETY: inotify_init1 has no memory-safety preconditions. + let fd = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) }; + if fd == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: the descriptor was just created and is owned here. + let inotify = unsafe { OwnedFd::from_raw_fd(fd) }; + let mut tree = Tree { + fd: inotify.as_raw_fd(), + root: root.clone(), + by_descriptor: HashMap::new(), + limit_reported: false, + excludes, + }; + let root_descriptor = tree.add(&root)?; + tree.add_below(&root, &sink, false); + let (stop, stop_write) = pipe()?; + Ok(( + Self { + inotify, + tree, + root_descriptor, + stop, + sink, + }, + stop_write, + )) + } + + fn run(self) { + let Self { + inotify, + mut tree, + root_descriptor, + stop, + sink, + } = self; + tree.run(root_descriptor, stop, sink); + drop(inotify); + } +} + struct Tree { fd: RawFd, root: PathBuf, diff --git a/rust/crates/remote/src/server/platform/macos_watch.rs b/rust/crates/remote/src/server/platform/macos_watch.rs index 2bd8eb38..c9ed32e7 100644 --- a/rust/crates/remote/src/server/platform/macos_watch.rs +++ b/rust/crates/remote/src/server/platform/macos_watch.rs @@ -8,6 +8,8 @@ //! free of framework wrapper crates. use crate::protocol::methods::{ChangeKind, WatchBackend}; +use crate::protocol::RemoteError; +use crate::server::fs::io_error; use crate::server::watch::{Excludes, RawEvent, Sink}; use std::collections::HashSet; use std::ffi::{c_char, c_void, CStr}; @@ -151,7 +153,19 @@ impl Drop for Watcher { extern "C" fn drain(_: *mut c_void) {} +/// Starts watching `root`. `requested` is the root as the client spelled it, +/// for error messages. FSEvents calls back on a dispatch queue, so no thread +/// of the server's is needed. pub(crate) fn start( + root: PathBuf, + requested: &str, + excludes: Arc, + sink: Sink, +) -> Result<(Watcher, Option), RemoteError> { + stream(root, excludes, sink).map_err(|error| io_error(error, requested)) +} + +fn stream( root: PathBuf, excludes: Arc, sink: Sink, diff --git a/rust/crates/remote/src/server/platform/unix.rs b/rust/crates/remote/src/server/platform/unix.rs index 9441a3aa..5139b4dc 100644 --- a/rust/crates/remote/src/server/platform/unix.rs +++ b/rust/crates/remote/src/server/platform/unix.rs @@ -278,11 +278,18 @@ pub(crate) fn collect_output( use std::io::Read; let (sender, receiver) = std::sync::mpsc::channel(); if let Some(mut stdout) = child.stdout.take() { - std::thread::spawn(move || { - let mut bytes = Vec::new(); - let _ = stdout.read_to_end(&mut bytes); - let _ = sender.send(bytes); - }); + let reader = std::thread::Builder::new() + .name("remote-helper-output".into()) + .spawn(move || { + let mut bytes = Vec::new(); + let _ = stdout.read_to_end(&mut bytes); + let _ = sender.send(bytes); + }); + if let Err(error) = reader { + // Unread, the helper could block on a full pipe until killed. + kill_helper(&mut child); + return Err(error); + } } else { let _ = sender.send(Vec::new()); } @@ -292,9 +299,7 @@ pub(crate) fn collect_output( break status; } if std::time::Instant::now() >= deadline { - let _ = signal_process_group(child.id(), libc::SIGKILL); - let _ = child.kill(); - let _ = child.wait(); + kill_helper(&mut child); return Err(io::Error::new( io::ErrorKind::TimedOut, "helper command timed out", @@ -308,3 +313,10 @@ pub(crate) fn collect_output( .unwrap_or_default(); Ok((status, stdout)) } + +/// Kills a helper's whole process group and reaps the helper. +fn kill_helper(child: &mut std::process::Child) { + let _ = signal_process_group(child.id(), libc::SIGKILL); + let _ = child.kill(); + let _ = child.wait(); +} diff --git a/rust/crates/remote/src/server/process.rs b/rust/crates/remote/src/server/process.rs index 5afea52a..d764c595 100644 --- a/rust/crates/remote/src/server/process.rs +++ b/rust/crates/remote/src/server/process.rs @@ -20,14 +20,14 @@ use crate::server::fs::{host_path, io_error}; use crate::server::platform::{self, ChildKind}; use crate::server::resources::Registry; use crate::server::session::Session; +use crate::server::threads::Parked; use crate::server::{parse, to_value}; use serde_json::{json, Value}; use std::io::{self, Read, Write}; use std::os::unix::process::ExitStatusExt; -use std::process::{Child, Command, ExitStatus, Stdio}; +use std::process::{Child, ChildStdin, Command, ExitStatus, Stdio}; use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError}; use std::sync::{Arc, Mutex}; -use std::thread; use std::time::{Duration, Instant}; pub(crate) const OUTPUT_CHUNK_BYTES: usize = 32 * 1024; @@ -172,6 +172,13 @@ impl ProcessTable { command.current_dir(host_path(cwd)?); } platform::prepare_child(&mut command, ChildKind::Plain); + // Every thread the child needs starts before the child does. + let stdin_writer = if params.pipe_stdin { + Some(InputWriter::::start(drop)?) + } else { + None + }; + let monitor = Self::monitor(session, params.process_id)?; let program_name = program.clone(); let mut child = session .spawner @@ -179,7 +186,9 @@ impl ProcessTable { .map_err(|error| spawn_error(&program_name, error))?; let pid = child.id(); - let stdin = child.stdin.take().map(start_input_writer); + let stdin = stdin_writer + .zip(child.stdin.take()) + .map(|(writer, pipe)| writer.attach(pipe)); let entry = RunningProcess { leader: Leader::new(pid), argv: params.argv.clone(), @@ -192,25 +201,23 @@ impl ProcessTable { let _ = child.wait(); return Err(error); } - self.start_monitor(Arc::clone(session), params.process_id, child); + let pipes: [Option>; 2] = [ + child.stdout.take().map(|pipe| Box::new(pipe) as _), + child.stderr.take().map(|pipe| Box::new(pipe) as _), + ]; + monitor.follow(pipes, child); Ok(SpawnResult { pid }) } - fn start_monitor(&self, session: Arc, process_id: u64, mut child: Child) { - let mut gate = OutputGate::new(); - let pipes = [ - child - .stdout - .take() - .map(|pipe| (Box::new(pipe) as Box, OutputStream::Stdout)), - child - .stderr - .take() - .map(|pipe| (Box::new(pipe) as Box, OutputStream::Stderr)), - ]; - for (pipe, stream) in pipes.into_iter().flatten() { - let session = Arc::clone(&session); - gate.start_reader(pipe, move |chunk| { + /// Readers for standard output and standard error, in that order, and + /// the waiter that reports the exit. + fn monitor( + session: &Arc, + process_id: u64, + ) -> Result>, RemoteError> { + let forwards = [OutputStream::Stdout, OutputStream::Stderr].map(|stream| { + let session = Arc::clone(session); + let forward: Forward = Box::new(move |chunk| { session.link.emit( methods::EVENT_PROCESS_OUTPUT, ProcessOutputEvent { @@ -220,27 +227,26 @@ impl ProcessTable { }, ); }); - } - thread::spawn(move || { - let status = child.wait(); - gate.finish(|| { - let registry = &session.processes.registry; - if let Some(process) = registry.lock().get_mut(&process_id) { - process.leader.exited = true; - process.stdin = None; - } - prune(registry, |process| &process.leader); - let (exit_code, signal) = exit_parts(status); - session.link.emit( - methods::EVENT_PROCESS_EXIT, - ProcessExitEvent { - process_id, - exit_code, - signal, - }, - ); - }); + forward }); + let session = Arc::clone(session); + Monitor::start(forwards, move |status| { + let registry = &session.processes.registry; + if let Some(process) = registry.lock().get_mut(&process_id) { + process.leader.exited = true; + process.stdin = None; + } + prune(registry, |process| &process.leader); + let (exit_code, signal) = exit_parts(status); + session.link.emit( + methods::EVENT_PROCESS_EXIT, + ProcessExitEvent { + process_id, + exit_code, + signal, + }, + ); + }) } fn write_stdin(&self, params: WriteStdinParams) -> Result<(), RemoteError> { @@ -385,19 +391,36 @@ pub(crate) fn exit_parts(status: io::Result) -> (Option, Option } } -/// Starts a thread that writes queued chunks to `pipe`. Dropping the sender -/// (close or exit) ends the loop after queued writes, and dropping the pipe -/// delivers end-of-file to the child. -pub(crate) fn start_input_writer(mut pipe: impl Write + Send + 'static) -> SyncSender> { - let (sender, receiver): (_, Receiver>) = mpsc::sync_channel(INPUT_QUEUE_CAPACITY); - thread::spawn(move || { - while let Ok(chunk) = receiver.recv() { - if pipe.write_all(&chunk).is_err() { - break; +/// The queue and thread that write a child's or stream's input, started +/// before the child or stream exists (see [`crate::server::threads`]). +pub(crate) struct InputWriter { + queue: SyncSender>, + thread: Parked, +} + +impl InputWriter { + /// Starts the writer thread. Once the queue's sender is dropped (close or + /// exit), the queued chunks are still written and `finish` receives the + /// pipe; after a failed write the pipe is dropped without `finish`. + /// Dropping a pipe delivers end-of-file to its reader. + pub(crate) fn start(finish: impl FnOnce(W) + Send + 'static) -> Result { + let (queue, chunks): (_, Receiver>) = mpsc::sync_channel(INPUT_QUEUE_CAPACITY); + let thread = Parked::start("remote-input", move |mut pipe: W| { + while let Ok(chunk) = chunks.recv() { + if pipe.write_all(&chunk).is_err() { + return; + } } - } - }); - sender + finish(pipe); + })?; + Ok(Self { queue, thread }) + } + + /// Hands `pipe` to the writer and returns the queue that feeds it. + pub(crate) fn attach(self, pipe: W) -> SyncSender> { + self.thread.run(pipe); + self.queue + } } pub(crate) fn queue_input(queue: &SyncSender>, data: Vec) -> Result<(), RemoteError> { @@ -414,20 +437,66 @@ pub(crate) fn queue_input(queue: &SyncSender>, data: Vec) -> Result< } } +/// A chunk forwarder of one output pipe. +pub(crate) type Forward = Box; + +/// The output readers and the exit waiter of one child, started before the +/// child (see [`crate::server::threads`]). +/// +/// Readers forward chunks through an [`OutputGate`]. The waiter reaps the +/// child, lets the readers drain, and then runs the exit action, so the exit +/// event follows the child's own output. +pub(crate) struct Monitor { + readers: Vec>, + waiter: Parked, +} + +impl Monitor { + /// Starts one reader per entry of `forwards`, and the waiter that runs + /// `exit` with the child's status. + pub(crate) fn start( + forwards: impl IntoIterator, + exit: impl FnOnce(io::Result) + Send + 'static, + ) -> Result { + let mut gate = OutputGate::new(); + let readers = forwards + .into_iter() + .map(|forward| gate.reader(forward)) + .collect::, _>>()?; + let waiter = Parked::start("remote-wait", move |mut child: Child| { + let status = child.wait(); + gate.finish(|| exit(status)); + })?; + Ok(Self { readers, waiter }) + } + + /// Follows `child`. `pipes` pairs with the forwards given to + /// [`Monitor::start`], in order; a missing pipe leaves its reader unused. + pub(crate) fn follow(self, pipes: impl IntoIterator>, child: Child) { + for (reader, pipe) in self.readers.into_iter().zip(pipes) { + if let Some(pipe) = pipe { + reader.run(pipe); + } + } + self.waiter.run(child); + } +} + /// Orders a child's output before its exit event. /// /// Readers forward chunks while holding the gate; `finish` waits briefly for /// the readers to reach end-of-file, then closes the gate and runs the exit /// action under it. Output read after that is dropped, because it can only -/// come from descendants that inherited the pipe. -pub(crate) struct OutputGate { +/// come from descendants that inherited the pipe. A reader that never +/// receives its pipe only makes `finish` wait out the grace period. +struct OutputGate { closed: Arc>, drained: (mpsc::Sender<()>, Receiver<()>), readers: usize, } impl OutputGate { - pub(crate) fn new() -> Self { + fn new() -> Self { Self { closed: Arc::new(Mutex::new(false)), drained: mpsc::channel(), @@ -435,15 +504,13 @@ impl OutputGate { } } - pub(crate) fn start_reader( + fn reader( &mut self, - mut pipe: impl Read + Send + 'static, - forward: impl Fn(&[u8]) + Send + 'static, - ) { - self.readers += 1; + forward: Forward, + ) -> Result, RemoteError> { let closed = Arc::clone(&self.closed); let drained = self.drained.0.clone(); - thread::spawn(move || { + let reader = Parked::start("remote-output", move |mut pipe: R| { let mut buffer = vec![0_u8; OUTPUT_CHUNK_BYTES]; loop { let read = match pipe.read(&mut buffer) { @@ -460,10 +527,12 @@ impl OutputGate { } } let _ = drained.send(()); - }); + })?; + self.readers += 1; + Ok(reader) } - pub(crate) fn finish(self, exit: impl FnOnce()) { + fn finish(self, exit: impl FnOnce()) { let deadline = Instant::now() + OUTPUT_DRAIN_GRACE; for _ in 0..self.readers { let remaining = deadline.saturating_duration_since(Instant::now()); diff --git a/rust/crates/remote/src/server/resources.rs b/rust/crates/remote/src/server/resources.rs index 9a457bdf..68b98d30 100644 --- a/rust/crates/remote/src/server/resources.rs +++ b/rust/crates/remote/src/server/resources.rs @@ -146,14 +146,25 @@ impl Drop for StartGuard { /// variable lets shutdown wait, with a deadline, until resources have ended. pub(crate) struct Registry { family: &'static str, + /// Most entries the family may hold at once. + limit: usize, entries: Mutex>, changed: Condvar, } impl Registry { + /// A family whose size only the client's own requests drive, such as + /// the processes it started. pub(crate) fn new(family: &'static str) -> Self { + Self::bounded(family, usize::MAX) + } + + /// A family holding at most `limit` entries. Further starts fail with + /// `BUSY` until an entry ends. + pub(crate) fn bounded(family: &'static str, limit: usize) -> Self { Self { family, + limit, entries: Mutex::new(BTreeMap::new()), changed: Condvar::new(), } @@ -163,22 +174,32 @@ impl Registry { crate::server::lock(&self.entries) } - /// Fails when the id is already live. The check and the later insert are - /// separated by the resource's start-up, so callers insert a placeholder - /// through [`Registry::reserve`] when start-up can be slow. + /// Fails when the id is already live or the family is full, so a start + /// is refused before it does any work. Both can change during the + /// resource's start-up, so [`Registry::insert`] checks again. pub(crate) fn ensure_free(&self, id: u64) -> Result<(), RemoteError> { - if self.lock().contains_key(&id) { - return Err(self.in_use(id)); - } - Ok(()) + self.admit(&self.lock(), id) } pub(crate) fn insert(&self, id: u64, entry: T) -> Result<(), RemoteError> { let mut entries = self.lock(); + self.admit(&entries, id)?; + entries.insert(id, entry); + Ok(()) + } + + /// An id in use is reported before a full family, so a client that + /// reuses an id learns about its own mistake. + fn admit(&self, entries: &BTreeMap, id: u64) -> Result<(), RemoteError> { if entries.contains_key(&id) { return Err(self.in_use(id)); } - entries.insert(id, entry); + if entries.len() >= self.limit { + return Err(RemoteError::new( + ErrorCode::Busy, + format!("{} limit of {} reached", self.family, self.limit), + )); + } Ok(()) } @@ -267,3 +288,26 @@ impl InFlight { *count } } + +#[cfg(test)] +mod tests { + use super::Registry; + use crate::protocol::ErrorCode; + + #[test] + fn bounded_registries_refuse_starts_until_an_entry_ends() { + let registry = Registry::bounded("tunnel", 2); + registry.insert(1, ()).unwrap(); + registry.insert(2, ()).unwrap(); + // An id in use is reported as such even when the family is full. + assert_eq!( + registry.insert(2, ()).unwrap_err().code, + ErrorCode::ResourceIdInUse + ); + assert_eq!(registry.ensure_free(3).unwrap_err().code, ErrorCode::Busy); + assert_eq!(registry.insert(3, ()).unwrap_err().code, ErrorCode::Busy); + registry.remove(1); + registry.ensure_free(3).unwrap(); + registry.insert(3, ()).unwrap(); + } +} diff --git a/rust/crates/remote/src/server/terminal.rs b/rust/crates/remote/src/server/terminal.rs index 38a78461..39ed63f1 100644 --- a/rust/crates/remote/src/server/terminal.rs +++ b/rust/crates/remote/src/server/terminal.rs @@ -14,11 +14,12 @@ use crate::server::connection::Context; use crate::server::fs::host_path; use crate::server::platform::{self, ChildKind}; use crate::server::process::{ - exit_parts, has_exited_leaders, prune, queue_input, spawn_error, start_input_writer, - terminate_groups, Leader, OutputGate, + exit_parts, has_exited_leaders, prune, queue_input, spawn_error, terminate_groups, Forward, + InputWriter, Leader, Monitor, }; use crate::server::resources::Registry; use crate::server::session::{Session, TERMINATION_GRACE}; +use crate::server::threads::Parked; use crate::server::{parse, to_value}; use serde_json::Value; use std::fs::File; @@ -28,7 +29,6 @@ use std::path::Path; use std::process::{Command, Stdio}; use std::sync::mpsc::SyncSender; use std::sync::Arc; -use std::thread; const DEFAULT_TERM: &str = "xterm-256color"; @@ -147,44 +147,47 @@ impl TerminalTable { .stdout(stdio(&slave)?) .stderr(stdio(&slave)?); platform::prepare_child(&mut command, ChildKind::Terminal); + let master = Arc::new(master); + let io_failure = |error| crate::server::fs::io_error(error, ""); + let reader = File::from(master.try_clone().map_err(io_failure)?); + let writer = File::from(master.try_clone().map_err(io_failure)?); + // Every thread the terminal needs starts before its program does. + let input = InputWriter::::start(drop)?; + let monitor = Self::monitor(session, params.terminal_id)?; let program = command.get_program().to_string_lossy().into_owned(); // The command, and with it the parent's copies of the slave side, is // dropped on the spawner thread right after the fork. - let child = session + let mut child = session .spawner .run(move || command.spawn()) .map_err(|error| spawn_error(&program, error))?; drop(slave); - let master = Arc::new(master); - let reader = File::from( - master - .try_clone() - .map_err(|error| crate::server::fs::io_error(error, ""))?, - ); - let writer = File::from( - master - .try_clone() - .map_err(|error| crate::server::fs::io_error(error, ""))?, - ); let pid = child.id(); let entry = RunningTerminal { leader: Leader::new(pid), columns: params.columns, rows: params.rows, master, - input: Some(start_input_writer(writer)), + input: Some(input.attach(writer)), }; if let Err(error) = self.registry.insert(params.terminal_id, entry) { + // Like a lost race in `process.spawn`: the client never saw this + // terminal, so its program must not keep running. let _ = platform::signal_process_group(pid, libc::SIGKILL); + let _ = child.wait(); return Err(error); } + monitor.follow([Some(reader)], child); + Ok(TerminalOpenResult { pid }) + } - let terminal_id = params.terminal_id; - let mut gate = OutputGate::new(); - let output_session = Arc::clone(session); - gate.start_reader(reader, move |chunk| { - output_session.link.emit( + /// The reader of the terminal's output and the waiter that reports the + /// exit of its program. + fn monitor(session: &Arc, terminal_id: u64) -> Result, RemoteError> { + let output = Arc::clone(session); + let forward: Forward = Box::new(move |chunk| { + output.link.emit( methods::EVENT_TERMINAL_OUTPUT, TerminalOutputEvent { terminal_id, @@ -193,28 +196,23 @@ impl TerminalTable { ); }); let session = Arc::clone(session); - let mut child = child; - thread::spawn(move || { - let status = child.wait(); - gate.finish(|| { - let registry = &session.terminals.registry; - if let Some(terminal) = registry.lock().get_mut(&terminal_id) { - terminal.leader.exited = true; - terminal.input = None; - } - prune(registry, |terminal| &terminal.leader); - let (exit_code, signal) = exit_parts(status); - session.link.emit( - methods::EVENT_TERMINAL_EXIT, - TerminalExitEvent { - terminal_id, - exit_code, - signal, - }, - ); - }); - }); - Ok(TerminalOpenResult { pid }) + Monitor::start([forward], move |status| { + let registry = &session.terminals.registry; + if let Some(terminal) = registry.lock().get_mut(&terminal_id) { + terminal.leader.exited = true; + terminal.input = None; + } + prune(registry, |terminal| &terminal.leader); + let (exit_code, signal) = exit_parts(status); + session.link.emit( + methods::EVENT_TERMINAL_EXIT, + TerminalExitEvent { + terminal_id, + exit_code, + signal, + }, + ); + }) } fn write(&self, params: TerminalWriteParams) -> Result<(), RemoteError> { @@ -252,42 +250,48 @@ impl TerminalTable { /// whole session, including background jobs, and `SIGKILL` after a grace /// period to whatever ignored it. fn close(&self, session: &Arc, params: TerminalParams) -> Result<(), RemoteError> { + // The escalation thread starts first, so that a host out of threads + // refuses the close before the terminal stops taking input. + let terminal_id = params.terminal_id; + let escalation = { + let session = Arc::clone(session); + Parked::start("remote-hangup", move |pid: u32| { + let terminals = &session.terminals.registry; + let deadline = std::time::Instant::now() + TERMINATION_GRACE; + let owned = || { + prune(terminals, |terminal| &terminal.leader); + terminals + .lock() + .get(&terminal_id) + .is_some_and(|terminal| terminal.leader.pid == pid) + }; + while std::time::Instant::now() < deadline { + if !owned() { + return; + } + // Jobs that are not the server's children report no exit, + // so the wait also wakes periodically to re-check the session. + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + terminals.wait_for_change( + remaining.min(crate::server::process::SESSION_POLL_INTERVAL), + ); + } + if owned() { + let _ = platform::signal_session(pid, libc::SIGKILL); + } + })? + }; prune(&self.registry, |terminal| &terminal.leader); let pid = { let mut terminals = self.registry.lock(); let terminal = terminals - .get_mut(¶ms.terminal_id) - .ok_or_else(|| self.registry.unknown(params.terminal_id))?; + .get_mut(&terminal_id) + .ok_or_else(|| self.registry.unknown(terminal_id))?; terminal.input = None; terminal.leader.pid }; let _ = platform::signal_session(pid, libc::SIGHUP); - let session = Arc::clone(session); - let terminal_id = params.terminal_id; - thread::spawn(move || { - let terminals = &session.terminals.registry; - let deadline = std::time::Instant::now() + TERMINATION_GRACE; - let owned = || { - prune(terminals, |terminal| &terminal.leader); - terminals - .lock() - .get(&terminal_id) - .is_some_and(|terminal| terminal.leader.pid == pid) - }; - while std::time::Instant::now() < deadline { - if !owned() { - return; - } - // Jobs that are not the server's children report no exit, so - // the wait also wakes periodically to re-check the session. - let remaining = deadline.saturating_duration_since(std::time::Instant::now()); - terminals - .wait_for_change(remaining.min(crate::server::process::SESSION_POLL_INTERVAL)); - } - if owned() { - let _ = platform::signal_session(pid, libc::SIGKILL); - } - }); + escalation.run(pid); Ok(()) } diff --git a/rust/crates/remote/src/server/threads.rs b/rust/crates/remote/src/server/threads.rs new file mode 100644 index 00000000..a487d02a --- /dev/null +++ b/rust/crates/remote/src/server/threads.rs @@ -0,0 +1,95 @@ +//! Threads started before the resource they serve. +//! +//! Creating a thread fails when the host reaches its thread or memory limit. +//! Processes, terminals, tunnels, watches and walks need threads, and once a +//! child runs, a socket is connected or a resource is registered, a thread +//! that cannot start leaves a child nobody waits for, a stream nobody reads or +//! an entry nobody removes. Every such thread is therefore started first and +//! parked until its value arrives: a failure answers `BUSY` while nothing +//! needs cleaning up yet, and handing the value over afterwards cannot fail. + +use crate::protocol::{ErrorCode, RemoteError}; +use serde_json::json; +use std::io; +use std::sync::mpsc::{self, SyncSender}; +use std::thread::{self, JoinHandle}; + +/// A started thread waiting for the value it works on. Dropping it without +/// [`Parked::run`] ends the thread without doing any work. +pub(crate) struct Parked { + value: SyncSender, + thread: JoinHandle<()>, +} + +impl Parked { + /// Starts a thread named `name` that runs `work` once it receives a value. + pub(crate) fn start( + name: &str, + work: impl FnOnce(T) + Send + 'static, + ) -> Result { + let (value, received) = mpsc::sync_channel::(1); + let thread = thread::Builder::new() + .name(name.into()) + .spawn(move || { + if let Ok(value) = received.recv() { + work(value); + } + }) + .map_err(unavailable)?; + Ok(Self { value, thread }) + } + + /// Hands `value` to the thread, which then runs its work. The returned + /// handle joins the thread; dropping it leaves the thread running. + pub(crate) fn run(self, value: T) -> JoinHandle<()> { + // The thread waits in `recv` until it receives this value or the + // sender is dropped, and the one-slot buffer takes the value without + // blocking. A failure would mean the thread ended on its own. + if self.value.send(value).is_err() { + eprintln!("lithe-remote-server: a parked thread ended before its work arrived"); + } + self.thread + } +} + +/// The answer to a request whose threads cannot start. Like the server's own +/// limits it is a capacity limit, so clients may retry later. +pub(crate) fn unavailable(error: io::Error) -> RemoteError { + RemoteError::new(ErrorCode::Busy, format!("cannot start a thread: {error}")) + .with_details(json!({ "osError": error.raw_os_error() })) +} + +#[cfg(test)] +mod tests { + use super::Parked; + use std::sync::mpsc; + use std::time::Duration; + + const STEP: Duration = Duration::from_secs(5); + + #[test] + fn parked_threads_run_their_value_or_end_without_one() { + let (done, finished) = mpsc::channel(); + let parked = Parked::start("test-parked", move |value: u32| { + let _ = done.send(value); + }) + .unwrap(); + let thread = parked.run(7); + assert_eq!(finished.recv_timeout(STEP), Ok(7)); + // Sending is the work's last step, so the join returns at once. + thread.join().unwrap(); + + // The work closure is dropped when the thread ends, which also drops + // its sender: the receiver then reports that the thread is gone. + let (gone, ended) = mpsc::channel::(); + let unused = Parked::start("test-parked", move |value: u32| { + let _ = gone.send(value); + }) + .unwrap(); + drop(unused); + assert_eq!( + ended.recv_timeout(STEP), + Err(mpsc::RecvTimeoutError::Disconnected) + ); + } +} diff --git a/rust/crates/remote/src/server/tunnel.rs b/rust/crates/remote/src/server/tunnel.rs index a2ce589c..43f1fe45 100644 --- a/rust/crates/remote/src/server/tunnel.rs +++ b/rust/crates/remote/src/server/tunnel.rs @@ -12,21 +12,26 @@ use crate::protocol::methods::{ use crate::protocol::{ErrorCode, RemoteError}; use crate::server::connection::Context; use crate::server::parse; -use crate::server::process::{queue_input, INPUT_QUEUE_CAPACITY}; +use crate::server::process::{queue_input, InputWriter}; use crate::server::resources::Registry; use crate::server::session::Session; +use crate::server::threads::Parked; use serde_json::{json, Value}; use std::io::{self, Read, Write}; use std::net::{Shutdown, TcpStream, ToSocketAddrs}; use std::os::unix::net::UnixStream; use std::sync::mpsc::SyncSender; use std::sync::Arc; -use std::thread; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); const READ_CHUNK_BYTES: usize = 32 * 1024; +/// Most tunnels one session keeps open. Every tunnel holds a socket and two +/// threads on the remote, and a single local page can open many connections, +/// so the number is bounded independently of what the client asks for. +const MAX_TUNNELS: usize = 256; + pub(crate) struct TunnelTable { registry: Registry, } @@ -88,7 +93,7 @@ impl Write for Stream { impl TunnelTable { pub(crate) fn new() -> Self { Self { - registry: Registry::new("tunnel"), + registry: Registry::bounded("tunnel", MAX_TUNNELS), } } @@ -164,47 +169,39 @@ impl TunnelTable { let session = &context.session; session.ids.observe(params.tunnel_id); self.registry.ensure_free(params.tunnel_id)?; + // Both threads start before the connection exists, so a host out of + // threads refuses the tunnel without having touched the target. When + // the write queue's sender is dropped (`tunnel.shutdownWrite`), the + // queued data is still written and then only the write side is shut + // down, so the peer can still answer. + let writer = InputWriter::start(|stream: Stream| stream.shutdown(Shutdown::Write))?; + let tunnel_id = params.tunnel_id; + let reader = { + let session = Arc::clone(session); + Parked::start("remote-tunnel", move |stream: Stream| { + forward(&session, tunnel_id, stream); + })? + }; let stream = connect(¶ms.target).map_err(|error| { RemoteError::new(ErrorCode::ConnectFailed, format!("cannot connect: {error}")) .with_details(json!({ "osError": error.raw_os_error() })) })?; let io_failure = |error: io::Error| crate::server::fs::io_error(error, ""); - let reader = stream.try_clone().map_err(io_failure)?; - let writer = stream.try_clone().map_err(io_failure)?; + let reading = stream.try_clone().map_err(io_failure)?; + let writing = stream.try_clone().map_err(io_failure)?; self.registry.insert( - params.tunnel_id, + tunnel_id, OpenTunnel { connection: context.connection, - input: Some(start_tunnel_writer(writer)), + input: Some(writer.attach(writing)), stream, }, )?; - let session = Arc::clone(session); - let tunnel_id = params.tunnel_id; - thread::Builder::new() - .name("remote-tunnel".into()) - .spawn(move || forward(&session, tunnel_id, reader)) - .map_err(io_failure)?; + reader.run(reading); Ok(()) } } -/// Writes queued chunks to the remote stream. When the queue's sender is -/// dropped (`tunnel.shutdownWrite`), the queued data is still written and -/// then only the write side is shut down, so the peer can still answer. -fn start_tunnel_writer(mut stream: Stream) -> SyncSender> { - let (sender, receiver) = std::sync::mpsc::sync_channel::>(INPUT_QUEUE_CAPACITY); - thread::spawn(move || { - while let Ok(chunk) = receiver.recv() { - if stream.write_all(&chunk).is_err() { - return; - } - } - stream.shutdown(Shutdown::Write); - }); - sender -} - fn connect(target: &TunnelTarget) -> io::Result { match target { TunnelTarget::Tcp { host, port } => { diff --git a/rust/crates/remote/src/server/walk.rs b/rust/crates/remote/src/server/walk.rs index 3d6a5781..f90973a3 100644 --- a/rust/crates/remote/src/server/walk.rs +++ b/rust/crates/remote/src/server/walk.rs @@ -13,12 +13,12 @@ use crate::server::fs::{host_path, kind_of}; use crate::server::parse; use crate::server::resources::Registry; use crate::server::session::Session; +use crate::server::threads::Parked; use serde_json::Value; use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use std::thread; /// Entries per `walk.entries` event: large enough to amortize framing, /// small enough to keep each frame far below the size limit. @@ -91,6 +91,18 @@ impl WalkTable { "only directories can be walked", )); } + self.registry.ensure_free(params.walk_id)?; + // The thread starts before the walk is registered, so a host out of + // threads refuses the walk instead of leaving an entry that no + // thread would ever remove. + let thread = { + let session = Arc::clone(session); + Parked::start("remote-walk", move |walker: Walker| { + let done = walker.run(&session); + session.walks.registry.remove(done.walk_id); + session.link.emit(methods::EVENT_WALK_DONE, done); + })? + }; let cancelled = Arc::new(AtomicBool::new(false)); self.registry.insert( params.walk_id, @@ -99,22 +111,13 @@ impl WalkTable { cancelled: Arc::clone(&cancelled), }, )?; - let session = Arc::clone(session); - let walker = Walker { + thread.run(Walker { walk_id: params.walk_id, root, excludes: params.exclude_names.into_iter().collect(), limit: params.max_entries.unwrap_or(u64::MAX), cancelled, - }; - thread::Builder::new() - .name("remote-walk".into()) - .spawn(move || { - let done = walker.run(&session); - session.walks.registry.remove(done.walk_id); - session.link.emit(methods::EVENT_WALK_DONE, done); - }) - .map_err(|error| crate::server::fs::io_error(error, ""))?; + }); Ok(()) } } diff --git a/rust/crates/remote/src/server/watch.rs b/rust/crates/remote/src/server/watch.rs index 5cf05608..f29f425f 100644 --- a/rust/crates/remote/src/server/watch.rs +++ b/rust/crates/remote/src/server/watch.rs @@ -17,13 +17,13 @@ use crate::server::fs::host_path; use crate::server::platform::watcher; use crate::server::resources::Registry; use crate::server::session::Session; +use crate::server::threads::Parked; use crate::server::{parse, to_value}; use serde_json::Value; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::sync::Arc; -use std::thread; use std::time::{Duration, Instant}; const QUIET_PERIOD: Duration = Duration::from_millis(50); @@ -152,23 +152,26 @@ impl WatchTable { "only directories can be watched", )); } + // The coalescer starts before the backend, so a host out of threads + // refuses the watch without a backend that nobody would stop. + let watch_id = params.watch_id; + let coalescer = { + let session = Arc::clone(session); + Parked::start("remote-watch", move |raw: Receiver| { + coalesce(raw, |batch| deliver(&session, watch_id, batch)); + })? + }; let excludes = Arc::new(Excludes::new(root.clone(), params.exclude_names)); let (sink, raw) = mpsc::channel(); - let (backend, watched_directories) = watcher::start(root, excludes, sink) - .map_err(|error| crate::server::fs::io_error(error, ¶ms.root))?; + let (backend, watched_directories) = watcher::start(root, ¶ms.root, excludes, sink)?; self.registry.insert( - params.watch_id, + watch_id, RunningWatch { root: params.root, _backend: backend, }, )?; - let session = Arc::clone(session); - let watch_id = params.watch_id; - thread::Builder::new() - .name("remote-watch".into()) - .spawn(move || coalesce(raw, |batch| deliver(&session, watch_id, batch))) - .map_err(|error| crate::server::fs::io_error(error, ""))?; + coalescer.run(raw); Ok(WatchStartResult { watched_directories, }) diff --git a/rust/crates/remote/tests/tunnels.rs b/rust/crates/remote/tests/tunnels.rs index c63d3658..3c1ae92d 100644 --- a/rust/crates/remote/tests/tunnels.rs +++ b/rust/crates/remote/tests/tunnels.rs @@ -179,6 +179,29 @@ fn port_forwards_bridge_local_connections_to_the_remote() { .unwrap(); } +// A forward on every interface would expose the remote service to the local +// network, so only loopback addresses are accepted. +#[test] +fn port_forwards_refuse_addresses_other_than_loopback() { + let (session, _events) = connect(); + let session = Arc::new(session); + for bind in ["0.0.0.0:0", "[::]:0"] { + let error = PortForward::start( + Arc::clone(&session), + bind.parse().unwrap(), + TunnelTarget::Tcp { + host: "127.0.0.1".into(), + port: 1, + }, + ) + .err() + .unwrap_or_else(|| panic!("{bind} was accepted")); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput, "{bind}"); + } + let session = Arc::into_inner(session).expect("no forward holds the session"); + session.shutdown(STEP_TIMEOUT); +} + // Regression: a local client that half-closes after its request, as // HTTP/1.0 clients and `nc -N` do, had the tunnel aborted. Queued data was // lost and the reply never arrived. diff --git a/rust/crates/remote/tests/watch_and_walk.rs b/rust/crates/remote/tests/watch_and_walk.rs index b64a2de8..d5a2ad85 100644 --- a/rust/crates/remote/tests/watch_and_walk.rs +++ b/rust/crates/remote/tests/watch_and_walk.rs @@ -3,7 +3,10 @@ mod support; use lithe_remote::client::api::{WatchEvent, WatchHandle}; -use lithe_remote::protocol::methods::{ChangeKind, FileKind, WatchErrorCode}; +use lithe_remote::client::session::ClientError; +use lithe_remote::protocol::methods::{self, ChangeKind, FileKind, WatchErrorCode}; +use lithe_remote::protocol::ErrorCode; +use serde_json::json; use std::collections::BTreeMap; use std::time::{Duration, Instant}; use support::{connect, TempDir, STEP_TIMEOUT}; @@ -145,6 +148,34 @@ fn removing_the_watched_root_ends_the_watch() { session.shutdown(STEP_TIMEOUT); } +// A refused duplicate must neither replace nor stop the running watch. +#[test] +fn a_live_watch_id_cannot_be_reused() { + let root = TempDir::new("watch-duplicate"); + let other = TempDir::new("watch-duplicate-other"); + let (session, _events) = connect(); + let watch = session.watch(root.str(), &[]).unwrap(); + let duplicate = session.request_value( + methods::WATCH_START, + json!({ "watchId": watch.id, "root": other.str() }), + STEP_TIMEOUT, + ); + match duplicate { + Err(ClientError::Remote(error)) => assert_eq!(error.code, ErrorCode::ResourceIdInUse), + other => panic!("expected RESOURCE_ID_IN_USE, got {other:?}"), + } + let state = session.state().unwrap(); + assert_eq!(state.watches.len(), 1); + assert_eq!(state.watches[0].root, root.str()); + + let file = root.join("still-watched.txt"); + std::fs::write(&file, b"x").unwrap(); + wait_for_changes(&watch, &[(&file, ChangeKind::Created)]); + watch.stop().unwrap(); + drop(watch); + session.shutdown(STEP_TIMEOUT); +} + #[test] fn walks_list_trees_in_order_without_following_links() { let root = TempDir::new("walk");