1use 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
36const BUF: usize = targz::BUF;
39
40const MAX_WINDOW: u64 = 1 << 30;
44
45const FRAME_MAGIC: u32 = 0xFD2F_B528;
46const SKIPPABLE_MAGIC: u32 = 0x184D_2A50;
50
51#[derive(Clone, Debug, PartialEq, Eq)]
53struct Frame {
54 start: u64,
56 end: u64,
58 checksum: bool,
61 window: u64,
63 dictionary: Option<u32>,
65}
66
67fn 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 } 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
254fn 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
280pub struct Solid {
283 storage: Arc<Storage>,
284 frames: Vec<Frame>,
285 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 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 pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
341 Walker::new(self, from)
342 }
343}
344
345pub(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
363pub 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 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 units: vec![Unit {
400 start: 0,
401 key: 0,
402 items,
403 encrypted: false,
404 }],
405 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 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
457struct 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
482fn 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
493struct ZstdFeed {
496 frames: Vec<Frame>,
497 storage: Arc<Storage>,
498 base: u64,
501 frame: usize,
503 decoder: Option<zstd::stream::read::Decoder<'static, BufReader<Bytes>>>,
504 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 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 self.finish()?;
603 if self.ended || start == buf.len() {
604 return Ok(start);
605 }
606 continue;
607 }
608 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 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 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
673pub 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
746struct 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 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
781struct 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 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 #[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 #[test]
910 fn a_window_descriptor_scales_the_mantissa_by_eighths() {
911 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 #[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}