package transfer
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"time"
"unicode/utf8"
"vcom/internal/vfs"
)
// oldPrefix names the aside copy of a replaced file on FSes without atomic
// replace:
/.vcom-old-<8hex>-.
const oldPrefix = ".vcom-old-"
// maxName is NAME_MAX on Linux and OpenSSH servers.
const maxName = 255
// WriteOptions control WriteAtomic.
type WriteOptions struct {
Perm fs.FileMode // final mode (0 → 0644); the temp file is 0600 while being written
ModTime time.Time // zero → leave as written
Replace bool // replace an existing target (else ErrExist if it exists)
Fsync bool // fsync before the rename (if the FS supports it)
}
// WriteAtomic is the only way the engine (and archive.Create, remote edit)
// writes a file: fill writes into /.vcom-part-<8hex>-, which is
// then closed, chmod'ed, chtimes'ed and renamed over path. On any error or
// cancellation the temp file is removed and an existing target is untouched:
// it is replaced only by the final rename (N-P0-4). A Close error is an
// error (N-P2-6).
func WriteAtomic(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) error {
tmp, err := writeTemp(ctx, fsys, path, o, fill)
if err != nil {
return err
}
if err := commit(ctx, fsys, tmp, path, o.Replace); err != nil {
removeQuiet(ctx, fsys, tmp)
return err
}
return nil
}
// tempName returns /<8hex>-, truncating name so the result
// fits NAME_MAX.
func tempName(fsys vfs.FS, path, prefix string) string {
ops := fsys.Paths()
var b [4]byte
_, _ = rand.Read(b[:])
head := prefix + hex.EncodeToString(b[:]) + "-"
name := ops.Base(path)
if len(head)+len(name) > maxName {
name = name[:maxName-len(head)]
for len(name) > 0 && !utf8.ValidString(name) {
name = name[:len(name)-1]
}
}
return ops.Join(ops.Dir(path), head+name)
}
// writeTemp writes the content into a fresh temp file next to path and
// returns its name; on error nothing is left behind.
func writeTemp(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) (string, error) {
if err := ctx.Err(); err != nil {
return "", err
}
var (
tmp string
f vfs.File
err error
)
for range 8 {
tmp = tempName(fsys, path, partPrefix)
f, err = fsys.Create(ctx, tmp, 0o600, vfs.CreateExcl)
if !errors.Is(err, vfs.ErrExist) {
break
}
}
if err != nil {
return "", err
}
// A hung network write is released by closing the file on cancel.
stop := context.AfterFunc(ctx, func() { _ = f.Close() })
err = fill(&ctxWriter{ctx: ctx, f: f})
if err == nil && o.Fsync && fsys.Caps().Fsync {
err = f.Sync()
}
var cerr error
if stop() {
cerr = f.Close()
}
if ctx.Err() != nil {
err = ctx.Err()
}
if err == nil && cerr != nil {
err = fmt.Errorf("close: %w", cerr)
}
if err == nil {
err = finishMeta(ctx, fsys, tmp, o)
}
if err != nil {
if rerr := removeQuiet(ctx, fsys, tmp); rerr != nil {
return "", &leftoverError{path: tmp, err: err}
}
return "", err
}
return tmp, nil
}
// leftoverError: the operation failed and its temp file could not be
// removed either (typically a dead connection). The executor removes it
// later — on a retry or at the end of the transfer.
type leftoverError struct {
path string
err error
}
func (e *leftoverError) Error() string { return e.err.Error() }
func (e *leftoverError) Unwrap() error { return e.err }
func finishMeta(ctx context.Context, fsys vfs.FS, p string, o WriteOptions) error {
caps := fsys.Caps()
perm := o.Perm
if perm == 0 {
perm = 0o644
}
if caps.Chmod {
if err := fsys.Chmod(ctx, p, perm); err != nil {
return err
}
}
if caps.Chtimes && !o.ModTime.IsZero() {
if err := fsys.Chtimes(ctx, p, o.ModTime, o.ModTime); err != nil {
return err
}
}
return nil
}
// commit renames tmp to path. Without replace it fails with ErrExist when
// path exists. With replace on an FS without atomic replace it renames the
// old target aside first and restores it if the second rename fails.
func commit(ctx context.Context, fsys vfs.FS, tmp, path string, replace bool) error {
if !replace {
return fsys.Rename(ctx, tmp, path, vfs.NoReplace)
}
if fsys.Caps().AtomicReplace {
return fsys.Rename(ctx, tmp, path, vfs.Replace)
}
err := fsys.Rename(ctx, tmp, path, vfs.NoReplace)
if !errors.Is(err, vfs.ErrExist) {
return err
}
old := tempName(fsys, path, oldPrefix)
if err := fsys.Rename(ctx, path, old, vfs.NoReplace); err != nil {
return err
}
if err := fsys.Rename(ctx, tmp, path, vfs.NoReplace); err != nil {
if rerr := fsys.Rename(context.WithoutCancel(ctx), old, path, vfs.NoReplace); rerr != nil {
return fmt.Errorf("%w (and restoring the old file from %s failed: %v)", err, old, rerr)
}
return err
}
removeQuiet(ctx, fsys, old)
return nil
}
// removeQuiet deletes a temp file even when ctx is already cancelled. A
// file that is already gone is not an error.
func removeQuiet(ctx context.Context, fsys vfs.FS, p string) error {
err := fsys.Remove(context.WithoutCancel(ctx), p)
if err == nil || errors.Is(err, vfs.ErrNotExist) {
return nil
}
return err
}
// ctxWriter stops writing once ctx is done and keeps the File's ReadFrom
// (pkg/sftp uses it for concurrent writes; N-P1-6).
type ctxWriter struct {
ctx context.Context
f vfs.File
}
func (w *ctxWriter) Write(p []byte) (int, error) {
if err := w.ctx.Err(); err != nil {
return 0, err
}
return w.f.Write(p)
}
func (w *ctxWriter) ReadFrom(r io.Reader) (int64, error) {
if rf, ok := w.f.(io.ReaderFrom); ok {
return rf.ReadFrom(r)
}
return io.Copy(struct{ io.Writer }{w}, r)
}