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