1use std::path::Path;
4
5use crate::ArchiveError;
6use crate::ArchiveReader;
7use crate::CreateRequest;
8use crate::EntrySink;
9use crate::ExtractRequest;
10use crate::ExtractionReport;
11use crate::OutputFile;
12use crate::OutputFormat;
13use crate::ProgressCallback;
14use crate::Result;
15use crate::SecurityConfig;
16use crate::config::ExtractionOptions;
17use crate::creation::CreationConfig;
18use crate::creation::CreationReport;
19use crate::formats::SevenZArchive;
20use crate::formats::ZipArchive;
21use crate::formats::compression::CompressionCodec;
22use crate::formats::compression::DecoderLimits;
23use crate::formats::detect::CreatableFormat;
24use crate::formats::detect::FormatFamily;
25use crate::formats::detect::detect_format;
26use crate::formats::detect::detect_format_from_extension;
27use crate::formats::detect::is_zip_family_alias;
28use crate::formats::source_fault::TapSource;
29use crate::inspection::ArchiveManifest;
30use crate::inspection::VerificationReport;
31use crate::inspection::integrity::TarTrailer;
32use crate::reader::SeekableFormat;
33use crate::reader::Source;
34use crate::reader::tar_archive;
35use crate::sink::SinkOptions;
36use crate::sink::SinkReuse;
37use crate::sink::SinkTarget;
38
39pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
72 archive_path: P,
73 output_dir: Q,
74 config: &SecurityConfig,
75) -> Result<ExtractionReport> {
76 ExtractRequest::new(config).extract(archive_path, output_dir)
77}
78
79pub(crate) fn extract_validated<P: AsRef<Path>, Q: AsRef<Path>>(
81 archive_path: P,
82 output_dir: Q,
83 config: &SecurityConfig,
84 options: &ExtractionOptions,
85 progress: &mut dyn ProgressCallback,
86) -> Result<ExtractionReport> {
87 let archive_path = archive_path.as_ref();
88 let output_dir = output_dir.as_ref();
89
90 let format = detect_format(archive_path)?;
92
93 match format.family() {
95 FormatFamily::Tar(codec) => {
96 extract_tar(archive_path, output_dir, config, options, progress, codec)
97 }
98 FormatFamily::Seekable(SeekableFormat::Zip) => {
99 extract_zip(archive_path, output_dir, config, options, progress)
100 }
101 FormatFamily::Seekable(SeekableFormat::SevenZ) => {
102 extract_7z(archive_path, output_dir, config, options, progress)
103 }
104 }
105}
106
107pub(crate) fn extract_staged(
111 output_dir: &Path,
112 options: &ExtractionOptions,
113 extract: impl FnOnce(&Path) -> Result<ExtractionReport>,
114) -> Result<ExtractionReport> {
115 if options.atomic {
116 extract_atomic(output_dir, extract)
117 } else {
118 extract(output_dir)
119 }
120}
121
122#[expect(
123 clippy::disallowed_methods,
124 reason = "stages the whole extraction in a private sibling directory, then renames it into place"
125)]
126fn extract_atomic(
127 output_dir: &Path,
128 extract: impl FnOnce(&Path) -> Result<ExtractionReport>,
129) -> Result<ExtractionReport> {
130 let canonical_output = if output_dir.exists() {
134 output_dir.canonicalize().map_err(ArchiveError::Io)?
135 } else {
136 output_dir.to_path_buf()
137 };
138
139 let parent = canonical_output
140 .parent()
141 .ok_or(ArchiveError::InvalidConfiguration {
142 setting: crate::ConfigSetting::OutputPath,
143 problem: crate::ConfigProblem::NoParent,
144 })?;
145
146 std::fs::create_dir_all(parent).map_err(ArchiveError::Io)?;
147
148 let temp_dir = tempfile::Builder::new()
149 .prefix(".exarch-")
150 .tempdir_in(parent)
151 .map_err(|e| {
152 ArchiveError::Io(std::io::Error::new(
153 e.kind(),
154 format!(
155 "failed to create temp directory in {}: {e}",
156 parent.display()
157 ),
158 ))
159 })?;
160
161 let result = extract(temp_dir.path());
162
163 match result {
164 Ok(report) => {
165 let temp_path = temp_dir.keep();
167 std::fs::rename(&temp_path, output_dir).map_err(|e| {
168 let _ = std::fs::remove_dir_all(&temp_path);
170 if e.kind() == std::io::ErrorKind::AlreadyExists {
172 ArchiveError::OutputExists {
173 path: output_dir.to_path_buf(),
174 }
175 } else {
176 ArchiveError::Io(std::io::Error::new(
177 e.kind(),
178 format!("failed to rename temp dir to {}: {e}", output_dir.display()),
179 ))
180 }
181 })?;
182
183 Ok(report)
184 }
185 Err(e) => {
186 Err(e.rolled_back())
188 }
189 }
190}
191
192fn extract_tar(
195 archive_path: &Path,
196 output_dir: &Path,
197 config: &SecurityConfig,
198 options: &ExtractionOptions,
199 progress: &mut dyn ProgressCallback,
200 codec: Option<CompressionCodec>,
201) -> Result<ExtractionReport> {
202 use crate::formats::tar::open_tar_stream;
203
204 let decoded = open_tar_stream(archive_path, codec, DecoderLimits::of(config))?;
205 let trailer = TarTrailer::for_codec(codec);
206 let source = decoded.source();
207 extract_tar_stream(
208 decoded.stream,
209 source,
210 trailer,
211 output_dir,
212 config,
213 options,
214 progress,
215 )
216}
217
218pub(crate) fn extract_tar_stream<R: std::io::Read>(
222 stream: R,
223 source: TapSource,
224 trailer: TarTrailer,
225 output_dir: &Path,
226 config: &SecurityConfig,
227 options: &ExtractionOptions,
228 progress: &mut dyn ProgressCallback,
229) -> Result<ExtractionReport> {
230 use crate::formats::TarArchive;
231 use crate::formats::traits::ArchiveFormat;
232
233 TarArchive::with_source(stream, source, trailer, config).extract(output_dir, options, progress)
234}
235
236fn extract_zip(
237 archive_path: &Path,
238 output_dir: &Path,
239 config: &SecurityConfig,
240 options: &ExtractionOptions,
241 progress: &mut dyn ProgressCallback,
242) -> Result<ExtractionReport> {
243 use crate::formats::ZipArchive;
244 use crate::formats::traits::ArchiveFormat;
245 use std::fs::File;
246
247 let file = File::open(archive_path)?;
248 let archive = ZipArchive::for_extraction(file, config, options.decode_reuse)?;
249 archive.extract(output_dir, options, progress)
250}
251
252fn extract_7z(
253 archive_path: &Path,
254 output_dir: &Path,
255 config: &SecurityConfig,
256 options: &ExtractionOptions,
257 progress: &mut dyn ProgressCallback,
258) -> Result<ExtractionReport> {
259 use crate::formats::SevenZArchive;
260 use crate::formats::traits::ArchiveFormat;
261 use std::fs::File;
262
263 let file = File::open(archive_path)?;
264 let archive = SevenZArchive::new(file, config)?;
265 archive.extract(output_dir, options, progress)
266}
267
268pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
303 output_path: P,
304 sources: &[Q],
305 config: &CreationConfig,
306) -> Result<CreationReport> {
307 CreateRequest::new(config).create(&OutputFile::replace(output_path.as_ref()), sources)
308}
309
310pub fn list_archive<P: AsRef<Path>>(
346 archive_path: P,
347 config: &SecurityConfig,
348) -> Result<ArchiveManifest> {
349 crate::inspection::list_archive(archive_path, config)
350}
351
352pub fn verify_archive<P: AsRef<Path>>(
407 archive_path: P,
408 config: &SecurityConfig,
409) -> Result<VerificationReport> {
410 crate::inspection::verify_archive(archive_path, config)
411}
412
413pub(crate) fn extract_to_sink_reusing<S: EntrySink>(
416 reader: ArchiveReader<'_>,
417 sink: &mut S,
418 config: &SecurityConfig,
419 options: SinkOptions,
420 progress: &mut dyn ProgressCallback,
421 reuse: Option<SinkReuse>,
422) -> Result<ExtractionReport> {
423 match reader.into_source() {
424 Source::Tar { stream, codec } => {
425 let archive = tar_archive(stream, codec, config)?;
426 let mut target = SinkTarget::new(sink, config);
427 archive.extract_into(&mut target, config, options, progress)
428 }
429 Source::Seekable {
430 reader,
431 format: SeekableFormat::Zip,
432 } => {
433 let mut archive = match reuse {
434 Some(reuse) => ZipArchive::for_sink(reader, config, &reuse)?,
435 None => ZipArchive::for_extraction(reader, config, options.decode_reuse)?,
436 };
437 archive.check_structure(config)?.extract_with(
438 |config| Ok(SinkTarget::new(sink, config)),
439 options,
440 progress,
441 )
442 }
443 Source::Seekable {
444 reader,
445 format: SeekableFormat::SevenZ,
446 } => {
447 let mut archive = SevenZArchive::new(reader, config)?;
448 archive.admit(config)?.extract_with(
449 |config| Ok(SinkTarget::new(sink, config)),
450 options,
451 progress,
452 )
453 }
454 }
455}
456
457fn reject_zip_family_creation(output: &Path) -> Result<()> {
469 let Some(ext) = output.extension().and_then(|e| e.to_str()) else {
470 return Ok(());
471 };
472 if is_zip_family_alias(ext) {
473 let ext_lower = ext.to_ascii_lowercase();
474 return Err(ArchiveError::unclassified(format!(
475 "creation for .{ext_lower} isn't supported: the format is ZIP-based but \
476 requires extra structure (signing, manifests, ordering) that exarch \
477 doesn't produce. Use .zip, or state the format with \
478 OutputFile::with_format(exarch_core::formats::detect::CreatableFormat::Zip) \
479 to override."
480 )));
481 }
482 Ok(())
483}
484
485pub(crate) fn resolve_output_format(output: &OutputFile) -> Result<CreatableFormat> {
491 match output.format() {
492 OutputFormat::Explicit(format) => Ok(format),
493 OutputFormat::FromExtension => {
494 reject_zip_family_creation(output.path())?;
495 CreatableFormat::try_from(detect_format_from_extension(output.path())?)
496 }
497 }
498}
499
500#[cfg(test)]
501#[allow(clippy::unwrap_used)]
502mod tests {
503 use super::*;
504 use crate::NoopProgress;
505 use crate::raw_zip::RawEntry;
506 use crate::raw_zip::RawZip;
507 use std::assert_matches;
508 use std::path::PathBuf;
509
510 #[test]
511 fn test_extract_archive_nonexistent_file() {
512 let config = SecurityConfig::default();
513 let result = extract_archive(
514 PathBuf::from("nonexistent_test.tar"),
515 PathBuf::from("/tmp/test"),
516 &config,
517 );
518 assert!(result.is_err());
520 }
521
522 #[test]
523 fn test_determine_creation_format_tar() {
524 let path = PathBuf::from("archive.tar");
525 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
526 assert_eq!(format, CreatableFormat::Tar);
527 }
528
529 #[test]
530 fn test_determine_creation_format_tar_gz() {
531 let path = PathBuf::from("archive.tar.gz");
532 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
533 assert_eq!(format, CreatableFormat::TarGz);
534
535 let path2 = PathBuf::from("archive.tgz");
536 let format2 = resolve_output_format(&OutputFile::replace(&path2)).unwrap();
537 assert_eq!(format2, CreatableFormat::TarGz);
538 }
539
540 #[test]
541 fn test_determine_creation_format_tar_bz2() {
542 let path = PathBuf::from("archive.tar.bz2");
543 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
544 assert_eq!(format, CreatableFormat::TarBz2);
545 }
546
547 #[test]
548 fn test_determine_creation_format_tar_xz() {
549 let path = PathBuf::from("archive.tar.xz");
550 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
551 assert_eq!(format, CreatableFormat::TarXz);
552 }
553
554 #[test]
555 fn test_determine_creation_format_tar_zst() {
556 let path = PathBuf::from("archive.tar.zst");
557 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
558 assert_eq!(format, CreatableFormat::TarZst);
559 }
560
561 #[test]
562 fn test_determine_creation_format_zip() {
563 let path = PathBuf::from("archive.zip");
564 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
565 assert_eq!(format, CreatableFormat::Zip);
566 }
567
568 #[test]
569 fn test_determine_creation_format_explicit() {
570 let path = PathBuf::from("archive.xyz");
571 let output = OutputFile::replace(&path).with_format(CreatableFormat::TarGz);
572 let format = resolve_output_format(&output).unwrap();
573 assert_eq!(format, CreatableFormat::TarGz);
574 }
575
576 #[test]
577 fn test_determine_creation_format_unknown() {
578 let path = PathBuf::from("archive.rar");
579 let result = resolve_output_format(&OutputFile::replace(&path));
580 assert!(result.is_err());
581 }
582
583 #[test]
584 fn test_determine_creation_format_ignores_stale_magic_bytes() {
585 let dir = tempfile::tempdir().unwrap();
588 let path = dir.path().join("backup.zip");
589 std::fs::write(&path, b"\x1f\x8b\x08\x00\x00\x00\x00\x00").unwrap();
591
592 let format = resolve_output_format(&OutputFile::replace(&path)).unwrap();
593 assert_eq!(
594 format,
595 CreatableFormat::Zip,
596 "creation format must follow extension, not stale on-disk magic bytes"
597 );
598 }
599
600 #[test]
601 fn test_extract_archive_7z_not_implemented() {
602 let dest = tempfile::TempDir::new().unwrap();
603 let path = PathBuf::from("test.7z");
604
605 let result = extract_archive(&path, dest.path(), &SecurityConfig::default());
606
607 assert!(result.is_err());
608 }
609
610 #[test]
611 fn test_create_archive_zip_family_not_supported() {
612 let dest = tempfile::TempDir::new().unwrap();
616 for ext in ["apk", "whl", "EPUB"] {
617 let archive_path = dest.path().join(format!("output.{ext}"));
618 let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
619 assert_matches!(
620 result,
621 Err(ArchiveError::InvalidArchive(_)),
622 ".{ext} should be rejected, got {result:?}",
623 );
624 }
625 }
626
627 #[test]
628 fn test_create_archive_zip_family_override_bypasses_guard() {
629 let dest = tempfile::TempDir::new().unwrap();
633 let src = dest.path().join("source.txt");
634 std::fs::write(&src, b"hello").unwrap();
635 let archive_path = dest.path().join("output.apk");
636 let result = CreateRequest::new(&CreationConfig::default()).create(
637 &OutputFile::replace(&archive_path).with_format(CreatableFormat::Zip),
638 &[&src],
639 );
640 assert!(
641 result.is_ok(),
642 "explicit format override should bypass the guard, got {result:?}",
643 );
644 }
645
646 #[test]
647 fn test_create_archive_7z_not_supported() {
648 let dest = tempfile::TempDir::new().unwrap();
649 let archive_path = dest.path().join("output.7z");
650
651 let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
652
653 assert!(result.is_err());
654 assert_matches!(
655 result.unwrap_err(),
656 ArchiveError::InvalidConfiguration { .. }
657 );
658 }
659
660 #[test]
661 fn test_extract_archive_with_options_and_progress_non_atomic_delegates_to_normal() {
662 let dest = tempfile::TempDir::new().unwrap();
663 let options = ExtractionOptions {
664 atomic: false,
665 skip_duplicates: true,
666 ..ExtractionOptions::default()
667 };
668 let result = ExtractRequest::new(&SecurityConfig::default())
669 .with_options(options)
670 .with_progress(&mut NoopProgress)
671 .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
672 assert!(result.is_err());
673 }
674
675 #[test]
676 fn test_extract_archive_with_options_delegates() {
677 let dest = tempfile::TempDir::new().unwrap();
678 let options = ExtractionOptions {
679 atomic: false,
680 skip_duplicates: true,
681 ..ExtractionOptions::default()
682 };
683 let result = ExtractRequest::new(&SecurityConfig::default())
684 .with_options(options)
685 .extract(PathBuf::from("nonexistent.tar.gz"), dest.path());
686 assert!(result.is_err());
687 }
688
689 #[test]
690 fn test_extract_atomic_success() {
691 use crate::create_archive;
692 use crate::creation::CreationConfig;
693
694 let archive_dir = tempfile::TempDir::new().unwrap();
696 let archive_path = archive_dir.path().join("test.tar.gz");
697
698 let src_dir = tempfile::TempDir::new().unwrap();
700 std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
701 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
702
703 let parent = tempfile::TempDir::new().unwrap();
704 let output_dir = parent.path().join("extracted");
705
706 let options = ExtractionOptions {
707 atomic: true,
708 skip_duplicates: true,
709 ..ExtractionOptions::default()
710 };
711 let result = ExtractRequest::new(&SecurityConfig::default())
712 .with_options(options)
713 .extract(&archive_path, &output_dir);
714
715 assert!(result.is_ok());
716 assert!(output_dir.exists());
717 let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
719 assert_eq!(
720 temp_entries.len(),
721 1,
722 "Expected only the output dir, found temp remnants"
723 );
724 }
725
726 #[test]
727 fn test_extract_atomic_failure_cleans_up() {
728 let parent = tempfile::TempDir::new().unwrap();
729 let output_dir = parent.path().join("extracted");
730
731 let options = ExtractionOptions {
732 atomic: true,
733 skip_duplicates: true,
734 ..ExtractionOptions::default()
735 };
736 let result = ExtractRequest::new(&SecurityConfig::default())
737 .with_options(options)
738 .extract(PathBuf::from("nonexistent_archive.tar.gz"), &output_dir);
739
740 assert!(result.is_err());
741 assert!(!output_dir.exists());
743 let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
745 assert!(
746 temp_entries.is_empty(),
747 "Temp dir not cleaned up after failure"
748 );
749 }
750
751 #[test]
752 fn test_extract_atomic_output_already_exists_fails() {
753 use crate::create_archive;
754 use crate::creation::CreationConfig;
755
756 let parent = tempfile::TempDir::new().unwrap();
757 let output_dir = parent.path().join("extracted");
758 std::fs::create_dir_all(&output_dir).unwrap();
759 std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();
762
763 let archive_dir = tempfile::TempDir::new().unwrap();
764 let archive_path = archive_dir.path().join("test.tar.gz");
765 let src_dir = tempfile::TempDir::new().unwrap();
766 std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
767 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
768
769 let options = ExtractionOptions {
770 atomic: true,
771 skip_duplicates: true,
772 ..ExtractionOptions::default()
773 };
774 let result = ExtractRequest::new(&SecurityConfig::default())
775 .with_options(options)
776 .extract(&archive_path, &output_dir);
777
778 assert!(result.is_err());
781 assert!(output_dir.join("existing.txt").exists());
783 }
784
785 #[test]
787 fn test_progress_callback_invoked_during_extraction() {
788 use crate::ProgressCallback;
789 use std::path::Path;
790
791 struct TrackingProgress {
792 started: usize,
793 completed: usize,
794 finished: bool,
795 }
796
797 impl ProgressCallback for TrackingProgress {
798 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
799 self.started += 1;
800 }
801
802 fn on_bytes_written(&mut self, _bytes: u64) {}
803
804 fn on_entry_complete(&mut self, _path: &Path) {
805 self.completed += 1;
806 }
807
808 fn on_complete(&mut self) {
809 self.finished = true;
810 }
811 }
812
813 let archive_dir = tempfile::TempDir::new().unwrap();
814 let archive_path = archive_dir.path().join("test.tar.gz");
815 let src_dir = tempfile::TempDir::new().unwrap();
816 std::fs::write(src_dir.path().join("a.txt"), b"hello").unwrap();
817 std::fs::write(src_dir.path().join("b.txt"), b"world").unwrap();
818 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
819
820 let dest = tempfile::TempDir::new().unwrap();
821 let mut progress = TrackingProgress {
822 started: 0,
823 completed: 0,
824 finished: false,
825 };
826
827 let report = ExtractRequest::new(&SecurityConfig::default())
828 .with_progress(&mut progress)
829 .extract(&archive_path, dest.path())
830 .unwrap();
831
832 assert!(report.files_extracted >= 2, "expected at least 2 files");
833 assert!(progress.started >= 2, "on_entry_start not called");
834 assert!(progress.completed >= 2, "on_entry_complete not called");
835 assert!(progress.finished, "on_complete not called");
836 }
837
838 #[test]
840 fn test_progress_callback_invoked_during_zip_extraction() {
841 use crate::ProgressCallback;
842 use std::path::Path;
843
844 struct TrackingProgress {
845 started: usize,
846 completed: usize,
847 finished: bool,
848 }
849
850 impl ProgressCallback for TrackingProgress {
851 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
852 self.started += 1;
853 }
854
855 fn on_bytes_written(&mut self, _bytes: u64) {}
856
857 fn on_entry_complete(&mut self, _path: &Path) {
858 self.completed += 1;
859 }
860
861 fn on_complete(&mut self) {
862 self.finished = true;
863 }
864 }
865
866 let tmp = tempfile::TempDir::new().unwrap();
867 let archive_path = tmp.path().join("test.zip");
868 let src_dir = tempfile::TempDir::new().unwrap();
869 std::fs::write(src_dir.path().join("x.txt"), b"foo").unwrap();
870 std::fs::write(src_dir.path().join("y.txt"), b"bar").unwrap();
871 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
872
873 let dest = tempfile::TempDir::new().unwrap();
874 let mut progress = TrackingProgress {
875 started: 0,
876 completed: 0,
877 finished: false,
878 };
879 let report = ExtractRequest::new(&SecurityConfig::default())
880 .with_progress(&mut progress)
881 .extract(&archive_path, dest.path())
882 .unwrap();
883
884 assert!(report.files_extracted >= 2, "expected at least 2 files");
885 assert!(progress.started >= 2, "on_entry_start not called for ZIP");
886 assert!(
887 progress.completed >= 2,
888 "on_entry_complete not called for ZIP"
889 );
890 assert!(progress.finished, "on_complete not called for ZIP");
891 }
892
893 #[test]
895 fn test_progress_callback_invoked_during_sevenz_extraction() {
896 use crate::ProgressCallback;
897 use std::path::Path;
898
899 struct TrackingProgress {
900 started: usize,
901 completed: usize,
902 finished: bool,
903 }
904
905 impl ProgressCallback for TrackingProgress {
906 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
907 self.started += 1;
908 }
909
910 fn on_bytes_written(&mut self, _bytes: u64) {}
911
912 fn on_entry_complete(&mut self, _path: &Path) {
913 self.completed += 1;
914 }
915
916 fn on_complete(&mut self) {
917 self.finished = true;
918 }
919 }
920
921 let fixture =
922 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
923
924 let dest = tempfile::TempDir::new().unwrap();
925 let mut progress = TrackingProgress {
926 started: 0,
927 completed: 0,
928 finished: false,
929 };
930 let report = ExtractRequest::new(&SecurityConfig::default())
931 .with_progress(&mut progress)
932 .extract(&fixture, dest.path())
933 .unwrap();
934
935 assert!(
936 report.files_extracted >= 1,
937 "expected at least 1 file from simple.7z"
938 );
939 assert!(progress.started >= 1, "on_entry_start not called for 7z");
940 assert!(
941 progress.completed >= 1,
942 "on_entry_complete not called for 7z"
943 );
944 assert!(progress.finished, "on_complete not called for 7z");
945 }
946
947 #[test]
950 fn test_on_bytes_written_called_for_tar() {
951 use crate::ProgressCallback;
952 use std::path::Path;
953
954 struct ByteTracker {
955 total: u64,
956 }
957
958 impl ProgressCallback for ByteTracker {
959 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
960
961 fn on_bytes_written(&mut self, bytes: u64) {
962 self.total += bytes;
963 }
964
965 fn on_entry_complete(&mut self, _path: &Path) {}
966
967 fn on_complete(&mut self) {}
968 }
969
970 let archive_dir = tempfile::TempDir::new().unwrap();
971 let archive_path = archive_dir.path().join("test.tar.gz");
972 let src_dir = tempfile::TempDir::new().unwrap();
973 std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
974 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
975
976 let dest = tempfile::TempDir::new().unwrap();
977 let mut progress = ByteTracker { total: 0 };
978 let report = ExtractRequest::new(&SecurityConfig::default())
979 .with_progress(&mut progress)
980 .extract(&archive_path, dest.path())
981 .unwrap();
982
983 assert!(
984 report.bytes_written > 0,
985 "report.bytes_written must be > 0, got {}",
986 report.bytes_written
987 );
988 assert!(
989 progress.total > 0,
990 "on_bytes_written must be called with > 0 bytes for TAR, got {}",
991 progress.total
992 );
993 }
994
995 #[test]
998 fn test_on_bytes_written_called_for_zip() {
999 use crate::ProgressCallback;
1000 use std::path::Path;
1001
1002 struct ByteTracker {
1003 total: u64,
1004 }
1005
1006 impl ProgressCallback for ByteTracker {
1007 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1008
1009 fn on_bytes_written(&mut self, bytes: u64) {
1010 self.total += bytes;
1011 }
1012
1013 fn on_entry_complete(&mut self, _path: &Path) {}
1014
1015 fn on_complete(&mut self) {}
1016 }
1017
1018 let tmp = tempfile::TempDir::new().unwrap();
1019 let archive_path = tmp.path().join("test.zip");
1020 let src_dir = tempfile::TempDir::new().unwrap();
1021 std::fs::write(src_dir.path().join("data.txt"), b"hello world").unwrap();
1022 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1023
1024 let dest = tempfile::TempDir::new().unwrap();
1025 let mut progress = ByteTracker { total: 0 };
1026 let report = ExtractRequest::new(&SecurityConfig::default())
1027 .with_progress(&mut progress)
1028 .extract(&archive_path, dest.path())
1029 .unwrap();
1030
1031 assert!(
1032 report.bytes_written > 0,
1033 "report.bytes_written must be > 0, got {}",
1034 report.bytes_written
1035 );
1036 assert!(
1037 progress.total > 0,
1038 "on_bytes_written must be called with > 0 bytes for ZIP, got {}",
1039 progress.total
1040 );
1041 }
1042
1043 #[test]
1046 fn test_on_bytes_written_called_for_sevenz() {
1047 use crate::ProgressCallback;
1048 use std::path::Path;
1049
1050 struct ByteTracker {
1051 total: u64,
1052 }
1053
1054 impl ProgressCallback for ByteTracker {
1055 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1056
1057 fn on_bytes_written(&mut self, bytes: u64) {
1058 self.total += bytes;
1059 }
1060
1061 fn on_entry_complete(&mut self, _path: &Path) {}
1062
1063 fn on_complete(&mut self) {}
1064 }
1065
1066 let fixture =
1067 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1068
1069 let dest = tempfile::TempDir::new().unwrap();
1070 let mut progress = ByteTracker { total: 0 };
1071 let report = ExtractRequest::new(&SecurityConfig::default())
1072 .with_progress(&mut progress)
1073 .extract(&fixture, dest.path())
1074 .unwrap();
1075
1076 assert!(
1077 report.bytes_written > 0,
1078 "report.bytes_written must be > 0, got {}",
1079 report.bytes_written
1080 );
1081 assert!(
1082 progress.total > 0,
1083 "on_bytes_written must be called with > 0 bytes for 7z, got {}",
1084 progress.total
1085 );
1086 }
1087
1088 #[test]
1091 fn test_tar_hardlink_calls_on_bytes_written() {
1092 use crate::ProgressCallback;
1093 use crate::formats::TarArchive;
1094 use crate::formats::traits::ArchiveFormat;
1095 use std::io::Cursor;
1096 use std::path::Path;
1097
1098 struct ByteTracker {
1099 total: u64,
1100 }
1101
1102 impl ProgressCallback for ByteTracker {
1103 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {}
1104
1105 fn on_bytes_written(&mut self, bytes: u64) {
1106 self.total += bytes;
1107 }
1108
1109 fn on_entry_complete(&mut self, _path: &Path) {}
1110
1111 fn on_complete(&mut self) {}
1112 }
1113
1114 let content = b"hello hardlink";
1116 let tar_data = {
1117 let mut builder = tar::Builder::new(Vec::new());
1118
1119 let mut header = tar::Header::new_gnu();
1120 header.set_size(content.len() as u64);
1121 header.set_mode(0o644);
1122 header.set_entry_type(tar::EntryType::Regular);
1123 header.set_cksum();
1124 builder
1125 .append_data(&mut header, "original.txt", content.as_ref())
1126 .unwrap();
1127
1128 let mut hdr = tar::Header::new_gnu();
1129 hdr.set_size(0);
1130 hdr.set_mode(0o644);
1131 hdr.set_entry_type(tar::EntryType::Link);
1132 hdr.set_link_name("original.txt").unwrap();
1133 hdr.set_cksum();
1134 builder
1135 .append_data(&mut hdr, "link.txt", std::io::empty())
1136 .unwrap();
1137
1138 builder.into_inner().unwrap()
1139 };
1140
1141 let temp = tempfile::TempDir::new().unwrap();
1142 let mut config = SecurityConfig::default();
1143 config.allowed.hardlinks = crate::Admit::Allow;
1144
1145 let archive = TarArchive::new(Cursor::new(tar_data), &config);
1146 let mut progress = ByteTracker { total: 0 };
1147 let report = archive
1148 .extract(temp.path(), &ExtractionOptions::default(), &mut progress)
1149 .unwrap();
1150
1151 let expected = (content.len() as u64) * 2;
1154 assert_eq!(
1155 progress.total, expected,
1156 "on_bytes_written must report bytes for both original and hardlink copy, \
1157 got {} (report.bytes_written={})",
1158 progress.total, report.bytes_written
1159 );
1160 }
1161
1162 #[test]
1165 fn test_tar_on_entry_complete_called_on_path_traversal_error() {
1166 use crate::ProgressCallback;
1167 use crate::formats::TarArchive;
1168 use crate::formats::traits::ArchiveFormat;
1169 use std::io::Cursor;
1170 use std::path::Path;
1171
1172 struct SymmetryTracker {
1173 started: usize,
1174 completed: usize,
1175 }
1176
1177 impl ProgressCallback for SymmetryTracker {
1178 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
1179 self.started += 1;
1180 }
1181
1182 fn on_bytes_written(&mut self, _bytes: u64) {}
1183
1184 fn on_entry_complete(&mut self, _path: &Path) {
1185 self.completed += 1;
1186 }
1187
1188 fn on_complete(&mut self) {}
1189 }
1190
1191 let tar_data = make_raw_tar_single(b"../../etc/passwd", b"evil");
1194
1195 let temp = tempfile::TempDir::new().unwrap();
1196 let archive = TarArchive::new(Cursor::new(tar_data), &SecurityConfig::default());
1197 let mut progress = SymmetryTracker {
1198 started: 0,
1199 completed: 0,
1200 };
1201 let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);
1202
1203 assert!(result.is_err(), "traversal entry must be rejected");
1204 assert_eq!(
1205 progress.started, progress.completed,
1206 "on_entry_complete must be called for every on_entry_start, \
1207 even when extraction fails: started={}, completed={}",
1208 progress.started, progress.completed
1209 );
1210 }
1211
1212 #[test]
1215 fn test_zip_on_entry_complete_called_on_path_traversal_error() {
1216 use crate::ProgressCallback;
1217 use crate::formats::ZipArchive;
1218 use crate::formats::traits::ArchiveFormat;
1219 use std::io::Cursor;
1220 use std::path::Path;
1221
1222 struct SymmetryTracker {
1223 started: usize,
1224 completed: usize,
1225 }
1226
1227 impl ProgressCallback for SymmetryTracker {
1228 fn on_entry_start(&mut self, _path: &Path, _position: crate::EntryPosition) {
1229 self.started += 1;
1230 }
1231
1232 fn on_bytes_written(&mut self, _bytes: u64) {}
1233
1234 fn on_entry_complete(&mut self, _path: &Path) {
1235 self.completed += 1;
1236 }
1237
1238 fn on_complete(&mut self) {}
1239 }
1240
1241 let zip_data = make_zip_with_traversal(b"../../etc/passwd", b"evil");
1243
1244 let temp = tempfile::TempDir::new().unwrap();
1245 let archive = ZipArchive::new(Cursor::new(zip_data), &SecurityConfig::default()).unwrap();
1246 let mut progress = SymmetryTracker {
1247 started: 0,
1248 completed: 0,
1249 };
1250 let result = archive.extract(temp.path(), &ExtractionOptions::default(), &mut progress);
1251
1252 assert!(result.is_err(), "traversal entry must be rejected");
1253 assert_eq!(
1254 progress.started, progress.completed,
1255 "on_entry_complete must be called for every on_entry_start in ZIP, \
1256 even when extraction fails: started={}, completed={}",
1257 progress.started, progress.completed
1258 );
1259 }
1260
1261 fn make_raw_tar_single(path: &[u8], data: &[u8]) -> Vec<u8> {
1264 let mut out = Vec::new();
1265 let mut header = [0u8; 512];
1266
1267 let path_len = path.len().min(100);
1268 header[..path_len].copy_from_slice(&path[..path_len]);
1269 header[100..108].copy_from_slice(b"0000644\0");
1270 header[108..116].copy_from_slice(b"0000000\0");
1271 header[116..124].copy_from_slice(b"0000000\0");
1272 let size_str = format!("{:011o}\0", data.len());
1273 header[124..136].copy_from_slice(size_str.as_bytes());
1274 header[136..148].copy_from_slice(b"00000000000\0");
1275 header[156] = b'0';
1276 header[257..263].copy_from_slice(b"ustar ");
1277 header[263..265].copy_from_slice(b" \0");
1278 header[148..156].copy_from_slice(b" ");
1279 let checksum: u32 = header.iter().map(|&b| u32::from(b)).sum();
1280 let ck_str = format!("{checksum:06o}\0 ");
1281 header[148..156].copy_from_slice(ck_str.as_bytes());
1282
1283 out.extend_from_slice(&header);
1284 out.extend_from_slice(data);
1285 let rem = data.len() % 512;
1286 if rem != 0 {
1287 out.extend(std::iter::repeat_n(0u8, 512 - rem));
1288 }
1289 out.extend(std::iter::repeat_n(0u8, 1024));
1290 out
1291 }
1292
1293 fn make_zip_with_traversal(path: &[u8], data: &[u8]) -> Vec<u8> {
1296 let entry = RawEntry {
1297 name: path.to_vec(),
1298 date: 0,
1299 ..RawEntry::stored("", data)
1300 };
1301 RawZip::new(vec![entry]).build().bytes
1302 }
1303}