Skip to main content

hatchzip_core/archive/
targz.rs

1//! A gzip-compressed tar is one compressed stream holding every entry, and a
2//! gzip stream can only be decoded from the front. So unlike every other
3//! format it is not split into units extracted from the end: the whole
4//! archive is one unit, extracted front to back, and the engine frees the
5//! compressed bytes behind the decoder by punching holes, at resume points
6//! (see `Run::stream_solid` in the engine).
7//!
8//! [`Walker`] decodes the stream and parses the tar inside it into events,
9//! and says where decoding can restart: at a deflate block boundary or a
10//! gzip member's start that falls where the tar parser's state is simple to
11//! write down. Opening the archive walks it once, start to end, before
12//! anything is touched: that lists the entries, checks every gzip CRC-32 and
13//! length, and measures how far the output runs ahead of the compressed
14//! bytes, which the space check needs. A resumed run walks from its resume
15//! point instead, since the bytes before it may be gone. The extraction
16//! walks the same way with the same buffer sizes, so it meets exactly the
17//! points the scan measured.
18//!
19//! The tar parser's own state machine is in [`TarStream`], driven by the
20//! decoder hooks of [`Feed`]. `tarxz` runs the same thing over xz blocks,
21//! so both compressed tars parse identically down to their events.
22
23use std::io::{self, Cursor, Read};
24use std::path::PathBuf;
25use std::sync::Arc;
26
27use anyhow::{Context, Result, anyhow, bail};
28use serde::{Deserialize, Serialize};
29
30use super::resumable::{GzPoint, Gzip};
31use super::storage::Storage;
32use super::{Format, Item, Kind, Opened, Sink, SolidStream, SolidWalker, Unit, Worker, safe_path};
33use crate::fsutil;
34use crate::journal::Resume;
35
36pub const NAME: &str = "tar.gz";
37
38/// Decoded output is handed out in pieces of at most this much.
39pub(super) const BUF: usize = 1024 * 1024;
40
41/// Long-name and pax records in front of one entry, together. GNU tar and
42/// pax write a few hundred bytes; anything this large is refused.
43pub(super) const MAX_HEADER: u64 = 1024 * 1024;
44
45/// The decoder's and the tar parser's state at a resume point, beyond the
46/// bit position and output length the journal's [`Resume`] already holds.
47#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct StreamPoint {
49    /// Which codec the point belongs to, so a journal can never be read as
50    /// the wrong compressed tar's: a `.tar.xz` point says `xz`. Older
51    /// tar.gz journals have no field and read as `gzip`, which was the only
52    /// codec then.
53    #[serde(default, skip_serializing_if = "CodecKind::is_gzip")]
54    pub kind: CodecKind,
55    /// Gzip or bzip2: the point is where a gzip member's or a bzip2
56    /// stream's header begins, not a block boundary inside one. Written even
57    /// at its default, and so are the three below: 0.1.8 reads this journal
58    /// structure and has no defaults, so a field left out makes it report
59    /// the journal as damaged. Only fields added after 0.1.8 may be omitted.
60    #[serde(default)]
61    pub member_start: bool,
62    /// Gzip: CRC-32 and length of the member's output before the point,
63    /// which its trailer is checked against.
64    #[serde(default)]
65    pub member_crc: u32,
66    #[serde(default)]
67    pub member_len: u64,
68    /// Gzip: the member's last 32 KiB of output before the point, which
69    /// deflate back-references may reach into. It is part tar headers and
70    /// part several files, so unlike a single ZIP entry's window it can't
71    /// be read back from one output file. Xz needs no window: a block
72    /// borrows nothing from before it.
73    #[serde(default, with = "hex")]
74    pub window: Vec<u8>,
75    /// Xz: which block of the stream the point is at, where its header
76    /// begins. Zstd: how many frames preceded the point, so a resumed run
77    /// still knows the stream had more than one. The pieces before it never
78    /// need decoding again.
79    #[serde(default, skip_serializing_if = "is_zero_u64")]
80    pub block: u64,
81    /// Bzip2: the stream's level digit and the combined CRC of its blocks
82    /// before the point, which the stream trailer is checked against.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub level: Option<u8>,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub combined_crc: Option<u32>,
87    /// Offset of the point in the uncompressed tar.
88    pub tar_pos: u64,
89    pub at: TarAt,
90}
91
92/// Which compressed-stream codec owns a resume point. The stream state it
93/// carries belongs to exactly one; a point read under another kind is
94/// refused, before anything is touched.
95#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
96#[serde(rename_all = "lowercase")]
97pub enum CodecKind {
98    #[default]
99    Gzip,
100    Xz,
101    Bzip2,
102    Zstd,
103}
104
105impl CodecKind {
106    pub fn is_gzip(&self) -> bool {
107        *self == Self::Gzip
108    }
109}
110
111fn is_zero_u64(v: &u64) -> bool {
112    *v == 0
113}
114
115/// Where the point falls in the tar.
116#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
117#[serde(rename_all = "snake_case")]
118pub enum TarAt {
119    /// At the start of an entry's header records.
120    Boundary,
121    /// Inside the data of a regular file, which starts at `data_start` in
122    /// the tar. How much of it is written is the resume point's `written`.
123    File {
124        path: PathBuf,
125        size: u64,
126        mode: Option<u32>,
127        /// Seconds from 1970, negative before it.
128        mtime: Option<i64>,
129        data_start: u64,
130    },
131    /// Inside bytes that extract to nothing: padding, or the data of an
132    /// entry that is not a regular file. `left` of them remain.
133    Skip { left: u64 },
134    /// Past the end-of-archive marker, where only zeros may follow.
135    End,
136}
137
138/// What a scan measured about the output, relative to where it started, in
139/// bytes on disk (each file rounded up to 4 KiB).
140#[derive(Clone, Debug, Default)]
141pub struct Profile {
142    /// Regular files, as they are written.
143    pub files: u64,
144    /// Links, made at the very end. Counted at their target's size, since
145    /// they are copied where the filesystem has no hard links.
146    pub links: u64,
147    /// The most the files written so far ever exceed the compressed bytes
148    /// consumed, at any point where decoding can restart. Negative while
149    /// the output stays below the compressed size.
150    pub lead: i128,
151    /// The most file output between two consecutive such points, or
152    /// between the start or end and the nearest one: how far the output can
153    /// run ahead before anything can be freed.
154    pub gap: u64,
155}
156
157pub struct Solid {
158    storage: Arc<Storage>,
159    /// The point the scan began at: a resumed run's, or the start.
160    from: Option<Resume>,
161    profile: Profile,
162}
163
164impl Solid {
165    /// Decodes from `from`, or from the start of the archive.
166    pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
167        Walker::new(&self.storage, from)
168    }
169}
170
171pub enum Event<'a> {
172    /// An entry begins. A regular file's data follows as `Data`, then
173    /// `FileEnd`; `done` is how much of it an earlier run already wrote. For
174    /// a symlink, `link` is its target.
175    Entry {
176        item: Item,
177        link: Option<Vec<u8>>,
178        done: u64,
179    },
180    Data(&'a [u8]),
181    FileEnd,
182    /// Decoding can restart right here; [`Walker::point`] describes how.
183    Point,
184    /// The tar ended, and so did the compressed stream, every check done.
185    End,
186}
187
188/// The parser's state between events, shared by the tar.xz walker.
189pub(super) enum State {
190    /// Collecting an entry's header records.
191    Header(Vec<u8>),
192    File {
193        item: Item,
194        data_start: u64,
195        left: u64,
196        pad: u64,
197    },
198    Skip(u64),
199    Trailer,
200}
201
202impl State {
203    /// Whether the parser's state here can be written down in a
204    /// [`StreamPoint`]. Inside an entry's header records it can't.
205    pub(super) fn at_rest(&self) -> bool {
206        match self {
207            State::Header(held) => held.is_empty(),
208            State::File { .. } | State::Skip(_) | State::Trailer => true,
209        }
210    }
211}
212
213/// The decoder hooks a [`TarStream`] needs from its compressed stream.
214pub(super) trait Feed {
215    /// Fills `buf` with more decoded bytes; 0 means the stream is over. A
216    /// call returns at most enough bytes to reach somewhere a point falls.
217    fn fill(&mut self, buf: &mut [u8]) -> Result<usize>;
218    /// Whether the bytes the last [`fill`](Self::fill) ended at make a
219    /// resume point.
220    fn restartable(&self) -> bool;
221    /// The resume point those bytes make, as the journal stores it. `at`
222    /// and `written` describe where the tar got to, which the codec stores
223    /// beside its own state.
224    fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume>;
225    /// The archive byte a resume point here would restart in. Cheap, for
226    /// the scan, which only measures.
227    fn point_byte(&self) -> Option<u64>;
228}
229
230impl Feed for Gzip {
231    fn fill(&mut self, buf: &mut [u8]) -> Result<usize> {
232        self.read(buf)
233    }
234
235    fn restartable(&self) -> bool {
236        self.restart_bit().is_some()
237    }
238
239    fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume> {
240        let point = self
241            .restart_point()?
242            .ok_or_else(|| anyhow!("the compressed stream cannot be resumed here"))?;
243        Ok(Resume {
244            unit: 0,
245            written,
246            bit: point.bit,
247            crc: 0,
248            stream: Some(Box::new(StreamPoint {
249                kind: CodecKind::Gzip,
250                member_start: point.member_start,
251                member_crc: point.crc,
252                member_len: point.len,
253                window: point.window,
254                block: 0,
255                level: None,
256                combined_crc: None,
257                tar_pos,
258                at,
259            })),
260        })
261    }
262
263    fn point_byte(&self) -> Option<u64> {
264        self.restart_bit().map(|(bit, _)| bit / 8)
265    }
266}
267
268/// The tar parser a compressed stream feeds: it hands out the archive's
269/// events and says where decoding can restart. The walk depends on nothing
270/// but the stream, so a [`TarStream`] outlives whatever handle made it.
271pub(super) struct TarStream<F: Feed> {
272    feed: F,
273    buf: Vec<u8>,
274    pos: usize,
275    len: usize,
276    /// Offset in the tar of `buf[pos]`.
277    tar_pos: u64,
278    state: State,
279    /// The decoder can restart where `buf` ends.
280    restartable: bool,
281    /// A file a resumed run continues, announced by the first event.
282    resumed: Option<(Item, u64)>,
283}
284
285impl<F: Feed> TarStream<F> {
286    /// Builds the tar side of a walk from `from`, or from the start. `from`
287    /// must belong to `feed`'s kind of stream; the caller checks that.
288    pub(super) fn new(feed: F, from: Option<&Resume>) -> Result<Self> {
289        let (tar_pos, state, resumed) = match from {
290            None => (0, State::Header(Vec::new()), None),
291            Some(r) => {
292                let s = r.stream.as_ref().ok_or_else(|| {
293                    anyhow!("the journal's resume point does not belong to a compressed tar")
294                })?;
295                let (state, resumed) = resumed_state(s, r.written)?;
296                (s.tar_pos, state, resumed)
297            }
298        };
299        Ok(Self {
300            feed,
301            buf: vec![0; BUF],
302            pos: 0,
303            len: 0,
304            tar_pos,
305            state,
306            restartable: false,
307            resumed,
308        })
309    }
310
311    /// Turns header records already held into an entry, when enough of them
312    /// arrived to tell. `None` means more bytes are needed, the bytes are a
313    /// zero block (the state moved to the trailer), or the entry extracts to
314    /// nothing (the state moved past it).
315    fn held_header(&mut self) -> Result<Option<Event<'static>>> {
316        let State::Header(held) = &self.state else {
317            return Ok(None);
318        };
319        match group(held)? {
320            Group::Need(_) => Ok(None),
321            Group::End => {
322                self.state = State::Trailer;
323                Ok(None)
324            }
325            Group::Complete => {
326                let held = match std::mem::replace(&mut self.state, State::Header(Vec::new())) {
327                    State::Header(held) => held,
328                    _ => unreachable!("held_header saw a header state"),
329                };
330                begin_entry(&mut self.tar_pos, &mut self.state, &held)
331            }
332        }
333    }
334
335    /// The next event. `Data` is at most `max` bytes.
336    pub(super) fn next(&mut self, max: usize) -> Result<Event<'_>> {
337        if let Some((item, done)) = self.resumed.take() {
338            return Ok(Event::Entry {
339                item,
340                link: None,
341                done,
342            });
343        }
344        loop {
345            match &self.state {
346                State::File { left: 0, pad, .. } => {
347                    self.state = State::Skip(*pad);
348                    return Ok(Event::FileEnd);
349                }
350                State::Skip(0) => {
351                    self.state = State::Header(Vec::new());
352                    continue;
353                }
354                _ => {}
355            }
356            if self.pos == self.len {
357                // A fill can end exactly after the last byte of a header
358                // record. The bytes are all here, so finish the entry before
359                // asking for more: otherwise a point at this offset is lost
360                // and a frame or block boundary cannot be used.
361                if let Some(event) = self.held_header()? {
362                    return Ok(event);
363                }
364                if std::mem::take(&mut self.restartable) && self.state.at_rest() {
365                    return Ok(Event::Point);
366                }
367                let n = self.feed.fill(&mut self.buf)?;
368                if n == 0 {
369                    return end_state(&self.state);
370                }
371                self.pos = 0;
372                self.len = n;
373                self.restartable = self.feed.restartable();
374            }
375            let avail = (self.len - self.pos) as u64;
376            match &mut self.state {
377                State::File { left, .. } => {
378                    let n = (*left).min(avail).min(max as u64) as usize;
379                    *left -= n as u64;
380                    self.pos += n;
381                    self.tar_pos += n as u64;
382                    return Ok(Event::Data(&self.buf[self.pos - n..self.pos]));
383                }
384                State::Skip(left) => {
385                    let n = (*left).min(avail);
386                    *left -= n;
387                    self.pos += n as usize;
388                    self.tar_pos += n;
389                }
390                State::Trailer => {
391                    if self.buf[self.pos..self.len].iter().any(|b| *b != 0) {
392                        bail!(
393                            "data follows the end of the tar archive inside the compressed \
394                             stream, at offset {}; extraction refused",
395                            self.tar_pos
396                        );
397                    }
398                    self.pos = self.len;
399                    self.tar_pos += avail;
400                }
401                State::Header(held) => match group(held)? {
402                    Group::Need(k) => {
403                        let n = (k as u64).min(avail) as usize;
404                        held.extend_from_slice(&self.buf[self.pos..self.pos + n]);
405                        self.pos += n;
406                        self.tar_pos += n as u64;
407                    }
408                    Group::End => self.state = State::Trailer,
409                    Group::Complete => {
410                        let held = std::mem::take(held);
411                        if let Some(event) = begin_entry(&mut self.tar_pos, &mut self.state, &held)?
412                        {
413                            return Ok(event);
414                        }
415                    }
416                },
417            }
418        }
419    }
420
421    /// The resume point at the `Point` event just returned. Its `unit` is
422    /// left for the engine to fill in.
423    pub(super) fn point(&self) -> Result<Resume> {
424        let (written, at) = match &self.state {
425            State::Header(_) => (0, TarAt::Boundary),
426            State::File {
427                item, data_start, ..
428            } => (
429                self.tar_pos - data_start,
430                TarAt::File {
431                    path: item.path.clone(),
432                    size: item.size,
433                    mode: item.mode,
434                    mtime: item.mtime.and_then(fsutil::epoch_secs),
435                    data_start: *data_start,
436                },
437            ),
438            State::Skip(left) => (0, TarAt::Skip { left: *left }),
439            State::Trailer => (0, TarAt::End),
440        };
441        self.feed.point(self.tar_pos, at, written)
442    }
443
444    /// The archive byte a resume point here would restart in. Cheap, for
445    /// the scan, which only measures.
446    pub(super) fn point_byte(&self) -> Option<u64> {
447        self.feed.point_byte()
448    }
449}
450
451pub(super) enum Group {
452    /// This many more bytes are needed to tell.
453    Need(usize),
454    /// The records end with an entry's own header.
455    Complete,
456    /// A zero block: the end of the archive.
457    End,
458}
459
460/// Whether `held`, the records seen since the last entry ended, is a whole
461/// entry header: any GNU long-name and long-link records and a pax record,
462/// each with its data, then the entry's own header.
463pub(super) fn group(held: &[u8]) -> Result<Group> {
464    let mut at = 0usize;
465    loop {
466        if held.len() < at + 512 {
467            return Ok(Group::Need(at + 512 - held.len()));
468        }
469        let block = &held[at..at + 512];
470        if block.iter().all(|b| *b == 0) {
471            if at == 0 {
472                return Ok(Group::End);
473            }
474            bail!("reading the tar headers: a long-name or pax record has no entry after it");
475        }
476        match block[156] {
477            b'L' | b'K' | b'x' => {
478                let size = ::tar::Header::from_byte_slice(block)
479                    .entry_size()
480                    .context("reading the tar headers")?;
481                let next = (at as u64 + 512).saturating_add(size.saturating_add(511) & !511);
482                if next > MAX_HEADER {
483                    bail!("reading the tar headers: an entry's header records exceed 1 MiB");
484                }
485                at = next as usize;
486            }
487            _ => return Ok(Group::Complete),
488        }
489    }
490}
491
492/// Turns a complete set of header records into the entry they describe,
493/// moving `state` past them and `tar_pos` to the data that follows. `None`
494/// means the records describe nothing to extract, like padding.
495pub(super) fn begin_entry(
496    tar_pos: &mut u64,
497    state: &mut State,
498    held: &[u8],
499) -> Result<Option<Event<'static>>> {
500    let last = &held[held.len() - 512..];
501    if last[156] == b'S' {
502        let name = ::tar::Header::from_byte_slice(last)
503            .path_bytes()
504            .into_owned();
505        bail!(
506            "'{}' is a sparse file, which is not supported",
507            String::from_utf8_lossy(&name)
508        );
509    }
510    let mut archive = ::tar::Archive::new(Cursor::new(held));
511    let mut entries = archive.entries().context("reading the tar headers")?;
512    let mut e = entries
513        .next()
514        .ok_or_else(|| anyhow!("reading the tar headers: an entry is incomplete"))?
515        .context("reading the tar headers")?;
516    let size = e.size();
517    let described = super::tar::describe(&mut e)?;
518    let data_start = *tar_pos;
519    let span = size
520        .checked_next_multiple_of(512)
521        .ok_or_else(|| anyhow!("reading the tar headers: an entry size is invalid"))?;
522    Ok(match described {
523        Some((item, _)) if item.kind == Kind::File => {
524            *state = State::File {
525                item: item.clone(),
526                data_start,
527                left: size,
528                pad: span - size,
529            };
530            Some(Event::Entry {
531                item,
532                link: None,
533                done: 0,
534            })
535        }
536        Some((item, link)) => {
537            *state = State::Skip(span);
538            Some(Event::Entry {
539                item,
540                link,
541                done: 0,
542            })
543        }
544        None => {
545            *state = State::Skip(span);
546            None
547        }
548    })
549}
550
551/// Whether the stream can end with the parser in `state`: it takes the
552/// end-of-archive marker, a final entry that GNU tar allows to have no
553/// marker, or the trailer after it. Anything else ends the tar early.
554pub(super) fn end_state(state: &State) -> Result<Event<'static>> {
555    match state {
556        State::Trailer => Ok(Event::End),
557        State::Header(held) if held.iter().all(|b| *b == 0) => Ok(Event::End),
558        _ => bail!("the tar archive inside the compressed stream ends early"),
559    }
560}
561
562/// The part of the tar state of a resume point that comes before the
563/// compressed data's offsets. For gzip, whether the point falls in a header
564/// or the entry data, and how much was written.
565pub(super) fn resumed_state(s: &StreamPoint, written: u64) -> Result<(State, Option<(Item, u64)>)> {
566    Ok(match &s.at {
567        TarAt::Boundary => (State::Header(Vec::new()), None),
568        TarAt::Skip { left } => (State::Skip(*left), None),
569        TarAt::End => (State::Trailer, None),
570        TarAt::File {
571            path,
572            size,
573            mode,
574            mtime,
575            data_start,
576        } => {
577            let done = s.tar_pos.checked_sub(*data_start);
578            let safe = safe_path(&path.to_string_lossy()).as_ref() == Some(path);
579            if done != Some(written) || written > *size || !safe {
580                bail!(
581                    "the journal's resume point is inconsistent; the archive will not be modified"
582                );
583            }
584            let item = Item {
585                path: path.clone(),
586                size: *size,
587                kind: Kind::File,
588                mode: *mode,
589                mtime: mtime.and_then(fsutil::from_epoch_secs),
590            };
591            let state = State::File {
592                item: item.clone(),
593                data_start: *data_start,
594                left: size - written,
595                pad: size.next_multiple_of(512) - size,
596            };
597            (state, Some((item, written)))
598        }
599    })
600}
601
602/// Walks the archive from `from`, or from its start, listing what is left
603/// and measuring it. Damage anywhere is found here, before anything is
604/// touched.
605pub struct Walker {
606    inner: TarStream<Gzip>,
607}
608
609impl Walker {
610    fn new(storage: &Storage, from: Option<&Resume>) -> Result<Self> {
611        let reader = storage.reader(None);
612        let end = storage.original_len();
613        let gz = match from {
614            None => Gzip::new(reader, end, &GzPoint::start())?,
615            Some(r) => {
616                let s = r.stream.as_ref().ok_or_else(|| {
617                    anyhow!("the journal's resume point does not belong to a compressed tar")
618                })?;
619                if s.kind != CodecKind::Gzip {
620                    bail!(
621                        "the journal's resume point belongs to {}, not this archive's \
622                         compressed stream",
623                        match s.kind {
624                            CodecKind::Gzip => "a gzip member of",
625                            CodecKind::Xz => "an xz block of",
626                            CodecKind::Bzip2 => "a bzip2 block of",
627                            CodecKind::Zstd => "a zstd frame of",
628                        }
629                    );
630                }
631                Gzip::new(
632                    reader,
633                    end,
634                    &GzPoint {
635                        bit: r.bit,
636                        member_start: s.member_start,
637                        crc: s.member_crc,
638                        len: s.member_len,
639                        window: s.window.clone(),
640                    },
641                )?
642            }
643        };
644        Ok(Self {
645            inner: TarStream::new(gz, from)?,
646        })
647    }
648
649    fn next(&mut self, max: usize) -> Result<Event<'_>> {
650        self.inner.next(max)
651    }
652
653    fn point(&self) -> Result<Resume> {
654        self.inner.point()
655    }
656
657    fn point_byte(&self) -> Option<u64> {
658        self.inner.point_byte()
659    }
660}
661
662impl SolidWalker for Walker {
663    fn next(&mut self, max: usize) -> Result<Event<'_>> {
664        self.next(max)
665    }
666
667    fn point(&self) -> Result<Resume> {
668        self.point()
669    }
670
671    fn point_byte(&self) -> Option<u64> {
672        self.point_byte()
673    }
674}
675
676/// Walks the archive from `from`, or from its start, listing what is left
677/// and measuring it. Damage anywhere is found here, before anything is
678/// touched.
679pub fn open(storage: &Arc<Storage>, from: Option<&Resume>) -> Result<Opened> {
680    let mut solid = Solid {
681        storage: storage.clone(),
682        from: from.cloned(),
683        profile: Profile::default(),
684    };
685    let name = storage
686        .primary()
687        .file_name()
688        .unwrap_or_default()
689        .to_string_lossy()
690        .into_owned();
691    storage.expect_reads(storage.original_len() - from.map_or(0, |r| r.bit / 8));
692    let (items, profile) = super::scan(&solid, from)
693        .map_err(|e| anyhow::Error::new(super::Damaged(e)))
694        .with_context(|| format!("checking {name} (nothing was changed)"))?;
695    solid.profile = profile;
696    Ok(Opened {
697        name: NAME,
698        format: Box::new(TarGz { solid }),
699        // Even with no entries left there is one unit, so that a resume point
700        // past the last entry still belongs to something.
701        units: vec![Unit {
702            start: 0,
703            key: 0,
704            items,
705            encrypted: false,
706        }],
707        // Nothing is saved: the stream is never truncated from the end.
708        tail_start: storage.original_len(),
709    })
710}
711
712struct TarGz {
713    solid: Solid,
714}
715
716impl Format for TarGz {
717    fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
718        Ok(Box::new(TarGzWorker { solid: &self.solid }))
719    }
720
721    fn solid(&self) -> Option<&dyn SolidStream> {
722        Some(&self.solid)
723    }
724}
725
726impl SolidStream for Solid {
727    fn profile(&self) -> &Profile {
728        &self.profile
729    }
730
731    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>> {
732        Ok(Box::new(self.walk(from)?))
733    }
734}
735
736/// Decodes the whole stream in one go, for `test` and `--verify-first`. The
737/// extraction itself goes through the engine's streaming path instead.
738struct TarGzWorker<'a> {
739    solid: &'a Solid,
740}
741
742impl Worker for TarGzWorker<'_> {
743    fn extract(&mut self, _unit: &Unit, sink: &mut dyn Sink) -> Result<()> {
744        let mut w = self.solid.walk(self.solid.from.as_ref())?;
745        loop {
746            match w.next(BUF)? {
747                Event::Entry { item, done, .. } if item.kind == Kind::File => {
748                    // A resumed run's open file: only its rest is here.
749                    let left = Item {
750                        size: item.size - done,
751                        ..item
752                    };
753                    let mut data = FileData {
754                        walker: &mut w,
755                        ended: false,
756                    };
757                    sink.item(&left, &mut data)?;
758                    let mut rest = [0u8; 4096];
759                    while data.read(&mut rest)? > 0 {}
760                }
761                Event::Entry { item, link, .. } => {
762                    sink.item(&item, &mut Cursor::new(link.unwrap_or_default()))?;
763                }
764                Event::Data(_) | Event::FileEnd | Event::Point => {}
765                Event::End => return Ok(()),
766            }
767        }
768    }
769}
770
771/// One file's data, read through the walker.
772struct FileData<'a> {
773    walker: &'a mut Walker,
774    ended: bool,
775}
776
777impl Read for FileData<'_> {
778    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
779        while !self.ended && !buf.is_empty() {
780            match self.walker.next(buf.len()) {
781                Ok(Event::Data(d)) => {
782                    buf[..d.len()].copy_from_slice(d);
783                    return Ok(d.len());
784                }
785                Ok(Event::Point) => {}
786                Ok(Event::FileEnd) => self.ended = true,
787                Ok(_) => return Err(io::Error::other("the tar entry ended unexpectedly")),
788                Err(e) => return Err(io::Error::other(format!("{e:#}"))),
789            }
790        }
791        Ok(0)
792    }
793}
794
795/// Bytes as a hex string, which keeps the journal readable JSON.
796mod hex {
797    use serde::{Deserialize, Deserializer, Serializer, de::Error};
798
799    pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
800        let mut out = String::with_capacity(bytes.len() * 2);
801        for b in bytes {
802            out.push_str(&format!("{b:02x}"));
803        }
804        s.serialize_str(&out)
805    }
806
807    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
808        let s = String::deserialize(d)?;
809        if !s.len().is_multiple_of(2) {
810            return Err(D::Error::custom("odd-length hex string"));
811        }
812        (0..s.len())
813            .step_by(2)
814            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(D::Error::custom))
815            .collect()
816    }
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    /// 0.1.8 reads this journal structure and has no defaults for the gzip
824    /// fields, so a point must write them even at their defaults. Only the
825    /// fields added after it may stay out.
826    #[test]
827    fn a_gzip_point_writes_every_field_older_builds_read() {
828        let point = StreamPoint {
829            kind: CodecKind::Gzip,
830            member_start: false,
831            member_crc: 0,
832            member_len: 0,
833            window: Vec::new(),
834            block: 0,
835            level: None,
836            combined_crc: None,
837            tar_pos: 0,
838            at: TarAt::Boundary,
839        };
840        let json = serde_json::to_value(&point).unwrap();
841        for field in [
842            "member_start",
843            "member_crc",
844            "member_len",
845            "window",
846            "tar_pos",
847        ] {
848            assert!(json.get(field).is_some(), "{field} missing from {json}");
849        }
850        assert!(json.get("kind").is_none(), "kind is new and stays out");
851        assert!(json.get("block").is_none(), "block is new and stays out");
852        assert!(json.get("level").is_none(), "level is new and stays out");
853        assert!(
854            json.get("combined_crc").is_none(),
855            "combined_crc is new and stays out"
856        );
857    }
858}