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..e2bf0da8 --- /dev/null +++ b/client/extract_linux_test.go @@ -0,0 +1,629 @@ +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/alecthomas/errors" + + "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 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} +} + +// 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 + // umask replaces the process umask for both extractions when non-zero. + umask int +} + +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"), + regular("dir/small", 0o600, "replaced"), + 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: "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{"path": ""}), + wholeSecond(regular("after-empty-global-path", 0o644, "x")), + globalHeader(map[string]string{}), + wholeSecond(regular("after-empty-global", 0o644, "x")), + }}, + {name: "ExistingTree", setup: existingTree, entries: []tarEntry{ + 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), + 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: "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: "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: "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: "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"), + regular("alias/sub/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"), + 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: "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")}}, + } + 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.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) + } + + 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 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 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"} { + 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 { + 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"}, + {"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) { + 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) + }) + } +} + +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 + 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 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)) +} + +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)) + assert.NoError(t, os.WriteFile(filepath.Join(dir, "stale"), []byte("old"), 0o644)) +} + +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 + if hdr.ModTime.IsZero() { + hdr.ModTime = archiveTime() + } + hdr.Format = tar.FormatPAX + hdr.Size = int64(len(entry.body)) + if hdr.Typeflag == tar.TypeXGlobalHeader { + 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. + 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 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() + 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/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..23b1a890 --- /dev/null +++ b/client/tar_delayed_linux.go @@ -0,0 +1,253 @@ +package client + +import ( + "path/filepath" + "strings" + + "github.com/alecthomas/errors" +) + +// 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 + // 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 + // 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. +// +// 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{} + // finishedViaLink is set when a finished directory may be reached through a path finishedPaths doesn't hold. + finishedViaLink bool + dest *destDir +} + +func newDirStack(dest *destDir) dirStack { + return dirStack{byName: map[string]*pendingDir{}, finishedPaths: map[string]struct{}{}, dest: dest} +} + +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 { + st, err := s.dest.lstat(dir.path) + if err != nil { + return err + } + dir.id = statID(st) + } + *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{}{} + s.finishedViaLink = s.finishedViaLink || top.viaLink + } +} + +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 + } + if s.finishedViaLink { + return true + } + 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 + st, err := s.dest.lstat(dir.path) + if err != nil { + return err + } + dir.id = statID(st) + } + 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) + e.dirStack.finishedViaLink = false + 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 each is still the same directory and rereads its mode. + 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 { + st, err := e.dest.lstat(dir.path) + if err != nil { + return err + } + if statID(st) != dir.id { + return errors.Errorf("%s: directory renamed before its status could be extracted", dir.path) + } + } + if dir.interdir { + if !verify && dir.hasSeen && dir.seen == dir.stat.mode { + 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 e.dest.chmod(dir.path, mode) + } + keepMode := !verify && dir.hasSeen && dir.seen == 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 + } + 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 := e.removeEntry(link.path); err != nil { + return err + } + if !link.symlink { + if err := e.dest.link(link.target, link.path); err != nil { + return err + } + continue + } + 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 + } + } + return nil +} diff --git a/client/tar_dest_internal_test.go b/client/tar_dest_internal_test.go new file mode 100644 index 00000000..c19144c8 --- /dev/null +++ b/client/tar_dest_internal_test.go @@ -0,0 +1,77 @@ +//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()) +} + +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_dest_linux.go b/client/tar_dest_linux.go new file mode 100644 index 00000000..2bfd3b74 --- /dev/null +++ b/client/tar_dest_linux.go @@ -0,0 +1,204 @@ +package client + +import ( + "os" + "runtime" + "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 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 { + // 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.dir) + } + d.fd = fd + return nil +} + +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) +} + +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) 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) +} + +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 new file mode 100644 index 00000000..6991fba3 --- /dev/null +++ b/client/tar_extractor_linux.go @@ -0,0 +1,1077 @@ +package client + +import ( + "archive/tar" + "context" + "io" + "io/fs" + "os" + "os/exec" + "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 + // 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. +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 + dest *destDir + 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{} + // 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 { + root := filepath.Clean(dir) + dest := &destDir{fd: -1, path: root, dir: dir} + return &tarExtractor{ + root: root, + dest: dest, + 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(dest), + delayedAt: map[string]int{}, + placeholders: map[fileID]struct{}{}, + claimed: -1, + users: map[string]int{}, + groups: map[string]int{}, + copyBuf: make([]byte, copyBufferBytes), + } +} + +// 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 has every bit set. + status, err := os.ReadFile("/proc/self/status") + if err != nil { + 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 unknownUmask + } + return int(umask) + } + } + return unknownUmask +} + +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) + } + 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) + } + 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 := e.writeFile(job.target, job.stat, e.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) + } +} + +// 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 + close(e.failed) + }) +} + +func (e *tarExtractor) readEntries(ctx context.Context, tr *tar.Reader, archive *countingReader) 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 archive.checkEnd() + } + 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 { + // 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) + } + 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 !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) + } + return e.recordDir(ctx, name, target, hdr, false, nil) + } + 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 err := e.apply(ctx, tr, hdr, name, target, viaLink); err != nil { + return err + } + 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) + } + 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(ctx, name, target, hdr, viaLink) + case hdr.Typeflag == tar.TypeSymlink: + 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(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) + } +} + +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) { + e.wait(target) + 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) + } +} + +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) + st, err := e.dest.lstat(parent) + switch { + case errors.Is(err, fs.ErrNotExist): + err = e.mkdirParent(name, parent, viaLink) + case err != nil: + case isDirStat(st): + case isSymlinkStat(st): + viaLink = true + 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) + } + if err != nil { + return false, err + } + if !viaLink { + e.dirs[parent] = struct{}{} + } + return viaLink, nil +} + +func (e *tarExtractor) requireDir(path string) error { + st, err := e.dest.stat(path) + if err != nil { + return err + } + if !isDirStat(st) { + return errors.Errorf("%s: not a directory", path) + } + return nil +} + +func (e *tarExtractor) mkdirParent(name, path string, viaLink bool) error { + desired, created, err := e.mkdirInterdir(path) + if err != nil { + return err + } + return e.dirStack.push(pendingDir{ + name: e.parentName(name, path), + path: path, + stat: entryStat{mode: desired}, + interdir: true, + seen: created, + hasSeen: true, + viaLink: viaLink, + }) +} + +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 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 + } + 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) { + 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(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. + st, err := e.dest.lstat(target) + switch { + case err == nil && isDirStat(st): + 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 st, err = e.dest.lstat(path); err != nil { + return err + } + return e.recordDir(ctx, name, path, hdr, true, seenMode(st)) + case err == nil: + if err := e.removeExisting(target, viaLink); err != nil { + return err + } + 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 + } + 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, 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) { + // 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 + } + // 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 + } + st, err := e.dest.lstat(target) + if err != nil { + return 0, err + } + // 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) +} + +func (e *tarExtractor) recordDir( + ctx context.Context, name, target string, hdr *tar.Header, viaLink bool, seen *uint32, +) error { + stat, err := e.stat(ctx, hdr) + if err != nil { + return err + } + if !viaLink { + e.dirs[target] = struct{}{} + } + dir := pendingDir{name: name, path: target, stat: stat, viaLink: viaLink} + if seen != nil { + dir.seen, dir.hasSeen = *seen, true + } + return e.dirStack.push(dir) +} + +func (e *tarExtractor) removeExisting(path string, viaLink bool) error { + 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 { + // The directory may also be cached under a path without symlinks. + 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) +} + +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(ctx, hdr) + 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. + remove := func(path string) error { return e.removeExisting(path, viaLink) } + 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) + }) + 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 := e.writeFile(target, stat, e.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 (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 = e.dest.create(target, 0o600) + return err + }) + if err != nil { + return err + } + err = write(f) + if err == nil { + err = e.setFileStat(f, target, stat) + } + return errors.Join(err, errors.Wrapf(f.Close(), "failed to close %s", target)) +} + +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 := e.setMtime(target, stat); err != nil { + return err + } + if e.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 := e.setMtime(path, stat); err != nil { + return err + } + if e.asRoot { + if err := e.dest.lchown(path, stat.uid, stat.gid); err != nil { + return err + } + } + if keepMode { + return nil + } + return e.dest.chmod(path, stat.mode) +} + +func (e *tarExtractor) setMtime(path string, stat entryStat) error { + // GNU tar leaves atime alone outside incremental mode. + return e.dest.setTimes(path, []unix.Timespec{{Nsec: unix.UTIME_OMIT}, stat.mtime}) +} + +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(ctx, e.users, hdr.Uname, hdr.Uid, userID) + stat.gid = cachedID(ctx, e.groups, hdr.Gname, hdr.Gid, groupID) + } + return stat, nil +} + +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 + } + id, ok := cache[name] + if !ok { + var err error + if id, err = lookup(ctx, name); err != nil { + id = -1 + } + cache[name] = id + } + if id < 0 { + return numeric + } + return id +} + +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) + } + id, err := strconv.Atoi(u.Uid) + return id, errors.WithStack(err) +} + +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) + } + id, err := strconv.Atoi(g.Gid) + return id, errors.WithStack(err) +} + +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.CommandContext(ctx, "getent", database, name).Output() //nolint:gosec // name is a single argument + if err != nil { + return 0, false + } + line, _, _ := strings.Cut(string(out), "\n") + fields := strings.Split(line, ":") + 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) +} + +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 + } + 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 e.dest.symlink(hdr.Linkname, target) }) + if err != nil { + return err + } + 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 := e.dest.create(target, 0) + if err == nil { + 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 = statID(st) + 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) { + 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 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 + } +} + +func (e *tarExtractor) isPlaceholder(path string) bool { + if len(e.placeholders) == 0 { + return false + } + st, err := e.dest.lstat(path) + if err != nil { + return false + } + _, ok := e.placeholders[statID(st)] + return ok +} + +func (e *tarExtractor) hardlink(name, target string, hdr *tar.Header, viaLink bool) error { + 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 { + // 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 := e.dest.link(source, target) + if err == nil { + return nil + } + if !errors.Is(err, fs.ErrExist) { + return err + } + if source == target || e.sameFile(source, target) { + return nil + } + if attempt > 0 { + return err + } + if err := e.removeExisting(target, viaLink); err != nil { + return err + } + } +} + +func (e *tarExtractor) sameFile(a, b string) bool { + as, err := e.dest.lstat(a) + if err != nil { + return false + } + bs, err := e.dest.lstat(b) + return err == nil && statID(as) == statID(bs) +} + +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 + } + 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 e.dest.mknod(target, kind|stat.mode&0o777, int(dev)) //nolint:gosec // Linux dev_t + }) + if err != nil { + return err + } + return e.setPathStat(target, stat, false) +} diff --git a/client/tar_owner_internal_test.go b/client/tar_owner_internal_test.go new file mode 100644 index 00000000..638e5707 --- /dev/null +++ b/client/tar_owner_internal_test.go @@ -0,0 +1,63 @@ +//go:build linux + +package client + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/alecthomas/assert/v2" +) + +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`) + + uid, err := userID(t.Context(), "directory-user") + assert.NoError(t, err) + assert.Equal(t, 4242, uid) + 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) +} + +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")) +} diff --git a/client/tar_pax_linux.go b/client/tar_pax_linux.go new file mode 100644 index 00000000..e399f573 --- /dev/null +++ b/client/tar_pax_linux.go @@ -0,0 +1,81 @@ +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": + // 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": + 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 +} 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