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};
17pub use crate::archive::targz::{StreamPoint, TarAt};
18use crate::fsutil;
19
20const VERSION: u32 = 3;
24const 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#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
42pub struct Resume {
43 pub unit: u64,
45 pub written: u64,
48 pub bit: u64,
51 pub crc: u32,
54 #[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 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 pub committed_len: u64,
76 pub links: Vec<Link>,
79 #[serde(default)]
82 pub resume: Option<Resume>,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub restoring: Option<Vec<(u64, Vec<u8>)>>,
89 #[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 #[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 #[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 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 #[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}