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