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