diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index f2b7fe42..82b96cfa 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -407,7 +407,9 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported: - `encoding_unmappable` - `cancelled` - `timed_out` -- `connection_closed` +- `connection_closed`: the remote connection the request names closed or was lost +- `forward_target_not_confirmed`: a port forward reaches another machine through the remote host and the user has not confirmed it +- `forward_limit_reached`: the remote connection keeps the most port forwards it allows - `remote_server_invalid`: the server build `remote.connect` would send cannot be read or is not the build its SHA-256 names - `unknown` diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 4bc0f5b8..36d0d38e 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -154,7 +154,7 @@ subscribe before creating the resource. | `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 | -| `ports.listening` | — | sorted `ports` (`address`, `port`) | +| `ports.listening` | — | `ports` sorted by `address` and `port`, one entry for each: `address`, `port`, and `pid` and `process` (the command name) when the server's user can inspect the owning process | `fs.copy` refuses, with `INVALID_REQUEST`, to copy a file onto itself — directly, through a symbolic link in either direction or onto a hard link — diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2856dc5b..276ed0b2 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -816,6 +816,9 @@ or removing a command fails until the table changes in the same commit. | `remote.hostInfo` | Return cached handshake capabilities of one connection | | `remote.workspaceTrust` | Read remote workspace trust decisions and one open workspace's trust | | `remote.editWorkspaceTrust` | Record or remove one remote workspace trust decision | +| `remote.startForward` | Forward a local port to a port as the remote host sees it | +| `remote.stopForward` | Stop one port forward and close its local port | +| `remote.forwards` | List the running port forwards of one connection | | `remote.connections` | Read the SSH connections the user saved | | `remote.editConnections` | Save, remove or record a folder on one saved SSH connection | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | @@ -5859,6 +5862,53 @@ persistent disconnect retains them until explicit release, shutdown or idle expi Forced server termination recovery remains unsupported, rather than risking deletion of inputs used by surviving processes. +#### Remote port forwards + +The ports page forwards a local port to a TCP port as the remote host sees +it. It lists candidates with `remote.hostRequest` and `ports.listening` +(`{ ports: [{ address, port, pid?, process? }] }`, one entry for each address +and port; `pid` and `process` only when the server's user can inspect the +owning process). Forwards belong to one connection: + +| Command | Request | Result | +| --- | --- | --- | +| `remote.startForward` | `{ sessionId, targetHost, targetPort, localPort?, allowNonLoopbackTarget? }` | `{ forward, created }` | +| `remote.stopForward` | `{ sessionId, forwardId }` | `{ stopped }` | +| `remote.forwards` | `{ sessionId }` | `{ forwards }`, by `id` | + +A forward is `{ id, localHost, localPort, requestedLocalPort?, +localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. + +- **Target.** `targetHost` is an IP address (IPv6 with or without brackets) + or a host name the remote host resolves, such as `localhost`. A wildcard + address (`0.0.0.0`, `::`), as `ports.listening` reports a program that + listens on every interface, becomes the host's loopback address of the + same family; `targetHost` in the result is the address sent to the host. + A malformed host or port `0` is `invalid_request` with `details.field` + (`targetHost` or `targetPort`). +- **Confirmation.** A target outside the host's loopback interface reaches + another machine through the host, so it starts only with + `allowNonLoopbackTarget: true`, which the native client sets after the + user confirmed that target. Without it the request fails with + `forward_target_not_confirmed` and nothing starts. `loopbackTarget` tells + the two apart in the list. +- **Local port.** The forward listens on `127.0.0.1`. `localPort` (absent or + `0` for a free one) is used when no local program accepts connections on + it, on `127.0.0.1` or `::1`; otherwise the forward listens on a free port, + `requestedLocalPort` keeps the asked one and `localPortChanged` is `true`. + A local port that cannot be opened at all is `unknown` with + `details.io`. +- **Once per target.** Starting a target that already has a forward returns + that forward with `created: false`, so a repeated click opens no second + local port. A connection keeps at most 64 forwards; one more is + `forward_limit_reached` with `details.maximum`. +- **Lifetime.** `remote.stopForward` closes the local port; connections it + already accepted run until either side closes them, and an unknown id + returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a + lost connection close every local port of the connection. Requests on a + connection whose session ended are `connection_closed` and forget it, as + for the other commands. `connections` counts accepted local connections. + #### Remote workspace trust A remote workspace is trusted, kept in safe mode or undecided, as a local diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 9fd7b232..fbea4a51 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1009,6 +1009,13 @@ pub enum RemoteCommand { /// Records or removes one remote workspace trust decision /// (`remote.editWorkspaceTrust`). EditWorkspaceTrust, + /// Forwards a local port to a port as the remote host sees it + /// (`remote.startForward`). + StartForward, + /// Stops one port forward and closes its local port (`remote.stopForward`). + StopForward, + /// Lists the running port forwards of one connection (`remote.forwards`). + Forwards, /// Reads the SSH connections the user saved (`remote.connections`). Connections, /// Saves, removes or records a folder on one saved SSH connection @@ -1578,6 +1585,9 @@ impl CoreCommand { "remote.hostInfo" => Some(Self::Remote(RemoteCommand::HostInfo)), "remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)), "remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)), + "remote.startForward" => Some(Self::Remote(RemoteCommand::StartForward)), + "remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)), + "remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)), "remote.connections" => Some(Self::Remote(RemoteCommand::Connections)), "remote.editConnections" => Some(Self::Remote(RemoteCommand::EditConnections)), "git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 9e7d2a79..ba8a7e8d 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -1,4 +1,5 @@ -//! `remote.*` commands: probing, authentication, connections, files and processes. +//! `remote.*` commands: probing, authentication, connections, files, +//! processes and port forwards. use crate::protocol::{CoreError, CoreResponse, ErrorCode, RemoteCommand}; use serde_json::{json, Value}; @@ -166,6 +167,42 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::StartForward => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::start) + { + Ok(started) => CoreResponse::success( + id, + serde_json::to_value(started).expect("port forward result should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } + RemoteCommand::StopForward => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::stop) + { + Ok(stopped) => CoreResponse::success( + id, + serde_json::to_value(stopped).expect("port forward result should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } + RemoteCommand::Forwards => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::list) + { + Ok(forwards) => CoreResponse::success( + id, + serde_json::to_value(forwards).expect("port forward list should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } RemoteCommand::Connections => { match serde_json::from_value(payload) .map_err(|error| { @@ -239,3 +276,9 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu } } } + +/// A `remote.*Forward` payload that does not decode. +fn invalid_forward_request(error: &serde_json::Error) -> CoreError { + CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward request") + .with_details(error.to_string()) +} diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index b9df12bb..6f14064f 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -201,6 +201,8 @@ pub(crate) fn is_hot(method: &str) -> bool { // and active runs probe their process tree's listening ports periodically. || method == "processMemory.summarize" || method == "process.listeningPorts" + // The ports page refreshes its forwards' connection counts while shown. + || method == "remote.forwards" } /// Explicit host provenance wins; Git provenance covers hosts that send only that. @@ -278,6 +280,7 @@ mod tests { "debug.transport.handle", "processMemory.summarize", "process.listeningPorts", + "remote.forwards", ] { assert!(is_hot(method), "{method}"); } @@ -288,6 +291,7 @@ mod tests { "file.write", "lsp.startServer", "remote.connect", + "remote.startForward", "debug.launch", ] { assert!(!is_hot(method), "{method}"); diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index b8a49172..91cb756b 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1248,3 +1248,162 @@ fn remote_workspace_trust_keys_the_host_real_path_on_the_connected_target() { "unknown" ); } + +// The ports page: a forward reaches a program listening on the host's +// wildcard address, a second click returns the same forward, a target on +// another machine waits for the user's confirmation, and every failure keeps +// its own category. +#[test] +fn remote_port_forwards_start_once_per_target_and_end_with_the_connection() { + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + + let host = HostFixture::new(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let echo = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(STEP)).unwrap(); + let mut buffer = [0_u8; 5]; + stream.read_exact(&mut buffer).unwrap(); + stream.write_all(&buffer).unwrap(); + }); + let call = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "timeoutMilliseconds": 30_000, "payload": payload}) + .to_string(), + )) + .unwrap() + }; + let ok = |response: Value| -> Value { + assert_eq!(response["ok"], true, "{response}"); + response["data"].clone() + }; + let error = |response: Value| -> Value { + assert_eq!(response["ok"], false, "{response}"); + response["error"].clone() + }; + let start = |payload: Value| { + let mut payload = payload; + payload["sessionId"] = json!(host.id); + call("remote.startForward", payload) + }; + + let started = ok(start(json!({"targetHost": "0.0.0.0", "targetPort": port}))); + assert_eq!(started["created"], true, "{started}"); + let forward = started["forward"].clone(); + assert_eq!(forward["targetHost"], "127.0.0.1", "{started}"); + assert_eq!(forward["loopbackTarget"], true, "{started}"); + assert_eq!(forward["localHost"], "127.0.0.1", "{started}"); + assert_eq!(forward["localPortChanged"], false, "{started}"); + assert!(forward.get("requestedLocalPort").is_none(), "{started}"); + // The wildcard and the loopback address name one target. + let again = ok(start( + json!({"targetHost": "127.0.0.1", "targetPort": port}), + )); + assert_eq!(again["created"], false, "{again}"); + assert_eq!(again["forward"]["id"], forward["id"], "{again}"); + + let local_port = u16::try_from(forward["localPort"].as_u64().unwrap()).unwrap(); + let mut local = TcpStream::connect(("127.0.0.1", local_port)).unwrap(); + local.set_read_timeout(Some(STEP)).unwrap(); + local.write_all(b"ports").unwrap(); + let mut answer = [0_u8; 5]; + local.read_exact(&mut answer).unwrap(); + assert_eq!(&answer, b"ports"); + drop(local); + echo.join().unwrap(); + + let listed = ok(call("remote.forwards", json!({"sessionId": host.id}))); + assert_eq!(listed["forwards"].as_array().unwrap().len(), 1, "{listed}"); + assert_eq!(listed["forwards"][0]["id"], forward["id"], "{listed}"); + + // A database on the host's network starts only once confirmed. + let elsewhere = json!({"targetHost": "192.0.2.10", "targetPort": 5432}); + assert_eq!( + error(start(elsewhere.clone()))["code"], + "forward_target_not_confirmed" + ); + let mut confirmed = elsewhere; + confirmed["allowNonLoopbackTarget"] = json!(true); + let outside = ok(start(confirmed)); + assert_eq!(outside["forward"]["loopbackTarget"], false, "{outside}"); + + for (payload, field) in [ + ( + json!({"targetHost": "127.0.0.1", "targetPort": 0}), + "targetPort", + ), + ( + json!({"targetHost": "-oProxyCommand", "targetPort": 22}), + "targetHost", + ), + ] { + let refused = error(start(payload)); + assert_eq!(refused["code"], "invalid_request", "{refused}"); + let details: Value = serde_json::from_str(refused["details"].as_str().unwrap()).unwrap(); + assert_eq!(details["field"], field, "{refused}"); + } + assert_eq!( + error(start( + json!({"targetHost": "127.0.0.1", "targetPort": 70_000}) + ))["code"], + "invalid_request" + ); + + // The connection keeps a bounded number of forwards; a target that + // already has one still answers at the limit. + let running = ok(call("remote.forwards", json!({"sessionId": host.id})))["forwards"] + .as_array() + .unwrap() + .len(); + let limit = lithe_remote::client::forward_set::MAX_FORWARDS; + for target in (1..).filter(|target| *target != port).take(limit - running) { + ok(start( + json!({"targetHost": "127.0.0.1", "targetPort": target}), + )); + } + let full = error(start(json!({"targetHost": "::1", "targetPort": 1}))); + assert_eq!(full["code"], "forward_limit_reached", "{full}"); + let details: Value = serde_json::from_str(full["details"].as_str().unwrap()).unwrap(); + assert_eq!(details["maximum"], limit, "{full}"); + assert_eq!( + ok(start( + json!({"targetHost": "127.0.0.1", "targetPort": port}) + ))["created"], + false + ); + + let stop = |forward_id: &Value| { + call( + "remote.stopForward", + json!({"sessionId": host.id, "forwardId": forward_id}), + ) + }; + assert_eq!(ok(stop(&forward["id"]))["stopped"], true); + assert_eq!(ok(stop(&forward["id"]))["stopped"], false); + assert_eq!( + error(call( + "remote.forwards", + json!({"sessionId": test_support::unique_id()}) + ))["code"], + "connection_closed" + ); + + // A connection whose session ended released its forwards and is + // forgotten, so the ports page reconnects instead of listing nothing. + test_support::drop_link(&host.id); + for _ in 0..2 { + assert_eq!( + error(call("remote.forwards", json!({"sessionId": host.id})))["code"], + "connection_closed" + ); + } + assert_eq!( + error(start( + json!({"targetHost": "127.0.0.1", "targetPort": port}) + ))["code"], + "connection_closed" + ); +} diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 20d59056..eb0d9bf4 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -72,6 +72,14 @@ pub enum ErrorCode { /// A long-lived connection the request names is closed or was lost; the /// caller can reconnect and retry. ConnectionClosed, + /// `remote.startForward` names a target outside the remote host's + /// loopback interface without `allowNonLoopbackTarget`. Nothing started; + /// the caller asks the user to confirm that target and repeats the + /// request with the flag. + ForwardTargetNotConfirmed, + /// `remote.startForward` found the connection at its forward limit + /// (`details.maximum`); stopping a forward makes room. + ForwardLimitReached, /// `remote.connect` reached a host whose server build the request names, /// but the local file could not be read or its SHA-256 is not the one the /// request gives for it. Nothing was installed on the host; the diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index 4a154891..ae1ec729 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -30,6 +30,7 @@ //! so an attempt never records two outcomes. use crate::client::bootstrap::{ServerArtifact, ServerTarget}; +use crate::client::forward_set; use crate::client::launch::{Deployment, LaunchError}; use crate::failure_log; use crate::protocol::methods::{encode_hex, HelloResult, TunnelTarget}; @@ -37,7 +38,7 @@ use serde_json::{json, Value}; use std::collections::hash_map::RandomState; use std::fmt; use std::hash::BuildHasher; -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; @@ -294,7 +295,10 @@ impl ConnectionLog { TunnelTarget::Tcp { host, port } => { fields.push(("target_kind", json!("tcp"))); fields.push(("remote_port", json!(port))); - fields.push(("target_scope", json!(scope(is_loopback_host(host))))); + fields.push(( + "target_scope", + json!(scope(forward_set::is_loopback_host(host))), + )); } TunnelTarget::Unix { .. } => fields.push(("target_kind", json!("unix"))), } @@ -343,17 +347,6 @@ fn scope(loopback: bool) -> &'static str { } } -fn is_loopback_host(host: &str) -> bool { - let unbracketed = host - .strip_prefix('[') - .and_then(|rest| rest.strip_suffix(']')) - .unwrap_or(host); - host.eq_ignore_ascii_case("localhost") - || unbracketed - .parse::() - .is_ok_and(|address| address.is_loopback()) -} - /// Mirrors the catalog's `version` type: 1 to 64 ASCII letters, digits and `._+-`. fn is_version(value: &str) -> bool { !value.is_empty() @@ -387,29 +380,6 @@ mod tests { assert_ne!(first, second); } - #[test] - fn loopback_hosts_are_recognized_without_resolving_names() { - for host in [ - "localhost", - "LOCALHOST", - "127.0.0.1", - "127.8.9.1", - "::1", - "[::1]", - ] { - assert!(is_loopback_host(host), "{host}"); - } - for host in [ - "0.0.0.0", - "10.0.0.1", - "example.com", - "localhost.example.com", - "[::2]", - ] { - assert!(!is_loopback_host(host), "{host}"); - } - } - #[test] fn server_versions_outside_the_catalog_vocabulary_are_left_out() { assert!(is_version("0.8.11+build.3")); diff --git a/rust/crates/remote/src/client/forward.rs b/rust/crates/remote/src/client/forward.rs index 7db6a55d..56c02220 100644 --- a/rust/crates/remote/src/client/forward.rs +++ b/rust/crates/remote/src/client/forward.rs @@ -114,6 +114,11 @@ impl PortForward { self.local_address } + /// Local connections handed to a bridge so far. + pub fn connections(&self) -> u64 { + self.accepted.load(Ordering::Relaxed) + } + /// 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. diff --git a/rust/crates/remote/src/client/forward_set.rs b/rust/crates/remote/src/client/forward_set.rs new file mode 100644 index 00000000..0cc280ad --- /dev/null +++ b/rust/crates/remote/src/client/forward_set.rs @@ -0,0 +1,530 @@ +//! The port forwards of one session, as the ports page manages them. +//! +//! A [`ForwardSet`] starts, lists and stops the [`PortForward`]s of one +//! [`RemoteSession`] and owns them until they stop: +//! +//! - **Targets** are named as the remote host sees them. A host listening on +//! every interface (`0.0.0.0`, `::`) is reached through the host's own +//! loopback address. A target that is not the host's loopback interface +//! reaches another machine through the host, for example a database on +//! the host's private network, so starting it requires +//! [`ForwardSpec::allow_non_loopback_target`], which the application sets +//! only after the user confirmed that target (design S28). +//! - **Local ports.** A forward listens on `127.0.0.1`. When the requested +//! port is taken locally, it listens on a free port instead and reports +//! [`ForwardInfo::local_port_changed`], so the user sees which address to +//! open instead of a failure. +//! - **Session end** releases every forward and closes their local ports +//! (design S29). A stopped connection never leaves a local port that +//! accepts connections and then drops them. +//! +//! Starting the same target twice returns the forward that already exists, +//! so a repeated click does not open a second local port. + +use crate::client::forward::PortForward; +use crate::client::session::RemoteSession; +use crate::protocol::methods::TunnelTarget; +use serde::Serialize; +use std::collections::BTreeMap; +use std::fmt; +use std::io; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak}; +use std::thread; +use std::time::Duration; + +/// Most forwards one session keeps at once. Each one holds a local port and +/// an acceptor thread; a page of forwards is far below this. +pub const MAX_FORWARDS: usize = 64; + +/// Longest host name a target may have, as in DNS. +const MAX_HOST_BYTES: usize = 253; + +/// Bound for checking whether a local program already uses a port. Loopback +/// connections are refused or accepted at once; this only covers a stalled +/// local stack. +const PROBE_TIMEOUT: Duration = Duration::from_millis(250); + +/// What to forward. +#[derive(Clone, Debug)] +pub struct ForwardSpec { + /// Host as the remote host resolves it: an IP address, with or without + /// brackets for IPv6, or a name such as `localhost`. + pub target_host: String, + /// TCP port on the target, 1 to 65535. + pub target_port: u16, + /// Local port to listen on; `None` or `0` lets the system choose one. + pub local_port: Option, + /// The user confirmed a target outside the remote host's loopback + /// interface (design S28). + pub allow_non_loopback_target: bool, +} + +/// A running forward, as listed on the ports page. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ForwardInfo { + /// Identifier within the session, never reused while the session lasts. + pub id: u64, + /// Local address the forward listens on, `127.0.0.1`. + pub local_host: String, + /// Local port the forward listens on. + pub local_port: u16, + /// Local port the request asked for, when it named one. + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_local_port: Option, + /// The requested local port was taken, so the forward listens on + /// `local_port` instead. + pub local_port_changed: bool, + /// Target host as sent to the remote host, after mapping a wildcard + /// address to the host's loopback address. + pub target_host: String, + /// Target TCP port. + pub target_port: u16, + /// The target is the remote host's loopback interface. + pub loopback_target: bool, + /// Local connections the forward has accepted so far. + pub connections: u64, +} + +/// The malformed part of a forward's target. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TargetField { + /// [`ForwardSpec::target_host`]. + Host, + /// [`ForwardSpec::target_port`]. + Port, +} + +/// Why a forward did not start or the set cannot answer. +#[derive(Debug)] +pub enum ForwardError { + /// The target host or port is malformed. + InvalidTarget(TargetField), + /// The target is outside the remote host's loopback interface and the + /// request did not confirm it (design S28). + TargetNotConfirmed, + /// The session already has [`MAX_FORWARDS`] forwards. + LimitReached, + /// The session ended; its forwards were released. + SessionClosed, + /// No local port could be opened, not even one the system chose. + Listen(io::Error), +} + +impl fmt::Display for ForwardError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidTarget(TargetField::Host) => { + formatter.write_str("invalid forward target host") + } + Self::InvalidTarget(TargetField::Port) => { + formatter.write_str("invalid forward target port") + } + Self::TargetNotConfirmed => formatter + .write_str("the forward target is outside the remote host and was not confirmed"), + Self::LimitReached => { + write!(formatter, "a session keeps at most {MAX_FORWARDS} forwards") + } + Self::SessionClosed => formatter.write_str("the remote connection closed"), + Self::Listen(error) => write!(formatter, "cannot listen on a local port: {error}"), + } + } +} + +impl std::error::Error for ForwardError {} + +/// The forwards of one session. +pub struct ForwardSet { + session: Arc, + state: Arc>, +} + +#[derive(Default)] +struct State { + /// Set when the session ended or the set closed; nothing starts after it. + closed: bool, + next_id: u64, + forwards: BTreeMap, +} + +struct Entry { + forward: PortForward, + requested_local_port: Option, + local_port_changed: bool, + target_host: String, + target_port: u16, + loopback_target: bool, +} + +impl Entry { + fn info(&self, id: u64) -> ForwardInfo { + let local = self.forward.local_address(); + ForwardInfo { + id, + local_host: local.ip().to_string(), + local_port: local.port(), + requested_local_port: self.requested_local_port, + local_port_changed: self.local_port_changed, + target_host: self.target_host.clone(), + target_port: self.target_port, + loopback_target: self.loopback_target, + connections: self.forward.connections(), + } + } +} + +impl ForwardSet { + /// An empty set whose forwards end together with `session`. + pub fn new(session: Arc) -> Self { + let state = Arc::new(Mutex::new(State::default())); + // Weak, because the forwards own the session: a strong reference in + // the session's own hook would keep both alive forever. + let released = Arc::downgrade(&state); + session.on_closed(move || release_in_background(&released)); + Self { session, state } + } + + /// Starts forwarding, or returns the forward that already reaches the + /// same target. The flag is `true` for a new forward. + pub fn start(&self, spec: ForwardSpec) -> Result<(ForwardInfo, bool), ForwardError> { + let target = TargetHost::parse(&spec.target_host)?; + if spec.target_port == 0 { + return Err(ForwardError::InvalidTarget(TargetField::Port)); + } + if !target.loopback && !spec.allow_non_loopback_target { + return Err(ForwardError::TargetNotConfirmed); + } + let requested = spec.local_port.filter(|port| *port != 0); + // Held while the forward starts, so two requests for one target + // cannot both open a local port. + let mut state = lock(&self.state); + if state.closed || self.session.is_closed() { + return Err(ForwardError::SessionClosed); + } + if let Some((id, entry)) = state.forwards.iter().find(|(_, entry)| { + entry.target_host == target.host && entry.target_port == spec.target_port + }) { + return Ok((entry.info(*id), false)); + } + if state.forwards.len() >= MAX_FORWARDS { + return Err(ForwardError::LimitReached); + } + let tunnel = TunnelTarget::Tcp { + host: target.host.clone(), + port: spec.target_port, + }; + let forward = listen(&self.session, requested, tunnel)?; + let local_port_changed = + requested.is_some_and(|port| port != forward.local_address().port()); + state.next_id += 1; + let id = state.next_id; + let entry = Entry { + forward, + requested_local_port: requested, + local_port_changed, + target_host: target.host, + target_port: spec.target_port, + loopback_target: target.loopback, + }; + let info = entry.info(id); + state.forwards.insert(id, entry); + Ok((info, true)) + } + + /// Stops one forward and closes its local port. Connections it already + /// accepted run until either side closes them. Returns whether the + /// forward existed. + pub fn stop(&self, id: u64) -> bool { + let removed = lock(&self.state).forwards.remove(&id); + // Dropped outside the lock: stopping waits for the acceptor thread. + removed.is_some() + } + + /// The running forwards, by identifier. + pub fn list(&self) -> Result, ForwardError> { + let state = lock(&self.state); + if state.closed || self.session.is_closed() { + return Err(ForwardError::SessionClosed); + } + Ok(state + .forwards + .iter() + .map(|(id, entry)| entry.info(*id)) + .collect()) + } + + /// Stops every forward and refuses new ones, before the session closes. + pub fn close(&self) { + let forwards = take_all(&self.state); + drop(forwards); + } +} + +impl Drop for ForwardSet { + fn drop(&mut self) { + self.close(); + } +} + +/// Marks the set closed and takes its forwards, which the caller drops +/// outside the lock. +fn take_all(state: &Mutex) -> BTreeMap { + let mut state = lock(state); + state.closed = true; + std::mem::take(&mut state.forwards) +} + +/// Releases the forwards of an ended session. Called by the session's reader +/// or writer thread, which must not wait for acceptor threads, so the +/// forwards stop on a thread of their own. +fn release_in_background(state: &Weak>) { + let Some(state) = state.upgrade() else { + return; + }; + let forwards = take_all(&state); + if forwards.is_empty() { + return; + } + let spawned = thread::Builder::new() + .name("remote-forward-release".into()) + .spawn(move || drop(forwards)); + // Without a thread, the closure that never ran is dropped with the + // error, which stops the forwards here; each stop is bounded. + crate::failure_log::io("remote.client.operation_failed", "forward_release", spawned); +} + +/// Opens the forward on `requested`, or on a free port when another local +/// program uses that port. +fn listen( + session: &Arc, + requested: Option, + target: TunnelTarget, +) -> Result { + let any_port = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0); + let Some(port) = requested else { + return PortForward::start(Arc::clone(session), any_port, target) + .map_err(ForwardError::Listen); + }; + if !in_use_locally(port) { + let bind = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port); + // A port bound without listening, or one below 1024 that needs + // privileges, is just as taken. The caller learns about the free + // port from `local_port_changed` instead of an error. + if let Ok(forward) = PortForward::start(Arc::clone(session), bind, target.clone()) { + return Ok(forward); + } + } + PortForward::start(Arc::clone(session), any_port, target).map_err(ForwardError::Listen) +} + +/// Whether a local program accepts connections on `port` of either loopback +/// address. +/// +/// Binding alone does not show this. On macOS and Windows a socket bound to +/// `127.0.0.1` opens next to a program that listens on every interface and +/// then receives that program's loopback connections, so the forward would +/// silently take over the local program's `localhost` address. A program +/// listening on `::1` only would instead keep the `localhost` connections of +/// browsers that try IPv6 first, and the forward would seem not to work. +fn in_use_locally(port: u16) -> bool { + [ + IpAddr::V4(Ipv4Addr::LOCALHOST), + IpAddr::V6(Ipv6Addr::LOCALHOST), + ] + .into_iter() + .any(|address| { + TcpStream::connect_timeout(&SocketAddr::new(address, port), PROBE_TIMEOUT).is_ok() + }) +} + +/// A validated target host and whether it is the remote host's loopback +/// interface. +#[derive(Debug, Eq, PartialEq)] +struct TargetHost { + host: String, + loopback: bool, +} + +impl TargetHost { + /// Accepts IP addresses, IPv6 in brackets or not, and DNS names. A + /// wildcard address becomes the loopback address of its family, and an + /// IPv4-mapped IPv6 address its IPv4 form. Names are not resolved: + /// only `localhost` counts as loopback, as the remote host resolves + /// other names, possibly elsewhere. + fn parse(host: &str) -> Result { + let address = match host + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + { + // Brackets only ever enclose an IPv6 address. + Some(inner) => Some( + inner + .parse::() + .map(IpAddr::V6) + .map_err(|_| ForwardError::InvalidTarget(TargetField::Host))?, + ), + None => host.parse::().ok(), + }; + if let Some(address) = address { + let address = match address.to_canonical() { + IpAddr::V4(address) if address.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST), + IpAddr::V6(address) if address.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST), + address => address, + }; + return Ok(Self { + host: address.to_string(), + loopback: address.is_loopback(), + }); + } + if !is_host_name(host) { + return Err(ForwardError::InvalidTarget(TargetField::Host)); + } + let host = host.to_ascii_lowercase(); + Ok(Self { + loopback: host == "localhost", + host, + }) + } +} + +/// True for a host name the remote resolver can look up: 1 to 253 bytes of +/// letters, digits, `-`, `_` and `.`, not starting with `-` or `.`, so it can +/// never read as an option or an address with a port. +fn is_host_name(host: &str) -> bool { + !host.is_empty() + && host.len() <= MAX_HOST_BYTES + && !host.starts_with(['-', '.']) + && host + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-_.".contains(&byte)) +} + +/// True for the host's loopback interface: `localhost` or a loopback address, +/// IPv6 in brackets or not and IPv4-mapped included. Names are not resolved. +pub(crate) fn is_loopback_host(host: &str) -> bool { + TargetHost::parse(host).is_ok_and(|target| target.loopback && !is_wildcard(host)) +} + +/// True for an address that listens on every interface, such as `0.0.0.0`. +fn is_wildcard(host: &str) -> bool { + host.strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or(host) + .parse::() + .is_ok_and(|address| address.to_canonical().is_unspecified()) +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn target(host: &str) -> TargetHost { + TargetHost::parse(host).unwrap() + } + + #[test] + fn wildcard_and_mapped_targets_become_the_hosts_loopback_address() { + for (host, expected) in [ + ("0.0.0.0", "127.0.0.1"), + ("::", "::1"), + ("[::]", "::1"), + ("::ffff:127.0.0.1", "127.0.0.1"), + ("::ffff:0.0.0.0", "127.0.0.1"), + ("[::1]", "::1"), + ("127.0.0.2", "127.0.0.2"), + ("LocalHost", "localhost"), + ] { + assert_eq!( + target(host), + TargetHost { + host: expected.into(), + loopback: true, + }, + "{host}" + ); + } + } + + #[test] + fn other_machines_are_targets_outside_the_loopback_interface() { + for (host, expected) in [ + ("10.0.0.5", "10.0.0.5"), + ("::ffff:10.0.0.5", "10.0.0.5"), + ("[fe80::1]", "fe80::1"), + ("db.internal", "db.internal"), + ("localhost.example.com", "localhost.example.com"), + ("my_service", "my_service"), + ] { + assert_eq!( + target(host), + TargetHost { + host: expected.into(), + loopback: false, + }, + "{host}" + ); + } + } + + #[test] + fn malformed_target_hosts_are_rejected_before_anything_is_sent() { + let long = "a".repeat(MAX_HOST_BYTES + 1); + for host in [ + "", + "-oProxyCommand", + ".hidden", + "host name", + "host:80", + "[::1", + "[db.internal]", + "[127.0.0.1]", + "[]", + "host\n", + long.as_str(), + ] { + assert!( + matches!( + TargetHost::parse(host), + Err(ForwardError::InvalidTarget(TargetField::Host)) + ), + "{host:?}" + ); + } + } + + #[test] + fn the_log_counts_only_the_loopback_interface_and_never_a_wildcard_as_loopback() { + for host in [ + "localhost", + "LOCALHOST", + "127.0.0.1", + "127.8.9.1", + "::1", + "[::1]", + "::ffff:127.0.0.1", + ] { + assert!(is_loopback_host(host), "{host}"); + } + for host in [ + "0.0.0.0", + "[::]", + "10.0.0.1", + "example.com", + "localhost.example.com", + "[::2]", + ] { + assert!(!is_loopback_host(host), "{host}"); + } + } + + #[test] + fn a_port_only_a_local_program_listens_on_counts_as_in_use() { + let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + assert!(in_use_locally(listener.local_addr().unwrap().port())); + } +} diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 3c90f67d..a03c4ddd 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -13,6 +13,8 @@ //! routes each resource's events to its subscriber. //! - [`api`] offers typed operations and resource handles on a session. //! - [`forward`] forwards local ports through tunnels. +//! - [`forward_set`] keeps the forwards of one session for the ports page, +//! confirms targets outside the host and releases them with the session. //! - [`connection_log`] records one connection's lifecycle in the v2 log, //! identified by a random id instead of the host or user name. //! - [`trust`] keeps the machine-local trust decisions on remote workspaces, @@ -30,6 +32,7 @@ mod command; pub mod connection_log; pub mod connections; pub mod forward; +pub mod forward_set; pub mod launch; pub mod session; pub mod transport; @@ -39,5 +42,6 @@ pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; pub use connection_log::{ConnectionKind, ConnectionLog}; pub use forward::PortForward; +pub use forward_set::{ForwardError, ForwardInfo, ForwardSet, ForwardSpec, TargetField}; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError}; diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index b0bc4748..afa256b1 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -16,6 +16,9 @@ //! //! The session records its lifecycle in a [`ConnectionLog`]: the handshake //! outcome, a stream that ends without a shutdown request, and the release. +//! +//! Owners of local resources tied to the session, such as port forwards, +//! register [`RemoteSession::on_closed`] to release them once the stream ends. use crate::client::connection_log::{ConnectionKind, ConnectionLog}; use crate::client::transport::{TransportChain, TransportError}; @@ -162,11 +165,16 @@ impl ClientError { type Reply = Result; +/// Work to run once, when the session's stream ends. +type ClosedHook = Box; + #[derive(Default)] struct Pending { /// Set once the stream ended; new requests fail immediately. closed: bool, waiting: HashMap>, + /// Registered by [`RemoteSession::on_closed`]; taken when `closed` is set. + on_closed: Vec, } type Routes = Mutex>>; @@ -760,6 +768,23 @@ impl RemoteSession { lock(&self.pending).closed } + /// Runs `hook` once the stream ends, or right away when it already has. + /// + /// The hook runs on the session's reader or writer thread, after every + /// waiting request has failed. It must neither block on the network nor + /// own the session: a hook that keeps the session alive would keep its + /// own registration, and so the session, alive forever. Hooks capture a + /// weak reference to their state and move slow cleanup to a thread. + pub fn on_closed(&self, hook: impl FnOnce() + Send + 'static) { + let mut pending = lock(&self.pending); + if pending.closed { + drop(pending); + hook(); + } else { + pending.on_closed.push(Box::new(hook)); + } + } + /// Asks the server to stop. A `--stdio` server ends; a persistent /// session ends together with everything it runs. pub fn shutdown(self, timeout: Duration) { @@ -984,14 +1009,23 @@ fn route(routes: &Routes, events: &SyncSender, event: Event) -> bool { } } +/// Marks the stream ended, fails every waiting request and then runs the +/// closed hooks, outside the lock so that a hook may use the session. The +/// reader and the writer can both end the stream; hooks run only once. fn close(pending: &Mutex) { - let mut pending = lock(pending); - pending.closed = true; - for (_, waiter) in pending.waiting.drain() { - // log-exempt: User cancellation: the remote request caller already ended the request and no longer waits for the disconnect reply. - let _ = waiter.send(Err(ClientError::Disconnected { - diagnostics: String::new(), - })); + let hooks = { + let mut pending = lock(pending); + pending.closed = true; + for (_, waiter) in pending.waiting.drain() { + // log-exempt: User cancellation: the remote request caller already ended the request and no longer waits for the disconnect reply. + let _ = waiter.send(Err(ClientError::Disconnected { + diagnostics: String::new(), + })); + } + std::mem::take(&mut pending.on_closed) + }; + for hook in hooks { + hook(); } } @@ -1239,4 +1273,28 @@ mod tests { )); assert!(!lock(&routes).contains_key(&("process".into(), 7))); } + + #[test] + fn closed_hooks_run_once_after_waiting_requests_fail() { + let pending = Arc::new(Mutex::new(Pending::default())); + let (waiter, reply) = mpsc::sync_channel(1); + lock(&pending).waiting.insert(1, waiter); + let runs = Arc::new(AtomicU64::new(0)); + let hook_runs = Arc::clone(&runs); + let hook_pending = Arc::clone(&pending); + lock(&pending).on_closed.push(Box::new(move || { + // The hook may use the session: the lock is released and every + // waiting request has already failed. + assert!(lock(&hook_pending).waiting.is_empty()); + hook_runs.fetch_add(1, Ordering::SeqCst); + })); + close(&pending); + // The writer can end the stream after the reader did. + close(&pending); + assert_eq!(runs.load(Ordering::SeqCst), 1); + assert!(matches!( + reply.try_recv(), + Ok(Err(ClientError::Disconnected { .. })) + )); + } } diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 06d0911b..0fdc9a6b 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -1280,13 +1280,22 @@ pub struct ListeningPort { pub address: String, /// TCP port. pub port: u16, + /// Process that holds the socket. Absent when the socket belongs to a + /// process the server's user cannot inspect, such as a proxy run by + /// `root`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pid: Option, + /// Command name of that process as the host reports it, which Linux + /// shortens to 15 bytes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub process: Option, } /// Result of `ports.listening`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ListeningPortsResult { - /// Sorted and without duplicates. + /// Sorted by address and port, one entry for each. pub ports: Vec, } diff --git a/rust/crates/remote/src/server/platform/linux.rs b/rust/crates/remote/src/server/platform/linux.rs index 06aef12f..4b25b891 100644 --- a/rust/crates/remote/src/server/platform/linux.rs +++ b/rust/crates/remote/src/server/platform/linux.rs @@ -2,7 +2,7 @@ use super::{unix, ChildKind}; use crate::protocol::methods::{ListeningPort, OperatingSystem, OrphanProtection}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::io; use std::net::{Ipv4Addr, Ipv6Addr}; use std::os::unix::process::CommandExt; @@ -94,15 +94,19 @@ pub(crate) fn sessions_with_members(sessions: &HashSet) -> HashSet { /// `(pid, session id)` of every process. fn process_sessions() -> impl Iterator { + process_ids().filter_map(|pid| { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + Some((pid, stat_session(&stat)?)) + }) +} + +/// Every process id in `/proc`, lowest first as the kernel lists them. +fn process_ids() -> impl Iterator { std::fs::read_dir("/proc") .into_iter() .flatten() .flatten() .filter_map(|entry| entry.file_name().to_str()?.parse::().ok()) - .filter_map(|pid| { - let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; - Some((pid, stat_session(&stat)?)) - }) } /// The session id is the fourth field after the command name, which is @@ -114,21 +118,103 @@ fn stat_session(stat: &str) -> Option { /// Listening TCP sockets in the server's network namespace, which inside a /// container is the container's own. Sockets of other users are included: -/// Docker's port proxies, for example, run as root. +/// Docker's port proxies, for example, run as root. Their owner stays +/// unknown, as only the user's own processes can be inspected. pub(crate) fn listening_ports() -> io::Result> { - let mut ports = Vec::new(); + let mut sockets = Vec::new(); for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] { match std::fs::read_to_string(table) { - Ok(contents) => ports.extend(parse_proc_net_tcp(&contents, ipv6)), + Ok(contents) => sockets.extend(parse_proc_net_tcp(&contents, ipv6)), // Kernels without IPv6 have no tcp6 table. Err(error) if error.kind() == io::ErrorKind::NotFound && ipv6 => {} Err(error) => return Err(error), } } - Ok(ports) + let owners = socket_owners(sockets.iter().filter_map(|socket| socket.inode).collect()); + Ok(sockets + .into_iter() + .map(|socket| { + let owner = socket.inode.and_then(|inode| owners.get(&inode)); + ListeningPort { + address: socket.address, + port: socket.port, + pid: owner.map(|owner| owner.pid), + process: owner.and_then(|owner| owner.name.clone()), + } + }) + .collect()) +} + +/// A listening socket from `/proc/net/tcp`, before its owner is known. +#[derive(Debug, Eq, PartialEq)] +struct Socket { + address: String, + port: u16, + /// Absent when the line has no inode or the kernel printed 0. + inode: Option, +} + +/// The process that holds a socket. +struct Owner { + pid: u32, + name: Option, +} + +/// Finds the processes holding the sockets with the inodes in `wanted`, by +/// reading their descriptor tables. `/proc//fd` is readable only for +/// the server user's own processes, so other users' sockets keep no owner. +/// A socket that several processes inherited goes to the lowest process id, +/// usually the parent that opened it. The scan ends once every socket has an +/// owner. +fn socket_owners(mut wanted: HashSet) -> HashMap { + let mut owners = HashMap::new(); + for pid in process_ids() { + if wanted.is_empty() { + break; + } + // Unreadable for other users' processes and gone for ones that just + // exited; neither owns a socket we can name. + let Ok(descriptors) = std::fs::read_dir(format!("/proc/{pid}/fd")) else { + continue; + }; + let mut name = None; + for descriptor in descriptors.flatten() { + let Some(inode) = std::fs::read_link(descriptor.path()) + .ok() + .and_then(|target| socket_inode(&target)) + else { + continue; + }; + if wanted.remove(&inode) { + let name = name.get_or_insert_with(|| process_name(pid)).clone(); + owners.insert(inode, Owner { pid, name }); + } + } + } + owners } -fn parse_proc_net_tcp(contents: &str, ipv6: bool) -> Vec { +/// The inode of a descriptor link such as `socket:[12345]`. +fn socket_inode(target: &Path) -> Option { + target + .to_str()? + .strip_prefix("socket:[")? + .strip_suffix(']')? + .parse() + .ok() +} + +/// The command name in `/proc//comm`, at most 15 bytes. +fn process_name(pid: u32) -> Option { + let name = std::fs::read_to_string(format!("/proc/{pid}/comm")).ok()?; + let name = name.trim_end_matches('\n'); + (!name.is_empty()).then(|| name.to_owned()) +} + +/// Listening sockets of one `/proc/net/tcp` or `tcp6` table. The columns are +/// `sl local_address rem_address st tx_queue:rx_queue tr:tm->when retrnsmt +/// uid timeout inode`. +fn parse_proc_net_tcp(contents: &str, ipv6: bool) -> Vec { contents .lines() .skip(1) @@ -139,14 +225,19 @@ fn parse_proc_net_tcp(contents: &str, ipv6: bool) -> Vec { if state != TCP_LISTEN_STATE { return None; } + let inode = fields + .nth(5) + .and_then(|inode| inode.parse().ok()) + .filter(|inode| *inode != 0); let (address, port) = local.split_once(':')?; - Some(ListeningPort { + Some(Socket { address: if ipv6 { parse_ipv6(address)?.to_string() } else { parse_ipv4(address)?.to_string() }, port: u16::from_str_radix(port, 16).ok()?, + inode, }) }) .collect() @@ -189,23 +280,57 @@ mod tests { assert_eq!( ports, vec![ - ListeningPort { + Socket { address: "127.0.0.1".into(), - port: 8080 + port: 8080, + inode: Some(1), }, - ListeningPort { + Socket { address: "0.0.0.0".into(), - port: 22 + port: 22, + inode: Some(2), }, ] ); - let ipv6 = " sl local_address remote_address st\n 0: 00000000000000000000000001000000:1538 00000000000000000000000000000000:0000 0A\n"; + // A table without the inode column, and one with inode 0, still + // list the port, just without an owner. + let ipv6 = " sl local_address remote_address st\n 0: 00000000000000000000000001000000:1538 00000000000000000000000000000000:0000 0A\n 1: 00000000000000000000000000000000:0050 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 0 1\n"; assert_eq!( parse_proc_net_tcp(ipv6, true), - vec![ListeningPort { - address: "::1".into(), - port: 5432 - }] + vec![ + Socket { + address: "::1".into(), + port: 5432, + inode: None, + }, + Socket { + address: "::".into(), + port: 80, + inode: None, + }, + ] ); } + + #[test] + fn only_socket_descriptors_name_an_inode() { + assert_eq!(socket_inode(Path::new("socket:[12345]")), Some(12345)); + for target in ["pipe:[12345]", "/dev/null", "socket:[]", "socket:[12345"] { + assert_eq!(socket_inode(Path::new(target)), None, "{target}"); + } + } + + // The test's own listener is in a process this user can inspect. + #[test] + fn listening_sockets_of_the_users_own_processes_name_their_owner() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let ports = listening_ports().unwrap(); + let own = ports + .iter() + .find(|listening| listening.port == port && listening.address == "127.0.0.1") + .unwrap_or_else(|| panic!("{port} not in {ports:?}")); + assert_eq!(own.pid, Some(std::process::id())); + assert!(own.process.is_some(), "{own:?}"); + } } diff --git a/rust/crates/remote/src/server/platform/macos.rs b/rust/crates/remote/src/server/platform/macos.rs index fa18eba8..6551ab69 100644 --- a/rust/crates/remote/src/server/platform/macos.rs +++ b/rust/crates/remote/src/server/platform/macos.rs @@ -112,11 +112,12 @@ fn process_sessions() -> Vec<(u32, u32)> { /// Listening TCP sockets of the remote user's processes. macOS has no /// `/proc`; `lsof` ships with the system and is the supported way to list -/// sockets without elevated rights. +/// sockets without elevated rights. `+c 0` asks for command names that are +/// not cut to nine characters. pub(crate) fn listening_ports() -> io::Result> { let mut command = Command::new("lsof"); command - .args(["-nP", "-iTCP", "-sTCP:LISTEN", "-Fn"]) + .args(["-nP", "+c", "0", "-iTCP", "-sTCP:LISTEN", "-Fpcn"]) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()); @@ -138,23 +139,50 @@ fn interpret_lsof(status: Option, stdout: &[u8]) -> io::Result Vec { - output - .lines() - .filter_map(|line| line.strip_prefix('n')) - .filter_map(|name| { - let (address, port) = name.rsplit_once(':')?; - let address = address.trim_start_matches('[').trim_end_matches(']'); - Some(ListeningPort { - address: if address == "*" { - "0.0.0.0".into() - } else { - address.into() - }, - port: port.parse().ok()?, - }) - }) - .collect() + let mut pid = None; + let mut process = None; + let mut ports = Vec::new(); + for line in output.lines() { + let Some((field, value)) = line.split_at_checked(1) else { + continue; + }; + match field { + "p" => { + pid = value.parse().ok(); + process = None; + } + "c" => process = (!value.is_empty()).then(|| value.to_owned()), + "n" => { + if let Some(mut port) = parse_lsof_address(value) { + port.pid = pid; + port.process = process.clone(); + ports.push(port); + } + } + _ => {} + } + } + ports +} + +/// An address such as `127.0.0.1:5432`, `[::1]:5432` or `*:3000`. +fn parse_lsof_address(name: &str) -> Option { + let (address, port) = name.rsplit_once(':')?; + let address = address.trim_start_matches('[').trim_end_matches(']'); + Some(ListeningPort { + address: if address == "*" { + "0.0.0.0".into() + } else { + address.into() + }, + port: port.parse().ok()?, + pid: None, + process: None, + }) } #[cfg(test)] @@ -173,24 +201,36 @@ mod tests { } #[test] - fn lsof_field_output_yields_addresses_and_ports() { - let output = "p123\nf5\nn127.0.0.1:5432\nf6\nn[::1]:5432\np456\nf9\nn*:3000\n"; + fn lsof_field_output_yields_addresses_ports_and_owners() { + let output = "p123\ncpostgres\nf5\nn127.0.0.1:5432\nf6\nn[::1]:5432\np456\nf9\nn*:3000\n"; + let owned = |address: &str, port, pid, process: Option<&str>| ListeningPort { + address: address.into(), + port, + pid, + process: process.map(str::to_owned), + }; assert_eq!( parse_lsof(output), vec![ - ListeningPort { - address: "127.0.0.1".into(), - port: 5432 - }, - ListeningPort { - address: "::1".into(), - port: 5432 - }, - ListeningPort { - address: "0.0.0.0".into(), - port: 3000 - }, + owned("127.0.0.1", 5432, Some(123), Some("postgres")), + owned("::1", 5432, Some(123), Some("postgres")), + // A process without a `c` line keeps no name from the one before. + owned("0.0.0.0", 3000, Some(456), None), ] ); } + + // The test's own listener is in a process this user can inspect. + #[test] + fn listening_sockets_of_the_users_own_processes_name_their_owner() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let ports = listening_ports().unwrap(); + let own = ports + .iter() + .find(|listening| listening.port == port && listening.address == "127.0.0.1") + .unwrap_or_else(|| panic!("{port} not in {ports:?}")); + assert_eq!(own.pid, Some(std::process::id())); + assert!(own.process.is_some(), "{own:?}"); + } } diff --git a/rust/crates/remote/src/server/ports.rs b/rust/crates/remote/src/server/ports.rs index e34f792e..54656099 100644 --- a/rust/crates/remote/src/server/ports.rs +++ b/rust/crates/remote/src/server/ports.rs @@ -11,7 +11,18 @@ use std::sync::Arc; pub(crate) fn handle(_session: &Arc) -> Result { let mut ports = platform::listening_ports().map_err(|error| crate::server::fs::io_error(error, ""))?; - ports.sort(); - ports.dedup(); + // Processes that inherited one listening socket, and sockets sharing a + // port through `SO_REUSEPORT`, list one address and port several times. + // The entry kept is the one with a known owner and the lowest process id, + // usually the parent that opened the socket. + ports.sort_by(|left, right| { + (&left.address, left.port, left.pid.is_none(), left.pid).cmp(&( + &right.address, + right.port, + right.pid.is_none(), + right.pid, + )) + }); + ports.dedup_by(|later, kept| later.address == kept.address && later.port == kept.port); to_value(ListeningPortsResult { ports }) } diff --git a/rust/crates/remote/tests/tunnels.rs b/rust/crates/remote/tests/tunnels.rs index 3c1ae92d..ab587aff 100644 --- a/rust/crates/remote/tests/tunnels.rs +++ b/rust/crates/remote/tests/tunnels.rs @@ -3,13 +3,17 @@ mod support; use lithe_remote::client::api::TunnelEvent; -use lithe_remote::client::PortForward; +use lithe_remote::client::forward_set::MAX_FORWARDS; +use lithe_remote::client::{ + ForwardError, ForwardSet, ForwardSpec, PortForward, RemoteSession, TargetField, +}; use lithe_remote::protocol::methods::TunnelTarget; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::os::unix::net::UnixListener; use std::sync::Arc; use std::thread; +use std::time::{Duration, Instant}; use support::{connect, STEP_TIMEOUT}; /// A one-connection echo server that uppercases what it reads, so the test @@ -257,12 +261,183 @@ fn listening_ports_include_a_local_listener() { let port = listener.local_addr().unwrap().port(); let (session, _events) = connect(); let ports = session.listening_ports().unwrap(); - assert!( - ports - .iter() - .any(|listening| listening.port == port && listening.address == "127.0.0.1"), - "{port} not in {ports:?}" - ); + let own = ports + .iter() + .find(|listening| listening.port == port && listening.address == "127.0.0.1") + .unwrap_or_else(|| panic!("{port} not in {ports:?}")); + // The server runs as the same user, so it can name the owner. + assert_eq!(own.pid, Some(std::process::id()), "{own:?}"); + assert!(own.process.is_some(), "{own:?}"); drop(listener); session.shutdown(STEP_TIMEOUT); } + +/// A forward to `host:port` on a port the system chooses, unconfirmed. +fn forward_to(host: &str, port: u16) -> ForwardSpec { + ForwardSpec { + target_host: host.into(), + target_port: port, + local_port: None, + allow_non_loopback_target: false, + } +} + +/// Ends the server through a shared session handle; forwards may still hold +/// other handles. +fn shut_down(session: &RemoteSession) { + session + .request_value( + lithe_remote::protocol::methods::SERVER_SHUTDOWN, + serde_json::Value::Null, + STEP_TIMEOUT, + ) + .unwrap(); +} + +// The ports page names the address a remote program listens on, often the +// wildcard address; the forward reaches it through the host's loopback +// address, and a second click returns the same forward. +#[test] +fn forward_sets_bridge_a_wildcard_listener_once_per_target() { + let (port, server) = spawn_tcp_echo(); + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + + let (info, created) = forwards.start(forward_to("0.0.0.0", port)).unwrap(); + assert!(created); + assert_eq!(info.target_host, "127.0.0.1"); + assert!(info.loopback_target); + assert_eq!(info.local_host, "127.0.0.1"); + assert_eq!(info.requested_local_port, None); + assert!(!info.local_port_changed); + let (again, created) = forwards.start(forward_to("127.0.0.1", port)).unwrap(); + assert!(!created); + assert_eq!(again.id, info.id); + assert_eq!(again.local_port, info.local_port); + + let mut local = TcpStream::connect((info.local_host.as_str(), info.local_port)).unwrap(); + local.set_read_timeout(Some(STEP_TIMEOUT)).unwrap(); + local.write_all(b"ports page").unwrap(); + let mut answer = vec![0_u8; b"ports page".len()]; + local.read_exact(&mut answer).unwrap(); + assert_eq!(answer, b"PORTS PAGE"); + drop(local); + server.join().unwrap(); + + assert_eq!(forwards.list().unwrap().len(), 1); + assert!(forwards.stop(info.id)); + assert!(!forwards.stop(info.id), "a stopped forward stops only once"); + assert!(forwards.list().unwrap().is_empty()); + shut_down(&session); +} + +// Design S28: a target outside the host's loopback interface reaches another +// machine through the host, so it starts only once the user confirmed it. +#[test] +fn forward_sets_start_targets_outside_the_host_only_when_confirmed() { + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + // A documentation address (RFC 5737). Nothing connects to the forward, + // so no packet is ever sent to it. + let elsewhere = forward_to("192.0.2.10", 5432); + + assert!(matches!( + forwards.start(elsewhere.clone()), + Err(ForwardError::TargetNotConfirmed) + )); + assert!(forwards.list().unwrap().is_empty()); + let (info, created) = forwards + .start(ForwardSpec { + allow_non_loopback_target: true, + ..elsewhere + }) + .unwrap(); + assert!(created); + assert!(!info.loopback_target); + assert_eq!(info.target_host, "192.0.2.10"); + + for (spec, field) in [ + (forward_to("127.0.0.1", 0), TargetField::Port), + (forward_to("-oProxyCommand", 22), TargetField::Host), + ] { + assert!( + matches!(forwards.start(spec.clone()), Err(ForwardError::InvalidTarget(found)) if found == field), + "{spec:?}" + ); + } + shut_down(&session); +} + +// A local program already using the requested port keeps it; the forward +// moves to a free port and says so. +#[test] +fn forward_sets_move_off_a_local_port_another_program_uses() { + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = taken.local_addr().unwrap().port(); + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + + let (info, created) = forwards + .start(ForwardSpec { + local_port: Some(port), + ..forward_to("localhost", 8080) + }) + .unwrap(); + assert!(created); + assert_eq!(info.requested_local_port, Some(port)); + assert!(info.local_port_changed); + assert_ne!(info.local_port, port); + drop(taken); + shut_down(&session); +} + +#[test] +fn forward_sets_refuse_more_forwards_than_the_limit() { + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + let limit = u16::try_from(MAX_FORWARDS).unwrap(); + for port in 1..=limit { + forwards.start(forward_to("127.0.0.1", port)).unwrap(); + } + assert!(matches!( + forwards.start(forward_to("127.0.0.1", limit + 1)), + Err(ForwardError::LimitReached) + )); + // A target that already has a forward still answers at the limit. + let (_, created) = forwards.start(forward_to("127.0.0.1", 1)).unwrap(); + assert!(!created); + shut_down(&session); +} + +// Design S29: when the connection ends, every local port closes, so a port +// never keeps accepting connections that lead nowhere. +#[test] +fn forward_sets_release_their_local_ports_when_the_session_ends() { + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + let (info, _) = forwards.start(forward_to("127.0.0.1", 1)).unwrap(); + + shut_down(&session); + // The release runs on a thread of its own once the session sees the + // stream end; the closed listener is its only observable result. + let deadline = Instant::now() + STEP_TIMEOUT; + while TcpStream::connect(("127.0.0.1", info.local_port)).is_ok() { + assert!( + Instant::now() < deadline, + "local port {} still accepts connections after the session ended", + info.local_port + ); + // test-stability: allow(rust-real-sleep) reason: the listener closes on a background thread without a waitable signal; the loop has a monotonic deadline and a diagnostic. + thread::sleep(Duration::from_millis(20)); + } + assert!(matches!(forwards.list(), Err(ForwardError::SessionClosed))); + assert!(matches!( + forwards.start(forward_to("127.0.0.1", 2)), + Err(ForwardError::SessionClosed) + )); +} diff --git a/rust/crates/workspace/src/forwards.rs b/rust/crates/workspace/src/forwards.rs new file mode 100644 index 00000000..5ea77ac4 --- /dev/null +++ b/rust/crates/workspace/src/forwards.rs @@ -0,0 +1,152 @@ +//! `remote.startForward`, `remote.stopForward` and `remote.forwards`: the +//! port forwards of one open connection, as the ports page manages them. +//! +//! Each connection owns its forwards. Closing the connection, or losing it, +//! closes every local port it opened (design S29). Which targets need the +//! user's confirmation (design S28), and how a local port another program +//! uses is replaced, are the rules of `lithe_remote::client::forward_set`. +//! The listening ports a forward can reach come from `ports.listening` +//! through `remote.hostRequest`. + +use crate::sessions::{forget, lookup, Connection}; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::forward_set::MAX_FORWARDS; +use lithe_remote::client::{ForwardError, ForwardInfo, ForwardSpec, TargetField}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::sync::Arc; + +/// `remote.startForward`: one forward to a port as the host sees it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StartRequest { + session_id: String, + /// An IP address, with or without brackets for IPv6, or a host name the + /// remote host resolves, such as `localhost`. + target_host: String, + target_port: u16, + /// Local port to listen on; absent or `0` lets the system choose one. + #[serde(default)] + local_port: Option, + /// The user confirmed a target outside the host's loopback interface. + #[serde(default)] + allow_non_loopback_target: bool, +} + +/// `remote.stopForward`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StopRequest { + session_id: String, + forward_id: u64, +} + +/// `remote.forwards`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ListRequest { + session_id: String, +} + +/// `remote.startForward` result. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Started { + forward: ForwardInfo, + /// `false` when a forward to the same target already ran; `forward` is + /// then that forward, unchanged. + created: bool, +} + +/// `remote.stopForward` result. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Stopped { + /// `false` when no forward of the connection had that id. + stopped: bool, +} + +/// `remote.forwards` result. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Forwards { + /// Running forwards, by id. + forwards: Vec, +} + +/// Starts a forward, or returns the one that already reaches the target. +pub fn start(request: StartRequest) -> Result { + let connection = open(&request.session_id)?; + let spec = ForwardSpec { + target_host: request.target_host, + target_port: request.target_port, + local_port: request.local_port, + allow_non_loopback_target: request.allow_non_loopback_target, + }; + let (forward, created) = connection + .forwards + .start(spec) + .map_err(|error| forward_error(&request.session_id, error))?; + Ok(Started { forward, created }) +} + +/// Stops one forward and closes its local port. +pub fn stop(request: StopRequest) -> Result { + let connection = open(&request.session_id)?; + Ok(Stopped { + stopped: connection.forwards.stop(request.forward_id), + }) +} + +/// Lists the running forwards of one connection. +pub fn list(request: ListRequest) -> Result { + let connection = open(&request.session_id)?; + let forwards = connection + .forwards + .list() + .map_err(|error| forward_error(&request.session_id, error))?; + Ok(Forwards { forwards }) +} + +/// The registered connection, while its session still runs. A session that +/// ended already released its forwards, so its connection is forgotten. +fn open(session_id: &str) -> Result, CoreError> { + let connection = lookup(session_id)?; + if connection.session.is_closed() { + return Err(forward_error(session_id, ForwardError::SessionClosed)); + } + Ok(connection) +} + +/// Gives each forward failure its own category. +fn forward_error(session_id: &str, error: ForwardError) -> CoreError { + match error { + ForwardError::InvalidTarget(field) => { + let field = match field { + TargetField::Host => "targetHost", + TargetField::Port => "targetPort", + }; + CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward target") + .with_details(json!({ "field": field }).to_string()) + } + ForwardError::TargetNotConfirmed => CoreError::new( + ErrorCode::ForwardTargetNotConfirmed, + "The forward reaches a machine other than the remote host and needs confirmation", + ), + ForwardError::LimitReached => CoreError::new( + ErrorCode::ForwardLimitReached, + "The remote connection has the most port forwards it keeps", + ) + .with_details(json!({ "maximum": MAX_FORWARDS }).to_string()), + ForwardError::SessionClosed => { + forget(session_id); + CoreError::new(ErrorCode::ConnectionClosed, "The remote connection closed") + } + // The system could not open even a port of its own choice, so no + // stable category applies; the error kind says why. + ForwardError::Listen(error) => { + CoreError::new(ErrorCode::Unknown, "No local port could be opened") + .with_details(json!({ "io": format!("{:?}", error.kind()) }).to_string()) + } + } +} diff --git a/rust/crates/workspace/src/fs.rs b/rust/crates/workspace/src/fs.rs index a8a0e2df..9a9bb733 100644 --- a/rust/crates/workspace/src/fs.rs +++ b/rust/crates/workspace/src/fs.rs @@ -13,17 +13,17 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; // consumers (for example snapshot hashing) can still read larger files. const MAX_READ_BYTES: u64 = 32 * 1024 * 1024; -#[cfg(any(test, feature = "test-support"))] +#[cfg(feature = "test-support")] thread_local! { static STAT_REQUESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Counts stat requests on the current test thread without retaining paths. -#[cfg(any(test, feature = "test-support"))] +#[cfg(feature = "test-support")] pub(crate) fn stat_requests_for_test() -> usize { STAT_REQUESTS.with(std::cell::Cell::get) } fn rpc(host: &Host, method: &str, params: Value) -> io::Result { - #[cfg(any(test, feature = "test-support"))] + #[cfg(feature = "test-support")] if method == methods::FS_STAT { STAT_REQUESTS.with(|count| count.set(count.get() + 1)); } diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index fa2eace4..3176d0f1 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -11,12 +11,14 @@ //! the SSH connections the user saved, [`probe`] checks that a saved SSH //! connection reaches a usable host, [`sessions`] opens and keeps the //! connections, [`host`] forwards finite requests and owned streaming resources -//! (processes, terminals, watches), [`upload`] streams a verified file to -//! the host, and [`trust`] keys remote workspace trust by what the connection -//! resolves. Domain semantics stay in their engines (Git, build, language -//! servers); this crate only supplies the IO boundary. +//! (processes, terminals, watches), [`forwards`] keeps the port forwards of +//! the ports page, [`upload`] streams a verified file to the host, and +//! [`trust`] keys remote workspace trust by what the connection resolves. +//! Domain semantics stay in their engines (Git, build, language servers); +//! this crate only supplies the IO boundary. pub mod connections; +pub mod forwards; pub mod fs; pub mod host; pub mod probe; diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index d20fd9a1..0234bc18 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -5,7 +5,7 @@ //! so the user authenticates once. The connection then stays open in this //! registry until `remote.disconnect`; requests such as `remote.readDir` use //! it by id. OpenSSH runs in its own process tree, which closing a connection -//! ends. +//! ends, together with the connection's port forwards. use crate::probe::{classify, diagnostics, ssh_hop, ProbeStatus, ProbedHost}; use lithe_git_host::ProcessTree; @@ -15,8 +15,8 @@ use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched use lithe_remote::client::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ - ArtifactError, ConnectionKind, ConnectionLog, Hop, RemoteSession, ServerArtifact, ServerTarget, - TransportChain, + ArtifactError, ConnectionKind, ConnectionLog, ForwardSet, Hop, RemoteSession, ServerArtifact, + ServerTarget, TransportChain, }; use lithe_remote::protocol::methods; use lithe_request_context::events as execution_events; @@ -102,13 +102,16 @@ pub struct ConnectResult { /// One open host connection in the registry. pub struct Connection { - /// Framed workspace session to the host server. - pub session: RemoteSession, + /// Framed workspace session to the host server, shared with the port + /// forwards that tunnel through it. + pub session: Arc, /// Git executable path and version found on the host, once resolved. pub git_tool: Mutex>, /// Where the connection ends, the key of its workspaces' trust together /// with their real paths. Fixed when the connection opens. pub(crate) trust_target: Target, + /// Port forwards of the ports page; they end with the session. + pub(crate) forwards: ForwardSet, pub(crate) transport: ConnectionTransport, } @@ -118,12 +121,31 @@ pub(crate) enum ConnectionTransport { child: Mutex, tree: ProcessTree, }, - #[cfg(any(test, feature = "test-support"))] + #[cfg(feature = "test-support")] InProcess, } impl Connection { + /// A registered connection over `session`, with no forwards yet. + pub(crate) fn new( + session: RemoteSession, + trust_target: Target, + transport: ConnectionTransport, + ) -> Self { + let session = Arc::new(session); + Self { + forwards: ForwardSet::new(Arc::clone(&session)), + session, + git_tool: Mutex::new(None), + trust_target, + transport, + } + } + pub(crate) fn close(&self) { + // Local ports close first, so nothing new is accepted into a tunnel + // the shutdown below is about to end. + self.forwards.close(); if let Err(error) = self.session.request_value( methods::SERVER_SHUTDOWN, serde_json::Value::Null, @@ -163,7 +185,7 @@ impl Connection { record_cleanup_io("tree-terminate", &error); } } - #[cfg(any(test, feature = "test-support"))] + #[cfg(feature = "test-support")] ConnectionTransport::InProcess => {} } } @@ -232,6 +254,18 @@ pub(crate) fn lookup(id: &str) -> Result, CoreError> { }) } +/// Removes a connection whose session ended and closes it in the background, +/// so the host reconnects instead of retrying a dead session. +pub(crate) fn forget(id: &str) { + if let Some(connection) = registry() + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .remove(id) + { + std::thread::spawn(move || connection.close()); + } +} + /// Opens a connection and registers it. pub fn connect(request: ConnectRequest) -> Result { connect_with(request, None) @@ -574,15 +608,14 @@ fn connect_logged( .unwrap_or_else(|poisoned| poisoned.into_inner()) .insert( id.clone(), - Arc::new(Connection { + Arc::new(Connection::new( session, - git_tool: Mutex::new(None), - trust_target: Target::new(&chain, capabilities.user_id), - transport: ConnectionTransport::Ssh { + Target::new(&chain, capabilities.user_id), + ConnectionTransport::Ssh { child: Mutex::new(child), tree, }, - }), + )), ); Ok(ConnectResult { status: ProbeStatus::Connected, @@ -822,15 +855,8 @@ pub fn request_error(session_id: &str, error: ClientError) -> CoreError { "The remote host did not answer in time", ), ClientError::Disconnected { diagnostics } => { - // A broken connection cannot recover; forget it so the host - // reconnects instead of retrying a dead session. - if let Some(connection) = registry() - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(session_id) - { - std::thread::spawn(move || connection.close()); - } + // A broken connection cannot recover. + forget(session_id); CoreError::new(ErrorCode::ConnectionClosed, "The remote connection closed") .with_details(diagnostics) } diff --git a/rust/crates/workspace/src/test_support.rs b/rust/crates/workspace/src/test_support.rs index 09fa4c7a..45eec91a 100644 --- a/rust/crates/workspace/src/test_support.rs +++ b/rust/crates/workspace/src/test_support.rs @@ -4,7 +4,7 @@ use crate::sessions::{lookup, nonce, registry, Connection, ConnectionTransport}; use lithe_remote::client::trust::Target; use lithe_remote::client::{RemoteSession, TransportChain}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; /// Registers `session` as a connected host and returns its session id. Its /// trust target has no hops, only the account the server reports. @@ -13,12 +13,11 @@ pub fn register_in_process(session: RemoteSession) -> String { let trust_target = Target::new(&TransportChain::local(), session.hello().host.user_id); registry().lock().unwrap().insert( id.clone(), - Arc::new(Connection { + Arc::new(Connection::new( session, - git_tool: Mutex::new(None), trust_target, - transport: ConnectionTransport::InProcess, - }), + ConnectionTransport::InProcess, + )), ); id }