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