Skip to main content

exarch_core/error/
tar_ambiguity.rs

1//! Typed refusals for TAR headers that different TAR readers resolve
2//! differently.
3
4use crate::closed_enum::closed_enum;
5use crate::formats::tar_extension_headers::MAX_PAX_RECORD_BYTES;
6
7closed_enum! {
8    /// A numeric header field that must be plain.
9    ///
10    /// # Examples
11    ///
12    /// ```
13    /// use exarch_core::TarHeaderField;
14    ///
15    /// assert_eq!(TarHeaderField::Checksum.to_string(), "checksum");
16    /// ```
17    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18    #[non_exhaustive]
19    pub enum TarHeaderField {
20        /// The `size` field.
21        Size => "size",
22        /// The `chksum` field.
23        Checksum => "checksum",
24    }
25}
26
27closed_enum! {
28    /// A TAR entry type that has no data and must not declare a payload.
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// use exarch_core::TarNonRegularKind;
34    ///
35    /// assert_eq!(TarNonRegularKind::Hardlink.to_string(), "hardlink");
36    /// ```
37    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38    #[non_exhaustive]
39    pub enum TarNonRegularKind {
40        /// A directory entry (`5`).
41        Directory => "directory",
42        /// A symbolic link entry (`2`).
43        Symlink => "symlink",
44        /// A hard link entry (`1`).
45        Hardlink => "hardlink",
46    }
47}
48
49impl TarNonRegularKind {
50    /// The kind of `entry_type`, or `None` for a type that may carry data.
51    pub(crate) const fn of(entry_type: tar::EntryType) -> Option<Self> {
52        match entry_type {
53            tar::EntryType::Directory => Some(Self::Directory),
54            tar::EntryType::Symlink => Some(Self::Symlink),
55            tar::EntryType::Link => Some(Self::Hardlink),
56            _ => None,
57        }
58    }
59}
60
61/// An extension header whose body the `tar` crate merges into the next entry.
62///
63/// # Examples
64///
65/// ```
66/// use exarch_core::TarExtensionKind;
67///
68/// assert_eq!(TarExtensionKind::Pax.typeflag(), b'x');
69/// assert_eq!(TarExtensionKind::LongName.to_string(), "GNU long name");
70/// ```
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum TarExtensionKind {
74    /// A local PAX header (`x`).
75    Pax,
76    /// A GNU long name record (`L`).
77    LongName,
78    /// A GNU long link record (`K`).
79    LongLink,
80}
81
82impl TarExtensionKind {
83    /// The typeflag byte that introduces this kind of header.
84    #[must_use]
85    pub const fn typeflag(self) -> u8 {
86        match self {
87            Self::Pax => b'x',
88            Self::LongName => b'L',
89            Self::LongLink => b'K',
90        }
91    }
92
93    const fn name(self) -> &'static str {
94        match self {
95            Self::Pax => "PAX",
96            Self::LongName => "GNU long name",
97            Self::LongLink => "GNU long link",
98        }
99    }
100
101    const fn entry_type_name(self) -> &'static str {
102        match self {
103            Self::Pax => "XHeader",
104            Self::LongName => "GNULongName",
105            Self::LongLink => "GNULongLink",
106        }
107    }
108}
109
110impl std::fmt::Display for TarExtensionKind {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.write_str(self.name())
113    }
114}
115
116/// The path-like PAX key that a GNU long record duplicates.
117///
118/// # Examples
119///
120/// ```
121/// use exarch_core::TarPathKey;
122///
123/// assert_eq!(TarPathKey::LinkPath.to_string(), "linkpath");
124/// ```
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum TarPathKey {
128    /// The `path` key, which a GNU long name record also describes.
129    Path,
130    /// The `linkpath` key, which a GNU long link record also describes.
131    LinkPath,
132}
133
134impl TarPathKey {
135    /// The key as a PAX record spells it.
136    #[must_use]
137    pub const fn as_str(self) -> &'static str {
138        match self {
139            Self::Path => "path",
140            Self::LinkPath => "linkpath",
141        }
142    }
143
144    const fn long_record(self) -> &'static str {
145        match self {
146            Self::Path => "name",
147            Self::LinkPath => "link",
148        }
149    }
150}
151
152impl std::fmt::Display for TarPathKey {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.write_str(self.as_str())
155    }
156}
157
158/// A TAR header or extension-header construct that readers such as `bsdtar`
159/// and Python `tarfile` resolve differently from the `tar` crate.
160///
161/// The `String` payloads named `key` are the record key decoded lossily and
162/// truncated to 256 bytes. The `path` payloads are the entry path decoded
163/// lossily and not truncated. Both exist for display only: never compare them
164/// with a real key or path.
165///
166/// # Examples
167///
168/// ```
169/// use exarch_core::ArchiveError;
170/// use exarch_core::TarAmbiguity;
171///
172/// let err = ArchiveError::TarAmbiguity(TarAmbiguity::ChecksumMismatch);
173/// assert_eq!(
174///     err.to_string(),
175///     "invalid archive: ambiguous TAR header: header checksum does not match the header bytes"
176/// );
177/// ```
178#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub enum TarAmbiguity {
181    /// A PAX record is not a well-formed `"<len> <key>=<value>\n"` record.
182    MalformedRecord,
183
184    /// A PAX record has an empty key.
185    EmptyKey,
186
187    /// A PAX record is longer than the 999999 bytes `libarchive` accepts.
188    OversizedRecord {
189        /// Lossy, truncated key; for display only.
190        key: String,
191    },
192
193    /// A PAX header repeats a key, so readers disagree on which value wins.
194    DuplicateRecord {
195        /// Lossy, truncated key; for display only.
196        key: String,
197    },
198
199    /// A PAX record (`GNU.sparse.*`, `SCHILY.realsize`) changes how the entry
200    /// data is read, which not every reader supports.
201    UnsupportedRecord {
202        /// Lossy, truncated key; for display only.
203        key: String,
204    },
205
206    /// A PAX `size` record is not a decimal number.
207    InvalidSize,
208
209    /// A global PAX header carries `path`, `linkpath` or `size`, which some
210    /// readers apply to every later entry.
211    GlobalOverride {
212        /// Lossy, truncated key; for display only.
213        key: String,
214    },
215
216    /// A global PAX header is larger than the metadata limit.
217    GlobalTooLarge {
218        /// Declared size of the header body.
219        size: u64,
220        /// Configured metadata limit.
221        limit: u64,
222    },
223
224    /// A global PAX header follows a local PAX header.
225    LocalBeforeGlobal,
226
227    /// A global PAX header follows a GNU long name or link record.
228    LongRecordBeforeGlobal,
229
230    /// A PAX record and a GNU long record both describe the same entry.
231    StackedLongRecord {
232        /// The PAX key that the GNU long record duplicates.
233        key: TarPathKey,
234    },
235
236    /// A PAX `size` record shares an extension chain with a GNU long name or
237    /// link record, so readers disagree on where the entry's data ends.
238    StackedSizeRecord,
239
240    /// An `x`, `L` or `K` header without a ustar or GNU magic.
241    UnrecognizedHeader {
242        /// The kind of extension header.
243        kind: TarExtensionKind,
244    },
245
246    /// A GNU sparse entry.
247    SparseEntry,
248
249    /// A header field is not a plain octal or base-256 number.
250    NonCanonicalNumber {
251        /// The offending field.
252        field: TarHeaderField,
253    },
254
255    /// A header has a `prefix` field but no ustar magic.
256    PrefixWithoutUstar,
257
258    /// The header checksum does not match the header bytes.
259    ChecksumMismatch,
260
261    /// An entry is preceded by two extension headers of the same kind.
262    DuplicateExtensionHeader {
263        /// The repeated kind.
264        kind: TarExtensionKind,
265    },
266
267    /// The bytes read before an entry do not end at the position of its
268    /// header.
269    WindowMismatch,
270
271    /// The padding after an extension header body holds non-zero bytes, which
272    /// some readers parse as further records.
273    NonZeroPadding,
274
275    /// A GNU long name or link body is not a single NUL-terminated string.
276    MalformedLongRecord {
277        /// The kind of extension header.
278        kind: TarExtensionKind,
279    },
280
281    /// A directory, symbolic link or hard link entry declares a payload, which
282    /// some readers skip as data and others parse as further headers.
283    NonRegularPayload {
284        /// The entry type.
285        kind: TarNonRegularKind,
286        /// Declared payload size in bytes.
287        size: u64,
288        /// Lossy entry path; for display only.
289        path: String,
290    },
291
292    /// A regular entry whose name ends in `/` declares a payload, so it is a
293    /// directory to some readers and a file to others.
294    DirectoryNamedPayload {
295        /// Declared payload size in bytes.
296        size: u64,
297        /// Lossy entry path; for display only.
298        path: String,
299    },
300}
301
302impl std::fmt::Display for TarAmbiguity {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        match self {
305            Self::MalformedRecord => f.write_str("malformed PAX record"),
306            Self::EmptyKey => f.write_str("PAX record with an empty key"),
307            Self::OversizedRecord { key } => write!(
308                f,
309                "PAX record {key:?} is longer than {MAX_PAX_RECORD_BYTES} bytes"
310            ),
311            Self::DuplicateRecord { key } => write!(f, "duplicate PAX record {key:?}"),
312            Self::UnsupportedRecord { key } => write!(f, "PAX record {key:?} is not supported"),
313            Self::InvalidSize => f.write_str("PAX `size` record is not a decimal number"),
314            Self::GlobalOverride { key } => {
315                write!(f, "global PAX record {key:?} would apply to later entries")
316            }
317            Self::GlobalTooLarge { size, limit } => write!(
318                f,
319                "global PAX header ({size} bytes) exceeds the metadata limit of {limit} bytes"
320            ),
321            Self::LocalBeforeGlobal => f.write_str("global PAX header follows a local PAX header"),
322            Self::LongRecordBeforeGlobal => {
323                f.write_str("global PAX header follows a GNU long name or link record")
324            }
325            Self::StackedLongRecord { key } => write!(
326                f,
327                "PAX `{key}` record and a GNU long {} record both describe the same entry",
328                key.long_record()
329            ),
330            Self::StackedSizeRecord => f.write_str(
331                "PAX `size` record and a GNU long name or link record share one extension chain",
332            ),
333            Self::UnrecognizedHeader { kind } => write!(
334                f,
335                "extension header {} lacks a ustar or GNU magic",
336                kind.entry_type_name()
337            ),
338            Self::SparseEntry => f.write_str("GNU sparse entries are not supported"),
339            Self::NonCanonicalNumber { field } => write!(
340                f,
341                "header {field} field is not a plain octal or base-256 number"
342            ),
343            Self::PrefixWithoutUstar => {
344                f.write_str("header carries a prefix field without a ustar magic")
345            }
346            Self::ChecksumMismatch => {
347                f.write_str("header checksum does not match the header bytes")
348            }
349            Self::DuplicateExtensionHeader { kind } => {
350                write!(f, "duplicate {kind} extension header")
351            }
352            Self::NonZeroPadding => {
353                f.write_str("extension header body is followed by non-zero padding")
354            }
355            Self::MalformedLongRecord { kind } => {
356                write!(
357                    f,
358                    "{kind} extension header is not a single NUL-terminated string"
359                )
360            }
361            Self::WindowMismatch => {
362                f.write_str("bytes read before the entry do not match the position of its header")
363            }
364            Self::NonRegularPayload { kind, size, path } => {
365                write!(f, "{kind} entry declares a {size} byte payload: {path}")
366            }
367            Self::DirectoryNamedPayload { size, path } => {
368                write!(
369                    f,
370                    "file entry with a directory name carries {size} bytes: {path}"
371                )
372            }
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn payload_messages_are_pinned() {
383        let directory = TarAmbiguity::NonRegularPayload {
384            kind: TarNonRegularKind::Directory,
385            size: 1024,
386            path: "x/".into(),
387        };
388        assert_eq!(
389            directory.to_string(),
390            "directory entry declares a 1024 byte payload: x/"
391        );
392        let named = TarAmbiguity::DirectoryNamedPayload {
393            size: 3,
394            path: "d/".into(),
395        };
396        let hardlink = TarAmbiguity::NonRegularPayload {
397            kind: TarNonRegularKind::Hardlink,
398            size: 2,
399            path: "l".into(),
400        };
401        assert_eq!(
402            hardlink.to_string(),
403            "hardlink entry declares a 2 byte payload: l"
404        );
405        assert_eq!(
406            named.to_string(),
407            "file entry with a directory name carries 3 bytes: d/"
408        );
409    }
410
411    #[test]
412    fn non_regular_kinds_display_in_lower_case_like_their_siblings() {
413        use crate::error::zip_inconsistency::ZipNonRegularKind;
414
415        let spellings: Vec<_> = TarNonRegularKind::ALL
416            .iter()
417            .map(ToString::to_string)
418            .collect();
419        assert_eq!(spellings, ["directory", "symlink", "hardlink"]);
420        for kind in TarNonRegularKind::ALL {
421            assert_eq!(kind.as_str(), kind.to_string());
422            assert_eq!(kind.to_string(), kind.to_string().to_lowercase());
423        }
424        assert_eq!(
425            TarNonRegularKind::Directory.to_string(),
426            ZipNonRegularKind::Directory.to_string()
427        );
428    }
429
430    #[test]
431    fn a_symlink_payload_message_uses_the_lower_case_kind() {
432        let symlink = TarAmbiguity::NonRegularPayload {
433            kind: TarNonRegularKind::Symlink,
434            size: 9,
435            path: "s".into(),
436        };
437        assert_eq!(
438            symlink.to_string(),
439            "symlink entry declares a 9 byte payload: s"
440        );
441    }
442
443    #[test]
444    fn extension_kind_messages_are_pinned() {
445        let cases = [
446            (TarExtensionKind::Pax, "PAX", "XHeader"),
447            (TarExtensionKind::LongName, "GNU long name", "GNULongName"),
448            (TarExtensionKind::LongLink, "GNU long link", "GNULongLink"),
449        ];
450        for (kind, name, entry_type) in cases {
451            assert_eq!(kind.to_string(), name);
452            assert_eq!(
453                TarAmbiguity::DuplicateExtensionHeader { kind }.to_string(),
454                format!("duplicate {name} extension header")
455            );
456            assert_eq!(
457                TarAmbiguity::MalformedLongRecord { kind }.to_string(),
458                format!("{name} extension header is not a single NUL-terminated string")
459            );
460            assert_eq!(
461                TarAmbiguity::UnrecognizedHeader { kind }.to_string(),
462                format!("extension header {entry_type} lacks a ustar or GNU magic")
463            );
464        }
465    }
466}