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