1use 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 pub archive: PathBuf,
48 pub format: &'static str,
49 pub entries: usize,
51 pub output: PathBuf,
53}
54
55pub fn restore(archive: &Path) -> Result<Restored> {
58 let (primary, paths) = session::locate(archive)?;
59 if !paths.exists() {
60 bail!(
61 "{} is not partially extracted; 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!("all entries are already extracted. Run extract to complete the cleanup");
68 }
69 if let Some(r) = &journal.resume {
73 bail!(
74 "{} cannot be restored: a large entry was being extracted, and the archive space \
75 of its first {} may already be released. Run extract to complete the \
76 extraction instead",
77 primary.display(),
78 engine::human(r.written)
79 );
80 }
81 recover(&mut journal, &paths)?;
82 let job = Job::resume(&journal, tail.clone(), true, None)?;
85 if job.units.is_empty() {
86 bail!("all entries are already extracted. Run extract to complete the extraction");
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 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 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 does not list the same entries as the remaining archive".to_string(),
169 Err(e) => format!("{e:#}"),
170 };
171 bail!(
172 "the restored archive failed verification ({why}) and the restore was reverted. \
173 No data was lost. Run extract to complete the extraction, and report this issue"
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
191fn 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
205pub(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}