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>
308 lines
8.1 KiB
Go
308 lines
8.1 KiB
Go
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)
|
|
}
|