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