Skip to main content

hatchzip_core/
journal.rs

1//! Progress record that makes an interrupted extraction resumable.
2//!
3//! ZIP and 7z keep their index at the end of the archive, which is the first
4//! thing truncation destroys. So before the first byte is reclaimed the tail
5//! of the archive is copied to a side file, and from then on the archive is
6//! parsed through a reader that serves the saved tail at its old offsets.
7
8use 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
20/// Version 3 added `resume`. A version 2 journal can't hold one, so it reads
21/// as is. Older HatchZip builds refuse version 3, which matters: they would
22/// delete a half-extracted file whose archive bytes are already freed.
23const VERSION: u32 = 3;
24/// An extraction that keeps the archive writes version 4, unless a later
25/// version below takes over.
26/// Builds before `keep` existed refuse it, which matters just as much: they
27/// would resume it in place and truncate the archive the user kept. Every
28/// other journal stays at version 3, so an older build can still finish it.
29const KEEP_VERSION: u32 = 4;
30/// An extraction that replaces existing files writes version 5, kept
31/// archive or not, unless a later version below takes over. Builds before
32/// `replace` existed refuse it: they would delete the person's files at the
33/// paths of entries left to do, and a restore would not put the replaced
34/// ones back.
35const REPLACE_VERSION: u32 = 5;
36/// One that keeps some existing files, or both copies of them, writes
37/// version 6. A build before that would finish it by deleting the files the
38/// person chose to keep.
39const CHOOSE_VERSION: u32 = 6;
40/// One with names that differ only in case writes version 7. A build before
41/// that never asks where it may resume such a run, so on a filesystem that
42/// ignores case it would delete an extracted file as its own.
43const 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/// Where extraction of a large file can pick up again after a crash. Its
54/// output up to `written` is flushed to disk, and the archive bytes before
55/// the one holding `bit` may already be freed, so this is the only way back.
56#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
57pub struct Resume {
58    /// The unit, by the offset it starts at.
59    pub unit: u64,
60    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
61    /// holds past this was written after the point and is thrown away.
62    pub written: u64,
63    /// Where decoding restarts, in bits from the start of the archive. Only
64    /// deflate streams ever stop between two bytes.
65    pub bit: u64,
66    /// CRC-32 of the first `written` bytes of output. Unused for a
67    /// compressed tar, whose checksums are per gzip member, in `stream`.
68    pub crc: u32,
69    /// For a compressed tar, where one stream holds every entry: the
70    /// decoder's and the tar parser's state at `bit`. `written` is then how
71    /// much of the entry being extracted is in its part file, if the point
72    /// lies inside a file. Older builds don't know the format and refuse the
73    /// journal before reading this.
74    #[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    /// Every part of the archive with its original length.
83    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    /// The archive is truncated to this once the latest batch is committed.
89    /// Every unit starting at or after it is done.
90    pub committed_len: u64,
91    /// Links are made last, so nothing extracted can be written through one
92    /// and every hard link's target already exists.
93    pub links: Vec<Link>,
94    /// The large file being extracted while its archive bytes are freed, if
95    /// one is in progress. It always belongs to the highest uncommitted unit.
96    #[serde(default)]
97    pub resume: Option<Resume>,
98    /// Every unit was extracted and the final commit was journaled: only the
99    /// archive's removal and the links are left. A compressed stream lands
100    /// here with its archive punched up to its last resume point, so it no
101    /// longer parses from its start and must not be read again.
102    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
103    pub done: bool,
104    /// Set while `restore` turns the archive back into a normal one: the
105    /// bytes it overwrites below `committed_len`, so that an interrupted
106    /// restore can be undone by putting them back and cutting off whatever it
107    /// appended.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
110    /// The extraction keeps the archive: nothing is truncated, punched or
111    /// deleted, and `committed_len` only records progress. A resume keeps
112    /// it too, whatever it is asked.
113    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
114    pub keep: bool,
115    /// The extraction replaces files that were in the output folder before
116    /// it started; see [`crate::replace`].
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub replace: Option<Replace>,
119    /// The folders, inside the output, where entries' names differ only in
120    /// case. A resume and a restore ask about them again, not trusting the
121    /// answer from when the run began; see [`crate::session::check_recorded_case`].
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub case_folders: Vec<PathBuf>,
124    /// Some of those names go outside ASCII, so a system that normalizes
125    /// names may take them for one file, whatever its filesystem says about
126    /// case. Asked again for the same reason.
127    #[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    /// Every file at the path of an entry left to do is in the replaced
134    /// files folder. Until then nothing is extracted, so whatever sits at
135    /// those paths is still the person's.
136    pub moved: bool,
137    /// Existing files, relative to the output, that go back over what was
138    /// extracted at their paths once the extraction completes.
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub keep: Vec<PathBuf>,
141    /// Existing files that go back to their paths once the extraction
142    /// completes, with the extracted copy renamed beside them.
143    #[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    /// The first volume of the archive the side files belong to.
155    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    /// Existing files are moved aside before the first entry is extracted,
199    /// and what to do with each once it completes.
200    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        // The version is checked before the rest is parsed, so a newer layout
252        // gets the version message rather than a confusing parse error.
253        #[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        // Names that differ only in case take the version over from all the
275        // others, so at that version it says nothing about the rest.
276        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            // The top of the output, where names can meet, is an empty path.
286            || 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        // Each is joined to the output folder and renamed, so each must stay
294        // inside it.
295        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    /// The journal is a file next to the archive, so anyone who could put
330    /// the archive there could have written it too. Whatever it names may
331    /// only be what an extraction of this archive touches: the archive's own
332    /// volumes, and links inside the output folder. The output folder itself
333    /// is checked by [`crate::session::check_output`].
334    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        // Restore only ever saves bytes it overwrites inside the archive.
356        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    /// Only an extraction that keeps the archive writes version 4, so older
412    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
413    #[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        // A mismatch means someone edited the file.
434        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    /// Replacing files is version 5 whether the archive is kept or not, and
441    /// no other journal may say it replaces anything.
442    #[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    /// Keeping some existing files is version 6, which an older build
477    /// refuses rather than deleting the files kept.
478    #[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    /// Folders where names differ only in case come with their own version,
498    /// alongside anything else a run does, and stay inside the output folder.
499    #[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    /// A run started by the previous release resumes; one started by a
522    /// release that knows more is refused before anything is touched.
523    #[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}