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