tar

package module
v0.1.141 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2026 License: BSD-3-Clause Imports: 42 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Advanced TAR Library (with Ratarmount-compatible Indexing)

Go Reference

This library is a highly optimized and advanced drop-in replacement for the Go standard library archive/tar.

It integrates high-speed compression, parallel extraction, and ratarmount-compatible SQLite indexing to enable instant random access within massive archives.

Design Principles & Requirements

This library is built with strict adherence to the following design constraints:

  • 100% Pure Go (Zero CGO): The entire library is written in pure Go. It cross-compiles natively and seamlessly to any target platform (Linux, macOS, Windows, FreeBSD, etc.) and architecture (amd64, arm64, 386, etc.) without requiring external C libraries or a GCC toolchain.
  • Maximum Code Reuse: Instead of reinventing decompression and archiving from scratch, the library maximizes the reuse of existing industry-standard code. It extends Go's native archive/tar and klauspost/compress to leverage their proven performance, safety, and stability.
  • True O(1) Random Access: Unlike standard sequential readers, this library provides true random access to compressed streams.
    • ZSTD (.tar.zst): Employs an O(1) fast path by jumping directly to byte-aligned, independent ZSTD frame boundaries stored in the index database.
    • GZIP (.tar.gz): Employs an O(1) fast path by parsing binary GZIDX metadata, recovering the 32KB sliding window (dictionary) via flate.NewReaderDict, and using a bit-shifting reader (bitShiftingReader) to align the unaligned DEFLATE bitstream.
  • Industrial Cache Compatibility: The indexing architecture and SQLite database schema are binary-compatible with the industrial standards used by ratarmount and zran (GZIDX). Index databases generated by the Python-based ratarmount can be natively opened and used by this Go library in O(1) time, and vice versa.

Key Features

  • Drop-in Compatibility: 100% compatible with the archive/tar API. You can seamlessly replace your existing archive/tar imports with github.com/unxed/tar.
  • High Performance: Uses klauspost/compress for highly-parallelized ZStandard and optimized Gzip compression streams.
  • Broad Compression Support: Built-in automatic format detection (magic bytes) for GZIP, BZIP2, XZ, and ZSTD.
  • Parallel Extraction: Reads TAR sequentially but delegates filesystem writes, file creations, and metadata restoration (chmod/chown) to a parallel worker pool.
  • Parallel GZIP Decompression via GZIDX: For indexed .tar.gz archives, ParallelDecompressGzipIndexed/TarFS.OpenParallelGzip split the decompression itself across the archive's saved GZIDX checkpoints, inflating independent segments concurrently in separate goroutines (each reseeded from its checkpoint's saved offset and 32KB sliding-dictionary window) and reassembling the bytes in order — unlike the single sequential decompressor used elsewhere, this uses multiple CPU cores to decompress one archive.
  • In-place Updates (Updater): Truncates existing TAR EOF zero blocks to allow appending new files without full archive rewrite.
  • ratarmount-compatible Indexing & Random Access (fs.FS):
    • Indexes .tar or compressed .tar.* archives on the fly into an SQLite database with a schema identical to ratarmount.
    • Exposes the archive as a standard Go fs.FS interface.
    • Facilitates O(1) random-access file reading for uncompressed .tar archives via io.SectionReader.
    • Automatically synthesizes missing parent folders on the fly.
    • Supports F4 Embedded TAR Index Format (F4SS) which bundles the index directly inside .tar, .tar.gz, or .tar.zst archives natively and compliantly. Read f4tar.md for details.
  • Unix Properties Preservation: Transparently preserves and restores Symlinks, Hardlinks, Unix permissions, UID/GID (numeric & string), timestamps, and special files (Devices, FIFOs).
  • NTFS & Windows Compatibility: Supports reading, writing, and restoring Windows Security Descriptors (NTFS ACLs) via PAX extended headers, alongside physical pre-allocation to prevent file fragmentation on NTFS.
  • Safe Extraction and Sanitization: Implements automatic path verification to block symlink directory traversal attacks (such as Tar Slip), sanitizes Zone.Identifier (Mark of the Web) streams, and safely cleans up partial files on errors unless configured otherwise.
  • POSIX Extended Attributes (PAX xattrs): Stores and restores complete extended attributes (including SELinux contexts and POSIX ACLs) using standard PAX records with SCHILY.xattr.* and LIBARCHIVE.xattr.* prefixes.
  • Windows Security Descriptors (PAX MSWINDOWS.raw_sd): Encodes raw Windows Security Descriptors (NTFS ACLs) as Base64 strings under the standard PAX record MSWINDOWS.raw_sd. This allows cross-platform preservation of Windows security settings.

Usage

1. Standard Drop-in Usage

Simply replace the import path.

import "github.com/unxed/tar"

// Use exactly like the standard library
r, err := tar.OpenReader("archive.tar.gz")
if err != nil {
	log.Fatal(err)
}
defer r.Close()
2. High-Speed Random Access via fs.FS

Generate an SQLite index once and enjoy O(1) random access reads (uncompressed and indexed ZSTD/GZIP) and full io/fs compatibility.

package main

import (
	"io/fs"
	"log"

	"github.com/unxed/tar"
)

func main() {
	// Automatically generates index.sqlite on first run if missing
	tfs, err := tar.NewFS("archive.tar", "index.sqlite")
	if err != nil {
		log.Fatal(err)
	}
	defer tfs.Close()

	// Perform random-access ReadFile (O(1) seek)
	data, err := fs.ReadFile(tfs, "folder/file.txt")
	if err != nil {
		log.Fatal(err)
	}
	log.Println("File contents:", string(data))
}
3. Concurrent Extraction
e, err := tar.NewExtractor("archive.tar.gz", "/path/to/dst", tar.WithExtractorConcurrency(8))
if err != nil {
	log.Fatal(err)
}
defer e.Close()

if err := e.Extract(context.Background()); err != nil {
	log.Fatal(err)
}
4. Parallel GZIP Decompression via GZIDX
tfs, err := tar.NewFS("archive.tar.gz", "archive.tar.gz.index.sqlite")
if err != nil {
	log.Fatal(err)
}
defer tfs.Close()

// Requires a GZIP archive that already has a saved GZIDX index (created
// on the fly by NewFS above, or embedded by the Archiver). Splits the
// decompression itself across the saved checkpoints, one goroutine per
// segment, instead of a single sequential decompressor.
rc, err := tfs.OpenParallelGzip(0) // 0 = runtime.GOMAXPROCS(0)
if err != nil {
	log.Fatal(err)
}
defer rc.Close()

tr := tar.NewReader(rc)
for {
	hdr, err := tr.Next()
	if err == io.EOF {
		break
	}
	// ... consume hdr / tr as with any archive/tar.Reader
}
5. Append files to TAR
f, err := os.OpenFile("archive.tar", os.O_RDWR, 0644)
if err != nil {
	log.Fatal(err)
}
defer f.Close()

updater, err := tar.NewUpdater(f, tar.APPEND_MODE_OVERWRITE)
if err != nil {
	log.Fatal(err)
}

err = updater.Append("newfile.txt", 4, []byte("data"))
if err != nil {
	log.Fatal(err)
}
updater.Close()

Pluggable Compression Architecture

This library features a modular, pluggable compression registry. If you want to enable true $O(1)$ random-access seeking for custom decompressors (e.g., custom GZIP or BZIP2 decoders), you can register them by implementing the following pure-Go interfaces:

// BlockOffsetImporter allows block-based decompressors (like ZSTD or BZIP2)
// to resume decompression from a specific byte or bit-aligned block boundary.
type BlockOffsetImporter interface {
	ResumeFromBlockOffset(r io.ReaderAt, bo *BlockOffset) (io.ReadCloser, error)
}

// GzipIndexImporter allows GZIP decompressors to resume decompression
// from a specific 32KB window dictionary checkpoint.
type GzipIndexImporter interface {
	ResumeFromGzipIndex(r io.ReaderAt, indexData []byte, targetOffset int64) (reader io.ReadCloser, uncompOffset int64, err error)
}

Once registered via RegisterDecompressor(), TarFS will automatically detect them and use their $O(1)$ fast paths during file reads.

Format Extensions

This library extends the standard TAR format by codifying advanced cross-platform metadata support and random-access indexing into the f4 tar extensions. These extensions provide high-fidelity storage for Windows ACLs, POSIX Xattrs, and $O(1)$ random-access indexes while remaining 100% compliant with standard TAR utilities.

See the technical specification in f4tar.md.

Why "f4"?

The name comes from the f4 file manager, a cross-platform asynchronous clone of Far Manager. This library was built to provide f4 with high-fidelity archive support, ensuring that system-specific metadata like Windows Security Descriptors (ACLs) and Linux Extended Attributes (Xattrs) are preserved seamlessly when moving data across OS boundaries.

License

This project is released under the BSD-3-Clause License. See the LICENSE file for details.

Acknowledgements

Please see CREDITS.md for a detailed list of third-party acknowledgements and inspirations.

Documentation

Index

Constants

View Source
const (
	Store uint16 = 0
	GZIP  uint16 = 1
	BZIP2 uint16 = 2
	XZ    uint16 = 3
	ZSTD  uint16 = 4
)

Compression formats

View Source
const (
	TypeReg           = tar.TypeReg
	TypeRegA          = tar.TypeRegA
	TypeLink          = tar.TypeLink
	TypeSymlink       = tar.TypeSymlink
	TypeChar          = tar.TypeChar
	TypeBlock         = tar.TypeBlock
	TypeDir           = tar.TypeDir
	TypeFifo          = tar.TypeFifo
	TypeCont          = tar.TypeCont
	TypeXHeader       = tar.TypeXHeader
	TypeXGlobalHeader = tar.TypeXGlobalHeader
	TypeGNUSparse     = tar.TypeGNUSparse
	TypeGNULongName   = tar.TypeGNULongName
	TypeGNULongLink   = tar.TypeGNULongLink
	TypeVol           = 'V' // GNUTYPE_VOLHDR (Volume header)
	TypeGNUDumpDir    = 'D' // GNUTYPE_DUMPDIR
	TypeGNUMultiVol   = 'M' // GNUTYPE_MULTIVOL
)
View Source
const (
	FormatUnknown = tar.FormatUnknown
	FormatUSTAR   = tar.FormatUSTAR
	FormatPAX     = tar.FormatPAX
	FormatGNU     = tar.FormatGNU
)
View Source
const DefaultGzipCheckpointSpacing = 2 << 20

DefaultGzipCheckpointSpacing is the uncompressed distance between checkpoints: each one keeps a 32 KiB window, so this is about 1.6% memory overhead while a far read decodes at most this much beyond its target.

View Source
const MappedStringMark = '\uFFFE'
View Source
const MappedStringMarkStr = "\uFFFE"

Variables

View Source
var (
	ErrHeader          = tar.ErrHeader
	ErrWriteTooLong    = tar.ErrWriteTooLong
	ErrFieldTooLong    = tar.ErrFieldTooLong
	ErrWriteAfterClose = tar.ErrWriteAfterClose
)
View Source
var ErrAlgorithm = errors.New("tar: unsupported compression algorithm")
View Source
var ErrArchiveLocked = errors.New("tar: cannot modify archive, it is locked")
View Source
var ErrArcidxNotFound = errors.New("arcidx: not found")

ErrArcidxNotFound is returned by ArcidxIndex.Lookup and ArcidxIndex.GetClosestBlockOffset when there is no matching entry.

View Source
var ErrDataAfterEnd = errors.New("tar: data after the end of the archive; not updating it in place")

ErrDataAfterEnd is returned by NewUpdater for an uncompressed archive that has something other than zero blocks after its end-of-archive marker and before its embedded index, if it has one. An entry written there would not be seen, and truncating the archive to append would destroy what is there.

View Source
var ErrNoGzipIndex = errors.New("tar: no GZIDX checkpoints available for parallel decompression")

ErrNoGzipIndex is returned by the parallel GZIP decompression helpers when no usable GZIDX checkpoints are available.

Functions

func AppendTarRecoveryRecord added in v0.1.33

func AppendTarRecoveryRecord(filename string, pct int) error

AppendTarRecoveryRecord генерирует PAR2 для TAR-архива и дописывает его в хвост с F4-футером

func Compress

func Compress(inputFilePath, outputFilePath string) error

Convenience top-level API compatible with targz package

func DetectFormat

func DetectFormat(r io.ReaderAt) (uint16, error)

DetectFormat looks at the magic bytes to determine the compression method.

func Extract

func Extract(inputFilePath, outputFilePath string) error

Convenience top-level API compatible with targz package

func ExtractShadowFileToWriter added in v0.1.101

func ExtractShadowFileToWriter(ra io.ReaderAt, fileSize int64, method uint16, targetName string, out io.Writer) error

ExtractShadowFileToWriter extracts a specific file payload from the Stream 2 metadata shadow stream.

func GetCacheIndexPath added in v0.1.119

func GetCacheIndexPath(archivePath string) (string, error)

GetCacheIndexPath returns the path to the cache directory for the SQLite index.

func GetStandardIndexPath added in v0.1.10

func GetStandardIndexPath(archivePath string) (string, error)

GetStandardIndexPath attempts to place the SQLite index next to the archive (sidecar). If the directory is read-only, it falls back to the user's cache directory.

func IndexArchive

func IndexArchive(archivePath, indexPath string) error

IndexArchive builds the index of an archive at indexPath, using whichever backend the tarindex_simple build tag currently binds to OpenIndex/Index (IndexBackendAuto). An index that could not be finished is removed again: the next open of the archive finds the file, takes it for a finished index and lists an empty archive without reporting anything (f4 issue #1187, where a tar.xz that cannot be decompressed at all opened as empty on the second try).

func IndexArchiveWithBackend added in v0.1.137

func IndexArchiveWithBackend(archivePath, indexPath string, backend IndexBackend) error

IndexArchiveWithBackend is IndexArchive with an explicit IndexBackend (index_backend.go), so a caller that asked NewFS/WithFSIndexBackend for a specific backend gets an index actually written in that backend's format, not the tag-bound default. fs.go's prepareIndex uses this instead of IndexArchive so building a fresh index and then opening it (the very next step in prepareIndex) agree on which backend they mean.

func LocateShadowStream added in v0.1.32

func LocateShadowStream(ra io.ReaderAt, fileSize int64, method uint16) (int64, int64, error)

LocateShadowStream finds the F4SS Magic Footer and returns the physical offset and size of Stream 2.

func NewGzipIndexTrackingReader added in v0.1.100

func NewGzipIndexTrackingReader(r io.Reader) (*gzipIndexTrackingReader, error)

func NewParallelGzipIndexedReader added in v0.1.138

func NewParallelGzipIndexedReader(ra io.ReaderAt, indexData []byte, concurrency int) io.ReadCloser

NewParallelGzipIndexedReader streams the decompressed bytes of a GZIP archive using ParallelDecompressGzipIndexed under the hood, so callers that need an io.Reader (e.g. archive/tar.NewReader or this package's tar.NewReader) can benefit from parallel inflate without buffering the whole decompressed archive in memory up front: segments are still decoded concurrently ahead of the reader, but handed to the consumer as an ordinary streaming Read().

func NewReader

func NewReader(r io.Reader) *tar.Reader

func NewWriter

func NewWriter(w io.Writer) *tar.Writer

func ParallelDecompressGzipIndexed added in v0.1.138

func ParallelDecompressGzipIndexed(ra io.ReaderAt, indexData []byte, w io.Writer, concurrency int) error

ParallelDecompressGzipIndexed decompresses a whole GZIP stream described by a previously saved GZIDX index (see GzipIndexExporter.ExportGzipIndex / FileIndex.GetGzipIndex) by splitting the work across the saved checkpoints: each segment between two consecutive checkpoints is inflated by its own goroutine, independently seeded from that checkpoint's saved offset and (when present) 32KB sliding-dictionary window, so multiple CPU cores can decompress the same archive concurrently instead of the single sequential decompressor used by OpenReader/Extract. Segments are written to w strictly in ascending order, so the output is byte-for-byte identical to a plain sequential decompression of the same stream.

concurrency caps how many segments are inflated at once; concurrency <= 0 selects runtime.GOMAXPROCS(0).

func RegisterCompressor

func RegisterCompressor(method uint16, comp Compressor)

func RegisterDecompressor

func RegisterDecompressor(method uint16, dcomp Decompressor)

func WriteMagicFooter added in v0.1.35

func WriteMagicFooter(w io.Writer, method uint16, shadowStart, shadowSize int64) error

WriteMagicFooter appends a physical footer at the end of the archive so TarFS can locate the shadow stream in O(1) time without scanning backwards.

Types

type AppendMode

type AppendMode int
const (
	APPEND_MODE_OVERWRITE AppendMode = iota
)

type Archiver

type Archiver struct {
	// contains filtered or unexported fields
}

func NewArchiver

func NewArchiver(filename string, chroot string, opts ...ArchiverOption) (*Archiver, error)

func (*Archiver) Archive

func (a *Archiver) Archive(ctx context.Context, files map[string]os.FileInfo) error

Archive writes files to the tar sequentially. For TAR, unlike ZIP, we cannot write data streams concurrently to the same file.

func (*Archiver) Close

func (a *Archiver) Close() error

func (*Archiver) SetComment added in v0.1.40

func (a *Archiver) SetComment(comment string)

SetComment sets the global archive comment stored inside the F4SS shadow metadata index.

func (*Archiver) Written added in v0.1.50

func (a *Archiver) Written() (bytes, entries int64)

type ArchiverOption

type ArchiverOption func(*archiverOptions) error

func WithArchiverDeterministic added in v0.1.138

func WithArchiverDeterministic(b bool) ArchiverOption

WithArchiverDeterministic enables "torrenttar"-style deterministic output, analogous to the torrentzip convention for ZIP: combined with the alphabetical entry order Archive already produces, it normalizes every entry's mtime/atime/ctime, uid/gid, resolved owner/group names and platform-specific extended metadata (POSIX ACLs, SELinux labels, other xattrs, Windows security descriptors), none of which are part of the archived content itself but which otherwise make the .tar depend on when, where and as whom it was built. With this enabled, archiving the same file tree twice always produces a byte-identical archive. The fixed modification time defaults to the Unix epoch; use WithArchiverDeterministicTime to pick a different one (e.g. a build's SOURCE_DATE_EPOCH).

func WithArchiverDeterministicTime added in v0.1.138

func WithArchiverDeterministicTime(t time.Time) ArchiverOption

WithArchiverDeterministicTime is like WithArchiverDeterministic(true) but pins the fixed modification time recorded for every entry to t instead of the Unix epoch.

func WithArchiverEmbeddedIndex added in v0.1.28

func WithArchiverEmbeddedIndex(b bool) ArchiverOption

func WithArchiverIndex added in v0.1.8

func WithArchiverIndex(path string) ArchiverOption

func WithArchiverLevel added in v0.1.47

func WithArchiverLevel(level int) ArchiverOption

WithArchiverLevel sets the compression level.

func WithArchiverLock added in v0.1.40

func WithArchiverLock(b bool) ArchiverOption

WithArchiverLock locks the archive to prevent modifications.

func WithArchiverMethod

func WithArchiverMethod(method uint16) ArchiverOption

func WithArchiverPassword added in v0.1.32

func WithArchiverPassword(p string) ArchiverOption

WithArchiverEmbeddedIndex appends the index directly inside the archive (F4 Shadow Stream). WithArchiverPassword enables F4Crypt AES-256-CTR encryption for the archive.

func WithArchiverPathMapping added in v0.1.57

func WithArchiverPathMapping(m map[string]string) ArchiverOption

WithArchiverPathMapping sets the path mapping for logical names in the archive.

func WithArchiverRecovery added in v0.1.34

func WithArchiverRecovery(pct int) ArchiverOption

WithArchiverRecovery устанавливает процент избыточности PAR2 для защиты архива

func WithArchiverSplitSize added in v0.1.37

func WithArchiverSplitSize(size int64) ArchiverOption

WithArchiverSplitSize enables creation of multi-volume archives

func WithArchiverXattrs added in v0.1.13

func WithArchiverXattrs(b bool) ArchiverOption

WithArchiverXattrs enables archiving of extended attributes (xattrs, POSIX ACLs, SELinux).

type ArcidxIndex added in v0.1.137

type ArcidxIndex struct {
	// contains filtered or unexported fields
}

ArcidxIndex is the FlatBuffers-backed counterpart of the sqlite Index type. It implements the same set of methods (Close, InitMetadata, Insert, Lookup, List, RecursiveSize, InsertBlockOffsets, GetClosestBlockOffset, GetGzipIndex, SaveGzipIndex) with the same signatures, using the shared FileNode/BlockOffset domain types from sqlite.go, so calling code can choose either backend without depending on sqlite-specific types.

func NewArcidxIndex added in v0.1.137

func NewArcidxIndex(path string) (*ArcidxIndex, error)

NewArcidxIndex creates a brand-new, empty, in-memory index that will be serialized to path on Close. Any existing file at path is left untouched until Close overwrites it; callers that want a guaranteed-fresh file (like indexer_enabled.go does for sqlite) should remove the old file themselves first.

func OpenArcidxIndex added in v0.1.137

func OpenArcidxIndex(path string) (*ArcidxIndex, error)

OpenArcidxIndex opens path for reading (and, once a write method is called, for read-modify-write access). If path does not exist or is empty, it behaves like NewArcidxIndex: this mirrors OpenIndex's "CREATE TABLE IF NOT EXISTS" semantics for a brand-new sqlite file. If path exists but its contents cannot be parsed as a valid ArchiveIndex FlatBuffers message, an error is returned instead of silently starting from empty, so callers can tell "no index yet" apart from "corrupted index".

func (*ArcidxIndex) Close added in v0.1.137

func (idx *ArcidxIndex) Close() error

Close flushes any buffered writes to disk (as a single FlatBuffers ArchiveIndex message, written atomically) and marks the index unusable. Calling Close on an index that was only ever read from (never materialized) is a cheap no-op, matching sql.DB.Close's idempotency.

func (*ArcidxIndex) GetClosestBlockOffset added in v0.1.137

func (idx *ArcidxIndex) GetClosestBlockOffset(table string, targetDataOffset int64) (*BlockOffset, error)

GetClosestBlockOffset returns the entry with the largest DataOffset that is still <= targetDataOffset, binary-searching the compression_blob.

func (*ArcidxIndex) GetGzipIndex added in v0.1.137

func (idx *ArcidxIndex) GetGzipIndex() ([]byte, error)

GetGzipIndex returns the raw serialized gzip random-access index previously stored with SaveGzipIndex, or (nil, nil) if none was saved.

func (*ArcidxIndex) InitMetadata added in v0.1.137

func (idx *ArcidxIndex) InitMetadata() error

InitMetadata records the backend identity in the index. Unlike sqlite's InitMetadata, which inserts free-form (name, version) rows into a "versions" table, this only has room for ArchiveIndex.backend_name / .version, which is what it sets.

func (*ArcidxIndex) Insert added in v0.1.137

func (idx *ArcidxIndex) Insert(nodes []FileNode) error

Insert adds nodes to the index, deduplicating paths, xattr keys and metadata tuples, and skipping any (path, name, offsetheader) triple already present (mirroring sqlite_enabled.go's `ON CONFLICT DO NOTHING`).

func (*ArcidxIndex) InsertBlockOffsets added in v0.1.137

func (idx *ArcidxIndex) InsertBlockOffsets(table string, offsets []BlockOffset) error

InsertBlockOffsets stores the (blockoffset, dataoffset) pairs used for random access into block-based compression formats (ZSTD, BZIP2). Unlike sqlite's per-key INSERT OR REPLACE table, this schema only has one compression_format/compression_blob pair for the whole index, so this is a wholesale replace, not an incremental merge; see the package doc comment.

func (*ArcidxIndex) List added in v0.1.137

func (idx *ArcidxIndex) List(p string) ([]FileNode, error)

List returns the latest entry for every distinct name directly under p (a ReadDir-style listing).

func (*ArcidxIndex) Lookup added in v0.1.137

func (idx *ArcidxIndex) Lookup(p string) (*FileNode, error)

Lookup returns the latest (highest offset_header) entry for path p.

func (*ArcidxIndex) RecursiveSize added in v0.1.137

func (idx *ArcidxIndex) RecursiveSize(p string) (int64, error)

RecursiveSize sums the size of the latest version of every file at or below p (p itself included), matching sqlite_enabled.go's semantics.

func (*ArcidxIndex) SaveGzipIndex added in v0.1.137

func (idx *ArcidxIndex) SaveGzipIndex(data []byte) error

SaveGzipIndex stores data (as produced by GzipIndexExporter) as the index's compression blob.

type BlockOffset added in v0.1.1

type BlockOffset struct {
	BlockOffset int64 // Compressed block offset (bit or byte depending on format)
	DataOffset  int64 // Uncompressed data offset (byte)
}

type BlockOffsetExporter added in v0.1.1

type BlockOffsetExporter interface {
	ExportBlockOffsets() []BlockOffset
}

BlockOffsetExporter exports boundary maps for block-based compression formats (ZSTD, BZIP2).

type BlockOffsetImporter added in v0.1.1

type BlockOffsetImporter interface {
	ResumeFromBlockOffset(r io.ReaderAt, bo *BlockOffset) (io.ReadCloser, error)
}

BlockOffsetImporter resumes decompression from a specific block boundary.

type BzipReaderAt added in v0.1.141

type BzipReaderAt struct {
	// contains filtered or unexported fields
}

BzipReaderAt gives random access to the uncompressed bytes of a bzip2 file available only as an io.ReaderAt. A bzip2 stream is a sequence of blocks that are compressed independently, each starting with the 48-bit magic 0x314159265359 at any bit position, so the file is scanned once for those magics and a read decodes only the block or blocks it falls in. A block is decoded on its own by giving the decoder a one-block stream made of its bits (the block's own CRC doubles as the stream CRC of a single block). Sizes of the blocks are learned by decoding them, so the first read at a far offset decodes the blocks before it once; after that the sizes are known. Several concatenated streams are supported (unxed/f4#1678). Safe for concurrent use; calls are serialised.

func NewBzipReaderAt added in v0.1.141

func NewBzipReaderAt(ra io.ReaderAt, size int64) (*BzipReaderAt, error)

NewBzipReaderAt opens ra, size bytes of bzip2 data.

func (*BzipReaderAt) Close added in v0.1.141

func (z *BzipReaderAt) Close() error

Close drops the cached block. The ReaderAt is the caller's.

func (*BzipReaderAt) Decoded added in v0.1.141

func (z *BzipReaderAt) Decoded() int64

Decoded reports how many uncompressed bytes have been decoded in total.

func (*BzipReaderAt) ReadAt added in v0.1.141

func (z *BzipReaderAt) ReadAt(p []byte, off int64) (int, error)

ReadAt implements io.ReaderAt over the uncompressed data.

func (*BzipReaderAt) Size added in v0.1.141

func (z *BzipReaderAt) Size() int64

Size returns the uncompressed size once every block has been sized, else -1.

type Compressor

type Compressor func(w io.Writer) (io.WriteCloser, error)

type Decompressor

type Decompressor interface {
	Decompress(r io.Reader) (io.ReadCloser, error)
}

type Extractor

type Extractor struct {
	// contains filtered or unexported fields
}

func NewExtractor

func NewExtractor(filename, chroot string, opts ...ExtractorOption) (*Extractor, error)

func (*Extractor) Close

func (e *Extractor) Close() error

func (*Extractor) Extract

func (e *Extractor) Extract(ctx context.Context) error

Extract reads TAR sequentially but delegates disk I/O and chmod/chown to a worker pool.

func (*Extractor) Written added in v0.1.51

func (e *Extractor) Written() (bytes, entries int64)

type ExtractorOption

type ExtractorOption func(*extractorOptions) error

func WithExtractorChownErrorHandler

func WithExtractorChownErrorHandler(fn func(name string, err error) error) ExtractorOption

WithExtractorChownErrorHandler allows gracefully ignoring chown errors which frequently happen when extracting archives as an unprivileged user.

func WithExtractorConcurrency

func WithExtractorConcurrency(n int) ExtractorOption

func WithExtractorIncremental added in v0.1.13

func WithExtractorIncremental(b bool) ExtractorOption

WithExtractorIncremental enables processing of GNU Dumpdir headers to remove deleted files during incremental restores.

func WithExtractorKeepBroken added in v0.1.22

func WithExtractorKeepBroken(b bool) ExtractorOption

func WithExtractorKeepNewerFiles added in v0.1.13

func WithExtractorKeepNewerFiles(keep bool) ExtractorOption

WithExtractorKeepNewerFiles prevents overwriting files that are newer on disk (--keep-newer-files)

func WithExtractorKeepOldFiles added in v0.1.13

func WithExtractorKeepOldFiles(keep bool) ExtractorOption

WithExtractorKeepOldFiles prevents overwriting existing files (-k or --keep-old-files)

func WithExtractorMaxFileSize

func WithExtractorMaxFileSize(n int64) ExtractorOption

func WithExtractorMaxRatio

func WithExtractorMaxRatio(n int64) ExtractorOption

func WithExtractorNoTimes added in v0.1.13

func WithExtractorNoTimes(noTimes bool) ExtractorOption

WithExtractorNoTimes prevents restoring original modification times (-m / --touch)

func WithExtractorNumericOwner added in v0.1.13

func WithExtractorNumericOwner(b bool) ExtractorOption

WithExtractorNumericOwner always uses numeric user/group IDs from the archive rather than resolving Uname/Gname (--numeric-owner).

func WithExtractorPassword added in v0.1.32

func WithExtractorPassword(p string) ExtractorOption

WithExtractorSafeWrites extracts files atomically by writing to a temporary file and renaming (--safe-writes). WithExtractorPassword provides the password for decrypting F4Crypt encrypted archives.

func WithExtractorSafeWrites added in v0.1.13

func WithExtractorSafeWrites(b bool) ExtractorOption

func WithExtractorSparse added in v0.1.13

func WithExtractorSparse(b bool) ExtractorOption

WithExtractorSparse enables extracting files as sparse files by seeking over zero-blocks (-S, --sparse).

func WithExtractorStripComponents added in v0.1.13

func WithExtractorStripComponents(count int) ExtractorOption

WithExtractorStripComponents strips the specified number of leading components from file names on extraction (--strip-components)

func WithExtractorTolerant added in v0.1.25

func WithExtractorTolerant(b bool) ExtractorOption

func WithExtractorUnlinkFirst added in v0.1.13

func WithExtractorUnlinkFirst(b bool) ExtractorOption

WithExtractorUnlinkFirst removes existing files prior to extracting over them (-U, --unlink-first).

func WithExtractorXattrs added in v0.1.13

func WithExtractorXattrs(b bool) ExtractorOption

WithExtractorXattrs enables restoration of extended attributes (xattrs, POSIX ACLs, SELinux).

type FSOption added in v0.1.32

type FSOption func(*fsOptions)

func WithFSIndexBackend added in v0.1.137

func WithFSIndexBackend(b IndexBackend) FSOption

WithFSIndexBackend explicitly selects which FileIndex implementation NewFS opens (see IndexBackend in index_backend.go). Omitting this option keeps the pre-existing IndexBackendAuto behavior: whichever backend the tarindex_simple build tag currently binds to OpenIndex/Index.

func WithFSPassword added in v0.1.32

func WithFSPassword(p string) FSOption

WithFSPassword provides the password for decrypting F4Crypt encrypted archives in TarFS.

type FileIndex added in v0.1.137

type FileIndex interface {
	Close() error
	InitMetadata() error
	Insert(nodes []FileNode) error
	Lookup(p string) (*FileNode, error)
	List(p string) ([]FileNode, error)
	RecursiveSize(p string) (int64, error)
	InsertBlockOffsets(table string, offsets []BlockOffset) error
	GetClosestBlockOffset(table string, targetDataOffset int64) (*BlockOffset, error)
	GetGzipIndex() ([]byte, error)
	SaveGzipIndex(data []byte) error
}

FileIndex is the method set both index backends implement: the SQLite-backed Index (sqlite_enabled.go/sqlite_disabled.go) and the FlatBuffers-backed ArcidxIndex (arcidx_index.go, unxed/tar#9). TarFS.Index (fs.go) is declared as this interface, not as a concrete *Index, so a single TarFS value can hold either backend - chosen explicitly via WithFSIndexBackend, or left to the tarindex_simple build tag as before - without needing two different builds of the tar package at once.

Every other caller of OpenIndex (writer.go, indexer_enabled.go) is untouched: they keep using the tag-bound Index/OpenIndex names directly, exactly as before this file was added.

type FileNode

type FileNode struct {
	Path           string
	Name           string
	OffsetHeader   int64
	Offset         int64
	Size           int64
	Mode           int64
	ModTime        time.Time
	Type           byte
	LinkName       string
	Uid            int
	Gid            int
	IsTar          bool
	IsSparse       bool
	IsGenerated    bool
	RecursionDepth int
	Xattrs         map[string][]byte
	Acl            []byte
}

type Format

type Format = tar.Format

type GzipIndexExporter added in v0.1.1

type GzipIndexExporter interface {
	ExportGzipIndex() ([]byte, error)
}

GzipIndexExporter exports the complete serialized GZIP index (compatible with zran.c/rapidgzip).

type GzipIndexImporter added in v0.1.1

type GzipIndexImporter interface {
	ResumeFromGzipIndex(r io.ReaderAt, indexData []byte, targetOffset int64) (reader io.ReadCloser, uncompOffset int64, err error)
}

GzipIndexImporter resumes GZIP decompression using the serialized index.

type GzipReaderAt added in v0.1.138

type GzipReaderAt struct {
	// contains filtered or unexported fields
}

GzipReaderAt gives random access to the uncompressed bytes of a GZIP file that is only available as an io.ReaderAt (a member of another archive, a remote file), without an index saved beforehand and without a local path.

It builds the checkpoint index (GZIDX: a position in the deflate stream plus the 32 KiB window, every spacing bytes) as it goes. A read past everything scanned so far continues the one sequential scan, and serves its bytes straight from it; a read behind the scan resumes from the nearest earlier checkpoint. So the first pass over the file costs one decompression, and a later read anywhere costs at most one checkpoint interval, never a decompression from the start (f4#1678).

Multi-member (concatenated) files are supported. Safe for concurrent use; calls are serialised.

func NewGzipReaderAt added in v0.1.138

func NewGzipReaderAt(ra io.ReaderAt, size int64, spacing int64) (*GzipReaderAt, error)

NewGzipReaderAt opens ra, size bytes of GZIP data, for random access. spacing <= 0 selects DefaultGzipCheckpointSpacing.

func (*GzipReaderAt) Close added in v0.1.138

func (g *GzipReaderAt) Close() error

Close releases the scan. The underlying ReaderAt is the caller's.

func (*GzipReaderAt) Decoded added in v0.1.138

func (g *GzipReaderAt) Decoded() int64

Decoded reports how many uncompressed bytes have been decoded in total.

func (*GzipReaderAt) ReadAt added in v0.1.138

func (g *GzipReaderAt) ReadAt(p []byte, off int64) (int, error)

ReadAt implements io.ReaderAt over the uncompressed data.

func (*GzipReaderAt) Size added in v0.1.138

func (g *GzipReaderAt) Size() int64

Size returns the uncompressed size once a read has reached the end of the data, and -1 before that.

type Header = tar.Header

Drop-in replacements for standard archive/tar types

func FileInfoHeader

func FileInfoHeader(fi os.FileInfo, link string) (*Header, error)

type Index

type Index struct {
	// contains filtered or unexported fields
}

func OpenIndex

func OpenIndex(dsn string) (*Index, error)

func (*Index) Close

func (idx *Index) Close() error

func (*Index) GetClosestBlockOffset added in v0.1.1

func (idx *Index) GetClosestBlockOffset(table string, targetDataOffset int64) (*BlockOffset, error)

func (*Index) GetGzipIndex added in v0.1.1

func (idx *Index) GetGzipIndex() ([]byte, error)

func (*Index) InitMetadata added in v0.1.29

func (idx *Index) InitMetadata() error

func (*Index) Insert

func (idx *Index) Insert(nodes []FileNode) error

func (*Index) InsertBlockOffsets added in v0.1.1

func (idx *Index) InsertBlockOffsets(table string, offsets []BlockOffset) error

func (*Index) List

func (idx *Index) List(p string) ([]FileNode, error)

func (*Index) Lookup

func (idx *Index) Lookup(p string) (*FileNode, error)

func (*Index) RecursiveSize

func (idx *Index) RecursiveSize(p string) (int64, error)

func (*Index) SaveGzipIndex added in v0.1.1

func (idx *Index) SaveGzipIndex(data []byte) error

type IndexBackend added in v0.1.137

type IndexBackend int

IndexBackend explicitly selects which FileIndex implementation NewFS opens for a given TarFS, independent of the tarindex_simple build tag. Pass one via WithFSIndexBackend.

const (
	// IndexBackendAuto (the default) keeps the pre-existing, tag-bound
	// behavior: NewFS opens whatever OpenIndex/Index currently name for this
	// build - the SQLite backend, unless the binary was built with
	// -tags tarindex_simple, in which case ArcidxIndex.
	IndexBackendAuto IndexBackend = iota
	// IndexBackendSQLite always opens the SQLite-backed Index, regardless of
	// the tarindex_simple tag. Only functional in builds that actually
	// compiled the SQLite backend in: on a tarindex_simple build it returns
	// ErrSQLiteBackendUnavailable (see tarindex_simple.go), and on the BSD/
	// Solaris/illumos OSes without cgo-free SQLite it returns the same
	// errNoSqlite the tag-bound OpenIndex already returns there
	// (sqlite_disabled.go) - not a new limitation, just reachable
	// explicitly now.
	IndexBackendSQLite
	// IndexBackendArcidx always opens the FlatBuffers-backed ArcidxIndex.
	// arcidx_index.go has no build tag of its own, so this works in every
	// build, including ones that also have the SQLite backend compiled in.
	IndexBackendArcidx
)

type MultiVolumeReader added in v0.1.37

type MultiVolumeReader struct {
	// contains filtered or unexported fields
}

func OpenMultiVolume added in v0.1.37

func OpenMultiVolume(mainPath string, flag int) (*MultiVolumeReader, int64, error)

func (*MultiVolumeReader) Append added in v0.1.37

func (m *MultiVolumeReader) Append(data []byte) error

func (*MultiVolumeReader) Close added in v0.1.37

func (m *MultiVolumeReader) Close() error

func (*MultiVolumeReader) ReadAt added in v0.1.37

func (m *MultiVolumeReader) ReadAt(p []byte, off int64) (n int, err error)

func (*MultiVolumeReader) WriteAt added in v0.1.37

func (m *MultiVolumeReader) WriteAt(p []byte, off int64) (n int, err error)

type MultiVolumeWriter added in v0.1.37

type MultiVolumeWriter struct {
	// contains filtered or unexported fields
}

func NewMultiVolumeWriter added in v0.1.37

func NewMultiVolumeWriter(mainPath string, splitSize int64) (*MultiVolumeWriter, error)

func (*MultiVolumeWriter) Close added in v0.1.37

func (m *MultiVolumeWriter) Close() error

func (*MultiVolumeWriter) Name added in v0.1.37

func (m *MultiVolumeWriter) Name() string

func (*MultiVolumeWriter) Sync added in v0.1.37

func (m *MultiVolumeWriter) Sync() error

func (*MultiVolumeWriter) Write added in v0.1.37

func (m *MultiVolumeWriter) Write(p []byte) (n int, err error)

type ReadCloser

type ReadCloser struct {
	*tar.Reader
	// contains filtered or unexported fields
}

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader opens a TAR or compressed TAR file (.tar, .tar.gz, .tar.zst, etc.).

func (*ReadCloser) Close

func (rc *ReadCloser) Close() error

func (*ReadCloser) Next added in v0.1.42

func (rc *ReadCloser) Next() (*Header, error)

type Reader

type Reader = tar.Reader

type TarFS

type TarFS struct {
	ArchivePath string
	IndexPath   string
	Index       FileIndex
	// contains filtered or unexported fields
}

func NewFS

func NewFS(archivePath, indexPath string, opts ...FSOption) (*TarFS, error)

NewFS opens a tar archive as a standard Go fs.FS (File System). This enables integration with http.FileServer, fs.WalkDir, etc. If the SQLite index does not exist, it will be generated automatically.

func (*TarFS) Close

func (t *TarFS) Close() error

func (*TarFS) GetComment added in v0.1.40

func (t *TarFS) GetComment() string

GetComment retrieves the global archive comment stored in the F4SS shadow metadata index.

func (*TarFS) Open

func (t *TarFS) Open(name string) (fs.File, error)

func (*TarFS) OpenParallelGzip added in v0.1.138

func (t *TarFS) OpenParallelGzip(concurrency int) (io.ReadCloser, error)

OpenParallelGzip opens the underlying archive of a GZIP-compressed TarFS for sequential reading (e.g. with this package's NewReader, to walk every entry, or with archive/tar), but decompresses it with ParallelDecompressGzipIndexed: independent goroutines inflate the archive's saved GZIDX checkpoints concurrently instead of the one sequential decompressor OpenReader/Extract normally use. It requires the FS to have been opened against a GZIP archive with a saved GZIDX index (see GetGzipIndex); ErrNoGzipIndex is returned when none is available.

concurrency caps how many segments are inflated at once; concurrency <= 0 selects runtime.GOMAXPROCS(0).

func (*TarFS) RecursiveSize

func (t *TarFS) RecursiveSize(name string) (int64, error)

type Updater

type Updater struct {
	// contains filtered or unexported fields
}

Updater adds entries to an existing archive.

Every reader that follows the tar format stops at the end-of-archive blocks, so an appended entry has to take their place. An uncompressed archive is updated in place: it is cut back to where its last entry ends -- which also drops an embedded index (F4SS), since the index no longer describes the archive -- and entries are written from there. Appending the name of an entry the archive already holds removes that entry first.

A compressed archive cannot be cut there: its end-of-archive blocks are inside the compressed stream. Entries written after that stream were read by this package's reader, which carries on past end-of-archive, but not by tar or 7-Zip, which stop where the format says to. So appended entries are kept aside, and Close writes the archive anew: its entries, less those whose names were appended, then the appended ones, in one compressed stream. The embedded index is dropped here too.

func NewUpdater

func NewUpdater(f *os.File, mode AppendMode, opts ...WriterOption) (*Updater, error)

func (*Updater) Append

func (u *Updater) Append(name string, size int64, data []byte) error

Append creates a new file entry in the archive.

func (*Updater) AppendHeader added in v0.1.129

func (u *Updater) AppendHeader(hdr *Header, r io.Reader) error

AppendHeader adds an entry described by hdr -- a file, a directory, a link, a device node or a FIFO -- with the hdr.Size bytes r holds for a file, and nothing read from r for the other types.

func (*Updater) AppendReader added in v0.1.63

func (u *Updater) AppendReader(name string, size int64, r io.Reader) error

AppendReader creates a new file entry in the archive from an io.Reader stream.

func (*Updater) Close

func (u *Updater) Close() error

type WriteCloser

type WriteCloser struct {
	*tar.Writer
	// contains filtered or unexported fields
}

func CreateWriter

func CreateWriter(name string, method uint16, opts ...WriterOption) (*WriteCloser, error)

func (*WriteCloser) Close

func (wc *WriteCloser) Close() error

func (*WriteCloser) SetCompressionLevel added in v0.1.103

func (wc *WriteCloser) SetCompressionLevel(level int) error

func (*WriteCloser) Write added in v0.1.8

func (wc *WriteCloser) Write(p []byte) (int, error)

func (*WriteCloser) WriteHeader added in v0.1.8

func (wc *WriteCloser) WriteHeader(hdr *Header) error

type Writer

type Writer = tar.Writer

type WriterOption added in v0.1.8

type WriterOption func(*writerOptions)

func WithWriterIndex added in v0.1.8

func WithWriterIndex(indexPath string) WriterOption

WithWriterIndex enables on-the-fly indexing during archive creation.

func WithWriterLevel added in v0.1.47

func WithWriterLevel(level int) WriterOption

func WithWriterSplitSize added in v0.1.37

func WithWriterSplitSize(size int64) WriterOption

type XCryptHeader added in v0.1.49

type XCryptHeader struct {
	Version    uint8
	KdfAlgo    uint8
	Cipher     uint8
	Iterations uint32
	Salt       []byte
	IV         []byte
	MAC        []byte
}

XCryptHeader represents the 93-byte binary header for encrypted streams

func (*XCryptHeader) DeriveKey added in v0.1.49

func (h *XCryptHeader) DeriveKey(password string) []byte

func (*XCryptHeader) Encode added in v0.1.49

func (h *XCryptHeader) Encode() []byte

type XzReaderAt added in v0.1.140

type XzReaderAt struct {
	// contains filtered or unexported fields
}

XzReaderAt gives random access to the uncompressed bytes of an .xz file available only as an io.ReaderAt. The file's own index, which lists every block with its compressed and uncompressed size, is read from the end, so the exact uncompressed size is known at once and a read decodes only the block or blocks it falls in. A file written as one block (the default for a single thread) can only be decoded from its start; there a forward read continues the decoder it has and only a read going back starts over (unxed/f4#1678). Safe for concurrent use; calls are serialised.

func NewXzReaderAt added in v0.1.140

func NewXzReaderAt(ra io.ReaderAt, size int64) (*XzReaderAt, error)

NewXzReaderAt opens ra, size bytes of xz data.

func (*XzReaderAt) Close added in v0.1.140

func (x *XzReaderAt) Close() error

Close releases the decoder. The ReaderAt is the caller's.

func (*XzReaderAt) Decoded added in v0.1.140

func (x *XzReaderAt) Decoded() int64

Decoded reports how many uncompressed bytes have been decoded in total.

func (*XzReaderAt) ReadAt added in v0.1.140

func (x *XzReaderAt) ReadAt(p []byte, off int64) (int, error)

ReadAt implements io.ReaderAt over the uncompressed data.

func (*XzReaderAt) Size added in v0.1.140

func (x *XzReaderAt) Size() int64

Size returns the uncompressed size, known from the file's index.

type ZstdReaderAt added in v0.1.139

type ZstdReaderAt struct {
	// contains filtered or unexported fields
}

ZstdReaderAt gives random access to the uncompressed bytes of a zstd file available only as an io.ReaderAt, using the frame boundaries. A zstd file made of several frames (pzstd, a chunked writer, zstd --seekable's data part, f4's own block-per-frame archives) can be entered at any frame: the frames are found by walking their block headers, without decompressing them, and a read decodes only the frame or frames it falls in.

A file that is one frame can only be decoded from its start, since a zstd block depends on the window before it; there a read continues the decoder it already has when it goes forward and starts again only when it goes back. Skippable frames are stepped over. Safe for concurrent use; calls are serialised (unxed/f4#1678).

func NewZstdReaderAt added in v0.1.139

func NewZstdReaderAt(ra io.ReaderAt, size int64) (*ZstdReaderAt, error)

NewZstdReaderAt opens ra, size bytes of zstd data.

func (*ZstdReaderAt) Close added in v0.1.139

func (z *ZstdReaderAt) Close() error

Close releases the decoder. The ReaderAt is the caller's.

func (*ZstdReaderAt) Decoded added in v0.1.139

func (z *ZstdReaderAt) Decoded() int64

Decoded reports how many uncompressed bytes have been decoded in total.

func (*ZstdReaderAt) ReadAt added in v0.1.139

func (z *ZstdReaderAt) ReadAt(p []byte, off int64) (int, error)

ReadAt implements io.ReaderAt over the uncompressed data.

func (*ZstdReaderAt) Size added in v0.1.139

func (z *ZstdReaderAt) Size() int64

Size returns the uncompressed size once every frame is known, else -1.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址