Skip to main content

hatchzip_core/
session.rs

1//! Opening an archive for extraction and working out whether it fits. Shared
2//! by the command line and the GUI, so the two never disagree.
3
4use std::collections::HashSet;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use anyhow::{Context, Result, bail};
10
11use crate::archive::storage::{self, Reads, Storage};
12use crate::engine::Job;
13use crate::fsutil;
14use crate::journal::{Journal, Paths, Plan};
15
16/// The first volume of the archive and where its journal lives. Paths are
17/// made absolute so a resume works from any directory.
18pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
19    let primary = std::path::absolute(storage::first_volume(archive))
20        .with_context(|| format!("resolving {}", archive.display()))?;
21    let paths = Paths::for_archive(&primary);
22    Ok((primary, paths))
23}
24
25/// The archive a finished run offers to extract for `path`, one of the files
26/// in `written`, the files it wrote: the first volume of its set, so a set
27/// is offered once whichever volume is asked about. `None` unless `path` and
28/// that first volume are archives by name and signature, and every volume of
29/// the set is in `written` ([`volumes_written`]). A native split ZIP is
30/// found by its `.z01`, whose split marker no other check names.
31///
32/// An archive with progress files next to it (a journal, its tail or
33/// folder list, a split ZIP's stub) is never offered, even when the run
34/// wrote them: a resume would follow what they say, not what the person
35/// was offered. A split ZIP is also opened read only, so a set whose index
36/// names more segments than are there is not offered.
37pub fn nested_offer(path: &Path, written: &HashSet<PathBuf>) -> Option<PathBuf> {
38    crate::archive::nested_kind(path)?;
39    let (primary, paths) = locate(path).ok()?;
40    // A `.zip` that happens to start with a local header names the set of
41    // the `.z01` next to it, which must itself look like a first segment.
42    let kind = crate::archive::nested_kind(&primary)?;
43    let side_files = [&paths.journal, &paths.tail, &paths.folders]
44        .into_iter()
45        .chain(&paths.stub)
46        .any(|p| fs::symlink_metadata(p).is_ok());
47    if side_files || !volumes_written(&primary, written) {
48        return None;
49    }
50    // Opening reads only the index and the local headers, and checks the
51    // segment count against the index. Other formats are not opened here:
52    // a compressed tar is decompressed in full to list it.
53    if kind == crate::archive::SPLIT_ZIP {
54        Job::open(&primary, false, None, Arc::default()).ok()?;
55    }
56    Some(primary)
57}
58
59/// Whether every volume of the set whose first volume is `primary` that
60/// exists on disk is in `written`. A set that is not split has one volume.
61///
62/// Extracting a set in place removes every volume, so an offer to extract it
63/// must not take in one the run did not write: a `.zip` next to the person's
64/// own `.z01` is the last segment of their set, not of the run's.
65///
66/// A native split ZIP also needs its `.zip`, which holds the index. A
67/// segment in `written` past a missing one, such as a `.z03` without the
68/// `.z02`, also makes this false. That only catches the gaps the run's own
69/// files show: a set missing its last segments before the `.zip` passes,
70/// and only opening it, which checks the index, finds that.
71pub fn volumes_written(primary: &Path, written: &HashSet<PathBuf>) -> bool {
72    let mut volumes = Vec::new();
73    if storage::is_split_zip(primary) {
74        for disk in 0.. {
75            let Some(segment) = storage::split_zip_segment(primary, disk) else {
76                break;
77            };
78            if !segment.exists() {
79                break;
80            }
81            volumes.push(segment);
82        }
83        match storage::split_zip_last(primary) {
84            Some(last) if last.exists() => volumes.push(last),
85            _ => return false,
86        }
87        let beyond_a_gap = written.iter().any(|w| {
88            w.parent() == primary.parent()
89                && !volumes.contains(w)
90                && storage::first_volume(w) == primary
91        });
92        if beyond_a_gap {
93            return false;
94        }
95    } else {
96        for index in 0.. {
97            let Some(volume) = storage::volume_path(primary, index) else {
98                break;
99            };
100            if index > 0 && !volume.exists() {
101                break;
102            }
103            volumes.push(volume);
104        }
105    }
106    volumes
107        .iter()
108        .filter(|v| v.exists())
109        .all(|v| written.contains(v))
110        && written.contains(primary)
111}
112
113/// Where an extraction goes, and who said so. A half-extracted archive's
114/// progress files lie next to it, where whoever supplied the archive could
115/// have put them, so a resume follows them only into a folder this
116/// computer recorded starting that extraction in (see [`check_output`]).
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum Output {
119    /// The folder next to the archive ([`default_output`]), or for a
120    /// half-extracted archive the folder its journal records.
121    Default,
122    /// A folder HatchZip worked out itself, such as the one "Extract to
123    /// folder" names after the archive. A resume goes there only when the
124    /// journal says so too, and is trusted as [`Output::Default`] is.
125    Computed(PathBuf),
126    /// A folder the person named for this run, typed or picked.
127    Named(PathBuf),
128}
129
130impl Output {
131    pub fn path(&self) -> Option<&Path> {
132        match self {
133            Self::Default => None,
134            Self::Computed(p) | Self::Named(p) => Some(p),
135        }
136    }
137}
138
139// Made once per open and taken apart at once, so the size of the largest
140// variant costs nothing worth boxing for.
141#[allow(clippy::large_enum_variant)]
142pub enum State {
143    /// Nothing touched yet. Nothing changes on disk until [`begin`] writes
144    /// the journal.
145    Fresh(Job, PathBuf),
146    Resume(Job, Journal),
147    /// The archive is gone but the run died before cleaning up.
148    Orphan(Journal),
149}
150
151/// Asks again what a run recorded when it began: see
152/// [`crate::engine::check_case_record`].
153pub(crate) fn check_recorded_case(journal: &Journal) -> Result<()> {
154    crate::engine::check_case_record(
155        &journal.output,
156        &journal.case_folders,
157        journal.case_beyond_ascii,
158    )
159}
160
161/// Whether names that differ only in case can both exist in `dir`, as far as
162/// HatchZip knows.
163pub fn case_sensitive(dir: &Path) -> bool {
164    crate::platform::case_sensitive(dir)
165}
166
167/// `writable` is false for anything that only looks, so it works on
168/// read-only media and never takes the lock. For a fresh extraction the
169/// output folder may already hold other files, but no folder where the
170/// archive has a file or the other way round; files the archive would
171/// replace are listed by [`existing`]. `password` only matters for encrypted archives; see
172/// [`open_encrypted`] for the ask-and-retry loop front ends want. What
173/// opening reads is counted in `reads`, which a front end can show from
174/// another thread: a compressed tar is read in full here.
175///
176/// `only` limits a fresh extraction to those entries and the folders among
177/// them (see [`Job::select`]), which [`begin`] then allows only while the
178/// archive is kept. A half-extracted archive goes on with the selection its
179/// journal records, and one given here must be part of it.
180pub fn open(
181    primary: &Path,
182    paths: &Paths,
183    output: Output,
184    only: Option<&[PathBuf]>,
185    writable: bool,
186    password: Option<&str>,
187    reads: &Arc<Reads>,
188) -> Result<State> {
189    if paths.exists() {
190        let (mut journal, tail) = Journal::load(paths)?;
191        // With every entry out, or the archive gone, this is no resume: it
192        // only finishes, and a lost list costs the folders' permissions and
193        // times, which the finish warns about.
194        if writable && !journal.done && journal.parts[0].0.exists() {
195            journal.check_folders(paths)?;
196        }
197        // Only a writable open deletes or writes anything in the folder.
198        if writable || output != Output::Default {
199            check_output(&journal, primary, &output)?;
200        }
201        if writable {
202            check_recorded_case(&journal)?;
203        }
204        if journal.restoring.is_some() {
205            if !writable {
206                bail!(
207                    "a restore of this archive was interrupted. Run restore again to complete \
208                     it, or run extract to resume the extraction"
209                );
210            }
211            crate::restore::recover(&mut journal, paths)?;
212        }
213        if !journal.parts[0].0.exists() {
214            check_first_part_gone(&journal)?;
215            if journal.keep {
216                // Only the person could have removed an archive this run
217                // promised to keep, and the rest of it is still to extract.
218                bail!(
219                    "{} was moved or deleted during an extraction that keeps it. Put it back \
220                     to resume, or delete {} to discard the progress",
221                    journal.parts[0].0.display(),
222                    paths.journal.display()
223                );
224            }
225            return Ok(State::Orphan(journal));
226        }
227        // The final commit was journaled: every unit is extracted, and only
228        // the archive's removal and the links are left. Nothing is read from
229        // it again; a compressed stream's start was punched away by then.
230        if journal.done {
231            return Ok(State::Orphan(journal));
232        }
233        if let Some(given) = only {
234            check_same_selection(&journal, given)?;
235        }
236        let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
237        check_no_links_on_the_way(&job, &journal.output)?;
238        return Ok(State::Resume(job, journal));
239    }
240    let mut job = Job::open(primary, writable, password, reads.clone())?;
241    if writable && job.format_name == crate::archive::SPLIT_ZIP {
242        paths.check_stub()?;
243    }
244    if let Some(given) = only {
245        job.select(given)?;
246    }
247    let output = match output {
248        Output::Named(o) => std::path::absolute(o)?,
249        // A folder worked out from the archive's name, like the default
250        // one, may be a link the archive's supplier put there.
251        Output::Computed(o) => {
252            let output = std::path::absolute(o)?;
253            refuse_linked_default(&output)?;
254            output
255        }
256        Output::Default => {
257            let output = default_output(primary);
258            refuse_linked_default(&output)?;
259            output
260        }
261    };
262    check_path_lengths(&job, &output)?;
263    if writable {
264        check_no_links_on_the_way(&job, &output)?;
265        check_collisions(&job, &output)?;
266        job.check_case(&output)?;
267    }
268    Ok(State::Fresh(job, output))
269}
270
271/// With the first part of a split archive gone, a run that never journaled
272/// its last commit has not deleted it: the first part is only ever shortened,
273/// and deleted with the rest once everything is out. So when a later part
274/// that still holds entries to extract is there, the first one was moved,
275/// and finishing the run as one whose archive is gone would delete the
276/// journal and the saved index the rest of the archive needs.
277pub(crate) fn check_first_part_gone(journal: &Journal) -> Result<()> {
278    if journal.done || journal.keep {
279        return Ok(());
280    }
281    let mut start = 0u64;
282    for (i, (part, len)) in journal.parts.iter().enumerate() {
283        if i > 0 && start < journal.committed_len && part.exists() {
284            bail!(
285                "{} was moved or deleted during the extraction, but {} and the rest of the \
286                 archive still need it. Put it back to resume. Nothing was modified",
287                journal.parts[0].0.display(),
288                part.display()
289            );
290        }
291        start = start.saturating_add(*len);
292    }
293    Ok(())
294}
295
296/// A resume goes on with what its journal records. Asking for entries now is
297/// fine when they are all part of that selection, and refused otherwise,
298/// before the archive is opened for writing.
299fn check_same_selection(journal: &Journal, given: &[PathBuf]) -> Result<()> {
300    let Some(recorded) = &journal.only else {
301        bail!(
302            "this archive is partially extracted with every entry selected. Resume it without \
303             choosing entries, or run restore first. Nothing was modified"
304        );
305    };
306    for g in given {
307        let p = crate::engine::selection_path(g)?;
308        // A path inside a recorded folder is part of the selection too.
309        if !crate::engine::picks(recorded, &p) {
310            bail!(
311                "this archive is partially extracted with other entries selected, and '{}' is \
312                 not one of them. Resume it without choosing entries to finish those, or run \
313                 restore first. Nothing was modified",
314                p.display()
315            );
316        }
317    }
318    Ok(())
319}
320
321/// The journal lies next to the archive, where anyone who supplied the
322/// archive could have put one, so it is used only for an extraction this
323/// computer recorded starting into that folder (see [`crate::chosen`]). A
324/// resume deletes what it finds at the paths of the entries left and cuts
325/// the archive to what the journal says, so a planted journal could
326/// otherwise destroy the archive and replace the person's own files in the
327/// folder it names. A folder given now must also be the journal's, and one
328/// HatchZip worked out ([`Output::Computed`]) vouches for nothing: a
329/// planted journal can name it as easily as the app does. Without the
330/// record the journal is never followed, whatever its format says: a
331/// planted one can claim to come from a release that kept no record.
332pub fn check_output(journal: &Journal, primary: &Path, given: &Output) -> Result<()> {
333    let default = default_output(primary);
334    let in_default = fsutil::same_path(&default, &journal.output);
335    if let Some(o) = given.path()
336        && !fsutil::same_path(&std::path::absolute(o)?, &journal.output)
337    {
338        bail!(
339            "this archive is already partially extracted to {}. Complete or restore that \
340             extraction first",
341            journal.output.display()
342        );
343    }
344    let named = matches!(given, Output::Named(_));
345    if crate::chosen::chose(primary, &journal.output) {
346        // A folder the person names is theirs to choose, link or not.
347        if in_default && !named {
348            refuse_linked_default(&default)?;
349        }
350        return Ok(());
351    }
352    let paths = Paths::for_archive(primary);
353    bail!(
354        "{} has progress files next to it for an extraction to {}, but HatchZip on this computer \
355         has no record of starting it, so they were not used. If you did not start this \
356         extraction, delete {}. Nothing was modified",
357        primary.display(),
358        journal.output.display(),
359        journal.side_files(&paths)
360    )
361}
362
363/// A link at the default output folder, next to the archive, would send the
364/// extraction wherever it points. A folder the person names is theirs to
365/// choose.
366fn refuse_linked_default(output: &Path) -> Result<()> {
367    if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
368        bail!(
369            "{} is a link, so files extracted there would land somewhere else. Remove the link, \
370             or choose the destination folder. Nothing was modified",
371            output.display()
372        );
373    }
374    Ok(())
375}
376
377/// A resume deletes and writes the files of the entries left, and its own
378/// links are only made once every entry is done. A link on the way to one of
379/// those files was put there by someone else, and following it would leave
380/// the output folder.
381pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
382    let mut checked = std::collections::HashSet::new();
383    for item in job.units.iter().flat_map(|u| &u.items) {
384        for parent in item
385            .path
386            .ancestors()
387            .skip(1)
388            .filter(|p| !p.as_os_str().is_empty())
389        {
390            if !checked.insert(parent.to_path_buf()) {
391                break;
392            }
393            if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
394                bail!(
395                    "{} is a link, and '{}' would be extracted through it. Nothing was modified",
396                    out.join(parent).display(),
397                    item.path.display()
398                );
399            }
400        }
401    }
402    Ok(())
403}
404
405/// A path the system can't create would only fail halfway through a run,
406/// after part of the archive is gone; macOS stops at 1024 bytes.
407fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
408    for item in job.units.iter().flat_map(|u| &u.items) {
409        if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
410            bail!(
411                "'{}' cannot be created in {}: the full path would be longer than this system \
412                 allows. The archive was not modified. Extract to a folder with a shorter path",
413                item.path.display(),
414                out.display()
415            );
416        }
417    }
418    Ok(())
419}
420
421/// Opens an archive that may be encrypted. `ask` is called whenever a
422/// password is needed or the last one was wrong, and returns `None` to give
423/// up. Archives with a password are proven with [`Job::check_password`]
424/// before this returns, so nothing is deleted on a wrong guess. Returns the
425/// state and the password that worked.
426#[allow(clippy::too_many_arguments)]
427pub fn open_encrypted(
428    primary: &Path,
429    paths: &Paths,
430    output: Output,
431    only: Option<&[PathBuf]>,
432    writable: bool,
433    password: Option<String>,
434    reads: &Arc<Reads>,
435    ask: impl FnMut(bool) -> Option<String>,
436) -> Result<(State, Option<String>)> {
437    open_encrypted_noting(
438        primary,
439        paths,
440        output,
441        only,
442        writable,
443        password,
444        reads,
445        ask,
446        |_, _| {},
447    )
448}
449
450/// [`open_encrypted`], calling `slow` with a file and its size before a
451/// password check that decodes all of it (see [`Job::slow_password_check`]),
452/// so a front end can say it may take a while.
453#[allow(clippy::too_many_arguments)]
454pub fn open_encrypted_noting(
455    primary: &Path,
456    paths: &Paths,
457    output: Output,
458    only: Option<&[PathBuf]>,
459    writable: bool,
460    mut password: Option<String>,
461    reads: &Arc<Reads>,
462    mut ask: impl FnMut(bool) -> Option<String>,
463    mut slow: impl FnMut(&Path, u64),
464) -> Result<(State, Option<String>)> {
465    let mut wrong = false;
466    loop {
467        let attempt = open(
468            primary,
469            paths,
470            output.clone(),
471            only,
472            writable,
473            password.as_deref(),
474            reads,
475        );
476        let failure = match attempt {
477            Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
478            Ok(state) => {
479                let job = match &state {
480                    State::Fresh(job, _) | State::Resume(job, _) => job,
481                    State::Orphan(_) => unreachable!(),
482                };
483                if !job.encrypted() {
484                    return Ok((state, password));
485                }
486                if password.is_some()
487                    && let Some((file, size)) = job.slow_password_check()
488                {
489                    slow(file, size);
490                }
491                match job.check_password() {
492                    Ok(()) => return Ok((state, password)),
493                    Err(e) => e,
494                }
495            }
496            Err(e) => e,
497        };
498        if failure.is::<crate::archive::WrongPassword>() {
499            wrong = true;
500        } else if !failure.is::<crate::archive::PasswordNeeded>() {
501            return Err(failure);
502        }
503        // Drop the open archive before asking, so nothing stays locked while
504        // a person types.
505        match ask(wrong) {
506            Some(p) => password = Some(p),
507            None => return Err(failure),
508        }
509    }
510}
511
512/// Refuses what no extraction into `out` can get past: a folder where the
513/// archive has a file, which is never deleted or replaced, a file where it
514/// needs a folder, which would only fail halfway, and anything at the name a
515/// file is first written under. That last one would be in the way of the
516/// file, or would be deleted as the run's own by a resume.
517fn check_collisions(job: &Job, out: &Path) -> Result<()> {
518    if !out.exists() {
519        return Ok(());
520    }
521    check_own_files(job, out)?;
522    let mut checked = std::collections::HashSet::new();
523    for item in job.units.iter().flat_map(|u| &u.items) {
524        let dest = out.join(&item.path);
525        let part = crate::engine::part_path(&dest);
526        if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
527            bail!(
528                "{} already exists. HatchZip first writes '{}' under that name and does not \
529                 replace a file it did not create. Move it or choose another destination. Nothing \
530                 was modified",
531                part.display(),
532                item.path.display()
533            );
534        }
535        if let Ok(meta) = fs::symlink_metadata(&dest) {
536            let dir = item.kind == crate::archive::Kind::Dir;
537            if dir && !meta.is_dir() {
538                bail!(
539                    "{} is a file, but the archive requires a folder at that location",
540                    dest.display()
541                );
542            }
543            if !dir && meta.is_dir() {
544                bail!(
545                    "{} is a folder, but the archive has a file at that location. Move the \
546                     folder or choose another destination",
547                    dest.display()
548                );
549            }
550        }
551        for parent in item
552            .path
553            .ancestors()
554            .skip(1)
555            .filter(|p| !p.as_os_str().is_empty())
556        {
557            if !checked.insert(parent.to_path_buf()) {
558                break;
559            }
560            if let Ok(meta) = fs::symlink_metadata(out.join(parent))
561                && !meta.is_dir()
562            {
563                bail!(
564                    "{} is a file, but the archive requires a folder at that location",
565                    out.join(parent).display()
566                );
567            }
568        }
569    }
570    Ok(())
571}
572
573/// Refuses an entry that would land on one of the archive's own files: a
574/// volume, or a progress file next to the first volume (`<archive>.hatchzip`,
575/// `<archive>.hatchzip-tail` and any later one). Written over, a volume would
576/// be lost before it was read, and a progress file would be trusted by the
577/// next resume as HatchZip's own. That can only happen when the archive's
578/// folder is inside the output folder. Names are compared ignoring case, as
579/// a case-insensitive filesystem would.
580fn check_own_files(job: &Job, out: &Path) -> Result<()> {
581    let text = |p: &Path| p.to_string_lossy().to_lowercase();
582    let folder = |p: &Path| {
583        let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
584        fs::canonicalize(dir.unwrap_or(Path::new(".")))
585            .ok()
586            .map(|d| text(&d))
587    };
588    let lower = |p: &Path| p.file_name().map(|n| text(Path::new(n)));
589    let Ok(out) = fs::canonicalize(out) else {
590        return Ok(());
591    };
592    let primary = job.storage.primary();
593    let own_folder = folder(primary);
594    let side = lower(primary).map(|n| format!("{n}.hatchzip"));
595    let volumes: Vec<_> = job
596        .storage
597        .parts()
598        .iter()
599        .map(|p| (folder(&p.path), lower(&p.path)))
600        .collect();
601    for item in job.units.iter().flat_map(|u| &u.items) {
602        let dest = out.join(&item.path);
603        let dir = dest.parent().map(text);
604        let name = lower(&dest);
605        let (Some(dir), Some(name)) = (dir, name) else {
606            continue;
607        };
608        let volume = volumes
609            .iter()
610            .any(|(d, n)| d.as_ref() == Some(&dir) && n.as_ref() == Some(&name));
611        let progress = own_folder.as_ref() == Some(&dir)
612            && side.as_ref().is_some_and(|s| name.starts_with(s.as_str()));
613        if volume || progress {
614            bail!(
615                "'{}' would be extracted onto {}, one of the archive's own files. Choose another \
616                 destination. Nothing was modified",
617                item.path.display(),
618                dest.display()
619            );
620        }
621    }
622    Ok(())
623}
624
625/// The files and links already in `out` at paths the archive extracts to,
626/// relative to `out`. A fresh extraction may only replace them when asked
627/// to; see [`begin`]. When there are any, what would keep them from being
628/// replaced is refused here, before a front end asks.
629pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
630    let found = crate::replace::found(job, out);
631    if !found.is_empty() {
632        crate::replace::check(job, out, &found)?;
633    }
634    Ok(found)
635}
636
637/// Whether everything in the archive sits under one name at its top, one
638/// folder or a single file. "Extract here" puts such an archive next to
639/// itself; anything else would scatter loose files, so it gets a folder.
640pub fn single_root(job: &Job) -> bool {
641    let mut roots = job
642        .units
643        .iter()
644        .flat_map(|u| &u.items)
645        .filter_map(|i| i.path.components().next());
646    let Some(first) = roots.next() else {
647        return false;
648    };
649    roots.all(|r| r == first)
650}
651
652/// Moves a fresh extraction opened writable by [`open`] to another folder,
653/// checking it as [`open`] checks the one it was given.
654pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
655    let out = std::path::absolute(out)?;
656    check_path_lengths(job, &out)?;
657    check_no_links_on_the_way(job, &out)?;
658    check_collisions(job, &out)?;
659    job.check_case(&out)?;
660    Ok(out)
661}
662
663/// `game.zip`, `game.7z.001`, `game.tar.gz`, `game.part1.rar` and `game.z01`
664/// all extract into `game`, next to them.
665pub fn default_output(primary: &Path) -> PathBuf {
666    let file_name = primary
667        .file_name()
668        .unwrap_or_default()
669        .to_string_lossy()
670        .into_owned();
671    let mut name = file_name.clone();
672    if let Some((stem, digits)) = name.rsplit_once('.')
673        && digits.len() >= 3
674        && digits.bytes().all(|b| b.is_ascii_digit())
675    {
676        name = stem.to_string();
677    }
678    // `game.z01` is the first segment of the split ZIP `game.zip`.
679    if let Some((stem, ext)) = name.rsplit_once('.')
680        && ext.len() >= 3
681        && ext.as_bytes()[0].eq_ignore_ascii_case(&b'z')
682        && ext.bytes().skip(1).all(|b| b.is_ascii_digit())
683    {
684        name = stem.to_string();
685    }
686    let lower = name.to_ascii_lowercase();
687    // `game.part2.rar` and `game.part02.rar` are volumes of `game`.
688    if let Some(stem) = lower.strip_suffix(".rar")
689        && let Some((_, digits)) = stem.rsplit_once(".part")
690        && !digits.is_empty()
691        && digits.bytes().all(|b| b.is_ascii_digit())
692    {
693        name.truncate(stem.len() - digits.len() - ".part".len());
694    } else {
695        for ext in [
696            ".zip", ".7z", ".tar.xz", ".txz", ".tar.bz2", ".tbz2", ".tbz", ".tar.zst", ".tzst",
697            ".tar", ".tar.gz", ".tgz", ".rar", ".exe",
698        ] {
699            if lower.ends_with(ext) && name.len() > ext.len() {
700                name.truncate(name.len() - ext.len());
701                break;
702            }
703        }
704    }
705    // What is left names a folder next to the archive, so it must be an
706    // ordinary name. `...zip` would leave `..`, the folder above, and `..zip`
707    // would leave `.`, the archive's own folder, where its entries could
708    // replace its progress files. Windows drops trailing dots and spaces, so
709    // `. .zip` is `.` there too.
710    if name == file_name || name.chars().all(|c| c == '.' || c == ' ') {
711        name = file_name;
712        name.push_str("-extracted");
713    }
714    primary.with_file_name(name)
715}
716
717/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
718pub fn display_name(job: &Job) -> String {
719    let parts = job.storage.parts();
720    let first = parts[0]
721        .path
722        .file_name()
723        .unwrap_or_default()
724        .to_string_lossy()
725        .into_owned();
726    match parts.len() {
727        1 => first,
728        n => format!("{first} (+{} more parts)", n - 1),
729    }
730}
731
732/// Whether the extraction of a half-extracted archive keeps it, given what
733/// the person asked for now. The journal decides: an extraction that keeps
734/// the archive goes on keeping it, and one that has already removed part of
735/// it can't start keeping it.
736pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
737    if asked && !journal.keep {
738        bail!(
739            "this archive is partially extracted in place, so part of it is already removed and \
740             it cannot be kept. Resume without --keep-archive, or run restore first"
741        );
742    }
743    Ok(journal.keep)
744}
745
746/// Whether an extraction fits, in the numbers a person needs to decide.
747pub struct SpacePlan {
748    /// Usable free space, counting files a crashed run left that will be
749    /// deleted before continuing.
750    pub free: u64,
751    /// Free space the extraction needs at its busiest moment, in the mode
752    /// asked for.
753    pub needed: u64,
754    pub keep_free: u64,
755    pub fits: bool,
756    /// Free space once finished, if it fits.
757    pub free_after: u64,
758    /// The plan is for an extraction that keeps the archive.
759    pub keep_archive: bool,
760    /// What an extraction that keeps the archive needs free: every
761    /// extracted file, as for any other extractor, plus the saved index.
762    pub normal_needs: u64,
763    /// What extracting in place needs free. Equal to `needed` unless the
764    /// archive is kept.
765    pub in_place_needs: u64,
766    /// Nothing is extracted yet, so either mode can still be chosen. A
767    /// half-extracted archive continues in the mode it started in.
768    pub either: bool,
769    /// False when the output is on another disk, so freeing the archive
770    /// doesn't help it.
771    pub reclaims: bool,
772    /// The shortfall comes from one solid block that can only be freed once
773    /// all of it is out.
774    pub solid_block_bound: bool,
775    /// The archive is one compressed stream (a `.tar.gz`) on a filesystem
776    /// that can't free space inside a file, such as FAT32 or exFAT, so it
777    /// stays whole until the extraction completes: `needed` is room for
778    /// every extracted file next to it.
779    pub archive_kept_whole: bool,
780}
781
782impl SpacePlan {
783    /// Whether an extraction that keeps the archive would fit too.
784    pub fn normal_fits(&self) -> bool {
785        self.free >= self.normal_needs + self.keep_free
786    }
787
788    pub fn in_place_fits(&self) -> bool {
789        self.free >= self.in_place_needs + self.keep_free
790    }
791}
792
793/// Refuses a destination that cannot become a folder: a file or a dangling
794/// link at its path, or where one of its folders would go. Called before
795/// anything is written, so a run cannot leave a journal that only promises a
796/// resume that would fail the same way.
797fn check_destination(out: &Path, resuming: bool) -> Result<()> {
798    let untouched = if resuming {
799        ""
800    } else {
801        ". Nothing was modified"
802    };
803    // Walk up until something exists. `exists` follows links, so a dangling
804    // one looks absent and `create_dir_all` would fail on it later; metadata
805    // that is not a folder stops the run here instead.
806    let mut path = out.to_path_buf();
807    loop {
808        match path.symlink_metadata() {
809            Ok(meta) => {
810                if path.is_dir() {
811                    return Ok(());
812                }
813                let what = if meta.is_file() {
814                    "is a file, not a folder"
815                } else {
816                    "is not a folder"
817                };
818                if path == out {
819                    bail!("the destination {} {what}{untouched}", out.display());
820                }
821                bail!(
822                    "the destination {} cannot be created: {} {what}{untouched}",
823                    out.display(),
824                    path.display()
825                );
826            }
827            Err(_) => {
828                if !path.pop() {
829                    return Ok(());
830                }
831            }
832        }
833    }
834}
835
836/// The space plan for extracting `job` into `out`, keeping the archive or
837/// not. For a half-extracted archive, `keep_archive` must be what its
838/// journal says; see [`keeps_archive`].
839pub fn plan(
840    job: &Job,
841    out: &Path,
842    resuming: bool,
843    keep_free: u64,
844    keep_archive: bool,
845) -> Result<SpacePlan> {
846    job.check_case(out)?;
847    check_destination(out, resuming)?;
848    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
849    let stale: u64 =
850        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
851    let free = fsutil::available_space(out)? + stale;
852    // Keeping the archive frees nothing, as if the output were on another
853    // disk: the replay counts every file and gives nothing back.
854    let (normal_needs, normal_end) = job.space_needed(!resuming, false);
855    let (in_place_needs, in_place_end) = if keep_archive && resuming {
856        (normal_needs, normal_end)
857    } else {
858        job.space_needed(!resuming, reclaims)
859    };
860    // The saved index is deleted at the end, when the archive is kept too.
861    let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
862    let normal_end = normal_end - if reclaims { tail } else { 0 };
863    let (needed, end) = if keep_archive {
864        (normal_needs, normal_end)
865    } else {
866        (in_place_needs, in_place_end)
867    };
868    let fits = free >= needed + keep_free;
869    Ok(SpacePlan {
870        free,
871        needed,
872        keep_free,
873        fits,
874        free_after: (free as i128 - end).max(0) as u64,
875        keep_archive,
876        normal_needs,
877        in_place_needs,
878        either: !resuming,
879        reclaims,
880        solid_block_bound: !fits
881            && !keep_archive
882            && !job.is_stream()
883            && job
884                .units
885                .iter()
886                .any(|u| u.items.len() > 1 && u.size() > free),
887        archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
888    })
889}
890
891/// Commits to a fresh extraction: saves the archive's tail and writes the
892/// journal. From here on the archive may be truncated, unless `keep_archive`
893/// is set, in which case nothing ever changes it. Files in the way (see
894/// [`existing`]) are refused unless `replace` is given; then the run moves
895/// them aside before it extracts anything, and once it is complete deletes
896/// them or puts back the ones the choices keep.
897pub fn begin(
898    job: &Job,
899    paths: &Paths,
900    output: PathBuf,
901    keep_archive: bool,
902    replace: Option<&crate::replace::Choices>,
903) -> Result<Journal> {
904    // Front ends ask earlier; the folder may have changed since.
905    job.check_case(&output)?;
906    check_destination(&output, false)?;
907    let found = existing(job, &output)?;
908    if let Some(first) = found.first()
909        && replace.is_none()
910    {
911        let what = match found.len() {
912            1 => format!("{} already exists", output.join(first).display()),
913            n => format!(
914                "{} and {} other {} already exist",
915                output.join(first).display(),
916                n - 1,
917                if n == 2 { "file" } else { "files" }
918            ),
919        };
920        bail!(
921            "{what}. Existing files are only replaced when that is requested. Move the files or \
922             choose another destination. Nothing was modified"
923        );
924    }
925    if job.selection().is_some() && !keep_archive {
926        // Truncating would destroy the entries left out.
927        bail!(
928            "only some entries are selected, and those are extracted only while the archive is \
929             kept. Nothing was modified"
930        );
931    }
932    if keep_archive {
933        job.storage.protect();
934    } else if let Some(why) = job.in_place_refusal() {
935        // Front ends say this earlier; this is the last line.
936        bail!("{why}. It can be extracted while keeping the archive");
937    }
938    crate::sfv::check_volumes(&job.storage)?;
939    // Whatever the folder: a resume trusts the journal only when this
940    // computer recorded starting the extraction (see [`check_output`]), so
941    // a run that can't be recorded could never be resumed.
942    crate::chosen::remember(&paths.archive, &output)?;
943    // A choice for a file that has gone since it was made has nothing to
944    // keep.
945    let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
946        paths
947            .iter()
948            .filter(|p| found.contains(p))
949            .cloned()
950            .collect()
951    };
952    let replace = replace
953        .filter(|_| !found.is_empty())
954        .map(|c| crate::journal::Replace {
955            moved: false,
956            keep: only_found(&c.keep),
957            both: only_found(&c.both),
958        });
959    let folders = crate::folders::of(&job.units, &output);
960    let plan = Plan {
961        format: job.format_name,
962        tail_start: job.tail_start,
963        output,
964        total_size: job.remaining_size(),
965        keep: keep_archive,
966        replace,
967        case_folders: job.case_folders(),
968        case_beyond_ascii: job.case_beyond_ascii(),
969        folders,
970        only: job.selection().map(<[PathBuf]>::to_vec),
971    };
972    Journal::create(paths, &job.storage, plan)
973}
974
975/// Checks the archive's volumes against an `.sfv` file next to it, if present.
976pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
977    crate::sfv::check_volumes_cancellable(storage, cancelled)
978}
979
980/// Before continuing a crashed run, deletes what it wrote for batches it
981/// never committed.
982pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
983    clear_output(job, out, false)
984}
985
986/// Discards a kept run's uncommitted output, including its open file. The
987/// untouched archive holds that file; normal resume must preserve it.
988pub(crate) fn clear_discarded(job: &Job, out: &Path) -> Result<()> {
989    clear_output(job, out, true)
990}
991
992fn clear_output(job: &Job, out: &Path, discard: bool) -> Result<()> {
993    check_no_links_on_the_way(job, out)?;
994    let found = if discard {
995        job.discarded_output(out)
996    } else {
997        job.uncommitted(out)
998    };
999    let mut listed = std::collections::HashMap::new();
1000    for (p, _) in &found {
1001        check_spelling(out, p, &mut listed)?;
1002    }
1003    for (p, _) in found {
1004        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
1005    }
1006    Ok(())
1007}
1008
1009/// Refuses to delete `path` unless every name from `out` down to it is
1010/// spelled on disk as in the entry. Where the filesystem folds names,
1011/// `makefile` also finds a `Makefile` that another program, or another
1012/// archive, put there after this run began, and that one isn't this run's
1013/// to delete. Spellings are compared decomposed and nothing else, since
1014/// HFS+ stores names decomposed whatever they were created as.
1015fn check_spelling(
1016    out: &Path,
1017    path: &Path,
1018    listed: &mut std::collections::HashMap<PathBuf, std::collections::HashSet<String>>,
1019) -> Result<()> {
1020    use unicode_normalization::UnicodeNormalization;
1021    let spelling = |n: &std::ffi::OsStr| n.to_string_lossy().nfd().collect::<String>();
1022    let Ok(rel) = path.strip_prefix(out) else {
1023        return Ok(());
1024    };
1025    let mut dir = out.to_path_buf();
1026    for name in rel.iter() {
1027        let names = match listed.entry(dir.clone()) {
1028            std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
1029            std::collections::hash_map::Entry::Vacant(e) => e.insert(
1030                fs::read_dir(&dir)
1031                    .with_context(|| format!("listing {}", dir.display()))?
1032                    .map(|e| e.map(|e| spelling(&e.file_name())))
1033                    .collect::<std::io::Result<_>>()
1034                    .with_context(|| format!("listing {}", dir.display()))?,
1035            ),
1036        };
1037        if !names.contains(&spelling(name)) {
1038            bail!(
1039                "{} is spelled differently on disk than in the archive, so it was not made by \
1040                 this extraction and is left alone. Move it out of the way, then run the command \
1041                 again",
1042                dir.join(name).display()
1043            );
1044        }
1045        dir.push(name);
1046    }
1047    Ok(())
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use std::io::Write;
1053
1054    use ::zip::write::{SimpleFileOptions, ZipWriter};
1055
1056    use super::*;
1057
1058    /// A resume only deletes what is spelled as its entry: a `Makefile` on
1059    /// disk isn't `makefile`'s, even where the filesystem would find it.
1060    #[test]
1061    fn a_resume_leaves_names_spelled_differently_alone() {
1062        let dir = tempfile::tempdir().unwrap();
1063        let out = dir.path();
1064        fs::create_dir(out.join("Src")).unwrap();
1065        fs::write(out.join("Src/Makefile"), b"theirs").unwrap();
1066        fs::write(out.join("Src/caf\u{e9}.txt"), b"ours").unwrap();
1067        let mut listed = std::collections::HashMap::new();
1068        assert!(check_spelling(out, &out.join("Src/makefile"), &mut listed).is_err());
1069        assert!(check_spelling(out, &out.join("src/Makefile"), &mut listed).is_err());
1070        assert!(check_spelling(out, &out.join("Src/Makefile"), &mut listed).is_ok());
1071        // HFS+ hands back the decomposed form of what was created composed.
1072        assert!(check_spelling(out, &out.join("Src/cafe\u{301}.txt"), &mut listed).is_ok());
1073    }
1074
1075    #[test]
1076    fn output_folder_drops_the_volume_and_format_suffixes() {
1077        let name = |n: &str| default_output(Path::new(n));
1078        assert_eq!(name("game.zip"), Path::new("game"));
1079        assert_eq!(name("game.7z.001"), Path::new("game"));
1080        assert_eq!(name("game.part1.rar"), Path::new("game"));
1081        assert_eq!(name("game.PART02.RAR"), Path::new("game"));
1082        assert_eq!(name("game.rar"), Path::new("game"));
1083        assert_eq!(name("game.tar.xz"), Path::new("game"));
1084        assert_eq!(name("game.txz"), Path::new("game"));
1085        assert_eq!(name("game.tar.zst"), Path::new("game"));
1086        assert_eq!(name("game.tzst"), Path::new("game"));
1087        assert_eq!(name("game.part.rar"), Path::new("game.part"));
1088        assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
1089    }
1090
1091    /// A name that would leave only dots, the folder above or the archive's
1092    /// own, gets a folder of its own instead.
1093    #[test]
1094    fn output_folder_is_never_the_folder_above_or_the_archives_own() {
1095        let name = |n: &str| default_output(&Path::new("dl").join(n));
1096        for n in [
1097            "...zip",
1098            "..zip",
1099            ".zip",
1100            ". .zip",
1101            "...tar.gz",
1102            "...7z.001",
1103            "...part1.rar",
1104            "..part2.rar",
1105        ] {
1106            assert_eq!(
1107                name(n),
1108                Path::new("dl").join(format!("{n}-extracted")),
1109                "{n}"
1110            );
1111        }
1112        assert_eq!(name("...game.zip"), Path::new("dl/...game"));
1113    }
1114
1115    /// Eight stored entries, so extracting in place frees the archive entry
1116    /// by entry and needs far less than keeping it.
1117    fn sample_zip(dir: &Path) -> PathBuf {
1118        let path = dir.join("plan.zip");
1119        let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
1120        let opts =
1121            SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
1122        for i in 0..8u8 {
1123            w.start_file(format!("data/{i}.bin"), opts).unwrap();
1124            w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
1125        }
1126        w.finish().unwrap();
1127        path
1128    }
1129
1130    #[test]
1131    fn keeping_the_archive_plans_for_every_file() {
1132        let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
1133        fs::create_dir_all(&dir).unwrap();
1134        let archive = sample_zip(&dir);
1135        let out = dir.join("out");
1136        let job = Job::open(&archive, false, None, Default::default()).unwrap();
1137        let files: u64 = job
1138            .units
1139            .iter()
1140            .flat_map(|u| &u.items)
1141            .map(|i| i.size.next_multiple_of(4096))
1142            .sum();
1143        let tail = job.storage.original_len() - job.tail_start;
1144
1145        let keep = plan(&job, &out, false, 0, true).unwrap();
1146        assert!(keep.keep_archive && keep.either);
1147        // Every file, plus the copy of the index a resume would need.
1148        assert_eq!(keep.needed, files + tail);
1149        assert_eq!(keep.normal_needs, keep.needed);
1150        assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
1151        // Nothing of the archive comes back; the saved index does.
1152        assert_eq!(keep.free.saturating_sub(keep.free_after), files);
1153
1154        let in_place = plan(&job, &out, false, 0, false).unwrap();
1155        assert!(!in_place.keep_archive);
1156        assert_eq!(in_place.normal_needs, keep.needed);
1157        assert_eq!(in_place.in_place_needs, in_place.needed);
1158        assert_eq!(keep.in_place_needs, in_place.needed);
1159        assert!(
1160            in_place.needed < keep.needed / 2,
1161            "in place {} vs kept {}",
1162            in_place.needed,
1163            keep.needed
1164        );
1165        drop(job);
1166        fs::remove_dir_all(&dir).unwrap();
1167    }
1168
1169    /// Once an extraction that keeps the archive has begun, nothing can
1170    /// change it, whatever the caller does.
1171    #[test]
1172    fn a_kept_archive_refuses_every_change() {
1173        let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
1174        fs::create_dir_all(&dir).unwrap();
1175        let archive = sample_zip(&dir);
1176        let before = fs::read(&archive).unwrap();
1177        let (primary, paths) = locate(&archive).unwrap();
1178        let reads = Arc::default();
1179        let State::Fresh(job, out) =
1180            open(&primary, &paths, Output::Default, None, true, None, &reads).unwrap()
1181        else {
1182            panic!("a new archive opens fresh");
1183        };
1184        let journal = begin(&job, &paths, out, true, None).unwrap();
1185        assert!(journal.keep);
1186        let len = job.storage.original_len();
1187        assert!(job.storage.set_len(len / 2).is_err());
1188        assert!(job.storage.punch(0, len / 2).is_err());
1189        assert!(job.storage.write_at(0, b"PK").is_err());
1190        assert!(job.storage.cut_to(0).is_err());
1191        drop(job);
1192        assert_eq!(fs::read(&archive).unwrap(), before);
1193
1194        // The journal says so, and a resumed job is protected as well.
1195        let (journal, tail) = Journal::load(&paths).unwrap();
1196        let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
1197        assert!(job.storage.set_len(0).is_err());
1198        assert_eq!(job.units.len(), 8, "nothing is committed yet");
1199        drop(job);
1200        assert_eq!(fs::read(&archive).unwrap(), before);
1201        assert!(keeps_archive(&journal, false).unwrap());
1202        assert!(keeps_archive(&journal, true).unwrap());
1203        fs::remove_dir_all(&dir).unwrap();
1204    }
1205}