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};
35use std::sync::Arc;
36
37use anyhow::{Context, Result, bail};
38
39use crate::archive::storage::{Storage, Tail};
40use crate::archive::{self, Kind};
41use crate::engine::{self, Job};
42use crate::fsutil;
43use crate::journal::{Journal, Link, Paths};
44use crate::session;
45
46pub struct Restored {
47    /// The first volume of the restored archive.
48    pub archive: PathBuf,
49    pub format: &'static str,
50    /// Entries the restored archive holds: the ones not yet extracted.
51    pub entries: usize,
52    /// Where the extracted entries stay.
53    pub output: PathBuf,
54    /// The extraction kept the archive, so it was never changed and only
55    /// the progress was discarded. The archive still holds every entry.
56    pub kept: bool,
57}
58
59/// Restores the half-extracted archive `archive` names (any volume of a
60/// split set works). `output` is the folder the extraction was started
61/// with, needed only when that was not the default one (see
62/// [`session::check_output`]).
63pub fn restore(archive: &Path, output: Option<&Path>) -> Result<Restored> {
64    let (primary, paths) = session::locate(archive)?;
65    if !paths.exists() {
66        bail!(
67            "{} is not partially extracted; there is nothing to restore",
68            primary.display()
69        );
70    }
71    let (mut journal, tail) = Journal::load(&paths)?;
72    session::check_output(&journal, &primary, output, "restore")?;
73    if journal.keep {
74        return discard(&journal, tail, &paths);
75    }
76    if !journal.parts[0].0.exists() {
77        bail!("all entries are already extracted. Run extract to complete the cleanup");
78    }
79    // A streamed entry gives its archive bytes back while it is extracted,
80    // and the journal holds a resume point exactly as long as some are gone.
81    // An entry with holes in it can't go back into an archive.
82    if let Some(r) = &journal.resume {
83        if r.stream.is_some() {
84            bail!(
85                "{} cannot be restored: part of its compressed data may already be released, \
86                 and a compressed tar cannot be rebuilt from what remains. Run extract to \
87                 complete the extraction instead",
88                primary.display()
89            );
90        }
91        bail!(
92            "{} cannot be restored: a large entry was being extracted, and the archive space \
93             of its first {} may already be released. Run extract to complete the \
94             extraction instead",
95            primary.display(),
96            engine::human(r.written)
97        );
98    }
99    recover(&mut journal, &paths)?;
100    // Restoring rewrites the index only and never decrypts file data, so no
101    // password is needed. An archive whose file names are encrypted (a 7z
102    // with an encrypted header, a RAR made with "Encrypt file names") can't
103    // even be listed without one, and a new index for it would have to be
104    // encrypted too, so it is refused.
105    let job = Job::resume(&journal, tail.clone(), true, None, Default::default())
106        .map_err(|e| names_encrypted(e, &primary, "restored"))?;
107    if job.units.is_empty() {
108        if !journal.links.is_empty() {
109            bail!(
110                "every entry is already extracted, so there is nothing to restore; only the \
111                 links remain to be created. Run extract to create them"
112            );
113        }
114        bail!("all entries are already extracted. Run extract to complete the extraction");
115    }
116    let out = journal.output.clone();
117    let keep = journal.committed_len;
118
119    let remaining: HashMap<&Path, &archive::Item> = job
120        .units
121        .iter()
122        .flat_map(|u| &u.items)
123        .map(|i| (i.path.as_path(), i))
124        .collect();
125    // Links are made at the very end of an extraction, so the journal holds
126    // every link whose entry is already cut off. A tar hard link whose
127    // target is still in the archive can't be made yet; it goes back in.
128    let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
129        .links
130        .iter()
131        .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
132    let mut expected: Vec<(PathBuf, Kind, u64)> = job
133        .units
134        .iter()
135        .flat_map(|u| &u.items)
136        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
137        .collect();
138    expected.extend(back_in.iter().map(|l| {
139        let size = remaining[l.target.as_path()].size;
140        (l.path.clone(), Kind::HardLink(l.target.clone()), size)
141    }));
142    expected.sort_by(|a, b| a.0.cmp(&b.0));
143
144    // Nothing was cut off yet, so the archive is still the original, index
145    // and all.
146    let untouched = keep == job.storage.original_len();
147    let index = if untouched {
148        None
149    } else {
150        let hard: Vec<(&Path, &Path)> = back_in
151            .iter()
152            .map(|l| (l.path.as_path(), l.target.as_path()))
153            .collect();
154        Some(archive::rebuild_index(
155            job.format_name,
156            &job.storage,
157            tail,
158            keep,
159            &hard,
160        )?)
161    };
162
163    session::clear_uncommitted(&job, &out)?;
164    let make: Vec<Link> = make.into_iter().cloned().collect();
165    engine::make_links(&make, &out).map_err(|e| {
166        anyhow::anyhow!(
167            "{e:#}\nThe archive was not modified. Resolve the problem shown for each link, then \
168             run restore again"
169        )
170    })?;
171
172    if let Some(index) = index {
173        let mut undo = Vec::with_capacity(index.patches.len());
174        for (at, bytes) in &index.patches {
175            let mut old = vec![0; bytes.len()];
176            let mut r = job.storage.reader(None);
177            r.seek(SeekFrom::Start(*at))?;
178            r.read_exact(&mut old)
179                .with_context(|| format!("reading {}", primary.display()))?;
180            undo.push((*at, old));
181        }
182        journal.restoring = Some(undo);
183        journal.save(&paths)?;
184
185        job.storage
186            .write_at(keep, &index.append)
187            .context("writing the new index")?;
188        engine::crash_point("restore-appended");
189        for (at, bytes) in &index.patches {
190            job.storage
191                .write_at(*at, bytes)
192                .context("writing the new index")?;
193        }
194        engine::crash_point("restore-written");
195
196        let found = reopen(&primary);
197        if !matches!(&found, Ok(f) if *f == expected) {
198            drop(job);
199            recover(&mut journal, &paths)?;
200            let why = match found {
201                Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
202                Err(e) => format!("{e:#}"),
203            };
204            bail!(
205                "the restored archive failed verification ({why}) and the restore was reverted. \
206                 No data was lost. Run extract to complete the extraction, and report this issue"
207            );
208        }
209    }
210    let format = job.format_name;
211    drop(job);
212
213    remove(&paths.journal)?;
214    fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
215    remove(&paths.tail)?;
216    Ok(Restored {
217        archive: primary,
218        format,
219        entries: expected.len(),
220        output: out,
221        kept: false,
222    })
223}
224
225/// An extraction that keeps the archive never changed it, so there is
226/// nothing to rebuild: what a crashed batch left half written is deleted, as
227/// a resume would, and the progress files go. Finished files stay.
228fn discard(journal: &Journal, tail: Arc<Tail>, paths: &Paths) -> Result<Restored> {
229    let primary = journal.parts[0].0.clone();
230    let mut restored = Restored {
231        archive: primary.clone(),
232        format: "",
233        entries: 0,
234        output: journal.output.clone(),
235        kept: true,
236    };
237    // Moved away by the person: nothing says which files are half written,
238    // and nothing else is left to do.
239    if primary.exists() {
240        let job = Job::resume(journal, tail, true, None, Default::default())
241            .map_err(|e| names_encrypted(e, &primary, "discarded"))?;
242        session::clear_uncommitted(&job, &journal.output)?;
243        restored.format = job.format_name;
244        restored.entries = job.item_count();
245    }
246    paths.remove()?;
247    Ok(restored)
248}
249
250/// Restore takes no password, so an archive that can't be read without one
251/// is refused with what to do instead, rather than asked for a password the
252/// command has no way to take.
253fn names_encrypted(e: anyhow::Error, primary: &Path, what: &str) -> anyhow::Error {
254    if !e.is::<archive::PasswordNeeded>() {
255        return e;
256    }
257    anyhow::anyhow!(
258        "{} has encrypted file names, so this extraction cannot be {what}: that needs the \
259         password, which restore does not take. Run extract with the password to complete \
260         the extraction instead",
261        primary.display()
262    )
263}
264
265/// Opens the archive as a fresh one, the way a later extraction would, and
266/// lists what is in it.
267fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
268    let job = Job::open_as_is(primary, false, None, Default::default())?;
269    let mut found: Vec<_> = job
270        .units
271        .iter()
272        .flat_map(|u| &u.items)
273        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
274        .collect();
275    found.sort_by(|a, b| a.0.cmp(&b.0));
276    Ok(found)
277}
278
279/// Puts an archive whose restore was interrupted back the way extraction
280/// left it: cuts off whatever restore appended past `committed_len` and puts
281/// back the bytes it overwrote below. Every run that opens a half-extracted
282/// archive for writing does this first, so `extract` continues and `restore`
283/// starts over.
284pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
285    let Some(undo) = journal.restoring.take() else {
286        return Ok(());
287    };
288    let storage = Storage::from_parts(&journal.parts, true)?;
289    storage
290        .cut_to(journal.committed_len)
291        .context("undoing an interrupted restore")?;
292    for (at, bytes) in &undo {
293        storage
294            .write_at(*at, bytes)
295            .context("undoing an interrupted restore")?;
296    }
297    drop(storage);
298    journal.save(paths)
299}
300
301fn remove(path: &Path) -> Result<()> {
302    match fs::remove_file(path) {
303        Err(e) if e.kind() != io::ErrorKind::NotFound => {
304            Err(e).with_context(|| format!("removing {}", path.display()))
305        }
306        _ => Ok(()),
307    }
308}