Skip to content

Commit 0b201bc

Browse files
committed
fix(remote): 理清远程服务的容量与失败边界(含 S27)
- S27:本地端口转发只允许监听 loopback 地址,其他地址返回 InvalidInput; 每个转发最多同时桥接 64 个连接,多出的连接留在系统监听队列里等待; 移除转发时唤醒 acceptor 最多等 1 秒,转发线程起不来不再 panic。 - 服务端:同一会话最多 256 个打开的 tunnel,超出回 BUSY。进程、终端、 tunnel、watch、walk 需要的线程都先启动、再登记资源(threads::Parked), 主机起不了线程时回 BUSY,不留下表项、子进程或 watch 后端;Linux inotify 后端的线程也先于目录注册启动。 - worker panic 会归还名额;daemon 里单个连接建立失败只关闭该连接, 不再结束整个会话和其中运行的程序;relay 线程起不来时返回错误而不是 panic。 - 客户端会话、测试命令、服务端 helper 的线程启动失败时,杀掉并回收子进程。 - 协议文档补齐 sessionToken 与 INVALID_SESSION_TOKEN、空闲超时规则、 日志权限与轮转、BUSY 的含义和适用范围、服务端安装校验、端口转发只走 loopback 与连接上限。
1 parent 43e3f27 commit 0b201bc

21 files changed

Lines changed: 1119 additions & 463 deletions

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

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,14 @@ clients. Design rationale lives in
1717
`<key>` is 1–64 characters from `[A-Za-z0-9._-]`. The daemon keeps its
1818
socket, lock and log under `<dir>` (default `$HOME/.lithe-server`) in
1919
directories only the user can access, and rejects peers with another user
20-
id. A session has one client at a time: a new connection replaces the
21-
current one. A session without a client ends after its idle timeout.
22-
Launchers serialize socket rechecking and daemon creation with a per-identity
20+
id. A session has one client at a time: a new connection that presents the
21+
session token (see below) replaces the current one. The idle timeout runs
22+
only while the session has neither a client nor running processes or open
23+
terminals; it is 10 minutes unless `server.hello` requests another with
24+
`idleTimeoutSeconds`, at most 24 hours, and the latest request applies. A
25+
connection the daemon cannot set up is closed without ending the session.
26+
The daemon log is created `0600`, never through a symbolic link, and moves to
27+
`<name>.log.1` once it reaches 1 MiB. Launchers serialize socket rechecking and daemon creation with a per-identity
2328
`.start` advisory lock in the private `run/` directory, bounded by the existing
2429
startup deadline. The lock is released when its owning descriptor closes; its
2530
inode is retained so concurrent waiters cannot lock different files. This keeps
@@ -35,7 +40,11 @@ a redundant launcher from restarting an explicitly closed session.
3540
3. Closing the client-to-server stream is a disconnect.
3641

3742
The server never listens on a network port; all traffic, including tunnels,
38-
uses this stream.
43+
uses this stream. Local port forwards are the client's: the reference client
44+
listens on loopback addresses only, because a remote development server
45+
usually has no authentication of its own, and bridges at most 64 connections
46+
per forward, leaving further ones in the system's listen queue until one
47+
ends. Other clients should keep both rules.
3948

4049
## Messages
4150

@@ -60,6 +69,12 @@ uses this stream.
6069
`terminal.write`, `terminal.resize`, `tunnel.write`, `tunnel.close`,
6170
`walk.cancel` — are applied in the order sent. Potentially blocking creation
6271
and teardown run on workers; other requests may complete in any order.
72+
- At most 64 requests run on workers at once; a further one fails with
73+
`BUSY` and changes nothing. When the host cannot start a thread that a
74+
request or a new process, terminal, tunnel, watch or walk needs, the
75+
request fails with `BUSY` the same way, before it has any effect.
76+
`environment.resolve` instead falls back to the server's environment and
77+
names the failure in `diagnostics`.
6378
- A `process.kill`, `terminal.close`, or `watch.stop` received while the same
6479
resource is starting records teardown before worker scheduling. The creating
6580
worker applies it after publication, even if the close worker is rejected as
@@ -88,7 +103,7 @@ subscribe before creating the resource.
88103

89104
| Method | Params | Result |
90105
| --- | --- | --- |
91-
| `server.hello` | `protocolVersion`, `clientName`, `idleTimeoutSeconds?` | `protocolVersion`, `serverVersion`, `host`, `session` |
106+
| `server.hello` | `protocolVersion`, `clientName`, `idleTimeoutSeconds?`, `sessionToken?` | `protocolVersion`, `serverVersion`, `host`, `session`; `INVALID_SESSION_TOKEN` closes the connection |
92107
| `server.resume` | `afterSeq?` | `truncated`; then every kept event after `afterSeq`, followed by live events |
93108
| `server.ack` | `seq` | `null`; events up to `seq` may be forgotten |
94109
| `server.shutdown` | — | `null`; the session ends |
@@ -125,7 +140,7 @@ subscribe before creating the resource.
125140
| `terminal.resize` | `terminalId`, `columns`, `rows` | `null` |
126141
| `terminal.close` | `terminalId` | `null`; `SIGHUP` to its session, `SIGKILL` after 2 s |
127142
| `environment.resolve` | `refresh` | `environment`, `source`, `diagnostics?` |
128-
| `tunnel.open` | `tunnelId`, `target` (`{kind: tcp, host, port}` / `{kind: unix, path}`) | `null`; `CONNECT_FAILED` on failure |
143+
| `tunnel.open` | `tunnelId`, `target` (`{kind: tcp, host, port}` / `{kind: unix, path}`) | `null`; `CONNECT_FAILED` on failure; `BUSY` while the session has 256 open tunnels |
129144
| `tunnel.write` | `tunnelId`, `data` | `null`; `BUSY` when the peer stops reading |
130145
| `tunnel.shutdownWrite` | `tunnelId` | `null`; queued data is sent, then the write side is shut down; replies keep arriving |
131146
| `tunnel.close` | `tunnelId` | `null`; aborts both directions, queued data is discarded |
@@ -229,7 +244,18 @@ changes were lost and the client must rescan the watched tree.
229244
## Event delivery and persistent sessions
230245

231246
`server.hello` returns `session` with `persistent`, `resumed`,
232-
`nextResourceId` and `lastEventSeq`. The session keeps every event until the
247+
`nextResourceId`, `lastEventSeq` and, for a persistent session,
248+
`sessionToken`: 128 random bits, hex encoded, fixed for the whole session.
249+
The first client of a persistent session is admitted whatever it presents;
250+
every later `server.hello` must present that token as `sessionToken`. A
251+
missing or different token fails with `INVALID_SESSION_TOKEN`, the server
252+
closes that connection, and the attached client is not disturbed. The socket
253+
already admits only the host account, so the token keeps other programs of
254+
that account, or a second window reusing the key, from taking over the
255+
session and its buffered output. Clients keep it in secret storage and never
256+
log it; the server compares it in constant time.
257+
258+
The session keeps every event until the
233259
client acknowledges it with `server.ack` (clients acknowledge periodically,
234260
for example every 256 events), up to 8 MiB; beyond that the oldest kept
235261
events are dropped. Written to a socket is not received: when a connection
@@ -262,13 +288,15 @@ list. Clients branch on these facts, never on `os` alone, and check
262288

263289
## Error codes
264290

265-
`PROTOCOL_MISMATCH`, `INVALID_REQUEST`, `UNKNOWN_METHOD`, `INVALID_PATH`,
291+
`PROTOCOL_MISMATCH`, `INVALID_SESSION_TOKEN`, `INVALID_REQUEST`,
292+
`UNKNOWN_METHOD`, `INVALID_PATH`,
266293
`NOT_FOUND`, `PERMISSION_DENIED`, `ALREADY_EXISTS`, `NOT_A_DIRECTORY`,
267294
`IS_A_DIRECTORY`, `DIRECTORY_NOT_EMPTY`, `CONFLICT`, `TOO_LARGE`,
268295
`UNKNOWN_RESOURCE`, `RESOURCE_ID_IN_USE`, `SPAWN_FAILED`, `CONNECT_FAILED`,
269296
`BUSY`, `UNSUPPORTED`, `IO`. Clients additionally produce `TIMEOUT` and
270297
`DISCONNECTED` locally. Messages are for people; OS error numbers stay in
271-
`details`.
298+
`details`. `BUSY` always means a capacity limit that may clear: retrying
299+
later is safe because the failed request changed nothing.
272300

273301
## Compatibility
274302

@@ -281,5 +309,11 @@ than reaching an older one.
281309
## Server identity
282310

283311
`lithe-remote-server --identity` prints one JSON line with `serverVersion`,
284-
`protocolVersion` and `sha256` of the executable itself. Bootstrappers reuse an
285-
installed server only when the hash matches the artifact they ship.
312+
`protocolVersion` and `sha256` of the executable itself. A binary is never
313+
trusted to report its own hash: bootstrappers reuse an installed server only
314+
when the host's own `sha256sum` or `shasum` computes the hash of the artifact
315+
they ship, and only from install directories that are not symbolic links,
316+
belong to the remote user and are not writable by the group or other users.
317+
On a host without a hash tool, a fresh upload is accepted when its size
318+
matches and `--identity` reports the expected hash, and it is uploaded again
319+
on every connection instead of being reused.

‎rust/crates/remote/src/client/command.rs‎

Lines changed: 47 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! Those tests drive real shells, so the module exists on Unix hosts only.
33
44
use std::io::{self, Read};
5-
use std::process::{Command, Stdio};
5+
use std::process::{Child, Command, Stdio};
66
use std::sync::mpsc::{self, Receiver};
77
use std::sync::{Arc, Mutex};
88
use std::thread;
@@ -49,25 +49,25 @@ pub fn run(argv: &[String], timeout: Duration) -> io::Result<CommandOutput> {
4949
.stdout(Stdio::piped())
5050
.stderr(Stdio::piped())
5151
.spawn()?;
52-
let stdout = capture(child.stdout.take());
53-
let stderr = capture(child.stderr.take());
52+
let captures =
53+
capture(child.stdout.take()).and_then(|stdout| Ok((stdout, capture(child.stderr.take())?)));
54+
let (stdout, stderr) = match captures {
55+
Ok(captures) => captures,
56+
Err(error) => {
57+
// Without a reader the child could block on a full pipe; a
58+
// started stdout reader ends once the child is gone.
59+
stop(&mut child);
60+
return Err(error);
61+
}
62+
};
5463

5564
let deadline = Instant::now() + timeout;
5665
let status = loop {
5766
if let Some(status) = child.try_wait()? {
5867
break status;
5968
}
6069
if Instant::now() >= deadline {
61-
crate::failure_log::kill(
62-
"remote.client.operation_failed",
63-
"process_kill",
64-
child.kill(),
65-
);
66-
crate::failure_log::io(
67-
"remote.client.operation_failed",
68-
"process_wait",
69-
child.wait(),
70-
);
70+
stop(&mut child);
7171
return Err(io::Error::new(
7272
io::ErrorKind::TimedOut,
7373
format!(
@@ -112,28 +112,44 @@ impl Capture {
112112
}
113113
}
114114

115-
fn capture(pipe: Option<impl Read + Send + 'static>) -> Capture {
115+
/// Kills and reaps a child that will not be waited for normally.
116+
fn stop(child: &mut Child) {
117+
crate::failure_log::kill(
118+
"remote.client.operation_failed",
119+
"process_kill",
120+
child.kill(),
121+
);
122+
crate::failure_log::io(
123+
"remote.client.operation_failed",
124+
"process_wait",
125+
child.wait(),
126+
);
127+
}
128+
129+
fn capture(pipe: Option<impl Read + Send + 'static>) -> io::Result<Capture> {
116130
let bytes = Arc::new(Mutex::new(Vec::new()));
117131
let (finished_sender, finished) = mpsc::channel();
118132
let shared = Arc::clone(&bytes);
119-
thread::spawn(move || {
120-
if let Some(mut pipe) = pipe {
121-
let mut buffer = [0_u8; 8192];
122-
loop {
123-
match pipe.read(&mut buffer) {
124-
Ok(0) | Err(_) => break,
125-
Ok(read) => {
126-
let mut captured = shared
127-
.lock()
128-
.unwrap_or_else(|poisoned| poisoned.into_inner());
129-
let room = CAPTURE_LIMIT_BYTES.saturating_sub(captured.len());
130-
captured.extend_from_slice(&buffer[..read.min(room)]);
133+
thread::Builder::new()
134+
.name("remote-command-output".into())
135+
.spawn(move || {
136+
if let Some(mut pipe) = pipe {
137+
let mut buffer = [0_u8; 8192];
138+
loop {
139+
match pipe.read(&mut buffer) {
140+
Ok(0) | Err(_) => break,
141+
Ok(read) => {
142+
let mut captured = shared
143+
.lock()
144+
.unwrap_or_else(|poisoned| poisoned.into_inner());
145+
let room = CAPTURE_LIMIT_BYTES.saturating_sub(captured.len());
146+
captured.extend_from_slice(&buffer[..read.min(room)]);
147+
}
131148
}
132149
}
133150
}
134-
}
135-
// log-exempt: User cancellation: the command caller already stopped collecting output and no longer waits for the capture completion notification.
136-
let _ = finished_sender.send(());
137-
});
138-
Capture { bytes, finished }
151+
// log-exempt: User cancellation: the command caller already stopped collecting output and no longer waits for the capture completion notification.
152+
let _ = finished_sender.send(());
153+
})?;
154+
Ok(Capture { bytes, finished })
139155
}

0 commit comments

Comments
 (0)