1use std::collections::HashMap;
34use std::fs;
35use std::io::{self, Read, Seek, SeekFrom};
36use std::path::{Path, PathBuf};
37use std::sync::Arc;
38
39use anyhow::{Context, Result, bail};
40
41use crate::archive::storage::{Storage, Tail};
42use crate::archive::{self, Kind};
43use crate::engine::{self, Job};
44use crate::fsutil;
45use crate::journal::{Journal, Link, Paths};
46use crate::{replace, session};
47
48pub struct Restored {
49 pub archive: PathBuf,
51 pub format: &'static str,
52 pub entries: usize,
54 pub output: PathBuf,
56 pub kept: bool,
59 pub set_aside: usize,
63}
64
65pub fn restore(archive: &Path, output: Option<&Path>) -> Result<Restored> {
70 let (primary, paths) = session::locate(archive)?;
71 if !paths.exists() {
72 bail!(
73 "{} is not partially extracted; there is nothing to restore",
74 primary.display()
75 );
76 }
77 let (mut journal, tail) = Journal::load(&paths)?;
78 session::check_output(&journal, &primary, output, "restore")?;
79 session::check_recorded_case(&journal)?;
80 if journal.keep {
81 return discard(&mut journal, tail, &paths);
82 }
83 if journal.done {
87 if !journal.links.is_empty() {
88 bail!(
89 "every entry is already extracted, so there is nothing to restore; only the \
90 links remain to be created. Run extract to create them"
91 );
92 }
93 bail!("every entry is already extracted; run extract to complete the cleanup");
94 }
95 if !journal.parts[0].0.exists() {
96 bail!("all entries are already extracted. Run extract to complete the cleanup");
97 }
98 if let Some(r) = &journal.resume {
102 if r.stream.is_some() {
103 bail!(
104 "{} cannot be restored: part of its compressed data may already be released, \
105 and a compressed tar cannot be rebuilt from what remains. Run extract to \
106 complete the extraction instead",
107 primary.display()
108 );
109 }
110 bail!(
111 "{} cannot be restored: a large entry was being extracted, and the archive space \
112 of its first {} may already be released. Run extract to complete the \
113 extraction instead",
114 primary.display(),
115 engine::human(r.written)
116 );
117 }
118 recover(&mut journal, &paths)?;
119 let job = Job::resume(&journal, tail.clone(), true, None, Default::default())
125 .map_err(|e| names_encrypted(e, &primary, "restored"))?;
126 if job.units.is_empty() {
127 if !journal.links.is_empty() {
128 bail!(
129 "every entry is already extracted, so there is nothing to restore; only the \
130 links remain to be created. Run extract to create them"
131 );
132 }
133 bail!("all entries are already extracted. Run extract to complete the extraction");
134 }
135 let out = journal.output.clone();
136 let keep = journal.committed_len;
137
138 let remaining: HashMap<&Path, &archive::Item> = job
139 .units
140 .iter()
141 .flat_map(|u| &u.items)
142 .map(|i| (i.path.as_path(), i))
143 .collect();
144 let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
148 .links
149 .iter()
150 .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
151 let mut expected: Vec<(PathBuf, Kind, u64)> = job
152 .units
153 .iter()
154 .flat_map(|u| &u.items)
155 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
156 .collect();
157 expected.extend(back_in.iter().map(|l| {
158 let size = remaining[l.target.as_path()].size;
159 (l.path.clone(), Kind::HardLink(l.target.clone()), size)
160 }));
161 expected.sort_by(|a, b| a.0.cmp(&b.0));
162
163 let untouched = keep == job.storage.original_len();
166 let index = if untouched {
167 None
168 } else {
169 let hard: Vec<(&Path, &Path)> = back_in
170 .iter()
171 .map(|l| (l.path.as_path(), l.target.as_path()))
172 .collect();
173 Some(archive::rebuild_index(
174 job.format_name,
175 &job.storage,
176 tail,
177 keep,
178 &hard,
179 )?)
180 };
181
182 session::clear_uncommitted(&job, &out)?;
183 let make: Vec<Link> = make.into_iter().cloned().collect();
184 engine::make_links(&make, &out).map_err(|e| {
185 anyhow::anyhow!(
186 "{e:#}\nThe archive was not modified. Resolve the problem shown for each link, then \
187 run restore again"
188 )
189 })?;
190
191 if let Some(index) = index {
192 let mut undo = Vec::with_capacity(index.patches.len());
193 for (at, bytes) in &index.patches {
194 let mut old = vec![0; bytes.len()];
195 let mut r = job.storage.reader(None);
196 r.seek(SeekFrom::Start(*at))?;
197 r.read_exact(&mut old)
198 .with_context(|| format!("reading {}", primary.display()))?;
199 undo.push((*at, old));
200 }
201 journal.restoring = Some(undo);
202 journal.save(&paths)?;
203
204 job.storage
205 .write_at(keep, &index.append)
206 .context("writing the new index")?;
207 engine::crash_point("restore-appended");
208 for (at, bytes) in &index.patches {
209 job.storage
210 .write_at(*at, bytes)
211 .context("writing the new index")?;
212 }
213 engine::crash_point("restore-written");
214
215 let found = reopen(&primary);
216 if !matches!(&found, Ok(f) if *f == expected) {
217 drop(job);
218 recover(&mut journal, &paths)?;
219 let why = match found {
220 Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
221 Err(e) => format!("{e:#}"),
222 };
223 bail!(
224 "the restored archive failed verification ({why}) and the restore was reverted. \
225 No data was lost. Run extract to complete the extraction, and report this issue"
226 );
227 }
228 }
229 let format = job.format_name;
230 drop(job);
231 let set_aside = put_back(&mut journal, &paths, false)?;
234
235 remove(&paths.journal)?;
236 fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
237 remove(&paths.tail)?;
238 crate::chosen::forget(&paths.archive);
241 Ok(Restored {
242 archive: primary,
243 format,
244 entries: expected.len(),
245 output: out,
246 kept: false,
247 set_aside,
248 })
249}
250
251fn discard(journal: &mut Journal, tail: Arc<Tail>, paths: &Paths) -> Result<Restored> {
257 let primary = journal.parts[0].0.clone();
258 let mut restored = Restored {
259 archive: primary.clone(),
260 format: "",
261 entries: 0,
262 output: journal.output.clone(),
263 kept: true,
264 set_aside: 0,
265 };
266 if primary.exists() {
269 let job = Job::resume(journal, tail, true, None, Default::default())
270 .map_err(|e| names_encrypted(e, &primary, "discarded"))?;
271 session::clear_uncommitted(&job, &journal.output)?;
272 restored.format = job.format_name;
273 restored.entries = job.item_count();
274 }
275 restored.set_aside = put_back(journal, paths, primary.exists())?;
277 paths.remove()?;
278 Ok(restored)
279}
280
281fn put_back(journal: &mut Journal, paths: &Paths, over: bool) -> Result<usize> {
287 let Some(r) = journal.replace.as_mut() else {
288 return Ok(0);
289 };
290 r.moved = false;
291 journal.save(paths)?;
292 replace::put_back(&journal.output, over)
293}
294
295fn names_encrypted(e: anyhow::Error, primary: &Path, what: &str) -> anyhow::Error {
299 if !e.is::<archive::PasswordNeeded>() {
300 return e;
301 }
302 anyhow::anyhow!(
303 "{} has encrypted file names, so this extraction cannot be {what}: that needs the \
304 password, which restore does not take. Run extract with the password to complete \
305 the extraction instead",
306 primary.display()
307 )
308}
309
310fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
313 let job = Job::open_as_is(primary, false, None, Default::default())?;
314 let mut found: Vec<_> = job
315 .units
316 .iter()
317 .flat_map(|u| &u.items)
318 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
319 .collect();
320 found.sort_by(|a, b| a.0.cmp(&b.0));
321 Ok(found)
322}
323
324pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
330 let Some(undo) = journal.restoring.take() else {
331 return Ok(());
332 };
333 let storage = Storage::from_parts(&journal.parts, true)?;
334 storage
335 .cut_to(journal.committed_len)
336 .context("undoing an interrupted restore")?;
337 for (at, bytes) in &undo {
338 storage
339 .write_at(*at, bytes)
340 .context("undoing an interrupted restore")?;
341 }
342 drop(storage);
343 journal.save(paths)
344}
345
346fn remove(path: &Path) -> Result<()> {
347 match fs::remove_file(path) {
348 Err(e) if e.kind() != io::ErrorKind::NotFound => {
349 Err(e).with_context(|| format!("removing {}", path.display()))
350 }
351 _ => Ok(()),
352 }
353}