Skip to main content

hatchzip_core/
restore.rs

1//! Turning a half-extracted archive back into a normal one.
2//!
3//! After an interrupted extraction the archive is a prefix of the original
4//! that holds exactly the entries still to do, and its index lives in the
5//! saved tail. Restore appends a new index for those entries, so any tool
6//! opens the archive again. Nothing below `committed_len` moves, which is why
7//! it needs no more free space than the new index takes.
8//!
9//! The order, and why each step is safe to interrupt:
10//!
11//! 1. Undo any earlier restore that was interrupted (see [`recover`]), and
12//!    finish a pending truncation, so the archive is exactly what extraction
13//!    left: `committed_len` bytes.
14//! 2. Build the new index in memory. Anything restore refuses, it refuses
15//!    here, before writing anything.
16//! 3. Delete output files of batches that were never committed, as a resume
17//!    does: those entries are still in the archive. Make the links the
18//!    journal holds for entries already cut off.
19//! 4. Save the journal with `restoring` set to the bytes step 6 overwrites.
20//!    From here on, any HatchZip run that finds the journal first cuts the
21//!    archive back to `committed_len` and puts those bytes back.
22//! 5. Append the new index at `committed_len` and flush it.
23//! 6. Overwrite what has to change below it (only the 7z start header) and
24//!    flush it.
25//! 7. Open the result as a fresh archive with the same parsers extraction
26//!    uses, and check it lists exactly the entries left. If not, undo.
27//! 8. Delete the journal, then the saved tail. A journal without its tail
28//!    can't be loaded, so the journal goes first; a tail left behind by a
29//!    crash in between is never read again.
30
31use std::collections::HashMap;
32use std::fs;
33use std::io::{self, Read, Seek, SeekFrom};
34use std::path::{Path, PathBuf};
35
36use anyhow::{Context, Result, bail};
37
38use crate::archive::storage::Storage;
39use crate::archive::{self, Kind};
40use crate::engine::{self, Job};
41use crate::fsutil;
42use crate::journal::{Journal, Link, Paths};
43use crate::session;
44
45pub struct Restored {
46    /// The first volume of the restored archive.
47    pub archive: PathBuf,
48    pub format: &'static str,
49    /// Entries the restored archive holds: the ones not yet extracted.
50    pub entries: usize,
51    /// Where the extracted entries stay.
52    pub output: PathBuf,
53}
54
55/// Restores the half-extracted archive `archive` names (any volume of a
56/// split set works).
57pub fn restore(archive: &Path) -> Result<Restored> {
58    let (primary, paths) = session::locate(archive)?;
59    if !paths.exists() {
60        bail!(
61            "{} is not partially extracted; there is nothing to restore",
62            primary.display()
63        );
64    }
65    let (mut journal, tail) = Journal::load(&paths)?;
66    if !journal.parts[0].0.exists() {
67        bail!("all entries are already extracted. Run extract to complete the cleanup");
68    }
69    // A streamed entry gives its archive bytes back while it is extracted,
70    // and the journal holds a resume point exactly as long as some are gone.
71    // An entry with holes in it can't go back into an archive.
72    if let Some(r) = &journal.resume {
73        if r.stream.is_some() {
74            bail!(
75                "{} cannot be restored: part of its compressed data may already be released, \
76                 and a compressed tar cannot be rebuilt from what remains. Run extract to \
77                 complete the extraction instead",
78                primary.display()
79            );
80        }
81        bail!(
82            "{} cannot be restored: a large entry was being extracted, and the archive space \
83             of its first {} may already be released. Run extract to complete the \
84             extraction instead",
85            primary.display(),
86            engine::human(r.written)
87        );
88    }
89    recover(&mut journal, &paths)?;
90    // Restoring rewrites the index only and never decrypts file data, so no
91    // password is needed, except for a 7z whose header itself is encrypted.
92    let job = Job::resume(&journal, tail.clone(), true, None)?;
93    if job.units.is_empty() {
94        bail!("all entries are already extracted. Run extract to complete the extraction");
95    }
96    let out = journal.output.clone();
97    let keep = journal.committed_len;
98
99    let remaining: HashMap<&Path, &archive::Item> = job
100        .units
101        .iter()
102        .flat_map(|u| &u.items)
103        .map(|i| (i.path.as_path(), i))
104        .collect();
105    // Links are made at the very end of an extraction, so the journal holds
106    // every link whose entry is already cut off. A tar hard link whose
107    // target is still in the archive can't be made yet; it goes back in.
108    let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
109        .links
110        .iter()
111        .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
112    let mut expected: Vec<(PathBuf, Kind, u64)> = job
113        .units
114        .iter()
115        .flat_map(|u| &u.items)
116        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
117        .collect();
118    expected.extend(back_in.iter().map(|l| {
119        let size = remaining[l.target.as_path()].size;
120        (l.path.clone(), Kind::HardLink(l.target.clone()), size)
121    }));
122    expected.sort_by(|a, b| a.0.cmp(&b.0));
123
124    // Nothing was cut off yet, so the archive is still the original, index
125    // and all.
126    let untouched = keep == job.storage.original_len();
127    let index = if untouched {
128        None
129    } else {
130        let hard: Vec<(&Path, &Path)> = back_in
131            .iter()
132            .map(|l| (l.path.as_path(), l.target.as_path()))
133            .collect();
134        Some(archive::rebuild_index(
135            job.format_name,
136            &job.storage,
137            tail,
138            keep,
139            &hard,
140        )?)
141    };
142
143    session::clear_uncommitted(&job, &out)?;
144    let make: Vec<Link> = make.into_iter().cloned().collect();
145    engine::make_links(&make, &out)?;
146
147    if let Some(index) = index {
148        let mut undo = Vec::with_capacity(index.patches.len());
149        for (at, bytes) in &index.patches {
150            let mut old = vec![0; bytes.len()];
151            let mut r = job.storage.reader(None);
152            r.seek(SeekFrom::Start(*at))?;
153            r.read_exact(&mut old)
154                .with_context(|| format!("reading {}", primary.display()))?;
155            undo.push((*at, old));
156        }
157        journal.restoring = Some(undo);
158        journal.save(&paths)?;
159
160        job.storage
161            .write_at(keep, &index.append)
162            .context("writing the new index")?;
163        engine::crash_point("restore-appended");
164        for (at, bytes) in &index.patches {
165            job.storage
166                .write_at(*at, bytes)
167                .context("writing the new index")?;
168        }
169        engine::crash_point("restore-written");
170
171        let found = reopen(&primary);
172        if !matches!(&found, Ok(f) if *f == expected) {
173            drop(job);
174            recover(&mut journal, &paths)?;
175            let why = match found {
176                Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
177                Err(e) => format!("{e:#}"),
178            };
179            bail!(
180                "the restored archive failed verification ({why}) and the restore was reverted. \
181                 No data was lost. Run extract to complete the extraction, and report this issue"
182            );
183        }
184    }
185    let format = job.format_name;
186    drop(job);
187
188    remove(&paths.journal)?;
189    fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
190    remove(&paths.tail)?;
191    Ok(Restored {
192        archive: primary,
193        format,
194        entries: expected.len(),
195        output: out,
196    })
197}
198
199/// Opens the archive as a fresh one, the way a later extraction would, and
200/// lists what is in it.
201fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
202    let job = Job::open(primary, false, None)?;
203    let mut found: Vec<_> = job
204        .units
205        .iter()
206        .flat_map(|u| &u.items)
207        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
208        .collect();
209    found.sort_by(|a, b| a.0.cmp(&b.0));
210    Ok(found)
211}
212
213/// Puts an archive whose restore was interrupted back the way extraction
214/// left it: cuts off whatever restore appended past `committed_len` and puts
215/// back the bytes it overwrote below. Every run that opens a half-extracted
216/// archive for writing does this first, so `extract` continues and `restore`
217/// starts over.
218pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
219    let Some(undo) = journal.restoring.take() else {
220        return Ok(());
221    };
222    let storage = Storage::from_parts(&journal.parts, true)?;
223    storage
224        .cut_to(journal.committed_len)
225        .context("undoing an interrupted restore")?;
226    for (at, bytes) in &undo {
227        storage
228            .write_at(*at, bytes)
229            .context("undoing an interrupted restore")?;
230    }
231    drop(storage);
232    journal.save(paths)
233}
234
235fn remove(path: &Path) -> Result<()> {
236    match fs::remove_file(path) {
237        Err(e) if e.kind() != io::ErrorKind::NotFound => {
238            Err(e).with_context(|| format!("removing {}", path.display()))
239        }
240        _ => Ok(()),
241    }
242}