1use 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
15pub 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 Fresh(Job, PathBuf),
28 Resume(Job, Journal),
29 Orphan(Journal),
31}
32
33pub fn open(
42 primary: &Path,
43 paths: &Paths,
44 output: Option<PathBuf>,
45 writable: bool,
46 password: Option<&str>,
47 reads: &Arc<Reads>,
48) -> Result<State> {
49 if paths.exists() {
50 let (mut journal, tail) = Journal::load(paths)?;
51 if writable || output.is_some() {
53 check_output(&journal, primary, output.as_deref(), "extract")?;
54 }
55 if journal.restoring.is_some() {
56 if !writable {
57 bail!(
58 "a restore of this archive was interrupted. Run restore again to complete \
59 it, or run extract to resume the extraction"
60 );
61 }
62 crate::restore::recover(&mut journal, paths)?;
63 }
64 if !journal.parts[0].0.exists() {
65 if journal.keep {
66 bail!(
69 "{} was moved or deleted during an extraction that keeps it. Put it back \
70 to resume, or delete {} to discard the progress",
71 journal.parts[0].0.display(),
72 paths.journal.display()
73 );
74 }
75 return Ok(State::Orphan(journal));
76 }
77 let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
78 check_no_links_on_the_way(&job, &journal.output)?;
79 return Ok(State::Resume(job, journal));
80 }
81 let job = Job::open(primary, writable, password, reads.clone())?;
82 let output = match output {
83 Some(o) => std::path::absolute(o)?,
84 None => {
85 let output = default_output(primary);
86 refuse_linked_default(&output)?;
87 output
88 }
89 };
90 check_path_lengths(&job, &output)?;
91 if writable {
92 check_no_links_on_the_way(&job, &output)?;
93 check_collisions(&job, &output)?;
94 }
95 Ok(State::Fresh(job, output))
96}
97
98pub fn check_output(
107 journal: &Journal,
108 primary: &Path,
109 given: Option<&Path>,
110 command: &str,
111) -> Result<()> {
112 let default = default_output(primary);
113 let in_default = fsutil::same_path(&default, &journal.output);
114 match given {
115 Some(o) => {
116 if !fsutil::same_path(&std::path::absolute(o)?, &journal.output) {
117 bail!(
118 "this archive is already partially extracted to {}. Complete or restore that \
119 extraction first",
120 journal.output.display()
121 );
122 }
123 }
124 None if crate::chosen::chose(primary, &journal.output) => {
125 if in_default {
126 refuse_linked_default(&default)?;
127 }
128 }
129 None if in_default => bail!(
131 "{} was partially extracted to {}, but this computer has no record of starting that \
132 extraction. If you started it, continue it by naming the folder again: hatchzip \
133 {command} \"{}\" -o \"{}\". Nothing was modified",
134 primary.display(),
135 journal.output.display(),
136 primary.display(),
137 journal.output.display()
138 ),
139 None => bail!(
140 "{} was partially extracted to {}, a folder not chosen on this computer. If you \
141 started that extraction, continue it by naming the folder again: hatchzip {command} \
142 \"{}\" -o \"{}\". Nothing was modified",
143 primary.display(),
144 journal.output.display(),
145 primary.display(),
146 journal.output.display()
147 ),
148 }
149 Ok(())
150}
151
152fn refuse_linked_default(output: &Path) -> Result<()> {
156 if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
157 bail!(
158 "{} is a link, so files extracted there would land somewhere else. Remove the link, \
159 or choose the destination folder. Nothing was modified",
160 output.display()
161 );
162 }
163 Ok(())
164}
165
166pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
171 let mut checked = std::collections::HashSet::new();
172 for item in job.units.iter().flat_map(|u| &u.items) {
173 for parent in item
174 .path
175 .ancestors()
176 .skip(1)
177 .filter(|p| !p.as_os_str().is_empty())
178 {
179 if !checked.insert(parent.to_path_buf()) {
180 break;
181 }
182 if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
183 bail!(
184 "{} is a link, and '{}' would be extracted through it. Nothing was modified",
185 out.join(parent).display(),
186 item.path.display()
187 );
188 }
189 }
190 }
191 Ok(())
192}
193
194fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
197 for item in job.units.iter().flat_map(|u| &u.items) {
198 if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
199 bail!(
200 "'{}' cannot be created in {}: the full path would be longer than this system \
201 allows. The archive was not modified. Extract to a folder with a shorter path",
202 item.path.display(),
203 out.display()
204 );
205 }
206 }
207 Ok(())
208}
209
210pub fn open_encrypted(
216 primary: &Path,
217 paths: &Paths,
218 output: Option<PathBuf>,
219 writable: bool,
220 password: Option<String>,
221 reads: &Arc<Reads>,
222 ask: impl FnMut(bool) -> Option<String>,
223) -> Result<(State, Option<String>)> {
224 open_encrypted_noting(
225 primary,
226 paths,
227 output,
228 writable,
229 password,
230 reads,
231 ask,
232 |_, _| {},
233 )
234}
235
236#[allow(clippy::too_many_arguments)]
240pub fn open_encrypted_noting(
241 primary: &Path,
242 paths: &Paths,
243 output: Option<PathBuf>,
244 writable: bool,
245 mut password: Option<String>,
246 reads: &Arc<Reads>,
247 mut ask: impl FnMut(bool) -> Option<String>,
248 mut slow: impl FnMut(&Path, u64),
249) -> Result<(State, Option<String>)> {
250 let mut wrong = false;
251 loop {
252 let attempt = open(
253 primary,
254 paths,
255 output.clone(),
256 writable,
257 password.as_deref(),
258 reads,
259 );
260 let failure = match attempt {
261 Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
262 Ok(state) => {
263 let job = match &state {
264 State::Fresh(job, _) | State::Resume(job, _) => job,
265 State::Orphan(_) => unreachable!(),
266 };
267 if !job.encrypted() {
268 return Ok((state, password));
269 }
270 if password.is_some()
271 && let Some((file, size)) = job.slow_password_check()
272 {
273 slow(file, size);
274 }
275 match job.check_password() {
276 Ok(()) => return Ok((state, password)),
277 Err(e) => e,
278 }
279 }
280 Err(e) => e,
281 };
282 if failure.is::<crate::archive::WrongPassword>() {
283 wrong = true;
284 } else if !failure.is::<crate::archive::PasswordNeeded>() {
285 return Err(failure);
286 }
287 match ask(wrong) {
290 Some(p) => password = Some(p),
291 None => return Err(failure),
292 }
293 }
294}
295
296fn check_collisions(job: &Job, out: &Path) -> Result<()> {
302 if !out.exists() {
303 return Ok(());
304 }
305 let mut checked = std::collections::HashSet::new();
306 for item in job.units.iter().flat_map(|u| &u.items) {
307 let dest = out.join(&item.path);
308 let part = crate::engine::part_path(&dest);
309 if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
310 bail!(
311 "{} already exists. HatchZip first writes '{}' under that name and does not \
312 replace a file it did not create. Move it or choose another destination. Nothing \
313 was modified",
314 part.display(),
315 item.path.display()
316 );
317 }
318 if let Ok(meta) = fs::symlink_metadata(&dest) {
319 let dir = item.kind == crate::archive::Kind::Dir;
320 if dir && !meta.is_dir() {
321 bail!(
322 "{} is a file, but the archive requires a folder at that location",
323 dest.display()
324 );
325 }
326 if !dir && meta.is_dir() {
327 bail!(
328 "{} is a folder, but the archive has a file at that location. Move the \
329 folder or choose another destination",
330 dest.display()
331 );
332 }
333 }
334 for parent in item
335 .path
336 .ancestors()
337 .skip(1)
338 .filter(|p| !p.as_os_str().is_empty())
339 {
340 if !checked.insert(parent.to_path_buf()) {
341 break;
342 }
343 if let Ok(meta) = fs::symlink_metadata(out.join(parent))
344 && !meta.is_dir()
345 {
346 bail!(
347 "{} is a file, but the archive requires a folder at that location",
348 out.join(parent).display()
349 );
350 }
351 }
352 }
353 Ok(())
354}
355
356pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
361 let found = crate::replace::found(job, out);
362 if !found.is_empty() {
363 crate::replace::check(job, out, &found)?;
364 }
365 Ok(found)
366}
367
368pub fn single_root(job: &Job) -> bool {
372 let mut roots = job
373 .units
374 .iter()
375 .flat_map(|u| &u.items)
376 .filter_map(|i| i.path.components().next());
377 let Some(first) = roots.next() else {
378 return false;
379 };
380 roots.all(|r| r == first)
381}
382
383pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
386 let out = std::path::absolute(out)?;
387 check_path_lengths(job, &out)?;
388 check_no_links_on_the_way(job, &out)?;
389 check_collisions(job, &out)?;
390 Ok(out)
391}
392
393pub fn default_output(primary: &Path) -> PathBuf {
397 let file_name = primary
398 .file_name()
399 .unwrap_or_default()
400 .to_string_lossy()
401 .into_owned();
402 let mut name = file_name.clone();
403 if let Some((stem, digits)) = name.rsplit_once('.')
404 && digits.len() >= 3
405 && digits.bytes().all(|b| b.is_ascii_digit())
406 {
407 name = stem.to_string();
408 }
409 let lower = name.to_ascii_lowercase();
410 if let Some(stem) = lower.strip_suffix(".rar")
412 && let Some((_, digits)) = stem.rsplit_once(".part")
413 && !digits.is_empty()
414 && digits.bytes().all(|b| b.is_ascii_digit())
415 {
416 name.truncate(stem.len() - digits.len() - ".part".len());
417 return primary.with_file_name(name);
418 }
419 for ext in [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".rar", ".exe"] {
420 if lower.ends_with(ext) && name.len() > ext.len() {
421 name.truncate(name.len() - ext.len());
422 break;
423 }
424 }
425 if name == file_name {
426 name.push_str("-extracted");
427 }
428 primary.with_file_name(name)
429}
430
431pub fn display_name(job: &Job) -> String {
433 let parts = job.storage.parts();
434 let first = parts[0]
435 .path
436 .file_name()
437 .unwrap_or_default()
438 .to_string_lossy()
439 .into_owned();
440 match parts.len() {
441 1 => first,
442 n => format!("{first} (+{} more parts)", n - 1),
443 }
444}
445
446pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
451 if asked && !journal.keep {
452 bail!(
453 "this archive is partially extracted in place, so part of it is already removed and \
454 it cannot be kept. Resume without --keep-archive, or run restore first"
455 );
456 }
457 Ok(journal.keep)
458}
459
460pub struct SpacePlan {
462 pub free: u64,
465 pub needed: u64,
468 pub keep_free: u64,
469 pub fits: bool,
470 pub free_after: u64,
472 pub keep_archive: bool,
474 pub normal_needs: u64,
477 pub in_place_needs: u64,
480 pub either: bool,
483 pub reclaims: bool,
486 pub solid_block_bound: bool,
489 pub archive_kept_whole: bool,
494}
495
496impl SpacePlan {
497 pub fn normal_fits(&self) -> bool {
499 self.free >= self.normal_needs + self.keep_free
500 }
501
502 pub fn in_place_fits(&self) -> bool {
503 self.free >= self.in_place_needs + self.keep_free
504 }
505}
506
507pub fn plan(
511 job: &Job,
512 out: &Path,
513 resuming: bool,
514 keep_free: u64,
515 keep_archive: bool,
516) -> Result<SpacePlan> {
517 let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
518 let stale: u64 =
519 job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
520 let free = fsutil::available_space(out)? + stale;
521 let (normal_needs, normal_end) = job.space_needed(!resuming, false);
524 let (in_place_needs, in_place_end) = if keep_archive && resuming {
525 (normal_needs, normal_end)
526 } else {
527 job.space_needed(!resuming, reclaims)
528 };
529 let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
531 let normal_end = normal_end - if reclaims { tail } else { 0 };
532 let (needed, end) = if keep_archive {
533 (normal_needs, normal_end)
534 } else {
535 (in_place_needs, in_place_end)
536 };
537 let fits = free >= needed + keep_free;
538 Ok(SpacePlan {
539 free,
540 needed,
541 keep_free,
542 fits,
543 free_after: (free as i128 - end).max(0) as u64,
544 keep_archive,
545 normal_needs,
546 in_place_needs,
547 either: !resuming,
548 reclaims,
549 solid_block_bound: !fits
550 && !keep_archive
551 && !job.is_stream()
552 && job
553 .units
554 .iter()
555 .any(|u| u.items.len() > 1 && u.size() > free),
556 archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
557 })
558}
559
560pub fn begin(
567 job: &Job,
568 paths: &Paths,
569 output: PathBuf,
570 keep_archive: bool,
571 replace: Option<&crate::replace::Choices>,
572) -> Result<Journal> {
573 let found = existing(job, &output)?;
575 if let Some(first) = found.first()
576 && replace.is_none()
577 {
578 let what = match found.len() {
579 1 => format!("{} already exists", output.join(first).display()),
580 n => format!(
581 "{} and {} other {} already exist",
582 output.join(first).display(),
583 n - 1,
584 if n == 2 { "file" } else { "files" }
585 ),
586 };
587 bail!(
588 "{what}. Existing files are only replaced when that is requested. Move the files or \
589 choose another destination. Nothing was modified"
590 );
591 }
592 if keep_archive {
593 job.storage.protect();
594 } else if let Some(why) = job.in_place_refusal() {
595 bail!("{why}. It can be extracted while keeping the archive");
597 }
598 crate::chosen::remember(&paths.archive, &output);
601 let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
604 paths
605 .iter()
606 .filter(|p| found.contains(p))
607 .cloned()
608 .collect()
609 };
610 let replace = replace
611 .filter(|_| !found.is_empty())
612 .map(|c| crate::journal::Replace {
613 moved: false,
614 keep: only_found(&c.keep),
615 both: only_found(&c.both),
616 });
617 let plan = Plan {
618 format: job.format_name,
619 tail_start: job.tail_start,
620 output,
621 total_size: job.remaining_size(),
622 keep: keep_archive,
623 replace,
624 };
625 Journal::create(paths, &job.storage, plan)
626}
627
628pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
631 check_no_links_on_the_way(job, out)?;
632 for (p, _) in job.uncommitted(out) {
633 fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
634 }
635 Ok(())
636}
637
638#[cfg(test)]
639mod tests {
640 use std::io::Write;
641
642 use ::zip::write::{SimpleFileOptions, ZipWriter};
643
644 use super::*;
645
646 #[test]
647 fn output_folder_drops_the_volume_and_format_suffixes() {
648 let name = |n: &str| default_output(Path::new(n));
649 assert_eq!(name("game.zip"), Path::new("game"));
650 assert_eq!(name("game.7z.001"), Path::new("game"));
651 assert_eq!(name("game.part1.rar"), Path::new("game"));
652 assert_eq!(name("game.PART02.RAR"), Path::new("game"));
653 assert_eq!(name("game.rar"), Path::new("game"));
654 assert_eq!(name("game.part.rar"), Path::new("game.part"));
655 assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
656 }
657
658 fn sample_zip(dir: &Path) -> PathBuf {
661 let path = dir.join("plan.zip");
662 let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
663 let opts =
664 SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
665 for i in 0..8u8 {
666 w.start_file(format!("data/{i}.bin"), opts).unwrap();
667 w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
668 }
669 w.finish().unwrap();
670 path
671 }
672
673 #[test]
674 fn keeping_the_archive_plans_for_every_file() {
675 let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
676 fs::create_dir_all(&dir).unwrap();
677 let archive = sample_zip(&dir);
678 let out = dir.join("out");
679 let job = Job::open(&archive, false, None, Default::default()).unwrap();
680 let files: u64 = job
681 .units
682 .iter()
683 .flat_map(|u| &u.items)
684 .map(|i| i.size.next_multiple_of(4096))
685 .sum();
686 let tail = job.storage.original_len() - job.tail_start;
687
688 let keep = plan(&job, &out, false, 0, true).unwrap();
689 assert!(keep.keep_archive && keep.either);
690 assert_eq!(keep.needed, files + tail);
692 assert_eq!(keep.normal_needs, keep.needed);
693 assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
694 assert_eq!(keep.free.saturating_sub(keep.free_after), files);
696
697 let in_place = plan(&job, &out, false, 0, false).unwrap();
698 assert!(!in_place.keep_archive);
699 assert_eq!(in_place.normal_needs, keep.needed);
700 assert_eq!(in_place.in_place_needs, in_place.needed);
701 assert_eq!(keep.in_place_needs, in_place.needed);
702 assert!(
703 in_place.needed < keep.needed / 2,
704 "in place {} vs kept {}",
705 in_place.needed,
706 keep.needed
707 );
708 drop(job);
709 fs::remove_dir_all(&dir).unwrap();
710 }
711
712 #[test]
715 fn a_kept_archive_refuses_every_change() {
716 let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
717 fs::create_dir_all(&dir).unwrap();
718 let archive = sample_zip(&dir);
719 let before = fs::read(&archive).unwrap();
720 let (primary, paths) = locate(&archive).unwrap();
721 let reads = Arc::default();
722 let State::Fresh(job, out) = open(&primary, &paths, None, true, None, &reads).unwrap()
723 else {
724 panic!("a new archive opens fresh");
725 };
726 let journal = begin(&job, &paths, out, true, None).unwrap();
727 assert!(journal.keep);
728 let len = job.storage.original_len();
729 assert!(job.storage.set_len(len / 2).is_err());
730 assert!(job.storage.punch(0, len / 2).is_err());
731 assert!(job.storage.write_at(0, b"PK").is_err());
732 assert!(job.storage.cut_to(0).is_err());
733 drop(job);
734 assert_eq!(fs::read(&archive).unwrap(), before);
735
736 let (journal, tail) = Journal::load(&paths).unwrap();
738 let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
739 assert!(job.storage.set_len(0).is_err());
740 assert_eq!(job.units.len(), 8, "nothing is committed yet");
741 drop(job);
742 assert_eq!(fs::read(&archive).unwrap(), before);
743 assert!(keeps_archive(&journal, false).unwrap());
744 assert!(keeps_archive(&journal, true).unwrap());
745 fs::remove_dir_all(&dir).unwrap();
746 }
747}