1use 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 pub archive: PathBuf,
55 pub format: &'static str,
56 pub entries: usize,
58 pub output: PathBuf,
60 pub kept: bool,
63 pub set_aside: usize,
67}
68
69pub 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 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 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 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 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 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 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 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 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 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 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
300fn 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 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 restored.set_aside = put_back(journal, paths, primary.exists())?;
326 paths.remove()?;
327 Ok(restored)
328}
329
330fn 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
344fn 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
359fn 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
373pub(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
395fn 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}