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, and only it does.
25/// Builds before `keep` existed refuse it, which matters just as much: they
26/// would resume it in place and truncate the archive the user kept. Every
27/// other journal stays at version 3, so an older build can still finish it.
28const KEEP_VERSION: u32 = 4;
29/// An extraction that replaces existing files writes version 5, kept
30/// archive or not. Builds before `replace` existed refuse it: they would
31/// delete the person's files at the paths of entries left to do, and a
32/// restore would not put the replaced ones back.
33const REPLACE_VERSION: u32 = 5;
34/// One that keeps some existing files, or both copies of them, writes
35/// version 6. A build before that would finish it by deleting the files the
36/// person chose to keep.
37const 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/// Where extraction of a large file can pick up again after a crash. Its
48/// output up to `written` is flushed to disk, and the archive bytes before
49/// the one holding `bit` may already be freed, so this is the only way back.
50#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
51pub struct Resume {
52    /// The unit, by the offset it starts at.
53    pub unit: u64,
54    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
55    /// holds past this was written after the point and is thrown away.
56    pub written: u64,
57    /// Where decoding restarts, in bits from the start of the archive. Only
58    /// deflate streams ever stop between two bytes.
59    pub bit: u64,
60    /// CRC-32 of the first `written` bytes of output. Unused for a
61    /// compressed tar, whose checksums are per gzip member, in `stream`.
62    pub crc: u32,
63    /// For a compressed tar, where one stream holds every entry: the
64    /// decoder's and the tar parser's state at `bit`. `written` is then how
65    /// much of the entry being extracted is in its part file, if the point
66    /// lies inside a file. Older builds don't know the format and refuse the
67    /// journal before reading this.
68    #[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    /// Every part of the archive with its original length.
77    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    /// The archive is truncated to this once the latest batch is committed.
83    /// Every unit starting at or after it is done.
84    pub committed_len: u64,
85    /// Links are made last, so nothing extracted can be written through one
86    /// and every hard link's target already exists.
87    pub links: Vec<Link>,
88    /// The large file being extracted while its archive bytes are freed, if
89    /// one is in progress. It always belongs to the highest uncommitted unit.
90    #[serde(default)]
91    pub resume: Option<Resume>,
92    /// Set while `restore` turns the archive back into a normal one: the
93    /// bytes it overwrites below `committed_len`, so that an interrupted
94    /// restore can be undone by putting them back and cutting off whatever it
95    /// appended.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
98    /// The extraction keeps the archive: nothing is truncated, punched or
99    /// deleted, and `committed_len` only records progress. A resume keeps
100    /// it too, whatever it is asked.
101    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
102    pub keep: bool,
103    /// The extraction replaces files that were in the output folder before
104    /// it started; see [`crate::replace`].
105    #[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    /// Every file at the path of an entry left to do is in the replaced
112    /// files folder. Until then nothing is extracted, so whatever sits at
113    /// those paths is still the person's.
114    pub moved: bool,
115    /// Existing files, relative to the output, that go back over what was
116    /// extracted at their paths once the extraction completes.
117    #[serde(default, skip_serializing_if = "Vec::is_empty")]
118    pub keep: Vec<PathBuf>,
119    /// Existing files that go back to their paths once the extraction
120    /// completes, with the extracted copy renamed beside them.
121    #[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    /// The first volume of the archive the side files belong to.
133    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    /// Existing files are moved aside before the first entry is extracted,
177    /// and what to do with each once it completes.
178    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        // The version is checked before the rest is parsed, so a newer layout
223        // gets the version message rather than a confusing parse error.
224        #[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        // Each is joined to the output folder and renamed, so each must stay
253        // inside it.
254        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    /// The journal is a file next to the archive, so anyone who could put
285    /// the archive there could have written it too. Whatever it names may
286    /// only be what an extraction of this archive touches: the archive's own
287    /// volumes, and links inside the output folder. The output folder itself
288    /// is checked by [`crate::session::check_output`].
289    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        // Restore only ever saves bytes it overwrites inside the archive.
311        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    /// Only an extraction that keeps the archive writes version 4, so older
367    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
368    #[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        // A mismatch means someone edited the file.
389        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    /// Replacing files is version 5 whether the archive is kept or not, and
396    /// no other journal may say it replaces anything.
397    #[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    /// Keeping some existing files is version 6, which an older build
432    /// refuses rather than deleting the files kept.
433    #[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    /// A run started by the previous release resumes; one started by a
453    /// release that knows more is refused before anything is touched.
454    #[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}