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};
35
36use anyhow::{Context, Result, bail};
37
38use crate::archive::storage::Storage;
39use crate::archive::{self, Kind};
40use crate::engine::{self, Job};
41use crate::fsutil;
42use crate::journal::{Journal, Link, Paths};
43use crate::session;
44
45pub struct Restored {
46    /// The first volume of the restored archive.
47    pub archive: PathBuf,
48    pub format: &'static str,
49    /// Entries the restored archive holds: the ones not yet extracted.
50    pub entries: usize,
51    /// Where the extracted entries stay.
52    pub output: PathBuf,
53}
54
55/// Restores the half-extracted archive `archive` names (any volume of a
56/// split set works).
57pub fn restore(archive: &Path) -> Result<Restored> {
58    let (primary, paths) = session::locate(archive)?;
59    if !paths.exists() {
60        bail!(
61            "{} is not half extracted, so there is nothing to restore",
62            primary.display()
63        );
64    }
65    let (mut journal, tail) = Journal::load(&paths)?;
66    if !journal.parts[0].0.exists() {
67        bail!("every entry is already extracted; run extract to finish cleaning up");
68    }
69    // A streamed entry gives its archive bytes back while it is extracted,
70    // and the journal holds a resume point exactly as long as some are gone.
71    // An entry with holes in it can't go back into an archive.
72    if let Some(r) = &journal.resume {
73        bail!(
74            "{} can't be restored: a large entry was being extracted, and the archive space \
75             of its first {} may already be freed, so it can't be put back. Run extract to \
76             finish the extraction instead",
77            primary.display(),
78            engine::human(r.written)
79        );
80    }
81    recover(&mut journal, &paths)?;
82    // Restoring rewrites the index only and never decrypts file data, so no
83    // password is needed, except for a 7z whose header itself is encrypted.
84    let job = Job::resume(&journal, tail.clone(), true, None)?;
85    if job.units.is_empty() {
86        bail!("every entry is already extracted; run extract to finish");
87    }
88    let out = journal.output.clone();
89    let keep = journal.committed_len;
90
91    let remaining: HashMap<&Path, &archive::Item> = job
92        .units
93        .iter()
94        .flat_map(|u| &u.items)
95        .map(|i| (i.path.as_path(), i))
96        .collect();
97    // Links are made at the very end of an extraction, so the journal holds
98    // every link whose entry is already cut off. A tar hard link whose
99    // target is still in the archive can't be made yet; it goes back in.
100    let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
101        .links
102        .iter()
103        .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
104    let mut expected: Vec<(PathBuf, Kind, u64)> = job
105        .units
106        .iter()
107        .flat_map(|u| &u.items)
108        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
109        .collect();
110    expected.extend(back_in.iter().map(|l| {
111        let size = remaining[l.target.as_path()].size;
112        (l.path.clone(), Kind::HardLink(l.target.clone()), size)
113    }));
114    expected.sort_by(|a, b| a.0.cmp(&b.0));
115
116    // Nothing was cut off yet, so the archive is still the original, index
117    // and all.
118    let untouched = keep == job.storage.original_len();
119    let index = if untouched {
120        None
121    } else {
122        let hard: Vec<(&Path, &Path)> = back_in
123            .iter()
124            .map(|l| (l.path.as_path(), l.target.as_path()))
125            .collect();
126        Some(archive::rebuild_index(
127            job.format_name,
128            &job.storage,
129            tail,
130            keep,
131            &hard,
132        )?)
133    };
134
135    session::clear_uncommitted(&job, &out)?;
136    let make: Vec<Link> = make.into_iter().cloned().collect();
137    engine::make_links(&make, &out)?;
138
139    if let Some(index) = index {
140        let mut undo = Vec::with_capacity(index.patches.len());
141        for (at, bytes) in &index.patches {
142            let mut old = vec![0; bytes.len()];
143            let mut r = job.storage.reader(None);
144            r.seek(SeekFrom::Start(*at))?;
145            r.read_exact(&mut old)
146                .with_context(|| format!("reading {}", primary.display()))?;
147            undo.push((*at, old));
148        }
149        journal.restoring = Some(undo);
150        journal.save(&paths)?;
151
152        job.storage
153            .write_at(keep, &index.append)
154            .context("writing the new index")?;
155        engine::crash_point("restore-appended");
156        for (at, bytes) in &index.patches {
157            job.storage
158                .write_at(*at, bytes)
159                .context("writing the new index")?;
160        }
161        engine::crash_point("restore-written");
162
163        let found = reopen(&primary);
164        if !matches!(&found, Ok(f) if *f == expected) {
165            drop(job);
166            recover(&mut journal, &paths)?;
167            let why = match found {
168                Ok(_) => "it doesn't list the same entries as what is left".to_string(),
169                Err(e) => format!("{e:#}"),
170            };
171            bail!(
172                "the restored archive failed its check ({why}), so the restore was undone. \
173                 Nothing is lost; run extract again to finish, and please report this"
174            );
175        }
176    }
177    let format = job.format_name;
178    drop(job);
179
180    remove(&paths.journal)?;
181    fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
182    remove(&paths.tail)?;
183    Ok(Restored {
184        archive: primary,
185        format,
186        entries: expected.len(),
187        output: out,
188    })
189}
190
191/// Opens the archive as a fresh one, the way a later extraction would, and
192/// lists what is in it.
193fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
194    let job = Job::open(primary, false, None)?;
195    let mut found: Vec<_> = job
196        .units
197        .iter()
198        .flat_map(|u| &u.items)
199        .map(|i| (i.path.clone(), i.kind.clone(), i.size))
200        .collect();
201    found.sort_by(|a, b| a.0.cmp(&b.0));
202    Ok(found)
203}
204
205/// Puts an archive whose restore was interrupted back the way extraction
206/// left it: cuts off whatever restore appended past `committed_len` and puts
207/// back the bytes it overwrote below. Every run that opens a half-extracted
208/// archive for writing does this first, so `extract` continues and `restore`
209/// starts over.
210pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
211    let Some(undo) = journal.restoring.take() else {
212        return Ok(());
213    };
214    let storage = Storage::from_parts(&journal.parts, true)?;
215    storage
216        .cut_to(journal.committed_len)
217        .context("undoing an interrupted restore")?;
218    for (at, bytes) in &undo {
219        storage
220            .write_at(*at, bytes)
221            .context("undoing an interrupted restore")?;
222    }
223    drop(storage);
224    journal.save(paths)
225}
226
227fn remove(path: &Path) -> Result<()> {
228    match fs::remove_file(path) {
229        Err(e) if e.kind() != io::ErrorKind::NotFound => {
230            Err(e).with_context(|| format!("removing {}", path.display()))
231        }
232        _ => Ok(()),
233    }
234}