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` and `game.7z.001` both extract into `game`, next to them.
176pub fn default_output(primary: &Path) -> PathBuf {
177    let file_name = primary
178        .file_name()
179        .unwrap_or_default()
180        .to_string_lossy()
181        .into_owned();
182    let mut name = file_name.clone();
183    if let Some((stem, digits)) = name.rsplit_once('.')
184        && digits.len() >= 3
185        && digits.bytes().all(|b| b.is_ascii_digit())
186    {
187        name = stem.to_string();
188    }
189    let lower = name.to_ascii_lowercase();
190    for ext in [".zip", ".7z", ".tar", ".exe"] {
191        if lower.ends_with(ext) && name.len() > ext.len() {
192            name.truncate(name.len() - ext.len());
193            break;
194        }
195    }
196    if name == file_name {
197        name.push_str("-extracted");
198    }
199    primary.with_file_name(name)
200}
201
202/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
203pub fn display_name(job: &Job) -> String {
204    let parts = job.storage.parts();
205    let first = parts[0]
206        .path
207        .file_name()
208        .unwrap_or_default()
209        .to_string_lossy()
210        .into_owned();
211    match parts.len() {
212        1 => first,
213        n => format!("{first} (+{} more parts)", n - 1),
214    }
215}
216
217/// Whether an extraction fits, in the numbers a person needs to decide.
218pub struct SpacePlan {
219    /// Usable free space, counting files a crashed run left that will be
220    /// deleted before continuing.
221    pub free: u64,
222    /// Free space HatchZip needs at its busiest moment.
223    pub needed: u64,
224    pub keep_free: u64,
225    pub fits: bool,
226    /// Free space once finished, if it fits.
227    pub free_after: u64,
228    /// What a normal extractor would need free.
229    pub normal_needs: u64,
230    /// False when the output is on another disk, so freeing the archive
231    /// doesn't help it.
232    pub reclaims: bool,
233    /// The shortfall comes from one solid block that can only be freed once
234    /// all of it is out.
235    pub solid_block_bound: bool,
236}
237
238pub fn plan(job: &Job, out: &Path, resuming: bool, keep_free: u64) -> Result<SpacePlan> {
239    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
240    let stale: u64 =
241        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
242    let free = fsutil::available_space(out)? + stale;
243    let (needed, end) = job.space_needed(!resuming, reclaims);
244    let fits = free >= needed + keep_free;
245    Ok(SpacePlan {
246        free,
247        needed,
248        keep_free,
249        fits,
250        free_after: (free as i128 - end).max(0) as u64,
251        normal_needs: job.remaining_size(),
252        reclaims,
253        solid_block_bound: !fits
254            && job
255                .units
256                .iter()
257                .any(|u| u.items.len() > 1 && u.size() > free),
258    })
259}
260
261/// Commits to a fresh extraction: saves the archive's tail and writes the
262/// journal. From here on the archive may be truncated.
263pub fn begin(job: &Job, paths: &Paths, output: PathBuf) -> Result<Journal> {
264    let plan = Plan {
265        format: job.format_name,
266        tail_start: job.tail_start,
267        output,
268        total_size: job.remaining_size(),
269    };
270    Journal::create(paths, &job.storage, plan)
271}
272
273/// Before continuing a crashed run, deletes what it wrote for batches it
274/// never committed.
275pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
276    for (p, _) in job.uncommitted(out) {
277        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
278    }
279    Ok(())
280}