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;
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/// Where extraction of a large file can pick up again after a crash. Its
39/// output up to `written` is flushed to disk, and the archive bytes before
40/// the one holding `bit` may already be freed, so this is the only way back.
41#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
42pub struct Resume {
43    /// The unit, by the offset it starts at.
44    pub unit: u64,
45    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
46    /// holds past this was written after the point and is thrown away.
47    pub written: u64,
48    /// Where decoding restarts, in bits from the start of the archive. Only
49    /// deflate streams ever stop between two bytes.
50    pub bit: u64,
51    /// CRC-32 of the first `written` bytes of output. Unused for a
52    /// compressed tar, whose checksums are per gzip member, in `stream`.
53    pub crc: u32,
54    /// For a compressed tar, where one stream holds every entry: the
55    /// decoder's and the tar parser's state at `bit`. `written` is then how
56    /// much of the entry being extracted is in its part file, if the point
57    /// lies inside a file. Older builds don't know the format and refuse the
58    /// journal before reading this.
59    #[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    /// Every part of the archive with its original length.
68    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    /// The archive is truncated to this once the latest batch is committed.
74    /// Every unit starting at or after it is done.
75    pub committed_len: u64,
76    /// Links are made last, so nothing extracted can be written through one
77    /// and every hard link's target already exists.
78    pub links: Vec<Link>,
79    /// The large file being extracted while its archive bytes are freed, if
80    /// one is in progress. It always belongs to the highest uncommitted unit.
81    #[serde(default)]
82    pub resume: Option<Resume>,
83    /// Set while `restore` turns the archive back into a normal one: the
84    /// bytes it overwrites below `committed_len`, so that an interrupted
85    /// restore can be undone by putting them back and cutting off whatever it
86    /// appended.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
89    /// The extraction keeps the archive: nothing is truncated, punched or
90    /// deleted, and `committed_len` only records progress. A resume keeps
91    /// it too, whatever it is asked.
92    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
93    pub keep: bool,
94}
95
96pub struct Paths {
97    /// The first volume of the archive the side files belong to.
98    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        // The version is checked before the rest is parsed, so a newer layout
176        // gets the version message rather than a confusing parse error.
177        #[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    /// The journal is a file next to the archive, so anyone who could put
223    /// the archive there could have written it too. Whatever it names may
224    /// only be what an extraction of this archive touches: the archive's own
225    /// volumes, and links inside the output folder. The output folder itself
226    /// is checked by [`crate::session::check_output`].
227    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        // Restore only ever saves bytes it overwrites inside the archive.
249        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    /// Only an extraction that keeps the archive writes version 4, so older
305    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
306    #[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        // A mismatch means someone edited the file.
327        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    /// A run started by the previous release resumes; one started by a
334    /// release that knows more is refused before anything is touched.
335    #[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}