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