exarch-core 0.12.0

Memory-safe archive extraction library with security validation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Typed refusals for TAR headers that different TAR readers resolve
//! differently.

use crate::closed_enum::closed_enum;
use crate::formats::tar_extension_headers::MAX_PAX_RECORD_BYTES;

closed_enum! {
    /// A numeric header field that must be plain.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::TarHeaderField;
    ///
    /// assert_eq!(TarHeaderField::Checksum.to_string(), "checksum");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum TarHeaderField {
        /// The `size` field.
        Size => "size",
        /// The `chksum` field.
        Checksum => "checksum",
        /// A GNU sparse map `offset` field.
        SparseOffset => "sparse offset",
        /// A GNU sparse map `numbytes` field.
        SparseLength => "sparse length",
        /// The GNU sparse `realsize` field.
        RealSize => "real size",
    }
}

closed_enum! {
    /// A TAR entry type that has no data and must not declare a payload.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::TarNonRegularKind;
    ///
    /// assert_eq!(TarNonRegularKind::Hardlink.to_string(), "hardlink");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum TarNonRegularKind {
        /// A directory entry (`5`).
        Directory => "directory",
        /// A symbolic link entry (`2`).
        Symlink => "symlink",
        /// A hard link entry (`1`).
        Hardlink => "hardlink",
        /// A GNU volume label entry (`V`).
        VolumeLabel => "volume label",
    }
}

impl TarNonRegularKind {
    /// The kind of `entry_type`, or `None` for a type that may carry data.
    pub(crate) fn of(entry_type: tar::EntryType) -> Option<Self> {
        match entry_type {
            tar::EntryType::Directory => Some(Self::Directory),
            tar::EntryType::Symlink => Some(Self::Symlink),
            tar::EntryType::Link => Some(Self::Hardlink),
            other if other.as_byte() == b'V' => Some(Self::VolumeLabel),
            _ => None,
        }
    }
}

closed_enum! {
    /// What is wrong with the map of an old GNU sparse entry that
    /// [`TarSparsePolicy::Expand`](crate::TarSparsePolicy) refuses.
    ///
    /// The map is accepted only when `bsdtar`, Python `tarfile` and the `tar`
    /// crate read it to the same bytes; each variant names one rule it breaks.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::SparseMapDefect;
    ///
    /// assert_eq!(SparseMapDefect::PartialSlot.to_string(), "partial slot");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum SparseMapDefect {
        /// A map slot has only one of its two fields set.
        PartialSlot => "partial slot",
        /// A used slot follows an unused one.
        SlotAfterEnd => "slot after the end of the map",
        /// An extended flag is neither zero nor one.
        ExtendedFlag => "invalid extended flag",
        /// The extension chain does not match the extended flags.
        ExtensionChain => "extension chain mismatch",
        /// A used slot in an extension block has a zero offset.
        ZeroOffsetExtension => "zero offset in an extension block",
        /// A zero-length slot is not the last one.
        InteriorZeroLength => "zero-length slot before the end",
    }
}

/// An extension header whose body the `tar` crate merges into the next entry.
///
/// # Examples
///
/// ```
/// use exarch_core::TarExtensionKind;
///
/// assert_eq!(TarExtensionKind::Pax.typeflag(), b'x');
/// assert_eq!(TarExtensionKind::LongName.to_string(), "GNU long name");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarExtensionKind {
    /// A local PAX header (`x`).
    Pax,
    /// A GNU long name record (`L`).
    LongName,
    /// A GNU long link record (`K`).
    LongLink,
}

impl TarExtensionKind {
    /// The typeflag byte that introduces this kind of header.
    #[must_use]
    pub const fn typeflag(self) -> u8 {
        match self {
            Self::Pax => b'x',
            Self::LongName => b'L',
            Self::LongLink => b'K',
        }
    }

    const fn name(self) -> &'static str {
        match self {
            Self::Pax => "PAX",
            Self::LongName => "GNU long name",
            Self::LongLink => "GNU long link",
        }
    }

    const fn entry_type_name(self) -> &'static str {
        match self {
            Self::Pax => "XHeader",
            Self::LongName => "GNULongName",
            Self::LongLink => "GNULongLink",
        }
    }
}

impl std::fmt::Display for TarExtensionKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

/// The path-like PAX key that a GNU long record duplicates.
///
/// # Examples
///
/// ```
/// use exarch_core::TarPathKey;
///
/// assert_eq!(TarPathKey::LinkPath.to_string(), "linkpath");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarPathKey {
    /// The `path` key, which a GNU long name record also describes.
    Path,
    /// The `linkpath` key, which a GNU long link record also describes.
    LinkPath,
}

impl TarPathKey {
    /// The key as a PAX record spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Path => "path",
            Self::LinkPath => "linkpath",
        }
    }

    const fn long_record(self) -> &'static str {
        match self {
            Self::Path => "name",
            Self::LinkPath => "link",
        }
    }
}

impl std::fmt::Display for TarPathKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A TAR header or extension-header construct that readers such as `bsdtar`
/// and Python `tarfile` resolve differently from the `tar` crate.
///
/// The `String` payloads named `key` are the record key decoded lossily and
/// truncated to 256 bytes. The `path` payloads are the entry path decoded
/// lossily and not truncated. Both exist for display only: never compare them
/// with a real key or path.
///
/// # Examples
///
/// ```
/// use exarch_core::ArchiveError;
/// use exarch_core::TarAmbiguity;
///
/// let err = ArchiveError::TarAmbiguity(TarAmbiguity::ChecksumMismatch);
/// assert_eq!(
///     err.to_string(),
///     "invalid archive: ambiguous TAR header: header checksum does not match the header bytes"
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarAmbiguity {
    /// A PAX record is not a well-formed `"<len> <key>=<value>\n"` record.
    MalformedRecord,

    /// A PAX record has an empty key.
    EmptyKey,

    /// A PAX record is longer than the 999999 bytes `libarchive` accepts.
    OversizedRecord {
        /// Lossy, truncated key; for display only.
        key: String,
    },

    /// A PAX header repeats a key, so readers disagree on which value wins.
    DuplicateRecord {
        /// Lossy, truncated key; for display only.
        key: String,
    },

    /// A PAX record (`GNU.sparse.*`, `SCHILY.realsize`, `SUN.holesdata`)
    /// changes how the entry data is read, which not every reader supports.
    UnsupportedRecord {
        /// Lossy, truncated key; for display only.
        key: String,
    },

    /// A PAX `size` record is not a decimal number.
    InvalidSize,

    /// A global PAX header carries `path`, `linkpath` or `size`, which some
    /// readers apply to every later entry.
    GlobalOverride {
        /// Lossy, truncated key; for display only.
        key: String,
    },

    /// A global PAX header is larger than the metadata limit.
    GlobalTooLarge {
        /// Declared size of the header body.
        size: u64,
        /// Configured metadata limit.
        limit: u64,
    },

    /// A global PAX header follows a local PAX header.
    LocalBeforeGlobal,

    /// A global PAX header follows a GNU long name or link record.
    LongRecordBeforeGlobal,

    /// A PAX record and a GNU long record both describe the same entry.
    StackedLongRecord {
        /// The PAX key that the GNU long record duplicates.
        key: TarPathKey,
    },

    /// A PAX `size` record shares an extension chain with a GNU long name or
    /// link record, so readers disagree on where the entry's data ends.
    StackedSizeRecord,

    /// An `x`, `L` or `K` header without a ustar or GNU magic.
    UnrecognizedHeader {
        /// The kind of extension header.
        kind: TarExtensionKind,
    },

    /// A GNU sparse entry, which
    /// [`TarSparsePolicy::Refuse`](crate::TarSparsePolicy) (the default)
    /// rejects.
    SparseEntry,

    /// A header field is not a plain octal or base-256 number.
    NonCanonicalNumber {
        /// The offending field.
        field: TarHeaderField,
    },

    /// A header has a `prefix` field but no ustar magic.
    PrefixWithoutUstar,

    /// The header checksum does not match the header bytes.
    ChecksumMismatch,

    /// An entry is preceded by two extension headers of the same kind.
    DuplicateExtensionHeader {
        /// The repeated kind.
        kind: TarExtensionKind,
    },

    /// The bytes read before an entry do not end at the position of its
    /// header.
    WindowMismatch,

    /// The padding after an extension header body holds non-zero bytes, which
    /// some readers parse as further records.
    NonZeroPadding,

    /// A GNU long name or link body is not a single NUL-terminated string.
    MalformedLongRecord {
        /// The kind of extension header.
        kind: TarExtensionKind,
    },

    /// A directory, symbolic link, hard link or volume label entry declares a
    /// payload, which some readers skip as data and others parse as further
    /// headers.
    NonRegularPayload {
        /// The entry type.
        kind: TarNonRegularKind,
        /// Declared payload size in bytes.
        size: u64,
        /// Lossy entry path; for display only.
        path: String,
    },

    /// A regular entry whose name ends in `/` declares a payload, so it is a
    /// directory to some readers and a file to others.
    DirectoryNamedPayload {
        /// Declared payload size in bytes.
        size: u64,
        /// Lossy entry path; for display only.
        path: String,
    },

    /// A local extension header precedes a GNU volume label. The `tar` crate
    /// merges it into the label, while `bsdtar` applies it to the next member,
    /// so the two read a different name for that member.
    ExtensionBeforeLabel {
        /// The kind of extension header.
        kind: TarExtensionKind,
    },

    /// The map of a GNU sparse entry breaks a rule that
    /// [`TarSparsePolicy::Expand`](crate::TarSparsePolicy) enforces: readers
    /// would interpret it differently, or it is malformed.
    SparseMap {
        /// What is wrong with the map.
        defect: SparseMapDefect,
    },
}

impl std::fmt::Display for TarAmbiguity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MalformedRecord => f.write_str("malformed PAX record"),
            Self::EmptyKey => f.write_str("PAX record with an empty key"),
            Self::OversizedRecord { key } => write!(
                f,
                "PAX record {key:?} is longer than {MAX_PAX_RECORD_BYTES} bytes"
            ),
            Self::DuplicateRecord { key } => write!(f, "duplicate PAX record {key:?}"),
            Self::UnsupportedRecord { key } => write!(f, "PAX record {key:?} is not supported"),
            Self::InvalidSize => f.write_str("PAX `size` record is not a decimal number"),
            Self::GlobalOverride { key } => {
                write!(f, "global PAX record {key:?} would apply to later entries")
            }
            Self::GlobalTooLarge { size, limit } => write!(
                f,
                "global PAX header ({size} bytes) exceeds the metadata limit of {limit} bytes"
            ),
            Self::LocalBeforeGlobal => f.write_str("global PAX header follows a local PAX header"),
            Self::LongRecordBeforeGlobal => {
                f.write_str("global PAX header follows a GNU long name or link record")
            }
            Self::StackedLongRecord { key } => write!(
                f,
                "PAX `{key}` record and a GNU long {} record both describe the same entry",
                key.long_record()
            ),
            Self::StackedSizeRecord => f.write_str(
                "PAX `size` record and a GNU long name or link record share one extension chain",
            ),
            Self::UnrecognizedHeader { kind } => write!(
                f,
                "extension header {} lacks a ustar or GNU magic",
                kind.entry_type_name()
            ),
            Self::SparseEntry => {
                f.write_str("GNU sparse entries are refused unless tar_sparse is expand")
            }
            Self::NonCanonicalNumber { field } => write!(
                f,
                "header {field} field is not a plain octal or base-256 number"
            ),
            Self::PrefixWithoutUstar => {
                f.write_str("header carries a prefix field without a ustar magic")
            }
            Self::ChecksumMismatch => {
                f.write_str("header checksum does not match the header bytes")
            }
            Self::DuplicateExtensionHeader { kind } => {
                write!(f, "duplicate {kind} extension header")
            }
            Self::NonZeroPadding => {
                f.write_str("extension header body is followed by non-zero padding")
            }
            Self::MalformedLongRecord { kind } => {
                write!(
                    f,
                    "{kind} extension header is not a single NUL-terminated string"
                )
            }
            Self::WindowMismatch => {
                f.write_str("bytes read before the entry do not match the position of its header")
            }
            Self::NonRegularPayload { kind, size, path } => {
                write!(f, "{kind} entry declares a {size} byte payload: {path}")
            }
            Self::DirectoryNamedPayload { size, path } => {
                write!(
                    f,
                    "file entry with a directory name carries {size} bytes: {path}"
                )
            }
            Self::ExtensionBeforeLabel { kind } => {
                write!(f, "a {kind} header precedes a volume label")
            }
            Self::SparseMap { defect } => write!(f, "GNU sparse map: {defect}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn payload_messages_are_pinned() {
        let directory = TarAmbiguity::NonRegularPayload {
            kind: TarNonRegularKind::Directory,
            size: 1024,
            path: "x/".into(),
        };
        assert_eq!(
            directory.to_string(),
            "directory entry declares a 1024 byte payload: x/"
        );
        let named = TarAmbiguity::DirectoryNamedPayload {
            size: 3,
            path: "d/".into(),
        };
        let hardlink = TarAmbiguity::NonRegularPayload {
            kind: TarNonRegularKind::Hardlink,
            size: 2,
            path: "l".into(),
        };
        assert_eq!(
            hardlink.to_string(),
            "hardlink entry declares a 2 byte payload: l"
        );
        assert_eq!(
            named.to_string(),
            "file entry with a directory name carries 3 bytes: d/"
        );
    }

    #[test]
    fn non_regular_kinds_display_in_lower_case_like_their_siblings() {
        use crate::error::zip_inconsistency::ZipNonRegularKind;

        let spellings: Vec<_> = TarNonRegularKind::ALL
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            spellings,
            ["directory", "symlink", "hardlink", "volume label"]
        );
        for kind in TarNonRegularKind::ALL {
            assert_eq!(kind.as_str(), kind.to_string());
            assert_eq!(kind.to_string(), kind.to_string().to_lowercase());
        }
        assert_eq!(
            TarNonRegularKind::Directory.to_string(),
            ZipNonRegularKind::Directory.to_string()
        );
    }

    #[test]
    fn volume_label_messages_are_pinned() {
        let payload = TarAmbiguity::NonRegularPayload {
            kind: TarNonRegularKind::VolumeLabel,
            size: 1024,
            path: "label".into(),
        };
        assert_eq!(
            payload.to_string(),
            "volume label entry declares a 1024 byte payload: label"
        );
        let cases = [
            (
                TarExtensionKind::Pax,
                "a PAX header precedes a volume label",
            ),
            (
                TarExtensionKind::LongName,
                "a GNU long name header precedes a volume label",
            ),
            (
                TarExtensionKind::LongLink,
                "a GNU long link header precedes a volume label",
            ),
        ];
        for (kind, text) in cases {
            assert_eq!(
                TarAmbiguity::ExtensionBeforeLabel { kind }.to_string(),
                text
            );
        }
    }

    #[test]
    fn only_the_label_typeflag_maps_to_the_volume_label_kind() {
        assert_eq!(
            TarNonRegularKind::of(tar::EntryType::new(b'V')),
            Some(TarNonRegularKind::VolumeLabel)
        );
        assert_eq!(TarNonRegularKind::of(tar::EntryType::new(b'D')), None);
        assert_eq!(TarNonRegularKind::of(tar::EntryType::Regular), None);
    }

    #[test]
    fn a_symlink_payload_message_uses_the_lower_case_kind() {
        let symlink = TarAmbiguity::NonRegularPayload {
            kind: TarNonRegularKind::Symlink,
            size: 9,
            path: "s".into(),
        };
        assert_eq!(
            symlink.to_string(),
            "symlink entry declares a 9 byte payload: s"
        );
    }

    #[test]
    fn extension_kind_messages_are_pinned() {
        let cases = [
            (TarExtensionKind::Pax, "PAX", "XHeader"),
            (TarExtensionKind::LongName, "GNU long name", "GNULongName"),
            (TarExtensionKind::LongLink, "GNU long link", "GNULongLink"),
        ];
        for (kind, name, entry_type) in cases {
            assert_eq!(kind.to_string(), name);
            assert_eq!(
                TarAmbiguity::DuplicateExtensionHeader { kind }.to_string(),
                format!("duplicate {name} extension header")
            );
            assert_eq!(
                TarAmbiguity::MalformedLongRecord { kind }.to_string(),
                format!("{name} extension header is not a single NUL-terminated string")
            );
            assert_eq!(
                TarAmbiguity::UnrecognizedHeader { kind }.to_string(),
                format!("extension header {entry_type} lacks a ustar or GNU magic")
            );
        }
    }
}