diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index f50eb4e5..54758f97 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -718,23 +718,17 @@ fn extract_all(target: Target, mut opts: Options) -> Result { let mut nested: Vec = Vec::new(); let mut seen = std::collections::HashSet::new(); for path in nested_candidates { - if hatchzip_core::archive::nested_kind(&path).is_none() { + // Extracting a set in place removes every volume, so each one + // must be a file this run wrote, never one the person had. + let Some(primary) = hatchzip_core::session::nested_offer(&path, &written) else { continue; - } + }; // A split set counts once, by its first volume, and the parent // archives are never nested. - let Ok((primary, _)) = locate(&path) else { - continue; - }; if parents.contains(&primary) || !seen.insert(primary.clone()) { continue; } - // Extracting a set in place removes every volume, so each one - // must be a file this run wrote, never one the person had. - if !hatchzip_core::session::volumes_written(&primary, &written) { - continue; - } - nested.push(path); + nested.push(primary); } if nested.is_empty() { say!("No archives among the extracted files."); diff --git a/crates/cli/tests/nested.rs b/crates/cli/tests/nested.rs index 3044f443..4b7691a0 100644 --- a/crates/cli/tests/nested.rs +++ b/crates/cli/tests/nested.rs @@ -206,6 +206,282 @@ fn a_set_whose_first_part_was_already_there_is_not_extracted() { assert_eq!(fs::read(out.join("set.zip")).unwrap(), inner); } +fn split_files() -> Files { + let mut files = Files::new(); + files.insert("data/big.bin".into(), noise(60_000, 5)); + files.insert("readme.txt".into(), b"split inside".to_vec()); + files +} + +/// `files` as the native split ZIP `set.z01`, `set.z02`, ..., `set.zip`, +/// named and in order, with enough segments that one in the middle can go +/// missing and the set still has a `.z01` and a `.zip`. +fn split_set(files: &Files) -> Vec<(String, Vec)> { + let tmp = TempDir::new().unwrap(); + let whole = fs::read(zip_of(tmp.path(), "whole.zip", files)).unwrap(); + let s = Split { + size: 10_000, + ..Split::default() + }; + let segments = split_zip_segments(&whole, &s); + let n = segments.len(); + assert!(n >= 4, "only {n} segments"); + segments + .into_iter() + .enumerate() + .map(|(i, bytes)| { + let name = split_zip_name(Path::new(""), "set", i, n, false); + (name.to_str().unwrap().to_string(), bytes) + }) + .collect() +} + +fn outer_of(parts: &[&(String, Vec)]) -> Vec { + let entries: Vec<(&str, &[u8])> = parts + .iter() + .map(|(name, bytes)| (name.as_str(), bytes.as_slice())) + .collect(); + zip_bytes(&entries) +} + +/// Every one of `parts` is in `out`, as it was written. +fn assert_parts(out: &Path, parts: &[&(String, Vec)]) { + for (name, bytes) in parts { + assert_eq!(&fs::read(out.join(name)).unwrap(), bytes, "{name}"); + } +} + +fn stdout_of(run: &std::process::Output) -> String { + String::from_utf8_lossy(&run.stdout).into_owned() +} + +/// A native split ZIP the run wrote whole is one archive, found by its +/// `.z01`, whose split marker is no ZIP signature, and extracted as a set +/// in place: every segment is gone afterwards. +#[test] +fn a_split_zip_inside_is_extracted_once_as_a_set() { + let tmp = TempDir::new().unwrap(); + let files = split_files(); + let parts = split_set(&files); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&parts.iter().collect::>())).unwrap(); + let out = tmp.path().join("out"); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + let stdout = stdout_of(&run); + assert!( + stdout.contains("Nested archive:") && stdout.contains("The nested archive was extracted."), + "the set is offered once: {stdout}" + ); + assert_tree(&out.join("set"), &files); + for (name, _) in &parts { + assert!(!out.join(name).exists(), "{name} is left"); + } +} + +/// The rest of a set next to the person's own `.z01` is not the run's set: +/// extracting it in place would remove their file. +#[test] +fn a_split_zip_whose_first_segment_was_already_there_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let out = tmp.path().join("out"); + fs::create_dir_all(&out).unwrap(); + fs::write(out.join(&parts[0].0), &parts[0].1).unwrap(); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&parts[1..].iter().collect::>())).unwrap(); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &parts.iter().collect::>()); +} + +/// With `--skip-existing`, a segment the person had stays in place of the +/// run's copy. It would be removed with the set, so the set is not offered. +#[test] +fn a_split_zip_with_a_skipped_segment_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let out = tmp.path().join("out"); + fs::create_dir_all(&out).unwrap(); + fs::write(out.join(&parts[1].0), &parts[1].1).unwrap(); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&parts.iter().collect::>())).unwrap(); + + let run = extract_nested(&archive, &out, &["--skip-existing"]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &parts.iter().collect::>()); + assert!(!out.join("set").exists(), "nothing was extracted"); +} + +/// `.z01`, `.z03`, ... and `.zip` without the `.z02` are a set with a hole, +/// so it is not offered. +#[test] +fn a_split_zip_missing_a_middle_segment_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let left: Vec<_> = parts + .iter() + .enumerate() + .filter(|(i, _)| *i != 1) + .map(|(_, p)| p) + .collect(); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&left)).unwrap(); + let out = tmp.path().join("out"); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &left); + assert!(!out.join(&parts[1].0).exists()); + assert!(!out.join("set").exists(), "nothing was extracted"); +} + +/// A `.z01` and a `.zip` look like a whole set by name, but the index says +/// there are more segments. Opening it finds that, so it is not offered, +/// and no progress file or folder is left behind. +#[test] +fn a_split_zip_missing_segments_its_index_names_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let ends = [&parts[0], &parts[parts.len() - 1]]; + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&ends)).unwrap(); + let out = tmp.path().join("out"); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &ends); + for left in [ + "set.z01.hatchzip", + "set.z01.hatchzip-tail", + "set.z01.hatchzip-folders", + "set.zip.hatchzip", + "set", + ] { + assert!(!out.join(left).exists(), "{left} is left"); + } +} + +/// The person's own `.z02` between the run's `.z01` and `.zip` makes the +/// set partly theirs, so it is not offered. +#[test] +fn a_split_zip_with_the_persons_middle_segment_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let out = tmp.path().join("out"); + fs::create_dir_all(&out).unwrap(); + fs::write(out.join(&parts[1].0), &parts[1].1).unwrap(); + let theirs: Vec<_> = parts + .iter() + .enumerate() + .filter(|(i, _)| *i != 1) + .map(|(_, p)| p) + .collect(); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&theirs)).unwrap(); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &parts.iter().collect::>()); + assert!(!out.join("set").exists(), "nothing was extracted"); +} + +/// An archive that carries progress files of its own would resume from what +/// they say, so neither a split set nor a single archive with one is +/// offered, and nothing changes. +#[test] +fn an_archive_inside_with_its_own_progress_files_is_not_extracted() { + let tmp = TempDir::new().unwrap(); + let parts = split_set(&split_files()); + let journal = (String::from("set.z01.hatchzip"), b"{}".to_vec()); + let plain = (String::from("foo.zip"), zip_bytes(&[("foo.txt", b"foo")])); + let plain_journal = (String::from("foo.zip.hatchzip"), b"{}".to_vec()); + let mut all: Vec<_> = parts.iter().collect(); + all.extend([&journal, &plain, &plain_journal]); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&all)).unwrap(); + let out = tmp.path().join("out"); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + assert!( + stdout_of(&run).contains("No archives among the extracted files."), + "{}", + stdout_of(&run) + ); + assert_parts(&out, &all); + assert!(!out.join("set").exists() && !out.join("foo").exists()); +} + +/// A RAR set inside counts once, by its first volume, even when a later +/// volume comes first in the archive. +#[cfg(feature = "rar")] +#[test] +fn a_rar_set_inside_is_extracted_once_from_its_first_volume() { + let tmp = TempDir::new().unwrap(); + let from = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rar/rar5"); + let mut volumes: Vec<(String, Vec)> = fs::read_dir(&from) + .unwrap() + .map(|e| { + let e = e.unwrap(); + let name = e.file_name().to_string_lossy().into_owned(); + (name, fs::read(e.path()).unwrap()) + }) + .collect(); + volumes.sort(); + assert!(volumes.len() >= 3 && volumes[1].0 == "set.part2.rar"); + // `set.part2.rar` first, then `set.part1.rar` and the rest. + volumes.swap(0, 1); + let archive = tmp.path().join("outer.zip"); + fs::write(&archive, outer_of(&volumes.iter().collect::>())).unwrap(); + let out = tmp.path().join("out"); + + let run = extract_nested(&archive, &out, &[]); + assert_ok(&run); + let stdout = stdout_of(&run); + assert!( + stdout.contains("Nested archive:") && stdout.contains("set.part1.rar"), + "the set is offered once, by its first volume: {stdout}" + ); + assert_eq!( + fs::read(out.join("set/game/d.pak")).unwrap(), + noise(6_000, 9) + ); + assert_eq!( + fs::read(out.join("set/game/a.pak")).unwrap(), + noise(30_000, 1) + ); + for (name, _) in &volumes { + assert!(!out.join(name).exists(), "{name} is left"); + } +} /// A link inside the output can point anywhere; the scan must not follow it. #[cfg(unix)] #[test] diff --git a/crates/core/src/archive/mod.rs b/crates/core/src/archive/mod.rs index 2c2ca430..4c1ff3e1 100644 --- a/crates/core/src/archive/mod.rs +++ b/crates/core/src/archive/mod.rs @@ -641,7 +641,14 @@ pub fn detect(path: &Path) -> Option<&'static str> { /// The format `path` holds if its name claims an archive format and its /// signature agrees. Both matter: `.jar`, `.docx`, `.pk3` and `.apk` are /// ZIPs, and `.ova` and `.gem` are tars, and none of them should be offered. +/// +/// A `.z01` that starts like the first segment of a native split ZIP is +/// [`SPLIT_ZIP`]. That says nothing about the rest of the set, which +/// [`crate::session::nested_offer`] checks before offering it. pub fn nested_kind(path: &Path) -> Option<&'static str> { + if storage::is_split_zip(path) { + return starts_like_split_zip(path).then_some(SPLIT_ZIP); + } let name = path.file_name()?.to_string_lossy().to_ascii_lowercase(); let expected = if name.ends_with(".zip") { "zip" @@ -671,6 +678,24 @@ pub fn nested_kind(path: &Path) -> Option<&'static str> { (detect(path)? == expected).then_some(expected) } +/// Whether the file at `path` starts the way the split reader takes a first +/// segment: the split marker `zip -s` writes, or the marker of a split that +/// needed one segment, then a local header; or a local header straight +/// away. `detect` never names such a file, as the marker is no signature. +fn starts_like_split_zip(path: &Path) -> bool { + if !fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) { + return false; + } + let mut head = [0u8; 8]; + let Ok(n) = fs::File::open(path).and_then(|mut f| read_up_to(&mut f, &mut head)) else { + return false; + }; + let head = &head[..n]; + let local: &[u8] = b"PK\x03\x04"; + head.starts_with(local) + || ((head.starts_with(b"PK\x07\x08") || head.starts_with(b"PK00")) && &head[4..] == local) +} + fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result { let mut n = 0; while n < buf.len() { diff --git a/crates/core/src/session.rs b/crates/core/src/session.rs index 3c8ac79e..83575a7a 100644 --- a/crates/core/src/session.rs +++ b/crates/core/src/session.rs @@ -22,12 +22,52 @@ pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> { Ok((primary, paths)) } +/// The archive a finished run offers to extract for `path`, one of the files +/// in `written`, the files it wrote: the first volume of its set, so a set +/// is offered once whichever volume is asked about. `None` unless `path` and +/// that first volume are archives by name and signature, and every volume of +/// the set is in `written` ([`volumes_written`]). A native split ZIP is +/// found by its `.z01`, whose split marker no other check names. +/// +/// An archive with progress files next to it (a journal, its tail or +/// folder list, a split ZIP's stub) is never offered, even when the run +/// wrote them: a resume would follow what they say, not what the person +/// was offered. A split ZIP is also opened read only, so a set whose index +/// names more segments than are there is not offered. +pub fn nested_offer(path: &Path, written: &HashSet) -> Option { + crate::archive::nested_kind(path)?; + let (primary, paths) = locate(path).ok()?; + // A `.zip` that happens to start with a local header names the set of + // the `.z01` next to it, which must itself look like a first segment. + let kind = crate::archive::nested_kind(&primary)?; + let side_files = [&paths.journal, &paths.tail, &paths.folders] + .into_iter() + .chain(&paths.stub) + .any(|p| fs::symlink_metadata(p).is_ok()); + if side_files || !volumes_written(&primary, written) { + return None; + } + // Opening reads only the index and the local headers, and checks the + // segment count against the index. Other formats are not opened here: + // a compressed tar is decompressed in full to list it. + if kind == crate::archive::SPLIT_ZIP { + Job::open(&primary, false, None, Arc::default()).ok()?; + } + Some(primary) +} + /// Whether every volume of the set whose first volume is `primary` that /// exists on disk is in `written`. A set that is not split has one volume. /// /// Extracting a set in place removes every volume, so an offer to extract it /// must not take in one the run did not write: a `.zip` next to the person's /// own `.z01` is the last segment of their set, not of the run's. +/// +/// A native split ZIP also needs its `.zip`, which holds the index. A +/// segment in `written` past a missing one, such as a `.z03` without the +/// `.z02`, also makes this false. That only catches the gaps the run's own +/// files show: a set missing its last segments before the `.zip` passes, +/// and only opening it, which checks the index, finds that. pub fn volumes_written(primary: &Path, written: &HashSet) -> bool { let mut volumes = Vec::new(); if storage::is_split_zip(primary) { @@ -40,8 +80,17 @@ pub fn volumes_written(primary: &Path, written: &HashSet) -> bool { } volumes.push(segment); } - if let Some(last) = storage::split_zip_last(primary) { - volumes.push(last); + match storage::split_zip_last(primary) { + Some(last) if last.exists() => volumes.push(last), + _ => return false, + } + let beyond_a_gap = written.iter().any(|w| { + w.parent() == primary.parent() + && !volumes.contains(w) + && storage::first_volume(w) == primary + }); + if beyond_a_gap { + return false; } } else { for index in 0.. { diff --git a/crates/gui/src/main_window.rs b/crates/gui/src/main_window.rs index f3ca570c..727df305 100644 --- a/crates/gui/src/main_window.rs +++ b/crates/gui/src/main_window.rs @@ -1121,7 +1121,7 @@ impl App { here: false, existing: self.settings.borrow().existing_files, only: None, - nested: false, + nested: None, }; let mut task = Task::extract(&self.name.borrow(), Some(&output), keep); if self.mode.get() == Mode::Resume && self.selected_run.get() { @@ -1204,7 +1204,7 @@ impl App { here: false, existing: self.settings.borrow().existing_files, only: Some(only), - nested: false, + nested: None, }; let task = Task::extract(&self.name.borrow(), Some(&output), true).selecting(); self.start_extraction(task, request); @@ -1214,13 +1214,14 @@ impl App { /// folder next to it. Only the files the run wrote are considered, so a /// file that was already there is never extracted as if it were new. fn extract_inside(&self) { - let nested: Vec = self + let (nested, written) = self .runner .task .borrow() .as_ref() - .map(|t| t.nested.clone()) - .unwrap_or_default() + .map(|t| (t.nested.clone(), t.written.clone())) + .unwrap_or_default(); + let nested: Vec = nested .into_iter() .filter(|p| hatchzip_core::archive::nested_kind(p).is_some()) .collect(); @@ -1243,8 +1244,13 @@ impl App { let jobs = nested .iter() .map(|path| { - let (task, mut request) = - crate::task_window::nested_job(path, keep, keep_free, verify_first); + let (task, mut request) = crate::task_window::nested_job( + path, + written.clone(), + keep, + keep_free, + verify_first, + ); if let Some(p) = &password { request.set_password(p.clone()); } diff --git a/crates/gui/src/task.rs b/crates/gui/src/task.rs index 689c466a..b9b13f7d 100644 --- a/crates/gui/src/task.rs +++ b/crates/gui/src/task.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use hatchzip_core::human; use crate::text::{Rate, count, plan_view, reading_text}; -use crate::work::{Counters, Update}; +use crate::work::{Counters, Update, Written}; use crate::{Phase, PlanView, TaskView}; /// Where this archive sits when several were queued from one right-click. @@ -53,6 +53,9 @@ pub struct Task { pub nested: Vec, /// The run resumed, so `nested` covers only the entries it still had. pub nested_partial: bool, + /// The files the run wrote, which each job for `nested` checks its + /// archive against again. + pub written: Written, /// The person closed the password or replace prompt, so the run never /// started. pub cancelled: bool, @@ -144,6 +147,7 @@ impl Task { warning: None, nested: Vec::new(), nested_partial: false, + written: Written::default(), cancelled: false, lower_reserve: None, queue: Queue::Single, @@ -254,6 +258,7 @@ impl Task { self.space = None; self.nested = Vec::new(); self.nested_partial = false; + self.written = Written::default(); self.cancelled = false; v.fraction = 0.0; v.amounts = "".into(); @@ -315,6 +320,7 @@ impl Task { warning, nested, nested_partial, + written, } => { self.keep = keep; // A right-click resume of a selection learns it only here. @@ -322,6 +328,7 @@ impl Task { self.warning = warning; self.nested = nested; self.nested_partial = nested_partial; + self.written = written; v.phase = Phase::Done; v.fraction = 1.0; v.rate = "".into(); @@ -544,6 +551,7 @@ mod tests { warning: None, nested: Vec::new(), nested_partial: false, + written: Written::default(), }); assert_eq!(t.view.phase, Phase::Done); assert_eq!(t.view.heading, "Extraction complete"); @@ -583,6 +591,7 @@ mod tests { warning: None, nested: Vec::new(), nested_partial: false, + written: Written::default(), }); assert_eq!( t.view.message, @@ -823,6 +832,7 @@ mod tests { warning: None, nested: Vec::new(), nested_partial: false, + written: Written::default(), }); assert_eq!(task.keeps_archive(), keep); } diff --git a/crates/gui/src/task_window.rs b/crates/gui/src/task_window.rs index 1bdf5328..b28247a0 100644 --- a/crates/gui/src/task_window.rs +++ b/crates/gui/src/task_window.rs @@ -16,7 +16,7 @@ use crate::args::{TaskArgs, TaskKind}; use crate::runner::Runner; use crate::settings::{AfterExtracting, Appearance, Existing, Settings}; use crate::task::Task; -use crate::work::Request; +use crate::work::{Request, Written}; use crate::{Messages, Palette, TaskWindow}; /// Where each kind of task puts the files. `None` for a test, and for files @@ -92,7 +92,7 @@ pub(crate) fn job_for( here: *kind == TaskKind::ExtractHere, existing: settings.existing_files, only: None, - nested: false, + nested: None, }, ), None => ( @@ -107,8 +107,11 @@ pub(crate) fn job_for( /// A nested archive found inside a finished extraction: next to itself in /// its own folder, asking about existing files, and not scanned again. +/// `written` is what the run that found it wrote, which the job checks the +/// archive against again before it starts. pub(crate) fn nested_job( archive: &Path, + written: Written, keep_archive: bool, keep_free: u64, verify_first: bool, @@ -132,7 +135,7 @@ pub(crate) fn nested_job( here: false, existing: Existing::Ask, only: None, - nested: true, + nested: Some(written), }, ) } @@ -231,12 +234,13 @@ fn build_in( *parent_output.borrow_mut() = r.task.borrow().as_ref().and_then(|t| t.output.clone()); let keep = r.task.borrow().as_ref().map_or(keep, |t| t.keeps_archive()); let keep_free = r.keep_free().unwrap_or(settings.keep_free); - let nested = r + let (nested, written) = r .task .borrow() .as_ref() - .map(|t| t.nested.clone()) - .unwrap_or_default() + .map(|t| (t.nested.clone(), t.written.clone())) + .unwrap_or_default(); + let nested = nested .into_iter() .filter(|p| hatchzip_core::archive::nested_kind(p).is_some()) .collect::>(); @@ -244,7 +248,13 @@ fn build_in( let jobs = nested .iter() .map(|path| { - let (task, mut request) = nested_job(path, keep, keep_free, settings.verify_first); + let (task, mut request) = nested_job( + path, + written.clone(), + keep, + keep_free, + settings.verify_first, + ); if let Some(p) = &password { request.set_password(p.clone()); } diff --git a/crates/gui/src/work.rs b/crates/gui/src/work.rs index 1173d30a..ac44d22a 100644 --- a/crates/gui/src/work.rs +++ b/crates/gui/src/work.rs @@ -39,6 +39,9 @@ impl Counters { } } +/// The files a finished run wrote, made absolute. +pub type Written = Arc>; + /// No `Debug`: a request can carry a password. #[derive(Clone)] pub enum Request { @@ -62,9 +65,11 @@ pub enum Request { /// Only these entries, and everything inside the folders among them, /// which keeps the archive. `None` extracts every entry. only: Option>, - /// This run is itself one of the archives found inside another; its - /// output is not scanned again, one level only. - nested: bool, + /// This run is itself one of the archives found inside another, with + /// the files that run wrote, which the archive is checked against + /// again before it starts. Its output is not scanned again, one + /// level only. + nested: Option, }, Test { archive: PathBuf, @@ -152,6 +157,9 @@ pub enum Update { /// The run resumed, so its entry list held only what was left: the /// offer does not cover files an earlier run extracted. nested_partial: bool, + /// The files this run wrote, which each offered archive is checked + /// against again when its own job starts. + written: Written, }, Tested(usize), /// The archive is whole again, holding this many entries; the ones @@ -209,7 +217,7 @@ pub fn run( here: *here, existing: *existing, only: only.clone(), - nested: *nested, + nested: nested.clone(), }, Secret { password: password.clone(), @@ -298,7 +306,7 @@ struct Choices { here: bool, existing: Existing, only: Option>, - nested: bool, + nested: Option, } fn extract( @@ -319,14 +327,25 @@ fn extract( only, nested: nested_run, } = choices; - // The file was an archive when the offer was made. It may have been - // replaced since, so it is checked again before anything is opened. - if nested_run && hatchzip_core::archive::nested_kind(archive).is_none() { - bail!( - "'{}' is no longer an archive that can be extracted inside, so it may have \ - been replaced. Extract it from its folder instead. Nothing was modified", - archive.display() - ); + // The file was an archive the run wrote whole when the offer was made. + // It may have been replaced since, or a part the person had may have + // joined its set, so it is checked again before anything is opened. A + // paused nested run has its own journal, which the offer would refuse; + // the journal then says what the set is. + if let Some(written) = &nested_run { + let (primary, paths) = session::locate(archive)?; + let still = if paths.exists() { + hatchzip_core::archive::nested_kind(archive).is_some() + } else { + session::nested_offer(archive, written).is_some_and(|p| p == primary) + }; + if !still { + bail!( + "'{}' is no longer an archive that can be extracted inside, so it may have \ + been replaced. Extract it from its folder instead. Nothing was modified", + archive.display() + ); + } } send(Update::Checking); let (primary, paths) = session::locate(archive)?; @@ -360,6 +379,7 @@ fn extract( warning, nested: Vec::new(), nested_partial: false, + written: Arc::default(), }); return Ok(()); } @@ -452,7 +472,7 @@ fn extract( // Every file this run may write, before the job moves into the run. A // nested archive is one of these: a folder scan would also find archives // the person already had there. - let candidates: Vec = if nested_run { + let candidates: Vec = if nested_run.is_some() { Vec::new() } else { job.units @@ -509,15 +529,11 @@ fn extract( .into_iter() .filter(|path| !kept.contains(path)) .filter_map(|path| { - let path = output.join(path); - hatchzip_core::archive::nested_kind(&path)?; - // A split set is one archive, named by its first volume; - // the parent archive is never offered back. - let (primary, _) = session::locate(&path).ok()?; - if parent_primary.as_ref() == Some(&primary) - || !seen.insert(primary.clone()) - || !session::volumes_written(&primary, &written) - { + // A split set is one archive, named by its first volume, + // and only when the run wrote all of it; the parent + // archive is never offered back. + let primary = session::nested_offer(&output.join(path), &written)?; + if parent_primary.as_ref() == Some(&primary) || !seen.insert(primary.clone()) { return None; } Some(primary) @@ -530,6 +546,7 @@ fn extract( warning, nested_partial: resumed && !nested.is_empty(), nested, + written: Arc::new(written), }); } Outcome::Paused => send(Update::Paused), @@ -618,7 +635,7 @@ mod tests { here: false, existing: Existing::Ask, only: None, - nested: false, + nested: None, }; assert!(extract.set_keep_free(500_000_000)); match extract { @@ -963,6 +980,235 @@ mod tests { assert_eq!(std::fs::read(out.join("set.zip")).unwrap(), inner); } + /// [`inner_zip`] as a native split ZIP laid out the way `zip -s` starts + /// one: the split marker and every entry in `set.z01`, and the index + /// alone in `set.zip`, the second and last disk. + fn split_inner() -> [(&'static str, Vec); 2] { + let zip = inner_zip(); + let short = |b: &[u8], i: usize| usize::from(u16::from_le_bytes([b[i], b[i + 1]])); + let word = |b: &[u8], i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap()); + let eocd = zip.len() - 22; + let count = short(&zip, eocd + 10); + let cd_len = word(&zip, eocd + 12); + let cd_at = word(&zip, eocd + 16) as usize; + let mut first = b"PK\x07\x08".to_vec(); + first.extend_from_slice(&zip[..cd_at]); + let mut index = zip[cd_at..cd_at + cd_len as usize].to_vec(); + let mut at = 0; + for _ in 0..count { + // Every entry is on disk 0, behind the marker. + let offset = word(&index, at + 42) + 4; + index[at + 42..at + 46].copy_from_slice(&offset.to_le_bytes()); + at += 46 + short(&index, at + 28) + short(&index, at + 30) + short(&index, at + 32); + } + let count = u16::try_from(count).unwrap(); + // The end record: this is disk 1, the index starts on it, and it + // holds every record. + index.extend_from_slice(b"PK\x05\x06"); + for field in [1u16, 1, count, count] { + index.extend_from_slice(&field.to_le_bytes()); + } + index.extend_from_slice(&cd_len.to_le_bytes()); + index.extend_from_slice(&0u32.to_le_bytes()); + index.extend_from_slice(&0u16.to_le_bytes()); + [("set.z01", first), ("set.zip", index)] + } + + /// What a finished extraction offers to extract inside, and the files it + /// wrote, keeping the person's file at every path the run finds taken + /// when `keep` is set. + fn offered(request: &Request, keep: bool) -> (Vec, Written) { + let counters = Arc::new(Counters::default()); + let seen = Mutex::new(Vec::new()); + run( + request, + &counters, + &|u| seen.lock().unwrap().push(u), + &mut |_| None, + &mut |found, _, _| { + assert!(keep, "nothing is replaced in a fresh folder"); + Some(hatchzip_core::replace::Choices { + keep: found.to_vec(), + ..Default::default() + }) + }, + ); + seen.into_inner() + .unwrap() + .into_iter() + .find_map(|u| match u { + Update::Extracted { + nested, written, .. + } => Some((nested, written)), + _ => None, + }) + .expect("the extraction finished") + } + + /// Every one of `files` is in `dir` as it was written. + fn assert_files(dir: &Path, files: &[(&str, &[u8])]) { + for (name, bytes) in files { + assert_eq!(std::fs::read(dir.join(name)).unwrap(), *bytes, "{name}"); + } + } + + /// A native split ZIP the run wrote whole is one archive, offered by its + /// `.z01`, whose split marker is no ZIP signature, and extracted as a + /// set: every segment is gone afterwards. + #[test] + fn a_split_zip_inside_is_offered_once_and_extracted_as_a_set() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let archive = zip_with(dir.path(), "game.zip", &[(z01, &first), (zip, &last)]); + let out = dir.path().join("out"); + let (nested, written) = offered(&extract(&archive, Some(out.clone()), false), false); + assert_eq!(nested, [out.join("set.z01")]); + + let (_, request) = crate::task_window::nested_job(&nested[0], written, false, 0, false); + let counters = Arc::new(Counters::default()); + let updates = collect(&request, &counters); + assert_eq!( + std::fs::read(out.join("set/inside.txt")).unwrap(), + b"inside", + "{updates:?}" + ); + assert!( + !out.join(z01).exists() && !out.join(zip).exists(), + "every segment is removed in place" + ); + } + + /// The set was the run's when it was offered. A segment the person puts + /// next to it before the job starts would be removed with it, so the job + /// refuses the set and changes nothing. + #[test] + fn a_split_zip_that_gains_a_segment_before_its_job_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let archive = zip_with(dir.path(), "game.zip", &[(z01, &first), (zip, &last)]); + let out = dir.path().join("out"); + let (nested, written) = offered(&extract(&archive, Some(out.clone()), false), false); + assert_eq!(nested, [out.join("set.z01")]); + let theirs: &[u8] = b"the person's own second segment"; + std::fs::write(out.join("set.z02"), theirs).unwrap(); + + let (_, request) = crate::task_window::nested_job(&nested[0], written, false, 0, false); + let counters = Arc::new(Counters::default()); + let updates = collect(&request, &counters); + assert_eq!(updates.len(), 1, "{updates:?}"); + assert!(updates[0].contains("no longer an archive"), "{updates:?}"); + assert_files(&out, &[(z01, &first), ("set.z02", theirs), (zip, &last)]); + assert!(!out.join("set").exists(), "nothing was extracted"); + } + + /// A segment the person had, kept in place of the run's copy, would be + /// removed with the set, so the set is not offered. + #[test] + fn a_split_zip_with_a_kept_segment_is_not_offered_inside() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let archive = zip_with(dir.path(), "game.zip", &[(z01, &first), (zip, &last)]); + let out = dir.path().join("out"); + std::fs::create_dir(&out).unwrap(); + let mut theirs = last.clone(); + theirs.extend_from_slice(b"the person's copy"); + std::fs::write(out.join(zip), &theirs).unwrap(); + + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), true); + assert!(nested.is_empty(), "the person's segment is not offered"); + assert_files(&out, &[(z01, &first), (zip, &theirs)]); + } + + /// A `.zip` the run wrote that is a ZIP on its own still names the set + /// of the person's `.z01` next to it, which is not offered. + #[test] + fn a_split_zip_whose_first_segment_is_the_persons_is_not_offered_inside() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, _)] = split_inner(); + let out = dir.path().join("out"); + std::fs::create_dir(&out).unwrap(); + std::fs::write(out.join(z01), &first).unwrap(); + let inner = inner_zip(); + let archive = zip_with(dir.path(), "game.zip", &[(zip, &inner)]); + + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), false); + assert!(nested.is_empty(), "the person's set is not offered"); + assert_files(&out, &[(z01, &first), (zip, &inner)]); + } + + /// The person's own `.z02` between the run's `.z01` and `.zip` makes the + /// set partly theirs, so it is not offered. + #[test] + fn a_split_zip_with_the_persons_middle_segment_is_not_offered_inside() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let out = dir.path().join("out"); + std::fs::create_dir(&out).unwrap(); + let theirs: &[u8] = b"the person's own second segment"; + std::fs::write(out.join("set.z02"), theirs).unwrap(); + let archive = zip_with(dir.path(), "game.zip", &[(z01, &first), (zip, &last)]); + + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), false); + assert!( + nested.is_empty(), + "a set partly the person's is not offered" + ); + assert_files(&out, &[(z01, &first), ("set.z02", theirs), (zip, &last)]); + } + + /// `.z01`, `.z03` and `.zip` are a set with a segment missing, not a set + /// of three, so it is not offered. + #[test] + fn a_split_zip_missing_a_middle_segment_is_not_offered_inside() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let third: &[u8] = b"the third segment"; + let archive = zip_with( + dir.path(), + "game.zip", + &[(z01, &first), ("set.z03", third), (zip, &last)], + ); + let out = dir.path().join("out"); + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), false); + assert!(nested.is_empty(), "a set with a hole is not offered"); + assert_files(&out, &[(z01, &first), ("set.z03", third), (zip, &last)]); + } + + /// A `.z01` without its `.zip`, which holds the index, is no set. + #[test] + fn a_split_zip_first_segment_alone_is_not_offered_inside() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), _] = split_inner(); + let archive = zip_with(dir.path(), "game.zip", &[(z01, &first)]); + let out = dir.path().join("out"); + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), false); + assert!(nested.is_empty(), "a lone first segment is not offered"); + assert_files(&out, &[(z01, &first)]); + } + + /// An archive that carries progress files of its own would resume from + /// what they say, so neither a set nor a single archive with one is + /// offered. + #[test] + fn an_archive_inside_with_its_own_progress_files_is_not_offered() { + let dir = tempfile::tempdir().unwrap(); + let [(z01, first), (zip, last)] = split_inner(); + let inner = inner_zip(); + let journal: &[u8] = b"{}"; + let files: [(&str, &[u8]); 5] = [ + (z01, &first), + (zip, &last), + ("set.z01.hatchzip", journal), + ("foo.zip", &inner), + ("foo.zip.hatchzip", journal), + ]; + let archive = zip_with(dir.path(), "game.zip", &files); + let out = dir.path().join("out"); + let (nested, _) = offered(&extract(&archive, Some(out.clone()), false), false); + assert!(nested.is_empty(), "{nested:?}"); + assert_files(&out, &files); + } + /// The file was an archive when it was offered. If it is replaced before /// the nested job starts, the job refuses it rather than opening the new /// file. @@ -974,7 +1220,7 @@ mod tests { std::fs::write(&path, &replaced).unwrap(); let mut request = extract(&path, Some(dir.path().join("out")), false); if let Request::Extract { nested, .. } = &mut request { - *nested = true; + *nested = Some(Arc::default()); } let counters = Arc::new(Counters::default()); let updates = collect(&request, &counters); @@ -1122,7 +1368,7 @@ mod tests { here: false, existing: Existing::Ask, only: None, - nested: false, + nested: None, } } @@ -1137,7 +1383,7 @@ mod tests { here: false, existing: Existing::Ask, only: None, - nested: false, + nested: None, } } @@ -1391,7 +1637,7 @@ mod tests { here: false, existing: Existing::Ask, only: None, - nested: false, + nested: None, }; assert_eq!(collect(&request, &counters), ["checking", "no space"]); assert!(!session::locate(&archive).unwrap().1.exists());