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 rejects directory entries (typeflag `'5'`) that present a nonzero size
37//! in their ustar header or pax `size` record. pax says that this size should be treated
38//! as a filesystem allocation hint rather than a physical size, but real-world parsers vary
39//! widely in how they handle it (some ignore it, others skip over that number of bytes, etc.).
40//!
41//! - tar-framing does not change a member type because of a path suffix. For example, it preserves
42//! a trailing slash in an effective member path. Before ustar, tar used a trailing slash to
43//! identify a directory. pax does not require an implementation to use this behavior. Therefore,
44//! a path suffix can conflict with the header type. The extraction layer in tar-codec rejects
45//! this conflict.
46//!
47//! - tar-framing rejects negative timestamps as well as timestamps that would exceed the
48//! precision of a `u64`. pax allows both of these, although it notes that portable timestamps
49//! cannot be negative and that tools may reject such timestamps.
50//!
51//! - tar-framing silently removes fractional components from parsed timestamps. Timestamps
52//! are truncated to second precision.
53//!
54//! - tar-framing rejects typeflags that are not explicitly defined in pax. pax says to handle
55//! these as regular files (i.e. assuming their size is a physical size), but this has marginal
56//! benefit in practice.
57//!
58//! - tar-framing rejects `hdrcharset` pax records that aren't UTF-8 or `BINARY`. pax says
59//! that "additional names may be agreed between the originator and the recipient," but
60//! we are the recipient and we don't accept any other `hdrcharset` names.
61//!
62//! ## GNU compatibility
63//!
64//! When decoding GNU-formatted tar streams, tar-framing attempts to follow the
65//! ["Basic Tar Format"] in the GNU docs. Specifically, tar-framing attempts
66//! to follow the rules for the "old GNU" format, i.e. GNU tar's non-pax format.
67//!
68//! tar-framing intentionally only supports a subset of the GNU tar format:
69//!
70//! - The GNU "longname" and "longlink" (`'L'` and `'K'`) typeflags are supported,
71//! with similar path-precedence semantics as their pax record equivalents.
72//!
73//! - Other GNU-specific typeflags are **not** supported whatsoever, and produce
74//! a framing error. This includes sparse files (`'S'`) and multivolume headers
75//! (`'M'`).
76//!
77//! - tar-framing accepts the GNU-specific "base-256" encoding for numbers, but rejects
78//! negative encodings as well as any value that would exceed the precision of a `u64`.
79//! tar-framing also allows "base-256" encodings where the numeric value _would_ fit
80//! into an octal encoding in the alloted buffer/byte span; GNU technically says that
81//! this is reserved for future use.
82//!
83//! ## General compatibility
84//!
85//! Because pax and GNU both use ustar as their baseline, any compatibility aspect of pax
86//! that is derived from ustar also applies during GNU tar decoding.
87//!
88//! tar-framing accepts wholly NUL `mode`, `uid`, `gid`, and `mtime` fields by default for
89//! compatibility with real-world writers in both families. These fields are represented as
90//! missing rather than assigned a value. This can be disabled with
91//! [`StreamPolicy::allow_all_nul_numeric_fields`].
92//!
93//! Separately, higher-level crates (like tar-codec) may choose to apply additional
94//! restrictions when processing logical archive members. For example, a consumer
95//! of tar-framing may choose to reject vendor-specific pax records, or member names
96//! that contain forbidden characters, or any other additional restriction.
97//!
98//! [POSIX.1-2024]: https://pubs.opengroup.org/onlinepubs/9799919799/
99//! [pax specification]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/pax.html
100//! [POSIX.1-2004]: https://pubs.opengroup.org/onlinepubs/009695399/toc.htm
101//! ["Basic Tar Format"]: https://www.gnu.org/software/tar/manual/html_node/Standard.html
102
103use std::fmt;
104
105mod error;
106pub mod header;
107pub mod logical;
108mod pax;
109pub mod stream;
110#[cfg(test)]
111mod test_support;
112pub mod write;
113
114pub use error::{FrameError, FrameErrorInner};
115pub use pax::{
116 HdrCharset, PaxError, PaxExtension, PaxKeyword, PaxRecord, PaxState, PaxString, PaxValue,
117};
118pub use stream::StreamPolicy;
119
120/// The size of a logical tar record.
121pub const BLOCK_SIZE: usize = 512;
122
123/// The default maximum size in bytes of one local or global pax extension.
124///
125/// This is 256 KiB.
126pub const DEFAULT_MAX_PAX_EXTENSION_SIZE: u64 = 256 * 1024;
127
128/// The default maximum total payload size of all global pax extensions.
129///
130/// This limit applies to the full archive. It does not reset after an ordinary
131/// member.
132///
133/// This is 1 MiB.
134pub const DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE: u64 = 4 * DEFAULT_MAX_PAX_EXTENSION_SIZE;
135
136/// The default maximum size in bytes of one GNU metadata extension.
137///
138/// This is 128 KiB.
139pub const DEFAULT_MAX_GNU_EXTENSION_SIZE: u64 = 128 * 1024;
140
141/// A single tar block.
142pub type Block = [u8; BLOCK_SIZE];
143
144/// An automatically detected, mutually exclusive tar archive family.
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum ArchiveFormat {
147 /// pax ustar headers with optional pax extended headers.
148 Pax,
149 /// Old GNU tar headers with optional `L` and `K` extension entries.
150 Gnu,
151}
152
153impl fmt::Display for ArchiveFormat {
154 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
155 match self {
156 Self::Pax => formatter.write_str("pax"),
157 Self::Gnu => formatter.write_str("GNU"),
158 }
159 }
160}
161
162/// The scope of a pax extended header.
163#[derive(Clone, Copy, Debug, Eq, PartialEq)]
164pub enum PaxKind {
165 /// A typeflag `x` header applying to the next ordinary member.
166 Local,
167 /// A typeflag `g` header updating persistent global values.
168 Global,
169}
170
171/// The supported GNU metadata extension kinds.
172#[derive(Clone, Copy, Debug, Eq, PartialEq)]
173pub enum GnuKind {
174 /// A typeflag `L` extension giving a long name for the next member.
175 LongName,
176 /// A typeflag `K` extension giving a long link name for the next member.
177 LongLink,
178}
179
180/// A supported ordinary ustar member type.
181///
182/// These are shared across both pax and GNU tar streams.
183#[derive(Clone, Copy, Debug, Eq, PartialEq)]
184pub enum UstarKind {
185 /// A regular file (`'0'` or NUL).
186 Regular,
187 /// A hard link (`'1'`).
188 HardLink,
189 /// A symbolic link (`'2'`).
190 SymbolicLink,
191 /// A character device (`'3'`).
192 CharacterDevice,
193 /// A block device (`'4'`).
194 BlockDevice,
195 /// A directory (`'5'`).
196 Directory,
197 /// A FIFO (`'6'`).
198 Fifo,
199 /// A contiguous file (`'7'`).
200 Contiguous,
201}