1use 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
14pub 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 Fresh(Job, PathBuf),
27 Resume(Job, Journal),
28 Orphan(Journal),
30}
31
32pub 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 half extracted into {}; finish it there 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 finish \
58 it, or extract to continue extracting"
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
80pub 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 match ask(wrong) {
127 Some(p) => password = Some(p),
128 None => return Err(failure),
129 }
130 }
131}
132
133fn 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, and HatchZip never overwrites files. \
148 Move it, or extract somewhere else",
149 dest.display()
150 );
151 }
152 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 needs a folder there",
167 out.join(parent).display()
168 );
169 }
170 }
171 }
172 Ok(())
173}
174
175pub 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
202pub 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
217pub struct SpacePlan {
219 pub free: u64,
222 pub needed: u64,
224 pub keep_free: u64,
225 pub fits: bool,
226 pub free_after: u64,
228 pub normal_needs: u64,
230 pub reclaims: bool,
233 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
261pub 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
273pub 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}