Skip to main content

hatchzip_core/archive/
tarxz.rs

1//! A `.xz`-compressed tar holds its whole tar in one stream, and like gzip
2//! a stream is decodable only from the front. Unlike gzip, that stream is a
3//! sequence of blocks that share nothing: every block decodes entirely from
4//! its own bytes. So the walk reads one block at a time, and a point
5//! between two blocks is a resume point that needs nothing from the output
6//! before it. The engine frees the blocks behind the decoder by punching
7//! them away at those points (see `Run::stream_solid` in the engine).
8//!
9//! [`crate::archive::xz`] parses the container: every block's header, where
10//! its data and check lie, and the filters it declares. The walk builds the
11//! filter chain each header names over a source bounded to the block's own
12//! compressed bytes, verifies every block's check as it completes, and
13//! refuses a block that does not decode before a file claims more of it. A
14//! resumed run starts at its resume point's block: the blocks before it
15//! were freed, and the container is parsed again without revalidating the
16//! headers those freed blocks write on, which no longer exist.
17//!
18//! A stream has to hold more than one block for any of that to matter: a
19//! single-threaded run of xz (`xz -T1`, or writing on one core) puts the
20//! whole archive in one block. Nothing can be freed while one block is
21//! being decoded, so such an archive is refused for in-place extraction,
22//! with `--keep-archive` still working: it decodes as usual, and the
23//! archive is left whole anyway. The tar parser itself is the one both
24//! compressed tars share, see `targz`.
25
26use std::io::{self, Cursor, Read, Seek, SeekFrom};
27use std::sync::Arc;
28
29use anyhow::{Context, Result, anyhow, bail};
30use lzma_rust2::Lzma2Reader;
31use lzma_rust2::filter::{bcj::BcjReader, delta::DeltaReader};
32
33use super::storage::Storage;
34use super::targz::{self, CodecKind, Event, Feed, Profile, StreamPoint, TarAt, TarStream};
35use super::xz::{Block, Check, Filter, Xz};
36use super::{
37    Format, Item, Kind, Opened, Sink, SolidStream, SolidWalker, Unit, Unsupported, Worker,
38};
39use crate::journal::Resume;
40
41pub const NAME: &str = "tar.xz";
42
43/// Decoded output is handed out in pieces of at most this much, as targz
44/// does.
45const BUF: usize = targz::BUF;
46
47/// The largest LZMA2 dictionary a block may name. It is allocated whole,
48/// and xz's presets top out at 256 MiB, so this only refuses archives
49/// built to exhaust the extractor's memory.
50const MAX_DICT: u32 = 1 << 30;
51
52const CRC64_POLY: u64 = 0xC96C_5795_D787_0F42;
53
54const fn make_crc64_table() -> [u64; 256] {
55    let mut table = [0; 256];
56    let mut i = 0;
57    while i < 256 {
58        let mut crc = i as u64;
59        let mut j = 0;
60        while j < 8 {
61            crc = if crc & 1 != 0 {
62                (crc >> 1) ^ CRC64_POLY
63            } else {
64                crc >> 1
65            };
66            j += 1;
67        }
68        table[i] = crc;
69        i += 1;
70    }
71    table
72}
73
74const CRC64_TABLE: [u64; 256] = make_crc64_table();
75
76/// CRC-64/XZ, what most xz archives check their blocks with. lzma-rust2
77/// keeps its own private.
78#[derive(Clone, Copy)]
79struct Crc64 {
80    state: u64,
81}
82
83impl Crc64 {
84    fn new() -> Self {
85        Self { state: u64::MAX }
86    }
87
88    fn update(&mut self, data: &[u8]) {
89        for &byte in data {
90            let index = ((self.state ^ u64::from(byte)) & 0xFF) as usize;
91            self.state = (self.state >> 8) ^ CRC64_TABLE[index];
92        }
93    }
94
95    fn finalize(self) -> u64 {
96        self.state ^ u64::MAX
97    }
98}
99
100/// The check a block runs against, as bytes little-endian, which is how
101/// the container stores them (spec 2.1.1.2).
102enum Running {
103    Crc32(crc32fast::Hasher),
104    Crc64(Crc64),
105    None,
106}
107
108impl Running {
109    fn new(check: Check) -> Self {
110        match check {
111            Check::Crc32 => Running::Crc32(crc32fast::Hasher::new()),
112            Check::Crc64 => Running::Crc64(Crc64::new()),
113            Check::None | Check::Sha256 | Check::Other { .. } => Running::None,
114        }
115    }
116
117    fn update(&mut self, data: &[u8]) {
118        match self {
119            Running::Crc32(h) => h.update(data),
120            Running::Crc64(h) => h.update(data),
121            Running::None => {}
122        }
123    }
124
125    fn finish(self) -> Vec<u8> {
126        match self {
127            Running::Crc32(h) => h.finalize().to_le_bytes().to_vec(),
128            Running::Crc64(h) => h.finalize().to_le_bytes().to_vec(),
129            Running::None => Vec::new(),
130        }
131    }
132}
133
134/// What refuses a multi-stream, unchecked or otherwise unsupported xz
135/// archive before anything is touched, except a single-block stream and a
136/// stream whose blocks carry no check: both decode fine, and are refused
137/// only for in-place extraction (see [`TarXz`]'s `Format` impl).
138fn policy(xz: &Xz) -> Result<()> {
139    let [stream] = xz.streams.as_slice() else {
140        bail!(
141            "the archive holds {} xz streams one after another, which is not supported. \
142             Extract them as separate archives",
143            xz.streams.len()
144        );
145    };
146    match stream.check {
147        Check::None | Check::Crc32 | Check::Crc64 => {}
148        Check::Sha256 => bail!(
149            "the archive checks every xz block with SHA-256, which is not supported. \
150             xz's default --check=crc64, or --check=crc32, works"
151        ),
152        Check::Other { .. } => bail!(
153            "the archive checks its xz blocks with a check of an unknown kind, which \
154             is not supported"
155        ),
156    }
157    for b in &stream.blocks {
158        for f in &b.filters {
159            match *f {
160                Filter::Unknown { id } => {
161                    bail!(
162                        "a block of the archive uses the xz filter {id:#x}, which is not \
163                         supported"
164                    );
165                }
166                Filter::Lzma2 { dict_size } if dict_size > MAX_DICT => bail!(
167                    "a block of the archive names an LZMA2 dictionary beyond 1 GiB, \
168                     which is not supported"
169                ),
170                _ => {}
171            }
172        }
173    }
174    Ok(())
175}
176
177/// The container with what the format refuses about it, and a resumed
178/// run's walk.
179pub struct Solid {
180    storage: Arc<Storage>,
181    xz: Xz,
182    /// The point the scan began at: a resumed run's, whose earlier blocks
183    /// were freed, or `None`.
184    from: Option<Resume>,
185    profile: Profile,
186}
187
188impl Solid {
189    fn new(storage: Arc<Storage>, from: Option<&Resume>) -> Result<Self> {
190        let from_byte = from.map_or(0, |r| r.bit / 8);
191        let xz = {
192            let mut reader = storage.reader(None);
193            Xz::parse_resumed(&mut reader, storage.original_len(), from_byte)
194                .context("reading the xz stream's structure")?
195        };
196        // A resume reads the same container, so it meets the same refusals;
197        // a journal that names a check or filter this build cannot verify
198        // fails here rather than halfway into a block.
199        policy(&xz).map_err(|e| anyhow::Error::new(super::Unsupported(e)))?;
200        Ok(Self {
201            storage,
202            xz,
203            from: from.cloned(),
204            profile: Profile::default(),
205        })
206    }
207
208    /// Walks the whole of what `from` leaves, or the whole archive.
209    pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
210        Walker::new(self, from)
211    }
212}
213
214/// Whether the xz stream opens with a tar header, reading only as far as the
215/// first one. Used to tell a nested `.tar.xz` from a compressed file that is
216/// not an archive, before either is offered.
217pub(crate) fn holds_tar(storage: &Arc<Storage>) -> bool {
218    let Ok(solid) = Solid::new(storage.clone(), None) else {
219        return false;
220    };
221    let Ok(mut walk) = solid.walk(None) else {
222        return false;
223    };
224    matches!(
225        walk.next(usize::MAX),
226        Ok(crate::archive::targz::Event::Entry { .. })
227    )
228}
229
230/// Walks the archive from `from`, or from its start, listing what is left
231/// and measuring it. Damage anywhere is found here, before anything is
232/// touched.
233pub fn open(storage: &Arc<Storage>, from: Option<&Resume>) -> Result<Opened> {
234    let name = storage
235        .primary()
236        .file_name()
237        .unwrap_or_default()
238        .to_string_lossy()
239        .into_owned();
240    storage.expect_reads(storage.original_len() - from.map_or(0, |r| r.bit / 8));
241    let read = (|| -> Result<(Solid, Vec<Item>, Profile)> {
242        let solid = Solid::new(storage.clone(), from)?;
243        let (items, profile) = super::scan(&solid, from)?;
244        Ok((solid, items, profile))
245    })();
246    // Unsupported is not damage: the archive is valid, this build just does
247    // not extract it. A parse error that says so (an oversized index) keeps
248    // the same class; everything else that stops the read is damage.
249    let (mut solid, items, profile) = read
250        .map_err(|e| {
251            if e.is::<Unsupported>()
252                || e.downcast_ref::<std::io::Error>()
253                    .is_some_and(|io| io.kind() == io::ErrorKind::Unsupported)
254            {
255                e
256            } else {
257                anyhow::Error::new(super::Damaged(e))
258            }
259        })
260        .with_context(|| format!("checking {name} (nothing was changed)"))?;
261    solid.profile = profile;
262    Ok(Opened {
263        name: NAME,
264        format: Box::new(TarXz { solid }),
265        // Even with no entries left there is one unit, so that a resume point
266        // past the last entry still belongs to something.
267        units: vec![Unit {
268            start: 0,
269            key: 0,
270            items,
271            encrypted: false,
272        }],
273        // Nothing is saved: the stream is never truncated from the end.
274        tail_start: storage.original_len(),
275    })
276}
277
278struct TarXz {
279    solid: Solid,
280}
281
282impl Format for TarXz {
283    fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
284        Ok(Box::new(TarXzWorker { solid: &self.solid }))
285    }
286
287    fn solid(&self) -> Option<&dyn SolidStream> {
288        Some(&self.solid)
289    }
290
291    fn refuses_in_place(&self) -> Option<String> {
292        let stream = self.solid.xz.streams.first()?;
293        let whole = stream.blocks.len() < 2;
294        let unchecked = stream.check == Check::None;
295        Some(match (whole, unchecked) {
296            (true, true) => String::from(
297                "the archive's whole tar is inside one xz block and its blocks carry no \
298                 check, so nothing of it can be freed as it is extracted",
299            ),
300            (true, false) => String::from(
301                "the archive's whole tar is inside one xz block, so nothing of the archive \
302                 can be freed as it is extracted",
303            ),
304            (false, true) => String::from(
305                "the archive's xz blocks carry no check, so damage inside them could not be \
306                 detected before the bytes behind are freed",
307            ),
308            (false, false) => return None,
309        })
310    }
311}
312
313impl SolidStream for Solid {
314    fn profile(&self) -> &Profile {
315        &self.profile
316    }
317
318    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>> {
319        Ok(Box::new(self.walk(from)?))
320    }
321}
322
323/// The compressed bytes of one block and nothing else: a decoder that lies
324/// about how much of the block it has decoded cannot read past them into
325/// the blocks that follow.
326struct Bytes {
327    reader: super::storage::Reader,
328    left: u64,
329}
330
331impl Read for Bytes {
332    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
333        let cap = self.left.min(buf.len() as u64) as usize;
334        if cap == 0 {
335            return Ok(0);
336        }
337        let n = self.reader.read(&mut buf[..cap])?;
338        if n == 0 && self.left > 0 {
339            return Err(io::Error::new(
340                io::ErrorKind::UnexpectedEof,
341                "the archive is shorter than its blocks say",
342            ));
343        }
344        self.left -= n as u64;
345        Ok(n)
346    }
347}
348
349/// The filter chain of one block, over its bounded source. The chain ends
350/// in LZMA2 (the container guarantees it), so the build goes backwards from
351/// the header's list: the LZMA2 decoder sits on the source and every size
352/// preserving filter the header names wraps it, until the last one,
353/// which is the first the writer applied.
354struct Stage(Box<dyn Read>);
355
356impl Stage {
357    fn build(b: &Block, storage: &Arc<Storage>) -> Result<Stage> {
358        let mut r = storage.reader(None);
359        // The reader starts at the file; the block owns its own slice of it.
360        r.seek(SeekFrom::Start(b.data_off))
361            .with_context(|| "reading the block's compressed data")?;
362        Stage::over(
363            Bytes {
364                reader: r,
365                left: b.comp_len,
366            },
367            b,
368        )
369    }
370
371    /// The chain over any source holding exactly the block's compressed
372    /// bytes. Tests decode a fixture's block from memory through it.
373    fn over(source: impl Read + 'static, b: &Block) -> Result<Stage> {
374        let mut chain: Box<dyn Read> = Box::new(source);
375        for f in b.filters.iter().rev() {
376            chain = match *f {
377                Filter::Lzma2 { dict_size } => {
378                    if dict_size > MAX_DICT {
379                        bail!(
380                            "a block of the archive names an LZMA2 dictionary beyond 1 GiB, \
381                             which is not supported"
382                        );
383                    }
384                    // No block borrows from the blocks before it, so no back
385                    // reference reaches past its own output: the declared
386                    // dictionary is an upper bound, and a block of a few KiB
387                    // does not need (or deserve) a gigabyte of it.
388                    let dict =
389                        dict_size.min(b.uncomp_len.clamp(4 * 1024, u64::from(u32::MAX)) as u32);
390                    Box::new(Lzma2Reader::new(chain, dict, None))
391                }
392                Filter::Delta { dist } => Box::new(DeltaReader::new(chain, dist as usize)),
393                Filter::Bcj { arch, start } => Box::new(bcjer(arch, chain, start as usize)?),
394                Filter::Unknown { .. } => {
395                    bail!("a block of the archive uses an xz filter that is not supported")
396                }
397            };
398        }
399        Ok(Stage(chain))
400    }
401
402    /// Reads decoded bytes; 0 means the block's stream ended.
403    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
404        Read::read(self.0.as_mut(), buf)
405    }
406}
407
408fn bcjer(arch: u64, inner: Box<dyn Read>, start: usize) -> Result<BcjReader<Box<dyn Read>>> {
409    Ok(match arch {
410        0x04 => BcjReader::new_x86(inner, start),
411        0x05 => BcjReader::new_ppc(inner, start),
412        0x06 => BcjReader::new_ia64(inner, start),
413        0x07 => BcjReader::new_arm(inner, start),
414        0x08 => BcjReader::new_arm_thumb(inner, start),
415        0x09 => BcjReader::new_sparc(inner, start),
416        0x0A => BcjReader::new_arm64(inner, start),
417        0x0B => BcjReader::new_riscv(inner, start),
418        _ => bail!("{arch:#x} is not a BCJ filter architecture, and it parses as one"),
419    })
420}
421
422/// The xz side of a walk: it decodes the stream one block at a time into
423/// the tar parser, and verifies each block's check where the container
424/// says it lies.
425struct XzFeed {
426    blocks: Vec<Block>,
427    check: Check,
428    storage: Arc<Storage>,
429    /// The chain of the block being decoded, `None` between blocks.
430    stage: Option<Stage>,
431    /// Which block `stage` decodes, or the next one to build. Past the last
432    /// block once the stream has ended.
433    block: usize,
434    /// Uncompressed bytes of the block `stage` is decoding, still to hand out.
435    left: u64,
436    /// The block's check, as its bytes come out of the chain.
437    running: Running,
438    /// Every block of the stream has been decoded.
439    ended: bool,
440}
441
442impl XzFeed {
443    fn new(storage: Arc<Storage>, check: Check, blocks: Vec<Block>, block: usize) -> Self {
444        Self {
445            blocks,
446            check,
447            storage,
448            stage: None,
449            block,
450            left: 0,
451            running: Running::None,
452            ended: false,
453        }
454    }
455
456    /// The block's uncompressed size is what its header says, so reaching
457    /// it means the whole block decoded. Its check is how a corrupt decode
458    /// gets caught, before anything can be worth the bytes it claims.
459    fn finish_block(&mut self) -> Result<()> {
460        let computed = std::mem::replace(&mut self.running, Running::None).finish();
461        match self.check {
462            // Nothing to compare. The format refuses in-place extraction of
463            // an unchecked stream, so only a kept run gets here.
464            Check::None => {}
465            Check::Crc32 | Check::Crc64 => {
466                let b = &self.blocks[self.block];
467                let stored = {
468                    let mut r = self.storage.reader(None);
469                    r.seek(SeekFrom::Start(b.check_off)).with_context(|| {
470                        format!(
471                            "reading the check of the archive's block {}",
472                            self.block + 1
473                        )
474                    })?;
475                    let mut out = vec![0u8; self.check.size() as usize];
476                    r.read_exact(&mut out).with_context(|| {
477                        format!(
478                            "reading the check of the archive's block {}",
479                            self.block + 1
480                        )
481                    })?;
482                    out
483                };
484                if stored != computed {
485                    let name = if self.check == Check::Crc32 {
486                        "CRC-32"
487                    } else {
488                        "CRC-64"
489                    };
490                    bail!(
491                        "the archive's block {} fails its {name} check; it is damaged",
492                        self.block + 1
493                    );
494                }
495            }
496            // The policy refuses these before a byte is decoded; reaching
497            // one means the container changed under the run.
498            Check::Sha256 | Check::Other { .. } => bail!(
499                "the archive's blocks are checked with a kind HatchZip does not verify, \
500                 which is not supported"
501            ),
502        }
503        self.stage = None;
504        self.block += 1;
505        self.ended = self.block == self.blocks.len();
506        Ok(())
507    }
508}
509
510impl Feed for XzFeed {
511    fn fill(&mut self, buf: &mut [u8]) -> Result<usize> {
512        if self.stage.is_none() {
513            let Some(b) = self.blocks.get(self.block) else {
514                self.ended = true;
515                return Ok(0);
516            };
517            anyhow::ensure!(
518                b.validated,
519                "the journal's resume point names a block this archive no longer holds \
520                 whole, and will not be modified"
521            );
522            self.stage = Some(Stage::build(b, &self.storage)?);
523            self.left = b.uncomp_len;
524            self.running = Running::new(self.check);
525        }
526        let want = self.left.min(buf.len() as u64) as usize;
527        let n = self
528            .stage
529            .as_mut()
530            .expect("the block's chain was just built")
531            .read(&mut buf[..want])
532            .with_context(|| format!("decoding the archive's block {}", self.block + 1))?;
533        if n == 0 {
534            bail!(
535                "the archive's block {} decodes {} bytes short of what its container says; \
536                 it is damaged",
537                self.block + 1,
538                self.left
539            );
540        }
541        self.left -= n as u64;
542        self.running.update(&buf[..n]);
543        if self.left == 0 {
544            self.finish_block()?;
545        }
546        Ok(n)
547    }
548
549    fn restartable(&self) -> bool {
550        // A block's end is the only place the stream restarts from, and it
551        // was just verified: the next block's header is intact.
552        self.stage.is_none() && !self.ended
553    }
554
555    fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume> {
556        let b = self
557            .blocks
558            .get(self.block)
559            .ok_or_else(|| anyhow!("the stream has no block a resume point could follow"))?;
560        Ok(Resume {
561            unit: 0,
562            written,
563            // Points are at block headers, always whole bytes.
564            bit: b.header_off * 8,
565            crc: 0,
566            stream: Some(Box::new(StreamPoint {
567                kind: CodecKind::Xz,
568                member_start: false,
569                member_crc: 0,
570                member_len: 0,
571                window: Vec::new(),
572                block: self.block as u64,
573                level: None,
574                combined_crc: None,
575                tar_pos,
576                at,
577            })),
578        })
579    }
580
581    fn point_byte(&self) -> Option<u64> {
582        if self.ended {
583            None
584        } else {
585            self.blocks.get(self.block).map(|b| b.header_off)
586        }
587    }
588}
589
590/// Walks the archive from `from`, or from its start, listing what is left
591/// and measuring it. Damage anywhere is found here, before anything is
592/// touched.
593pub struct Walker {
594    inner: TarStream<XzFeed>,
595}
596
597impl Walker {
598    fn new(solid: &Solid, from: Option<&Resume>) -> Result<Self> {
599        let stream = solid
600            .xz
601            .streams
602            .first()
603            .ok_or_else(|| anyhow!("the archive holds no xz stream"))?;
604        let feed = match from {
605            None => XzFeed::new(
606                solid.storage.clone(),
607                stream.check,
608                stream.blocks.clone(),
609                0,
610            ),
611            Some(r) => {
612                let s = r.stream.as_ref().ok_or_else(|| {
613                    anyhow!("the journal's resume point does not belong to a compressed tar")
614                })?;
615                if s.kind != CodecKind::Xz {
616                    bail!(
617                        "the journal's resume point belongs to {} tar, not this archive's",
618                        match s.kind {
619                            CodecKind::Gzip => "a gzip member of a",
620                            CodecKind::Xz => "an xz block of a",
621                            CodecKind::Bzip2 => "a bzip2 block of a",
622                            CodecKind::Zstd => "a zstd frame of a",
623                        }
624                    );
625                }
626                let Ok(block) = usize::try_from(s.block) else {
627                    bail!("the journal's resume point names a block the format has none of");
628                };
629                let Some(b) = stream.blocks.get(block) else {
630                    bail!(
631                        "the journal's resume point names block {}, which the archive's \
632                         xz stream does not hold",
633                        block + 1
634                    );
635                };
636                if !b.validated || b.header_off != r.bit / 8 {
637                    bail!(
638                        "the journal's resume point is inconsistent; the archive will \
639                         not be modified"
640                    );
641                }
642                if !matches!(s.at, TarAt::File { .. }) && r.written != 0 {
643                    bail!(
644                        "the journal's resume point claims a file is open where none is; \
645                         the archive will not be modified"
646                    );
647                }
648                XzFeed::new(
649                    solid.storage.clone(),
650                    stream.check,
651                    stream.blocks.clone(),
652                    block,
653                )
654            }
655        };
656        Ok(Self {
657            inner: TarStream::new(feed, from)?,
658        })
659    }
660
661    fn next(&mut self, max: usize) -> Result<Event<'_>> {
662        self.inner.next(max)
663    }
664
665    fn point(&self) -> Result<Resume> {
666        self.inner.point()
667    }
668
669    fn point_byte(&self) -> Option<u64> {
670        self.inner.point_byte()
671    }
672}
673
674impl SolidWalker for Walker {
675    fn next(&mut self, max: usize) -> Result<Event<'_>> {
676        self.next(max)
677    }
678
679    fn point(&self) -> Result<Resume> {
680        self.point()
681    }
682
683    fn point_byte(&self) -> Option<u64> {
684        self.point_byte()
685    }
686}
687
688/// Decodes the whole stream in one go, for `test` and `--verify-first`. The
689/// extraction itself goes through the engine's streaming path instead.
690struct TarXzWorker<'a> {
691    solid: &'a Solid,
692}
693
694impl Worker for TarXzWorker<'_> {
695    fn extract(&mut self, _unit: &Unit, sink: &mut dyn Sink) -> Result<()> {
696        let mut w = self.solid.walk(self.solid.from.as_ref())?;
697        loop {
698            match w.next(BUF)? {
699                Event::Entry { item, done, .. } if item.kind == Kind::File => {
700                    // A resumed run's open file: only its rest is here.
701                    let left = Item {
702                        size: item.size - done,
703                        ..item
704                    };
705                    let mut data = FileData {
706                        walker: &mut w,
707                        ended: false,
708                    };
709                    sink.item(&left, &mut data)?;
710                    let mut rest = [0u8; 4096];
711                    while data.read(&mut rest)? > 0 {}
712                }
713                Event::Entry { item, link, .. } => {
714                    sink.item(&item, &mut Cursor::new(link.unwrap_or_default()))?;
715                }
716                Event::Data(_) | Event::FileEnd | Event::Point => {}
717                Event::End => return Ok(()),
718            }
719        }
720    }
721}
722
723/// One file's data, read through the walker.
724struct FileData<'a> {
725    walker: &'a mut Walker,
726    ended: bool,
727}
728
729impl Read for FileData<'_> {
730    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
731        while !self.ended && !buf.is_empty() {
732            match self.walker.next(buf.len()) {
733                Ok(Event::Data(d)) => {
734                    buf[..d.len()].copy_from_slice(d);
735                    return Ok(d.len());
736                }
737                Ok(Event::Point) => {}
738                Ok(Event::FileEnd) => self.ended = true,
739                Ok(_) => return Err(io::Error::other("the tar entry ended unexpectedly")),
740                Err(e) => return Err(io::Error::other(format!("{e:#}"))),
741            }
742        }
743        Ok(0)
744    }
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750    use std::io::Cursor;
751
752    /// The fixtures come from the real xz CLI; see fixtures/xz/.
753    fn fixture(name: &str) -> &'static [u8] {
754        match name {
755            "t1" => include_bytes!("fixtures/xz/xz-t1.xz"),
756            "multi" => include_bytes!("fixtures/xz/xz-multi.xz"),
757            "uneven" => include_bytes!("fixtures/xz/xz-uneven.xz"),
758            "crc32" => include_bytes!("fixtures/xz/xz-crc32.xz"),
759            "nocheck" => include_bytes!("fixtures/xz/xz-nocheck.xz"),
760            "sha256" => include_bytes!("fixtures/xz/xz-sha256.xz"),
761            "bcj" => include_bytes!("fixtures/xz/xz-bcj.xz"),
762            "delta" => include_bytes!("fixtures/xz/xz-delta.xz"),
763            "multistream" => include_bytes!("fixtures/xz/xz-multistream.xz"),
764            _ => unreachable!(),
765        }
766    }
767
768    fn parse(name: &str) -> Xz {
769        let bytes = fixture(name);
770        Xz::parse(&mut Cursor::new(bytes), bytes.len() as u64).unwrap()
771    }
772
773    /// Decodes every block of a fixture through the same chain the walk
774    /// builds, and checks each block against the bytes the real xz CLI
775    /// stored at the offset the index records. Returns the output.
776    fn decode(name: &str) -> Vec<u8> {
777        let bytes = fixture(name);
778        let xz = parse(name);
779        let stream = &xz.streams[0];
780        let mut out = Vec::new();
781        for block in &stream.blocks {
782            let from = block.data_off as usize;
783            let to = from + block.comp_len as usize;
784            let mut stage = Stage::over(Cursor::new(bytes[from..to].to_vec()), block).unwrap();
785            let mut running = Running::new(stream.check);
786            let mut left = block.uncomp_len;
787            let mut buf = vec![0u8; 64 * 1024];
788            while left > 0 {
789                let want = (left as usize).min(buf.len());
790                let n = stage.read(&mut buf[..want]).unwrap();
791                assert!(n > 0, "block ended early");
792                running.update(&buf[..n]);
793                out.extend_from_slice(&buf[..n]);
794                left -= n as u64;
795            }
796            if stream.check != Check::None {
797                let at = block.check_off as usize;
798                let stored = &bytes[at..at + stream.check.size() as usize];
799                assert_eq!(running.finish(), stored, "block check");
800            }
801        }
802        out
803    }
804
805    #[test]
806    fn crc64_matches_the_known_vector() {
807        let mut crc = Crc64::new();
808        crc.update(b"123456789");
809        assert_eq!(crc.finalize(), 0x995D_C9BB_DF19_39FA);
810    }
811
812    #[test]
813    fn one_block_passes_policy_but_still_cannot_free_anything() {
814        let xz = parse("t1");
815        assert!(xz.streams[0].blocks.len() < 2);
816        policy(&xz).unwrap();
817    }
818
819    #[test]
820    fn several_blocks_pass_policy() {
821        policy(&parse("multi")).unwrap();
822    }
823
824    #[test]
825    fn concatenated_streams_are_refused() {
826        let err = policy(&parse("multistream")).unwrap_err();
827        assert!(
828            err.to_string().contains("one after another"),
829            "got: {err:#}"
830        );
831    }
832
833    #[test]
834    fn sha256_checks_are_refused() {
835        let err = policy(&parse("sha256")).unwrap_err();
836        assert!(err.to_string().contains("SHA-256"), "got: {err:#}");
837    }
838
839    #[test]
840    fn an_unchecked_stream_passes_policy_because_it_extracts_while_kept() {
841        let xz = parse("nocheck");
842        assert_eq!(xz.streams[0].check, Check::None);
843        policy(&xz).unwrap();
844    }
845
846    /// Same payload through every single-block shape: the LZMA2 reader and
847    /// the container's check must reproduce what the real xz CLI wrote.
848    #[test]
849    fn real_archives_decode_through_their_block_chains() {
850        let plain = decode("t1");
851        assert_eq!(plain.len(), 8192);
852        for name in ["multi", "crc32", "nocheck"] {
853            assert_eq!(decode(name), plain, "{name} decoded differently");
854        }
855        // BCJ and Delta were made from another payload; both filters must
856        // reproduce it, and it is the one that starts like an executable.
857        let filtered = decode("bcj");
858        assert_eq!(filtered.len(), 8192);
859        assert_eq!(decode("delta"), filtered, "delta decoded differently");
860        assert!(filtered.starts_with(b"MZ"));
861    }
862
863    #[test]
864    fn uneven_blocks_decode_to_the_whole_payload() {
865        let out = decode("uneven");
866        assert_eq!(out.len(), 29_491_200);
867        assert!(out.iter().enumerate().all(|(i, b)| *b == (i % 256) as u8));
868    }
869}