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    /// Saturates instead of wrapping: sizes come straight from the archive.
127    pub fn size(&self) -> u64 {
128        self.items
129            .iter()
130            .fold(0u64, |sum, i| sum.saturating_add(i.size))
131    }
132}
133
134pub trait Format: Send + Sync {
135    /// A worker decodes units on one thread. `threads` is a hint for codecs
136    /// that can decode a single stream on several cores.
137    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
138
139    /// For a unit holding one file whose data [`resumable`] can decode from
140    /// the middle: where that data lies. Such units can free their archive
141    /// bytes while they are extracted instead of only once they are done.
142    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
143        Ok(None)
144    }
145
146    /// For an archive that is one compressed stream, decodable only from the
147    /// front: its single unit, extracted front to back while the bytes behind
148    /// the decoder are freed.
149    fn solid(&self) -> Option<&Solid> {
150        None
151    }
152
153    /// The decoder finds a unit only by reading everything before it, and
154    /// one handle can't be shared between threads. A batch is then decoded
155    /// on one thread by one worker, lowest unit first, so the worker can
156    /// walk forward instead of starting over for every unit.
157    fn serial(&self) -> bool {
158        false
159    }
160
161    /// Why the archive can't be extracted in place, if it can't: it can
162    /// still be extracted while it is kept.
163    fn refuses_in_place(&self) -> Option<String> {
164        None
165    }
166
167    fn password_check(&self) -> PasswordCheck {
168        PasswordCheck::Sample
169    }
170
171    /// Proves the password from the headers alone; only called when
172    /// [`password_check`](Self::password_check) says it can.
173    fn prove_password(&self) -> Result<()> {
174        Ok(())
175    }
176}
177
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum Codec {
180    Stored,
181    /// Raw deflate, as ZIP stores it.
182    Deflate,
183}
184
185#[derive(Clone, Debug)]
186pub struct Stream {
187    /// Where the file's data begins. The headers before it stay untouched
188    /// until the unit is committed, so the archive still parses on resume.
189    pub data_start: u64,
190    /// Length of the data in the archive.
191    pub packed: u64,
192    pub codec: Codec,
193    /// CRC-32 of the output, if the format records one.
194    pub crc: Option<u32>,
195}
196
197pub trait Worker {
198    /// Decodes `unit`, handing each item to `sink` in order.
199    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
200}
201
202pub trait Sink {
203    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
204}
205
206pub struct Opened {
207    pub name: &'static str,
208    pub format: Box<dyn Format>,
209    pub units: Vec<Unit>,
210    /// Everything from here to the end is saved before anything is reclaimed.
211    pub tail_start: u64,
212}
213
214/// Parses the archive. `resume` carries the format recorded by an earlier
215/// run, the tail it saved and its resume point, which a compressed tar is
216/// read from; a fresh run sniffs the format instead. The password is only
217/// needed for encrypted archives; whether it is right is found out when a
218/// unit is decoded (see `Job::check_password`).
219pub fn open(
220    storage: &Arc<Storage>,
221    resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
222    password: Option<&str>,
223) -> Result<Opened> {
224    let (name, tail, point) = match resume {
225        Some((name, tail, point)) => (name.to_string(), Some(tail), point),
226        None => (sniff(storage)?.to_string(), None, None),
227    };
228    match name.as_str() {
229        "zip" => zip::open(storage, tail, password),
230        "7z" => sevenz::open(storage, tail, password),
231        "tar" => tar::open(storage, tail),
232        #[cfg(feature = "rar")]
233        RAR => rar::open(storage, tail.is_some(), password),
234        #[cfg(not(feature = "rar"))]
235        RAR => Err(no_rar()),
236        targz::NAME => targz::open(storage, point),
237        other => bail!("unknown archive format '{other}' in the journal"),
238    }
239}
240
241/// What turns the first `keep` bytes of a half-extracted archive back into an
242/// archive any tool opens.
243pub struct NewIndex {
244    /// Written at `keep`.
245    pub append: Vec<u8>,
246    /// Written over bytes below `keep`: the 7z start header, which has to
247    /// point at the new header.
248    pub patches: Vec<(u64, Vec<u8>)>,
249}
250
251/// Builds the [`NewIndex`] for the entries that start below `keep`, from
252/// the tail an earlier run saved. `hard_links` are tar links already cut off
253/// whose targets are still in the archive.
254pub fn rebuild_index(
255    format: &str,
256    storage: &Storage,
257    tail: Arc<Tail>,
258    keep: u64,
259    hard_links: &[(&Path, &Path)],
260) -> Result<NewIndex> {
261    let (append, patches) = match format {
262        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
263        "tar" => (tar::closing(hard_links)?, Vec::new()),
264        "7z" => {
265            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
266            (header, vec![(0, start)])
267        }
268        // No index: the last volume left only needs its end header back.
269        #[cfg(feature = "rar")]
270        RAR => (rar::closing(storage, keep)?, Vec::new()),
271        #[cfg(not(feature = "rar"))]
272        RAR => return Err(no_rar()),
273        other => bail!("unknown archive format '{other}' in the journal"),
274    };
275    Ok(NewIndex { append, patches })
276}
277
278fn sniff(storage: &Storage) -> Result<&'static str> {
279    let mut head = [0u8; 512];
280    let mut r = storage.reader(None);
281    let n = read_up_to(&mut r, &mut head)?;
282    let head = &head[..n];
283    let starts = |magic: &[u8]| head.starts_with(magic);
284    if starts(b"7z\xBC\xAF\x27\x1C") {
285        return Ok("7z");
286    }
287    let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
288    if is_tar(head) {
289        return Ok("tar");
290    }
291    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
292    if starts(b"\x1F\x8B") {
293        // Look inside: a plain .gz of one file is not an archive.
294        let mut gz = resumable::Gzip::new(
295            storage.reader(None),
296            storage.original_len(),
297            &resumable::GzPoint::start(),
298        )?;
299        let mut first = [0u8; 512];
300        let mut n = 0;
301        while n < first.len() {
302            match gz
303                .read(&mut first[n..])
304                .context("reading the start of the compressed stream")?
305            {
306                0 => break,
307                k => n += k,
308            }
309        }
310        let named = [".tar.gz", ".tgz", ".taz"]
311            .iter()
312            .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
313        if is_tar(&first[..n]) || named {
314            return Ok(targz::NAME);
315        }
316        bail!(
317            "this is a gzip-compressed file that does not contain a tar archive. Only \
318             compressed tar archives (.tar.gz) can be extracted"
319        );
320    }
321    if starts(b"\x28\xB5\x2F\xFD") || starts(b"\xFD7zXZ\x00") || starts(b"BZh") {
322        bail!(
323            "this is a compressed stream (.zst, .xz or .bz2). In-place extraction of these \
324             compressed streams is not supported yet"
325        );
326    }
327    if starts(b"Rar!\x1A\x07") {
328        return Ok(RAR);
329    }
330    if ext.ends_with(".tar") || ext.contains(".tar.") {
331        return Ok("tar");
332    }
333    // Anything else gets a ZIP parse: self-extracting archives put an
334    // executable in front, so the signature isn't at the start.
335    Ok("zip")
336}
337
338fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
339    let mut n = 0;
340    while n < buf.len() {
341        match r.read(&mut buf[n..])? {
342            0 => break,
343            k => n += k,
344        }
345    }
346    Ok(n)
347}
348
349/// Turns an archive member name into a relative path that can't leave the
350/// output folder. Leading slashes are dropped, as tar does; `..`, drive
351/// letters and NUL bytes are refused.
352pub fn safe_path(name: &str) -> Option<PathBuf> {
353    if name.contains('\0') {
354        return None;
355    }
356    let mut out = PathBuf::new();
357    for part in name.split(['/', '\\']) {
358        match part {
359            "" | "." => {}
360            ".." => return None,
361            p if p.contains(':') => return None,
362            p => out.push(p),
363        }
364    }
365    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
366    (clean && !out.as_os_str().is_empty()).then_some(out)
367}
368
369/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
370/// the Windows attributes.
371fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
372    (attrs & 0x8000 != 0).then_some(attrs >> 16)
373}
374
375const S_IFMT: u32 = 0o170000;
376const S_IFLNK: u32 = 0o120000;
377
378fn is_symlink_mode(mode: Option<u32>) -> bool {
379    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
380}