Skip to main content

hatchzip_core/archive/
mod.rs

1//! What the engine needs from an archive format: the archive split into
2//! units, byte ranges that can be truncated away once every file in them is
3//! safely on disk, and a way to decode one unit.
4
5#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11pub mod targz;
12mod zip;
13
14use std::io::Read;
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17use std::time::SystemTime;
18
19use anyhow::{Context, Result, bail};
20
21use crate::journal::Resume;
22use storage::{Storage, Tail};
23use targz::Solid;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum Kind {
27    File,
28    Dir,
29    /// The link target is the item's data.
30    Symlink,
31    /// Hard links point at an earlier entry, which is extracted later than
32    /// the link when going from the end, so they are made at the very end.
33    HardLink(PathBuf),
34}
35
36#[derive(Clone, Debug)]
37pub struct Item {
38    pub path: PathBuf,
39    pub size: u64,
40    pub kind: Kind,
41    pub mode: Option<u32>,
42    pub mtime: Option<SystemTime>,
43}
44
45pub struct Unit {
46    /// Where the unit's bytes begin. Once it is committed the archive is
47    /// truncated to this offset.
48    pub start: u64,
49    /// The format's own handle for the unit: a ZIP entry index, a 7z block.
50    pub key: usize,
51    pub items: Vec<Item>,
52    /// Decoding it needs the archive's password.
53    pub encrypted: bool,
54}
55
56/// The archive is encrypted and nothing can be read without its password.
57/// Front ends look for this error to ask for one.
58#[derive(Debug)]
59pub struct PasswordNeeded;
60
61impl std::fmt::Display for PasswordNeeded {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.write_str("this archive is password protected")
64    }
65}
66
67impl std::error::Error for PasswordNeeded {}
68
69/// The password doesn't open the archive.
70#[derive(Debug)]
71pub struct WrongPassword;
72
73impl std::fmt::Display for WrongPassword {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.write_str("incorrect password")
76    }
77}
78
79impl std::error::Error for WrongPassword {}
80
81/// The archive is damaged, found while opening it and before anything was
82/// touched. Front ends look for this error to report damage as such.
83#[derive(Debug)]
84pub struct Damaged(pub anyhow::Error);
85
86impl std::fmt::Display for Damaged {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{:#}", self.0)
89    }
90}
91
92impl std::error::Error for Damaged {}
93
94/// The format name of RAR archives in the journal.
95pub const RAR: &str = "rar";
96
97/// Whether this build extracts RAR archives. Builds without UnRAR refuse
98/// them before anything is touched.
99pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
100
101/// Why a build without UnRAR refuses a RAR archive.
102pub fn no_rar() -> anyhow::Error {
103    anyhow::anyhow!(
104        "this build of HatchZip does not include RAR support, and the archive was not \
105         modified. Download the release build from hatchzip.dev or \
106         github.com/xevrion/hatchzip/releases"
107    )
108}
109
110/// How the password of an encrypted archive is proven before anything is
111/// touched.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum PasswordCheck {
114    /// Decode the start of the smallest encrypted unit: a wrong password
115    /// fails at once, or within the first blocks.
116    Sample,
117    /// The headers hold a check value for the password, so
118    /// [`Format::prove_password`] answers without decoding anything.
119    Headers,
120    /// Only the checksum at the end of a file can tell, so the smallest
121    /// encrypted unit is decoded whole, writing nothing.
122    WholeUnit,
123}
124
125impl Unit {
126    pub fn size(&self) -> u64 {
127        self.items.iter().map(|i| i.size).sum()
128    }
129}
130
131pub trait Format: Send + Sync {
132    /// A worker decodes units on one thread. `threads` is a hint for codecs
133    /// that can decode a single stream on several cores.
134    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
135
136    /// For a unit holding one file whose data [`resumable`] can decode from
137    /// the middle: where that data lies. Such units can free their archive
138    /// bytes while they are extracted instead of only once they are done.
139    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
140        Ok(None)
141    }
142
143    /// For an archive that is one compressed stream, decodable only from the
144    /// front: its single unit, extracted front to back while the bytes behind
145    /// the decoder are freed.
146    fn solid(&self) -> Option<&Solid> {
147        None
148    }
149
150    /// The decoder finds a unit only by reading everything before it, and
151    /// one handle can't be shared between threads. A batch is then decoded
152    /// on one thread by one worker, lowest unit first, so the worker can
153    /// walk forward instead of starting over for every unit.
154    fn serial(&self) -> bool {
155        false
156    }
157
158    /// Why the archive can't be extracted in place, if it can't: it can
159    /// still be extracted while it is kept.
160    fn refuses_in_place(&self) -> Option<String> {
161        None
162    }
163
164    fn password_check(&self) -> PasswordCheck {
165        PasswordCheck::Sample
166    }
167
168    /// Proves the password from the headers alone; only called when
169    /// [`password_check`](Self::password_check) says it can.
170    fn prove_password(&self) -> Result<()> {
171        Ok(())
172    }
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum Codec {
177    Stored,
178    /// Raw deflate, as ZIP stores it.
179    Deflate,
180}
181
182#[derive(Clone, Debug)]
183pub struct Stream {
184    /// Where the file's data begins. The headers before it stay untouched
185    /// until the unit is committed, so the archive still parses on resume.
186    pub data_start: u64,
187    /// Length of the data in the archive.
188    pub packed: u64,
189    pub codec: Codec,
190    /// CRC-32 of the output, if the format records one.
191    pub crc: Option<u32>,
192}
193
194pub trait Worker {
195    /// Decodes `unit`, handing each item to `sink` in order.
196    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
197}
198
199pub trait Sink {
200    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
201}
202
203pub struct Opened {
204    pub name: &'static str,
205    pub format: Box<dyn Format>,
206    pub units: Vec<Unit>,
207    /// Everything from here to the end is saved before anything is reclaimed.
208    pub tail_start: u64,
209}
210
211/// Parses the archive. `resume` carries the format recorded by an earlier
212/// run, the tail it saved and its resume point, which a compressed tar is
213/// read from; a fresh run sniffs the format instead. The password is only
214/// needed for encrypted archives; whether it is right is found out when a
215/// unit is decoded (see `Job::check_password`).
216pub fn open(
217    storage: &Arc<Storage>,
218    resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
219    password: Option<&str>,
220) -> Result<Opened> {
221    let (name, tail, point) = match resume {
222        Some((name, tail, point)) => (name.to_string(), Some(tail), point),
223        None => (sniff(storage)?.to_string(), None, None),
224    };
225    match name.as_str() {
226        "zip" => zip::open(storage, tail, password),
227        "7z" => sevenz::open(storage, tail, password),
228        "tar" => tar::open(storage, tail),
229        #[cfg(feature = "rar")]
230        RAR => rar::open(storage, tail.is_some(), password),
231        #[cfg(not(feature = "rar"))]
232        RAR => Err(no_rar()),
233        targz::NAME => targz::open(storage, point),
234        other => bail!("unknown archive format '{other}' in the journal"),
235    }
236}
237
238/// What turns the first `keep` bytes of a half-extracted archive back into an
239/// archive any tool opens.
240pub struct NewIndex {
241    /// Written at `keep`.
242    pub append: Vec<u8>,
243    /// Written over bytes below `keep`: the 7z start header, which has to
244    /// point at the new header.
245    pub patches: Vec<(u64, Vec<u8>)>,
246}
247
248/// Builds the [`NewIndex`] for the entries that start below `keep`, from
249/// the tail an earlier run saved. `hard_links` are tar links already cut off
250/// whose targets are still in the archive.
251pub fn rebuild_index(
252    format: &str,
253    storage: &Storage,
254    tail: Arc<Tail>,
255    keep: u64,
256    hard_links: &[(&Path, &Path)],
257) -> Result<NewIndex> {
258    let (append, patches) = match format {
259        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
260        "tar" => (tar::closing(hard_links)?, Vec::new()),
261        "7z" => {
262            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
263            (header, vec![(0, start)])
264        }
265        // No index: the last volume left only needs its end header back.
266        #[cfg(feature = "rar")]
267        RAR => (rar::closing(storage, keep)?, Vec::new()),
268        #[cfg(not(feature = "rar"))]
269        RAR => return Err(no_rar()),
270        other => bail!("unknown archive format '{other}' in the journal"),
271    };
272    Ok(NewIndex { append, patches })
273}
274
275fn sniff(storage: &Storage) -> Result<&'static str> {
276    let mut head = [0u8; 512];
277    let mut r = storage.reader(None);
278    let n = read_up_to(&mut r, &mut head)?;
279    let head = &head[..n];
280    let starts = |magic: &[u8]| head.starts_with(magic);
281    if starts(b"7z\xBC\xAF\x27\x1C") {
282        return Ok("7z");
283    }
284    let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
285    if is_tar(head) {
286        return Ok("tar");
287    }
288    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
289    if starts(b"\x1F\x8B") {
290        // Look inside: a plain .gz of one file is not an archive.
291        let mut gz = resumable::Gzip::new(
292            storage.reader(None),
293            storage.original_len(),
294            &resumable::GzPoint::start(),
295        )?;
296        let mut first = [0u8; 512];
297        let mut n = 0;
298        while n < first.len() {
299            match gz
300                .read(&mut first[n..])
301                .context("reading the start of the compressed stream")?
302            {
303                0 => break,
304                k => n += k,
305            }
306        }
307        let named = [".tar.gz", ".tgz", ".taz"]
308            .iter()
309            .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
310        if is_tar(&first[..n]) || named {
311            return Ok(targz::NAME);
312        }
313        bail!(
314            "this is a gzip-compressed file that does not contain a tar archive. Only \
315             compressed tar archives (.tar.gz) can be extracted"
316        );
317    }
318    if starts(b"\x28\xB5\x2F\xFD") || starts(b"\xFD7zXZ\x00") || starts(b"BZh") {
319        bail!(
320            "this is a compressed stream (.zst, .xz or .bz2). In-place extraction of these \
321             compressed streams is not supported yet"
322        );
323    }
324    if starts(b"Rar!\x1A\x07") {
325        return Ok(RAR);
326    }
327    if ext.ends_with(".tar") || ext.contains(".tar.") {
328        return Ok("tar");
329    }
330    // Anything else gets a ZIP parse: self-extracting archives put an
331    // executable in front, so the signature isn't at the start.
332    Ok("zip")
333}
334
335fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
336    let mut n = 0;
337    while n < buf.len() {
338        match r.read(&mut buf[n..])? {
339            0 => break,
340            k => n += k,
341        }
342    }
343    Ok(n)
344}
345
346/// Turns an archive member name into a relative path that can't leave the
347/// output folder. Leading slashes are dropped, as tar does; `..`, drive
348/// letters and NUL bytes are refused.
349pub fn safe_path(name: &str) -> Option<PathBuf> {
350    if name.contains('\0') {
351        return None;
352    }
353    let mut out = PathBuf::new();
354    for part in name.split(['/', '\\']) {
355        match part {
356            "" | "." => {}
357            ".." => return None,
358            p if p.contains(':') => return None,
359            p => out.push(p),
360        }
361    }
362    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
363    (clean && !out.as_os_str().is_empty()).then_some(out)
364}
365
366/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
367/// the Windows attributes.
368fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
369    (attrs & 0x8000 != 0).then_some(attrs >> 16)
370}
371
372const S_IFMT: u32 = 0o170000;
373const S_IFLNK: u32 = 0o120000;
374
375fn is_symlink_mode(mode: Option<u32>) -> bool {
376    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
377}