diff --git a/internal/transfer/atomic.go b/internal/transfer/atomic.go index 499f70b..bf16f54 100644 --- a/internal/transfer/atomic.go +++ b/internal/transfer/atomic.go @@ -1,5 +1,185 @@ 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 { + removeQuiet(ctx, fsys, tmp) + return "", err + } + return tmp, nil +} + +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. +func removeQuiet(ctx context.Context, fsys vfs.FS, p string) { + _ = fsys.Remove(context.WithoutCancel(ctx), p) +} + +// 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) +} diff --git a/internal/transfer/conflict.go b/internal/transfer/conflict.go new file mode 100644 index 0000000..295f647 --- /dev/null +++ b/internal/transfer/conflict.go @@ -0,0 +1,161 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "path" + "strings" + + "vcom/internal/vfs" +) + +// resolve decides what to do with an item whose target exists. +func (e *executor) resolve(it Item, existing vfs.FileInfo, kind ConflictKind) (ResolveAction, error) { + if r, ok := e.applyAll[kind]; ok { + return e.restrict(it, kind, r), nil + } + var a ResolveAction + switch e.opts.Conflict { + case Overwrite: + a = ResolveOverwrite + case Skip: + a = ResolveSkip + case KeepBoth: + a = ResolveKeepBoth + case OverwriteOlder: + a = ResolveSkip + if it.ModTime.After(existing.ModTime) { + a = ResolveOverwrite + } + default: // Ask + if e.h.Resolve == nil { + a = ResolveSkip + break + } + c := Conflict{Item: it, Kind: kind} + c.Item.Existing = &existing + res, err := e.h.Resolve(e.ctx, c) + if err != nil { + return ResolveAbort, err + } + if res.ApplyToAll && res.Action != ResolveAbort { + e.applyAll[kind] = res.Action + } + a = res.Action + } + return e.restrict(it, kind, a), nil +} + +// restrict: a type mismatch (file↔dir, link↔dir) is never overwritten — +// that would mean deleting a directory tree. +func (e *executor) restrict(it Item, kind ConflictKind, a ResolveAction) ResolveAction { + if kind == TypeMismatch && a == ResolveOverwrite { + e.rep.Warnings = append(e.rep.Warnings, it.Rel+": target is of another type (file/directory); not overwritten") + return ResolveSkip + } + return a +} + +func conflictKind(it Item, existing vfs.FileInfo) ConflictKind { + if (it.Kind == Dir) != existing.IsDir() { + return TypeMismatch + } + return FileFile +} + +// keepBothName returns "name (n).ext" for n = 1, 2, ... (".tar.gz" and +// friends stay together; dot-files and directories get no extension split). +func keepBothName(name string, n int, isDir bool) string { + stem, ext := name, "" + if !isDir { + lower := strings.ToLower(name) + for _, double := range []string{".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"} { + if strings.HasSuffix(lower, double) && len(name) > len(double) { + ext = name[len(name)-len(double):] + break + } + } + if ext == "" { + if ext = path.Ext(name); ext == name { + ext = "" + } + } + stem = name[:len(name)-len(ext)] + } + return fmt.Sprintf("%s (%d)%s", stem, n, ext) +} + +// freeRel finds a rel "name (n).ext" that does not exist in the target. +func (e *executor) freeRel(rel string, isDir bool) (string, error) { + parent, name := splitRel(rel) + for n := 1; n <= 10000; n++ { + cand := keepBothName(name, n, isDir) + if parent != "" { + cand = parent + "/" + cand + } + _, err := e.to.Lstat(e.ctx, dstPath(e.to, e.toDir, cand)) + if errors.Is(err, vfs.ErrNotExist) { + return cand, nil + } + if err != nil { + return "", err + } + } + return "", fmt.Errorf("no free name for %s", rel) +} + +var errStop = errors.New("transfer stopped") + +// handleError applies the error policy. It returns errStop to end the +// transfer, nil to skip the item, or errRetry. +func (e *executor) handleError(it Item, op string, err error) error { + if e.ctx.Err() != nil { + return errStop + } + ie := ItemError{Item: it, Op: op, Err: err} + record := func() { + e.rep.Errors = append(e.rep.Errors, ie) + e.rep.Failed++ + e.markIncomplete(it.Rel) + } + if e.skipErrors || e.opts.OnError == ErrorSkipAll { + record() + return nil + } + if e.opts.OnError == ErrorAbort { + record() + e.rep.Err = fmt.Errorf("%w: %v", ErrAborted, ie) + return errStop + } + if e.h.OnError == nil { + record() + return nil + } + a, herr := e.h.OnError(e.ctx, ie) + if herr != nil { + record() + if e.ctx.Err() == nil { + e.rep.Err = herr + } + return errStop + } + switch a { + case ErrorRetry: + return errRetry + case ErrorSkipRest: + e.skipErrors = true + case ErrorStop: + record() + e.rep.Err = fmt.Errorf("%w: %v", ErrAborted, ie) + return errStop + } + record() + return nil +} + +var errRetry = errors.New("retry") + +func isCancel(ctx context.Context, err error) bool { + return ctx.Err() != nil || errors.Is(err, context.Canceled) +} diff --git a/internal/transfer/errors.go b/internal/transfer/errors.go index 5c3ccb7..1f61957 100644 --- a/internal/transfer/errors.go +++ b/internal/transfer/errors.go @@ -11,3 +11,6 @@ var ( ErrReadOnly = errors.New("read-only file system") ErrAborted = errors.New("transfer aborted") ) + +// ErrUnsupportedMove is temporary (task 3.5). +var ErrUnsupportedMove = errors.New("move is not implemented yet") diff --git a/internal/transfer/execute.go b/internal/transfer/execute.go new file mode 100644 index 0000000..b7879de --- /dev/null +++ b/internal/transfer/execute.go @@ -0,0 +1,543 @@ +package transfer + +import ( + "context" + "errors" + "fmt" + "io" + "io/fs" + "sort" + "time" + + "vcom/internal/vfs" +) + +// Execute runs a plan (design §4.3). It never returns early without a +// Report: Report.Cancelled is set when ctx was cancelled, Report.Err on an +// abort. Completed items stay in place; the item in flight leaves nothing +// under its target name. +func Execute(ctx context.Context, plan *Plan, h Hooks) Report { + e := newExecutor(ctx, plan, h) + e.run() + return e.rep +} + +type executor struct { + ctx context.Context + plan *Plan + h Hooks + to vfs.FS + toDir string + opts Options + move bool + + rep Report + prog *emitter + applyAll map[ConflictKind]ResolveAction + skipErrors bool + doneBytes int64 // processed bytes of finished items + renamed map[string]string // rel of a dir written under another name → its new rel + skipped map[string]bool // rel of dirs whose subtree is not written + incomplete map[string]bool // rel of source dirs that keep content (move) + dirFix []dirFix + affected map[string]bool + srcDirs []Item // move: source directories, removed post-order + crossVol bool +} + +type dirFix struct { + path string + mode fs.FileMode // 0: leave + mtime time.Time // zero: leave +} + +func newExecutor(ctx context.Context, plan *Plan, h Hooks) *executor { + e := &executor{ + ctx: ctx, + plan: plan, + h: h, + to: plan.Req.To, + toDir: plan.Req.ToDir, + opts: plan.Req.Opts, + move: plan.Req.Op == Move, + prog: newEmitter(h.Progress, h.ProgressInterval), + applyAll: map[ConflictKind]ResolveAction{}, + renamed: map[string]string{}, + skipped: map[string]bool{}, + incomplete: map[string]bool{}, + affected: map[string]bool{}, + } + if fb, ok := plan.Req.From.(FSBacked); ok { + e.crossVol = fb.FS().Volume() != e.to.Volume() + } else { + e.crossVol = true + } + e.prog.p = Progress{Phase: Copying, FilesTotal: plan.TotalFiles, BytesTotal: plan.TotalBytes} + return e +} + +func (e *executor) run() { + e.rep.Warnings = append(e.rep.Warnings, e.plan.Warnings...) + e.affected[e.toDir] = true + e.prog.emit(true) + + items := e.plan.Items + if e.move { + items = e.renameWhole(items) + } + var err error + if op, ok := e.plan.Req.From.(Opener); ok { + for _, it := range items { + if err = e.process(it, func() (io.ReadCloser, error) { return op.Open(e.ctx, it) }); err != nil { + break + } + } + } else { + err = e.plan.Req.From.Stream(e.ctx, items, func(it Item, r io.Reader) error { + used := false + return e.process(it, func() (io.ReadCloser, error) { + if used { + return nil, errors.New("this source cannot be read twice") + } + used = true + return io.NopCloser(r), nil + }) + }) + } + if err != nil && !errors.Is(err, errStop) && e.rep.Err == nil && !isCancel(e.ctx, err) { + e.rep.Err = err + } + e.finish() +} + +// finish applies directory modes/mtimes (post-order, so read-only source +// directories can be filled: N-P1-17), removes moved source directories and +// fills the report. +func (e *executor) finish() { + bg := context.WithoutCancel(e.ctx) + for i := len(e.dirFix) - 1; i >= 0; i-- { + d := e.dirFix[i] + caps := e.to.Caps() + if caps.Chmod && d.mode != 0 { + if err := e.to.Chmod(bg, d.path, d.mode); err != nil { + e.rep.Warnings = append(e.rep.Warnings, fmt.Sprintf("%s: chmod: %v", d.path, err)) + } + } + if caps.Chtimes && !d.mtime.IsZero() { + if err := e.to.Chtimes(bg, d.path, d.mtime, d.mtime); err != nil { + e.rep.Warnings = append(e.rep.Warnings, fmt.Sprintf("%s: chtimes: %v", d.path, err)) + } + } + } + if e.move && e.ctx.Err() == nil && e.rep.Err == nil { + e.removeSourceDirs() + } + if e.ctx.Err() != nil { + e.rep.Cancelled = true + } + dirs := make([]string, 0, len(e.affected)) + for d := range e.affected { + dirs = append(dirs, d) + } + sort.Strings(dirs) + for _, d := range dirs { + e.rep.Affected = append(e.rep.Affected, vfs.Location{FS: e.to, Path: d}) + } + if e.move { + e.addSourceAffected() + } + e.prog.p.Phase = Finishing + e.prog.p.Current = "" + e.prog.emit(true) +} + +// mapRel applies KeepBoth renames of ancestor directories. +func (e *executor) mapRel(rel string) string { + for i := len(rel) - 1; i > 0; i-- { + if rel[i] != '/' { + continue + } + if nr, ok := e.renamed[rel[:i]]; ok { + return nr + rel[i:] + } + } + return rel +} + +// underSkipped reports whether an ancestor directory was skipped or failed. +func (e *executor) underSkipped(rel string) bool { + for i := len(rel) - 1; i > 0; i-- { + if rel[i] == '/' && e.skipped[rel[:i]] { + return true + } + } + return false +} + +// markIncomplete records that rel stays in the source, so its source +// ancestors must not be removed by a move. +func (e *executor) markIncomplete(rel string) { + for { + parent, _ := splitRel(rel) + if parent == "" { + return + } + e.incomplete[parent] = true + rel = parent + } +} + +func (e *executor) skipItem(it Item) { + if it.Kind != Dir { + e.rep.Skipped++ + e.finishFile(it, false) + } else { + e.skipped[it.Rel] = true + } + e.markIncomplete(it.Rel) +} + +// finishFile advances the per-file counters. +func (e *executor) finishFile(it Item, done bool) { + if it.Kind == File || it.Kind == Symlink { + e.prog.p.FilesDone++ + e.doneBytes += it.Size + } + if done { + e.rep.Done++ + e.rep.Bytes += it.Size + } + e.prog.p.BytesDone = e.doneBytes + e.prog.p.CurrentDone, e.prog.p.CurrentSize = 0, 0 + e.prog.emit(false) +} + +func (e *executor) process(it Item, open func() (io.ReadCloser, error)) error { + if err := e.ctx.Err(); err != nil { + return errStop + } + if e.underSkipped(it.Rel) { + e.skipItem(it) + return nil + } + e.prog.p.Current = it.Rel + var err error + switch it.Kind { + case Special: + e.rep.Skipped++ + e.markIncomplete(it.Rel) // already in plan.Warnings + case Dir: + err = e.doDir(it) + default: + err = e.doFile(it, open) + } + return err +} + +func (e *executor) parentAffected(rel string) { + parent, _ := splitRel(rel) + if parent == "" { + e.affected[e.toDir] = true + return + } + e.affected[dstPath(e.to, e.toDir, parent)] = true +} + +// perm is the mode to give a written item. +func (e *executor) perm(it Item) fs.FileMode { + if !e.opts.PreserveMode { + if it.Kind == Dir { + return 0o755 + } + return 0o644 + } + m := it.Mode & (fs.ModePerm | fs.ModeSticky) + if !e.crossVol { + m |= it.Mode & (fs.ModeSetuid | fs.ModeSetgid) + } + return m +} + +func (e *executor) doDir(it Item) error { + rel := e.mapRel(it.Rel) + dst := dstPath(e.to, e.toDir, rel) + if e.move { + e.srcDirs = append(e.srcDirs, it) + } + if it.ScanErr != nil { + for { + switch err := e.handleError(it, "scan", it.ScanErr); err { + case errRetry: + continue // a directory listing from Prepare cannot be redone here + case nil: + e.skipped[it.Rel] = true + return nil + default: + return err + } + } + } + existing := it.Existing + for attempt := 0; ; attempt++ { + if existing != nil { + if existing.IsDir() { + e.fixDir(it, dst, false) + return nil + } + a, err := e.resolve(it, *existing, TypeMismatch) + if err != nil { + e.rep.Err = err + return errStop + } + switch a { + case ResolveAbort: + e.rep.Err = ErrAborted + return errStop + case ResolveKeepBoth: + nr, err := e.freeRel(rel, true) + if err != nil { + return e.dirFailed(it, "mkdir", err) + } + e.renamed[it.Rel] = nr + rel, dst, existing = nr, dstPath(e.to, e.toDir, nr), nil + continue + default: + e.skipItem(it) + return nil + } + } + err := e.to.Mkdir(e.ctx, dst, 0o700) + if err == nil { + e.parentAffected(rel) + e.affected[dst] = true + e.fixDir(it, dst, true) + return nil + } + if errors.Is(err, vfs.ErrExist) && attempt < 3 { + fi, lerr := e.to.Lstat(e.ctx, dst) + if lerr == nil { + existing = &fi // appeared after the plan: merge or conflict + continue + } + } + if r := e.handleError(it, "mkdir", err); r != errRetry { + if r == nil { + e.skipped[it.Rel] = true + } + return r + } + } +} + +func (e *executor) dirFailed(it Item, op string, err error) error { + r := e.handleError(it, op, err) + if r == nil || r == errRetry { + e.skipped[it.Rel] = true + return nil + } + return r +} + +// fixDir schedules mode/mtime for a directory: created ones get the real +// mode after they are filled; existing ones only when preserving. +func (e *executor) fixDir(it Item, dst string, created bool) { + f := dirFix{path: dst} + if created || e.opts.PreserveMode { + f.mode = e.perm(it) + } + if e.opts.PreserveTimes { + f.mtime = it.ModTime + } + if f.mode != 0 || !f.mtime.IsZero() { + e.dirFix = append(e.dirFix, f) + } +} + +// doFile copies a file or symlink item. +func (e *executor) doFile(it Item, open func() (io.ReadCloser, error)) error { + rel := e.mapRel(it.Rel) + replace := false + if it.Existing != nil { + switch next, err := e.decide(it, &rel, *it.Existing); { + case err != nil: + return err + case next == ResolveSkip: + e.skipItem(it) + return nil + case next == ResolveOverwrite: + replace = true + } + } + for { + dst := dstPath(e.to, e.toDir, rel) + e.prog.p.CurrentSize = it.Size + tmp, op, err := e.writeItem(it, dst, replace, open) + if err == nil { + err, op = e.commitItem(it, &rel, tmp, &replace), "rename" + if errors.Is(err, errSkipItem) { + e.skipItem(it) + return nil + } + if errors.Is(err, errStop) { + return err + } + } + if err == nil { + e.parentAffected(rel) + if e.move { + if rerr := e.removeSource(it); rerr != nil { + return rerr + } + } + e.finishFile(it, true) + return nil + } + if isCancel(e.ctx, err) { + return errStop + } + switch r := e.handleError(it, op, err); r { + case errRetry: + continue + case nil: + e.finishFile(it, false) + return nil + default: + return r + } + } +} + +// decide resolves a planned or runtime conflict for a file item; for +// KeepBoth it rewrites *rel to a free name. +func (e *executor) decide(it Item, rel *string, existing vfs.FileInfo) (ResolveAction, error) { + a, err := e.resolve(it, existing, conflictKind(it, existing)) + if err != nil { + e.rep.Err = err + return 0, errStop + } + switch a { + case ResolveAbort: + e.rep.Err = ErrAborted + return 0, errStop + case ResolveKeepBoth: + nr, err := e.freeRel(*rel, false) + if err != nil { + return 0, err + } + *rel = nr + return ResolveKeepBoth, nil + } + return a, nil +} + +var errSkipItem = errors.New("skip item") + +// commitItem renames the temp into place; a target that appeared after the +// plan is a conflict resolved by policy (Ask asks). +func (e *executor) commitItem(it Item, rel *string, tmp string, replace *bool) error { + for range 5 { + dst := dstPath(e.to, e.toDir, *rel) + err := commit(e.ctx, e.to, tmp, dst, *replace) + if !errors.Is(err, vfs.ErrExist) || *replace { + if err != nil { + removeQuiet(e.ctx, e.to, tmp) + } + return err + } + fi, lerr := e.to.Lstat(e.ctx, dst) + if lerr != nil { + removeQuiet(e.ctx, e.to, tmp) + return lerr + } + a, derr := e.decide(it, rel, fi) + if derr != nil { + removeQuiet(e.ctx, e.to, tmp) + return derr + } + switch a { + case ResolveSkip: + removeQuiet(e.ctx, e.to, tmp) + return errSkipItem + case ResolveOverwrite: + *replace = true + } + } + removeQuiet(e.ctx, e.to, tmp) + return fmt.Errorf("%s: target keeps changing", *rel) +} + +// writeItem produces the temp file (or temp symlink) next to dst. +func (e *executor) writeItem(it Item, dst string, replace bool, open func() (io.ReadCloser, error)) (string, string, error) { + if it.Kind == Symlink { + if !e.to.Caps().Symlinks { + return "", "symlink", fmt.Errorf("%w: symlinks on %s", vfs.ErrUnsupported, e.to.Label()) + } + var err error + for range 8 { + tmp := tempName(e.to, dst, partPrefix) + if err = e.to.Symlink(e.ctx, it.LinkTarget, tmp); err == nil { + return tmp, "symlink", nil + } + if !errors.Is(err, vfs.ErrExist) { + break + } + } + return "", "symlink", err + } + + src, err := open() + if err != nil { + return "", "read", err + } + defer src.Close() + o := WriteOptions{ + Perm: e.perm(it), + Fsync: e.opts.Fsync == FsyncAlways || (e.opts.Fsync == FsyncReplace && replace), + } + if e.opts.PreserveTimes { + o.ModTime = it.ModTime + } + pr := &progressReader{ctx: e.ctx, r: src, size: it.Size, onRead: func(n int64) { + e.prog.p.CurrentDone = n + e.prog.p.BytesDone = e.doneBytes + min(n, it.Size) + e.prog.emit(false) + }} + var readErr error + tmp, err := writeTemp(e.ctx, e.to, dst, o, func(w io.Writer) error { + _, err := io.Copy(w, readTracker{pr, &readErr}) + return err + }) + if err != nil { + op := "write" + if readErr != nil && errors.Is(err, readErr) { + op = "read" + } + return "", op, err + } + if e.move && pr.n != it.Size { + removeQuiet(e.ctx, e.to, tmp) + return "", "read", fmt.Errorf("source changed during the move: read %d of %d bytes", pr.n, it.Size) + } + return tmp, "write", nil +} + +// readTracker remembers a read error so it can be told from a write error. +type readTracker struct { + r io.Reader + err *error +} + +func (t readTracker) Read(p []byte) (int, error) { + n, err := t.r.Read(p) + if err != nil && err != io.EOF { + *t.err = err + } + return n, err +} + +func (t readTracker) Size() int64 { + if s, ok := t.r.(interface{ Size() int64 }); ok { + return s.Size() + } + return 0 +} diff --git a/internal/transfer/execute_test.go b/internal/transfer/execute_test.go new file mode 100644 index 0000000..e9182af --- /dev/null +++ b/internal/transfer/execute_test.go @@ -0,0 +1,386 @@ +package transfer + +import ( + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/vfs" + "vcom/internal/vfs/vfstest" +) + +// run prepares and executes; it fails the test on a Prepare error. +func run(t *testing.T, r Request, h Hooks) (*Plan, Report) { + t.Helper() + plan, err := Prepare(bg, r, nil) + if err != nil { + t.Fatalf("prepare: %v", err) + } + return plan, Execute(bg, plan, h) +} + +func overwrite(o *Options) { o.Conflict = Overwrite } +func skipAll(o *Options) { o.OnError = ErrorSkipAll } +func follow(o *Options) { o.Symlinks = FollowLinks } + +func TestOverwriteFailureKeepsDest(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("f.txt", "").WithSize(300 << 10)}, + fstree.Spec{fstree.File("f.txt", "OLD VALUABLE")}) + to := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 2, syscall.ENOSPC)} + _, rep := run(t, req(Copy, local, join(src, "f.txt"), to, dst, overwrite, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Done != 0 || len(rep.Errors) != 1 || !errors.Is(rep.Errors[0].Err, syscall.ENOSPC) { + t.Fatalf("report %+v", rep) + } + if rep.Errors[0].Op != "write" { + t.Fatalf("op %q", rep.Errors[0].Op) + } + if got := read(t, filepath.Join(dst, "f.txt")); got != "OLD VALUABLE" { + t.Fatalf("old target damaged: %q (N-P0-4)", got) + } + noLeftovers(t, dst) + + // Unreadable source (the testbed case): the old target survives too. + if os.Geteuid() != 0 { + if err := os.Chmod(filepath.Join(src, "f.txt"), 0); err != nil { + t.Fatal(err) + } + _, rep = run(t, req(Copy, local, join(src, "f.txt"), local, dst, overwrite, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Errors[0].Op != "read" || !errors.Is(rep.Errors[0].Err, vfs.ErrPermission) { + t.Fatalf("unreadable source: %+v", rep) + } + if got := read(t, filepath.Join(dst, "f.txt")); got != "OLD VALUABLE" { + t.Fatalf("old target damaged by unreadable source: %q", got) + } + noLeftovers(t, dst) + } +} + +func TestCloseErrorIsItemError(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("a", "data")}, nil) + closeErr := errors.New("EIO on close") + to := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpClose, 1, closeErr)} + _, rep := run(t, req(Copy, local, join(src, "a"), to, dst, skipAll), Hooks{}) + if rep.Failed != 1 || rep.Done != 0 || !errors.Is(rep.Errors[0].Err, closeErr) { + t.Fatalf("close error must fail the item (N-P2-6): %+v", rep) + } + if _, err := os.Lstat(filepath.Join(dst, "a")); !os.IsNotExist(err) { + t.Fatal("file committed despite the close error") + } + noLeftovers(t, dst) +} + +func TestDirMergeKeepsExtra(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.File("proj/a.txt", "new"), fstree.File("proj/sub/b", "b")}, + fstree.Spec{fstree.File("proj/keep.txt", "user data"), fstree.File("proj/a.txt", "old"), fstree.File("proj/sub/c", "c")}) + _, rep := run(t, req(Copy, local, join(src, "proj"), local, dst, overwrite), Hooks{}) + if rep.Err != nil || rep.Done != 2 { + t.Fatalf("report %+v", rep) + } + fstree.Equal(t, fstree.FromSpec(fstree.Spec{ + fstree.File("proj/a.txt", "new"), + fstree.File("proj/keep.txt", "user data"), + fstree.File("proj/sub/b", "b"), + fstree.File("proj/sub/c", "c"), + }), fstree.Snapshot(t, dst), fstree.Opts{}) +} + +func TestCopyReadOnlyDir(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("ro/a.txt", "x"), + fstree.File("ro/inner/b", "y"), + fstree.Dir("ro/inner").WithMode(0o555), + fstree.Dir("ro").WithMode(0o555), + }, nil) + t.Cleanup(func() { + for _, d := range []string{filepath.Join(dst, "ro"), filepath.Join(dst, "ro", "inner")} { + _ = os.Chmod(d, 0o755) + } + }) + _, rep := run(t, req(Copy, local, join(src, "ro"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("copying a read-only dir failed (N-P1-17): %+v", rep) + } + for _, d := range []string{"ro", "ro/inner"} { + if fi, _ := os.Stat(filepath.Join(dst, d)); fi.Mode().Perm() != 0o555 { + t.Errorf("%s mode %v, want 0555", d, fi.Mode().Perm()) + } + } + if read(t, filepath.Join(dst, "ro", "inner", "b")) != "y" { + t.Fatal("content missing") + } +} + +func TestLocalMtime(t *testing.T) { + old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + src, dst := layout(t, fstree.Spec{ + fstree.File("d/f.txt", "x").WithMTime(old), + fstree.Dir("d").WithMTime(old.Add(time.Hour)), + }, nil) + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{}) + if rep.Err != nil || rep.Done != 1 { + t.Fatalf("%+v", rep) + } + if fi, _ := os.Stat(filepath.Join(dst, "d", "f.txt")); !fi.ModTime().Equal(old) { + t.Fatalf("file mtime %v (N-P1-9)", fi.ModTime()) + } + if fi, _ := os.Stat(filepath.Join(dst, "d")); !fi.ModTime().Equal(old.Add(time.Hour)) { + t.Fatalf("dir mtime %v", fi.ModTime()) + } +} + +func TestPermsPreserved(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("run.sh", "#!/bin/sh").WithMode(0o755), + fstree.File("secret", "s").WithMode(0o600), + fstree.Dir("shared"), + }, nil) + if err := os.Chmod(filepath.Join(src, "shared"), 0o777|fs.ModeSticky); err != nil { + t.Fatal(err) + } + _, rep := run(t, req(Copy, local, join(src, "run.sh", "secret", "shared"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + for name, want := range map[string]fs.FileMode{"run.sh": 0o755, "secret": 0o600, "shared": 0o777 | fs.ModeSticky} { + fi, _ := os.Stat(filepath.Join(dst, name)) + if got := fi.Mode() & (fs.ModePerm | fs.ModeSticky); got != want { + t.Errorf("%s mode %v, want %v", name, got, want) + } + } + // PreserveMode off: plain defaults. + _, dst2 := layout(t, nil, nil) + _, rep = run(t, req(Copy, local, join(src, "run.sh"), local, dst2, func(o *Options) { o.PreserveMode = false }), Hooks{}) + if fi, _ := os.Stat(filepath.Join(dst2, "run.sh")); rep.Done != 1 || fi.Mode().Perm() != 0o644 { + t.Fatalf("PreserveMode=false: %v", fi.Mode()) + } +} + +func TestBrokenSymlinkCopiedAsLink(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.Symlink("dir/broken", "nowhere"), fstree.File("dir/f", "x")}, nil) + _, rep := run(t, req(Copy, local, join(src, "dir"), local, dst), Hooks{}) + if rep.Err != nil || rep.Failed != 0 || rep.Done != 2 { + t.Fatalf("%+v", rep) + } + if tgt, err := os.Readlink(filepath.Join(dst, "dir", "broken")); err != nil || tgt != "nowhere" { + t.Fatalf("broken link: %q %v (N-P1-8)", tgt, err) + } + noLeftovers(t, dst) +} + +func TestSymlinkToDirCopiedAsLink(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("data/big", "").WithSize(1 << 20), + fstree.Symlink("proj/link", "../data"), + fstree.File("proj/own", "o"), + }, nil) + plan, rep := run(t, req(Copy, local, join(src, "proj"), local, dst), Hooks{}) + if rep.Err != nil || rep.Done != 2 || plan.TotalBytes != 1 { + t.Fatalf("plan bytes %d, report %+v", plan.TotalBytes, rep) + } + if fi, err := os.Lstat(filepath.Join(dst, "proj", "link")); err != nil || fi.Mode()&fs.ModeSymlink == 0 { + t.Fatal("link to a directory was not copied as a link") + } + // A link given as a root is copied as a link too. + _, dst2 := layout(t, nil, nil) + if _, rep := run(t, req(Copy, local, join(src, "proj/link"), local, dst2), Hooks{}); rep.Done != 1 { + t.Fatalf("%+v", rep) + } + if tgt, _ := os.Readlink(filepath.Join(dst2, "link")); tgt != "../data" { + t.Fatalf("root link target %q", tgt) + } +} + +func TestFollowLinksCycle(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/f", "x"), + fstree.Symlink("d/loop", "."), + fstree.Symlink("d/up", ".."), + fstree.File("ext/g", "g"), + fstree.Symlink("d/ext", "../ext"), + }, nil) + plan, rep := run(t, req(Copy, local, join(src, "d"), local, dst, follow), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + if len(plan.Warnings) == 0 || !strings.Contains(plan.Warnings[0], "d/loop: symlink loop") { + t.Fatalf("warnings %v", plan.Warnings) + } + for _, w := range plan.Warnings { + if !strings.Contains(w, "symlink loop") { + t.Fatalf("unexpected warning %q", w) + } + } + // ext followed: a real directory with the file. + if fi, err := os.Lstat(filepath.Join(dst, "d", "ext")); err != nil || !fi.IsDir() || read(t, filepath.Join(dst, "d", "ext", "g")) != "g" { + t.Fatal("followed link to a directory not copied as a directory") + } + // up (→ src) is no ancestor of d, so it is followed once; its own d/loop + // and d/up inside are cut as loops — the walk terminates. + if fi, err := os.Lstat(filepath.Join(dst, "d", "loop")); err != nil || fi.Mode()&fs.ModeSymlink == 0 { + t.Fatal("loop must stay a link") + } +} + +func TestFifoSkippedWithWarning(t *testing.T) { + src, dst := layout(t, fstree.Spec{fstree.FIFO("d/pipe"), fstree.File("d/f", "x")}, nil) + done := make(chan Report, 1) + go func() { + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{}) + done <- rep + }() + select { + case rep := <-done: + if rep.Done != 1 || rep.Skipped != 1 || len(rep.Warnings) != 1 || !strings.Contains(rep.Warnings[0], "d/pipe") { + t.Fatalf("%+v", rep) + } + case <-time.After(5 * time.Second): + t.Fatal("blocked reading a FIFO (U-P1-10)") + } + if _, err := os.Lstat(filepath.Join(dst, "d", "pipe")); !os.IsNotExist(err) { + t.Fatal("FIFO copied") + } +} + +func TestNoTempLeftovers(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/a", "").WithSize(100 << 10), + fstree.File("d/b", "b"), + fstree.Symlink("d/l", "a"), + }, fstree.Spec{fstree.File("d/a", "old"), fstree.File("d/l", "old")}) + hooks := map[string]func(vfstest.Op, string) error{ + "write": vfstest.FailNth(vfstest.OpWrite, 2, syscall.EIO), + "close": vfstest.FailNth(vfstest.OpClose, 1, syscall.EIO), + "chmod": vfstest.FailNth(vfstest.OpChmod, 1, syscall.EPERM), + "chtimes": vfstest.FailNth(vfstest.OpChtimes, 1, syscall.EPERM), + "rename": vfstest.FailNth(vfstest.OpRename, 2, syscall.EIO), + "symlink": func(op vfstest.Op, _ string) error { + if op == vfstest.OpSymlink { + return syscall.EIO + } + return nil + }, + } + for name, hook := range hooks { + to := &vfstest.FaultFS{FS: local, Hook: hook} + _, rep := run(t, req(Copy, local, join(src, "d"), to, dst, overwrite, skipAll), Hooks{}) + if rep.Failed == 0 { + t.Errorf("%s: no failure injected? %+v", name, rep) + } + noLeftovers(t, dst) + if got := read(t, filepath.Join(dst, "d", "a")); got != "old" && len(got) != 100<<10 { + t.Errorf("%s: target a is partial (%d bytes)", name, len(got)) + } + } +} + +// atomicOff hides atomic replace, as on an SFTP server without posix-rename. +type atomicOff struct{ vfs.FS } + +func (a atomicOff) Caps() vfs.Caps { + c := a.FS.Caps() + c.AtomicReplace = false + return c +} + +func (a atomicOff) Rename(ctx context.Context, from, to string, mode vfs.RenameMode) error { + if mode == vfs.Replace { + return errors.New("Replace used without Caps.AtomicReplace") + } + return a.FS.Rename(ctx, from, to, mode) +} + +func TestWriteAtomicWithoutAtomicReplace(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "f") + if err := os.WriteFile(p, []byte("old"), 0o600); err != nil { + t.Fatal(err) + } + fsys := atomicOff{local} + write := func(s string) error { + return WriteAtomic(bg, fsys, p, WriteOptions{Replace: true, Perm: 0o640}, func(w io.Writer) error { + _, err := io.WriteString(w, s) + return err + }) + } + if err := write("new"); err != nil { + t.Fatal(err) + } + if read(t, p) != "new" { + t.Fatal("not replaced") + } + noLeftovers(t, dir) + // Without Replace an existing target is ErrExist and stays. + err := WriteAtomic(bg, local, p, WriteOptions{}, func(w io.Writer) error { _, err := io.WriteString(w, "x"); return err }) + if !errors.Is(err, vfs.ErrExist) || read(t, p) != "new" { + t.Fatalf("no-replace: %v", err) + } + noLeftovers(t, dir) + if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 { + t.Fatalf("mode %v", fi.Mode()) + } + // A very long name still fits NAME_MAX in the temp name. + long := filepath.Join(dir, strings.Repeat("я", 127)) // 254 bytes + if err := WriteAtomic(bg, local, long, WriteOptions{}, func(w io.Writer) error { return nil }); err != nil { + t.Fatalf("long name: %v", err) + } +} + +func TestProgressHonestAndThrottled(t *testing.T) { + src, dst := layout(t, fstree.Spec{ + fstree.File("d/big", "").WithSize(4 << 20), + fstree.File("d/small", "12345"), + }, nil) + var calls []Progress + plan, rep := run(t, req(Copy, local, join(src, "d"), local, dst), Hooks{ + Progress: func(p Progress) { calls = append(calls, p) }, + ProgressInterval: time.Hour, + }) + if rep.Err != nil || rep.Bytes != plan.TotalBytes { + t.Fatalf("%+v", rep) + } + if len(calls) > 3 { + t.Fatalf("%d progress calls with a 1h interval: not throttled", len(calls)) + } + last := calls[len(calls)-1] + if last.BytesTotal != 4<<20+5 || last.BytesDone != last.BytesTotal || last.FilesDone != 2 || last.FilesTotal != 2 { + t.Fatalf("final progress %+v", last) + } + // Default interval: several calls, monotonic, never above the total. + calls = nil + _, dst2 := layout(t, nil, nil) + _, _ = run(t, req(Copy, local, join(src, "d"), local, dst2), Hooks{ + Progress: func(p Progress) { calls = append(calls, p) }, + ProgressInterval: time.Nanosecond, + }) + for i := 1; i < len(calls); i++ { + if calls[i].BytesDone < calls[i-1].BytesDone || calls[i].BytesDone > calls[i].BytesTotal { + t.Fatalf("progress not monotonic/bounded at %d: %+v -> %+v", i, calls[i-1], calls[i]) + } + } + if len(calls) < 10 { + t.Fatalf("only %d progress calls for a 4 MiB file", len(calls)) + } +} + +func TestSourceNeverModified(t *testing.T) { + spec := fstree.Spec{ + fstree.File("d/a", "aaa").WithMode(0o640).WithMTime(time.Unix(1e9, 0)), + fstree.Symlink("d/l", "a"), + fstree.Dir("d/sub").WithMode(0o700), + } + src, dst := layout(t, spec, fstree.Spec{fstree.File("d/a", "other")}) + before := fstree.Snapshot(t, src) + _, rep := run(t, req(Copy, local, join(src, "d"), local, dst, overwrite), Hooks{}) + if rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%+v", rep) + } + fstree.Equal(t, before, fstree.Snapshot(t, src), fstree.Opts{Mode: true, MTime: true, Links: true}) +} diff --git a/internal/transfer/move.go b/internal/transfer/move.go new file mode 100644 index 0000000..07fea5f --- /dev/null +++ b/internal/transfer/move.go @@ -0,0 +1,12 @@ +package transfer + +// Move support lands in task 3.5; until then Execute refuses Op Move. + +func (e *executor) renameWhole(items []Item) []Item { + e.rep.Err = ErrUnsupportedMove + return nil +} + +func (e *executor) removeSource(Item) error { return nil } +func (e *executor) removeSourceDirs() {} +func (e *executor) addSourceAffected() {} diff --git a/internal/transfer/reader.go b/internal/transfer/reader.go new file mode 100644 index 0000000..f831238 --- /dev/null +++ b/internal/transfer/reader.go @@ -0,0 +1,65 @@ +package transfer + +import ( + "context" + "io" + "time" +) + +// progressReader checks ctx before every chunk (cancellation inside a file: +// N-P1-7) and reports bytes read. Size lets pkg/sftp pick its concurrent +// ReadFrom path. +type progressReader struct { + ctx context.Context + r io.Reader + size int64 + n int64 + onRead func(total int64) +} + +func (r *progressReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + n, err := r.r.Read(p) + if n > 0 { + r.n += int64(n) + if r.onRead != nil { + r.onRead(r.n) + } + } + return n, err +} + +func (r *progressReader) Size() int64 { return r.size } + +// defaultProgressInterval bounds how often Hooks.Progress is called. +const defaultProgressInterval = 50 * time.Millisecond + +// emitter throttles progress callbacks. +type emitter struct { + fn func(Progress) + every time.Duration + last time.Time + p Progress +} + +func newEmitter(fn func(Progress), every time.Duration) *emitter { + if every <= 0 { + every = defaultProgressInterval + } + return &emitter{fn: fn, every: every} +} + +// emit calls fn if the interval has passed or force is set. +func (e *emitter) emit(force bool) { + if e.fn == nil { + return + } + now := time.Now() + if !force && now.Sub(e.last) < e.every { + return + } + e.last = now + e.fn(e.p) +}