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