1pub 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 Symlink,
29 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 pub start: u64,
47 pub key: usize,
49 pub items: Vec<Item>,
50 pub encrypted: bool,
52}
53
54#[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#[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#[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 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
102
103 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
107 Ok(None)
108 }
109
110 fn solid(&self) -> Option<&Solid> {
114 None
115 }
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub enum Codec {
120 Stored,
121 Deflate,
123}
124
125#[derive(Clone, Debug)]
126pub struct Stream {
127 pub data_start: u64,
130 pub packed: u64,
132 pub codec: Codec,
133 pub crc: Option<u32>,
135}
136
137pub trait Worker {
138 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 pub tail_start: u64,
152}
153
154pub 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
177pub struct NewIndex {
180 pub append: Vec<u8>,
182 pub patches: Vec<(u64, Vec<u8>)>,
185}
186
187pub 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 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 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
280pub 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
300fn 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}