#[cfg(feature = "rar")]
mod rar;
pub mod resumable;
mod sevenz;
pub mod storage;
mod tar;
mod tarbz2;
pub mod targz;
pub mod tarxz;
pub mod tarzst;
mod xz;
mod zip;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use anyhow::{Context, Result, bail};
use crate::journal::Resume;
use storage::{Storage, Tail};
use targz::Event;
use targz::Profile;
pub trait SolidStream: Send + Sync {
fn profile(&self) -> &targz::Profile;
fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
}
pub trait SolidWalker {
fn next(&mut self, max: usize) -> Result<Event<'_>>;
fn point(&self) -> Result<Resume>;
fn point_byte(&self) -> Option<u64>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Kind {
File,
Dir,
Symlink,
HardLink(PathBuf),
}
#[derive(Clone, Debug)]
pub struct Item {
pub path: PathBuf,
pub size: u64,
pub kind: Kind,
pub mode: Option<u32>,
pub mtime: Option<SystemTime>,
}
#[derive(Clone)]
pub struct Unit {
pub start: u64,
pub key: usize,
pub items: Vec<Item>,
pub encrypted: bool,
}
#[derive(Debug)]
pub struct PasswordNeeded;
impl std::fmt::Display for PasswordNeeded {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("this archive is password protected")
}
}
impl std::error::Error for PasswordNeeded {}
#[derive(Debug)]
pub struct WrongPassword;
impl std::fmt::Display for WrongPassword {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("incorrect password")
}
}
impl std::error::Error for WrongPassword {}
#[derive(Debug)]
pub struct Damaged(pub anyhow::Error);
impl std::fmt::Display for Damaged {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:#}", self.0)
}
}
impl std::error::Error for Damaged {}
#[derive(Debug)]
pub struct Unsupported(pub anyhow::Error);
impl std::fmt::Display for Unsupported {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:#}", self.0)
}
}
impl std::error::Error for Unsupported {}
pub const RAR: &str = "rar";
pub const SPLIT_ZIP: &str = zip::SPLIT;
pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
pub fn no_rar() -> anyhow::Error {
anyhow::anyhow!(
"this build of HatchZip does not include RAR support, and the archive was not \
modified. Download the release build from hatchzip.dev or \
github.com/xevrion/hatchzip/releases"
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PasswordCheck {
Sample,
Headers,
WholeUnit,
}
impl Unit {
pub fn size(&self) -> u64 {
self.items
.iter()
.fold(0u64, |sum, i| sum.saturating_add(i.size))
}
}
pub trait Format: Send + Sync {
fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
Ok(None)
}
fn solid(&self) -> Option<&dyn SolidStream> {
None
}
fn serial(&self) -> bool {
false
}
fn refuses_in_place(&self) -> Option<String> {
None
}
fn password_check(&self) -> PasswordCheck {
PasswordCheck::Sample
}
fn prove_password(&self) -> Result<()> {
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Codec {
Stored,
Deflate,
}
#[derive(Clone, Debug)]
pub struct Stream {
pub data_start: u64,
pub packed: u64,
pub codec: Codec,
pub crc: Option<u32>,
}
pub trait Worker {
fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
}
pub trait Sink {
fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
}
pub struct Opened {
pub name: &'static str,
pub format: Box<dyn Format>,
pub units: Vec<Unit>,
pub tail_start: u64,
}
pub fn open(
storage: &Arc<Storage>,
resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
password: Option<&str>,
) -> Result<Opened> {
let (name, tail, point) = match resume {
Some((name, tail, point)) => (name.to_string(), Some(tail), point),
None => (sniff(storage)?.to_string(), None, None),
};
match name.as_str() {
"zip" => zip::open(storage, tail, password),
zip::SPLIT => zip::open_split(storage, tail, password),
"7z" => sevenz::open(storage, tail, password),
"tar" => tar::open(storage, tail),
#[cfg(feature = "rar")]
RAR => rar::open(storage, tail.is_some(), password),
#[cfg(not(feature = "rar"))]
RAR => Err(no_rar()),
targz::NAME => targz::open(storage, point),
tarbz2::NAME => tarbz2::open(storage, point),
tarxz::NAME => tarxz::open(storage, point),
tarzst::NAME => tarzst::open(storage, point),
other => bail!("unknown archive format '{other}' in the journal"),
}
}
pub struct NewIndex {
pub append: Vec<u8>,
pub patches: Vec<(u64, Vec<u8>)>,
pub new_last: bool,
}
fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
let from_byte = from.map_or(0, |r| r.bit / 8);
let mut w = solid.walk(from)?;
let mut items = Vec::new();
let mut p = Profile::default();
let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
loop {
match w.next(usize::MAX)? {
Event::Entry { item, .. } => {
if item.kind == Kind::File {
size = item.size;
}
items.push(item);
}
Event::Data(d) => out += d.len() as u64,
Event::FileEnd => out += size.next_multiple_of(4096) - size,
Event::Point => {
let consumed = w
.point_byte()
.unwrap_or(from_byte)
.saturating_sub(from_byte);
p.lead = p.lead.max(out as i128 - consumed as i128);
p.gap = p.gap.max(out - last);
last = out;
}
Event::End => break,
}
}
p.gap = p.gap.max(out - last);
p.files = out;
tar::size_links(&mut items);
p.links = items
.iter()
.filter(|i| i.kind != Kind::File)
.fold(0u64, |sum, i| {
let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
sum.saturating_add(size)
});
Ok((items, p))
}
pub fn rebuild_index(
format: &str,
storage: &Storage,
tail: Arc<Tail>,
keep: u64,
hard_links: &[(&Path, &Path)],
) -> Result<NewIndex> {
if format == zip::SPLIT {
let (append, new_last) = zip::rebuild_split_index(storage.parts(), &tail, keep)?;
return Ok(NewIndex {
append,
patches: Vec::new(),
new_last,
});
}
let (append, patches) = match format {
"zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
"tar" => (tar::closing(hard_links)?, Vec::new()),
"7z" => {
let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
(header, vec![(0, start)])
}
#[cfg(feature = "rar")]
RAR => (rar::closing(storage, keep)?, Vec::new()),
#[cfg(not(feature = "rar"))]
RAR => return Err(no_rar()),
other => bail!("unknown archive format '{other}' in the journal"),
};
Ok(NewIndex {
append,
patches,
new_last: false,
})
}
fn sniff(storage: &Storage) -> Result<&'static str> {
if storage.parts().len() > 1 && storage::is_split_zip(storage.primary()) {
return Ok(zip::SPLIT);
}
let mut head = [0u8; 512];
let mut r = storage.reader(None);
let n = read_up_to(&mut r, &mut head)?;
let head = &head[..n];
let starts = |magic: &[u8]| head.starts_with(magic);
if starts(b"7z\xBC\xAF\x27\x1C") {
return Ok("7z");
}
let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
if is_tar(head) {
return Ok("tar");
}
let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
if starts(b"\x1F\x8B") {
let named = [".tar.gz", ".tgz", ".taz"]
.iter()
.any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
if gzip_holds_tar(storage)? || named {
return Ok(targz::NAME);
}
bail!(
"this is a gzip-compressed file that does not contain a tar archive. Only \
compressed tar archives (.tar.gz) can be extracted"
);
}
if starts(b"\xFD7zXZ\x00") {
return Ok(tarxz::NAME);
}
if starts(b"BZh") {
let first = (|| -> Result<_> {
let mut bz = tarbz2::Bzip2::new(
storage.reader(None),
storage.original_len(),
&tarbz2::BzPoint::start(),
)?;
let mut first = [0; 512];
let mut n = 0;
while n < first.len() {
let k = bz.read(&mut first[n..])?;
if k == 0 {
break;
}
n += k;
}
Ok((first, n))
})()
.map_err(|e| {
if e.downcast_ref::<std::io::Error>().is_some() {
e
} else {
anyhow::Error::new(Damaged(e))
}
})
.context(
"checking the bzip2 archive (nothing was changed); if it is damaged, download it again",
)?;
let named = named_bzip2(
&storage
.primary()
.file_name()
.unwrap_or_default()
.to_string_lossy(),
);
if is_tar(&first.0[..first.1]) || named {
return Ok(tarbz2::NAME);
}
bail!(
"this is a bzip2-compressed file that does not contain a tar archive; the file was not changed. Decompress it with bzip2, or use a .tar.bz2 archive"
);
}
let zstd_magic = head.len() >= 4 && {
let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
};
if zstd_magic {
if named_zstd(&ext) || tarzst::holds_tar(storage)? {
return Ok(tarzst::NAME);
}
bail!(
"this is a zstd-compressed file that does not contain a tar archive. Only \
compressed tar archives (.tar.zst) can be extracted"
);
}
if starts(b"Rar!\x1A\x07") {
return Ok(RAR);
}
if ext.ends_with(".tar") || ext.contains(".tar.") {
return Ok("tar");
}
Ok("zip")
}
fn named_bzip2(name: &str) -> bool {
let name = name.to_ascii_lowercase();
let base = match name.rsplit_once('.') {
Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
_ => &name,
};
[".tar.bz2", ".tbz2", ".tbz"]
.iter()
.any(|e| base.ends_with(e))
}
fn named_zstd(name: &str) -> bool {
let name = name.to_ascii_lowercase();
let base = match name.rsplit_once('.') {
Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
_ => &name,
};
[".tar.zst", ".tzst"].iter().any(|e| base.ends_with(e))
}
fn gzip_holds_tar(storage: &Storage) -> Result<bool> {
let mut gz = resumable::Gzip::new(
storage.reader(None),
storage.original_len(),
&resumable::GzPoint::start(),
)?;
let mut first = [0u8; 512];
let mut n = 0;
while n < first.len() {
match gz
.read(&mut first[n..])
.context("reading the start of the compressed stream")?
{
0 => break,
k => n += k,
}
}
Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
}
fn bzip2_holds_tar(storage: &Storage) -> Result<bool> {
let mut bz = tarbz2::Bzip2::new(
storage.reader(None),
storage.original_len(),
&tarbz2::BzPoint::start(),
)?;
let mut first = [0u8; 512];
let mut n = 0;
while n < first.len() {
match bz.read(&mut first[n..])? {
0 => break,
k => n += k,
}
}
Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
}
fn zip_has_an_index(path: &Path) -> bool {
const MAX: u64 = 22 + 0xFFFF;
let Ok(mut file) = fs::File::open(path) else {
return false;
};
let Ok(len) = file.metadata().map(|m| m.len()) else {
return false;
};
if len < 22 {
return false;
}
let start = len.saturating_sub(MAX);
if file.seek(SeekFrom::Start(start)).is_err() {
return false;
}
let mut tail = Vec::with_capacity((len - start) as usize);
if file.take(len - start).read_to_end(&mut tail).is_err() {
return false;
}
let has = |magic: &[u8]| tail.windows(magic.len()).any(|w| w == magic);
has(b"PK\x05\x06") || has(b"PK\x06\x06")
}
pub fn detect(path: &Path) -> Option<&'static str> {
let meta = fs::symlink_metadata(path).ok()?;
if !meta.is_file() {
return None;
}
let mut head = [0u8; 512];
let n = read_up_to(&mut fs::File::open(path).ok()?, &mut head).ok()?;
let head = &head[..n];
let starts = |magic: &[u8]| head.starts_with(magic);
if starts(b"7z\xBC\xAF\x27\x1C") {
return Some("7z");
}
if head.len() >= 263 && &head[257..262] == b"ustar" {
return Some("tar");
}
if starts(b"\xFD7zXZ\x00") {
let storage = Arc::new(Storage::open(path, false).ok()?);
return tarxz::holds_tar(&storage).then_some(tarxz::NAME);
}
if starts(b"Rar!\x1A\x07") {
return cfg!(feature = "rar").then_some(RAR);
}
if starts(b"\x1F\x8B") {
let storage = Storage::open(path, false).ok()?;
return gzip_holds_tar(&storage).ok()?.then_some(targz::NAME);
}
if starts(b"BZh") {
let storage = Storage::open(path, false).ok()?;
return bzip2_holds_tar(&storage).ok()?.then_some(tarbz2::NAME);
}
let zstd = head.len() >= 4 && {
let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
};
if zstd {
let storage = Arc::new(Storage::open(path, false).ok()?);
return tarzst::holds_tar(&storage).ok()?.then_some(tarzst::NAME);
}
if starts(b"PK\x03\x04") || starts(b"PK\x05\x06") {
return zip_has_an_index(path).then_some("zip");
}
None
}
pub fn nested_kind(path: &Path) -> Option<&'static str> {
if storage::is_split_zip(path) {
return starts_like_split_zip(path).then_some(SPLIT_ZIP);
}
let name = path.file_name()?.to_string_lossy().to_ascii_lowercase();
let expected = if name.ends_with(".zip") {
"zip"
} else if name.ends_with(".7z") {
"7z"
} else if name.ends_with(".tar") {
"tar"
} else if [".tar.gz", ".tgz", ".taz"]
.iter()
.any(|e| name.ends_with(e))
{
targz::NAME
} else if [".tar.xz", ".txz"].iter().any(|e| name.ends_with(e)) {
tarxz::NAME
} else if [".tar.zst", ".tzst"].iter().any(|e| name.ends_with(e)) {
tarzst::NAME
} else if [".tar.bz2", ".tbz2", ".tbz"]
.iter()
.any(|e| name.ends_with(e))
{
tarbz2::NAME
} else if name.ends_with(".rar") {
RAR
} else {
return None;
};
(detect(path)? == expected).then_some(expected)
}
fn starts_like_split_zip(path: &Path) -> bool {
if !fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) {
return false;
}
let mut head = [0u8; 8];
let Ok(n) = fs::File::open(path).and_then(|mut f| read_up_to(&mut f, &mut head)) else {
return false;
};
let head = &head[..n];
let local: &[u8] = b"PK\x03\x04";
head.starts_with(local)
|| ((head.starts_with(b"PK\x07\x08") || head.starts_with(b"PK00")) && &head[4..] == local)
}
fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
let mut n = 0;
while n < buf.len() {
match r.read(&mut buf[n..])? {
0 => break,
k => n += k,
}
}
Ok(n)
}
pub fn safe_path(name: &str) -> Option<PathBuf> {
if name.contains('\0') {
return None;
}
let mut out = PathBuf::new();
for part in name.split(['/', '\\']) {
match part {
"" | "." => {}
".." => return None,
p if out.as_os_str().is_empty()
&& p.len() == 2
&& p.as_bytes()[0].is_ascii_alphabetic()
&& p.ends_with(':') =>
{
return None;
}
p => out.push(p),
}
}
let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
(clean && !out.as_os_str().is_empty()).then_some(out)
}
fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
(attrs & 0x8000 != 0).then_some(attrs >> 16)
}
const S_IFMT: u32 = 0o170000;
const S_IFLNK: u32 = 0o120000;
fn is_symlink_mode(mode: Option<u32>) -> bool {
mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
}
#[cfg(test)]
mod named_tests {
use super::named_bzip2;
#[test]
fn only_the_file_name_and_a_split_number_select_bzip2() {
for yes in ["a.tar.bz2", "A.TBZ2", "a.tbz", "a.tar.bz2.001", "a.tbz2.12"] {
assert!(named_bzip2(yes), "{yes}");
}
for no in [
"a.zip",
"a.tar.bz2.old",
"a.tar.bz2.",
"a.bz2",
"a.tar.gz.001",
] {
assert!(!named_bzip2(no), "{no}");
}
}
}