diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 82b96cfa..ce6d1fc1 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -410,6 +410,10 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported: - `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 +- `forward_host_port_in_use`: another program on the remote host already uses the port a host or reverse forward asks for +- `forward_host_port_denied`: the remote host does not allow listening on the port a host or reverse forward asks for +- `forward_host_unsupported`: the remote server cannot listen on host ports for host or reverse forwards +- `reverse_forward_disabled`: the remote workspace settings do not allow reverse forwards - `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 36d0d38e..06681617 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -49,8 +49,10 @@ Other clients should do the same. bytes of UTF-8 JSON. Frames larger than 16 MiB are rejected. 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. Local port forwards are the client's: the reference client +All traffic, including tunnels, uses this stream. The server listens on a +network port only for a forwarding rule the user added (`listener.open`, see +"Listeners"); such a port belongs to the connection that opened it and +closes with it. 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 @@ -154,6 +156,10 @@ 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 | +| `listener.open` | `listenerId`, `host` (an IP address), `port` (`0`: the host chooses), `relay?` (a `tunnel.open` target) | `port`; `ADDRESS_IN_USE` when another socket holds the port, `PERMISSION_DENIED` when the host refuses it, `BUSY` while the session has 64 listeners | +| `listener.adopt` | `listenerId`, `acceptId`, `tunnelId` | `null`; the waiting connection becomes that tunnel; `UNKNOWN_RESOURCE` when it no longer waits | +| `listener.close` | `listenerId` | `listenerId`, `port`, `connections`, `failedConnections`; closes the port and every connection it relays or still holds | +| `listener.list` | — | `listeners` by `listenerId`: `listenerId`, `port`, `connections`, `failedConnections` | | `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 — @@ -257,10 +263,40 @@ environment and caches it for the session. `process.spawn` with | `walk.done` | `walkId`, `total`, `truncated`, `cancelled`, `skippedNonUtf8`, `unreadableDirectories` | | `tunnel.data` | `tunnelId`, `data` | | `tunnel.closed` | `tunnelId`, `error?` — the last event of the tunnel | +| `listener.accepted` | `listenerId`, `acceptId` — a reverse listener holds a connection for `listener.adopt` | `watch.changed` batches are coalesced and sorted by path. With `overflow` changes were lost and the client must rescan the watched tree. +## Listeners + +The `listener` feature lets a client make the host listen on a TCP port for +a forwarding rule the user added: + +- With `relay`, a **host rule**: the host connects every accepted connection + to that target itself and copies the bytes on the host, so nothing + crosses the stream. `host` is a loopback address, or `0.0.0.0` or `::` + when the user confirmed listening on every interface. At most 64 + connections of one listener and 256 of the session are relayed at once; + further ones wait in the kernel's backlog, or are closed and counted as + failed when the session is at its limit. +- Without `relay`, a **reverse rule**: `host` must be a loopback address. + Every accepted connection waits, at most 16 at once per listener, for the + client, which receives `listener.accepted`, subscribes to a new tunnel and + calls `listener.adopt`; the connection then behaves as a tunnel the client + opened. A connection not adopted within 10 seconds is closed and counted + as failed. + +Host names are refused, so the host never resolves what the client sends as +an address to bind. `failedConnections` counts connections that never +reached their target: a relay target that refused, a connection not adopted +in time, or one the host had no thread or tunnel left for. A listener +belongs to the connection that opened it, also in a persistent session, and +closes when that connection ends; clients do not reopen one after a +reconnect on their own, so a host port is open only while the user's rule +is. `listener.close` waits up to one second for the port to be released, so +a rule edited to the same port can bind it again at once. + ## Event delivery and persistent sessions `server.hello` returns `session` with `persistent`, `resumed`, @@ -291,8 +327,8 @@ events after `afterSeq` were dropped; the client re-reads state and rescans watches. While no client is attached, a persistent session keeps processes, terminals -and watches running. Tunnels and walks belong to the connection that opened -them and end with it. After `server.shutdown` a persistent session is no +and watches running. Tunnels, walks and listeners belong to the connection +that opened them and end with it. After `server.shutdown` a persistent session is no longer reachable, even while it is still terminating its processes; the next connection with the same key starts a fresh session. @@ -318,7 +354,7 @@ the field. `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 +`ADDRESS_IN_USE`, `BUSY`, `UNSUPPORTED`, `IO`. Clients additionally produce `TIMEOUT` and `DISCONNECTED` locally. Messages are for people; OS error numbers stay in `details`. `BUSY` always means a capacity limit that may clear: retrying later is safe because the failed request changed nothing. diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 94064712..2a5454bc 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -818,7 +818,9 @@ or removing a command fails until the table changes in the same commit. | `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.startHostForward` | Make the remote host listen on a port and connect it to another server | +| `remote.startReverseForward` | Make the remote host listen on a loopback port that reaches a port on this machine | +| `remote.stopForward` | Stop one port forward and close the port it listens on | | `remote.forwards` | List the running port forwards of one connection | | `remote.parseForwardAddress` | Read a port, `host:port` or URL typed into the ports page into a forward target | | `remote.connections` | Read the SSH connections the user saved | @@ -829,7 +831,7 @@ or removing a command fails until the table changes in the same commit. | `remote.mottyHosts` | List the SSH hosts saved in Motty for an import | | `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine | | `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to | -| `remote.editPreferences` | Set the SSH program or the reconnect limit, or make one automatic again | +| `remote.editPreferences` | Set the SSH program, the reconnect limit or whether reverse forwards are allowed, or make one automatic again | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | | `git.remotes` | Return configured fetch remote names and URLs | | `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations | @@ -5927,17 +5929,18 @@ the distributions each time it opens. #### Remote workspace preferences -The settings page "Tools › Remote Workspace" edits two values that apply to +The settings page "Tools › Remote Workspace" edits three values that apply to every connection. Native clients keep them in one machine-local document, read it, and publish the `document` an edit returns atomically, as for the saved connections; Core validates the document, applies every edit and tells what each automatic value resolves to. `remote.preferences` accepts `{ document: string|null, homeDirectory? }` -and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`: +and returns `{ preferences, ssh, reconnect, reverseForwarding, storage, +sshConfig? }`: -- `preferences` is `{ sshProgram, reconnectLimitSeconds }`, the stored - values; `null` is automatic. +- `preferences` is `{ sshProgram, reconnectLimitSeconds, + allowReverseForwarding }`, the stored values; `null` is automatic. - `ssh` is `{ source, path, status }`, the OpenSSH client every connection starts. `source` is `setting` for a stored program and `automatic` otherwise, which is the first executable `ssh` (`ssh.exe` on Windows) in an @@ -5951,6 +5954,9 @@ and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`: double up to 30 seconds and add up to the limit; the last one is shortened to fit. A limit of 0 never reconnects, so the list is empty. Clients wait these pauses and decide nothing else about the schedule. +- `reverseForwarding` is `{ source, allowed }`: whether the ports page may + start reverse forwards (automatic: not allowed), because every user of the + host can reach the local port one opens. - `storage` is `{ relativePath: "remote/preferences.json", maximumBytes: 16384 }`. - `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`, @@ -5963,10 +5969,12 @@ and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`: existing executable file, or makes the program automatic with `null`. - `reconnectLimit: { seconds: number|null }` stores 0 to 3600 seconds, or makes the limit automatic with `null`. +- `reverseForwarding: { allowed: boolean|null }` allows or refuses reverse + forwards, or makes the switch automatic with `null`. The result is `{ changed, document: string|null }`; an unchanged edit -returns a `null` document and must not create a source. Neither or both -fields is `invalid_request` with `{ field: "operation", reason: "invalid" +returns a `null` document and must not create a source. No field or more +than one is `invalid_request` with `{ field: "operation", reason: "invalid" }`; a refused value is `invalid_request` with `{ field, reason }`, where `field` is `sshProgram` or `reconnectLimitSeconds` and `reason` is `invalid` (empty, surrounding spaces or control characters), `tooLong` @@ -6111,8 +6119,18 @@ 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` +The ports page runs three kinds of forwards over one connection: + +- a **local** forward listens on this machine and reaches a TCP port as the + remote host sees it; +- a **host** forward makes the host listen on a port and connect every + accepted connection to another server itself, as `ssh -L` on a jump host + does; the bytes never cross the connection; +- a **reverse** forward makes the host listen on its loopback interface and + brings every accepted connection back to a port on this machine's loopback + interface, as `ssh -R 127.0.0.1:…` does. + +The page 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: @@ -6120,12 +6138,26 @@ owning process). Forwards belong to one connection: | Command | Request | Result | | --- | --- | --- | | `remote.startForward` | `{ sessionId, targetHost, targetPort, localPort?, allowNonLoopbackTarget? }` | `{ forward, created }` | +| `remote.startHostForward` | `{ sessionId, targetHost, targetPort, listenPort?, allInterfaces?, allowNonLoopbackTarget? }` | `{ forward, created }` | +| `remote.startReverseForward` | `{ sessionId, localPort, listenPort?, preferences }` | `{ forward, created }` | | `remote.stopForward` | `{ sessionId, forwardId }` | `{ stopped }` | | `remote.forwards` | `{ sessionId }` | `{ forwards }`, by `id` | | `remote.parseForwardAddress` | `{ text }` | `{ targetHost, targetPort, scheme?, path? }` | -A forward is `{ id, localHost, localPort, requestedLocalPort?, -localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. +A forward is `{ id, kind, localHost?, localPort?, requestedLocalPort?, +localPortChanged, hostListenHost?, hostListenPort?, requestedHostPort?, +allInterfaces, targetHost?, targetPort?, loopbackTarget, connections, +failedConnections }`. `kind` is `local`, `host` or `reverse`; a field that +does not apply to the kind is absent: + +| Kind | Listens on | Reaches | +| --- | --- | --- | +| `local` | `localHost:localPort` | `targetHost:targetPort` as the host sees it | +| `host` | `hostListenHost:hostListenPort` | `targetHost:targetPort` as the host resolves it | +| `reverse` | `hostListenHost:hostListenPort` (always `127.0.0.1`) | `localHost:localPort` (always `127.0.0.1`) on this machine | + +`connections` counts accepted connections and `failedConnections` those +that could not reach their target (always 0 for a local forward). - **Target.** `targetHost` is an IP address (IPv6 with or without brackets) or a host name the remote host resolves, such as `localhost`. A wildcard @@ -6133,7 +6165,8 @@ localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. 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`). + (`targetHost`, `targetPort`, or `localPort` for a reverse forward's port + `0`). - **Typed address.** `remote.parseForwardAddress` reads what the user typed into the page, without a connection and without resolving anything: a port alone (`3000`, on `localhost`), `host:port` with brackets around an @@ -6153,23 +6186,42 @@ localPortChanged, targetHost, targetPort, loopbackTarget, connections }`. `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. + the two apart in the list. The rule is the same for host forwards. - **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 +- **Host port.** Host and reverse forwards listen on the host port + `listenPort` (absent or `0` for one the host chooses) and never move to + another one: a port another host program uses is + `forward_host_port_in_use`, and one the host refuses, such as a port below + 1024 for an unprivileged user, is `forward_host_port_denied`. A host + forward listens on the host's loopback interface unless `allInterfaces` is + `true`; native clients ask the user every time and never remember it, + because every machine that reaches the host can then use the port. A + server that cannot listen is `forward_host_unsupported`. +- **Reverse forwards are off by default.** `remote.startReverseForward` + takes the current remote preferences `document` as `preferences` and is + `reverse_forward_disabled` unless they allow reverse forwards; native + clients also ask the user before each one starts. The local side only ever + connects to `127.0.0.1`, then `::1`, so a host user cannot reach the local + network through it. +- **Once per rule.** Starting a rule that already runs returns that forward + with `created: false`, so a repeated click opens no second port: a local + forward by target, a host forward by host port (or any port when none is + asked), interfaces and target, a reverse forward by host port and local + port. A connection keeps at most 64 forwards of all kinds together; one + more is `forward_limit_reached` with `details.maximum`. +- **Lifetime.** `remote.stopForward` closes the port the forward listens + on; connections it already accepted run until either side closes them, + except a host forward's, which the host closes with its port. An unknown + id returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a + lost connection close every port the connection opened on either side, + and a reconnect reopens none of them. Requests on a connection whose session ended are `connection_closed` and forget it, as - for the other commands. `connections` counts accepted local connections. + for the other commands. #### Remote workspace trust diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 0efcefa5..0b1a9b0d 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1014,6 +1014,12 @@ pub enum RemoteCommand { /// Forwards a local port to a port as the remote host sees it /// (`remote.startForward`). StartForward, + /// Makes the remote host listen on a port and connect it to another + /// server (`remote.startHostForward`). + StartHostForward, + /// Makes the remote host listen on a loopback port that reaches a port + /// on this machine (`remote.startReverseForward`). + StartReverseForward, /// Stops one port forward and closes its local port (`remote.stopForward`). StopForward, /// Lists the running port forwards of one connection (`remote.forwards`). @@ -1613,6 +1619,8 @@ impl CoreCommand { "remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)), "remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)), "remote.startForward" => Some(Self::Remote(RemoteCommand::StartForward)), + "remote.startHostForward" => Some(Self::Remote(RemoteCommand::StartHostForward)), + "remote.startReverseForward" => Some(Self::Remote(RemoteCommand::StartReverseForward)), "remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)), "remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)), "remote.parseForwardAddress" => Some(Self::Remote(RemoteCommand::ParseForwardAddress)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 1cc905f9..208afe01 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -179,6 +179,30 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu Err(error) => CoreResponse::failure(id, error), } } + RemoteCommand::StartHostForward => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::start_host) + { + Ok(started) => CoreResponse::success( + id, + serde_json::to_value(started).expect("port forward result should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + } + } + RemoteCommand::StartReverseForward => { + match serde_json::from_value(payload) + .map_err(|error| invalid_forward_request(&error)) + .and_then(lithe_workspace::forwards::start_reverse) + { + 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)) diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 6f14064f..d31e5c07 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -292,6 +292,8 @@ mod tests { "lsp.startServer", "remote.connect", "remote.startForward", + "remote.startHostForward", + "remote.startReverseForward", "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 c79efe69..8b2e82d6 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1538,3 +1538,143 @@ fn remote_port_forwards_start_once_per_target_and_end_with_the_connection() { "connection_closed" ); } + +// Forwards that listen on the host: a host port relays to another server, a +// taken host port keeps its own category, and a reverse forward waits for the +// settings switch before it brings host connections back to a local port. +#[test] +fn remote_host_and_reverse_forwards_follow_their_own_rules() { + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + + let echo = || { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let worker = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(STEP)).unwrap(); + let mut buffer = [0_u8; 4]; + stream.read_exact(&mut buffer).unwrap(); + stream.write_all(&buffer).unwrap(); + }); + (port, worker) + }; + let exchange = |port: u64| { + let mut stream = TcpStream::connect(("127.0.0.1", u16::try_from(port).unwrap())).unwrap(); + stream.set_read_timeout(Some(STEP)).unwrap(); + stream.write_all(b"ping").unwrap(); + let mut answer = [0_u8; 4]; + stream.read_exact(&mut answer).unwrap(); + answer + }; + let host = HostFixture::new(); + let call = |command: &str, payload: Value| -> Value { + let mut payload = payload; + payload["sessionId"] = json!(host.id); + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "timeoutMilliseconds": 30_000, "payload": payload}) + .to_string(), + )) + .unwrap() + }; + let plain = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"id": test_support::unique_id(), "command": command, + "payload": payload}) + .to_string(), + )) + .unwrap() + }; + let ok = |response: Value| -> Value { + assert_eq!(response["ok"], true, "{response}"); + response["data"].clone() + }; + let code = |response: Value| -> Value { + assert_eq!(response["ok"], false, "{response}"); + response["error"]["code"].clone() + }; + + let (target_port, target) = echo(); + let started = ok(call( + "remote.startHostForward", + json!({"targetHost": "localhost", "targetPort": target_port}), + )); + let forward = started["forward"].clone(); + assert_eq!(forward["kind"], "host", "{started}"); + assert_eq!(forward["hostListenHost"], "127.0.0.1", "{started}"); + assert_eq!(forward["allInterfaces"], false, "{started}"); + assert!(forward.get("localPort").is_none(), "{started}"); + assert_eq!( + &exchange(forward["hostListenPort"].as_u64().unwrap()), + b"ping" + ); + target.join().unwrap(); + + assert_eq!( + code(call( + "remote.startHostForward", + json!({"targetHost": "192.0.2.10", "targetPort": 5432}), + )), + "forward_target_not_confirmed" + ); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + assert_eq!( + code(call( + "remote.startHostForward", + json!({"listenPort": taken.local_addr().unwrap().port(), + "targetHost": "127.0.0.1", "targetPort": target_port}), + )), + "forward_host_port_in_use" + ); + + // Reverse forwards stay off until the user turns them on. + let (local_port, local) = echo(); + let reverse = json!({"localPort": local_port, "preferences": null}); + assert_eq!( + code(call("remote.startReverseForward", reverse.clone())), + "reverse_forward_disabled" + ); + let read = ok(plain("remote.preferences", json!({"document": null}))); + assert_eq!( + read["reverseForwarding"], + json!({"source": "automatic", "allowed": false}), + "{read}" + ); + let edited = ok(plain( + "remote.editPreferences", + json!({"document": null, "reverseForwarding": {"allowed": true}}), + )); + let mut allowed = reverse; + allowed["preferences"] = edited["document"].clone(); + let started = ok(call("remote.startReverseForward", allowed.clone())); + let back = started["forward"].clone(); + assert_eq!(back["kind"], "reverse", "{started}"); + assert_eq!(back["hostListenHost"], "127.0.0.1", "{started}"); + assert_eq!(back["localPort"], local_port, "{started}"); + assert_eq!(&exchange(back["hostListenPort"].as_u64().unwrap()), b"ping"); + local.join().unwrap(); + let again = ok(call("remote.startReverseForward", allowed.clone())); + assert_eq!(again["created"], false, "{again}"); + assert_eq!(again["forward"]["id"], back["id"], "{again}"); + + allowed["localPort"] = json!(0); + let refused = call("remote.startReverseForward", allowed); + assert_eq!(code(refused.clone()), "invalid_request"); + let details: Value = + serde_json::from_str(refused["error"]["details"].as_str().unwrap()).unwrap(); + assert_eq!(details["field"], "localPort", "{refused}"); + + let listed = ok(call("remote.forwards", json!({}))); + let kinds: Vec<&str> = listed["forwards"] + .as_array() + .unwrap() + .iter() + .map(|forward| forward["kind"].as_str().unwrap()) + .collect(); + assert_eq!(kinds, ["host", "reverse"], "{listed}"); + assert_eq!( + ok(call("remote.stopForward", json!({"forwardId": back["id"]})))["stopped"], + true + ); +} diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index a4edf634..c252769f 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1407,6 +1407,40 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 12, owner: "lithe-core", }, + EventMetadata { + id: "remote.forward.host_removed", + channel: "remote", + level: LogLevel::Info, + message: "Port forward on host port {listen_port} removed", + fields: &[ + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "connections", field_type: FieldType::Int, required: true, description: "Number of connections the host port accepted during its lifetime", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Time from starting the forward until the host stopped listening", reason: None }, + FieldMetadata { name: "failed_connections", field_type: FieldType::Int, required: true, description: "Accepted connections that never reached their target", reason: None }, + FieldMetadata { name: "listen_port", field_type: FieldType::Int, required: true, description: "TCP port the remote host stopped listening on", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "remote.forward.host_started", + channel: "remote", + level: LogLevel::Info, + message: "Port forward started on host port {listen_port}", + fields: &[ + FieldMetadata { name: "bind_scope", field_type: FieldType::Token, required: true, description: "Whether the host listener is bound to loopback only or to every interface", reason: None }, + FieldMetadata { name: "connection", field_type: FieldType::Id, required: true, description: "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token", reason: None }, + FieldMetadata { name: "kind", field_type: FieldType::Token, required: true, description: "host when the remote host relays to another server, reverse when connections come back to this machine", reason: None }, + FieldMetadata { name: "listen_port", field_type: FieldType::Int, required: true, description: "TCP port the remote host listens on, after the system chose one for port 0", reason: None }, + FieldMetadata { name: "local_port", field_type: FieldType::Int, required: false, description: "Loopback port on this machine a reverse forward connects to; absent for host forwards", reason: None }, + FieldMetadata { name: "target_port", field_type: FieldType::Int, required: false, description: "TCP port a host forward relays to; absent for reverse forwards, and the target host is never logged", reason: None }, + FieldMetadata { name: "target_scope", field_type: FieldType::Token, required: false, description: "Whether a host forward's target is a loopback name or address, or another network host", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "remote.forward.removed", channel: "remote", diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index eb0d9bf4..38acf3d3 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -80,6 +80,20 @@ pub enum ErrorCode { /// `remote.startForward` found the connection at its forward limit /// (`details.maximum`); stopping a forward makes room. ForwardLimitReached, + /// `remote.startHostForward` or `remote.startReverseForward` asked for a + /// host port another program on the host already listens on. Nothing + /// started; another port, or none to let the host choose, can. + ForwardHostPortInUse, + /// The remote host refused to listen on the requested host port, as + /// Linux does for ports below 1024 to unprivileged users. Nothing started. + ForwardHostPortDenied, + /// The remote server the connection runs cannot listen on host ports, so + /// only forwards that listen on this machine are available. + ForwardHostUnsupported, + /// `remote.startReverseForward` was refused because the remote + /// preferences do not allow reverse forwards (`allowReverseForwarding`). + /// Nothing started; the user can allow them in the settings. + ReverseForwardDisabled, /// `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/api.rs b/rust/crates/remote/src/client/api.rs index 91eff5c5..32c02133 100644 --- a/rust/crates/remote/src/client/api.rs +++ b/rust/crates/remote/src/client/api.rs @@ -10,15 +10,16 @@ use crate::client::session::{ClientError, Event, RemoteSession}; use crate::protocol::methods::{ self, decode_bytes, encode_bytes, CopyParams, CopyResult, CreateDirParams, EnvironmentResolveParams, EnvironmentResolveResult, EnvironmentSource, FileMetadata, - FileVersion, KillParams, ListeningPort, ListeningPortsResult, OutputStream, PathParams, - ProcessExitEvent, ProcessOutputEvent, ProcessParams, ReadDirResult, ReadFileParams, - ReadFileResult, RealPathResult, RemoveParams, RenameParams, ResourceLabel, ServerState, - SetPermissionsParams, SpawnParams, SpawnResult, TerminalExitEvent, TerminalOpenParams, - TerminalOpenResult, TerminalOutputEvent, TerminalParams, TerminalResizeParams, - TerminalWriteParams, TunnelClosedEvent, TunnelDataEvent, TunnelOpenParams, TunnelParams, - TunnelTarget, TunnelWriteParams, VolumeInfo, WalkDoneEvent, WalkEntriesEvent, WalkEntry, - WalkParams, WalkStartParams, WatchChangedEvent, WatchErrorEvent, WatchParams, WatchStartParams, - WatchStartResult, WriteFileParams, MAX_TRANSFER_BYTES, + FileVersion, KillParams, ListenerAdoptParams, ListenerOpenParams, ListenerOpened, + ListenerParams, ListenerState, ListenersResult, ListeningPort, ListeningPortsResult, + OutputStream, PathParams, ProcessExitEvent, ProcessOutputEvent, ProcessParams, ReadDirResult, + ReadFileParams, ReadFileResult, RealPathResult, RemoveParams, RenameParams, ResourceLabel, + ServerState, SetPermissionsParams, SpawnParams, SpawnResult, TerminalExitEvent, + TerminalOpenParams, TerminalOpenResult, TerminalOutputEvent, TerminalParams, + TerminalResizeParams, TerminalWriteParams, TunnelClosedEvent, TunnelDataEvent, + TunnelOpenParams, TunnelParams, TunnelTarget, TunnelWriteParams, VolumeInfo, WalkDoneEvent, + WalkEntriesEvent, WalkEntry, WalkParams, WalkStartParams, WatchChangedEvent, WatchErrorEvent, + WatchParams, WatchStartParams, WatchStartResult, WriteFileParams, MAX_TRANSFER_BYTES, }; use crate::protocol::{ErrorCode, RemoteError}; use serde::de::DeserializeOwned; @@ -517,6 +518,72 @@ impl RemoteSession { } } } + + /// Opens a host listener and returns the bound port. With `relay` the + /// host connects accepted connections to that target itself; without + /// it the caller subscribes to `listener` events for `listener_id` + /// first and adopts every accepted connection with + /// [`RemoteSession::adopt_tunnel`]. + pub fn open_listener( + &self, + listener_id: u64, + host: &str, + port: u16, + relay: Option, + ) -> Result { + self.call::<_, ListenerOpened>( + methods::LISTENER_OPEN, + &ListenerOpenParams { + listener_id, + host: host.into(), + port, + relay, + }, + ) + .map(|opened| opened.port) + } + + /// Closes a host listener and every connection it still holds, and + /// returns its final counts. + pub fn close_listener(&self, listener_id: u64) -> Result { + self.call(methods::LISTENER_CLOSE, &ListenerParams { listener_id }) + } + + /// The session's host listeners with their connection counts. + pub fn listeners(&self) -> Result, ClientError> { + self.call::<_, ListenersResult>(methods::LISTENER_LIST, &json!({})) + .map(|result| result.listeners) + } + + /// Turns the connection `accept_id` of a reverse listener into a tunnel, + /// subscribing to its events first as [`RemoteSession::open_tunnel`] + /// does. + pub fn adopt_tunnel( + &self, + listener_id: u64, + accept_id: u64, + ) -> Result, ClientError> { + let tunnel_id = self.allocate_id(); + let events = self.subscribe("tunnel", tunnel_id); + match self.call_unit( + methods::LISTENER_ADOPT, + &ListenerAdoptParams { + listener_id, + accept_id, + tunnel_id, + }, + ) { + Ok(()) => Ok(TunnelHandle { + session: self, + id: tunnel_id, + events, + }), + Err(error) => { + self.unsubscribe("tunnel", tunnel_id); + Err(error) + } + } + } } /// A spawned process. Dropping it only ends the subscription; the process diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index df544c3e..a2825971 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -22,7 +22,8 @@ //! 6. `remote.connection.cleaned` when the established session is released. //! //! Port forwards over the session add `remote.forward.started` and -//! `remote.forward.removed`. +//! `remote.forward.removed`; forwards that listen on the host add +//! `remote.forward.host_started` and `remote.forward.host_removed`. //! //! Several layers can see the same failure: the launch script, the protocol //! handshake, and the caller that owns the SSH process. Each reports the most @@ -52,6 +53,8 @@ pub(crate) const INTERRUPTED: &str = "remote.connection.interrupted"; pub(crate) const CLEANED: &str = "remote.connection.cleaned"; pub(crate) const FORWARD_STARTED: &str = "remote.forward.started"; pub(crate) const FORWARD_REMOVED: &str = "remote.forward.removed"; +pub(crate) const HOST_FORWARD_STARTED: &str = "remote.forward.host_started"; +pub(crate) const HOST_FORWARD_REMOVED: &str = "remote.forward.host_removed"; // Session states only move forward, in this order. @@ -320,6 +323,64 @@ impl ConnectionLog { ); } + /// Records a host port that relays to `target_host:target_port`. Only the + /// ports and whether each side is a loopback address are recorded. + pub(crate) fn host_forward_started( + &self, + listen_port: u16, + all_interfaces: bool, + target_host: &str, + target_port: u16, + ) { + self.emit( + HOST_FORWARD_STARTED, + vec![ + ("kind", json!("host")), + ("listen_port", json!(listen_port)), + ("bind_scope", json!(scope(!all_interfaces))), + ("target_port", json!(target_port)), + ( + "target_scope", + json!(scope(forward_set::is_loopback_host(target_host))), + ), + ], + ); + } + + /// Records a host loopback port whose connections reach `local_port` on + /// this machine's loopback. + pub(crate) fn reverse_forward_started(&self, listen_port: u16, local_port: u16) { + self.emit( + HOST_FORWARD_STARTED, + vec![ + ("kind", json!("reverse")), + ("listen_port", json!(listen_port)), + ("bind_scope", json!(scope(true))), + ("local_port", json!(local_port)), + ], + ); + } + + /// Records a host port that stopped after accepting `connections`, of + /// which `failed_connections` never reached their target. + pub(crate) fn host_forward_removed( + &self, + listen_port: u16, + connections: u64, + failed_connections: u64, + duration: Duration, + ) { + self.emit( + HOST_FORWARD_REMOVED, + vec![ + ("listen_port", json!(listen_port)), + ("connections", json!(connections)), + ("failed_connections", json!(failed_connections)), + ("duration_ms", millis(duration)), + ], + ); + } + /// True for the first outcome of the attempt. fn settle(&self) -> bool { !self.0.settled.swap(true, Ordering::AcqRel) diff --git a/rust/crates/remote/src/client/forward.rs b/rust/crates/remote/src/client/forward.rs index 56c02220..8f269ec0 100644 --- a/rust/crates/remote/src/client/forward.rs +++ b/rust/crates/remote/src/client/forward.rs @@ -20,7 +20,7 @@ //! [`ConnectionLog`] with the local port and the number of accepted //! connections; the remote host and socket path are not recorded. -use crate::client::api::TunnelEvent; +use crate::client::api::{TunnelEvent, TunnelHandle}; use crate::client::connection_log::ConnectionLog; use crate::client::session::{ClientError, RemoteSession}; use crate::protocol::methods::TunnelTarget; @@ -249,14 +249,14 @@ impl Acceptor { } /// The connections one forward is bridging, at most `limit` at once. -struct Slots { +pub(crate) struct Slots { limit: usize, active: Mutex, freed: Condvar, } impl Slots { - fn new(limit: usize) -> Self { + pub(crate) fn new(limit: usize) -> Self { Self { limit, active: Mutex::new(0), @@ -265,7 +265,7 @@ impl Slots { } /// Waits for a free slot, or returns `None` once the forward stops. - fn acquire(self: &Arc, stopping: &AtomicBool) -> Option { + pub(crate) 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) { @@ -284,7 +284,7 @@ impl Slots { /// One bridged connection's slot, freed when its bridge ends, including when /// the bridge thread never starts or panics. -struct Slot(Arc); +pub(crate) struct Slot(Arc); impl Drop for Slot { fn drop(&mut self) { @@ -311,6 +311,16 @@ fn bridge( return Err(error); } }; + pump(session, local, tunnel) +} + +/// Copies bytes between a local connection and an open tunnel until either +/// side closes, passing a half-close on in both directions. +pub(crate) fn pump( + session: &RemoteSession, + local: TcpStream, + tunnel: TunnelHandle<'_>, +) -> Result<(), ClientError> { let mut to_remote = local.try_clone().map_err(ClientError::Spawn)?; let mut to_local = local; let local_done = Arc::new(AtomicBool::new(false)); @@ -379,7 +389,7 @@ fn bridge( // matching the catalog's rate=12 even across concurrent forwarded connections. const FAILURE_LOG_INTERVAL: Duration = Duration::from_secs(5); static ACCEPT_LOG: Mutex> = Mutex::new(None); -static BRIDGE_LOG: Mutex> = Mutex::new(None); +pub(crate) static BRIDGE_LOG: Mutex> = Mutex::new(None); fn permit_failure(last: &mut Option, now: Instant) -> bool { if last.is_some_and(|previous| now.saturating_duration_since(previous) < FAILURE_LOG_INTERVAL) { @@ -389,7 +399,7 @@ fn permit_failure(last: &mut Option, now: Instant) -> bool { true } -fn forward_failed( +pub(crate) fn forward_failed( event: &str, log: &ConnectionLog, stage: &'static str, diff --git a/rust/crates/remote/src/client/forward_set.rs b/rust/crates/remote/src/client/forward_set.rs index a4886621..95197ea9 100644 --- a/rust/crates/remote/src/client/forward_set.rs +++ b/rust/crates/remote/src/client/forward_set.rs @@ -1,31 +1,51 @@ //! 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: +//! A [`ForwardSet`] starts, lists and stops the forwards of one +//! [`RemoteSession`] and owns them until they stop. A forward is one of +//! three [`ForwardKind`]s: +//! +//! - **Local** ([`ForwardSpec`]): a port on this machine's loopback interface +//! reaches a target as the remote host sees it, through tunnels. +//! - **Host** ([`HostForwardSpec`]): a port on the remote host reaches another +//! server, and the host connects to it itself. +//! - **Reverse** ([`ReverseForwardSpec`]): a port on the remote host's +//! loopback interface reaches a port on this machine's loopback interface. +//! +//! The rules: //! //! - **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. +//! `allow_non_loopback_target`, which the application sets only after the +//! user confirmed that target (design S28). +//! - **Local ports.** A local 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. +//! - **Host ports.** A host forward listens on the host's loopback interface +//! unless [`HostForwardSpec::all_interfaces`] is set, which the +//! application sets only after the user confirmed it for this rule. A +//! reverse forward always listens on the host's loopback interface. A +//! requested host port that is taken fails with +//! [`ForwardError::HostPortInUse`] instead of moving: other machines rely +//! on that port. +//! - **Session end** releases every forward and closes their ports (design +//! S29). The host closes its listeners when this client disconnects, and +//! nothing reopens them after a reconnect. //! -//! Starting the same target twice returns the forward that already exists, -//! so a repeated click does not open a second local port. +//! Starting a forward identical to a running one returns the running one, so +//! a repeated click does not open a second port. All kinds count against +//! [`MAX_FORWARDS`] together. use crate::client::forward::PortForward; -use crate::client::session::RemoteSession; -use crate::protocol::methods::TunnelTarget; +use crate::client::host_forward::{HostForward, ReverseForward}; +use crate::client::session::{ClientError, RemoteSession}; +use crate::protocol::message::ErrorCode; +use crate::protocol::methods::{Feature, TunnelTarget}; use serde::Serialize; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream}; @@ -33,8 +53,8 @@ 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. +/// Most forwards one session keeps at once, of all kinds together. Each one +/// holds a port and a 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. @@ -45,7 +65,14 @@ const MAX_HOST_BYTES: usize = 253; /// local stack. const PROBE_TIMEOUT: Duration = Duration::from_millis(250); -/// What to forward. +/// The loopback address local and reverse forwards use on this machine, and +/// host listeners use on the host unless a rule binds every interface. +const LOOPBACK: &str = "127.0.0.1"; + +/// The address a host forward listens on when it binds every interface. +const ALL_INTERFACES: &str = "0.0.0.0"; + +/// What a local forward forwards. #[derive(Clone, Debug)] pub struct ForwardSpec { /// Host as the remote host resolves it: an IP address, with or without @@ -60,40 +87,107 @@ pub struct ForwardSpec { pub allow_non_loopback_target: bool, } +/// A port on the remote host that reaches another server. +#[derive(Clone, Debug)] +pub struct HostForwardSpec { + /// Host port to listen on; `None` or `0` lets the host choose one. + pub listen_port: Option, + /// Listen on every interface of the host instead of its loopback + /// interface. The user confirms this each time a rule starts. + pub all_interfaces: bool, + /// Host as the remote host resolves it, as in [`ForwardSpec`]. + pub target_host: String, + /// TCP port on the target, 1 to 65535. + pub target_port: u16, + /// The user confirmed a target outside the remote host's loopback + /// interface (design S28). + pub allow_non_loopback_target: bool, +} + +/// A port on the remote host's loopback interface that reaches a port on +/// this machine's loopback interface. +#[derive(Clone, Debug)] +pub struct ReverseForwardSpec { + /// Host port to listen on; `None` or `0` lets the host choose one. + pub listen_port: Option, + /// Port on this machine's loopback interface, 1 to 65535. + pub local_port: u16, +} + +/// Where a forward listens and where its connections go. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ForwardKind { + /// A local port reaches a target through the host. + Local, + /// A host port reaches another server; the host connects to it. + Host, + /// A host loopback port reaches this machine's loopback interface. + Reverse, +} + /// 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. + /// Which kind of forward this is. + pub kind: ForwardKind, + /// This machine's side: the loopback address a local forward listens on, + /// or that a reverse forward connects to. Absent for host forwards. + #[serde(skip_serializing_if = "Option::is_none")] + pub local_host: Option, + /// The local port a local forward listens on, or that a reverse forward + /// connects to. Absent for host forwards. + #[serde(skip_serializing_if = "Option::is_none")] + pub local_port: Option, + /// Local port a local forward's 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 + /// The requested local port was taken, so the local 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. + /// The address a host or reverse forward listens on, on the host: + /// `127.0.0.1`, or `0.0.0.0` for every interface. Absent for local + /// forwards. + #[serde(skip_serializing_if = "Option::is_none")] + pub host_listen_host: Option, + /// The port a host or reverse forward listens on, on the host. + #[serde(skip_serializing_if = "Option::is_none")] + pub host_listen_port: Option, + /// Host port the request asked for, when it named one. + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_host_port: Option, + /// A host forward listens on every interface of the host. + pub all_interfaces: bool, + /// Target host of a local or host forward as sent to the remote host, + /// after mapping a wildcard address to the host's loopback address. + /// Absent for reverse forwards, whose target is `local_port`. + #[serde(skip_serializing_if = "Option::is_none")] + pub target_host: Option, + /// Target TCP port of a local or host forward. + #[serde(skip_serializing_if = "Option::is_none")] + pub target_port: Option, + /// The target is a loopback interface: the host's for local and host + /// forwards, this machine's for reverse forwards. pub loopback_target: bool, - /// Local connections the forward has accepted so far. + /// Connections the forward has accepted so far. pub connections: u64, + /// Accepted connections of a host or reverse forward that never reached + /// their target. Local forwards report 0. + pub failed_connections: u64, } -/// The malformed part of a forward's target. +/// The malformed part of a forward's request. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum TargetField { - /// [`ForwardSpec::target_host`]. + /// The target host. Host, - /// [`ForwardSpec::target_port`]. + /// The target port. Port, + /// [`ReverseForwardSpec::local_port`]. + LocalPort, } /// Why a forward did not start or the set cannot answer. @@ -110,6 +204,16 @@ pub enum ForwardError { SessionClosed, /// No local port could be opened, not even one the system chose. Listen(io::Error), + /// The remote server predates host listeners, so only local forwards + /// work on this connection. + HostListenerUnsupported, + /// Another program on the host uses the requested host port. + HostPortInUse, + /// The host does not let the server listen on the requested port, such + /// as a port below 1024 for a user without that privilege. + HostPortDenied, + /// The host refused to listen for another reason. + Remote(ClientError), } impl fmt::Display for ForwardError { @@ -121,6 +225,9 @@ impl fmt::Display for ForwardError { Self::InvalidTarget(TargetField::Port) => { formatter.write_str("invalid forward target port") } + Self::InvalidTarget(TargetField::LocalPort) => { + formatter.write_str("invalid reverse forward local port") + } Self::TargetNotConfirmed => formatter .write_str("the forward target is outside the remote host and was not confirmed"), Self::LimitReached => { @@ -128,12 +235,35 @@ impl fmt::Display for ForwardError { } Self::SessionClosed => formatter.write_str("the remote connection closed"), Self::Listen(error) => write!(formatter, "cannot listen on a local port: {error}"), + Self::HostListenerUnsupported => { + formatter.write_str("the remote server cannot listen on host ports") + } + Self::HostPortInUse => formatter.write_str("the host port is in use"), + Self::HostPortDenied => { + formatter.write_str("the host does not allow listening on that port") + } + Self::Remote(error) => write!(formatter, "the host cannot listen: {error}"), } } } impl std::error::Error for ForwardError {} +impl From for ForwardError { + fn from(error: ClientError) -> Self { + match error { + ClientError::Remote(remote) if remote.code == ErrorCode::AddressInUse => { + Self::HostPortInUse + } + ClientError::Remote(remote) if remote.code == ErrorCode::PermissionDenied => { + Self::HostPortDenied + } + ClientError::Disconnected { .. } => Self::SessionClosed, + error => Self::Remote(error), + } + } +} + /// The forwards of one session. pub struct ForwardSet { session: Arc, @@ -145,35 +275,169 @@ struct State { /// Set when the session ended or the set closed; nothing starts after it. closed: bool, next_id: u64, + /// Host-side forwards being started without the lock, counted against + /// [`MAX_FORWARDS`]. + starting: usize, forwards: BTreeMap, } -struct Entry { - forward: PortForward, - requested_local_port: Option, - local_port_changed: bool, - target_host: String, - target_port: u16, - loopback_target: bool, +enum Entry { + Local { + forward: PortForward, + requested_local_port: Option, + local_port_changed: bool, + target: TargetHost, + target_port: u16, + }, + Host { + forward: HostForward, + requested_port: Option, + all_interfaces: bool, + target: TargetHost, + target_port: u16, + }, + Reverse { + forward: ReverseForward, + requested_port: Option, + local_port: u16, + }, } impl Entry { fn info(&self, id: u64) -> ForwardInfo { - let local = self.forward.local_address(); - ForwardInfo { + let empty = 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(), + kind: ForwardKind::Local, + local_host: None, + local_port: None, + requested_local_port: None, + local_port_changed: false, + host_listen_host: None, + host_listen_port: None, + requested_host_port: None, + all_interfaces: false, + target_host: None, + target_port: None, + loopback_target: false, + connections: 0, + failed_connections: 0, + }; + match self { + Self::Local { + forward, + requested_local_port, + local_port_changed, + target, + target_port, + } => { + let local = forward.local_address(); + ForwardInfo { + local_host: Some(local.ip().to_string()), + local_port: Some(local.port()), + requested_local_port: *requested_local_port, + local_port_changed: *local_port_changed, + target_host: Some(target.host.clone()), + target_port: Some(*target_port), + loopback_target: target.loopback, + connections: forward.connections(), + ..empty + } + } + Self::Host { + forward, + requested_port, + all_interfaces, + target, + target_port, + } => ForwardInfo { + kind: ForwardKind::Host, + host_listen_host: Some(listen_host(*all_interfaces).into()), + host_listen_port: Some(forward.port()), + requested_host_port: *requested_port, + all_interfaces: *all_interfaces, + target_host: Some(target.host.clone()), + target_port: Some(*target_port), + loopback_target: target.loopback, + ..empty + }, + Self::Reverse { + forward, + requested_port, + local_port, + } => ForwardInfo { + kind: ForwardKind::Reverse, + local_host: Some(LOOPBACK.into()), + local_port: Some(*local_port), + host_listen_host: Some(LOOPBACK.into()), + host_listen_port: Some(forward.port()), + requested_host_port: *requested_port, + loopback_target: true, + failed_connections: forward.local_failures(), + ..empty + }, + } + } + + /// The host listener behind a host or reverse forward. + fn listener_id(&self) -> Option { + match self { + Self::Local { .. } => None, + Self::Host { forward, .. } => Some(forward.listener_id()), + Self::Reverse { forward, .. } => Some(forward.listener_id()), + } + } + + /// Whether this forward already serves a request for the same rule. A + /// request that lets the system choose a port matches any port. + fn serves(&self, other: &Entry) -> bool { + let same_port = |requested: &Option, port: u16| requested.is_none_or(|r| r == port); + match (self, other) { + ( + Self::Host { + forward, + all_interfaces, + target, + target_port, + .. + }, + Self::Host { + requested_port, + all_interfaces: other_all, + target: other_target, + target_port: other_port, + .. + }, + ) => { + all_interfaces == other_all + && target.host == other_target.host + && target_port == other_port + && same_port(requested_port, forward.port()) + } + ( + Self::Reverse { + forward, + local_port, + .. + }, + Self::Reverse { + requested_port, + local_port: other_local, + .. + }, + ) => local_port == other_local && same_port(requested_port, forward.port()), + _ => false, } } } +fn listen_host(all_interfaces: bool) -> &'static str { + if all_interfaces { + ALL_INTERFACES + } else { + LOOPBACK + } +} + impl ForwardSet { /// An empty set whose forwards end together with `session`. pub fn new(session: Arc) -> Self { @@ -185,29 +449,29 @@ impl ForwardSet { Self { session, state } } - /// Starts forwarding, or returns the forward that already reaches the - /// same target. The flag is `true` for a new forward. + /// Starts a local forward, 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 target = confirmed_target( + &spec.target_host, + spec.target_port, + spec.allow_non_loopback_target, + )?; 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. + // cannot both open a local port. Opening a local port never waits + // for the session. 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 + matches!(entry, Entry::Local { target: running, target_port, .. } + if running.host == target.host && *target_port == spec.target_port) }) { return Ok((entry.info(*id), false)); } - if state.forwards.len() >= MAX_FORWARDS { + if state.forwards.len() + state.starting >= MAX_FORWARDS { return Err(ForwardError::LimitReached); } let tunnel = TunnelTarget::Tcp { @@ -219,39 +483,147 @@ impl ForwardSet { requested.is_some_and(|port| port != forward.local_address().port()); state.next_id += 1; let id = state.next_id; - let entry = Entry { + let entry = Entry::Local { forward, requested_local_port: requested, local_port_changed, - target_host: target.host, + target, 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. + /// Starts a host forward, or returns the one that already serves the + /// same rule. The flag is `true` for a new forward. + pub fn start_host(&self, spec: HostForwardSpec) -> Result<(ForwardInfo, bool), ForwardError> { + let target = confirmed_target( + &spec.target_host, + spec.target_port, + spec.allow_non_loopback_target, + )?; + let requested = spec.listen_port.filter(|port| *port != 0); + let reservation = self.reserve()?; + let forward = HostForward::start( + Arc::clone(&self.session), + requested.unwrap_or(0), + spec.all_interfaces, + &target.host, + spec.target_port, + )?; + reservation.commit(Entry::Host { + forward, + requested_port: requested, + all_interfaces: spec.all_interfaces, + target, + target_port: spec.target_port, + }) + } + + /// Starts a reverse forward, or returns the one that already serves the + /// same rule. The flag is `true` for a new forward. The application + /// offers reverse forwards only when the user allowed them. + pub fn start_reverse( + &self, + spec: ReverseForwardSpec, + ) -> Result<(ForwardInfo, bool), ForwardError> { + if spec.local_port == 0 { + return Err(ForwardError::InvalidTarget(TargetField::LocalPort)); + } + let requested = spec.listen_port.filter(|port| *port != 0); + let reservation = self.reserve()?; + let forward = ReverseForward::start( + Arc::clone(&self.session), + requested.unwrap_or(0), + spec.local_port, + )?; + reservation.commit(Entry::Reverse { + forward, + requested_port: requested, + local_port: spec.local_port, + }) + } + + /// Takes a place for a host-side forward. The lock is not held while + /// the host answers: the session's close hook takes it from the thread + /// that delivers the answer. + fn reserve(&self) -> Result, ForwardError> { + if !self + .session + .hello() + .host + .features + .contains(&Feature::Listener) + { + return Err(ForwardError::HostListenerUnsupported); + } + let mut state = lock(&self.state); + if state.closed || self.session.is_closed() { + return Err(ForwardError::SessionClosed); + } + if state.forwards.len() + state.starting >= MAX_FORWARDS { + return Err(ForwardError::LimitReached); + } + state.starting += 1; + Ok(Reservation { set: self }) + } + + /// Stops one forward and closes its port. Connections a local or reverse + /// forward already accepted run until either side closes them; a host + /// forward closes its relayed connections. 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. + // Dropped outside the lock: stopping waits for the acceptor thread + // or the host. removed.is_some() } - /// The running forwards, by identifier. + /// The running forwards, by identifier, with the host's current counts + /// for host and reverse forwards. pub fn list(&self) -> Result, ForwardError> { - let state = lock(&self.state); - if state.closed || self.session.is_closed() { - return Err(ForwardError::SessionClosed); + let (mut forwards, listeners) = { + let state = lock(&self.state); + if state.closed || self.session.is_closed() { + return Err(ForwardError::SessionClosed); + } + let forwards: Vec = state + .forwards + .iter() + .map(|(id, entry)| entry.info(*id)) + .collect(); + let listeners: Vec<(usize, u64)> = state + .forwards + .values() + .enumerate() + .filter_map(|(index, entry)| entry.listener_id().map(|id| (index, id))) + .collect(); + (forwards, listeners) + }; + if listeners.is_empty() { + return Ok(forwards); } - Ok(state - .forwards - .iter() - .map(|(id, entry)| entry.info(*id)) - .collect()) + // Asked outside the lock, for the same reason as in `reserve`. + let counts: HashMap = self + .session + .listeners()? + .into_iter() + .map(|state| { + ( + state.listener_id, + (state.connections, state.failed_connections), + ) + }) + .collect(); + for (index, listener_id) in listeners { + if let Some((connections, failed)) = counts.get(&listener_id) { + let info = &mut forwards[index]; + info.connections = *connections; + info.failed_connections += failed; + } + } + Ok(forwards) } /// Stops every forward and refuses new ones, before the session closes. @@ -267,6 +639,63 @@ impl Drop for ForwardSet { } } +/// A place taken for a host-side forward that is starting. +struct Reservation<'a> { + set: &'a ForwardSet, +} + +impl Reservation<'_> { + /// Adds the started forward, or returns the forward that served the same + /// rule meanwhile; the new one then closes again. A set that closed + /// meanwhile closes it too. + fn commit(self, entry: Entry) -> Result<(ForwardInfo, bool), ForwardError> { + let mut state = lock(&self.set.state); + if state.closed { + drop(state); + drop(entry); + return Err(ForwardError::SessionClosed); + } + if let Some((id, running)) = state + .forwards + .iter() + .find(|(_, running)| running.serves(&entry)) + { + let info = running.info(*id); + drop(state); + drop(entry); + return Ok((info, false)); + } + state.next_id += 1; + let id = state.next_id; + let info = entry.info(id); + state.forwards.insert(id, entry); + Ok((info, true)) + } +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + lock(&self.set.state).starting -= 1; + } +} + +/// Validates a target host and port, and requires the confirmation for a +/// target outside the host's loopback interface. +fn confirmed_target( + host: &str, + port: u16, + allow_non_loopback_target: bool, +) -> Result { + let target = TargetHost::parse(host)?; + if port == 0 { + return Err(ForwardError::InvalidTarget(TargetField::Port)); + } + if !target.loopback && !allow_non_loopback_target { + return Err(ForwardError::TargetNotConfirmed); + } + Ok(target) +} + /// Marks the set closed and takes its forwards, which the caller drops /// outside the lock. fn take_all(state: &Mutex) -> BTreeMap { diff --git a/rust/crates/remote/src/client/host_forward.rs b/rust/crates/remote/src/client/host_forward.rs new file mode 100644 index 00000000..a488dd1d --- /dev/null +++ b/rust/crates/remote/src/client/host_forward.rs @@ -0,0 +1,382 @@ +//! Forwards that listen on the remote host. +//! +//! - A [`HostForward`] makes the host listen on a port and connect every +//! accepted connection to another server itself, as `ssh -L` does on a jump +//! host. The bytes never cross the session. +//! - A [`ReverseForward`] makes the host listen on its loopback interface and +//! hands every accepted connection to this machine, which connects it to a +//! port on its own loopback interface, as `ssh -R 127.0.0.1:…` does. +//! +//! Both are listeners of the session: the host closes them when this client +//! disconnects, and they are not reopened after a reconnect. A reverse forward +//! only ever reaches this machine's loopback interface, so a remote user +//! cannot use it to reach the local network. +//! +//! Starting and removing a forward are recorded in the session's +//! [`ConnectionLog`] with the ports and whether each side is a loopback +//! address; hosts are not recorded. + +use crate::client::connection_log::ConnectionLog; +use crate::client::forward::{forward_failed, pump, Slot, Slots, BRIDGE_LOG}; +use crate::client::session::{ClientError, Event, RemoteSession}; +use crate::protocol::methods::{self, ListenerAcceptedEvent, TunnelTarget}; +use std::io; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::Receiver; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +/// Most connections one reverse forward bridges at once. +const MAX_CONNECTIONS: usize = 64; + +/// How long a reverse connection waits for the local port to accept. +const LOCAL_CONNECT_TIMEOUT: Duration = Duration::from_secs(2); + +/// The address a host forward listens on: loopback unless the user confirmed +/// every interface for this rule. +fn listen_host(all_interfaces: bool) -> &'static str { + if all_interfaces { + "0.0.0.0" + } else { + "127.0.0.1" + } +} + +/// A host port that relays to another server. Dropping it closes the port; +/// connections already relayed are closed with it. +pub struct HostForward { + session: Arc, + listener_id: u64, + port: u16, + started: Instant, + log: ConnectionLog, +} + +impl HostForward { + /// Makes the host listen on `port`, 0 for a port the host chooses, and + /// connect every accepted connection to `target_host:target_port`. The + /// host listens on its loopback interface unless `all_interfaces` is set. + pub fn start( + session: Arc, + port: u16, + all_interfaces: bool, + target_host: &str, + target_port: u16, + ) -> Result { + let listener_id = session.allocate_id(); + let target = TunnelTarget::Tcp { + host: target_host.into(), + port: target_port, + }; + let port = + session.open_listener(listener_id, listen_host(all_interfaces), port, Some(target))?; + let log = session.connection_log().clone(); + log.host_forward_started(port, all_interfaces, target_host, target_port); + Ok(Self { + session, + listener_id, + port, + started: Instant::now(), + log, + }) + } + + /// The port the host listens on, with the port it chose for port 0. + pub fn port(&self) -> u16 { + self.port + } + + /// The listener's id in [`RemoteSession::listeners`]. + pub fn listener_id(&self) -> u64 { + self.listener_id + } +} + +impl Drop for HostForward { + fn drop(&mut self) { + let (connections, failed) = close(&self.session, self.listener_id); + self.log + .host_forward_removed(self.port, connections, failed, self.started.elapsed()); + } +} + +/// A host loopback port whose connections reach a port on this machine's +/// loopback interface. Dropping it closes the host port; connections already +/// bridged run until either side closes. +pub struct ReverseForward { + session: Arc, + listener_id: u64, + port: u16, + stopping: Arc, + handler: Option>, + /// Connections the host handed over that could not reach the local port. + failed: Arc, + started: Instant, + log: ConnectionLog, +} + +impl ReverseForward { + /// Makes the host listen on its loopback `port`, 0 for a port the host + /// chooses, and connects every accepted connection to `local_port` on + /// this machine's loopback interface. + pub fn start( + session: Arc, + port: u16, + local_port: u16, + ) -> Result { + let listener_id = session.allocate_id(); + let events = session.subscribe("listener", listener_id); + let port = match session.open_listener(listener_id, "127.0.0.1", port, None) { + Ok(port) => port, + Err(error) => { + session.unsubscribe("listener", listener_id); + return Err(error); + } + }; + let log = session.connection_log().clone(); + let stopping = Arc::new(AtomicBool::new(false)); + let failed = Arc::new(AtomicU64::new(0)); + let handler = Handler { + session: Arc::clone(&session), + listener_id, + local_port, + events, + stopping: Arc::clone(&stopping), + failed: Arc::clone(&failed), + slots: Arc::new(Slots::new(MAX_CONNECTIONS)), + log: log.clone(), + }; + let handler = match thread::Builder::new() + .name("remote-reverse-forward".into()) + .spawn(move || handler.run()) + { + Ok(handler) => handler, + Err(error) => { + close(&session, listener_id); + session.unsubscribe("listener", listener_id); + return Err(ClientError::Spawn(error)); + } + }; + log.reverse_forward_started(port, local_port); + Ok(Self { + session, + listener_id, + port, + stopping, + handler: Some(handler), + failed, + started: Instant::now(), + log, + }) + } + + /// The loopback port the host listens on, with the port it chose for port 0. + pub fn port(&self) -> u16 { + self.port + } + + /// The listener's id in [`RemoteSession::listeners`]. + pub fn listener_id(&self) -> u64 { + self.listener_id + } + + /// Connections the host handed over that could not reach the local port. + pub fn local_failures(&self) -> u64 { + self.failed.load(Ordering::Relaxed) + } +} + +impl Drop for ReverseForward { + fn drop(&mut self) { + self.stopping.store(true, Ordering::Release); + let (connections, failed) = close(&self.session, self.listener_id); + // Ending the subscription disconnects the handler's channel, so the + // handler returns even when no event arrives. + self.session.unsubscribe("listener", self.listener_id); + if let Some(handler) = self.handler.take() { + crate::failure_log::outcome( + "remote.client.operation_failed", + "reverse_forward_join", + handler.join(), + "panic", + "thread", + ); + } + self.log.host_forward_removed( + self.port, + connections, + failed + self.failed.load(Ordering::Relaxed), + self.started.elapsed(), + ); + } +} + +/// Closes a listener and returns its final connection and failure counts. A +/// session that already ended closed it on the host, and its counts are gone. +fn close(session: &RemoteSession, listener_id: u64) -> (u64, u64) { + if session.is_closed() { + return (0, 0); + } + match session.close_listener(listener_id) { + Ok(state) => (state.connections, state.failed_connections), + Err(error) => { + crate::failure_log::client::<()>("listener_close", Err(error)); + (0, 0) + } + } +} + +/// The thread that takes a reverse forward's accepted connections. +struct Handler { + session: Arc, + listener_id: u64, + local_port: u16, + events: Receiver, + stopping: Arc, + failed: Arc, + slots: Arc, + log: ConnectionLog, +} + +impl Handler { + fn run(self) { + // The channel disconnects when the forward is removed or the session + // ends. + while let Ok(event) = self.events.recv() { + if self.stopping.load(Ordering::Acquire) { + return; + } + if event.event != methods::EVENT_LISTENER_ACCEPTED { + continue; + } + let accepted = match serde_json::from_value::(event.params) { + Ok(accepted) => accepted, + Err(_) => { + forward_failed( + "remote.forward.connection_failed", + &self.log, + "accepted_event", + "invalid", + "protocol", + &BRIDGE_LOG, + ); + continue; + } + }; + // A connection that waits here past the host's adoption timeout + // is closed by the host and counted there. + let Some(slot) = self.slots.acquire(&self.stopping) else { + return; + }; + self.bridge(accepted.accept_id, slot); + } + if !self.stopping.load(Ordering::Acquire) && !self.session.is_closed() { + // The subscription was dropped because its queue overflowed: no + // later connection would be adopted, so the port closes now. + close(&self.session, self.listener_id); + } + } + + fn bridge(&self, accept_id: u64, slot: Slot) { + let session = Arc::clone(&self.session); + let listener_id = self.listener_id; + let local_port = self.local_port; + let failed = Arc::clone(&self.failed); + let log = self.log.clone(); + let spawned = thread::Builder::new() + .name("remote-reverse-connection".into()) + .spawn(move || { + let _slot = slot; + let result = reverse_bridge(&session, listener_id, accept_id, local_port, &failed); + if let Err(failure) = result { + failure.record(&log); + } + }); + if let Err(error) = spawned { + // The host closes the connection when it is not adopted in time. + forward_failed( + "remote.forward.connection_failed", + &self.log, + "spawn", + &format!("{:?}", error.kind()), + "io", + &BRIDGE_LOG, + ); + } + } +} + +/// Why a reverse connection ended early. +enum ReverseFailure { + Remote(ClientError), + Local(io::ErrorKind), +} + +impl ReverseFailure { + fn record(&self, log: &ConnectionLog) { + match self { + Self::Remote(error) => { + if let Some(category) = crate::failure_log::bridge_category(error) { + forward_failed( + "remote.forward.connection_failed", + log, + "adopt", + &category, + "remote", + &BRIDGE_LOG, + ); + } + } + Self::Local(kind) => forward_failed( + "remote.forward.connection_failed", + log, + "local_connect", + &format!("{kind:?}"), + "io", + &BRIDGE_LOG, + ), + } + } +} + +fn reverse_bridge( + session: &RemoteSession, + listener_id: u64, + accept_id: u64, + local_port: u16, + failed: &AtomicU64, +) -> Result<(), ReverseFailure> { + // The host counts connections it could not hand over. + let tunnel = session + .adopt_tunnel(listener_id, accept_id) + .map_err(ReverseFailure::Remote)?; + let local = match connect_loopback(local_port) { + Ok(local) => local, + Err(error) => { + failed.fetch_add(1, Ordering::Relaxed); + crate::failure_log::client("tunnel_close", tunnel.close()); + return Err(ReverseFailure::Local(error.kind())); + } + }; + crate::failure_log::teardown( + "remote.client.operation_failed", + "nodelay", + local.set_nodelay(true), + ); + pump(session, local, tunnel).map_err(ReverseFailure::Remote) +} + +/// Connects to `port` on this machine's loopback interface, IPv4 first. +fn connect_loopback(port: u16) -> io::Result { + let v4 = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + match TcpStream::connect_timeout(&v4, LOCAL_CONNECT_TIMEOUT) { + Ok(stream) => Ok(stream), + Err(first) => { + let v6 = SocketAddr::from((Ipv6Addr::LOCALHOST, port)); + // log-exempt: Same failure already recorded: the IPv4 error is returned and recorded by the caller when IPv6 fails too. + TcpStream::connect_timeout(&v6, LOCAL_CONNECT_TIMEOUT).map_err(|_| first) + } + } +} diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index e2a5157a..3ddb5b03 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -15,6 +15,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. +//! - [`host_forward`] makes the host listen: relaying to another server, or +//! back to this machine's loopback interface. //! - [`forward_address`] reads the addresses typed into the ports page: //! ports, `host:port` and URLs. //! - [`forward_set`] keeps the forwards of one session for the ports page, @@ -46,6 +48,7 @@ pub mod connections; pub mod forward; pub mod forward_address; pub mod forward_set; +pub mod host_forward; pub mod launch; #[cfg(feature = "motty")] pub mod motty; @@ -62,7 +65,11 @@ pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; pub use connection_log::{ConnectionKind, ConnectionLog}; pub use forward::PortForward; pub use forward_address::{AddressError, ForwardAddress}; -pub use forward_set::{ForwardError, ForwardInfo, ForwardSet, ForwardSpec, TargetField}; +pub use forward_set::{ + ForwardError, ForwardInfo, ForwardKind, ForwardSet, ForwardSpec, HostForwardSpec, + ReverseForwardSpec, TargetField, +}; +pub use host_forward::{HostForward, ReverseForward}; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; pub use transport::{ ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError, WslHop, diff --git a/rust/crates/remote/src/client/preferences.rs b/rust/crates/remote/src/client/preferences.rs index e8540268..e387158d 100644 --- a/rust/crates/remote/src/client/preferences.rs +++ b/rust/crates/remote/src/client/preferences.rs @@ -13,6 +13,11 @@ //! - `reconnectLimitSeconds` bounds how long a client keeps reconnecting a //! lost session automatically. [`reconnect_delays`] turns it into the //! pauses between attempts, so every client waits the same way. +//! - `allowReverseForwarding` lets the ports page start reverse forwards: a +//! port on the host's loopback interface that reaches a port on this +//! machine's loopback interface. [`Preferences::reverse_forwarding`] is off +//! unless the user turned it on, because every user of the host can then +//! reach that local port. //! - The document lives at [`STORAGE_PATH`] below the platform's //! user-preference directory, never on a host or in a workspace. It holds //! no secret. This module validates and edits it; the platform adapter @@ -50,6 +55,9 @@ const MAX_PAUSE_MILLISECONDS: u64 = 30_000; /// Program name OpenSSH installs on `PATH`. const SSH_NAME: &str = "ssh"; +/// Whether reverse forwards are offered when the document sets nothing. +pub const DEFAULT_ALLOW_REVERSE_FORWARDING: bool = false; + /// Why a document or an edit was refused. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -107,6 +115,9 @@ pub struct Preferences { /// `None` uses [`DEFAULT_RECONNECT_LIMIT_SECONDS`]. #[serde(default, skip_serializing_if = "Option::is_none")] reconnect_limit_seconds: Option, + /// `None` uses [`DEFAULT_ALLOW_REVERSE_FORWARDING`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + allow_reverse_forwarding: Option, } impl Default for Preferences { @@ -115,6 +126,7 @@ impl Default for Preferences { version: 1, ssh_program: None, reconnect_limit_seconds: None, + allow_reverse_forwarding: None, } } } @@ -160,6 +172,15 @@ impl SshProgram { } } +/// Whether the ports page offers reverse forwards. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReverseForwarding { + pub source: Source, + /// The value that takes effect. + pub allowed: bool, +} + /// How long a lost session is reconnected automatically. #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -245,6 +266,30 @@ impl Preferences { Ok(()) } + /// The stored reverse-forwarding switch, `None` when automatic. + pub fn allow_reverse_forwarding(&self) -> Option { + self.allow_reverse_forwarding + } + + /// Turns reverse forwards on or off, or makes the switch automatic with + /// `None`. + pub fn set_allow_reverse_forwarding(&mut self, allowed: Option) { + self.allow_reverse_forwarding = allowed; + } + + /// Whether reverse forwards are offered, and whether the user decided. + pub fn reverse_forwarding(&self) -> ReverseForwarding { + ReverseForwarding { + source: match self.allow_reverse_forwarding { + Some(_) => Source::Setting, + None => Source::Automatic, + }, + allowed: self + .allow_reverse_forwarding + .unwrap_or(DEFAULT_ALLOW_REVERSE_FORWARDING), + } + } + /// Sets the reconnect limit, or makes it automatic with `None`. pub fn set_reconnect_limit(&mut self, seconds: Option) -> Result<(), PreferenceError> { if let Some(seconds) = seconds { diff --git a/rust/crates/remote/src/client/preferences/tests.rs b/rust/crates/remote/src/client/preferences/tests.rs index 6b0eec40..3806ff35 100644 --- a/rust/crates/remote/src/client/preferences/tests.rs +++ b/rust/crates/remote/src/client/preferences/tests.rs @@ -60,6 +60,31 @@ fn a_missing_document_is_every_value_automatic() { vec![1_000, 2_000, 4_000, 8_000, 16_000, 29_000] ); assert_eq!(preferences.text().unwrap(), "{\n \"version\": 1\n}\n"); + let reverse = preferences.reverse_forwarding(); + assert_eq!( + (reverse.source, reverse.allowed), + (Source::Automatic, false) + ); +} + +#[test] +fn reverse_forwarding_is_off_until_the_user_turns_it_on() { + let mut preferences = Preferences::default(); + preferences.set_allow_reverse_forwarding(Some(true)); + let read = Preferences::parse(Some(&preferences.text().unwrap())).unwrap(); + assert_eq!(read.allow_reverse_forwarding(), Some(true)); + let reverse = read.reverse_forwarding(); + assert_eq!((reverse.source, reverse.allowed), (Source::Setting, true)); + + preferences.set_allow_reverse_forwarding(Some(false)); + let reverse = preferences.reverse_forwarding(); + assert_eq!((reverse.source, reverse.allowed), (Source::Setting, false)); + preferences.set_allow_reverse_forwarding(None); + assert_eq!(preferences, Preferences::default()); + assert_eq!( + refusal("{\"version\":1,\"allowReverseForwarding\":\"yes\"}").field, + "document" + ); } #[test] diff --git a/rust/crates/remote/src/failure_log.rs b/rust/crates/remote/src/failure_log.rs index 961a2949..cd96e74f 100644 --- a/rust/crates/remote/src/failure_log.rs +++ b/rust/crates/remote/src/failure_log.rs @@ -30,6 +30,8 @@ pub const LIFECYCLE_EVENTS: &[&str] = &[ "remote.connection.cleaned", "remote.forward.started", "remote.forward.removed", + "remote.forward.host_started", + "remote.forward.host_removed", ]; /// Borrowed scalar fields; callers supply only fixed summaries and stable categories. diff --git a/rust/crates/remote/src/protocol/message.rs b/rust/crates/remote/src/protocol/message.rs index 934c709f..acfe65dc 100644 --- a/rust/crates/remote/src/protocol/message.rs +++ b/rust/crates/remote/src/protocol/message.rs @@ -112,6 +112,8 @@ pub enum ErrorCode { SpawnFailed, /// A tunnel could not connect to its remote target. ConnectFailed, + /// A listener could not bind its port because another socket holds it. + AddressInUse, /// 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 diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 0fdc9a6b..8a17a88b 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -165,6 +165,19 @@ pub const TUNNEL_CLOSE: &str = "tunnel.close"; /// Lists the TCP ports listening on the host as a [`ListeningPortsResult`]. pub const PORTS_LISTENING: &str = "ports.listening"; +/// Listens on a host TCP port for a forwarding rule the user added, see +/// [`ListenerOpenParams`]; fails with `ADDRESS_IN_USE` when the port is taken. +pub const LISTENER_OPEN: &str = "listener.open"; +/// Stops a listener and closes the connections it relays or still holds; +/// returns its final [`ListenerState`]. +pub const LISTENER_CLOSE: &str = "listener.close"; +/// Hands a connection a reverse listener accepted to a new tunnel, see +/// [`ListenerAdoptParams`]. +pub const LISTENER_ADOPT: &str = "listener.adopt"; +/// The session's listeners and their connection counts, as a +/// [`ListenersResult`]. +pub const LISTENER_LIST: &str = "listener.list"; + /// Output of a spawned process, carried by [`ProcessOutputEvent`]. pub const EVENT_PROCESS_OUTPUT: &str = "process.output"; /// End of a spawned process, carried by [`ProcessExitEvent`]. @@ -185,6 +198,9 @@ pub const EVENT_WALK_DONE: &str = "walk.done"; pub const EVENT_TUNNEL_DATA: &str = "tunnel.data"; /// End of a tunnel, carried by [`TunnelClosedEvent`]. pub const EVENT_TUNNEL_CLOSED: &str = "tunnel.closed"; +/// A reverse listener accepted a connection, carried by +/// [`ListenerAcceptedEvent`]. +pub const EVENT_LISTENER_ACCEPTED: &str = "listener.accepted"; /// Largest byte count one `fs.readFile` or `fs.writeFile` call may move. /// Base64 inflates it by a third, which keeps the frame under @@ -455,6 +471,9 @@ pub enum Feature { Environment, /// `tunnel.*` and `ports.listening`. Tunnel, + /// `listener.*` methods and events: host ports for host-side and + /// reverse forwarding rules. + Listener, /// The session survives disconnection when started with `--connect`. Persistence, } @@ -1299,6 +1318,95 @@ pub struct ListeningPortsResult { pub ports: Vec, } +// --------------------------------------------------------------------------- +// Listeners +// --------------------------------------------------------------------------- + +/// Parameters of `listener.open`. +/// +/// With `relay`, the host connects every accepted connection to that target +/// itself: a host-side rule, such as a host port that reaches a database on +/// another server. Without it, every accepted connection waits for the +/// client to adopt it as a tunnel (`listener.accepted`, `listener.adopt`): a +/// reverse rule, which reaches a port on the user's machine. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerOpenParams { + /// Client-chosen id that the listener's events carry. + pub listener_id: u64, + /// IP address to bind: a loopback address, or with `relay` also `0.0.0.0` + /// or `::` for every interface. Names are refused. + pub host: String, + /// TCP port to bind; `0` lets the host choose one. + pub port: u16, + /// Where the host connects accepted connections; absent for a reverse + /// listener. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub relay: Option, +} + +/// Result of `listener.open`. +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerOpened { + /// Bound port, with the one the host chose for port 0. + pub port: u16, +} + +/// Parameters of `listener.close`. +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerParams { + /// Id the listener was opened with. + pub listener_id: u64, +} + +/// Parameters of `listener.adopt`. +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerAdoptParams { + /// Id the listener was opened with. + pub listener_id: u64, + /// `acceptId` of the `listener.accepted` event. + pub accept_id: u64, + /// Client-chosen id of the tunnel the connection becomes; the client + /// subscribes to it first, as for `tunnel.open`. + pub tunnel_id: u64, +} + +/// Parameters of the `listener.accepted` event. +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerAcceptedEvent { + /// Id the listener was opened with. + pub listener_id: u64, + /// Identifies the waiting connection for `listener.adopt`. + pub accept_id: u64, +} + +/// One listener in `listener.list`. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenerState { + /// Id the listener was opened with. + pub listener_id: u64, + /// Bound port. + pub port: u16, + /// Connections accepted so far. + pub connections: u64, + /// Accepted connections that never reached their target: the relay + /// target refused, or the host had no thread or tunnel left for them. + pub failed_connections: u64, +} + +/// Result of `listener.list`. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ListenersResult { + /// By id. + pub listeners: Vec, +} + /// Output of `lithe-remote-server --identity`, used by the bootstrapper to /// decide whether an installed binary can be reused. #[derive(Clone, Debug, Deserialize, Serialize)] diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index c54a6a21..4408723d 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -284,6 +284,9 @@ fn handle(context: &Context, method: &str, params: Value) -> Result session.tunnels.handle(context, method, params), + method if method.starts_with("listener.") => { + session.listeners.handle(context, method, params) + } methods::ENVIRONMENT_RESOLVE => environment::handle(session, params), methods::PORTS_LISTENING => ports::handle(session), _ => Err(RemoteError::new( @@ -399,6 +402,8 @@ impl ResourceOrder { methods::TERMINAL_CLOSE => ("terminal", "terminalId", false), methods::WATCH_START => ("watch", "watchId", true), methods::WATCH_STOP => ("watch", "watchId", false), + methods::LISTENER_OPEN => ("listener", "listenerId", true), + methods::LISTENER_CLOSE => ("listener", "listenerId", false), _ => return Ok(Self::Independent), }; let Some(id) = params.get(field).and_then(Value::as_u64) else { @@ -412,6 +417,9 @@ impl ResourceOrder { "terminal" => { parse::(params.clone())?; } + "listener" => { + parse::(params.clone())?; + } _ => { parse::(params.clone())?; } @@ -423,6 +431,7 @@ impl ResourceOrder { close_method: match family { "terminal" => methods::TERMINAL_CLOSE, "watch" => methods::WATCH_STOP, + "listener" => methods::LISTENER_CLOSE, _ => methods::PROCESS_KILL, }, close_params: if family == "process" { diff --git a/rust/crates/remote/src/server/listener.rs b/rust/crates/remote/src/server/listener.rs new file mode 100644 index 00000000..c0b213de --- /dev/null +++ b/rust/crates/remote/src/server/listener.rs @@ -0,0 +1,617 @@ +//! Host ports that accept connections for forwarding rules the user added. +//! +//! A host rule (`relay`) connects every accepted connection to another +//! endpoint as the host sees it, such as a database on a second server, and +//! copies the bytes on the host; nothing crosses the protocol stream. A +//! reverse rule hands every accepted connection to the client as a +//! `listener.accepted` event, and the client adopts it as a tunnel that it +//! connects to a port on the user's machine. A listener belongs to the client +//! connection that opened it and closes with it; clients do not reopen one on +//! their own, so a host port is open only while the user's rule is. + +use crate::protocol::methods::{ + self, ListenerAcceptedEvent, ListenerAdoptParams, ListenerOpenParams, ListenerOpened, + ListenerParams, ListenerState, ListenersResult, TunnelTarget, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use crate::server::connection::Context; +use crate::server::resources::Registry; +use crate::server::session::Session; +use crate::server::threads::unavailable; +use crate::server::tunnel::{self, Stream}; +use crate::server::{lock, parse}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::io::{self, Read, Write}; +use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::os::fd::AsRawFd; +use std::os::unix::net::UnixStream; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +/// Listeners one session keeps open: one per rule. Clients cap their rules +/// at the same number. +const MAX_LISTENERS: usize = 64; +/// Relayed connections of one listener at once. Further connections wait in +/// the kernel's backlog until one ends. +const MAX_RELAYS_PER_LISTENER: usize = 64; +/// Relayed connections of all of a session's listeners at once. Each holds +/// two sockets and two threads; connections over the limit are closed and +/// counted as failed. +const MAX_RELAYS: usize = 256; +/// Accepted connections of one reverse listener waiting for the client. +/// Further connections wait in the kernel's backlog. +const MAX_PENDING: usize = 16; +/// How long an accepted connection waits for `listener.adopt`. A client that +/// missed the event or cannot serve it must not hold the slot. +const ADOPT_TIMEOUT: Duration = Duration::from_secs(10); +/// Pause after a failed `accept`, such as when the process is out of file +/// descriptors, so the loop does not spin while the condition lasts. +const ACCEPT_RETRY: Duration = Duration::from_millis(200); +/// How long `listener.close` waits for the port to be released, so that a +/// rule edited to the same port can bind it again at once. +const CLOSE_WAIT: Duration = Duration::from_secs(1); + +pub(crate) struct ListenerTable { + registry: Registry, + /// Relayed connections of all listeners, against [`MAX_RELAYS`]. + relays: Arc, +} + +struct OpenListener { + connection: u64, + port: u16, + shared: Arc, + /// Disconnects when the accept loop has ended and released the port. + ended: Receiver<()>, +} + +impl OpenListener { + fn state(&self, listener_id: u64) -> ListenerState { + ListenerState { + listener_id, + port: self.port, + connections: self.shared.connections.load(Ordering::Relaxed), + failed_connections: self.shared.failed.load(Ordering::Relaxed), + } + } +} + +/// What the accept loop, relays and requests share about one listener. +struct Shared { + state: Mutex, + /// Write side of the accept loop's wake-up socket. A byte means the + /// state changed; it is non-blocking, and a full buffer already holds a + /// wake-up. + waker: UnixStream, + connections: AtomicU64, + failed: AtomicU64, +} + +#[derive(Default)] +struct State { + stopping: bool, + next_accept: u64, + /// The sockets of every relayed connection, shut down on close. + relays: BTreeMap>, + /// Accepted connections waiting for `listener.adopt`, with the moment + /// they are given up. + pending: BTreeMap, +} + +impl Shared { + fn wake(&self) { + let _ = (&self.waker).write(&[1]); + } + + /// Ends the accept loop and every connection the listener still holds. + fn stop(&self) { + let mut state = lock(&self.state); + state.stopping = true; + for streams in std::mem::take(&mut state.relays).into_values() { + for stream in streams { + stream.shutdown(Shutdown::Both); + } + } + state.pending.clear(); + drop(state); + self.wake(); + } +} + +impl ListenerTable { + pub(crate) fn new() -> Self { + Self { + registry: Registry::bounded("listener", MAX_LISTENERS), + relays: Arc::new(AtomicUsize::new(0)), + } + } + + pub(crate) fn handle( + &self, + context: &Context, + method: &str, + params: Value, + ) -> Result { + match method { + methods::LISTENER_OPEN => { + let port = self.open(context, parse(params)?)?; + crate::server::to_value(ListenerOpened { port }) + } + methods::LISTENER_CLOSE => { + let params: ListenerParams = parse(params)?; + let listener = self + .registry + .remove(params.listener_id) + .ok_or_else(|| self.registry.unknown(params.listener_id))?; + listener.shared.stop(); + // The loop ends right after the wake-up; the wait only + // bounds a host that does not schedule it. + if listener.ended.recv_timeout(CLOSE_WAIT) == Err(RecvTimeoutError::Timeout) { + eprintln!("lithe-remote-server: a listener did not release its port in time"); + } + crate::server::to_value(listener.state(params.listener_id)) + } + methods::LISTENER_ADOPT => { + self.adopt(context, parse(params)?)?; + Ok(Value::Null) + } + methods::LISTENER_LIST => crate::server::to_value(ListenersResult { + listeners: self + .registry + .lock() + .iter() + .map(|(listener_id, listener)| listener.state(*listener_id)) + .collect(), + }), + _ => Err(RemoteError::new( + ErrorCode::UnknownMethod, + format!("unknown method {method}"), + )), + } + } + + /// Closes the listeners of a client connection that ended. Their accept + /// loops end on their own; nothing waits for them. + pub(crate) fn close_owned_by(&self, connection: u64) { + self.registry.retain(|listener| { + let keep = listener.connection != connection; + if !keep { + listener.shared.stop(); + } + keep + }); + } + + pub(crate) fn close_all(&self) { + self.registry.retain(|listener| { + listener.shared.stop(); + false + }); + } + + fn open(&self, context: &Context, params: ListenerOpenParams) -> Result { + let address = bind_address(¶ms)?; + let session = &context.session; + session.ids.observe(params.listener_id); + self.registry.ensure_free(params.listener_id)?; + let listener = TcpListener::bind(address).map_err(bind_error)?; + let port = listener + .local_addr() + .map_err(|error| crate::server::fs::io_error(error, ""))? + .port(); + let io_failure = |error: io::Error| crate::server::fs::io_error(error, ""); + // Accepting must not block: the loop only accepts after `poll` + // reported a connection, which may be gone by then. + listener.set_nonblocking(true).map_err(io_failure)?; + let (waker, wakeups) = UnixStream::pair().map_err(io_failure)?; + waker.set_nonblocking(true).map_err(io_failure)?; + let shared = Arc::new(Shared { + state: Mutex::new(State::default()), + waker, + connections: AtomicU64::new(0), + failed: AtomicU64::new(0), + }); + let (finished, ended) = mpsc::channel::<()>(); + let accept = Accept { + session: Arc::clone(session), + listener_id: params.listener_id, + listener, + wakeups, + shared: Arc::clone(&shared), + relay: params.relay, + relays: Arc::clone(&self.relays), + }; + // The id is registered before the loop runs, so the first + // `listener.accepted` event never names an unknown listener. + self.registry.insert( + params.listener_id, + OpenListener { + connection: context.connection, + port, + shared: Arc::clone(&shared), + ended, + }, + )?; + let spawned = thread::Builder::new() + .name("remote-listener".into()) + .spawn(move || { + accept.run(); + drop(finished); + }); + if let Err(error) = spawned { + self.registry.remove(params.listener_id); + return Err(unavailable(error)); + } + Ok(port) + } + + fn adopt(&self, context: &Context, params: ListenerAdoptParams) -> Result<(), RemoteError> { + let shared = { + let listeners = self.registry.lock(); + let listener = listeners + .get(¶ms.listener_id) + .ok_or_else(|| self.registry.unknown(params.listener_id))?; + Arc::clone(&listener.shared) + }; + let waiting = lock(&shared.state).pending.remove(¶ms.accept_id); + let Some((stream, _)) = waiting else { + return Err(RemoteError::new( + ErrorCode::UnknownResource, + format!( + "connection {} of listener {} is not waiting", + params.accept_id, params.listener_id + ), + )); + }; + shared.wake(); + let adopted = context + .session + .tunnels + .adopt(context, params.tunnel_id, Stream::Tcp(stream)); + if adopted.is_err() { + shared.failed.fetch_add(1, Ordering::Relaxed); + } + adopted + } +} + +/// The address `listener.open` binds. Host rules may listen on every +/// interface because the user confirmed that; reverse rules reach the user's +/// machine and therefore listen on loopback only. +fn bind_address(params: &ListenerOpenParams) -> Result { + let host: IpAddr = params.host.parse().map_err(|_| { + RemoteError::new( + ErrorCode::InvalidRequest, + "a listener host must be an IP address", + ) + })?; + let allowed = host.is_loopback() || (params.relay.is_some() && host.is_unspecified()); + if !allowed { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "a listener binds a loopback address, or every interface for a host rule", + )); + } + Ok(SocketAddr::new(host, params.port)) +} + +fn bind_error(error: io::Error) -> RemoteError { + let code = match error.kind() { + io::ErrorKind::AddrInUse => ErrorCode::AddressInUse, + io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, + _ => ErrorCode::Io, + }; + RemoteError::new(code, format!("cannot listen: {error}")) + .with_details(json!({ "osError": error.raw_os_error() })) +} + +/// The accept loop of one listener and what it needs. +struct Accept { + session: Arc, + listener_id: u64, + listener: TcpListener, + /// Read side of [`Shared::waker`]. + wakeups: UnixStream, + shared: Arc, + relay: Option, + relays: Arc, +} + +impl Accept { + fn run(mut self) { + loop { + let (room, deadline) = { + let mut state = lock(&self.shared.state); + if state.stopping { + return; + } + let now = Instant::now(); + // Dropping a connection the client never adopted closes it, + // and it never reached its target. + let waiting = state.pending.len(); + state.pending.retain(|_, (_, deadline)| *deadline > now); + let expired = (waiting - state.pending.len()) as u64; + self.shared.failed.fetch_add(expired, Ordering::Relaxed); + let room = if self.relay.is_some() { + state.relays.len() < MAX_RELAYS_PER_LISTENER + } else { + state.pending.len() < MAX_PENDING + }; + let deadline = state + .pending + .values() + .map(|(_, deadline)| deadline.saturating_duration_since(now)) + .min(); + (room, deadline) + }; + let (woken, connecting) = match self.wait(room, deadline) { + Ok(ready) => ready, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => return, + }; + if woken { + let mut drained = [0_u8; 64]; + if matches!(self.wakeups.read(&mut drained), Ok(0) | Err(_)) { + return; + } + } + if connecting { + self.accept(); + } + } + } + + /// Waits until the state changes, a connection arrives while there is + /// room for it, or the first waiting connection is given up. Returns + /// whether the wake-up socket and the listener are readable. + fn wait(&self, room: bool, deadline: Option) -> io::Result<(bool, bool)> { + let mut descriptors = [ + libc::pollfd { + fd: self.wakeups.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }, + libc::pollfd { + fd: self.listener.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }, + ]; + let count = if room { 2 } else { 1 }; + let timeout = deadline.map_or(-1, |deadline| { + // Rounded up, so the loop does not wake just before the deadline. + deadline + .as_millis() + .saturating_add(1) + .min(libc::c_int::MAX as u128) as libc::c_int + }); + // SAFETY: the array is live and `count` does not exceed its length. + let ready = unsafe { libc::poll(descriptors.as_mut_ptr(), count, timeout) }; + if ready == -1 { + return Err(io::Error::last_os_error()); + } + Ok(( + descriptors[0].revents != 0, + room && descriptors[1].revents != 0, + )) + } + + fn accept(&self) { + let stream = match self.listener.accept() { + Ok((stream, _)) => stream, + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return, + Err(error) if error.kind() == io::ErrorKind::Interrupted => return, + Err(_) => { + thread::sleep(ACCEPT_RETRY); + return; + } + }; + // BSD hosts hand out accepted sockets with the listener's + // non-blocking flag; the copies below block. + if stream.set_nonblocking(false).is_err() { + return; + } + let _ = stream.set_nodelay(true); + self.shared.connections.fetch_add(1, Ordering::Relaxed); + match &self.relay { + Some(target) => self.relay(stream, target.clone()), + None => self.hand_over(stream), + } + } + + fn hand_over(&self, stream: TcpStream) { + let accept_id = { + let mut state = lock(&self.shared.state); + if state.stopping { + return; + } + let accept_id = state.next_accept; + state.next_accept += 1; + state + .pending + .insert(accept_id, (stream, Instant::now() + ADOPT_TIMEOUT)); + accept_id + }; + self.session.link.emit( + methods::EVENT_LISTENER_ACCEPTED, + ListenerAcceptedEvent { + listener_id: self.listener_id, + accept_id, + }, + ); + } + + fn relay(&self, stream: TcpStream, target: TunnelTarget) { + let admitted = self + .relays + .try_update(Ordering::AcqRel, Ordering::Acquire, |relays| { + (relays < MAX_RELAYS).then_some(relays + 1) + }) + .is_ok(); + if !admitted { + self.shared.failed.fetch_add(1, Ordering::Relaxed); + return; + } + let relay = Relay { + shared: Arc::clone(&self.shared), + relays: Arc::clone(&self.relays), + id: 0, + }; + let Some(relay) = relay.register(&stream) else { + return; + }; + let spawned = thread::Builder::new().name("remote-relay".into()).spawn({ + let relay = relay.clone(); + move || relay.run(stream, &target) + }); + if spawned.is_err() { + relay.fail(); + } + } +} + +/// One relayed connection. Ending it releases its slot and wakes the accept +/// loop, whatever the reason. +#[derive(Clone)] +struct Relay { + shared: Arc, + relays: Arc, + id: u64, +} + +impl Relay { + /// Records the accepted socket so that close can shut it down. Returns + /// `None`, with the slot released, when the listener is stopping. + fn register(mut self, stream: &TcpStream) -> Option { + let clone = stream.try_clone().ok(); + let shared = Arc::clone(&self.shared); + let mut state = lock(&shared.state); + let (Some(clone), false) = (clone, state.stopping) else { + drop(state); + self.release(); + return None; + }; + self.id = state.next_accept; + state.next_accept += 1; + state.relays.insert(self.id, vec![Stream::Tcp(clone)]); + Some(self) + } + + fn run(self, accepted: TcpStream, target: &TunnelTarget) { + let Ok(upstream) = tunnel::connect(target) else { + self.fail(); + return; + }; + let streams = (|| { + Some(( + accepted.try_clone().ok()?, + upstream.try_clone().ok()?, + upstream.try_clone().ok()?, + )) + })(); + let Some((answer, request, tracked)) = streams else { + self.fail(); + return; + }; + { + let mut state = lock(&self.shared.state); + let Some(tracked_streams) = state.relays.get_mut(&self.id) else { + // Closed while connecting. + drop(state); + upstream.shutdown(Shutdown::Both); + self.end(); + return; + }; + tracked_streams.push(tracked); + } + let Ok(reply) = thread::Builder::new() + .name("remote-relay".into()) + .spawn(move || pipe(upstream, Stream::Tcp(answer))) + else { + request.shutdown(Shutdown::Both); + self.fail(); + return; + }; + pipe(Stream::Tcp(accepted), request); + let _ = reply.join(); + self.end(); + } + + fn fail(&self) { + self.shared.failed.fetch_add(1, Ordering::Relaxed); + self.end(); + } + + fn end(&self) { + let streams = lock(&self.shared.state).relays.remove(&self.id); + for stream in streams.into_iter().flatten() { + stream.shutdown(Shutdown::Both); + } + self.release(); + } + + fn release(&self) { + self.relays.fetch_sub(1, Ordering::AcqRel); + self.shared.wake(); + } +} + +/// Copies one direction until end-of-file, then half-closes the other side +/// so its peer can still answer. A failure ends both directions. +fn pipe(mut from: Stream, mut to: Stream) { + match io::copy(&mut from, &mut to) { + Ok(_) => to.shutdown(Shutdown::Write), + Err(_) => { + from.shutdown(Shutdown::Both); + to.shutdown(Shutdown::Both); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn params(host: &str, relay: bool) -> ListenerOpenParams { + ListenerOpenParams { + listener_id: 1, + host: host.into(), + port: 0, + relay: relay.then(|| TunnelTarget::Tcp { + host: "127.0.0.1".into(), + port: 1, + }), + } + } + + #[test] + fn reverse_listeners_bind_loopback_and_host_rules_may_bind_every_interface() { + assert!(bind_address(¶ms("127.0.0.1", false)).is_ok()); + assert!(bind_address(¶ms("::1", false)).is_ok()); + assert!(bind_address(¶ms("0.0.0.0", true)).is_ok()); + assert!(bind_address(¶ms("::", true)).is_ok()); + for (host, relay) in [ + ("0.0.0.0", false), + ("::", false), + ("192.168.1.2", true), + ("localhost", true), + ] { + let error = bind_address(¶ms(host, relay)).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest, "relay={relay}"); + } + } + + #[test] + fn a_taken_port_reports_address_in_use() { + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = taken.local_addr().unwrap().port(); + let error = TcpListener::bind(("127.0.0.1", port)) + .map_err(bind_error) + .unwrap_err(); + assert_eq!(error.code, ErrorCode::AddressInUse); + } +} diff --git a/rust/crates/remote/src/server/mod.rs b/rust/crates/remote/src/server/mod.rs index f92deff6..6ce842ce 100644 --- a/rust/crates/remote/src/server/mod.rs +++ b/rust/crates/remote/src/server/mod.rs @@ -25,6 +25,7 @@ mod daemon; mod environment; mod fs; mod link; +mod listener; mod platform; mod ports; mod process; diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index 5fd1a1a4..b919c8d7 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -58,6 +58,7 @@ pub(crate) fn host_capabilities() -> HostCapabilities { Feature::Terminal, Feature::Environment, Feature::Tunnel, + Feature::Listener, Feature::Persistence, ]; features.sort(); diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index dd7d6e0d..e79ec348 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -4,6 +4,7 @@ use crate::protocol::methods::{encode_hex, ServerState, SessionToken}; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::environment::EnvironmentCache; use crate::server::link::Link; +use crate::server::listener::ListenerTable; use crate::server::process::ProcessTable; use crate::server::resources::{IdWatermark, InFlight, PendingStarts}; use crate::server::spawner::Spawner; @@ -87,6 +88,7 @@ pub(crate) struct Session { pub(crate) terminals: TerminalTable, pub(crate) watches: WatchTable, pub(crate) tunnels: TunnelTable, + pub(crate) listeners: ListenerTable, pub(crate) walks: WalkTable, pub(crate) uploads: crate::server::upload::UploadTable, pub(crate) run_directories: crate::server::run_directory::RunDirectories, @@ -121,6 +123,7 @@ impl Session { terminals: TerminalTable::new(), watches: WatchTable::new(), tunnels: TunnelTable::new(), + listeners: ListenerTable::new(), walks: WalkTable::new(), uploads: crate::server::upload::UploadTable::default(), run_directories: crate::server::run_directory::RunDirectories::new( @@ -225,10 +228,12 @@ impl Session { } /// Resources bound to a client connection. Tunnels end because their - /// local sockets are gone; walks end because their results would only - /// fill the replay buffer. + /// local sockets are gone; listeners close because a host port stays + /// open only while the client that holds the rule is connected; walks end + /// because their results would only fill the replay buffer. pub(crate) fn release_connection_resources(&self, connection: u64) { self.uploads.release(connection); + self.listeners.close_owned_by(connection); self.tunnels.close_owned_by(connection); self.walks.cancel_owned_by(connection); } @@ -236,6 +241,7 @@ impl Session { /// Ends everything the session started. pub(crate) fn terminate_all(&self) { self.ending.store(true, Ordering::Release); + self.listeners.close_all(); self.tunnels.close_all(); self.walks.cancel_all(); self.watches.stop_all(); diff --git a/rust/crates/remote/src/server/tunnel.rs b/rust/crates/remote/src/server/tunnel.rs index 43f1fe45..17df23f2 100644 --- a/rust/crates/remote/src/server/tunnel.rs +++ b/rust/crates/remote/src/server/tunnel.rs @@ -3,7 +3,8 @@ //! The client listens locally and opens one tunnel per accepted connection, //! which is how a web server, database or debugger on the remote becomes //! reachable from the user's machine. Tunnels travel inside the protocol -//! stream, so the server never opens a listening port of its own. +//! stream; the server listens on a port only for a rule the user added, see +//! `listener`, whose reverse connections become tunnels here. use crate::protocol::methods::{ self, decode_bytes, encode_bytes, TunnelClosedEvent, TunnelDataEvent, TunnelOpenParams, @@ -44,20 +45,21 @@ struct OpenTunnel { stream: Stream, } -enum Stream { +/// A connected byte stream: a tunnel's, or one a listener relays. +pub(crate) enum Stream { Tcp(TcpStream), Unix(UnixStream), } impl Stream { - fn try_clone(&self) -> io::Result { + pub(crate) fn try_clone(&self) -> io::Result { Ok(match self { Self::Tcp(stream) => Self::Tcp(stream.try_clone()?), Self::Unix(stream) => Self::Unix(stream.try_clone()?), }) } - fn shutdown(&self, how: Shutdown) { + pub(crate) fn shutdown(&self, how: Shutdown) { let _ = match self { Self::Tcp(stream) => stream.shutdown(how), Self::Unix(stream) => stream.shutdown(how), @@ -166,26 +168,48 @@ impl TunnelTable { } fn open(&self, context: &Context, params: TunnelOpenParams) -> Result<(), RemoteError> { + self.start(context, params.tunnel_id, || { + connect(¶ms.target).map_err(|error| { + RemoteError::new(ErrorCode::ConnectFailed, format!("cannot connect: {error}")) + .with_details(json!({ "osError": error.raw_os_error() })) + }) + }) + } + + /// Turns a connection a reverse listener accepted into the tunnel + /// `tunnel_id`, as if `tunnel.open` had connected it. The connection is + /// closed when the tunnel cannot start. + pub(crate) fn adopt( + &self, + context: &Context, + tunnel_id: u64, + stream: Stream, + ) -> Result<(), RemoteError> { + self.start(context, tunnel_id, || Ok(stream)) + } + + fn start( + &self, + context: &Context, + tunnel_id: u64, + stream: impl FnOnce() -> Result, + ) -> Result<(), RemoteError> { let session = &context.session; - session.ids.observe(params.tunnel_id); - self.registry.ensure_free(params.tunnel_id)?; + session.ids.observe(tunnel_id); + self.registry.ensure_free(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 stream = stream()?; let io_failure = |error: io::Error| crate::server::fs::io_error(error, ""); let reading = stream.try_clone().map_err(io_failure)?; let writing = stream.try_clone().map_err(io_failure)?; @@ -202,7 +226,9 @@ impl TunnelTable { } } -fn connect(target: &TunnelTarget) -> io::Result { +/// Connects to `target` as the host sees it, within [`CONNECT_TIMEOUT`] per +/// address. +pub(crate) fn connect(target: &TunnelTarget) -> io::Result { match target { TunnelTarget::Tcp { host, port } => { let mut last_error = None; diff --git a/rust/crates/remote/tests/tunnels.rs b/rust/crates/remote/tests/tunnels.rs index ab587aff..04f2157a 100644 --- a/rust/crates/remote/tests/tunnels.rs +++ b/rust/crates/remote/tests/tunnels.rs @@ -5,7 +5,8 @@ mod support; use lithe_remote::client::api::TunnelEvent; use lithe_remote::client::forward_set::MAX_FORWARDS; use lithe_remote::client::{ - ForwardError, ForwardSet, ForwardSpec, PortForward, RemoteSession, TargetField, + ForwardError, ForwardKind, ForwardSet, ForwardSpec, HostForwardSpec, PortForward, + RemoteSession, ReverseForwardSpec, TargetField, }; use lithe_remote::protocol::methods::TunnelTarget; use std::io::{Read, Write}; @@ -306,9 +307,9 @@ fn forward_sets_bridge_a_wildcard_listener_once_per_target() { 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_eq!(info.target_host.as_deref(), Some("127.0.0.1")); assert!(info.loopback_target); - assert_eq!(info.local_host, "127.0.0.1"); + assert_eq!(info.local_host.as_deref(), Some("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(); @@ -316,7 +317,8 @@ fn forward_sets_bridge_a_wildcard_listener_once_per_target() { 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(); + let local_port = info.local_port.unwrap(); + let mut local = TcpStream::connect(("127.0.0.1", 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()]; @@ -356,7 +358,7 @@ fn forward_sets_start_targets_outside_the_host_only_when_confirmed() { .unwrap(); assert!(created); assert!(!info.loopback_target); - assert_eq!(info.target_host, "192.0.2.10"); + assert_eq!(info.target_host.as_deref(), Some("192.0.2.10")); for (spec, field) in [ (forward_to("127.0.0.1", 0), TargetField::Port), @@ -389,7 +391,7 @@ fn forward_sets_move_off_a_local_port_another_program_uses() { assert!(created); assert_eq!(info.requested_local_port, Some(port)); assert!(info.local_port_changed); - assert_ne!(info.local_port, port); + assert_ne!(info.local_port, Some(port)); drop(taken); shut_down(&session); } @@ -421,16 +423,17 @@ fn forward_sets_release_their_local_ports_when_the_session_ends() { let session = Arc::new(session); let forwards = ForwardSet::new(Arc::clone(&session)); let (info, _) = forwards.start(forward_to("127.0.0.1", 1)).unwrap(); + let local_port = info.local_port.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() { + while TcpStream::connect(("127.0.0.1", local_port)).is_ok() { assert!( Instant::now() < deadline, "local port {} still accepts connections after the session ended", - info.local_port + 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)); @@ -441,3 +444,180 @@ fn forward_sets_release_their_local_ports_when_the_session_ends() { Err(ForwardError::SessionClosed) )); } + +/// A host forward on a port the host chooses, on its loopback interface, +/// unconfirmed. +fn host_forward_to(host: &str, port: u16) -> HostForwardSpec { + HostForwardSpec { + listen_port: None, + all_interfaces: false, + target_host: host.into(), + target_port: port, + allow_non_loopback_target: false, + } +} + +/// Sends `request` over `port` on this machine's loopback interface and +/// reads the echo server's uppercased answer. +fn exchange(port: u16, request: &[u8]) -> Vec { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream.set_read_timeout(Some(STEP_TIMEOUT)).unwrap(); + stream.write_all(request).unwrap(); + let mut answer = vec![0_u8; request.len()]; + stream.read_exact(&mut answer).unwrap(); + answer +} + +// The test server runs on this machine, so the host's loopback interface is +// this machine's too. +#[test] +fn host_forwards_relay_a_host_port_to_another_server() { + 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_host(host_forward_to("127.0.0.1", port)) + .unwrap(); + assert!(created); + assert_eq!(info.kind, ForwardKind::Host); + assert_eq!(info.host_listen_host.as_deref(), Some("127.0.0.1")); + assert!(!info.all_interfaces); + assert_eq!(info.local_port, None); + let host_port = info.host_listen_port.unwrap(); + let (again, created) = forwards + .start_host(host_forward_to("127.0.0.1", port)) + .unwrap(); + assert!(!created); + assert_eq!(again.id, info.id); + + assert_eq!(exchange(host_port, b"jump host"), b"JUMP HOST"); + server.join().unwrap(); + let listed = forwards.list().unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].connections, 1); + assert_eq!(listed[0].failed_connections, 0); + + assert!(forwards.stop(info.id)); + // Closing waits until the host released the port. + assert!(TcpStream::connect(("127.0.0.1", host_port)).is_err()); + shut_down(&session); +} + +#[test] +fn host_forwards_report_a_taken_host_port_and_check_their_targets() { + 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 error = forwards + .start_host(HostForwardSpec { + listen_port: Some(port), + ..host_forward_to("127.0.0.1", 8080) + }) + .unwrap_err(); + assert!(matches!(error, ForwardError::HostPortInUse), "{error:?}"); + // A documentation address (RFC 5737); nothing connects to it. + assert!(matches!( + forwards.start_host(host_forward_to("192.0.2.10", 5432)), + Err(ForwardError::TargetNotConfirmed) + )); + assert!(matches!( + forwards.start_host(host_forward_to("127.0.0.1", 0)), + Err(ForwardError::InvalidTarget(TargetField::Port)) + )); + assert!(forwards.list().unwrap().is_empty()); + drop(taken); + shut_down(&session); +} + +#[test] +fn reverse_forwards_bring_host_connections_back_to_a_local_port() { + let (local_port, server) = spawn_tcp_echo(); + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + + assert!(matches!( + forwards.start_reverse(ReverseForwardSpec { + listen_port: None, + local_port: 0, + }), + Err(ForwardError::InvalidTarget(TargetField::LocalPort)) + )); + let (info, created) = forwards + .start_reverse(ReverseForwardSpec { + listen_port: None, + local_port, + }) + .unwrap(); + assert!(created); + assert_eq!(info.kind, ForwardKind::Reverse); + assert_eq!(info.host_listen_host.as_deref(), Some("127.0.0.1")); + assert_eq!(info.local_port, Some(local_port)); + assert_eq!(info.target_host, None); + + let host_port = info.host_listen_port.unwrap(); + assert_eq!(exchange(host_port, b"reverse"), b"REVERSE"); + server.join().unwrap(); + assert_eq!(forwards.list().unwrap()[0].connections, 1); + assert!(forwards.stop(info.id)); + assert!(TcpStream::connect(("127.0.0.1", host_port)).is_err()); + shut_down(&session); +} + +// One limit covers every kind, so host listeners cannot exceed what the +// ports page shows. +#[test] +fn forward_kinds_share_one_limit() { + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + let local = u16::try_from(MAX_FORWARDS - 1).unwrap(); + for port in 1..=local { + forwards.start(forward_to("127.0.0.1", port)).unwrap(); + } + forwards + .start_host(host_forward_to("127.0.0.1", 1)) + .unwrap(); + assert!(matches!( + forwards.start_reverse(ReverseForwardSpec { + listen_port: None, + local_port: 1, + }), + Err(ForwardError::LimitReached) + )); + shut_down(&session); +} + +// The host closes its listeners when the client disconnects; nothing +// reopens them. +#[test] +fn host_ports_close_when_the_session_ends() { + let (session, _events) = connect(); + let session = Arc::new(session); + let forwards = ForwardSet::new(Arc::clone(&session)); + let (info, _) = forwards + .start_host(host_forward_to("127.0.0.1", 1)) + .unwrap(); + let host_port = info.host_listen_port.unwrap(); + + shut_down(&session); + let deadline = Instant::now() + STEP_TIMEOUT; + // The host can exit before this client reads the end of its stream. + while !session.is_closed() || TcpStream::connect(("127.0.0.1", host_port)).is_ok() { + assert!( + Instant::now() < deadline, + "host port {host_port} still accepts connections after the session ended" + ); + // test-stability: allow(rust-real-sleep) reason: the host closes the listener when its process exits, without a signal to this test; the loop has a monotonic deadline and a diagnostic. + thread::sleep(Duration::from_millis(20)); + } + assert!(matches!( + forwards.start_host(host_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 index d4925140..cbd3e135 100644 --- a/rust/crates/workspace/src/forwards.rs +++ b/rust/crates/workspace/src/forwards.rs @@ -1,20 +1,32 @@ -//! `remote.startForward`, `remote.stopForward` and `remote.forwards`: the -//! port forwards of one open connection, as the ports page manages them. +//! `remote.startForward`, `remote.startHostForward`, +//! `remote.startReverseForward`, `remote.stopForward` and `remote.forwards`: +//! the port forwards of one open connection, as the ports page manages them. //! `remote.parseForwardAddress` reads what the user typed into the page, a //! port, `host:port` or a URL, without a connection. //! +//! - A local forward listens on this machine and reaches a port as the host +//! sees it. +//! - A host forward listens on the host and connects to another server from +//! there; it listens on every host interface only when the request says so. +//! - A reverse forward listens on the host's loopback interface and reaches a +//! port on this machine's loopback interface. It starts only when the +//! remote preferences allow reverse forwards. +//! //! 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`. +//! closes every port it opened on either side (design S29), and none is +//! reopened after a reconnect. Which targets need the user's confirmation +//! (design S28), how a local port another program uses is replaced, and the +//! one limit every kind shares 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 crate::sessions::{forget, lookup, request_error, Connection}; use lithe_protocol::{CoreError, ErrorCode}; use lithe_remote::client::forward_set::MAX_FORWARDS; use lithe_remote::client::{ - forward_address, ForwardAddress, ForwardError, ForwardInfo, ForwardSpec, TargetField, + forward_address, ForwardAddress, ForwardError, ForwardInfo, ForwardSpec, HostForwardSpec, + ReverseForwardSpec, TargetField, }; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -37,6 +49,43 @@ pub struct StartRequest { allow_non_loopback_target: bool, } +/// `remote.startHostForward`: a host port that connects to another server. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StartHostRequest { + session_id: String, + /// Host port to listen on; absent or `0` lets the host choose one. + #[serde(default)] + listen_port: Option, + /// Listen on every host interface instead of its loopback interface. The + /// caller asks the user every time; Core never remembers it. + #[serde(default)] + all_interfaces: bool, + /// The server to connect to, as the host resolves it. + target_host: String, + target_port: u16, + /// The user confirmed a target outside the host's loopback interface. + #[serde(default)] + allow_non_loopback_target: bool, +} + +/// `remote.startReverseForward`: a host loopback port that reaches a port on +/// this machine's loopback interface. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StartReverseRequest { + session_id: String, + /// Host port to listen on; absent or `0` lets the host choose one. + #[serde(default)] + listen_port: Option, + /// The port on this machine's loopback interface. + local_port: u16, + /// Current remote preferences document, `null` when the source does not + /// exist; it decides whether reverse forwards may start. + #[serde(default)] + preferences: Option, +} + /// `remote.parseForwardAddress`: an address typed into the ports page. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -59,13 +108,14 @@ pub struct ListRequest { session_id: String, } -/// `remote.startForward` result. +/// Result of `remote.startForward`, `remote.startHostForward` and +/// `remote.startReverseForward`. #[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. + /// `false` when the same rule already ran; `forward` is then that + /// forward, unchanged. created: bool, } @@ -101,6 +151,44 @@ pub fn start(request: StartRequest) -> Result { Ok(Started { forward, created }) } +/// Starts a host forward, or returns the one that already runs the same rule. +pub fn start_host(request: StartHostRequest) -> Result { + let connection = open(&request.session_id)?; + let spec = HostForwardSpec { + listen_port: request.listen_port, + all_interfaces: request.all_interfaces, + target_host: request.target_host, + target_port: request.target_port, + allow_non_loopback_target: request.allow_non_loopback_target, + }; + let (forward, created) = connection + .forwards + .start_host(spec) + .map_err(|error| forward_error(&request.session_id, error))?; + Ok(Started { forward, created }) +} + +/// Starts a reverse forward when the preferences allow it, or returns the +/// one that already runs the same rule. +pub fn start_reverse(request: StartReverseRequest) -> Result { + if !crate::preferences::reverse_forwarding_allowed(request.preferences.as_deref())? { + return Err(CoreError::new( + ErrorCode::ReverseForwardDisabled, + "Reverse port forwards are turned off in the remote workspace settings", + )); + } + let connection = open(&request.session_id)?; + let spec = ReverseForwardSpec { + listen_port: request.listen_port, + local_port: request.local_port, + }; + let (forward, created) = connection + .forwards + .start_reverse(spec) + .map_err(|error| forward_error(&request.session_id, error))?; + Ok(Started { forward, created }) +} + /// Reads an address typed into the ports page into the target of a forward. /// Nothing is resolved or contacted. pub fn parse_address(request: AddressRequest) -> Result { @@ -110,7 +198,7 @@ pub fn parse_address(request: AddressRequest) -> Result Result { let connection = open(&request.session_id)?; Ok(Stopped { @@ -145,6 +233,7 @@ fn forward_error(session_id: &str, error: ForwardError) -> CoreError { let field = match field { TargetField::Host => "targetHost", TargetField::Port => "targetPort", + TargetField::LocalPort => "localPort", }; CoreError::new(ErrorCode::InvalidRequest, "Invalid port forward target") .with_details(json!({ "field": field }).to_string()) @@ -158,6 +247,19 @@ fn forward_error(session_id: &str, error: ForwardError) -> CoreError { "The remote connection has the most port forwards it keeps", ) .with_details(json!({ "maximum": MAX_FORWARDS }).to_string()), + ForwardError::HostPortInUse => CoreError::new( + ErrorCode::ForwardHostPortInUse, + "Another program on the remote host already uses the port", + ), + ForwardError::HostPortDenied => CoreError::new( + ErrorCode::ForwardHostPortDenied, + "The remote host does not allow listening on the port", + ), + ForwardError::HostListenerUnsupported => CoreError::new( + ErrorCode::ForwardHostUnsupported, + "The remote server cannot listen on host ports", + ), + ForwardError::Remote(error) => request_error(session_id, error), ForwardError::SessionClosed => { forget(session_id); CoreError::new(ErrorCode::ConnectionClosed, "The remote connection closed") diff --git a/rust/crates/workspace/src/preferences.rs b/rust/crates/workspace/src/preferences.rs index 601483f3..194d44fd 100644 --- a/rust/crates/workspace/src/preferences.rs +++ b/rust/crates/workspace/src/preferences.rs @@ -25,8 +25,8 @@ pub struct ReadRequest { home_directory: Option, } -/// `remote.editPreferences`: exactly one of `sshProgram` and -/// `reconnectLimit`. +/// `remote.editPreferences`: exactly one of `sshProgram`, `reconnectLimit` +/// and `reverseForwarding`. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EditRequest { @@ -36,6 +36,8 @@ pub struct EditRequest { ssh_program: Option, #[serde(default)] reconnect_limit: Option, + #[serde(default)] + reverse_forwarding: Option, } /// The SSH program to use; `path: null` makes it automatic. @@ -52,6 +54,13 @@ struct LimitEdit { seconds: Option, } +/// Whether reverse forwards are allowed; `allowed: null` makes it automatic. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct SwitchEdit { + allowed: Option, +} + /// Where the native client keeps the document. #[derive(Serialize)] #[serde(rename_all = "camelCase")] @@ -74,9 +83,11 @@ pub fn read(request: ReadRequest) -> Result { "preferences": { "sshProgram": preferences.ssh_program(), "reconnectLimitSeconds": preferences.reconnect_limit_seconds(), + "allowReverseForwarding": preferences.allow_reverse_forwarding(), }, "ssh": ssh, "reconnect": preferences.reconnect(), + "reverseForwarding": preferences.reverse_forwarding(), "storage": STORAGE, }); if let Some(home) = request.home_directory { @@ -102,13 +113,18 @@ pub fn read(request: ReadRequest) -> Result { pub fn edit(request: EditRequest) -> Result { let before = parse(request.document.as_deref())?; let mut after = before.clone(); - match (request.ssh_program, request.reconnect_limit) { - (Some(program), None) => after + match ( + request.ssh_program, + request.reconnect_limit, + request.reverse_forwarding, + ) { + (Some(program), None, None) => after .set_ssh_program(program.path.as_deref()) .map_err(invalid_request)?, - (None, Some(limit)) => after + (None, Some(limit), None) => after .set_reconnect_limit(limit.seconds) .map_err(invalid_request)?, + (None, None, Some(switch)) => after.set_allow_reverse_forwarding(switch.allowed), _ => { return Err(CoreError::new( ErrorCode::InvalidRequest, @@ -141,6 +157,11 @@ pub(crate) fn ssh_program( Ok(ssh.command().to_owned()) } +/// Whether the preferences in `document` allow reverse forwards. +pub(crate) fn reverse_forwarding_allowed(document: Option<&str>) -> Result { + Ok(parse(document)?.reverse_forwarding().allowed) +} + /// A stored document that cannot be decoded is a parse failure, not a bad /// request: the caller sent what the source holds. fn parse(document: Option<&str>) -> Result { diff --git a/rust/crates/workspace/src/preferences/tests.rs b/rust/crates/workspace/src/preferences/tests.rs index 068c56fe..3c0eeb69 100644 --- a/rust/crates/workspace/src/preferences/tests.rs +++ b/rust/crates/workspace/src/preferences/tests.rs @@ -18,11 +18,19 @@ fn reading_no_document_reports_automatic_values_and_the_storage() { .unwrap(); assert_eq!( result["preferences"], - json!({ "sshProgram": null, "reconnectLimitSeconds": null }) + json!({ + "sshProgram": null, + "reconnectLimitSeconds": null, + "allowReverseForwarding": null, + }) ); assert_eq!(result["ssh"]["source"], "automatic"); assert_eq!(result["reconnect"]["source"], "automatic"); assert_eq!(result["reconnect"]["limitSeconds"], 60); + assert_eq!( + result["reverseForwarding"], + json!({ "source": "automatic", "allowed": false }) + ); assert_eq!( result["storage"], json!({ "relativePath": "remote/preferences.json", "maximumBytes": 16384 }) @@ -84,6 +92,34 @@ fn an_edit_changes_one_value_and_publishes_the_document() { assert_eq!(automatic["document"], "{\n \"version\": 1\n}\n"); } +#[test] +fn reverse_forwards_stay_refused_until_the_switch_allows_them() { + assert!(!reverse_forwarding_allowed(None).unwrap()); + let allowed = edit(request(json!({ + "document": null, + "reverseForwarding": { "allowed": true }, + }))) + .unwrap(); + let document = allowed["document"].as_str().unwrap().to_owned(); + assert!(reverse_forwarding_allowed(Some(&document)).unwrap()); + let state = read(request(json!({ "document": document }))).unwrap(); + assert_eq!( + state["reverseForwarding"], + json!({ "source": "setting", "allowed": true }) + ); + + let refused = edit(request(json!({ + "document": document, + "reverseForwarding": { "allowed": false }, + }))) + .unwrap(); + let document = refused["document"].as_str().unwrap().to_owned(); + assert!(!reverse_forwarding_allowed(Some(&document)).unwrap()); + + let error = reverse_forwarding_allowed(Some("not json")).unwrap_err(); + assert!(matches!(error.code, ErrorCode::ParseFailed)); +} + #[test] fn an_edit_names_exactly_one_value_and_refuses_bad_programs_by_field() { for both_or_neither in [ @@ -93,6 +129,11 @@ fn an_edit_names_exactly_one_value_and_refuses_bad_programs_by_field() { "sshProgram": { "path": null }, "reconnectLimit": { "seconds": null }, }), + json!({ + "document": null, + "reconnectLimit": { "seconds": null }, + "reverseForwarding": { "allowed": true }, + }), ] { let error = edit(request(both_or_neither)).unwrap_err(); assert!(matches!(error.code, ErrorCode::InvalidRequest)); diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index 04ad8c28..481c53d6 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -387,6 +387,84 @@ } }, "owner": "lithe-core" + }, + { + "id": "remote.forward.host_started", + "channel": "remote", + "level": "info", + "message": "Port forward started on host port {listen_port}", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "kind": { + "type": "token", + "required": true, + "description": "host when the remote host relays to another server, reverse when connections come back to this machine" + }, + "listen_port": { + "type": "int", + "required": true, + "description": "TCP port the remote host listens on, after the system chose one for port 0" + }, + "bind_scope": { + "type": "token", + "required": true, + "description": "Whether the host listener is bound to loopback only or to every interface" + }, + "target_port": { + "type": "int", + "required": false, + "description": "TCP port a host forward relays to; absent for reverse forwards, and the target host is never logged" + }, + "target_scope": { + "type": "token", + "required": false, + "description": "Whether a host forward's target is a loopback name or address, or another network host" + }, + "local_port": { + "type": "int", + "required": false, + "description": "Loopback port on this machine a reverse forward connects to; absent for host forwards" + } + }, + "owner": "lithe-core" + }, + { + "id": "remote.forward.host_removed", + "channel": "remote", + "level": "info", + "message": "Port forward on host port {listen_port} removed", + "fields": { + "connection": { + "type": "id", + "required": true, + "description": "Random per-connection log identifier that correlates this connection's lines; never a host, user name or session token" + }, + "listen_port": { + "type": "int", + "required": true, + "description": "TCP port the remote host stopped listening on" + }, + "connections": { + "type": "int", + "required": true, + "description": "Number of connections the host port accepted during its lifetime" + }, + "failed_connections": { + "type": "int", + "required": true, + "description": "Accepted connections that never reached their target" + }, + "duration": { + "type": "duration", + "required": true, + "description": "Time from starting the forward until the host stopped listening" + } + }, + "owner": "lithe-core" } ] }