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