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