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