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};
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/// `writable` is false for anything that only looks, so it works on
34/// read-only media and never takes the lock. For a fresh extraction the
35/// output folder may already hold other files, but nothing in the archive may
36/// land on top of one. `password` only matters for encrypted archives; see
37/// [`open_encrypted`] for the ask-and-retry loop front ends want. What
38/// opening reads is counted in `reads`, which a front end can show from
39/// another thread: a compressed tar is read in full here.
40pub fn open(
41    primary: &Path,
42    paths: &Paths,
43    output: Option<PathBuf>,
44    writable: bool,
45    password: Option<&str>,
46    reads: &Arc<Reads>,
47) -> Result<State> {
48    if paths.exists() {
49        let (mut journal, tail) = Journal::load(paths)?;
50        // Only a writable open deletes or writes anything in the folder.
51        if writable || output.is_some() {
52            check_output(&journal, primary, output.as_deref(), "extract")?;
53        }
54        if journal.restoring.is_some() {
55            if !writable {
56                bail!(
57                    "a restore of this archive was interrupted. Run restore again to complete \
58                     it, or run extract to resume the extraction"
59                );
60            }
61            crate::restore::recover(&mut journal, paths)?;
62        }
63        if !journal.parts[0].0.exists() {
64            if journal.keep {
65                // Only the person could have removed an archive this run
66                // promised to keep, and the rest of it is still to extract.
67                bail!(
68                    "{} was moved or deleted during an extraction that keeps it. Put it back \
69                     to resume, or delete {} to discard the progress",
70                    journal.parts[0].0.display(),
71                    paths.journal.display()
72                );
73            }
74            return Ok(State::Orphan(journal));
75        }
76        let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
77        check_no_links_on_the_way(&job, &journal.output)?;
78        return Ok(State::Resume(job, journal));
79    }
80    let job = Job::open(primary, writable, password, reads.clone())?;
81    let output = match output {
82        Some(o) => std::path::absolute(o)?,
83        None => {
84            let output = default_output(primary);
85            refuse_linked_default(&output)?;
86            output
87        }
88    };
89    check_path_lengths(&job, &output)?;
90    if writable {
91        check_collisions(&job, &output)?;
92    }
93    Ok(State::Fresh(job, output))
94}
95
96/// The journal lies next to the archive, where anyone who supplied the
97/// archive could have put one, so the folder it names is used only if it is
98/// the archive's default folder, one this person chose for it (see
99/// [`crate::chosen`]), or the one they give again (`given`). Otherwise a
100/// planted journal could have a resume delete and write files anywhere.
101/// `command` is the one to run again, with `-o`.
102pub fn check_output(
103    journal: &Journal,
104    primary: &Path,
105    given: Option<&Path>,
106    command: &str,
107) -> Result<()> {
108    match given {
109        Some(o) => {
110            if !fsutil::same_path(&std::path::absolute(o)?, &journal.output) {
111                bail!(
112                    "this archive is already partially extracted to {}. Complete or restore that \
113                     extraction first",
114                    journal.output.display()
115                );
116            }
117        }
118        None => {
119            let default = default_output(primary);
120            if fsutil::same_path(&default, &journal.output) {
121                refuse_linked_default(&default)?;
122            } else if !crate::chosen::chose(primary, &journal.output) {
123                bail!(
124                    "{} was partially extracted to {}, a folder not chosen on this computer. If \
125                     you started that extraction, continue it by naming the folder again: \
126                     hatchzip {command} \"{}\" -o \"{}\". Nothing was modified",
127                    primary.display(),
128                    journal.output.display(),
129                    primary.display(),
130                    journal.output.display()
131                );
132            }
133        }
134    }
135    Ok(())
136}
137
138/// A link at the default output folder, next to the archive, would send the
139/// extraction wherever it points. A folder the person names is theirs to
140/// choose.
141fn refuse_linked_default(output: &Path) -> Result<()> {
142    if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
143        bail!(
144            "{} is a link, so files extracted there would land somewhere else. Remove the link, \
145             or choose the destination folder. Nothing was modified",
146            output.display()
147        );
148    }
149    Ok(())
150}
151
152/// A resume deletes and writes the files of the entries left, and its own
153/// links are only made once every entry is done. A link on the way to one of
154/// those files was put there by someone else, and following it would leave
155/// the output folder.
156pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
157    let mut checked = std::collections::HashSet::new();
158    for item in job.units.iter().flat_map(|u| &u.items) {
159        for parent in item
160            .path
161            .ancestors()
162            .skip(1)
163            .filter(|p| !p.as_os_str().is_empty())
164        {
165            if !checked.insert(parent.to_path_buf()) {
166                break;
167            }
168            if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
169                bail!(
170                    "{} is a link, and '{}' would be extracted through it. Nothing was modified",
171                    out.join(parent).display(),
172                    item.path.display()
173                );
174            }
175        }
176    }
177    Ok(())
178}
179
180/// A path the system can't create would only fail halfway through a run,
181/// after part of the archive is gone; macOS stops at 1024 bytes.
182fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
183    for item in job.units.iter().flat_map(|u| &u.items) {
184        if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
185            bail!(
186                "'{}' cannot be created in {}: the full path would be longer than this system \
187                 allows. The archive was not modified. Extract to a folder with a shorter path",
188                item.path.display(),
189                out.display()
190            );
191        }
192    }
193    Ok(())
194}
195
196/// Opens an archive that may be encrypted. `ask` is called whenever a
197/// password is needed or the last one was wrong, and returns `None` to give
198/// up. Archives with a password are proven with [`Job::check_password`]
199/// before this returns, so nothing is deleted on a wrong guess. Returns the
200/// state and the password that worked.
201pub fn open_encrypted(
202    primary: &Path,
203    paths: &Paths,
204    output: Option<PathBuf>,
205    writable: bool,
206    password: Option<String>,
207    reads: &Arc<Reads>,
208    ask: impl FnMut(bool) -> Option<String>,
209) -> Result<(State, Option<String>)> {
210    open_encrypted_noting(
211        primary,
212        paths,
213        output,
214        writable,
215        password,
216        reads,
217        ask,
218        |_, _| {},
219    )
220}
221
222/// [`open_encrypted`], calling `slow` with a file and its size before a
223/// password check that decodes all of it (see [`Job::slow_password_check`]),
224/// so a front end can say it may take a while.
225#[allow(clippy::too_many_arguments)]
226pub fn open_encrypted_noting(
227    primary: &Path,
228    paths: &Paths,
229    output: Option<PathBuf>,
230    writable: bool,
231    mut password: Option<String>,
232    reads: &Arc<Reads>,
233    mut ask: impl FnMut(bool) -> Option<String>,
234    mut slow: impl FnMut(&Path, u64),
235) -> Result<(State, Option<String>)> {
236    let mut wrong = false;
237    loop {
238        let attempt = open(
239            primary,
240            paths,
241            output.clone(),
242            writable,
243            password.as_deref(),
244            reads,
245        );
246        let failure = match attempt {
247            Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
248            Ok(state) => {
249                let job = match &state {
250                    State::Fresh(job, _) | State::Resume(job, _) => job,
251                    State::Orphan(_) => unreachable!(),
252                };
253                if !job.encrypted() {
254                    return Ok((state, password));
255                }
256                if password.is_some()
257                    && let Some((file, size)) = job.slow_password_check()
258                {
259                    slow(file, size);
260                }
261                match job.check_password() {
262                    Ok(()) => return Ok((state, password)),
263                    Err(e) => e,
264                }
265            }
266            Err(e) => e,
267        };
268        if failure.is::<crate::archive::WrongPassword>() {
269            wrong = true;
270        } else if !failure.is::<crate::archive::PasswordNeeded>() {
271            return Err(failure);
272        }
273        // Drop the open archive before asking, so nothing stays locked while
274        // a person types.
275        match ask(wrong) {
276            Some(p) => password = Some(p),
277            None => return Err(failure),
278        }
279    }
280}
281
282/// HatchZip never overwrites a file. That is also what lets a crashed run
283/// delete whatever sits at the paths of its uncommitted entries: before the
284/// run started, nothing did.
285fn check_collisions(job: &Job, out: &Path) -> Result<()> {
286    if !out.exists() {
287        return Ok(());
288    }
289    let mut checked = std::collections::HashSet::new();
290    for item in job.units.iter().flat_map(|u| &u.items) {
291        let dest = out.join(&item.path);
292        if let Ok(meta) = fs::symlink_metadata(&dest)
293            && !(meta.is_dir() && item.kind == crate::archive::Kind::Dir)
294        {
295            bail!(
296                "{} already exists. HatchZip does not overwrite existing files. \
297                 Move the file or choose another destination",
298                dest.display()
299            );
300        }
301        // A file where the archive needs a folder would only fail halfway.
302        for parent in item
303            .path
304            .ancestors()
305            .skip(1)
306            .filter(|p| !p.as_os_str().is_empty())
307        {
308            if !checked.insert(parent.to_path_buf()) {
309                break;
310            }
311            if let Ok(meta) = fs::symlink_metadata(out.join(parent))
312                && !meta.is_dir()
313            {
314                bail!(
315                    "{} is a file, but the archive requires a folder at that location",
316                    out.join(parent).display()
317                );
318            }
319        }
320    }
321    Ok(())
322}
323
324/// `game.zip`, `game.7z.001`, `game.tar.gz` and `game.part1.rar` all extract
325/// into `game`, next
326/// to them.
327pub fn default_output(primary: &Path) -> PathBuf {
328    let file_name = primary
329        .file_name()
330        .unwrap_or_default()
331        .to_string_lossy()
332        .into_owned();
333    let mut name = file_name.clone();
334    if let Some((stem, digits)) = name.rsplit_once('.')
335        && digits.len() >= 3
336        && digits.bytes().all(|b| b.is_ascii_digit())
337    {
338        name = stem.to_string();
339    }
340    let lower = name.to_ascii_lowercase();
341    // `game.part2.rar` and `game.part02.rar` are volumes of `game`.
342    if let Some(stem) = lower.strip_suffix(".rar")
343        && let Some((_, digits)) = stem.rsplit_once(".part")
344        && !digits.is_empty()
345        && digits.bytes().all(|b| b.is_ascii_digit())
346    {
347        name.truncate(stem.len() - digits.len() - ".part".len());
348        return primary.with_file_name(name);
349    }
350    for ext in [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".rar", ".exe"] {
351        if lower.ends_with(ext) && name.len() > ext.len() {
352            name.truncate(name.len() - ext.len());
353            break;
354        }
355    }
356    if name == file_name {
357        name.push_str("-extracted");
358    }
359    primary.with_file_name(name)
360}
361
362/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
363pub fn display_name(job: &Job) -> String {
364    let parts = job.storage.parts();
365    let first = parts[0]
366        .path
367        .file_name()
368        .unwrap_or_default()
369        .to_string_lossy()
370        .into_owned();
371    match parts.len() {
372        1 => first,
373        n => format!("{first} (+{} more parts)", n - 1),
374    }
375}
376
377/// Whether the extraction of a half-extracted archive keeps it, given what
378/// the person asked for now. The journal decides: an extraction that keeps
379/// the archive goes on keeping it, and one that has already removed part of
380/// it can't start keeping it.
381pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
382    if asked && !journal.keep {
383        bail!(
384            "this archive is partially extracted in place, so part of it is already removed and \
385             it cannot be kept. Resume without --keep-archive, or run restore first"
386        );
387    }
388    Ok(journal.keep)
389}
390
391/// Whether an extraction fits, in the numbers a person needs to decide.
392pub struct SpacePlan {
393    /// Usable free space, counting files a crashed run left that will be
394    /// deleted before continuing.
395    pub free: u64,
396    /// Free space the extraction needs at its busiest moment, in the mode
397    /// asked for.
398    pub needed: u64,
399    pub keep_free: u64,
400    pub fits: bool,
401    /// Free space once finished, if it fits.
402    pub free_after: u64,
403    /// The plan is for an extraction that keeps the archive.
404    pub keep_archive: bool,
405    /// What an extraction that keeps the archive needs free: every
406    /// extracted file, as for any other extractor, plus the saved index.
407    pub normal_needs: u64,
408    /// What extracting in place needs free. Equal to `needed` unless the
409    /// archive is kept.
410    pub in_place_needs: u64,
411    /// Nothing is extracted yet, so either mode can still be chosen. A
412    /// half-extracted archive continues in the mode it started in.
413    pub either: bool,
414    /// False when the output is on another disk, so freeing the archive
415    /// doesn't help it.
416    pub reclaims: bool,
417    /// The shortfall comes from one solid block that can only be freed once
418    /// all of it is out.
419    pub solid_block_bound: bool,
420    /// The archive is one compressed stream (a `.tar.gz`) on a filesystem
421    /// that can't free space inside a file, such as FAT32 or exFAT, so it
422    /// stays whole until the extraction completes: `needed` is room for
423    /// every extracted file next to it.
424    pub archive_kept_whole: bool,
425}
426
427impl SpacePlan {
428    /// Whether an extraction that keeps the archive would fit too.
429    pub fn normal_fits(&self) -> bool {
430        self.free >= self.normal_needs + self.keep_free
431    }
432
433    pub fn in_place_fits(&self) -> bool {
434        self.free >= self.in_place_needs + self.keep_free
435    }
436}
437
438/// The space plan for extracting `job` into `out`, keeping the archive or
439/// not. For a half-extracted archive, `keep_archive` must be what its
440/// journal says; see [`keeps_archive`].
441pub fn plan(
442    job: &Job,
443    out: &Path,
444    resuming: bool,
445    keep_free: u64,
446    keep_archive: bool,
447) -> Result<SpacePlan> {
448    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
449    let stale: u64 =
450        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
451    let free = fsutil::available_space(out)? + stale;
452    // Keeping the archive frees nothing, as if the output were on another
453    // disk: the replay counts every file and gives nothing back.
454    let (normal_needs, normal_end) = job.space_needed(!resuming, false);
455    let (in_place_needs, in_place_end) = if keep_archive && resuming {
456        (normal_needs, normal_end)
457    } else {
458        job.space_needed(!resuming, reclaims)
459    };
460    // The saved index is deleted at the end, when the archive is kept too.
461    let tail = (job.storage.original_len() - job.tail_start) as i128;
462    let normal_end = normal_end - if reclaims { tail } else { 0 };
463    let (needed, end) = if keep_archive {
464        (normal_needs, normal_end)
465    } else {
466        (in_place_needs, in_place_end)
467    };
468    let fits = free >= needed + keep_free;
469    Ok(SpacePlan {
470        free,
471        needed,
472        keep_free,
473        fits,
474        free_after: (free as i128 - end).max(0) as u64,
475        keep_archive,
476        normal_needs,
477        in_place_needs,
478        either: !resuming,
479        reclaims,
480        solid_block_bound: !fits
481            && !keep_archive
482            && !job.is_stream()
483            && job
484                .units
485                .iter()
486                .any(|u| u.items.len() > 1 && u.size() > free),
487        archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
488    })
489}
490
491/// Commits to a fresh extraction: saves the archive's tail and writes the
492/// journal. From here on the archive may be truncated, unless `keep_archive`
493/// is set, in which case nothing ever changes it.
494pub fn begin(job: &Job, paths: &Paths, output: PathBuf, keep_archive: bool) -> Result<Journal> {
495    if keep_archive {
496        job.storage.protect();
497    } else if let Some(why) = job.in_place_refusal() {
498        // Front ends say this earlier; this is the last line.
499        bail!("{why}. It can be extracted while keeping the archive");
500    }
501    if !fsutil::same_path(&output, &default_output(&paths.archive)) {
502        crate::chosen::remember(&paths.archive, &output);
503    }
504    let plan = Plan {
505        format: job.format_name,
506        tail_start: job.tail_start,
507        output,
508        total_size: job.remaining_size(),
509        keep: keep_archive,
510    };
511    Journal::create(paths, &job.storage, plan)
512}
513
514/// Before continuing a crashed run, deletes what it wrote for batches it
515/// never committed.
516pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
517    check_no_links_on_the_way(job, out)?;
518    for (p, _) in job.uncommitted(out) {
519        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
520    }
521    Ok(())
522}
523
524#[cfg(test)]
525mod tests {
526    use std::io::Write;
527
528    use ::zip::write::{SimpleFileOptions, ZipWriter};
529
530    use super::*;
531
532    #[test]
533    fn output_folder_drops_the_volume_and_format_suffixes() {
534        let name = |n: &str| default_output(Path::new(n));
535        assert_eq!(name("game.zip"), Path::new("game"));
536        assert_eq!(name("game.7z.001"), Path::new("game"));
537        assert_eq!(name("game.part1.rar"), Path::new("game"));
538        assert_eq!(name("game.PART02.RAR"), Path::new("game"));
539        assert_eq!(name("game.rar"), Path::new("game"));
540        assert_eq!(name("game.part.rar"), Path::new("game.part"));
541        assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
542    }
543
544    /// Eight stored entries, so extracting in place frees the archive entry
545    /// by entry and needs far less than keeping it.
546    fn sample_zip(dir: &Path) -> PathBuf {
547        let path = dir.join("plan.zip");
548        let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
549        let opts =
550            SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
551        for i in 0..8u8 {
552            w.start_file(format!("data/{i}.bin"), opts).unwrap();
553            w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
554        }
555        w.finish().unwrap();
556        path
557    }
558
559    #[test]
560    fn keeping_the_archive_plans_for_every_file() {
561        let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
562        fs::create_dir_all(&dir).unwrap();
563        let archive = sample_zip(&dir);
564        let out = dir.join("out");
565        let job = Job::open(&archive, false, None, Default::default()).unwrap();
566        let files: u64 = job
567            .units
568            .iter()
569            .flat_map(|u| &u.items)
570            .map(|i| i.size.next_multiple_of(4096))
571            .sum();
572        let tail = job.storage.original_len() - job.tail_start;
573
574        let keep = plan(&job, &out, false, 0, true).unwrap();
575        assert!(keep.keep_archive && keep.either);
576        // Every file, plus the copy of the index a resume would need.
577        assert_eq!(keep.needed, files + tail);
578        assert_eq!(keep.normal_needs, keep.needed);
579        assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
580        // Nothing of the archive comes back; the saved index does.
581        assert_eq!(keep.free.saturating_sub(keep.free_after), files);
582
583        let in_place = plan(&job, &out, false, 0, false).unwrap();
584        assert!(!in_place.keep_archive);
585        assert_eq!(in_place.normal_needs, keep.needed);
586        assert_eq!(in_place.in_place_needs, in_place.needed);
587        assert_eq!(keep.in_place_needs, in_place.needed);
588        assert!(
589            in_place.needed < keep.needed / 2,
590            "in place {} vs kept {}",
591            in_place.needed,
592            keep.needed
593        );
594        drop(job);
595        fs::remove_dir_all(&dir).unwrap();
596    }
597
598    /// Once an extraction that keeps the archive has begun, nothing can
599    /// change it, whatever the caller does.
600    #[test]
601    fn a_kept_archive_refuses_every_change() {
602        let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
603        fs::create_dir_all(&dir).unwrap();
604        let archive = sample_zip(&dir);
605        let before = fs::read(&archive).unwrap();
606        let (primary, paths) = locate(&archive).unwrap();
607        let reads = Arc::default();
608        let State::Fresh(job, out) = open(&primary, &paths, None, true, None, &reads).unwrap()
609        else {
610            panic!("a new archive opens fresh");
611        };
612        let journal = begin(&job, &paths, out, true).unwrap();
613        assert!(journal.keep);
614        let len = job.storage.original_len();
615        assert!(job.storage.set_len(len / 2).is_err());
616        assert!(job.storage.punch(0, len / 2).is_err());
617        assert!(job.storage.write_at(0, b"PK").is_err());
618        assert!(job.storage.cut_to(0).is_err());
619        drop(job);
620        assert_eq!(fs::read(&archive).unwrap(), before);
621
622        // The journal says so, and a resumed job is protected as well.
623        let (journal, tail) = Journal::load(&paths).unwrap();
624        let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
625        assert!(job.storage.set_len(0).is_err());
626        assert_eq!(job.units.len(), 8, "nothing is committed yet");
627        drop(job);
628        assert_eq!(fs::read(&archive).unwrap(), before);
629        assert!(keeps_archive(&journal, false).unwrap());
630        assert!(keeps_archive(&journal, true).unwrap());
631        fs::remove_dir_all(&dir).unwrap();
632    }
633}