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
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! Archive manifest types for listing.

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

use crate::ArchiveError;
use crate::EntrySelection;
use crate::Malformation;
use crate::Result;
use crate::ZipEntryIndex;
use crate::closed_enum::closed_enum;
use crate::formats::detect::ArchiveType;
use crate::security::Compressed;
use crate::security::RawMode;
use crate::security::Uncompressed;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::check_link_target_length;
use crate::selection::EntryShape;

closed_enum! {
    /// Whether an archive entry's data is encrypted.
    ///
    /// Reported for every entry whether or not a password was supplied.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ClosedEnum;
    /// use exarch_core::EntryEncryption;
    ///
    /// assert_eq!(EntryEncryption::Encrypted.as_str(), "encrypted");
    /// assert_eq!(EntryEncryption::default(), EntryEncryption::Plain);
    /// ```
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum EntryEncryption {
        /// The entry's data is stored without encryption
        #[default]
        Plain => "plain",

        /// The entry's data is encrypted
        Encrypted => "encrypted",
    }
}

/// 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,
    selection: EntrySelection,
}

/// 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 that lists every entry as extracted.
    #[must_use]
    pub fn new(format: ArchiveType) -> Self {
        Self::with_selection(format, EntrySelection::default())
    }

    /// Creates a new empty manifest for a listing made under `selection`.
    ///
    /// The manifest keeps the selection, so its landings and dispositions can
    /// never disagree with the selection it was listed with.
    #[must_use]
    pub fn with_selection(format: ArchiveType, selection: EntrySelection) -> Self {
        Self {
            entries: Vec::new(),
            oversized: Vec::new(),
            total_size: 0,
            format,
            selection,
        }
    }

    /// The selection this manifest was listed with.
    ///
    /// Every entry is listed whatever the selection is; the selection decides
    /// which of them [`landings`](Self::landings) and
    /// [`dispositions`](Self::dispositions) report as extracted.
    #[must_use]
    pub const fn selection(&self) -> &EntrySelection {
        &self.selection
    }

    /// 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().saturating_add(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.checked_sub(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`. Only regular files add to the total; the data of
    /// a link entry (a ZIP symlink's stored target) is bounded by the
    /// symlink-target size limit instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ArchiveManifest;
    /// use exarch_core::ArchiveType;
    /// use exarch_core::ManifestEntryKind;
    /// use exarch_core::Uncompressed;
    ///
    /// let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
    /// let kind = ManifestEntryKind::File {
    ///     size: Uncompressed(10),
    /// };
    /// let entry = ArchiveEntry::new(PathBuf::from("a.txt"), kind);
    /// 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::from(Malformation::TotalSizeOverflow))?;
        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,

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

    /// Permission bits as stored in the archive, before sanitization
    pub mode: Option<RawMode>,

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

    /// Whether this entry's data is encrypted
    pub encryption: EntryEncryption,
}

impl EntryEncryption {
    /// The marker for an entry whose format flag says encrypted or not.
    pub(crate) const fn from_flag(encrypted: bool) -> Self {
        if encrypted {
            Self::Encrypted
        } else {
            Self::Plain
        }
    }
}

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

    /// Returns `true` when this entry's data is encrypted.
    #[must_use]
    pub const fn is_encrypted(&self) -> bool {
        matches!(self.encryption, EntryEncryption::Encrypted)
    }

    /// Returns the entry path as text.
    ///
    /// Front ends that expose paths as strings call this so that every one
    /// applies the same policy: a path that is not valid UTF-8 is refused
    /// rather than rendered lossily, because a lossy rendering could give two
    /// distinct entries one name.
    ///
    /// # Errors
    ///
    /// Returns [`Malformation::EntryPathNotUtf8`] when the path is not valid
    /// UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    ///
    /// use exarch_core::ArchiveEntry;
    /// use exarch_core::ManifestEntryKind;
    ///
    /// let entry = ArchiveEntry::new(PathBuf::from("a/b.txt"), ManifestEntryKind::Directory);
    /// assert_eq!(entry.utf8_path()?, "a/b.txt");
    /// # Ok::<(), exarch_core::Malformation>(())
    /// ```
    pub fn utf8_path(&self) -> std::result::Result<&str, Malformation> {
        crate::utf8_entry_path(&self.path)
    }

    /// Returns the uncompressed size in bytes: the size of a regular file, and
    /// 0 for every other kind.
    #[must_use]
    pub const fn size(&self) -> u64 {
        self.kind.size()
    }

    /// 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::Compressed;
/// use exarch_core::SolidBlock;
/// use exarch_core::Uncompressed;
///
/// let block = SolidBlock::new(Compressed(100), Uncompressed(13_800));
/// assert_eq!(block.compressed, Compressed(100));
/// assert_eq!(block.uncompressed, 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: Compressed,

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

impl SolidBlock {
    /// Creates a block from its compressed and uncompressed totals.
    #[must_use]
    pub const fn new(compressed: Compressed, uncompressed: Uncompressed) -> 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::Compressed;
/// use exarch_core::EntryCompression;
///
/// assert_eq!(
///     EntryCompression::Entry(Compressed(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(Compressed),

    /// 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.0),
            Self::SolidBlockStart(block) => Some(block.compressed.0),
            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.0),
            Self::Unknown | Self::SolidBlockStart(_) | Self::SolidBlockMember => None,
        }
    }
}

closed_enum! {
    /// What a [`LinkTarget`] holds, without the target itself.
    ///
    /// The string form is stable and shared by every front end, so a binding
    /// reports the state of a target it cannot carry without matching the
    /// variants itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::LinkTarget;
    /// use exarch_core::LinkTargetState;
    ///
    /// assert_eq!(LinkTarget::Missing.state(), LinkTargetState::Missing);
    /// assert_eq!(LinkTargetState::Unreadable.as_str(), "unreadable");
    /// ```
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum LinkTargetState {
        /// [`LinkTarget::Recorded`].
        Recorded => "recorded",
        /// [`LinkTarget::Missing`].
        Missing => "missing",
        /// [`LinkTarget::Unread`].
        Unread => "unread",
        /// [`LinkTarget::Unreadable`].
        Unreadable => "unreadable",
        /// [`LinkTarget::Oversized`].
        Oversized => "oversized",
    }
}

/// 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 what this target holds, without the target itself.
    #[must_use]
    pub const fn state(&self) -> LinkTargetState {
        match self {
            Self::Recorded(_) => LinkTargetState::Recorded,
            Self::Missing => LinkTargetState::Missing,
            Self::Unread => LinkTargetState::Unread,
            Self::Unreadable => LinkTargetState::Unreadable,
            Self::Oversized { .. } => LinkTargetState::Oversized,
        }
    }

    /// 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,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum EpochSide {
    Before,
    AtOrAfter,
}

/// A point in time as an offset from the Unix epoch, which may be negative.
///
/// [`SystemTime`] cannot be turned into a signed number without choosing a
/// representation for times before 1970; this type fixes it once so every
/// front end reports the same value. It is built only from a [`SystemTime`],
/// so the magnitude and the side of the epoch always agree. It has no
/// ordering: compare the [`SystemTime`] it came from.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use std::time::UNIX_EPOCH;
///
/// use exarch_core::UnixTime;
///
/// let before = UnixTime::from(UNIX_EPOCH - Duration::from_millis(1500));
/// assert_eq!(before.as_millis(), -1500);
/// assert_eq!(before.as_secs_f64(), -1.5);
///
/// let after = UnixTime::from(UNIX_EPOCH + Duration::from_secs(2));
/// assert_eq!(after.as_millis(), 2000);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnixTime {
    magnitude: Duration,
    side: EpochSide,
}

impl From<SystemTime> for UnixTime {
    fn from(time: SystemTime) -> Self {
        match time.duration_since(UNIX_EPOCH) {
            Ok(magnitude) => Self {
                magnitude,
                side: EpochSide::AtOrAfter,
            },
            Err(error) => Self {
                magnitude: error.duration(),
                side: EpochSide::Before,
            },
        }
    }
}

impl UnixTime {
    /// Seconds since the epoch, negative before it.
    #[must_use]
    pub fn as_secs_f64(self) -> f64 {
        match self.side {
            EpochSide::AtOrAfter => self.magnitude.as_secs_f64(),
            EpochSide::Before => -self.magnitude.as_secs_f64(),
        }
    }

    /// Milliseconds since the epoch, rounded toward negative infinity.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use std::time::UNIX_EPOCH;
    ///
    /// use exarch_core::UnixTime;
    ///
    /// let time = UnixTime::from(UNIX_EPOCH - Duration::from_micros(1));
    /// assert_eq!(time.as_millis(), -1);
    /// ```
    #[must_use]
    pub fn as_millis(self) -> i128 {
        let floor = i128::try_from(self.magnitude.as_millis()).unwrap_or(i128::MAX);
        match self.side {
            EpochSide::AtOrAfter => floor,
            EpochSide::Before if self.magnitude.subsec_nanos().is_multiple_of(1_000_000) => {
                floor.saturating_neg()
            }
            EpochSide::Before => floor.saturating_add(1).saturating_neg(),
        }
    }
}

/// 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;
/// use exarch_core::Uncompressed;
///
/// 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")));
/// let file = ManifestEntryKind::File {
///     size: Uncompressed(3),
/// };
/// assert_eq!(file.link_target(), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ManifestEntryKind {
    /// Regular file
    File {
        /// Uncompressed size in bytes
        size: Uncompressed,
    },

    /// 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 {
    /// What kind of entry the selection sees.
    pub(crate) const fn shape(&self) -> EntryShape {
        match self {
            Self::File { .. } => EntryShape::File,
            Self::Directory => EntryShape::Directory,
            Self::Symlink { .. } => EntryShape::Link(LinkKind::Symlink),
            Self::Hardlink { .. } => EntryShape::Link(LinkKind::Hardlink),
        }
    }

    /// 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 the uncompressed size of a regular file, and 0 for any other
    /// kind.
    #[must_use]
    pub const fn size(&self) -> u64 {
        match self {
            Self::File { size } => size.0,
            Self::Directory | Self::Symlink { .. } | Self::Hardlink { .. } => 0,
        }
    }

    /// 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.
    ///
    /// Closed by design: a new variant is a breaking change, and every
    /// front end pins [`ALL`](Self::ALL) in a drift test so it cannot go
    /// unnoticed.
    #[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)]
mod tests {
    use std::assert_matches;

    use super::*;

    fn file(size: u64) -> ManifestEntryKind {
        ManifestEntryKind::File {
            size: Uncompressed(size),
        }
    }

    #[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: file(1024),
            compression: EntryCompression::Entry(Compressed(512)),
            mode: Some(RawMode::new(0o644)),
            modified: None,
            encryption: EntryEncryption::Plain,
        };

        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"), file(u64::MAX));
        manifest.add_entry(big).unwrap();

        let more = ArchiveEntry::new(PathBuf::from("b"), 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_only_regular_files_carry_a_size() {
        let target = LinkTarget::Recorded("t".into());
        let symlink = ManifestEntryKind::Symlink {
            target: target.clone(),
        };
        let hardlink = ManifestEntryKind::Hardlink { target };
        assert_eq!(file(7).size(), 7);
        for kind in [ManifestEntryKind::Directory, symlink, hardlink] {
            assert_eq!(kind.size(), 0);
        }

        let mut manifest = ArchiveManifest::new(ArchiveType::Tar);
        for kind in [
            file(5),
            ManifestEntryKind::Symlink {
                target: LinkTarget::Missing,
            },
        ] {
            manifest
                .add_entry(ArchiveEntry::new(PathBuf::from("x"), kind))
                .unwrap();
        }
        assert_eq!(manifest.total_size(), 5);
    }

    #[test]
    fn test_utf8_path_accepts_text_and_refuses_other_bytes() {
        let text = ArchiveEntry::new(PathBuf::from("a/é.txt"), ManifestEntryKind::Directory);
        assert_eq!(text.utf8_path().unwrap(), "a/é.txt");

        #[cfg(unix)]
        {
            use std::ffi::OsStr;
            use std::os::unix::ffi::OsStrExt;

            let raw = PathBuf::from(OsStr::from_bytes(b"a/\xff"));
            let entry = ArchiveEntry::new(raw.clone(), ManifestEntryKind::Directory);
            assert_matches!(
                entry.utf8_path(),
                Err(Malformation::EntryPathNotUtf8 { path }) if path == raw
            );
        }
    }

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

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

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

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

    #[test]
    fn test_solid_entries_have_no_per_file_ratio() {
        let mut entry = ArchiveEntry::new(PathBuf::from("a"), file(1000));
        entry.compression =
            EntryCompression::SolidBlockStart(SolidBlock::new(Compressed(10), Uncompressed(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), 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);
    }
}