Skip to main content

tar_framing/
lib.rs

1//! Low level framing of tar streams.
2//!
3//! This crate provides two APIs:
4//!
5//! - [`stream`] is a low-level, lossless per-block framing API.
6//! - [`logical`] is a medium-level, assembled member reader API.
7//!
8//! [`stream`] provides the basic static machine enforcement for a tar
9//! stream, including ensuring that any given stream is either strictly
10//! pax *or* GNU and not a mix of the two. [`logical`] is layered on top
11//! of [`stream`] and provides APIs for accessing the "effective" metadata
12//! for each assembled member.
13//!
14//! This crate tries to faithfully extract pax or GNU entries without mixing the
15//! two. See the sections below for compatibility notes.
16//!
17//! ## pax compatibility
18//!
19//! When decoding pax-formatted tar streams, tar-framing attempts to conform to
20//! pax as specified in [POSIX.1-2024], i.e. "issue 8" of the POSIX specification.
21//! See the [pax specification] for full details.
22//!
23//! However, there are a few small deviations from a pedantic reading of [POSIX.1-2024]
24//! that are worth noting:
25//!
26//! - tar-framing permits a `ctime` pax record, despite not being specified in [POSIX.1-2024].
27//!   The ctime record was removed from pax in [POSIX.1-2004] (which is itself a minor edit
28//!   of POSIX.1-2001). However, many real-world pax archives still contain it, and its
29//!   presence does not compromise or introduce ambiguity during framing.
30//!
31//! - tar-framing permits implementation-defined vendor pax records to contain arbitrary
32//!   bytes, including invalid UTF-8. POSIX requires extended-header values to default
33//!   to UTF-8, but real-world writers including star, GNU tar, and libarchive use raw
34//!   `SCHILY.xattr.*` values. Standard and reserved pax record values remain strict UTF-8.
35//!
36//! - tar-framing requires multi-digit pax `size` values to start with a nonzero digit.
37//!   POSIX specifies decimal, so `0777` means 777 bytes. However,
38//!   some misbehaving parsers will interpret `0777` as octal (511)
39//!   instead, so tar-framing rejects this form.
40//!
41//! - tar-framing rejects directory entries (typeflag `'5'`) that present a nonzero size
42//!   in their ustar header or pax `size` record. pax says that this size should be treated
43//!   as a filesystem allocation hint rather than a physical size, but real-world parsers vary
44//!   widely in how they handle it (some ignore it, others skip over that number of bytes, etc.).
45//!
46//! - By default, tar-framing rejects hard links (typeflag `'1'`) with a nonzero size in
47//!   their ustar header or effective pax `size` record. Readers disagree on whether the
48//!   block after such a link contains payload bytes or the next member header. To read
49//!   archives written with `pax -o linkdata`, enable [`StreamPolicy::allow_pax_hardlink_linkdata`].
50//!
51//! - tar-framing does not change a member type because of a path suffix. For example, it preserves
52//!   a trailing slash in an effective member path. Before ustar, tar used a trailing slash to
53//!   identify a directory. pax does not require an implementation to use this behavior. Therefore,
54//!   a path suffix can conflict with the header type. The extraction layer in tar-codec rejects
55//!   this conflict.
56//!
57//! - tar-framing rejects negative timestamps as well as timestamps that would exceed the
58//!   precision of a `u64`. pax allows both of these, although it notes that portable timestamps
59//!   cannot be negative and that tools may reject such timestamps.
60//!
61//! - tar-framing silently removes fractional components from parsed timestamps. Timestamps
62//!   are truncated to second precision.
63//!
64//! - tar-framing rejects typeflags that are not explicitly defined in pax. pax says to handle
65//!   these as regular files (i.e. assuming their size is a physical size), but this has marginal
66//!   benefit in practice.
67//!
68//! - tar-framing rejects `hdrcharset` pax records that aren't UTF-8 or `BINARY`. pax says
69//!   that "additional names may be agreed between the originator and the recipient," but
70//!   we are the recipient and we don't accept any other `hdrcharset` names.
71//!
72//! ## GNU compatibility
73//!
74//! When decoding GNU-formatted tar streams, tar-framing attempts to follow the
75//! ["Basic Tar Format"] in the GNU docs. Specifically, tar-framing attempts
76//! to follow the rules for the "old GNU" format, i.e. GNU tar's non-pax format.
77//!
78//! tar-framing intentionally only supports a subset of the GNU tar format:
79//!
80//! - The GNU "longname" and "longlink" (`'L'` and `'K'`) typeflags are supported,
81//!   with similar path-precedence semantics as their pax record equivalents.
82//!
83//! - Other GNU-specific typeflags are **not** supported whatsoever, and produce
84//!   a framing error. This includes sparse files (`'S'`) and multivolume headers
85//!   (`'M'`).
86//!
87//! - tar-framing accepts the GNU-specific "base-256" encoding for numbers, but rejects
88//!   negative encodings as well as any value that would exceed the precision of a `u64`.
89//!   tar-framing also allows "base-256" encodings where the numeric value _would_ fit
90//!   into an octal encoding in the alloted buffer/byte span; GNU technically says that
91//!   this is reserved for future use.
92//!
93//! ## General compatibility
94//!
95//! Because pax and GNU both use ustar as their baseline, any compatibility aspect of pax
96//! that is derived from ustar also applies during GNU tar decoding.
97//!
98//! tar-framing does not support tar families other than pax and GNU. That includes the "legacy" (V7) and star families.
99//!
100//! Only hard links and symbolic links may carry a link target in the ordinary
101//! `linkname` field, a pax `linkpath` record, or a GNU long-link extension.
102//! A pax deletion cannot hide a populated `linkname` on a non-link member.
103//!
104//! tar-framing accepts wholly NUL `mode`, `uid`, `gid`, and `mtime` fields by default for
105//! compatibility with real-world writers in both families. These fields are represented as
106//! missing rather than assigned a value. This can be disabled with
107//! [`StreamPolicy::allow_all_nul_numeric_fields`].
108//!
109//! By default, tar-framing follows a strict reading of pax and requires the `uname` and `gname`
110//! header fields to be NUL terminated (the `magic` field is also required to be NUL terminated, but
111//! is so by definition). However, some encoders will incorrectly pack a 32-byte value into
112//! these fields, rather than honoring the 31-byte + NUL terminator limit.
113//! CPython's `tarfile` in particular does this.
114//! This can be disabled with [`StreamPolicy::allow_header_uname_and_gname_without_terminator`].
115//!
116//! Separately, higher-level crates (like tar-codec) may choose to apply additional
117//! restrictions when processing logical archive members. For example, a consumer
118//! of tar-framing may choose to reject vendor-specific pax records, or member names
119//! that contain forbidden characters, or any other additional restriction.
120//!
121//! [POSIX.1-2024]: https://pubs.opengroup.org/onlinepubs/9799919799/
122//! [pax specification]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/pax.html
123//! [POSIX.1-2004]: https://pubs.opengroup.org/onlinepubs/009695399/toc.htm
124//! ["Basic Tar Format"]: https://www.gnu.org/software/tar/manual/html_node/Standard.html
125
126use std::fmt;
127
128mod error;
129pub mod header;
130pub mod logical;
131mod pax;
132pub mod stream;
133#[cfg(test)]
134mod test_support;
135pub mod write;
136
137pub use error::{FrameError, FrameErrorInner};
138pub use pax::{
139    HdrCharset, PaxError, PaxExtension, PaxKeyword, PaxRecord, PaxState, PaxString, PaxValue,
140};
141pub use stream::StreamPolicy;
142
143/// The size of a logical tar record.
144pub const BLOCK_SIZE: usize = 512;
145
146/// The default maximum size in bytes of one local or global pax extension.
147///
148/// This is 256 KiB.
149pub const DEFAULT_MAX_PAX_EXTENSION_SIZE: u64 = 256 * 1024;
150
151/// The default maximum total payload size of all global pax extensions.
152///
153/// This limit applies to the full archive. It does not reset after an ordinary
154/// member.
155///
156/// This is 1 MiB.
157pub const DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE: u64 = 4 * DEFAULT_MAX_PAX_EXTENSION_SIZE;
158
159/// The default maximum size in bytes of one GNU metadata extension.
160///
161/// This is 128 KiB.
162pub const DEFAULT_MAX_GNU_EXTENSION_SIZE: u64 = 128 * 1024;
163
164/// A single tar block.
165pub type Block = [u8; BLOCK_SIZE];
166
167/// An automatically detected, mutually exclusive tar archive family.
168#[derive(Clone, Copy, Debug, Eq, PartialEq)]
169pub enum ArchiveFormat {
170    /// pax ustar headers with optional pax extended headers.
171    Pax,
172    /// Old GNU tar headers with optional `L` and `K` extension entries.
173    Gnu,
174}
175
176impl fmt::Display for ArchiveFormat {
177    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            Self::Pax => formatter.write_str("pax"),
180            Self::Gnu => formatter.write_str("GNU"),
181        }
182    }
183}
184
185/// The scope of a pax extended header.
186#[derive(Clone, Copy, Debug, Eq, PartialEq)]
187pub enum PaxKind {
188    /// A typeflag `x` header applying to the next ordinary member.
189    Local,
190    /// A typeflag `g` header updating persistent global values.
191    Global,
192}
193
194/// The supported GNU metadata extension kinds.
195#[derive(Clone, Copy, Debug, Eq, PartialEq)]
196pub enum GnuKind {
197    /// A typeflag `L` extension giving a long name for the next member.
198    LongName,
199    /// A typeflag `K` extension giving a long link name for the next member.
200    LongLink,
201}
202
203/// A supported ordinary ustar member type.
204///
205/// These are shared across both pax and GNU tar streams.
206#[derive(Clone, Copy, Debug, Eq, PartialEq)]
207pub enum UstarKind {
208    /// A regular file (`'0'` or NUL).
209    Regular,
210    /// A hard link (`'1'`).
211    HardLink,
212    /// A symbolic link (`'2'`).
213    SymbolicLink,
214    /// A character device (`'3'`).
215    CharacterDevice,
216    /// A block device (`'4'`).
217    BlockDevice,
218    /// A directory (`'5'`).
219    Directory,
220    /// A FIFO (`'6'`).
221    Fifo,
222    /// A contiguous file (`'7'`).
223    Contiguous,
224}