feat(archive): index zip/tar/tar.gz and stream members in one pass (5A.1)
BuildIndex reads the zip directory or walks a tar(.gz) once, with progress and cancellation; no temp directory. Zip-slip names (.., absolute, drive letters) and members below a symlink or file of the same archive are rejected in any order; member count and total size are limited. NewSource feeds members to transfer: directories and links from the index, file contents in archive order from a single open; Unpack = Prepare + Execute. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9c898e862b
commit
af453aa705
5 changed files with 985 additions and 0 deletions
89
internal/archive/format.go
Normal file
89
internal/archive/format.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// Package archive reads and writes zip, tar and tar.gz archives on top of
|
||||
// vfs (design §5.1–5.3): an Index is built without unpacking anything to a
|
||||
// temp directory, NewSource feeds members to the transfer engine in one pass
|
||||
// over the archive (Unpack), and Create writes an archive through
|
||||
// transfer.WriteAtomic.
|
||||
package archive
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Format of an archive.
|
||||
type Format uint8
|
||||
|
||||
const (
|
||||
Zip Format = iota
|
||||
Tar
|
||||
TarGz
|
||||
)
|
||||
|
||||
func (f Format) String() string {
|
||||
switch f {
|
||||
case Zip:
|
||||
return "zip"
|
||||
case Tar:
|
||||
return "tar"
|
||||
case TarGz:
|
||||
return "tar.gz"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
// Ext is the file extension, with the dot.
|
||||
func (f Format) Ext() string { return "." + f.String() }
|
||||
|
||||
// knownExts in match order (longest first).
|
||||
var knownExts = []struct {
|
||||
ext string
|
||||
f Format
|
||||
}{
|
||||
{".tar.gz", TarGz}, {".tgz", TarGz}, {".tar", Tar}, {".zip", Zip},
|
||||
}
|
||||
|
||||
// DetectFormat guesses the format from the file name.
|
||||
func DetectFormat(name string) (Format, bool) {
|
||||
lower := strings.ToLower(name)
|
||||
for _, k := range knownExts {
|
||||
if strings.HasSuffix(lower, k.ext) && len(lower) > len(k.ext) {
|
||||
return k.f, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// stripArchiveExt removes a known archive extension, or else the last
|
||||
// extension (report.pdf → report).
|
||||
func stripArchiveExt(name string) string {
|
||||
lower := strings.ToLower(name)
|
||||
for _, k := range knownExts {
|
||||
if strings.HasSuffix(lower, k.ext) && len(name) > len(k.ext) {
|
||||
return name[:len(name)-len(k.ext)]
|
||||
}
|
||||
}
|
||||
if ext := path.Ext(name); ext != "" && ext != name {
|
||||
return name[:len(name)-len(ext)]
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// Name proposes an archive file name for the given sources (paths or base
|
||||
// names, slash-separated): one source → its name without extension
|
||||
// (foo.tar.gz → foo.zip, not foo.tar.zip; U-P2); several → the name of
|
||||
// their parent directory, or "archive".
|
||||
func Name(srcNames []string, f Format) string {
|
||||
if len(srcNames) == 1 {
|
||||
base := path.Base(strings.TrimRight(srcNames[0], "/"))
|
||||
if b := stripArchiveExt(base); b != "" && b != "." && b != "/" {
|
||||
return b + f.Ext()
|
||||
}
|
||||
}
|
||||
if len(srcNames) > 1 {
|
||||
parent := path.Base(path.Dir(srcNames[0]))
|
||||
if parent != "." && parent != "/" && parent != "" {
|
||||
return parent + f.Ext()
|
||||
}
|
||||
}
|
||||
return "archive" + f.Ext()
|
||||
}
|
||||
135
internal/archive/helpers_test.go
Normal file
135
internal/archive/helpers_test.go
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
package archive
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var bg = context.Background()
|
||||
|
||||
// member describes an entry for test archives.
|
||||
type member struct {
|
||||
name string
|
||||
body string
|
||||
mode fs.FileMode // type bits + perm; 0 → regular 0644
|
||||
link string
|
||||
}
|
||||
|
||||
var mtime = time.Date(2020, 5, 6, 7, 8, 9, 0, time.UTC)
|
||||
|
||||
func dir(name string) member { return member{name: name, mode: fs.ModeDir | 0o755} }
|
||||
func file(name, body string) member { return member{name: name, body: body} }
|
||||
func symlink(name, target string) member {
|
||||
return member{name: name, mode: fs.ModeSymlink | 0o777, link: target}
|
||||
}
|
||||
|
||||
// makeArchive writes members in the given format to a byte slice.
|
||||
func makeArchive(t *testing.T, f Format, ms ...member) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
switch f {
|
||||
case Zip:
|
||||
zw := zip.NewWriter(&buf)
|
||||
for _, m := range ms {
|
||||
mode := m.mode
|
||||
if mode == 0 {
|
||||
mode = 0o644
|
||||
}
|
||||
h := &zip.FileHeader{Name: m.name, Method: zip.Deflate, Modified: mtime}
|
||||
h.SetMode(mode)
|
||||
w, err := zw.CreateHeader(h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := m.body
|
||||
if mode&fs.ModeSymlink != 0 {
|
||||
body = m.link
|
||||
}
|
||||
if _, err := w.Write([]byte(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
default:
|
||||
var gz *gzip.Writer
|
||||
var tw *tar.Writer
|
||||
if f == TarGz {
|
||||
gz = gzip.NewWriter(&buf)
|
||||
tw = tar.NewWriter(gz)
|
||||
} else {
|
||||
tw = tar.NewWriter(&buf)
|
||||
}
|
||||
for _, m := range ms {
|
||||
h := &tar.Header{Name: m.name, Mode: 0o644, ModTime: mtime, Typeflag: tar.TypeReg, Size: int64(len(m.body))}
|
||||
switch {
|
||||
case m.mode.IsDir():
|
||||
h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0
|
||||
case m.mode&fs.ModeSymlink != 0:
|
||||
h.Typeflag, h.Mode, h.Size, h.Linkname = tar.TypeSymlink, 0o777, 0, m.link
|
||||
case m.mode&fs.ModeNamedPipe != 0:
|
||||
h.Typeflag, h.Size = tar.TypeFifo, 0
|
||||
case m.mode != 0:
|
||||
h.Mode = int64(m.mode.Perm())
|
||||
}
|
||||
if err := tw.WriteHeader(h); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Size > 0 {
|
||||
if _, err := tw.Write([]byte(m.body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gz != nil {
|
||||
if err := gz.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// writeArchive stores an archive as <tmp>/<name> and returns its path.
|
||||
func writeArchive(t *testing.T, name string, ms ...member) string {
|
||||
t.Helper()
|
||||
f, ok := DetectFormat(name)
|
||||
if !ok {
|
||||
t.Fatalf("bad name %s", name)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), name)
|
||||
if err := os.WriteFile(p, makeArchive(t, f, ms...), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func index(t *testing.T, f Format, ms ...member) *Index {
|
||||
t.Helper()
|
||||
b := makeArchive(t, f, ms...)
|
||||
idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), f, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
func paths(idx *Index) []string {
|
||||
var out []string
|
||||
for _, e := range idx.Entries {
|
||||
out = append(out, e.Path)
|
||||
}
|
||||
return out
|
||||
}
|
||||
308
internal/archive/index.go
Normal file
308
internal/archive/index.go
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
package archive
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Entry is one member of an archive.
|
||||
type Entry struct {
|
||||
Path string // clean, slash-separated, relative ("dir/file"); never "..", never absolute
|
||||
Mode fs.FileMode
|
||||
Size int64
|
||||
ModTime time.Time
|
||||
Link string // symlink target, as stored
|
||||
// Implicit: a parent directory that has no entry of its own.
|
||||
Implicit bool
|
||||
ord int // position in the archive (header number); -1 for implicit dirs
|
||||
}
|
||||
|
||||
// IsDir, IsSymlink and IsRegular classify the entry.
|
||||
func (e Entry) IsDir() bool { return e.Mode.IsDir() }
|
||||
func (e Entry) IsSymlink() bool { return e.Mode&fs.ModeSymlink != 0 }
|
||||
func (e Entry) IsRegular() bool { return e.Mode.IsRegular() }
|
||||
|
||||
// Index lists an archive's members, sorted by path (parents first).
|
||||
type Index struct {
|
||||
Format Format
|
||||
Entries []Entry
|
||||
TotalBytes int64 // sum of regular file sizes (shown before unpacking)
|
||||
Rejected []string // unsafe names dropped (zip-slip, absolute, under a symlink)
|
||||
byPath map[string]int
|
||||
}
|
||||
|
||||
// Lookup returns the entry at p ("" or "/" is not an entry).
|
||||
func (x *Index) Lookup(p string) (Entry, bool) {
|
||||
i, ok := x.byPath[strings.Trim(path.Clean("/"+p), "/")]
|
||||
if !ok {
|
||||
return Entry{}, false
|
||||
}
|
||||
return x.Entries[i], true
|
||||
}
|
||||
|
||||
// Limits protect against archive bombs.
|
||||
type Limits struct {
|
||||
MaxMembers int // default 1 000 000
|
||||
MaxBytes int64 // sum of declared sizes; 0 = unlimited
|
||||
}
|
||||
|
||||
// DefaultLimits are used by BuildIndex.
|
||||
var DefaultLimits = Limits{MaxMembers: 1_000_000}
|
||||
|
||||
// ErrTooManyMembers and ErrTooLarge are returned when Limits are exceeded.
|
||||
var (
|
||||
ErrTooManyMembers = errors.New("archive has too many members")
|
||||
ErrTooLarge = errors.New("archive is too large")
|
||||
)
|
||||
|
||||
// BuildIndex reads the archive's directory (zip) or walks it once (tar,
|
||||
// tar.gz: one decompression pass). progress gets the member count so far;
|
||||
// ctx cancels the pass.
|
||||
func BuildIndex(ctx context.Context, r io.ReaderAt, size int64, f Format, progress func(n int)) (*Index, error) {
|
||||
return BuildIndexLimits(ctx, r, size, f, DefaultLimits, progress)
|
||||
}
|
||||
|
||||
// BuildIndexLimits is BuildIndex with explicit limits.
|
||||
func BuildIndexLimits(ctx context.Context, r io.ReaderAt, size int64, f Format, lim Limits, progress func(n int)) (*Index, error) {
|
||||
b := &indexBuilder{idx: &Index{Format: f}, lim: lim, kinds: map[string]fs.FileMode{}, progress: progress}
|
||||
var err error
|
||||
switch f {
|
||||
case Zip:
|
||||
err = b.zip(ctx, r, size)
|
||||
case Tar, TarGz:
|
||||
err = b.tar(ctx, io.NewSectionReader(r, 0, size), f == TarGz)
|
||||
default:
|
||||
err = fmt.Errorf("archive: unknown format %d", f)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.finish()
|
||||
return b.idx, nil
|
||||
}
|
||||
|
||||
type indexBuilder struct {
|
||||
idx *Index
|
||||
lim Limits
|
||||
n int
|
||||
kinds map[string]fs.FileMode // path → type bits of entries seen
|
||||
entries map[string]Entry
|
||||
progress func(int)
|
||||
}
|
||||
|
||||
func (b *indexBuilder) zip(ctx context.Context, r io.ReaderAt, size int64) error {
|
||||
zr, err := zip.NewReader(r, size)
|
||||
if err != nil && !errors.Is(err, zip.ErrInsecurePath) { // insecure names are rejected below
|
||||
return err
|
||||
}
|
||||
for i, zf := range zr.File {
|
||||
if i%256 == 0 {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
mode := zf.Mode()
|
||||
e := Entry{Path: zf.Name, Mode: mode, Size: int64(zf.UncompressedSize64), ModTime: zf.Modified, ord: i}
|
||||
if mode&fs.ModeSymlink != 0 {
|
||||
e.Size = 0
|
||||
link, err := readZipLink(zf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", zf.Name, err)
|
||||
}
|
||||
e.Link = link
|
||||
}
|
||||
if err := b.add(e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readZipLink reads a symlink's target, stored as the member's body.
|
||||
func readZipLink(zf *zip.File) (string, error) {
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rc.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(rc, 4096))
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func (b *indexBuilder) tar(ctx context.Context, r io.Reader, gz bool) error {
|
||||
if gz {
|
||||
zr, err := gzip.NewReader(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer zr.Close()
|
||||
r = zr
|
||||
}
|
||||
tr := tar.NewReader(&ctxReader{ctx: ctx, r: r})
|
||||
for i := 0; ; i++ {
|
||||
h, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, tar.ErrInsecurePath) {
|
||||
err = nil // (GODEBUG=tarinsecurepath=0) rejected by cleanName instead
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return err
|
||||
}
|
||||
e, ok := tarEntry(h, i)
|
||||
if !ok {
|
||||
continue // PAX globals, GNU long-name records handled by archive/tar
|
||||
}
|
||||
if err := b.add(e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tarEntry(h *tar.Header, ord int) (Entry, bool) {
|
||||
fi := h.FileInfo()
|
||||
e := Entry{Path: h.Name, Mode: fi.Mode(), Size: h.Size, ModTime: h.ModTime, ord: ord}
|
||||
switch h.Typeflag {
|
||||
case tar.TypeReg, tar.TypeRegA, tar.TypeGNUSparse:
|
||||
case tar.TypeDir:
|
||||
e.Size = 0
|
||||
case tar.TypeSymlink:
|
||||
e.Size, e.Link = 0, h.Linkname
|
||||
case tar.TypeLink:
|
||||
// Hard links are indexed as specials (skipped on unpack): following
|
||||
// them would need a second pass.
|
||||
e.Mode, e.Size = fs.ModeIrregular|fi.Mode().Perm(), 0
|
||||
case tar.TypeChar, tar.TypeBlock, tar.TypeFifo:
|
||||
e.Size = 0
|
||||
default:
|
||||
return Entry{}, false
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
|
||||
// cleanName returns the safe relative path of a member, or false for
|
||||
// zip-slip ("..", absolute paths, drive letters).
|
||||
func cleanName(name string) (string, bool) {
|
||||
name = strings.ReplaceAll(name, "\\", "/")
|
||||
if strings.HasPrefix(name, "/") || (len(name) > 1 && name[1] == ':') {
|
||||
return "", false
|
||||
}
|
||||
for _, part := range strings.Split(name, "/") {
|
||||
if part == ".." {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
c := path.Clean(name)
|
||||
if c == "." || c == "" {
|
||||
return "", false
|
||||
}
|
||||
return c, true
|
||||
}
|
||||
|
||||
func (b *indexBuilder) add(e Entry) error {
|
||||
b.n++
|
||||
if b.lim.MaxMembers > 0 && b.n > b.lim.MaxMembers {
|
||||
return fmt.Errorf("%w (more than %d)", ErrTooManyMembers, b.lim.MaxMembers)
|
||||
}
|
||||
if b.progress != nil && b.n%256 == 0 {
|
||||
b.progress(b.n)
|
||||
}
|
||||
p, ok := cleanName(e.Path)
|
||||
if !ok {
|
||||
b.idx.Rejected = append(b.idx.Rejected, e.Path)
|
||||
return nil
|
||||
}
|
||||
// A member below a symlink (or file) of the same archive would be
|
||||
// written through that link on unpack: reject it.
|
||||
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||
if m, seen := b.kinds[d]; seen && !m.IsDir() {
|
||||
b.idx.Rejected = append(b.idx.Rejected, e.Path)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
e.Path = p
|
||||
if e.Mode.IsRegular() {
|
||||
b.idx.TotalBytes += e.Size
|
||||
if b.lim.MaxBytes > 0 && b.idx.TotalBytes > b.lim.MaxBytes {
|
||||
return fmt.Errorf("%w (more than %d bytes)", ErrTooLarge, b.lim.MaxBytes)
|
||||
}
|
||||
}
|
||||
if b.entries == nil {
|
||||
b.entries = map[string]Entry{}
|
||||
}
|
||||
if old, dup := b.entries[p]; dup && old.Mode.IsRegular() {
|
||||
b.idx.TotalBytes -= old.Size // a later member with the same name wins (tar semantics)
|
||||
}
|
||||
b.entries[p] = e
|
||||
b.kinds[p] = e.Mode.Type()
|
||||
return nil
|
||||
}
|
||||
|
||||
// finish drops members below a non-directory (in any archive order), adds
|
||||
// implicit parent directories and sorts.
|
||||
func (b *indexBuilder) finish() {
|
||||
for p := range b.entries {
|
||||
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||
if e, ok := b.entries[d]; ok && !e.IsDir() {
|
||||
b.idx.Rejected = append(b.idx.Rejected, p)
|
||||
if old := b.entries[p]; old.Mode.IsRegular() {
|
||||
b.idx.TotalBytes -= old.Size
|
||||
}
|
||||
delete(b.entries, p)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(b.idx.Rejected)
|
||||
for p := range b.entries {
|
||||
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||
if _, ok := b.entries[d]; ok {
|
||||
break
|
||||
}
|
||||
b.entries[d] = Entry{Path: d, Mode: fs.ModeDir | 0o755, Implicit: true, ord: -1}
|
||||
}
|
||||
}
|
||||
x := b.idx
|
||||
x.Entries = make([]Entry, 0, len(b.entries))
|
||||
for _, e := range b.entries {
|
||||
x.Entries = append(x.Entries, e)
|
||||
}
|
||||
// Sort by components: "a/b" right after "a" (plain order puts "a-b" between).
|
||||
sort.Slice(x.Entries, func(i, j int) bool {
|
||||
return strings.ReplaceAll(x.Entries[i].Path, "/", "\x00") < strings.ReplaceAll(x.Entries[j].Path, "/", "\x00")
|
||||
})
|
||||
x.byPath = make(map[string]int, len(x.Entries))
|
||||
for i, e := range x.Entries {
|
||||
x.byPath[e.Path] = i
|
||||
}
|
||||
if b.progress != nil {
|
||||
b.progress(b.n)
|
||||
}
|
||||
}
|
||||
|
||||
// ctxReader stops a long decompression on cancel.
|
||||
type ctxReader struct {
|
||||
ctx context.Context
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (c *ctxReader) Read(p []byte) (int, error) {
|
||||
if err := c.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return c.r.Read(p)
|
||||
}
|
||||
211
internal/archive/index_test.go
Normal file
211
internal/archive/index_test.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
package archive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"vcom/internal/transfer"
|
||||
"vcom/internal/vfs/localfs"
|
||||
"vcom/internal/vfs/vfstest"
|
||||
)
|
||||
|
||||
func TestIndexZip(t *testing.T) {
|
||||
idx := index(t, Zip,
|
||||
dir("docs/"),
|
||||
file("docs/a.txt", "hello"),
|
||||
file("deep/x/y.bin", "12345678"), // parents implicit
|
||||
symlink("docs/ln", "a.txt"),
|
||||
)
|
||||
if got := fmt.Sprint(paths(idx)); got != "[deep deep/x deep/x/y.bin docs docs/a.txt docs/ln]" {
|
||||
t.Fatalf("paths %s", got)
|
||||
}
|
||||
if idx.TotalBytes != 13 || idx.Format != Zip {
|
||||
t.Fatalf("total %d", idx.TotalBytes)
|
||||
}
|
||||
e, _ := idx.Lookup("/docs/ln")
|
||||
if !e.IsSymlink() || e.Link != "a.txt" {
|
||||
t.Fatalf("link %+v", e)
|
||||
}
|
||||
d, _ := idx.Lookup("deep")
|
||||
if !d.IsDir() || !d.Implicit {
|
||||
t.Fatalf("implicit dir %+v", d)
|
||||
}
|
||||
f, _ := idx.Lookup("docs/a.txt")
|
||||
if f.Size != 5 || !f.ModTime.Equal(mtime) || f.Mode.Perm() != 0o644 {
|
||||
t.Fatalf("file %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIndexTarGz(t *testing.T) {
|
||||
var ms []member
|
||||
for i := range 1000 {
|
||||
ms = append(ms, file(fmt.Sprintf("d/f%04d", i), "x"))
|
||||
}
|
||||
ms = append(ms, symlink("d/ln", "f0000"), member{name: "d/fifo", mode: os.ModeNamedPipe | 0o644})
|
||||
b := makeArchive(t, TarGz, ms...)
|
||||
var progress []int
|
||||
idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) { progress = append(progress, n) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(idx.Entries) != 1003 || idx.TotalBytes != 1000 {
|
||||
t.Fatalf("%d entries, %d bytes", len(idx.Entries), idx.TotalBytes)
|
||||
}
|
||||
if len(progress) < 3 || progress[len(progress)-1] != 1002 {
|
||||
t.Fatalf("progress %v", progress)
|
||||
}
|
||||
if e, _ := idx.Lookup("d/fifo"); e.Mode&os.ModeNamedPipe == 0 {
|
||||
t.Fatalf("fifo %+v", e)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(bg)
|
||||
_, err = BuildIndex(ctx, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) {
|
||||
if n >= 256 {
|
||||
cancel()
|
||||
}
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancel: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZipSlipRejected(t *testing.T) {
|
||||
for _, f := range []Format{Zip, Tar} {
|
||||
idx := index(t, f,
|
||||
file("../evil", "x"),
|
||||
file("/abs/path", "x"),
|
||||
file("a/../../up", "x"),
|
||||
file(`..\win`, "x"),
|
||||
file("C:/drive", "x"),
|
||||
file("ok/./file", "fine"),
|
||||
symlink("esc", "/etc"),
|
||||
file("esc/passwd", "through the link"),
|
||||
file("plainfile", "f"),
|
||||
file("plainfile/child", "under a file"),
|
||||
)
|
||||
if got := fmt.Sprint(paths(idx)); got != "[esc ok ok/file plainfile]" {
|
||||
t.Errorf("%v: kept %s", f, got)
|
||||
}
|
||||
if len(idx.Rejected) != 7 {
|
||||
t.Errorf("%v: rejected %v", f, idx.Rejected)
|
||||
}
|
||||
if idx.TotalBytes != 5 {
|
||||
t.Errorf("%v: total %d", f, idx.TotalBytes)
|
||||
}
|
||||
}
|
||||
// A member under a link is rejected whatever the order in the archive.
|
||||
idx := index(t, Tar, file("esc/passwd", "x"), symlink("esc", "/etc"))
|
||||
if fmt.Sprint(paths(idx)) != "[esc]" {
|
||||
t.Fatalf("order-dependent: %v", paths(idx))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemberLimit(t *testing.T) {
|
||||
var ms []member
|
||||
for i := range 11 {
|
||||
ms = append(ms, file(fmt.Sprintf("f%d", i), "abc"))
|
||||
}
|
||||
for _, f := range []Format{Zip, TarGz} {
|
||||
b := makeArchive(t, f, ms...)
|
||||
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 10}, nil); !errors.Is(err, ErrTooManyMembers) {
|
||||
t.Errorf("%v members: %v", f, err)
|
||||
}
|
||||
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxBytes: 30}, nil); !errors.Is(err, ErrTooLarge) {
|
||||
t.Errorf("%v bytes: %v", f, err)
|
||||
}
|
||||
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 11, MaxBytes: 33}, nil); err != nil {
|
||||
t.Errorf("%v at the limit: %v", f, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// opens counts FS opens of one path.
|
||||
type opens struct {
|
||||
mu sync.Mutex
|
||||
n map[string]int
|
||||
}
|
||||
|
||||
func (o *opens) hook(op vfstest.Op, p string) error {
|
||||
if op == vfstest.OpOpen {
|
||||
o.mu.Lock()
|
||||
if o.n == nil {
|
||||
o.n = map[string]int{}
|
||||
}
|
||||
o.n[p]++
|
||||
o.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSourceSinglePass(t *testing.T) {
|
||||
for _, name := range []string{"a.tar.gz", "a.zip", "a.tar"} {
|
||||
var ms []member
|
||||
for i := range 50 {
|
||||
ms = append(ms, file(fmt.Sprintf("top/f%02d", i), strings.Repeat("y", i)))
|
||||
}
|
||||
ms = append(ms, symlink("top/ln", "f01"), dir("top/empty/"))
|
||||
arch := writeArchive(t, name, ms...)
|
||||
o := &opens{}
|
||||
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: o.hook}
|
||||
idx, err := IndexFile(bg, fsys, arch, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dst := t.TempDir()
|
||||
rep := Unpack(bg, fsys, arch, idx, nil, localfs.New(), dst, transfer.DefaultOptions(), transfer.Hooks{})
|
||||
if rep.Err != nil || rep.Done != 51 || rep.Failed != 0 {
|
||||
t.Fatalf("%s: %+v", name, rep)
|
||||
}
|
||||
if o.n[arch] != 2 { // one for the index, one for the unpack
|
||||
t.Fatalf("%s: archive opened %d times, want 2 (one pass per phase)", name, o.n[arch])
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(dst, "top", "f49"))
|
||||
if len(b) != 49 {
|
||||
t.Fatalf("%s: f49 has %d bytes", name, len(b))
|
||||
}
|
||||
if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "f01" {
|
||||
t.Fatalf("%s: link %q", name, l)
|
||||
}
|
||||
if fi, err := os.Stat(filepath.Join(dst, "top", "empty")); err != nil || !fi.IsDir() {
|
||||
t.Fatalf("%s: empty dir missing", name)
|
||||
}
|
||||
if fi, _ := os.Stat(filepath.Join(dst, "top", "f10")); !fi.ModTime().Equal(mtime) {
|
||||
t.Fatalf("%s: mtime %v", name, fi.ModTime())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameAndDetect(t *testing.T) {
|
||||
cases := []struct {
|
||||
src []string
|
||||
f Format
|
||||
want string
|
||||
}{
|
||||
{[]string{"foo.tar.gz"}, Zip, "foo.zip"},
|
||||
{[]string{"/x/foo.zip"}, TarGz, "foo.tar.gz"},
|
||||
{[]string{"report.pdf"}, Tar, "report.tar"},
|
||||
{[]string{"photos/"}, Zip, "photos.zip"},
|
||||
{[]string{"/home/u/proj/a", "/home/u/proj/b"}, Zip, "proj.zip"},
|
||||
{[]string{"a", "b"}, Tar, "archive.tar"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Name(c.src, c.f); got != c.want {
|
||||
t.Errorf("Name(%v, %v) = %q, want %q", c.src, c.f, got, c.want)
|
||||
}
|
||||
}
|
||||
for name, want := range map[string]Format{"a.ZIP": Zip, "a.tgz": TarGz, "a.tar.gz": TarGz, "a.tar": Tar} {
|
||||
if f, ok := DetectFormat(name); !ok || f != want {
|
||||
t.Errorf("DetectFormat(%s) = %v %v", name, f, ok)
|
||||
}
|
||||
}
|
||||
if _, ok := DetectFormat(".zip"); ok {
|
||||
t.Error("bare extension detected")
|
||||
}
|
||||
}
|
||||
242
internal/archive/source.go
Normal file
242
internal/archive/source.go
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
package archive
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"vcom/internal/transfer"
|
||||
"vcom/internal/vfs"
|
||||
)
|
||||
|
||||
// IndexFile opens p on fsys, detects the format from the name and builds the
|
||||
// index. It reads the archive once and creates no temp files.
|
||||
func IndexFile(ctx context.Context, fsys vfs.FS, p string, progress func(n int)) (*Index, error) {
|
||||
f, ok := DetectFormat(p)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("archive: %s: unknown archive format", p)
|
||||
}
|
||||
file, err := fsys.Open(ctx, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
fi, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return BuildIndex(ctx, file, fi.Size, f, progress)
|
||||
}
|
||||
|
||||
// NewSource returns a transfer.Source with the given members (archive paths;
|
||||
// nil or empty = the whole archive). A member's Rel starts at its own name,
|
||||
// so extracting "docs/a" yields "a" in the target. Stream reads the archive
|
||||
// in one pass: directories and links come first (from the index), then file
|
||||
// contents in archive order.
|
||||
func NewSource(fsys vfs.FS, archivePath string, idx *Index, members []string) transfer.Source {
|
||||
return &source{fs: fsys, path: archivePath, idx: idx, members: members}
|
||||
}
|
||||
|
||||
type source struct {
|
||||
fs vfs.FS
|
||||
path string
|
||||
idx *Index
|
||||
members []string
|
||||
ordRel map[string]int // Rel of a file item → its ordinal in the archive
|
||||
}
|
||||
|
||||
func (s *source) Label() string { return s.fs.Paths().Base(s.path) }
|
||||
|
||||
func (s *source) Walk(ctx context.Context, fn func(transfer.Item) error) error {
|
||||
s.ordRel = map[string]int{}
|
||||
emit := func(e Entry, rel string, root int) error {
|
||||
it := transfer.Item{Rel: rel, Size: e.Size, Mode: e.Mode, ModTime: e.ModTime, LinkTarget: e.Link, Root: root}
|
||||
switch {
|
||||
case e.IsDir():
|
||||
it.Kind = transfer.Dir
|
||||
case e.IsSymlink():
|
||||
it.Kind = transfer.Symlink
|
||||
case e.IsRegular():
|
||||
it.Kind = transfer.File
|
||||
s.ordRel[rel] = e.ord
|
||||
default:
|
||||
it.Kind = transfer.Special
|
||||
}
|
||||
return fn(it)
|
||||
}
|
||||
if len(s.members) == 0 {
|
||||
roots := map[string]int{}
|
||||
for i, e := range s.idx.Entries {
|
||||
if i%256 == 0 {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
top, _, _ := strings.Cut(e.Path, "/")
|
||||
r, ok := roots[top]
|
||||
if !ok {
|
||||
r = len(roots)
|
||||
roots[top] = r
|
||||
}
|
||||
if err := emit(e, e.Path, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for r, m := range s.members {
|
||||
m = strings.Trim(path.Clean("/"+m), "/")
|
||||
if _, ok := s.idx.Lookup(m); !ok {
|
||||
return fmt.Errorf("%s: %w", m, vfs.ErrNotExist)
|
||||
}
|
||||
parent := path.Dir(m)
|
||||
cut := 0
|
||||
if parent != "." {
|
||||
cut = len(parent) + 1
|
||||
}
|
||||
for _, e := range s.idx.Entries {
|
||||
if e.Path != m && !strings.HasPrefix(e.Path, m+"/") {
|
||||
continue
|
||||
}
|
||||
if err := emit(e, e.Path[cut:], r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (s *source) Stream(ctx context.Context, items []transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||
wanted := map[int]transfer.Item{}
|
||||
for _, it := range items {
|
||||
if it.Kind == transfer.File {
|
||||
ord, ok := s.ordRel[it.Rel]
|
||||
if !ok {
|
||||
return fmt.Errorf("archive: %s is not in the plan of this source", it.Rel)
|
||||
}
|
||||
wanted[ord] = it
|
||||
continue
|
||||
}
|
||||
if err := fn(it, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(wanted) == 0 {
|
||||
return nil
|
||||
}
|
||||
file, err := s.fs.Open(ctx, s.path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
switch s.idx.Format {
|
||||
case Zip:
|
||||
err = s.streamZip(ctx, file, wanted, fn)
|
||||
default:
|
||||
err = s.streamTar(ctx, file, wanted, fn)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, it := range wanted { // members that vanished from the archive since indexing
|
||||
if err := fn(it, errReader{fmt.Errorf("%s: %w in the archive", it.Rel, vfs.ErrNotExist)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *source) streamZip(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||
fi, err := file.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
zr, err := zip.NewReader(file, fi.Size)
|
||||
if err != nil && !errors.Is(err, zip.ErrInsecurePath) {
|
||||
return err
|
||||
}
|
||||
for i, zf := range zr.File {
|
||||
it, ok := wanted[i]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
delete(wanted, i)
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
if err := fn(it, errReader{err}); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err = fn(it, rc)
|
||||
rc.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *source) streamTar(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||
var r io.Reader = &ctxReader{ctx: ctx, r: file}
|
||||
if s.idx.Format == TarGz {
|
||||
zr, err := gzip.NewReader(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer zr.Close()
|
||||
r = zr
|
||||
}
|
||||
tr := tar.NewReader(r)
|
||||
for i := 0; len(wanted) > 0; i++ {
|
||||
_, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, tar.ErrInsecurePath) {
|
||||
err = nil
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return err
|
||||
}
|
||||
it, ok := wanted[i] // i counts headers exactly as BuildIndex does
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
delete(wanted, i)
|
||||
if err := fn(it, tr); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type errReader struct{ err error }
|
||||
|
||||
func (r errReader) Read([]byte) (int, error) { return 0, r.err }
|
||||
|
||||
// Unpack extracts members (nil = all) of the indexed archive into toDir on
|
||||
// any FS through the transfer engine: conflicts are resolved by opts/hooks
|
||||
// instead of silent overwrites, files are written via temp + rename, and an
|
||||
// existing symlink in the target is never written through (U-P1-11).
|
||||
func Unpack(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, members []string,
|
||||
to vfs.FS, toDir string, opts transfer.Options, h transfer.Hooks) transfer.Report {
|
||||
req := transfer.Request{Op: transfer.Copy, From: NewSource(fsys, archivePath, idx, members), To: to, ToDir: toDir, Opts: opts}
|
||||
plan, err := transfer.Prepare(ctx, req, h.Progress)
|
||||
if err != nil {
|
||||
return transfer.Report{Err: err, Cancelled: ctx.Err() != nil}
|
||||
}
|
||||
return transfer.Execute(ctx, plan, h)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue