Skip to main content

reth_cli_commands/download/
extract.rs

1use super::{
2    fetch::{ArchiveFetcher, DownloadedArchive},
3    is_managed_snapshot_path,
4    progress::{
5        ArchiveExtractionProgress, ArchiveExtractionProgressHandle, DownloadProgress,
6        DownloadRequestLimiter, ProgressReader, SharedProgressReader,
7    },
8    session::DownloadSession,
9    verify::ExtractedHashes,
10    MAX_DOWNLOAD_RETRIES, RETRY_BACKOFF_SECS,
11};
12use eyre::{Result, WrapErr};
13use lz4::Decoder;
14use reqwest::blocking::Client as BlockingClient;
15use reth_cli_util::cancellation::CancellationToken;
16use reth_fs_util::{self as fs, FsPathError};
17use std::{
18    cell::RefCell,
19    collections::HashSet,
20    fs::FileTimes,
21    io::{self, BufWriter, Read},
22    mem,
23    ops::Range,
24    os::unix::fs::PermissionsExt,
25    panic::{self, AssertUnwindSafe},
26    path::{Component, Path, PathBuf},
27    sync::{
28        atomic::{AtomicBool, Ordering},
29        mpsc::{sync_channel, Receiver, SendError, SyncSender, TrySendError},
30        Arc,
31    },
32    thread,
33    time::{Duration, Instant, UNIX_EPOCH},
34};
35use tar::Archive;
36use tracing::{info, warn};
37use url::Url;
38use zstd::stream::read::Decoder as ZstdDecoder;
39
40const EXTENSION_TAR_LZ4: &str = ".tar.lz4";
41const EXTENSION_TAR_ZSTD: &str = ".tar.zst";
42const STREAMING_EXTRACTION_PROGRESS_MIN_FILE_SIZE: u64 = 64 * 1024 * 1024;
43const EXTRACTION_PROGRESS_POLL_INTERVAL: Duration = Duration::from_millis(100);
44
45/// Extracted file bytes sent to the hashing thread at a time.
46const FILE_HASH_BATCH_SIZE: usize = 1 << 20;
47
48/// Batches buffered for the hashing thread before extraction waits for it.
49const FILE_HASH_QUEUE_LEN: usize = 16;
50
51/// Size of each decoded buffer handed from the decoder thread to the unpack thread.
52const DECODED_CHUNK_SIZE: usize = 1 << 20;
53
54/// Decoded buffers queued between the decoder thread and the unpack thread.
55const DECODED_CHUNK_QUEUE_LEN: usize = 16;
56
57/// Bytes written to an extracted regular file per write.
58const EXTRACTED_FILE_WRITE_SIZE: usize = 8 << 20;
59
60/// Decoded bytes read after the tar end marker. Covers the padding `tar` writes, so the
61/// compression checksum of a normal archive is checked, without decoding an unbounded suffix.
62const MAX_TRAILING_DECODED_BYTES: u64 = 1 << 20;
63
64/// Supported compression formats for snapshots
65#[derive(Debug, Clone, Copy)]
66pub(crate) enum CompressionFormat {
67    /// LZ4-compressed tar archive.
68    Lz4,
69    /// Zstandard-compressed tar archive.
70    Zstd,
71}
72
73impl CompressionFormat {
74    /// Detect compression format from file extension
75    pub(crate) fn from_url(url: &str) -> Result<Self> {
76        let path =
77            Url::parse(url).map(|u| u.path().to_string()).unwrap_or_else(|_| url.to_string());
78
79        if path.ends_with(EXTENSION_TAR_LZ4) {
80            Ok(Self::Lz4)
81        } else if path.ends_with(EXTENSION_TAR_ZSTD) {
82            Ok(Self::Zstd)
83        } else {
84            Err(eyre::eyre!(
85                "Unsupported file format. Expected .tar.lz4 or .tar.zst, got: {}",
86                path
87            ))
88        }
89    }
90}
91
92/// Extracts a compressed tar archive to the target directory with progress tracking.
93fn extract_archive<R: Read>(
94    reader: R,
95    total_size: u64,
96    format: CompressionFormat,
97    target_dir: &Path,
98    static_files_dir: Option<&Path>,
99    cancel_token: CancellationToken,
100) -> Result<bool> {
101    let progress_reader = ProgressReader::new(reader, total_size, cancel_token);
102    let installed =
103        extract_archive_raw(progress_reader, format, target_dir, static_files_dir, None)?;
104    println!();
105    Ok(installed)
106}
107
108/// Extracts a compressed tar archive without progress tracking and reports whether it installed
109/// any execution files.
110fn extract_archive_raw<R: Read>(
111    reader: R,
112    format: CompressionFormat,
113    target_dir: &Path,
114    static_files_dir: Option<&Path>,
115    progress: Option<&mut ArchiveExtractionProgress>,
116) -> Result<bool> {
117    match format {
118        CompressionFormat::Lz4 => unpack_archive(
119            Archive::new(Decoder::new(reader)?),
120            target_dir,
121            static_files_dir,
122            progress,
123            None,
124        ),
125        CompressionFormat::Zstd => unpack_archive(
126            Archive::new(ZstdDecoder::new(reader)?),
127            target_dir,
128            static_files_dir,
129            progress,
130            None,
131        ),
132    }
133}
134
135/// Extracts a compressed tar archive like [`extract_archive_raw`], hashing each declared output
136/// written as a regular file from the bytes written to it so verification does not have to read
137/// it back. `outputs` holds the destination paths of the archive's declared outputs.
138///
139/// Decompression runs on its own thread, feeding the tar unpack and file writes on the calling
140/// thread through a bounded queue of decoded buffers, so a large archive is not limited by one
141/// core doing both. Up to [`MAX_TRAILING_DECODED_BYTES`] after the tar end marker are decoded
142/// too, so the compression checksum of a normal archive is validated. `on_unpack_error` runs as
143/// soon as unpacking fails or panics, before this waits for the decoder, so the caller can stop
144/// whatever feeds `reader`. A panic resumes once the decoder is joined.
145pub(crate) fn extract_archive_hashed<R: Read + Send>(
146    reader: R,
147    format: CompressionFormat,
148    target_dir: &Path,
149    static_files_dir: Option<&Path>,
150    outputs: HashSet<PathBuf>,
151    progress: Option<&mut ArchiveExtractionProgress>,
152    on_unpack_error: impl FnOnce(),
153) -> Result<ExtractedHashes> {
154    let (sender, chunks) = sync_channel(DECODED_CHUNK_QUEUE_LEN);
155    let (recycled, reusable) = sync_channel(DECODED_CHUNK_QUEUE_LEN);
156    thread::scope(|scope| {
157        let decoder = scope.spawn(move || decode_archive(reader, format, &sender, &reusable));
158        let mut chunks = DecodedChunks { chunks, recycled, chunk: Vec::new(), offset: 0 };
159        // A panic is caught here, not only by the caller, so the input is stopped before the
160        // decoder, which may be waiting on it, is joined.
161        let unpacked = panic::catch_unwind(AssertUnwindSafe(|| -> Result<FileHasher> {
162            let hasher = RefCell::new(FileHasher::spawn(outputs));
163            unpack_archive(
164                Archive::new(FileHashTee { inner: &mut chunks, position: 0, hasher: &hasher }),
165                target_dir,
166                static_files_dir,
167                progress,
168                Some(&hasher),
169            )?;
170            io::copy(&mut Read::take(&mut chunks, MAX_TRAILING_DECODED_BYTES), &mut io::sink())?;
171            Ok(hasher.into_inner())
172        }));
173        if !matches!(unpacked, Ok(Ok(_))) {
174            on_unpack_error();
175        }
176        // Stops a decoder that is still sending.
177        drop(chunks);
178        decoder.join().map_err(|_| eyre::eyre!("Archive decoder thread panicked"))?;
179        unpacked.unwrap_or_else(|payload| panic::resume_unwind(payload))?.join()
180    })
181}
182
183/// Decodes `reader` into recycled buffers and sends them, in order, until the end of the
184/// stream or until the receiver is gone, which only happens when unpacking stopped. A decode
185/// error is sent in place of the next buffer.
186fn decode_archive<R: Read>(
187    reader: R,
188    format: CompressionFormat,
189    sender: &SyncSender<io::Result<Vec<u8>>>,
190    reusable: &Receiver<Vec<u8>>,
191) {
192    let decode = || -> io::Result<()> {
193        let mut decoder: Box<dyn Read + '_> = match format {
194            CompressionFormat::Lz4 => Box::new(Decoder::new(reader)?),
195            CompressionFormat::Zstd => Box::new(ZstdDecoder::new(reader)?),
196        };
197        loop {
198            let mut chunk = reusable.try_recv().unwrap_or_default();
199            chunk.resize(DECODED_CHUNK_SIZE, 0);
200            let read = loop {
201                match decoder.read(&mut chunk) {
202                    Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
203                    result => break result?,
204                }
205            };
206            if read == 0 {
207                return Ok(())
208            }
209            chunk.truncate(read);
210            if sender.send(Ok(chunk)).is_err() {
211                return Ok(())
212            }
213        }
214    };
215    if let Err(error) = decode() {
216        // The receiver is gone only after unpacking stopped, which reports its own error.
217        match sender.send(Err(error)) {
218            Ok(()) | Err(SendError(_)) => {}
219        }
220    }
221}
222
223/// Presents decoded buffers from [`decode_archive`] as one byte stream, returning each consumed
224/// buffer to the decoder for reuse.
225struct DecodedChunks {
226    /// Decoded buffers, or the decode error that ended the stream.
227    chunks: Receiver<io::Result<Vec<u8>>>,
228    /// Consumed buffers returned to the decoder.
229    recycled: SyncSender<Vec<u8>>,
230    /// Buffer being read.
231    chunk: Vec<u8>,
232    /// Bytes of `chunk` already read.
233    offset: usize,
234}
235
236impl Read for DecodedChunks {
237    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
238        if buf.is_empty() {
239            return Ok(0)
240        }
241        if self.offset == self.chunk.len() {
242            // Recycle before blocking so the decoder can reuse this buffer for the chunk being
243            // waited on. A full queue or a finished decoder just drops it.
244            match self.recycled.try_send(mem::take(&mut self.chunk)) {
245                Ok(()) | Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => {}
246            }
247            // Reset with the take, so reads after the end of the stream or an error find an
248            // empty chunk again.
249            self.offset = 0;
250            match self.chunks.recv() {
251                Ok(chunk) => self.chunk = chunk?,
252                Err(_) => return Ok(0),
253            }
254        }
255        let len = buf.len().min(self.chunk.len() - self.offset);
256        buf[..len].copy_from_slice(&self.chunk[self.offset..self.offset + len]);
257        self.offset += len;
258        Ok(len)
259    }
260}
261
262fn unpack_archive<R: Read>(
263    mut archive: Archive<R>,
264    target_dir: &Path,
265    static_files_dir: Option<&Path>,
266    mut progress: Option<&mut ArchiveExtractionProgress>,
267    hasher: Option<&RefCell<FileHasher>>,
268) -> Result<bool> {
269    let entries = archive.entries().wrap_err_with(|| {
270        format!("failed to read archive entries for `{}`", target_dir.display())
271    })?;
272
273    let mut installed_execution_file = false;
274    for entry in entries {
275        let mut entry = entry.wrap_err_with(|| {
276            format!("failed to read archive entry for `{}`", target_dir.display())
277        })?;
278        // Check the path before it can contribute an extraction hash or touch the output tree.
279        let entry_type = entry.header().entry_type();
280        // `tar` yields some metadata headers as entries, but unpacking them writes no file.
281        if entry_type.is_pax_global_extensions() ||
282            entry_type.is_pax_local_extensions() ||
283            entry_type.is_gnu_longname() ||
284            entry_type.is_gnu_longlink()
285        {
286            continue
287        }
288        let path = entry.path()?;
289        eyre::ensure!(
290            !entry_type.is_symlink() && !entry_type.is_hard_link(),
291            "Archive links are unsupported: `{}`",
292            path.display()
293        );
294        let directory = entry_type.is_dir() || is_legacy_tar_directory(&entry);
295        if !is_managed_snapshot_path(&path, directory) {
296            continue
297        }
298        let hashing = match hasher {
299            Some(hasher) => {
300                hasher.borrow_mut().start_entry(&entry, target_dir, static_files_dir)?
301            }
302            None => false,
303        };
304        // A config file or a directory does not count as restored execution data. Links are
305        // rejected above and `tar` unpacks unknown entry types as files, so anything else counts.
306        let execution_file =
307            !directory && path.strip_prefix(".").unwrap_or(&path) != Path::new("reth.toml");
308        installed_execution_file |= extract_entry_with_progress(
309            &mut entry,
310            target_dir,
311            static_files_dir,
312            progress.as_deref_mut(),
313        )? && execution_file;
314        if hashing && let Some(hasher) = hasher {
315            hasher.borrow_mut().finish_file()?;
316        }
317    }
318
319    Ok(installed_execution_file)
320}
321
322/// Passes archive bytes from the decompressor to the tar reader, feeding them to a
323/// [`FileHasher`] on the way.
324struct FileHashTee<'a, R> {
325    /// Decompressed tar stream.
326    inner: R,
327    /// Offset in the tar stream of the next byte read, which matches tar's own entry offsets.
328    position: u64,
329    /// Hasher of the file being extracted.
330    hasher: &'a RefCell<FileHasher>,
331}
332
333impl<R: Read> Read for FileHashTee<'_, R> {
334    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
335        let read = self.inner.read(buf)?;
336        self.hasher.borrow_mut().feed(self.position, &buf[..read])?;
337        self.position += read as u64;
338        Ok(read)
339    }
340}
341
342/// Hashes the data of each regular file as tar extracts it, on a separate thread so hashing
343/// stays off the extraction thread.
344struct FileHasher {
345    /// Tar stream offsets of the current file's data; empty when no file is being hashed.
346    range: Range<u64>,
347    /// Bytes of the current file seen so far.
348    seen: u64,
349    /// Current file bytes not yet sent to the hashing thread.
350    batch: Vec<u8>,
351    /// Sends work to the hashing thread.
352    sender: SyncSender<FileHashMessage>,
353    /// Hashing thread, which returns the hashes of every completed file.
354    thread: thread::JoinHandle<ExtractedHashes>,
355    /// Destination paths of the archive's declared outputs; other entries are not hashed, so
356    /// the recorded hashes are bounded by the manifest rather than the archive's entry count.
357    outputs: HashSet<PathBuf>,
358}
359
360/// Work for the [`FileHasher`] thread.
361enum FileHashMessage {
362    /// Starts hashing the file extracted to this path.
363    Start(PathBuf),
364    /// Next bytes of the current file.
365    Bytes(Vec<u8>),
366    /// Records the current file's hash.
367    Finish,
368    /// Drops the current file because not all of its bytes were seen.
369    Discard,
370    /// Drops every recorded hash, because an entry replaces a file that an earlier entry may
371    /// have written.
372    ForgetAll,
373}
374
375impl FileHasher {
376    /// Starts the hashing thread for an archive with the given declared output paths.
377    fn spawn(outputs: HashSet<PathBuf>) -> Self {
378        let (sender, receiver) = sync_channel(FILE_HASH_QUEUE_LEN);
379        let thread = thread::spawn(move || {
380            let mut hashes = ExtractedHashes::default();
381            let mut current = None;
382            for message in receiver {
383                match message {
384                    FileHashMessage::Start(path) => current = Some((path, blake3::Hasher::new())),
385                    FileHashMessage::Bytes(bytes) => {
386                        if let Some((_, hasher)) = &mut current {
387                            hasher.update(&bytes);
388                        }
389                    }
390                    FileHashMessage::Finish => {
391                        if let Some((path, hasher)) = current.take() {
392                            hashes.insert(path, hasher.count(), hasher.finalize());
393                        }
394                    }
395                    FileHashMessage::Discard => current = None,
396                    FileHashMessage::ForgetAll => hashes.clear(),
397                }
398            }
399            hashes
400        });
401        Self {
402            range: 0..0,
403            seen: 0,
404            batch: Vec::with_capacity(FILE_HASH_BATCH_SIZE),
405            sender,
406            thread,
407            outputs,
408        }
409    }
410
411    /// Starts hashing `entry` if it is a regular file at a declared output path, and returns
412    /// whether it did.
413    ///
414    /// Other entries, such as links, sparse files and undeclared paths, get no hash, so their
415    /// outputs are verified by reading them back.
416    fn start_entry<R: Read>(
417        &mut self,
418        entry: &tar::Entry<'_, R>,
419        target_dir: &Path,
420        static_files_dir: Option<&Path>,
421    ) -> Result<bool> {
422        let Some(path) = entry_destination_path(entry, target_dir, static_files_dir)? else {
423            return Ok(false)
424        };
425        // This entry replaces a file already at the destination. An earlier entry may have
426        // written it under another spelling of the path, such as a different case on a
427        // case-insensitive filesystem, so which recorded hash it had is unknown and none is kept.
428        if std::fs::symlink_metadata(&path).is_ok_and(|metadata| !metadata.is_dir()) {
429            self.send(FileHashMessage::ForgetAll)?;
430        }
431        if !self.outputs.contains(&path) {
432            return Ok(false)
433        }
434        if !is_regular_file(entry) {
435            return Ok(false)
436        }
437        let start = entry.raw_file_position();
438        self.range = start..start + entry.size();
439        self.seen = 0;
440        self.send(FileHashMessage::Start(path))?;
441        Ok(true)
442    }
443
444    /// Hashes the bytes of the current file among `bytes`, which start at tar stream offset
445    /// `position`.
446    fn feed(&mut self, position: u64, bytes: &[u8]) -> io::Result<()> {
447        let start = self.range.start.max(position);
448        let end = self.range.end.min(position + bytes.len() as u64);
449        if start >= end {
450            return Ok(())
451        }
452        self.seen += end - start;
453        let mut bytes = &bytes[(start - position) as usize..(end - position) as usize];
454        // Batches are filled exactly, so a batch never outgrows its allocation.
455        while !bytes.is_empty() {
456            let (head, tail) =
457                bytes.split_at(bytes.len().min(FILE_HASH_BATCH_SIZE - self.batch.len()));
458            self.batch.extend_from_slice(head);
459            bytes = tail;
460            if self.batch.len() == FILE_HASH_BATCH_SIZE {
461                self.send_batch()?;
462            }
463        }
464        Ok(())
465    }
466
467    /// Records the current file's hash once all of its bytes were seen, and discards it
468    /// otherwise.
469    fn finish_file(&mut self) -> io::Result<()> {
470        self.send_batch()?;
471        let complete = self.seen == self.range.end - self.range.start;
472        self.range = 0..0;
473        self.send(if complete { FileHashMessage::Finish } else { FileHashMessage::Discard })
474    }
475
476    /// Waits for the hashing thread and returns the hashes of every completed file.
477    fn join(self) -> Result<ExtractedHashes> {
478        drop(self.sender);
479        self.thread.join().map_err(|_| eyre::eyre!("Extracted file hashing thread panicked"))
480    }
481
482    fn send_batch(&mut self) -> io::Result<()> {
483        if self.batch.is_empty() {
484            return Ok(())
485        }
486        let batch = mem::replace(&mut self.batch, Vec::with_capacity(FILE_HASH_BATCH_SIZE));
487        self.send(FileHashMessage::Bytes(batch))
488    }
489
490    fn send(&self, message: FileHashMessage) -> io::Result<()> {
491        self.sender.send(message).map_err(|_| io::Error::other("extracted file hashing stopped"))
492    }
493}
494
495/// Returns the path within the static files directory, accepting tar's optional `./` prefix.
496pub(crate) fn static_file_relative_path(path: &Path) -> Option<&Path> {
497    path.strip_prefix(".").unwrap_or(path).strip_prefix("static_files").ok()
498}
499
500/// Fails if any existing component of `relative_path` below `root` is a symlink.
501///
502/// Components that do not exist yet are ignored. `root` itself is trusted and not checked. This
503/// is a point-in-time check: it does not stop a link from being created right after it returns.
504pub(crate) fn ensure_no_symlinks(root: &Path, relative_path: &Path) -> Result<()> {
505    let mut current = root.to_path_buf();
506    for part in relative_path.components() {
507        current.push(part);
508        match std::fs::symlink_metadata(&current) {
509            Ok(metadata) => eyre::ensure!(
510                !metadata.file_type().is_symlink(),
511                "Archive path `{}` contains a symlink",
512                current.display()
513            ),
514            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
515            Err(err) => return Err(err.into()),
516        }
517    }
518    Ok(())
519}
520
521/// Extracts static files beneath their configured root without allowing archive paths or links
522/// to escape it.
523fn unpack_static_file<R: Read>(
524    entry: &mut tar::Entry<'_, R>,
525    static_files_dir: &Path,
526    relative_path: &Path,
527) -> Result<()> {
528    eyre::ensure!(
529        relative_path
530            .components()
531            .all(|part| matches!(part, Component::Normal(_) | Component::CurDir)),
532        "Invalid static file archive path: {}",
533        relative_path.display()
534    );
535    let entry_type = entry.header().entry_type();
536    eyre::ensure!(
537        entry_type.is_file() || entry_type.is_dir(),
538        "Unsupported static file archive entry"
539    );
540    fs::create_dir_all(static_files_dir)?;
541    let root = static_files_dir.to_path_buf();
542    let dest = root.join(relative_path);
543    // Check each existing ancestor before creating directories or replacing an output.
544    ensure_no_symlinks(&root, relative_path)?;
545    if relative_path.as_os_str().is_empty() {
546        return Ok(())
547    }
548    if let Some(parent) = dest.parent() {
549        fs::create_dir_all(parent)?;
550    }
551    if is_regular_file(entry) {
552        return write_regular_file(entry, &dest, &root)
553    }
554    entry.unpack(dest)?;
555    Ok(())
556}
557
558/// Returns whether `entry` holds its data as one sequential run of bytes.
559fn is_regular_file<R: Read>(entry: &tar::Entry<'_, R>) -> bool {
560    let entry_type = entry.header().entry_type();
561    (entry_type.is_file() || entry_type.is_contiguous()) && !is_legacy_tar_directory(entry)
562}
563
564/// Keeps directory classification consistent with the `tar` crate's BSD-tar compatibility rule.
565fn is_legacy_tar_directory<R: Read>(entry: &tar::Entry<'_, R>) -> bool {
566    entry.header().as_ustar().is_none() && entry.path_bytes().ends_with(b"/")
567}
568
569/// Writes a regular file entry to `dest` in large blocks.
570///
571/// `tar` copies file data in 8 KiB writes, which costs a syscall and a filesystem lock per
572/// 8 KiB. This mirrors `tar`'s unpacking of a regular file into `root`: missing parent
573/// directories are created only inside `root`, an existing file is replaced, and the
574/// permission bits and modification time are restored.
575fn write_regular_file<R: Read>(
576    entry: &mut tar::Entry<'_, R>,
577    dest: &Path,
578    root: &Path,
579) -> Result<()> {
580    let parent = dest.parent().ok_or_else(|| eyre::eyre!("Invalid archive path"))?;
581    let mut missing = Vec::new();
582    let mut ancestor = parent;
583    while ancestor.symlink_metadata().is_err() {
584        missing.push(ancestor);
585        let Some(next) = ancestor.parent() else { break };
586        ancestor = next;
587    }
588    for dir in missing.into_iter().rev() {
589        if let Some(dir_parent) = dir.parent() {
590            ensure_inside(root, dir_parent)?;
591        }
592        fs::create_dir_all(dir)?;
593    }
594    ensure_inside(root, parent)?;
595
596    fs::remove_file_if_exists(dest)?;
597    let file = std::fs::OpenOptions::new()
598        .write(true)
599        .create_new(true)
600        .open(dest)
601        .map_err(|error| FsPathError::create_file(error, dest))?;
602    // Copying zero-fills the whole buffer before the first read, so a small file gets a buffer
603    // of its own size.
604    let capacity = entry.size().min(EXTRACTED_FILE_WRITE_SIZE as u64) as usize;
605    let mut writer = BufWriter::with_capacity(capacity, file);
606    let written = io::copy(entry, &mut writer)?;
607    let file = writer.into_inner().map_err(|error| error.into_error())?;
608    eyre::ensure!(written == entry.size(), "Archive entry ended early: {}", dest.display());
609
610    if let Ok(mode) = entry.header().mode() {
611        file.set_permissions(std::fs::Permissions::from_mode(mode & 0o777))?;
612    }
613    // Like `tar`, read the time as signed seconds, so times before the epoch are kept, avoid zero
614    // times, and set the access time too. Times `SystemTime` cannot represent are skipped.
615    if let Ok(mtime) = entry.header().mtime() {
616        let secs = mtime.max(1).cast_signed();
617        let offset = Duration::from_secs(secs.unsigned_abs());
618        let modified =
619            if secs < 0 { UNIX_EPOCH.checked_sub(offset) } else { UNIX_EPOCH.checked_add(offset) };
620        if let Some(modified) = modified {
621            file.set_times(FileTimes::new().set_accessed(modified).set_modified(modified))?;
622        }
623    }
624    Ok(())
625}
626
627/// Fails unless `dir` resolves to a path inside `root`, so archive entries cannot escape `root`
628/// through symlinks.
629fn ensure_inside(root: &Path, dir: &Path) -> Result<()> {
630    eyre::ensure!(
631        dir.canonicalize()?.starts_with(root.canonicalize()?),
632        "Archive entry would unpack outside of {}",
633        root.display()
634    );
635    Ok(())
636}
637
638fn unpack_entry<R: Read>(
639    entry: &mut tar::Entry<'_, R>,
640    target_dir: &Path,
641    static_files_dir: Option<&Path>,
642) -> Result<bool> {
643    let path = entry.path()?.into_owned();
644    if let Some(static_files_dir) = static_files_dir &&
645        let Some(relative_path) = static_file_relative_path(&path)
646    {
647        unpack_static_file(entry, static_files_dir, relative_path)?;
648        Ok(true)
649    } else {
650        ensure_no_symlinks(target_dir, &path)?;
651        if is_regular_file(entry) &&
652            let Some(dest) = entry_destination_path(entry, target_dir, static_files_dir)?
653        {
654            write_regular_file(entry, &dest, target_dir)?;
655            Ok(true)
656        } else {
657            Ok(entry.unpack_in(target_dir)?)
658        }
659    }
660}
661
662fn extract_entry_with_progress<R: Read>(
663    entry: &mut tar::Entry<'_, R>,
664    target_dir: &Path,
665    static_files_dir: Option<&Path>,
666    progress: Option<&mut ArchiveExtractionProgress>,
667) -> Result<bool> {
668    let size = entry.header().entry_size().unwrap_or(0);
669    let entry_type = entry.header().entry_type();
670
671    if !entry_type.is_file() || size == 0 {
672        return unpack_entry(entry, target_dir, static_files_dir)
673            .wrap_err_with(|| format!("failed to extract archive into `{}`", target_dir.display()))
674    }
675
676    if size < STREAMING_EXTRACTION_PROGRESS_MIN_FILE_SIZE {
677        let installed = unpack_entry(entry, target_dir, static_files_dir).wrap_err_with(|| {
678            format!("failed to extract archive into `{}`", target_dir.display())
679        })?;
680        if let Some(progress) = progress {
681            progress.record_extracted(size);
682        }
683        return Ok(installed)
684    }
685
686    let Some(progress_handle) = progress.as_ref().and_then(|progress| progress.handle()) else {
687        return unpack_entry(entry, target_dir, static_files_dir)
688            .wrap_err_with(|| format!("failed to extract archive into `{}`", target_dir.display()))
689    };
690
691    let Some(entry_path) = entry_destination_path(entry, target_dir, static_files_dir)? else {
692        return unpack_entry(entry, target_dir, static_files_dir)
693            .wrap_err_with(|| format!("failed to extract archive into `{}`", target_dir.display()))
694    };
695
696    let stop = Arc::new(AtomicBool::new(false));
697    let monitor = spawn_extraction_progress_monitor(entry_path, progress_handle, Arc::clone(&stop));
698    let unpack_result = unpack_entry(entry, target_dir, static_files_dir)
699        .wrap_err_with(|| format!("failed to extract archive into `{}`", target_dir.display()));
700    stop.store(true, Ordering::Relaxed);
701
702    let monitor_result = monitor.join();
703    let installed = unpack_result?;
704    monitor_result.map_err(|_| eyre::eyre!("extraction progress monitor panicked"))?;
705    Ok(installed)
706}
707
708fn entry_destination_path<R: Read>(
709    entry: &tar::Entry<'_, R>,
710    target_dir: &Path,
711    static_files_dir: Option<&Path>,
712) -> Result<Option<PathBuf>> {
713    let mut file_dst = target_dir.to_path_buf();
714    let path = entry.path().wrap_err("invalid path in archive entry")?;
715    let path = if let Some(static_files_dir) = static_files_dir &&
716        let Some(relative_path) = static_file_relative_path(&path)
717    {
718        file_dst = static_files_dir.to_path_buf();
719        relative_path
720    } else {
721        path.as_ref()
722    };
723
724    for part in path.components() {
725        match part {
726            Component::Prefix(..) | Component::RootDir | Component::CurDir => continue,
727            Component::ParentDir => return Ok(None),
728            Component::Normal(part) => file_dst.push(part),
729        }
730    }
731
732    if file_dst == target_dir {
733        return Ok(None)
734    }
735
736    Ok(Some(file_dst))
737}
738
739fn spawn_extraction_progress_monitor(
740    entry_path: PathBuf,
741    progress: ArchiveExtractionProgressHandle,
742    stop: Arc<AtomicBool>,
743) -> thread::JoinHandle<()> {
744    thread::spawn(move || {
745        let mut extracted = 0_u64;
746
747        loop {
748            record_extracted_file_bytes(&entry_path, &progress, &mut extracted);
749            if stop.load(Ordering::Relaxed) {
750                break;
751            }
752            thread::sleep(EXTRACTION_PROGRESS_POLL_INTERVAL);
753        }
754    })
755}
756
757fn record_extracted_file_bytes(
758    entry_path: &Path,
759    progress: &ArchiveExtractionProgressHandle,
760    extracted: &mut u64,
761) {
762    let Ok(meta) = fs::metadata(entry_path) else { return };
763    let len = meta.len();
764    if len > *extracted {
765        progress.record_extracted(len - *extracted);
766        *extracted = len;
767    }
768}
769
770/// Extracts a snapshot from a local file.
771fn extract_from_file(
772    path: &Path,
773    format: CompressionFormat,
774    target_dir: &Path,
775    static_files_dir: Option<&Path>,
776) -> Result<bool> {
777    let file = std::fs::File::open(path)?;
778    let total_size = file.metadata()?.len();
779    info!(target: "reth::cli",
780        file = %path.display(),
781        size = %DownloadProgress::format_size(total_size),
782        "Extracting local archive"
783    );
784    let start = Instant::now();
785    let installed = extract_archive(
786        file,
787        total_size,
788        format,
789        target_dir,
790        static_files_dir,
791        CancellationToken::new(),
792    )?;
793    if installed {
794        info!(target: "reth::cli",
795            file = %path.display(),
796            elapsed = %DownloadProgress::format_duration(start.elapsed()),
797            "Local extraction complete"
798        );
799    }
800    Ok(installed)
801}
802
803/// Streams a remote archive directly into the extractor without writing to disk.
804///
805/// Returns whether it installed any execution files. On failure, retries from scratch up to
806/// [`MAX_DOWNLOAD_RETRIES`] times.
807pub(crate) fn streaming_download_and_extract(
808    url: &str,
809    format: CompressionFormat,
810    target_dir: &Path,
811    static_files_dir: Option<&Path>,
812    session: &DownloadSession,
813) -> Result<bool> {
814    if let Some(path) = archive_file_url_path(url)? {
815        let size = path.metadata()?.len();
816        let installed = extract_from_file(&path, format, target_dir, static_files_dir)?;
817        session.record_archive_output_complete(size);
818        return Ok(installed)
819    }
820
821    let shared = session.progress();
822    let quiet = session.progress().is_some();
823    let mut last_error: Option<eyre::Error> = None;
824
825    for attempt in 1..=MAX_DOWNLOAD_RETRIES {
826        if attempt > 1 {
827            info!(target: "reth::cli",
828                url = %url,
829                attempt,
830                max = MAX_DOWNLOAD_RETRIES,
831                "Retrying streaming download from scratch"
832            );
833        }
834
835        let client = BlockingClient::builder().connect_timeout(Duration::from_secs(30)).build()?;
836        let _request_permit = session
837            .request_limiter()
838            .map(|limiter| limiter.acquire(session.progress(), session.cancel_token()))
839            .transpose()?;
840
841        let response = match client.get(url).send().and_then(|r| r.error_for_status()) {
842            Ok(r) => r,
843            Err(error) => {
844                let err = eyre::Error::from(error);
845                if attempt < MAX_DOWNLOAD_RETRIES {
846                    warn!(target: "reth::cli",
847                        url = %url,
848                        attempt,
849                        max = MAX_DOWNLOAD_RETRIES,
850                        err = %err,
851                        "Streaming request failed, retrying"
852                    );
853                }
854                last_error = Some(err);
855                if attempt < MAX_DOWNLOAD_RETRIES {
856                    std::thread::sleep(
857                        session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
858                    );
859                }
860                continue;
861            }
862        };
863
864        if !quiet && let Some(size) = response.content_length() {
865            info!(target: "reth::cli",
866                url = %url,
867                size = %DownloadProgress::format_size(size),
868                "Streaming archive"
869            );
870        }
871
872        let result = if let Some(progress) = shared {
873            let reader = SharedProgressReader { inner: response, progress: Arc::clone(progress) };
874            extract_archive_raw(reader, format, target_dir, static_files_dir, None)
875        } else {
876            let total_size = response.content_length().unwrap_or(0);
877            extract_archive(
878                response,
879                total_size,
880                format,
881                target_dir,
882                static_files_dir,
883                session.cancel_token().clone(),
884            )
885        };
886
887        match result {
888            Ok(installed) => return Ok(installed),
889            Err(error) => {
890                if attempt < MAX_DOWNLOAD_RETRIES {
891                    warn!(target: "reth::cli",
892                        url = %url,
893                        attempt,
894                        max = MAX_DOWNLOAD_RETRIES,
895                        err = %error,
896                        "Streaming extraction failed, retrying"
897                    );
898                }
899                last_error = Some(error);
900                if attempt < MAX_DOWNLOAD_RETRIES {
901                    std::thread::sleep(
902                        session.retry_delay(Duration::from_secs(RETRY_BACKOFF_SECS)),
903                    );
904                }
905            }
906        }
907    }
908
909    Err(last_error.unwrap_or_else(|| {
910        eyre::eyre!("Streaming download failed after {MAX_DOWNLOAD_RETRIES} attempts")
911    }))
912}
913
914/// Resolves a `file://` archive URL to its local path.
915fn archive_file_url_path(url: &str) -> Result<Option<PathBuf>> {
916    let Ok(parsed) = Url::parse(url) else { return Ok(None) };
917    if parsed.scheme() != "file" {
918        return Ok(None)
919    }
920
921    parsed
922        .to_file_path()
923        .map(Some)
924        .map_err(|_| eyre::eyre!("Invalid file:// archive URL path: {url}"))
925}
926
927/// Fetches the snapshot from a remote URL with resume support, then extracts it.
928fn download_and_extract(
929    url: &str,
930    format: CompressionFormat,
931    target_dir: &Path,
932    static_files_dir: Option<&Path>,
933    session: DownloadSession,
934) -> Result<()> {
935    let quiet = session.progress().is_some();
936    let fetcher = ArchiveFetcher::new(url.to_string(), target_dir, session.clone(), None);
937    let DownloadedArchive { path: downloaded_path, size: total_size } =
938        fetcher.download(None, None)?;
939
940    let file_name =
941        downloaded_path.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default();
942
943    if !quiet {
944        info!(target: "reth::cli",
945            file = %file_name,
946            size = %DownloadProgress::format_size(total_size),
947            "Extracting archive"
948        );
949    }
950    let file = fs::open(&downloaded_path)?;
951
952    let installed = if quiet {
953        extract_archive_raw(file, format, target_dir, static_files_dir, None)?
954    } else {
955        extract_archive(
956            file,
957            total_size,
958            format,
959            target_dir,
960            static_files_dir,
961            session.cancel_token().clone(),
962        )?
963    };
964    fetcher.cleanup_downloaded_files();
965    ensure_execution_files(installed)?;
966    if !quiet {
967        info!(target: "reth::cli",
968            file = %file_name,
969            "Extraction complete"
970        );
971    }
972
973    session.record_archive_output_complete(total_size);
974
975    Ok(())
976}
977
978fn ensure_execution_files(installed: bool) -> Result<()> {
979    eyre::ensure!(installed, "Snapshot archive contains no execution files");
980    Ok(())
981}
982
983/// Downloads and extracts a snapshot, blocking until finished.
984///
985/// Supports `file://` URLs for local files and HTTP(S) URLs for remote downloads.
986/// When `resumable` is true, downloads to a `.part` file first with HTTP Range resume
987/// support. Otherwise streams directly into the extractor.
988fn blocking_download_and_extract(
989    url: &str,
990    target_dir: &Path,
991    static_files_dir: Option<&Path>,
992    resumable: bool,
993    request_limiter: Option<Arc<DownloadRequestLimiter>>,
994    cancel_token: CancellationToken,
995    retry_backoff: Option<Duration>,
996) -> Result<()> {
997    let format = CompressionFormat::from_url(url)?;
998
999    if let Ok(parsed_url) = Url::parse(url) &&
1000        parsed_url.scheme() == "file"
1001    {
1002        let session = DownloadSession::new(None, request_limiter, cancel_token)
1003            .with_retry_backoff(retry_backoff);
1004        let file_path = parsed_url
1005            .to_file_path()
1006            .map_err(|_| eyre::eyre!("Invalid file:// URL path: {}", url))?;
1007        let installed = extract_from_file(&file_path, format, target_dir, static_files_dir)?;
1008        ensure_execution_files(installed)?;
1009        session.record_archive_output_complete(file_path.metadata()?.len());
1010        Ok(())
1011    } else if let Some(request_limiter) = request_limiter {
1012        download_and_extract(
1013            url,
1014            format,
1015            target_dir,
1016            static_files_dir,
1017            DownloadSession::new(None, Some(request_limiter), cancel_token)
1018                .with_retry_backoff(retry_backoff),
1019        )
1020    } else if resumable {
1021        let session =
1022            DownloadSession::new(None, Some(DownloadRequestLimiter::new(1)), cancel_token)
1023                .with_retry_backoff(retry_backoff);
1024        download_and_extract(url, format, target_dir, static_files_dir, session)
1025    } else {
1026        let session =
1027            DownloadSession::new(None, None, cancel_token).with_retry_backoff(retry_backoff);
1028        let installed =
1029            streaming_download_and_extract(url, format, target_dir, static_files_dir, &session)?;
1030        ensure_execution_files(installed)?;
1031        session.record_archive_output_complete(0);
1032        Ok(())
1033    }
1034}
1035
1036/// Downloads and extracts a snapshot archive asynchronously.
1037///
1038/// Download progress is reported using a local progress bar.
1039/// When `resumable` is true, uses two-phase download with `.part` files.
1040pub(crate) async fn stream_and_extract(
1041    url: &str,
1042    target_dir: &Path,
1043    static_files_dir: Option<&Path>,
1044    resumable: bool,
1045    request_limiter: Option<Arc<DownloadRequestLimiter>>,
1046    cancel_token: CancellationToken,
1047    retry_backoff: Option<Duration>,
1048) -> Result<()> {
1049    let target_dir = target_dir.to_path_buf();
1050    let static_files_dir = static_files_dir.map(Path::to_path_buf);
1051    let url = url.to_string();
1052    reth_tasks::spawn_blocking(move || {
1053        blocking_download_and_extract(
1054            &url,
1055            &target_dir,
1056            static_files_dir.as_deref(),
1057            resumable,
1058            request_limiter,
1059            cancel_token,
1060            retry_backoff,
1061        )
1062    })
1063    .await??;
1064
1065    Ok(())
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071    use crate::download::fetch::tests::spawn_response_server;
1072    use std::io::Write;
1073
1074    #[test]
1075    fn custom_static_root_cannot_be_redirected_by_archive_symlinks() {
1076        for custom_path in ["custom", "custom/nested"] {
1077            let target = tempfile::tempdir().unwrap();
1078            let outside = tempfile::tempdir().unwrap();
1079            fs::create_dir_all(outside.path().join("nested")).unwrap();
1080            for path in ["headers", "nested/headers"] {
1081                fs::write(outside.path().join(path), b"keep").unwrap();
1082            }
1083            let custom = target.path().join(custom_path);
1084            let mut archive = tar::Builder::new(Vec::new());
1085            let mut link = tar::Header::new_gnu();
1086            link.set_entry_type(tar::EntryType::Symlink);
1087            link.set_size(0);
1088            link.set_mode(0o777);
1089            archive.append_link(&mut link, "custom", outside.path()).unwrap();
1090            let mut file = tar::Header::new_gnu();
1091            file.set_size(4);
1092            file.set_mode(0o644);
1093            file.set_cksum();
1094            archive.append_data(&mut file, "static_files/headers", b"data".as_slice()).unwrap();
1095            let tar = archive.into_inner().unwrap();
1096            let err = unpack_archive(
1097                Archive::new(tar.as_slice()),
1098                target.path(),
1099                Some(&custom),
1100                None,
1101                None,
1102            )
1103            .unwrap_err();
1104            assert!(format!("{err:#}").contains("Archive links are unsupported"));
1105            let outputs = [super::super::manifest::OutputFileChecksum {
1106                path: "static_files/headers".into(),
1107                size: 4,
1108                blake3: String::new(),
1109            }];
1110            super::super::verify::OutputVerifier::new(target.path(), Some(&custom))
1111                .cleanup(&outputs);
1112            for path in ["headers", "nested/headers"] {
1113                assert_eq!(fs::read(outside.path().join(path)).unwrap(), b"keep");
1114            }
1115        }
1116    }
1117
1118    #[test]
1119    fn link_entries_are_rejected_without_custom_static_dir() {
1120        for entry_type in [tar::EntryType::Symlink, tar::EntryType::Link] {
1121            for with_progress in [false, true] {
1122                let root = tempfile::tempdir().unwrap();
1123                let target = root.path().join("target");
1124                let outside = root.path().join("outside");
1125                fs::create_dir_all(&target).unwrap();
1126                fs::create_dir_all(&outside).unwrap();
1127                fs::write(outside.join("file"), b"keep").unwrap();
1128
1129                let mut archive = tar::Builder::new(Vec::new());
1130                let mut link = tar::Header::new_gnu();
1131                link.set_entry_type(entry_type);
1132                link.set_size(0);
1133                link.set_mode(0o777);
1134                // A symlink to the outside directory would redirect the entry below, a hard link
1135                // would alias the outside file.
1136                let link_target =
1137                    if entry_type.is_symlink() { outside.clone() } else { outside.join("file") };
1138                archive.append_link(&mut link, "db", link_target).unwrap();
1139                let mut file = tar::Header::new_gnu();
1140                file.set_size(4);
1141                file.set_mode(0o644);
1142                file.set_cksum();
1143                archive.append_data(&mut file, "db/file", b"data".as_slice()).unwrap();
1144                let tar = archive.into_inner().unwrap();
1145
1146                let mut progress = ArchiveExtractionProgress::new(None);
1147                let progress = with_progress.then_some(&mut progress);
1148                let err =
1149                    unpack_archive(Archive::new(tar.as_slice()), &target, None, progress, None)
1150                        .unwrap_err();
1151                assert!(format!("{err:#}").contains("Archive links are unsupported"));
1152
1153                assert!(
1154                    !target.join("db").exists() && target.join("db").symlink_metadata().is_err()
1155                );
1156                assert_eq!(fs::read(outside.join("file")).unwrap(), b"keep");
1157                assert_eq!(fs::read_dir(&outside).unwrap().count(), 1);
1158            }
1159        }
1160    }
1161
1162    #[test]
1163    fn extracted_hashes_replace_read_back_only_for_regular_files() {
1164        let checksum = |path: &str, data: &[u8]| super::super::manifest::OutputFileChecksum {
1165            path: path.into(),
1166            size: data.len() as u64,
1167            blake3: blake3::hash(data).to_hex().to_string(),
1168        };
1169        let data = (0..3 * FILE_HASH_BATCH_SIZE + 5).map(|i| (i % 251) as u8).collect::<Vec<_>>();
1170        let mut archive = tar::Builder::new(Vec::new());
1171        let mut header = tar::Header::new_gnu();
1172        header.set_size(data.len() as u64);
1173        header.set_mode(0o644);
1174        header.set_cksum();
1175        archive.append_data(&mut header, "./db/data", data.as_slice()).unwrap();
1176        archive.append_data(&mut header, "db/extra", data.as_slice()).unwrap();
1177        let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1178        let target = tempfile::tempdir().unwrap();
1179
1180        let hashes = extract_archive_hashed(
1181            tar.as_slice(),
1182            CompressionFormat::Zstd,
1183            target.path(),
1184            None,
1185            HashSet::from([target.path().join("db/data")]),
1186            None,
1187            || {},
1188        )
1189        .unwrap();
1190
1191        // A file the archive did not write has no extraction hash, so it is read back.
1192        fs::write(target.path().join("db/other"), &data).unwrap();
1193        let verifier = super::super::verify::OutputVerifier::new(target.path(), None);
1194        let outputs = [checksum("db/data", &data), checksum("db/other", &data)];
1195        assert!(verifier.verify_with_progress(&outputs, None, Some(&hashes)).unwrap());
1196        let missing = [checksum("db/data", &data), checksum("db/missing", b"")];
1197        assert!(
1198            !verifier.verify_with_progress(&missing, None, Some(&hashes)).unwrap(),
1199            "an output the archive never produced still fails"
1200        );
1201
1202        // Corrupt the files on disk: the extracted declared file keeps its extraction hash, while
1203        // the other file and the undeclared entry are read back and see the corruption.
1204        let mut corrupt = data.clone();
1205        corrupt[7] ^= 1;
1206        fs::write(target.path().join("db/data"), &corrupt).unwrap();
1207        fs::write(target.path().join("db/other"), &corrupt).unwrap();
1208        fs::write(target.path().join("db/extra"), &corrupt).unwrap();
1209        assert!(verifier.verify_with_progress(&outputs[..1], None, Some(&hashes)).unwrap());
1210        assert!(!verifier.verify_with_progress(&outputs[1..], None, Some(&hashes)).unwrap());
1211        assert!(!verifier
1212            .verify_with_progress(&[checksum("db/extra", &data)], None, Some(&hashes))
1213            .unwrap());
1214
1215        let mut wrong = outputs[..1].to_vec();
1216        wrong[0].blake3 = blake3::hash(&corrupt).to_hex().to_string();
1217        assert!(
1218            !verifier.verify_with_progress(&wrong, None, Some(&hashes)).unwrap(),
1219            "extraction hashes are compared with the manifest"
1220        );
1221
1222        // Static files in a custom directory are found by their manifest path.
1223        let mut archive = tar::Builder::new(Vec::new());
1224        archive.append_data(&mut header, "./static_files/headers", data.as_slice()).unwrap();
1225        let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1226        let custom = tempfile::tempdir().unwrap();
1227        let hashes = extract_archive_hashed(
1228            tar.as_slice(),
1229            CompressionFormat::Zstd,
1230            target.path(),
1231            Some(custom.path()),
1232            HashSet::from([custom.path().join("headers")]),
1233            None,
1234            || {},
1235        )
1236        .unwrap();
1237        fs::write(custom.path().join("headers"), &corrupt).unwrap();
1238        let verifier =
1239            super::super::verify::OutputVerifier::new(target.path(), Some(custom.path()));
1240        assert!(verifier
1241            .verify_with_progress(&[checksum("static_files/headers", &data)], None, Some(&hashes))
1242            .unwrap());
1243
1244        // An entry that replaces a file written by an earlier entry drops the recorded hashes,
1245        // whether it is hashed or not; tar writes unknown entry types as regular files. On a
1246        // case-insensitive filesystem `db/DATA` replaces `db/data` as well.
1247        for (path, entry_type) in
1248            [("db/data", tar::EntryType::Fifo), ("db/DATA", tar::EntryType::Regular)]
1249        {
1250            let mut archive = tar::Builder::new(Vec::new());
1251            header.set_entry_type(tar::EntryType::Regular);
1252            archive.append_data(&mut header, "db/data", data.as_slice()).unwrap();
1253            header.set_entry_type(entry_type);
1254            archive.append_data(&mut header, path, corrupt.as_slice()).unwrap();
1255            let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1256            let target = tempfile::tempdir().unwrap();
1257            let hashes = extract_archive_hashed(
1258                tar.as_slice(),
1259                CompressionFormat::Zstd,
1260                target.path(),
1261                None,
1262                HashSet::from([target.path().join("db/data")]),
1263                None,
1264                || {},
1265            )
1266            .unwrap();
1267            let replaced = fs::read(target.path().join("db/data")).unwrap() == corrupt;
1268            assert!(replaced || entry_type == tar::EntryType::Regular);
1269            let verifier = super::super::verify::OutputVerifier::new(target.path(), None);
1270            assert_eq!(
1271                verifier
1272                    .verify_with_progress(&[checksum("db/data", &data)], None, Some(&hashes))
1273                    .unwrap(),
1274                !replaced,
1275                "`{path}` replaced the hashed file: {replaced}"
1276            );
1277        }
1278
1279        // An output the archive made unreadable is an error, as it is for a read-back, unless
1280        // the user can read it regardless.
1281        #[cfg(unix)]
1282        {
1283            let mut archive = tar::Builder::new(Vec::new());
1284            header.set_entry_type(tar::EntryType::Regular);
1285            header.set_mode(0o200);
1286            archive.append_data(&mut header, "db/data", data.as_slice()).unwrap();
1287            let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1288            let target = tempfile::tempdir().unwrap();
1289            let hashes = extract_archive_hashed(
1290                tar.as_slice(),
1291                CompressionFormat::Zstd,
1292                target.path(),
1293                None,
1294                HashSet::from([target.path().join("db/data")]),
1295                None,
1296                || {},
1297            )
1298            .unwrap();
1299            let readable = fs::open(target.path().join("db/data")).is_ok();
1300            let verifier = super::super::verify::OutputVerifier::new(target.path(), None);
1301            let verified =
1302                verifier.verify_with_progress(&[checksum("db/data", &data)], None, Some(&hashes));
1303            assert_eq!(verified.is_ok(), readable);
1304        }
1305    }
1306
1307    #[test]
1308    fn hashed_extraction_writes_files_and_stops_on_either_side_failing() {
1309        let data = (0..3 * DECODED_CHUNK_SIZE + 5).map(|i| (i % 251) as u8).collect::<Vec<_>>();
1310        let mut archive = tar::Builder::new(Vec::new());
1311        let mut header = tar::Header::new_gnu();
1312        header.set_size(data.len() as u64);
1313        header.set_mode(0o640);
1314        header.set_mtime(1_700_000_000);
1315        header.set_cksum();
1316        archive.append_data(&mut header, "db/data", data.as_slice()).unwrap();
1317        let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1318
1319        let target = tempfile::tempdir().unwrap();
1320        let mut stopped_input = false;
1321        extract_archive_hashed(
1322            tar.as_slice(),
1323            CompressionFormat::Zstd,
1324            target.path(),
1325            None,
1326            HashSet::from([target.path().join("db/data")]),
1327            None,
1328            || stopped_input = true,
1329        )
1330        .unwrap();
1331        assert!(!stopped_input);
1332        let path = target.path().join("db/data");
1333        assert_eq!(fs::read(&path).unwrap(), data);
1334        let metadata = std::fs::metadata(&path).unwrap();
1335        assert_eq!(metadata.permissions().mode() & 0o777, 0o640);
1336        assert_eq!(metadata.modified().unwrap(), UNIX_EPOCH + Duration::from_secs(1_700_000_000));
1337
1338        // A decode error on the decoder thread fails extraction.
1339        let target = tempfile::tempdir().unwrap();
1340        let error = extract_archive_hashed(
1341            &tar[..tar.len() - 4],
1342            CompressionFormat::Zstd,
1343            target.path(),
1344            None,
1345            HashSet::from([target.path().join("db/data")]),
1346            None,
1347            || {},
1348        )
1349        .unwrap_err();
1350        assert_eq!(error.root_cause().to_string(), "incomplete frame");
1351
1352        // An unpack error stops the input before waiting for the decoder, which is blocked on
1353        // input that would otherwise never end.
1354        let mut archive = tar::Builder::new(Vec::new());
1355        let mut link = tar::Header::new_gnu();
1356        link.set_entry_type(tar::EntryType::Symlink);
1357        link.set_size(0);
1358        link.set_mode(0o777);
1359        archive.append_link(&mut link, "static_files/link", "elsewhere").unwrap();
1360        let mut encoder = zstd::Encoder::new(Vec::new(), 0).unwrap();
1361        encoder.write_all(&archive.into_inner().unwrap()).unwrap();
1362        encoder.flush().unwrap();
1363        let (feed, input) = sync_channel(1);
1364        feed.send(Ok(encoder.get_ref().clone())).unwrap();
1365        let reader = DecodedChunks {
1366            chunks: input,
1367            recycled: sync_channel(0).0,
1368            chunk: Vec::new(),
1369            offset: 0,
1370        };
1371        let custom = tempfile::tempdir().unwrap();
1372        let error = extract_archive_hashed(
1373            reader,
1374            CompressionFormat::Zstd,
1375            target.path(),
1376            Some(custom.path()),
1377            HashSet::new(),
1378            None,
1379            move || drop(feed),
1380        )
1381        .unwrap_err();
1382        assert_eq!(
1383            error.root_cause().to_string(),
1384            "Archive links are unsupported: `static_files/link`"
1385        );
1386    }
1387
1388    #[test]
1389    fn hashed_extraction_reads_past_the_end_of_an_archive_without_end_marker() {
1390        let mut archive = tar::Builder::new(Vec::new());
1391        let mut header = tar::Header::new_gnu();
1392        header.set_size(4);
1393        header.set_cksum();
1394        archive.append_data(&mut header, "db/data", b"data".as_slice()).unwrap();
1395        let mut tar = archive.into_inner().unwrap();
1396        // Drops the two zero blocks that mark the end of the archive, so tar stops at the end
1397        // of the stream and the remaining stream is read after it.
1398        tar.truncate(tar.len() - 1024);
1399        let tar = zstd::encode_all(tar.as_slice(), 0).unwrap();
1400
1401        let target = tempfile::tempdir().unwrap();
1402        extract_archive_hashed(
1403            tar.as_slice(),
1404            CompressionFormat::Zstd,
1405            target.path(),
1406            None,
1407            HashSet::from([target.path().join("db/data")]),
1408            None,
1409            || {},
1410        )
1411        .unwrap();
1412        assert_eq!(fs::read(target.path().join("db/data")).unwrap(), b"data");
1413    }
1414
1415    #[test]
1416    fn hashed_extraction_stops_decoding_a_long_suffix_after_the_end_marker() {
1417        let mut archive = tar::Builder::new(Vec::new());
1418        let mut header = tar::Header::new_gnu();
1419        header.set_size(4);
1420        header.set_cksum();
1421        archive.append_data(&mut header, "db/data", b"data".as_slice()).unwrap();
1422        let mut tar = archive.into_inner().unwrap();
1423        tar.resize(tar.len() + 2 * MAX_TRAILING_DECODED_BYTES as usize, 0);
1424        let mut compressed = zstd::encode_all(tar.as_slice(), 0).unwrap();
1425        // Bytes that are not a zstd frame, past the limit, so they are never decoded.
1426        compressed.extend_from_slice(b"not a zstd frame");
1427
1428        let target = tempfile::tempdir().unwrap();
1429        extract_archive_hashed(
1430            compressed.as_slice(),
1431            CompressionFormat::Zstd,
1432            target.path(),
1433            None,
1434            HashSet::from([target.path().join("db/data")]),
1435            None,
1436            || {},
1437        )
1438        .unwrap();
1439        assert_eq!(fs::read(target.path().join("db/data")).unwrap(), b"data");
1440    }
1441
1442    #[test]
1443    fn legacy_directory_entry_is_extracted_as_directory() {
1444        let mut archive = tar::Builder::new(Vec::new());
1445        for (path, data) in [("db/", b"".as_slice()), ("db/data", b"data".as_slice())] {
1446            let mut header = tar::Header::new_old();
1447            header.set_path(path).unwrap();
1448            header.set_entry_type(tar::EntryType::Regular);
1449            header.set_size(data.len() as u64);
1450            header.set_mode(0o755);
1451            header.set_cksum();
1452            archive.append(&header, data).unwrap();
1453        }
1454        let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1455
1456        let target = tempfile::tempdir().unwrap();
1457        assert!(extract_archive_raw(
1458            tar.as_slice(),
1459            CompressionFormat::Zstd,
1460            target.path(),
1461            None,
1462            None,
1463        )
1464        .unwrap());
1465        assert!(target.path().join("db").is_dir());
1466        assert_eq!(fs::read(target.path().join("db/data")).unwrap(), b"data");
1467    }
1468
1469    #[test]
1470    fn legacy_restore_requires_execution_files() {
1471        let mut archive = tar::Builder::new(Vec::new());
1472        let mut directory = tar::Header::new_gnu();
1473        directory.set_entry_type(tar::EntryType::Directory);
1474        directory.set_size(0);
1475        directory.set_mode(0o755);
1476        archive.append_data(&mut directory, "db", io::empty()).unwrap();
1477
1478        let config = b"[stages]";
1479        let mut header = tar::Header::new_gnu();
1480        header.set_size(config.len() as u64);
1481        header.set_mode(0o600);
1482        archive.append_data(&mut header, "reth.toml", config.as_slice()).unwrap();
1483
1484        let snapshot = tempfile::tempdir().unwrap();
1485        let path = snapshot.path().join("snapshot.tar.zst");
1486        fs::write(&path, zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap())
1487            .unwrap();
1488        let url = Url::from_file_path(path).unwrap();
1489        let target = tempfile::tempdir().unwrap();
1490
1491        let err = blocking_download_and_extract(
1492            url.as_str(),
1493            target.path(),
1494            None,
1495            false,
1496            None,
1497            CancellationToken::new(),
1498            None,
1499        )
1500        .unwrap_err();
1501        assert_eq!(err.to_string(), "Snapshot archive contains no execution files");
1502    }
1503
1504    #[test]
1505    fn legacy_restore_counts_unknown_entry_types_as_files() {
1506        let mut archive = tar::Builder::new(Vec::new());
1507        let mut header = tar::Header::new_gnu();
1508        header.set_entry_type(tar::EntryType::new(b'9'));
1509        header.set_size(4);
1510        header.set_mode(0o600);
1511        archive.append_data(&mut header, "db/data", b"data".as_slice()).unwrap();
1512
1513        let snapshot = tempfile::tempdir().unwrap();
1514        let path = snapshot.path().join("snapshot.tar.zst");
1515        fs::write(&path, zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap())
1516            .unwrap();
1517        let url = Url::from_file_path(path).unwrap();
1518        let target = tempfile::tempdir().unwrap();
1519
1520        blocking_download_and_extract(
1521            url.as_str(),
1522            target.path(),
1523            None,
1524            false,
1525            None,
1526            CancellationToken::new(),
1527            None,
1528        )
1529        .unwrap();
1530        assert_eq!(fs::read(target.path().join("db/data")).unwrap(), b"data");
1531    }
1532
1533    #[test]
1534    fn legacy_restore_ignores_tar_metadata_entries() {
1535        let mut archive = tar::Builder::new(Vec::new());
1536        let records = b"15 comment=abc\n";
1537        let mut header = tar::Header::new_ustar();
1538        header.set_entry_type(tar::EntryType::XGlobalHeader);
1539        header.set_size(records.len() as u64);
1540        header.set_mode(0o600);
1541        archive.append_data(&mut header, "db/data", records.as_slice()).unwrap();
1542
1543        let snapshot = tempfile::tempdir().unwrap();
1544        let path = snapshot.path().join("snapshot.tar.zst");
1545        fs::write(&path, zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap())
1546            .unwrap();
1547        let url = Url::from_file_path(path).unwrap();
1548        let target = tempfile::tempdir().unwrap();
1549
1550        let err = blocking_download_and_extract(
1551            url.as_str(),
1552            target.path(),
1553            None,
1554            false,
1555            None,
1556            CancellationToken::new(),
1557            None,
1558        )
1559        .unwrap_err();
1560        assert_eq!(err.to_string(), "Snapshot archive contains no execution files");
1561        assert!(!target.path().join("db").exists());
1562    }
1563
1564    #[test]
1565    fn rejected_legacy_download_removes_the_archive() {
1566        let mut archive = tar::Builder::new(Vec::new());
1567        let mut header = tar::Header::new_gnu();
1568        header.set_size(4);
1569        header.set_mode(0o600);
1570        archive.append_data(&mut header, "README.txt", b"docs".as_slice()).unwrap();
1571        let compressed = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1572        let headers = format!(
1573            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1574            compressed.len()
1575        );
1576        let url = spawn_response_server(vec![[headers.as_bytes(), &compressed].concat().leak()]);
1577        let target = tempfile::tempdir().unwrap();
1578
1579        let err = blocking_download_and_extract(
1580            &url,
1581            target.path(),
1582            None,
1583            true,
1584            Some(DownloadRequestLimiter::new(1)),
1585            CancellationToken::new(),
1586            Some(Duration::ZERO),
1587        )
1588        .unwrap_err();
1589        assert_eq!(err.to_string(), "Snapshot archive contains no execution files");
1590        assert!(!target.path().join("archive.tar.zst").exists());
1591    }
1592
1593    #[test]
1594    fn regular_file_keeps_pre_epoch_mtime() {
1595        let mut archive = tar::Builder::new(Vec::new());
1596        let mut header = tar::Header::new_gnu();
1597        header.set_size(4);
1598        header.set_mode(0o600);
1599        // Tar stores times before the epoch as the two's complement of the seconds.
1600        header.set_mtime((-86_400_i64).cast_unsigned());
1601        header.set_cksum();
1602        archive.append_data(&mut header, "db/data", b"data".as_slice()).unwrap();
1603        let tar = zstd::encode_all(archive.into_inner().unwrap().as_slice(), 0).unwrap();
1604
1605        let target = tempfile::tempdir().unwrap();
1606        extract_archive_raw(tar.as_slice(), CompressionFormat::Zstd, target.path(), None, None)
1607            .unwrap();
1608        let path = target.path().join("db/data");
1609        // Checked before reading the file, which may update its access time.
1610        let metadata = std::fs::metadata(&path).unwrap();
1611        let time = UNIX_EPOCH - Duration::from_secs(86_400);
1612        assert_eq!(metadata.modified().unwrap(), time);
1613        assert_eq!(metadata.accessed().unwrap(), time);
1614        assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
1615        assert_eq!(fs::read(&path).unwrap(), b"data");
1616    }
1617
1618    #[test]
1619    fn archive_installs_only_managed_outputs() {
1620        let mut archive = tar::Builder::new(Vec::new());
1621        for path in ["db/data", "rocksdb/index", "static_files/header", "reth.toml", "README.txt"] {
1622            let mut header = tar::Header::new_gnu();
1623            header.set_size(4);
1624            header.set_mode(0o600);
1625            archive.append_data(&mut header, path, b"data".as_slice()).unwrap();
1626        }
1627        let target = tempfile::tempdir().unwrap();
1628        unpack_archive(
1629            Archive::new(archive.into_inner().unwrap().as_slice()),
1630            target.path(),
1631            None,
1632            None,
1633            None,
1634        )
1635        .unwrap();
1636        for path in ["db/data", "rocksdb/index", "static_files/header", "reth.toml"] {
1637            assert_eq!(fs::read(target.path().join(path)).unwrap(), b"data");
1638        }
1639        assert!(!target.path().join("README.txt").exists());
1640    }
1641
1642    #[test]
1643    fn remap_static_files_in_both_compression_formats() {
1644        let mut archive = tar::Builder::new(Vec::new());
1645        let mut directory = tar::Header::new_gnu();
1646        directory.set_entry_type(tar::EntryType::Directory);
1647        directory.set_size(0);
1648        directory.set_mode(0o755);
1649        directory.set_cksum();
1650        archive.append_data(&mut directory, "./static_files/", std::io::empty()).unwrap();
1651        for path in ["./static_files/nested/headers", "db/data"] {
1652            let mut header = tar::Header::new_gnu();
1653            header.set_size(4);
1654            header.set_mode(0o644);
1655            header.set_cksum();
1656            archive.append_data(&mut header, path, b"data".as_slice()).unwrap();
1657        }
1658        let tar = archive.into_inner().unwrap();
1659        for format in [CompressionFormat::Lz4, CompressionFormat::Zstd] {
1660            let bytes = match format {
1661                CompressionFormat::Lz4 => {
1662                    let mut encoder = lz4::EncoderBuilder::new().build(Vec::new()).unwrap();
1663                    std::io::copy(&mut tar.as_slice(), &mut encoder).unwrap();
1664                    let (bytes, result) = encoder.finish();
1665                    result.unwrap();
1666                    bytes
1667                }
1668                CompressionFormat::Zstd => zstd::encode_all(tar.as_slice(), 0).unwrap(),
1669            };
1670            let target = tempfile::tempdir().unwrap();
1671            let custom = tempfile::tempdir().unwrap();
1672            extract_archive_raw(bytes.as_slice(), format, target.path(), Some(custom.path()), None)
1673                .unwrap();
1674            assert_eq!(fs::read(custom.path().join("nested/headers")).unwrap(), b"data");
1675            assert_eq!(fs::read(target.path().join("db/data")).unwrap(), b"data");
1676            assert!(!target.path().join("static_files").exists());
1677        }
1678    }
1679
1680    #[test]
1681    fn test_compression_format_detection() {
1682        assert!(matches!(
1683            CompressionFormat::from_url("https://example.com/snapshot.tar.lz4"),
1684            Ok(CompressionFormat::Lz4)
1685        ));
1686        assert!(matches!(
1687            CompressionFormat::from_url("https://example.com/snapshot.tar.zst"),
1688            Ok(CompressionFormat::Zstd)
1689        ));
1690        assert!(matches!(
1691            CompressionFormat::from_url("file:///path/to/snapshot.tar.lz4"),
1692            Ok(CompressionFormat::Lz4)
1693        ));
1694        assert!(matches!(
1695            CompressionFormat::from_url("file:///path/to/snapshot.tar.zst"),
1696            Ok(CompressionFormat::Zstd)
1697        ));
1698        assert!(CompressionFormat::from_url("https://example.com/snapshot.tar.gz").is_err());
1699    }
1700}