1use 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
43const BUF: usize = targz::BUF;
46
47const 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#[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
100enum 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
134fn 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
177pub struct Solid {
180 storage: Arc<Storage>,
181 xz: Xz,
182 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 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 pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
210 Walker::new(self, from)
211 }
212}
213
214pub fn open(storage: &Arc<Storage>, from: Option<&Resume>) -> Result<Opened> {
218 let name = storage
219 .primary()
220 .file_name()
221 .unwrap_or_default()
222 .to_string_lossy()
223 .into_owned();
224 storage.expect_reads(storage.original_len() - from.map_or(0, |r| r.bit / 8));
225 let read = (|| -> Result<(Solid, Vec<Item>, Profile)> {
226 let solid = Solid::new(storage.clone(), from)?;
227 let (items, profile) = super::scan(&solid, from)?;
228 Ok((solid, items, profile))
229 })();
230 let (mut solid, items, profile) = read
234 .map_err(|e| {
235 if e.is::<Unsupported>()
236 || e.downcast_ref::<std::io::Error>()
237 .is_some_and(|io| io.kind() == io::ErrorKind::Unsupported)
238 {
239 e
240 } else {
241 anyhow::Error::new(super::Damaged(e))
242 }
243 })
244 .with_context(|| format!("checking {name} (nothing was changed)"))?;
245 solid.profile = profile;
246 Ok(Opened {
247 name: NAME,
248 format: Box::new(TarXz { solid }),
249 units: vec![Unit {
252 start: 0,
253 key: 0,
254 items,
255 encrypted: false,
256 }],
257 tail_start: storage.original_len(),
259 })
260}
261
262struct TarXz {
263 solid: Solid,
264}
265
266impl Format for TarXz {
267 fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
268 Ok(Box::new(TarXzWorker { solid: &self.solid }))
269 }
270
271 fn solid(&self) -> Option<&dyn SolidStream> {
272 Some(&self.solid)
273 }
274
275 fn refuses_in_place(&self) -> Option<String> {
276 let stream = self.solid.xz.streams.first()?;
277 let whole = stream.blocks.len() < 2;
278 let unchecked = stream.check == Check::None;
279 Some(match (whole, unchecked) {
280 (true, true) => String::from(
281 "the archive's whole tar is inside one xz block and its blocks carry no \
282 check, so nothing of it can be freed as it is extracted",
283 ),
284 (true, false) => String::from(
285 "the archive's whole tar is inside one xz block, so nothing of the archive \
286 can be freed as it is extracted",
287 ),
288 (false, true) => String::from(
289 "the archive's xz blocks carry no check, so damage inside them could not be \
290 detected before the bytes behind are freed",
291 ),
292 (false, false) => return None,
293 })
294 }
295}
296
297impl SolidStream for Solid {
298 fn profile(&self) -> &Profile {
299 &self.profile
300 }
301
302 fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>> {
303 Ok(Box::new(self.walk(from)?))
304 }
305}
306
307struct Bytes {
311 reader: super::storage::Reader,
312 left: u64,
313}
314
315impl Read for Bytes {
316 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
317 let cap = self.left.min(buf.len() as u64) as usize;
318 if cap == 0 {
319 return Ok(0);
320 }
321 let n = self.reader.read(&mut buf[..cap])?;
322 if n == 0 && self.left > 0 {
323 return Err(io::Error::new(
324 io::ErrorKind::UnexpectedEof,
325 "the archive is shorter than its blocks say",
326 ));
327 }
328 self.left -= n as u64;
329 Ok(n)
330 }
331}
332
333struct Stage(Box<dyn Read>);
339
340impl Stage {
341 fn build(b: &Block, storage: &Arc<Storage>) -> Result<Stage> {
342 let mut r = storage.reader(None);
343 r.seek(SeekFrom::Start(b.data_off))
345 .with_context(|| "reading the block's compressed data")?;
346 Stage::over(
347 Bytes {
348 reader: r,
349 left: b.comp_len,
350 },
351 b,
352 )
353 }
354
355 fn over(source: impl Read + 'static, b: &Block) -> Result<Stage> {
358 let mut chain: Box<dyn Read> = Box::new(source);
359 for f in b.filters.iter().rev() {
360 chain = match *f {
361 Filter::Lzma2 { dict_size } => {
362 if dict_size > MAX_DICT {
363 bail!(
364 "a block of the archive names an LZMA2 dictionary beyond 1 GiB, \
365 which is not supported"
366 );
367 }
368 let dict =
373 dict_size.min(b.uncomp_len.clamp(4 * 1024, u64::from(u32::MAX)) as u32);
374 Box::new(Lzma2Reader::new(chain, dict, None))
375 }
376 Filter::Delta { dist } => Box::new(DeltaReader::new(chain, dist as usize)),
377 Filter::Bcj { arch, start } => Box::new(bcjer(arch, chain, start as usize)?),
378 Filter::Unknown { .. } => {
379 bail!("a block of the archive uses an xz filter that is not supported")
380 }
381 };
382 }
383 Ok(Stage(chain))
384 }
385
386 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
388 Read::read(self.0.as_mut(), buf)
389 }
390}
391
392fn bcjer(arch: u64, inner: Box<dyn Read>, start: usize) -> Result<BcjReader<Box<dyn Read>>> {
393 Ok(match arch {
394 0x04 => BcjReader::new_x86(inner, start),
395 0x05 => BcjReader::new_ppc(inner, start),
396 0x06 => BcjReader::new_ia64(inner, start),
397 0x07 => BcjReader::new_arm(inner, start),
398 0x08 => BcjReader::new_arm_thumb(inner, start),
399 0x09 => BcjReader::new_sparc(inner, start),
400 0x0A => BcjReader::new_arm64(inner, start),
401 0x0B => BcjReader::new_riscv(inner, start),
402 _ => bail!("{arch:#x} is not a BCJ filter architecture, and it parses as one"),
403 })
404}
405
406struct XzFeed {
410 blocks: Vec<Block>,
411 check: Check,
412 storage: Arc<Storage>,
413 stage: Option<Stage>,
415 block: usize,
418 left: u64,
420 running: Running,
422 ended: bool,
424}
425
426impl XzFeed {
427 fn new(storage: Arc<Storage>, check: Check, blocks: Vec<Block>, block: usize) -> Self {
428 Self {
429 blocks,
430 check,
431 storage,
432 stage: None,
433 block,
434 left: 0,
435 running: Running::None,
436 ended: false,
437 }
438 }
439
440 fn finish_block(&mut self) -> Result<()> {
444 let computed = std::mem::replace(&mut self.running, Running::None).finish();
445 match self.check {
446 Check::None => {}
449 Check::Crc32 | Check::Crc64 => {
450 let b = &self.blocks[self.block];
451 let stored = {
452 let mut r = self.storage.reader(None);
453 r.seek(SeekFrom::Start(b.check_off)).with_context(|| {
454 format!(
455 "reading the check of the archive's block {}",
456 self.block + 1
457 )
458 })?;
459 let mut out = vec![0u8; self.check.size() as usize];
460 r.read_exact(&mut out).with_context(|| {
461 format!(
462 "reading the check of the archive's block {}",
463 self.block + 1
464 )
465 })?;
466 out
467 };
468 if stored != computed {
469 let name = if self.check == Check::Crc32 {
470 "CRC-32"
471 } else {
472 "CRC-64"
473 };
474 bail!(
475 "the archive's block {} fails its {name} check; it is damaged",
476 self.block + 1
477 );
478 }
479 }
480 Check::Sha256 | Check::Other { .. } => bail!(
483 "the archive's blocks are checked with a kind HatchZip does not verify, \
484 which is not supported"
485 ),
486 }
487 self.stage = None;
488 self.block += 1;
489 self.ended = self.block == self.blocks.len();
490 Ok(())
491 }
492}
493
494impl Feed for XzFeed {
495 fn fill(&mut self, buf: &mut [u8]) -> Result<usize> {
496 if self.stage.is_none() {
497 let Some(b) = self.blocks.get(self.block) else {
498 self.ended = true;
499 return Ok(0);
500 };
501 anyhow::ensure!(
502 b.validated,
503 "the journal's resume point names a block this archive no longer holds \
504 whole, and will not be modified"
505 );
506 self.stage = Some(Stage::build(b, &self.storage)?);
507 self.left = b.uncomp_len;
508 self.running = Running::new(self.check);
509 }
510 let want = self.left.min(buf.len() as u64) as usize;
511 let n = self
512 .stage
513 .as_mut()
514 .expect("the block's chain was just built")
515 .read(&mut buf[..want])
516 .with_context(|| format!("decoding the archive's block {}", self.block + 1))?;
517 if n == 0 {
518 bail!(
519 "the archive's block {} decodes {} bytes short of what its container says; \
520 it is damaged",
521 self.block + 1,
522 self.left
523 );
524 }
525 self.left -= n as u64;
526 self.running.update(&buf[..n]);
527 if self.left == 0 {
528 self.finish_block()?;
529 }
530 Ok(n)
531 }
532
533 fn restartable(&self) -> bool {
534 self.stage.is_none() && !self.ended
537 }
538
539 fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume> {
540 let b = self
541 .blocks
542 .get(self.block)
543 .ok_or_else(|| anyhow!("the stream has no block a resume point could follow"))?;
544 Ok(Resume {
545 unit: 0,
546 written,
547 bit: b.header_off * 8,
549 crc: 0,
550 stream: Some(Box::new(StreamPoint {
551 kind: CodecKind::Xz,
552 member_start: false,
553 member_crc: 0,
554 member_len: 0,
555 window: Vec::new(),
556 block: self.block as u64,
557 tar_pos,
558 at,
559 })),
560 })
561 }
562
563 fn point_byte(&self) -> Option<u64> {
564 if self.ended {
565 None
566 } else {
567 self.blocks.get(self.block).map(|b| b.header_off)
568 }
569 }
570}
571
572pub struct Walker {
576 inner: TarStream<XzFeed>,
577}
578
579impl Walker {
580 fn new(solid: &Solid, from: Option<&Resume>) -> Result<Self> {
581 let stream = solid
582 .xz
583 .streams
584 .first()
585 .ok_or_else(|| anyhow!("the archive holds no xz stream"))?;
586 let feed = match from {
587 None => XzFeed::new(
588 solid.storage.clone(),
589 stream.check,
590 stream.blocks.clone(),
591 0,
592 ),
593 Some(r) => {
594 let s = r.stream.as_ref().ok_or_else(|| {
595 anyhow!("the journal's resume point does not belong to a compressed tar")
596 })?;
597 if s.kind != CodecKind::Xz {
598 bail!(
599 "the journal's resume point belongs to {} tar, not this archive's",
600 match s.kind {
601 CodecKind::Gzip => "a gzip member of a",
602 CodecKind::Xz => "an xz block of a",
603 }
604 );
605 }
606 let Ok(block) = usize::try_from(s.block) else {
607 bail!("the journal's resume point names a block the format has none of");
608 };
609 let Some(b) = stream.blocks.get(block) else {
610 bail!(
611 "the journal's resume point names block {}, which the archive's \
612 xz stream does not hold",
613 block + 1
614 );
615 };
616 if !b.validated || b.header_off != r.bit / 8 {
617 bail!(
618 "the journal's resume point is inconsistent; the archive will \
619 not be modified"
620 );
621 }
622 if !matches!(s.at, TarAt::File { .. }) && r.written != 0 {
623 bail!(
624 "the journal's resume point claims a file is open where none is; \
625 the archive will not be modified"
626 );
627 }
628 XzFeed::new(
629 solid.storage.clone(),
630 stream.check,
631 stream.blocks.clone(),
632 block,
633 )
634 }
635 };
636 Ok(Self {
637 inner: TarStream::new(feed, from)?,
638 })
639 }
640
641 fn next(&mut self, max: usize) -> Result<Event<'_>> {
642 self.inner.next(max)
643 }
644
645 fn point(&self) -> Result<Resume> {
646 self.inner.point()
647 }
648
649 fn point_byte(&self) -> Option<u64> {
650 self.inner.point_byte()
651 }
652}
653
654impl SolidWalker for Walker {
655 fn next(&mut self, max: usize) -> Result<Event<'_>> {
656 self.next(max)
657 }
658
659 fn point(&self) -> Result<Resume> {
660 self.point()
661 }
662
663 fn point_byte(&self) -> Option<u64> {
664 self.point_byte()
665 }
666}
667
668struct TarXzWorker<'a> {
671 solid: &'a Solid,
672}
673
674impl Worker for TarXzWorker<'_> {
675 fn extract(&mut self, _unit: &Unit, sink: &mut dyn Sink) -> Result<()> {
676 let mut w = self.solid.walk(self.solid.from.as_ref())?;
677 loop {
678 match w.next(BUF)? {
679 Event::Entry { item, done, .. } if item.kind == Kind::File => {
680 let left = Item {
682 size: item.size - done,
683 ..item
684 };
685 let mut data = FileData {
686 walker: &mut w,
687 ended: false,
688 };
689 sink.item(&left, &mut data)?;
690 let mut rest = [0u8; 4096];
691 while data.read(&mut rest)? > 0 {}
692 }
693 Event::Entry { item, link, .. } => {
694 sink.item(&item, &mut Cursor::new(link.unwrap_or_default()))?;
695 }
696 Event::Data(_) | Event::FileEnd | Event::Point => {}
697 Event::End => return Ok(()),
698 }
699 }
700 }
701}
702
703struct FileData<'a> {
705 walker: &'a mut Walker,
706 ended: bool,
707}
708
709impl Read for FileData<'_> {
710 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
711 while !self.ended && !buf.is_empty() {
712 match self.walker.next(buf.len()) {
713 Ok(Event::Data(d)) => {
714 buf[..d.len()].copy_from_slice(d);
715 return Ok(d.len());
716 }
717 Ok(Event::Point) => {}
718 Ok(Event::FileEnd) => self.ended = true,
719 Ok(_) => return Err(io::Error::other("the tar entry ended unexpectedly")),
720 Err(e) => return Err(io::Error::other(format!("{e:#}"))),
721 }
722 }
723 Ok(0)
724 }
725}
726
727#[cfg(test)]
728mod tests {
729 use super::*;
730 use std::io::Cursor;
731
732 fn fixture(name: &str) -> &'static [u8] {
734 match name {
735 "t1" => include_bytes!("fixtures/xz/xz-t1.xz"),
736 "multi" => include_bytes!("fixtures/xz/xz-multi.xz"),
737 "uneven" => include_bytes!("fixtures/xz/xz-uneven.xz"),
738 "crc32" => include_bytes!("fixtures/xz/xz-crc32.xz"),
739 "nocheck" => include_bytes!("fixtures/xz/xz-nocheck.xz"),
740 "sha256" => include_bytes!("fixtures/xz/xz-sha256.xz"),
741 "bcj" => include_bytes!("fixtures/xz/xz-bcj.xz"),
742 "delta" => include_bytes!("fixtures/xz/xz-delta.xz"),
743 "multistream" => include_bytes!("fixtures/xz/xz-multistream.xz"),
744 _ => unreachable!(),
745 }
746 }
747
748 fn parse(name: &str) -> Xz {
749 let bytes = fixture(name);
750 Xz::parse(&mut Cursor::new(bytes), bytes.len() as u64).unwrap()
751 }
752
753 fn decode(name: &str) -> Vec<u8> {
757 let bytes = fixture(name);
758 let xz = parse(name);
759 let stream = &xz.streams[0];
760 let mut out = Vec::new();
761 for block in &stream.blocks {
762 let from = block.data_off as usize;
763 let to = from + block.comp_len as usize;
764 let mut stage = Stage::over(Cursor::new(bytes[from..to].to_vec()), block).unwrap();
765 let mut running = Running::new(stream.check);
766 let mut left = block.uncomp_len;
767 let mut buf = vec![0u8; 64 * 1024];
768 while left > 0 {
769 let want = (left as usize).min(buf.len());
770 let n = stage.read(&mut buf[..want]).unwrap();
771 assert!(n > 0, "block ended early");
772 running.update(&buf[..n]);
773 out.extend_from_slice(&buf[..n]);
774 left -= n as u64;
775 }
776 if stream.check != Check::None {
777 let at = block.check_off as usize;
778 let stored = &bytes[at..at + stream.check.size() as usize];
779 assert_eq!(running.finish(), stored, "block check");
780 }
781 }
782 out
783 }
784
785 #[test]
786 fn crc64_matches_the_known_vector() {
787 let mut crc = Crc64::new();
788 crc.update(b"123456789");
789 assert_eq!(crc.finalize(), 0x995D_C9BB_DF19_39FA);
790 }
791
792 #[test]
793 fn one_block_passes_policy_but_still_cannot_free_anything() {
794 let xz = parse("t1");
795 assert!(xz.streams[0].blocks.len() < 2);
796 policy(&xz).unwrap();
797 }
798
799 #[test]
800 fn several_blocks_pass_policy() {
801 policy(&parse("multi")).unwrap();
802 }
803
804 #[test]
805 fn concatenated_streams_are_refused() {
806 let err = policy(&parse("multistream")).unwrap_err();
807 assert!(
808 err.to_string().contains("one after another"),
809 "got: {err:#}"
810 );
811 }
812
813 #[test]
814 fn sha256_checks_are_refused() {
815 let err = policy(&parse("sha256")).unwrap_err();
816 assert!(err.to_string().contains("SHA-256"), "got: {err:#}");
817 }
818
819 #[test]
820 fn an_unchecked_stream_passes_policy_because_it_extracts_while_kept() {
821 let xz = parse("nocheck");
822 assert_eq!(xz.streams[0].check, Check::None);
823 policy(&xz).unwrap();
824 }
825
826 #[test]
829 fn real_archives_decode_through_their_block_chains() {
830 let plain = decode("t1");
831 assert_eq!(plain.len(), 8192);
832 for name in ["multi", "crc32", "nocheck"] {
833 assert_eq!(decode(name), plain, "{name} decoded differently");
834 }
835 let filtered = decode("bcj");
838 assert_eq!(filtered.len(), 8192);
839 assert_eq!(decode("delta"), filtered, "delta decoded differently");
840 assert!(filtered.starts_with(b"MZ"));
841 }
842
843 #[test]
844 fn uneven_blocks_decode_to_the_whole_payload() {
845 let out = decode("uneven");
846 assert_eq!(out.len(), 29_491_200);
847 assert!(out.iter().enumerate().all(|(i, b)| *b == (i % 256) as u8));
848 }
849}