1use 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
19const 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#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
36pub struct Resume {
37 pub unit: u64,
39 pub written: u64,
42 pub bit: u64,
45 pub crc: u32,
47}
48
49#[derive(Serialize, Deserialize)]
50pub struct Journal {
51 pub version: u32,
52 pub format: String,
53 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 pub committed_len: u64,
62 pub links: Vec<Link>,
65 #[serde(default)]
68 pub resume: Option<Resume>,
69 #[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 #[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 complete 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 #[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}