exarch-core 0.7.0

Memory-safe archive extraction library with security validation
Documentation
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Archive manifest types for listing.

use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;

use crate::ArchiveError;
use crate::Result;
use crate::ZipEntryIndex;
use crate::closed_enum::closed_enum;
use crate::formats::detect::ArchiveType;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::check_link_target_length;

/// Complete manifest of archive contents.
///
/// Generated by `list_archive()`, contains metadata about all entries
/// without extracting them to disk. Fields are private so that the entry
/// count and total size always agree with the stored entries.
///
/// # Examples
///
/// ```no_run
/// use exarch_core::SecurityConfig;
/// use exarch_core::list_archive;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SecurityConfig::default();
/// let manifest = list_archive("archive.tar.gz", &config)?;
///
/// for entry in manifest.entries() {
///     println!("{}: {} bytes", entry.path.display(), entry.size);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ArchiveManifest {
    entries: Vec<ArchiveEntry>,
    oversized: Vec<OversizedEntry>,
    total_size: u64,
    format: ArchiveType,
}

/// The position of an entry in an [`ArchiveManifest`], only obtainable from
/// the manifest that holds it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct EntryPosition(usize);

/// An entry whose path exceeds the host's name limits.
///
/// Only the position and the path length are kept, so an archive of many
/// entries with huge names cannot inflate the manifest. The entry is not in
/// [`ArchiveManifest::entries`].
///
/// # Examples
///
/// ```
/// use exarch_core::OversizedEntry;
///
/// let entry = OversizedEntry::new(3, 70_000);
/// assert_eq!(entry.index, 3);
/// assert_eq!(entry.bytes, 70_000);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OversizedEntry {
    /// Zero-based position among the listed entries, kept and dropped
    pub index: usize,

    /// Length of the stored path in bytes
    pub bytes: usize,
}

impl OversizedEntry {
    /// Creates a record of the entry at `index` with a path of `bytes` bytes.
    #[must_use]
    pub const fn new(index: usize, bytes: usize) -> Self {
        Self { index, bytes }
    }
}

impl ArchiveManifest {
    /// Creates a new empty manifest.
    #[must_use]
    pub fn new(format: ArchiveType) -> Self {
        Self {
            entries: Vec::new(),
            oversized: Vec::new(),
            total_size: 0,
            format,
        }
    }

    /// Records an entry dropped for its over-long path; its position counts
    /// the kept and the dropped entries listed before it.
    pub(crate) fn add_oversized(&mut self, bytes: usize) {
        let index = self.entries.len() + self.oversized.len();
        self.oversized.push(OversizedEntry::new(index, bytes));
    }

    /// Returns the entries dropped because their path exceeds the host's
    /// limits; only the verification pre-flight produces any.
    #[must_use]
    pub fn oversized_entries(&self) -> &[OversizedEntry] {
        &self.oversized
    }

    /// Returns the position in [`entries`](Self::entries) of the ZIP entry
    /// with the given index, or `None` when that entry was dropped for its
    /// over-long path.
    ///
    /// ZIP entries are listed in index order, and the dropped ones record
    /// their listing position, so the kept entry's position is its index less
    /// the dropped entries before it.
    pub(crate) fn position_of_zip_entry(&self, index: ZipEntryIndex) -> Option<usize> {
        let index = index.get();
        let dropped_before = self.oversized.partition_point(|o| o.index < index);
        if self
            .oversized
            .get(dropped_before)
            .is_some_and(|o| o.index == index)
        {
            return None;
        }
        let position = index - dropped_before;
        (position < self.entries.len()).then_some(position)
    }

    /// Adds an entry to the manifest.
    ///
    /// # Errors
    ///
    /// Returns [`ArchiveError::InvalidArchive`] if the total uncompressed size
    /// would overflow `u64`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ArchiveManifest;
    /// use exarch_core::ManifestEntryKind;
    /// use exarch_core::formats::detect::ArchiveType;
    ///
    /// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
    /// let entry = ArchiveEntry::new(PathBuf::from("a.txt"), ManifestEntryKind::File, 10);
    /// manifest.add_entry(entry)?;
    /// assert_eq!(manifest.total_entries(), 1);
    /// assert_eq!(manifest.total_size(), 10);
    /// # Ok::<(), exarch_core::ArchiveError>(())
    /// ```
    pub fn add_entry(&mut self, entry: ArchiveEntry) -> Result<()> {
        self.total_size = self.total_size.checked_add(entry.size).ok_or_else(|| {
            ArchiveError::InvalidArchive("archive total size overflows u64".to_string())
        })?;
        self.entries.push(entry);
        Ok(())
    }

    /// The position the next added entry takes.
    pub(crate) fn next_position(&self) -> EntryPosition {
        EntryPosition(self.entries.len())
    }

    /// Sets the target of the symlink entry at `position`, which listing reads
    /// after the entry was added. Any other entry is left alone.
    pub(crate) fn set_link_target(&mut self, position: EntryPosition, target: LinkTarget) {
        if let Some(ArchiveEntry {
            kind: ManifestEntryKind::Symlink { target: slot },
            ..
        }) = self.entries.get_mut(position.0)
        {
            *slot = target;
        }
    }

    /// Returns all entries in the archive (files, dirs, symlinks, hardlinks).
    #[must_use]
    pub fn entries(&self) -> &[ArchiveEntry] {
        &self.entries
    }

    /// Consumes the manifest and returns its entries.
    #[must_use]
    pub fn into_entries(self) -> Vec<ArchiveEntry> {
        self.entries
    }

    /// Returns the total number of entries.
    #[must_use]
    pub fn total_entries(&self) -> usize {
        self.entries.len()
    }

    /// Returns the total uncompressed size in bytes.
    #[must_use]
    pub const fn total_size(&self) -> u64 {
        self.total_size
    }

    /// Returns the archive format.
    #[must_use]
    pub const fn format(&self) -> ArchiveType {
        self.format
    }
}

/// Single entry in archive manifest.
///
/// Contains metadata about a file, directory, symlink, or hardlink
/// without extracting it to disk. Construct with [`ArchiveEntry::new`] and
/// assign the optional fields.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ArchiveEntry {
    /// Entry path (relative, as stored in archive)
    pub path: PathBuf,

    /// Entry kind; link kinds carry their target
    pub kind: ManifestEntryKind,

    /// Uncompressed size in bytes (0 for directories)
    pub size: u64,

    /// How this entry's data is compressed, as far as the format exposes it
    pub compression: EntryCompression,

    /// File permissions (Unix mode)
    pub mode: Option<u32>,

    /// Modification time
    pub modified: Option<SystemTime>,
}

impl ArchiveEntry {
    /// Creates an entry with all optional metadata unset.
    #[must_use]
    pub const fn new(path: PathBuf, kind: ManifestEntryKind, size: u64) -> Self {
        Self {
            path,
            kind,
            size,
            compression: EntryCompression::Unknown,
            mode: None,
            modified: None,
        }
    }

    /// Returns the compressed size in bytes when the format reports one.
    ///
    /// For the first file of a solid block this is the size of the whole
    /// block; other solid members report `None`.
    #[must_use]
    pub const fn compressed_size(&self) -> Option<u64> {
        self.compression.compressed_size()
    }

    /// Returns the compression ratio of an entry that owns its compressed
    /// data, or `None` when none can be attributed to it (TAR, solid members,
    /// empty entries).
    #[must_use]
    pub fn compression_ratio(&self) -> Option<f64> {
        self.compression
            .entry_compressed_size()
            .filter(|&c| c > 0)
            .map(|c| self.size as f64 / c as f64)
    }
}

/// Compressed and uncompressed totals of one solid block.
///
/// # Examples
///
/// ```
/// use exarch_core::SolidBlock;
///
/// let block = SolidBlock::new(100, 13_800);
/// assert_eq!(block.compressed, 100);
/// assert_eq!(block.uncompressed, 13_800);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SolidBlock {
    /// Sum of the block's pack stream sizes in bytes
    pub compressed: u64,

    /// Sum of the uncompressed sizes of every file in the block
    pub uncompressed: u64,
}

impl SolidBlock {
    /// Creates a block from its compressed and uncompressed totals.
    #[must_use]
    pub const fn new(compressed: u64, uncompressed: u64) -> Self {
        Self {
            compressed,
            uncompressed,
        }
    }
}

/// How an archive entry's data is compressed.
///
/// Solid 7z members share one compressed stream, so only the block as a whole
/// has a meaningful ratio; encoding that here keeps a per-file ratio from
/// being computed for them.
///
/// # Examples
///
/// ```
/// use exarch_core::EntryCompression;
///
/// assert_eq!(EntryCompression::Entry(40).compressed_size(), Some(40));
/// assert_eq!(EntryCompression::Unknown.compressed_size(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryCompression {
    /// The format does not expose a compressed size (TAR) or the entry has no
    /// data stream (empty 7z files)
    Unknown,

    /// The entry owns this many compressed bytes (ZIP, 7z single-file block)
    Entry(u64),

    /// First file of a solid block; carries the totals of the whole block
    SolidBlockStart(SolidBlock),

    /// Later file of a solid block; its data is accounted to the block start
    SolidBlockMember,
}

impl EntryCompression {
    /// Compressed size to report for the entry: the entry's own size, or the
    /// whole block's size for a solid block start.
    #[must_use]
    pub const fn compressed_size(&self) -> Option<u64> {
        match self {
            Self::Entry(compressed) => Some(*compressed),
            Self::SolidBlockStart(block) => Some(block.compressed),
            Self::Unknown | Self::SolidBlockMember => None,
        }
    }

    /// Compressed size owned by the entry alone, for per-file ratio checks.
    #[must_use]
    pub const fn entry_compressed_size(&self) -> Option<u64> {
        match self {
            Self::Entry(compressed) => Some(*compressed),
            Self::Unknown | Self::SolidBlockStart(_) | Self::SolidBlockMember => None,
        }
    }
}

/// Link target of a manifest entry, as far as the listing could keep it.
///
/// An over-long target is not retained: only its byte length is kept, so an
/// archive of many links with huge targets cannot inflate the manifest.
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// use exarch_core::LinkKind;
/// use exarch_core::LinkTarget;
///
/// assert_eq!(
///     LinkTarget::Recorded("a.txt".into()).path(),
///     Some(Path::new("a.txt"))
/// );
/// assert_eq!(LinkTarget::Oversized { bytes: 9000 }.path(), None);
/// // 40000 exceeds the path limit of every supported host
/// assert_eq!(
///     LinkTarget::classify("x".repeat(40_000).into(), LinkKind::Symlink),
///     LinkTarget::Oversized { bytes: 40_000 }
/// );
/// assert_eq!(LinkTarget::Missing.path(), None);
/// assert_eq!(LinkTarget::Unread.path(), None);
/// assert_eq!(LinkTarget::Unreadable.path(), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LinkTarget {
    /// Target as stored in the archive, within the host's name limits
    Recorded(PathBuf),

    /// The archive stores no target
    Missing,

    /// The archive stores a target that was not read: a 7z target kept in
    /// compressed entry data, left alone by a listing that skips stored
    /// targets (the default), by a verification without an integrity check, or
    /// by an integrity pass whose budget or admission limits did not reach it
    Unread,

    /// The archive stores a target that could not be read: a 7z reparse point
    /// (in every listing), or a 7z target whose read was attempted and failed
    /// because its block is refused for decoding or its data is corrupt
    Unreadable,

    /// The target exceeds the host's name limits; only its length is kept
    Oversized {
        /// Length of the stored target in bytes
        bytes: usize,
    },
}

impl LinkTarget {
    /// Keeps `path` when it fits the host's limits for `kind`, otherwise
    /// drops it and keeps only its length.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::assert_matches;
    ///
    /// use exarch_core::LinkKind;
    /// use exarch_core::LinkTarget;
    ///
    /// let long_component: std::path::PathBuf = "x".repeat(300).into();
    /// assert_matches!(
    ///     LinkTarget::classify(long_component.clone(), LinkKind::Symlink),
    ///     LinkTarget::Recorded(_)
    /// );
    /// assert_eq!(
    ///     LinkTarget::classify(long_component, LinkKind::Hardlink),
    ///     LinkTarget::Oversized { bytes: 300 }
    /// );
    /// ```
    #[must_use]
    pub fn classify(path: PathBuf, kind: LinkKind) -> Self {
        if check_link_target_length(&path, kind).is_ok() {
            Self::Recorded(path)
        } else {
            Self::Oversized {
                bytes: path.as_os_str().len(),
            }
        }
    }

    /// Returns the recorded target, or `None` when it is missing or oversized.
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        match self {
            Self::Recorded(path) => Some(path),
            Self::Missing | Self::Unread | Self::Unreadable | Self::Oversized { .. } => None,
        }
    }
}

/// Kind of a manifest entry; link kinds carry their target.
///
/// The target lives in the variant, so a regular file cannot carry one.
/// [`LinkTarget::Missing`] and [`LinkTarget::Oversized`] occur only in entries
/// produced by the pre-flight listing that
/// [`verify_archive`](crate::verify_archive) uses, where such a target must
/// become a report issue instead of a listing error. 7z link targets are
/// [`LinkTarget::Unread`] by default, in verification without an integrity
/// check, and for links an integrity pass did not reach (budget or admission
/// limits). [`LinkTarget::Unreadable`] marks a 7z reparse point in every
/// listing, and a target whose read was attempted and failed.
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// use exarch_core::LinkTarget;
/// use exarch_core::ManifestEntryKind;
/// use exarch_core::ManifestEntryType;
///
/// let kind = ManifestEntryKind::Symlink {
///     target: LinkTarget::Recorded("a.txt".into()),
/// };
/// assert_eq!(kind.entry_type(), ManifestEntryType::Symlink);
/// assert_eq!(kind.link_target(), Some(Path::new("a.txt")));
/// assert_eq!(ManifestEntryKind::File.link_target(), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ManifestEntryKind {
    /// Regular file
    File,

    /// Directory
    Directory,

    /// Symbolic link
    Symlink {
        /// Link target as stored in the archive
        target: LinkTarget,
    },

    /// Hard link
    Hardlink {
        /// Link target as stored in the archive
        target: LinkTarget,
    },
}

impl ManifestEntryKind {
    /// Returns the wire tag of this kind.
    #[must_use]
    pub const fn entry_type(&self) -> ManifestEntryType {
        match self {
            Self::File => ManifestEntryType::File,
            Self::Directory => ManifestEntryType::Directory,
            Self::Symlink { .. } => ManifestEntryType::Symlink,
            Self::Hardlink { .. } => ManifestEntryType::Hardlink,
        }
    }

    /// Returns `true` for a symlink or a hardlink.
    #[must_use]
    pub const fn is_link(&self) -> bool {
        matches!(self, Self::Symlink { .. } | Self::Hardlink { .. })
    }

    /// Returns the target of a symlink, if one was recorded.
    #[must_use]
    pub fn symlink_target(&self) -> Option<&Path> {
        match self {
            Self::Symlink { target } => target.path(),
            Self::File | Self::Directory | Self::Hardlink { .. } => None,
        }
    }

    /// Returns the target of a hardlink, if one was recorded.
    #[must_use]
    pub fn hardlink_target(&self) -> Option<&Path> {
        match self {
            Self::Hardlink { target } => target.path(),
            Self::File | Self::Directory | Self::Symlink { .. } => None,
        }
    }

    /// Returns the link target of a symlink or hardlink, if one was recorded.
    #[must_use]
    pub fn link_target(&self) -> Option<&Path> {
        self.symlink_target().or_else(|| self.hardlink_target())
    }
}

closed_enum! {
    /// Entry type in manifest (does NOT require validation).
    ///
    /// Unlike `EntryType`, this enum is used for read-only listing
    /// and does not enforce security constraints.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum ManifestEntryType {
        /// Regular file
        File => "File",

        /// Directory
        Directory => "Directory",

        /// Symbolic link
        Symlink => "Symlink",

        /// Hard link
        Hardlink => "Hardlink",
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use std::assert_matches;

    use super::*;

    #[test]
    fn test_manifest_new() {
        let manifest = ArchiveManifest::new(ArchiveType::TarGz);
        assert_eq!(manifest.total_entries(), 0);
        assert_eq!(manifest.total_size(), 0);
        assert!(manifest.entries().is_empty());
        assert_eq!(manifest.format(), ArchiveType::TarGz);
    }

    #[test]
    fn test_manifest_add_entry() {
        let mut manifest = ArchiveManifest::new(ArchiveType::TarGz);

        let entry = ArchiveEntry {
            path: PathBuf::from("file.txt"),
            kind: ManifestEntryKind::File,
            size: 1024,
            compression: EntryCompression::Entry(512),
            mode: Some(0o644),
            modified: None,
        };

        manifest.add_entry(entry).unwrap();

        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.total_size(), 1024);
        assert_eq!(manifest.entries().len(), 1);
    }

    #[test]
    fn test_manifest_add_entry_size_overflow() {
        let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
        let big = ArchiveEntry::new(PathBuf::from("a"), ManifestEntryKind::File, u64::MAX);
        manifest.add_entry(big).unwrap();

        let more = ArchiveEntry::new(PathBuf::from("b"), ManifestEntryKind::File, 1);
        assert_matches!(
            manifest.add_entry(more),
            Err(ArchiveError::InvalidArchive(_))
        );
        assert_eq!(manifest.total_entries(), 1);
        assert_eq!(manifest.total_size(), u64::MAX);
    }

    #[test]
    fn test_compression_ratio() {
        let entry = ArchiveEntry {
            path: PathBuf::from("file.txt"),
            kind: ManifestEntryKind::File,
            size: 1000,
            compression: EntryCompression::Entry(100),
            mode: None,
            modified: None,
        };

        assert_eq!(entry.compression_ratio(), Some(10.0));
    }

    #[test]
    fn test_compression_ratio_no_compressed() {
        let entry = ArchiveEntry {
            path: PathBuf::from("file.txt"),
            kind: ManifestEntryKind::File,
            size: 1000,
            compression: EntryCompression::Unknown,
            mode: None,
            modified: None,
        };

        assert_eq!(entry.compression_ratio(), None);
    }

    #[test]
    fn test_solid_entries_have_no_per_file_ratio() {
        let mut entry = ArchiveEntry::new(PathBuf::from("a"), ManifestEntryKind::File, 1000);
        entry.compression = EntryCompression::SolidBlockStart(SolidBlock::new(10, 2000));
        assert_eq!(entry.compression_ratio(), None);
        assert_eq!(entry.compressed_size(), Some(10));

        entry.compression = EntryCompression::SolidBlockMember;
        assert_eq!(entry.compression_ratio(), None);
        assert_eq!(entry.compressed_size(), None);
    }

    #[test]
    fn test_manifest_entry_type_display() {
        assert_eq!(ManifestEntryType::File.to_string(), "File");
        assert_eq!(ManifestEntryType::Directory.to_string(), "Directory");
        assert_eq!(ManifestEntryType::Symlink.to_string(), "Symlink");
        assert_eq!(ManifestEntryType::Hardlink.to_string(), "Hardlink");
    }

    #[test]
    fn test_position_of_zip_entry_skips_dropped_entries() {
        let mut manifest = ArchiveManifest::new(ArchiveType::Zip);
        manifest.add_oversized(300);
        for name in ["a", "b"] {
            let entry = ArchiveEntry::new(PathBuf::from(name), ManifestEntryKind::File, 0);
            manifest.add_entry(entry).unwrap();
        }
        manifest.add_oversized(300);

        let position = |index| manifest.position_of_zip_entry(ZipEntryIndex::new(index));
        assert_eq!(position(0), None);
        assert_eq!(position(1), Some(0));
        assert_eq!(position(2), Some(1));
        assert_eq!(position(3), None);
        assert_eq!(position(9), None);
    }
}