diff --git a/internal/archive/create.go b/internal/archive/create.go new file mode 100644 index 0000000..999e9c9 --- /dev/null +++ b/internal/archive/create.go @@ -0,0 +1,386 @@ +package archive + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "io/fs" + "strings" + "time" + + "vcom/internal/transfer" + "vcom/internal/vfs" +) + +// Create errors. +var ( + ErrSameFile = errors.New("the archive would overwrite one of its sources") + ErrIntoSource = errors.New("the archive would be written inside a source directory") +) + +// Create writes the given sources (any FS) into archivePath on dst (any FS) +// in format f (design ยง5.1). The archive is written through +// transfer.WriteAtomic: a failed or cancelled run leaves neither a partial +// archive nor a damaged previous one, and a source is never truncated. +// Refused up front: an archivePath that is one of the sources or lies inside +// a source directory (also through symlinks; U-P0-1). An existing archive is +// a conflict for h.Resolve (Overwrite / KeepBoth = "name (1).zip" / Skip / +// Abort); without Resolve it is refused. Symlinks are stored as links. +// Errors of the zip/tar/gzip writers' Close fail the operation (N-P2-13). +func Create(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string, f Format, + h transfer.Hooks) transfer.Report { + var rep transfer.Report + fail := func(err error) transfer.Report { + rep.Err = err + rep.Cancelled = ctx.Err() != nil + return rep + } + if dst.Caps().ReadOnly { + return fail(fmt.Errorf("%w: %s", transfer.ErrReadOnly, dst.Label())) + } + archivePath = dst.Paths().Clean(archivePath) + if err := checkSources(ctx, src, paths, dst, archivePath); err != nil { + return fail(err) + } + + target, replace, skip, err := resolveTarget(ctx, dst, archivePath, h) + if err != nil { + return fail(err) + } + if skip { + rep.Skipped = 1 + return rep + } + + var items []transfer.Item + var total int64 + seen := map[string]bool{} + err = transfer.FSSource(src, paths, transfer.CopyLinks).Walk(ctx, func(it transfer.Item) error { + if !strings.Contains(it.Rel, "/") { + if seen[it.Rel] { + return fmt.Errorf("%w: %s", transfer.ErrDuplicateName, it.Rel) + } + seen[it.Rel] = true + } + items = append(items, it) + if it.Kind == transfer.File { + total += it.Size + } + return nil + }) + if err != nil { + return fail(err) + } + + w := &writer{ctx: ctx, src: src, f: f, h: h, rep: &rep, items: items, total: total} + err = transfer.WriteAtomic(ctx, dst, target, transfer.WriteOptions{Perm: 0o644, Replace: replace, Fsync: true}, w.fill) + if ctx.Err() != nil { + rep.Cancelled = true + } + if err != nil { + if !rep.Cancelled && rep.Err == nil { + rep.Err = err + } + rep.Done, rep.Bytes = 0, 0 + return rep + } + rep.Affected = []vfs.Location{{FS: dst, Path: dst.Paths().Dir(target)}} + w.progress(true) + return rep +} + +func checkSources(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string) error { + for _, p := range paths { + same, err := vfs.SameFile(ctx, src, p, dst, archivePath) + if err != nil { + return err + } + if same { + return fmt.Errorf("%w: %s", ErrSameFile, p) + } + if src.Volume() != dst.Volume() { + continue + } + fi, err := src.Lstat(ctx, p) + if err != nil { + return err + } + if !fi.IsDir() { + continue + } + in, err := vfs.Within(ctx, dst, archivePath, p) + if err != nil { + return err + } + if in { + return fmt.Errorf("%w: %s", ErrIntoSource, p) + } + } + return nil +} + +// resolveTarget handles an existing archive file. +func resolveTarget(ctx context.Context, dst vfs.FS, p string, h transfer.Hooks) (target string, replace, skip bool, err error) { + fi, err := dst.Lstat(ctx, p) + if errors.Is(err, vfs.ErrNotExist) { + return p, false, false, nil + } + if err != nil { + return "", false, false, err + } + if fi.IsDir() { + return "", false, false, fmt.Errorf("%s is a directory", p) + } + if h.Resolve == nil { + return "", false, false, fmt.Errorf("%s: %w", p, vfs.ErrExist) + } + res, err := h.Resolve(ctx, transfer.Conflict{ + Item: transfer.Item{Rel: dst.Paths().Base(p), Kind: transfer.File, Existing: &fi}, + Kind: transfer.FileFile, + }) + if err != nil { + return "", false, false, err + } + switch res.Action { + case transfer.ResolveOverwrite: + return p, true, false, nil + case transfer.ResolveSkip: + return "", false, true, nil + case transfer.ResolveKeepBoth: + free, err := FreeName(ctx, dst, p) + return free, false, false, err + } + return "", false, false, transfer.ErrAborted +} + +// FreeName returns p or the first free "name (n).ext" next to it (the +// archive extension, e.g. .tar.gz, stays together). +func FreeName(ctx context.Context, fsys vfs.FS, p string) (string, error) { + ops := fsys.Paths() + dir, base := ops.Dir(p), ops.Base(p) + stem := stripArchiveExt(base) + ext := base[len(stem):] + for n := 0; n <= 10000; n++ { + cand := p + if n > 0 { + cand = ops.Join(dir, fmt.Sprintf("%s (%d)%s", stem, n, ext)) + } + _, err := fsys.Lstat(ctx, cand) + if errors.Is(err, vfs.ErrNotExist) { + return cand, nil + } + if err != nil { + return "", err + } + } + return "", fmt.Errorf("no free name for %s", p) +} + +// writer streams the items into the archive format. +type writer struct { + ctx context.Context + src vfs.FS + f Format + h transfer.Hooks + rep *transfer.Report + items []transfer.Item + total int64 + done int64 + files int + last time.Time +} + +func (w *writer) progress(force bool) { + if w.h.Progress == nil { + return + } + every := w.h.ProgressInterval + if every <= 0 { + every = 50 * time.Millisecond + } + if !force && time.Since(w.last) < every { + return + } + w.last = time.Now() + w.h.Progress(transfer.Progress{Phase: transfer.Copying, FilesDone: w.files, BytesDone: w.done, BytesTotal: w.total}) +} + +func (w *writer) fill(out io.Writer) error { + switch w.f { + case Zip: + zw := zip.NewWriter(out) + if err := w.each(zipAdder{zw}); err != nil { + return err + } + return zw.Close() + case Tar, TarGz: + var gz *gzip.Writer + if w.f == TarGz { + gz = gzip.NewWriter(out) + out = gz + } + tw := tar.NewWriter(out) + if err := w.each(tarAdder{tw}); err != nil { + return err + } + if err := tw.Close(); err != nil { + return err + } + if gz != nil { + return gz.Close() + } + return nil + } + return fmt.Errorf("archive: unknown format %d", w.f) +} + +// adder writes one entry; body is nil except for regular files. +type adder interface { + add(it transfer.Item, body io.Reader) error +} + +func (w *writer) each(a adder) error { + for _, it := range w.items { + if err := w.ctx.Err(); err != nil { + return err + } + switch it.Kind { + case transfer.Special: + w.rep.Skipped++ + w.rep.Warnings = append(w.rep.Warnings, it.Rel+": special file skipped") + continue + case transfer.Dir, transfer.Symlink: + if err := a.add(it, nil); err != nil { + return err + } + if it.Kind == transfer.Symlink { + w.rep.Done++ + w.files++ + } + continue + } + if err := w.addFile(a, it); err != nil { + return err + } + } + return nil +} + +// addFile opens the source first, so an unreadable file can be skipped +// (OnError) before its header is written. An error in the middle of a file +// aborts the archive (a tar header already promised its size). +func (w *writer) addFile(a adder, it transfer.Item) error { + for { + r, err := w.src.Open(w.ctx, it.Src) + if err == nil { + start := w.done + pr := &countReader{ctx: w.ctx, r: r, onRead: func(n int64) { w.done = start + n; w.progress(false) }} + err = a.add(it, pr) + r.Close() + if err != nil { + return fmt.Errorf("%s: %w", it.Rel, err) + } + if pr.n != it.Size { + return fmt.Errorf("%s: changed while archiving (%d of %d bytes)", it.Rel, pr.n, it.Size) + } + w.files++ + w.rep.Done++ + w.rep.Bytes += it.Size + return nil + } + ie := transfer.ItemError{Item: it, Op: "read", Err: err} + act := transfer.ErrorSkip + switch { + case w.h.OnError != nil: + var herr error + if act, herr = w.h.OnError(w.ctx, ie); herr != nil { + return herr + } + } + switch act { + case transfer.ErrorRetry: + continue + case transfer.ErrorStop: + w.rep.Errors = append(w.rep.Errors, ie) + w.rep.Failed++ + return fmt.Errorf("%w: %v", transfer.ErrAborted, ie) + } + w.rep.Errors = append(w.rep.Errors, ie) + w.rep.Failed++ + w.done += it.Size + return nil + } +} + +type countReader struct { + ctx context.Context + r io.Reader + n int64 + onRead func(int64) +} + +func (c *countReader) Read(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + n, err := c.r.Read(p) + c.n += int64(n) + if n > 0 { + c.onRead(c.n) + } + return n, err +} + +type zipAdder struct{ zw *zip.Writer } + +func (z zipAdder) add(it transfer.Item, body io.Reader) error { + h := &zip.FileHeader{Name: it.Rel, Modified: it.ModTime, Method: zip.Deflate} + switch it.Kind { + case transfer.Dir: + h.Name += "/" + h.Method = zip.Store + h.SetMode(fs.ModeDir | it.Mode.Perm()) + case transfer.Symlink: + h.Method = zip.Store + h.SetMode(fs.ModeSymlink | 0o777) + body = strings.NewReader(it.LinkTarget) + default: + h.SetMode(it.Mode.Perm()) + h.UncompressedSize64 = uint64(it.Size) + } + w, err := z.zw.CreateHeader(h) + if err != nil { + return err + } + if body != nil { + _, err = io.Copy(w, body) + } + return err +} + +type tarAdder struct{ tw *tar.Writer } + +func (t tarAdder) add(it transfer.Item, body io.Reader) error { + h := &tar.Header{Name: it.Rel, ModTime: it.ModTime, Mode: int64(it.Mode.Perm())} + switch it.Kind { + case transfer.Dir: + h.Typeflag, h.Name = tar.TypeDir, it.Rel+"/" + case transfer.Symlink: + h.Typeflag, h.Linkname, h.Mode = tar.TypeSymlink, it.LinkTarget, 0o777 + default: + h.Typeflag, h.Size = tar.TypeReg, it.Size + } + if err := t.tw.WriteHeader(h); err != nil { + return err + } + if body != nil { + if _, err := io.Copy(t.tw, body); err != nil { + return err + } + } + return nil +} diff --git a/internal/archive/create_test.go b/internal/archive/create_test.go new file mode 100644 index 0000000..f199c91 --- /dev/null +++ b/internal/archive/create_test.go @@ -0,0 +1,214 @@ +package archive + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "vcom/internal/testutil/fstree" + "vcom/internal/transfer" + "vcom/internal/vfs" + "vcom/internal/vfs/localfs" + "vcom/internal/vfs/vfstest" +) + +var local = localfs.New() + +func noTemps(t *testing.T, dir string) { + t.Helper() + ents, _ := os.ReadDir(dir) + for _, e := range ents { + if strings.HasPrefix(e.Name(), ".vcom-") { + t.Errorf("temp left: %s", e.Name()) + } + } +} + +func TestUP01_ArchiveDoesNotDestroySource(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("data.tar", "").WithSize(64 << 10)}) + before, _ := os.ReadFile(filepath.Join(dir, "data.tar")) + name := Name([]string{"data.tar"}, Tar) + if name != "data.tar" { + t.Fatalf("name %s", name) + } + rep := Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, filepath.Join(dir, name), Tar, + transfer.Hooks{Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }}) + if !errors.Is(rep.Err, ErrSameFile) { + t.Fatalf("err = %v, want ErrSameFile (U-P0-1)", rep.Err) + } + if after, _ := os.ReadFile(filepath.Join(dir, "data.tar")); string(after) != string(before) { + t.Fatal("source damaged") + } + // With another name (what the UI offers) it works. + free, err := FreeName(bg, local, filepath.Join(dir, name)) + if err != nil || filepath.Base(free) != "data (1).tar" { + t.Fatalf("free name %q %v", free, err) + } + rep = Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, free, Tar, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 1 { + t.Fatalf("%+v", rep) + } + idx, err := IndexFile(bg, local, free, nil) + if err != nil || len(idx.Entries) != 1 || idx.Entries[0].Size != 64<<10 { + t.Fatalf("index %+v %v", idx, err) + } +} + +func TestArchiveIntoSourceDirRejected(t *testing.T) { + dir := t.TempDir() + fstree.Build(t, dir, fstree.Spec{fstree.File("proj/a", "a"), fstree.Dir("proj/sub"), fstree.Symlink("alias", "proj")}) + for _, target := range []string{ + filepath.Join(dir, "proj", "proj.zip"), + filepath.Join(dir, "proj", "sub", "x.zip"), + filepath.Join(dir, "alias", "x.zip"), // through a symlink + } { + rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, target, Zip, transfer.Hooks{}) + if !errors.Is(rep.Err, ErrIntoSource) { + t.Errorf("%s: %v", target, rep.Err) + } + if _, err := os.Lstat(target); !os.IsNotExist(err) { + t.Errorf("%s written", target) + } + } + if rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, filepath.Join(dir, "proj.zip"), Zip, transfer.Hooks{}); rep.Err != nil { + t.Fatal(rep.Err) + } +} + +func TestArchiveCancelRemovesPartial(t *testing.T) { + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("d/big", "").WithSize(4 << 20), fstree.File("d/b", "b")}) + out := t.TempDir() + old := filepath.Join(out, "d.tar.gz") + if err := os.WriteFile(old, []byte("previous archive"), 0o644); err != nil { + t.Fatal(err) + } + dst := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error { + if op == vfstest.OpWrite { + time.Sleep(2 * time.Millisecond) + } + return nil + }} + ctx, cancel := context.WithCancel(bg) + time.AfterFunc(50*time.Millisecond, cancel) + rep := Create(ctx, local, []string{filepath.Join(src, "d")}, dst, old, TarGz, transfer.Hooks{ + Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) { + return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil + }}) + if !rep.Cancelled || rep.Done != 0 { + t.Fatalf("%+v", rep) + } + if b, _ := os.ReadFile(old); string(b) != "previous archive" { + t.Fatal("previous archive damaged by a cancelled overwrite") + } + noTemps(t, out) +} + +func TestArchiveCloseErrorReported(t *testing.T) { + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("a", "data")}) + for _, f := range []Format{Zip, Tar, TarGz} { + out := t.TempDir() + dst := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpClose, 1, syscall.EIO)} + target := filepath.Join(out, "a"+f.Ext()) + rep := Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{}) + if !errors.Is(rep.Err, syscall.EIO) || rep.Done != 0 { + t.Fatalf("%v: close error not reported (N-P2-13): %+v", f, rep) + } + if _, err := os.Lstat(target); !os.IsNotExist(err) { + t.Fatalf("%v: archive committed", f) + } + noTemps(t, out) + // A write error while the writers flush on Close is reported too. + dst = &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 1, syscall.ENOSPC)} + rep = Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{}) + if !errors.Is(rep.Err, syscall.ENOSPC) { + t.Fatalf("%v: flush error: %+v", f, rep) + } + noTemps(t, out) + } +} + +func TestArchiveNameTarGzToZip(t *testing.T) { + if got := Name([]string{"/srv/foo.tar.gz"}, Zip); got != "foo.zip" { + t.Fatalf("got %s (U-P2: was foo.tar.zip)", got) + } + out := t.TempDir() + fstree.Build(t, out, fstree.Spec{fstree.File("a (1).tar.gz", ""), fstree.File("a.tar.gz", "")}) + if p, _ := FreeName(bg, local, filepath.Join(out, "a.tar.gz")); filepath.Base(p) != "a (2).tar.gz" { + t.Fatalf("free %s", p) + } +} + +func TestArchiveSymlinksPreserved(t *testing.T) { + src := t.TempDir() + mt := time.Date(2019, 3, 4, 5, 6, 7, 0, time.UTC) + spec := fstree.Spec{ + fstree.File("d/run.sh", "#!/bin/sh").WithMode(0o755).WithMTime(mt), + fstree.Symlink("d/ln", "run.sh"), + fstree.Symlink("d/broken", "../nowhere"), + fstree.Dir("d/empty"), + } + fstree.Build(t, src, spec) + for _, f := range []Format{Zip, Tar, TarGz} { + out := t.TempDir() + arch := filepath.Join(out, "d"+f.Ext()) + rep := Create(bg, local, []string{filepath.Join(src, "d")}, local, arch, f, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("%v: %+v", f, rep) + } + idx, err := IndexFile(bg, local, arch, nil) + if err != nil { + t.Fatal(err) + } + for p, want := range map[string]string{"d/ln": "run.sh", "d/broken": "../nowhere"} { + if e, ok := idx.Lookup(p); !ok || !e.IsSymlink() || e.Link != want { + t.Fatalf("%v: %s = %+v", f, p, e) + } + } + // Round trip through Unpack gives the same tree (modes, mtimes, links). + back := t.TempDir() + if rep := Unpack(bg, local, arch, idx, nil, local, back, transfer.DefaultOptions(), transfer.Hooks{}); rep.Err != nil || rep.Failed != 0 { + t.Fatalf("%v: unpack %+v", f, rep) + } + fstree.Equal(t, fstree.Snapshot(t, filepath.Join(src, "d")), fstree.Snapshot(t, filepath.Join(back, "d")), + fstree.Opts{Mode: true, Links: true}) + if fi, _ := os.Stat(filepath.Join(back, "d", "run.sh")); !fi.ModTime().Equal(mt) { + t.Fatalf("%v: mtime %v", f, fi.ModTime()) + } + } +} + +func TestArchiveExistingTargetIsConflict(t *testing.T) { + src, out := t.TempDir(), t.TempDir() + fstree.Build(t, src, fstree.Spec{fstree.File("a", "new")}) + target := filepath.Join(out, "a.zip") + _ = os.WriteFile(target, []byte("old"), 0o644) + if rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{}); !errors.Is(rep.Err, vfs.ErrExist) { + t.Fatalf("no Resolve: %v", rep.Err) + } + rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{ + Resolve: func(_ context.Context, c transfer.Conflict) (transfer.Resolution, error) { + if c.Item.Existing == nil { + t.Error("no Existing") + } + return transfer.Resolution{Action: transfer.ResolveKeepBoth}, nil + }}) + if rep.Err != nil || len(rep.Affected) != 1 { + t.Fatalf("%+v", rep) + } + if b, _ := os.ReadFile(target); string(b) != "old" { + t.Fatal("KeepBoth overwrote") + } + if _, err := os.Stat(filepath.Join(out, "a (1).zip")); err != nil { + t.Fatal(err) + } +} diff --git a/internal/archive/remote_test.go b/internal/archive/remote_test.go new file mode 100644 index 0000000..854a8e3 --- /dev/null +++ b/internal/archive/remote_test.go @@ -0,0 +1,84 @@ +package archive + +import ( + "context" + "net" + "os" + "path/filepath" + "strconv" + "testing" + + "golang.org/x/crypto/ssh/knownhosts" + + "vcom/internal/ssh/conn" + "vcom/internal/testutil/fstree" + "vcom/internal/testutil/sshtest" + "vcom/internal/transfer" + "vcom/internal/vfs/sftpfs" +) + +// remoteFS starts an in-process SSH/SFTP server and returns an FS on it. +// The server shares this machine's file system, so results are checked on +// disk. +func remoteFS(t *testing.T) *sftpfs.FS { + t.Helper() + home := sshtest.IsolatedHome(t) + srv := sshtest.Start(t, sshtest.Options{}) + kh := filepath.Join(home, ".ssh", "known_hosts") + f, err := os.OpenFile(kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + for _, k := range srv.HostKeys { + _, _ = f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(srv.Addr)}, k.PublicKey()) + "\n") + } + f.Close() + pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{ + Home: home, AgentSocket: "-", KnownHostsFiles: []string{kh}, + }}) + t.Cleanup(func() { pool.Close() }) + host, port, _ := net.SplitHostPort(srv.Addr) + p, _ := strconv.Atoi(port) + l, err := pool.Acquire(context.Background(), conn.Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: srv.Password}) + if err != nil { + t.Fatal(err) + } + fsys := sftpfs.New(l) + t.Cleanup(fsys.Release) + return fsys +} + +// N-P1-15: archiving onto (and from) a remote panel works through vfs. +func TestArchiveToRemote(t *testing.T) { + remote := remoteFS(t) + src := t.TempDir() + fstree.Build(t, src, fstree.Spec{ + fstree.File("proj/a.txt", "alpha"), + fstree.File("proj/sub/b.bin", "").WithSize(300 << 10), + fstree.Symlink("proj/ln", "a.txt"), + }) + out := t.TempDir() + target := filepath.Join(out, "proj.tar.gz") + rep := Create(bg, local, []string{filepath.Join(src, "proj")}, remote, target, TarGz, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("local โ†’ remote: %+v", rep) + } + idx, err := IndexFile(bg, remote, target, nil) + if err != nil { + t.Fatal(err) + } + if e, ok := idx.Lookup("proj/sub/b.bin"); !ok || e.Size != 300<<10 { + t.Fatalf("index %+v", e) + } + if e, _ := idx.Lookup("proj/ln"); e.Link != "a.txt" { + t.Fatalf("link %+v", e) + } + noTemps(t, out) + + // Remote source โ†’ local archive. + back := filepath.Join(t.TempDir(), "again.zip") + rep = Create(bg, remote, []string{filepath.Join(src, "proj")}, local, back, Zip, transfer.Hooks{}) + if rep.Err != nil || rep.Done != 3 { + t.Fatalf("remote โ†’ local: %+v", rep) + } +}