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 REPLACE_VERSION: u32 = 5;
34const CHOOSE_VERSION: u32 = 6;
38const READABLE: [u32; 5] = [2, 3, 4, 5, 6];
39
40#[derive(Serialize, Deserialize, Clone)]
41pub struct Link {
42 pub path: PathBuf,
43 pub target: PathBuf,
44 pub hard: bool,
45}
46
47#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
51pub struct Resume {
52 pub unit: u64,
54 pub written: u64,
57 pub bit: u64,
60 pub crc: u32,
63 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub stream: Option<Box<StreamPoint>>,
70}
71
72#[derive(Serialize, Deserialize)]
73pub struct Journal {
74 pub version: u32,
75 pub format: String,
76 pub parts: Vec<(PathBuf, u64)>,
78 pub tail_start: u64,
79 pub tail_crc: u32,
80 pub output: PathBuf,
81 pub total_size: u64,
82 pub committed_len: u64,
85 pub links: Vec<Link>,
88 #[serde(default)]
91 pub resume: Option<Resume>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub restoring: Option<Vec<(u64, Vec<u8>)>>,
98 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
102 pub keep: bool,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub replace: Option<Replace>,
107}
108
109#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
110pub struct Replace {
111 pub moved: bool,
115 #[serde(default, skip_serializing_if = "Vec::is_empty")]
118 pub keep: Vec<PathBuf>,
119 #[serde(default, skip_serializing_if = "Vec::is_empty")]
122 pub both: Vec<PathBuf>,
123}
124
125impl Replace {
126 fn chose(&self) -> bool {
127 !self.keep.is_empty() || !self.both.is_empty()
128 }
129}
130
131pub struct Paths {
132 pub archive: PathBuf,
134 pub journal: PathBuf,
135 pub tail: PathBuf,
136}
137
138impl Paths {
139 pub fn for_archive(archive: &Path) -> Self {
140 let with = |suffix: &str| {
141 let mut s = archive.as_os_str().to_owned();
142 s.push(suffix);
143 PathBuf::from(s)
144 };
145 Self {
146 archive: archive.to_path_buf(),
147 journal: with(".hatchzip"),
148 tail: with(".hatchzip-tail"),
149 }
150 }
151
152 pub fn exists(&self) -> bool {
153 self.journal.exists()
154 }
155
156 pub fn remove(&self) -> Result<()> {
157 crate::chosen::forget(&self.archive);
158 for p in [&self.tail, &self.journal] {
159 match fs::remove_file(p) {
160 Err(e) if e.kind() != io::ErrorKind::NotFound => {
161 return Err(e).with_context(|| format!("removing {}", p.display()));
162 }
163 _ => {}
164 }
165 }
166 Ok(())
167 }
168}
169
170pub struct Plan {
171 pub format: &'static str,
172 pub tail_start: u64,
173 pub output: PathBuf,
174 pub total_size: u64,
175 pub keep: bool,
176 pub replace: Option<Replace>,
179}
180
181fn version_for(keep: bool, replace: Option<&Replace>) -> u32 {
182 if replace.is_some_and(Replace::chose) {
183 CHOOSE_VERSION
184 } else if replace.is_some() {
185 REPLACE_VERSION
186 } else if keep {
187 KEEP_VERSION
188 } else {
189 VERSION
190 }
191}
192
193impl Journal {
194 pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
195 let mut tail = Vec::new();
196 let mut r = storage.reader(None);
197 r.seek(SeekFrom::Start(plan.tail_start))?;
198 r.read_to_end(&mut tail)?;
199 fsutil::write_atomic(&paths.tail, &tail)?;
200 let journal = Self {
201 version: version_for(plan.keep, plan.replace.as_ref()),
202 format: plan.format.to_string(),
203 parts: storage.record(),
204 tail_start: plan.tail_start,
205 tail_crc: crc32fast::hash(&tail),
206 output: plan.output,
207 total_size: plan.total_size,
208 committed_len: storage.original_len(),
209 links: Vec::new(),
210 resume: None,
211 restoring: None,
212 keep: plan.keep,
213 replace: plan.replace,
214 };
215 journal.save(paths)?;
216 Ok(journal)
217 }
218
219 pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
220 let bytes = fs::read(&paths.journal)
221 .with_context(|| format!("reading {}", paths.journal.display()))?;
222 #[derive(Deserialize)]
225 struct Versioned {
226 version: u32,
227 }
228 let version = serde_json::from_slice::<Versioned>(&bytes)
229 .with_context(|| format!("{} is damaged", paths.journal.display()))?
230 .version;
231 if !READABLE.contains(&version) {
232 let which = if version > VERSION {
233 "a newer"
234 } else {
235 "an older"
236 };
237 bail!(
238 "{} was written by {which} HatchZip version (journal format {version}); \
239 complete the extraction with that version",
240 paths.journal.display()
241 );
242 }
243 let mut journal: Self = serde_json::from_slice(&bytes)
244 .with_context(|| format!("{} is damaged", paths.journal.display()))?;
245 let replaces = version == REPLACE_VERSION || version == CHOOSE_VERSION;
246 if journal.replace.is_some() != replaces
247 || journal.replace.as_ref().is_some_and(Replace::chose) != (version == CHOOSE_VERSION)
248 || (!replaces && journal.keep != (version == KEEP_VERSION))
249 {
250 bail!("{} is damaged", paths.journal.display());
251 }
252 let inside = |p: &PathBuf| {
255 p.components().next().is_some()
256 && p.components().all(|c| matches!(c, Component::Normal(_)))
257 };
258 if let Some(r) = &journal.replace
259 && !r.keep.iter().chain(&r.both).all(inside)
260 {
261 bail!("{} is damaged", paths.journal.display());
262 }
263 journal.version = version_for(journal.keep, journal.replace.as_ref());
264 journal.check_bound(paths)?;
265 let tail =
266 fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
267 let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
268 if crc32fast::hash(&tail) != journal.tail_crc
269 || journal.tail_start + tail.len() as u64 != len
270 {
271 bail!("{} does not match its journal", paths.tail.display());
272 }
273 let tail = Arc::new(Tail {
274 start: journal.tail_start,
275 bytes: tail,
276 });
277 Ok((journal, tail))
278 }
279
280 pub fn save(&self, paths: &Paths) -> Result<()> {
281 fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
282 }
283
284 fn check_bound(&self, paths: &Paths) -> Result<()> {
290 let foreign = || {
291 anyhow!(
292 "{} does not belong to {}, so it was not used and nothing was modified. If the \
293 archive was moved during an extraction, move it back to resume; otherwise \
294 delete {} and {}",
295 paths.journal.display(),
296 paths.archive.display(),
297 paths.journal.display(),
298 paths.tail.display()
299 )
300 };
301 if self.parts.is_empty() {
302 return Err(foreign());
303 }
304 for (i, (part, _)) in self.parts.iter().enumerate() {
305 if !storage::volume_path(&paths.archive, i).is_some_and(|v| fsutil::same_path(&v, part))
306 {
307 return Err(foreign());
308 }
309 }
310 let len: u64 = self.parts.iter().map(|(_, l)| l).sum();
312 let within = |(at, bytes): &(u64, Vec<u8>)| {
313 at.checked_add(bytes.len() as u64)
314 .is_some_and(|end| end <= len)
315 };
316 if self
317 .restoring
318 .as_ref()
319 .is_some_and(|r| !r.iter().all(within))
320 {
321 bail!(
322 "{} is damaged: it records bytes outside the archive. Nothing was modified",
323 paths.journal.display()
324 );
325 }
326 let inside = |p: &Path| {
327 p.components().next().is_some()
328 && p.components().all(|c| matches!(c, Component::Normal(_)))
329 };
330 for link in &self.links {
331 if !inside(&link.path) || (link.hard && !inside(&link.target)) {
332 bail!(
333 "{} is damaged: it records a link outside the output folder. Nothing was \
334 modified",
335 paths.journal.display()
336 );
337 }
338 }
339 Ok(())
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 fn write(dir: &Path, version: u32) -> Paths {
348 write_with(dir, version, "")
349 }
350
351 fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
352 let paths = Paths::for_archive(&dir.join("game.zip"));
353 let tail = b"saved tail";
354 fs::write(&paths.tail, tail).unwrap();
355 let json = format!(
356 r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
357 "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
358 serde_json::to_string(&dir.join("game.zip")).unwrap(),
359 tail.len(),
360 crc32fast::hash(tail)
361 );
362 fs::write(&paths.journal, json).unwrap();
363 paths
364 }
365
366 #[test]
369 fn keeping_the_archive_is_version_4_and_only_that_is() {
370 let dir =
371 std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
372 fs::create_dir_all(&dir).unwrap();
373
374 let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
375 assert!(journal.keep);
376 assert_eq!(journal.version, KEEP_VERSION);
377 let saved = serde_json::to_string(&journal).unwrap();
378 assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));
379
380 let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
381 assert!(!journal.keep);
382 assert!(
383 !serde_json::to_string(&journal)
384 .unwrap()
385 .contains(r#""keep":"#)
386 );
387
388 assert!(Journal::load(&write(&dir, 4)).is_err());
390 assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());
391
392 fs::remove_dir_all(&dir).unwrap();
393 }
394
395 #[test]
398 fn replacing_files_is_version_5_and_only_that_is() {
399 let dir =
400 std::env::temp_dir().join(format!("hatchzip-journal-replace-{}", std::process::id()));
401 fs::create_dir_all(&dir).unwrap();
402
403 let moving = r#","replace":{"moved":false}"#;
404 let (journal, _) = Journal::load(&write_with(&dir, 5, moving)).unwrap();
405 assert_eq!(journal.replace, Some(replace(false)));
406 assert!(!journal.keep);
407 let saved = serde_json::to_string(&journal).unwrap();
408 assert!(saved.contains(r#""version":5"#), "{saved}");
409 assert!(!saved.contains("both"), "{saved}");
410
411 let kept = r#","keep":true,"replace":{"moved":true}"#;
412 let (journal, _) = Journal::load(&write_with(&dir, 5, kept)).unwrap();
413 assert!(journal.keep && journal.replace == Some(replace(true)));
414 assert_eq!(journal.version, REPLACE_VERSION);
415
416 assert!(Journal::load(&write(&dir, 5)).is_err());
417 assert!(Journal::load(&write_with(&dir, 3, moving)).is_err());
418 assert!(Journal::load(&write_with(&dir, 4, &format!(r#","keep":true{moving}"#))).is_err());
419
420 fs::remove_dir_all(&dir).unwrap();
421 }
422
423 fn replace(moved: bool) -> Replace {
424 Replace {
425 moved,
426 keep: Vec::new(),
427 both: Vec::new(),
428 }
429 }
430
431 #[test]
434 fn choosing_per_file_is_version_6_and_only_that_is() {
435 let dir =
436 std::env::temp_dir().join(format!("hatchzip-journal-choose-{}", std::process::id()));
437 fs::create_dir_all(&dir).unwrap();
438
439 let chose = r#","replace":{"moved":false,"keep":["a.txt"],"both":["b/c.txt"]}"#;
440 let (journal, _) = Journal::load(&write_with(&dir, 6, chose)).unwrap();
441 let r = journal.replace.as_ref().unwrap();
442 assert_eq!(r.keep, [PathBuf::from("a.txt")]);
443 assert_eq!(r.both, [PathBuf::from("b/c.txt")]);
444 assert_eq!(journal.version, CHOOSE_VERSION);
445
446 assert!(Journal::load(&write_with(&dir, 5, chose)).is_err());
447 assert!(Journal::load(&write_with(&dir, 6, r#","replace":{"moved":false}"#)).is_err());
448
449 fs::remove_dir_all(&dir).unwrap();
450 }
451
452 #[test]
455 fn reads_version_2_and_refuses_newer_journals() {
456 let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
457 fs::create_dir_all(&dir).unwrap();
458
459 let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
460 assert_eq!(journal.resume, None);
461 assert_eq!(journal.version, VERSION);
462
463 let err = Journal::load(&write(&dir, CHOOSE_VERSION + 1))
464 .err()
465 .unwrap();
466 assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
467 let err = Journal::load(&write(&dir, 1)).err().unwrap();
468 assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
469
470 fs::remove_dir_all(&dir).unwrap();
471 }
472}