Skip to content

Commit e9d4cb2

Browse files
committed
feat(remote): host and reverse port forwards through a server listener (Refs 1lck/Lithe-IDEA#2231)
The server can now listen on a host port for a forwarding rule the user added (listener.open/adopt/close/list, listener.accepted, feature "listener"). Host rules relay every accepted connection on the host; reverse rules hand each connection to the client as a tunnel that reaches this machine's loopback interface. Core adds remote.startHostForward and remote.startReverseForward. Host forwards listen on the host's loopback interface unless the request asks for every interface; reverse forwards bind loopback only and start only when the new remote preference allowReverseForwarding is on (off by default). All kinds share the 64-forward limit, report kind and failedConnections, and are never reopened after a reconnect. New error codes: forward_host_port_in_use, forward_host_port_denied, forward_host_unsupported, reverse_forward_disabled.
1 parent 49fb750 commit e9d4cb2

31 files changed

Lines changed: 2699 additions & 165 deletions

‎rust/contracts/application-boundary.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,10 @@ meaning; `lithe_protocol::ErrorCode` documents when it is reported:
410410
- `connection_closed`: the remote connection the request names closed or was lost
411411
- `forward_target_not_confirmed`: a port forward reaches another machine through the remote host and the user has not confirmed it
412412
- `forward_limit_reached`: the remote connection keeps the most port forwards it allows
413+
- `forward_host_port_in_use`: another program on the remote host already uses the port a host or reverse forward asks for
414+
- `forward_host_port_denied`: the remote host does not allow listening on the port a host or reverse forward asks for
415+
- `forward_host_unsupported`: the remote server cannot listen on host ports for host or reverse forwards
416+
- `reverse_forward_disabled`: the remote workspace settings do not allow reverse forwards
413417
- `remote_server_invalid`: the server build `remote.connect` would send cannot
414418
be read or is not the build its SHA-256 names
415419
- `unknown`

‎rust/contracts/remote-workspace-protocol-v1.md‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,10 @@ Other clients should do the same.
4949
bytes of UTF-8 JSON. Frames larger than 16 MiB are rejected.
5050
3. Closing the client-to-server stream is a disconnect.
5151

52-
The server never listens on a network port; all traffic, including tunnels,
53-
uses this stream. Local port forwards are the client's: the reference client
52+
All traffic, including tunnels, uses this stream. The server listens on a
53+
network port only for a forwarding rule the user added (`listener.open`, see
54+
"Listeners"); such a port belongs to the connection that opened it and
55+
closes with it. Local port forwards are the client's: the reference client
5456
listens on loopback addresses only, because a remote development server
5557
usually has no authentication of its own, and bridges at most 64 connections
5658
per forward, leaving further ones in the system's listen queue until one
@@ -154,6 +156,10 @@ subscribe before creating the resource.
154156
| `tunnel.write` | `tunnelId`, `data` | `null`; `BUSY` when the peer stops reading |
155157
| `tunnel.shutdownWrite` | `tunnelId` | `null`; queued data is sent, then the write side is shut down; replies keep arriving |
156158
| `tunnel.close` | `tunnelId` | `null`; aborts both directions, queued data is discarded |
159+
| `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 |
160+
| `listener.adopt` | `listenerId`, `acceptId`, `tunnelId` | `null`; the waiting connection becomes that tunnel; `UNKNOWN_RESOURCE` when it no longer waits |
161+
| `listener.close` | `listenerId` | `listenerId`, `port`, `connections`, `failedConnections`; closes the port and every connection it relays or still holds |
162+
| `listener.list` | — | `listeners` by `listenerId`: `listenerId`, `port`, `connections`, `failedConnections` |
157163
| `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 |
158164

159165
`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
257263
| `walk.done` | `walkId`, `total`, `truncated`, `cancelled`, `skippedNonUtf8`, `unreadableDirectories` |
258264
| `tunnel.data` | `tunnelId`, `data` |
259265
| `tunnel.closed` | `tunnelId`, `error?` — the last event of the tunnel |
266+
| `listener.accepted` | `listenerId`, `acceptId` — a reverse listener holds a connection for `listener.adopt` |
260267

261268
`watch.changed` batches are coalesced and sorted by path. With `overflow`
262269
changes were lost and the client must rescan the watched tree.
263270

271+
## Listeners
272+
273+
The `listener` feature lets a client make the host listen on a TCP port for
274+
a forwarding rule the user added:
275+
276+
- With `relay`, a **host rule**: the host connects every accepted connection
277+
to that target itself and copies the bytes on the host, so nothing
278+
crosses the stream. `host` is a loopback address, or `0.0.0.0` or `::`
279+
when the user confirmed listening on every interface. At most 64
280+
connections of one listener and 256 of the session are relayed at once;
281+
further ones wait in the kernel's backlog, or are closed and counted as
282+
failed when the session is at its limit.
283+
- Without `relay`, a **reverse rule**: `host` must be a loopback address.
284+
Every accepted connection waits, at most 16 at once per listener, for the
285+
client, which receives `listener.accepted`, subscribes to a new tunnel and
286+
calls `listener.adopt`; the connection then behaves as a tunnel the client
287+
opened. A connection not adopted within 10 seconds is closed and counted
288+
as failed.
289+
290+
Host names are refused, so the host never resolves what the client sends as
291+
an address to bind. `failedConnections` counts connections that never
292+
reached their target: a relay target that refused, a connection not adopted
293+
in time, or one the host had no thread or tunnel left for. A listener
294+
belongs to the connection that opened it, also in a persistent session, and
295+
closes when that connection ends; clients do not reopen one after a
296+
reconnect on their own, so a host port is open only while the user's rule
297+
is. `listener.close` waits up to one second for the port to be released, so
298+
a rule edited to the same port can bind it again at once.
299+
264300
## Event delivery and persistent sessions
265301

266302
`server.hello` returns `session` with `persistent`, `resumed`,
@@ -291,8 +327,8 @@ events after `afterSeq` were dropped; the client re-reads state and rescans
291327
watches.
292328

293329
While no client is attached, a persistent session keeps processes, terminals
294-
and watches running. Tunnels and walks belong to the connection that opened
295-
them and end with it. After `server.shutdown` a persistent session is no
330+
and watches running. Tunnels, walks and listeners belong to the connection
331+
that opened them and end with it. After `server.shutdown` a persistent session is no
296332
longer reachable, even while it is still terminating its processes; the next
297333
connection with the same key starts a fresh session.
298334

@@ -318,7 +354,7 @@ the field.
318354
`NOT_FOUND`, `PERMISSION_DENIED`, `ALREADY_EXISTS`, `NOT_A_DIRECTORY`,
319355
`IS_A_DIRECTORY`, `DIRECTORY_NOT_EMPTY`, `CONFLICT`, `TOO_LARGE`,
320356
`UNKNOWN_RESOURCE`, `RESOURCE_ID_IN_USE`, `SPAWN_FAILED`, `CONNECT_FAILED`,
321-
`BUSY`, `UNSUPPORTED`, `IO`. Clients additionally produce `TIMEOUT` and
357+
`ADDRESS_IN_USE`, `BUSY`, `UNSUPPORTED`, `IO`. Clients additionally produce `TIMEOUT` and
322358
`DISCONNECTED` locally. Messages are for people; OS error numbers stay in
323359
`details`. `BUSY` always means a capacity limit that may clear: retrying
324360
later is safe because the failed request changed nothing.

‎rust/contracts/rust-core-api.md‎

Lines changed: 75 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -818,7 +818,9 @@ or removing a command fails until the table changes in the same commit.
818818
| `remote.workspaceTrust` | Read remote workspace trust decisions and one open workspace's trust |
819819
| `remote.editWorkspaceTrust` | Record or remove one remote workspace trust decision |
820820
| `remote.startForward` | Forward a local port to a port as the remote host sees it |
821-
| `remote.stopForward` | Stop one port forward and close its local port |
821+
| `remote.startHostForward` | Make the remote host listen on a port and connect it to another server |
822+
| `remote.startReverseForward` | Make the remote host listen on a loopback port that reaches a port on this machine |
823+
| `remote.stopForward` | Stop one port forward and close the port it listens on |
822824
| `remote.forwards` | List the running port forwards of one connection |
823825
| `remote.parseForwardAddress` | Read a port, `host:port` or URL typed into the ports page into a forward target |
824826
| `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.
829831
| `remote.mottyHosts` | List the SSH hosts saved in Motty for an import |
830832
| `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine |
831833
| `remote.preferences` | Read the remote workspace settings and what each automatic value resolves to |
832-
| `remote.editPreferences` | Set the SSH program or the reconnect limit, or make one automatic again |
834+
| `remote.editPreferences` | Set the SSH program, the reconnect limit or whether reverse forwards are allowed, or make one automatic again |
833835
| `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation |
834836
| `git.remotes` | Return configured fetch remote names and URLs |
835837
| `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations |
@@ -5927,17 +5929,18 @@ the distributions each time it opens.
59275929

59285930
#### Remote workspace preferences
59295931

5930-
The settings page "Tools › Remote Workspace" edits two values that apply to
5932+
The settings page "Tools › Remote Workspace" edits three values that apply to
59315933
every connection. Native clients keep them in one machine-local document,
59325934
read it, and publish the `document` an edit returns atomically, as for the
59335935
saved connections; Core validates the document, applies every edit and
59345936
tells what each automatic value resolves to.
59355937

59365938
`remote.preferences` accepts `{ document: string|null, homeDirectory? }`
5937-
and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`:
5939+
and returns `{ preferences, ssh, reconnect, reverseForwarding, storage,
5940+
sshConfig? }`:
59385941

5939-
- `preferences` is `{ sshProgram, reconnectLimitSeconds }`, the stored
5940-
values; `null` is automatic.
5942+
- `preferences` is `{ sshProgram, reconnectLimitSeconds,
5943+
allowReverseForwarding }`, the stored values; `null` is automatic.
59415944
- `ssh` is `{ source, path, status }`, the OpenSSH client every connection
59425945
starts. `source` is `setting` for a stored program and `automatic`
59435946
otherwise, which is the first executable `ssh` (`ssh.exe` on Windows) in an
@@ -5951,6 +5954,9 @@ and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`:
59515954
double up to 30 seconds and add up to the limit; the last one is shortened
59525955
to fit. A limit of 0 never reconnects, so the list is empty. Clients wait
59535956
these pauses and decide nothing else about the schedule.
5957+
- `reverseForwarding` is `{ source, allowed }`: whether the ports page may
5958+
start reverse forwards (automatic: not allowed), because every user of the
5959+
host can reach the local port one opens.
59545960
- `storage` is `{ relativePath: "remote/preferences.json", maximumBytes:
59555961
16384 }`.
59565962
- `sshConfig` is `{ path, exists }` for `.ssh/config` below `homeDirectory`,
@@ -5963,10 +5969,12 @@ and returns `{ preferences, ssh, reconnect, storage, sshConfig? }`:
59635969
existing executable file, or makes the program automatic with `null`.
59645970
- `reconnectLimit: { seconds: number|null }` stores 0 to 3600 seconds, or
59655971
makes the limit automatic with `null`.
5972+
- `reverseForwarding: { allowed: boolean|null }` allows or refuses reverse
5973+
forwards, or makes the switch automatic with `null`.
59665974

59675975
The result is `{ changed, document: string|null }`; an unchanged edit
5968-
returns a `null` document and must not create a source. Neither or both
5969-
fields is `invalid_request` with `{ field: "operation", reason: "invalid"
5976+
returns a `null` document and must not create a source. No field or more
5977+
than one is `invalid_request` with `{ field: "operation", reason: "invalid"
59705978
}`; a refused value is `invalid_request` with `{ field, reason }`, where
59715979
`field` is `sshProgram` or `reconnectLimitSeconds` and `reason` is
59725980
`invalid` (empty, surrounding spaces or control characters), `tooLong`
@@ -6111,29 +6119,54 @@ deletion of inputs used by surviving processes.
61116119

61126120
#### Remote port forwards
61136121

6114-
The ports page forwards a local port to a TCP port as the remote host sees
6115-
it. It lists candidates with `remote.hostRequest` and `ports.listening`
6122+
The ports page runs three kinds of forwards over one connection:
6123+
6124+
- a **local** forward listens on this machine and reaches a TCP port as the
6125+
remote host sees it;
6126+
- a **host** forward makes the host listen on a port and connect every
6127+
accepted connection to another server itself, as `ssh -L` on a jump host
6128+
does; the bytes never cross the connection;
6129+
- a **reverse** forward makes the host listen on its loopback interface and
6130+
brings every accepted connection back to a port on this machine's loopback
6131+
interface, as `ssh -R 127.0.0.1:…` does.
6132+
6133+
The page lists candidates with `remote.hostRequest` and `ports.listening`
61166134
(`{ ports: [{ address, port, pid?, process? }] }`, one entry for each address
61176135
and port; `pid` and `process` only when the server's user can inspect the
61186136
owning process). Forwards belong to one connection:
61196137

61206138
| Command | Request | Result |
61216139
| --- | --- | --- |
61226140
| `remote.startForward` | `{ sessionId, targetHost, targetPort, localPort?, allowNonLoopbackTarget? }` | `{ forward, created }` |
6141+
| `remote.startHostForward` | `{ sessionId, targetHost, targetPort, listenPort?, allInterfaces?, allowNonLoopbackTarget? }` | `{ forward, created }` |
6142+
| `remote.startReverseForward` | `{ sessionId, localPort, listenPort?, preferences }` | `{ forward, created }` |
61236143
| `remote.stopForward` | `{ sessionId, forwardId }` | `{ stopped }` |
61246144
| `remote.forwards` | `{ sessionId }` | `{ forwards }`, by `id` |
61256145
| `remote.parseForwardAddress` | `{ text }` | `{ targetHost, targetPort, scheme?, path? }` |
61266146

6127-
A forward is `{ id, localHost, localPort, requestedLocalPort?,
6128-
localPortChanged, targetHost, targetPort, loopbackTarget, connections }`.
6147+
A forward is `{ id, kind, localHost?, localPort?, requestedLocalPort?,
6148+
localPortChanged, hostListenHost?, hostListenPort?, requestedHostPort?,
6149+
allInterfaces, targetHost?, targetPort?, loopbackTarget, connections,
6150+
failedConnections }`. `kind` is `local`, `host` or `reverse`; a field that
6151+
does not apply to the kind is absent:
6152+
6153+
| Kind | Listens on | Reaches |
6154+
| --- | --- | --- |
6155+
| `local` | `localHost:localPort` | `targetHost:targetPort` as the host sees it |
6156+
| `host` | `hostListenHost:hostListenPort` | `targetHost:targetPort` as the host resolves it |
6157+
| `reverse` | `hostListenHost:hostListenPort` (always `127.0.0.1`) | `localHost:localPort` (always `127.0.0.1`) on this machine |
6158+
6159+
`connections` counts accepted connections and `failedConnections` those
6160+
that could not reach their target (always 0 for a local forward).
61296161

61306162
- **Target.** `targetHost` is an IP address (IPv6 with or without brackets)
61316163
or a host name the remote host resolves, such as `localhost`. A wildcard
61326164
address (`0.0.0.0`, `::`), as `ports.listening` reports a program that
61336165
listens on every interface, becomes the host's loopback address of the
61346166
same family; `targetHost` in the result is the address sent to the host.
61356167
A malformed host or port `0` is `invalid_request` with `details.field`
6136-
(`targetHost` or `targetPort`).
6168+
(`targetHost`, `targetPort`, or `localPort` for a reverse forward's port
6169+
`0`).
61376170
- **Typed address.** `remote.parseForwardAddress` reads what the user typed
61386171
into the page, without a connection and without resolving anything: a
61396172
port alone (`3000`, on `localhost`), `host:port` with brackets around an
@@ -6153,23 +6186,42 @@ localPortChanged, targetHost, targetPort, loopbackTarget, connections }`.
61536186
`allowNonLoopbackTarget: true`, which the native client sets after the
61546187
user confirmed that target. Without it the request fails with
61556188
`forward_target_not_confirmed` and nothing starts. `loopbackTarget` tells
6156-
the two apart in the list.
6189+
the two apart in the list. The rule is the same for host forwards.
61576190
- **Local port.** The forward listens on `127.0.0.1`. `localPort` (absent or
61586191
`0` for a free one) is used when no local program accepts connections on
61596192
it, on `127.0.0.1` or `::1`; otherwise the forward listens on a free port,
61606193
`requestedLocalPort` keeps the asked one and `localPortChanged` is `true`.
61616194
A local port that cannot be opened at all is `unknown` with
61626195
`details.io`.
6163-
- **Once per target.** Starting a target that already has a forward returns
6164-
that forward with `created: false`, so a repeated click opens no second
6165-
local port. A connection keeps at most 64 forwards; one more is
6166-
`forward_limit_reached` with `details.maximum`.
6167-
- **Lifetime.** `remote.stopForward` closes the local port; connections it
6168-
already accepted run until either side closes them, and an unknown id
6169-
returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a
6170-
lost connection close every local port of the connection. Requests on a
6196+
- **Host port.** Host and reverse forwards listen on the host port
6197+
`listenPort` (absent or `0` for one the host chooses) and never move to
6198+
another one: a port another host program uses is
6199+
`forward_host_port_in_use`, and one the host refuses, such as a port below
6200+
1024 for an unprivileged user, is `forward_host_port_denied`. A host
6201+
forward listens on the host's loopback interface unless `allInterfaces` is
6202+
`true`; native clients ask the user every time and never remember it,
6203+
because every machine that reaches the host can then use the port. A
6204+
server that cannot listen is `forward_host_unsupported`.
6205+
- **Reverse forwards are off by default.** `remote.startReverseForward`
6206+
takes the current remote preferences `document` as `preferences` and is
6207+
`reverse_forward_disabled` unless they allow reverse forwards; native
6208+
clients also ask the user before each one starts. The local side only ever
6209+
connects to `127.0.0.1`, then `::1`, so a host user cannot reach the local
6210+
network through it.
6211+
- **Once per rule.** Starting a rule that already runs returns that forward
6212+
with `created: false`, so a repeated click opens no second port: a local
6213+
forward by target, a host forward by host port (or any port when none is
6214+
asked), interfaces and target, a reverse forward by host port and local
6215+
port. A connection keeps at most 64 forwards of all kinds together; one
6216+
more is `forward_limit_reached` with `details.maximum`.
6217+
- **Lifetime.** `remote.stopForward` closes the port the forward listens
6218+
on; connections it already accepted run until either side closes them,
6219+
except a host forward's, which the host closes with its port. An unknown
6220+
id returns `stopped: false`. `remote.disconnect`, `remote.closeAll` and a
6221+
lost connection close every port the connection opened on either side,
6222+
and a reconnect reopens none of them. Requests on a
61716223
connection whose session ended are `connection_closed` and forget it, as
6172-
for the other commands. `connections` counts accepted local connections.
6224+
for the other commands.
61736225

61746226
#### Remote workspace trust
61756227

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1014,6 +1014,12 @@ pub enum RemoteCommand {
10141014
/// Forwards a local port to a port as the remote host sees it
10151015
/// (`remote.startForward`).
10161016
StartForward,
1017+
/// Makes the remote host listen on a port and connect it to another
1018+
/// server (`remote.startHostForward`).
1019+
StartHostForward,
1020+
/// Makes the remote host listen on a loopback port that reaches a port
1021+
/// on this machine (`remote.startReverseForward`).
1022+
StartReverseForward,
10171023
/// Stops one port forward and closes its local port (`remote.stopForward`).
10181024
StopForward,
10191025
/// Lists the running port forwards of one connection (`remote.forwards`).
@@ -1613,6 +1619,8 @@ impl CoreCommand {
16131619
"remote.workspaceTrust" => Some(Self::Remote(RemoteCommand::WorkspaceTrust)),
16141620
"remote.editWorkspaceTrust" => Some(Self::Remote(RemoteCommand::EditWorkspaceTrust)),
16151621
"remote.startForward" => Some(Self::Remote(RemoteCommand::StartForward)),
1622+
"remote.startHostForward" => Some(Self::Remote(RemoteCommand::StartHostForward)),
1623+
"remote.startReverseForward" => Some(Self::Remote(RemoteCommand::StartReverseForward)),
16161624
"remote.stopForward" => Some(Self::Remote(RemoteCommand::StopForward)),
16171625
"remote.forwards" => Some(Self::Remote(RemoteCommand::Forwards)),
16181626
"remote.parseForwardAddress" => Some(Self::Remote(RemoteCommand::ParseForwardAddress)),

0 commit comments

Comments
 (0)