Skip to main content

hatchzip_core/archive/
storage.rs

1//! The archive's bytes, whether one file or a split set (`.001`, `.002`, ...),
2//! and the only code allowed to shrink them.
3
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, Read, Seek, SeekFrom};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use anyhow::{Context, Result, anyhow, bail};
10
11use crate::platform;
12
13#[derive(Clone, Debug)]
14pub struct Part {
15    pub path: PathBuf,
16    /// Where this part begins in the joined archive.
17    pub start: u64,
18    /// The part's length before extraction started.
19    pub len: u64,
20}
21
22/// Bytes from the end of the archive saved to a side file, served back at
23/// their original offsets once the real ones are truncated away.
24pub struct Tail {
25    pub start: u64,
26    pub bytes: Vec<u8>,
27}
28
29pub struct Storage {
30    parts: Arc<[Part]>,
31    /// The first part stays open and locked for the whole run, so two runs
32    /// can't eat the same archive.
33    first: File,
34}
35
36impl Storage {
37    /// Opens `path`, plus its sibling volumes if it is part of a split set.
38    pub fn open(path: &Path, writable: bool) -> Result<Self> {
39        let paths = volume_set(path)?;
40        let mut parts = Vec::with_capacity(paths.len());
41        let mut start = 0;
42        for p in paths {
43            let len = fs::metadata(&p)
44                .with_context(|| format!("reading {}", p.display()))?
45                .len();
46            parts.push(Part {
47                path: p,
48                start,
49                len,
50            });
51            start += len;
52        }
53        Self::with_parts(parts, writable)
54    }
55
56    /// Reopens a set whose original layout was recorded in the journal.
57    pub fn from_parts(recorded: &[(PathBuf, u64)], writable: bool) -> Result<Self> {
58        let mut parts = Vec::with_capacity(recorded.len());
59        let mut start = 0;
60        for (path, len) in recorded {
61            parts.push(Part {
62                path: path.clone(),
63                start,
64                len: *len,
65            });
66            start += len;
67        }
68        Self::with_parts(parts, writable)
69    }
70
71    fn with_parts(parts: Vec<Part>, writable: bool) -> Result<Self> {
72        let path = &parts[0].path;
73        let first = if writable {
74            platform::open_exclusive(path).map_err(|e| match e.kind() {
75                io::ErrorKind::WouldBlock => {
76                    anyhow!(
77                        "{} is in use by another program or HatchZip run",
78                        path.display()
79                    )
80                }
81                _ => anyhow!(e).context(format!(
82                    "opening {} for reading and writing",
83                    path.display()
84                )),
85            })?
86        } else {
87            File::open(path).with_context(|| format!("opening {}", path.display()))?
88        };
89        Ok(Self {
90            parts: parts.into(),
91            first,
92        })
93    }
94
95    pub fn primary(&self) -> &Path {
96        &self.parts[0].path
97    }
98
99    pub fn parts(&self) -> &[Part] {
100        &self.parts
101    }
102
103    pub fn record(&self) -> Vec<(PathBuf, u64)> {
104        self.parts.iter().map(|p| (p.path.clone(), p.len)).collect()
105    }
106
107    /// The archive's original length.
108    pub fn original_len(&self) -> u64 {
109        self.parts.last().map_or(0, |p| p.start + p.len)
110    }
111
112    /// How much of the archive is still on disk, checking that what is left
113    /// is an untouched prefix of the original.
114    pub fn current_len(&self) -> Result<u64> {
115        let mut end = 0;
116        for (i, p) in self.parts.iter().enumerate() {
117            let actual = match fs::metadata(&p.path) {
118                Ok(m) => m.len(),
119                Err(e) if e.kind() == io::ErrorKind::NotFound && i > 0 => 0,
120                Err(e) => return Err(e).with_context(|| format!("reading {}", p.path.display())),
121            };
122            if actual > p.len {
123                bail!(
124                    "{} grew since extraction started; refusing to touch it",
125                    p.path.display()
126                );
127            }
128            if actual == 0 && i > 0 {
129                break;
130            }
131            if end != p.start {
132                bail!(
133                    "{} is missing a piece before {}",
134                    self.primary().display(),
135                    p.path.display()
136                );
137            }
138            end = p.start + actual;
139            if actual < p.len {
140                break;
141            }
142        }
143        Ok(end)
144    }
145
146    /// Shrinks the archive to its first `len` bytes: whole volumes past that
147    /// point are deleted, the one it falls in is truncated.
148    pub fn set_len(&self, len: u64) -> Result<()> {
149        for (i, p) in self.parts.iter().enumerate().rev() {
150            if p.start + p.len <= len {
151                break;
152            }
153            if i == 0 {
154                self.first.set_len(len)?;
155            } else if p.start >= len {
156                match fs::remove_file(&p.path) {
157                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
158                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
159                    }
160                    _ => {}
161                }
162            } else {
163                let f = OpenOptions::new().write(true).open(&p.path)?;
164                if f.metadata()?.len() > len - p.start {
165                    f.set_len(len - p.start)?;
166                }
167            }
168        }
169        Ok(())
170    }
171
172    /// Gives back the disk space of the bytes in `[from, to)` while every
173    /// offset stays where it was; they read as zeros afterwards. Returns
174    /// false if the filesystem can't. Filesystems free whole blocks only, so
175    /// up to a block at each end may stay allocated until truncation.
176    pub fn punch(&self, from: u64, to: u64) -> Result<bool> {
177        for (i, p) in self.parts.iter().enumerate() {
178            let (start, end) = (from.max(p.start), to.min(p.start + p.len));
179            if start >= end {
180                continue;
181            }
182            let (offset, len) = (start - p.start, end - start);
183            let punched = if i == 0 {
184                platform::punch_hole(&self.first, offset, len)
185            } else {
186                OpenOptions::new()
187                    .write(true)
188                    .open(&p.path)
189                    .and_then(|f| platform::punch_hole(&f, offset, len))
190            };
191            if !punched.with_context(|| format!("freeing space in {}", p.path.display()))? {
192                return Ok(false);
193            }
194        }
195        Ok(true)
196    }
197
198    /// Like [`set_len`](Self::set_len), but also cuts volumes that grew past
199    /// their original length. Only for undoing an interrupted restore, which
200    /// is the one thing that appends to an archive: the volume it appended to
201    /// may have been whole, and `set_len` never touches whole volumes.
202    pub fn cut_to(&self, len: u64) -> Result<()> {
203        for (i, p) in self.parts.iter().enumerate().rev() {
204            let keep = len.saturating_sub(p.start).min(p.len);
205            if i > 0 && keep == 0 {
206                match fs::remove_file(&p.path) {
207                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
208                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
209                    }
210                    _ => {}
211                }
212                continue;
213            }
214            let shrink = |f: &File| -> io::Result<()> {
215                if f.metadata()?.len() > keep {
216                    f.set_len(keep)?;
217                    f.sync_all()?;
218                }
219                Ok(())
220            };
221            let done = if i == 0 {
222                shrink(&self.first)
223            } else {
224                match OpenOptions::new().write(true).open(&p.path) {
225                    Ok(f) => shrink(&f),
226                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
227                    Err(e) => Err(e),
228                }
229            };
230            done.with_context(|| format!("shortening {}", p.path.display()))?;
231        }
232        Ok(())
233    }
234
235    /// Writes `bytes` at `offset` of the joined archive and flushes them to
236    /// disk. Bytes inside the archive go to the volume that holds them; bytes
237    /// past its current end go to the last volume still there, which grows.
238    pub fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
239        let end = self.current_len()?;
240        if offset > end {
241            bail!(
242                "{} is shorter than expected; refusing to write past its end",
243                self.primary().display()
244            );
245        }
246        let last = self.parts.partition_point(|p| p.start < end).max(1) - 1;
247        let mut at = offset;
248        let mut rest = bytes;
249        while !rest.is_empty() {
250            let i = if at >= end {
251                last
252            } else {
253                self.parts.partition_point(|p| p.start <= at) - 1
254            };
255            let p = &self.parts[i];
256            let room = if i == last {
257                rest.len()
258            } else {
259                ((p.start + p.len - at) as usize).min(rest.len())
260            };
261            let (now, later) = rest.split_at(room);
262            self.write_part(i, at - p.start, now)
263                .with_context(|| format!("writing to {}", p.path.display()))?;
264            at += room as u64;
265            rest = later;
266        }
267        Ok(())
268    }
269
270    fn write_part(&self, i: usize, at: u64, bytes: &[u8]) -> io::Result<()> {
271        let write = |mut f: &File| -> io::Result<()> {
272            f.seek(SeekFrom::Start(at))?;
273            io::Write::write_all(&mut f, bytes)?;
274            f.sync_all()
275        };
276        if i == 0 {
277            // On Windows the locked handle is the only one allowed to write.
278            write(&self.first)
279        } else {
280            write(&OpenOptions::new().write(true).open(&self.parts[i].path)?)
281        }
282    }
283
284    /// Deletes whatever is left of every part.
285    pub fn remove(self) -> Result<()> {
286        let Self { parts, first } = self;
287        drop(first);
288        for p in parts.iter() {
289            match fs::remove_file(&p.path) {
290                Err(e) if e.kind() != io::ErrorKind::NotFound => {
291                    return Err(e).with_context(|| format!("deleting {}", p.path.display()));
292                }
293                _ => {}
294            }
295        }
296        Ok(())
297    }
298
299    pub fn reader(&self, tail: Option<Arc<Tail>>) -> Reader {
300        Reader {
301            parts: self.parts.clone(),
302            open: None,
303            tail,
304            len: self.original_len(),
305            pos: 0,
306        }
307    }
308}
309
310/// The path of the first volume, if `path` names any volume of a split set.
311pub fn first_volume(path: &Path) -> PathBuf {
312    match split_suffix(path) {
313        Some((base, width, _)) => numbered(&base, width, 1),
314        None => path.to_path_buf(),
315    }
316}
317
318fn volume_set(path: &Path) -> Result<Vec<PathBuf>> {
319    let Some((base, width, n)) = split_suffix(path) else {
320        return Ok(vec![path.to_path_buf()]);
321    };
322    if n != 1 {
323        bail!(
324            "{} is not the first part; open {} instead",
325            path.display(),
326            numbered(&base, width, 1).display()
327        );
328    }
329    let mut parts = vec![path.to_path_buf()];
330    loop {
331        let next = numbered(&base, width, parts.len() as u64 + 1);
332        if !next.exists() {
333            return Ok(parts);
334        }
335        parts.push(next);
336    }
337}
338
339/// `game.7z.001` is `("game.7z", 3, 1)`. Only names with a real extension
340/// before the number count, so a file that just happens to end in digits
341/// isn't mistaken for a volume.
342fn split_suffix(path: &Path) -> Option<(PathBuf, usize, u64)> {
343    let name = path.file_name()?.to_str()?;
344    let (stem, digits) = name.rsplit_once('.')?;
345    if digits.len() < 3 || !digits.bytes().all(|b| b.is_ascii_digit()) || !stem.contains('.') {
346        return None;
347    }
348    Some((
349        path.with_file_name(stem),
350        digits.len(),
351        digits.parse().ok()?,
352    ))
353}
354
355fn numbered(base: &Path, width: usize, n: u64) -> PathBuf {
356    let mut s = base.as_os_str().to_owned();
357    s.push(format!(".{n:0width$}"));
358    PathBuf::from(s)
359}
360
361/// Reads the joined archive. Parts or regions that were already truncated
362/// away read as zeros: format parsers scan backwards over them looking for
363/// end records, and zeros never match a signature.
364pub struct Reader {
365    parts: Arc<[Part]>,
366    open: Option<(usize, File)>,
367    tail: Option<Arc<Tail>>,
368    len: u64,
369    pos: u64,
370}
371
372impl Read for Reader {
373    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
374        if self.pos >= self.len || buf.is_empty() {
375            return Ok(0);
376        }
377        let live_end = match &self.tail {
378            Some(t) if self.pos >= t.start => {
379                let at = (self.pos - t.start) as usize;
380                let src = t.bytes.get(at..).unwrap_or(&[]);
381                let n = src.len().min(buf.len());
382                buf[..n].copy_from_slice(&src[..n]);
383                self.pos += n as u64;
384                return Ok(n);
385            }
386            Some(t) => t.start,
387            None => self.len,
388        };
389        let i = self.parts.partition_point(|p| p.start <= self.pos) - 1;
390        let part = &self.parts[i];
391        let room = (part.start + part.len).min(live_end) - self.pos;
392        let room = room.min(buf.len() as u64) as usize;
393        if self.open.as_ref().is_none_or(|(j, _)| *j != i) {
394            self.open = File::open(&part.path).ok().map(|f| (i, f));
395        }
396        let n = match &mut self.open {
397            Some((_, f)) => {
398                f.seek(SeekFrom::Start(self.pos - part.start))?;
399                f.read(&mut buf[..room])?
400            }
401            None => 0,
402        };
403        let n = if n == 0 {
404            buf[..room].fill(0);
405            room
406        } else {
407            n
408        };
409        self.pos += n as u64;
410        Ok(n)
411    }
412}
413
414impl Seek for Reader {
415    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
416        let pos = match to {
417            SeekFrom::Start(p) => Some(p),
418            SeekFrom::End(d) => self.len.checked_add_signed(d),
419            SeekFrom::Current(d) => self.pos.checked_add_signed(d),
420        };
421        self.pos = pos.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "bad seek"))?;
422        Ok(self.pos)
423    }
424}