From 6b29e4305c49c44b043d48eecadc3f673f1d1ba5 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 05:45:53 +0000 Subject: [PATCH 01/11] perf(client): extract snapshots in-process with parallel file writes On Linux, replace the tar process in the zstd | tar restore pipeline with an in-process extractor that writes file contents from a pool of goroutines while keeping GNU tar's -xp semantics and archive order. Other platforms keep the zstd | tar pipeline. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/archive.go | 46 +- client/extract_linux.go | 77 +++ client/extract_linux_test.go | 342 +++++++++++++ client/extract_other.go | 58 +++ client/tar_delayed_linux.go | 242 ++++++++++ client/tar_extractor_linux.go | 877 ++++++++++++++++++++++++++++++++++ go.mod | 2 +- 7 files changed, 1600 insertions(+), 44 deletions(-) create mode 100644 client/extract_linux.go create mode 100644 client/extract_linux_test.go create mode 100644 client/extract_other.go create mode 100644 client/tar_delayed_linux.go create mode 100644 client/tar_extractor_linux.go diff --git a/client/archive.go b/client/archive.go index ab60d754..449019e5 100644 --- a/client/archive.go +++ b/client/archive.go @@ -66,7 +66,7 @@ func Extract(ctx context.Context, r io.Reader, directory string, threads int) (r return errors.Wrap(err, "failed to create target directory") } - // Relax read-only dirs (e.g. Hermit package trees) so tar can overwrite them; restored on failure. + // Relax read-only dirs (e.g. Hermit package trees) so extraction can overwrite them; restored on failure. relaxed, err := makeTreeWritable(directory) defer func() { if rerr != nil { @@ -76,47 +76,7 @@ func Extract(ctx context.Context, r io.Reader, directory string, threads int) (r if err != nil { return errors.Wrap(err, "failed to make target directory writable") } - - zstdCmd := exec.CommandContext(ctx, "zstd", "-dc", fmt.Sprintf("-T%d", threads)) //nolint:gosec - tarCmd := exec.CommandContext(ctx, "tar", "-xpf", "-", "-C", directory) - - pr, pw, err := os.Pipe() - if err != nil { - return errors.Wrap(err, "failed to create pipe") - } - - var zstdStderr, tarStderr bytes.Buffer - zstdCmd.Stdin = r - zstdCmd.Stdout = pw - zstdCmd.Stderr = &zstdStderr - - tarCmd.Stdin = pr - tarCmd.Stderr = &tarStderr - - if err := zstdCmd.Start(); err != nil { - pw.Close() //nolint:errcheck,gosec - pr.Close() //nolint:errcheck,gosec - return errors.Wrap(err, "failed to start zstd") - } - pw.Close() //nolint:errcheck,gosec - - if err := tarCmd.Start(); err != nil { - pr.Close() //nolint:errcheck,gosec - return errors.Join(errors.Wrap(err, "failed to start tar"), zstdCmd.Wait()) - } - pr.Close() //nolint:errcheck,gosec - - zstdErr := zstdCmd.Wait() - tarErr := tarCmd.Wait() - - var errs []error - if zstdErr != nil { - errs = append(errs, errors.Errorf("zstd failed: %w: %s", zstdErr, zstdStderr.String())) - } - if tarErr != nil { - errs = append(errs, errors.Errorf("tar failed: %w: %s", tarErr, tarStderr.String())) - } - return errors.Join(errs...) + return extractStream(ctx, r, directory, threads) } // dirMode is a directory path and its pre-relaxation mode. @@ -127,7 +87,7 @@ type dirMode struct { // makeTreeWritable adds owner-write to every directory under root, returning the originals of those it changed. // -// tar overwrites a file by unlinking it, which requires a writable parent directory. +// Extraction overwrites a file by unlinking it, which requires a writable parent directory. func makeTreeWritable(root string) ([]dirMode, error) { var changed []dirMode err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error { diff --git a/client/extract_linux.go b/client/extract_linux.go new file mode 100644 index 00000000..5bdae3bb --- /dev/null +++ b/client/extract_linux.go @@ -0,0 +1,77 @@ +package client + +import ( + "archive/tar" + "bufio" + "bytes" + "context" + "fmt" + "io" + "os" + "os/exec" + "runtime" + + "github.com/alecthomas/errors" + "golang.org/x/sys/unix" +) + +const ( + maxExtractWriters = 8 + // decodedPipeBytes sizes the zstd pipe and the read buffer, cutting syscalls per decoded megabyte. + decodedPipeBytes = 1 << 20 +) + +// extractStream decodes r with zstd and applies the tar stream in-process. +// +// A single tar process spends most of a restore waiting on per-file syscalls, so file contents are written +// concurrently while entries keep GNU tar's -xp semantics and archive order. +func extractStream(ctx context.Context, r io.Reader, directory string, threads int) error { + zstdCmd := exec.CommandContext(ctx, "zstd", "-dc", fmt.Sprintf("-T%d", threads)) //nolint:gosec + pr, pw, err := os.Pipe() + if err != nil { + return errors.Wrap(err, "failed to create pipe") + } + var zstdStderr bytes.Buffer + zstdCmd.Stdin = r + zstdCmd.Stdout = pw + zstdCmd.Stderr = &zstdStderr + if err := zstdCmd.Start(); err != nil { + pw.Close() //nolint:errcheck,gosec + pr.Close() //nolint:errcheck,gosec + return errors.Wrap(err, "failed to start zstd") + } + pw.Close() //nolint:errcheck,gosec + + _, _ = unix.FcntlInt(pr.Fd(), unix.F_SETPIPE_SZ, decodedPipeBytes) //nolint:errcheck // only costs throughput + br := bufio.NewReaderSize(pr, decodedPipeBytes) + writers := min(runtime.GOMAXPROCS(0), maxExtractWriters) + extractErr := newTarExtractor(directory, writers).extract(ctx, br) + if extractErr == nil { + // tar.Reader stops at the end-of-archive marker; consume the padding so zstd isn't killed by SIGPIPE. + if _, err := io.Copy(io.Discard, br); err != nil { + extractErr = errors.Wrap(err, "failed to read archive") + } + } + pr.Close() //nolint:errcheck,gosec + zstdErr := zstdCmd.Wait() + + var errs []error + if zstdErr != nil { + errs = append(errs, errors.Errorf("zstd failed: %w: %s", zstdErr, zstdStderr.String())) + } + if extractErr != nil { + errs = append(errs, extractErr) + } + return errors.Join(errs...) +} + +// nextTarEntry wraps tar.Reader.Next, leaving name checks to the extractor. +// +// GODEBUG=tarinsecurepath=0 makes Next reject names that GNU tar extracts after stripping leading slashes. +func nextTarEntry(tr *tar.Reader) (*tar.Header, error) { //nolint:privatedoc // explains why + hdr, err := tr.Next() + if errors.Is(err, tar.ErrInsecurePath) && hdr != nil { + return hdr, nil + } + return hdr, errors.WithStack(err) +} diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go new file mode 100644 index 00000000..74e5768d --- /dev/null +++ b/client/extract_linux_test.go @@ -0,0 +1,342 @@ +package client_test + +import ( + "archive/tar" + "bytes" + "crypto/sha256" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/alecthomas/assert/v2" + + "github.com/block/cachew/client" +) + +type tarEntry struct { + hdr tar.Header + body string + // rawName replaces the encoded name, for names archive/tar refuses to write. + rawName string +} + +func regular(name string, mode int64, body string) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeReg, Name: name, Mode: mode}, body: body} +} + +func directory(name string, mode int64) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeDir, Name: name, Mode: mode}} +} + +func symlink(name, target string) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeSymlink, Name: name, Linkname: target, Mode: 0o777}} +} + +func hardlink(name, target string) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeLink, Name: name, Linkname: target}} +} + +func regularWithSlash(name string, mode int64) tarEntry { + placeholder := strings.TrimSuffix(name, "/") + "_" + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeReg, Name: placeholder, Mode: mode}, rawName: name} +} + +func typed(flag byte, name string, mode int64, body string) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: flag, Name: name, Mode: mode}, body: body} +} + +// extractCase is an archive plus the tree it is extracted over. +type extractCase struct { + name string + setup func(t *testing.T, dir string) + entries []tarEntry +} + +func TestExtractMatchesGNUTar(t *testing.T) { + if out, err := exec.Command("tar", "--version").Output(); err != nil || !bytes.Contains(out, []byte("GNU tar")) { + t.Skip("GNU tar is not installed") + } + if os.Geteuid() == 0 { + t.Skip("ownership differs as root; cases assume an unprivileged user") + } + // Large enough to be written in several chunks. + large := strings.Repeat("0123456789abcdef", 9<<16) + cases := []extractCase{ + {name: "Tree", entries: []tarEntry{ + directory("./", 0o750), + directory("a/", 0o755), + regular("a/file", 0o640, "hello"), + regular("a/exec", 0o755, "#!/bin/sh\n"), + regular("a/empty", 0o600, ""), + regular("a/large", 0o644, large), + regular("a/setuid", 0o4755, "x"), + directory("a/setgid/", 0o2775), + directory("a/setgid/child/", 0o700), + regular("a/setgid/implicit/file", 0o644, "y"), + directory("a/sticky/", 0o1777), + directory("readonly/", 0o555), + regular("readonly/file", 0o444, "ro"), + regular("missing/parents/file", 0o644, "z"), + regular("./dot//slashes/./file", 0o644, "dots"), + }}, + {name: "Links", entries: []tarEntry{ + directory("dir/", 0o755), + regular("dir/small", 0o644, "small"), + regular("dir/large", 0o644, large), + symlink("relative", "dir/small"), + symlink("dangling", "nowhere"), + symlink("absolute", "/etc"), + symlink("dotdot", "../outside"), + symlink("dir-link", "dir"), + regular("dir-link/through", 0o644, "via symlink"), + hardlink("hard-small", "dir/small"), + hardlink("hard-large", "dir/large"), + hardlink("hard-absolute", "absolute"), + hardlink("hard-rooted", "/dir/small"), + hardlink("hard-escaping", "../../dir/small"), + typed(tar.TypeFifo, "fifo", 0o640, ""), + }}, + {name: "Duplicates", entries: []tarEntry{ + regular("file", 0o644, "first"), + regular("file", 0o600, "second"), + regular("large-then-small", 0o644, large), + hardlink("link-to-large", "large-then-small"), + regular("large-then-small", 0o600, "small"), + regular("small-then-large", 0o644, "small"), + regular("small-then-large", 0o600, large), + regular("file-then-link", 0o644, "x"), + symlink("file-then-link", "file"), + symlink("link-then-file", "file"), + regular("link-then-file", 0o644, "replaced"), + regular("file-then-dir", 0o644, "x"), + directory("file-then-dir/", 0o755), + directory("dir-then-file/", 0o755), + regular("dir-then-file", 0o644, "x"), + symlink("unsafe-twice", "/first"), + symlink("unsafe-twice", "/second"), + directory("real/", 0o755), + symlink("link-then-dir", "real"), + directory("link-then-dir/", 0o700), + directory("twice/", 0o755), + directory("twice/", 0o700), + }}, + {name: "UnusualHeaders", entries: []tarEntry{ + typed(tar.TypeXGlobalHeader, "global", 0, ""), + typed('V', "volume", 0, ""), + regularWithSlash("trailing-slash/", 0o755), + typed('Z', "unknown-type", 0o644, "data"), + regular("/absolute/file", 0o644, "abs"), + }}, + {name: "ExistingTree", setup: existingTree, entries: []tarEntry{ + regular("file-over-dir-parent/file", 0o644, "x"), + directory("symlink-to-dir/", 0o755), + regular("symlink-to-dir/file", 0o644, "x"), + regular("symlinked-parent/file", 0o644, "into target"), + regular("dangling", 0o644, "x"), + regular("readonly", 0o644, "rewritten"), + }}, + {name: "OutOfOrder", entries: []tarEntry{ + directory("revisited/", 0o755), + regular("revisited/first", 0o644, "x"), + directory("other/", 0o755), + regular("revisited/later", 0o644, "x"), + directory("./mixed/", 0o755), + regular("mixed/file", 0o644, "x"), + directory("link-parent/", 0o755), + symlink("link-parent/unsafe", "/absolute"), + regular("after-link", 0o644, "x"), + }}, + {name: "RevisitReadOnly", entries: []tarEntry{ + directory("readonly/", 0o555), + regular("elsewhere", 0o644, "x"), + regular("readonly/late", 0o644, "x"), + }}, + {name: "Rewrites", entries: rewrites()}, + {name: "DotDotName", entries: []tarEntry{regular("a/../escape", 0o644, "x")}}, + {name: "ThroughUnsafeLink", entries: []tarEntry{symlink("u", "/tmp"), regular("u/file", 0o644, "x")}}, + {name: "ThroughLinkToUnsafeLink", entries: []tarEntry{ + symlink("u", "/tmp"), + symlink("s", "u"), + regular("s/file", 0o644, "x"), + }}, + {name: "FileOverNonEmptyDir", entries: []tarEntry{regular("d/f", 0o644, "x"), regular("d", 0o644, "x")}}, + {name: "FileOverTargetDir", entries: []tarEntry{regular(".", 0o644, "x")}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + archive := buildTar(t, tc.entries) + gnuDir, goDir := t.TempDir(), t.TempDir() + t.Cleanup(func() { makeWritable(t, gnuDir); makeWritable(t, goDir) }) + if tc.setup != nil { + tc.setup(t, gnuDir) + tc.setup(t, goDir) + } + + gnuTar := exec.Command("tar", "-xpf", "-", "-C", gnuDir) + gnuTar.Stdin = bytes.NewReader(archive) + gnuOut, gnuErr := gnuTar.CombinedOutput() + goErr := client.Extract(t.Context(), bytes.NewReader(zstdCompress(t, archive)), goDir, 0) + + assert.Equal(t, gnuErr == nil, goErr == nil, "GNU tar: %v %s\nExtract: %v", gnuErr, gnuOut, goErr) + if gnuErr == nil { + assert.Equal(t, treeState(t, gnuDir), treeState(t, goDir)) + } + }) + } +} + +func TestExtractLaterEntryReplacesUnsafeSymlink(t *testing.T) { + // GNU tar finds placeholders by inode number, so a file reusing a freed placeholder's inode confuses it. + cases := []struct { + name string + entries []tarEntry + want string + }{ + {"File", []tarEntry{symlink("entry", "/first"), regular("entry", 0o644, "file")}, "file"}, + {"LinkAfterFile", []tarEntry{ + symlink("entry", "/first"), regular("entry", 0o644, "file"), symlink("entry", "/second"), + }, "-> /second"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + archive := zstdCompress(t, buildTar(t, tc.entries)) + assert.NoError(t, client.Extract(t.Context(), bytes.NewReader(archive), dir, 0)) + got, err := os.Readlink(filepath.Join(dir, "entry")) + if err == nil { + got = "-> " + got + } else { + data, readErr := os.ReadFile(filepath.Join(dir, "entry")) + assert.NoError(t, readErr) + got = string(data) + } + assert.Equal(t, tc.want, got) + }) + } +} + +// rewrites writes many small files twice, so queued writes must land in archive order. +func rewrites() []tarEntry { //nolint:privatedoc // explains why + var entries []tarEntry + for round := range 2 { + for i := range 500 { + entries = append(entries, regular(fmt.Sprintf("many/%03d", i), 0o644, fmt.Sprintf("round %d file %d", round, i))) + if round == 0 && i%50 == 0 { + entries = append(entries, hardlink(fmt.Sprintf("many/link-%03d", i), fmt.Sprintf("many/%03d", i))) + } + } + } + return entries +} + +func existingTree(t *testing.T, dir string) { + t.Helper() + assert.NoError(t, os.WriteFile(filepath.Join(dir, "file-over-dir-parent"), []byte("x"), 0o644)) + assert.NoError(t, os.Mkdir(filepath.Join(dir, "real"), 0o755)) + assert.NoError(t, os.Symlink("real", filepath.Join(dir, "symlink-to-dir"))) + assert.NoError(t, os.Mkdir(filepath.Join(dir, "target"), 0o755)) + assert.NoError(t, os.Symlink("target", filepath.Join(dir, "symlinked-parent"))) + assert.NoError(t, os.Symlink("nowhere", filepath.Join(dir, "dangling"))) + assert.NoError(t, os.WriteFile(filepath.Join(dir, "readonly"), []byte("old"), 0o444)) +} + +func archiveTime() time.Time { + return time.Date(2020, 1, 2, 3, 4, 5, 123456789, time.UTC) +} + +func buildTar(t *testing.T, entries []tarEntry) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, entry := range entries { + hdr := entry.hdr + hdr.ModTime = archiveTime() + hdr.Format = tar.FormatPAX + hdr.Size = int64(len(entry.body)) + if hdr.Typeflag == tar.TypeXGlobalHeader { + hdr = tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: hdr.Name, PAXRecords: map[string]string{"comment": "x"}} + } + if entry.rawName != "" { + // A single USTAR block, so the name can be patched in place. + hdr.Format = tar.FormatUSTAR + hdr.ModTime = hdr.ModTime.Truncate(time.Second) + } + assert.NoError(t, tw.Flush()) + offset := buf.Len() + assert.NoError(t, tw.WriteHeader(&hdr)) + _, err := tw.Write([]byte(entry.body)) + assert.NoError(t, err) + if entry.rawName != "" { + assert.NoError(t, tw.Flush()) + patchName(buf.Bytes()[offset:offset+512], entry.rawName) + } + } + assert.NoError(t, tw.Close()) + return buf.Bytes() +} + +func patchName(block []byte, name string) { + copy(block[:100], append([]byte(name), make([]byte, 100)...)) + copy(block[148:156], " ") + sum := 0 + for _, b := range block { + sum += int(b) + } + copy(block[148:156], fmt.Sprintf("%06o\x00 ", sum)) +} + +func zstdCompress(t *testing.T, data []byte) []byte { + t.Helper() + cmd := exec.Command("zstd", "-c") + cmd.Stdin = bytes.NewReader(data) + out, err := cmd.Output() + assert.NoError(t, err) + return out +} + +// treeState describes every path under root; only archived mtimes are comparable, the rest are extraction times. +func treeState(t *testing.T, root string) map[string]string { //nolint:privatedoc // explains why + t.Helper() + state := map[string]string{} + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + info, err := d.Info() + if err != nil { + return err + } + rel, err := filepath.Rel(root, path) + if err != nil { + return err + } + desc := fmt.Sprintf("%v nlink=%d", info.Mode(), info.Sys().(*syscall.Stat_t).Nlink) //nolint:forcetypeassert + if !info.ModTime().After(archiveTime()) { + desc += " mtime=" + info.ModTime().Format(time.RFC3339Nano) + } + switch { + case info.Mode()&fs.ModeSymlink != 0: + target, err := os.Readlink(path) + if err != nil { + return err + } + desc += " -> " + target + case info.Mode().IsRegular(): + data, err := os.ReadFile(path) + if err != nil { + return err + } + desc += fmt.Sprintf(" sha256=%x", sha256.Sum256(data)) + } + state[rel] = desc + return nil + }) + assert.NoError(t, err) + return state +} diff --git a/client/extract_other.go b/client/extract_other.go new file mode 100644 index 00000000..6bec2f95 --- /dev/null +++ b/client/extract_other.go @@ -0,0 +1,58 @@ +//go:build !linux + +package client + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "os/exec" + + "github.com/alecthomas/errors" +) + +// extractStream pipes r through zstd into the system tar. +func extractStream(ctx context.Context, r io.Reader, directory string, threads int) error { + zstdCmd := exec.CommandContext(ctx, "zstd", "-dc", fmt.Sprintf("-T%d", threads)) //nolint:gosec + tarCmd := exec.CommandContext(ctx, "tar", "-xpf", "-", "-C", directory) + + pr, pw, err := os.Pipe() + if err != nil { + return errors.Wrap(err, "failed to create pipe") + } + + var zstdStderr, tarStderr bytes.Buffer + zstdCmd.Stdin = r + zstdCmd.Stdout = pw + zstdCmd.Stderr = &zstdStderr + + tarCmd.Stdin = pr + tarCmd.Stderr = &tarStderr + + if err := zstdCmd.Start(); err != nil { + pw.Close() //nolint:errcheck,gosec + pr.Close() //nolint:errcheck,gosec + return errors.Wrap(err, "failed to start zstd") + } + pw.Close() //nolint:errcheck,gosec + + if err := tarCmd.Start(); err != nil { + pr.Close() //nolint:errcheck,gosec + return errors.Join(errors.Wrap(err, "failed to start tar"), zstdCmd.Wait()) + } + pr.Close() //nolint:errcheck,gosec + + zstdErr := zstdCmd.Wait() + tarErr := tarCmd.Wait() + + var errs []error + if zstdErr != nil { + errs = append(errs, errors.Errorf("zstd failed: %w: %s", zstdErr, zstdStderr.String())) + } + if tarErr != nil { + errs = append(errs, errors.Errorf("tar failed: %w: %s", tarErr, tarStderr.String())) + } + return errors.Join(errs...) +} diff --git a/client/tar_delayed_linux.go b/client/tar_delayed_linux.go new file mode 100644 index 00000000..926d092a --- /dev/null +++ b/client/tar_delayed_linux.go @@ -0,0 +1,242 @@ +package client + +import ( + "os" + "path/filepath" + "strings" + + "github.com/alecthomas/errors" + "golang.org/x/sys/unix" +) + +// pendingDir is directory metadata that GNU tar applies once it stops extracting into the directory. +type pendingDir struct { + // name is the member name; GNU tar compares names as strings to decide when a directory is finished. + name string + path string + stat entryStat + // interdir marks a missing parent created for an entry, which only gets its permission bits restored. + interdir bool + // created is the mode a directory was made with; GNU tar skips the chmod when it already matches. + created uint32 + wasCreated bool + // afterLinks holds the directory back until delayed links exist; id detects it being replaced meanwhile. + afterLinks bool + id fileID +} + +// dirStack mirrors GNU tar's delayed_set_stat list, deferring the metadata calls it would make mid-extraction. +// +// GNU tar applies a directory's metadata when an entry outside it arrives. Applying it then would mean waiting for +// queued writes, so finished directories are recorded and only applied early if a later entry modifies one. +type dirStack struct { + // pending is the list GNU tar keeps, innermost directory last. + pending []*pendingDir + byName map[string]*pendingDir + // finished holds directories GNU tar would already have applied, in order, keyed by path in finishedPaths. + finished []*pendingDir + finishedPaths map[string]struct{} +} + +func newDirStack() dirStack { + return dirStack{byName: map[string]*pendingDir{}, finishedPaths: map[string]struct{}{}} +} + +func (s *dirStack) push(dir pendingDir) error { + // A name already pending is updated in place, keeping its position and whether it is held back. + existing, ok := s.byName[dir.name] + if ok { + dir.afterLinks, dir.id = existing.afterLinks, existing.id + if existing.interdir && existing.afterLinks { + info, err := os.Lstat(dir.path) + if err != nil { + return errors.WithStack(err) + } + dir.id = idOf(info) + } + *existing = dir + } else { + existing = &dir + s.pending = append(s.pending, existing) + s.byName[dir.name] = existing + } + if mustBeDot(dir.name) { + return s.markAfterLinks(len(s.pending) - 1) + } + return nil +} + +func (s *dirStack) finishNonAncestors(name string) { + // GNU tar applies these before extracting name; recording them lets queued writes keep running. + for len(s.pending) > 0 { + top := s.pending[len(s.pending)-1] + if top.afterLinks || isNameAncestor(top.name, name) { + return + } + s.pop() + s.finished = append(s.finished, top) + s.finishedPaths[top.path] = struct{}{} + } +} + +func (s *dirStack) pop() *pendingDir { + top := s.pending[len(s.pending)-1] + s.pending = s.pending[:len(s.pending)-1] + delete(s.byName, top.name) + return top +} + +func (s *dirStack) touchesFinished(root, path string) bool { + // Writing path changes its parent's mtime, so an applied directory on the way must be applied first. + if len(s.finishedPaths) == 0 { + return false + } + for ; len(path) >= len(root); path = filepath.Dir(path) { + if _, ok := s.finishedPaths[path]; ok { + return true + } + if path == root { + return false + } + } + return false +} + +func (s *dirStack) markAfterLinks(i int) error { + // Held-back directories wait for delayed links, so their outer directories must wait too. + for ; i >= 0 && !s.pending[i].afterLinks; i-- { + dir := s.pending[i] + dir.afterLinks = true + info, err := os.Lstat(dir.path) + if err != nil { + return errors.WithStack(err) + } + dir.id = idOf(info) + } + return nil +} + +func (s *dirStack) markLinkParent(name string) error { + // Only the directory directly containing a delayed link is held back, matching GNU tar's string comparison. + for i := len(s.pending) - 1; i >= 0; i-- { + dir := s.pending[i] + if dir.afterLinks { + continue + } + rest, ok := strings.CutPrefix(name, dir.name+"/") + if ok && !strings.Contains(rest, "/") { + return s.markAfterLinks(i) + } + } + return nil +} + +func isNameAncestor(dir, name string) bool { + return len(dir) < len(name) && strings.HasPrefix(name, dir) && + (name[len(dir)] == '/' || strings.HasSuffix(dir, "/")) +} + +func mustBeDot(name string) bool { + for { + rest, ok := strings.CutPrefix(name, "./") + if !ok { + return name == "" || name == "." + } + name = strings.TrimLeft(rest, "/") + } +} + +func (e *tarExtractor) flushFinished() error { + // Queued writes into these directories must land first or they would bump the restored mtimes. + e.waitAll() + for _, dir := range e.dirStack.finished { + if err := e.applyDir(dir, false); err != nil { + return err + } + } + e.dirStack.finished = nil + clear(e.dirStack.finishedPaths) + return nil +} + +// finish applies directory metadata and delayed links in GNU tar's order once every entry is extracted. +func (e *tarExtractor) finish() error { + if err := e.flushFinished(); err != nil { + return err + } + stack := &e.dirStack + for len(stack.pending) > 0 && !stack.pending[len(stack.pending)-1].afterLinks { + if err := e.applyDir(stack.pop(), false); err != nil { + return err + } + } + if err := e.applyDelayedLinks(); err != nil { + return err + } + verify := false + for len(stack.pending) > 0 { + dir := stack.pop() + // From the first held-back directory on, GNU tar checks that each is still the same directory. + verify = verify || dir.afterLinks + if err := e.applyDir(dir, verify); err != nil { + return err + } + } + return nil +} + +func (e *tarExtractor) applyDir(dir *pendingDir, verify bool) error { + if verify { + info, err := os.Lstat(dir.path) + if err != nil { + return errors.WithStack(err) + } + if idOf(info) != dir.id { + return errors.Errorf("%s: directory renamed before its status could be extracted", dir.path) + } + } + if dir.interdir { + var st unix.Stat_t + if err := unix.Lstat(dir.path, &st); err != nil { + return errors.Wrapf(err, "failed to stat %s", dir.path) + } + // Only permission bits are restored, keeping any set-group-ID bit inherited from the parent. + mode := st.Mode&0o7000 | dir.stat.mode + if mode == st.Mode&0o7777 { + return nil + } + return errors.Wrapf(unix.Chmod(dir.path, mode), "failed to chmod %s", dir.path) + } + keepMode := !verify && dir.wasCreated && dir.created == dir.stat.mode + return e.setPathStat(dir.path, dir.stat, keepMode) +} + +// applyDelayedLinks replaces each placeholder still in place with its link, in archive order. +func (e *tarExtractor) applyDelayedLinks() error { + for _, link := range e.delayed { + if link.replaced { + continue + } + info, err := os.Lstat(link.path) + if err != nil || idOf(info) != link.id { + // An entry reached the placeholder through another path and replaced it. + continue + } + if err := removeEntry(link.path); err != nil { + return err + } + if !link.symlink { + if err := os.Link(link.target, link.path); err != nil { + return errors.Wrapf(err, "failed to link %s to %s", link.path, link.target) + } + continue + } + if err := os.Symlink(link.target, link.path); err != nil { + return errors.Wrapf(err, "failed to create symlink %s", link.path) + } + if err := e.setPathStat(link.path, link.stat, true); err != nil { + return err + } + } + return nil +} diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go new file mode 100644 index 00000000..7829a8a9 --- /dev/null +++ b/client/tar_extractor_linux.go @@ -0,0 +1,877 @@ +package client + +import ( + "archive/tar" + "context" + "io" + "io/fs" + "os" + "os/user" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + + "github.com/alecthomas/errors" + "golang.org/x/sync/semaphore" + "golang.org/x/sys/unix" +) + +// GNU tar type flags that archive/tar has no names for. +const ( + gnuTypeDumpDir = 'D' + gnuTypeMultiVolume = 'M' + gnuTypeVolumeHeader = 'V' +) + +const ( + // maxBufferedFile is the largest file read whole before it is queued; larger files are streamed in chunks. + maxBufferedFile = 1 << 20 + streamChunkSize = 4 << 20 + // maxBufferedBytes bounds the file contents held in memory while they wait for a writer. + maxBufferedBytes = 64 << 20 + copyBufferBytes = 1 << 20 + // pruneInFlightAt is the pending-write map size that triggers dropping completed writes. + pruneInFlightAt = 1024 +) + +// entryStat is the metadata applied to an extracted entry. +type entryStat struct { + uid, gid int + mode uint32 + mtime unix.Timespec +} + +// fileWrite is a buffered regular file queued for a writer goroutine. +type fileWrite struct { + target string + stat entryStat + data []byte + done chan struct{} +} + +// fileID identifies an inode. +type fileID struct { + dev, ino uint64 +} + +// delayedLink is a placeholder file that becomes a link once extraction finishes, as in GNU tar. +// +// GNU tar never creates a symlink with an absolute or ".." target, or a hard link to one, until the end, so later +// entries cannot be written through it. +type delayedLink struct { + path string + id fileID + symlink bool + target string + stat entryStat + // replaced is set once a later entry claims the path; inode numbers alone can be reused. + replaced bool +} + +// tarExtractor applies a tar stream to root with the behaviour of GNU tar's "tar -xp". +// +// Regular files up to maxBufferedFile are written by writer goroutines and larger ones are streamed to their own +// goroutine. Before an entry touches a path it waits for any pending write to it, so entries apply in archive order. +type tarExtractor struct { + root string + asRoot bool + umask int + numWriters int + buffer *semaphore.Weighted + jobs chan fileWrite + streams sync.WaitGroup + // chunks recycles stream buffers; fresh 4 MiB allocations cost more in page faults than the write itself. + chunks chan []byte + failOnce sync.Once + failed chan struct{} + failErr error + + // The fields below belong to the goroutine reading the archive. + inFlight map[string]chan struct{} + // dirs holds directories known to exist whose path goes through no symlink. + dirs map[string]struct{} + dirStack dirStack + delayed []delayedLink + delayedAt map[string]int + placeholders map[fileID]struct{} + users map[string]int + groups map[string]int + copyBuf []byte +} + +func newTarExtractor(root string, writers int) *tarExtractor { + root = filepath.Clean(root) + return &tarExtractor{ + root: root, + asRoot: os.Geteuid() == 0, + umask: processUmask(), + numWriters: writers, + buffer: semaphore.NewWeighted(maxBufferedBytes), + jobs: make(chan fileWrite, 4*writers), + chunks: make(chan []byte, maxBufferedBytes/streamChunkSize), + failed: make(chan struct{}), + inFlight: map[string]chan struct{}{}, + dirs: map[string]struct{}{root: {}}, + dirStack: newDirStack(), + delayedAt: map[string]int{}, + placeholders: map[fileID]struct{}{}, + users: map[string]int{}, + groups: map[string]int{}, + copyBuf: make([]byte, copyBufferBytes), + } +} + +func processUmask() int { + // unix.Umask reads the umask by changing it, racing other goroutines; unknown is 0o777, assuming all bits masked. + status, err := os.ReadFile("/proc/self/status") + if err != nil { + return 0o777 + } + for line := range strings.Lines(string(status)) { + if value, ok := strings.CutPrefix(line, "Umask:"); ok { + umask, err := strconv.ParseInt(strings.TrimSpace(value), 8, 32) + if err != nil { + return 0o777 + } + return int(umask) + } + } + return 0o777 +} + +func (e *tarExtractor) extract(ctx context.Context, r io.Reader) error { + var writers sync.WaitGroup + for range e.numWriters { + writers.Go(e.runWriter) + } + if err := e.readEntries(ctx, tar.NewReader(r)); err != nil { + // Queued writes are skipped once extraction has failed. + e.fail(err) + } + close(e.jobs) + writers.Wait() + e.streams.Wait() + if e.failErr != nil { + return e.failErr + } + return e.finish() +} + +func (e *tarExtractor) runWriter() { + for job := range e.jobs { + select { + case <-e.failed: + default: + err := writeFile(job.target, job.stat, e.asRoot, removeEntry, func(f *os.File) error { + _, err := f.Write(job.data) + return errors.WithStack(err) + }) + if err != nil { + e.fail(err) + } + } + e.buffer.Release(int64(len(job.data))) + close(job.done) + } +} + +func (e *tarExtractor) fail(err error) { + e.failOnce.Do(func() { + e.failErr = err + close(e.failed) + }) +} + +func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader) error { + for { + select { + case <-e.failed: + return nil + default: + } + if err := ctx.Err(); err != nil { + return errors.WithStack(err) + } + hdr, err := nextTarEntry(tr) + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return errors.Wrap(err, "failed to read archive") + } + if err := e.entry(ctx, tr, hdr); err != nil { + return err + } + } +} + +func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Header) error { + if hdr.Typeflag == tar.TypeXGlobalHeader { + return nil + } + if containsDotDot(hdr.Name) { + return errors.Errorf("%s: member name contains '..'", hdr.Name) + } + name := memberName(hdr.Name) + e.dirStack.finishNonAncestors(name) + switch hdr.Typeflag { + case gnuTypeVolumeHeader: + return nil + case gnuTypeMultiVolume: + return errors.Errorf("%s: cannot extract a file continued from another volume", hdr.Name) + } + target := filepath.Join(e.root, name) + if e.dirStack.touchesFinished(e.root, target) { + if err := e.flushFinished(); err != nil { + return err + } + } + isDir := isDirEntry(hdr) + if target == e.root { + if !isDir { + return errors.Errorf("%s: cannot replace the target directory", hdr.Name) + } + return e.recordDir(name, target, hdr, false, nil) + } + claimed, hadPlaceholder := e.claim(target, isDir) + viaLink, err := e.ensureParent(name, target) + if err != nil { + return err + } + if viaLink { + // The path may alias one with a queued write or an applied directory, so settle both first. + if err := e.flushFinished(); err != nil { + return err + } + } + if err := e.apply(ctx, tr, hdr, name, target, viaLink); err != nil { + return err + } + if hadPlaceholder && e.delayed[claimed].replaced { + // The inode is free for reuse, so it must not identify a placeholder any more. + delete(e.placeholders, e.delayed[claimed].id) + } + return nil +} + +func memberName(name string) string { + // GNU tar strips trailing slashes and then leading slashes and ".." prefixes; a lone "/" names the root. + if trimmed := strings.TrimRight(name, "/"); trimmed != "" { + name = trimmed + } + return saferName(name) +} + +func (e *tarExtractor) apply( + ctx context.Context, tr *tar.Reader, hdr *tar.Header, name, target string, viaLink bool, +) error { + switch { + case isDirEntry(hdr): + return e.dir(name, target, hdr, viaLink) + case hdr.Typeflag == tar.TypeSymlink: + return e.symlink(name, target, hdr, viaLink) + case hdr.Typeflag == tar.TypeLink: + return e.hardlink(name, target, hdr, viaLink) + case hdr.Typeflag == tar.TypeChar, hdr.Typeflag == tar.TypeBlock, hdr.Typeflag == tar.TypeFifo: + return e.node(target, hdr, viaLink) + default: + // GNU tar extracts regular, contiguous, sparse and unknown entry types as regular files. + return e.regular(ctx, tr, hdr, target, viaLink) + } +} + +func isDirEntry(hdr *tar.Header) bool { + switch hdr.Typeflag { + case tar.TypeDir, gnuTypeDumpDir: + return true + case tar.TypeReg, tar.TypeCont: + return strings.HasSuffix(hdr.Name, "/") + } + return false +} + +func containsDotDot(name string) bool { + return slices.Contains(strings.Split(name, "/"), "..") +} + +func saferName(name string) string { + // GNU tar drops everything up to the last ".." component, then any leading slashes. + start := 0 + for i := 0; i < len(name); { + if strings.HasPrefix(name[i:], "..") && (i+2 == len(name) || name[i+2] == '/') { + start = i + 2 + } + next := strings.IndexByte(name[i:], '/') + if next < 0 { + break + } + i += next + 1 + } + name = strings.TrimLeft(name[start:], "/") + if name == "" { + return "." + } + return name +} + +func (e *tarExtractor) claim(target string, isDir bool) (int, bool) { + e.wait(target) + i, ok := e.delayedAt[target] + if ok { + e.delayed[i].replaced = true + delete(e.delayedAt, target) + } + if !isDir { + e.forgetDir(target) + } + return i, ok +} + +func (e *tarExtractor) forgetDir(path string) { + if _, ok := e.dirs[path]; !ok { + return + } + prefix := path + string(filepath.Separator) + for dir := range e.dirs { + if dir == path || strings.HasPrefix(dir, prefix) { + delete(e.dirs, dir) + } + } +} + +func (e *tarExtractor) wait(path string) { + if done, ok := e.inFlight[path]; ok { + <-done + delete(e.inFlight, path) + } +} + +func (e *tarExtractor) waitAll() { + for _, done := range e.inFlight { + <-done + } + clear(e.inFlight) +} + +func (e *tarExtractor) pruneInFlight() { + // Completed writes are dropped in batches so the map stays proportional to the writer queue. + if len(e.inFlight) < pruneInFlightAt { + return + } + for path, done := range e.inFlight { + select { + case <-done: + delete(e.inFlight, path) + default: + } + } +} + +// ensureParent creates target's missing parent directories and reports whether its path goes through a symlink. +// +// Like GNU tar it follows existing symlinks to directories; placeholders for unsafe links are regular files, so +// paths through them fail. +func (e *tarExtractor) ensureParent(name, target string) (bool, error) { + parent := filepath.Dir(target) + if _, ok := e.dirs[parent]; ok { + return false, nil + } + viaLink, err := e.ensureParent(name, parent) + if err != nil { + return false, err + } + e.wait(parent) + info, err := os.Lstat(parent) + switch { + case errors.Is(err, fs.ErrNotExist): + err = e.mkdirParent(name, parent) + case err != nil: + err = errors.WithStack(err) + case info.IsDir(): + case info.Mode()&fs.ModeSymlink != 0: + viaLink = true + err = requireDir(parent) + default: + err = errors.Errorf("%s: not a directory", parent) + } + if err != nil { + return false, err + } + if !viaLink { + e.dirs[parent] = struct{}{} + } + return viaLink, nil +} + +func requireDir(path string) error { + info, err := os.Stat(path) + if err != nil { + return errors.WithStack(err) + } + if !info.IsDir() { + return errors.Errorf("%s: not a directory", path) + } + return nil +} + +func (e *tarExtractor) mkdirParent(name, path string) error { + // GNU tar gives unlisted parents the umask's mode, owner-writable and searchable until extraction finishes. + if err := os.Mkdir(path, 0o777); err != nil { + return errors.WithStack(err) + } + var st unix.Stat_t + if err := unix.Lstat(path, &st); err != nil { + return errors.Wrapf(err, "failed to stat %s", path) + } + desired := st.Mode & 0o777 + if !e.asRoot && desired&0o300 != 0o300 { + if err := unix.Chmod(path, st.Mode&0o7777|0o300); err != nil { + return errors.Wrapf(err, "failed to chmod %s", path) + } + } + return e.dirStack.push(pendingDir{ + name: e.parentName(name, path), + path: path, + stat: entryStat{mode: desired}, + interdir: true, + }) +} + +func (e *tarExtractor) parentName(name, path string) string { + // GNU tar names a created parent by the member name's prefix, which name comparisons later rely on. + for i := range len(name) { + if name[i] == '/' && filepath.Join(e.root, name[:i]) == path { + return name[:i] + } + } + rel, err := filepath.Rel(e.root, path) + if err != nil { + return path + } + return rel +} + +func (e *tarExtractor) dir(name, target string, hdr *tar.Header, viaLink bool) error { + // Like GNU tar, keep an existing directory but replace anything else, even a symlink to a directory. + info, err := os.Lstat(target) + switch { + case err == nil && info.IsDir(): + return e.recordDir(name, target, hdr, viaLink, nil) + case err == nil: + if err := e.removeExisting(target, viaLink); err != nil { + return err + } + case !errors.Is(err, fs.ErrNotExist): + return errors.WithStack(err) + } + created, err := e.mkdir(target, hdr) + if err != nil { + return err + } + return e.recordDir(name, target, hdr, viaLink, &created) +} + +func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { + // Owner-only until applyDirs sets the archived mode, so other users cannot use it early. + mode := uint32(hdr.Mode) & 0o700 //nolint:gosec // mode bits only + if !e.asRoot { + mode |= 0o300 + } + if err := unix.Mkdir(target, mode); err != nil { + return 0, errors.Wrapf(err, "failed to create directory %s", target) + } + // GNU tar clears the umask for -p; this process can't, so undo it where it would affect the owner. + if e.umask&int(mode) != 0 { + return mode, errors.Wrapf(unix.Chmod(target, mode), "failed to chmod %s", target) + } + return mode, nil +} + +func (e *tarExtractor) recordDir(name, target string, hdr *tar.Header, viaLink bool, created *uint32) error { + stat, err := e.stat(hdr) + if err != nil { + return err + } + if !viaLink { + e.dirs[target] = struct{}{} + } + dir := pendingDir{name: name, path: target, stat: stat} + if created != nil { + dir.created, dir.wasCreated = *created, true + } + return e.dirStack.push(dir) +} + +func (e *tarExtractor) removeExisting(path string, viaLink bool) error { + if info, err := os.Lstat(path); err == nil && info.IsDir() { + // Queued writes may still be filling the directory, which GNU tar would find non-empty. + e.waitAll() + if viaLink { + // The directory may also be cached under a path without symlinks. + e.dirs = map[string]struct{}{e.root: {}} + } + } + return removeEntry(path) +} + +func removeEntry(path string) error { + return errors.Wrapf(os.Remove(path), "failed to replace %s", path) +} + +func createReplacing(path string, remove func(string) error, create func() error) error { + // GNU tar's default overwrites an existing entry by removing it and retrying once. + err := create() + if !errors.Is(err, fs.ErrExist) { + return err + } + if err := remove(path); err != nil { + return err + } + return create() +} + +func (e *tarExtractor) regular( + ctx context.Context, tr *tar.Reader, hdr *tar.Header, target string, viaLink bool, +) error { + stat, err := e.stat(hdr) + if err != nil { + return err + } + switch { + case viaLink: + // Written before the next entry, since a later path may alias this one. + remove := func(path string) error { return e.removeExisting(path, viaLink) } + return writeFile(target, stat, e.asRoot, remove, func(f *os.File) error { + // Hiding ReadFrom keeps io.CopyBuffer on the large buffer instead of os.File's 32 KiB copy loop. + _, err := io.CopyBuffer(struct{ io.Writer }{f}, tr, e.copyBuf) + return errors.Wrapf(err, "failed to write %s", target) + }) + case hdr.Size > maxBufferedFile: + return e.stream(ctx, tr, hdr, target, stat) + } + if err := e.buffer.Acquire(ctx, hdr.Size); err != nil { + return errors.WithStack(err) + } + data := make([]byte, hdr.Size) + if _, err := io.ReadFull(tr, data); err != nil { + e.buffer.Release(hdr.Size) + return errors.Wrapf(err, "failed to read %s", hdr.Name) + } + done := make(chan struct{}) + e.inFlight[target] = done + e.jobs <- fileWrite{target: target, stat: stat, data: data, done: done} + e.pruneInFlight() + return nil +} + +func (e *tarExtractor) stream(ctx context.Context, tr *tar.Reader, hdr *tar.Header, target string, stat entryStat) error { + // A goroutine writes the file while the reader moves on, so decoding continues during large writes. + chunks := make(chan []byte, 4) + done := make(chan struct{}) + e.inFlight[target] = done + e.streams.Go(func() { + defer close(done) + err := writeFile(target, stat, e.asRoot, removeEntry, func(f *os.File) error { + for chunk := range chunks { + _, err := f.Write(chunk) + e.releaseChunk(chunk) + if err != nil { + return errors.Wrapf(err, "failed to write %s", target) + } + } + return nil + }) + for chunk := range chunks { + e.releaseChunk(chunk) + } + if err != nil { + e.fail(err) + } + }) + defer close(chunks) + for remaining := hdr.Size; remaining > 0; { + n := min(remaining, streamChunkSize) + if err := e.buffer.Acquire(ctx, n); err != nil { + return errors.WithStack(err) + } + chunk := e.newChunk(n) + if _, err := io.ReadFull(tr, chunk); err != nil { + e.releaseChunk(chunk) + return errors.Wrapf(err, "failed to read %s", hdr.Name) + } + chunks <- chunk + remaining -= n + } + return nil +} + +func (e *tarExtractor) newChunk(n int64) []byte { + select { + case chunk := <-e.chunks: + return chunk[:n] + default: + return make([]byte, n, streamChunkSize) + } +} + +func (e *tarExtractor) releaseChunk(chunk []byte) { + e.buffer.Release(int64(len(chunk))) + select { + case e.chunks <- chunk[:cap(chunk)]: + default: + } +} + +func writeFile( + target string, stat entryStat, asRoot bool, remove func(string) error, write func(*os.File) error, +) error { + var f *os.File + err := createReplacing(target, remove, func() error { + var err error + f, err = os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + return errors.WithStack(err) + }) + if err != nil { + return errors.Wrapf(err, "failed to create %s", target) + } + err = write(f) + if err == nil { + err = setFileStat(f, stat, asRoot) + } + return errors.Join(err, errors.Wrapf(f.Close(), "failed to close %s", target)) +} + +func setFileStat(f *os.File, stat entryStat, asRoot bool) error { + // Mode goes last, as in GNU tar, because chown can clear set-ID bits. + if err := setMtime(f.Name(), stat); err != nil { + return err + } + if asRoot { + if err := f.Chown(stat.uid, stat.gid); err != nil { + return errors.WithStack(err) + } + } + return errors.Wrapf(unix.Fchmod(int(f.Fd()), stat.mode), "failed to chmod %s", f.Name()) //nolint:gosec // fd +} + +func (e *tarExtractor) setPathStat(path string, stat entryStat, keepMode bool) error { + if err := setMtime(path, stat); err != nil { + return err + } + if e.asRoot { + if err := os.Lchown(path, stat.uid, stat.gid); err != nil { + return errors.WithStack(err) + } + } + if keepMode { + return nil + } + return errors.Wrapf(unix.Chmod(path, stat.mode), "failed to chmod %s", path) +} + +func setMtime(path string, stat entryStat) error { + // GNU tar leaves atime alone outside incremental mode. + times := []unix.Timespec{{Nsec: unix.UTIME_OMIT}, stat.mtime} + err := unix.UtimesNanoAt(unix.AT_FDCWD, path, times, unix.AT_SYMLINK_NOFOLLOW) + return errors.Wrapf(err, "failed to set times on %s", path) +} + +func (e *tarExtractor) stat(hdr *tar.Header) (entryStat, error) { + mtime, err := unix.TimeToTimespec(hdr.ModTime) + if err != nil { + return entryStat{}, errors.Wrapf(err, "%s: unsupported modification time", hdr.Name) + } + stat := entryStat{mode: uint32(hdr.Mode) & 0o7777, mtime: mtime} //nolint:gosec // mode bits only + if e.asRoot { + stat.uid = cachedID(e.users, hdr.Uname, hdr.Uid, userID) + stat.gid = cachedID(e.groups, hdr.Gname, hdr.Gid, groupID) + } + return stat, nil +} + +func cachedID(cache map[string]int, name string, numeric int, lookup func(string) (int, error)) int { + // GNU tar prefers the archived owner name and falls back to the numeric ID when the name is unknown. + if name == "" { + return numeric + } + id, ok := cache[name] + if !ok { + var err error + if id, err = lookup(name); err != nil { + id = -1 + } + cache[name] = id + } + if id < 0 { + return numeric + } + return id +} + +func userID(name string) (int, error) { + u, err := user.Lookup(name) + if err != nil { + return 0, errors.WithStack(err) + } + id, err := strconv.Atoi(u.Uid) + return id, errors.WithStack(err) +} + +func groupID(name string) (int, error) { + g, err := user.LookupGroup(name) + if err != nil { + return 0, errors.WithStack(err) + } + id, err := strconv.Atoi(g.Gid) + return id, errors.WithStack(err) +} + +func isUnsafeLinkTarget(target string) bool { + // GNU tar defers symlinks whose target is absolute or has a ".." component. + return strings.HasPrefix(target, "/") || containsDotDot(target) +} + +func (e *tarExtractor) symlink(name, target string, hdr *tar.Header, viaLink bool) error { + stat, err := e.stat(hdr) + if err != nil { + return err + } + if isUnsafeLinkTarget(hdr.Linkname) { + return e.placeholder(name, target, delayedLink{symlink: true, target: hdr.Linkname, stat: stat}, viaLink) + } + remove := func(path string) error { return e.removeExisting(path, viaLink) } + err = createReplacing(target, remove, func() error { return errors.WithStack(os.Symlink(hdr.Linkname, target)) }) + if err != nil { + return errors.Wrapf(err, "failed to create symlink %s", target) + } + return e.setPathStat(target, stat, true) +} + +// placeholder creates the empty file GNU tar puts where a deferred link goes, and records the link. +func (e *tarExtractor) placeholder(name, target string, link delayedLink, viaLink bool) error { + for attempt := 0; ; attempt++ { + f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0) + if err == nil { + info, err := f.Stat() + closeErr := f.Close() + if err = errors.Join(err, closeErr); err != nil { + return errors.Wrapf(err, "failed to create placeholder %s", target) + } + link.path = target + link.id = idOf(info) + e.delayedAt[target] = len(e.delayed) + e.delayed = append(e.delayed, link) + e.placeholders[link.id] = struct{}{} + return e.dirStack.markLinkParent(name) + } + if attempt > 0 || !errors.Is(err, fs.ErrExist) { + return errors.Wrapf(err, "failed to create placeholder %s", target) + } + if e.isPlaceholder(target) { + // GNU tar keeps the first of several deferred links at the same path. + e.keepDelayed(target) + return nil + } + if err := e.removeExisting(target, viaLink); err != nil { + return err + } + } +} + +func (e *tarExtractor) keepDelayed(path string) { + // The placeholder stays in place, so undo claim marking it replaced. + for i := len(e.delayed) - 1; i >= 0; i-- { + if e.delayed[i].path == path && e.delayed[i].replaced { + e.delayed[i].replaced = false + e.delayedAt[path] = i + return + } + } +} + +func (e *tarExtractor) isPlaceholder(path string) bool { + if len(e.placeholders) == 0 { + return false + } + info, err := os.Lstat(path) + if err != nil { + return false + } + _, ok := e.placeholders[idOf(info)] + return ok +} + +func idOf(info fs.FileInfo) fileID { + sys, ok := info.Sys().(*unix.Stat_t) + if !ok { + return fileID{} + } + return fileID{dev: sys.Dev, ino: sys.Ino} +} + +func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bool) error { + source := filepath.Join(e.root, saferName(hdr.Linkname)) + if _, ok := e.dirs[filepath.Dir(source)]; ok { + e.wait(source) + } else { + // The source path may go through a symlink to a file with a queued write. + e.waitAll() + } + if e.isPlaceholder(source) { + return e.placeholder(name, target, delayedLink{target: source}, viaLink) + } + for attempt := 0; ; attempt++ { + err := os.Link(source, target) + if err == nil { + return nil + } + if !errors.Is(err, fs.ErrExist) { + return errors.Wrapf(err, "failed to link %s to %s", target, source) + } + if source == target || sameFile(source, target) { + return nil + } + if attempt > 0 { + return errors.Wrapf(err, "failed to link %s to %s", target, source) + } + if err := e.removeExisting(target, viaLink); err != nil { + return err + } + } +} + +func sameFile(a, b string) bool { + ai, err := os.Lstat(a) + if err != nil { + return false + } + bi, err := os.Lstat(b) + return err == nil && os.SameFile(ai, bi) +} + +func (e *tarExtractor) node(target string, hdr *tar.Header, viaLink bool) error { + stat, err := e.stat(hdr) + if err != nil { + return err + } + var kind uint32 + switch hdr.Typeflag { + case tar.TypeChar: + kind = unix.S_IFCHR + case tar.TypeBlock: + kind = unix.S_IFBLK + default: + kind = unix.S_IFIFO + } + dev := unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor)) //nolint:gosec // device numbers are 32-bit + remove := func(path string) error { return e.removeExisting(path, viaLink) } + err = createReplacing(target, remove, func() error { + return errors.WithStack(unix.Mknod(target, kind|stat.mode&0o777, int(dev))) //nolint:gosec // Linux dev_t + }) + if err != nil { + return errors.Wrapf(err, "failed to create %s", target) + } + return e.setPathStat(target, stat, false) +} diff --git a/go.mod b/go.mod index 51158c2d..4cb61388 100644 --- a/go.mod +++ b/go.mod @@ -30,6 +30,7 @@ require ( golang.org/x/crypto v0.49.0 golang.org/x/mod v0.39.0 golang.org/x/sync v0.22.0 + golang.org/x/sys v0.47.0 ) require ( @@ -88,7 +89,6 @@ require ( go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.52.0 // indirect - golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.35.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect From f2aaec296bf4e439adbb95ee2bbfabb6d2a17766 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 06:12:33 +0000 Subject: [PATCH 02/11] fix(client): match GNU tar on review edge cases in the extractor - Read inode identity from syscall.Stat_t, which is what os returns, so replaced placeholders and freed inodes are detected. - Treat a directory reached through a symlink as possibly aliased, so its delayed metadata is applied before an entry under the real path. - Apply PAX global headers to later members, as GNU tar does. - Reject empty archives and archives cut off inside member padding. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 73 ++++++++++++++++++++++++++++++-- client/tar_delayed_linux.go | 9 ++++ client/tar_extractor_linux.go | 53 ++++++++++++++++++++---- client/tar_pax_linux.go | 78 +++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+), 12 deletions(-) create mode 100644 client/tar_pax_linux.go diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 74e5768d..7902e1f8 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -47,6 +47,16 @@ func regularWithSlash(name string, mode int64) tarEntry { return tarEntry{hdr: tar.Header{Typeflag: tar.TypeReg, Name: placeholder, Mode: mode}, rawName: name} } +func globalHeader(records map[string]string) tarEntry { + return tarEntry{hdr: tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: "global", PAXRecords: records}} +} + +func wholeSecond(entry tarEntry) tarEntry { + // Whole seconds fit the USTAR field, so the member has no mtime record of its own. + entry.hdr.ModTime = time.Date(2019, 1, 2, 3, 4, 5, 0, time.UTC) + return entry +} + func typed(flag byte, name string, mode int64, body string) tarEntry { return tarEntry{hdr: tar.Header{Typeflag: flag, Name: name, Mode: mode}, body: body} } @@ -98,6 +108,7 @@ func TestExtractMatchesGNUTar(t *testing.T) { hardlink("hard-small", "dir/small"), hardlink("hard-large", "dir/large"), hardlink("hard-absolute", "absolute"), + regular("dir/small", 0o600, "replaced"), hardlink("hard-rooted", "/dir/small"), hardlink("hard-escaping", "../../dir/small"), typed(tar.TypeFifo, "fifo", 0o640, ""), @@ -133,13 +144,26 @@ func TestExtractMatchesGNUTar(t *testing.T) { typed('Z', "unknown-type", 0o644, "data"), regular("/absolute/file", 0o644, "abs"), }}, + {name: "GlobalHeaders", entries: []tarEntry{ + globalHeader(map[string]string{"mtime": "1500000000.5", "linkpath": "global-target"}), + wholeSecond(regular("global-mtime", 0o644, "x")), + regular("own-mtime-record", 0o644, "x"), + wholeSecond(symlink("global-linkpath", "own-target")), + globalHeader(map[string]string{"comment": "replaces the first global header"}), + wholeSecond(regular("after-replacing-global", 0o644, "x")), + globalHeader(map[string]string{"mtime": "1400000000"}), + wholeSecond(regular("global-mtime-again", 0o644, "x")), + globalHeader(map[string]string{}), + wholeSecond(regular("after-empty-global", 0o644, "x")), + }}, {name: "ExistingTree", setup: existingTree, entries: []tarEntry{ - regular("file-over-dir-parent/file", 0o644, "x"), directory("symlink-to-dir/", 0o755), regular("symlink-to-dir/file", 0o644, "x"), regular("symlinked-parent/file", 0o644, "into target"), regular("dangling", 0o644, "x"), regular("readonly", 0o644, "rewritten"), + symlink("unsafe", "/first"), + symlink("stale", "/second"), }}, {name: "OutOfOrder", entries: []tarEntry{ directory("revisited/", 0o755), @@ -152,6 +176,14 @@ func TestExtractMatchesGNUTar(t *testing.T) { symlink("link-parent/unsafe", "/absolute"), regular("after-link", 0o644, "x"), }}, + {name: "AliasedDirectory", entries: []tarEntry{ + directory("real/", 0o755), + symlink("alias", "real"), + directory("alias/replaced/", 0o755), + regular("real/replaced", 0o644, "x"), + directory("alias/written/", 0o700), + regular("real/written/file", 0o644, "x"), + }}, {name: "RevisitReadOnly", entries: []tarEntry{ directory("readonly/", 0o555), regular("elsewhere", 0o644, "x"), @@ -165,6 +197,9 @@ func TestExtractMatchesGNUTar(t *testing.T) { symlink("s", "u"), regular("s/file", 0o644, "x"), }}, + {name: "UnderExistingFile", setup: existingTree, entries: []tarEntry{ + regular("file-over-dir-parent/file", 0o644, "x"), + }}, {name: "FileOverNonEmptyDir", entries: []tarEntry{regular("d/f", 0o644, "x"), regular("d", 0o644, "x")}}, {name: "FileOverTargetDir", entries: []tarEntry{regular(".", 0o644, "x")}}, } @@ -191,6 +226,31 @@ func TestExtractMatchesGNUTar(t *testing.T) { } } +func TestExtractRejectsGlobalDataLayoutRecords(t *testing.T) { + // GNU tar reads member data using these, but archive/tar has already sized the member from its own header. + for _, key := range []string{"size", "GNU.sparse.realsize"} { + t.Run(key, func(t *testing.T) { + entries := []tarEntry{globalHeader(map[string]string{key: "1"}), regular("file", 0o644, "data")} + archive := zstdCompress(t, buildTar(t, entries)) + err := client.Extract(t.Context(), bytes.NewReader(archive), t.TempDir(), 0) + assert.Error(t, err) + }) + } +} + +func TestExtractRejectsIncompleteArchive(t *testing.T) { + archive := buildTar(t, []tarEntry{wholeSecond(regular("file", 0o644, "data"))}) + for name, data := range map[string][]byte{ + "Empty": nil, + "MissingPadding": archive[:512+len("data")], + } { + t.Run(name, func(t *testing.T) { + err := client.Extract(t.Context(), bytes.NewReader(zstdCompress(t, data)), t.TempDir(), 0) + assert.Error(t, err) + }) + } +} + func TestExtractLaterEntryReplacesUnsafeSymlink(t *testing.T) { // GNU tar finds placeholders by inode number, so a file reusing a freed placeholder's inode confuses it. cases := []struct { @@ -244,6 +304,7 @@ func existingTree(t *testing.T, dir string) { assert.NoError(t, os.Symlink("target", filepath.Join(dir, "symlinked-parent"))) assert.NoError(t, os.Symlink("nowhere", filepath.Join(dir, "dangling"))) assert.NoError(t, os.WriteFile(filepath.Join(dir, "readonly"), []byte("old"), 0o444)) + assert.NoError(t, os.WriteFile(filepath.Join(dir, "stale"), []byte("old"), 0o644)) } func archiveTime() time.Time { @@ -256,11 +317,17 @@ func buildTar(t *testing.T, entries []tarEntry) []byte { tw := tar.NewWriter(&buf) for _, entry := range entries { hdr := entry.hdr - hdr.ModTime = archiveTime() + if hdr.ModTime.IsZero() { + hdr.ModTime = archiveTime() + } hdr.Format = tar.FormatPAX hdr.Size = int64(len(entry.body)) if hdr.Typeflag == tar.TypeXGlobalHeader { - hdr = tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: hdr.Name, PAXRecords: map[string]string{"comment": "x"}} + records := hdr.PAXRecords + if records == nil { + records = map[string]string{"comment": "x"} + } + hdr = tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: hdr.Name, PAXRecords: records} } if entry.rawName != "" { // A single USTAR block, so the name can be patched in place. diff --git a/client/tar_delayed_linux.go b/client/tar_delayed_linux.go index 926d092a..4f0c0800 100644 --- a/client/tar_delayed_linux.go +++ b/client/tar_delayed_linux.go @@ -23,6 +23,8 @@ type pendingDir struct { // afterLinks holds the directory back until delayed links exist; id detects it being replaced meanwhile. afterLinks bool id fileID + // viaLink marks a path through a symlink, which entries can reach under another name. + viaLink bool } // dirStack mirrors GNU tar's delayed_set_stat list, deferring the metadata calls it would make mid-extraction. @@ -36,6 +38,8 @@ type dirStack struct { // finished holds directories GNU tar would already have applied, in order, keyed by path in finishedPaths. finished []*pendingDir finishedPaths map[string]struct{} + // finishedViaLink is set when a finished directory may be reached through a path finishedPaths doesn't hold. + finishedViaLink bool } func newDirStack() dirStack { @@ -76,6 +80,7 @@ func (s *dirStack) finishNonAncestors(name string) { s.pop() s.finished = append(s.finished, top) s.finishedPaths[top.path] = struct{}{} + s.finishedViaLink = s.finishedViaLink || top.viaLink } } @@ -91,6 +96,9 @@ func (s *dirStack) touchesFinished(root, path string) bool { if len(s.finishedPaths) == 0 { return false } + if s.finishedViaLink { + return true + } for ; len(path) >= len(root); path = filepath.Dir(path) { if _, ok := s.finishedPaths[path]; ok { return true @@ -156,6 +164,7 @@ func (e *tarExtractor) flushFinished() error { } e.dirStack.finished = nil clear(e.dirStack.finishedPaths) + e.dirStack.finishedViaLink = false return nil } diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 7829a8a9..a4c03634 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -12,6 +12,7 @@ import ( "strconv" "strings" "sync" + "syscall" "github.com/alecthomas/errors" "golang.org/x/sync/semaphore" @@ -34,6 +35,8 @@ const ( copyBufferBytes = 1 << 20 // pruneInFlightAt is the pending-write map size that triggers dropping completed writes. pruneInFlightAt = 1024 + // blockSize is the tar record unit; a complete archive is a whole number of blocks. + blockSize = 512 ) // entryStat is the metadata applied to an extracted entry. @@ -98,6 +101,7 @@ type tarExtractor struct { placeholders map[fileID]struct{} users map[string]int groups map[string]int + globalPAX map[string]string copyBuf []byte } @@ -146,7 +150,8 @@ func (e *tarExtractor) extract(ctx context.Context, r io.Reader) error { for range e.numWriters { writers.Go(e.runWriter) } - if err := e.readEntries(ctx, tar.NewReader(r)); err != nil { + archive := &countingReader{r: r} + if err := e.readEntries(ctx, tar.NewReader(archive), archive); err != nil { // Queued writes are skipped once extraction has failed. e.fail(err) } @@ -177,6 +182,29 @@ func (e *tarExtractor) runWriter() { } } +// countingReader counts the bytes tar.Reader consumes, which shows where the archive ended. +type countingReader struct { + r io.Reader + n int64 +} + +func (c *countingReader) Read(p []byte) (int, error) { + n, err := c.r.Read(p) + c.n += int64(n) + return n, err //nolint:wrapcheck // io.Reader errors such as io.EOF must pass through unwrapped +} + +func (c *countingReader) checkEnd() error { + // tar.Reader reports io.EOF for an empty stream and for one cut off in a member's padding; GNU tar rejects both. + switch { + case c.n == 0: + return errors.New("archive is empty") + case c.n%blockSize != 0: + return errors.Errorf("unexpected EOF in archive after %d bytes", c.n) + } + return nil +} + func (e *tarExtractor) fail(err error) { e.failOnce.Do(func() { e.failErr = err @@ -184,7 +212,7 @@ func (e *tarExtractor) fail(err error) { }) } -func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader) error { +func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader, archive *countingReader) error { for { select { case <-e.failed: @@ -196,7 +224,7 @@ func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader) error { } hdr, err := nextTarEntry(tr) if errors.Is(err, io.EOF) { - return nil + return archive.checkEnd() } if err != nil { return errors.Wrap(err, "failed to read archive") @@ -209,7 +237,12 @@ func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader) error { func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Header) error { if hdr.Typeflag == tar.TypeXGlobalHeader { - return nil + // As in GNU tar, each global header replaces the previous one, even an empty one. + e.globalPAX = hdr.PAXRecords + return checkGlobalPAX(e.globalPAX) + } + if err := applyGlobalPAX(hdr, e.globalPAX); err != nil { + return err } if containsDotDot(hdr.Name) { return errors.Errorf("%s: member name contains '..'", hdr.Name) @@ -386,7 +419,7 @@ func (e *tarExtractor) ensureParent(name, target string) (bool, error) { info, err := os.Lstat(parent) switch { case errors.Is(err, fs.ErrNotExist): - err = e.mkdirParent(name, parent) + err = e.mkdirParent(name, parent, viaLink) case err != nil: err = errors.WithStack(err) case info.IsDir(): @@ -416,7 +449,7 @@ func requireDir(path string) error { return nil } -func (e *tarExtractor) mkdirParent(name, path string) error { +func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { // GNU tar gives unlisted parents the umask's mode, owner-writable and searchable until extraction finishes. if err := os.Mkdir(path, 0o777); err != nil { return errors.WithStack(err) @@ -436,6 +469,7 @@ func (e *tarExtractor) mkdirParent(name, path string) error { path: path, stat: entryStat{mode: desired}, interdir: true, + viaLink: viaLink, }) } @@ -497,7 +531,7 @@ func (e *tarExtractor) recordDir(name, target string, hdr *tar.Header, viaLink b if !viaLink { e.dirs[target] = struct{}{} } - dir := pendingDir{name: name, path: target, stat: stat} + dir := pendingDir{name: name, path: target, stat: stat, viaLink: viaLink} if created != nil { dir.created, dir.wasCreated = *created, true } @@ -804,11 +838,12 @@ func (e *tarExtractor) isPlaceholder(path string) bool { } func idOf(info fs.FileInfo) fileID { - sys, ok := info.Sys().(*unix.Stat_t) + // os reports syscall.Stat_t, a different type from unix.Stat_t. + sys, ok := info.Sys().(*syscall.Stat_t) if !ok { return fileID{} } - return fileID{dev: sys.Dev, ino: sys.Ino} + return fileID{dev: uint64(sys.Dev), ino: sys.Ino} //nolint:unconvert // Dev is uint32 on some architectures } func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bool) error { diff --git a/client/tar_pax_linux.go b/client/tar_pax_linux.go new file mode 100644 index 00000000..8ea2bb4e --- /dev/null +++ b/client/tar_pax_linux.go @@ -0,0 +1,78 @@ +package client + +import ( + "archive/tar" + "strconv" + "strings" + "time" + + "github.com/alecthomas/errors" +) + +func checkGlobalPAX(records map[string]string) error { + // These change where member data ends, which archive/tar has already decided from the member's own header. + for key := range records { + if key == "size" || strings.HasPrefix(key, "GNU.sparse.") { + return errors.Errorf("unsupported %q record in a PAX global header", key) + } + } + return nil +} + +// applyGlobalPAX applies the records of the last PAX global header to hdr, as GNU tar does. +// +// archive/tar returns global headers without merging them into later members, and a member's own records win. +func applyGlobalPAX(hdr *tar.Header, records map[string]string) error { + for key, value := range records { + if _, ok := hdr.PAXRecords[key]; ok { + continue + } + var err error + switch key { + case "path": + hdr.Name = value + case "linkpath": + hdr.Linkname = value + case "uname": + hdr.Uname = value + case "gname": + hdr.Gname = value + case "uid": + hdr.Uid, err = parsePAXID(value) + case "gid": + hdr.Gid, err = parsePAXID(value) + case "mtime": + hdr.ModTime, err = parsePAXTime(value) + } + if err != nil { + return errors.Wrapf(err, "%s: invalid %q record in a PAX global header", hdr.Name, key) + } + } + return nil +} + +func parsePAXID(value string) (int, error) { + // GNU tar accepts any uid_t, which is 32 bits on Linux; int is narrower on 32-bit platforms. + id, err := strconv.ParseUint(value, 10, min(32, strconv.IntSize-1)) + return int(id), errors.WithStack(err) +} + +func parsePAXTime(value string) (time.Time, error) { + // Same format as archive/tar's unexported parser: decimal seconds with an optional fraction. + secs, frac, _ := strings.Cut(value, ".") + s, err := strconv.ParseInt(secs, 10, 64) + if err != nil { + return time.Time{}, errors.WithStack(err) + } + if frac == "" { + return time.Unix(s, 0), nil + } + if strings.Trim(frac, "0123456789") != "" { + return time.Time{}, errors.Errorf("invalid fraction %q", frac) + } + ns, _ := strconv.ParseInt((frac + "000000000")[:9], 10, 64) //nolint:errcheck // digits only + if strings.HasPrefix(secs, "-") { + ns = -ns + } + return time.Unix(s, ns), nil +} From ff04f9c9523debb91dc4c8b29e3634c79d77780e Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 06:34:03 +0000 Subject: [PATCH 03/11] fix(client): resolve archive owner names through NSS Release binaries are built with CGO_ENABLED=0, where os/user only reads /etc/passwd and /etc/group. GNU tar resolves names with getpwnam, so as root it maps LDAP or SSSD names that os/user misses. Look names up with getent first, which queries NSS, and fall back to os/user when it is unavailable. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/tar_extractor_linux.go | 28 +++++++++++++++++++++++++ client/tar_owner_internal_test.go | 34 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 client/tar_owner_internal_test.go diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index a4c03634..3e12c7db 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -6,6 +6,7 @@ import ( "io" "io/fs" "os" + "os/exec" "os/user" "path/filepath" "slices" @@ -745,6 +746,9 @@ func cachedID(cache map[string]int, name string, numeric int, lookup func(string } func userID(name string) (int, error) { + if id, ok := nssID("passwd", name); ok { + return id, nil + } u, err := user.Lookup(name) if err != nil { return 0, errors.WithStack(err) @@ -754,6 +758,9 @@ func userID(name string) (int, error) { } func groupID(name string) (int, error) { + if id, ok := nssID("group", name); ok { + return id, nil + } g, err := user.LookupGroup(name) if err != nil { return 0, errors.WithStack(err) @@ -762,6 +769,27 @@ func groupID(name string) (int, error) { return id, errors.WithStack(err) } +func nssID(database, name string) (int, bool) { + // GNU tar resolves names through NSS, as getent does; os/user without cgo only reads /etc/passwd and /etc/group. + // + // A leading "-" would be parsed as a getent option. + if strings.HasPrefix(name, "-") { + return 0, false + } + out, err := exec.Command("getent", database, name).Output() //nolint:gosec,noctx // fixed binary, name is one argument + if err != nil { + return 0, false + } + line, _, _ := strings.Cut(string(out), "\n") + fields := strings.Split(line, ":") + // getent also accepts a numeric ID as the key, which getpwnam doesn't. + if len(fields) < 3 || fields[0] != name { + return 0, false + } + id, err := strconv.Atoi(fields[2]) + return id, err == nil +} + func isUnsafeLinkTarget(target string) bool { // GNU tar defers symlinks whose target is absolute or has a ".." component. return strings.HasPrefix(target, "/") || containsDotDot(target) diff --git a/client/tar_owner_internal_test.go b/client/tar_owner_internal_test.go new file mode 100644 index 00000000..f9c251ee --- /dev/null +++ b/client/tar_owner_internal_test.go @@ -0,0 +1,34 @@ +//go:build linux + +package client + +import ( + "os" + "path/filepath" + "testing" + + "github.com/alecthomas/assert/v2" +) + +func TestOwnerLookupUsesNSS(t *testing.T) { + bin := t.TempDir() + getent := `#!/bin/sh +case "$1 $2" in +"passwd directory-user") echo "directory-user:*:4242:4242::/home/directory-user:/bin/sh" ;; +"group directory-group") echo "directory-group:*:4343:" ;; +"passwd 0") echo "root:x:0:0:root:/root:/bin/sh" ;; +*) exit 2 ;; +esac +` + assert.NoError(t, os.WriteFile(filepath.Join(bin, "getent"), []byte(getent), 0o755)) + t.Setenv("PATH", bin) + + uid, err := userID("directory-user") + assert.NoError(t, err) + assert.Equal(t, 4242, uid) + gid, err := groupID("directory-group") + assert.NoError(t, err) + assert.Equal(t, 4343, gid) + _, err = userID("0") + assert.Error(t, err) +} From 8a7a55f1822991c48e965e929d66671803a24fc3 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 07:05:07 +0000 Subject: [PATCH 04/11] fix(client): match GNU tar for trailing-dot names, long paths and cancelled lookups A directory member named "d/." kept that name on the directory stack, so the next entry "d/file" looked like it was outside it. A read-only "d" got its mode before the file was created and the restore failed, and a writable one lost its archived mtime. The trailing "/." is now stripped, as GNU tar ends up doing, and an unlisted parent skips its final chmod when it was created with the archived mode, since GNU tar compares against the mode it cached at creation. Paths were passed to the kernel as destination + member name, so a member whose name fits in PATH_MAX failed under a long destination. All filesystem calls now go through a descriptor for the destination with the *at syscalls, as GNU tar does after -C. getent lookups ran without the Extract context, so a cancelled restore still waited on a slow NSS backend. They now use exec.CommandContext and stop before the os/user fallback. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 119 +++++++++++----- client/tar_delayed_linux.go | 51 +++---- client/tar_dest_linux.go | 128 +++++++++++++++++ client/tar_extractor_linux.go | 228 ++++++++++++++++-------------- client/tar_owner_internal_test.go | 35 +++-- 5 files changed, 384 insertions(+), 177 deletions(-) create mode 100644 client/tar_dest_linux.go diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 7902e1f8..d4d22de6 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -15,6 +15,7 @@ import ( "time" "github.com/alecthomas/assert/v2" + "github.com/alecthomas/errors" "github.com/block/cachew/client" ) @@ -184,6 +185,23 @@ func TestExtractMatchesGNUTar(t *testing.T) { directory("alias/written/", 0o700), regular("real/written/file", 0o644, "x"), }}, + {name: "TrailingDot", entries: []tarEntry{ + directory("created/./", 0o555), + regular("created/file", 0o644, "x"), + directory("nested/created/././", 0o555), + regular("nested/created/file", 0o644, "x"), + regular("existing/before", 0o644, "x"), + directory("existing/./", 0o700), + regular("existing/after", 0o644, "x"), + regular("aliased/before", 0o644, "x"), + directory("./aliased/", 0o700), + regular("aliased/after", 0o644, "x"), + }}, + {name: "TrailingDotOverDirectory", entries: []tarEntry{ + directory("d/", 0o755), + directory("d/./", 0o555), + regular("d/file", 0o644, "x"), + }}, {name: "RevisitReadOnly", entries: []tarEntry{ directory("readonly/", 0o555), regular("elsewhere", 0o644, "x"), @@ -226,6 +244,34 @@ func TestExtractMatchesGNUTar(t *testing.T) { } } +func TestExtractLongMemberNames(t *testing.T) { + if out, err := exec.Command("tar", "--version").Output(); err != nil || !bytes.Contains(out, []byte("GNU tar")) { + t.Skip("GNU tar is not installed") + } + // Each name fits in PATH_MAX but not once joined to the destination, which GNU tar resolves names against. + deep := strings.TrimSuffix(strings.Repeat(strings.Repeat("d", 200)+"/", 20), "/") + archive := buildTar(t, []tarEntry{ + directory(deep+"/", 0o750), + regular(deep+"/file", 0o640, "x"), + regular(deep+"/replaced", 0o644, "x"), + regular(deep+"/replaced", 0o600, "y"), + symlink(deep+"/link", "file"), + hardlink(deep+"/hard", deep+"/file"), + symlink(deep+"/absolute", "/elsewhere"), + }) + prefix := strings.Repeat("p", 200) + gnuDir, goDir := filepath.Join(t.TempDir(), prefix), filepath.Join(t.TempDir(), prefix) + assert.NoError(t, os.Mkdir(gnuDir, 0o755)) + assert.NoError(t, os.Mkdir(goDir, 0o755)) + + gnuTar := exec.Command("tar", "-xpf", "-", "-C", gnuDir) + gnuTar.Stdin = bytes.NewReader(archive) + out, err := gnuTar.CombinedOutput() + assert.NoError(t, err, "%s", out) + assert.NoError(t, client.Extract(t.Context(), bytes.NewReader(zstdCompress(t, archive)), goDir, 0)) + assert.Equal(t, treeState(t, gnuDir), treeState(t, goDir)) +} + func TestExtractRejectsGlobalDataLayoutRecords(t *testing.T) { // GNU tar reads member data using these, but archive/tar has already sized the member from its own header. for _, key := range []string{"size", "GNU.sparse.realsize"} { @@ -367,43 +413,44 @@ func zstdCompress(t *testing.T, data []byte) []byte { return out } -// treeState describes every path under root; only archived mtimes are comparable, the rest are extraction times. -func treeState(t *testing.T, root string) map[string]string { //nolint:privatedoc // explains why +// treeState describes every path under dir; only archived mtimes are comparable, the rest are extraction times. +// +// It resolves paths through an os.Root, so trees deeper than PATH_MAX can be compared. +func treeState(t *testing.T, dir string) map[string]string { //nolint:privatedoc // explains why t.Helper() - state := map[string]string{} - err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - info, err := d.Info() - if err != nil { - return err - } - rel, err := filepath.Rel(root, path) - if err != nil { - return err - } - desc := fmt.Sprintf("%v nlink=%d", info.Mode(), info.Sys().(*syscall.Stat_t).Nlink) //nolint:forcetypeassert - if !info.ModTime().After(archiveTime()) { - desc += " mtime=" + info.ModTime().Format(time.RFC3339Nano) - } - switch { - case info.Mode()&fs.ModeSymlink != 0: - target, err := os.Readlink(path) - if err != nil { - return err - } - desc += " -> " + target - case info.Mode().IsRegular(): - data, err := os.ReadFile(path) - if err != nil { - return err - } - desc += fmt.Sprintf(" sha256=%x", sha256.Sum256(data)) - } - state[rel] = desc - return nil - }) + root, err := os.OpenRoot(dir) assert.NoError(t, err) + defer root.Close() + state := map[string]string{} + describeTree(t, root, ".", state) return state } + +func describeTree(t *testing.T, root *os.Root, name string, state map[string]string) { + t.Helper() + info, err := root.Lstat(name) + assert.NoError(t, err) + desc := fmt.Sprintf("%v nlink=%d", info.Mode(), info.Sys().(*syscall.Stat_t).Nlink) //nolint:forcetypeassert + if !info.ModTime().After(archiveTime()) { + desc += " mtime=" + info.ModTime().Format(time.RFC3339Nano) + } + switch { + case info.Mode()&fs.ModeSymlink != 0: + target, err := root.Readlink(name) + assert.NoError(t, err) + desc += " -> " + target + case info.Mode().IsRegular(): + data, err := root.ReadFile(name) + assert.NoError(t, err) + desc += fmt.Sprintf(" sha256=%x", sha256.Sum256(data)) + case info.IsDir(): + f, err := root.Open(name) + assert.NoError(t, err) + children, err := f.Readdirnames(-1) + assert.NoError(t, errors.Join(err, f.Close())) + for _, child := range children { + describeTree(t, root, filepath.Join(name, child), state) + } + } + state[name] = desc +} diff --git a/client/tar_delayed_linux.go b/client/tar_delayed_linux.go index 4f0c0800..1ca66891 100644 --- a/client/tar_delayed_linux.go +++ b/client/tar_delayed_linux.go @@ -1,12 +1,10 @@ package client import ( - "os" "path/filepath" "strings" "github.com/alecthomas/errors" - "golang.org/x/sys/unix" ) // pendingDir is directory metadata that GNU tar applies once it stops extracting into the directory. @@ -40,10 +38,11 @@ type dirStack struct { finishedPaths map[string]struct{} // finishedViaLink is set when a finished directory may be reached through a path finishedPaths doesn't hold. finishedViaLink bool + dest *destDir } -func newDirStack() dirStack { - return dirStack{byName: map[string]*pendingDir{}, finishedPaths: map[string]struct{}{}} +func newDirStack(dest *destDir) dirStack { + return dirStack{byName: map[string]*pendingDir{}, finishedPaths: map[string]struct{}{}, dest: dest} } func (s *dirStack) push(dir pendingDir) error { @@ -52,11 +51,11 @@ func (s *dirStack) push(dir pendingDir) error { if ok { dir.afterLinks, dir.id = existing.afterLinks, existing.id if existing.interdir && existing.afterLinks { - info, err := os.Lstat(dir.path) + st, err := s.dest.lstat(dir.path) if err != nil { - return errors.WithStack(err) + return err } - dir.id = idOf(info) + dir.id = statID(st) } *existing = dir } else { @@ -115,11 +114,11 @@ func (s *dirStack) markAfterLinks(i int) error { for ; i >= 0 && !s.pending[i].afterLinks; i-- { dir := s.pending[i] dir.afterLinks = true - info, err := os.Lstat(dir.path) + st, err := s.dest.lstat(dir.path) if err != nil { - return errors.WithStack(err) + return err } - dir.id = idOf(info) + dir.id = statID(st) } return nil } @@ -196,25 +195,29 @@ func (e *tarExtractor) finish() error { func (e *tarExtractor) applyDir(dir *pendingDir, verify bool) error { if verify { - info, err := os.Lstat(dir.path) + st, err := e.dest.lstat(dir.path) if err != nil { - return errors.WithStack(err) + return err } - if idOf(info) != dir.id { + if statID(st) != dir.id { return errors.Errorf("%s: directory renamed before its status could be extracted", dir.path) } } if dir.interdir { - var st unix.Stat_t - if err := unix.Lstat(dir.path, &st); err != nil { - return errors.Wrapf(err, "failed to stat %s", dir.path) + if dir.wasCreated && dir.created == dir.stat.mode { + // GNU tar compares against the mode it made the directory with, so a chmod through another name stays. + return nil + } + st, err := e.dest.lstat(dir.path) + if err != nil { + return err } // Only permission bits are restored, keeping any set-group-ID bit inherited from the parent. mode := st.Mode&0o7000 | dir.stat.mode if mode == st.Mode&0o7777 { return nil } - return errors.Wrapf(unix.Chmod(dir.path, mode), "failed to chmod %s", dir.path) + return e.dest.chmod(dir.path, mode) } keepMode := !verify && dir.wasCreated && dir.created == dir.stat.mode return e.setPathStat(dir.path, dir.stat, keepMode) @@ -226,22 +229,22 @@ func (e *tarExtractor) applyDelayedLinks() error { if link.replaced { continue } - info, err := os.Lstat(link.path) - if err != nil || idOf(info) != link.id { + st, err := e.dest.lstat(link.path) + if err != nil || statID(st) != link.id { // An entry reached the placeholder through another path and replaced it. continue } - if err := removeEntry(link.path); err != nil { + if err := e.removeEntry(link.path); err != nil { return err } if !link.symlink { - if err := os.Link(link.target, link.path); err != nil { - return errors.Wrapf(err, "failed to link %s to %s", link.path, link.target) + if err := e.dest.link(link.target, link.path); err != nil { + return err } continue } - if err := os.Symlink(link.target, link.path); err != nil { - return errors.Wrapf(err, "failed to create symlink %s", link.path) + if err := e.dest.symlink(link.target, link.path); err != nil { + return err } if err := e.setPathStat(link.path, link.stat, true); err != nil { return err diff --git a/client/tar_dest_linux.go b/client/tar_dest_linux.go new file mode 100644 index 00000000..13eece05 --- /dev/null +++ b/client/tar_dest_linux.go @@ -0,0 +1,128 @@ +package client + +import ( + "os" + "strings" + + "github.com/alecthomas/errors" + "golang.org/x/sys/unix" +) + +// destDir resolves extraction paths against an open descriptor for the destination, as GNU tar does after -C. +// +// Only the member name then counts towards PATH_MAX, so a long destination path doesn't make deep members fail. +type destDir struct { + fd int + path string +} + +func (d *destDir) open() error { + // Like tar -C, a destination that is a symlink is followed. + fd, err := unix.Open(d.path, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return errors.Wrapf(err, "failed to open %s", d.path) + } + d.fd = fd + return nil +} + +func (d *destDir) close() error { + return errors.Wrapf(unix.Close(d.fd), "failed to close %s", d.path) +} + +func (d *destDir) rel(path string) string { + // Callers build paths by joining member names onto the destination; anything else stays absolute. + if path == d.path { + return "." + } + prefix := strings.TrimSuffix(d.path, "/") + "/" + if rel, ok := strings.CutPrefix(path, prefix); ok && rel != "" { + return rel + } + return path +} + +func (d *destDir) lstat(path string) (unix.Stat_t, error) { + var st unix.Stat_t + err := unix.Fstatat(d.fd, d.rel(path), &st, unix.AT_SYMLINK_NOFOLLOW) + return st, errors.Wrapf(err, "failed to stat %s", path) +} + +func (d *destDir) stat(path string) (unix.Stat_t, error) { + var st unix.Stat_t + err := unix.Fstatat(d.fd, d.rel(path), &st, 0) + return st, errors.Wrapf(err, "failed to stat %s", path) +} + +func (d *destDir) mkdir(path string, mode uint32) error { + return errors.Wrapf(unix.Mkdirat(d.fd, d.rel(path), mode), "failed to create directory %s", path) +} + +func (d *destDir) chmod(path string, mode uint32) error { + return errors.Wrapf(unix.Fchmodat(d.fd, d.rel(path), mode, 0), "failed to chmod %s", path) +} + +func (d *destDir) lchown(path string, uid, gid int) error { + err := unix.Fchownat(d.fd, d.rel(path), uid, gid, unix.AT_SYMLINK_NOFOLLOW) + return errors.Wrapf(err, "failed to chown %s", path) +} + +func (d *destDir) setTimes(path string, times []unix.Timespec) error { + err := unix.UtimesNanoAt(d.fd, d.rel(path), times, unix.AT_SYMLINK_NOFOLLOW) + return errors.Wrapf(err, "failed to set times on %s", path) +} + +func (d *destDir) create(path string, perm uint32) (*os.File, error) { + for { + fd, err := unix.Openat(d.fd, d.rel(path), unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC, perm) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + return nil, errors.Wrapf(err, "failed to create %s", path) + } + return os.NewFile(uintptr(fd), path), nil + } +} + +func (d *destDir) symlink(target, path string) error { + return errors.Wrapf(unix.Symlinkat(target, d.fd, d.rel(path)), "failed to create symlink %s", path) +} + +func (d *destDir) link(source, path string) error { + err := unix.Linkat(d.fd, d.rel(source), d.fd, d.rel(path), 0) + return errors.Wrapf(err, "failed to link %s to %s", path, source) +} + +func (d *destDir) mknod(path string, mode uint32, dev int) error { + return errors.Wrapf(unix.Mknodat(d.fd, d.rel(path), mode, dev), "failed to create %s", path) +} + +func (d *destDir) remove(path string) error { + // As os.Remove: rmdir(file) fails with ENOTDIR, which shows that unlink's error is the one to report. + rel := d.rel(path) + err := unix.Unlinkat(d.fd, rel, 0) + if err == nil { + return nil + } + rmdirErr := unix.Unlinkat(d.fd, rel, unix.AT_REMOVEDIR) + if rmdirErr == nil { + return nil + } + if !errors.Is(rmdirErr, unix.ENOTDIR) { + err = rmdirErr + } + return errors.Wrapf(err, "failed to remove %s", path) +} + +func isDirStat(st unix.Stat_t) bool { + return st.Mode&unix.S_IFMT == unix.S_IFDIR +} + +func isSymlinkStat(st unix.Stat_t) bool { + return st.Mode&unix.S_IFMT == unix.S_IFLNK +} + +func statID(st unix.Stat_t) fileID { + return fileID{dev: uint64(st.Dev), ino: st.Ino} //nolint:unconvert // Dev is uint32 on some architectures +} diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 3e12c7db..ceb58b0f 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -13,7 +13,6 @@ import ( "strconv" "strings" "sync" - "syscall" "github.com/alecthomas/errors" "golang.org/x/sync/semaphore" @@ -80,6 +79,7 @@ type delayedLink struct { // goroutine. Before an entry touches a path it waits for any pending write to it, so entries apply in archive order. type tarExtractor struct { root string + dest *destDir asRoot bool umask int numWriters int @@ -108,8 +108,10 @@ type tarExtractor struct { func newTarExtractor(root string, writers int) *tarExtractor { root = filepath.Clean(root) + dest := &destDir{fd: -1, path: root} return &tarExtractor{ root: root, + dest: dest, asRoot: os.Geteuid() == 0, umask: processUmask(), numWriters: writers, @@ -119,7 +121,7 @@ func newTarExtractor(root string, writers int) *tarExtractor { failed: make(chan struct{}), inFlight: map[string]chan struct{}{}, dirs: map[string]struct{}{root: {}}, - dirStack: newDirStack(), + dirStack: newDirStack(dest), delayedAt: map[string]int{}, placeholders: map[fileID]struct{}{}, users: map[string]int{}, @@ -146,7 +148,11 @@ func processUmask() int { return 0o777 } -func (e *tarExtractor) extract(ctx context.Context, r io.Reader) error { +func (e *tarExtractor) extract(ctx context.Context, r io.Reader) (err error) { + if err := e.dest.open(); err != nil { + return err + } + defer func() { err = errors.Join(err, e.dest.close()) }() var writers sync.WaitGroup for range e.numWriters { writers.Go(e.runWriter) @@ -170,7 +176,7 @@ func (e *tarExtractor) runWriter() { select { case <-e.failed: default: - err := writeFile(job.target, job.stat, e.asRoot, removeEntry, func(f *os.File) error { + err := e.writeFile(job.target, job.stat, e.removeEntry, func(f *os.File) error { _, err := f.Write(job.data) return errors.WithStack(err) }) @@ -267,7 +273,7 @@ func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Heade if !isDir { return errors.Errorf("%s: cannot replace the target directory", hdr.Name) } - return e.recordDir(name, target, hdr, false, nil) + return e.recordDir(ctx, name, target, hdr, false, nil) } claimed, hadPlaceholder := e.claim(target, isDir) viaLink, err := e.ensureParent(name, target) @@ -303,13 +309,13 @@ func (e *tarExtractor) apply( ) error { switch { case isDirEntry(hdr): - return e.dir(name, target, hdr, viaLink) + return e.dir(ctx, name, target, hdr, viaLink) case hdr.Typeflag == tar.TypeSymlink: - return e.symlink(name, target, hdr, viaLink) + return e.symlink(ctx, name, target, hdr, viaLink) case hdr.Typeflag == tar.TypeLink: return e.hardlink(name, target, hdr, viaLink) case hdr.Typeflag == tar.TypeChar, hdr.Typeflag == tar.TypeBlock, hdr.Typeflag == tar.TypeFifo: - return e.node(target, hdr, viaLink) + return e.node(ctx, target, hdr, viaLink) default: // GNU tar extracts regular, contiguous, sparse and unknown entry types as regular files. return e.regular(ctx, tr, hdr, target, viaLink) @@ -417,16 +423,15 @@ func (e *tarExtractor) ensureParent(name, target string) (bool, error) { return false, err } e.wait(parent) - info, err := os.Lstat(parent) + st, err := e.dest.lstat(parent) switch { case errors.Is(err, fs.ErrNotExist): err = e.mkdirParent(name, parent, viaLink) case err != nil: - err = errors.WithStack(err) - case info.IsDir(): - case info.Mode()&fs.ModeSymlink != 0: + case isDirStat(st): + case isSymlinkStat(st): viaLink = true - err = requireDir(parent) + err = e.requireDir(parent) default: err = errors.Errorf("%s: not a directory", parent) } @@ -439,12 +444,12 @@ func (e *tarExtractor) ensureParent(name, target string) (bool, error) { return viaLink, nil } -func requireDir(path string) error { - info, err := os.Stat(path) +func (e *tarExtractor) requireDir(path string) error { + st, err := e.dest.stat(path) if err != nil { - return errors.WithStack(err) + return err } - if !info.IsDir() { + if !isDirStat(st) { return errors.Errorf("%s: not a directory", path) } return nil @@ -452,25 +457,30 @@ func requireDir(path string) error { func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { // GNU tar gives unlisted parents the umask's mode, owner-writable and searchable until extraction finishes. - if err := os.Mkdir(path, 0o777); err != nil { - return errors.WithStack(err) + if err := e.dest.mkdir(path, 0o777); err != nil { + return err } - var st unix.Stat_t - if err := unix.Lstat(path, &st); err != nil { - return errors.Wrapf(err, "failed to stat %s", path) + st, err := e.dest.lstat(path) + if err != nil { + return err } - desired := st.Mode & 0o777 - if !e.asRoot && desired&0o300 != 0o300 { - if err := unix.Chmod(path, st.Mode&0o7777|0o300); err != nil { - return errors.Wrapf(err, "failed to chmod %s", path) + desired, created := st.Mode&0o777, st.Mode&0o777 + if !e.asRoot { + created |= 0o300 + } + if created != desired { + if err := e.dest.chmod(path, st.Mode&0o7000|created); err != nil { + return err } } return e.dirStack.push(pendingDir{ - name: e.parentName(name, path), - path: path, - stat: entryStat{mode: desired}, - interdir: true, - viaLink: viaLink, + name: e.parentName(name, path), + path: path, + stat: entryStat{mode: desired}, + interdir: true, + created: created, + wasCreated: true, + viaLink: viaLink, }) } @@ -488,24 +498,28 @@ func (e *tarExtractor) parentName(name, path string) string { return rel } -func (e *tarExtractor) dir(name, target string, hdr *tar.Header, viaLink bool) error { +func (e *tarExtractor) dir(ctx context.Context, name, target string, hdr *tar.Header, viaLink bool) error { // Like GNU tar, keep an existing directory but replace anything else, even a symlink to a directory. - info, err := os.Lstat(target) + st, err := e.dest.lstat(target) switch { - case err == nil && info.IsDir(): - return e.recordDir(name, target, hdr, viaLink, nil) + case err == nil && isDirStat(st): + return e.recordDir(ctx, name, target, hdr, viaLink, nil) case err == nil: if err := e.removeExisting(target, viaLink); err != nil { return err } case !errors.Is(err, fs.ErrNotExist): - return errors.WithStack(err) + return err } created, err := e.mkdir(target, hdr) if err != nil { return err } - return e.recordDir(name, target, hdr, viaLink, &created) + // GNU tar's mkdir of "d/." fails, so it creates "d" as a parent and moves this entry's metadata onto it. + for strings.HasSuffix(name, "/.") { + name = strings.TrimSuffix(name, "/.") + } + return e.recordDir(ctx, name, target, hdr, viaLink, &created) } func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { @@ -514,18 +528,20 @@ func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { if !e.asRoot { mode |= 0o300 } - if err := unix.Mkdir(target, mode); err != nil { - return 0, errors.Wrapf(err, "failed to create directory %s", target) + if err := e.dest.mkdir(target, mode); err != nil { + return 0, err } // GNU tar clears the umask for -p; this process can't, so undo it where it would affect the owner. if e.umask&int(mode) != 0 { - return mode, errors.Wrapf(unix.Chmod(target, mode), "failed to chmod %s", target) + return mode, e.dest.chmod(target, mode) } return mode, nil } -func (e *tarExtractor) recordDir(name, target string, hdr *tar.Header, viaLink bool, created *uint32) error { - stat, err := e.stat(hdr) +func (e *tarExtractor) recordDir( + ctx context.Context, name, target string, hdr *tar.Header, viaLink bool, created *uint32, +) error { + stat, err := e.stat(ctx, hdr) if err != nil { return err } @@ -540,7 +556,7 @@ func (e *tarExtractor) recordDir(name, target string, hdr *tar.Header, viaLink b } func (e *tarExtractor) removeExisting(path string, viaLink bool) error { - if info, err := os.Lstat(path); err == nil && info.IsDir() { + if st, err := e.dest.lstat(path); err == nil && isDirStat(st) { // Queued writes may still be filling the directory, which GNU tar would find non-empty. e.waitAll() if viaLink { @@ -548,11 +564,11 @@ func (e *tarExtractor) removeExisting(path string, viaLink bool) error { e.dirs = map[string]struct{}{e.root: {}} } } - return removeEntry(path) + return e.removeEntry(path) } -func removeEntry(path string) error { - return errors.Wrapf(os.Remove(path), "failed to replace %s", path) +func (e *tarExtractor) removeEntry(path string) error { + return errors.Wrapf(e.dest.remove(path), "failed to replace %s", path) } func createReplacing(path string, remove func(string) error, create func() error) error { @@ -570,7 +586,7 @@ func createReplacing(path string, remove func(string) error, create func() error func (e *tarExtractor) regular( ctx context.Context, tr *tar.Reader, hdr *tar.Header, target string, viaLink bool, ) error { - stat, err := e.stat(hdr) + stat, err := e.stat(ctx, hdr) if err != nil { return err } @@ -578,7 +594,7 @@ func (e *tarExtractor) regular( case viaLink: // Written before the next entry, since a later path may alias this one. remove := func(path string) error { return e.removeExisting(path, viaLink) } - return writeFile(target, stat, e.asRoot, remove, func(f *os.File) error { + return e.writeFile(target, stat, remove, func(f *os.File) error { // Hiding ReadFrom keeps io.CopyBuffer on the large buffer instead of os.File's 32 KiB copy loop. _, err := io.CopyBuffer(struct{ io.Writer }{f}, tr, e.copyBuf) return errors.Wrapf(err, "failed to write %s", target) @@ -608,7 +624,7 @@ func (e *tarExtractor) stream(ctx context.Context, tr *tar.Reader, hdr *tar.Head e.inFlight[target] = done e.streams.Go(func() { defer close(done) - err := writeFile(target, stat, e.asRoot, removeEntry, func(f *os.File) error { + err := e.writeFile(target, stat, e.removeEntry, func(f *os.File) error { for chunk := range chunks { _, err := f.Write(chunk) e.releaseChunk(chunk) @@ -659,31 +675,31 @@ func (e *tarExtractor) releaseChunk(chunk []byte) { } } -func writeFile( - target string, stat entryStat, asRoot bool, remove func(string) error, write func(*os.File) error, +func (e *tarExtractor) writeFile( + target string, stat entryStat, remove func(string) error, write func(*os.File) error, ) error { var f *os.File err := createReplacing(target, remove, func() error { var err error - f, err = os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) - return errors.WithStack(err) + f, err = e.dest.create(target, 0o600) + return err }) if err != nil { - return errors.Wrapf(err, "failed to create %s", target) + return err } err = write(f) if err == nil { - err = setFileStat(f, stat, asRoot) + err = e.setFileStat(f, target, stat) } return errors.Join(err, errors.Wrapf(f.Close(), "failed to close %s", target)) } -func setFileStat(f *os.File, stat entryStat, asRoot bool) error { +func (e *tarExtractor) setFileStat(f *os.File, target string, stat entryStat) error { // Mode goes last, as in GNU tar, because chown can clear set-ID bits. - if err := setMtime(f.Name(), stat); err != nil { + if err := e.setMtime(target, stat); err != nil { return err } - if asRoot { + if e.asRoot { if err := f.Chown(stat.uid, stat.gid); err != nil { return errors.WithStack(err) } @@ -692,41 +708,41 @@ func setFileStat(f *os.File, stat entryStat, asRoot bool) error { } func (e *tarExtractor) setPathStat(path string, stat entryStat, keepMode bool) error { - if err := setMtime(path, stat); err != nil { + if err := e.setMtime(path, stat); err != nil { return err } if e.asRoot { - if err := os.Lchown(path, stat.uid, stat.gid); err != nil { - return errors.WithStack(err) + if err := e.dest.lchown(path, stat.uid, stat.gid); err != nil { + return err } } if keepMode { return nil } - return errors.Wrapf(unix.Chmod(path, stat.mode), "failed to chmod %s", path) + return e.dest.chmod(path, stat.mode) } -func setMtime(path string, stat entryStat) error { +func (e *tarExtractor) setMtime(path string, stat entryStat) error { // GNU tar leaves atime alone outside incremental mode. - times := []unix.Timespec{{Nsec: unix.UTIME_OMIT}, stat.mtime} - err := unix.UtimesNanoAt(unix.AT_FDCWD, path, times, unix.AT_SYMLINK_NOFOLLOW) - return errors.Wrapf(err, "failed to set times on %s", path) + return e.dest.setTimes(path, []unix.Timespec{{Nsec: unix.UTIME_OMIT}, stat.mtime}) } -func (e *tarExtractor) stat(hdr *tar.Header) (entryStat, error) { +func (e *tarExtractor) stat(ctx context.Context, hdr *tar.Header) (entryStat, error) { mtime, err := unix.TimeToTimespec(hdr.ModTime) if err != nil { return entryStat{}, errors.Wrapf(err, "%s: unsupported modification time", hdr.Name) } stat := entryStat{mode: uint32(hdr.Mode) & 0o7777, mtime: mtime} //nolint:gosec // mode bits only if e.asRoot { - stat.uid = cachedID(e.users, hdr.Uname, hdr.Uid, userID) - stat.gid = cachedID(e.groups, hdr.Gname, hdr.Gid, groupID) + stat.uid = cachedID(ctx, e.users, hdr.Uname, hdr.Uid, userID) + stat.gid = cachedID(ctx, e.groups, hdr.Gname, hdr.Gid, groupID) } return stat, nil } -func cachedID(cache map[string]int, name string, numeric int, lookup func(string) (int, error)) int { +func cachedID( + ctx context.Context, cache map[string]int, name string, numeric int, lookup func(context.Context, string) (int, error), +) int { // GNU tar prefers the archived owner name and falls back to the numeric ID when the name is unknown. if name == "" { return numeric @@ -734,7 +750,7 @@ func cachedID(cache map[string]int, name string, numeric int, lookup func(string id, ok := cache[name] if !ok { var err error - if id, err = lookup(name); err != nil { + if id, err = lookup(ctx, name); err != nil { id = -1 } cache[name] = id @@ -745,10 +761,13 @@ func cachedID(cache map[string]int, name string, numeric int, lookup func(string return id } -func userID(name string) (int, error) { - if id, ok := nssID("passwd", name); ok { +func userID(ctx context.Context, name string) (int, error) { + if id, ok := nssID(ctx, "passwd", name); ok { return id, nil } + if err := ctx.Err(); err != nil { + return 0, errors.WithStack(err) + } u, err := user.Lookup(name) if err != nil { return 0, errors.WithStack(err) @@ -757,10 +776,13 @@ func userID(name string) (int, error) { return id, errors.WithStack(err) } -func groupID(name string) (int, error) { - if id, ok := nssID("group", name); ok { +func groupID(ctx context.Context, name string) (int, error) { + if id, ok := nssID(ctx, "group", name); ok { return id, nil } + if err := ctx.Err(); err != nil { + return 0, errors.WithStack(err) + } g, err := user.LookupGroup(name) if err != nil { return 0, errors.WithStack(err) @@ -769,14 +791,14 @@ func groupID(name string) (int, error) { return id, errors.WithStack(err) } -func nssID(database, name string) (int, bool) { +func nssID(ctx context.Context, database, name string) (int, bool) { // GNU tar resolves names through NSS, as getent does; os/user without cgo only reads /etc/passwd and /etc/group. // // A leading "-" would be parsed as a getent option. if strings.HasPrefix(name, "-") { return 0, false } - out, err := exec.Command("getent", database, name).Output() //nolint:gosec,noctx // fixed binary, name is one argument + out, err := exec.CommandContext(ctx, "getent", database, name).Output() //nolint:gosec // name is a single argument if err != nil { return 0, false } @@ -795,8 +817,8 @@ func isUnsafeLinkTarget(target string) bool { return strings.HasPrefix(target, "/") || containsDotDot(target) } -func (e *tarExtractor) symlink(name, target string, hdr *tar.Header, viaLink bool) error { - stat, err := e.stat(hdr) +func (e *tarExtractor) symlink(ctx context.Context, name, target string, hdr *tar.Header, viaLink bool) error { + stat, err := e.stat(ctx, hdr) if err != nil { return err } @@ -804,9 +826,9 @@ func (e *tarExtractor) symlink(name, target string, hdr *tar.Header, viaLink boo return e.placeholder(name, target, delayedLink{symlink: true, target: hdr.Linkname, stat: stat}, viaLink) } remove := func(path string) error { return e.removeExisting(path, viaLink) } - err = createReplacing(target, remove, func() error { return errors.WithStack(os.Symlink(hdr.Linkname, target)) }) + err = createReplacing(target, remove, func() error { return e.dest.symlink(hdr.Linkname, target) }) if err != nil { - return errors.Wrapf(err, "failed to create symlink %s", target) + return err } return e.setPathStat(target, stat, true) } @@ -814,15 +836,16 @@ func (e *tarExtractor) symlink(name, target string, hdr *tar.Header, viaLink boo // placeholder creates the empty file GNU tar puts where a deferred link goes, and records the link. func (e *tarExtractor) placeholder(name, target string, link delayedLink, viaLink bool) error { for attempt := 0; ; attempt++ { - f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0) + f, err := e.dest.create(target, 0) if err == nil { - info, err := f.Stat() + var st unix.Stat_t + err := unix.Fstat(int(f.Fd()), &st) //nolint:gosec // fd closeErr := f.Close() if err = errors.Join(err, closeErr); err != nil { return errors.Wrapf(err, "failed to create placeholder %s", target) } link.path = target - link.id = idOf(info) + link.id = statID(st) e.delayedAt[target] = len(e.delayed) e.delayed = append(e.delayed, link) e.placeholders[link.id] = struct{}{} @@ -857,23 +880,14 @@ func (e *tarExtractor) isPlaceholder(path string) bool { if len(e.placeholders) == 0 { return false } - info, err := os.Lstat(path) + st, err := e.dest.lstat(path) if err != nil { return false } - _, ok := e.placeholders[idOf(info)] + _, ok := e.placeholders[statID(st)] return ok } -func idOf(info fs.FileInfo) fileID { - // os reports syscall.Stat_t, a different type from unix.Stat_t. - sys, ok := info.Sys().(*syscall.Stat_t) - if !ok { - return fileID{} - } - return fileID{dev: uint64(sys.Dev), ino: sys.Ino} //nolint:unconvert // Dev is uint32 on some architectures -} - func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bool) error { source := filepath.Join(e.root, saferName(hdr.Linkname)) if _, ok := e.dirs[filepath.Dir(source)]; ok { @@ -886,18 +900,18 @@ func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bo return e.placeholder(name, target, delayedLink{target: source}, viaLink) } for attempt := 0; ; attempt++ { - err := os.Link(source, target) + err := e.dest.link(source, target) if err == nil { return nil } if !errors.Is(err, fs.ErrExist) { - return errors.Wrapf(err, "failed to link %s to %s", target, source) + return err } - if source == target || sameFile(source, target) { + if source == target || e.sameFile(source, target) { return nil } if attempt > 0 { - return errors.Wrapf(err, "failed to link %s to %s", target, source) + return err } if err := e.removeExisting(target, viaLink); err != nil { return err @@ -905,17 +919,17 @@ func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bo } } -func sameFile(a, b string) bool { - ai, err := os.Lstat(a) +func (e *tarExtractor) sameFile(a, b string) bool { + as, err := e.dest.lstat(a) if err != nil { return false } - bi, err := os.Lstat(b) - return err == nil && os.SameFile(ai, bi) + bs, err := e.dest.lstat(b) + return err == nil && statID(as) == statID(bs) } -func (e *tarExtractor) node(target string, hdr *tar.Header, viaLink bool) error { - stat, err := e.stat(hdr) +func (e *tarExtractor) node(ctx context.Context, target string, hdr *tar.Header, viaLink bool) error { + stat, err := e.stat(ctx, hdr) if err != nil { return err } @@ -931,10 +945,10 @@ func (e *tarExtractor) node(target string, hdr *tar.Header, viaLink bool) error dev := unix.Mkdev(uint32(hdr.Devmajor), uint32(hdr.Devminor)) //nolint:gosec // device numbers are 32-bit remove := func(path string) error { return e.removeExisting(path, viaLink) } err = createReplacing(target, remove, func() error { - return errors.WithStack(unix.Mknod(target, kind|stat.mode&0o777, int(dev))) //nolint:gosec // Linux dev_t + return e.dest.mknod(target, kind|stat.mode&0o777, int(dev)) //nolint:gosec // Linux dev_t }) if err != nil { - return errors.Wrapf(err, "failed to create %s", target) + return err } return e.setPathStat(target, stat, false) } diff --git a/client/tar_owner_internal_test.go b/client/tar_owner_internal_test.go index f9c251ee..78a68cef 100644 --- a/client/tar_owner_internal_test.go +++ b/client/tar_owner_internal_test.go @@ -3,32 +3,47 @@ package client import ( + "context" "os" "path/filepath" "testing" + "time" "github.com/alecthomas/assert/v2" ) func TestOwnerLookupUsesNSS(t *testing.T) { - bin := t.TempDir() - getent := `#!/bin/sh -case "$1 $2" in + stubGetent(t, `case "$1 $2" in "passwd directory-user") echo "directory-user:*:4242:4242::/home/directory-user:/bin/sh" ;; "group directory-group") echo "directory-group:*:4343:" ;; "passwd 0") echo "root:x:0:0:root:/root:/bin/sh" ;; *) exit 2 ;; -esac -` - assert.NoError(t, os.WriteFile(filepath.Join(bin, "getent"), []byte(getent), 0o755)) - t.Setenv("PATH", bin) +esac`) - uid, err := userID("directory-user") + uid, err := userID(t.Context(), "directory-user") assert.NoError(t, err) assert.Equal(t, 4242, uid) - gid, err := groupID("directory-group") + gid, err := groupID(t.Context(), "directory-group") assert.NoError(t, err) assert.Equal(t, 4343, gid) - _, err = userID("0") + _, err = userID(t.Context(), "0") + assert.Error(t, err) +} + +func TestOwnerLookupStopsWhenCancelled(t *testing.T) { + stubGetent(t, "exec sleep 30") + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + + start := time.Now() + _, err := userID(ctx, "directory-user") assert.Error(t, err) + assert.True(t, time.Since(start) < 10*time.Second) +} + +func stubGetent(t *testing.T, script string) { + t.Helper() + bin := t.TempDir() + assert.NoError(t, os.WriteFile(filepath.Join(bin, "getent"), []byte("#!/bin/sh\n"+script+"\n"), 0o755)) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) } From 11246ab16722de527106c0140720e97295ee6fa6 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 07:31:28 +0000 Subject: [PATCH 05/11] fix(client): match GNU tar for terminal dots, symlinked destinations and NSS aliases Open the destination exactly as the caller passed it. Cleaning it first turned "base/link/../dest" into "base/dest", while tar -C resolves the symlink and then "..", so members landed in a different directory. Handle a member name ending in "/." the way GNU tar does. For a directory, mkdir resolves a symlink at the parent component, so a link to a directory is kept and members are written through it, while a dangling link or a file fails. Every non-directory at such a name fails, because nothing but a directory can exist there. A hard link whose target ends in "/" or "/." fails with ENOTDIR. Accept the record NSS returns for a user or group name even when it is spelled differently (an alias resolving to its canonical entry). The name check is still applied to keys getent would treat as numeric IDs, which getpwnam and getgrnam don't. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 57 +++++++++++++++++++++++++++++++ client/tar_dest_linux.go | 10 +++--- client/tar_extractor_linux.go | 40 ++++++++++++++++++---- client/tar_owner_internal_test.go | 14 ++++++++ 4 files changed, 111 insertions(+), 10 deletions(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index d4d22de6..7a1c11e4 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -202,6 +202,46 @@ func TestExtractMatchesGNUTar(t *testing.T) { directory("d/./", 0o555), regular("d/file", 0o644, "x"), }}, + {name: "TrailingDotThroughSymlink", entries: []tarEntry{ + directory("real/", 0o755), + symlink("alias", "real"), + directory("alias/./", 0o700), + regular("alias/file", 0o644, "x"), + directory("other/", 0o755), + symlink("other-alias", "other"), + directory("other-alias/././", 0o750), + regular("other/file", 0o644, "x"), + directory("untouched/", 0o755), + symlink("untouched-alias", "untouched"), + directory("untouched-alias/./", 0o711), + }}, + {name: "TrailingDotThroughSymlinkReadOnly", entries: []tarEntry{ + directory("real/", 0o755), + symlink("alias", "real"), + directory("alias/./", 0o555), + regular("alias/file", 0o644, "x"), + }}, + {name: "TrailingDotThroughDanglingSymlink", entries: []tarEntry{ + symlink("alias", "missing"), + directory("alias/./", 0o700), + }}, + {name: "TrailingDotThroughSymlinkToFile", entries: []tarEntry{ + regular("file", 0o644, "x"), + symlink("alias", "file"), + directory("alias/./", 0o700), + }}, + {name: "TrailingDotOverFile", entries: []tarEntry{regular("f", 0o644, "x"), directory("f/./", 0o700)}}, + {name: "FileAtTrailingDot", entries: []tarEntry{directory("d/", 0o755), regular("d/.", 0o644, "x")}}, + {name: "FileAtMissingTrailingDot", entries: []tarEntry{regular("m/.", 0o644, "x")}}, + {name: "SymlinkAtTrailingDot", entries: []tarEntry{symlink("m/.", "x")}}, + {name: "FifoAtTrailingDot", entries: []tarEntry{directory("d/", 0o755), typed(tar.TypeFifo, "d/.", 0o644, "")}}, + {name: "HardlinkAtTrailingDot", entries: []tarEntry{ + regular("f", 0o644, "x"), + directory("d/", 0o755), + hardlink("d/.", "f"), + }}, + {name: "HardlinkToTrailingSlash", entries: []tarEntry{regular("f", 0o644, "x"), hardlink("h", "f/")}}, + {name: "HardlinkToTrailingDot", entries: []tarEntry{regular("f", 0o644, "x"), hardlink("h", "f/.")}}, {name: "RevisitReadOnly", entries: []tarEntry{ directory("readonly/", 0o555), regular("elsewhere", 0o644, "x"), @@ -272,6 +312,23 @@ func TestExtractLongMemberNames(t *testing.T) { assert.Equal(t, treeState(t, gnuDir), treeState(t, goDir)) } +func TestExtractOpensDestinationAsGiven(t *testing.T) { + // tar -C resolves ".." after a symlink in the filesystem, where filepath.Clean would drop the symlink. + base := t.TempDir() + for _, dir := range []string{"other/child", "other/dest", "base/dest"} { + assert.NoError(t, os.MkdirAll(filepath.Join(base, dir), 0o755)) + } + assert.NoError(t, os.Symlink(filepath.Join(base, "other/child"), filepath.Join(base, "base/link"))) + + archive := zstdCompress(t, buildTar(t, []tarEntry{regular("file", 0o644, "x")})) + dest := filepath.Join(base, "base/link") + "/../dest" + assert.NoError(t, client.Extract(t.Context(), bytes.NewReader(archive), dest, 0)) + _, err := os.Stat(filepath.Join(base, "other/dest/file")) + assert.NoError(t, err) + _, err = os.Stat(filepath.Join(base, "base/dest/file")) + assert.True(t, errors.Is(err, fs.ErrNotExist)) +} + func TestExtractRejectsGlobalDataLayoutRecords(t *testing.T) { // GNU tar reads member data using these, but archive/tar has already sized the member from its own header. for _, key := range []string{"size", "GNU.sparse.realsize"} { diff --git a/client/tar_dest_linux.go b/client/tar_dest_linux.go index 13eece05..a3fc0846 100644 --- a/client/tar_dest_linux.go +++ b/client/tar_dest_linux.go @@ -12,15 +12,17 @@ import ( // // Only the member name then counts towards PATH_MAX, so a long destination path doesn't make deep members fail. type destDir struct { - fd int + fd int + // path is the cleaned destination that member paths are joined onto; dir is the caller's path, opened as given. path string + dir string } func (d *destDir) open() error { - // Like tar -C, a destination that is a symlink is followed. - fd, err := unix.Open(d.path, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + // Like tar -C, symlinks are followed, so a ".." after one leads somewhere filepath.Clean wouldn't. + fd, err := unix.Open(d.dir, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { - return errors.Wrapf(err, "failed to open %s", d.path) + return errors.Wrapf(err, "failed to open %s", d.dir) } d.fd = fd return nil diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index ceb58b0f..9fdf3de9 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -106,9 +106,9 @@ type tarExtractor struct { copyBuf []byte } -func newTarExtractor(root string, writers int) *tarExtractor { - root = filepath.Clean(root) - dest := &destDir{fd: -1, path: root} +func newTarExtractor(dir string, writers int) *tarExtractor { + root := filepath.Clean(dir) + dest := &destDir{fd: -1, path: root, dir: dir} return &tarExtractor{ root: root, dest: dest, @@ -269,6 +269,10 @@ func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Heade } } isDir := isDirEntry(hdr) + if !isDir && strings.HasSuffix(name, "/.") { + // Only a directory can exist at "x/." and it can't be removed through that name, so GNU tar always fails. + return errors.Errorf("%s: cannot create a non-directory at a name ending in \".\"", hdr.Name) + } if target == e.root { if !isDir { return errors.Errorf("%s: cannot replace the target directory", hdr.Name) @@ -504,6 +508,13 @@ func (e *tarExtractor) dir(ctx context.Context, name, target string, hdr *tar.He switch { case err == nil && isDirStat(st): return e.recordDir(ctx, name, target, hdr, viaLink, nil) + case err == nil && strings.HasSuffix(name, "/."): + // GNU tar's mkdir of "x/." resolves a symlink at x, so a link to a directory stays and anything else fails. + path := target + "/." + if _, err := e.dest.lstat(path); err != nil { + return err + } + return e.recordDir(ctx, name, path, hdr, true, nil) case err == nil: if err := e.removeExisting(target, viaLink); err != nil { return err @@ -804,14 +815,26 @@ func nssID(ctx context.Context, database, name string) (int, bool) { } line, _, _ := strings.Cut(string(out), "\n") fields := strings.Split(line, ":") - // getent also accepts a numeric ID as the key, which getpwnam doesn't. - if len(fields) < 3 || fields[0] != name { + if len(fields) < 3 { + return 0, false + } + // getent looks a numeric key up as an ID, which getpwnam doesn't; for a name, NSS may return the canonical one. + if isGetentID(name) && fields[0] != name { return 0, false } id, err := strconv.Atoi(fields[2]) return id, err == nil } +func isGetentID(key string) bool { + // getent's test is strtoul consuming the whole key: optional leading space and sign, then decimal digits. + key = strings.TrimLeft(key, " \t\n\v\f\r") + if key != "" && (key[0] == '+' || key[0] == '-') { + key = key[1:] + } + return key != "" && strings.Trim(key, "0123456789") == "" +} + func isUnsafeLinkTarget(target string) bool { // GNU tar defers symlinks whose target is absolute or has a ".." component. return strings.HasPrefix(target, "/") || containsDotDot(target) @@ -889,7 +912,12 @@ func (e *tarExtractor) isPlaceholder(path string) bool { } func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bool) error { - source := filepath.Join(e.root, saferName(hdr.Linkname)) + link := saferName(hdr.Linkname) + if strings.HasSuffix(link, "/") || strings.HasSuffix(link, "/.") { + // Only a directory can be named like this, and directories can't be hard linked. + return errors.Errorf("%s: cannot hard link to %s: not a directory", hdr.Name, hdr.Linkname) + } + source := filepath.Join(e.root, link) if _, ok := e.dirs[filepath.Dir(source)]; ok { e.wait(source) } else { diff --git a/client/tar_owner_internal_test.go b/client/tar_owner_internal_test.go index 78a68cef..638e5707 100644 --- a/client/tar_owner_internal_test.go +++ b/client/tar_owner_internal_test.go @@ -16,7 +16,10 @@ func TestOwnerLookupUsesNSS(t *testing.T) { stubGetent(t, `case "$1 $2" in "passwd directory-user") echo "directory-user:*:4242:4242::/home/directory-user:/bin/sh" ;; "group directory-group") echo "directory-group:*:4343:" ;; +"passwd AliasUser") echo "canonical-user:*:4444:4444::/home/canonical-user:/bin/sh" ;; +"group AliasGroup") echo "canonical-group:*:4545:" ;; "passwd 0") echo "root:x:0:0:root:/root:/bin/sh" ;; +"passwd 1234") echo "1234:*:4646:4646::/home/1234:/bin/sh" ;; *) exit 2 ;; esac`) @@ -26,6 +29,17 @@ esac`) gid, err := groupID(t.Context(), "directory-group") assert.NoError(t, err) assert.Equal(t, 4343, gid) + // NSS can resolve an alias to its canonical name, which getpwnam accepts too. + uid, err = userID(t.Context(), "AliasUser") + assert.NoError(t, err) + assert.Equal(t, 4444, uid) + gid, err = groupID(t.Context(), "AliasGroup") + assert.NoError(t, err) + assert.Equal(t, 4545, gid) + // getent looks numeric keys up by ID, so only a record with that exact name matches what getpwnam would find. + uid, err = userID(t.Context(), "1234") + assert.NoError(t, err) + assert.Equal(t, 4646, uid) _, err = userID(t.Context(), "0") assert.Error(t, err) } From 3005a986898c15c23d29389c64e35d2521ac53a6 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 07:53:37 +0000 Subject: [PATCH 06/11] fix(client): settle aliased placeholders and finished directories before writing through symlinks A deferred link's placeholder can also be removed through a symlinked path (alias -> ., then alias/u). Only the literal path marked it replaced, so if a later file reused the freed inode number, the final pass mistook it for the placeholder and replaced it with the link. Forget a placeholder whenever it is removed, whatever path reached it. When an entry's path goes through a symlink, directories GNU tar has already finished were applied only after missing parents had been created through the link. A new subdirectory decides its setgid bit and group at mkdir, so under a setgid directory reached through a symlink it missed both. Apply finished directories as soon as the symlink is found. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 8 ++++++++ client/tar_extractor_linux.go | 32 ++++++++++++++++++++++++-------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 7a1c11e4..4a98b544 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -202,6 +202,11 @@ func TestExtractMatchesGNUTar(t *testing.T) { directory("d/./", 0o555), regular("d/file", 0o644, "x"), }}, + {name: "SetgidDirThroughSymlink", entries: []tarEntry{ + directory("real/", 0o2775), + symlink("alias", "real"), + regular("alias/sub/file", 0o644, "x"), + }}, {name: "TrailingDotThroughSymlink", entries: []tarEntry{ directory("real/", 0o755), symlink("alias", "real"), @@ -365,6 +370,9 @@ func TestExtractLaterEntryReplacesUnsafeSymlink(t *testing.T) { {"LinkAfterFile", []tarEntry{ symlink("entry", "/first"), regular("entry", 0o644, "file"), symlink("entry", "/second"), }, "-> /second"}, + {"FileThroughAlias", []tarEntry{ + symlink("entry", "/first"), symlink("alias", "."), regular("alias/entry", 0o644, "file"), + }, "file"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 9fdf3de9..40a3e543 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -280,16 +280,11 @@ func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Heade return e.recordDir(ctx, name, target, hdr, false, nil) } claimed, hadPlaceholder := e.claim(target, isDir) + // A path through a symlink may alias one with a queued write or an applied directory; ensureParent settles both. viaLink, err := e.ensureParent(name, target) if err != nil { return err } - if viaLink { - // The path may alias one with a queued write or an applied directory, so settle both first. - if err := e.flushFinished(); err != nil { - return err - } - } if err := e.apply(ctx, tr, hdr, name, target, viaLink); err != nil { return err } @@ -435,7 +430,10 @@ func (e *tarExtractor) ensureParent(name, target string) (bool, error) { case isDirStat(st): case isSymlinkStat(st): viaLink = true - err = e.requireDir(parent) + if err = e.requireDir(parent); err == nil { + // The link may lead into an applied directory, whose setgid bit and group a new subdirectory inherits. + err = e.flushFinished() + } default: err = errors.Errorf("%s: not a directory", parent) } @@ -567,7 +565,8 @@ func (e *tarExtractor) recordDir( } func (e *tarExtractor) removeExisting(path string, viaLink bool) error { - if st, err := e.dest.lstat(path); err == nil && isDirStat(st) { + st, err := e.dest.lstat(path) + if err == nil && isDirStat(st) { // Queued writes may still be filling the directory, which GNU tar would find non-empty. e.waitAll() if viaLink { @@ -575,9 +574,26 @@ func (e *tarExtractor) removeExisting(path string, viaLink bool) error { e.dirs = map[string]struct{}{e.root: {}} } } + if err == nil { + e.forgetPlaceholder(statID(st)) + } return e.removeEntry(path) } +func (e *tarExtractor) forgetPlaceholder(id fileID) { + // The path may alias the placeholder's, and once removed its inode number can be reused by a later file. + if _, ok := e.placeholders[id]; !ok { + return + } + delete(e.placeholders, id) + for i := range e.delayed { + if e.delayed[i].id == id && !e.delayed[i].replaced { + e.delayed[i].replaced = true + delete(e.delayedAt, e.delayed[i].path) + } + } +} + func (e *tarExtractor) removeEntry(path string) error { return errors.Wrapf(e.dest.remove(path), "failed to replace %s", path) } From dfa38f9d9c008b4e5fc31f615de7490e47ddf340 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 08:01:18 +0000 Subject: [PATCH 07/11] fix(client): track placeholders made through symlinks by inode, not only path A placeholder created through a symlinked path is recorded under that path, so two cases still missed it: - A regular file written to the literal path goes to a writer goroutine, which removes the placeholder without forgetting it. If the new file reused the freed inode number, the final pass turned it back into the link. Once any placeholder has been made through a symlink, check the target's inode before queueing the write. - When a duplicate deferred link finds a placeholder already in place, keepDelayed revived the newest replaced entry with the same path, which could be one removed earlier through an alias. Only undo the claim the current entry made. GNU tar has the same exposure when inodes are reused; on tmpfs, which never reuses them, it produces the results the new tests expect. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 7 ++++++ client/tar_extractor_linux.go | 43 +++++++++++++++++++++-------------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 4a98b544..34ef17df 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -373,6 +373,13 @@ func TestExtractLaterEntryReplacesUnsafeSymlink(t *testing.T) { {"FileThroughAlias", []tarEntry{ symlink("entry", "/first"), symlink("alias", "."), regular("alias/entry", 0o644, "file"), }, "file"}, + {"DuplicateKeepsLinkMadeThroughAlias", []tarEntry{ + symlink("source", "/first"), hardlink("entry", "source"), symlink("alias", "."), + regular("alias/entry", 0o644, "file"), symlink("alias/entry", "/second"), symlink("entry", "/third"), + }, "-> /second"}, + {"FileOverLinkMadeThroughAlias", []tarEntry{ + symlink("alias", "."), symlink("alias/entry", "/first"), regular("entry", 0o644, "file"), + }, "file"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 40a3e543..59026942 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -100,10 +100,14 @@ type tarExtractor struct { delayed []delayedLink delayedAt map[string]int placeholders map[fileID]struct{} - users map[string]int - groups map[string]int - globalPAX map[string]string - copyBuf []byte + // claimed is the delayed link the current entry's path held, or -1; only that claim can be undone. + claimed int + // placeholderViaLink is set once a placeholder is made through a symlink, so delayedAt misses its other paths. + placeholderViaLink bool + users map[string]int + groups map[string]int + globalPAX map[string]string + copyBuf []byte } func newTarExtractor(dir string, writers int) *tarExtractor { @@ -124,6 +128,7 @@ func newTarExtractor(dir string, writers int) *tarExtractor { dirStack: newDirStack(dest), delayedAt: map[string]int{}, placeholders: map[fileID]struct{}{}, + claimed: -1, users: map[string]int{}, groups: map[string]int{}, copyBuf: make([]byte, copyBufferBytes), @@ -279,7 +284,7 @@ func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Heade } return e.recordDir(ctx, name, target, hdr, false, nil) } - claimed, hadPlaceholder := e.claim(target, isDir) + e.claim(target, isDir) // A path through a symlink may alias one with a queued write or an applied directory; ensureParent settles both. viaLink, err := e.ensureParent(name, target) if err != nil { @@ -288,7 +293,7 @@ func (e *tarExtractor) entry(ctx context.Context, tr *tar.Reader, hdr *tar.Heade if err := e.apply(ctx, tr, hdr, name, target, viaLink); err != nil { return err } - if hadPlaceholder && e.delayed[claimed].replaced { + if claimed := e.claimed; claimed >= 0 && e.delayed[claimed].replaced { // The inode is free for reuse, so it must not identify a placeholder any more. delete(e.placeholders, e.delayed[claimed].id) } @@ -355,17 +360,17 @@ func saferName(name string) string { return name } -func (e *tarExtractor) claim(target string, isDir bool) (int, bool) { +func (e *tarExtractor) claim(target string, isDir bool) { e.wait(target) - i, ok := e.delayedAt[target] - if ok { + e.claimed = -1 + if i, ok := e.delayedAt[target]; ok { e.delayed[i].replaced = true delete(e.delayedAt, target) + e.claimed = i } if !isDir { e.forgetDir(target) } - return i, ok } func (e *tarExtractor) forgetDir(path string) { @@ -617,6 +622,12 @@ func (e *tarExtractor) regular( if err != nil { return err } + if !viaLink && e.placeholderViaLink { + // A writer removes what is at target without forgetting a placeholder, which claim only finds by its own path. + if st, err := e.dest.lstat(target); err == nil { + e.forgetPlaceholder(statID(st)) + } + } switch { case viaLink: // Written before the next entry, since a later path may alias this one. @@ -888,6 +899,7 @@ func (e *tarExtractor) placeholder(name, target string, link delayedLink, viaLin e.delayedAt[target] = len(e.delayed) e.delayed = append(e.delayed, link) e.placeholders[link.id] = struct{}{} + e.placeholderViaLink = e.placeholderViaLink || viaLink return e.dirStack.markLinkParent(name) } if attempt > 0 || !errors.Is(err, fs.ErrExist) { @@ -905,13 +917,10 @@ func (e *tarExtractor) placeholder(name, target string, link delayedLink, viaLin } func (e *tarExtractor) keepDelayed(path string) { - // The placeholder stays in place, so undo claim marking it replaced. - for i := len(e.delayed) - 1; i >= 0; i-- { - if e.delayed[i].path == path && e.delayed[i].replaced { - e.delayed[i].replaced = false - e.delayedAt[path] = i - return - } + // The placeholder stays in place, so undo this entry's claim; a placeholder already removed must stay forgotten. + if i := e.claimed; i >= 0 && e.delayed[i].path == path { + e.delayed[i].replaced = false + e.delayedAt[path] = i } } From e6fccfc454e4439b0980b00aa0110a22a3e036a2 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 08:35:17 +0000 Subject: [PATCH 08/11] fix(client): keep inherited setgid and GNU tar's recorded directory modes Two directory-mode differences from GNU tar 1.35 with -p: - When the umask masks owner bits, the chmod that undoes it dropped a set-group-ID bit inherited from the parent, so the directory lost it and its subdirectories lost the group. Keep the inherited special bits. - GNU tar skips a directory's final chmod when the archived mode equals the mode it last saw for that record: the mode it made it with or, for an existing directory, the mode it found. Records of existing directories now keep that mode too, read after finished directories are applied. A missing "d/." is created the way GNU tar does, as a missing parent whose record then takes the entry's metadata. Repeated "d/./" headers, or a revisited directory followed by "d/./", now end with GNU tar's mode. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 33 ++++++++++++++++++ client/tar_delayed_linux.go | 11 +++--- client/tar_extractor_linux.go | 64 +++++++++++++++++++++++++---------- 3 files changed, 84 insertions(+), 24 deletions(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 34ef17df..bbfc9591 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -67,6 +67,8 @@ type extractCase struct { name string setup func(t *testing.T, dir string) entries []tarEntry + // umask replaces the process umask for both extractions when non-zero. + umask int } func TestExtractMatchesGNUTar(t *testing.T) { @@ -202,6 +204,28 @@ func TestExtractMatchesGNUTar(t *testing.T) { directory("d/./", 0o555), regular("d/file", 0o644, "x"), }}, + {name: "RepeatedTrailingDot", entries: []tarEntry{ + directory("d/./", 0o755), + directory("d/./", 0o700), + directory("e/./", 0o700), + directory("e/./", 0o755), + }}, + {name: "RevisitedDirKeepsSeenMode", entries: []tarEntry{ + directory("d/", 0o755), + regular("elsewhere", 0o644, "x"), + directory("d/", 0o755), + directory("d/./", 0o700), + }}, + {name: "TrailingDotThroughSymlinkRepeated", entries: []tarEntry{ + directory("real/", 0o755), + symlink("alias", "real"), + directory("alias/./", 0o755), + directory("alias/././", 0o700), + }}, + {name: "SetgidInheritedUnderOwnerUmask", setup: setgidRoot, umask: 0o277, entries: []tarEntry{ + directory("child/", 0o700), + regular("child/sub/file", 0o644, "x"), + }}, {name: "SetgidDirThroughSymlink", entries: []tarEntry{ directory("real/", 0o2775), symlink("alias", "real"), @@ -271,6 +295,10 @@ func TestExtractMatchesGNUTar(t *testing.T) { archive := buildTar(t, tc.entries) gnuDir, goDir := t.TempDir(), t.TempDir() t.Cleanup(func() { makeWritable(t, gnuDir); makeWritable(t, goDir) }) + if tc.umask != 0 { + old := syscall.Umask(tc.umask) + t.Cleanup(func() { syscall.Umask(old) }) + } if tc.setup != nil { tc.setup(t, gnuDir) tc.setup(t, goDir) @@ -413,6 +441,11 @@ func rewrites() []tarEntry { //nolint:privatedoc // explains why return entries } +func setgidRoot(t *testing.T, dir string) { + t.Helper() + assert.NoError(t, os.Chmod(dir, fs.ModeSetgid|0o755)) +} + func existingTree(t *testing.T, dir string) { t.Helper() assert.NoError(t, os.WriteFile(filepath.Join(dir, "file-over-dir-parent"), []byte("x"), 0o644)) diff --git a/client/tar_delayed_linux.go b/client/tar_delayed_linux.go index 1ca66891..3b471d98 100644 --- a/client/tar_delayed_linux.go +++ b/client/tar_delayed_linux.go @@ -15,9 +15,9 @@ type pendingDir struct { stat entryStat // interdir marks a missing parent created for an entry, which only gets its permission bits restored. interdir bool - // created is the mode a directory was made with; GNU tar skips the chmod when it already matches. - created uint32 - wasCreated bool + // seen is the mode GNU tar last saw the directory with; it skips the chmod if that matches, even if changed since. + seen uint32 + hasSeen bool // afterLinks holds the directory back until delayed links exist; id detects it being replaced meanwhile. afterLinks bool id fileID @@ -204,8 +204,7 @@ func (e *tarExtractor) applyDir(dir *pendingDir, verify bool) error { } } if dir.interdir { - if dir.wasCreated && dir.created == dir.stat.mode { - // GNU tar compares against the mode it made the directory with, so a chmod through another name stays. + if dir.hasSeen && dir.seen == dir.stat.mode { return nil } st, err := e.dest.lstat(dir.path) @@ -219,7 +218,7 @@ func (e *tarExtractor) applyDir(dir *pendingDir, verify bool) error { } return e.dest.chmod(dir.path, mode) } - keepMode := !verify && dir.wasCreated && dir.created == dir.stat.mode + keepMode := !verify && dir.hasSeen && dir.seen == dir.stat.mode return e.setPathStat(dir.path, dir.stat, keepMode) } diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 59026942..153e265a 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -481,13 +481,13 @@ func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { } } return e.dirStack.push(pendingDir{ - name: e.parentName(name, path), - path: path, - stat: entryStat{mode: desired}, - interdir: true, - created: created, - wasCreated: true, - viaLink: viaLink, + name: e.parentName(name, path), + path: path, + stat: entryStat{mode: desired}, + interdir: true, + seen: created, + hasSeen: true, + viaLink: viaLink, }) } @@ -510,14 +510,18 @@ func (e *tarExtractor) dir(ctx context.Context, name, target string, hdr *tar.He st, err := e.dest.lstat(target) switch { case err == nil && isDirStat(st): - return e.recordDir(ctx, name, target, hdr, viaLink, nil) + return e.recordDir(ctx, name, target, hdr, viaLink, seenMode(st)) case err == nil && strings.HasSuffix(name, "/."): + // The link may lead into an applied directory, whose mode GNU tar records as it finds it. + if err := e.flushFinished(); err != nil { + return err + } // GNU tar's mkdir of "x/." resolves a symlink at x, so a link to a directory stays and anything else fails. path := target + "/." - if _, err := e.dest.lstat(path); err != nil { + if st, err = e.dest.lstat(path); err != nil { return err } - return e.recordDir(ctx, name, path, hdr, true, nil) + return e.recordDir(ctx, name, path, hdr, true, seenMode(st)) case err == nil: if err := e.removeExisting(target, viaLink); err != nil { return err @@ -525,15 +529,34 @@ func (e *tarExtractor) dir(ctx context.Context, name, target string, hdr *tar.He case !errors.Is(err, fs.ErrNotExist): return err } + if strings.HasSuffix(name, "/.") { + return e.dotDir(ctx, name, target, hdr, viaLink) + } created, err := e.mkdir(target, hdr) if err != nil { return err } - // GNU tar's mkdir of "d/." fails, so it creates "d" as a parent and moves this entry's metadata onto it. + return e.recordDir(ctx, name, target, hdr, viaLink, &created) +} + +func (e *tarExtractor) dotDir(ctx context.Context, name, target string, hdr *tar.Header, viaLink bool) error { + // GNU tar's mkdir of "d/." fails, so it creates "d" as a missing parent and moves this entry's metadata onto it. + if err := e.mkdirParent(name, target, viaLink); err != nil { + return err + } + st, err := e.dest.lstat(target) + if err != nil { + return err + } for strings.HasSuffix(name, "/.") { name = strings.TrimSuffix(name, "/.") } - return e.recordDir(ctx, name, target, hdr, viaLink, &created) + return e.recordDir(ctx, name, target, hdr, viaLink, seenMode(st)) +} + +func seenMode(st unix.Stat_t) *uint32 { + mode := st.Mode & 0o7777 + return &mode } func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { @@ -546,14 +569,19 @@ func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { return 0, err } // GNU tar clears the umask for -p; this process can't, so undo it where it would affect the owner. - if e.umask&int(mode) != 0 { - return mode, e.dest.chmod(target, mode) + if e.umask&int(mode) == 0 { + return mode, nil + } + st, err := e.dest.lstat(target) + if err != nil { + return 0, err } - return mode, nil + // A set-group-ID bit inherited from the parent decides the group of subdirectories, so it must survive. + return mode, e.dest.chmod(target, st.Mode&0o7000|mode) } func (e *tarExtractor) recordDir( - ctx context.Context, name, target string, hdr *tar.Header, viaLink bool, created *uint32, + ctx context.Context, name, target string, hdr *tar.Header, viaLink bool, seen *uint32, ) error { stat, err := e.stat(ctx, hdr) if err != nil { @@ -563,8 +591,8 @@ func (e *tarExtractor) recordDir( e.dirs[target] = struct{}{} } dir := pendingDir{name: name, path: target, stat: stat, viaLink: viaLink} - if created != nil { - dir.created, dir.wasCreated = *created, true + if seen != nil { + dir.seen, dir.hasSeen = *seen, true } return e.dirStack.push(dir) } From d66fe6529e5a3c9e225cf0bfd8a9c4523d9c8242 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 09:09:23 +0000 Subject: [PATCH 09/11] fix(client): create directories under a cleared umask on a private thread When the umask masks owner bits, the chmod that undoes it cannot keep an inherited set-group-ID bit for a caller outside the directory's group: Linux clears S_ISGID on chmod by a non-member, so subdirectories and files lose the group. GNU tar avoids this because -p clears the umask before mkdir. Directories whose mode the umask would change are now created by a locked thread that unshares its filesystem attributes and clears its own umask, so the process umask is untouched. Missing parents follow GNU tar's make_directories and get owner rwx while children are written. Where unshare is refused, such as under Docker's default seccomp profile, extraction keeps the previous mkdir and chmod path. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 45 +++++++++++++++++++ client/tar_dest_internal_test.go | 56 ++++++++++++++++++++++++ client/tar_dest_linux.go | 74 ++++++++++++++++++++++++++++++++ client/tar_extractor_linux.go | 53 +++++++++++++++-------- 4 files changed, 209 insertions(+), 19 deletions(-) create mode 100644 client/tar_dest_internal_test.go diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index bbfc9591..5dd0b700 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -427,6 +427,51 @@ func TestExtractLaterEntryReplacesUnsafeSymlink(t *testing.T) { } } +func TestExtractKeepsSetgidGroupForNonMember(t *testing.T) { + entries := []tarEntry{directory("child/", 0o700), regular("child/sub/file", 0o644, "x")} + if dest := os.Getenv("CACHEW_TEST_NON_MEMBER_DEST"); dest != "" { + archive := zstdCompress(t, buildTar(t, entries)) + assert.NoError(t, client.Extract(t.Context(), bytes.NewReader(archive), dest, 0)) + return + } + if os.Geteuid() != 0 { + t.Skip("needs root to give the destination a group the extracting user isn't in") + } + if _, err := exec.LookPath("setpriv"); err != nil { + t.Skip("setpriv is not installed") + } + // The kernel clears set-group-ID on chmod by a non-member, which GNU tar avoids by clearing the umask. + const nobody, group = 65534, 4242 + tmp := t.TempDir() + assert.NoError(t, os.Chmod(filepath.Dir(tmp), 0o755)) + assert.NoError(t, os.Chmod(tmp, 0o755)) + exe, err := os.Executable() + assert.NoError(t, err) + data, err := os.ReadFile(exe) + assert.NoError(t, err) + bin := filepath.Join(tmp, "client.test") + assert.NoError(t, os.WriteFile(bin, data, 0o755)) //nolint:gosec // nobody must run it + dest := filepath.Join(tmp, "dest") + assert.NoError(t, os.Mkdir(dest, 0o755)) + assert.NoError(t, os.Chown(dest, nobody, group)) + assert.NoError(t, os.Chmod(dest, fs.ModeSetgid|0o775)) + + cmd := exec.Command("setpriv", "--reuid=65534", "--regid=65534", "--clear-groups", "sh", "-c", + `umask 0277 && exec "$0" -test.run='^TestExtractKeepsSetgidGroupForNonMember$'`, bin) + cmd.Dir = tmp + cmd.Env = append(os.Environ(), "CACHEW_TEST_NON_MEMBER_DEST="+dest) + out, err := cmd.CombinedOutput() + assert.NoError(t, err, "%s", out) + for _, name := range []string{"child", "child/sub", "child/sub/file"} { + info, err := os.Lstat(filepath.Join(dest, name)) + assert.NoError(t, err) + assert.Equal(t, uint32(group), info.Sys().(*syscall.Stat_t).Gid, name) //nolint:forcetypeassert + } + info, err := os.Lstat(filepath.Join(dest, "child")) + assert.NoError(t, err) + assert.Equal(t, fs.ModeDir|fs.ModeSetgid|0o700, info.Mode()) +} + // rewrites writes many small files twice, so queued writes must land in archive order. func rewrites() []tarEntry { //nolint:privatedoc // explains why var entries []tarEntry diff --git a/client/tar_dest_internal_test.go b/client/tar_dest_internal_test.go new file mode 100644 index 00000000..9118cc31 --- /dev/null +++ b/client/tar_dest_internal_test.go @@ -0,0 +1,56 @@ +//go:build linux + +package client + +import ( + "archive/tar" + "bytes" + "io/fs" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/alecthomas/assert/v2" +) + +func TestUnmaskedMkdirKeepsProcessUmask(t *testing.T) { + dir := t.TempDir() + assert.NoError(t, os.Chmod(dir, fs.ModeSetgid|0o755)) + old := syscall.Umask(0o277) + t.Cleanup(func() { syscall.Umask(old) }) + dest := &destDir{fd: -1, path: dir, dir: dir} + assert.NoError(t, dest.open()) + umask, ok := dest.unmaskedThread() + if !ok { + assert.NoError(t, dest.close()) + t.Skip("this process can't give a thread its own umask") + } + + assert.Equal(t, uint32(0o277), umask) + assert.NoError(t, dest.mkdirUnmasked(filepath.Join(dir, "d"), 0o700)) + assert.NoError(t, dest.close()) + info, err := os.Stat(filepath.Join(dir, "d")) + assert.NoError(t, err) + assert.Equal(t, fs.ModeDir|fs.ModeSetgid|0o700, info.Mode()) + assert.Equal(t, 0o277, processUmask()) +} + +func TestMkdirWithoutUnmaskedThreadKeepsInheritedSetgid(t *testing.T) { + dir := t.TempDir() + assert.NoError(t, os.Chmod(dir, fs.ModeSetgid|0o755)) + old := syscall.Umask(0o277) + t.Cleanup(func() { syscall.Umask(old) }) + var archive bytes.Buffer + tw := tar.NewWriter(&archive) + assert.NoError(t, tw.WriteHeader(&tar.Header{Typeflag: tar.TypeDir, Name: "child/", Mode: 0o700})) + assert.NoError(t, tw.Close()) + e := newTarExtractor(dir, 1) + // As where unshare is refused, such as under Docker's default seccomp profile. + e.dest.unmaskedTried = true + + assert.NoError(t, e.extract(t.Context(), &archive)) + info, err := os.Stat(filepath.Join(dir, "child")) + assert.NoError(t, err) + assert.Equal(t, fs.ModeDir|fs.ModeSetgid|0o700, info.Mode()) +} diff --git a/client/tar_dest_linux.go b/client/tar_dest_linux.go index a3fc0846..2bfd3b74 100644 --- a/client/tar_dest_linux.go +++ b/client/tar_dest_linux.go @@ -2,6 +2,7 @@ package client import ( "os" + "runtime" "strings" "github.com/alecthomas/errors" @@ -16,6 +17,57 @@ type destDir struct { // path is the cleaned destination that member paths are joined onto; dir is the caller's path, opened as given. path string dir string + // unmasked is started on first use and stays nil where this process can't give a thread its own umask. + unmasked *unmaskedDirs + unmaskedTried bool +} + +// unmaskedDirs creates directories from an OS thread with its own cleared umask, as GNU tar clears it for -p. +// +// Restoring masked bits with chmod instead drops an inherited set-group-ID bit if the caller isn't in the group. +type unmaskedDirs struct { + // umask is the process umask when the thread started. + umask uint32 + reqs chan mkdirRequest +} + +type mkdirRequest struct { + path string + mode uint32 + done chan error +} + +func startUnmaskedDirs(fd int) *unmaskedDirs { + u := &unmaskedDirs{reqs: make(chan mkdirRequest)} + started := make(chan bool) + go u.serve(fd, started) + if !<-started { + return nil + } + return u +} + +func (u *unmaskedDirs) serve(fd int, started chan<- bool) { + // Unlocked only on handover, so the thread exits with this goroutine and its umask can't reach other goroutines. + runtime.LockOSThread() + // /proc/self shows the main thread's umask, and Go keeps that thread instead of exiting it, so hand over. + if unix.Gettid() == unix.Getpid() { + handedOver := make(chan bool) + go u.serve(fd, handedOver) + started <- <-handedOver + runtime.UnlockOSThread() + return + } + // Seccomp profiles such as Docker's default refuse unshare; callers then fall back to chmod. + if unix.Unshare(unix.CLONE_FS) != nil { + started <- false + return + } + u.umask = uint32(unix.Umask(0)) //nolint:gosec // permission bits only + started <- true + for req := range u.reqs { + req.done <- unix.Mkdirat(fd, req.path, req.mode) + } } func (d *destDir) open() error { @@ -29,6 +81,9 @@ func (d *destDir) open() error { } func (d *destDir) close() error { + if d.unmasked != nil { + close(d.unmasked.reqs) + } return errors.Wrapf(unix.Close(d.fd), "failed to close %s", d.path) } @@ -60,6 +115,25 @@ func (d *destDir) mkdir(path string, mode uint32) error { return errors.Wrapf(unix.Mkdirat(d.fd, d.rel(path), mode), "failed to create directory %s", path) } +func (d *destDir) unmaskedThread() (umask uint32, ok bool) { + // Started only for umasks that mask owner bits, which are rare, so the common path keeps one thread less. + if !d.unmaskedTried { + d.unmaskedTried = true + d.unmasked = startUnmaskedDirs(d.fd) + } + if d.unmasked == nil { + return 0, false + } + return d.unmasked.umask, true +} + +func (d *destDir) mkdirUnmasked(path string, mode uint32) error { + // Only valid once unmaskedThread has reported the thread available. + done := make(chan error, 1) + d.unmasked.reqs <- mkdirRequest{path: d.rel(path), mode: mode, done: done} + return errors.Wrapf(<-done, "failed to create directory %s", path) +} + func (d *destDir) chmod(path string, mode uint32) error { return errors.Wrapf(unix.Fchmodat(d.fd, d.rel(path), mode, 0), "failed to chmod %s", path) } diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 153e265a..2212ad69 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -463,23 +463,10 @@ func (e *tarExtractor) requireDir(path string) error { } func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { - // GNU tar gives unlisted parents the umask's mode, owner-writable and searchable until extraction finishes. - if err := e.dest.mkdir(path, 0o777); err != nil { - return err - } - st, err := e.dest.lstat(path) + desired, created, err := e.mkdirInterdir(path) if err != nil { return err } - desired, created := st.Mode&0o777, st.Mode&0o777 - if !e.asRoot { - created |= 0o300 - } - if created != desired { - if err := e.dest.chmod(path, st.Mode&0o7000|created); err != nil { - return err - } - } return e.dirStack.push(pendingDir{ name: e.parentName(name, path), path: path, @@ -491,6 +478,31 @@ func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { }) } +func (e *tarExtractor) mkdirInterdir(path string) (desired, created uint32, err error) { + // GNU tar gives unlisted parents the umask's mode, owner-writable and searchable until extraction finishes. + if !e.asRoot && e.umask&0o300 != 0 { + if umask, ok := e.dest.unmaskedThread(); ok { + desired = 0o777 &^ umask + return desired, desired | 0o300, e.dest.mkdirUnmasked(path, desired|0o300) + } + } + if err := e.dest.mkdir(path, 0o777); err != nil { + return 0, 0, err + } + st, err := e.dest.lstat(path) + if err != nil { + return 0, 0, err + } + desired, created = st.Mode&0o777, st.Mode&0o777 + if !e.asRoot { + created |= 0o300 + } + if created == desired { + return desired, created, nil + } + return desired, created, e.dest.chmod(path, st.Mode&0o7000|created) +} + func (e *tarExtractor) parentName(name, path string) string { // GNU tar names a created parent by the member name's prefix, which name comparisons later rely on. for i := range len(name) { @@ -565,18 +577,21 @@ func (e *tarExtractor) mkdir(target string, hdr *tar.Header) (uint32, error) { if !e.asRoot { mode |= 0o300 } + // GNU tar clears the umask for -p; only one thread here can, so it's used where the umask would affect the owner. + if e.umask&int(mode) == 0 { + return mode, e.dest.mkdir(target, mode) + } + if _, ok := e.dest.unmaskedThread(); ok { + return mode, e.dest.mkdirUnmasked(target, mode) + } if err := e.dest.mkdir(target, mode); err != nil { return 0, err } - // GNU tar clears the umask for -p; this process can't, so undo it where it would affect the owner. - if e.umask&int(mode) == 0 { - return mode, nil - } st, err := e.dest.lstat(target) if err != nil { return 0, err } - // A set-group-ID bit inherited from the parent decides the group of subdirectories, so it must survive. + // Keeps an inherited set-group-ID bit, which decides subdirectories' group, unless the caller isn't in the group. return mode, e.dest.chmod(target, st.Mode&0o7000|mode) } From ad86f0bda60aef936b3de8b2ae82c135551594ab Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 09:44:57 +0000 Subject: [PATCH 10/11] fix(client): match GNU tar's implicit-parent modes under default ACLs and links Two differences from GNU tar 1.35 with -p for directories created as missing parents: - A default POSIX ACL replaces the umask when a directory is created, so reading the mode back after mkdir could leave a parent group- or world-writable. GNU tar's make_directories computes the mode from the umask instead; do the same, and read it back only when the umask can't be read. - From the first directory held back for deferred links, GNU tar rereads each directory's mode before restoring it. Implicit parents skipped that when the mode matched the one they were created with, so a later header for the same directory under another name could leave its mode in place. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 21 +++++++++++++++++++ client/tar_delayed_linux.go | 4 ++-- client/tar_dest_internal_test.go | 21 +++++++++++++++++++ client/tar_extractor_linux.go | 35 ++++++++++++++++++++++++++++---- 4 files changed, 75 insertions(+), 6 deletions(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 5dd0b700..47652bba 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -226,6 +226,13 @@ func TestExtractMatchesGNUTar(t *testing.T) { directory("child/", 0o700), regular("child/sub/file", 0o644, "x"), }}, + {name: "ImplicitParentUnderDefaultACL", setup: permissiveDefaultACL, entries: []tarEntry{ + regular("d/file", 0o644, "x"), + }}, + {name: "UnsafeLinkParentReachedByAlias", entries: []tarEntry{ + symlink("d/u", "/tmp"), + directory("./d/", 0o777), + }}, {name: "SetgidDirThroughSymlink", entries: []tarEntry{ directory("real/", 0o2775), symlink("alias", "real"), @@ -486,6 +493,20 @@ func rewrites() []tarEntry { //nolint:privatedoc // explains why return entries } +func permissiveDefaultACL(t *testing.T, dir string) { + t.Helper() + // The kernel's xattr layout: version 2, then user, group and other entries, each granting rwx. + acl := []byte{2, 0, 0, 0} + for _, tag := range []byte{0x01, 0x04, 0x20} { + acl = append(acl, tag, 0, 7, 0, 0xff, 0xff, 0xff, 0xff) + } + err := syscall.Setxattr(dir, "system.posix_acl_default", acl, 0) + if errors.Is(err, syscall.ENOTSUP) { + t.Skip("the filesystem doesn't support POSIX ACLs") + } + assert.NoError(t, err) +} + func setgidRoot(t *testing.T, dir string) { t.Helper() assert.NoError(t, os.Chmod(dir, fs.ModeSetgid|0o755)) diff --git a/client/tar_delayed_linux.go b/client/tar_delayed_linux.go index 3b471d98..23b1a890 100644 --- a/client/tar_delayed_linux.go +++ b/client/tar_delayed_linux.go @@ -184,7 +184,7 @@ func (e *tarExtractor) finish() error { verify := false for len(stack.pending) > 0 { dir := stack.pop() - // From the first held-back directory on, GNU tar checks that each is still the same directory. + // From the first held-back directory on, GNU tar checks each is still the same directory and rereads its mode. verify = verify || dir.afterLinks if err := e.applyDir(dir, verify); err != nil { return err @@ -204,7 +204,7 @@ func (e *tarExtractor) applyDir(dir *pendingDir, verify bool) error { } } if dir.interdir { - if dir.hasSeen && dir.seen == dir.stat.mode { + if !verify && dir.hasSeen && dir.seen == dir.stat.mode { return nil } st, err := e.dest.lstat(dir.path) diff --git a/client/tar_dest_internal_test.go b/client/tar_dest_internal_test.go index 9118cc31..c19144c8 100644 --- a/client/tar_dest_internal_test.go +++ b/client/tar_dest_internal_test.go @@ -54,3 +54,24 @@ func TestMkdirWithoutUnmaskedThreadKeepsInheritedSetgid(t *testing.T) { assert.NoError(t, err) assert.Equal(t, fs.ModeDir|fs.ModeSetgid|0o700, info.Mode()) } + +func TestImplicitParentWithUnreadableUmaskKeepsCreatedMode(t *testing.T) { + dir := t.TempDir() + old := syscall.Umask(0o027) + t.Cleanup(func() { syscall.Umask(old) }) + var archive bytes.Buffer + tw := tar.NewWriter(&archive) + assert.NoError(t, tw.WriteHeader(&tar.Header{Typeflag: tar.TypeReg, Name: "d/file", Mode: 0o644, Size: 1})) + _, err := tw.Write([]byte("x")) + assert.NoError(t, err) + assert.NoError(t, tw.Close()) + e := newTarExtractor(dir, 1) + // As when /proc/self/status can't be read and unshare is refused. + e.umask = unknownUmask + e.dest.unmaskedTried = true + + assert.NoError(t, e.extract(t.Context(), &archive)) + info, err := os.Stat(filepath.Join(dir, "d")) + assert.NoError(t, err) + assert.Equal(t, fs.ModeDir|0o750, info.Mode()) +} diff --git a/client/tar_extractor_linux.go b/client/tar_extractor_linux.go index 2212ad69..6991fba3 100644 --- a/client/tar_extractor_linux.go +++ b/client/tar_extractor_linux.go @@ -135,22 +135,25 @@ func newTarExtractor(dir string, writers int) *tarExtractor { } } +// unknownUmask stands for an unreadable umask, with every bit set so directory modes are always repaired. +const unknownUmask = -1 + func processUmask() int { - // unix.Umask reads the umask by changing it, racing other goroutines; unknown is 0o777, assuming all bits masked. + // unix.Umask reads the umask by changing it, racing other goroutines; unknown has every bit set. status, err := os.ReadFile("/proc/self/status") if err != nil { - return 0o777 + return unknownUmask } for line := range strings.Lines(string(status)) { if value, ok := strings.CutPrefix(line, "Umask:"); ok { umask, err := strconv.ParseInt(strings.TrimSpace(value), 8, 32) if err != nil { - return 0o777 + return unknownUmask } return int(umask) } } - return 0o777 + return unknownUmask } func (e *tarExtractor) extract(ctx context.Context, r io.Reader) (err error) { @@ -486,6 +489,30 @@ func (e *tarExtractor) mkdirInterdir(path string) (desired, created uint32, err return desired, desired | 0o300, e.dest.mkdirUnmasked(path, desired|0o300) } } + if e.umask == unknownUmask { + return e.mkdirInterdirReadBack(path) + } + // Taken from the umask, not read back, since a default ACL replaces the umask when creating. + desired = 0o777 &^ uint32(e.umask) //nolint:gosec // permission bits only + created = desired + if !e.asRoot { + created |= 0o300 + } + if err := e.dest.mkdir(path, created); err != nil { + return 0, 0, err + } + if uint32(e.umask)&created == 0 { //nolint:gosec // permission bits only + return desired, created, nil + } + st, err := e.dest.lstat(path) + if err != nil { + return 0, 0, err + } + return desired, created, e.dest.chmod(path, st.Mode&0o7000|created) +} + +func (e *tarExtractor) mkdirInterdirReadBack(path string) (desired, created uint32, err error) { + // Without a known umask, the mode mkdir leaves is the closest to GNU tar's. if err := e.dest.mkdir(path, 0o777); err != nil { return 0, 0, err } From b322584a8bb7245f4896cbce8e1d484eebc63bcb Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 10:02:02 +0000 Subject: [PATCH 11/11] fix(client): ignore an empty path record in a PAX global header GNU tar 1.35 ignores an empty path value and keeps the member's own name, so an archive whose global header sets path= extracts normally. Applying it cleared every later member's name, which then resolved to the destination and failed the restore. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- client/extract_linux_test.go | 2 ++ client/tar_pax_linux.go | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/client/extract_linux_test.go b/client/extract_linux_test.go index 47652bba..e2bf0da8 100644 --- a/client/extract_linux_test.go +++ b/client/extract_linux_test.go @@ -156,6 +156,8 @@ func TestExtractMatchesGNUTar(t *testing.T) { wholeSecond(regular("after-replacing-global", 0o644, "x")), globalHeader(map[string]string{"mtime": "1400000000"}), wholeSecond(regular("global-mtime-again", 0o644, "x")), + globalHeader(map[string]string{"path": ""}), + wholeSecond(regular("after-empty-global-path", 0o644, "x")), globalHeader(map[string]string{}), wholeSecond(regular("after-empty-global", 0o644, "x")), }}, diff --git a/client/tar_pax_linux.go b/client/tar_pax_linux.go index 8ea2bb4e..e399f573 100644 --- a/client/tar_pax_linux.go +++ b/client/tar_pax_linux.go @@ -30,7 +30,10 @@ func applyGlobalPAX(hdr *tar.Header, records map[string]string) error { var err error switch key { case "path": - hdr.Name = value + // GNU tar ignores an empty path, keeping the name from the member's own header. + if value != "" { + hdr.Name = value + } case "linkpath": hdr.Linkname = value case "uname":