pub mod resumable;
mod sevenz;
pub mod storage;
mod tar;
mod zip;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use anyhow::{Result, bail};
use storage::{Storage, Tail};
#[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>,
}
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 {}
impl Unit {
pub fn size(&self) -> u64 {
self.items.iter().map(|i| i.size).sum()
}
}
pub trait Format: Send + Sync {
fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
Ok(None)
}
}
#[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>)>,
password: Option<&str>,
) -> Result<Opened> {
let (name, tail) = match resume {
Some((name, tail)) => (name.to_string(), Some(tail)),
None => (sniff(storage)?.to_string(), None),
};
match name.as_str() {
"zip" => zip::open(storage, tail, password),
"7z" => sevenz::open(storage, tail, password),
"tar" => tar::open(storage, tail),
other => bail!("unknown archive format '{other}' in the journal"),
}
}
pub struct NewIndex {
pub append: Vec<u8>,
pub patches: Vec<(u64, Vec<u8>)>,
}
pub fn rebuild_index(
format: &str,
storage: &Storage,
tail: Arc<Tail>,
keep: u64,
hard_links: &[(&Path, &Path)],
) -> Result<NewIndex> {
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)])
}
other => bail!("unknown archive format '{other}' in the journal"),
};
Ok(NewIndex { append, patches })
}
fn sniff(storage: &Storage) -> Result<&'static str> {
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");
}
if head.len() >= 263 && &head[257..262] == b"ustar" {
return Ok("tar");
}
if starts(b"\x1F\x8B")
|| starts(b"\x28\xB5\x2F\xFD")
|| starts(b"\xFD7zXZ\x00")
|| starts(b"BZh")
{
bail!(
"this is a compressed stream (.gz, .zst, .xz or .bz2). In-place extraction of \
compressed streams is not supported"
);
}
if starts(b"Rar!\x1A\x07") {
bail!("RAR archives are not supported");
}
let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
if ext.ends_with(".tar") || ext.contains(".tar.") {
return Ok("tar");
}
Ok("zip")
}
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 p.contains(':') => 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)
}