feat(vfs): add sftpfs over pooled SSH connections (2B.5)
SFTP implementation of vfs.FS on a conn.Lease: passes the conformance suite on the in-process stand (and on a real sshd under the integration tag), including RemoveTree on a symlink to a directory (N-P0-3). Volume is the host key fingerprint (N-P0-5); metadata calls return on ctx cancel, a watchdog probes hung calls; io.Copy uses concurrent reads/writes (N-P1-6). Connection errors map to vfs.ErrConnLost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
538418d553
commit
38e05c695f
6 changed files with 1088 additions and 0 deletions
69
internal/vfs/sftpfs/errors.go
Normal file
69
internal/vfs/sftpfs/errors.go
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
package sftpfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/vfs"
|
||||
)
|
||||
|
||||
// sshFxOPUnsupported is SSH_FX_OP_UNSUPPORTED.
|
||||
const sshFxOPUnsupported = 8
|
||||
|
||||
// mapErr turns an SFTP/connection error into vfs sentinels: a dead or closed
|
||||
// connection becomes vfs.ErrConnLost (still matching conn.ErrConnLost /
|
||||
// conn.ErrClosed), SSH_FX_OP_UNSUPPORTED becomes vfs.ErrUnsupported.
|
||||
// ENOENT/EACCES already arrive as fs.ErrNotExist/fs.ErrPermission from
|
||||
// pkg/sftp. Context errors and io.EOF pass through untouched.
|
||||
func (f *FS) mapErr(err error) error {
|
||||
if err == nil || err == io.EOF || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return err
|
||||
}
|
||||
err = f.c.MapErr(err)
|
||||
if errors.Is(err, conn.ErrConnLost) || errors.Is(err, conn.ErrClosed) {
|
||||
if errors.Is(err, vfs.ErrConnLost) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %w", vfs.ErrConnLost, err)
|
||||
}
|
||||
var se *sftp.StatusError
|
||||
if errors.As(err, &se) && se.Code == sshFxOPUnsupported {
|
||||
return fmt.Errorf("%w: %w", vfs.ErrUnsupported, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// wrap maps err and attaches op and path (unless the error already is a
|
||||
// *fs.PathError, as pkg/sftp returns for some calls).
|
||||
func (f *FS) wrap(op, p string, err error) error {
|
||||
err = f.mapErr(err)
|
||||
if err == nil || err == io.EOF || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return err
|
||||
}
|
||||
var pe *fs.PathError
|
||||
if errors.As(err, &pe) && !errors.Is(err, vfs.ErrConnLost) {
|
||||
return err
|
||||
}
|
||||
return &fs.PathError{Op: op, Path: p, Err: err}
|
||||
}
|
||||
|
||||
// existErr refines a failed create/mkdir/rename: SFTP v3 has no
|
||||
// "already exists" status (OpenSSH and pkg/sftp send SSH_FX_FAILURE), so if
|
||||
// the target now exists the error becomes vfs.ErrExist.
|
||||
func (f *FS) existErr(ctx context.Context, op, p string, err error) error {
|
||||
werr := f.wrap(op, p, err)
|
||||
if werr == nil || errors.Is(werr, vfs.ErrNotExist) || errors.Is(werr, vfs.ErrPermission) ||
|
||||
errors.Is(werr, vfs.ErrConnLost) || ctx.Err() != nil {
|
||||
return werr
|
||||
}
|
||||
if _, lerr := f.lstatRaw(ctx, p); lerr == nil {
|
||||
return &fs.PathError{Op: op, Path: p, Err: vfs.ErrExist}
|
||||
}
|
||||
return werr
|
||||
}
|
||||
163
internal/vfs/sftpfs/integration_test.go
Normal file
163
internal/vfs/sftpfs/integration_test.go
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
//go:build integration
|
||||
|
||||
package sftpfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"golang.org/x/crypto/ssh/knownhosts"
|
||||
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/vfs"
|
||||
"vcom/internal/vfs/vfstest"
|
||||
)
|
||||
|
||||
const sshdPath = "/usr/sbin/sshd"
|
||||
|
||||
// realSSHD starts the system sshd as the current user on a free port and
|
||||
// returns an FS connected to it. The test is skipped when that is not
|
||||
// possible (no sshd, sandbox without ports, ...).
|
||||
func realSSHD(t *testing.T) *FS {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(sshdPath); err != nil {
|
||||
t.Skip("no " + sshdPath)
|
||||
}
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "vcom-sshd")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
writeKey := func(name string) ssh.PublicKey {
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blk, err := ssh.MarshalPrivateKey(priv, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, name), pem.EncodeToMemory(blk), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ := ssh.NewSignerFromKey(priv)
|
||||
return s.PublicKey()
|
||||
}
|
||||
hostPub := writeKey("host_key")
|
||||
clientPub := writeKey("client_key")
|
||||
if err := os.WriteFile(filepath.Join(dir, "authorized_keys"), ssh.MarshalAuthorizedKey(clientPub), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
ln.Close()
|
||||
cfg := fmt.Sprintf(`Port %d
|
||||
ListenAddress 127.0.0.1
|
||||
HostKey %[2]s/host_key
|
||||
PidFile %[2]s/sshd.pid
|
||||
AuthorizedKeysFile %[2]s/authorized_keys
|
||||
StrictModes no
|
||||
UsePAM no
|
||||
PasswordAuthentication no
|
||||
KbdInteractiveAuthentication no
|
||||
PubkeyAuthentication yes
|
||||
Subsystem sftp internal-sftp
|
||||
`, port, dir)
|
||||
if err := os.WriteFile(filepath.Join(dir, "sshd_config"), []byte(cfg), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
cmd := exec.Command(sshdPath, "-D", "-e", "-f", filepath.Join(dir, "sshd_config"))
|
||||
cmd.Stdout, cmd.Stderr = &out, &out
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
|
||||
addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
c, err := net.DialTimeout("tcp", addr, 100*time.Millisecond)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Skipf("sshd did not start: %s", out.String())
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
kh := filepath.Join(dir, "known_hosts")
|
||||
if err := os.WriteFile(kh, []byte(knownhosts.Line([]string{knownhosts.Normalize(addr)}, hostPub)+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{
|
||||
Home: dir, AgentSocket: "-", KnownHostsFiles: []string{kh}, DefaultIdentityFiles: []string{},
|
||||
}})
|
||||
t.Cleanup(func() { pool.Close() })
|
||||
l, err := pool.Acquire(context.Background(), conn.Endpoint{
|
||||
Alias: "sshd", User: u.Username, Host: "127.0.0.1", Port: port,
|
||||
IdentityFiles: []string{filepath.Join(dir, "client_key")}, IdentitiesOnly: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("cannot log in to the test sshd: %v\n%s", err, out.String())
|
||||
}
|
||||
f := New(l)
|
||||
t.Cleanup(f.Release)
|
||||
return f
|
||||
}
|
||||
|
||||
// SSH_FXP_SYMLINK argument order differs between the draft and OpenSSH; the
|
||||
// link must point where we asked.
|
||||
func TestSymlinkOrderOpenSSH(t *testing.T) {
|
||||
f := realSSHD(t)
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
if err := f.Symlink(ctx, "target-name", dir+"/link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.Readlink(filepath.Join(dir, "link"))
|
||||
if err != nil || got != "target-name" {
|
||||
t.Fatalf("link -> %q (%v), want target-name", got, err)
|
||||
}
|
||||
if t2, err := f.ReadLink(ctx, dir+"/link"); err != nil || t2 != "target-name" {
|
||||
t.Errorf("ReadLink = %q, %v", t2, err)
|
||||
}
|
||||
c := f.Caps()
|
||||
if !c.NoReplace || !c.AtomicReplace {
|
||||
t.Errorf("OpenSSH caps = %+v", c)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "a"), []byte("a"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "b"), []byte("b"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Rename(ctx, dir+"/a", dir+"/b", vfs.NoReplace); !errors.Is(err, vfs.ErrExist) {
|
||||
t.Errorf("Rename(NoReplace) onto existing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConformanceOpenSSH(t *testing.T) {
|
||||
vfstest.Run(t, func(t *testing.T) (vfs.FS, string) { return realSSHD(t), t.TempDir() })
|
||||
}
|
||||
439
internal/vfs/sftpfs/sftpfs.go
Normal file
439
internal/vfs/sftpfs/sftpfs.go
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
// Package sftpfs is vfs.FS over a pooled SSH connection (design §2.4).
|
||||
//
|
||||
// Every call takes the current *sftp.Client from the leased conn.Conn, so a
|
||||
// reconnect is picked up transparently. Metadata calls honour ctx: a
|
||||
// cancelled ctx returns at once while the abandoned request finishes (or
|
||||
// fails) in the background; the result is discarded. A call hanging longer
|
||||
// than the watchdog interval triggers an out-of-band keepalive that marks a
|
||||
// dead connection Lost, which fails the hung request.
|
||||
package sftpfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/vfs"
|
||||
)
|
||||
|
||||
// Watchdog settings (§3.4); variables so tests can shorten them.
|
||||
var (
|
||||
watchdogAfter = 30 * time.Second
|
||||
watchdogTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// linkStatParallel bounds the Stat calls ReadDir issues for symlink targets.
|
||||
const linkStatParallel = 16
|
||||
|
||||
// FS is an SFTP file system. It owns its lease: call Release when the panel
|
||||
// or job is done with it.
|
||||
type FS struct {
|
||||
lease *conn.Lease
|
||||
c *conn.Conn
|
||||
caps vfs.Caps
|
||||
label string
|
||||
vol vfs.VolumeID
|
||||
// serverRealPath: the server's REALPATH resolves symlinks (OpenSSH does,
|
||||
// pkg/sftp's server only cleans the path).
|
||||
serverRealPath bool
|
||||
}
|
||||
|
||||
var (
|
||||
_ vfs.FS = (*FS)(nil)
|
||||
_ vfs.Execer = (*FS)(nil)
|
||||
)
|
||||
|
||||
// New builds an FS on lease and takes ownership of it.
|
||||
func New(lease *conn.Lease) *FS {
|
||||
c := lease.Conn()
|
||||
cc := c.Caps()
|
||||
openssh := strings.Contains(c.ServerVersion(), "OpenSSH")
|
||||
return &FS{
|
||||
lease: lease,
|
||||
c: c,
|
||||
label: c.Endpoint().Label(),
|
||||
vol: vfs.VolumeID("ssh:" + c.Identity().FingerprintSHA256),
|
||||
caps: vfs.Caps{
|
||||
AtomicReplace: cc.PosixRename,
|
||||
// OpenSSH implements SSH_FXP_RENAME with link(2)+unlink(2): it
|
||||
// never replaces. Other servers (pkg/sftp uses rename(2)) may, so
|
||||
// there NoReplace is only a non-atomic Lstat pre-check.
|
||||
NoReplace: openssh,
|
||||
Symlinks: true,
|
||||
Chmod: true,
|
||||
Chtimes: true,
|
||||
Fsync: cc.Fsync,
|
||||
},
|
||||
serverRealPath: openssh,
|
||||
}
|
||||
}
|
||||
|
||||
// Release gives the lease back to the pool. Idempotent.
|
||||
func (f *FS) Release() { f.lease.Release() }
|
||||
|
||||
// Lease returns the lease this FS holds (Acquire on it for a second user).
|
||||
func (f *FS) Lease() *conn.Lease { return f.lease }
|
||||
|
||||
// Conn exposes the connection (state, reconnect, events).
|
||||
func (f *FS) Conn() *conn.Conn { return f.c }
|
||||
|
||||
func (f *FS) Kind() vfs.Kind { return vfs.KindSFTP }
|
||||
func (f *FS) Volume() vfs.VolumeID { return f.vol }
|
||||
func (f *FS) Caps() vfs.Caps { return f.caps }
|
||||
func (f *FS) Label() string { return f.label }
|
||||
func (f *FS) Paths() vfs.PathOps { return vfs.PosixPaths }
|
||||
func (f *FS) String() string { return "sftp:" + f.label }
|
||||
func (f *FS) client() (*sftp.Client, error) {
|
||||
cl, err := f.c.Client()
|
||||
if err != nil {
|
||||
return nil, f.mapErr(err)
|
||||
}
|
||||
return cl, nil
|
||||
}
|
||||
|
||||
// call runs fn on the current client, returning early when ctx is done.
|
||||
func (f *FS) call(ctx context.Context, fn func(cl *sftp.Client) error) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
cl, err := f.client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- fn(cl) }()
|
||||
wd := time.NewTimer(watchdogAfter)
|
||||
defer wd.Stop()
|
||||
for {
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-wd.C:
|
||||
// Hung for long: check the link out of band. A dead link is
|
||||
// closed by Probe, which makes fn return with an error.
|
||||
go f.c.Probe(context.Background(), watchdogTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// openCall is call for functions returning an open file: if ctx gives up
|
||||
// first, the file opened later is closed instead of leaking.
|
||||
func (f *FS) openCall(ctx context.Context, open func(cl *sftp.Client) (*sftp.File, error)) (*sftp.File, error) {
|
||||
var mu sync.Mutex
|
||||
var sf *sftp.File
|
||||
abandoned := false
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
h, err := open(cl)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if abandoned {
|
||||
if h != nil {
|
||||
h.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
sf = h
|
||||
return err
|
||||
})
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if err != nil {
|
||||
abandoned = true
|
||||
if sf != nil && ctx.Err() != nil {
|
||||
sf.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return sf, nil
|
||||
}
|
||||
|
||||
func toInfo(name string, fi os.FileInfo) vfs.FileInfo {
|
||||
return vfs.FileInfo{Name: name, Size: fi.Size(), Mode: fi.Mode(), ModTime: fi.ModTime()}
|
||||
}
|
||||
|
||||
func base(p string) string { return vfs.PosixPaths.Base(p) }
|
||||
|
||||
func (f *FS) lstatRaw(ctx context.Context, p string) (os.FileInfo, error) {
|
||||
var fi os.FileInfo
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
var err error
|
||||
fi, err = cl.Lstat(p)
|
||||
return err
|
||||
})
|
||||
return fi, err
|
||||
}
|
||||
|
||||
// Stat follows symlinks.
|
||||
func (f *FS) Stat(ctx context.Context, p string) (vfs.FileInfo, error) {
|
||||
var fi os.FileInfo
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
var err error
|
||||
fi, err = cl.Stat(p)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return vfs.FileInfo{}, f.wrap("stat", p, err)
|
||||
}
|
||||
return toInfo(base(p), fi), nil
|
||||
}
|
||||
|
||||
// Lstat does not follow symlinks; for a symlink Target/LinkErr are filled.
|
||||
func (f *FS) Lstat(ctx context.Context, p string) (vfs.FileInfo, error) {
|
||||
var out vfs.FileInfo
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
fi, err := cl.Lstat(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = toInfo(base(p), fi)
|
||||
if out.IsSymlink() {
|
||||
f.fillTarget(cl, p, &out)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return vfs.FileInfo{}, f.wrap("lstat", p, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *FS) fillTarget(cl *sftp.Client, p string, fi *vfs.FileInfo) {
|
||||
t, err := cl.Stat(p)
|
||||
if err != nil {
|
||||
fi.LinkErr = f.wrap("stat", p, err)
|
||||
return
|
||||
}
|
||||
ti := toInfo(fi.Name, t)
|
||||
fi.Target = &ti
|
||||
}
|
||||
|
||||
// ReadDir lists p with lstat semantics; symlink targets are resolved with
|
||||
// at most 16 parallel Stat calls.
|
||||
func (f *FS) ReadDir(ctx context.Context, p string) ([]vfs.FileInfo, error) {
|
||||
var out []vfs.FileInfo
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
ents, err := cl.ReadDir(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = make([]vfs.FileInfo, len(ents))
|
||||
sem := make(chan struct{}, linkStatParallel)
|
||||
var wg sync.WaitGroup
|
||||
for i, e := range ents {
|
||||
out[i] = toInfo(e.Name(), e)
|
||||
if !out[i].IsSymlink() {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func(fi *vfs.FileInfo) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
f.fillTarget(cl, vfs.PosixPaths.Join(p, fi.Name), fi)
|
||||
}(&out[i])
|
||||
}
|
||||
wg.Wait()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, f.wrap("readdir", p, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *FS) ReadLink(ctx context.Context, p string) (string, error) {
|
||||
var t string
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
var err error
|
||||
t, err = cl.ReadLink(p)
|
||||
return err
|
||||
})
|
||||
return t, f.wrap("readlink", p, err)
|
||||
}
|
||||
|
||||
func (f *FS) Open(ctx context.Context, p string) (vfs.File, error) {
|
||||
sf, err := f.openCall(ctx, func(cl *sftp.Client) (*sftp.File, error) { return cl.Open(p) })
|
||||
if err != nil {
|
||||
return nil, f.wrap("open", p, err)
|
||||
}
|
||||
return &file{f: sf, fs: f, path: p}, nil
|
||||
}
|
||||
|
||||
// Create opens p for writing. CreateExcl fails with vfs.ErrExist on any
|
||||
// existing entry (a dangling symlink included) and applies perm; CreateTrunc
|
||||
// keeps an existing file's mode.
|
||||
func (f *FS) Create(ctx context.Context, p string, perm fs.FileMode, mode vfs.CreateMode) (vfs.File, error) {
|
||||
flags := os.O_WRONLY | os.O_CREATE
|
||||
if mode == vfs.CreateExcl {
|
||||
flags |= os.O_EXCL
|
||||
} else {
|
||||
flags |= os.O_TRUNC
|
||||
}
|
||||
sf, err := f.openCall(ctx, func(cl *sftp.Client) (*sftp.File, error) {
|
||||
sf, err := cl.OpenFile(p, flags)
|
||||
if err == nil && mode == vfs.CreateExcl {
|
||||
if cerr := sf.Chmod(perm.Perm()); cerr != nil {
|
||||
sf.Close()
|
||||
return nil, cerr
|
||||
}
|
||||
}
|
||||
return sf, err
|
||||
})
|
||||
if err != nil {
|
||||
if mode == vfs.CreateExcl {
|
||||
return nil, f.existErr(ctx, "create", p, err)
|
||||
}
|
||||
return nil, f.wrap("create", p, err)
|
||||
}
|
||||
return &file{f: sf, fs: f, path: p}, nil
|
||||
}
|
||||
|
||||
func (f *FS) Mkdir(ctx context.Context, p string, perm fs.FileMode) error {
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
if err := cl.Mkdir(p); err != nil {
|
||||
return err
|
||||
}
|
||||
if perm.Perm() != 0o755 {
|
||||
return cl.Chmod(p, perm.Perm())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return f.existErr(ctx, "mkdir", p, err)
|
||||
}
|
||||
|
||||
// Remove deletes a file, a symlink (never its target) or an empty directory.
|
||||
func (f *FS) Remove(ctx context.Context, p string) error {
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
fi, err := cl.Lstat(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
return cl.RemoveDirectory(p)
|
||||
}
|
||||
return cl.Remove(p)
|
||||
})
|
||||
return f.wrap("remove", p, err)
|
||||
}
|
||||
|
||||
// Rename moves from to to. NoReplace refuses an existing target with
|
||||
// vfs.ErrExist (atomically on OpenSSH, see Caps.NoReplace). Replace uses
|
||||
// posix-rename@openssh.com when available; without it an existing target
|
||||
// yields vfs.ErrExist and the transfer engine renames it aside.
|
||||
func (f *FS) Rename(ctx context.Context, from, to string, mode vfs.RenameMode) error {
|
||||
if mode == vfs.NoReplace || !f.caps.AtomicReplace {
|
||||
if _, err := f.lstatRaw(ctx, to); err == nil {
|
||||
if _, serr := f.lstatRaw(ctx, from); serr != nil {
|
||||
return f.wrap("rename", from, serr)
|
||||
}
|
||||
return &fs.PathError{Op: "rename", Path: to, Err: vfs.ErrExist}
|
||||
}
|
||||
}
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
if mode == vfs.Replace && f.caps.AtomicReplace {
|
||||
return cl.PosixRename(from, to)
|
||||
}
|
||||
return cl.Rename(from, to)
|
||||
})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
werr := f.wrap("rename", from, err)
|
||||
if errors.Is(werr, vfs.ErrNotExist) {
|
||||
return werr
|
||||
}
|
||||
return f.existErr(ctx, "rename", to, err)
|
||||
}
|
||||
|
||||
func (f *FS) Chmod(ctx context.Context, p string, mode fs.FileMode) error {
|
||||
err := f.call(ctx, func(cl *sftp.Client) error { return cl.Chmod(p, mode.Perm()) })
|
||||
return f.wrap("chmod", p, err)
|
||||
}
|
||||
|
||||
func (f *FS) Chtimes(ctx context.Context, p string, atime, mtime time.Time) error {
|
||||
err := f.call(ctx, func(cl *sftp.Client) error { return cl.Chtimes(p, atime, mtime) })
|
||||
return f.wrap("chtimes", p, err)
|
||||
}
|
||||
|
||||
// Exec runs argv on the server (vfs.Execer); vfs.ErrUnsupported when the
|
||||
// server refuses exec (ForceCommand internal-sftp).
|
||||
func (f *FS) Exec(ctx context.Context, argv []string) ([]byte, error) {
|
||||
if !f.c.ExecSupported(ctx) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, vfs.ErrUnsupported
|
||||
}
|
||||
out, _, err := f.c.Exec(ctx, argv, 0)
|
||||
return out, f.mapErr(err)
|
||||
}
|
||||
|
||||
// file is an open remote file.
|
||||
type file struct {
|
||||
f *sftp.File
|
||||
fs *FS
|
||||
path string
|
||||
}
|
||||
|
||||
func (fl *file) err(op string, err error) error {
|
||||
if err == nil || err == io.EOF {
|
||||
return err
|
||||
}
|
||||
return fl.fs.wrap(op, fl.path, err)
|
||||
}
|
||||
|
||||
func (fl *file) Read(p []byte) (int, error) {
|
||||
n, err := fl.f.Read(p)
|
||||
return n, fl.err("read", err)
|
||||
}
|
||||
|
||||
func (fl *file) ReadAt(p []byte, off int64) (int, error) {
|
||||
n, err := fl.f.ReadAt(p, off)
|
||||
return n, fl.err("read", err)
|
||||
}
|
||||
|
||||
func (fl *file) Write(p []byte) (int, error) {
|
||||
n, err := fl.f.Write(p)
|
||||
return n, fl.err("write", err)
|
||||
}
|
||||
|
||||
// ReadFrom lets io.Copy use pkg/sftp's concurrent writes (N-P1-6). The
|
||||
// source should expose Size() int64 (os.File, bytes.Reader, the transfer
|
||||
// engine's ctx reader), otherwise pkg/sftp falls back to sequential writes.
|
||||
func (fl *file) ReadFrom(r io.Reader) (int64, error) {
|
||||
n, err := fl.f.ReadFrom(r)
|
||||
return n, fl.err("write", err)
|
||||
}
|
||||
|
||||
// WriteTo lets io.Copy use concurrent reads.
|
||||
func (fl *file) WriteTo(w io.Writer) (int64, error) {
|
||||
n, err := fl.f.WriteTo(w)
|
||||
return n, fl.err("read", err)
|
||||
}
|
||||
|
||||
func (fl *file) Close() error { return fl.err("close", fl.f.Close()) }
|
||||
|
||||
func (fl *file) Stat() (vfs.FileInfo, error) {
|
||||
fi, err := fl.f.Stat()
|
||||
if err != nil {
|
||||
return vfs.FileInfo{}, fl.err("stat", err)
|
||||
}
|
||||
return toInfo(base(fl.path), fi), nil
|
||||
}
|
||||
|
||||
func (fl *file) Sync() error {
|
||||
if !fl.fs.caps.Fsync {
|
||||
return &fs.PathError{Op: "sync", Path: fl.path, Err: vfs.ErrUnsupported}
|
||||
}
|
||||
return fl.err("sync", fl.f.Sync())
|
||||
}
|
||||
293
internal/vfs/sftpfs/sftpfs_test.go
Normal file
293
internal/vfs/sftpfs/sftpfs_test.go
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
package sftpfs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/ssh/knownhosts"
|
||||
|
||||
"vcom/internal/ssh/conn"
|
||||
"vcom/internal/testutil/sshtest"
|
||||
"vcom/internal/vfs"
|
||||
"vcom/internal/vfs/vfstest"
|
||||
)
|
||||
|
||||
// stand is an isolated HOME with a server, its keys in known_hosts and a pool.
|
||||
type stand struct {
|
||||
t *testing.T
|
||||
srv *sshtest.Server
|
||||
pool *conn.Pool
|
||||
kh string
|
||||
}
|
||||
|
||||
func newStand(t *testing.T, o sshtest.Options) *stand {
|
||||
t.Helper()
|
||||
home := sshtest.IsolatedHome(t)
|
||||
s := &stand{t: t, srv: sshtest.Start(t, o), kh: filepath.Join(home, ".ssh", "known_hosts")}
|
||||
s.trust(s.srv.Addr)
|
||||
s.pool = conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{
|
||||
Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh},
|
||||
}})
|
||||
t.Cleanup(func() { s.pool.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
// trust appends the server's host keys for addr to known_hosts.
|
||||
func (s *stand) trust(addr string) {
|
||||
s.t.Helper()
|
||||
f, err := os.OpenFile(s.kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
for _, k := range s.srv.HostKeys {
|
||||
if _, err := f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(addr)}, k.PublicKey()) + "\n"); err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stand) proxy() *sshtest.Proxy {
|
||||
px := sshtest.NewProxy(s.t, s.srv.Addr)
|
||||
s.trust(px.Addr)
|
||||
return px
|
||||
}
|
||||
|
||||
func endpoint(addr, password string) conn.Endpoint {
|
||||
host, port, _ := net.SplitHostPort(addr)
|
||||
p, _ := strconv.Atoi(port)
|
||||
return conn.Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password}
|
||||
}
|
||||
|
||||
// fs opens an FS on addr ("" = the server itself).
|
||||
func (s *stand) fs(addr string) *FS {
|
||||
s.t.Helper()
|
||||
if addr == "" {
|
||||
addr = s.srv.Addr
|
||||
}
|
||||
l, err := s.pool.Acquire(context.Background(), endpoint(addr, s.srv.Password))
|
||||
if err != nil {
|
||||
s.t.Fatalf("acquire: %v", err)
|
||||
}
|
||||
f := New(l)
|
||||
s.t.Cleanup(f.Release)
|
||||
return f
|
||||
}
|
||||
|
||||
func TestConformance(t *testing.T) {
|
||||
vfstest.Run(t, func(t *testing.T) (vfs.FS, string) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
return s.fs(""), t.TempDir()
|
||||
})
|
||||
}
|
||||
|
||||
// N-P0-5: two aliases of one server (different HostName/port) are one
|
||||
// volume, so copying a file onto itself through them is detected.
|
||||
func TestVolumeByHostKey(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
direct := s.fs("")
|
||||
viaProxy := s.fs(s.proxy().Addr)
|
||||
if direct.Lease().Conn() == viaProxy.Lease().Conn() {
|
||||
t.Fatal("test needs two distinct connections")
|
||||
}
|
||||
if direct.Volume() != viaProxy.Volume() || direct.Volume() == "" {
|
||||
t.Fatalf("volumes differ: %q vs %q", direct.Volume(), viaProxy.Volume())
|
||||
}
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "f")
|
||||
if err := os.WriteFile(p, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same, err := vfs.SameFile(context.Background(), direct, p, viaProxy, p)
|
||||
if err != nil || !same {
|
||||
t.Fatalf("SameFile through aliases = %v, %v", same, err)
|
||||
}
|
||||
other := newStand(t, sshtest.Options{}).fs("")
|
||||
if other.Volume() == direct.Volume() {
|
||||
t.Error("different servers share a volume")
|
||||
}
|
||||
}
|
||||
|
||||
// A metadata call on a frozen link returns promptly once ctx is cancelled.
|
||||
func TestCallCancelReturnsFast(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
px := s.proxy()
|
||||
f := s.fs(px.Addr)
|
||||
dir := t.TempDir()
|
||||
px.Freeze(true)
|
||||
defer px.Freeze(false)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
var cancelled time.Time
|
||||
time.AfterFunc(50*time.Millisecond, func() { cancelled = time.Now(); cancel() })
|
||||
_, err := f.ReadDir(ctx, dir)
|
||||
el := time.Since(cancelled)
|
||||
if !errors.Is(err, vfs.ErrCancelled) {
|
||||
t.Fatalf("err = %v, want ErrCancelled", err)
|
||||
}
|
||||
if el > 100*time.Millisecond {
|
||||
t.Errorf("returned %v after cancel", el)
|
||||
}
|
||||
_, err = f.Open(ctx, filepath.Join(dir, "x"))
|
||||
if !errors.Is(err, vfs.ErrCancelled) {
|
||||
t.Errorf("Open with a cancelled ctx: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// N-P1-6: upload went one 32 KiB packet per RTT (4 MiB at 20 ms RTT took
|
||||
// seconds). io.Copy into a File must use concurrent writes.
|
||||
func TestUploadThroughputLatency(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
px := s.proxy()
|
||||
px.SetDelay(10 * time.Millisecond) // RTT ≈ 20 ms
|
||||
f := s.fs(px.Addr)
|
||||
dir := t.TempDir()
|
||||
src := filepath.Join(dir, "big.bin")
|
||||
data := sshtest.WriteRandom(t, src, 4<<20, 0o644)
|
||||
lf, err := os.Open(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lf.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
start := time.Now()
|
||||
rf, err := f.Create(ctx, filepath.Join(dir, "up.bin"), 0o644, vfs.CreateExcl)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.Copy(rf, lf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := rf.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
up := time.Since(start)
|
||||
|
||||
start = time.Now()
|
||||
rf2, err := f.Open(ctx, filepath.Join(dir, "up.bin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if _, err := io.Copy(&buf, rf2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rf2.Close()
|
||||
down := time.Since(start)
|
||||
t.Logf("4 MiB @ 20 ms RTT: upload %v, download %v", up, down)
|
||||
if !bytes.Equal(buf.Bytes(), data) {
|
||||
t.Fatal("content mismatch")
|
||||
}
|
||||
if up > 500*time.Millisecond {
|
||||
t.Errorf("upload took %v, want <= 500ms", up)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnLostMapsToVFS(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
px := s.proxy()
|
||||
f := s.fs(px.Addr)
|
||||
dir := t.TempDir()
|
||||
px.KillAll()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for f.Conn().State() != conn.Lost && time.Now().Before(deadline) {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
_, err := f.ReadDir(context.Background(), dir)
|
||||
if !errors.Is(err, vfs.ErrConnLost) || !errors.Is(err, conn.ErrConnLost) {
|
||||
t.Fatalf("err = %v, want vfs.ErrConnLost", err)
|
||||
}
|
||||
if err := s.pool.Reconnect(context.Background(), f.Conn().Key()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.ReadDir(context.Background(), dir); err != nil {
|
||||
t.Fatalf("ReadDir after reconnect: %v", err)
|
||||
}
|
||||
s.pool.Close()
|
||||
if _, err := f.Stat(context.Background(), dir); !errors.Is(err, vfs.ErrConnLost) {
|
||||
t.Errorf("after pool close: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The watchdog notices a hung call on a dead link without waiting for the
|
||||
// regular keepalive.
|
||||
func TestWatchdogMarksLost(t *testing.T) {
|
||||
oldAfter, oldTimeout := watchdogAfter, watchdogTimeout
|
||||
watchdogAfter, watchdogTimeout = 100*time.Millisecond, 100*time.Millisecond
|
||||
defer func() { watchdogAfter, watchdogTimeout = oldAfter, oldTimeout }()
|
||||
s := newStand(t, sshtest.Options{})
|
||||
px := s.proxy()
|
||||
f := s.fs(px.Addr)
|
||||
px.Freeze(true)
|
||||
defer px.Freeze(false)
|
||||
start := time.Now()
|
||||
_, err := f.Stat(context.Background(), t.TempDir())
|
||||
if !errors.Is(err, vfs.ErrConnLost) {
|
||||
t.Fatalf("err = %v, want ErrConnLost", err)
|
||||
}
|
||||
if el := time.Since(start); el > 2*time.Second {
|
||||
t.Errorf("hung call returned after %v", el)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapsAndInfo(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
f := s.fs("")
|
||||
c := f.Caps()
|
||||
if !c.AtomicReplace || c.NoReplace || c.Fsync || c.Trash || c.Exec || c.ReadOnly || !c.Symlinks {
|
||||
t.Errorf("caps on pkg/sftp server = %+v", c)
|
||||
}
|
||||
if f.Kind() != vfs.KindSFTP || f.Label() != "u@test" || f.Paths().Sep() != '/' {
|
||||
t.Errorf("kind %v label %q", f.Kind(), f.Label())
|
||||
}
|
||||
out, err := f.Exec(context.Background(), []string{"echo", "a b"})
|
||||
if err != nil || string(out) != "a b\n" {
|
||||
t.Errorf("Exec = %q, %v", out, err)
|
||||
}
|
||||
noexec := newStand(t, sshtest.Options{NoExec: true}).fs("")
|
||||
if _, err := noexec.Exec(context.Background(), []string{"true"}); !errors.Is(err, vfs.ErrUnsupported) {
|
||||
t.Errorf("Exec without exec: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RealPath resolves links even when the server's REALPATH does not.
|
||||
func TestRealPathResolvesChains(t *testing.T) {
|
||||
s := newStand(t, sshtest.Options{})
|
||||
f := s.fs("")
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
must := func(err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must(f.Mkdir(ctx, dir+"/real", 0o755))
|
||||
must(f.Mkdir(ctx, dir+"/real/sub", 0o755))
|
||||
must(f.Symlink(ctx, "real", dir+"/a"))
|
||||
must(f.Symlink(ctx, dir+"/a/sub", dir+"/b"))
|
||||
got, err := f.RealPath(ctx, dir+"/b/../sub")
|
||||
must(err)
|
||||
if want := dir + "/real/sub"; got != want {
|
||||
// b -> real/sub, b/.. is real (symlinks resolved before ..), real/sub
|
||||
t.Errorf("RealPath = %q, want %q", got, want)
|
||||
}
|
||||
must(f.Symlink(ctx, "loop", dir+"/loop"))
|
||||
if _, err := f.RealPath(ctx, dir+"/loop"); err == nil {
|
||||
t.Error("symlink loop resolved")
|
||||
}
|
||||
if _, err := f.RealPath(ctx, dir+"/missing"); !errors.Is(err, vfs.ErrNotExist) {
|
||||
t.Errorf("missing: %v", err)
|
||||
}
|
||||
}
|
||||
93
internal/vfs/sftpfs/symlink.go
Normal file
93
internal/vfs/sftpfs/symlink.go
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
package sftpfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
|
||||
"vcom/internal/vfs"
|
||||
)
|
||||
|
||||
var errTooManyLinks = errors.New("too many levels of symbolic links")
|
||||
|
||||
// maxLinks bounds symlink resolution in RealPath (like Linux ELOOP).
|
||||
const maxLinks = 40
|
||||
|
||||
// RealPath returns the absolute path with every symlink resolved. OpenSSH's
|
||||
// REALPATH does this; for other servers it is resolved component by
|
||||
// component on the client.
|
||||
func (f *FS) RealPath(ctx context.Context, p string) (string, error) {
|
||||
var out string
|
||||
err := f.call(ctx, func(cl *sftp.Client) error {
|
||||
if f.serverRealPath {
|
||||
var err error
|
||||
out, err = cl.RealPath(p)
|
||||
return err
|
||||
}
|
||||
// The server's REALPATH would clean ".." lexically before links are
|
||||
// resolved; use it only to anchor a relative path.
|
||||
abs := p
|
||||
if !vfs.PosixPaths.IsAbs(p) {
|
||||
wd, err := cl.RealPath(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
abs = wd + "/" + p
|
||||
}
|
||||
var err error
|
||||
out, err = resolveLinks(cl, abs)
|
||||
return err
|
||||
})
|
||||
return out, f.wrap("realpath", p, err)
|
||||
}
|
||||
|
||||
func resolveLinks(cl *sftp.Client, abs string) (string, error) {
|
||||
ops := vfs.PosixPaths
|
||||
rest := strings.Split(strings.Trim(abs, "/"), "/")
|
||||
cur := "/"
|
||||
links := 0
|
||||
for len(rest) > 0 {
|
||||
name := rest[0]
|
||||
rest = rest[1:]
|
||||
if name == "" || name == "." {
|
||||
continue
|
||||
}
|
||||
if name == ".." {
|
||||
cur = ops.Dir(cur)
|
||||
continue
|
||||
}
|
||||
next := ops.Join(cur, name)
|
||||
fi, err := cl.Lstat(next)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if fi.Mode()&fs.ModeSymlink == 0 {
|
||||
cur = next
|
||||
continue
|
||||
}
|
||||
if links++; links > maxLinks {
|
||||
return "", &fs.PathError{Op: "realpath", Path: abs, Err: errTooManyLinks}
|
||||
}
|
||||
t, err := cl.ReadLink(next)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ops.IsAbs(t) {
|
||||
cur = "/"
|
||||
}
|
||||
rest = append(strings.Split(strings.Trim(t, "/"), "/"), rest...)
|
||||
}
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
// Symlink creates p pointing at target. pkg/sftp marshals SSH_FXP_SYMLINK in
|
||||
// OpenSSH's (historically swapped) argument order, which pkg/sftp's server
|
||||
// also expects, so no per-server swap is needed (verified against a real
|
||||
// sshd in TestSymlinkOrderOpenSSH, tag integration).
|
||||
func (f *FS) Symlink(ctx context.Context, target, p string) error {
|
||||
err := f.call(ctx, func(cl *sftp.Client) error { return cl.Symlink(target, p) })
|
||||
return f.existErr(ctx, "symlink", p, err)
|
||||
}
|
||||
|
|
@ -100,3 +100,34 @@
|
|||
- `IdleClose < 0` — закрыть сразу после последнего `Release`. `Release` идемпотентен на уровне каждой аренды:
|
||||
лишние вызовы не отбирают чужие ссылки. После `Pool.Close` аренды безопасны: `Client()` → `ErrClosed`,
|
||||
`Acquire` → `ErrPoolClosed`.
|
||||
|
||||
## 2B.5 `vfs/sftpfs`
|
||||
|
||||
- **Конструктор `sftpfs.New(lease)`** забирает аренду; `(*FS).Release()` отдаёт её пулу (у `vfs.FS` нет Close).
|
||||
Доступ к соединению — `Lease()`, `Conn()` (состояние, reconnect). Помимо `vfs.FS` реализован `vfs.Execer`
|
||||
(`ErrUnsupported`, если сервер не даёт exec).
|
||||
- **Порядок аргументов SYMLINK — без swap.** pkg/sftp-клиент сериализует пакет в порядке OpenSSH (target, link), и
|
||||
pkg/sftp-сервер читает так же, поэтому `cl.Symlink(target, link)` верен для обоих; определять сервер по
|
||||
`ServerVersion()` не нужно. Проверено интеграционным `TestSymlinkOrderOpenSSH` против настоящего
|
||||
`/usr/sbin/sshd` (тег `integration`; sshd запускается от текущего пользователя на свободном порту, при
|
||||
невозможности — skip). Под тем же тегом весь conformance-набор прогоняется на OpenSSH — зелёный.
|
||||
- **`Caps.NoReplace` только для OpenSSH** (там SSH_FXP_RENAME = link+unlink, не перезаписывает). pkg/sftp-сервер
|
||||
делает `rename(2)` и перезаписывает цель, поэтому `Rename(NoReplace)` всегда делает Lstat-проверку цели
|
||||
(на OpenSSH она лишь даёт чистый `ErrExist`, атомарность обеспечивает сервер). Без posix-rename
|
||||
`Rename(Replace)` при существующей цели тоже отдаёт `ErrExist` — transfer делает rename-в-сторону.
|
||||
- **`ErrExist`:** SFTP v3 отвечает `SSH_FX_FAILURE`; для Create(Excl)/Mkdir/Rename/Symlink при FAILURE
|
||||
проверяется Lstat цели (подсказка A).
|
||||
- **RealPath:** REALPATH OpenSSH разрешает симлинки — используется он. REALPATH pkg/sftp-сервера только чистит
|
||||
путь (причём `..` лексически, до симлинков), поэтому для не-OpenSSH путь разрешается на клиенте по компонентам
|
||||
(Lstat/ReadLink, ≤ 40 ссылок). Это нужно `vfs.SameFile/Within` (N-P0-5/6) и conformance.
|
||||
- **Ошибки:** `conn.ErrConnLost`/`conn.ErrClosed` → `fmt.Errorf("%w: %w", vfs.ErrConnLost, err)` (матчится и
|
||||
`vfs`, и `conn`); `SSH_FX_OP_UNSUPPORTED` → `vfs.ErrUnsupported`; ENOENT/EACCES уже приходят как
|
||||
`fs.ErrNotExist/ErrPermission`; `io.EOF` из `Read` не оборачивается.
|
||||
- **Отмена и watchdog:** все метаданные идут через `call(ctx)`: отмена возвращает сразу, результат брошенного
|
||||
вызова выбрасывается (файл, открытый брошенным `Open/Create`, закрывается). Через 30 с ожидания —
|
||||
`Conn.Probe(5 с)`; мёртвое соединение → `Lost` → висящий вызов получает `ErrConnLost`. Операции над открытым
|
||||
`File` ctx не принимают (§2.4/§4.3: отмену внутри файла делает transfer через ctx-reader и Close).
|
||||
- **Throughput:** `File` реализует `ReadFrom`/`WriteTo` (делегирует pkg/sftp с concurrent writes/reads), поэтому
|
||||
`io.Copy` из `*os.File` идёт параллельно: 4 МиБ при RTT 20 мс — upload ≈ 0,13 с, download ≈ 0,19 с (было ~2,6 с).
|
||||
- `Create(CreateExcl)` применяет `perm` через fsetstat; `CreateTrunc` режим существующего файла не меняет.
|
||||
`Mkdir` делает chmod, только если `perm != 0755` (умолчание сервера).
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue