diff --git a/internal/vfs/write.go b/internal/vfs/write.go index e83227a..90181ce 100644 --- a/internal/vfs/write.go +++ b/internal/vfs/write.go @@ -49,7 +49,9 @@ func (f *FS) Filewrite(r *sftp.Request) (io.WriterAt, error) { if !ok { return nil, failure("too many concurrent transfers") } - return newWriter(ctx, f, files, loc.rest, release, flags.Creat || flags.Trunc, !exists || flags.Trunc), nil + // An existing file opened without O_TRUNC is left untouched when nothing is written. + create := (!exists && flags.Creat) || flags.Trunc + return newWriter(ctx, f, files, loc.rest, release, create, !exists || flags.Trunc), nil } // Limits on how far out of order a client's writes may arrive. pkg/sftp @@ -76,7 +78,7 @@ type writer struct { fs *FS files *apiclient.Files path string - create bool // Creat or Trunc was set: a write-less close still creates the file + create bool // a new file opened with Creat, or any Trunc: a write-less close still creates an empty file (an existing file opened without Trunc is left unchanged) baseKnown bool // the stream must start at offset 0 (new or truncated file) release func() pr *io.PipeReader @@ -266,8 +268,9 @@ func (w *writer) TransferError(err error) { } // Close ends the upload. A clean end commits it. An aborted upload, or one -// with a gap that never filled, commits nothing. An unstarted create or -// truncate with no data makes an empty file. Close is idempotent. +// with a gap that never filled, commits nothing. An unstarted create of a new +// file, or an unstarted truncate, with no data makes an empty file. An existing +// file opened without truncation is left unchanged. Close is idempotent. func (w *writer) Close() error { w.mu.Lock() defer w.mu.Unlock() diff --git a/internal/vfs/write_existing_test.go b/internal/vfs/write_existing_test.go new file mode 100644 index 0000000..5d9e322 --- /dev/null +++ b/internal/vfs/write_existing_test.go @@ -0,0 +1,29 @@ +package vfs + +import ( + "bytes" + "testing" +) + +// An existing file opened with CREAT but without TRUNC, then closed with no +// writes, must keep its contents. A write-less close may only create an empty +// file when the file is new or truncation was requested. +func TestCreatWithoutTruncOnExistingFileKeepsContents(t *testing.T) { + fx := newFixture(t, nil, Options{}, testServers) + original := []byte("server.properties contents") + fx.api.seedFile(testNS, "survival", "/keep.properties", original) + + w, err := fx.fs.Filewrite(openReq("/survival/keep.properties", fxfWrite|fxfCreat)) + if err != nil { + t.Fatalf("open: %v", err) + } + closeOrFail(t, w) + + got, ok := fx.api.fileData(testNS, "survival", "/keep.properties") + if !ok { + t.Fatalf("existing file was removed by a write-less CREAT close") + } + if !bytes.Equal(got, original) { + t.Fatalf("existing file changed by a write-less CREAT close: got %q, want %q", got, original) + } +}