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 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#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
37pub struct Resume {
38 pub unit: u64,
40 pub written: u64,
43 pub bit: u64,
46 pub crc: u32,
49 #[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 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 pub committed_len: u64,
71 pub links: Vec<Link>,
74 #[serde(default)]
77 pub resume: Option<Resume>,
78 #[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 #[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 #[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}