archivefs mounts an archive by indexing it: no temp directory, virtual posix paths, symlinks resolved inside the archive (absolute and escaping links are broken), members opened directly (zip) or by a sequential scan (tar). All mutations return ErrReadOnly (U-P0-2). vfstest.RunReadOnly checks any read-only FS against a fixture tree; it runs on zip, tar and tar.gz mounts and on vfs.ReadOnly(localfs). archive.OpenMember opens a single member. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
94 lines
2.1 KiB
Go
94 lines
2.1 KiB
Go
package archive
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"compress/gzip"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
|
|
"vcom/internal/vfs"
|
|
)
|
|
|
|
// OpenMember opens one regular member for reading. zip members are read
|
|
// directly; tar and tar.gz are scanned sequentially up to the member
|
|
// (expensive — meant for preview and single files, bulk extraction uses
|
|
// NewSource). The returned reader owns the archive file.
|
|
func OpenMember(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, p string) (io.ReadCloser, error) {
|
|
e, ok := idx.Lookup(p)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%s: %w", p, vfs.ErrNotExist)
|
|
}
|
|
if !e.IsRegular() {
|
|
return nil, fmt.Errorf("%s: not a regular file", p)
|
|
}
|
|
file, err := fsys.Open(ctx, archivePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rc, err := openMember(ctx, file, idx.Format, e.ord)
|
|
if err != nil {
|
|
file.Close()
|
|
return nil, err
|
|
}
|
|
return rc, nil
|
|
}
|
|
|
|
func openMember(ctx context.Context, file vfs.File, f Format, ord int) (io.ReadCloser, error) {
|
|
if f == Zip {
|
|
fi, err := file.Stat()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
zr, err := zip.NewReader(file, fi.Size)
|
|
if err != nil && !errors.Is(err, zip.ErrInsecurePath) {
|
|
return nil, err
|
|
}
|
|
if ord >= len(zr.File) {
|
|
return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist)
|
|
}
|
|
rc, err := zr.File[ord].Open()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return multiCloser{rc, []io.Closer{rc, file}}, nil
|
|
}
|
|
var r io.Reader = &ctxReader{ctx: ctx, r: file}
|
|
closers := []io.Closer{file}
|
|
if f == TarGz {
|
|
zr, err := gzip.NewReader(r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r = zr
|
|
closers = append([]io.Closer{zr}, closers...)
|
|
}
|
|
tr := tar.NewReader(r)
|
|
for i := 0; ; i++ {
|
|
_, err := tr.Next()
|
|
if err == io.EOF {
|
|
return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist)
|
|
}
|
|
if err != nil && !errors.Is(err, tar.ErrInsecurePath) {
|
|
return nil, err
|
|
}
|
|
if i == ord {
|
|
return multiCloser{tr, closers}, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
type multiCloser struct {
|
|
io.Reader
|
|
cs []io.Closer
|
|
}
|
|
|
|
func (m multiCloser) Close() error {
|
|
var errs []error
|
|
for _, c := range m.cs {
|
|
errs = append(errs, c.Close())
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|