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())?;
100 if job.units.is_empty() {
101 if !journal.links.is_empty() {
102 bail!(
103 "every entry is already extracted, so there is nothing to restore; only the \
104 links remain to be created. Run extract to create them"
105 );
106 }
107 bail!("all entries are already extracted. Run extract to complete the extraction");
108 }
109 let out = journal.output.clone();
110 let keep = journal.committed_len;
111
112 let remaining: HashMap<&Path, &archive::Item> = job
113 .units
114 .iter()
115 .flat_map(|u| &u.items)
116 .map(|i| (i.path.as_path(), i))
117 .collect();
118 let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
122 .links
123 .iter()
124 .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
125 let mut expected: Vec<(PathBuf, Kind, u64)> = job
126 .units
127 .iter()
128 .flat_map(|u| &u.items)
129 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
130 .collect();
131 expected.extend(back_in.iter().map(|l| {
132 let size = remaining[l.target.as_path()].size;
133 (l.path.clone(), Kind::HardLink(l.target.clone()), size)
134 }));
135 expected.sort_by(|a, b| a.0.cmp(&b.0));
136
137 let untouched = keep == job.storage.original_len();
140 let index = if untouched {
141 None
142 } else {
143 let hard: Vec<(&Path, &Path)> = back_in
144 .iter()
145 .map(|l| (l.path.as_path(), l.target.as_path()))
146 .collect();
147 Some(archive::rebuild_index(
148 job.format_name,
149 &job.storage,
150 tail,
151 keep,
152 &hard,
153 )?)
154 };
155
156 session::clear_uncommitted(&job, &out)?;
157 let make: Vec<Link> = make.into_iter().cloned().collect();
158 engine::make_links(&make, &out).map_err(|e| {
159 anyhow::anyhow!(
160 "{e:#}\nThe archive was not modified. Resolve the problem shown for each link, then \
161 run restore again"
162 )
163 })?;
164
165 if let Some(index) = index {
166 let mut undo = Vec::with_capacity(index.patches.len());
167 for (at, bytes) in &index.patches {
168 let mut old = vec![0; bytes.len()];
169 let mut r = job.storage.reader(None);
170 r.seek(SeekFrom::Start(*at))?;
171 r.read_exact(&mut old)
172 .with_context(|| format!("reading {}", primary.display()))?;
173 undo.push((*at, old));
174 }
175 journal.restoring = Some(undo);
176 journal.save(&paths)?;
177
178 job.storage
179 .write_at(keep, &index.append)
180 .context("writing the new index")?;
181 engine::crash_point("restore-appended");
182 for (at, bytes) in &index.patches {
183 job.storage
184 .write_at(*at, bytes)
185 .context("writing the new index")?;
186 }
187 engine::crash_point("restore-written");
188
189 let found = reopen(&primary);
190 if !matches!(&found, Ok(f) if *f == expected) {
191 drop(job);
192 recover(&mut journal, &paths)?;
193 let why = match found {
194 Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
195 Err(e) => format!("{e:#}"),
196 };
197 bail!(
198 "the restored archive failed verification ({why}) and the restore was reverted. \
199 No data was lost. Run extract to complete the extraction, and report this issue"
200 );
201 }
202 }
203 let format = job.format_name;
204 drop(job);
205
206 remove(&paths.journal)?;
207 fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
208 remove(&paths.tail)?;
209 Ok(Restored {
210 archive: primary,
211 format,
212 entries: expected.len(),
213 output: out,
214 kept: false,
215 })
216}
217
218fn discard(journal: &Journal, tail: Arc<Tail>, paths: &Paths) -> Result<Restored> {
222 let primary = journal.parts[0].0.clone();
223 let mut restored = Restored {
224 archive: primary.clone(),
225 format: "",
226 entries: 0,
227 output: journal.output.clone(),
228 kept: true,
229 };
230 if primary.exists() {
233 let job = Job::resume(journal, tail, true, None, Default::default())?;
234 session::clear_uncommitted(&job, &journal.output)?;
235 restored.format = job.format_name;
236 restored.entries = job.item_count();
237 }
238 paths.remove()?;
239 Ok(restored)
240}
241
242fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
245 let job = Job::open_as_is(primary, false, None, Default::default())?;
246 let mut found: Vec<_> = job
247 .units
248 .iter()
249 .flat_map(|u| &u.items)
250 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
251 .collect();
252 found.sort_by(|a, b| a.0.cmp(&b.0));
253 Ok(found)
254}
255
256pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
262 let Some(undo) = journal.restoring.take() else {
263 return Ok(());
264 };
265 let storage = Storage::from_parts(&journal.parts, true)?;
266 storage
267 .cut_to(journal.committed_len)
268 .context("undoing an interrupted restore")?;
269 for (at, bytes) in &undo {
270 storage
271 .write_at(*at, bytes)
272 .context("undoing an interrupted restore")?;
273 }
274 drop(storage);
275 journal.save(paths)
276}
277
278fn remove(path: &Path) -> Result<()> {
279 match fs::remove_file(path) {
280 Err(e) if e.kind() != io::ErrorKind::NotFound => {
281 Err(e).with_context(|| format!("removing {}", path.display()))
282 }
283 _ => Ok(()),
284 }
285}