1use std::collections::HashMap;
32use std::fs;
33use std::io::{self, Read, Seek, SeekFrom};
34use std::path::{Path, PathBuf};
35
36use anyhow::{Context, Result, bail};
37
38use crate::archive::storage::Storage;
39use crate::archive::{self, Kind};
40use crate::engine::{self, Job};
41use crate::fsutil;
42use crate::journal::{Journal, Link, Paths};
43use crate::session;
44
45pub struct Restored {
46 pub archive: PathBuf,
48 pub format: &'static str,
49 pub entries: usize,
51 pub output: PathBuf,
53}
54
55pub fn restore(archive: &Path) -> Result<Restored> {
58 let (primary, paths) = session::locate(archive)?;
59 if !paths.exists() {
60 bail!(
61 "{} is not partially extracted; there is nothing to restore",
62 primary.display()
63 );
64 }
65 let (mut journal, tail) = Journal::load(&paths)?;
66 if !journal.parts[0].0.exists() {
67 bail!("all entries are already extracted. Run extract to complete the cleanup");
68 }
69 if let Some(r) = &journal.resume {
73 if r.stream.is_some() {
74 bail!(
75 "{} cannot be restored: part of its compressed data may already be released, \
76 and a compressed tar cannot be rebuilt from what remains. Run extract to \
77 complete the extraction instead",
78 primary.display()
79 );
80 }
81 bail!(
82 "{} cannot be restored: a large entry was being extracted, and the archive space \
83 of its first {} may already be released. Run extract to complete the \
84 extraction instead",
85 primary.display(),
86 engine::human(r.written)
87 );
88 }
89 recover(&mut journal, &paths)?;
90 let job = Job::resume(&journal, tail.clone(), true, None)?;
93 if job.units.is_empty() {
94 bail!("all entries are already extracted. Run extract to complete the extraction");
95 }
96 let out = journal.output.clone();
97 let keep = journal.committed_len;
98
99 let remaining: HashMap<&Path, &archive::Item> = job
100 .units
101 .iter()
102 .flat_map(|u| &u.items)
103 .map(|i| (i.path.as_path(), i))
104 .collect();
105 let (back_in, make): (Vec<&Link>, Vec<&Link>) = journal
109 .links
110 .iter()
111 .partition(|l| l.hard && remaining.contains_key(l.target.as_path()));
112 let mut expected: Vec<(PathBuf, Kind, u64)> = job
113 .units
114 .iter()
115 .flat_map(|u| &u.items)
116 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
117 .collect();
118 expected.extend(back_in.iter().map(|l| {
119 let size = remaining[l.target.as_path()].size;
120 (l.path.clone(), Kind::HardLink(l.target.clone()), size)
121 }));
122 expected.sort_by(|a, b| a.0.cmp(&b.0));
123
124 let untouched = keep == job.storage.original_len();
127 let index = if untouched {
128 None
129 } else {
130 let hard: Vec<(&Path, &Path)> = back_in
131 .iter()
132 .map(|l| (l.path.as_path(), l.target.as_path()))
133 .collect();
134 Some(archive::rebuild_index(
135 job.format_name,
136 &job.storage,
137 tail,
138 keep,
139 &hard,
140 )?)
141 };
142
143 session::clear_uncommitted(&job, &out)?;
144 let make: Vec<Link> = make.into_iter().cloned().collect();
145 engine::make_links(&make, &out)?;
146
147 if let Some(index) = index {
148 let mut undo = Vec::with_capacity(index.patches.len());
149 for (at, bytes) in &index.patches {
150 let mut old = vec![0; bytes.len()];
151 let mut r = job.storage.reader(None);
152 r.seek(SeekFrom::Start(*at))?;
153 r.read_exact(&mut old)
154 .with_context(|| format!("reading {}", primary.display()))?;
155 undo.push((*at, old));
156 }
157 journal.restoring = Some(undo);
158 journal.save(&paths)?;
159
160 job.storage
161 .write_at(keep, &index.append)
162 .context("writing the new index")?;
163 engine::crash_point("restore-appended");
164 for (at, bytes) in &index.patches {
165 job.storage
166 .write_at(*at, bytes)
167 .context("writing the new index")?;
168 }
169 engine::crash_point("restore-written");
170
171 let found = reopen(&primary);
172 if !matches!(&found, Ok(f) if *f == expected) {
173 drop(job);
174 recover(&mut journal, &paths)?;
175 let why = match found {
176 Ok(_) => "it does not list the same entries as the remaining archive".to_string(),
177 Err(e) => format!("{e:#}"),
178 };
179 bail!(
180 "the restored archive failed verification ({why}) and the restore was reverted. \
181 No data was lost. Run extract to complete the extraction, and report this issue"
182 );
183 }
184 }
185 let format = job.format_name;
186 drop(job);
187
188 remove(&paths.journal)?;
189 fsutil::sync_dir(paths.journal.parent().unwrap_or(Path::new(".")))?;
190 remove(&paths.tail)?;
191 Ok(Restored {
192 archive: primary,
193 format,
194 entries: expected.len(),
195 output: out,
196 })
197}
198
199fn reopen(primary: &Path) -> Result<Vec<(PathBuf, Kind, u64)>> {
202 let job = Job::open(primary, false, None)?;
203 let mut found: Vec<_> = job
204 .units
205 .iter()
206 .flat_map(|u| &u.items)
207 .map(|i| (i.path.clone(), i.kind.clone(), i.size))
208 .collect();
209 found.sort_by(|a, b| a.0.cmp(&b.0));
210 Ok(found)
211}
212
213pub(crate) fn recover(journal: &mut Journal, paths: &Paths) -> Result<()> {
219 let Some(undo) = journal.restoring.take() else {
220 return Ok(());
221 };
222 let storage = Storage::from_parts(&journal.parts, true)?;
223 storage
224 .cut_to(journal.committed_len)
225 .context("undoing an interrupted restore")?;
226 for (at, bytes) in &undo {
227 storage
228 .write_at(*at, bytes)
229 .context("undoing an interrupted restore")?;
230 }
231 drop(storage);
232 journal.save(paths)
233}
234
235fn remove(path: &Path) -> Result<()> {
236 match fs::remove_file(path) {
237 Err(e) if e.kind() != io::ErrorKind::NotFound => {
238 Err(e).with_context(|| format!("removing {}", path.display()))
239 }
240 _ => Ok(()),
241 }
242}