From 8c45dc42a9fc4ded9f7270e5a5d3f65c0fcd1daf Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Thu, 3 Dec 2026 23:48:25 -0800 Subject: [PATCH] sftp: copy only the stored bytes on a non-truncating open A size set by a truncate that grows a file stores nothing, but opening the file for writing without O_TRUNC copied its whole logical size into the temp file as zeros. Copy up to the last stored byte and extend the temp file to the size, which leaves the rest sparse. Co-Authored-By: Claude Opus 5.5 --- weed/sftpd/sftp_copy_existing_test.go | 19 ++++++------ weed/sftpd/sftp_exec.go | 3 +- weed/sftpd/sftp_filer.go | 43 ++++++++++++++++----------- weed/sftpd/sftp_read_write_test.go | 28 +++++++++++++++++ 4 files changed, 66 insertions(+), 27 deletions(-) diff --git a/weed/sftpd/sftp_copy_existing_test.go b/weed/sftpd/sftp_copy_existing_test.go index 37559252fb..90802ab7aa 100644 --- a/weed/sftpd/sftp_copy_existing_test.go +++ b/weed/sftpd/sftp_copy_existing_test.go @@ -160,19 +160,21 @@ func TestCopyExistingContentIgnoresStaleRemoteSize(t *testing.T) { } } -// A file whose size is all holes still keeps its zeros. +// A size set past the stored bytes stores nothing, so there is nothing to +// copy: the caller keeps that hole sparse. func TestCopyExistingContentAllHoles(t *testing.T) { entries := map[string]*filer_pb.Entry{ - "/home/holes.bin": chunkedEntry(10), + "/home/holes.bin": chunkedEntry(1 << 40), + "/home/grown.txt": {Attributes: &filer_pb.FuseAttributes{FileSize: 1 << 40}, Content: []byte("x")}, } fs := newCopyTestServer(t, "", entries) var dst bytes.Buffer - if _, err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil { - t.Fatalf("all-holes file: %v", err) + if _, err := fs.copyExistingContent("/home/holes.bin", &dst); err != nil || dst.Len() != 0 { + t.Fatalf("all-holes file: err=%v written=%d, want nothing", err, dst.Len()) } - if dst.Len() != 10 || !bytes.Equal(dst.Bytes(), make([]byte, 10)) { - t.Fatalf("wrote %d bytes, want 10 zeros", dst.Len()) + if _, err := fs.copyExistingContent("/home/grown.txt", &dst); err != nil || dst.String() != "x" { + t.Fatalf("grown inline file: err=%v written=%d, want only %q", err, dst.Len(), "x") } } @@ -216,9 +218,8 @@ func TestCopyExistingContentTrailingGap(t *testing.T) { if _, err := fs.copyExistingContent("/home/trailing.bin", &dst); err != nil { t.Fatalf("copyExistingContent: %v", err) } - want := append(append([]byte{}, chunkA...), make([]byte, 40)...) - if !bytes.Equal(dst.Bytes(), want) { - t.Fatalf("copied %d bytes, want %d with a zero-filled tail", dst.Len(), len(want)) + if !bytes.Equal(dst.Bytes(), chunkA) { + t.Fatalf("copied %d bytes, want the %d stored ones", dst.Len(), len(chunkA)) } } diff --git a/weed/sftpd/sftp_exec.go b/weed/sftpd/sftp_exec.go index 3a74580c25..934f1b1028 100644 --- a/weed/sftpd/sftp_exec.go +++ b/weed/sftpd/sftp_exec.go @@ -13,6 +13,7 @@ import ( "regexp" "strings" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/glog" filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "golang.org/x/crypto/ssh" @@ -168,7 +169,7 @@ func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (stri return hex.EncodeToString(entry.Attributes.Md5), nil } h := newHash(kind) - if err := fs.writeContent(ctx, absPath, entry, ctxWriter{ctx, h}); err != nil { + if err := fs.writeContent(ctx, absPath, entry, int64(filer.FileSize(entry)), ctxWriter{ctx, h}); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil diff --git a/weed/sftpd/sftp_filer.go b/weed/sftpd/sftp_filer.go index 63583ba9d3..97bfdeee52 100644 --- a/weed/sftpd/sftp_filer.go +++ b/weed/sftpd/sftp_filer.go @@ -201,10 +201,15 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) { return nil, err } } - // Without O_TRUNC the client writes into the existing file, so start from its current bytes. + // Without O_TRUNC the client writes into the existing file, so start from + // its current bytes. Past the stored ones it is a hole, kept sparse. var existing *filer_pb.Entry if !flags.Trunc && !exclusive { - if existing, err = fs.copyExistingContent(absPath, tmpFile); err != nil { + existing, err = fs.copyExistingContent(absPath, tmpFile) + if err == nil && existing != nil { + err = tmpFile.Truncate(int64(filer.FileSize(existing))) + } + if err != nil { tmpFile.Close() os.Remove(tmpFile.Name()) return nil, err @@ -280,8 +285,8 @@ func (fs *SftpServer) checkWritable(absPath string) (*filer_pb.Entry, error) { return entry, fs.checkEntryProtected(absPath, entry) } -// copyExistingContent writes the file's content to dst and returns the entry -// it copied, or nil when there is no file. +// copyExistingContent writes the file's content up to its last stored byte +// to dst and returns the entry it copied, or nil when there is no file. func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) (*filer_pb.Entry, error) { entry, err := fs.getEntry(absPath) if err == os.ErrNotExist { @@ -293,34 +298,38 @@ func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) (*filer if entry.IsDirectory { return nil, nil } - return entry, fs.writeContent(context.Background(), absPath, entry, dst) + return entry, fs.writeContent(context.Background(), absPath, entry, storedSize(entry), dst) } -// writeContent writes the file's whole logical content to dst: inline bytes, -// then chunks, with zeros for the gaps and tail no chunk stores. -func (fs *SftpServer) writeContent(ctx context.Context, absPath string, entry *filer_pb.Entry, dst io.Writer) error { - size := int64(filer.FileSize(entry)) +// storedSize is where the file's last stored byte ends. A size set past it, +// as a truncate that grows the file does, stores nothing. +func storedSize(entry *filer_pb.Entry) int64 { + stored := filer.TotalSize(entry.GetChunks()) + if len(entry.Content) > 0 { + stored = uint64(len(entry.Content)) + } + return int64(min(stored, filer.FileSize(entry))) +} + +// writeContent writes the first size bytes of the file's logical content to +// dst: inline bytes, then chunks, with zeros for the gaps no chunk stores. +func (fs *SftpServer) writeContent(ctx context.Context, absPath string, entry *filer_pb.Entry, size int64, dst io.Writer) error { remote := entry.GetRemoteEntry() if len(entry.Content) == 0 && len(entry.GetChunks()) == 0 { if remote != nil && remote.RemoteSize > 0 { return fmt.Errorf("existing content of %s is not readable", absPath) } - if size == 0 { - return nil - } return writeZeros(dst, size) } if size == 0 { return nil } if len(entry.Content) > 0 { - if _, err := dst.Write(entry.Content); err != nil { + content := entry.Content[:min(int64(len(entry.Content)), size)] + if _, err := dst.Write(content); err != nil { return err } - if remaining := size - int64(len(entry.Content)); remaining > 0 { - return writeZeros(dst, remaining) - } - return nil + return writeZeros(dst, size-int64(len(content))) } streamFn, err := filer.PrepareStreamContentWithThrottler(ctx, lookupFileIdFn(filer.LookupFn(fs)), filer.JwtForVolumeServer, entry.GetChunks(), 0, size, 0) if err != nil { diff --git a/weed/sftpd/sftp_read_write_test.go b/weed/sftpd/sftp_read_write_test.go index 79e368a755..83212ec66f 100644 --- a/weed/sftpd/sftp_read_write_test.go +++ b/weed/sftpd/sftp_read_write_test.go @@ -164,6 +164,34 @@ func TestReadWriteOpenUploadsOnlyChanges(t *testing.T) { } } +// A truncate can grow a file to any size without storing anything. Opening it +// for writing must not turn that size into zeros on the server's disk. +func TestReadWriteOpenGrownFile(t *testing.T) { + rw := newRWTest(t, PermAll) + const size = 1 << 40 + rw.fake.mu.Lock() + rw.fake.entries["/buckets/b/grown.txt"] = &filer_pb.Entry{Name: "grown.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: size, FileMode: 0o644}} + rw.fake.mu.Unlock() + + f, err := rw.client.OpenFile("/b/grown.txt", os.O_RDWR) + if err != nil { + t.Fatalf("open read-write: %v", err) + } + buf := make([]byte, 2) + if n, err := f.ReadAt(buf, 0); n != 2 || string(buf) != "x\x00" { + t.Fatalf("read at 0 = %q (err=%v), want %q", buf[:n], err, "x\x00") + } + if n, err := f.ReadAt(buf, size-2); n != 2 || string(buf) != "\x00\x00" { + t.Fatalf("read at the end = %q (err=%v), want two zeros", buf[:n], err) + } + if err := f.Close(); err != nil { + t.Fatalf("close: %v", err) + } + if got := rw.uploads(); len(got) != 0 { + t.Fatalf("uploaded %d times on close, want none", len(got)) + } +} + // Without read permission a read-write open still writes, as a write-only // open would, but reads only what the handle itself wrote. func TestReadWriteOpenWithoutReadPermission(t *testing.T) {