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