Skip to main content

hatchzip_core/archive/
tarzst.rs

1//! A `.zst`-compressed tar is a sequence of independent zstd frames, each
2//! holding the next stretch of one tar. A frame decodes only from its start,
3//! so a frame boundary is a resume point that needs no decoder state and no
4//! window, exactly like a gzip member start, and the engine frees the frames
5//! behind the decoder by punching them away at those points. The tar parser
6//! is the one every compressed tar shares, see `targz`.
7//!
8//! The `zstd` CLI writes one frame however many threads it uses, so most
9//! `.tar.zst` files have no boundary at all and cannot free anything while
10//! they decode. They are refused for in-place extraction with a message
11//! naming `--keep-archive`, which decodes them whole and leaves the archive
12//! as it was. `pzstd` and concatenated files write several frames and free
13//! space as they go.
14//!
15//! The frames are parsed here, block by block, before anything is decoded:
16//! their offsets, whether each carries the XXH64 checksum, and the window its
17//! header declares. The `zstd` crate then decodes one bounded frame at a
18//! time, so a decoder that lies about its input cannot read into the next
19//! frame, and every frame's checksum is verified before its bytes can be
20//! punched.
21
22use std::io::{self, BufReader, Read, Seek, SeekFrom};
23use std::sync::Arc;
24
25use anyhow::{Context, Result, anyhow, bail};
26
27use super::storage::{Reader, Storage};
28use super::targz::{self, CodecKind, Event, Feed, Profile, StreamPoint, TarAt, TarStream};
29use super::{
30    Format, Item, Kind, Opened, Sink, SolidStream, SolidWalker, Unit, Unsupported, Worker,
31};
32use crate::journal::Resume;
33
34pub const NAME: &str = "tar.zst";
35
36/// Decoded output is handed out in pieces of at most this much, as targz
37/// does.
38const BUF: usize = targz::BUF;
39
40/// The largest window a frame may name. It is allocated whole while the
41/// frame decodes; zstd's presets top out at 128 MiB, and `--long=31` asks
42/// for 2 GiB, which this refuses before anything is touched.
43const MAX_WINDOW: u64 = 1 << 30;
44
45const FRAME_MAGIC: u32 = 0xFD2F_B528;
46/// Skippable frames use the low nibble of this magic, `0x184D2A50` through
47/// `0x184D2A5F`. `pzstd` writes one before every frame and the seekable
48/// format puts its table in one at the end.
49const SKIPPABLE_MAGIC: u32 = 0x184D_2A50;
50
51/// One zstd frame, as the container describes it.
52#[derive(Clone, Debug, PartialEq, Eq)]
53struct Frame {
54    /// Where the frame's magic begins: what a resume point records.
55    start: u64,
56    /// First byte after the frame, checksum included.
57    end: u64,
58    /// Whether the frame header says the XXH64 checksum follows its last
59    /// block.
60    checksum: bool,
61    /// The window the header declares, in bytes.
62    window: u64,
63    /// The dictionary the header names, if any.
64    dictionary: Option<u32>,
65}
66
67/// Reads every frame from `from` (0 for the whole archive, or a resumed
68/// run's frame start) to the end, skipping skippable frames. Damage here is
69/// found before anything is touched.
70fn parse_frames<R: Read + Seek>(reader: &mut R, len: u64, from: u64) -> Result<Vec<Frame>> {
71    fn taken<R: Read + Seek>(reader: &mut R, at: u64, buf: &mut [u8]) -> Result<()> {
72        reader.seek(SeekFrom::Start(at))?;
73        reader.read_exact(buf).map_err(|e| {
74            anyhow::anyhow!("the archive is shorter than its zstd frame says; it is damaged: {e}")
75        })
76    }
77
78    fn u32_at<R: Read + Seek>(reader: &mut R, at: u64) -> Result<u32> {
79        let mut b = [0u8; 4];
80        taken(reader, at, &mut b)?;
81        Ok(u32::from_le_bytes(b))
82    }
83
84    fn le<R: Read + Seek>(reader: &mut R, at: u64, n: usize) -> Result<u64> {
85        let mut b = [0u8; 8];
86        taken(reader, at, &mut b[..n])?;
87        Ok(u64::from_le_bytes(b))
88    }
89
90    if from > len {
91        bail!("the journal's resume point is past the end of the archive");
92    }
93    let mut at = from;
94    let mut frames = Vec::new();
95    while at < len {
96        if len - at < 4 {
97            bail!(
98                "the archive ends {} bytes into a zstd frame header; it is truncated",
99                len - at
100            );
101        }
102        let magic = u32_at(reader, at)?;
103        if magic & 0xFFFF_FFF0 == SKIPPABLE_MAGIC {
104            if frames.is_empty() && from > 0 {
105                bail!(
106                    "the journal's resume point does not name a zstd frame header; the archive \
107                     will not be modified"
108                );
109            }
110            if len - at < 8 {
111                bail!("the archive ends inside a skippable zstd frame; it is truncated");
112            }
113            let size = u64::from(u32_at(reader, at + 4)?);
114            at = at
115                .checked_add(8 + size)
116                .filter(|end| *end <= len)
117                .ok_or_else(|| {
118                    anyhow::anyhow!(
119                        "a skippable zstd frame says it holds {size} bytes, more than the \
120                         archive has; it is truncated"
121                    )
122                })?;
123            continue;
124        }
125        if magic != FRAME_MAGIC {
126            if from > 0 && frames.is_empty() {
127                bail!(
128                    "the journal's resume point does not name a zstd frame header; the archive \
129                     will not be modified"
130                );
131            }
132            bail!("the bytes at offset {at} are not a zstd frame header; the archive is damaged");
133        }
134        if len - at < 5 {
135            bail!("the archive ends inside a zstd frame header; it is truncated");
136        }
137
138        let mut header = [0u8; 14];
139        let n = (len - at - 4).min(header.len() as u64) as usize;
140        taken(reader, at + 4, &mut header[..n])?;
141        let descriptor = header[0];
142        if descriptor & 0x18 != 0 {
143            bail!("a zstd frame header sets a reserved bit; the archive is damaged");
144        }
145        let single = descriptor & 0x20 != 0;
146        let checksum = descriptor & 0x04 != 0;
147        let dict_size = [0usize, 1, 2, 4][(descriptor & 0x03) as usize];
148        let fcs_size = match descriptor >> 6 {
149            0 if single => 1,
150            0 => 0,
151            1 => 2,
152            2 => 4,
153            _ => 8,
154        };
155
156        let mut pos = at + 5;
157        let window = if single {
158            0 // Filled in from the content size below.
159        } else {
160            if n < 2 {
161                bail!("the archive ends inside a zstd frame header; it is truncated");
162            }
163            let wd = header[1];
164            pos += 1;
165            let exp = u64::from(wd >> 3);
166            let mant = u64::from(wd & 0x07);
167            (1u64 << (10 + exp)) + (mant << (exp + 7))
168        };
169        let dictionary = match dict_size {
170            0 => None,
171            1 | 2 | 4 => {
172                let id = le(reader, pos, dict_size)?;
173                pos += dict_size as u64;
174                u32::try_from(id).ok().filter(|id| *id != 0)
175            }
176            _ => unreachable!(),
177        };
178        let content = if fcs_size == 0 {
179            None
180        } else {
181            let value = le(reader, pos, fcs_size)?;
182            pos += fcs_size as u64;
183            Some(if fcs_size == 2 { value + 256 } else { value })
184        };
185        let window = if single {
186            content.ok_or_else(|| {
187                anyhow::anyhow!("a zstd frame declares a single segment but no content size")
188            })?
189        } else {
190            window
191        };
192
193        loop {
194            if pos + 3 > len {
195                bail!("the archive ends inside a zstd frame; it is truncated");
196            }
197            let mut h = [0u8; 3];
198            taken(reader, pos, &mut h)?;
199            let header = u32::from_le_bytes([h[0], h[1], h[2], 0]);
200            pos += 3;
201            let last = header & 1 != 0;
202            let kind = (header >> 1) & 0x03;
203            let size = u64::from(header >> 3);
204            let data = match kind {
205                0 | 2 => size,
206                1 => 1,
207                _ => bail!("a zstd frame uses a reserved block type; the archive is damaged"),
208            };
209            pos = pos
210                .checked_add(data)
211                .filter(|end| *end <= len)
212                .ok_or_else(|| {
213                    anyhow::anyhow!(
214                        "a zstd block says it holds {data} bytes, more than the archive has; it is \
215                     truncated"
216                    )
217                })?;
218            if last {
219                break;
220            }
221        }
222        if checksum {
223            pos = pos
224                .checked_add(4)
225                .filter(|end| *end <= len)
226                .ok_or_else(|| {
227                    anyhow::anyhow!(
228                        "the archive ends before a zstd frame's checksum; it is truncated"
229                    )
230                })?;
231        }
232        frames.push(Frame {
233            start: at,
234            end: pos,
235            checksum,
236            window,
237            dictionary,
238        });
239        at = pos;
240    }
241    if frames.is_empty() {
242        bail!(
243            "the archive holds no zstd frame{}",
244            if from > 0 {
245                " from the journal's resume point; it will not be modified"
246            } else {
247                ""
248            }
249        );
250    }
251    Ok(frames)
252}
253
254/// What the format refuses about a parsed stream before anything is
255/// decoded. A window over the cap or a dictionary is valid zstd that this
256/// build cannot extract in place.
257fn policy(frames: &[Frame]) -> Result<()> {
258    if frames.is_empty() {
259        bail!("the archive holds no zstd frame");
260    }
261    for f in frames {
262        if let Some(id) = f.dictionary {
263            bail!(
264                "a frame of the archive needs the zstd dictionary {id}, and dictionaries are \
265                 not supported"
266            );
267        }
268        if f.window > MAX_WINDOW {
269            bail!(
270                "a frame of the archive needs a {} window, beyond the {} limit, so it cannot be \
271                 decoded here. Recompress it without --long, or extract it with another program",
272                crate::human(f.window),
273                crate::human(MAX_WINDOW)
274            );
275        }
276    }
277    Ok(())
278}
279
280/// The container with what the format refuses about it, and a resumed
281/// run's walk.
282pub struct Solid {
283    storage: Arc<Storage>,
284    frames: Vec<Frame>,
285    /// How many frames came before the first one here. A fresh run starts at
286    /// 0; a resumed one starts after the frames an earlier run punched away,
287    /// so the stream is still known to have had more than one.
288    from_index: u64,
289    from: Option<Resume>,
290    profile: Profile,
291}
292
293impl Solid {
294    fn new(storage: Arc<Storage>, from: Option<&Resume>) -> Result<Self> {
295        let (from_byte, from_index) = match from {
296            None => (0, 0),
297            Some(r) => {
298                let s = r.stream.as_ref().ok_or_else(|| {
299                    anyhow!("the journal's resume point does not belong to a compressed tar")
300                })?;
301                if s.kind != CodecKind::Zstd {
302                    bail!(
303                        "the journal's resume point belongs to {} tar, not this archive's",
304                        match s.kind {
305                            CodecKind::Gzip => "a gzip member of a",
306                            CodecKind::Bzip2 => "a bzip2 block of a",
307                            CodecKind::Xz => "an xz block of a",
308                            CodecKind::Zstd => "a zstd frame of a",
309                        }
310                    );
311                }
312                if r.bit % 8 != 0 {
313                    bail!(
314                        "the journal's resume point is not on a zstd frame boundary; the archive \
315                         will not be modified"
316                    );
317                }
318                (r.bit / 8, s.block)
319            }
320        };
321        let frames = {
322            let mut reader = storage.reader(None);
323            parse_frames(&mut reader, storage.original_len(), from_byte)
324                .context("reading the zstd stream's structure")?
325        };
326        // A resume reads the same container, so it meets the same refusals;
327        // a journal that names a frame this build cannot decode fails here
328        // rather than halfway into the stream.
329        policy(&frames).map_err(|e| anyhow::Error::new(Unsupported(e)))?;
330        Ok(Self {
331            storage,
332            frames,
333            from_index,
334            from: from.cloned(),
335            profile: Profile::default(),
336        })
337    }
338
339    /// Walks the whole of what `from` leaves, or the whole archive.
340    pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
341        Walker::new(self, from)
342    }
343}
344
345/// Whether the zstd stream opens with a tar header, reading only as far as
346/// the first one. Used to tell a plain `.zst` of one file from a compressed
347/// tar before either is offered.
348pub(crate) fn holds_tar(storage: &Storage) -> Result<bool> {
349    let storage = Arc::new(Storage::open(storage.primary(), false)?);
350    let solid = Solid::new(storage.clone(), None)?;
351    let mut feed = ZstdFeed::new(storage.clone(), solid.frames.clone(), 0, 0);
352    let mut first = [0u8; 512];
353    let mut n = 0;
354    while n < first.len() {
355        match feed.fill(&mut first[n..])? {
356            0 => break,
357            k => n += k,
358        }
359    }
360    Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
361}
362
363/// Walks the archive from `from`, or from its start, listing what is left
364/// and measuring it. Damage anywhere is found here, before anything is
365/// touched.
366pub fn open(storage: &Arc<Storage>, from: Option<&Resume>) -> Result<Opened> {
367    let name = storage
368        .primary()
369        .file_name()
370        .unwrap_or_default()
371        .to_string_lossy()
372        .into_owned();
373    storage.expect_reads(storage.original_len() - from.map_or(0, |r| r.bit / 8));
374    let read = (|| -> Result<(Solid, Vec<Item>, Profile)> {
375        let solid = Solid::new(storage.clone(), from)?;
376        let (items, profile) = super::scan(&solid, from)?;
377        Ok((solid, items, profile))
378    })();
379    // Unsupported is not damage: the archive is valid, this build just does
380    // not extract it. Everything else that stops the read is damage.
381    let (mut solid, items, profile) = read
382        .map_err(|e| {
383            if e.is::<Unsupported>()
384                || e.downcast_ref::<std::io::Error>()
385                    .is_some_and(|io| io.kind() == io::ErrorKind::Unsupported)
386            {
387                e
388            } else {
389                anyhow::Error::new(super::Damaged(e))
390            }
391        })
392        .with_context(|| format!("checking {name} (nothing was changed)"))?;
393    solid.profile = profile;
394    Ok(Opened {
395        name: NAME,
396        format: Box::new(TarZst { solid }),
397        // Even with no entries left there is one unit, so that a resume point
398        // past the last entry still belongs to something.
399        units: vec![Unit {
400            start: 0,
401            key: 0,
402            items,
403            encrypted: false,
404        }],
405        // Nothing is saved: the stream is never truncated from the end.
406        tail_start: storage.original_len(),
407    })
408}
409
410struct TarZst {
411    solid: Solid,
412}
413
414impl Format for TarZst {
415    fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
416        Ok(Box::new(TarZstWorker { solid: &self.solid }))
417    }
418
419    fn solid(&self) -> Option<&dyn SolidStream> {
420        Some(&self.solid)
421    }
422
423    fn refuses_in_place(&self) -> Option<String> {
424        let frames = &self.solid.frames;
425        // On a resume, frames before the point were punched away, but the
426        // count they contributed is in the journal.
427        let whole = self.solid.from_index + (frames.len() as u64) < 2;
428        let unchecked = frames.iter().any(|f| !f.checksum);
429        Some(match (whole, unchecked) {
430            (true, true) => String::from(
431                "the archive's whole tar is inside one zstd frame and its frames carry no \
432                 checksum, so nothing of it can be freed as it is extracted",
433            ),
434            (true, false) => String::from(
435                "the archive's whole tar is inside one zstd frame, so nothing of the archive \
436                 can be freed as it is extracted",
437            ),
438            (false, true) => String::from(
439                "the archive's zstd frames do not all carry a checksum, so damage inside them \
440                 could not be detected before the bytes behind are freed",
441            ),
442            (false, false) => return None,
443        })
444    }
445}
446
447impl SolidStream for Solid {
448    fn profile(&self) -> &Profile {
449        &self.profile
450    }
451
452    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>> {
453        Ok(Box::new(self.walk(from)?))
454    }
455}
456
457/// The compressed bytes of one frame and nothing else: a decoder that lies
458/// about how much of the frame it has decoded cannot read into the next one.
459struct Bytes {
460    reader: Reader,
461    left: u64,
462}
463
464impl Read for Bytes {
465    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
466        let cap = self.left.min(buf.len() as u64) as usize;
467        if cap == 0 {
468            return Ok(0);
469        }
470        let n = self.reader.read(&mut buf[..cap])?;
471        if n == 0 && self.left > 0 {
472            return Err(io::Error::new(
473                io::ErrorKind::UnexpectedEof,
474                "the archive is shorter than its frames say",
475            ));
476        }
477        self.left -= n as u64;
478        Ok(n)
479    }
480}
481
482/// The window the decoder may allocate for a frame, as a log. The header's
483/// size was already checked against the cap; this keeps a decoder that reads
484/// a different header from growing past it.
485fn window_log(window: u64) -> u32 {
486    let mut log = 10;
487    while (1u64 << log) < window && log < 30 {
488        log += 1;
489    }
490    log
491}
492
493/// The zstd side of a walk: it decodes one frame at a time into the tar
494/// parser, and verifies each frame's checksum before the next frame starts.
495struct ZstdFeed {
496    frames: Vec<Frame>,
497    storage: Arc<Storage>,
498    /// Absolute index of `frames[0]`, so points keep counting across a
499    /// resume.
500    base: u64,
501    /// Which frame to decode, relative to `frames`.
502    frame: usize,
503    decoder: Option<zstd::stream::read::Decoder<'static, BufReader<Bytes>>>,
504    /// A byte the end-of-frame probe read, handed out on the next fill.
505    pending: Option<u8>,
506    ended: bool,
507}
508
509impl ZstdFeed {
510    fn new(storage: Arc<Storage>, frames: Vec<Frame>, base: u64, frame: usize) -> Self {
511        Self {
512            frames,
513            storage,
514            base,
515            frame,
516            decoder: None,
517            pending: None,
518            ended: false,
519        }
520    }
521
522    fn build(&self) -> Result<zstd::stream::read::Decoder<'static, BufReader<Bytes>>> {
523        let f = &self.frames[self.frame];
524        let mut reader = self.storage.reader(None);
525        reader
526            .seek(SeekFrom::Start(f.start))
527            .with_context(|| format!("reading zstd frame {}", self.base + self.frame as u64 + 1))?;
528        let bytes = Bytes {
529            reader,
530            left: f.end - f.start,
531        };
532        let mut decoder = zstd::stream::read::Decoder::new(bytes).with_context(|| {
533            format!(
534                "starting the decoder for zstd frame {}",
535                self.base + self.frame as u64 + 1
536            )
537        })?;
538        decoder
539            .window_log_max(window_log(f.window))
540            .with_context(|| {
541                format!(
542                    "setting the window limit for zstd frame {}",
543                    self.base + self.frame as u64 + 1
544                )
545            })?;
546        Ok(decoder.single_frame())
547    }
548
549    /// The frame just ended: consume and verify what is left of it, then
550    /// move on. A checksum mismatch is an error here, before a point can be
551    /// journaled.
552    fn finish(&mut self) -> Result<()> {
553        if let Some(mut decoder) = self.decoder.take() {
554            decoder.finish_frame().with_context(|| {
555                format!(
556                    "the archive's zstd frame {} is damaged or fails its checksum",
557                    self.base + self.frame as u64 + 1
558                )
559            })?;
560        }
561        self.frame += 1;
562        self.ended = self.frame == self.frames.len();
563        Ok(())
564    }
565}
566
567impl Feed for ZstdFeed {
568    fn fill(&mut self, buf: &mut [u8]) -> Result<usize> {
569        if buf.is_empty() || self.ended {
570            return Ok(0);
571        }
572        let mut start = 0;
573        if let Some(byte) = self.pending.take() {
574            buf[0] = byte;
575            start = 1;
576            if buf.len() == 1 {
577                return Ok(1);
578            }
579        }
580        loop {
581            if self.decoder.is_none() {
582                anyhow::ensure!(
583                    self.frame < self.frames.len(),
584                    "the walk asks for input past the last zstd frame"
585                );
586                self.decoder = Some(self.build()?);
587            }
588            let n = self
589                .decoder
590                .as_mut()
591                .expect("the frame's decoder was just built")
592                .read(&mut buf[start..])
593                .with_context(|| {
594                    format!(
595                        "decoding zstd frame {}; the archive is damaged",
596                        self.base + self.frame as u64 + 1
597                    )
598                })?;
599            if n == 0 {
600                // A frame with no output of its own. The tar parser must not
601                // see an end here while frames remain, so go on in this fill.
602                self.finish()?;
603                if self.ended || start == buf.len() {
604                    return Ok(start);
605                }
606                continue;
607            }
608            // Read one byte ahead: when the frame ends at these bytes, the
609            // checksum is verified now and `restartable` can announce the
610            // point before the tar parser asks for the next frame.
611            let mut probe = [0u8; 1];
612            let more = self
613                .decoder
614                .as_mut()
615                .expect("the frame's decoder is still open")
616                .read(&mut probe)
617                .with_context(|| {
618                    format!(
619                        "reading the end of zstd frame {}; the archive is damaged",
620                        self.base + self.frame as u64 + 1
621                    )
622                })?;
623            if more == 0 {
624                self.finish()?;
625            } else {
626                self.pending = Some(probe[0]);
627            }
628            return Ok(start + n);
629        }
630    }
631
632    fn restartable(&self) -> bool {
633        // A frame boundary is the one place this stream restarts from, and
634        // its checksum was just verified.
635        self.decoder.is_none() && !self.ended
636    }
637
638    fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume> {
639        let f = self
640            .frames
641            .get(self.frame)
642            .ok_or_else(|| anyhow!("the stream has no zstd frame a resume point could follow"))?;
643        Ok(Resume {
644            unit: 0,
645            written,
646            // Frame starts are whole bytes.
647            bit: f.start * 8,
648            crc: 0,
649            stream: Some(Box::new(StreamPoint {
650                kind: CodecKind::Zstd,
651                member_start: false,
652                member_crc: 0,
653                member_len: 0,
654                window: Vec::new(),
655                block: self.base + self.frame as u64,
656                level: None,
657                combined_crc: None,
658                tar_pos,
659                at,
660            })),
661        })
662    }
663
664    fn point_byte(&self) -> Option<u64> {
665        if self.ended {
666            None
667        } else {
668            self.frames.get(self.frame).map(|f| f.start)
669        }
670    }
671}
672
673/// Walks the archive from `from`, or from its start, listing what is left
674/// and measuring it. Damage anywhere is found here, before anything is
675/// touched.
676pub struct Walker {
677    inner: TarStream<ZstdFeed>,
678}
679
680impl Walker {
681    fn new(solid: &Solid, from: Option<&Resume>) -> Result<Self> {
682        let feed = match from {
683            None => ZstdFeed::new(solid.storage.clone(), solid.frames.clone(), 0, 0),
684            Some(r) => {
685                let s = r.stream.as_ref().ok_or_else(|| {
686                    anyhow!("the journal's resume point does not belong to a compressed tar")
687                })?;
688                if s.kind != CodecKind::Zstd {
689                    bail!(
690                        "the journal's resume point belongs to {} tar, not this archive's",
691                        match s.kind {
692                            CodecKind::Gzip => "a gzip member of a",
693                            CodecKind::Bzip2 => "a bzip2 block of a",
694                            CodecKind::Xz => "an xz block of a",
695                            CodecKind::Zstd => "a zstd frame of a",
696                        }
697                    );
698                }
699                if solid.frames.first().is_none_or(|f| f.start != r.bit / 8) {
700                    bail!(
701                        "the journal's resume point is inconsistent; the archive will not be \
702                         modified"
703                    );
704                }
705                if !matches!(s.at, TarAt::File { .. }) && r.written != 0 {
706                    bail!(
707                        "the journal's resume point claims a file is open where none is; \
708                         the archive will not be modified"
709                    );
710                }
711                ZstdFeed::new(solid.storage.clone(), solid.frames.clone(), s.block, 0)
712            }
713        };
714        Ok(Self {
715            inner: TarStream::new(feed, from)?,
716        })
717    }
718
719    fn next(&mut self, max: usize) -> Result<Event<'_>> {
720        self.inner.next(max)
721    }
722
723    fn point(&self) -> Result<Resume> {
724        self.inner.point()
725    }
726
727    fn point_byte(&self) -> Option<u64> {
728        self.inner.point_byte()
729    }
730}
731
732impl SolidWalker for Walker {
733    fn next(&mut self, max: usize) -> Result<Event<'_>> {
734        self.next(max)
735    }
736
737    fn point(&self) -> Result<Resume> {
738        self.point()
739    }
740
741    fn point_byte(&self) -> Option<u64> {
742        self.point_byte()
743    }
744}
745
746/// Decodes the whole stream in one go, for `test` and `--verify-first`. The
747/// extraction itself goes through the engine's streaming path instead.
748struct TarZstWorker<'a> {
749    solid: &'a Solid,
750}
751
752impl Worker for TarZstWorker<'_> {
753    fn extract(&mut self, _unit: &Unit, sink: &mut dyn Sink) -> Result<()> {
754        let mut w = self.solid.walk(self.solid.from.as_ref())?;
755        loop {
756            match w.next(BUF)? {
757                Event::Entry { item, done, .. } if item.kind == Kind::File => {
758                    // A resumed run's open file: only its rest is here.
759                    let left = Item {
760                        size: item.size - done,
761                        ..item
762                    };
763                    let mut data = FileData {
764                        walker: &mut w,
765                        ended: false,
766                    };
767                    sink.item(&left, &mut data)?;
768                    let mut rest = [0u8; 4096];
769                    while data.read(&mut rest)? > 0 {}
770                }
771                Event::Entry { item, link, .. } => {
772                    sink.item(&item, &mut io::Cursor::new(link.unwrap_or_default()))?;
773                }
774                Event::Data(_) | Event::FileEnd | Event::Point => {}
775                Event::End => return Ok(()),
776            }
777        }
778    }
779}
780
781/// One file's data, read through the walker.
782struct FileData<'a> {
783    walker: &'a mut Walker,
784    ended: bool,
785}
786
787impl Read for FileData<'_> {
788    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
789        while !self.ended && !buf.is_empty() {
790            match self.walker.next(buf.len()) {
791                Ok(Event::Data(d)) => {
792                    buf[..d.len()].copy_from_slice(d);
793                    return Ok(d.len());
794                }
795                Ok(Event::Point) => {}
796                Ok(Event::FileEnd) => self.ended = true,
797                Ok(_) => return Err(io::Error::other("the tar entry ended unexpectedly")),
798                Err(e) => return Err(io::Error::other(format!("{e:#}"))),
799            }
800        }
801        Ok(0)
802    }
803}
804
805#[cfg(test)]
806mod tests {
807    use super::*;
808    use std::io::Cursor;
809
810    fn bytes(name: &str) -> &'static [u8] {
811        match name {
812            "one" => include_bytes!("fixtures/zst/zst-one.tar.zst"),
813            "two" => include_bytes!("fixtures/zst/zst-two.tar.zst"),
814            "skip" => include_bytes!("fixtures/zst/zst-skip.tar.zst"),
815            "seekable" => include_bytes!("fixtures/zst/zst-seekable.tar.zst"),
816            "pzstd" => include_bytes!("fixtures/zst/zst-pzstd.tar.zst"),
817            "nocheck" => include_bytes!("fixtures/zst/zst-nocheck-one.tar.zst"),
818            "nocheck_two" => include_bytes!("fixtures/zst/zst-nocheck-two.tar.zst"),
819            "long27" => include_bytes!("fixtures/zst/zst-long27.tar.zst"),
820            "long31" => include_bytes!("fixtures/zst/zst-long31.tar.zst"),
821            "dict" => include_bytes!("fixtures/zst/zst-dict.tar.zst"),
822            "bad_check" => include_bytes!("fixtures/zst/zst-bad-check.tar.zst"),
823            "truncated" => include_bytes!("fixtures/zst/zst-truncated.tar.zst"),
824            "bad_magic" => include_bytes!("fixtures/zst/zst-bad-magic.tar.zst"),
825            "notar" => include_bytes!("fixtures/zst/zst-notar.tar.zst"),
826            _ => unreachable!(),
827        }
828    }
829
830    fn frames(name: &str) -> Vec<Frame> {
831        let b = bytes(name);
832        parse_frames(&mut Cursor::new(b), b.len() as u64, 0).unwrap()
833    }
834
835    fn refused(name: &str) -> String {
836        let b = bytes(name);
837        format!(
838            "{:#}",
839            parse_frames(&mut Cursor::new(b), b.len() as u64, 0).unwrap_err()
840        )
841    }
842
843    #[test]
844    fn one_frame_covers_the_whole_file() {
845        let b = bytes("one");
846        let f = frames("one");
847        assert_eq!(f.len(), 1);
848        assert_eq!(f[0].start, 0);
849        assert_eq!(f[0].end, b.len() as u64);
850        assert!(f[0].checksum);
851        // The tar is 260 KiB and the frame declares no separate window, so
852        // its content size is the window.
853        assert_eq!(f[0].window, 266_240);
854        assert_eq!(f[0].dictionary, None);
855    }
856
857    #[test]
858    fn two_frames_are_listed_in_order() {
859        let f = frames("two");
860        assert_eq!(f.len(), 2);
861        assert_eq!(f[0].start, 0);
862        assert_eq!(f[1].start, f[0].end);
863        assert_eq!(f[1].end, bytes("two").len() as u64);
864        assert!(f.iter().all(|f| f.checksum));
865    }
866
867    #[test]
868    fn skippable_frames_are_not_frames() {
869        let f = frames("skip");
870        assert_eq!(f.len(), 2);
871        assert_eq!(f[0].start, 0);
872        assert!(f[1].start > f[0].end, "the skippable frame sits between");
873    }
874
875    #[test]
876    fn a_trailing_seek_table_is_skipped() {
877        let f = frames("seekable");
878        assert_eq!(f.len(), 2);
879        assert!(
880            f[1].end < bytes("seekable").len() as u64,
881            "the table follows the last frame"
882        );
883    }
884
885    /// `pzstd` writes a skippable frame before every frame, not only the
886    /// first, and several real frames follow.
887    #[test]
888    fn pzstd_frames_survive_their_skippable_headers() {
889        let f = frames("pzstd");
890        assert_eq!(f.len(), 2);
891        assert_eq!(f[0].start, 12, "the leading skippable frame comes first");
892        assert_eq!(f[1].start, f[0].end + 12);
893    }
894
895    #[test]
896    fn frames_without_a_check_say_so() {
897        assert!(!frames("nocheck")[0].checksum);
898        assert!(frames("nocheck_two").iter().all(|f| !f.checksum));
899    }
900
901    #[test]
902    fn a_window_descriptor_is_read_as_declared() {
903        assert_eq!(frames("long27")[0].window, 1 << 27);
904    }
905
906    /// RFC 8878 adds `(windowBase / 8) * mantissa`, not `mantissa << exp`.
907    /// A hand-built header is the only way to cover a nonzero mantissa:
908    /// libzstd always writes 0.
909    #[test]
910    fn a_window_descriptor_scales_the_mantissa_by_eighths() {
911        // Descriptor 0, window descriptor exp 0 and mantissa 1: 1024 plus
912        // one eighth of 1024, then a last raw block of size 0.
913        let bytes = [0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x01, 0x01, 0x00, 0x00];
914        let frames = parse_frames(&mut Cursor::new(bytes), bytes.len() as u64, 0).unwrap();
915        assert_eq!(frames.len(), 1);
916        assert_eq!(frames[0].window, 1024 + 128);
917    }
918
919    #[test]
920    fn a_dictionary_is_refused() {
921        let err = format!("{:#}", policy(&frames("dict")).unwrap_err());
922        assert!(err.contains("dictionary"), "got: {err}");
923    }
924
925    #[test]
926    fn a_window_over_the_cap_is_refused() {
927        let err = format!("{:#}", policy(&frames("long31")).unwrap_err());
928        assert!(err.contains("window"), "got: {err}");
929        assert!(err.contains("1.1 GB"), "got: {err}");
930    }
931
932    #[test]
933    fn a_resume_point_must_name_a_frame_start() {
934        let b = bytes("two");
935        let second = frames("two")[1].start;
936        let rest = parse_frames(&mut Cursor::new(b), b.len() as u64, second).unwrap();
937        assert_eq!(rest.len(), 1);
938        assert_eq!(rest[0].start, second);
939
940        let err = format!(
941            "{:#}",
942            parse_frames(&mut Cursor::new(b), b.len() as u64, 100).unwrap_err()
943        );
944        assert!(err.contains("resume point"), "got: {err}");
945    }
946
947    fn storage_of(
948        name: &str,
949        as_name: &str,
950    ) -> (
951        tempfile::TempDir,
952        std::sync::Arc<super::super::storage::Storage>,
953    ) {
954        let dir = tempfile::tempdir().unwrap();
955        let path = dir.path().join(as_name);
956        std::fs::write(&path, bytes(name)).unwrap();
957        let storage =
958            std::sync::Arc::new(super::super::storage::Storage::open(&path, false).unwrap());
959        (dir, storage)
960    }
961
962    fn opened(name: &str) -> (tempfile::TempDir, super::super::Opened) {
963        let (dir, storage) = storage_of(name, name);
964        let opened = open(&storage, None).unwrap();
965        (dir, opened)
966    }
967
968    fn open_error(name: &str, as_name: &str) -> String {
969        let (_dir, storage) = storage_of(name, as_name);
970        match open(&storage, None) {
971            Ok(_) => panic!("{name} opened"),
972            Err(e) => format!("{e:#}"),
973        }
974    }
975
976    fn files(
977        w: &mut dyn super::super::SolidWalker,
978    ) -> std::collections::BTreeMap<std::path::PathBuf, Vec<u8>> {
979        use super::super::targz::Event;
980        let mut all = std::collections::BTreeMap::new();
981        let mut current: Option<(std::path::PathBuf, Vec<u8>)> = None;
982        loop {
983            match w.next(usize::MAX).unwrap() {
984                Event::Entry { item, .. } => {
985                    if item.kind == super::super::Kind::File {
986                        current = Some((item.path.clone(), Vec::new()));
987                    }
988                }
989                Event::Data(d) => {
990                    if let Some((_, buf)) = &mut current {
991                        buf.extend_from_slice(d);
992                    }
993                }
994                Event::FileEnd => {
995                    if let Some((path, data)) = current.take() {
996                        assert!(all.insert(path, data).is_none());
997                    }
998                }
999                Event::Point => {}
1000                Event::End => break,
1001            }
1002        }
1003        all
1004    }
1005
1006    /// A run of empty frames must not end the walk and must not recurse per
1007    /// frame; ten thousand is far past any stack.
1008    #[test]
1009    fn many_empty_frames_before_the_tar_are_skipped() {
1010        let mut empty = zstd::stream::write::Encoder::new(Vec::new(), 3).unwrap();
1011        empty
1012            .set_parameter(zstd::zstd_safe::CParameter::ChecksumFlag(true))
1013            .unwrap();
1014        let empty = empty.finish().unwrap();
1015
1016        let mut many = Vec::new();
1017        for _ in 0..10_000 {
1018            many.extend_from_slice(&empty);
1019        }
1020        many.extend_from_slice(bytes("one"));
1021        let dir = tempfile::tempdir().unwrap();
1022        let path = dir.path().join("empty-frames.tar.zst");
1023        std::fs::write(&path, many).unwrap();
1024        let storage =
1025            std::sync::Arc::new(super::super::storage::Storage::open(&path, false).unwrap());
1026        let opened = open(&storage, None).unwrap();
1027        let mut w = opened.format.solid().unwrap().walk(None).unwrap();
1028        let all = files(&mut *w);
1029        assert_eq!(all.len(), 3);
1030    }
1031
1032    #[test]
1033    fn a_real_archive_walks_to_its_entries() {
1034        let (_dir, o) = opened("one");
1035        let mut w = o.format.solid().unwrap().walk(None).unwrap();
1036        let all = files(&mut *w);
1037        assert_eq!(all.len(), 3);
1038        assert_eq!(
1039            all[std::path::Path::new("game/data/random.bin")].len(),
1040            128 * 1024
1041        );
1042        assert_eq!(
1043            all[std::path::Path::new("game/data/text.txt")].len(),
1044            128 * 1024
1045        );
1046        assert!(all.contains_key(std::path::Path::new("game/README.txt")));
1047    }
1048
1049    #[test]
1050    fn a_single_frame_is_refused_in_place() {
1051        let (_dir, o) = opened("one");
1052        let why = o
1053            .format
1054            .refuses_in_place()
1055            .expect("one frame cannot be freed");
1056        assert!(why.contains("one zstd frame"), "got: {why}");
1057    }
1058
1059    #[test]
1060    fn several_checked_frames_free_space() {
1061        for name in ["two", "skip", "seekable", "pzstd"] {
1062            let (_dir, o) = opened(name);
1063            assert!(
1064                o.format.refuses_in_place().is_none(),
1065                "{name}: {}",
1066                o.format.refuses_in_place().unwrap_or_default()
1067            );
1068        }
1069    }
1070
1071    #[test]
1072    fn frames_without_a_check_are_refused_in_place() {
1073        for name in ["nocheck", "nocheck_two"] {
1074            let (_dir, o) = opened(name);
1075            let why = o.format.refuses_in_place().unwrap();
1076            assert!(why.contains("checksum"), "{name}: {why}");
1077        }
1078    }
1079
1080    #[test]
1081    fn damage_is_refused_before_anything_is_touched() {
1082        for (name, says) in [
1083            ("bad_check", "damaged"),
1084            ("truncated", "truncated"),
1085            ("bad_magic", "zstd frame"),
1086        ] {
1087            let err = open_error(name, name);
1088            assert!(err.contains(says), "{name}: {err}");
1089        }
1090    }
1091
1092    #[test]
1093    fn a_window_over_the_cap_or_a_dictionary_is_unsupported() {
1094        for name in ["long31", "dict"] {
1095            let (_dir, storage) = storage_of(name, name);
1096            let err = match open(&storage, None) {
1097                Ok(_) => panic!("{name} opened"),
1098                Err(e) => e,
1099            };
1100            assert!(err.is::<super::super::Unsupported>(), "{name}: {err:#}");
1101        }
1102    }
1103
1104    #[test]
1105    fn a_bare_zstd_file_is_not_an_archive() {
1106        let (_dir, storage) = storage_of("notar", "notar.zst");
1107        let err = match super::super::open(&storage, None, None) {
1108            Ok(_) => panic!("a plain zstd file opened as an archive"),
1109            Err(e) => format!("{e:#}"),
1110        };
1111        assert!(err.contains("does not contain a tar archive"), "got: {err}");
1112    }
1113
1114    #[test]
1115    fn a_resumed_walk_continues_where_the_point_is() {
1116        let (_dir, o) = opened("two");
1117        let mut w = o.format.solid().unwrap().walk(None).unwrap();
1118        let mut point = None;
1119        loop {
1120            match w.next(usize::MAX).unwrap() {
1121                super::super::targz::Event::Point => {
1122                    point = Some(w.point().unwrap());
1123                    break;
1124                }
1125                super::super::targz::Event::End => break,
1126                _ => {}
1127            }
1128        }
1129        let point = point.expect("two frames have a boundary");
1130        let (_dir2, storage) = storage_of("two", "two");
1131        let o = open(&storage, Some(&point)).unwrap();
1132        let mut w = o.format.solid().unwrap().walk(Some(&point)).unwrap();
1133        let resumed = files(&mut *w);
1134        assert!(!resumed.is_empty(), "the walk found the rest of the tar");
1135    }
1136
1137    #[test]
1138    fn a_resume_still_knows_the_stream_was_multi_frame() {
1139        let (_dir, o) = opened("two");
1140        let mut w = o.format.solid().unwrap().walk(None).unwrap();
1141        let mut point = None;
1142        loop {
1143            match w.next(usize::MAX).unwrap() {
1144                super::super::targz::Event::Point => {
1145                    point = Some(w.point().unwrap());
1146                    break;
1147                }
1148                super::super::targz::Event::End => break,
1149                _ => {}
1150            }
1151        }
1152        let point = point.expect("two frames have a boundary");
1153        let (_dir2, storage) = storage_of("two", "two");
1154        let o = open(&storage, Some(&point)).unwrap();
1155        assert!(
1156            o.format.refuses_in_place().is_none(),
1157            "a resumed multi-frame stream still frees space"
1158        );
1159    }
1160
1161    #[test]
1162    fn bad_magic_and_truncation_are_refused() {
1163        let err = refused("bad_magic");
1164        assert!(err.contains("zstd frame"), "got: {err}");
1165        let err = refused("truncated");
1166        assert!(
1167            err.contains("shorter") || err.contains("truncated") || err.contains("ends"),
1168            "got: {err}"
1169        );
1170    }
1171}