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};
17use crate::fsutil;
18
19/// Version 3 added `resume`. A version 2 journal can't hold one, so it reads
20/// as is. Older HatchZip builds refuse version 3, which matters: they would
21/// delete a half-extracted file whose archive bytes are already freed.
22const VERSION: u32 = 3;
23const READABLE: [u32; 2] = [2, 3];
24
25#[derive(Serialize, Deserialize, Clone)]
26pub struct Link {
27    pub path: PathBuf,
28    pub target: PathBuf,
29    pub hard: bool,
30}
31
32/// Where extraction of a large file can pick up again after a crash. Its
33/// output up to `written` is flushed to disk, and the archive bytes before
34/// the one holding `bit` may already be freed, so this is the only way back.
35#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
36pub struct Resume {
37    /// The unit, by the offset it starts at.
38    pub unit: u64,
39    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
40    /// holds past this was written after the point and is thrown away.
41    pub written: u64,
42    /// Where decoding restarts, in bits from the start of the archive. Only
43    /// deflate streams ever stop between two bytes.
44    pub bit: u64,
45    /// CRC-32 of the first `written` bytes of output.
46    pub crc: u32,
47}
48
49#[derive(Serialize, Deserialize)]
50pub struct Journal {
51    pub version: u32,
52    pub format: String,
53    /// Every part of the archive with its original length.
54    pub parts: Vec<(PathBuf, u64)>,
55    pub tail_start: u64,
56    pub tail_crc: u32,
57    pub output: PathBuf,
58    pub total_size: u64,
59    /// The archive is truncated to this once the latest batch is committed.
60    /// Every unit starting at or after it is done.
61    pub committed_len: u64,
62    /// Links are made last, so nothing extracted can be written through one
63    /// and every hard link's target already exists.
64    pub links: Vec<Link>,
65    /// The large file being extracted while its archive bytes are freed, if
66    /// one is in progress. It always belongs to the highest uncommitted unit.
67    #[serde(default)]
68    pub resume: Option<Resume>,
69    /// Set while `restore` turns the archive back into a normal one: the
70    /// bytes it overwrites below `committed_len`, so that an interrupted
71    /// restore can be undone by putting them back and cutting off whatever it
72    /// appended.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
75}
76
77pub struct Paths {
78    pub journal: PathBuf,
79    pub tail: PathBuf,
80}
81
82impl Paths {
83    pub fn for_archive(archive: &Path) -> Self {
84        let with = |suffix: &str| {
85            let mut s = archive.as_os_str().to_owned();
86            s.push(suffix);
87            PathBuf::from(s)
88        };
89        Self {
90            journal: with(".hatchzip"),
91            tail: with(".hatchzip-tail"),
92        }
93    }
94
95    pub fn exists(&self) -> bool {
96        self.journal.exists()
97    }
98
99    pub fn remove(&self) -> Result<()> {
100        for p in [&self.tail, &self.journal] {
101            match fs::remove_file(p) {
102                Err(e) if e.kind() != io::ErrorKind::NotFound => {
103                    return Err(e).with_context(|| format!("removing {}", p.display()));
104                }
105                _ => {}
106            }
107        }
108        Ok(())
109    }
110}
111
112pub struct Plan {
113    pub format: &'static str,
114    pub tail_start: u64,
115    pub output: PathBuf,
116    pub total_size: u64,
117}
118
119impl Journal {
120    pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
121        let mut tail = Vec::new();
122        let mut r = storage.reader(None);
123        r.seek(SeekFrom::Start(plan.tail_start))?;
124        r.read_to_end(&mut tail)?;
125        fsutil::write_atomic(&paths.tail, &tail)?;
126        let journal = Self {
127            version: VERSION,
128            format: plan.format.to_string(),
129            parts: storage.record(),
130            tail_start: plan.tail_start,
131            tail_crc: crc32fast::hash(&tail),
132            output: plan.output,
133            total_size: plan.total_size,
134            committed_len: storage.original_len(),
135            links: Vec::new(),
136            resume: None,
137            restoring: None,
138        };
139        journal.save(paths)?;
140        Ok(journal)
141    }
142
143    pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
144        let bytes = fs::read(&paths.journal)
145            .with_context(|| format!("reading {}", paths.journal.display()))?;
146        // The version is checked before the rest is parsed, so a newer layout
147        // gets the version message rather than a confusing parse error.
148        #[derive(Deserialize)]
149        struct Versioned {
150            version: u32,
151        }
152        let version = serde_json::from_slice::<Versioned>(&bytes)
153            .with_context(|| format!("{} is damaged", paths.journal.display()))?
154            .version;
155        if !READABLE.contains(&version) {
156            let which = if version > VERSION {
157                "a newer"
158            } else {
159                "an older"
160            };
161            bail!(
162                "{} was written by {which} HatchZip version (journal format {version}); \
163                 finish the extraction with that version",
164                paths.journal.display()
165            );
166        }
167        let mut journal: Self = serde_json::from_slice(&bytes)
168            .with_context(|| format!("{} is damaged", paths.journal.display()))?;
169        journal.version = VERSION;
170        let tail =
171            fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
172        let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
173        if crc32fast::hash(&tail) != journal.tail_crc
174            || journal.tail_start + tail.len() as u64 != len
175        {
176            bail!("{} does not match its journal", paths.tail.display());
177        }
178        let tail = Arc::new(Tail {
179            start: journal.tail_start,
180            bytes: tail,
181        });
182        Ok((journal, tail))
183    }
184
185    pub fn save(&self, paths: &Paths) -> Result<()> {
186        fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    fn write(dir: &Path, version: u32) -> Paths {
195        let paths = Paths::for_archive(&dir.join("game.zip"));
196        let tail = b"saved tail";
197        fs::write(&paths.tail, tail).unwrap();
198        let json = format!(
199            r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
200                "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]}}"#,
201            serde_json::to_string(&dir.join("game.zip")).unwrap(),
202            tail.len(),
203            crc32fast::hash(tail)
204        );
205        fs::write(&paths.journal, json).unwrap();
206        paths
207    }
208
209    /// A run started by the previous release resumes; one started by a
210    /// release that knows more is refused before anything is touched.
211    #[test]
212    fn reads_version_2_and_refuses_newer_journals() {
213        let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
214        fs::create_dir_all(&dir).unwrap();
215
216        let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
217        assert_eq!(journal.resume, None);
218        assert_eq!(journal.version, VERSION);
219
220        let err = Journal::load(&write(&dir, VERSION + 1)).err().unwrap();
221        assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
222        let err = Journal::load(&write(&dir, 1)).err().unwrap();
223        assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
224
225        fs::remove_dir_all(&dir).unwrap();
226    }
227}