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;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
10use anyhow::{Context, Result, anyhow, bail};
11
12use crate::platform;
13
14#[derive(Clone, Debug)]
15pub struct Part {
16    pub path: PathBuf,
17    /// Where this part begins in the joined archive.
18    pub start: u64,
19    /// The part's length before extraction started.
20    pub len: u64,
21}
22
23/// Bytes from the end of the archive saved to a side file, served back at
24/// their original offsets once the real ones are truncated away.
25pub struct Tail {
26    pub start: u64,
27    pub bytes: Vec<u8>,
28}
29
30pub struct Storage {
31    parts: Arc<[Part]>,
32    /// The first part stays open and locked for the whole run, so two runs
33    /// can't eat the same archive.
34    first: File,
35    /// Set for an extraction that keeps the archive. Every method that
36    /// changes the archive's bytes refuses from then on, so a bug elsewhere
37    /// can't cost the user an archive they asked to keep.
38    whole: AtomicBool,
39    reads: Arc<Reads>,
40}
41
42/// How much of the archive its readers have read. Opening a compressed tar
43/// decodes all of it before anything else, which takes minutes for a large
44/// one, so front ends show this from another thread while an archive opens.
45#[derive(Debug, Default)]
46pub struct Reads {
47    pub done: AtomicU64,
48    /// How much the current pass reads in all: the archive's length, or
49    /// less when a resumed compressed tar is read from its resume point.
50    pub total: AtomicU64,
51}
52
53impl Reads {
54    pub fn reset(&self) {
55        self.done.store(0, Ordering::Relaxed);
56        self.total.store(0, Ordering::Relaxed);
57    }
58
59    /// The share of the pass read so far, if a pass is under way.
60    pub fn fraction(&self) -> Option<f64> {
61        let total = self.total.load(Ordering::Relaxed);
62        let done = self.done.load(Ordering::Relaxed);
63        (total > 0).then(|| (done as f64 / total as f64).min(1.0))
64    }
65}
66
67impl Storage {
68    /// Opens `path`, plus its sibling volumes if it is part of a split set.
69    pub fn open(path: &Path, writable: bool) -> Result<Self> {
70        let paths = volume_set(path)?;
71        let mut parts = Vec::with_capacity(paths.len());
72        let mut start = 0;
73        for p in paths {
74            let len = fs::metadata(&p)
75                .with_context(|| format!("reading {}", p.display()))?
76                .len();
77            parts.push(Part {
78                path: p,
79                start,
80                len,
81            });
82            start += len;
83        }
84        Self::with_parts(parts, writable)
85    }
86
87    /// Reopens a set whose original layout was recorded in the journal.
88    pub fn from_parts(recorded: &[(PathBuf, u64)], writable: bool) -> Result<Self> {
89        let mut parts = Vec::with_capacity(recorded.len());
90        let mut start = 0;
91        for (path, len) in recorded {
92            parts.push(Part {
93                path: path.clone(),
94                start,
95                len: *len,
96            });
97            start += len;
98        }
99        Self::with_parts(parts, writable)
100    }
101
102    fn with_parts(parts: Vec<Part>, writable: bool) -> Result<Self> {
103        let path = &parts[0].path;
104        let first = if writable {
105            platform::open_exclusive(path).map_err(|e| match e.kind() {
106                io::ErrorKind::WouldBlock => {
107                    anyhow!(
108                        "{} is in use by another program or HatchZip process",
109                        path.display()
110                    )
111                }
112                _ => anyhow!(e).context(format!(
113                    "opening {} for reading and writing",
114                    path.display()
115                )),
116            })?
117        } else {
118            File::open(path).with_context(|| format!("opening {}", path.display()))?
119        };
120        Ok(Self {
121            parts: parts.into(),
122            first,
123            whole: AtomicBool::new(false),
124            reads: Arc::default(),
125        })
126    }
127
128    /// From now on nothing may shrink, punch, write to or delete the
129    /// archive.
130    pub fn protect(&self) {
131        self.whole.store(true, Ordering::Relaxed);
132    }
133
134    pub fn protected(&self) -> bool {
135        self.whole.load(Ordering::Relaxed)
136    }
137
138    fn may_change(&self) -> Result<()> {
139        if self.protected() {
140            bail!(
141                "refusing to modify {}: this extraction keeps the archive",
142                self.primary().display()
143            );
144        }
145        Ok(())
146    }
147
148    pub fn primary(&self) -> &Path {
149        &self.parts[0].path
150    }
151
152    pub fn parts(&self) -> &[Part] {
153        &self.parts
154    }
155
156    pub fn record(&self) -> Vec<(PathBuf, u64)> {
157        self.parts.iter().map(|p| (p.path.clone(), p.len)).collect()
158    }
159
160    /// The archive's original length.
161    pub fn original_len(&self) -> u64 {
162        self.parts.last().map_or(0, |p| p.start + p.len)
163    }
164
165    /// How much of the archive is still on disk, checking that what is left
166    /// is an untouched prefix of the original.
167    pub fn current_len(&self) -> Result<u64> {
168        let mut end = 0;
169        for (i, p) in self.parts.iter().enumerate() {
170            let actual = match fs::metadata(&p.path) {
171                Ok(m) => m.len(),
172                Err(e) if e.kind() == io::ErrorKind::NotFound && i > 0 => 0,
173                Err(e) => return Err(e).with_context(|| format!("reading {}", p.path.display())),
174            };
175            if actual > p.len {
176                bail!(
177                    "{} has grown since extraction started and will not be modified",
178                    p.path.display()
179                );
180            }
181            if actual == 0 && i > 0 {
182                break;
183            }
184            if end != p.start {
185                bail!(
186                    "{} is missing a piece before {}",
187                    self.primary().display(),
188                    p.path.display()
189                );
190            }
191            end = p.start + actual;
192            if actual < p.len {
193                break;
194            }
195        }
196        Ok(end)
197    }
198
199    /// Shrinks the archive to its first `len` bytes: whole volumes past that
200    /// point are deleted, the one it falls in is truncated.
201    pub fn set_len(&self, len: u64) -> Result<()> {
202        self.may_change()?;
203        for (i, p) in self.parts.iter().enumerate().rev() {
204            if p.start + p.len <= len {
205                break;
206            }
207            if i == 0 {
208                self.first.set_len(len)?;
209            } else if p.start >= len {
210                match fs::remove_file(&p.path) {
211                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
212                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
213                    }
214                    _ => {}
215                }
216            } else {
217                let f = OpenOptions::new().write(true).open(&p.path)?;
218                if f.metadata()?.len() > len - p.start {
219                    f.set_len(len - p.start)?;
220                }
221            }
222        }
223        Ok(())
224    }
225
226    /// Gives back the disk space of the bytes in `[from, to)` while every
227    /// offset stays where it was; they read as zeros afterwards. Returns
228    /// false if the filesystem can't. Filesystems free whole blocks only, so
229    /// up to a block at each end may stay allocated until truncation.
230    pub fn punch(&self, from: u64, to: u64) -> Result<bool> {
231        self.may_change()?;
232        for (i, p) in self.parts.iter().enumerate() {
233            let (start, end) = (from.max(p.start), to.min(p.start + p.len));
234            if start >= end {
235                continue;
236            }
237            let (offset, len) = (start - p.start, end - start);
238            let punched = if i == 0 {
239                platform::punch_hole(&self.first, offset, len)
240            } else {
241                OpenOptions::new()
242                    .write(true)
243                    .open(&p.path)
244                    .and_then(|f| platform::punch_hole(&f, offset, len))
245            };
246            if !punched.with_context(|| format!("freeing space in {}", p.path.display()))? {
247                return Ok(false);
248            }
249        }
250        Ok(true)
251    }
252
253    /// Like [`set_len`](Self::set_len), but also cuts volumes that grew past
254    /// their original length. Only for undoing an interrupted restore, which
255    /// is the one thing that appends to an archive: the volume it appended to
256    /// may have been whole, and `set_len` never touches whole volumes.
257    pub fn cut_to(&self, len: u64) -> Result<()> {
258        self.may_change()?;
259        for (i, p) in self.parts.iter().enumerate().rev() {
260            let keep = len.saturating_sub(p.start).min(p.len);
261            if i > 0 && keep == 0 {
262                match fs::remove_file(&p.path) {
263                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
264                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
265                    }
266                    _ => {}
267                }
268                continue;
269            }
270            let shrink = |f: &File| -> io::Result<()> {
271                if f.metadata()?.len() > keep {
272                    f.set_len(keep)?;
273                    f.sync_all()?;
274                }
275                Ok(())
276            };
277            let done = if i == 0 {
278                shrink(&self.first)
279            } else {
280                match OpenOptions::new().write(true).open(&p.path) {
281                    Ok(f) => shrink(&f),
282                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
283                    Err(e) => Err(e),
284                }
285            };
286            done.with_context(|| format!("shortening {}", p.path.display()))?;
287        }
288        Ok(())
289    }
290
291    /// Writes `bytes` at `offset` of the joined archive and flushes them to
292    /// disk. Bytes inside the archive go to the volume that holds them; bytes
293    /// past its current end go to the last volume still there, which grows.
294    pub fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
295        self.may_change()?;
296        let end = self.current_len()?;
297        if offset > end {
298            bail!(
299                "{} is shorter than expected; refusing to write past its end",
300                self.primary().display()
301            );
302        }
303        let last = self.parts.partition_point(|p| p.start < end).max(1) - 1;
304        let mut at = offset;
305        let mut rest = bytes;
306        while !rest.is_empty() {
307            let i = if at >= end {
308                last
309            } else {
310                self.parts.partition_point(|p| p.start <= at) - 1
311            };
312            let p = &self.parts[i];
313            let room = if i == last {
314                rest.len()
315            } else {
316                ((p.start + p.len - at) as usize).min(rest.len())
317            };
318            let (now, later) = rest.split_at(room);
319            self.write_part(i, at - p.start, now)
320                .with_context(|| format!("writing to {}", p.path.display()))?;
321            at += room as u64;
322            rest = later;
323        }
324        Ok(())
325    }
326
327    fn write_part(&self, i: usize, at: u64, bytes: &[u8]) -> io::Result<()> {
328        let write = |mut f: &File| -> io::Result<()> {
329            f.seek(SeekFrom::Start(at))?;
330            io::Write::write_all(&mut f, bytes)?;
331            f.sync_all()
332        };
333        if i == 0 {
334            // On Windows the locked handle is the only one allowed to write.
335            write(&self.first)
336        } else {
337            write(&OpenOptions::new().write(true).open(&self.parts[i].path)?)
338        }
339    }
340
341    /// Deletes whatever is left of every part.
342    pub fn remove(self) -> Result<()> {
343        self.may_change()?;
344        let Self { parts, first, .. } = self;
345        drop(first);
346        for p in parts.iter() {
347            match fs::remove_file(&p.path) {
348                Err(e) if e.kind() != io::ErrorKind::NotFound => {
349                    return Err(e).with_context(|| format!("deleting {}", p.path.display()));
350                }
351                _ => {}
352            }
353        }
354        Ok(())
355    }
356
357    pub fn reader(&self, tail: Option<Arc<Tail>>) -> Reader {
358        Reader {
359            parts: self.parts.clone(),
360            open: None,
361            tail,
362            len: self.original_len(),
363            pos: 0,
364            reads: self.reads.clone(),
365        }
366    }
367
368    /// Counts what every reader made from now on reads into `reads`, a pass
369    /// over the whole archive by default.
370    pub fn count_reads(&mut self, reads: Arc<Reads>) {
371        reads.done.store(0, Ordering::Relaxed);
372        reads.total.store(self.original_len(), Ordering::Relaxed);
373        self.reads = reads;
374    }
375
376    /// Starts the count over for a pass that reads `total` bytes.
377    pub fn expect_reads(&self, total: u64) {
378        self.reads.done.store(0, Ordering::Relaxed);
379        self.reads.total.store(total, Ordering::Relaxed);
380    }
381}
382
383/// The path of the first volume, if `path` names any volume of a split set.
384pub fn first_volume(path: &Path) -> PathBuf {
385    if let Some(rar) = rar_volume(path) {
386        return rar.volume(0);
387    }
388    match split_suffix(path) {
389        Some((base, width, _)) => numbered(&base, width, 1),
390        None => path.to_path_buf(),
391    }
392}
393
394fn volume_set(path: &Path) -> Result<Vec<PathBuf>> {
395    if let Some(rar) = rar_volume(path) {
396        if rar.index != 0 {
397            bail!(
398                "{} is not the first volume. Open {} instead",
399                path.display(),
400                rar.volume(0).display()
401            );
402        }
403        let mut volumes = vec![path.to_path_buf()];
404        while rar.volume(volumes.len()).exists() {
405            volumes.push(rar.volume(volumes.len()));
406        }
407        return Ok(volumes);
408    }
409    let Some((base, width, n)) = split_suffix(path) else {
410        return Ok(vec![path.to_path_buf()]);
411    };
412    if n != 1 {
413        bail!(
414            "{} is not the first part. Open {} instead",
415            path.display(),
416            numbered(&base, width, 1).display()
417        );
418    }
419    let mut parts = vec![path.to_path_buf()];
420    loop {
421        let next = numbered(&base, width, parts.len() as u64 + 1);
422        if !next.exists() {
423            return Ok(parts);
424        }
425        parts.push(next);
426    }
427}
428
429/// `game.7z.001` is `("game.7z", 3, 1)`. Only names with a real extension
430/// before the number count, so a file that just happens to end in digits
431/// isn't mistaken for a volume.
432fn split_suffix(path: &Path) -> Option<(PathBuf, usize, u64)> {
433    let name = path.file_name()?.to_str()?;
434    let (stem, digits) = name.rsplit_once('.')?;
435    if digits.len() < 3 || !digits.bytes().all(|b| b.is_ascii_digit()) || !stem.contains('.') {
436        return None;
437    }
438    Some((
439        path.with_file_name(stem),
440        digits.len(),
441        digits.parse().ok()?,
442    ))
443}
444
445fn numbered(base: &Path, width: usize, n: u64) -> PathBuf {
446    let mut s = base.as_os_str().to_owned();
447    s.push(format!(".{n:0width$}"));
448    PathBuf::from(s)
449}
450
451/// Reads the joined archive. Parts or regions that were already truncated
452/// away read as zeros: format parsers scan backwards over them looking for
453/// end records, and zeros never match a signature.
454pub struct Reader {
455    parts: Arc<[Part]>,
456    open: Option<(usize, File)>,
457    tail: Option<Arc<Tail>>,
458    len: u64,
459    pos: u64,
460    reads: Arc<Reads>,
461}
462
463impl Read for Reader {
464    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
465        let n = self.read_at_pos(buf)?;
466        self.reads.done.fetch_add(n as u64, Ordering::Relaxed);
467        Ok(n)
468    }
469}
470
471impl Reader {
472    fn read_at_pos(&mut self, buf: &mut [u8]) -> io::Result<usize> {
473        if self.pos >= self.len || buf.is_empty() {
474            return Ok(0);
475        }
476        let live_end = match &self.tail {
477            Some(t) if self.pos >= t.start => {
478                let at = (self.pos - t.start) as usize;
479                let src = t.bytes.get(at..).unwrap_or(&[]);
480                let n = src.len().min(buf.len());
481                buf[..n].copy_from_slice(&src[..n]);
482                self.pos += n as u64;
483                return Ok(n);
484            }
485            Some(t) => t.start,
486            None => self.len,
487        };
488        let i = self.parts.partition_point(|p| p.start <= self.pos) - 1;
489        let part = &self.parts[i];
490        let room = (part.start + part.len).min(live_end) - self.pos;
491        let room = room.min(buf.len() as u64) as usize;
492        if self.open.as_ref().is_none_or(|(j, _)| *j != i) {
493            self.open = File::open(&part.path).ok().map(|f| (i, f));
494        }
495        let n = match &mut self.open {
496            Some((_, f)) => {
497                f.seek(SeekFrom::Start(self.pos - part.start))?;
498                f.read(&mut buf[..room])?
499            }
500            None => 0,
501        };
502        let n = if n == 0 {
503            buf[..room].fill(0);
504            room
505        } else {
506            n
507        };
508        self.pos += n as u64;
509        Ok(n)
510    }
511}
512
513impl Seek for Reader {
514    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
515        let pos = match to {
516            SeekFrom::Start(p) => Some(p),
517            SeekFrom::End(d) => self.len.checked_add_signed(d),
518            SeekFrom::Current(d) => self.pos.checked_add_signed(d),
519        };
520        self.pos = pos.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "bad seek"))?;
521        Ok(self.pos)
522    }
523}
524
525/// How the volumes of a RAR set are named, and which one a path is.
526struct RarSet {
527    /// The path without the part of the name that changes.
528    stem: PathBuf,
529    style: RarStyle,
530    /// 0 for the first volume.
531    index: usize,
532    /// Upper case extensions stay upper case.
533    upper: bool,
534}
535
536enum RarStyle {
537    /// `name.part1.rar`, `name.part01.rar`: the number's width is kept.
538    Part { width: usize },
539    /// `name.rar`, `name.r00`, `name.r01`, ..., `name.r99`, `name.s00`, ...
540    Old,
541}
542
543impl RarSet {
544    fn volume(&self, index: usize) -> PathBuf {
545        let mut name = self.stem.as_os_str().to_owned();
546        let case = |s: String| if self.upper { s.to_uppercase() } else { s };
547        match self.style {
548            RarStyle::Part { width } => {
549                name.push(case(format!(".part{:0width$}.rar", index + 1)));
550            }
551            RarStyle::Old if index == 0 => name.push(case(".rar".into())),
552            RarStyle::Old => {
553                let n = index - 1;
554                let letter = (b'r' + (n / 100) as u8) as char;
555                name.push(case(format!(".{letter}{:02}", n % 100)));
556            }
557        }
558        PathBuf::from(name)
559    }
560}
561
562/// Recognises a volume of a RAR set by its name. A bare `name.rar` counts
563/// only if `name.r00` sits next to it, so a single RAR file is not a set.
564fn rar_volume(path: &Path) -> Option<RarSet> {
565    let name = path.file_name()?.to_str()?;
566    let lower = name.to_ascii_lowercase();
567    let upper = name.chars().rev().take(3).all(|c| !c.is_ascii_lowercase());
568    let (stem_len, ext) = lower.rsplit_once('.').map(|(s, e)| (s.len(), e))?;
569    let stem = &name[..stem_len];
570    if ext == "rar" {
571        if let Some((before, digits)) = stem.to_ascii_lowercase().rsplit_once(".part")
572            && !digits.is_empty()
573            && digits.bytes().all(|b| b.is_ascii_digit())
574        {
575            let n: usize = digits.parse().ok()?;
576            return Some(RarSet {
577                stem: path.with_file_name(&name[..before.len()]),
578                style: RarStyle::Part {
579                    width: digits.len(),
580                },
581                index: n.checked_sub(1)?,
582                upper,
583            });
584        }
585        let set = RarSet {
586            stem: path.with_file_name(stem),
587            style: RarStyle::Old,
588            index: 0,
589            upper,
590        };
591        return set.volume(1).exists().then_some(set);
592    }
593    let bytes = ext.as_bytes();
594    if bytes.len() == 3
595        && (b'r'..=b'z').contains(&bytes[0])
596        && bytes[1].is_ascii_digit()
597        && bytes[2].is_ascii_digit()
598    {
599        let n = usize::from(bytes[0] - b'r') * 100
600            + usize::from(bytes[1] - b'0') * 10
601            + usize::from(bytes[2] - b'0');
602        let set = RarSet {
603            stem: path.with_file_name(stem),
604            style: RarStyle::Old,
605            index: n + 1,
606            upper,
607        };
608        // Other formats number their volumes the same way (`.z01` for a
609        // split ZIP), so it is a RAR volume only next to its first one.
610        return set.volume(0).exists().then_some(set);
611    }
612    None
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    /// What front ends show while an archive opens: every reader counts, a
620    /// split set is one pass, and a pass can start part way in.
621    #[test]
622    fn reads_are_counted_across_volumes() {
623        let dir = std::env::temp_dir().join(format!("hatchzip-reads-{}", std::process::id()));
624        fs::create_dir_all(&dir).unwrap();
625        fs::write(dir.join("game.7z.001"), vec![1u8; 3000]).unwrap();
626        fs::write(dir.join("game.7z.002"), vec![2u8; 1000]).unwrap();
627
628        let mut storage = Storage::open(&dir.join("game.7z.001"), false).unwrap();
629        let reads = Arc::new(Reads::default());
630        storage.count_reads(reads.clone());
631        assert_eq!(reads.fraction(), Some(0.0));
632
633        let mut half = vec![0; 2000];
634        storage.reader(None).read_exact(&mut half).unwrap();
635        assert_eq!(reads.fraction(), Some(0.5));
636        let mut rest = Vec::new();
637        let mut r = storage.reader(None);
638        r.seek(SeekFrom::Start(2000)).unwrap();
639        r.read_to_end(&mut rest).unwrap();
640        assert_eq!(reads.fraction(), Some(1.0));
641
642        // A resumed pass that starts at byte 3000 has 1000 bytes to read.
643        storage.expect_reads(1000);
644        let mut last = vec![0; 500];
645        r.seek(SeekFrom::Start(3000)).unwrap();
646        r.read_exact(&mut last).unwrap();
647        assert_eq!(reads.fraction(), Some(0.5));
648
649        reads.reset();
650        assert_eq!(reads.fraction(), None);
651        drop(storage);
652        fs::remove_dir_all(&dir).unwrap();
653    }
654}