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 if journal.keep {
80 return discard(&mut journal, tail, &paths);
81 }
82 if !journal.parts[0].0.exists() {
83 bail!("all entries are already extracted. Run extract to complete the cleanup");
84 }
85 if let Some(r) = &journal.resume {
89 if r.stream.is_some() {
90 bail!(
91 "{} cannot be restored: part of its compressed data may already be released, \
92 and a compressed tar cannot be rebuilt from what remains. Run extract to \
93 complete the extraction instead",
94 primary.display()
95 );
96 }
97 bail!(
98 "{} cannot be restored: a large entry was being extracted, and the archive space \
99 of its first {} may already be released. Run extract to complete the \
100 extraction instead",
101 primary.display(),
102 engine::human(r.written)
103 );
104 }
105 recover(&mut journal, &paths)?;
106 let job = Job::resume(&journal, tail.clone(), true, None, Default::default())
112 .map_err(|e| names_encrypted(e, &primary, "restored"))?;
113 if job.units.is_empty() {
114 if !journal.links.is_empty() {
115 bail!(
116 "every entry is already extracted, so there is nothing to restore; only the \
117 links remain to be created. Run extract to create them"
118 );
119 }
120 bail!("all entries are already extracted. Run extract to complete the extraction");
121 }
122 let out = journal.output.clone();
123 let keep = journal.committed_len;
124
125 let remaining: HashMap<&Path, &archive::Item> = job
126 .units
127 .iter()
128 .flat_map(|u| &u.items)
129 .map(|i| (i.path.as_path(), i))
130 .collect();
131 let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
135 .links
136 .iter()
137 .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
138 let mut expected: Vec<(PathBuf, Kind, u64)> = job
139 .units
140 .iter()
141 .flat_map(|u| &u.items)
142 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
143 .collect();
144 expected.extend(back_in.iter().map(|l| {
145 let size = remaining[l.target.as_path()].size;
146 (l.path.clone(), Kind::HardLink(l.target.clone()), size)
147 }));
148 expected.sort_by(|a, b| a.0.cmp(&b.0));
149
150 let untouched = keep == job.storage.original_len();
153 let index = if untouched {
154 None
155 } else {
156 let hard: Vec<(&Path, &Path)> = back_in
157 .iter()
158 .map(|l| (l.path.as_path(), l.target.as_path()))
159 .collect();
160 Some(archive::rebuild_index(
161 job.format_name,
162 &job.storage,
163 tail,
164 keep,
165 &hard,
166 )?)
167 };
168
169 session::clear_uncommitted(&job, &out)?;
170 let make: Vec<Link> = make.into_iter().cloned().collect();
171 engine::make_links(&make, &out).map_err(|e| {
172 anyhow::anyhow!(
173 "{e:#}\nThe archive was not modified. Resolve the problem shown for each link, then \
174 run restore again"
175 )
176 })?;
177
178 if let Some(index) = index {
179 let mut undo = Vec::with_capacity(index.patches.len());
180 for (at, bytes) in &index.patches {
181 let mut old = vec![0; bytes.len()];
182 let mut r = job.storage.reader(None);
183 r.seek(SeekFrom::Start(*at))?;
184 r.read_exact(&mut old)
185 .with_context(|| format!("reading {}", primary.display()))?;
186 undo.push((*at, old));
187 }
188 journal.restoring = Some(undo);
189 journal.save(&paths)?;
190
191 job.storage
192 .write_at(keep, &index.append)
193 .context("writing the new index")?;
194 engine::crash_point("restore-appended");
195 for (at, bytes) in &index.patches {
196 job.storage
197 .write_at(*at, bytes)
198 .context("writing the new index")?;
199 }
200 engine::crash_point("restore-written");
201
202 let found = reopen(&primary);
203 if !matches!(&found, Ok(f) if *f == expected) {
204 drop(job);
205 recover(&mut journal, &paths)?;
206 let why = match found {
207 Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
208 Err(e) => format!("{e:#}"),
209 };
210 bail!(
211 "the restored archive failed verification ({why}) and the restore was reverted. \
212 No data was lost. Run extract to complete the extraction, and report this issue"
213 );
214 }
215 }
216 let format = job.format_name;
217 drop(job);
218 let set_aside = put_back(&mut journal, &paths, false)?;
221
222 remove(&paths.journal)?;
223 fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
224 remove(&paths.tail)?;
225 crate::chosen::forget(&paths.archive);
228 Ok(Restored {
229 archive: primary,
230 format,
231 entries: expected.len(),
232 output: out,
233 kept: false,
234 set_aside,
235 })
236}
237
238fn discard(journal: &mut Journal, tail: Arc<Tail>, paths: &Paths) -> Result<Restored> {
244 let primary = journal.parts[0].0.clone();
245 let mut restored = Restored {
246 archive: primary.clone(),
247 format: "",
248 entries: 0,
249 output: journal.output.clone(),
250 kept: true,
251 set_aside: 0,
252 };
253 if primary.exists() {
256 let job = Job::resume(journal, tail, true, None, Default::default())
257 .map_err(|e| names_encrypted(e, &primary, "discarded"))?;
258 session::clear_uncommitted(&job, &journal.output)?;
259 restored.format = job.format_name;
260 restored.entries = job.item_count();
261 }
262 restored.set_aside = put_back(journal, paths, primary.exists())?;
264 paths.remove()?;
265 Ok(restored)
266}
267
268fn put_back(journal: &mut Journal, paths: &Paths, over: bool) -> Result<usize> {
274 let Some(r) = journal.replace.as_mut() else {
275 return Ok(0);
276 };
277 r.moved = false;
278 journal.save(paths)?;
279 replace::put_back(&journal.output, over)
280}
281
282fn names_encrypted(e: anyhow::Error, primary: &Path, what: &str) -> anyhow::Error {
286 if !e.is::<archive::PasswordNeeded>() {
287 return e;
288 }
289 anyhow::anyhow!(
290 "{} has encrypted file names, so this extraction cannot be {what}: that needs the \
291 password, which restore does not take. Run extract with the password to complete \
292 the extraction instead",
293 primary.display()
294 )
295}
296
297fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
300 let job = Job::open_as_is(primary, false, None, Default::default())?;
301 let mut found: Vec<_> = job
302 .units
303 .iter()
304 .flat_map(|u| &u.items)
305 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
306 .collect();
307 found.sort_by(|a, b| a.0.cmp(&b.0));
308 Ok(found)
309}
310
311pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
317 let Some(undo) = journal.restoring.take() else {
318 return Ok(());
319 };
320 let storage = Storage::from_parts(&journal.parts, true)?;
321 storage
322 .cut_to(journal.committed_len)
323 .context("undoing an interrupted restore")?;
324 for (at, bytes) in &undo {
325 storage
326 .write_at(*at, bytes)
327 .context("undoing an interrupted restore")?;
328 }
329 drop(storage);
330 journal.save(paths)
331}
332
333fn remove(path: &Path) -> Result<()> {
334 match fs::remove_file(path) {
335 Err(e) if e.kind() != io::ErrorKind::NotFound => {
336 Err(e).with_context(|| format!("removing {}", path.display()))
337 }
338 _ => Ok(()),
339 }
340}