1use std::fs;
9use std::io::{self, Read, Seek, SeekFrom};
10use std::path::{Component, Path, PathBuf};
11use std::sync::Arc;
12
13use anyhow::{Context, Result, anyhow, bail};
14use serde::{Deserialize, Serialize};
15
16use crate::archive::storage::{self, Storage, Tail};
17pub use crate::archive::targz::{StreamPoint, TarAt};
18use crate::fsutil;
19
20const VERSION: u32 = 3;
24const KEEP_VERSION: u32 = 4;
29const READABLE: [u32; 3] = [2, 3, 4];
30
31#[derive(Serialize, Deserialize, Clone)]
32pub struct Link {
33 pub path: PathBuf,
34 pub target: PathBuf,
35 pub hard: bool,
36}
37
38#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
42pub struct Resume {
43 pub unit: u64,
45 pub written: u64,
48 pub bit: u64,
51 pub crc: u32,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub stream: Option<Box<StreamPoint>>,
61}
62
63#[derive(Serialize, Deserialize)]
64pub struct Journal {
65 pub version: u32,
66 pub format: String,
67 pub parts: Vec<(PathBuf, u64)>,
69 pub tail_start: u64,
70 pub tail_crc: u32,
71 pub output: PathBuf,
72 pub total_size: u64,
73 pub committed_len: u64,
76 pub links: Vec<Link>,
79 #[serde(default)]
82 pub resume: Option<Resume>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub restoring: Option<Vec<(u64, Vec<u8>)>>,
89 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
93 pub keep: bool,
94}
95
96pub struct Paths {
97 pub archive: PathBuf,
99 pub journal: PathBuf,
100 pub tail: PathBuf,
101}
102
103impl Paths {
104 pub fn for_archive(archive: &Path) -> Self {
105 let with = |suffix: &str| {
106 let mut s = archive.as_os_str().to_owned();
107 s.push(suffix);
108 PathBuf::from(s)
109 };
110 Self {
111 archive: archive.to_path_buf(),
112 journal: with(".hatchzip"),
113 tail: with(".hatchzip-tail"),
114 }
115 }
116
117 pub fn exists(&self) -> bool {
118 self.journal.exists()
119 }
120
121 pub fn remove(&self) -> Result<()> {
122 crate::chosen::forget(&self.archive);
123 for p in [&self.tail, &self.journal] {
124 match fs::remove_file(p) {
125 Err(e) if e.kind() != io::ErrorKind::NotFound => {
126 return Err(e).with_context(|| format!("removing {}", p.display()));
127 }
128 _ => {}
129 }
130 }
131 Ok(())
132 }
133}
134
135pub struct Plan {
136 pub format: &'static str,
137 pub tail_start: u64,
138 pub output: PathBuf,
139 pub total_size: u64,
140 pub keep: bool,
141}
142
143fn version_for(keep: bool) -> u32 {
144 if keep { KEEP_VERSION } else { VERSION }
145}
146
147impl Journal {
148 pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
149 let mut tail = Vec::new();
150 let mut r = storage.reader(None);
151 r.seek(SeekFrom::Start(plan.tail_start))?;
152 r.read_to_end(&mut tail)?;
153 fsutil::write_atomic(&paths.tail, &tail)?;
154 let journal = Self {
155 version: version_for(plan.keep),
156 format: plan.format.to_string(),
157 parts: storage.record(),
158 tail_start: plan.tail_start,
159 tail_crc: crc32fast::hash(&tail),
160 output: plan.output,
161 total_size: plan.total_size,
162 committed_len: storage.original_len(),
163 links: Vec::new(),
164 resume: None,
165 restoring: None,
166 keep: plan.keep,
167 };
168 journal.save(paths)?;
169 Ok(journal)
170 }
171
172 pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
173 let bytes = fs::read(&paths.journal)
174 .with_context(|| format!("reading {}", paths.journal.display()))?;
175 #[derive(Deserialize)]
178 struct Versioned {
179 version: u32,
180 }
181 let version = serde_json::from_slice::<Versioned>(&bytes)
182 .with_context(|| format!("{} is damaged", paths.journal.display()))?
183 .version;
184 if !READABLE.contains(&version) {
185 let which = if version > VERSION {
186 "a newer"
187 } else {
188 "an older"
189 };
190 bail!(
191 "{} was written by {which} HatchZip version (journal format {version}); \
192 complete the extraction with that version",
193 paths.journal.display()
194 );
195 }
196 let mut journal: Self = serde_json::from_slice(&bytes)
197 .with_context(|| format!("{} is damaged", paths.journal.display()))?;
198 if journal.keep != (version == KEEP_VERSION) {
199 bail!("{} is damaged", paths.journal.display());
200 }
201 journal.version = version_for(journal.keep);
202 journal.check_bound(paths)?;
203 let tail =
204 fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
205 let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
206 if crc32fast::hash(&tail) != journal.tail_crc
207 || journal.tail_start + tail.len() as u64 != len
208 {
209 bail!("{} does not match its journal", paths.tail.display());
210 }
211 let tail = Arc::new(Tail {
212 start: journal.tail_start,
213 bytes: tail,
214 });
215 Ok((journal, tail))
216 }
217
218 pub fn save(&self, paths: &Paths) -> Result<()> {
219 fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
220 }
221
222 fn check_bound(&self, paths: &Paths) -> Result<()> {
228 let foreign = || {
229 anyhow!(
230 "{} does not belong to {}, so it was not used and nothing was modified. If the \
231 archive was moved during an extraction, move it back to resume; otherwise \
232 delete {} and {}",
233 paths.journal.display(),
234 paths.archive.display(),
235 paths.journal.display(),
236 paths.tail.display()
237 )
238 };
239 if self.parts.is_empty() {
240 return Err(foreign());
241 }
242 for (i, (part, _)) in self.parts.iter().enumerate() {
243 if !storage::volume_path(&paths.archive, i).is_some_and(|v| fsutil::same_path(&v, part))
244 {
245 return Err(foreign());
246 }
247 }
248 let len: u64 = self.parts.iter().map(|(_, l)| l).sum();
250 let within = |(at, bytes): &(u64, Vec<u8>)| {
251 at.checked_add(bytes.len() as u64)
252 .is_some_and(|end| end <= len)
253 };
254 if self
255 .restoring
256 .as_ref()
257 .is_some_and(|r| !r.iter().all(within))
258 {
259 bail!(
260 "{} is damaged: it records bytes outside the archive. Nothing was modified",
261 paths.journal.display()
262 );
263 }
264 let inside = |p: &Path| {
265 p.components().next().is_some()
266 && p.components().all(|c| matches!(c, Component::Normal(_)))
267 };
268 for link in &self.links {
269 if !inside(&link.path) || (link.hard && !inside(&link.target)) {
270 bail!(
271 "{} is damaged: it records a link outside the output folder. Nothing was \
272 modified",
273 paths.journal.display()
274 );
275 }
276 }
277 Ok(())
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 fn write(dir: &Path, version: u32) -> Paths {
286 write_with(dir, version, "")
287 }
288
289 fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
290 let paths = Paths::for_archive(&dir.join("game.zip"));
291 let tail = b"saved tail";
292 fs::write(&paths.tail, tail).unwrap();
293 let json = format!(
294 r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
295 "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
296 serde_json::to_string(&dir.join("game.zip")).unwrap(),
297 tail.len(),
298 crc32fast::hash(tail)
299 );
300 fs::write(&paths.journal, json).unwrap();
301 paths
302 }
303
304 #[test]
307 fn keeping_the_archive_is_version_4_and_only_that_is() {
308 let dir =
309 std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
310 fs::create_dir_all(&dir).unwrap();
311
312 let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
313 assert!(journal.keep);
314 assert_eq!(journal.version, KEEP_VERSION);
315 let saved = serde_json::to_string(&journal).unwrap();
316 assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));
317
318 let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
319 assert!(!journal.keep);
320 assert!(
321 !serde_json::to_string(&journal)
322 .unwrap()
323 .contains(r#""keep":"#)
324 );
325
326 assert!(Journal::load(&write(&dir, 4)).is_err());
328 assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());
329
330 fs::remove_dir_all(&dir).unwrap();
331 }
332
333 #[test]
336 fn reads_version_2_and_refuses_newer_journals() {
337 let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
338 fs::create_dir_all(&dir).unwrap();
339
340 let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
341 assert_eq!(journal.resume, None);
342 assert_eq!(journal.version, VERSION);
343
344 let err = Journal::load(&write(&dir, KEEP_VERSION + 1)).err().unwrap();
345 assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
346 let err = Journal::load(&write(&dir, 1)).err().unwrap();
347 assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
348
349 fs::remove_dir_all(&dir).unwrap();
350 }
351}