1pub mod resumable;
6mod sevenz;
7pub mod storage;
8mod tar;
9mod zip;
10
11use std::io::Read;
12use std::path::{Component, Path, PathBuf};
13use std::sync::Arc;
14use std::time::SystemTime;
15
16use anyhow::{Result, bail};
17
18use storage::{Storage, Tail};
19
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Kind {
22 File,
23 Dir,
24 Symlink,
26 HardLink(PathBuf),
29}
30
31#[derive(Clone, Debug)]
32pub struct Item {
33 pub path: PathBuf,
34 pub size: u64,
35 pub kind: Kind,
36 pub mode: Option<u32>,
37 pub mtime: Option<SystemTime>,
38}
39
40pub struct Unit {
41 pub start: u64,
44 pub key: usize,
46 pub items: Vec<Item>,
47 pub encrypted: bool,
49}
50
51#[derive(Debug)]
54pub struct PasswordNeeded;
55
56impl std::fmt::Display for PasswordNeeded {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.write_str("this archive is password protected")
59 }
60}
61
62impl std::error::Error for PasswordNeeded {}
63
64#[derive(Debug)]
66pub struct WrongPassword;
67
68impl std::fmt::Display for WrongPassword {
69 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70 f.write_str("incorrect password")
71 }
72}
73
74impl std::error::Error for WrongPassword {}
75
76impl Unit {
77 pub fn size(&self) -> u64 {
78 self.items.iter().map(|i| i.size).sum()
79 }
80}
81
82pub trait Format: Send + Sync {
83 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
86
87 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
91 Ok(None)
92 }
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Codec {
97 Stored,
98 Deflate,
100}
101
102#[derive(Clone, Debug)]
103pub struct Stream {
104 pub data_start: u64,
107 pub packed: u64,
109 pub codec: Codec,
110 pub crc: Option<u32>,
112}
113
114pub trait Worker {
115 fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
117}
118
119pub trait Sink {
120 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
121}
122
123pub struct Opened {
124 pub name: &'static str,
125 pub format: Box<dyn Format>,
126 pub units: Vec<Unit>,
127 pub tail_start: u64,
129}
130
131pub fn open(
136 storage: &Arc<Storage>,
137 resume: Option<(&str, Arc<Tail>)>,
138 password: Option<&str>,
139) -> Result<Opened> {
140 let (name, tail) = match resume {
141 Some((name, tail)) => (name.to_string(), Some(tail)),
142 None => (sniff(storage)?.to_string(), None),
143 };
144 match name.as_str() {
145 "zip" => zip::open(storage, tail, password),
146 "7z" => sevenz::open(storage, tail, password),
147 "tar" => tar::open(storage, tail),
148 other => bail!("unknown archive format '{other}' in the journal"),
149 }
150}
151
152pub struct NewIndex {
155 pub append: Vec<u8>,
157 pub patches: Vec<(u64, Vec<u8>)>,
160}
161
162pub fn rebuild_index(
166 format: &str,
167 storage: &Storage,
168 tail: Arc<Tail>,
169 keep: u64,
170 hard_links: &[(&Path, &Path)],
171) -> Result<NewIndex> {
172 let (append, patches) = match format {
173 "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
174 "tar" => (tar::closing(hard_links)?, Vec::new()),
175 "7z" => {
176 let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
177 (header, vec![(0, start)])
178 }
179 other => bail!("unknown archive format '{other}' in the journal"),
180 };
181 Ok(NewIndex { append, patches })
182}
183
184fn sniff(storage: &Storage) -> Result<&'static str> {
185 let mut head = [0u8; 512];
186 let mut r = storage.reader(None);
187 let n = read_up_to(&mut r, &mut head)?;
188 let head = &head[..n];
189 let starts = |magic: &[u8]| head.starts_with(magic);
190 if starts(b"7z\xBC\xAF\x27\x1C") {
191 return Ok("7z");
192 }
193 if head.len() >= 263 && &head[257..262] == b"ustar" {
194 return Ok("tar");
195 }
196 if starts(b"\x1F\x8B")
197 || starts(b"\x28\xB5\x2F\xFD")
198 || starts(b"\xFD7zXZ\x00")
199 || starts(b"BZh")
200 {
201 bail!(
202 "this is a compressed stream (.gz, .zst, .xz or .bz2). In-place extraction of \
203 compressed streams is not supported"
204 );
205 }
206 if starts(b"Rar!\x1A\x07") {
207 bail!("RAR archives are not supported");
208 }
209 let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
210 if ext.ends_with(".tar") || ext.contains(".tar.") {
211 return Ok("tar");
212 }
213 Ok("zip")
216}
217
218fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
219 let mut n = 0;
220 while n < buf.len() {
221 match r.read(&mut buf[n..])? {
222 0 => break,
223 k => n += k,
224 }
225 }
226 Ok(n)
227}
228
229pub fn safe_path(name: &str) -> Option<PathBuf> {
233 if name.contains('\0') {
234 return None;
235 }
236 let mut out = PathBuf::new();
237 for part in name.split(['/', '\\']) {
238 match part {
239 "" | "." => {}
240 ".." => return None,
241 p if p.contains(':') => return None,
242 p => out.push(p),
243 }
244 }
245 let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
246 (clean && !out.as_os_str().is_empty()).then_some(out)
247}
248
249fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
252 (attrs & 0x8000 != 0).then_some(attrs >> 16)
253}
254
255const S_IFMT: u32 = 0o170000;
256const S_IFLNK: u32 = 0o120000;
257
258fn is_symlink_mode(mode: Option<u32>) -> bool {
259 mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
260}