1use 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
38pub(super) const BUF: usize = 1024 * 1024;
40
41pub(super) const MAX_HEADER: u64 = 1024 * 1024;
44
45#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
48pub struct StreamPoint {
49 #[serde(default, skip_serializing_if = "CodecKind::is_gzip")]
54 pub kind: CodecKind,
55 #[serde(default)]
61 pub member_start: bool,
62 #[serde(default)]
65 pub member_crc: u32,
66 #[serde(default)]
67 pub member_len: u64,
68 #[serde(default, with = "hex")]
74 pub window: Vec<u8>,
75 #[serde(default, skip_serializing_if = "is_zero_u64")]
78 pub block: u64,
79 pub tar_pos: u64,
81 pub at: TarAt,
82}
83
84#[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#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
107#[serde(rename_all = "snake_case")]
108pub enum TarAt {
109 Boundary,
111 File {
114 path: PathBuf,
115 size: u64,
116 mode: Option<u32>,
117 mtime: Option<i64>,
119 data_start: u64,
120 },
121 Skip { left: u64 },
124 End,
126}
127
128#[derive(Clone, Debug, Default)]
131pub struct Profile {
132 pub files: u64,
134 pub links: u64,
137 pub lead: i128,
141 pub gap: u64,
145}
146
147pub struct Solid {
148 storage: Arc<Storage>,
149 from: Option<Resume>,
151 profile: Profile,
152}
153
154impl Solid {
155 pub fn walk(&self, from: Option<&Resume>) -> Result<Walker> {
157 Walker::new(&self.storage, from)
158 }
159}
160
161pub enum Event<'a> {
162 Entry {
166 item: Item,
167 link: Option<Vec<u8>>,
168 done: u64,
169 },
170 Data(&'a [u8]),
171 FileEnd,
172 Point,
174 End,
176}
177
178pub(super) enum State {
180 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 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
203pub(super) trait Feed {
205 fn fill(&mut self, buf: &mut [u8]) -> Result<usize>;
208 fn restartable(&self) -> bool;
211 fn point(&self, tar_pos: u64, at: TarAt, written: u64) -> Result<Resume>;
215 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
256pub(super) struct TarStream<F: Feed> {
260 feed: F,
261 buf: Vec<u8>,
262 pos: usize,
263 len: usize,
264 tar_pos: u64,
266 state: State,
267 restartable: bool,
269 resumed: Option<(Item, u64)>,
271}
272
273impl<F: Feed> TarStream<F> {
274 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 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 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 pub(super) fn point_byte(&self) -> Option<u64> {
404 self.feed.point_byte()
405 }
406}
407
408pub(super) enum Group {
409 Need(usize),
411 Complete,
413 End,
415}
416
417pub(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
449pub(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
508pub(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
519pub(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
559pub 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
631pub 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 units: vec![Unit {
657 start: 0,
658 key: 0,
659 items,
660 encrypted: false,
661 }],
662 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
691struct 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 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
726struct 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
750mod 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 #[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}