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};
6
7use anyhow::{Context, Result, bail};
8
9use crate::archive::storage;
10use crate::engine::Job;
11use crate::fsutil;
12use crate::journal::{Journal, Paths, Plan};
13
14/// The first volume of the archive and where its journal lives. Paths are
15/// made absolute so a resume works from any directory.
16pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
17    let primary = std::path::absolute(storage::first_volume(archive))
18        .with_context(|| format!("resolving {}", archive.display()))?;
19    let paths = Paths::for_archive(&primary);
20    Ok((primary, paths))
21}
22
23pub enum State {
24    /// Nothing touched yet. Nothing changes on disk until [`begin`] writes
25    /// the journal.
26    Fresh(Job, PathBuf),
27    Resume(Job, Journal),
28    /// The archive is gone but the run died before cleaning up.
29    Orphan(Journal),
30}
31
32/// `writable` is false for anything that only looks, so it works on
33/// read-only media and never takes the lock. For a fresh extraction the
34/// output folder may already hold other files, but nothing in the archive may
35/// land on top of one. `password` only matters for encrypted archives; see
36/// [`open_encrypted`] for the ask-and-retry loop front ends want.
37pub fn open(
38    primary: &Path,
39    paths: &Paths,
40    output: Option<PathBuf>,
41    writable: bool,
42    password: Option<&str>,
43) -> Result<State> {
44    if paths.exists() {
45        let (mut journal, tail) = Journal::load(paths)?;
46        if let Some(o) = &output
47            && std::path::absolute(o)? != journal.output
48        {
49            bail!(
50                "this archive is already partially extracted to {}. Complete or restore that extraction first",
51                journal.output.display()
52            );
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            return Ok(State::Orphan(journal));
65        }
66        let job = Job::resume(&journal, tail, writable, password)?;
67        return Ok(State::Resume(job, journal));
68    }
69    let job = Job::open(primary, writable, password)?;
70    let output = match output {
71        Some(o) => std::path::absolute(o)?,
72        None => default_output(primary),
73    };
74    if writable {
75        check_collisions(&job, &output)?;
76    }
77    Ok(State::Fresh(job, output))
78}
79
80/// Opens an archive that may be encrypted. `ask` is called whenever a
81/// password is needed or the last one was wrong, and returns `None` to give
82/// up. Archives with a password are proven with [`Job::check_password`]
83/// before this returns, so nothing is deleted on a wrong guess. Returns the
84/// state and the password that worked.
85pub fn open_encrypted(
86    primary: &Path,
87    paths: &Paths,
88    output: Option<PathBuf>,
89    writable: bool,
90    mut password: Option<String>,
91    mut ask: impl FnMut(bool) -> Option<String>,
92) -> Result<(State, Option<String>)> {
93    let mut wrong = false;
94    loop {
95        let attempt = open(
96            primary,
97            paths,
98            output.clone(),
99            writable,
100            password.as_deref(),
101        );
102        let failure = match attempt {
103            Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
104            Ok(state) => {
105                let job = match &state {
106                    State::Fresh(job, _) | State::Resume(job, _) => job,
107                    State::Orphan(_) => unreachable!(),
108                };
109                if !job.encrypted() {
110                    return Ok((state, password));
111                }
112                match job.check_password() {
113                    Ok(()) => return Ok((state, password)),
114                    Err(e) => e,
115                }
116            }
117            Err(e) => e,
118        };
119        if failure.is::<crate::archive::WrongPassword>() {
120            wrong = true;
121        } else if !failure.is::<crate::archive::PasswordNeeded>() {
122            return Err(failure);
123        }
124        // Drop the open archive before asking, so nothing stays locked while
125        // a person types.
126        match ask(wrong) {
127            Some(p) => password = Some(p),
128            None => return Err(failure),
129        }
130    }
131}
132
133/// HatchZip never overwrites a file. That is also what lets a crashed run
134/// delete whatever sits at the paths of its uncommitted entries: before the
135/// run started, nothing did.
136fn check_collisions(job: &Job, out: &Path) -> Result<()> {
137    if !out.exists() {
138        return Ok(());
139    }
140    let mut checked = std::collections::HashSet::new();
141    for item in job.units.iter().flat_map(|u| &u.items) {
142        let dest = out.join(&item.path);
143        if let Ok(meta) = fs::symlink_metadata(&dest)
144            && !(meta.is_dir() && item.kind == crate::archive::Kind::Dir)
145        {
146            bail!(
147                "{} already exists. HatchZip does not overwrite existing files. \
148                 Move the file or choose another destination",
149                dest.display()
150            );
151        }
152        // A file where the archive needs a folder would only fail halfway.
153        for parent in item
154            .path
155            .ancestors()
156            .skip(1)
157            .filter(|p| !p.as_os_str().is_empty())
158        {
159            if !checked.insert(parent.to_path_buf()) {
160                break;
161            }
162            if let Ok(meta) = fs::symlink_metadata(out.join(parent))
163                && !meta.is_dir()
164            {
165                bail!(
166                    "{} is a file, but the archive requires a folder at that location",
167                    out.join(parent).display()
168                );
169            }
170        }
171    }
172    Ok(())
173}
174
175/// `game.zip`, `game.7z.001` and `game.tar.gz` all extract into `game`, next
176/// to them.
177pub fn default_output(primary: &Path) -> PathBuf {
178    let file_name = primary
179        .file_name()
180        .unwrap_or_default()
181        .to_string_lossy()
182        .into_owned();
183    let mut name = file_name.clone();
184    if let Some((stem, digits)) = name.rsplit_once('.')
185        && digits.len() >= 3
186        && digits.bytes().all(|b| b.is_ascii_digit())
187    {
188        name = stem.to_string();
189    }
190    let lower = name.to_ascii_lowercase();
191    for ext in [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".exe"] {
192        if lower.ends_with(ext) && name.len() > ext.len() {
193            name.truncate(name.len() - ext.len());
194            break;
195        }
196    }
197    if name == file_name {
198        name.push_str("-extracted");
199    }
200    primary.with_file_name(name)
201}
202
203/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
204pub fn display_name(job: &Job) -> String {
205    let parts = job.storage.parts();
206    let first = parts[0]
207        .path
208        .file_name()
209        .unwrap_or_default()
210        .to_string_lossy()
211        .into_owned();
212    match parts.len() {
213        1 => first,
214        n => format!("{first} (+{} more parts)", n - 1),
215    }
216}
217
218/// Whether an extraction fits, in the numbers a person needs to decide.
219pub struct SpacePlan {
220    /// Usable free space, counting files a crashed run left that will be
221    /// deleted before continuing.
222    pub free: u64,
223    /// Free space HatchZip needs at its busiest moment.
224    pub needed: u64,
225    pub keep_free: u64,
226    pub fits: bool,
227    /// Free space once finished, if it fits.
228    pub free_after: u64,
229    /// What a normal extractor would need free.
230    pub normal_needs: u64,
231    /// False when the output is on another disk, so freeing the archive
232    /// doesn't help it.
233    pub reclaims: bool,
234    /// The shortfall comes from one solid block that can only be freed once
235    /// all of it is out.
236    pub solid_block_bound: bool,
237    /// The archive is one compressed stream (a `.tar.gz`) on a filesystem
238    /// that can't free space inside a file, such as FAT32 or exFAT, so it
239    /// stays whole until the extraction completes: `needed` is room for
240    /// every extracted file next to it.
241    pub archive_kept_whole: bool,
242}
243
244pub fn plan(job: &Job, out: &Path, resuming: bool, keep_free: u64) -> Result<SpacePlan> {
245    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
246    let stale: u64 =
247        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
248    let free = fsutil::available_space(out)? + stale;
249    let (needed, end) = job.space_needed(!resuming, reclaims);
250    let fits = free >= needed + keep_free;
251    Ok(SpacePlan {
252        free,
253        needed,
254        keep_free,
255        fits,
256        free_after: (free as i128 - end).max(0) as u64,
257        normal_needs: job.remaining_size(),
258        reclaims,
259        solid_block_bound: !fits
260            && !job.is_stream()
261            && job
262                .units
263                .iter()
264                .any(|u| u.items.len() > 1 && u.size() > free),
265        archive_kept_whole: job.kept_whole(reclaims),
266    })
267}
268
269/// Commits to a fresh extraction: saves the archive's tail and writes the
270/// journal. From here on the archive may be truncated.
271pub fn begin(job: &Job, paths: &Paths, output: PathBuf) -> Result<Journal> {
272    let plan = Plan {
273        format: job.format_name,
274        tail_start: job.tail_start,
275        output,
276        total_size: job.remaining_size(),
277    };
278    Journal::create(paths, &job.storage, plan)
279}
280
281/// Before continuing a crashed run, deletes what it wrote for batches it
282/// never committed.
283pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
284    for (p, _) in job.uncommitted(out) {
285        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
286    }
287    Ok(())
288}