1#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11pub mod targz;
12pub mod tarxz;
13mod xz;
14mod zip;
15
16use std::io::Read;
17use std::path::{Component, Path, PathBuf};
18use std::sync::Arc;
19use std::time::SystemTime;
20
21use anyhow::{Context, Result, bail};
22
23use crate::journal::Resume;
24use storage::{Storage, Tail};
25use targz::Event;
26use targz::Profile;
27
28pub trait SolidStream: Send + Sync {
34 fn profile(&self) -> &targz::Profile;
36 fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
40}
41
42pub trait SolidWalker {
45 fn next(&mut self, max: usize) -> Result<Event<'_>>;
48 fn point(&self) -> Result<Resume>;
51 fn point_byte(&self) -> Option<u64>;
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Kind {
58 File,
59 Dir,
60 Symlink,
62 HardLink(PathBuf),
65}
66
67#[derive(Clone, Debug)]
68pub struct Item {
69 pub path: PathBuf,
70 pub size: u64,
71 pub kind: Kind,
72 pub mode: Option<u32>,
73 pub mtime: Option<SystemTime>,
74}
75
76pub struct Unit {
77 pub start: u64,
80 pub key: usize,
82 pub items: Vec<Item>,
83 pub encrypted: bool,
85}
86
87#[derive(Debug)]
90pub struct PasswordNeeded;
91
92impl std::fmt::Display for PasswordNeeded {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.write_str("this archive is password protected")
95 }
96}
97
98impl std::error::Error for PasswordNeeded {}
99
100#[derive(Debug)]
102pub struct WrongPassword;
103
104impl std::fmt::Display for WrongPassword {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 f.write_str("incorrect password")
107 }
108}
109
110impl std::error::Error for WrongPassword {}
111
112#[derive(Debug)]
115pub struct Damaged(pub anyhow::Error);
116
117impl std::fmt::Display for Damaged {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 write!(f, "{:#}", self.0)
120 }
121}
122
123impl std::error::Error for Damaged {}
124
125#[derive(Debug)]
130pub struct Unsupported(pub anyhow::Error);
131
132impl std::fmt::Display for Unsupported {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 write!(f, "{:#}", self.0)
135 }
136}
137
138impl std::error::Error for Unsupported {}
139
140pub const RAR: &str = "rar";
142
143pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
146
147pub fn no_rar() -> anyhow::Error {
149 anyhow::anyhow!(
150 "this build of HatchZip does not include RAR support, and the archive was not \
151 modified. Download the release build from hatchzip.dev or \
152 github.com/xevrion/hatchzip/releases"
153 )
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum PasswordCheck {
160 Sample,
163 Headers,
166 WholeUnit,
169}
170
171impl Unit {
172 pub fn size(&self) -> u64 {
174 self.items
175 .iter()
176 .fold(0u64, |sum, i| sum.saturating_add(i.size))
177 }
178}
179
180pub trait Format: Send + Sync {
181 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
184
185 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
189 Ok(None)
190 }
191
192 fn solid(&self) -> Option<&dyn SolidStream> {
196 None
197 }
198
199 fn serial(&self) -> bool {
204 false
205 }
206
207 fn refuses_in_place(&self) -> Option<String> {
210 None
211 }
212
213 fn password_check(&self) -> PasswordCheck {
214 PasswordCheck::Sample
215 }
216
217 fn prove_password(&self) -> Result<()> {
220 Ok(())
221 }
222}
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
225pub enum Codec {
226 Stored,
227 Deflate,
229}
230
231#[derive(Clone, Debug)]
232pub struct Stream {
233 pub data_start: u64,
236 pub packed: u64,
238 pub codec: Codec,
239 pub crc: Option<u32>,
241}
242
243pub trait Worker {
244 fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
246}
247
248pub trait Sink {
249 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
250}
251
252pub struct Opened {
253 pub name: &'static str,
254 pub format: Box<dyn Format>,
255 pub units: Vec<Unit>,
256 pub tail_start: u64,
258}
259
260pub fn open(
266 storage: &Arc<Storage>,
267 resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
268 password: Option<&str>,
269) -> Result<Opened> {
270 let (name, tail, point) = match resume {
271 Some((name, tail, point)) => (name.to_string(), Some(tail), point),
272 None => (sniff(storage)?.to_string(), None, None),
273 };
274 match name.as_str() {
275 "zip" => zip::open(storage, tail, password),
276 "7z" => sevenz::open(storage, tail, password),
277 "tar" => tar::open(storage, tail),
278 #[cfg(feature = "rar")]
279 RAR => rar::open(storage, tail.is_some(), password),
280 #[cfg(not(feature = "rar"))]
281 RAR => Err(no_rar()),
282 targz::NAME => targz::open(storage, point),
283 tarxz::NAME => tarxz::open(storage, point),
284 other => bail!("unknown archive format '{other}' in the journal"),
285 }
286}
287
288pub struct NewIndex {
291 pub append: Vec<u8>,
293 pub patches: Vec<(u64, Vec<u8>)>,
296}
297
298fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
304 let from_byte = from.map_or(0, |r| r.bit / 8);
305 let mut w = solid.walk(from)?;
306 let mut items = Vec::new();
307 let mut p = Profile::default();
308 let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
309 loop {
310 match w.next(usize::MAX)? {
311 Event::Entry { item, .. } => {
312 if item.kind == Kind::File {
313 size = item.size;
314 }
315 items.push(item);
316 }
317 Event::Data(d) => out += d.len() as u64,
318 Event::FileEnd => out += size.next_multiple_of(4096) - size,
319 Event::Point => {
320 let consumed = w
321 .point_byte()
322 .unwrap_or(from_byte)
323 .saturating_sub(from_byte);
324 p.lead = p.lead.max(out as i128 - consumed as i128);
325 p.gap = p.gap.max(out - last);
326 last = out;
327 }
328 Event::End => break,
329 }
330 }
331 p.gap = p.gap.max(out - last);
332 p.files = out;
333 tar::size_links(&mut items);
334 p.links = items
335 .iter()
336 .filter(|i| i.kind != Kind::File)
337 .fold(0u64, |sum, i| {
338 let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
339 sum.saturating_add(size)
340 });
341 Ok((items, p))
342}
343
344pub fn rebuild_index(
348 format: &str,
349 storage: &Storage,
350 tail: Arc<Tail>,
351 keep: u64,
352 hard_links: &[(&Path, &Path)],
353) -> Result<NewIndex> {
354 let (append, patches) = match format {
355 "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
356 "tar" => (tar::closing(hard_links)?, Vec::new()),
357 "7z" => {
358 let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
359 (header, vec![(0, start)])
360 }
361 #[cfg(feature = "rar")]
363 RAR => (rar::closing(storage, keep)?, Vec::new()),
364 #[cfg(not(feature = "rar"))]
365 RAR => return Err(no_rar()),
366 other => bail!("unknown archive format '{other}' in the journal"),
367 };
368 Ok(NewIndex { append, patches })
369}
370
371fn sniff(storage: &Storage) -> Result<&'static str> {
372 let mut head = [0u8; 512];
373 let mut r = storage.reader(None);
374 let n = read_up_to(&mut r, &mut head)?;
375 let head = &head[..n];
376 let starts = |magic: &[u8]| head.starts_with(magic);
377 if starts(b"7z\xBC\xAF\x27\x1C") {
378 return Ok("7z");
379 }
380 let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
381 if is_tar(head) {
382 return Ok("tar");
383 }
384 let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
385 if starts(b"\x1F\x8B") {
386 let mut gz = resumable::Gzip::new(
388 storage.reader(None),
389 storage.original_len(),
390 &resumable::GzPoint::start(),
391 )?;
392 let mut first = [0u8; 512];
393 let mut n = 0;
394 while n < first.len() {
395 match gz
396 .read(&mut first[n..])
397 .context("reading the start of the compressed stream")?
398 {
399 0 => break,
400 k => n += k,
401 }
402 }
403 let named = [".tar.gz", ".tgz", ".taz"]
404 .iter()
405 .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
406 if is_tar(&first[..n]) || named {
407 return Ok(targz::NAME);
408 }
409 bail!(
410 "this is a gzip-compressed file that does not contain a tar archive. Only \
411 compressed tar archives (.tar.gz) can be extracted"
412 );
413 }
414 if starts(b"\xFD7zXZ\x00") {
415 return Ok(tarxz::NAME);
418 }
419 if starts(b"\x28\xB5\x2F\xFD") || starts(b"BZh") {
420 bail!(
421 "this is a compressed stream (.zst or .bz2). In-place extraction of these \
422 compressed streams is not supported yet"
423 );
424 }
425 if starts(b"Rar!\x1A\x07") {
426 return Ok(RAR);
427 }
428 if ext.ends_with(".tar") || ext.contains(".tar.") {
429 return Ok("tar");
430 }
431 Ok("zip")
434}
435
436fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
437 let mut n = 0;
438 while n < buf.len() {
439 match r.read(&mut buf[n..])? {
440 0 => break,
441 k => n += k,
442 }
443 }
444 Ok(n)
445}
446
447pub fn safe_path(name: &str) -> Option<PathBuf> {
451 if name.contains('\0') {
452 return None;
453 }
454 let mut out = PathBuf::new();
455 for part in name.split(['/', '\\']) {
456 match part {
457 "" | "." => {}
458 ".." => return None,
459 p if out.as_os_str().is_empty()
463 && p.len() == 2
464 && p.as_bytes()[0].is_ascii_alphabetic()
465 && p.ends_with(':') =>
466 {
467 return None;
468 }
469 p => out.push(p),
470 }
471 }
472 let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
473 (clean && !out.as_os_str().is_empty()).then_some(out)
474}
475
476fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
479 (attrs & 0x8000 != 0).then_some(attrs >> 16)
480}
481
482const S_IFMT: u32 = 0o170000;
483const S_IFLNK: u32 = 0o120000;
484
485fn is_symlink_mode(mode: Option<u32>) -> bool {
486 mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
487}