Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
exarch-core
Memory-safe archive extraction and creation library with security validation.
This crate is part of the exarch workspace.
Installation
[]
= "0.11"
[!IMPORTANT] Requires Rust 1.100 or later (Edition 2024).
Usage
use ;
Custom Security Configuration
[!IMPORTANT] Since v0.4.0,
SecurityConfig,AllowedFeatures, andExtractionOptionsare#[non_exhaustive]. UseDefault::default()plus the fluentwith_*builder methods instead of struct literal syntax. Since v0.6.1,ArchiveError,QuotaResource,ArchiveType,CompressionCodec,IssueCategory, andEntryTypeare#[non_exhaustive]too — an exhaustivematchon any of them (including theError Handlingexample below) needs a wildcard_arm.
use ;
let config = default
.with_max_file_size // 100 MB per file
.with_max_total_size // 1 GB total
.with_max_file_count // Max 10k entries (files, directories and links all count)
.with_max_compression_ratio // 50x compression limit
.with_allowed_extensions; // optional allowlist; an empty list is refused, `ExtensionFilter::Any` is the default
Available builders on SecurityConfig: with_max_file_size, with_max_total_size, with_max_compression_ratio, with_max_file_count, with_max_path_depth, with_allowed, with_allow_symlinks, with_allow_hardlinks, with_allow_absolute_paths, with_allow_world_writable, with_preserve_permissions, with_allowed_extensions, with_banned_path_components, with_allow_solid_archives, with_solid_archives, with_solid_limits, with_max_tar_metadata_bytes, with_max_decoder_memory, with_compressed_member_allowance, with_allow_windows_reserved_names, with_zip_consistency, with_parallel_decode, with_repeated_paths. On ExtractionOptions: with_staging (Staging::{InPlace, Atomic, AtomicReplace}), with_existing_files (ExistingFiles::{Skip, Overwrite, Refuse}), with_decode_reuse.
Request Values
Optional inputs (options, progress) are setters on a request value instead of more functions:
use ;
let config = default;
let mut progress = NoopProgress;
let report = new
.with_options
.with_progress
.extract?;
ListRequest, VerifyRequest, SinkExtractRequest and CreateRequest follow the same shape.
Security Features
exarch-core provides defense-in-depth protection against common archive vulnerabilities:
| Protection | Description | Default |
|---|---|---|
| Path traversal | Blocks ../ and absolute paths |
Enabled |
| Symlink attacks | Prevents symlinks escaping extraction directory | Blocked |
| Hardlink attacks | Validates hardlink targets within extraction directory | Blocked |
| Zip bombs | Detects high compression ratios | Enabled (100x limit) |
| TAR metadata bombs | Bounds GNU long-name/long-link and PAX header record reads | Enabled (4 MiB, 16 MiB for permissive()) |
| Permission sanitization | Strips setuid/setgid bits | Enabled |
| Size limits | Configurable file and total size limits | 50 MB / 500 MB |
| Decoder memory | Bounds the xz dictionary and the zstd window (TAR and ZIP) by max_decoder_memory |
Enabled (256 MiB) |
| Compressed members | Bounds gzip members and bzip2 streams by compressed_member_allowance plus one per 16 KiB of output |
Enabled (10,000) |
[!NOTE] The zstd window bound relies on the
zstdcrate being built without itslegacyfeature (the workspace setsdefault-features = false): libzstd decodes pre-v0.8 frames with no window check. The ZIP frame walk refuses such frames as a second line of defense, but a downstream build should keep the feature off.
[!CAUTION] Default configuration blocks symlinks and hardlinks. Enable only when you trust the archive source.
Encrypted Archives
With the encryption feature, ZIP archives that use WinZip AES and 7z archives that use AES-256 (content or header) are read through a Password. It is passed per request with with_password on ExtractRequest, ListRequest, VerifyRequest and SinkExtractRequest, never stored in SecurityConfig, wiped on drop, and printed as Password(..).
use Arc;
use ExtractRequest;
use Password;
use SecurityConfig;
let config = default;
let password = new;
new
.with_password
.extract?;
Failures are Violation::Encrypted under SECURITY_VIOLATION / ENCRYPTED with a typed EncryptionRefusal: PasswordRequired, WrongPassword, AuthenticationFailed, WrongPasswordOrCorrupt, UnusablePassword (a 7z password that is not UTF-8), WeakEncryptionRefused (ZipCrypto, 7z raw-key mode) and KdfCostExceeded. SecurityConfig::max_kdf_work bounds the key derivation of a 7z operation; ZIP AES costs 1000 PBKDF2 rounds per entry, bounded by max_file_count. A password for an archive that is not encrypted is ignored. Residuals: sevenz-rust2 keeps the last derived 7z key in process memory until the next derivation or exit, and a 7z password is converted for sevenz-rust2 without being wiped there.
Repeated Paths and Occupied Destinations
By default an archive that names one path twice keeps the first copy and lets the existing-files policy decide every repeat. with_repeated_paths(RepeatedPaths::Refuse) rejects such an archive instead, as Violation::RepeatedPath.
An entry that would replace something already in the destination is refused with a typed error in every format and on every host: ArchiveError::DestinationOccupied (a file over a directory, a directory over a file, an entry below a file, or any landing under ExistingFiles::Refuse) or an EXISTING_SYMLINK security violation (a file or link over an existing symlink under ExistingFiles::Overwrite). ArchiveError::occupancy() returns the typed details: the occupant kind of every conflicting path and, for a symlink, who made it. An archive path that is not a regular file (a FIFO, a pipe, a device) is refused up front as ArchiveError::SourceNotAccessible.
Archive Creation
Create archives with secure defaults:
use ;
// Simple creation with defaults
let config = default;
let report = create_archive?;
println!;
Output Files
create_archive replaces an existing output atomically once the archive is complete; a failed creation leaves the output as it was. Use CreateRequest with an OutputFile to refuse an existing file or to state the format:
use ;
use CompressionLevel;
let config = default
.with_compression_level
.with_exclude_patterns;
let report = new.create?;
The output is staged in a temporary file in its directory (which must be writable), is never archived into itself, and must be absent, a regular file or a symlink to one.
CreationConfig Options
| Option | Default | Description |
|---|---|---|
follow_symlinks |
false |
Follow symbolic links |
include_hidden |
false |
Include hidden files (.*) |
max_file_size |
unbounded | Skip files above this size (Limit<NonZeroU64>) |
compression_level |
6 |
Compression level (1-9) |
exclude_patterns |
[".git", ".DS_Store", "*.tmp"] |
Glob patterns to exclude |
strip_prefix |
None |
Strip prefix from paths |
preserve_permissions |
true |
Preserve Unix permissions |
parallelism |
Parallelism::Sequential |
Parallelism::Threads(n) compresses ZIP entries on up to n worker threads; the archive bytes do not change, and other formats ignore it |
The walk is sorted by file name and ZIP entries carry the source modification time, so archives are byte-identical across runs and Parallelism modes. A source that changes while it is archived fails with ArchiveError::SourceChanged; FIFOs, sockets and devices are skipped as SkipKind::SpecialFile.
Supported Formats
| Extension | Format | Compression | Extract | Create | List | Verify |
|---|---|---|---|---|---|---|
.tar |
TAR | None | ✅ | ✅ | ✅ | ✅ |
.tar.gz, .tgz |
TAR | Gzip | ✅ | ✅ | ✅ | ✅ |
.tar.bz2, .tbz2 |
TAR | Bzip2 | ✅ | ✅ | ✅ | ✅ |
.tar.xz, .txz |
TAR | XZ | ✅ | ✅ | ✅ | ✅ |
.tar.zst, .tzst |
TAR | Zstd | ✅ | ✅ | ✅ | ✅ |
.zip |
ZIP | Deflate, Deflate64, Bzip2, Zstd | ✅ | ✅ | ✅ | ✅ |
.jar, .war, .ear, .nar, .nbm, .apk, .aab, .ipa, .appx, .msix, .whl, .vsix, .xpi, .epub |
ZIP-family | Deflate, Deflate64, Bzip2, Zstd | ✅ | — | ✅ | ✅ |
.7z |
7z | LZMA/LZMA2 | ✅ | — | ✅ | ✅ |
[!NOTE] ZIP-family formats share the ZIP container but add extra structure — signing (
.apk/.aab/.ipa/.appx/.msix), checksum manifests (.whl), ordering rules (.epub), or descriptor files (.war/.ear/.vsix/.nbm) — which exarch-core doesn't produce. Creation is rejected to avoid silently emitting a bare ZIP with a misleading extension; callers who want that can stateCreatableFormat::ZipwithOutputFile::with_format.
[!NOTE] 7z creation is not yet supported. Solid 7z archives are rejected for security reasons. Password-protected ZIP (WinZip AES) and 7z (AES-256) archives are read when a
Passwordis supplied (featureencryption); ZipCrypto is refused as too weak. A 7z archive holding a Windows reparse point is refused as a whole; a UnixS_IFLNKsymlink is read and validated through the symlink policy, so it is created only with symlinks allowed, and a 7z FIFO, socket or device node is refused.
[!NOTE]
detect_formatfalls back to magic-byte inspection when the file extension is absent, unrecognised, or contradicts the file content. When magic bytes and extension disagree, magic bytes take precedence. Archive creation always uses extension-only detection.
API Overview
Main Types
| Type | Description |
|---|---|
extract_archive |
High-level extraction function |
create_archive |
High-level archive creation function |
list_archive |
List archive contents |
verify_archive |
Verify archive security without extracting |
ExtractRequest |
Extraction with options and progress |
ListRequest |
Listing with ListOptions and progress, from a path or a reader; for_extraction keeps what extraction can reuse |
VerifyRequest |
Verification with VerificationOptions (e.g. decoding the payload to check integrity) and progress |
SinkExtractRequest |
Extraction into an EntrySink |
CreateRequest |
Creation into an OutputFile, a writer or memory |
OutputFile |
The archive file to create: path, replace policy, format |
SecurityConfig |
Security configuration for extraction |
CreationConfig |
Configuration for archive creation |
ExtractionReport |
Extraction statistics, warnings, and skipped-entry counts |
CreationReport |
Creation statistics and results |
ArchiveError |
Error types for all operations |
VerificationIssue |
One typed verify finding with its code, sub-code and message |
Readers, Sinks and Writers
Archives that are not files on disk go through the same validation pipeline. ArchiveReader wraps a TAR stream or a seekable ZIP/7z source, and ArchiveReader::detect / detect_stream pick the format from the leading bytes. ListRequest::list_reader and VerifyRequest::verify_reader list and verify such a source without a temporary directory. SinkExtractRequest takes a SinkOptions and delivers validated entries to an EntrySink instead of a directory; MemorySink keeps them in memory under a MemoryLimit that counts payload, path bytes and a fixed per-entry overhead, and a full sink fails with QuotaExceeded (SinkCapacity), and an error that wrote nothing reports PartialWrites::Discarded. PathModel::Portable makes a sink validate against the strictest rules of every platform on every host. 7z archives are accepted by sinks too.
In the other direction ArchiveWriter with CreateRequest::write builds a TAR (any codec) or ZIP into any Write (and Seek for ZIP) instead of a file; ArchiveWriter::of_type takes a CreatableFormat, so a format that cannot be created is unrepresentable. Every request reports per-entry progress.
Error Handling
use ;
match extract_archive
Performance
Optimized for throughput with:
- Atomic permission setting — Sets Unix permissions during file creation (1 syscall vs 2)
- Streaming extraction (no full archive buffering)
- Reusable 64KB copy buffers per archive
- Buffered I/O for file writes
SmallVecfor hardlink tracking (avoids heap allocation for typical archives)- Fast-path quota checks for unlimited quotas
Throughput targets:
- TAR extraction: 2,136 MB/s (target: 500 MB/s)
- ZIP extraction: 1,444 MB/s (target: 300 MB/s)
Related Crates
exarch-python— Python bindings via PyO3exarch-node— Node.js bindings via napi-rs
MSRV Policy
[!NOTE] Minimum Supported Rust Version: 1.100. MSRV increases are minor version bumps.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.