1use 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 pub archive: PathBuf,
49 pub format: &'static str,
50 pub entries: usize,
52 pub output: PathBuf,
54 pub kept: bool,
57}
58
59pub fn restore(archive: &Path, output: Option<&Path>) -> Result<Restored> {
64 let (primary, paths) = session::locate(archive)?;
65 if !paths.exists() {
66 bail!(
67 "{} is not partially extracted; there is nothing to restore",
68 primary.display()
69 );
70 }
71 let (mut journal, tail) = Journal::load(&paths)?;
72 session::check_output(&journal, &primary, output, "restore")?;
73 if journal.keep {
74 return discard(&journal, tail, &paths);
75 }
76 if !journal.parts[0].0.exists() {
77 bail!("all entries are already extracted. Run extract to complete the cleanup");
78 }
79 if let Some(r) = &journal.resume {
83 if r.stream.is_some() {
84 bail!(
85 "{} cannot be restored: part of its compressed data may already be released, \
86 and a compressed tar cannot be rebuilt from what remains. Run extract to \
87 complete the extraction instead",
88 primary.display()
89 );
90 }
91 bail!(
92 "{} cannot be restored: a large entry was being extracted, and the archive space \
93 of its first {} may already be released. Run extract to complete the \
94 extraction instead",
95 primary.display(),
96 engine::human(r.written)
97 );
98 }
99 recover(&mut journal, &paths)?;
100 let job = Job::resume(&journal, tail.clone(), true, None, Default::default())
106 .map_err(|e| names_encrypted(e, &primary, "restored"))?;
107 if job.units.is_empty() {
108 if !journal.links.is_empty() {
109 bail!(
110 "every entry is already extracted, so there is nothing to restore; only the \
111 links remain to be created. Run extract to create them"
112 );
113 }
114 bail!("all entries are already extracted. Run extract to complete the extraction");
115 }
116 let out = journal.output.clone();
117 let keep = journal.committed_len;
118
119 let remaining: HashMap<&Path, &archive::Item> = job
120 .units
121 .iter()
122 .flat_map(|u| &u.items)
123 .map(|i| (i.path.as_path(), i))
124 .collect();
125 let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
129 .links
130 .iter()
131 .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
132 let mut expected: Vec<(PathBuf, Kind, u64)> = job
133 .units
134 .iter()
135 .flat_map(|u| &u.items)
136 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
137 .collect();
138 expected.extend(back_in.iter().map(|l| {
139 let size = remaining[l.target.as_path()].size;
140 (l.path.clone(), Kind::HardLink(l.target.clone()), size)
141 }));
142 expected.sort_by(|a, b| a.0.cmp(&b.0));
143
144 let untouched = keep == job.storage.original_len();
147 let index = if untouched {
148 None
149 } else {
150 let hard: Vec<(&Path, &Path)> = back_in
151 .iter()
152 .map(|l| (l.path.as_path(), l.target.as_path()))
153 .collect();
154 Some(archive::rebuild_index(
155 job.format_name,
156 &job.storage,
157 tail,
158 keep,
159 &hard,
160 )?)
161 };
162
163 session::clear_uncommitted(&job, &out)?;
164 let make: Vec<Link> = make.into_iter().cloned().collect();
165 engine::make_links(&make, &out).map_err(|e| {
166 anyhow::anyhow!(
167 "{e:#}\nThe archive was not modified. Resolve the problem shown for each link, then \
168 run restore again"
169 )
170 })?;
171
172 if let Some(index) = index {
173 let mut undo = Vec::with_capacity(index.patches.len());
174 for (at, bytes) in &index.patches {
175 let mut old = vec![0; bytes.len()];
176 let mut r = job.storage.reader(None);
177 r.seek(SeekFrom::Start(*at))?;
178 r.read_exact(&mut old)
179 .with_context(|| format!("reading {}", primary.display()))?;
180 undo.push((*at, old));
181 }
182 journal.restoring = Some(undo);
183 journal.save(&paths)?;
184
185 job.storage
186 .write_at(keep, &index.append)
187 .context("writing the new index")?;
188 engine::crash_point("restore-appended");
189 for (at, bytes) in &index.patches {
190 job.storage
191 .write_at(*at, bytes)
192 .context("writing the new index")?;
193 }
194 engine::crash_point("restore-written");
195
196 let found = reopen(&primary);
197 if !matches!(&found, Ok(f) if *f == expected) {
198 drop(job);
199 recover(&mut journal, &paths)?;
200 let why = match found {
201 Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
202 Err(e) => format!("{e:#}"),
203 };
204 bail!(
205 "the restored archive failed verification ({why}) and the restore was reverted. \
206 No data was lost. Run extract to complete the extraction, and report this issue"
207 );
208 }
209 }
210 let format = job.format_name;
211 drop(job);
212
213 remove(&paths.journal)?;
214 fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
215 remove(&paths.tail)?;
216 Ok(Restored {
217 archive: primary,
218 format,
219 entries: expected.len(),
220 output: out,
221 kept: false,
222 })
223}
224
225fn discard(journal: &Journal, tail: Arc<Tail>, paths: &Paths) -> Result<Restored> {
229 let primary = journal.parts[0].0.clone();
230 let mut restored = Restored {
231 archive: primary.clone(),
232 format: "",
233 entries: 0,
234 output: journal.output.clone(),
235 kept: true,
236 };
237 if primary.exists() {
240 let job = Job::resume(journal, tail, true, None, Default::default())
241 .map_err(|e| names_encrypted(e, &primary, "discarded"))?;
242 session::clear_uncommitted(&job, &journal.output)?;
243 restored.format = job.format_name;
244 restored.entries = job.item_count();
245 }
246 paths.remove()?;
247 Ok(restored)
248}
249
250fn names_encrypted(e: anyhow::Error, primary: &Path, what: &str) -> anyhow::Error {
254 if !e.is::<archive::PasswordNeeded>() {
255 return e;
256 }
257 anyhow::anyhow!(
258 "{} has encrypted file names, so this extraction cannot be {what}: that needs the \
259 password, which restore does not take. Run extract with the password to complete \
260 the extraction instead",
261 primary.display()
262 )
263}
264
265fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
268 let job = Job::open_as_is(primary, false, None, Default::default())?;
269 let mut found: Vec<_> = job
270 .units
271 .iter()
272 .flat_map(|u| &u.items)
273 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
274 .collect();
275 found.sort_by(|a, b| a.0.cmp(&b.0));
276 Ok(found)
277}
278
279pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
285 let Some(undo) = journal.restoring.take() else {
286 return Ok(());
287 };
288 let storage = Storage::from_parts(&journal.parts, true)?;
289 storage
290 .cut_to(journal.committed_len)
291 .context("undoing an interrupted restore")?;
292 for (at, bytes) in &undo {
293 storage
294 .write_at(*at, bytes)
295 .context("undoing an interrupted restore")?;
296 }
297 drop(storage);
298 journal.save(paths)
299}
300
301fn remove(path: &Path) -> Result<()> {
302 match fs::remove_file(path) {
303 Err(e) if e.kind() != io::ErrorKind::NotFound => {
304 Err(e).with_context(|| format!("removing {}", path.display()))
305 }
306 _ => Ok(()),
307 }
308}