| 1 | package reversesshfs |
| 2 | |
| 3 | import ( |
| 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 | |
| 23 | type Driver = string |
| 24 | |
| 25 | const ( |
| 26 | DriverAuto = Driver("auto") |
| 27 | DriverBuiltin = Driver("builtin") |
| 28 | DriverOpensshSftpServer = Driver("openssh-sftp-server") |
| 29 | ) |
| 30 | |
| 31 | type ReverseSSHFS struct { |
| 32 | *ssh.SSHConfig |
| 33 | Driver Driver |
| 34 | OpensshSftpServerBinary string |
| 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 | |
| 45 | |
| 46 | ReadonlyNames []string |
| 47 | |
| 48 | rooted atomic.Pointer[rootedHandlers] |
| 49 | } |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | func (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 | |
| 64 | func (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 | |
| 84 | func 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 | |
| 94 | sshd, err := filepath.EvalSymlinks(f) |
| 95 | if err != nil { |
| 96 | continue |
| 97 | } |
| 98 | |
| 99 | local := filepath.Dir(filepath.Dir(sshd)) |
| 100 | |
| 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 | |
| 108 | cygpathCmd := exec.Command("cygpath", "-w", "/usr/lib/ssh/sftp-server") |
| 109 | |
| 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", |
| 119 | "/usr/libexec/openssh/sftp-server", |
| 120 | "/usr/lib/sftp-server", |
| 121 | "/usr/lib/openssh/sftp-server", |
| 122 | "/usr/lib/ssh/sftp-server", |
| 123 | } |
| 124 | for _, cand := range candidates { |
| 125 | if exe, err := exec.LookPath(cand); err == nil { |
| 126 | return exe |
| 127 | } |
| 128 | } |
| 129 | return "" |
| 130 | } |
| 131 | |
| 132 | func 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 | |
| 147 | func (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 | |
| 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 | |
| 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 | |
| 229 | "-e", |
| 230 | |
| 231 | NOTE: |
| 232 | |
| 233 | "-d", strings.ReplaceAll(rsf.LocalPath, "%", "%%"), |
| 234 | } |
| 235 | if rsf.Readonly { |
| 236 | |
| 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 | |
| 282 | logrus.WithError(err).Warnf("failed to confirm whether %v [remote] is successfully mounted", rsf.RemotePath) |
| 283 | } |
| 284 | return nil |
| 285 | } |
| 286 | |
| 287 | func addQuotes(input string) string { |
| 288 | input = strconv.Quote(input) |
| 289 | |
| 290 | |
| 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 | |
| 299 | func (rsf *ReverseSSHFS) waitForRemoteReady() error { |
| 300 | scriptName := "wait-for-remote-ready" |
| 301 | scriptTemplate := `#!/bin/sh |
| 302 | set -eu |
| 303 | dir="{{.Dir}}" |
| 304 | max_trial="{{.MaxTrial}}" |
| 305 | LANG=C |
| 306 | LC_ALL=C |
| 307 | export LANG LC_ALL |
| 308 | i=0 |
| 309 | while : ; 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)) |
| 322 | done |
| 323 | ` |
| 324 | t, err := template.New(scriptName).Parse(scriptTemplate) |
| 325 | if err != nil { |
| 326 | return err |
| 327 | } |
| 328 | m := map[string]string{ |
| 329 | |
| 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 | |
| 344 | func (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 | |
| 357 | _ = cmd.Wait() |
| 358 | } |
| 359 | if len(errors) > 0 { |
| 360 | return fmt.Errorf("%v", errors) |
| 361 | } |
| 362 | return nil |
| 363 | } |
| 364 | |
| 365 | |
| 366 | func convertMSYS2Path(localPath string) string { |
| 367 | if len(localPath) >= 3 && localPath[0] == '/' && localPath[2] == '/' { |
| 368 | driveLetter := strings.ToUpper(string(localPath[1])) |
| 369 | |
| 370 | remainingPath := strings.ReplaceAll(localPath[2:], "/", "\\") |
| 371 | return driveLetter + ":" + remainingPath |
| 372 | } |
| 373 | return localPath |
| 374 | } |