geezipx-core 0.5.0

Compression/decompression core engine for GeeZipX
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
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
//! Archive format abstraction layer.
//!
//! Defines the shared traits [`ArchiveReader`] and [`ArchiveWriter`] that
//! every archive format implementation must satisfy.  Concrete
//! implementations live in submodules (`zip`, `tar`, ...).
//!
//! # Design goals
//!
//! - **Core/CLI decoupling** — callers interact only via these traits and
//!   the [`Entry`] / [`ExtractReport`] types.
//! - **Streaming** — individual entry payloads flow through [`Read`] /
//!   [`Write`] so large files never need to be fully buffered.
//! - **Object-safe** — both traits use `&mut self` / `self: Box<Self>`
//!   receivers so they can be used through `Box<dyn ArchiveReader>` etc.
pub mod gzip;
#[cfg(feature = "rar")]
pub mod rar;
pub mod seven_zip;
pub mod tar;
pub mod targz;
pub mod tarxz;
pub mod tarzst;
pub mod xz;
pub mod zip;
pub mod zstd;

use std::io::{Read, Write};
use std::path::Path;

use crate::detect::ArchiveFormat;
use crate::error::{GeeZipError, GeeZipResult};

/// A single entry inside an archive.
#[derive(Debug, Clone)]
pub struct Entry {
    /// Relative path inside the archive (forward-slash separated).
    pub path: String,
    /// Uncompressed size in bytes.
    pub size: u64,
    /// Compressed size in bytes (0 if unknown).
    pub compressed_size: u64,
    /// CRC-32 checksum, if the format provides it.
    pub crc32: Option<u32>,
    /// Last modification time as Unix timestamp (seconds since epoch), if available.
    pub modified: Option<u64>,
    pub is_dir: bool,
}

/// Convert a calendar date/time to a Unix timestamp (seconds since epoch).
///
/// Used by archive readers that provide modification timestamps in a
/// decomposed form that we cannot assume the OS can `mktime` for us.
/// This avoids pulling in a date-time crate for the core library.
pub(crate) fn datetime_to_timestamp(
    year: u64,
    month: u64,
    day: u64,
    hour: u64,
    minute: u64,
    second: u64,
) -> u64 {
    // Validate month/day to prevent silent garbage results (e.g. from malformed
    // archive metadata). Returns 0 on invalid input as a safe fallback.
    if !(1..=12).contains(&month) || day == 0 {
        return 0;
    }
    let is_leap = |y: u64| (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400);
    let days_in_months: [u64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // Also reject day exceeding the month's length.
    let max_day = if month == 2 && is_leap(year) {
        29
    } else {
        days_in_months[(month - 1) as usize]
    };
    if day > max_day {
        return 0;
    }

    // Days from 1970-01-01 to (year-01-01).
    let mut total_days = 0u64;
    for y in 1970..year {
        total_days += if is_leap(y) { 366 } else { 365 };
    }

    // Days from (year-01-01) to (year-month-day).
    for m in 0..(month.saturating_sub(1)) {
        let idx = m as usize;
        total_days += if idx == 1 && is_leap(year) {
            29
        } else {
            days_in_months[idx]
        };
    }
    total_days += day.saturating_sub(1);

    total_days * 86_400 + hour * 3_600 + minute * 60 + second
}
/// Result of extracting an entire archive.
#[derive(Debug, Default)]
pub struct ExtractReport {
    /// Number of files successfully extracted.
    pub files_extracted: usize,
    /// Total uncompressed bytes written.
    pub bytes_extracted: u64,
    /// Number of files skipped (e.g. due to `--no-clobber`).
    pub files_skipped: usize,
    /// Per-file errors that did **not** abort the whole operation.
    pub errors: Vec<(String, crate::error::GeeZipError)>,
}

/// Archive reader trait — list entries and extract data.
///
/// Implementations are expected to be object-safe so callers can work
/// with `Box<dyn ArchiveReader>`.
pub trait ArchiveReader: Send {
    /// The format of the archive being read.
    fn format(&self) -> ArchiveFormat;

    /// Return the list of entries in the archive.
    fn entries(&mut self) -> GeeZipResult<Vec<Entry>>;

    /// Extract a single entry's content into `writer`.
    ///
    /// The caller is responsible for locating the output path; this
    /// method only writes the decompressed payload.
    fn extract(&mut self, entry: &Entry, writer: &mut dyn Write) -> GeeZipResult<u64>;

    /// Extract all entries under `dest`.
    ///
    /// Default implementation calls [`extract`](ArchiveReader::extract)
    /// for each entry, creating parent directories as needed.
    fn extract_all(&mut self, dest: &Path, overwrite: bool) -> GeeZipResult<ExtractReport> {
        let entries = self.entries()?;
        let mut report = ExtractReport::default();

        // Normalise the destination once so we use a consistent base.
        let dest = normalize_path(dest);

        for entry in &entries {
            let entry_path = Path::new(&entry.path);

            // --- Path safety checks (Zip Slip protection) ---
            let target = match check_entry_path_safety(entry_path, &entry.path, &dest) {
                Ok(t) => t,
                Err((name, err)) => {
                    report.errors.push((name, err));
                    continue;
                }
            };

            // Handle directory entries — create directory and skip file I/O.
            if entry.is_dir {
                if let Err(e) = std::fs::create_dir_all(&target) {
                    report.errors.push((
                        entry.path.clone(),
                        crate::error::GeeZipError::io(e, "creating directory"),
                    ));
                    continue;
                }
                report.files_extracted += 1;
                continue;
            }

            // Create parent directory.
            if let Some(parent) = target.parent() {
                if !parent.exists() {
                    if let Err(e) = std::fs::create_dir_all(parent) {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(e, "creating parent directory"),
                        ));
                        continue;
                    }
                }
            }

            // Write entry content — atomically create or fail (avoids TOCTOU
            // between path-exists check and file creation for the no-clobber path).
            let mut output = if overwrite {
                match std::fs::File::create(&target) {
                    Ok(f) => f,
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(
                                e,
                                format!("creating output file '{}'", target.display()),
                            ),
                        ));
                        continue;
                    }
                }
            } else {
                match std::fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&target)
                {
                    Ok(f) => f,
                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                        report.files_skipped += 1;
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::clobber_denied(target.display().to_string()),
                        ));
                        continue;
                    }
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(
                                e,
                                format!("creating output file '{}'", target.display()),
                            ),
                        ));
                        continue;
                    }
                }
            };

            match self.extract(entry, &mut output) {
                Ok(bytes) => {
                    report.files_extracted += 1;
                    report.bytes_extracted += bytes;
                }
                Err(e) => {
                    report.errors.push((entry.path.clone(), e));
                }
            }
        }

        Ok(report)
    }

    /// Extract all entries under `dest`, checking `is_cancelled()` before
    /// each entry and before every write to the output file.
    ///
    /// The default implementation mirrors [`extract_all`](ArchiveReader::extract_all)
    /// but also wraps the output file in a `CancellableWriter` that returns
    /// `ErrorKind::Interrupted` when the user presses Ctrl+C.
    ///
    /// When cancellation is detected the operation is aborted immediately and
    /// returns [`GeeZipError::Cancelled`]. Already-extracted files are
    /// preserved (the caller decides whether to report the partial state).
    fn extract_all_with_cancel(
        &mut self,
        dest: &Path,
        overwrite: bool,
        is_cancelled: &dyn Fn() -> bool,
    ) -> GeeZipResult<ExtractReport> {
        let entries = self.entries()?;
        let mut report = ExtractReport::default();

        // Normalise the destination once so we use a consistent base.
        let dest = normalize_path(dest);

        for entry in &entries {
            // Check cancellation before processing each entry.
            if is_cancelled() {
                return Err(GeeZipError::Cancelled);
            }

            let entry_path = Path::new(&entry.path);

            // --- Path safety checks (Zip Slip protection) ---
            let target = match check_entry_path_safety(entry_path, &entry.path, &dest) {
                Ok(t) => t,
                Err((name, err)) => {
                    report.errors.push((name, err));
                    continue;
                }
            };

            // Handle directory entries — create directory and skip file I/O.
            if entry.is_dir {
                if let Err(e) = std::fs::create_dir_all(&target) {
                    report.errors.push((
                        entry.path.clone(),
                        crate::error::GeeZipError::io(e, "creating directory"),
                    ));
                    continue;
                }
                report.files_extracted += 1;
                continue;
            }

            // Create parent directory.
            if let Some(parent) = target.parent() {
                if !parent.exists() {
                    if let Err(e) = std::fs::create_dir_all(parent) {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(e, "creating parent directory"),
                        ));
                        continue;
                    }
                }
            }

            // Write entry content — atomically create or fail.
            let output = if overwrite {
                match std::fs::File::create(&target) {
                    Ok(f) => f,
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(
                                e,
                                format!("creating output file '{}'", target.display()),
                            ),
                        ));
                        continue;
                    }
                }
            } else {
                match std::fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&target)
                {
                    Ok(f) => f,
                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                        report.files_skipped += 1;
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::clobber_denied(target.display().to_string()),
                        ));
                        continue;
                    }
                    Err(e) => {
                        report.errors.push((
                            entry.path.clone(),
                            crate::error::GeeZipError::io(
                                e,
                                format!("creating output file '{}'", target.display()),
                            ),
                        ));
                        continue;
                    }
                }
            };

            let mut output = CancellableWriter::new(output, is_cancelled);

            match self.extract(entry, &mut output) {
                Ok(bytes) => {
                    if output.was_cancelled() {
                        return Err(GeeZipError::Cancelled);
                    }
                    report.files_extracted += 1;
                    report.bytes_extracted += bytes;
                }
                Err(e) => {
                    report.errors.push((entry.path.clone(), e));
                }
            }
        }

        Ok(report)
    }

    /// Set a password for decrypting encrypted entries (ZIP AES-256).
    ///
    /// The default implementation is a no-op. Only archive formats that
    /// support encryption (currently ZIP) override this method.
    fn set_password(&mut self, _password: &str) -> GeeZipResult<()> {
        Ok(())
    }
}

/// Archive writer trait — add files and finalise.
///
/// Implementations own their output writer internally.  Callers construct
/// the writer then call [`finish`](ArchiveWriter::finish) to finalise the
/// archive.
pub trait ArchiveWriter: Send {
    /// The format being written.
    fn format(&self) -> ArchiveFormat;

    /// Add a new entry from a byte stream.
    ///
    /// **Note:** Some archive formats (notably tar) require the entry
    /// size to be known _before_ the payload is written, which means
    /// the implementation may need to buffer the entire entry in
    /// memory.  For streaming-friendly formats (e.g., ZIP) this is
    /// handled transparently by the encoder.  Callers should avoid
    /// passing unbounded streams when using tar-based writers.
    fn add_entry_from_reader(&mut self, path: &Path, reader: &mut dyn Read) -> GeeZipResult<()>;

    /// Finalise the archive and return the total bytes written.
    ///
    /// After this call the writer is consumed and must not be used again.
    fn finish(self: Box<Self>) -> GeeZipResult<u64>;

    /// Add a directory entry to the archive.
    ///
    /// The default implementation does nothing, which is correct for formats
    /// that don't require explicit directory entries (ZIP stores them
    /// implicitly via path prefixes in file entries). Override this for
    /// formats like tar that require explicit directory headers.
    fn add_directory(&mut self, _path: &Path) -> GeeZipResult<()> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Resolve a path by eliminating `.` and `..` components, without
/// accessing the filesystem (unlike `canonicalize`).
pub(crate) fn normalize_path(path: &Path) -> std::path::PathBuf {
    let mut components: Vec<std::ffi::OsString> = Vec::new();
    let root_separator = std::ffi::OsString::from(std::path::MAIN_SEPARATOR.to_string());

    for component in path.components() {
        match component {
            std::path::Component::RootDir => {
                components.push(root_separator.clone());
            }
            std::path::Component::CurDir => {
                // Keep the first CurDir so that normalize_path(".") stays "."
                // and normalize_path("./foo") stays "./foo".
                // This preserves the relative prefix for starts_with
                // comparisons in extract_all's Zip Slip check.
                if components.is_empty() {
                    components.push(std::ffi::OsString::from("."));
                }
            }
            std::path::Component::ParentDir => {
                if let Some(last) = components.last() {
                    if last.as_os_str() == root_separator.as_os_str() {
                        // Cannot go above root (e.g. /foo/.. stays /) — discard.
                        continue;
                    } else if last.as_os_str() == "." {
                        // `.` followed by `..` → replace with `..`
                        components.pop();
                        components.push(std::ffi::OsString::from(".."));
                    } else if last.as_os_str() == ".." {
                        // Multiple `..` in a row — keep them all
                        components.push(std::ffi::OsString::from(".."));
                    } else {
                        // Normal component — pop it (foo/.. cancels out)
                        components.pop();
                    }
                } else {
                    // Leading `..` with nothing to pop — keep it
                    components.push(std::ffi::OsString::from(".."));
                }
            }
            c => components.push(c.as_os_str().to_os_string()),
        }
    }

    let mut result = std::path::PathBuf::new();
    for c in components {
        result.push(c);
    }
    // If the result would be empty (e.g. input was `foo/..`), emit `.`
    // so that `starts_with` checks still work correctly.
    if result.as_os_str().is_empty() {
        result.push(".");
    }
    result
}

/// Check whether extracting `entry_path` under `dest` would escape the
/// target directory (Zip Slip protection).
///
/// Returns `Ok(normalised_target)` if safe, or `Err((name, err))` suitable
/// for pushing into [`ExtractReport::errors`].
pub fn check_entry_path_safety(
    entry_path: &Path,
    entry_name: &str,
    dest: &Path,
) -> std::result::Result<std::path::PathBuf, (String, GeeZipError)> {
    // Reject absolute entry paths (e.g. /etc/passwd, C:\\foo).
    if entry_path.has_root() {
        return Err((
            entry_name.to_owned(),
            GeeZipError::PathTraversal {
                entry: entry_name.to_owned(),
                target: dest.display().to_string(),
            },
        ));
    }

    // On Windows, also reject UNC / device-prefixed paths.
    #[cfg(windows)]
    {
        let path_os = entry_name.replace("/", "\\");
        if path_os.starts_with("\\\\") {
            return Err((
                entry_name.to_owned(),
                GeeZipError::PathTraversal {
                    entry: entry_name.to_owned(),
                    target: dest.display().to_string(),
                },
            ));
        }
    }

    // Resolve the target relative to dest, then normalise.
    let target = normalize_path(&dest.join(entry_path));

    // Verify the resolved path is still under dest.
    if !target.starts_with(dest) {
        return Err((
            entry_name.to_owned(),
            GeeZipError::PathTraversal {
                entry: entry_name.to_owned(),
                target: dest.display().to_string(),
            },
        ));
    }

    Ok(target)
}

/// Check whether an entry path is potentially dangerous (Zip Slip)
/// **without** requiring a destination directory.
///
/// Returns `true` if the path:
/// - Is absolute (e.g. `/etc/passwd`, `C:\\foo`).
/// - Starts with a Windows UNC / device prefix (`\\`).
/// - Normalises to a path that escapes the current directory
///   (e.g. `../evil.txt`, `foo/../../evil.txt`).
///
/// This is suitable for read-only operations such as `list` where
/// we only need to warn the user, not block extraction.
pub fn is_entry_path_dangerous(path: &Path) -> bool {
    // Reject absolute entry paths.
    if path.has_root() {
        return true;
    }

    // On Windows, also reject UNC / device-prefixed paths.
    #[cfg(windows)]
    {
        let path_os = path.to_string_lossy().replace("/", "\\");
        if path_os.starts_with("\\\\") {
            return true;
        }
    }

    // Normalise and check whether the result escapes above cwd.
    let normalised = normalize_path(path);
    let first = normalised.components().next();
    matches!(first, Some(std::path::Component::ParentDir))
}

/// Counting writer wrapper that tracks total bytes written through a
/// writer chain.
///
/// Used internally by [`TarWriter`](crate::archive::tar::TarWriter) and
/// [`TarGzWriter`](crate::archive::targz::TarGzWriter).
pub(crate) struct CountWriter<W> {
    pub(crate) inner: W,
    pub(crate) count: u64,
}

impl<W: std::io::Write> std::io::Write for CountWriter<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let n = self.inner.write(buf)?;
        self.count += n as u64;
        Ok(n)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

// ---------------------------------------------------------------------------
// CancellableWriter
// ---------------------------------------------------------------------------

/// Writer wrapper that checks cancellation before every `write` and `flush`.
///
/// Used by [`extract_all_with_cancel`](ArchiveReader::extract_all_with_cancel)
/// to support Ctrl+C cancellation during per-entry extraction.
///
/// On cancellation the wrapper returns `ErrorKind::Interrupted` with
/// message "operation cancelled by user".
pub(crate) struct CancellableWriter<'a, W> {
    inner: W,
    is_cancelled: &'a dyn Fn() -> bool,
    cancelled: bool,
}

impl<'a, W> CancellableWriter<'a, W> {
    pub(crate) fn new(inner: W, is_cancelled: &'a dyn Fn() -> bool) -> Self {
        CancellableWriter {
            inner,
            is_cancelled,
            cancelled: false,
        }
    }

    /// Returns `true` if a cancellation was detected during the last write.
    pub(crate) fn was_cancelled(&self) -> bool {
        self.cancelled
    }
}

impl<W: std::io::Write> std::io::Write for CancellableWriter<'_, W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if (self.is_cancelled)() {
            self.cancelled = true;
            return Err(std::io::Error::new(
                std::io::ErrorKind::Interrupted,
                "operation cancelled by user",
            ));
        }
        self.inner.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if (self.is_cancelled)() {
            self.cancelled = true;
            return Err(std::io::Error::new(
                std::io::ErrorKind::Interrupted,
                "operation cancelled by user",
            ));
        }
        self.inner.flush()
    }
}

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

    #[test]
    fn normalize_path_simple() {
        let p = normalize_path(Path::new("/a/b/c"));
        assert_eq!(p, Path::new("/a/b/c"));
    }

    #[test]
    fn normalize_path_with_dotdot() {
        let p = normalize_path(Path::new("/a/b/../c"));
        assert_eq!(p, Path::new("/a/c"));
    }

    #[test]
    fn normalize_path_with_curdir() {
        let p = normalize_path(Path::new("/a/./b"));
        assert_eq!(p, Path::new("/a/b"));
    }

    #[test]
    fn normalize_path_below_root_escape() {
        // Escaping above root — this is fine, normalize just does its thing.
        let p = normalize_path(Path::new("/a/../../c"));
        assert_eq!(p, Path::new("/c"));
    }

    #[test]
    fn normalize_path_preserves_leading_curdir() {
        // normalize_path must keep a leading CurDir so that
        // starts_with comparisons work for dest=".".
        assert_eq!(normalize_path(Path::new(".")), Path::new("."));
        assert_eq!(normalize_path(Path::new("./foo")), Path::new("./foo"));
        assert_eq!(normalize_path(Path::new("./a/b")), Path::new("./a/b"));
    }

    #[test]
    fn normalize_path_with_leading_dotdot() {
        // Parent-dir at the start must be preserved.
        assert_eq!(normalize_path(Path::new("../foo")), Path::new("../foo"));
        assert_eq!(normalize_path(Path::new("./../foo")), Path::new("../foo"));
        assert_eq!(normalize_path(Path::new("./..")), Path::new(".."));
        assert_eq!(normalize_path(Path::new("./a/../../b")), Path::new("../b"));
    }

    #[test]
    fn normalize_path_multiple_dotdot() {
        assert_eq!(
            normalize_path(Path::new("../../foo")),
            Path::new("../../foo")
        );
        assert_eq!(
            normalize_path(Path::new("./../../foo")),
            Path::new("../../foo")
        );
        assert_eq!(normalize_path(Path::new("a/../..")), Path::new(".."));
    }

    #[test]
    fn normalize_path_complex_traversal() {
        assert_eq!(
            normalize_path(Path::new("a/b/../../../c")),
            Path::new("../c")
        );
        assert_eq!(normalize_path(Path::new("a/./../../b")), Path::new("../b"));
        assert_eq!(
            normalize_path(Path::new("a/./../b/.././c/../d")),
            Path::new("d")
        );
    }

    #[test]
    fn normalize_path_ipv6_root() {
        // Regression: check that OS root separator comparison works.
        assert_eq!(normalize_path(Path::new("/a/b/../c")), Path::new("/a/c"));
        assert_eq!(normalize_path(Path::new("/a/../../c")), Path::new("/c"));
    }

    #[test]
    fn normalize_path_curdir_peers() {
        // Ensure these still pass for dest="." checks.
        assert_eq!(normalize_path(Path::new(".")), Path::new("."));
        assert_eq!(normalize_path(Path::new("./foo")), Path::new("./foo"));
        assert_eq!(normalize_path(Path::new("./a/b")), Path::new("./a/b"));
    }

    #[test]
    fn cancellable_writer_detects_cancellation() {
        let mut buf = Vec::new();
        let cancelled = true;
        let is_cancelled = || cancelled;
        let mut writer = CancellableWriter::new(&mut buf, &is_cancelled);

        // write should fail with Interrupted
        let result = writer.write(b"hello");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted);
        assert!(writer.was_cancelled());
        // buffer should be empty since the write didn't go through
        assert!(buf.is_empty());
    }

    #[test]
    fn cancellable_writer_passes_through_when_not_cancelled() {
        let mut buf = Vec::new();
        let cancelled = false;
        let is_cancelled = || cancelled;
        let mut writer = CancellableWriter::new(&mut buf, &is_cancelled);

        let n = writer.write(b"hello").unwrap();
        assert_eq!(n, 5);
        assert!(!writer.was_cancelled());
        assert_eq!(&buf, b"hello");
    }

    #[test]
    fn datetime_to_timestamp_rejects_invalid_month_day() {
        // month must be 1..=12, day must be >=1 and <= month length.
        assert_eq!(datetime_to_timestamp(2026, 0, 15, 0, 0, 0), 0);
        assert_eq!(datetime_to_timestamp(2026, 13, 15, 0, 0, 0), 0);
        assert_eq!(datetime_to_timestamp(2026, 6, 0, 0, 0, 0), 0);
        assert_eq!(datetime_to_timestamp(2026, 6, 31, 0, 0, 0), 0); // Jun has 30 days
        assert!(datetime_to_timestamp(2026, 6, 15, 0, 0, 0) > 0); // valid input => non-zero
        assert!(datetime_to_timestamp(2026, 6, 15, 0, 0, 0) > 0);
    }

    #[test]
    fn cancellable_writer_flush_detects_cancellation() {
        use std::cell::Cell;
        let cancelled = Cell::new(false);
        let is_cancelled = || cancelled.get();
        let mut buf = Vec::new();
        let mut writer = CancellableWriter::new(&mut buf, &is_cancelled);
        writer.write_all(b"data").unwrap();
        // Now flip the flag and flush should fail.
        cancelled.set(true);
        let result = writer.flush();
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted);
        assert!(writer.was_cancelled());
        // Data written before cancellation should still be present.
        assert_eq!(&buf, b"data");
    }

    #[test]
    #[cfg(not(windows))]
    fn check_entry_path_safety_rejects_absolute() {
        // Absolute entry paths (e.g., /etc/passwd) should be rejected.
        // Unix absolute paths (starting with /) are used because the function's
        // has_root() check is independent of platform-specific path conventions.
        let dest = Path::new("/tmp/out");
        let result = check_entry_path_safety(Path::new("/etc/passwd"), "/etc/passwd", dest);
        assert!(result.is_err());
        let (name, err) = result.unwrap_err();
        assert_eq!(name, "/etc/passwd");
        assert!(matches!(err, GeeZipError::PathTraversal { .. }));
    }

    #[test]
    fn check_entry_path_safety_rejects_traversal() {
        // Path traversal via .. should be rejected.
        let dest = Path::new("/tmp/out");
        let result = check_entry_path_safety(Path::new("../etc/passwd"), "../etc/passwd", dest);
        assert!(result.is_err());
        let (name, err) = result.unwrap_err();
        assert_eq!(name, "../etc/passwd");
        assert!(matches!(err, GeeZipError::PathTraversal { .. }));
    }

    #[test]
    fn check_entry_path_safety_accepts_normal() {
        // Normal relative paths should be accepted.
        let dest = Path::new("/tmp/out");
        let result = check_entry_path_safety(Path::new("file.txt"), "file.txt", dest);
        assert!(result.is_ok());
        let target = result.unwrap();
        assert_eq!(target, Path::new("/tmp/out/file.txt"));
    }

    #[test]
    fn normalize_path_edge_cases() {
        // Empty path normalizes to "."
        assert_eq!(normalize_path(Path::new("")), Path::new("."));
        // Single root
        assert_eq!(normalize_path(Path::new("/")), Path::new("/"));
        // Trailing dot cancels out
        assert_eq!(normalize_path(Path::new("foo/.")), Path::new("foo"));
        // Multiple consecutive slashes (collapsed by path components)
        assert_eq!(normalize_path(Path::new("a//b")), Path::new("a/b"));
        assert!(!normalize_path(Path::new("a//b")).as_os_str().is_empty());
    }

    #[test]
    fn datetime_to_timestamp_leap_year() {
        // 2024-02-29 12:00:00 is a valid leap year date.
        let ts = datetime_to_timestamp(2024, 2, 29, 12, 0, 0);
        assert!(ts > 0, "leap year Feb 29 should produce a valid timestamp");
        // 2023-02-29 is not a leap year, so should be rejected.
        assert_eq!(datetime_to_timestamp(2023, 2, 29, 0, 0, 0), 0);
    }

    #[test]
    fn datetime_to_timestamp_valid_date_range() {
        // A date well past epoch should produce a large timestamp.
        let ts = datetime_to_timestamp(2026, 6, 2, 0, 0, 0);
        assert!(ts > 0);
        assert!(ts > 1700000000, "2026-06-02 should be well past epoch");
    }

    // ---------------------------------------------------------------------------
    // CountWriter tests
    // ---------------------------------------------------------------------------

    #[test]
    fn count_writer_tracks_bytes() {
        let inner = Vec::new();
        let mut writer = CountWriter { inner, count: 0 };

        let n = writer.write(b"hello").unwrap();
        assert_eq!(n, 5);
        assert_eq!(writer.count, 5);

        let n = writer.write(b" world").unwrap();
        assert_eq!(n, 6);
        assert_eq!(writer.count, 11);

        writer.flush().unwrap();

        assert_eq!(&writer.inner, b"hello world");
    }

    // ---------------------------------------------------------------------------
    // extract_all tests (via mock readers)
    // ---------------------------------------------------------------------------

    /// Mock reader used for testing extract_all with directory entries.
    struct MockDirReader {
        entries: Vec<Entry>,
    }

    impl ArchiveReader for MockDirReader {
        fn format(&self) -> ArchiveFormat {
            ArchiveFormat::Tar
        }

        fn entries(&mut self) -> GeeZipResult<Vec<Entry>> {
            Ok(self.entries.clone())
        }

        fn extract(&mut self, _entry: &Entry, writer: &mut dyn Write) -> GeeZipResult<u64> {
            // The extract_all default implementation only calls extract
            // for non-directory entries, so this is only reached for files.
            let content = b"file content";
            writer.write_all(content)?;
            Ok(content.len() as u64)
        }
    }

    #[test]
    fn extract_all_creates_directories() {
        let entries = vec![
            Entry {
                path: "emptydir".into(),
                size: 0,
                compressed_size: 0,
                crc32: None,
                modified: None,
                is_dir: true,
            },
            Entry {
                path: "emptydir/file.txt".into(),
                size: 12,
                compressed_size: 0,
                crc32: None,
                modified: None,
                is_dir: false,
            },
        ];

        let mut reader = MockDirReader { entries };
        let tmp = tempfile::tempdir().unwrap();
        let report = reader.extract_all(tmp.path(), true).unwrap();

        assert!(
            tmp.path().join("emptydir").is_dir(),
            "directory entry should create a directory on disk"
        );
        assert!(
            tmp.path().join("emptydir/file.txt").is_file(),
            "file entry should be extracted"
        );
        assert_eq!(report.files_extracted, 2);
        assert_eq!(report.bytes_extracted, 12);
        assert!(report.errors.is_empty(), "extract_all errors: {report:?}");
    }

    /// Mock reader that always writes the same content on extract.
    struct MockFileReader {
        entries: Vec<Entry>,
    }

    impl ArchiveReader for MockFileReader {
        fn format(&self) -> ArchiveFormat {
            ArchiveFormat::Tar
        }

        fn entries(&mut self) -> GeeZipResult<Vec<Entry>> {
            Ok(self.entries.clone())
        }

        fn extract(&mut self, _entry: &Entry, writer: &mut dyn Write) -> GeeZipResult<u64> {
            let content = b"mock file content";
            writer.write_all(content)?;
            Ok(content.len() as u64)
        }
    }

    #[test]
    fn extract_all_skips_existing_on_no_clobber() {
        let entries = vec![Entry {
            path: "existing.txt".into(),
            size: 16,
            compressed_size: 0,
            crc32: None,
            modified: None,
            is_dir: false,
        }];

        let tmp = tempfile::tempdir().unwrap();
        let dest = tmp.path().to_path_buf();

        // First extract with overwrite = true should create the file.
        let mut reader = MockFileReader {
            entries: entries.clone(),
        };
        let report1 = reader.extract_all(&dest, true).unwrap();
        assert_eq!(
            report1.files_extracted, 1,
            "should extract the file on first run"
        );
        assert_eq!(report1.files_skipped, 0);
        assert!(report1.errors.is_empty(), "errors: {report1:?}");

        let content = std::fs::read_to_string(dest.join("existing.txt")).unwrap();
        assert_eq!(content, "mock file content");

        // Second extract with overwrite = false should skip the existing file.
        let mut reader2 = MockFileReader {
            entries: entries.clone(),
        };
        let report2 = reader2.extract_all(&dest, false).unwrap();
        assert_eq!(report2.files_extracted, 0);
        assert_eq!(report2.files_skipped, 1);
        assert_eq!(
            report2.errors.len(),
            1,
            "should have one ClobberDenied error"
        );
        assert!(
            matches!(report2.errors[0].1, GeeZipError::ClobberDenied { .. }),
            "error should be ClobberDenied"
        );

        // Verify the file content was NOT overwritten.
        let content2 = std::fs::read_to_string(dest.join("existing.txt")).unwrap();
        assert_eq!(
            content2, "mock file content",
            "file should not be overwritten"
        );
    }
}