Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 8ef4c4328b sftp: check the size before returning a stored md5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:24:06 -08:00
Chris LuandClaude Opus 5.5 3bb31554f1 sftp: fail the hash of an out-of-range size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:10:53 -08:00
Chris LuandClaude Opus 5.5 0f7f779054 sftp: refuse a setstat size past the largest file offset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:32:50 -08:00
Chris LuandClaude Opus 5.5 613cd55bdd sftp: hash nothing past an out-of-range size
A stored size past the largest file offset turned negative and sliced the
inline content out of range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:32:26 -08:00
Chris LuandClaude Opus 5.5 ff9102bc2a sftp: cap what the test filer reads from an upload
An upload that wrongly carries a large hole now fails the test instead of
filling memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:31:43 -08:00
Chris LuandClaude Opus 5.5 1570202788 sftp: leave the data end alone on an empty write
A zero-length WRITE far past the data moved the data end there, so
Close uploaded the hole before it as zeros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:31:43 -08:00
Chris LuandClaude Opus 5.5 944c3224be sftp: upload only up to the written data on close
Close streamed the whole temp file, so a hole after the data, from a
truncate that grew the file before or during the open, was read back
and uploaded as zeros. Track where the copied and written bytes end,
upload up to there, and keep the rest as the file's size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 23:49:32 -08:00
Chris LuandClaude Opus 5.5 8c45dc42a9 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 <noreply@anthropic.com>
2026-12-03 23:48:25 -08:00
6 changed files with 185 additions and 31 deletions

No files matched your search

+10 -9
View File
@@ -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))
}
}
+7 -1
View File
@@ -9,10 +9,12 @@ import (
"fmt"
"hash"
"io"
"math"
"path"
"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"
@@ -164,11 +166,15 @@ func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (stri
// the filer keeps the MD5 of files uploaded in one piece, and writers
// clear it when they change the content; it is the same MD5 the S3 and
// WebDAV ETags report
size := filer.FileSize(entry)
if size > math.MaxInt64 {
return "", fmt.Errorf("size %d is out of range", size)
}
if kind == "md5" && entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
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(size), ctxWriter{ctx, h}); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
+32
View File
@@ -180,6 +180,25 @@ func TestFileHashStopsWhenCanceled(t *testing.T) {
}
}
// A stored size past the largest file offset fails the hash instead of
// crashing it or reporting the digest of empty input.
func TestFileHashOutOfRangeSize(t *testing.T) {
fs := newCopyTestServer(t, "127.0.0.1:1", map[string]*filer_pb.Entry{
"/home/huge.txt": {Name: "huge.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: 1 << 63, Md5: []byte{0xab}}},
"/home/empty.txt": {Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{}},
})
fs.user.Permissions = map[string][]string{"/": {"read"}}
for _, kind := range []string{"md5", "sha1"} {
if sum, err := fs.fileHash(context.Background(), kind, "/home/huge.txt"); err == nil {
t.Fatalf("%s of an out-of-range size = %s, want an error", kind, sum)
}
}
empty := sha1.Sum(nil)
if sum, err := fs.fileHash(context.Background(), "sha1", "/home/empty.txt"); err != nil || sum != hex.EncodeToString(empty[:]) {
t.Fatalf("hash of an empty file = %s, %v", sum, err)
}
}
// A size change through SFTP drops the stored MD5, which md5sum would report;
// other attribute changes keep it.
func TestSetstatSizeClearsMd5(t *testing.T) {
@@ -202,6 +221,19 @@ func TestSetstatSizeClearsMd5(t *testing.T) {
}
}
func TestSetstatRejectsOutOfRangeSize(t *testing.T) {
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
"/buckets/b": {Name: "b", IsDirectory: true},
"/buckets/b/f": {Name: "f", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: 1}},
})
if err := fs.setFileStat("/buckets/b/f", sftp.FileAttrFlags{Size: true}, &sftp.FileStat{Size: 1 << 63}); err == nil {
t.Fatal("setstat of a size past the largest file offset succeeded")
}
if fake.lastUpdate != nil {
t.Fatalf("stored %v", fake.lastUpdate.Entry)
}
}
func openTestSession(t *testing.T, fs *SftpServer) ssh.Channel {
t.Helper()
_, key, err := ed25519.GenerateKey(rand.Reader)
+21 -2
View File
@@ -72,6 +72,9 @@ type SeaweedSftpFileWriter struct {
// pkg/sftp may run pipelined writes in any order.
append bool
appendFrom int64
// dataEnd is where the copied and written bytes end. Past it, up to the
// temp file's size, the file is a hole that Close does not upload.
dataEnd int64
}
type fileStat struct {
@@ -124,6 +127,7 @@ func (w *SeaweedSftpFileWriter) setStat(flags sftp.FileAttrFlags, attrs *sftp.Fi
return true, err
}
w.appendFrom = min(w.appendFrom, int64(attrs.Size))
w.dataEnd = min(w.dataEnd, int64(attrs.Size))
flags.Size = false
}
w.changed = true // the upload on close applies it
@@ -137,6 +141,9 @@ func (w *SeaweedSftpFileWriter) Write(p []byte) (int, error) {
w.changed = true
n, err := w.tmpFile.WriteAt(p, w.offset)
w.offset += int64(n)
if n > 0 {
w.dataEnd = max(w.dataEnd, w.offset)
}
return n, err
}
@@ -147,7 +154,11 @@ func (w *SeaweedSftpFileWriter) WriteAt(p []byte, off int64) (int, error) {
return 0, fmt.Errorf("append to %s: write at offset %d is below the end of the file", w.req.Filepath, off)
}
w.changed = true
return w.tmpFile.WriteAt(p, off)
n, err := w.tmpFile.WriteAt(p, off)
if n > 0 {
w.dataEnd = max(w.dataEnd, off+int64(n))
}
return n, err
}
// ReadAt reads the file as written so far. Unless the open truncated it, that
@@ -174,6 +185,10 @@ func (w *SeaweedSftpFileWriter) Close() error {
return nil
}
info, err := w.tmpFile.Stat()
if err != nil {
return err
}
if _, err := w.tmpFile.Seek(0, io.SeekStart); err != nil {
return err
}
@@ -198,6 +213,10 @@ func (w *SeaweedSftpFileWriter) Close() error {
}
}
stats := w.setStats
if info.Size() > w.dataEnd {
stats = append(stats, fileStat{flags: sftp.FileAttrFlags{Size: true}, attrs: &sftp.FileStat{Size: uint64(info.Size())}})
}
// Stream the file to the absolute path (after HomeDir translation)
return w.fs.putFile(w.absPath, w.tmpFile, w.fs.user, mode, w.setStats)
return w.fs.putFile(w.absPath, io.LimitReader(w.tmpFile, w.dataEnd), w.fs.user, mode, stats)
}
+32 -18
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
@@ -201,10 +202,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
@@ -228,6 +234,7 @@ func (fs *SftpServer) newFileWriter(r *sftp.Request) (io.WriterAt, error) {
// read-write open reads them, so whether it may read is decided on the
// entry they came from. Without read permission it still writes.
if existing != nil {
w.dataEnd = storedSize(existing)
w.skipUploadIfUnchanged = true
if flags.Read {
w.readErr = fs.checkEntryPermission(absPath, existing, "read")
@@ -280,8 +287,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 +300,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 {
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 {
@@ -536,6 +547,9 @@ func (fs *SftpServer) setFileStat(absPath string, flags sftp.FileAttrFlags, attr
if err := fs.checkFilePermission(absPath, "write"); err != nil {
return err
}
if flags.Size && attrs.Size > math.MaxInt64 {
return fmt.Errorf("size %d is out of range", attrs.Size)
}
entry, err := fs.getEntry(absPath)
if err != nil {
return err
+83 -1
View File
@@ -60,7 +60,7 @@ func newRWTest(t *testing.T, perms ...string) *rwTest {
fs.user.Permissions = map[string][]string{"/buckets": perms}
rw := &rwTest{fs: fs, fake: fake}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
rw.mu.Lock()
rw.bodies = append(rw.bodies, string(body))
rw.mu.Unlock()
@@ -164,6 +164,88 @@ 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))
}
}
// Close uploads the bytes up to the last one copied or written, and keeps a
// hole after them, however it was made, as the file's size.
func TestCloseKeepsTrailingHoleAsSize(t *testing.T) {
const size = 1 << 40
for _, c := range []struct {
name string
flags int
do func(*sftp.File) error
want string
}{
{name: "write in grown file", flags: os.O_RDWR, do: func(f *sftp.File) error {
_, err := f.WriteAt([]byte("y"), 1)
return err
}, want: "xy"},
{name: "empty write past the data", flags: os.O_RDWR, do: func(f *sftp.File) error {
if _, err := f.WriteAt([]byte("y"), 1); err != nil {
return err
}
_, err := f.WriteAt(nil, size-1)
return err
}, want: "xy"},
{name: "ftruncate up", flags: os.O_RDWR | os.O_TRUNC, do: func(f *sftp.File) error {
if _, err := f.Write([]byte("abc")); err != nil {
return err
}
return f.Truncate(size)
}, want: "abc"},
} {
t.Run(c.name, func(t *testing.T) {
rw := newRWTest(t, PermAll)
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", c.flags)
if err != nil {
t.Fatalf("open: %v", err)
}
if err := c.do(f); err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if err := f.Close(); err != nil {
t.Fatalf("close: %v", err)
}
if got := rw.uploads(); len(got) != 1 || got[0] != c.want {
t.Fatalf("uploaded on close = %q, want one upload of %q", got, c.want)
}
if got := rw.fake.lastUpdate.GetEntry().GetAttributes().GetFileSize(); got != size {
t.Fatalf("stored size %d, want %d", got, uint64(size))
}
})
}
}
// 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) {