Skip to main content

exarch_core/
api.rs

1//! High-level public API for archive extraction, creation, and inspection.
2
3use std::path::Path;
4
5use crate::ArchiveError;
6use crate::ArchiveReader;
7use crate::EntrySink;
8use crate::ExtractionReport;
9use crate::ListOptions;
10use crate::NoopProgress;
11use crate::ProgressCallback;
12use crate::Result;
13use crate::SecurityConfig;
14use crate::VerificationOptions;
15use crate::config::ExtractionOptions;
16use crate::config::Validated;
17use crate::creation::CreationConfig;
18use crate::creation::CreationReport;
19use crate::formats::SevenZArchive;
20use crate::formats::ZipArchive;
21use crate::formats::compression::CompressionCodec;
22use crate::formats::detect::CreatableFormat;
23use crate::formats::detect::CreationFamily;
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::inspection::ArchiveManifest;
29use crate::inspection::VerificationReport;
30use crate::inspection::list::ListPass;
31use crate::reader::SeekableFormat;
32use crate::reader::Source;
33use crate::reader::tar_archive;
34use crate::sink::SinkOptions;
35use crate::sink::SinkTarget;
36
37/// Extracts an archive to the specified output directory.
38///
39/// This is the main high-level API for extracting archives with security
40/// validation. The archive format is automatically detected.
41///
42/// # Arguments
43///
44/// * `archive_path` - Path to the archive file
45/// * `output_dir` - Directory where files will be extracted
46/// * `config` - Security configuration for the extraction
47///
48/// # Errors
49///
50/// Returns an error if:
51/// - Archive file cannot be opened
52/// - Archive format is unsupported
53/// - Security validation fails
54/// - I/O operations fail
55///
56/// # Examples
57///
58/// ```no_run
59/// use exarch_core::SecurityConfig;
60/// use exarch_core::extract_archive;
61///
62/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
63/// let config = SecurityConfig::default();
64/// let report = extract_archive("archive.tar.gz", "/tmp/output", &config)?;
65/// println!("Extracted {} files", report.files_extracted);
66/// # Ok(())
67/// # }
68/// ```
69pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
70    archive_path: P,
71    output_dir: Q,
72    config: &SecurityConfig,
73) -> Result<ExtractionReport> {
74    let mut noop = NoopProgress;
75    extract_archive_with_progress(archive_path, output_dir, config, &mut noop)
76}
77
78/// Extracts an archive with progress reporting.
79///
80/// Same as `extract_archive` but accepts a `ProgressCallback` for
81/// real-time progress updates during extraction.
82///
83/// # Arguments
84///
85/// * `archive_path` - Path to the archive file
86/// * `output_dir` - Directory where files will be extracted
87/// * `config` - Security configuration for the extraction
88/// * `progress` - Callback for progress updates
89///
90/// # Errors
91///
92/// Returns an error if:
93/// - Archive file cannot be opened
94/// - Archive format is unsupported
95/// - Security validation fails
96/// - I/O operations fail
97///
98/// # Examples
99///
100/// ```no_run
101/// use exarch_core::NoopProgress;
102/// use exarch_core::SecurityConfig;
103/// use exarch_core::extract_archive_with_progress;
104///
105/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
106/// let config = SecurityConfig::default();
107/// let mut progress = NoopProgress;
108/// let report =
109///     extract_archive_with_progress("archive.tar.gz", "/tmp/output", &config, &mut progress)?;
110/// println!("Extracted {} files", report.files_extracted);
111/// # Ok(())
112/// # }
113/// ```
114pub fn extract_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
115    archive_path: P,
116    output_dir: Q,
117    config: &SecurityConfig,
118    progress: &mut dyn ProgressCallback,
119) -> Result<ExtractionReport> {
120    let options = ExtractionOptions::default();
121    extract_archive_with_options_and_progress(archive_path, output_dir, config, &options, progress)
122}
123
124fn extract_impl<P: AsRef<Path>, Q: AsRef<Path>>(
125    archive_path: P,
126    output_dir: Q,
127    config: &SecurityConfig,
128    options: &ExtractionOptions,
129    progress: &mut dyn ProgressCallback,
130) -> Result<ExtractionReport> {
131    let config = config.clone().validate()?;
132    let config = &config;
133
134    let archive_path = archive_path.as_ref();
135    let output_dir = output_dir.as_ref();
136
137    // Detect archive format from file extension
138    let format = detect_format(archive_path)?;
139
140    // Dispatch to format-specific extraction
141    match format.family() {
142        FormatFamily::Tar(codec) => {
143            extract_tar(archive_path, output_dir, config, options, progress, codec)
144        }
145        FormatFamily::Seekable(SeekableFormat::Zip) => {
146            extract_zip(archive_path, output_dir, config, options, progress)
147        }
148        FormatFamily::Seekable(SeekableFormat::SevenZ) => {
149            extract_7z(archive_path, output_dir, config, options, progress)
150        }
151    }
152}
153
154/// Extracts an archive with extraction options and optional progress reporting.
155///
156/// This is the canonical extraction implementation. All other
157/// `extract_archive*` functions are thin wrappers that delegate here. Use this
158/// directly when you need both [`ExtractionOptions`] (e.g., atomic mode) and a
159/// progress callback.
160///
161/// # Arguments
162///
163/// * `archive_path` - Path to the archive file
164/// * `output_dir` - Directory where files will be extracted
165/// * `config` - Security configuration for the extraction
166/// * `options` - Extraction behavior options (e.g., atomic mode)
167/// * `progress` - Callback for progress updates
168///
169/// # Errors
170///
171/// Returns an error if:
172/// - Archive file cannot be opened
173/// - Archive format is unsupported
174/// - Security validation fails
175/// - I/O operations fail
176/// - Atomic temp dir creation or rename fails
177///
178/// # Examples
179///
180/// ```no_run
181/// use exarch_core::ExtractionOptions;
182/// use exarch_core::NoopProgress;
183/// use exarch_core::SecurityConfig;
184/// use exarch_core::extract_archive_with_options_and_progress;
185///
186/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
187/// let config = SecurityConfig::default();
188/// let options = ExtractionOptions::default().with_atomic(true);
189/// let mut progress = NoopProgress;
190/// let report = extract_archive_with_options_and_progress(
191///     "archive.tar.gz",
192///     "/tmp/output",
193///     &config,
194///     &options,
195///     &mut progress,
196/// )?;
197/// println!("Extracted {} files", report.files_extracted);
198/// # Ok(())
199/// # }
200/// ```
201pub fn extract_archive_with_options_and_progress<P: AsRef<Path>, Q: AsRef<Path>>(
202    archive_path: P,
203    output_dir: Q,
204    config: &SecurityConfig,
205    options: &ExtractionOptions,
206    progress: &mut dyn ProgressCallback,
207) -> Result<ExtractionReport> {
208    if options.atomic {
209        extract_atomic(archive_path, output_dir, config, options, progress)
210    } else {
211        extract_impl(archive_path, output_dir, config, options, progress)
212    }
213}
214
215/// Extracts an archive with extraction options (no progress reporting).
216///
217/// Convenience wrapper around [`extract_archive_with_options_and_progress`]
218/// that passes a no-op progress callback. Use this when you need
219/// [`ExtractionOptions`] but do not require progress updates.
220///
221/// # Errors
222///
223/// Returns an error if:
224/// - Archive file cannot be opened
225/// - Archive format is unsupported
226/// - Security validation fails
227/// - I/O operations fail
228/// - Atomic temp dir creation or rename fails
229///
230/// # Examples
231///
232/// ```no_run
233/// use exarch_core::ExtractionOptions;
234/// use exarch_core::SecurityConfig;
235/// use exarch_core::extract_archive_with_options;
236///
237/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
238/// let config = SecurityConfig::default();
239/// let options = ExtractionOptions::default().with_atomic(true);
240/// let report = extract_archive_with_options("archive.tar.gz", "/tmp/output", &config, &options)?;
241/// println!("Extracted {} files", report.files_extracted);
242/// # Ok(())
243/// # }
244/// ```
245pub fn extract_archive_with_options<P: AsRef<Path>, Q: AsRef<Path>>(
246    archive_path: P,
247    output_dir: Q,
248    config: &SecurityConfig,
249    options: &ExtractionOptions,
250) -> Result<ExtractionReport> {
251    let mut noop = NoopProgress;
252    extract_archive_with_options_and_progress(archive_path, output_dir, config, options, &mut noop)
253}
254
255fn extract_atomic<P: AsRef<Path>, Q: AsRef<Path>>(
256    archive_path: P,
257    output_dir: Q,
258    config: &SecurityConfig,
259    options: &ExtractionOptions,
260    progress: &mut dyn ProgressCallback,
261) -> Result<ExtractionReport> {
262    let output_dir = output_dir.as_ref();
263
264    // Canonicalize output_dir to resolve any symlinks in the path before
265    // computing the parent, so temp dir lands on the same filesystem.
266    // If output_dir doesn't exist yet, use its lexical parent.
267    let canonical_output = if output_dir.exists() {
268        output_dir.canonicalize().map_err(ArchiveError::Io)?
269    } else {
270        output_dir.to_path_buf()
271    };
272
273    let parent = canonical_output
274        .parent()
275        .ok_or_else(|| ArchiveError::InvalidConfiguration {
276            reason: "output directory has no parent".into(),
277        })?;
278
279    std::fs::create_dir_all(parent).map_err(ArchiveError::Io)?;
280
281    let temp_dir = tempfile::Builder::new()
282        .prefix(".exarch-")
283        .tempdir_in(parent)
284        .map_err(|e| {
285            ArchiveError::Io(std::io::Error::new(
286                e.kind(),
287                format!(
288                    "failed to create temp directory in {}: {e}",
289                    parent.display()
290                ),
291            ))
292        })?;
293
294    let result = extract_impl(archive_path, temp_dir.path(), config, options, progress);
295
296    match result {
297        Ok(report) => {
298            // Consume TempDir to prevent Drop cleanup, then rename.
299            let temp_path = temp_dir.keep();
300            std::fs::rename(&temp_path, output_dir).map_err(|e| {
301                // Rename failed: clean up temp dir
302                let _ = std::fs::remove_dir_all(&temp_path);
303                // Map AlreadyExists to OutputExists for caller clarity
304                if e.kind() == std::io::ErrorKind::AlreadyExists {
305                    ArchiveError::OutputExists {
306                        path: output_dir.to_path_buf(),
307                    }
308                } else {
309                    ArchiveError::Io(std::io::Error::new(
310                        e.kind(),
311                        format!("failed to rename temp dir to {}: {e}", output_dir.display()),
312                    ))
313                }
314            })?;
315
316            Ok(report)
317        }
318        Err(e) => {
319            // TempDir Drop runs here: cleans up temp dir automatically.
320            Err(e.rolled_back())
321        }
322    }
323}
324
325/// Opens `archive_path` as a TAR stream (decoded with `codec` when present)
326/// and extracts it.
327fn extract_tar(
328    archive_path: &Path,
329    output_dir: &Path,
330    config: &SecurityConfig<Validated>,
331    options: &ExtractionOptions,
332    progress: &mut dyn ProgressCallback,
333    codec: Option<CompressionCodec>,
334) -> Result<ExtractionReport> {
335    use crate::formats::TarArchive;
336    use crate::formats::tar::open_tar_stream;
337    use crate::formats::traits::ArchiveFormat;
338
339    let stream = open_tar_stream(archive_path, codec, config.max_decoder_memory)?;
340    let mut archive = TarArchive::new(stream);
341    archive.extract(output_dir, config, options, progress)
342}
343
344fn extract_zip(
345    archive_path: &Path,
346    output_dir: &Path,
347    config: &SecurityConfig<Validated>,
348    options: &ExtractionOptions,
349    progress: &mut dyn ProgressCallback,
350) -> Result<ExtractionReport> {
351    use crate::formats::ZipArchive;
352    use crate::formats::traits::ArchiveFormat;
353    use std::fs::File;
354
355    let file = File::open(archive_path)?;
356    let mut archive = ZipArchive::new(file)?;
357    archive.extract(output_dir, config, options, progress)
358}
359
360fn extract_7z(
361    archive_path: &Path,
362    output_dir: &Path,
363    config: &SecurityConfig<Validated>,
364    options: &ExtractionOptions,
365    progress: &mut dyn ProgressCallback,
366) -> Result<ExtractionReport> {
367    use crate::formats::SevenZArchive;
368    use crate::formats::traits::ArchiveFormat;
369    use std::fs::File;
370
371    let file = File::open(archive_path)?;
372    let mut archive = SevenZArchive::new(file)?;
373    archive.extract(output_dir, config, options, progress)
374}
375
376/// Creates an archive from source files and directories.
377///
378/// Format is auto-detected from output file extension, or can be
379/// explicitly set via `config.format`.
380///
381/// # Arguments
382///
383/// * `output_path` - Path to the output archive file
384/// * `sources` - Source files and directories to include
385/// * `config` - Creation configuration
386///
387/// # Errors
388///
389/// Returns an error if:
390/// - Cannot determine archive format
391/// - Source files don't exist
392/// - I/O operations fail
393/// - Configuration is invalid
394///
395/// # Examples
396///
397/// ```no_run
398/// use exarch_core::create_archive;
399/// use exarch_core::creation::CreationConfig;
400///
401/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
402/// let config = CreationConfig::default();
403/// let report = create_archive("output.tar.gz", &["src/", "Cargo.toml"], &config)?;
404/// println!("Created archive with {} files", report.files_added);
405/// # Ok(())
406/// # }
407/// ```
408pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
409    output_path: P,
410    sources: &[Q],
411    config: &CreationConfig,
412) -> Result<CreationReport> {
413    let mut noop = NoopProgress;
414    create_archive_with_progress(output_path, sources, config, &mut noop)
415}
416
417/// Creates an archive with progress reporting.
418///
419/// Same as `create_archive` but accepts a `ProgressCallback` for
420/// real-time progress updates during creation.
421///
422/// # Arguments
423///
424/// * `output_path` - Path to the output archive file
425/// * `sources` - Source files and directories to include
426/// * `config` - Creation configuration
427/// * `progress` - Callback for progress updates
428///
429/// # Errors
430///
431/// Returns an error if:
432/// - Cannot determine archive format
433/// - Source files don't exist
434/// - I/O operations fail
435/// - Configuration is invalid
436///
437/// # Examples
438///
439/// ```no_run
440/// use exarch_core::NoopProgress;
441/// use exarch_core::create_archive_with_progress;
442/// use exarch_core::creation::CreationConfig;
443///
444/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
445/// let config = CreationConfig::default();
446/// let mut progress = NoopProgress;
447/// let report = create_archive_with_progress(
448///     "output.tar.gz",
449///     &["src/", "Cargo.toml"],
450///     &config,
451///     &mut progress,
452/// )?;
453/// println!("Created archive with {} files", report.files_added);
454/// # Ok(())
455/// # }
456/// ```
457pub fn create_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
458    output_path: P,
459    sources: &[Q],
460    config: &CreationConfig,
461    progress: &mut dyn ProgressCallback,
462) -> Result<CreationReport> {
463    let config = config.clone().validate()?;
464    let config = &config;
465
466    let output = output_path.as_ref();
467
468    // Block creation for the ZIP-family extensions (mirrors the 7z block
469    // below). They're all ZIP underneath but add extra requirements -
470    // signing (apk/aab/ipa/appx/msix), checksum manifests (whl), ordering
471    // and stored-compression rules (epub), descriptor files
472    // (war/ear/vsix/nbm) - which exarch doesn't produce. Silently emitting
473    // a bare ZIP with one of these extensions would be misleading, so we
474    // error instead. Callers who need the override can set
475    // CreationConfig::format = Some(CreatableFormat::Zip).
476    if config.format.is_none() {
477        reject_zip_family_creation(output)?;
478    }
479
480    // Determine format from extension or config
481    let format = determine_creation_format(output, config)?;
482
483    let source_refs: Vec<&Path> = sources.iter().map(AsRef::as_ref).collect();
484    let creator = creator_for_format(format);
485    creator.create(output, &source_refs, config, progress)
486}
487
488fn creator_for_format(format: CreatableFormat) -> Box<dyn crate::formats::traits::FormatCreator> {
489    match format.family() {
490        CreationFamily::Tar(codec) => Box::new(crate::creation::TarCreator(codec)),
491        CreationFamily::Zip => Box::new(crate::creation::ZipCreator),
492    }
493}
494
495/// Lists archive contents without extracting.
496///
497/// Returns a manifest containing metadata for all entries in the archive.
498/// No files are written to disk during this operation.
499///
500/// # Arguments
501///
502/// * `archive_path` - Path to archive file
503/// * `config` - Security configuration (quota limits apply)
504///
505/// # Errors
506///
507/// Returns error if:
508/// - Archive file cannot be opened
509/// - Archive format is unsupported or corrupted
510/// - Quota limits exceeded (file count, total size, single file size)
511/// - Declared compressed sizes exceed the archive length
512///
513/// # Examples
514///
515/// ```no_run
516/// use exarch_core::SecurityConfig;
517/// use exarch_core::list_archive;
518///
519/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
520/// let config = SecurityConfig::default();
521/// let manifest = list_archive("archive.tar.gz", &config)?;
522///
523/// println!("Archive contains {} files", manifest.total_entries());
524/// for entry in manifest.entries() {
525///     println!("{}: {} bytes", entry.path.display(), entry.size);
526/// }
527/// # Ok(())
528/// # }
529/// ```
530pub fn list_archive<P: AsRef<Path>>(
531    archive_path: P,
532    config: &SecurityConfig,
533) -> Result<ArchiveManifest> {
534    crate::inspection::list_archive(archive_path, config)
535}
536
537/// Lists archive contents without extracting, with
538/// [`ListOptions`].
539///
540/// [`ListOptions::stored_targets`](crate::ListOptions::stored_targets) set to
541/// [`StoredTargets::Read`](crate::StoredTargets::Read) reads 7z symlink
542/// targets, which decodes the blocks that hold them; by default they are left
543/// unread, so listing decodes no entry data. This is a Rust API option only:
544/// the Python and Node `list_archive` leave 7z targets unread.
545///
546/// # Errors
547///
548/// Same as [`list_archive`].
549///
550/// # Examples
551///
552/// ```no_run
553/// use exarch_core::ListOptions;
554/// use exarch_core::SecurityConfig;
555/// use exarch_core::StoredTargets;
556/// use exarch_core::list_archive_with_options;
557///
558/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
559/// let config = SecurityConfig::default();
560/// let options = ListOptions::default().with_stored_targets(StoredTargets::Read);
561/// let manifest = list_archive_with_options("archive.7z", &config, &options)?;
562/// println!("Archive contains {} entries", manifest.total_entries());
563/// # Ok(())
564/// # }
565/// ```
566pub fn list_archive_with_options<P: AsRef<Path>>(
567    archive_path: P,
568    config: &SecurityConfig,
569    options: &crate::ListOptions,
570) -> Result<ArchiveManifest> {
571    crate::inspection::list_archive_with_options(archive_path, config, options)
572}
573
574/// Verifies archive security without extracting.
575///
576/// Performs metadata-only validation:
577/// - Security checks (path traversal, zip bombs, CVEs)
578/// - Policy checks (file types, permissions)
579///
580/// Payload integrity (checksums, decode-to-end) is not verified: the report's
581/// `integrity_status` is
582/// [`IntegrityStatus::Skipped`](crate::IntegrityStatus::Skipped);
583/// use [`verify_archive_with_options`] to request it.
584///
585/// # Arguments
586///
587/// * `archive_path` - Path to archive file
588/// * `config` - Security configuration for validation
589///
590/// # Errors
591///
592/// Returns error if:
593/// - Archive file cannot be opened
594/// - Archive is severely corrupted (cannot read structure)
595/// - Declared compressed sizes exceed the archive length
596/// - An entry name is a path traversal (`..` component, or an absolute path
597///   unless `allowed.absolute_paths` is set): the listing step rejects it with
598///   [`ArchiveError::PathTraversal`] before a report exists
599///
600/// Other security violations are reported in `VerificationReport::issues`
601/// instead: disallowed links, link targets that escape the destination,
602/// quota and compression-ratio violations, NUL bytes, banned components and
603/// unsafe permissions.
604///
605/// # Examples
606///
607/// ```no_run
608/// use exarch_core::SecurityConfig;
609/// use exarch_core::VerificationStatus;
610/// use exarch_core::verify_archive;
611///
612/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
613/// let config = SecurityConfig::default();
614/// let report = verify_archive("archive.tar.gz", &config)?;
615///
616/// if report.status() == VerificationStatus::Pass {
617///     println!("Archive is safe to extract");
618/// } else {
619///     eprintln!("Security issues found:");
620///     for issue in report.issues() {
621///         eprintln!("  [{}] {}", issue.severity, issue.message);
622///     }
623/// }
624/// # Ok(())
625/// # }
626/// ```
627pub fn verify_archive<P: AsRef<Path>>(
628    archive_path: P,
629    config: &SecurityConfig,
630) -> Result<VerificationReport> {
631    crate::inspection::verify_archive(archive_path, config)
632}
633
634/// Verifies archive security, optionally checking payload integrity.
635///
636/// See [`crate::inspection::verify_archive_with_options`] for what each
637/// integrity status means per format.
638///
639/// # Errors
640///
641/// Returns the errors of [`verify_archive`]; with integrity requested, a TAR
642/// entry whose content fails to decode is also an error.
643///
644/// # Examples
645///
646/// ```no_run
647/// use exarch_core::SecurityConfig;
648/// use exarch_core::VerificationOptions;
649/// use exarch_core::verify_archive_with_options;
650///
651/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
652/// let report = verify_archive_with_options(
653///     "archive.zip",
654///     &SecurityConfig::default(),
655///     &VerificationOptions::default(),
656/// )?;
657/// println!("{}", report.integrity_status());
658/// # Ok(())
659/// # }
660/// ```
661pub fn verify_archive_with_options<P: AsRef<Path>>(
662    archive_path: P,
663    config: &SecurityConfig,
664    options: &crate::VerificationOptions,
665) -> Result<VerificationReport> {
666    crate::inspection::verify_archive_with_options(archive_path, config, options)
667}
668
669/// Lists the contents of an archive read from a reader.
670///
671/// The reader counterpart of [`list_archive_with_options`]: the same listing,
672/// limits and failures, for an archive that is not a file on disk.
673///
674/// # Errors
675///
676/// Same as [`list_archive`], except that nothing is opened or detected: a
677/// malformed archive fails as it would from a file.
678///
679/// # Examples
680///
681/// ```
682/// use exarch_core::ArchiveReader;
683/// use exarch_core::ListOptions;
684/// use exarch_core::SecurityConfig;
685/// use exarch_core::list_reader;
686///
687/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
688/// let mut builder = tar::Builder::new(Vec::new());
689/// let mut header = tar::Header::new_gnu();
690/// header.set_size(2);
691/// header.set_mode(0o644);
692/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
693/// let bytes = builder.into_inner()?;
694///
695/// let reader = ArchiveReader::tar(std::io::Cursor::new(bytes), None);
696/// let manifest = list_reader(reader, &SecurityConfig::default(), &ListOptions::default())?;
697/// assert_eq!(manifest.total_entries(), 1);
698/// # Ok(())
699/// # }
700/// ```
701pub fn list_reader(
702    reader: ArchiveReader<'_>,
703    config: &SecurityConfig,
704    options: &ListOptions,
705) -> Result<ArchiveManifest> {
706    list_reader_with_progress(reader, config, options, &mut NoopProgress)
707}
708
709/// Lists the contents of an archive read from a reader, reporting progress.
710///
711/// [`list_reader`] with a [`ProgressCallback`], which sees the events of
712/// [`list_archive_with_progress`](crate::list_archive_with_progress): one
713/// `on_entry_start` / `on_entry_complete` pair per listed entry, `total` 0 for
714/// TAR, and `on_complete` once after the manifest was built.
715///
716/// # Errors
717///
718/// Same as [`list_reader`]. `on_complete` is not called on failure.
719///
720/// # Examples
721///
722/// ```
723/// use exarch_core::ArchiveReader;
724/// use exarch_core::ListOptions;
725/// use exarch_core::NoopProgress;
726/// use exarch_core::SecurityConfig;
727/// use exarch_core::list_reader_with_progress;
728///
729/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
730/// let mut builder = tar::Builder::new(Vec::new());
731/// let mut header = tar::Header::new_gnu();
732/// header.set_size(2);
733/// header.set_mode(0o644);
734/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
735/// let bytes = builder.into_inner()?;
736///
737/// let reader = ArchiveReader::tar(std::io::Cursor::new(bytes), None);
738/// let manifest = list_reader_with_progress(
739///     reader,
740///     &SecurityConfig::default(),
741///     &ListOptions::default(),
742///     &mut NoopProgress,
743/// )?;
744/// assert_eq!(manifest.total_entries(), 1);
745/// # Ok(())
746/// # }
747/// ```
748pub fn list_reader_with_progress(
749    reader: ArchiveReader<'_>,
750    config: &SecurityConfig,
751    options: &ListOptions,
752    progress: &mut dyn ProgressCallback,
753) -> Result<ArchiveManifest> {
754    let config = config.clone().validate()?;
755    let manifest = reader.list(
756        &config,
757        &mut ListPass::strict_with(options.stored_targets).with_progress(progress),
758    )?;
759    progress.on_complete();
760    Ok(manifest)
761}
762
763/// Verifies an archive read from a reader, optionally checking payload
764/// integrity.
765///
766/// The reader counterpart of [`verify_archive_with_options`]; nothing is
767/// written and no filesystem path is needed.
768///
769/// # Errors
770///
771/// Same as [`verify_archive_with_options`].
772///
773/// # Examples
774///
775/// ```
776/// use exarch_core::ArchiveReader;
777/// use exarch_core::SecurityConfig;
778/// use exarch_core::VerificationOptions;
779/// use exarch_core::VerificationStatus;
780/// use exarch_core::verify_reader;
781///
782/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
783/// let mut builder = tar::Builder::new(Vec::new());
784/// let mut header = tar::Header::new_gnu();
785/// header.set_size(2);
786/// header.set_mode(0o644);
787/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
788/// let bytes = builder.into_inner()?;
789///
790/// let reader = ArchiveReader::tar(std::io::Cursor::new(bytes), None);
791/// let report = verify_reader(
792///     reader,
793///     &SecurityConfig::default(),
794///     &VerificationOptions::default(),
795/// )?;
796/// assert_eq!(report.status(), VerificationStatus::Pass);
797/// # Ok(())
798/// # }
799/// ```
800pub fn verify_reader(
801    reader: ArchiveReader<'_>,
802    config: &SecurityConfig,
803    options: &VerificationOptions,
804) -> Result<VerificationReport> {
805    verify_reader_with_progress(reader, config, options, &mut NoopProgress)
806}
807
808/// Verifies an archive read from a reader, reporting progress.
809///
810/// [`verify_reader`] with a [`ProgressCallback`], which sees the events of
811/// [`verify_archive_with_progress`](crate::verify_archive_with_progress): one
812/// `on_entry_start` / `on_entry_complete` pair per scanned entry, and
813/// `on_complete` once when a report is returned, including one whose status
814/// is `Fail`.
815///
816/// # Errors
817///
818/// Same as [`verify_reader`]. `on_complete` is not called on failure.
819///
820/// # Examples
821///
822/// ```
823/// use exarch_core::ArchiveReader;
824/// use exarch_core::NoopProgress;
825/// use exarch_core::SecurityConfig;
826/// use exarch_core::VerificationOptions;
827/// use exarch_core::VerificationStatus;
828/// use exarch_core::verify_reader_with_progress;
829///
830/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
831/// let mut builder = tar::Builder::new(Vec::new());
832/// let mut header = tar::Header::new_gnu();
833/// header.set_size(2);
834/// header.set_mode(0o644);
835/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
836/// let bytes = builder.into_inner()?;
837///
838/// let reader = ArchiveReader::tar(std::io::Cursor::new(bytes), None);
839/// let report = verify_reader_with_progress(
840///     reader,
841///     &SecurityConfig::default(),
842///     &VerificationOptions::default(),
843///     &mut NoopProgress,
844/// )?;
845/// assert_eq!(report.status(), VerificationStatus::Pass);
846/// # Ok(())
847/// # }
848/// ```
849pub fn verify_reader_with_progress(
850    reader: ArchiveReader<'_>,
851    config: &SecurityConfig,
852    options: &VerificationOptions,
853    progress: &mut dyn ProgressCallback,
854) -> Result<VerificationReport> {
855    let config = config.clone().validate()?;
856    let report = reader.verify(&config, *options, progress)?;
857    progress.on_complete();
858    Ok(report)
859}
860
861/// Extracts an archive read from a reader into an [`EntrySink`].
862///
863/// Equivalent to [`extract_to_sink_with_progress`] with a [`NoopProgress`].
864///
865/// Every entry passes the validation pipeline of [`extract_archive`] and is
866/// then delivered to `sink` instead of being written under a directory. See the
867/// [`sink`](crate::sink) module for what the sink may rely on and what it must
868/// do.
869///
870/// # Errors
871///
872/// Returns the errors of [`extract_archive`], plus any error the sink returns:
873/// [`ArchiveError::Io`] if no entry was delivered yet,
874/// [`ArchiveError::PartialExtraction`] wrapping it afterwards. A sink that
875/// reports [`SinkFull`](crate::SinkFull) ends the extraction with a
876/// [`QuotaResource::SinkCapacity`](crate::QuotaResource::SinkCapacity) quota
877/// error.
878///
879/// A 7z source is read in two phases: everything the file table can refuse
880/// (admission, ratios, quotas, link policy, paths, name lengths) is refused
881/// before the sink sees an entry, then the entries are decoded and delivered in
882/// archive order.
883///
884/// # Examples
885///
886/// ```
887/// use std::io;
888/// use std::path::Path;
889///
890/// use exarch_core::ArchiveReader;
891/// use exarch_core::EntrySink;
892/// use exarch_core::SafePath;
893/// use exarch_core::SanitizedMode;
894/// use exarch_core::SecurityConfig;
895/// use exarch_core::SinkOptions;
896/// use exarch_core::extract_to_sink;
897///
898/// #[derive(Default)]
899/// struct Count(usize);
900///
901/// impl EntrySink for Count {
902///     type File = io::Sink;
903///
904///     fn create_directory(&mut self, _: &SafePath) -> io::Result<()> {
905///         Ok(())
906///     }
907///
908///     fn create_file(
909///         &mut self,
910///         _: &SafePath,
911///         _: Option<SanitizedMode>,
912///         _: u64,
913///     ) -> io::Result<io::Sink> {
914///         Ok(io::sink())
915///     }
916///
917///     fn finish_file(&mut self, _: &SafePath, _: io::Sink) -> io::Result<()> {
918///         self.0 += 1;
919///         Ok(())
920///     }
921///
922///     fn create_symlink(&mut self, _: &SafePath, _: &Path) -> io::Result<()> {
923///         Ok(())
924///     }
925///
926///     fn create_hardlink(&mut self, _: &SafePath, _: &SafePath) -> io::Result<()> {
927///         Ok(())
928///     }
929/// }
930///
931/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
932/// let mut builder = tar::Builder::new(Vec::new());
933/// let mut header = tar::Header::new_gnu();
934/// header.set_size(2);
935/// header.set_mode(0o644);
936/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
937/// let bytes = builder.into_inner()?;
938///
939/// let mut sink = Count::default();
940/// let reader = ArchiveReader::tar(io::Cursor::new(bytes), None);
941/// extract_to_sink(
942///     reader,
943///     &mut sink,
944///     &SecurityConfig::default(),
945///     &SinkOptions::default(),
946/// )?;
947/// assert_eq!(sink.0, 1);
948/// # Ok(())
949/// # }
950/// ```
951pub fn extract_to_sink<S: EntrySink>(
952    reader: ArchiveReader<'_>,
953    sink: &mut S,
954    config: &SecurityConfig,
955    options: &SinkOptions,
956) -> Result<ExtractionReport> {
957    extract_to_sink_with_progress(reader, sink, config, options, &mut NoopProgress)
958}
959
960/// Extracts an archive read from a reader into an [`EntrySink`], reporting
961/// progress.
962///
963/// Behaves as [`extract_to_sink`]; `progress` receives the same events as the
964/// path-based [`extract_archive_with_progress`].
965///
966/// # Errors
967///
968/// Returns the errors of [`extract_to_sink`].
969///
970/// # Examples
971///
972/// ```
973/// use std::io;
974///
975/// use exarch_core::ArchiveReader;
976/// use exarch_core::MemorySink;
977/// use exarch_core::NoopProgress;
978/// use exarch_core::SecurityConfig;
979/// use exarch_core::SinkOptions;
980/// use exarch_core::extract_to_sink_with_progress;
981///
982/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
983/// let mut builder = tar::Builder::new(Vec::new());
984/// let mut header = tar::Header::new_gnu();
985/// header.set_size(2);
986/// header.set_mode(0o644);
987/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
988/// let bytes = builder.into_inner()?;
989///
990/// let mut sink = MemorySink::default();
991/// let report = extract_to_sink_with_progress(
992///     ArchiveReader::tar(io::Cursor::new(bytes), None),
993///     &mut sink,
994///     &SecurityConfig::default(),
995///     &SinkOptions::default(),
996///     &mut NoopProgress,
997/// )?;
998/// assert_eq!(report.files_extracted, 1);
999/// # Ok(())
1000/// # }
1001/// ```
1002pub fn extract_to_sink_with_progress<S: EntrySink>(
1003    reader: ArchiveReader<'_>,
1004    sink: &mut S,
1005    config: &SecurityConfig,
1006    options: &SinkOptions,
1007    progress: &mut dyn ProgressCallback,
1008) -> Result<ExtractionReport> {
1009    let config = config.clone().validate()?;
1010    match reader.into_source() {
1011        Source::Tar { stream, codec } => {
1012            let mut archive = tar_archive(stream, codec, config.max_decoder_memory)?;
1013            let mut target = SinkTarget::new(sink, &config);
1014            archive.extract_into(&mut target, &config, *options, progress)
1015        }
1016        Source::Seekable {
1017            reader,
1018            format: SeekableFormat::Zip,
1019        } => {
1020            let mut archive = ZipArchive::new(reader)?;
1021            let checked = archive.check_structure(&config)?;
1022            let mut target = SinkTarget::new(sink, &config);
1023            archive.extract_into(checked, &mut target, &config, *options, progress)
1024        }
1025        Source::Seekable {
1026            reader,
1027            format: SeekableFormat::SevenZ,
1028        } => {
1029            let mut archive = SevenZArchive::new(reader)?;
1030            let admission = archive.admit(&config)?;
1031            let mut target = SinkTarget::new(sink, &config);
1032            archive.extract_into(admission, &mut target, *options, progress)
1033        }
1034    }
1035}
1036
1037/// Rejects creation for ZIP-family extensions that aren't plain `.zip`.
1038///
1039/// See the call site in `create_archive_with_progress` for the rationale.
1040/// Returns `Ok(())` for anything else - `.zip`, tar variants, unknown
1041/// extensions (those get caught later by `detect_format`).
1042fn reject_zip_family_creation(output: &Path) -> Result<()> {
1043    let Some(ext) = output.extension().and_then(|e| e.to_str()) else {
1044        return Ok(());
1045    };
1046    if is_zip_family_alias(ext) {
1047        let ext_lower = ext.to_ascii_lowercase();
1048        return Err(ArchiveError::InvalidArchive(format!(
1049            "creation for .{ext_lower} isn't supported: the format is ZIP-based but \
1050             requires extra structure (signing, manifests, ordering) that exarch \
1051             doesn't produce. Use .zip, or set CreationConfig::format = Some(\
1052             exarch_core::formats::detect::CreatableFormat::Zip) to override."
1053        )));
1054    }
1055    Ok(())
1056}
1057
1058/// Determines archive format from output path or config.
1059///
1060/// Uses extension-only detection; magic-byte detection is intentionally
1061/// excluded so that a pre-existing output file with stale bytes cannot
1062/// override the caller's intended format.
1063fn determine_creation_format<State>(
1064    output: &Path,
1065    config: &CreationConfig<State>,
1066) -> Result<CreatableFormat> {
1067    // If format explicitly set in config, use it
1068    if let Some(format) = config.format {
1069        return Ok(format);
1070    }
1071
1072    // Auto-detect from extension only — never from magic bytes.
1073    CreatableFormat::try_from(detect_format_from_extension(output)?)
1074}
1075
1076#[cfg(test)]
1077#[allow(clippy::unwrap_used)]
1078mod tests {
1079    use super::*;
1080    use crate::raw_zip::RawEntry;
1081    use crate::raw_zip::RawZip;
1082    use std::assert_matches;
1083    use std::path::PathBuf;
1084
1085    #[test]
1086    fn test_extract_archive_nonexistent_file() {
1087        let config = SecurityConfig::default();
1088        let result = extract_archive(
1089            PathBuf::from("nonexistent_test.tar"),
1090            PathBuf::from("/tmp/test"),
1091            &config,
1092        );
1093        // Should fail because file doesn't exist
1094        assert!(result.is_err());
1095    }
1096
1097    #[test]
1098    fn test_determine_creation_format_tar() {
1099        let config = CreationConfig::default();
1100        let path = PathBuf::from("archive.tar");
1101        let format = determine_creation_format(&path, &config).unwrap();
1102        assert_eq!(format, CreatableFormat::Tar);
1103    }
1104
1105    #[test]
1106    fn test_determine_creation_format_tar_gz() {
1107        let config = CreationConfig::default();
1108        let path = PathBuf::from("archive.tar.gz");
1109        let format = determine_creation_format(&path, &config).unwrap();
1110        assert_eq!(format, CreatableFormat::TarGz);
1111
1112        let path2 = PathBuf::from("archive.tgz");
1113        let format2 = determine_creation_format(&path2, &config).unwrap();
1114        assert_eq!(format2, CreatableFormat::TarGz);
1115    }
1116
1117    #[test]
1118    fn test_determine_creation_format_tar_bz2() {
1119        let config = CreationConfig::default();
1120        let path = PathBuf::from("archive.tar.bz2");
1121        let format = determine_creation_format(&path, &config).unwrap();
1122        assert_eq!(format, CreatableFormat::TarBz2);
1123    }
1124
1125    #[test]
1126    fn test_determine_creation_format_tar_xz() {
1127        let config = CreationConfig::default();
1128        let path = PathBuf::from("archive.tar.xz");
1129        let format = determine_creation_format(&path, &config).unwrap();
1130        assert_eq!(format, CreatableFormat::TarXz);
1131    }
1132
1133    #[test]
1134    fn test_determine_creation_format_tar_zst() {
1135        let config = CreationConfig::default();
1136        let path = PathBuf::from("archive.tar.zst");
1137        let format = determine_creation_format(&path, &config).unwrap();
1138        assert_eq!(format, CreatableFormat::TarZst);
1139    }
1140
1141    #[test]
1142    fn test_determine_creation_format_zip() {
1143        let config = CreationConfig::default();
1144        let path = PathBuf::from("archive.zip");
1145        let format = determine_creation_format(&path, &config).unwrap();
1146        assert_eq!(format, CreatableFormat::Zip);
1147    }
1148
1149    #[test]
1150    fn test_determine_creation_format_explicit() {
1151        let config = CreationConfig::default().with_format(Some(CreatableFormat::TarGz));
1152        let path = PathBuf::from("archive.xyz");
1153        let format = determine_creation_format(&path, &config).unwrap();
1154        assert_eq!(format, CreatableFormat::TarGz);
1155    }
1156
1157    #[test]
1158    fn test_determine_creation_format_unknown() {
1159        let config = CreationConfig::default();
1160        let path = PathBuf::from("archive.rar");
1161        let result = determine_creation_format(&path, &config);
1162        assert!(result.is_err());
1163    }
1164
1165    #[test]
1166    fn test_determine_creation_format_ignores_stale_magic_bytes() {
1167        // Regression for C1: a pre-existing output file whose bytes match a
1168        // different format must not override the extension-derived format.
1169        let dir = tempfile::tempdir().unwrap();
1170        let path = dir.path().join("backup.zip");
1171        // Write gzip magic bytes into a file named .zip
1172        std::fs::write(&path, b"\x1f\x8b\x08\x00\x00\x00\x00\x00").unwrap();
1173
1174        let config = CreationConfig::default();
1175        let format = determine_creation_format(&path, &config).unwrap();
1176        assert_eq!(
1177            format,
1178            CreatableFormat::Zip,
1179            "creation format must follow extension, not stale on-disk magic bytes"
1180        );
1181    }
1182
1183    #[test]
1184    fn test_extract_archive_7z_not_implemented() {
1185        let dest = tempfile::TempDir::new().unwrap();
1186        let path = PathBuf::from("test.7z");
1187
1188        let result = extract_archive(&path, dest.path(), &SecurityConfig::default());
1189
1190        assert!(result.is_err());
1191    }
1192
1193    #[test]
1194    fn test_create_archive_invalid_compression_level_rejected_before_io() {
1195        for ext in ["tar.gz", "tar.bz2", "tar.xz", "tar.zst"] {
1196            let dest = tempfile::TempDir::new().unwrap();
1197            let archive_path = dest.path().join(format!("output.{ext}"));
1198            let mut config = CreationConfig::default();
1199            config.compression_level = Some(200);
1200            let result = create_archive(&archive_path, &[] as &[&str], &config);
1201            assert_matches!(
1202                result,
1203                Err(ArchiveError::InvalidCompressionLevel { level: 200 }),
1204                "{ext}: expected InvalidCompressionLevel, got {result:?}",
1205            );
1206            // Verify no I/O happened — output file must not exist
1207            assert!(
1208                !archive_path.exists(),
1209                "{ext}: output file must not be created"
1210            );
1211        }
1212    }
1213
1214    #[test]
1215    fn test_create_archive_zip_family_not_supported() {
1216        // Mirrors test_create_archive_7z_not_supported. Spot-checks a couple
1217        // of extensions rather than every one - the integration test
1218        // covers the full list.
1219        let dest = tempfile::TempDir::new().unwrap();
1220        for ext in ["apk", "whl", "EPUB"] {
1221            let archive_path = dest.path().join(format!("output.{ext}"));
1222            let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
1223            assert_matches!(
1224                result,
1225                Err(ArchiveError::InvalidArchive(_)),
1226                ".{ext} should be rejected, got {result:?}",
1227            );
1228        }
1229    }
1230
1231    #[test]
1232    fn test_create_archive_zip_family_override_bypasses_guard() {
1233        // Explicit CreationConfig::format = Some(Zip) is the escape hatch -
1234        // skips the ZIP-family guard. Caller takes responsibility for the
1235        // resulting file not being spec-valid.
1236        let dest = tempfile::TempDir::new().unwrap();
1237        let src = dest.path().join("source.txt");
1238        std::fs::write(&src, b"hello").unwrap();
1239        let archive_path = dest.path().join("output.apk");
1240        let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1241        let result = create_archive(&archive_path, &[&src], &config);
1242        assert!(
1243            result.is_ok(),
1244            "explicit format override should bypass the guard, got {result:?}",
1245        );
1246    }
1247
1248    #[test]
1249    fn test_create_archive_7z_not_supported() {
1250        let dest = tempfile::TempDir::new().unwrap();
1251        let archive_path = dest.path().join("output.7z");
1252
1253        let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
1254
1255        assert!(result.is_err());
1256        assert_matches!(
1257            result.unwrap_err(),
1258            ArchiveError::InvalidConfiguration { .. }
1259        );
1260    }
1261
1262    #[test]
1263    fn test_extract_archive_with_options_and_progress_non_atomic_delegates_to_normal() {
1264        let dest = tempfile::TempDir::new().unwrap();
1265        let options = ExtractionOptions {
1266            atomic: false,
1267            skip_duplicates: true,
1268        };
1269        let result = extract_archive_with_options_and_progress(
1270            PathBuf::from("nonexistent.tar.gz"),
1271            dest.path(),
1272            &SecurityConfig::default(),
1273            &options,
1274            &mut NoopProgress,
1275        );
1276        assert!(result.is_err());
1277    }
1278
1279    #[test]
1280    fn test_extract_archive_with_options_delegates() {
1281        let dest = tempfile::TempDir::new().unwrap();
1282        let options = ExtractionOptions {
1283            atomic: false,
1284            skip_duplicates: true,
1285        };
1286        let result = extract_archive_with_options(
1287            PathBuf::from("nonexistent.tar.gz"),
1288            dest.path(),
1289            &SecurityConfig::default(),
1290            &options,
1291        );
1292        assert!(result.is_err());
1293    }
1294
1295    #[test]
1296    fn test_extract_atomic_success() {
1297        use crate::create_archive;
1298        use crate::creation::CreationConfig;
1299
1300        // Create a valid tar.gz to extract
1301        let archive_dir = tempfile::TempDir::new().unwrap();
1302        let archive_path = archive_dir.path().join("test.tar.gz");
1303
1304        // Create a simple archive with one file
1305        let src_dir = tempfile::TempDir::new().unwrap();
1306        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
1307        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1308
1309        let parent = tempfile::TempDir::new().unwrap();
1310        let output_dir = parent.path().join("extracted");
1311
1312        let options = ExtractionOptions {
1313            atomic: true,
1314            skip_duplicates: true,
1315        };
1316        let result = extract_archive_with_options(
1317            &archive_path,
1318            &output_dir,
1319            &SecurityConfig::default(),
1320            &options,
1321        );
1322
1323        assert!(result.is_ok());
1324        assert!(output_dir.exists());
1325        // No temp dir remnants
1326        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
1327        assert_eq!(
1328            temp_entries.len(),
1329            1,
1330            "Expected only the output dir, found temp remnants"
1331        );
1332    }
1333
1334    #[test]
1335    fn test_extract_atomic_failure_cleans_up() {
1336        let parent = tempfile::TempDir::new().unwrap();
1337        let output_dir = parent.path().join("extracted");
1338
1339        let options = ExtractionOptions {
1340            atomic: true,
1341            skip_duplicates: true,
1342        };
1343        let result = extract_archive_with_options(
1344            PathBuf::from("nonexistent_archive.tar.gz"),
1345            &output_dir,
1346            &SecurityConfig::default(),
1347            &options,
1348        );
1349
1350        assert!(result.is_err());
1351        // Output dir must not exist
1352        assert!(!output_dir.exists());
1353        // No temp dir remnants in parent
1354        let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
1355        assert!(
1356            temp_entries.is_empty(),
1357            "Temp dir not cleaned up after failure"
1358        );
1359    }
1360
1361    #[test]
1362    fn test_extract_atomic_output_already_exists_fails() {
1363        use crate::create_archive;
1364        use crate::creation::CreationConfig;
1365
1366        let parent = tempfile::TempDir::new().unwrap();
1367        let output_dir = parent.path().join("extracted");
1368        std::fs::create_dir_all(&output_dir).unwrap();
1369        // Create a file in output_dir so it's non-empty (rename over non-empty
1370        // dir fails on most OSes)
1371        std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();
1372
1373        let archive_dir = tempfile::TempDir::new().unwrap();
1374        let archive_path = archive_dir.path().join("test.tar.gz");
1375        let src_dir = tempfile::TempDir::new().unwrap();
1376        std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
1377        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1378
1379        let options = ExtractionOptions {
1380            atomic: true,
1381            skip_duplicates: true,
1382        };
1383        let result = extract_archive_with_options(
1384            &archive_path,
1385            &output_dir,
1386            &SecurityConfig::default(),
1387            &options,
1388        );
1389
1390        // Should fail with OutputExists or Io (platform dependent rename
1391        // semantics)
1392        assert!(result.is_err());
1393        // Output dir must still have old content (not corrupted)
1394        assert!(output_dir.join("existing.txt").exists());
1395    }
1396
1397    // Regression test for issue #170: progress callback silently dropped
1398    #[test]
1399    fn test_progress_callback_invoked_during_extraction() {
1400        use crate::ProgressCallback;
1401        use std::path::Path;
1402
1403        struct TrackingProgress {
1404            started: usize,
1405            completed: usize,
1406            finished: bool,
1407        }
1408
1409        impl ProgressCallback for TrackingProgress {
1410            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1411                self.started += 1;
1412            }
1413
1414            fn on_bytes_written(&mut self, _bytes: u64) {}
1415
1416            fn on_entry_complete(&mut self, _path: &Path) {
1417                self.completed += 1;
1418            }
1419
1420            fn on_complete(&mut self) {
1421                self.finished = true;
1422            }
1423        }
1424
1425        let archive_dir = tempfile::TempDir::new().unwrap();
1426        let archive_path = archive_dir.path().join("test.tar.gz");
1427        let src_dir = tempfile::TempDir::new().unwrap();
1428        std::fs::write(src_dir.path().join("a.txt"), b"hello").unwrap();
1429        std::fs::write(src_dir.path().join("b.txt"), b"world").unwrap();
1430        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1431
1432        let dest = tempfile::TempDir::new().unwrap();
1433        let mut progress = TrackingProgress {
1434            started: 0,
1435            completed: 0,
1436            finished: false,
1437        };
1438
1439        let report = extract_archive_with_progress(
1440            &archive_path,
1441            dest.path(),
1442            &SecurityConfig::default(),
1443            &mut progress,
1444        )
1445        .unwrap();
1446
1447        assert!(report.files_extracted >= 2, "expected at least 2 files");
1448        assert!(progress.started >= 2, "on_entry_start not called");
1449        assert!(progress.completed >= 2, "on_entry_complete not called");
1450        assert!(progress.finished, "on_complete not called");
1451    }
1452
1453    // Regression test for issue #170: ZIP format
1454    #[test]
1455    fn test_progress_callback_invoked_during_zip_extraction() {
1456        use crate::ProgressCallback;
1457        use std::path::Path;
1458
1459        struct TrackingProgress {
1460            started: usize,
1461            completed: usize,
1462            finished: bool,
1463        }
1464
1465        impl ProgressCallback for TrackingProgress {
1466            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1467                self.started += 1;
1468            }
1469
1470            fn on_bytes_written(&mut self, _bytes: u64) {}
1471
1472            fn on_entry_complete(&mut self, _path: &Path) {
1473                self.completed += 1;
1474            }
1475
1476            fn on_complete(&mut self) {
1477                self.finished = true;
1478            }
1479        }
1480
1481        let tmp = tempfile::TempDir::new().unwrap();
1482        let archive_path = tmp.path().join("test.zip");
1483        let src_dir = tempfile::TempDir::new().unwrap();
1484        std::fs::write(src_dir.path().join("x.txt"), b"foo").unwrap();
1485        std::fs::write(src_dir.path().join("y.txt"), b"bar").unwrap();
1486        let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1487        create_archive(&archive_path, &[src_dir.path()], &config).unwrap();
1488
1489        let dest = tempfile::TempDir::new().unwrap();
1490        let mut progress = TrackingProgress {
1491            started: 0,
1492            completed: 0,
1493            finished: false,
1494        };
1495        let report = extract_archive_with_progress(
1496            &archive_path,
1497            dest.path(),
1498            &SecurityConfig::default(),
1499            &mut progress,
1500        )
1501        .unwrap();
1502
1503        assert!(report.files_extracted >= 2, "expected at least 2 files");
1504        assert!(progress.started >= 2, "on_entry_start not called for ZIP");
1505        assert!(
1506            progress.completed >= 2,
1507            "on_entry_complete not called for ZIP"
1508        );
1509        assert!(progress.finished, "on_complete not called for ZIP");
1510    }
1511
1512    // Regression test for issue #170: 7z format
1513    #[test]
1514    fn test_progress_callback_invoked_during_sevenz_extraction() {
1515        use crate::ProgressCallback;
1516        use std::path::Path;
1517
1518        struct TrackingProgress {
1519            started: usize,
1520            completed: usize,
1521            finished: bool,
1522        }
1523
1524        impl ProgressCallback for TrackingProgress {
1525            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1526                self.started += 1;
1527            }
1528
1529            fn on_bytes_written(&mut self, _bytes: u64) {}
1530
1531            fn on_entry_complete(&mut self, _path: &Path) {
1532                self.completed += 1;
1533            }
1534
1535            fn on_complete(&mut self) {
1536                self.finished = true;
1537            }
1538        }
1539
1540        let fixture =
1541            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1542
1543        let dest = tempfile::TempDir::new().unwrap();
1544        let mut progress = TrackingProgress {
1545            started: 0,
1546            completed: 0,
1547            finished: false,
1548        };
1549        let report = extract_archive_with_progress(
1550            &fixture,
1551            dest.path(),
1552            &SecurityConfig::default(),
1553            &mut progress,
1554        )
1555        .unwrap();
1556
1557        assert!(
1558            report.files_extracted >= 1,
1559            "expected at least 1 file from simple.7z"
1560        );
1561        assert!(progress.started >= 1, "on_entry_start not called for 7z");
1562        assert!(
1563            progress.completed >= 1,
1564            "on_entry_complete not called for 7z"
1565        );
1566        assert!(progress.finished, "on_complete not called for 7z");
1567    }
1568
1569    // Regression test for issue #304: on_bytes_written must be called with > 0
1570    // bytes when extracting non-empty files from TAR archives.
1571    #[test]
1572    fn test_on_bytes_written_called_for_tar() {
1573        use crate::ProgressCallback;
1574        use std::path::Path;
1575
1576        struct ByteTracker {
1577            total: u64,
1578        }
1579
1580        impl ProgressCallback for ByteTracker {
1581            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1582
1583            fn on_bytes_written(&mut self, bytes: u64) {
1584                self.total += bytes;
1585            }
1586
1587            fn on_entry_complete(&mut self, _path: &Path) {}
1588
1589            fn on_complete(&mut self) {}
1590        }
1591
1592        let archive_dir = tempfile::TempDir::new().unwrap();
1593        let archive_path = archive_dir.path().join("test.tar.gz");
1594        let src_dir = tempfile::TempDir::new().unwrap();
1595        std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
1596        create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1597
1598        let dest = tempfile::TempDir::new().unwrap();
1599        let mut progress = ByteTracker { total: 0 };
1600        let report = extract_archive_with_progress(
1601            &archive_path,
1602            dest.path(),
1603            &SecurityConfig::default(),
1604            &mut progress,
1605        )
1606        .unwrap();
1607
1608        assert!(
1609            report.bytes_written > 0,
1610            "report.bytes_written must be > 0, got {}",
1611            report.bytes_written
1612        );
1613        assert!(
1614            progress.total > 0,
1615            "on_bytes_written must be called with > 0 bytes for TAR, got {}",
1616            progress.total
1617        );
1618    }
1619
1620    // Regression test for issue #304: on_bytes_written must be called with > 0
1621    // bytes when extracting non-empty files from ZIP archives.
1622    #[test]
1623    fn test_on_bytes_written_called_for_zip() {
1624        use crate::ProgressCallback;
1625        use std::path::Path;
1626
1627        struct ByteTracker {
1628            total: u64,
1629        }
1630
1631        impl ProgressCallback for ByteTracker {
1632            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1633
1634            fn on_bytes_written(&mut self, bytes: u64) {
1635                self.total += bytes;
1636            }
1637
1638            fn on_entry_complete(&mut self, _path: &Path) {}
1639
1640            fn on_complete(&mut self) {}
1641        }
1642
1643        let tmp = tempfile::TempDir::new().unwrap();
1644        let archive_path = tmp.path().join("test.zip");
1645        let src_dir = tempfile::TempDir::new().unwrap();
1646        std::fs::write(src_dir.path().join("data.txt"), b"hello world").unwrap();
1647        let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1648        create_archive(&archive_path, &[src_dir.path()], &config).unwrap();
1649
1650        let dest = tempfile::TempDir::new().unwrap();
1651        let mut progress = ByteTracker { total: 0 };
1652        let report = extract_archive_with_progress(
1653            &archive_path,
1654            dest.path(),
1655            &SecurityConfig::default(),
1656            &mut progress,
1657        )
1658        .unwrap();
1659
1660        assert!(
1661            report.bytes_written > 0,
1662            "report.bytes_written must be > 0, got {}",
1663            report.bytes_written
1664        );
1665        assert!(
1666            progress.total > 0,
1667            "on_bytes_written must be called with > 0 bytes for ZIP, got {}",
1668            progress.total
1669        );
1670    }
1671
1672    // Regression test for issue #304: on_bytes_written must be called with > 0
1673    // bytes when extracting non-empty files from 7z archives.
1674    #[test]
1675    fn test_on_bytes_written_called_for_sevenz() {
1676        use crate::ProgressCallback;
1677        use std::path::Path;
1678
1679        struct ByteTracker {
1680            total: u64,
1681        }
1682
1683        impl ProgressCallback for ByteTracker {
1684            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1685
1686            fn on_bytes_written(&mut self, bytes: u64) {
1687                self.total += bytes;
1688            }
1689
1690            fn on_entry_complete(&mut self, _path: &Path) {}
1691
1692            fn on_complete(&mut self) {}
1693        }
1694
1695        let fixture =
1696            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1697
1698        let dest = tempfile::TempDir::new().unwrap();
1699        let mut progress = ByteTracker { total: 0 };
1700        let report = extract_archive_with_progress(
1701            &fixture,
1702            dest.path(),
1703            &SecurityConfig::default(),
1704            &mut progress,
1705        )
1706        .unwrap();
1707
1708        assert!(
1709            report.bytes_written > 0,
1710            "report.bytes_written must be > 0, got {}",
1711            report.bytes_written
1712        );
1713        assert!(
1714            progress.total > 0,
1715            "on_bytes_written must be called with > 0 bytes for 7z, got {}",
1716            progress.total
1717        );
1718    }
1719
1720    // Regression test for BYTES-1: on_bytes_written must be called when TAR
1721    // hardlinks are extracted (copy path in create_hardlink).
1722    #[test]
1723    fn test_tar_hardlink_calls_on_bytes_written() {
1724        use crate::ProgressCallback;
1725        use crate::formats::TarArchive;
1726        use crate::formats::traits::ArchiveFormat;
1727        use std::io::Cursor;
1728        use std::path::Path;
1729
1730        struct ByteTracker {
1731            total: u64,
1732        }
1733
1734        impl ProgressCallback for ByteTracker {
1735            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1736
1737            fn on_bytes_written(&mut self, bytes: u64) {
1738                self.total += bytes;
1739            }
1740
1741            fn on_entry_complete(&mut self, _path: &Path) {}
1742
1743            fn on_complete(&mut self) {}
1744        }
1745
1746        // Build a TAR with one regular file and one hardlink pointing to it.
1747        let content = b"hello hardlink";
1748        let tar_data = {
1749            let mut builder = tar::Builder::new(Vec::new());
1750
1751            let mut header = tar::Header::new_gnu();
1752            header.set_size(content.len() as u64);
1753            header.set_mode(0o644);
1754            header.set_entry_type(tar::EntryType::Regular);
1755            header.set_cksum();
1756            builder
1757                .append_data(&mut header, "original.txt", content.as_ref())
1758                .unwrap();
1759
1760            let mut hdr = tar::Header::new_gnu();
1761            hdr.set_size(0);
1762            hdr.set_mode(0o644);
1763            hdr.set_entry_type(tar::EntryType::Link);
1764            hdr.set_link_name("original.txt").unwrap();
1765            hdr.set_cksum();
1766            builder
1767                .append_data(&mut hdr, "link.txt", std::io::empty())
1768                .unwrap();
1769
1770            builder.into_inner().unwrap()
1771        };
1772
1773        let temp = tempfile::TempDir::new().unwrap();
1774        let mut config = SecurityConfig::default();
1775        config.allowed.hardlinks = true;
1776        let config = config.validate().unwrap();
1777
1778        let mut archive = TarArchive::new(Cursor::new(tar_data));
1779        let mut progress = ByteTracker { total: 0 };
1780        let report = archive
1781            .extract(
1782                temp.path(),
1783                &config,
1784                &ExtractionOptions::default(),
1785                &mut progress,
1786            )
1787            .unwrap();
1788
1789        // The hardlink copies the file content — bytes should be reported
1790        // twice.
1791        let expected = (content.len() as u64) * 2;
1792        assert_eq!(
1793            progress.total, expected,
1794            "on_bytes_written must report bytes for both original and hardlink copy, \
1795             got {} (report.bytes_written={})",
1796            progress.total, report.bytes_written
1797        );
1798    }
1799
1800    // Regression test for issue #305: on_entry_complete must be called even
1801    // when TAR extraction fails mid-entry due to a path traversal violation.
1802    #[test]
1803    fn test_tar_on_entry_complete_called_on_path_traversal_error() {
1804        use crate::ProgressCallback;
1805        use crate::formats::TarArchive;
1806        use crate::formats::traits::ArchiveFormat;
1807        use std::io::Cursor;
1808        use std::path::Path;
1809
1810        struct SymmetryTracker {
1811            started: usize,
1812            completed: usize,
1813        }
1814
1815        impl ProgressCallback for SymmetryTracker {
1816            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1817                self.started += 1;
1818            }
1819
1820            fn on_bytes_written(&mut self, _bytes: u64) {}
1821
1822            fn on_entry_complete(&mut self, _path: &Path) {
1823                self.completed += 1;
1824            }
1825
1826            fn on_complete(&mut self) {}
1827        }
1828
1829        // Build a minimal TAR with a path-traversal entry at raw bytes level
1830        // (bypassing the `tar` crate's sanitization).
1831        let tar_data = make_raw_tar_single(b"../../etc/passwd", b"evil");
1832
1833        let temp = tempfile::TempDir::new().unwrap();
1834        let mut archive = TarArchive::new(Cursor::new(tar_data));
1835        let mut progress = SymmetryTracker {
1836            started: 0,
1837            completed: 0,
1838        };
1839        let result = archive.extract(
1840            temp.path(),
1841            &SecurityConfig::default().validate().unwrap(),
1842            &ExtractionOptions::default(),
1843            &mut progress,
1844        );
1845
1846        assert!(result.is_err(), "traversal entry must be rejected");
1847        assert_eq!(
1848            progress.started, progress.completed,
1849            "on_entry_complete must be called for every on_entry_start, \
1850             even when extraction fails: started={}, completed={}",
1851            progress.started, progress.completed
1852        );
1853    }
1854
1855    // Regression test for issue #305: on_entry_complete must be called even
1856    // when ZIP extraction fails mid-entry due to a path traversal violation.
1857    #[test]
1858    fn test_zip_on_entry_complete_called_on_path_traversal_error() {
1859        use crate::ProgressCallback;
1860        use crate::formats::ZipArchive;
1861        use crate::formats::traits::ArchiveFormat;
1862        use std::io::Cursor;
1863        use std::path::Path;
1864
1865        struct SymmetryTracker {
1866            started: usize,
1867            completed: usize,
1868        }
1869
1870        impl ProgressCallback for SymmetryTracker {
1871            fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1872                self.started += 1;
1873            }
1874
1875            fn on_bytes_written(&mut self, _bytes: u64) {}
1876
1877            fn on_entry_complete(&mut self, _path: &Path) {
1878                self.completed += 1;
1879            }
1880
1881            fn on_complete(&mut self) {}
1882        }
1883
1884        // Build a ZIP with a traversal path using zip::ZipWriter.
1885        let zip_data = make_zip_with_traversal(b"../../etc/passwd", b"evil");
1886
1887        let temp = tempfile::TempDir::new().unwrap();
1888        let mut archive = ZipArchive::new(Cursor::new(zip_data)).unwrap();
1889        let mut progress = SymmetryTracker {
1890            started: 0,
1891            completed: 0,
1892        };
1893        let result = archive.extract(
1894            temp.path(),
1895            &SecurityConfig::default().validate().unwrap(),
1896            &ExtractionOptions::default(),
1897            &mut progress,
1898        );
1899
1900        assert!(result.is_err(), "traversal entry must be rejected");
1901        assert_eq!(
1902            progress.started, progress.completed,
1903            "on_entry_complete must be called for every on_entry_start in ZIP, \
1904             even when extraction fails: started={}, completed={}",
1905            progress.started, progress.completed
1906        );
1907    }
1908
1909    // Builds a single-entry POSIX ustar TAR with an arbitrary raw path,
1910    // bypassing the `tar` crate's path sanitization.
1911    fn make_raw_tar_single(path: &[u8], data: &[u8]) -> Vec<u8> {
1912        let mut out = Vec::new();
1913        let mut header = [0u8; 512];
1914
1915        let path_len = path.len().min(100);
1916        header[..path_len].copy_from_slice(&path[..path_len]);
1917        header[100..108].copy_from_slice(b"0000644\0");
1918        header[108..116].copy_from_slice(b"0000000\0");
1919        header[116..124].copy_from_slice(b"0000000\0");
1920        let size_str = format!("{:011o}\0", data.len());
1921        header[124..136].copy_from_slice(size_str.as_bytes());
1922        header[136..148].copy_from_slice(b"00000000000\0");
1923        header[156] = b'0';
1924        header[257..263].copy_from_slice(b"ustar ");
1925        header[263..265].copy_from_slice(b" \0");
1926        header[148..156].copy_from_slice(b"        ");
1927        let checksum: u32 = header.iter().map(|&b| u32::from(b)).sum();
1928        let ck_str = format!("{checksum:06o}\0 ");
1929        header[148..156].copy_from_slice(ck_str.as_bytes());
1930
1931        out.extend_from_slice(&header);
1932        out.extend_from_slice(data);
1933        let rem = data.len() % 512;
1934        if rem != 0 {
1935            out.extend(std::iter::repeat_n(0u8, 512 - rem));
1936        }
1937        out.extend(std::iter::repeat_n(0u8, 1024));
1938        out
1939    }
1940
1941    // Builds a single-entry ZIP whose name is written verbatim, so a traversal
1942    // path survives into the headers.
1943    fn make_zip_with_traversal(path: &[u8], data: &[u8]) -> Vec<u8> {
1944        let entry = RawEntry {
1945            name: path.to_vec(),
1946            date: 0,
1947            ..RawEntry::stored("", data)
1948        };
1949        RawZip::new(vec![entry]).build().bytes
1950    }
1951}