From d001a706fbcfa0e32ed046eaa9c20438fca92ce8 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Wed, 2 Dec 2026 14:33:08 -0800 Subject: [PATCH] sftp: apply an fsetstat sent while an upload is still buffering "put -p" sets the mode and times on the open handle before closing it, but the upload only reaches the filer on close, so the setstat found no entry and the client failed with "No such file or directory". Keep such attributes on the open upload: a size cuts the buffered bytes, the mode goes on the PUT, and the rest is set once the file is stored. Co-Authored-By: Claude Opus 5.5 --- weed/sftpd/sftp_exec_test.go | 2 +- weed/sftpd/sftp_file_writer.go | 68 ++++++++++++++++++++++++++++- weed/sftpd/sftp_filer.go | 35 +++++++++------ weed/sftpd/sftp_filer_test.go | 55 +++++++++++++++++++++++ weed/sftpd/sftp_object_lock_test.go | 4 +- weed/sftpd/sftp_server.go | 4 ++ 6 files changed, 149 insertions(+), 19 deletions(-) diff --git a/weed/sftpd/sftp_exec_test.go b/weed/sftpd/sftp_exec_test.go index e5d43846f0..141f5b041b 100644 --- a/weed/sftpd/sftp_exec_test.go +++ b/weed/sftpd/sftp_exec_test.go @@ -192,7 +192,7 @@ func TestSetstatSizeClearsMd5(t *testing.T) { req := sftp.NewRequest("Setstat", "/b/f") req.Flags = 1 // SSH_FILEXFER_ATTR_SIZE req.Attrs = binary.BigEndian.AppendUint64(nil, size) - if err := fs.setFileStatWithRequest("/buckets/b/f", req); err != nil { + if err := fs.setFileStat("/buckets/b/f", req.AttrFlags(), req.Attributes()); err != nil { t.Fatalf("setstat size %d: %v", size, err) } got := fake.lastUpdate.Entry.Attributes diff --git a/weed/sftpd/sftp_file_writer.go b/weed/sftpd/sftp_file_writer.go index 13ac526b7b..2f84737acf 100644 --- a/weed/sftpd/sftp_file_writer.go +++ b/weed/sftpd/sftp_file_writer.go @@ -48,7 +48,7 @@ func (l listerat) ListAt(ls []os.FileInfo, offset int64) (int, error) { // SeaweedSftpFileWriter buffers writes and flushes on Close. type SeaweedSftpFileWriter struct { - fs SftpServer + fs *SftpServer req *sftp.Request absPath string // Absolute path after HomeDir translation mu sync.Mutex @@ -57,6 +57,55 @@ type SeaweedSftpFileWriter struct { uid uint32 gid uint32 offset int64 + closed bool + setStats []fileStat // attributes set while the upload buffered +} + +type fileStat struct { + flags sftp.FileAttrFlags + attrs *sftp.FileStat +} + +func (fs *SftpServer) trackUpload(w *SeaweedSftpFileWriter) { + fs.uploadsMu.Lock() + defer fs.uploadsMu.Unlock() + if fs.uploads == nil { + fs.uploads = make(map[string]*SeaweedSftpFileWriter) + } + fs.uploads[w.absPath] = w +} + +func (fs *SftpServer) untrackUpload(w *SeaweedSftpFileWriter) { + fs.uploadsMu.Lock() + defer fs.uploadsMu.Unlock() + if fs.uploads[w.absPath] == w { + delete(fs.uploads, w.absPath) + } +} + +func (fs *SftpServer) openUpload(absPath string) *SeaweedSftpFileWriter { + fs.uploadsMu.Lock() + defer fs.uploadsMu.Unlock() + return fs.uploads[absPath] +} + +// setStat takes an fsetstat on the handle of a buffering upload, whose entry +// may not exist yet: a size cuts the buffered bytes, the rest is applied once +// the upload is stored. It does not handle it once the upload has closed. +func (w *SeaweedSftpFileWriter) setStat(flags sftp.FileAttrFlags, attrs *sftp.FileStat) (handled bool, err error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.closed { + return false, nil + } + if flags.Size { + if err := w.tmpFile.Truncate(int64(attrs.Size)); err != nil { + return true, err + } + flags.Size = false + } + w.setStats = append(w.setStats, fileStat{flags: flags, attrs: attrs}) + return true, nil } func (w *SeaweedSftpFileWriter) Write(p []byte) (int, error) { @@ -77,6 +126,8 @@ func (w *SeaweedSftpFileWriter) Close() error { w.mu.Lock() defer w.mu.Unlock() + defer w.fs.untrackUpload(w) + w.closed = true defer os.Remove(w.tmpFile.Name()) // Clean up temp file defer w.tmpFile.Close() @@ -98,7 +149,20 @@ func (w *SeaweedSftpFileWriter) Close() error { if perm := os.FileMode(existing.GetAttributes().GetFileMode()).Perm(); perm != 0 { mode = perm } + for _, st := range w.setStats { + if st.flags.Permissions { + mode = st.attrs.FileMode().Perm() + } + } // Stream the file to the absolute path (after HomeDir translation) - return w.fs.putFile(w.absPath, w.tmpFile, w.fs.user, mode) + if err := w.fs.putFile(w.absPath, w.tmpFile, w.fs.user, mode); err != nil { + return err + } + for _, st := range w.setStats { + if err := w.fs.setFileStat(w.absPath, st.flags, st.attrs); err != nil { + return err + } + } + return nil } diff --git a/weed/sftpd/sftp_filer.go b/weed/sftpd/sftp_filer.go index f4e5fc3735..98ff110912 100644 --- a/weed/sftpd/sftp_filer.go +++ b/weed/sftpd/sftp_filer.go @@ -127,7 +127,12 @@ func (fs *SftpServer) dispatchCmd(r *sftp.Request) error { case "Rmdir": return fs.removeDir(absPath) case "Setstat": - return fs.setFileStatWithRequest(absPath, r) + if w := fs.openUpload(absPath); w != nil { + if handled, err := w.setStat(r.AttrFlags(), r.Attributes()); handled { + return err + } + } + return fs.setFileStat(absPath, r.AttrFlags(), r.Attributes()) default: return fmt.Errorf("unsupported: %s", r.Method) } @@ -179,8 +184,8 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) { } } - return &SeaweedSftpFileWriter{ - fs: *fs, + w := &SeaweedSftpFileWriter{ + fs: fs, req: r, absPath: absPath, tmpFile: tmpFile, @@ -188,7 +193,9 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) { uid: fs.user.Uid, gid: fs.user.Gid, offset: 0, - }, nil + } + fs.trackUpload(w) + return w, nil } // checkWritable refuses an upload onto a directory, which the filer would @@ -458,7 +465,7 @@ func (fs *SftpServer) checkRenameKeepsAcl(absPath, absTarget string) error { return nil } -func (fs *SftpServer) setFileStatWithRequest(absPath string, r *sftp.Request) error { +func (fs *SftpServer) setFileStat(absPath string, flags sftp.FileAttrFlags, attrs *sftp.FileStat) error { if err := fs.checkFilePermission(absPath, "write"); err != nil { return err } @@ -471,18 +478,18 @@ func (fs *SftpServer) setFileStatWithRequest(absPath string, r *sftp.Request) er } dir, _ := util.FullPath(absPath).DirAndName() // apply attrs - if r.AttrFlags().Permissions { - entry.Attributes.FileMode = uint32(r.Attributes().FileMode()) + if flags.Permissions { + entry.Attributes.FileMode = uint32(attrs.FileMode()) } - if r.AttrFlags().UidGid { - entry.Attributes.Uid = uint32(r.Attributes().UID) - entry.Attributes.Gid = uint32(r.Attributes().GID) + if flags.UidGid { + entry.Attributes.Uid = uint32(attrs.UID) + entry.Attributes.Gid = uint32(attrs.GID) } - if r.AttrFlags().Acmodtime { - entry.Attributes.Mtime = int64(r.Attributes().Mtime) + if flags.Acmodtime { + entry.Attributes.Mtime = int64(attrs.Mtime) } - if r.AttrFlags().Size { - if size := uint64(r.Attributes().Size); size != entry.Attributes.FileSize { + if flags.Size { + if size := uint64(attrs.Size); size != entry.Attributes.FileSize { entry.Attributes.FileSize = size // the stored MD5 described the old content entry.Attributes.Md5 = nil diff --git a/weed/sftpd/sftp_filer_test.go b/weed/sftpd/sftp_filer_test.go index 7b2169127d..48a7374964 100644 --- a/weed/sftpd/sftp_filer_test.go +++ b/weed/sftpd/sftp_filer_test.go @@ -3,6 +3,7 @@ package sftpd import ( "context" "crypto/rand" + "encoding/binary" "encoding/hex" "fmt" "io" @@ -10,6 +11,7 @@ import ( "net/http" "net/http/httptest" "os" + "path" "strings" "testing" "time" @@ -320,3 +322,56 @@ func TestUploadFileMode(t *testing.T) { }) } } + +// An fsetstat on an upload's handle, as "put -p" sends before closing, finds +// no entry yet: it has to wait for the upload and apply then. +func TestSetstatOnBufferingUpload(t *testing.T) { + fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{ + "/buckets/plain": {Name: "plain", IsDirectory: true}, + }) + var gotMode, gotBody string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + gotMode, gotBody = r.URL.Query().Get("mode"), string(body) + fake.mu.Lock() + fake.entries[r.URL.Path] = &filer_pb.Entry{Name: path.Base(r.URL.Path), Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: uint64(len(body))}} + fake.mu.Unlock() + _, _ = w.Write([]byte(`{}`)) + })) + t.Cleanup(ts.Close) + _, grpcPort, _ := net.SplitHostPort(fs.filerAddr.ToGrpcAddress()) + fs.filerAddr = pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://") + "." + grpcPort) + + open := sftp.NewRequest("Put", "/plain/new") + open.Flags = 0x1a // write, create, truncate + w, err := fs.newFileWriter(open) + if err != nil { + t.Fatalf("newFileWriter: %v", err) + } + if _, err := w.WriteAt([]byte("hello world"), 0); err != nil { + t.Fatalf("write: %v", err) + } + const mtime = 1700000000 + setstat := sftp.NewRequest("Setstat", "/plain/new") + setstat.Flags = 0x1 | 0x4 | 0x8 // size, permissions, times + setstat.Attrs = binary.BigEndian.AppendUint64(nil, 5) + setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, 0100600) + setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, mtime) + setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, mtime) + if err := fs.dispatchCmd(setstat); err != nil { + t.Fatalf("setstat before close: %v", err) + } + if err := w.(io.Closer).Close(); err != nil { + t.Fatalf("close: %v", err) + } + if gotMode != "600" || gotBody != "hello" { + t.Errorf("uploaded mode %q body %q, want 600 and the body cut to 5 bytes", gotMode, gotBody) + } + got := fake.lastUpdate.GetEntry().GetAttributes() + if got.GetMtime() != mtime || os.FileMode(got.GetFileMode()).Perm() != 0600 { + t.Errorf("stored mtime %d mode %o, want %d and 600", got.GetMtime(), got.GetFileMode(), mtime) + } + if fs.openUpload("/buckets/plain/new") != nil { + t.Error("closed upload is still tracked") + } +} diff --git a/weed/sftpd/sftp_object_lock_test.go b/weed/sftpd/sftp_object_lock_test.go index a5fb7a395e..1daf20b808 100644 --- a/weed/sftpd/sftp_object_lock_test.go +++ b/weed/sftpd/sftp_object_lock_test.go @@ -250,14 +250,14 @@ func TestWriteAndSetstatRefuseProtectedEntries(t *testing.T) { } t.Fatalf("overwrite of %s: got %v, want os.ErrPermission", p, err) } - if err := fs.setFileStatWithRequest("/buckets"+p, sftp.NewRequest("Setstat", p)); !errors.Is(err, os.ErrPermission) { + if err := fs.setFileStat("/buckets"+p, sftp.FileAttrFlags{}, &sftp.FileStat{}); !errors.Is(err, os.ErrPermission) { t.Fatalf("setstat of %s: got %v, want os.ErrPermission", p, err) } } if fake.updates != 0 { t.Fatalf("setstat of a protected entry reached the filer") } - if err := fs.setFileStatWithRequest("/buckets/b/unlocked", sftp.NewRequest("Setstat", "/b/unlocked")); err != nil { + if err := fs.setFileStat("/buckets/b/unlocked", sftp.FileAttrFlags{}, &sftp.FileStat{}); err != nil { t.Fatalf("setstat of an unprotected entry: %v", err) } if _, ok := fake.lastUpdate.ExpectedExtended[s3_constants.ExtLegalHoldKey]; !ok { diff --git a/weed/sftpd/sftp_server.go b/weed/sftpd/sftp_server.go index 58abdf550c..7f8741007a 100644 --- a/weed/sftpd/sftp_server.go +++ b/weed/sftpd/sftp_server.go @@ -8,6 +8,7 @@ import ( "os" "path" "strings" + "sync" "time" "unicode/utf8" @@ -29,6 +30,9 @@ type SftpServer struct { filerSigningKey []byte filerSigningExpiresAfter int bucketsDir string + + uploadsMu sync.Mutex + uploads map[string]*SeaweedSftpFileWriter } // NewSftpServer constructs the server.