跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

reversesshfs.go

374 行 · 11.7 KB历史下载
1package reversesshfs
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "html/template"
8 "io"
9 "os"
10 "os/exec"
11 "path"
12 "path/filepath"
13 "runtime"
14 "strconv"
15 "strings"
16 "sync/atomic"
17
18 "github.com/lima-vm/sshocker/pkg/ssh"
19 "github.com/lima-vm/sshocker/pkg/util"
20 "github.com/sirupsen/logrus"
21)
22
23type Driver = string
24
25const (
26 DriverAuto = Driver("auto") // Default
27 DriverBuiltin = Driver("builtin") // Legacy. Unrecommended.
28 DriverOpensshSftpServer = Driver("openssh-sftp-server") // More robust and secure. Recommended.
29)
30
31type ReverseSSHFS struct {
32 *ssh.SSHConfig
33 Driver Driver
34 OpensshSftpServerBinary string // used only when Driver == DriverOpensshSftpServer
35 LocalPath string
36 Host string
37 Port int
38 RemotePath string
39 Readonly bool
40 sshCmd *exec.Cmd
41 opensshSftpServerCmd *exec.Cmd
42 SSHFSAdditionalArgs []string
43
44 // ReadonlyNames makes a path read-only when any of its components is one of these names
45 // (compared case-insensitively). Requires DriverBuiltin on Linux, macOS, or Windows.
46 ReadonlyNames []string
47
48 rooted atomic.Pointer[rootedHandlers]
49}
50
51// ExpectRemove makes the next removal of hostPath requested by the remote, within a few seconds,
52// succeed without touching hostPath. It is used to relay a local deletion to the remote,
53// by removing the path there, which emits an inotify event on the remote.
54// It returns false, and the removal must not be relayed, when unsupported (not using DriverBuiltin
55// on Linux, macOS, or Windows), or when the remote itself just removed or moved away hostPath.
56func (rsf *ReverseSSHFS) ExpectRemove(hostPath string) bool {
57 h := rsf.rooted.Load()
58 if h == nil {
59 return false
60 }
61 return h.expectRemove(hostPath)
62}
63
64func (rsf *ReverseSSHFS) Prepare() error {
65 sshBinary := rsf.SSHConfig.Binary()
66 sshArgs := rsf.SSHConfig.Args()
67 if !path.IsAbs(rsf.RemotePath) {
68 return fmt.Errorf("unexpected relative path: %q", rsf.RemotePath)
69 }
70 if rsf.Port != 0 {
71 sshArgs = append(sshArgs, "-p", strconv.Itoa(rsf.Port))
72 }
73 sshArgs = append(sshArgs, rsf.Host, "--")
74 sshArgs = append(sshArgs, "mkdir", "-p", addQuotes(rsf.RemotePath))
75 sshCmd := exec.Command(sshBinary, sshArgs...)
76 logrus.Debugf("executing ssh for preparing sshfs: %s %v", sshCmd.Path, sshCmd.Args)
77 out, err := sshCmd.CombinedOutput()
78 if err != nil {
79 return fmt.Errorf("failed to mkdir %q (remote): %q: %w", rsf.RemotePath, string(out), err)
80 }
81 return nil
82}
83
84func DetectOpensshSftpServerBinary() string {
85 if exe, err := exec.LookPath("sftp-server"); err == nil {
86 return exe
87 }
88 homebrewSSHD := []string{
89 "/usr/local/sbin/sshd",
90 "/opt/homebrew/sbin/sshd",
91 }
92 for _, f := range homebrewSSHD {
93 // sshd is like "/usr/local/Cellar/openssh/8.9p1/sbin/sshd"
94 sshd, err := filepath.EvalSymlinks(f)
95 if err != nil {
96 continue
97 }
98 // local is like "/usr/local/Cellar/openssh"
99 local := filepath.Dir(filepath.Dir(sshd))
100 // sftpServer is like "/usr/local/Cellar/openssh/8.9p1/libexec/sftp-server"
101 sftpServer := filepath.Join(local, "libexec", "sftp-server")
102 if exe, err := exec.LookPath(sftpServer); err == nil {
103 return exe
104 }
105 }
106 if runtime.GOOS == "windows" {
107 // unix path is like "/usr/lib/ssh/sftp-server"
108 cygpathCmd := exec.Command("cygpath", "-w", "/usr/lib/ssh/sftp-server")
109 // windows path is like `C:\msys64\usr\lib\ssh\sftp-server.exe`
110 if out, err := cygpathCmd.Output(); err == nil {
111 sftpServer := strings.TrimSpace(string(out))
112 if exe, err := exec.LookPath(sftpServer); err == nil {
113 return exe
114 }
115 }
116 }
117 candidates := []string{
118 "/usr/libexec/sftp-server", // macOS, OpenWrt
119 "/usr/libexec/openssh/sftp-server", // Fedora
120 "/usr/lib/sftp-server", // Debian (symlink to openssh/sftp-server)
121 "/usr/lib/openssh/sftp-server", // Debian
122 "/usr/lib/ssh/sftp-server", // Alpine
123 }
124 for _, cand := range candidates {
125 if exe, err := exec.LookPath(cand); err == nil {
126 return exe
127 }
128 }
129 return ""
130}
131
132func DetectDriver(explicitOpensshSftpServerBinary string) (Driver, string, error) {
133 if explicitOpensshSftpServerBinary != "" {
134 exe, err := exec.LookPath(explicitOpensshSftpServerBinary)
135 if err != nil {
136 return "", "", err
137 }
138 return DriverOpensshSftpServer, exe, nil
139 }
140 exe := DetectOpensshSftpServerBinary()
141 if exe != "" {
142 return DriverOpensshSftpServer, exe, nil
143 }
144 return DriverBuiltin, "", nil
145}
146
147func (rsf *ReverseSSHFS) Start() error {
148 sshBinary := rsf.SSHConfig.Binary()
149 sshArgs := rsf.SSHConfig.Args()
150 if !filepath.IsAbs(rsf.LocalPath) && !path.IsAbs(rsf.LocalPath) {
151 return fmt.Errorf("unexpected relative path: %q", rsf.LocalPath)
152 }
153 if runtime.GOOS == "windows" && path.IsAbs(rsf.LocalPath) {
154 logrus.Infof("Accepting %q Unix path, assuming Cygwin/msys2 OpenSSH", rsf.LocalPath)
155 // Convert MSYS2 path to Windows native path
156 rsf.LocalPath = convertMSYS2Path(rsf.LocalPath)
157 logrus.Infof("Converted path for native Windows OpenSSH: %q", rsf.LocalPath)
158 }
159
160 if !path.IsAbs(rsf.RemotePath) {
161 return fmt.Errorf("unexpected relative path: %q", rsf.RemotePath)
162 }
163 if rsf.Port != 0 {
164 sshArgs = append(sshArgs, "-p", strconv.Itoa(rsf.Port))
165 }
166 sshArgs = append(sshArgs, rsf.Host, "--")
167 sshArgs = append(sshArgs, "sshfs", addQuotes(":"+rsf.LocalPath), addQuotes(rsf.RemotePath), "-o", "slave")
168 if rsf.Readonly {
169 sshArgs = append(sshArgs, "-o", "ro")
170 }
171 sshArgs = append(sshArgs, rsf.SSHFSAdditionalArgs...)
172 rsf.sshCmd = exec.Command(sshBinary, sshArgs...)
173 rsf.sshCmd.Stderr = os.Stderr
174 driver := rsf.Driver
175 opensshSftpServerBinary := rsf.OpensshSftpServerBinary
176 switch driver {
177 case DriverBuiltin, DriverOpensshSftpServer:
178 // NOP
179 case "", DriverAuto:
180 if len(rsf.ReadonlyNames) > 0 {
181 driver = DriverBuiltin
182 break
183 }
184 var err error
185 driver, opensshSftpServerBinary, err = DetectDriver(opensshSftpServerBinary)
186 if err != nil {
187 return fmt.Errorf("failed to choose driver automatically: %w", err)
188 }
189 logrus.Debugf("Chosen driver %q", driver)
190 default:
191 return fmt.Errorf("unknown driver %q", driver)
192 }
193 if len(rsf.ReadonlyNames) > 0 && driver != DriverBuiltin {
194 return fmt.Errorf("ReadonlyNames requires driver %q, got %q", DriverBuiltin, driver)
195 }
196 var (
197 builtinSftpServer interface{ Serve() error }
198 rooted *rootedHandlers
199 )
200 switch driver {
201 case DriverBuiltin:
202 stdinPipe, err := rsf.sshCmd.StdinPipe()
203 if err != nil {
204 return err
205 }
206 stdoutPipe, err := rsf.sshCmd.StdoutPipe()
207 if err != nil {
208 return err
209 }
210 stdio := &util.RWC{
211 ReadCloser: stdoutPipe,
212 WriteCloser: stdinPipe,
213 }
214 builtinSftpServer, rooted, err = newRootedServer(stdio, rsf.LocalPath, rsf.Readonly, rsf.ReadonlyNames)
215 rsf.rooted.Store(rooted)
216 if err != nil {
217 return err
218 }
219 case DriverOpensshSftpServer:
220 if opensshSftpServerBinary == "" {
221 opensshSftpServerBinary = DetectOpensshSftpServerBinary()
222 if opensshSftpServerBinary == "" {
223 return errors.New("no openssh sftp-server found")
224 }
225 }
226 logrus.Debugf("Using OpenSSH SFTP Server %q", opensshSftpServerBinary)
227 sftpServerArgs := []string{
228 // `-e` available since OpenSSH 5.4p1 (2010) https://github.com/openssh/openssh-portable/commit/7bee06ab
229 "-e",
230 // `-d` available since OpenSSH 6.2p1 (2013) https://github.com/openssh/openssh-portable/commit/502ab0ef
231 // NOTE: `-d` just chdirs the sftp server process to the specified directory.
232 // This is expected to be used in conjunction with chroot (in future), however, macOS does not support unprivileged chroot.
233 "-d", strings.ReplaceAll(rsf.LocalPath, "%", "%%"),
234 }
235 if rsf.Readonly {
236 // `-R` available since OpenSSH 5.4p1 (2010) https://github.com/openssh/openssh-portable/commit/db7bf825
237 sftpServerArgs = append(sftpServerArgs, "-R")
238 }
239 rsf.opensshSftpServerCmd = exec.Command(opensshSftpServerBinary, sftpServerArgs...)
240 rsf.opensshSftpServerCmd.Stderr = os.Stderr
241 var err error
242 rsf.opensshSftpServerCmd.Stdin, err = rsf.sshCmd.StdoutPipe()
243 if err != nil {
244 return err
245 }
246 rsf.sshCmd.Stdin, err = rsf.opensshSftpServerCmd.StdoutPipe()
247 if err != nil {
248 return err
249 }
250 }
251 logrus.Debugf("executing ssh for remote sshfs: %s %v", rsf.sshCmd.Path, rsf.sshCmd.Args)
252 if err := rsf.sshCmd.Start(); err != nil {
253 if rooted != nil {
254 rooted.Close()
255 }
256 return err
257 }
258 logrus.Debugf("starting sftp server for %v", rsf.LocalPath)
259 switch driver {
260 case DriverBuiltin:
261 go func() {
262 if rooted != nil {
263 defer rooted.Close()
264 }
265 if srvErr := builtinSftpServer.Serve(); srvErr != nil {
266 if errors.Is(srvErr, io.EOF) {
267 logrus.WithError(srvErr).Debugf("sftp server for %v exited with EOF (negligible)", rsf.LocalPath)
268 } else {
269 logrus.WithError(srvErr).Errorf("sftp server for %v exited", rsf.LocalPath)
270 }
271 }
272 }()
273 case DriverOpensshSftpServer:
274 logrus.Debugf("executing OpenSSH SFTP Server: %s %v", rsf.opensshSftpServerCmd.Path, rsf.opensshSftpServerCmd.Args)
275 if err := rsf.opensshSftpServerCmd.Start(); err != nil {
276 return err
277 }
278 }
279 logrus.Debugf("waiting for remote ready")
280 if err := rsf.waitForRemoteReady(); err != nil {
281 // not a fatal error
282 logrus.WithError(err).Warnf("failed to confirm whether %v [remote] is successfully mounted", rsf.RemotePath)
283 }
284 return nil
285}
286
287func addQuotes(input string) string {
288 input = strconv.Quote(input)
289 // exec.Command on Windows would escape wrapping double quotes in a way, which is not compatible
290 // with passing arguments into bash shell over ssh, replacing with single quotes as a workaround.
291 if runtime.GOOS == "windows" {
292 input = strings.TrimPrefix(input, "\"")
293 input = strings.TrimSuffix(input, "\"")
294 return fmt.Sprintf(`'%s'`, input)
295 }
296 return input
297}
298
299func (rsf *ReverseSSHFS) waitForRemoteReady() error {
300 scriptName := "wait-for-remote-ready"
301 scriptTemplate := `#!/bin/sh
302set -eu
303dir="{{.Dir}}"
304max_trial="{{.MaxTrial}}"
305LANG=C
306LC_ALL=C
307export LANG LC_ALL
308i=0
309while : ; do
310 # FIXME: not really robust
311 # spaces in file names are encoded as '\040' in the mount table
312 if mount | sed 's/\\040/ /g' | grep "on ${dir}" | egrep -qw "fuse.sshfs|osxfuse"; then
313 echo '{"return":{}}'
314 exit 0
315 fi
316 sleep 1
317 if [ $i -ge ${max_trial} ]; then
318 echo >&2 "sshfs does not seem to be mounted on ${dir}"
319 exit 1
320 fi
321 i=$((i + 1))
322done
323`
324 t, err := template.New(scriptName).Parse(scriptTemplate)
325 if err != nil {
326 return err
327 }
328 m := map[string]string{
329 // rsf.RemotePath should have been verified during rsf.Prepare()
330 "Dir": rsf.RemotePath,
331 "MaxTrial": "30",
332 }
333 var b bytes.Buffer
334 if err := t.Execute(&b, m); err != nil {
335 return err
336 }
337 script := b.String()
338 logrus.Debugf("generated script %q with map %v: %q", scriptName, m, script)
339 stdout, stderr, err := ssh.ExecuteScript(rsf.Host, rsf.Port, rsf.SSHConfig, script, scriptName)
340 logrus.Debugf("executed script %q, stdout=%q, stderr=%q, err=%v", scriptName, stdout, stderr, err)
341 return err
342}
343
344func (rsf *ReverseSSHFS) Close() error {
345 if rsf.sshCmd != nil {
346 logrus.Debugf("killing processes for remote sshfs: %s %v", rsf.sshCmd.Path, rsf.sshCmd.Args)
347 }
348 var errors []error
349 for _, cmd := range []*exec.Cmd{rsf.sshCmd, rsf.opensshSftpServerCmd} {
350 if cmd == nil || cmd.Process == nil {
351 continue
352 }
353 if err := cmd.Process.Kill(); err != nil {
354 errors = append(errors, err)
355 }
356 // Reap it, and close its pipes. The error is the kill itself, or a second Close.
357 _ = cmd.Wait()
358 }
359 if len(errors) > 0 {
360 return fmt.Errorf("%v", errors)
361 }
362 return nil
363}
364
365// convertMSYS2Path converts an MSYS2 style path (e.g., /c/Users/...) to a Windows native path
366func convertMSYS2Path(localPath string) string {
367 if len(localPath) >= 3 && localPath[0] == '/' && localPath[2] == '/' {
368 driveLetter := strings.ToUpper(string(localPath[1]))
369 // Explicitly force backslashes, bypassing WSL/Linux environment quirks
370 remainingPath := strings.ReplaceAll(localPath[2:], "/", "\\")
371 return driveLetter + ":" + remainingPath
372 }
373 return localPath
374}