use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use crate::archive::storage::{self, Reads, Storage};
use crate::engine::Job;
use crate::fsutil;
use crate::journal::{Journal, Paths, Plan};
pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
let primary = std::path::absolute(storage::first_volume(archive))
.with_context(|| format!("resolving {}", archive.display()))?;
let paths = Paths::for_archive(&primary);
Ok((primary, paths))
}
pub enum State {
Fresh(Job, PathBuf),
Resume(Job, Journal),
Orphan(Journal),
}
pub(crate) fn check_recorded_case(journal: &Journal) -> Result<()> {
crate::engine::check_case_record(
&journal.output,
&journal.case_folders,
journal.case_beyond_ascii,
)
}
pub fn case_sensitive(dir: &Path) -> bool {
crate::platform::case_sensitive(dir)
}
pub fn open(
primary: &Path,
paths: &Paths,
output: Option<PathBuf>,
writable: bool,
password: Option<&str>,
reads: &Arc<Reads>,
) -> Result<State> {
if paths.exists() {
let (mut journal, tail) = Journal::load(paths)?;
if writable && !journal.done && journal.parts[0].0.exists() {
journal.check_folders(paths)?;
}
if writable || output.is_some() {
check_output(&journal, primary, output.as_deref(), "extract")?;
}
if writable {
check_recorded_case(&journal)?;
}
if journal.restoring.is_some() {
if !writable {
bail!(
"a restore of this archive was interrupted. Run restore again to complete \
it, or run extract to resume the extraction"
);
}
crate::restore::recover(&mut journal, paths)?;
}
if !journal.parts[0].0.exists() {
if journal.keep {
bail!(
"{} was moved or deleted during an extraction that keeps it. Put it back \
to resume, or delete {} to discard the progress",
journal.parts[0].0.display(),
paths.journal.display()
);
}
return Ok(State::Orphan(journal));
}
if journal.done {
return Ok(State::Orphan(journal));
}
let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
check_no_links_on_the_way(&job, &journal.output)?;
return Ok(State::Resume(job, journal));
}
let job = Job::open(primary, writable, password, reads.clone())?;
let output = match output {
Some(o) => std::path::absolute(o)?,
None => {
let output = default_output(primary);
refuse_linked_default(&output)?;
output
}
};
check_path_lengths(&job, &output)?;
if writable {
check_no_links_on_the_way(&job, &output)?;
check_collisions(&job, &output)?;
job.check_case(&output)?;
}
Ok(State::Fresh(job, output))
}
pub fn check_output(
journal: &Journal,
primary: &Path,
given: Option<&Path>,
command: &str,
) -> Result<()> {
let default = default_output(primary);
let in_default = fsutil::same_path(&default, &journal.output);
match given {
Some(o) => {
if !fsutil::same_path(&std::path::absolute(o)?, &journal.output) {
bail!(
"this archive is already partially extracted to {}. Complete or restore that \
extraction first",
journal.output.display()
);
}
}
None if crate::chosen::chose(primary, &journal.output) => {
if in_default {
refuse_linked_default(&default)?;
}
}
None if in_default => bail!(
"{} was partially extracted to {}, but this computer has no record of starting that \
extraction. If you started it, continue it by naming the folder again: hatchzip \
{command} \"{}\" -o \"{}\". Nothing was modified",
primary.display(),
journal.output.display(),
primary.display(),
journal.output.display()
),
None => bail!(
"{} was partially extracted to {}, a folder not chosen on this computer. If you \
started that extraction, continue it by naming the folder again: hatchzip {command} \
\"{}\" -o \"{}\". Nothing was modified",
primary.display(),
journal.output.display(),
primary.display(),
journal.output.display()
),
}
Ok(())
}
fn refuse_linked_default(output: &Path) -> Result<()> {
if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
bail!(
"{} is a link, so files extracted there would land somewhere else. Remove the link, \
or choose the destination folder. Nothing was modified",
output.display()
);
}
Ok(())
}
pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
let mut checked = std::collections::HashSet::new();
for item in job.units.iter().flat_map(|u| &u.items) {
for parent in item
.path
.ancestors()
.skip(1)
.filter(|p| !p.as_os_str().is_empty())
{
if !checked.insert(parent.to_path_buf()) {
break;
}
if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
bail!(
"{} is a link, and '{}' would be extracted through it. Nothing was modified",
out.join(parent).display(),
item.path.display()
);
}
}
}
Ok(())
}
fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
for item in job.units.iter().flat_map(|u| &u.items) {
if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
bail!(
"'{}' cannot be created in {}: the full path would be longer than this system \
allows. The archive was not modified. Extract to a folder with a shorter path",
item.path.display(),
out.display()
);
}
}
Ok(())
}
pub fn open_encrypted(
primary: &Path,
paths: &Paths,
output: Option<PathBuf>,
writable: bool,
password: Option<String>,
reads: &Arc<Reads>,
ask: impl FnMut(bool) -> Option<String>,
) -> Result<(State, Option<String>)> {
open_encrypted_noting(
primary,
paths,
output,
writable,
password,
reads,
ask,
|_, _| {},
)
}
#[allow(clippy::too_many_arguments)]
pub fn open_encrypted_noting(
primary: &Path,
paths: &Paths,
output: Option<PathBuf>,
writable: bool,
mut password: Option<String>,
reads: &Arc<Reads>,
mut ask: impl FnMut(bool) -> Option<String>,
mut slow: impl FnMut(&Path, u64),
) -> Result<(State, Option<String>)> {
let mut wrong = false;
loop {
let attempt = open(
primary,
paths,
output.clone(),
writable,
password.as_deref(),
reads,
);
let failure = match attempt {
Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
Ok(state) => {
let job = match &state {
State::Fresh(job, _) | State::Resume(job, _) => job,
State::Orphan(_) => unreachable!(),
};
if !job.encrypted() {
return Ok((state, password));
}
if password.is_some()
&& let Some((file, size)) = job.slow_password_check()
{
slow(file, size);
}
match job.check_password() {
Ok(()) => return Ok((state, password)),
Err(e) => e,
}
}
Err(e) => e,
};
if failure.is::<crate::archive::WrongPassword>() {
wrong = true;
} else if !failure.is::<crate::archive::PasswordNeeded>() {
return Err(failure);
}
match ask(wrong) {
Some(p) => password = Some(p),
None => return Err(failure),
}
}
}
fn check_collisions(job: &Job, out: &Path) -> Result<()> {
if !out.exists() {
return Ok(());
}
check_own_files(job, out)?;
let mut checked = std::collections::HashSet::new();
for item in job.units.iter().flat_map(|u| &u.items) {
let dest = out.join(&item.path);
let part = crate::engine::part_path(&dest);
if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
bail!(
"{} already exists. HatchZip first writes '{}' under that name and does not \
replace a file it did not create. Move it or choose another destination. Nothing \
was modified",
part.display(),
item.path.display()
);
}
if let Ok(meta) = fs::symlink_metadata(&dest) {
let dir = item.kind == crate::archive::Kind::Dir;
if dir && !meta.is_dir() {
bail!(
"{} is a file, but the archive requires a folder at that location",
dest.display()
);
}
if !dir && meta.is_dir() {
bail!(
"{} is a folder, but the archive has a file at that location. Move the \
folder or choose another destination",
dest.display()
);
}
}
for parent in item
.path
.ancestors()
.skip(1)
.filter(|p| !p.as_os_str().is_empty())
{
if !checked.insert(parent.to_path_buf()) {
break;
}
if let Ok(meta) = fs::symlink_metadata(out.join(parent))
&& !meta.is_dir()
{
bail!(
"{} is a file, but the archive requires a folder at that location",
out.join(parent).display()
);
}
}
}
Ok(())
}
fn check_own_files(job: &Job, out: &Path) -> Result<()> {
let text = |p: &Path| p.to_string_lossy().to_lowercase();
let folder = |p: &Path| {
let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
fs::canonicalize(dir.unwrap_or(Path::new(".")))
.ok()
.map(|d| text(&d))
};
let lower = |p: &Path| p.file_name().map(|n| text(Path::new(n)));
let Ok(out) = fs::canonicalize(out) else {
return Ok(());
};
let primary = job.storage.primary();
let own_folder = folder(primary);
let side = lower(primary).map(|n| format!("{n}.hatchzip"));
let volumes: Vec<_> = job
.storage
.parts()
.iter()
.map(|p| (folder(&p.path), lower(&p.path)))
.collect();
for item in job.units.iter().flat_map(|u| &u.items) {
let dest = out.join(&item.path);
let dir = dest.parent().map(text);
let name = lower(&dest);
let (Some(dir), Some(name)) = (dir, name) else {
continue;
};
let volume = volumes
.iter()
.any(|(d, n)| d.as_ref() == Some(&dir) && n.as_ref() == Some(&name));
let progress = own_folder.as_ref() == Some(&dir)
&& side.as_ref().is_some_and(|s| name.starts_with(s.as_str()));
if volume || progress {
bail!(
"'{}' would be extracted onto {}, one of the archive's own files. Choose another \
destination. Nothing was modified",
item.path.display(),
dest.display()
);
}
}
Ok(())
}
pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
let found = crate::replace::found(job, out);
if !found.is_empty() {
crate::replace::check(job, out, &found)?;
}
Ok(found)
}
pub fn single_root(job: &Job) -> bool {
let mut roots = job
.units
.iter()
.flat_map(|u| &u.items)
.filter_map(|i| i.path.components().next());
let Some(first) = roots.next() else {
return false;
};
roots.all(|r| r == first)
}
pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
let out = std::path::absolute(out)?;
check_path_lengths(job, &out)?;
check_no_links_on_the_way(job, &out)?;
check_collisions(job, &out)?;
job.check_case(&out)?;
Ok(out)
}
pub fn default_output(primary: &Path) -> PathBuf {
let file_name = primary
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
let mut name = file_name.clone();
if let Some((stem, digits)) = name.rsplit_once('.')
&& digits.len() >= 3
&& digits.bytes().all(|b| b.is_ascii_digit())
{
name = stem.to_string();
}
let lower = name.to_ascii_lowercase();
if let Some(stem) = lower.strip_suffix(".rar")
&& let Some((_, digits)) = stem.rsplit_once(".part")
&& !digits.is_empty()
&& digits.bytes().all(|b| b.is_ascii_digit())
{
name.truncate(stem.len() - digits.len() - ".part".len());
} else {
for ext in [
".zip", ".7z", ".tar.xz", ".txz", ".tar", ".tar.gz", ".tgz", ".rar", ".exe",
] {
if lower.ends_with(ext) && name.len() > ext.len() {
name.truncate(name.len() - ext.len());
break;
}
}
}
if name == file_name || name.chars().all(|c| c == '.' || c == ' ') {
name = file_name;
name.push_str("-extracted");
}
primary.with_file_name(name)
}
pub fn display_name(job: &Job) -> String {
let parts = job.storage.parts();
let first = parts[0]
.path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned();
match parts.len() {
1 => first,
n => format!("{first} (+{} more parts)", n - 1),
}
}
pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
if asked && !journal.keep {
bail!(
"this archive is partially extracted in place, so part of it is already removed and \
it cannot be kept. Resume without --keep-archive, or run restore first"
);
}
Ok(journal.keep)
}
pub struct SpacePlan {
pub free: u64,
pub needed: u64,
pub keep_free: u64,
pub fits: bool,
pub free_after: u64,
pub keep_archive: bool,
pub normal_needs: u64,
pub in_place_needs: u64,
pub either: bool,
pub reclaims: bool,
pub solid_block_bound: bool,
pub archive_kept_whole: bool,
}
impl SpacePlan {
pub fn normal_fits(&self) -> bool {
self.free >= self.normal_needs + self.keep_free
}
pub fn in_place_fits(&self) -> bool {
self.free >= self.in_place_needs + self.keep_free
}
}
pub fn plan(
job: &Job,
out: &Path,
resuming: bool,
keep_free: u64,
keep_archive: bool,
) -> Result<SpacePlan> {
job.check_case(out)?;
let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
let stale: u64 =
job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
let free = fsutil::available_space(out)? + stale;
let (normal_needs, normal_end) = job.space_needed(!resuming, false);
let (in_place_needs, in_place_end) = if keep_archive && resuming {
(normal_needs, normal_end)
} else {
job.space_needed(!resuming, reclaims)
};
let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
let normal_end = normal_end - if reclaims { tail } else { 0 };
let (needed, end) = if keep_archive {
(normal_needs, normal_end)
} else {
(in_place_needs, in_place_end)
};
let fits = free >= needed + keep_free;
Ok(SpacePlan {
free,
needed,
keep_free,
fits,
free_after: (free as i128 - end).max(0) as u64,
keep_archive,
normal_needs,
in_place_needs,
either: !resuming,
reclaims,
solid_block_bound: !fits
&& !keep_archive
&& !job.is_stream()
&& job
.units
.iter()
.any(|u| u.items.len() > 1 && u.size() > free),
archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
})
}
pub fn begin(
job: &Job,
paths: &Paths,
output: PathBuf,
keep_archive: bool,
replace: Option<&crate::replace::Choices>,
) -> Result<Journal> {
job.check_case(&output)?;
let found = existing(job, &output)?;
if let Some(first) = found.first()
&& replace.is_none()
{
let what = match found.len() {
1 => format!("{} already exists", output.join(first).display()),
n => format!(
"{} and {} other {} already exist",
output.join(first).display(),
n - 1,
if n == 2 { "file" } else { "files" }
),
};
bail!(
"{what}. Existing files are only replaced when that is requested. Move the files or \
choose another destination. Nothing was modified"
);
}
if keep_archive {
job.storage.protect();
} else if let Some(why) = job.in_place_refusal() {
bail!("{why}. It can be extracted while keeping the archive");
}
crate::sfv::check_volumes(&job.storage)?;
crate::chosen::remember(&paths.archive, &output);
let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
paths
.iter()
.filter(|p| found.contains(p))
.cloned()
.collect()
};
let replace = replace
.filter(|_| !found.is_empty())
.map(|c| crate::journal::Replace {
moved: false,
keep: only_found(&c.keep),
both: only_found(&c.both),
});
let folders = crate::folders::of(&job.units, &output);
let plan = Plan {
format: job.format_name,
tail_start: job.tail_start,
output,
total_size: job.remaining_size(),
keep: keep_archive,
replace,
case_folders: job.case_folders(),
case_beyond_ascii: job.case_beyond_ascii(),
folders,
};
Journal::create(paths, &job.storage, plan)
}
pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
crate::sfv::check_volumes_cancellable(storage, cancelled)
}
pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
check_no_links_on_the_way(job, out)?;
let found = job.uncommitted(out);
let mut listed = std::collections::HashMap::new();
for (p, _) in &found {
check_spelling(out, p, &mut listed)?;
}
for (p, _) in found {
fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
}
Ok(())
}
fn check_spelling(
out: &Path,
path: &Path,
listed: &mut std::collections::HashMap<PathBuf, std::collections::HashSet<String>>,
) -> Result<()> {
use unicode_normalization::UnicodeNormalization;
let spelling = |n: &std::ffi::OsStr| n.to_string_lossy().nfd().collect::<String>();
let Ok(rel) = path.strip_prefix(out) else {
return Ok(());
};
let mut dir = out.to_path_buf();
for name in rel.iter() {
let names = match listed.entry(dir.clone()) {
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
std::collections::hash_map::Entry::Vacant(e) => e.insert(
fs::read_dir(&dir)
.with_context(|| format!("listing {}", dir.display()))?
.map(|e| e.map(|e| spelling(&e.file_name())))
.collect::<std::io::Result<_>>()
.with_context(|| format!("listing {}", dir.display()))?,
),
};
if !names.contains(&spelling(name)) {
bail!(
"{} is spelled differently on disk than in the archive, so it was not made by \
this extraction and is left alone. Move it out of the way, then run the command \
again",
dir.join(name).display()
);
}
dir.push(name);
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::Write;
use ::zip::write::{SimpleFileOptions, ZipWriter};
use super::*;
#[test]
fn a_resume_leaves_names_spelled_differently_alone() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path();
fs::create_dir(out.join("Src")).unwrap();
fs::write(out.join("Src/Makefile"), b"theirs").unwrap();
fs::write(out.join("Src/caf\u{e9}.txt"), b"ours").unwrap();
let mut listed = std::collections::HashMap::new();
assert!(check_spelling(out, &out.join("Src/makefile"), &mut listed).is_err());
assert!(check_spelling(out, &out.join("src/Makefile"), &mut listed).is_err());
assert!(check_spelling(out, &out.join("Src/Makefile"), &mut listed).is_ok());
assert!(check_spelling(out, &out.join("Src/cafe\u{301}.txt"), &mut listed).is_ok());
}
#[test]
fn output_folder_drops_the_volume_and_format_suffixes() {
let name = |n: &str| default_output(Path::new(n));
assert_eq!(name("game.zip"), Path::new("game"));
assert_eq!(name("game.7z.001"), Path::new("game"));
assert_eq!(name("game.part1.rar"), Path::new("game"));
assert_eq!(name("game.PART02.RAR"), Path::new("game"));
assert_eq!(name("game.rar"), Path::new("game"));
assert_eq!(name("game.tar.xz"), Path::new("game"));
assert_eq!(name("game.txz"), Path::new("game"));
assert_eq!(name("game.part.rar"), Path::new("game.part"));
assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
}
#[test]
fn output_folder_is_never_the_folder_above_or_the_archives_own() {
let name = |n: &str| default_output(&Path::new("dl").join(n));
for n in [
"...zip",
"..zip",
".zip",
". .zip",
"...tar.gz",
"...7z.001",
"...part1.rar",
"..part2.rar",
] {
assert_eq!(
name(n),
Path::new("dl").join(format!("{n}-extracted")),
"{n}"
);
}
assert_eq!(name("...game.zip"), Path::new("dl/...game"));
}
fn sample_zip(dir: &Path) -> PathBuf {
let path = dir.join("plan.zip");
let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
let opts =
SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
for i in 0..8u8 {
w.start_file(format!("data/{i}.bin"), opts).unwrap();
w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
}
w.finish().unwrap();
path
}
#[test]
fn keeping_the_archive_plans_for_every_file() {
let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let archive = sample_zip(&dir);
let out = dir.join("out");
let job = Job::open(&archive, false, None, Default::default()).unwrap();
let files: u64 = job
.units
.iter()
.flat_map(|u| &u.items)
.map(|i| i.size.next_multiple_of(4096))
.sum();
let tail = job.storage.original_len() - job.tail_start;
let keep = plan(&job, &out, false, 0, true).unwrap();
assert!(keep.keep_archive && keep.either);
assert_eq!(keep.needed, files + tail);
assert_eq!(keep.normal_needs, keep.needed);
assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
assert_eq!(keep.free.saturating_sub(keep.free_after), files);
let in_place = plan(&job, &out, false, 0, false).unwrap();
assert!(!in_place.keep_archive);
assert_eq!(in_place.normal_needs, keep.needed);
assert_eq!(in_place.in_place_needs, in_place.needed);
assert_eq!(keep.in_place_needs, in_place.needed);
assert!(
in_place.needed < keep.needed / 2,
"in place {} vs kept {}",
in_place.needed,
keep.needed
);
drop(job);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_kept_archive_refuses_every_change() {
let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let archive = sample_zip(&dir);
let before = fs::read(&archive).unwrap();
let (primary, paths) = locate(&archive).unwrap();
let reads = Arc::default();
let State::Fresh(job, out) = open(&primary, &paths, None, true, None, &reads).unwrap()
else {
panic!("a new archive opens fresh");
};
let journal = begin(&job, &paths, out, true, None).unwrap();
assert!(journal.keep);
let len = job.storage.original_len();
assert!(job.storage.set_len(len / 2).is_err());
assert!(job.storage.punch(0, len / 2).is_err());
assert!(job.storage.write_at(0, b"PK").is_err());
assert!(job.storage.cut_to(0).is_err());
drop(job);
assert_eq!(fs::read(&archive).unwrap(), before);
let (journal, tail) = Journal::load(&paths).unwrap();
let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
assert!(job.storage.set_len(0).is_err());
assert_eq!(job.units.len(), 8, "nothing is committed yet");
drop(job);
assert_eq!(fs::read(&archive).unwrap(), before);
assert!(keeps_archive(&journal, false).unwrap());
assert!(keeps_archive(&journal, true).unwrap());
fs::remove_dir_all(&dir).unwrap();
}
}