Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Linux 静态版用 Rust 自带的 `rust-lld` 链接,在 macOS 和 Linux 上都
- **路径**:协议里的路径是远端主机上的绝对路径。这一层是文件系统和进程的适配器,工具链、终端和调试器都需要真实的主机路径;以工作区为根的相对标识在这一层之上构造。
- **错误**:错误码稳定(例如 `NOT_FOUND`、`CONFLICT`、`DIRECTORY_NOT_EMPTY`),客户端按错误码分支。`message` 只给人看,OS 错误号放在 `details` 里。
- **兼容**:不兼容的修改才提升协议版本号。新增方法通过 `features` 列表声明,客户端先查列表再调用。
- **只走标准输入输出**:服务不监听任何 TCP 端口,所以共享主机上的其他用户连不进来。端口转发以后也走这条流。
- **只走标准输入输出**:服务的协议通道不监听任何 TCP 端口,所以共享主机上的其他用户连不进协议。端口转发也走这条流。唯一的例外是 #2231 §8 设计的主机侧转发规则(T3 主机端口到其他服务器、T4 反向转发,尚未实现):服务只在用户建立并确认的规则存在期间按规则打开监听,默认只绑定主机回环地址(#2231 S20、S27、S29)。

### 文件和进程的语义

Expand Down Expand Up @@ -178,7 +178,7 @@ inotify 的坑:目录是逐个注册的,新建目录要在收到创建事件
- **终端**:用伪终端(PTY)运行,被启动的程序成为新会话的首进程,并把这个终端设为控制终端,和 SSH 登录时完全一样。所以作业控制、`Ctrl-C`、窗口大小变化(内核会发 `SIGWINCH`)都符合用户习惯。默认程序是用户的登录 shell,按 POSIX 惯例在 `argv[0]` 前加 `-`,sh、bash、zsh、fish、csh 都认。关闭终端相当于关掉终端窗口:向它的整个会话发 `SIGHUP`,2 秒后还在的发 `SIGKILL`。
- **登录环境**:经 SSH 或 `docker exec` 执行的命令,拿到的环境往往很少,nvm、SDKMAN、Homebrew 加进 `PATH` 的路径都不在里面。服务会用用户自己的 shell 以交互式登录 shell 启动一次,让它运行 `lithe-remote-server --print-environment`,读取它最终得到的环境,并在会话内缓存。用服务自己的二进制输出环境,可以避开 GNU 和 BSD `env` 的参数差异;每次尝试最多等 10 秒,profile 卡住(例如启动 tmux)也不会挂住服务;交互式失败就退回非交互登录 shell,再失败就用服务自己的环境,并在 `diagnostics` 里说明原因。`process.spawn` 指定 `environment: login` 就会用这个环境作为基础。
- **复制**:`fs.copy` 拒绝把文件复制到它自己身上(同一路径、经过符号链接的任一方向、或者是硬链接),也拒绝在解析链接之后把目录复制进它自己。覆盖写入会在读取源文件之前先截断目标,第一版因此会把源文件清空。socket、FIFO 和设备文件从不复制:作为复制对象本身时返回 `UNSUPPORTED`,在目录树里时跳过并计数,因为打开 FIFO 读取可能永远阻塞。
- **端口**:隧道把远端的 TCP 端口或 Unix socket(Docker、数据库的 socket)接到协议流里。客户端的 `PortForward` 在本地监听,每个连接开一条隧道,所以浏览器访问 `127.0.0.1:<本地端口>` 就能到达只监听在远端回环地址上的服务。本地客户端发完请求后半关闭时(HTTP/1.0、`nc -N`),转发用 `tunnel.shutdownWrite`:先把排队的数据写完,再只关闭写入端,远端的响应照常返回;`tunnel.close` 只用于中止。`ports.listening` 列出远端正在监听的端口,为以后的自动转发做准备。
- **端口**:隧道把远端的 TCP 端口或 Unix socket(Docker、数据库的 socket)接到协议流里。客户端的 `PortForward` 在本地监听,每个连接开一条隧道,所以浏览器访问 `127.0.0.1:<本地端口>` 就能到达只监听在远端回环地址上的服务。本地客户端发完请求后半关闭时(HTTP/1.0、`nc -N`),转发用 `tunnel.shutdownWrite`:先把排队的数据写完,再只关闭写入端,远端的响应照常返回;`tunnel.close` 只用于中止。`ports.listening` 列出远端正在监听的端口,桌面端的“端口”工具窗口用它列出主机上的端口,默认不自动转发。转发目标的输入(端口、`主机:端口`、网址)由 Core 的 `remote.parseForwardAddress` 解析。转发按“在哪一侧监听、由哪一侧连接哪个目标”建模为四类规则(#2231 §8 D10):T1 本机到主机回环、T2 本机到主机能访问的其他服务器(已实现);T3 主机端口到其他服务器、T4 反向转发(已设计,未实现)。T3 在主机上完成转发,数据不绕回本机;T4 默认关闭。

### 后续阶段

Expand Down Expand Up @@ -289,7 +289,7 @@ M2 接入“打开远程文件夹”时,SSH 连接的配置界面参考用户

- 不要在功能代码里拼 `ssh host 'mvn package'`。所有远端执行都走 `process.spawn`。
- 不要为了“远程 Mac”在客户端写 `if os == macos`。缺少的事实应该补进能力描述。
- 不要让服务监听 TCP 端口,也不要把服务装到其他用户可写的目录。
- 不要让服务为自己的协议监听 TCP 端口,也不要把服务装到其他用户可写的目录。主机侧转发规则的监听只按用户确认的规则打开(见“协议的几条硬规则”)。
- 不要在 SSH 跳转后面传入用户提供的任意字符串(例如带 `'` 的路径)。把它放进协议请求里,不要放在命令行里。

## 考虑过的备选方案
Expand Down
6 changes: 6 additions & 0 deletions desktop/internal/core/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ const (
CodeTimedOut ErrorCode = "timed_out"
// CodeConnectionClosed means a long-lived connection named by the request is closed.
CodeConnectionClosed ErrorCode = "connection_closed"
// CodeForwardTargetNotConfirmed means remote.startForward named a target outside the host's
// loopback interface the user did not confirm (S28); nothing was forwarded.
CodeForwardTargetNotConfirmed ErrorCode = "forward_target_not_confirmed"
// CodeForwardLimitReached means the session already runs as many forwards as Core allows;
// details carry the maximum.
CodeForwardLimitReached ErrorCode = "forward_limit_reached"
// CodeRemoteServerInvalid means the remote server build for the host's platform could not be
// read, or its SHA-256 is not the one the application's manifest names; nothing was sent to
// the host.
Expand Down
132 changes: 132 additions & 0 deletions desktop/internal/core/remote_forward.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package core

import "context"

// RemoteForward is one forward of a session: a listener on this computer's loopback interface
// whose connections Core carries over the session to a port as the host sees it. Only this
// computer's processes can reach the listener (S27), and the host never reaches back (S29).
type RemoteForward struct {
// ID names the forward to RemoteStopForward; it is unique within the session.
ID uint64 `json:"id"`
// LocalHost and LocalPort are where the forward listens on this computer; LocalHost is
// always a loopback address.
LocalHost string `json:"localHost"`
LocalPort uint16 `json:"localPort"`
// RequestedLocalPort is the local port the forward was asked for, absent when any was
// accepted; LocalPortChanged reports that it was taken and the system chose LocalPort.
RequestedLocalPort *uint16 `json:"requestedLocalPort,omitempty"`
LocalPortChanged bool `json:"localPortChanged"`
// TargetHost and TargetPort are the forward's target as the host resolves it, and
// LoopbackTarget reports that the target is on the host's own loopback interface.
TargetHost string `json:"targetHost"`
TargetPort uint16 `json:"targetPort"`
LoopbackTarget bool `json:"loopbackTarget"`
// Connections is the number of connections the forward carries now.
Connections uint64 `json:"connections"`
}

// RemoteForwardTarget is what RemoteStartForward forwards to.
type RemoteForwardTarget struct {
// Host is an IP address, with or without brackets for IPv6, or a name the host resolves,
// such as localhost; Port is the port there.
Host string `json:"targetHost"`
Port uint16 `json:"targetPort"`
// LocalPort is the local port to listen on; 0 lets the system choose one. A taken port is
// replaced by one the system chooses, which the forward reports as LocalPortChanged.
LocalPort uint16 `json:"localPort,omitempty"`
// AllowNonLoopback records that the user confirmed a target outside the host's loopback
// interface; without it such a target fails with CodeForwardTargetNotConfirmed (S28).
AllowNonLoopback bool `json:"allowNonLoopbackTarget,omitempty"`
}

// RemoteListeningPort is a TCP port listening on the host.
type RemoteListeningPort struct {
// Address is the bound address as the host reports it, such as 127.0.0.1, :: or 0.0.0.0.
Address string `json:"address"`
Port uint16 `json:"port"`
// PID and Process are the process that holds the socket and its command name, which Linux
// shortens to 15 bytes; both are absent for a process the server's user cannot inspect.
PID uint32 `json:"pid,omitempty"`
Process string `json:"process,omitempty"`
}

// RemoteStartForward forwards a local port to target over the session sessionID. created is
// false when a forward to the same target already ran: forward is then that forward, unchanged.
// A target outside the host's loopback interface that the user did not confirm fails with
// CodeForwardTargetNotConfirmed, a session at its limit with CodeForwardLimitReached, an invalid
// target with CodeInvalidRequest and a broken or unknown session with CodeConnectionClosed.
func (c *Client) RemoteStartForward(ctx context.Context, sessionID string, target RemoteForwardTarget) (forward RemoteForward, created bool, err error) {
var result struct {
Forward RemoteForward `json:"forward"`
Created bool `json:"created"`
}
err = c.Execute(ctx, "remote.startForward", struct {
SessionID string `json:"sessionId"`
RemoteForwardTarget
}{sessionID, target}, &result)
if err != nil {
return RemoteForward{}, false, err
}
return result.Forward, result.Created, nil
}

// RemoteStopForward stops the forward id of the session sessionID and closes its connections;
// stopped is false when the session has no such forward.
func (c *Client) RemoteStopForward(ctx context.Context, sessionID string, id uint64) (stopped bool, err error) {
var result struct {
Stopped bool `json:"stopped"`
}
err = c.Execute(ctx, "remote.stopForward", struct {
SessionID string `json:"sessionId"`
ForwardID uint64 `json:"forwardId"`
}{sessionID, id}, &result)
return result.Stopped, err
}

// RemoteForwards lists the running forwards of the session sessionID by id. A session that ends
// stops all of them.
func (c *Client) RemoteForwards(ctx context.Context, sessionID string) ([]RemoteForward, error) {
var result struct {
Forwards []RemoteForward `json:"forwards"`
}
err := c.Execute(ctx, "remote.forwards", struct {
SessionID string `json:"sessionId"`
}{sessionID}, &result)
return result.Forwards, err
}

// RemoteListeningPorts lists the TCP ports listening on the host of the session sessionID,
// sorted by address and port.
func (c *Client) RemoteListeningPorts(ctx context.Context, sessionID string) ([]RemoteListeningPort, error) {
var result struct {
Ports []RemoteListeningPort `json:"ports"`
}
err := c.RemoteHostRequest(ctx, sessionID, "ports.listening", nil, &result)
return result.Ports, err
}

// RemoteForwardAddress is an address the user typed into the Ports window, as a forward target:
// TargetHost and TargetPort are what the host dials, TargetHost without brackets and a name in
// lower case. Scheme and Path come only from an address written as a URL, which the window opens
// the same way: Scheme in lower case, and Path what follows the host and port, its query and
// fragment included, empty when that is empty or "/".
type RemoteForwardAddress struct {
TargetHost string `json:"targetHost"`
TargetPort uint16 `json:"targetPort"`
Scheme string `json:"scheme,omitempty"`
Path string `json:"path,omitempty"`
}

// RemoteParseForwardAddress reads text, a port alone (on localhost), host:port with brackets
// around an IPv6 host, or a URL, whose scheme gives the port when it names none (80 for http and
// ws, 443 for https and wss). A refused address fails with CodeInvalidRequest, and
// RemoteConnectionFieldError names the field text and the reason: empty, tooLong, malformed,
// scheme, credentials (a user name or password, refused rather than kept), host or port. Nothing
// is resolved or contacted, and no session is needed.
func (c *Client) RemoteParseForwardAddress(ctx context.Context, text string) (RemoteForwardAddress, error) {
var address RemoteForwardAddress
err := c.Execute(ctx, "remote.parseForwardAddress", struct {
Text string `json:"text"`
}{text}, &address)
return address, err
}
30 changes: 30 additions & 0 deletions desktop/internal/core/remote_helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,36 @@ func TestRemoteParseAddressSplitsTheFields(t *testing.T) {
}
}

// A port, host:port or URL typed into the Ports window becomes a forward target; a URL keeps its
// scheme and path and gives its default port, and a user name or password is refused by reason.
func TestRemoteParseForwardAddressReadsPortsAndURLs(t *testing.T) {
client := NewClient()
ctx := testContext(t)
cases := map[string]RemoteForwardAddress{
"3000": {TargetHost: "localhost", TargetPort: 3000},
"10.0.0.5:9000": {TargetHost: "10.0.0.5", TargetPort: 9000},
"[::1]:5432": {TargetHost: "::1", TargetPort: 5432},
"HTTPS://Build.Example/app?x=1": {TargetHost: "build.example", TargetPort: 443, Scheme: "https", Path: "/app?x=1"},
"http://localhost:3000/": {TargetHost: "localhost", TargetPort: 3000, Scheme: "http"},
}
for text, want := range cases {
if got, err := client.RemoteParseForwardAddress(ctx, text); err != nil || got != want {
t.Errorf("address %q = %+v, err = %v, want %+v", text, got, err, want)
}
}
for text, reason := range map[string]string{
"https://dev:secret@build.example": "credentials",
"postgres://build.example": "port",
"not a port": "malformed",
"70000": "port",
} {
_, err := client.RemoteParseForwardAddress(ctx, text)
if field, got, ok := RemoteConnectionFieldError(err); !ok || field != "text" || got != reason {
t.Errorf("address #%d: field %q, reason %q, want text and %q", len(text), field, got, reason)
}
}
}

// The effective values name where each comes from: the connection, the SSH configuration or the
// default.
func TestRemoteEffectiveSettingsNameTheirSources(t *testing.T) {
Expand Down
12 changes: 12 additions & 0 deletions desktop/internal/core/remote_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) {
if _, saved, err := client.RemoteWriteFile(ctx, "no-such-session", "/srv/repo/README.md", []byte("text"), &RemoteFileVersion{Size: 4, ModifiedMs: &modified}); saved || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("writeFile = %v, %v, want connection_closed", saved, err)
}
if _, created, err := client.RemoteStartForward(ctx, "no-such-session", RemoteForwardTarget{Host: "127.0.0.1", Port: 8080}); created || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("startForward = %v, %v, want connection_closed", created, err)
}
if stopped, err := client.RemoteStopForward(ctx, "no-such-session", 1); stopped || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("stopForward = %v, %v, want connection_closed", stopped, err)
}
if _, err := client.RemoteForwards(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("forwards = %v, want connection_closed", err)
}
if _, err := client.RemoteListeningPorts(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed {
t.Fatalf("ports.listening = %v, want connection_closed", err)
}
}

// A context without its remote workspace sends requests that compute from their payload as
Expand Down
2 changes: 2 additions & 0 deletions desktop/internal/i18n/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ type ToolMessages struct {
Debug string
Notifications string
Background string
// Ports names the tool window of a remote workspace that lists the host's ports and forwards.
Ports string
// ToolWindows names the stripe button that lists the stripe buttons the user hid.
ToolWindows string
// DragHint tells assistive technology that a toolbar item can be dragged elsewhere.
Expand Down
Loading
Loading