1#[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 Symlink,
31 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 pub start: u64,
49 pub key: usize,
51 pub items: Vec<Item>,
52 pub encrypted: bool,
54}
55
56#[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#[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#[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
94pub const RAR: &str = "rar";
96
97pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
100
101pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum PasswordCheck {
114 Sample,
117 Headers,
120 WholeUnit,
123}
124
125impl Unit {
126 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 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
138
139 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
143 Ok(None)
144 }
145
146 fn solid(&self) -> Option<&Solid> {
150 None
151 }
152
153 fn serial(&self) -> bool {
158 false
159 }
160
161 fn refuses_in_place(&self) -> Option<String> {
164 None
165 }
166
167 fn password_check(&self) -> PasswordCheck {
168 PasswordCheck::Sample
169 }
170
171 fn prove_password(&self) -> Result<()> {
174 Ok(())
175 }
176}
177
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
179pub enum Codec {
180 Stored,
181 Deflate,
183}
184
185#[derive(Clone, Debug)]
186pub struct Stream {
187 pub data_start: u64,
190 pub packed: u64,
192 pub codec: Codec,
193 pub crc: Option<u32>,
195}
196
197pub trait Worker {
198 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 pub tail_start: u64,
212}
213
214pub 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
241pub struct NewIndex {
244 pub append: Vec<u8>,
246 pub patches: Vec<(u64, Vec<u8>)>,
249}
250
251pub 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 #[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 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 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
349pub 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
369fn 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}