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::{Path, PathBuf};
11use std::sync::Arc;
12
13use anyhow::{Context, Result, bail};
14use serde::{Deserialize, Serialize};
15
16use crate::archive::storage::{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    pub journal: PathBuf,
98    pub tail: PathBuf,
99}
100
101impl Paths {
102    pub fn for_archive(archive: &Path) -> Self {
103        let with = |suffix: &str| {
104            let mut s = archive.as_os_str().to_owned();
105            s.push(suffix);
106            PathBuf::from(s)
107        };
108        Self {
109            journal: with(".hatchzip"),
110            tail: with(".hatchzip-tail"),
111        }
112    }
113
114    pub fn exists(&self) -> bool {
115        self.journal.exists()
116    }
117
118    pub fn remove(&self) -> Result<()> {
119        for p in [&self.tail, &self.journal] {
120            match fs::remove_file(p) {
121                Err(e) if e.kind() != io::ErrorKind::NotFound => {
122                    return Err(e).with_context(|| format!("removing {}", p.display()));
123                }
124                _ => {}
125            }
126        }
127        Ok(())
128    }
129}
130
131pub struct Plan {
132    pub format: &'static str,
133    pub tail_start: u64,
134    pub output: PathBuf,
135    pub total_size: u64,
136    pub keep: bool,
137}
138
139fn version_for(keep: bool) -> u32 {
140    if keep { KEEP_VERSION } else { VERSION }
141}
142
143impl Journal {
144    pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
145        let mut tail = Vec::new();
146        let mut r = storage.reader(None);
147        r.seek(SeekFrom::Start(plan.tail_start))?;
148        r.read_to_end(&mut tail)?;
149        fsutil::write_atomic(&paths.tail, &tail)?;
150        let journal = Self {
151            version: version_for(plan.keep),
152            format: plan.format.to_string(),
153            parts: storage.record(),
154            tail_start: plan.tail_start,
155            tail_crc: crc32fast::hash(&tail),
156            output: plan.output,
157            total_size: plan.total_size,
158            committed_len: storage.original_len(),
159            links: Vec::new(),
160            resume: None,
161            restoring: None,
162            keep: plan.keep,
163        };
164        journal.save(paths)?;
165        Ok(journal)
166    }
167
168    pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
169        let bytes = fs::read(&paths.journal)
170            .with_context(|| format!("reading {}", paths.journal.display()))?;
171        // The version is checked before the rest is parsed, so a newer layout
172        // gets the version message rather than a confusing parse error.
173        #[derive(Deserialize)]
174        struct Versioned {
175            version: u32,
176        }
177        let version = serde_json::from_slice::<Versioned>(&bytes)
178            .with_context(|| format!("{} is damaged", paths.journal.display()))?
179            .version;
180        if !READABLE.contains(&version) {
181            let which = if version > VERSION {
182                "a newer"
183            } else {
184                "an older"
185            };
186            bail!(
187                "{} was written by {which} HatchZip version (journal format {version}); \
188                 complete the extraction with that version",
189                paths.journal.display()
190            );
191        }
192        let mut journal: Self = serde_json::from_slice(&bytes)
193            .with_context(|| format!("{} is damaged", paths.journal.display()))?;
194        if journal.keep != (version == KEEP_VERSION) {
195            bail!("{} is damaged", paths.journal.display());
196        }
197        journal.version = version_for(journal.keep);
198        let tail =
199            fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
200        let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
201        if crc32fast::hash(&tail) != journal.tail_crc
202            || journal.tail_start + tail.len() as u64 != len
203        {
204            bail!("{} does not match its journal", paths.tail.display());
205        }
206        let tail = Arc::new(Tail {
207            start: journal.tail_start,
208            bytes: tail,
209        });
210        Ok((journal, tail))
211    }
212
213    pub fn save(&self, paths: &Paths) -> Result<()> {
214        fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    fn write(dir: &Path, version: u32) -> Paths {
223        write_with(dir, version, "")
224    }
225
226    fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
227        let paths = Paths::for_archive(&dir.join("game.zip"));
228        let tail = b"saved tail";
229        fs::write(&paths.tail, tail).unwrap();
230        let json = format!(
231            r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
232                "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
233            serde_json::to_string(&dir.join("game.zip")).unwrap(),
234            tail.len(),
235            crc32fast::hash(tail)
236        );
237        fs::write(&paths.journal, json).unwrap();
238        paths
239    }
240
241    /// Only an extraction that keeps the archive writes version 4, so older
242    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
243    #[test]
244    fn keeping_the_archive_is_version_4_and_only_that_is() {
245        let dir =
246            std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
247        fs::create_dir_all(&dir).unwrap();
248
249        let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
250        assert!(journal.keep);
251        assert_eq!(journal.version, KEEP_VERSION);
252        let saved = serde_json::to_string(&journal).unwrap();
253        assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));
254
255        let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
256        assert!(!journal.keep);
257        assert!(
258            !serde_json::to_string(&journal)
259                .unwrap()
260                .contains(r#""keep":"#)
261        );
262
263        // A mismatch means someone edited the file.
264        assert!(Journal::load(&write(&dir, 4)).is_err());
265        assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());
266
267        fs::remove_dir_all(&dir).unwrap();
268    }
269
270    /// A run started by the previous release resumes; one started by a
271    /// release that knows more is refused before anything is touched.
272    #[test]
273    fn reads_version_2_and_refuses_newer_journals() {
274        let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
275        fs::create_dir_all(&dir).unwrap();
276
277        let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
278        assert_eq!(journal.resume, None);
279        assert_eq!(journal.version, VERSION);
280
281        let err = Journal::load(&write(&dir, KEEP_VERSION + 1)).err().unwrap();
282        assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
283        let err = Journal::load(&write(&dir, 1)).err().unwrap();
284        assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
285
286        fs::remove_dir_all(&dir).unwrap();
287    }
288}