ziperu 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1454 @@
1
+ //! `Ziperu::Native::TarReader`: reads a tar archive in one pass, header
2
+ //! by header, from a file or any Ruby IO with `read` (a pipe, a socket).
3
+ //!
4
+ //! The archive may be plain or compressed with gzip, zstd, xz or bzip2;
5
+ //! which is told from its first bytes, never from a name. The codecs are
6
+ //! the ones the zip crate already links.
7
+ //!
8
+ //! The headers are parsed here rather than by a crate, so that what is
9
+ //! taken for an entry, and what is refused, is decided in one place:
10
+ //!
11
+ //! - v7, ustar (with its name prefix) and GNU headers; GNU long names and
12
+ //! long link names (`L`, `K`); PAX extended headers (`x`), of which
13
+ //! `path`, `linkpath`, `size`, `mtime`, `uid`, `gid`, `uname` and `gname`
14
+ //! are applied. PAX global headers (`g`) are read and ignored.
15
+ //! - Only a regular file has data. The size field of a link, a directory
16
+ //! or a device is ignored, as GNU tar, libarchive and Python do.
17
+ //! - Sparse files and multi-volume archives are refused, not guessed at.
18
+ //! - An extended header or long name over `META_MAX` is refused: it would
19
+ //! be held in memory whole.
20
+ //! - The archive ends at the first all-zero block, or at the end of the
21
+ //! input on a block boundary. Input that ends anywhere else is a
22
+ //! truncated archive. An archive with no entries is two zero blocks,
23
+ //! as `tar` writes one; a single zero block is not an archive.
24
+ //! - A compressed archive is then read to the end of its stream, which
25
+ //! is where gzip, xz and bzip2 keep the checksum of what they hold:
26
+ //! tar has none for an entry's data, so that is the only check on it.
27
+ //! Zeros after a gzip or bzip2 stream are padding, as `gzip` has it;
28
+ //! anything else there is refused.
29
+ //!
30
+ //! `extract_begin`, `extract_entry` and `extract_finish` put entries on
31
+ //! disk through `placer.rs`, under the rules a zip's entries go by. Ruby
32
+ //! drives them one entry at a time, since it is Ruby that knows what is
33
+ //! excluded, renamed or a link.
34
+ //!
35
+ //! Two limits are enforced here because a single call can run long
36
+ //! (skipping a large entry): the ratio of tar bytes out to compressed
37
+ //! bytes in, and the number of bytes read from the input.
38
+
39
+ use std::cell::{Cell, RefCell, RefMut};
40
+ use std::fs;
41
+ use std::io::{self, BufRead, BufReader, Cursor, Read, Write};
42
+ use std::sync::atomic::{AtomicU64, Ordering};
43
+ use std::sync::Arc;
44
+
45
+ use magnus::{
46
+ gc::Marker, prelude::*, typed_data::DataTypeFunctions, value::Opaque, Error, IntoValue, RArray,
47
+ RHash, RString, Ruby, Symbol, TypedData, Value,
48
+ };
49
+
50
+ use crate::errors::{busy_error, io_error, IntoRuby, ERROR, LIMIT_ERROR};
51
+ use crate::extract::{raise as extract_raise, system_time};
52
+ use crate::gvl::{maybe_without_gvl, Cancellable};
53
+ use crate::placer::{Failure, Notice, OnExists, Placer, Spec};
54
+ use crate::source::RubyError;
55
+ use crate::stream::RubyRead;
56
+
57
+ const BLOCK: usize = 512;
58
+ const CHUNK: usize = 64 * 1024;
59
+ /// The most a long name or an extended header may hold.
60
+ const META_MAX: u64 = 1 << 20;
61
+ /// The ratio limit is not applied to the first bytes out: a small archive
62
+ /// is mostly zero padding, and compresses a hundredfold honestly.
63
+ const RATIO_FLOOR: u64 = 1 << 20;
64
+ /// What an xz block's decoder may allocate, in KiB. `xz -9` needs 65 MiB;
65
+ /// a header can ask for 4 GiB.
66
+ const XZ_MEM_LIMIT_KB: u32 = 256 * 1024;
67
+ /// How much `read` takes on at a time: its buffer grows as the data
68
+ /// arrives, never to the size a header merely claims.
69
+ const READ_STEP: usize = 1 << 20;
70
+
71
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
72
+ enum Compression {
73
+ None,
74
+ Gzip,
75
+ Zstd,
76
+ Xz,
77
+ Bzip2,
78
+ }
79
+
80
+ impl Compression {
81
+ /// What the first bytes of the input say it is. A tar header starts
82
+ /// with a file name, so each magic has to be one no name begins with:
83
+ /// for bzip2 that takes the block magic after "BZh" and the level.
84
+ fn detect(magic: &[u8]) -> Self {
85
+ const BZ_BLOCK: &[u8] = &[0x31, 0x41, 0x59, 0x26, 0x53, 0x59];
86
+ const BZ_END: &[u8] = &[0x17, 0x72, 0x45, 0x38, 0x50, 0x90];
87
+ if magic.starts_with(&[0x1f, 0x8b]) {
88
+ Compression::Gzip
89
+ } else if magic.starts_with(&[0x28, 0xb5, 0x2f, 0xfd]) {
90
+ Compression::Zstd
91
+ } else if magic.starts_with(&[0xfd, b'7', b'z', b'X', b'Z', 0]) {
92
+ Compression::Xz
93
+ } else if magic.len() >= 10
94
+ && magic.starts_with(b"BZh")
95
+ && (b'1'..=b'9').contains(&magic[3])
96
+ && (&magic[4..10] == BZ_BLOCK || &magic[4..10] == BZ_END)
97
+ {
98
+ Compression::Bzip2
99
+ } else {
100
+ Compression::None
101
+ }
102
+ }
103
+
104
+ fn name(self) -> &'static str {
105
+ match self {
106
+ Compression::None => "none",
107
+ Compression::Gzip => "gzip",
108
+ Compression::Zstd => "zstd",
109
+ Compression::Xz => "xz",
110
+ Compression::Bzip2 => "bzip2",
111
+ }
112
+ }
113
+ }
114
+
115
+ /// Counts what is read from the input itself, before any decoding.
116
+ struct Counted<R> {
117
+ inner: R,
118
+ count: Arc<AtomicU64>,
119
+ }
120
+
121
+ impl<R: Read> Read for Counted<R> {
122
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
123
+ let n = self.inner.read(buf)?;
124
+ self.count.fetch_add(n as u64, Ordering::Relaxed);
125
+ Ok(n)
126
+ }
127
+ }
128
+
129
+ /// Compressed streams end to end, read as one, as the command-line tools
130
+ /// have it; zero bytes after the last are padding (a tape's, a block
131
+ /// device's) and anything else there is an error of the decoder's.
132
+ struct Members<R, D> {
133
+ current: Option<D>,
134
+ start: fn(R) -> D,
135
+ stop: fn(D) -> R,
136
+ }
137
+
138
+ impl<R: BufRead, D: Read> Members<R, D> {
139
+ fn new(input: R, start: fn(R) -> D, stop: fn(D) -> R) -> Self {
140
+ Self {
141
+ current: Some(start(input)),
142
+ start,
143
+ stop,
144
+ }
145
+ }
146
+ }
147
+
148
+ impl<R: BufRead, D: Read> Read for Members<R, D> {
149
+ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
150
+ loop {
151
+ let Some(decoder) = self.current.as_mut() else {
152
+ return Ok(0);
153
+ };
154
+ let n = decoder.read(buf)?;
155
+ if n > 0 || buf.is_empty() {
156
+ return Ok(n);
157
+ }
158
+ // This member is over: what comes after it?
159
+ let Some(decoder) = self.current.take() else {
160
+ return Ok(0);
161
+ };
162
+ let mut input = (self.stop)(decoder);
163
+ loop {
164
+ let chunk = input.fill_buf()?;
165
+ if chunk.is_empty() {
166
+ return Ok(0);
167
+ }
168
+ let (len, zeros) = (chunk.len(), chunk.iter().take_while(|&&b| b == 0).count());
169
+ input.consume(zeros);
170
+ if zeros < len {
171
+ break;
172
+ }
173
+ }
174
+ self.current = Some((self.start)(input));
175
+ }
176
+ }
177
+ }
178
+
179
+ /// The tar stream: `raw` with its compression, if any, taken off.
180
+ fn open_input(
181
+ raw: impl Read + Send + 'static,
182
+ count: Arc<AtomicU64>,
183
+ ) -> io::Result<(Compression, Box<dyn Read + Send>)> {
184
+ let mut raw = BufReader::with_capacity(
185
+ CHUNK,
186
+ Counted {
187
+ inner: Cancellable(raw),
188
+ count,
189
+ },
190
+ );
191
+ let mut magic = [0u8; 10];
192
+ let mut have = 0;
193
+ while have < magic.len() {
194
+ let n = raw.read(&mut magic[have..])?;
195
+ if n == 0 {
196
+ break;
197
+ }
198
+ have += n;
199
+ }
200
+ let compression = Compression::detect(&magic[..have]);
201
+ let head = Cursor::new(magic[..have].to_vec()).chain(raw);
202
+ let input: Box<dyn Read + Send> = match compression {
203
+ Compression::None => Box::new(head),
204
+ // Several members or frames end to end are one stream, as the
205
+ // command-line tools have it.
206
+ Compression::Gzip => Box::new(Members::new(
207
+ head,
208
+ flate2::bufread::GzDecoder::new,
209
+ flate2::bufread::GzDecoder::into_inner,
210
+ )),
211
+ Compression::Zstd => Box::new(zstd::stream::read::Decoder::new(head)?),
212
+ Compression::Xz => Box::new(lzma_rust2::XzReader::new_mem_limit(
213
+ head,
214
+ true,
215
+ XZ_MEM_LIMIT_KB,
216
+ )),
217
+ Compression::Bzip2 => Box::new(Members::new(
218
+ head,
219
+ bzip2::bufread::BzDecoder::new,
220
+ bzip2::bufread::BzDecoder::into_inner,
221
+ )),
222
+ };
223
+ Ok((compression, input))
224
+ }
225
+
226
+ /// Why reading stopped.
227
+ #[derive(Debug)]
228
+ enum Fail {
229
+ Io(io::Error),
230
+ /// The bytes are not a tar archive, or not a whole one.
231
+ Invalid(String),
232
+ /// A tar archive, of a kind not read here.
233
+ Unsupported(String),
234
+ /// More came out, for what went in, than the limit allows.
235
+ Ratio(f64, f64),
236
+ /// More was read from the input than the limit allows.
237
+ Input(u64, u64),
238
+ }
239
+
240
+ impl From<io::Error> for Fail {
241
+ fn from(e: io::Error) -> Self {
242
+ Fail::Io(e)
243
+ }
244
+ }
245
+
246
+ /// What an entry is, from its type flag.
247
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
248
+ enum Kind {
249
+ File,
250
+ Directory,
251
+ Symlink,
252
+ Hardlink,
253
+ CharacterDevice,
254
+ BlockDevice,
255
+ Fifo,
256
+ /// A type flag not known here; it has data, as a file does.
257
+ Other,
258
+ }
259
+
260
+ impl Kind {
261
+ fn name(self) -> &'static str {
262
+ match self {
263
+ Kind::File => "file",
264
+ Kind::Directory => "directory",
265
+ Kind::Symlink => "symlink",
266
+ Kind::Hardlink => "hardlink",
267
+ Kind::CharacterDevice => "character_device",
268
+ Kind::BlockDevice => "block_device",
269
+ Kind::Fifo => "fifo",
270
+ Kind::Other => "other",
271
+ }
272
+ }
273
+
274
+ fn has_data(self) -> bool {
275
+ matches!(self, Kind::File | Kind::Other)
276
+ }
277
+ }
278
+
279
+ /// One entry, with long names and extended headers applied.
280
+ #[derive(Debug)]
281
+ struct Meta {
282
+ name: Vec<u8>,
283
+ link: Vec<u8>,
284
+ kind: Kind,
285
+ /// The bytes of data that follow; zero for what has none.
286
+ size: u64,
287
+ mtime_sec: i64,
288
+ mtime_nsec: u32,
289
+ mode: u32,
290
+ uid: i64,
291
+ gid: i64,
292
+ uname: Vec<u8>,
293
+ gname: Vec<u8>,
294
+ }
295
+
296
+ /// A header block's fields, as they stand in it.
297
+ struct Raw {
298
+ meta: Meta,
299
+ /// The type flag itself.
300
+ flag: u8,
301
+ /// The size field, whatever the type.
302
+ size: u64,
303
+ }
304
+
305
+ /// A numeric field: octal digits, ended by a NUL or spaces; or, with the
306
+ /// first byte 0x80 or 0xff, a big-endian binary number (GNU's way of
307
+ /// holding what octal cannot, negative for 0xff).
308
+ fn number(field: &[u8]) -> Option<i64> {
309
+ let first = *field.first()?;
310
+ if first == 0x80 || first == 0xff {
311
+ let mut n: i128 = 0;
312
+ for &b in &field[1..] {
313
+ n = (n << 8) | i128::from(b);
314
+ }
315
+ if first == 0xff {
316
+ n -= 1i128 << (8 * (field.len() - 1));
317
+ }
318
+ return i64::try_from(n).ok();
319
+ }
320
+ let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
321
+ let digits = field[..end].trim_ascii();
322
+ let mut n: u64 = 0;
323
+ for &b in digits {
324
+ if !(b'0'..=b'7').contains(&b) {
325
+ return None;
326
+ }
327
+ n = n.checked_mul(8)?.checked_add(u64::from(b - b'0'))?;
328
+ }
329
+ i64::try_from(n).ok()
330
+ }
331
+
332
+ /// A text field: up to its first NUL.
333
+ fn text(field: &[u8]) -> &[u8] {
334
+ let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
335
+ &field[..end]
336
+ }
337
+
338
+ /// Whether the block's checksum field holds the sum of its bytes, taken
339
+ /// with that field as spaces. Old writers summed the bytes as signed.
340
+ fn checksum_ok(block: &[u8; BLOCK]) -> bool {
341
+ let Some(stored) = number(&block[148..156]) else {
342
+ return false;
343
+ };
344
+ let (mut unsigned, mut signed) = (0i64, 0i64);
345
+ for (i, &b) in block.iter().enumerate() {
346
+ let b = if (148..156).contains(&i) { b' ' } else { b };
347
+ unsigned += i64::from(b);
348
+ signed += i64::from(b as i8);
349
+ }
350
+ stored == unsigned || stored == signed
351
+ }
352
+
353
+ fn parse_header(block: &[u8; BLOCK]) -> Result<Raw, &'static str> {
354
+ if !checksum_ok(block) {
355
+ return Err("a header's checksum does not match");
356
+ }
357
+ let posix = &block[257..263] == b"ustar\0";
358
+ let mut name = text(&block[0..100]).to_vec();
359
+ let flag = block[156];
360
+ if posix {
361
+ let prefix = text(&block[345..500]);
362
+ if !prefix.is_empty() {
363
+ let mut joined = prefix.to_vec();
364
+ joined.push(b'/');
365
+ joined.extend_from_slice(&name);
366
+ name = joined;
367
+ }
368
+ }
369
+ let size = number(&block[124..136])
370
+ .and_then(|n| u64::try_from(n).ok())
371
+ .ok_or("a header's size is not a number")?;
372
+ let mode = number(&block[100..108])
373
+ .and_then(|n| u32::try_from(n & 0o7777).ok())
374
+ .ok_or("a header's mode is not a number")?;
375
+ let uid = number(&block[108..116]).ok_or("a header's uid is not a number")?;
376
+ let gid = number(&block[116..124]).ok_or("a header's gid is not a number")?;
377
+ let mtime = number(&block[136..148]).ok_or("a header's time is not a number")?;
378
+ let kind = match flag {
379
+ 0 | b'0' | b'7' => Kind::File,
380
+ b'1' => Kind::Hardlink,
381
+ b'2' => Kind::Symlink,
382
+ b'3' => Kind::CharacterDevice,
383
+ b'4' => Kind::BlockDevice,
384
+ b'5' => Kind::Directory,
385
+ b'6' => Kind::Fifo,
386
+ _ => Kind::Other,
387
+ };
388
+ Ok(Raw {
389
+ meta: Meta {
390
+ name,
391
+ link: text(&block[157..257]).to_vec(),
392
+ kind,
393
+ size: if kind.has_data() { size } else { 0 },
394
+ mtime_sec: mtime,
395
+ mtime_nsec: 0,
396
+ mode,
397
+ uid,
398
+ gid,
399
+ uname: text(&block[265..297]).to_vec(),
400
+ gname: text(&block[297..329]).to_vec(),
401
+ },
402
+ flag,
403
+ size,
404
+ })
405
+ }
406
+
407
+ /// A key and its value.
408
+ type PaxRecord<'a> = (&'a [u8], &'a [u8]);
409
+
410
+ /// The records of a PAX extended header: `<length> <key>=<value>\n`, the
411
+ /// length in decimal and counting the whole record.
412
+ fn parse_pax(data: &[u8]) -> Result<Vec<PaxRecord<'_>>, &'static str> {
413
+ const BAD: &str = "an extended header is malformed";
414
+ let mut rest = data;
415
+ let mut records = Vec::new();
416
+ // Some writers pad the last record's block with NULs.
417
+ while !rest.is_empty() && rest[0] != 0 {
418
+ let space = rest.iter().take(20).position(|&b| b == b' ').ok_or(BAD)?;
419
+ let length: usize = std::str::from_utf8(&rest[..space])
420
+ .ok()
421
+ .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
422
+ .and_then(|s| s.parse().ok())
423
+ .ok_or(BAD)?;
424
+ if length < space + 3 || length > rest.len() || rest[length - 1] != b'\n' {
425
+ return Err(BAD);
426
+ }
427
+ let record = &rest[space + 1..length - 1];
428
+ let equals = record.iter().position(|&b| b == b'=').ok_or(BAD)?;
429
+ records.push((&record[..equals], &record[equals + 1..]));
430
+ rest = &rest[length..];
431
+ }
432
+ Ok(records)
433
+ }
434
+
435
+ fn pax_number(value: &[u8]) -> Option<i64> {
436
+ std::str::from_utf8(value).ok()?.parse().ok()
437
+ }
438
+
439
+ /// A PAX time: seconds, with an optional decimal fraction. Returns whole
440
+ /// seconds and the nanoseconds past them.
441
+ fn pax_time(value: &[u8]) -> Option<(i64, u32)> {
442
+ let s = std::str::from_utf8(value).ok()?;
443
+ let (whole, fraction) = s.split_once('.').unwrap_or((s, ""));
444
+ let sec: i64 = whole.parse().ok()?;
445
+ if !fraction.bytes().all(|b| b.is_ascii_digit()) {
446
+ return None;
447
+ }
448
+ let mut nsec = 0u32;
449
+ for i in 0..9 {
450
+ let digit = fraction.as_bytes().get(i).map_or(0, |b| b - b'0');
451
+ nsec = nsec * 10 + u32::from(digit);
452
+ }
453
+ if whole.starts_with('-') && nsec > 0 {
454
+ // -1.25 is three quarters of a second past -2.
455
+ Some((sec.checked_sub(1)?, 1_000_000_000 - nsec))
456
+ } else {
457
+ Some((sec, nsec))
458
+ }
459
+ }
460
+
461
+ /// Applies an extended header's records to the entry that follows it.
462
+ fn apply_pax(meta: &mut Meta, data: &[u8]) -> Result<(), Fail> {
463
+ let invalid = |what: &str| Fail::Invalid(format!("an extended header's {what} is not valid"));
464
+ for (key, value) in parse_pax(data).map_err(|e| Fail::Invalid(e.to_string()))? {
465
+ match key {
466
+ // A header's own name fields end at a NUL, so only here can a
467
+ // name hold one; no file system takes it.
468
+ b"path" | b"linkpath" if value.contains(&0) => return Err(invalid("name")),
469
+ b"path" => meta.name = value.to_vec(),
470
+ b"linkpath" => meta.link = value.to_vec(),
471
+ b"uname" => meta.uname = value.to_vec(),
472
+ b"gname" => meta.gname = value.to_vec(),
473
+ b"size" => {
474
+ let size = pax_number(value)
475
+ .and_then(|n| u64::try_from(n).ok())
476
+ .ok_or_else(|| invalid("size"))?;
477
+ if meta.kind.has_data() {
478
+ meta.size = size;
479
+ }
480
+ }
481
+ b"uid" => meta.uid = pax_number(value).ok_or_else(|| invalid("uid"))?,
482
+ b"gid" => meta.gid = pax_number(value).ok_or_else(|| invalid("gid"))?,
483
+ b"mtime" => {
484
+ (meta.mtime_sec, meta.mtime_nsec) =
485
+ pax_time(value).ok_or_else(|| invalid("mtime"))?;
486
+ }
487
+ _ if key.starts_with(b"GNU.sparse.") => {
488
+ return Err(Fail::Unsupported(
489
+ "sparse files in a tar archive are not supported".to_string(),
490
+ ));
491
+ }
492
+ _ => {}
493
+ }
494
+ }
495
+ Ok(())
496
+ }
497
+
498
+ struct State {
499
+ input: Box<dyn Read + Send>,
500
+ compression: Compression,
501
+ /// Bytes read from the input, before decoding.
502
+ raw_in: Arc<AtomicU64>,
503
+ /// Bytes of the tar stream taken so far.
504
+ out: u64,
505
+ /// Data left in the current entry, and the padding after it.
506
+ remaining: u64,
507
+ padding: u64,
508
+ done: bool,
509
+ max_ratio: Option<f64>,
510
+ max_input: Option<u64>,
511
+ }
512
+
513
+ impl State {
514
+ /// One read of the tar stream, counted and checked against the limits.
515
+ fn take(&mut self, buf: &mut [u8]) -> Result<usize, Fail> {
516
+ let n = self.input.read(buf)?;
517
+ self.out += n as u64;
518
+ let read = self.raw_in.load(Ordering::Relaxed);
519
+ if let Some(limit) = self.max_input {
520
+ if read > limit {
521
+ return Err(Fail::Input(read, limit));
522
+ }
523
+ }
524
+ if let Some(limit) = self.max_ratio {
525
+ if self.compression != Compression::None && self.out > RATIO_FLOOR {
526
+ let ratio = self.out as f64 / read.max(1) as f64;
527
+ if ratio > limit {
528
+ return Err(Fail::Ratio(ratio, limit));
529
+ }
530
+ }
531
+ }
532
+ Ok(n)
533
+ }
534
+
535
+ /// Fills `buf`; how much of it was filled before the input ended.
536
+ fn take_all(&mut self, buf: &mut [u8]) -> Result<usize, Fail> {
537
+ let mut have = 0;
538
+ while have < buf.len() {
539
+ let n = self.take(&mut buf[have..])?;
540
+ if n == 0 {
541
+ break;
542
+ }
543
+ have += n;
544
+ }
545
+ Ok(have)
546
+ }
547
+
548
+ fn truncated() -> Fail {
549
+ Fail::Invalid("the archive is cut short".to_string())
550
+ }
551
+
552
+ fn take_exact(&mut self, buf: &mut [u8]) -> Result<(), Fail> {
553
+ if self.take_all(buf)? < buf.len() {
554
+ return Err(Self::truncated());
555
+ }
556
+ Ok(())
557
+ }
558
+
559
+ fn skip(&mut self, mut count: u64) -> Result<(), Fail> {
560
+ let mut scratch = vec![0u8; (count.min(CHUNK as u64)) as usize];
561
+ while count > 0 {
562
+ let step = count.min(scratch.len() as u64) as usize;
563
+ self.take_exact(&mut scratch[..step])?;
564
+ count -= step as u64;
565
+ }
566
+ Ok(())
567
+ }
568
+
569
+ /// Reads a compressed stream to its end, so that the codec checks
570
+ /// what it has decoded. What follows the end of the archive is not
571
+ /// looked at, only passed over, under the same limits as the rest.
572
+ fn drain(&mut self) -> Result<(), Fail> {
573
+ if self.compression == Compression::None {
574
+ return Ok(());
575
+ }
576
+ let mut scratch = vec![0u8; CHUNK];
577
+ while self.take(&mut scratch)? > 0 {}
578
+ Ok(())
579
+ }
580
+
581
+ /// The data of a long name or an extended header, and past its padding.
582
+ fn metadata(&mut self, size: u64) -> Result<Vec<u8>, Fail> {
583
+ if size > META_MAX {
584
+ return Err(Fail::Invalid(format!(
585
+ "a long name or extended header of {size} bytes is over the {META_MAX} allowed"
586
+ )));
587
+ }
588
+ let mut data = vec![0u8; size as usize];
589
+ self.take_exact(&mut data)?;
590
+ self.skip(padding_after(size))?;
591
+ Ok(data)
592
+ }
593
+
594
+ /// Skips what is left of the current entry and reads up to the next
595
+ /// one; `None` at the end of the archive.
596
+ fn next(&mut self) -> Result<Option<Meta>, Fail> {
597
+ if self.done {
598
+ return Ok(None);
599
+ }
600
+ let rest = self.remaining + self.padding;
601
+ (self.remaining, self.padding) = (0, 0);
602
+ self.skip(rest)?;
603
+
604
+ let mut long_name: Option<Vec<u8>> = None;
605
+ let mut long_link: Option<Vec<u8>> = None;
606
+ let mut extended: Option<Vec<u8>> = None;
607
+ loop {
608
+ let offset = self.out;
609
+ let mut block = [0u8; BLOCK];
610
+ let have = self.take_all(&mut block)?;
611
+ let pending = long_name.is_some() || long_link.is_some() || extended.is_some();
612
+ if have == 0 && offset > 0 && !pending {
613
+ // No end marker: the input ends where an entry could start.
614
+ self.done = true;
615
+ return Ok(None);
616
+ }
617
+ if have < BLOCK {
618
+ return Err(if offset == 0 {
619
+ Fail::Invalid("not a tar archive".to_string())
620
+ } else {
621
+ Self::truncated()
622
+ });
623
+ }
624
+ if block.iter().all(|&b| b == 0) {
625
+ if offset == 0 {
626
+ // An archive of nothing is its end marker alone: two
627
+ // zero blocks. Fewer, or zeros that give way to
628
+ // something else, are not an archive.
629
+ let mut second = [1u8; BLOCK];
630
+ let have = self.take_all(&mut second)?;
631
+ if have < BLOCK || second.iter().any(|&b| b != 0) {
632
+ return Err(Fail::Invalid("not a tar archive".to_string()));
633
+ }
634
+ }
635
+ if pending {
636
+ return Err(Self::truncated());
637
+ }
638
+ self.done = true;
639
+ self.drain()?;
640
+ return Ok(None);
641
+ }
642
+ let Raw {
643
+ mut meta,
644
+ flag,
645
+ size,
646
+ } = parse_header(&block).map_err(|why| {
647
+ Fail::Invalid(if offset == 0 {
648
+ "not a tar archive".to_string()
649
+ } else {
650
+ format!("{why} (at offset {offset})")
651
+ })
652
+ })?;
653
+ match flag {
654
+ b'L' => {
655
+ long_name = Some(text(&self.metadata(size)?).to_vec());
656
+ continue;
657
+ }
658
+ b'K' => {
659
+ long_link = Some(text(&self.metadata(size)?).to_vec());
660
+ continue;
661
+ }
662
+ // 'X' is how Solaris marks the same thing.
663
+ b'x' | b'X' => {
664
+ extended = Some(self.metadata(size)?);
665
+ continue;
666
+ }
667
+ // Global settings, a comment: read past.
668
+ b'g' => {
669
+ self.metadata(size)?;
670
+ continue;
671
+ }
672
+ // A volume label has no data and names no file.
673
+ b'V' => continue,
674
+ b'S' => {
675
+ return Err(Fail::Unsupported(
676
+ "sparse files in a tar archive are not supported".to_string(),
677
+ ))
678
+ }
679
+ b'M' => {
680
+ return Err(Fail::Unsupported(
681
+ "multi-volume tar archives are not supported".to_string(),
682
+ ))
683
+ }
684
+ _ => {}
685
+ }
686
+ if let Some(name) = long_name.take() {
687
+ meta.name = name;
688
+ }
689
+ if let Some(link) = long_link.take() {
690
+ meta.link = link;
691
+ }
692
+ if let Some(data) = extended.take() {
693
+ apply_pax(&mut meta, &data)?;
694
+ }
695
+ // An old-style directory: no type for it, a name that ends in
696
+ // a slash. The whole name, that is: of a long one the header
697
+ // holds the first hundred bytes, which can end in a slash
698
+ // when the name does not.
699
+ if matches!(flag, 0 | b'0') && meta.name.ends_with(b"/") {
700
+ meta.kind = Kind::Directory;
701
+ meta.size = 0;
702
+ }
703
+ self.remaining = meta.size;
704
+ self.padding = padding_after(meta.size);
705
+ return Ok(Some(meta));
706
+ }
707
+ }
708
+
709
+ /// Fills `buf` with the current entry's data; the caller asks for no
710
+ /// more than is left of it.
711
+ fn read_data(&mut self, buf: &mut [u8]) -> Result<(), Fail> {
712
+ debug_assert!(buf.len() as u64 <= self.remaining);
713
+ self.take_exact(buf)?;
714
+ self.remaining -= buf.len() as u64;
715
+ Ok(())
716
+ }
717
+ }
718
+
719
+ /// The zero bytes that bring `size` bytes of data up to a whole block.
720
+ fn padding_after(size: u64) -> u64 {
721
+ (BLOCK as u64 - size % BLOCK as u64) % BLOCK as u64
722
+ }
723
+
724
+ #[derive(TypedData)]
725
+ #[magnus(class = "Ziperu::Native::TarReader", free_immediately, mark)]
726
+ pub struct TarReader {
727
+ inner: RefCell<Option<State>>,
728
+ /// The Ruby IO read from, if that is what the input is.
729
+ io: Option<Opaque<Value>>,
730
+ compression: Compression,
731
+ raw_in: Arc<AtomicU64>,
732
+ /// A read failed part-way: where the stream stands is not known, so
733
+ /// nothing more is read from it.
734
+ failed: Cell<bool>,
735
+ /// Where entries are put, once `extract_begin` has said.
736
+ placer: RefCell<Option<Placer>>,
737
+ }
738
+
739
+ impl DataTypeFunctions for TarReader {
740
+ fn mark(&self, marker: &Marker) {
741
+ if let Some(io) = self.io {
742
+ marker.mark(io);
743
+ }
744
+ }
745
+ }
746
+
747
+ impl TarReader {
748
+ /// `max_ratio` and `max_input` are the limits described at the top of
749
+ /// this file, nil for none.
750
+ pub fn open_path(
751
+ ruby: &Ruby,
752
+ path: String,
753
+ max_ratio: Option<f64>,
754
+ max_input: Option<u64>,
755
+ ) -> Result<Self, Error> {
756
+ let file = fs::File::open(&path).rb(ruby)?;
757
+ Self::start(ruby, file, None, max_ratio, max_input)
758
+ }
759
+
760
+ /// Any Ruby object with `read(n)`; it is read forward only.
761
+ pub fn open_io(
762
+ ruby: &Ruby,
763
+ io: Value,
764
+ max_ratio: Option<f64>,
765
+ max_input: Option<u64>,
766
+ ) -> Result<Self, Error> {
767
+ let opaque = Opaque::from(io);
768
+ Self::start(
769
+ ruby,
770
+ RubyRead::new(opaque),
771
+ Some(opaque),
772
+ max_ratio,
773
+ max_input,
774
+ )
775
+ }
776
+
777
+ fn start(
778
+ ruby: &Ruby,
779
+ raw: impl Read + Send + 'static,
780
+ io: Option<Opaque<Value>>,
781
+ max_ratio: Option<f64>,
782
+ max_input: Option<u64>,
783
+ ) -> Result<Self, Error> {
784
+ let raw_in = Arc::new(AtomicU64::new(0));
785
+ let (compression, input) = open_input(raw, Arc::clone(&raw_in))
786
+ .map_err(|e| raise(ruby, Compression::None, Fail::Io(e)))?;
787
+ Ok(Self {
788
+ inner: RefCell::new(Some(State {
789
+ input,
790
+ compression,
791
+ raw_in: Arc::clone(&raw_in),
792
+ out: 0,
793
+ remaining: 0,
794
+ padding: 0,
795
+ done: false,
796
+ max_ratio,
797
+ max_input,
798
+ })),
799
+ io,
800
+ compression,
801
+ raw_in,
802
+ failed: Cell::new(false),
803
+ placer: RefCell::new(None),
804
+ })
805
+ }
806
+
807
+ fn state(&self, ruby: &Ruby) -> Result<RefMut<'_, State>, Error> {
808
+ if self.failed.get() {
809
+ return Err(Error::new(
810
+ ruby.exception_io_error(),
811
+ "the tar reader failed earlier and cannot go on",
812
+ ));
813
+ }
814
+ let guard = self
815
+ .inner
816
+ .try_borrow_mut()
817
+ .map_err(|_| busy_error(ruby, "tar reader"))?;
818
+ RefMut::filter_map(guard, Option::as_mut)
819
+ .map_err(|_| Error::new(ruby.exception_io_error(), "closed stream"))
820
+ }
821
+
822
+ /// Runs `work` on the state, with the GVL released unless the input is
823
+ /// a Ruby IO. A failure is final.
824
+ fn run<T>(
825
+ &self,
826
+ ruby: &Ruby,
827
+ work: impl FnOnce(&mut State) -> Result<T, Fail>,
828
+ ) -> Result<T, Error> {
829
+ let mut state = self.state(ruby)?;
830
+ let outcome = maybe_without_gvl(self.io.is_some(), || work(&mut state));
831
+ drop(state);
832
+ outcome.map_err(|fail| {
833
+ self.failed.set(true);
834
+ raise(ruby, self.compression, fail)
835
+ })
836
+ }
837
+
838
+ /// Skips what is left of the current entry and reads the next header:
839
+ /// a Hash of its fields, or nil at the end of the archive.
840
+ pub fn next_entry(ruby: &Ruby, rb_self: &Self) -> Result<Option<RHash>, Error> {
841
+ let Some(meta) = rb_self.run(ruby, State::next)? else {
842
+ return Ok(None);
843
+ };
844
+ let h = ruby.hash_new();
845
+ let text = |bytes: &[u8]| ruby.str_from_slice(bytes);
846
+ h.aset(ruby.to_symbol("name"), text(&meta.name))?;
847
+ h.aset(ruby.to_symbol("linkname"), text(&meta.link))?;
848
+ h.aset(ruby.to_symbol("type"), ruby.to_symbol(meta.kind.name()))?;
849
+ h.aset(ruby.to_symbol("size"), meta.size)?;
850
+ h.aset(ruby.to_symbol("mtime_sec"), meta.mtime_sec)?;
851
+ h.aset(ruby.to_symbol("mtime_nsec"), meta.mtime_nsec)?;
852
+ h.aset(ruby.to_symbol("mode"), meta.mode)?;
853
+ h.aset(ruby.to_symbol("uid"), meta.uid)?;
854
+ h.aset(ruby.to_symbol("gid"), meta.gid)?;
855
+ h.aset(ruby.to_symbol("uname"), text(&meta.uname))?;
856
+ h.aset(ruby.to_symbol("gname"), text(&meta.gname))?;
857
+ Ok(Some(h))
858
+ }
859
+
860
+ /// Up to `want` bytes of the current entry's data, or nil at its end.
861
+ pub fn read(ruby: &Ruby, rb_self: &Self, want: usize) -> Result<Option<RString>, Error> {
862
+ let left = rb_self.state(ruby)?.remaining;
863
+ if left == 0 {
864
+ return Ok(None);
865
+ }
866
+ let want = (want as u64).min(left) as usize;
867
+ // What is left is what a header says, which may be far more than
868
+ // the archive holds: the buffer is for what has really arrived.
869
+ let mut buf = Vec::new();
870
+ rb_self.run(ruby, |state| {
871
+ while buf.len() < want {
872
+ let have = buf.len();
873
+ buf.resize(have + (want - have).min(READ_STEP), 0);
874
+ state.read_data(&mut buf[have..])?;
875
+ }
876
+ Ok(())
877
+ })?;
878
+ Ok(Some(ruby.str_from_slice(&buf)))
879
+ }
880
+
881
+ /// `:none`, `:gzip`, `:zstd`, `:xz` or `:bzip2`.
882
+ pub fn compression(ruby: &Ruby, rb_self: &Self) -> Symbol {
883
+ ruby.to_symbol(rb_self.compression.name())
884
+ }
885
+
886
+ /// Bytes read from the input so far (compressed, if it is).
887
+ pub fn bytes_in(&self) -> u64 {
888
+ self.raw_in.load(Ordering::Relaxed)
889
+ }
890
+
891
+ /// Says where `extract_entry` puts entries: under `dest`, an absolute
892
+ /// path. `on_exists` is 0 raise, 1 overwrite, 2 skip.
893
+ pub fn extract_begin(
894
+ ruby: &Ruby,
895
+ rb_self: &Self,
896
+ dest: String,
897
+ on_exists: u8,
898
+ ) -> Result<(), Error> {
899
+ let on_exists = match on_exists {
900
+ 0 => OnExists::Raise,
901
+ 1 => OnExists::Overwrite,
902
+ 2 => OnExists::Skip,
903
+ other => {
904
+ return Err(Error::new(
905
+ ruby.exception_arg_error(),
906
+ format!("on_exists code {other} is not 0, 1 or 2"),
907
+ ))
908
+ }
909
+ };
910
+ *rb_self
911
+ .placer
912
+ .try_borrow_mut()
913
+ .map_err(|_| busy_error(ruby, "tar reader"))? = Some(Placer::new(&dest, on_exists));
914
+ Ok(())
915
+ }
916
+
917
+ /// Puts the current entry at `name` under the destination: a
918
+ /// directory, or a file holding what is left of the entry's data.
919
+ /// `spec` is `[name, mtime_sec, mtime_nsec, mode, directory, replace]`,
920
+ /// the time and mode nil to leave them alone; with `replace` a file
921
+ /// already there is overwritten whatever the policy (the caller knows
922
+ /// it for one this run wrote).
923
+ ///
924
+ /// Returns the bytes written for a file, nil for a directory or an
925
+ /// entry left out under the policy, and `[kind, path]` for one left
926
+ /// out with a warning due (`:unsafe`, or `:link` with the link).
927
+ pub fn extract_entry(ruby: &Ruby, rb_self: &Self, spec: RArray) -> Result<Value, Error> {
928
+ let name: String = spec.entry(0)?;
929
+ let mtime = match spec.entry::<Option<i64>>(1)? {
930
+ Some(sec) => system_time(sec, spec.entry(2)?),
931
+ None => None,
932
+ };
933
+ let replace: bool = spec.entry(5)?;
934
+ let spec = Spec {
935
+ index: 0,
936
+ name,
937
+ mtime,
938
+ mode: spec.entry(3)?,
939
+ directory: spec.entry(4)?,
940
+ };
941
+
942
+ let mut state = rb_self.state(ruby)?;
943
+ let mut placer = rb_self.placer(ruby)?;
944
+ let policy = placer.on_exists();
945
+ if replace {
946
+ placer.set_on_exists(OnExists::Overwrite);
947
+ placer.set_own(true);
948
+ }
949
+ // What went wrong reading the archive, as opposed to writing the
950
+ // file: `place` only knows the second kind.
951
+ let mut read_fail: Option<Fail> = None;
952
+ let outcome = maybe_without_gvl(rb_self.io.is_some(), || {
953
+ let state = &mut *state;
954
+ let read_fail = &mut read_fail;
955
+ placer.place(&spec, |file| {
956
+ let mut buf = vec![0u8; CHUNK];
957
+ let mut written = 0u64;
958
+ while state.remaining > 0 {
959
+ crate::gvl::check()?;
960
+ let step = state.remaining.min(CHUNK as u64) as usize;
961
+ if let Err(fail) = state.read_data(&mut buf[..step]) {
962
+ *read_fail = Some(fail);
963
+ return Err(Failure::Io(io::Error::other("reading the archive failed")));
964
+ }
965
+ file.write_all(&buf[..step])?;
966
+ written += step as u64;
967
+ }
968
+ Ok(written)
969
+ })
970
+ });
971
+ placer.set_on_exists(policy);
972
+ placer.set_own(false);
973
+ let notice = placer.take_notices().pop();
974
+ drop(placer);
975
+ drop(state);
976
+
977
+ if let Some(fail) = read_fail {
978
+ rb_self.failed.set(true);
979
+ return Err(raise(ruby, rb_self.compression, fail));
980
+ }
981
+ let written =
982
+ outcome.map_err(|failure| extract_raise(ruby, ruby.qnil().as_value(), failure))?;
983
+ Ok(match notice {
984
+ Some((_, Notice::Unsafe(path))) => {
985
+ (ruby.to_symbol("unsafe"), path).into_value_with(ruby)
986
+ }
987
+ Some((_, Notice::Link(path))) => (ruby.to_symbol("link"), path).into_value_with(ruby),
988
+ Some((_, Notice::Oversize)) | None => written.into_value_with(ruby),
989
+ })
990
+ }
991
+
992
+ /// Gives the directories made their times and modes, now that nothing
993
+ /// more goes into them.
994
+ pub fn extract_finish(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
995
+ let mut placer = rb_self.placer(ruby)?;
996
+ let outcome = maybe_without_gvl(false, || placer.stamp_directories());
997
+ drop(placer);
998
+ outcome.map_err(|(_, failure)| extract_raise(ruby, ruby.qnil().as_value(), failure))
999
+ }
1000
+
1001
+ fn placer(&self, ruby: &Ruby) -> Result<RefMut<'_, Placer>, Error> {
1002
+ let guard = self
1003
+ .placer
1004
+ .try_borrow_mut()
1005
+ .map_err(|_| busy_error(ruby, "tar reader"))?;
1006
+ RefMut::filter_map(guard, Option::as_mut).map_err(|_| {
1007
+ Error::new(
1008
+ ruby.exception_io_error(),
1009
+ "extract_begin has not been called",
1010
+ )
1011
+ })
1012
+ }
1013
+
1014
+ pub fn close(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
1015
+ rb_self
1016
+ .inner
1017
+ .try_borrow_mut()
1018
+ .map_err(|_| busy_error(ruby, "tar reader"))?
1019
+ .take();
1020
+ Ok(())
1021
+ }
1022
+ }
1023
+
1024
+ fn raise(ruby: &Ruby, compression: Compression, fail: Fail) -> Error {
1025
+ let invalid = |why: String| {
1026
+ Error::new(
1027
+ ruby.get_inner(&ERROR),
1028
+ format!("invalid tar archive: {why}"),
1029
+ )
1030
+ };
1031
+ match fail {
1032
+ Fail::Invalid(why) => invalid(why),
1033
+ Fail::Unsupported(why) => Error::new(ruby.get_inner(&ERROR), why),
1034
+ Fail::Ratio(ratio, allowed) => {
1035
+ let ratio = (ratio * 10.0).round() / 10.0;
1036
+ limit_error(ruby, ("a compression ratio", ratio, allowed))
1037
+ }
1038
+ Fail::Input(read, allowed) => limit_error(ruby, ("an archive size", read, allowed)),
1039
+ Fail::Io(e) => {
1040
+ let ours = crate::gvl::is_cancelled(&e)
1041
+ || e.get_ref().is_some_and(|inner| inner.is::<RubyError>());
1042
+ if ours {
1043
+ return io_error(ruby, e);
1044
+ }
1045
+ use io::ErrorKind::*;
1046
+ match e.kind() {
1047
+ UnexpectedEof => invalid("the archive is cut short".to_string()),
1048
+ // How the decoders report data they cannot make sense of.
1049
+ InvalidData | InvalidInput | Other | OutOfMemory
1050
+ if compression != Compression::None =>
1051
+ {
1052
+ invalid(format!("the {} data is corrupt ({e})", compression.name()))
1053
+ }
1054
+ _ => io_error(ruby, e),
1055
+ }
1056
+ }
1057
+ }
1058
+ }
1059
+
1060
+ /// `Ziperu::LimitError.new(what, actual, limit)`.
1061
+ fn limit_error<A: magnus::ArgList>(ruby: &Ruby, args: A) -> Error {
1062
+ match ruby.get_inner(&LIMIT_ERROR).new_instance(args) {
1063
+ Ok(exception) => Error::from(exception),
1064
+ Err(e) => e,
1065
+ }
1066
+ }
1067
+
1068
+ #[cfg(test)]
1069
+ mod tests {
1070
+ use super::*;
1071
+ use crate::test_rng::{Rng, CASES};
1072
+
1073
+ fn octal(field: &mut [u8], value: u64) {
1074
+ let digits = format!("{:0width$o}", value, width = field.len() - 1);
1075
+ field[..digits.len()].copy_from_slice(digits.as_bytes());
1076
+ field[digits.len()] = 0;
1077
+ }
1078
+
1079
+ /// A ustar header block for `name`, with a good checksum.
1080
+ fn header(name: &[u8], flag: u8, size: u64) -> [u8; BLOCK] {
1081
+ let mut b = [0u8; BLOCK];
1082
+ b[..name.len()].copy_from_slice(name);
1083
+ octal(&mut b[100..108], 0o644);
1084
+ octal(&mut b[108..116], 1000);
1085
+ octal(&mut b[116..124], 1000);
1086
+ octal(&mut b[124..136], size);
1087
+ octal(&mut b[136..148], 1_700_000_000);
1088
+ b[156] = flag;
1089
+ b[257..263].copy_from_slice(b"ustar\0");
1090
+ b[263..265].copy_from_slice(b"00");
1091
+ seal(&mut b);
1092
+ b
1093
+ }
1094
+
1095
+ fn seal(b: &mut [u8; BLOCK]) {
1096
+ b[148..156].copy_from_slice(b" ");
1097
+ let sum: u64 = b.iter().map(|&x| u64::from(x)).sum();
1098
+ let digits = format!("{sum:06o}\0 ");
1099
+ b[148..156].copy_from_slice(digits.as_bytes());
1100
+ }
1101
+
1102
+ fn padded(data: &[u8]) -> Vec<u8> {
1103
+ let mut out = data.to_vec();
1104
+ out.resize(data.len() + padding_after(data.len() as u64) as usize, 0);
1105
+ out
1106
+ }
1107
+
1108
+ fn reader(bytes: Vec<u8>) -> State {
1109
+ let raw_in = Arc::new(AtomicU64::new(0));
1110
+ let (compression, input) = open_input(Cursor::new(bytes), Arc::clone(&raw_in)).unwrap();
1111
+ State {
1112
+ input,
1113
+ compression,
1114
+ raw_in,
1115
+ out: 0,
1116
+ remaining: 0,
1117
+ padding: 0,
1118
+ done: false,
1119
+ max_ratio: None,
1120
+ max_input: None,
1121
+ }
1122
+ }
1123
+
1124
+ fn names(bytes: Vec<u8>) -> Result<Vec<String>, Fail> {
1125
+ let mut state = reader(bytes);
1126
+ let mut names = Vec::new();
1127
+ while let Some(meta) = state.next()? {
1128
+ names.push(String::from_utf8_lossy(&meta.name).into_owned());
1129
+ }
1130
+ Ok(names)
1131
+ }
1132
+
1133
+ #[test]
1134
+ fn reads_numbers() {
1135
+ assert_eq!(number(b"0000644\0"), Some(0o644));
1136
+ assert_eq!(number(b" 644 \0"), Some(0o644));
1137
+ assert_eq!(number(b"\0\0\0\0\0\0\0\0"), Some(0));
1138
+ assert_eq!(number(b" "), Some(0));
1139
+ assert_eq!(number(b"0000648\0"), None);
1140
+ assert_eq!(
1141
+ number(&[0x80, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]),
1142
+ Some(1 << 32)
1143
+ );
1144
+ assert_eq!(number(&[0xff; 12]), Some(-1));
1145
+ assert_eq!(
1146
+ number(&[0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
1147
+ None
1148
+ );
1149
+ assert_eq!(number(&[0x81, 0, 0, 0, 0, 0, 0, 0]), None);
1150
+ }
1151
+
1152
+ #[test]
1153
+ fn reads_pax_records() {
1154
+ let records = parse_pax(b"12 path=a/b\n18 mtime=1.500000\n").unwrap();
1155
+ assert_eq!(
1156
+ records,
1157
+ vec![(&b"path"[..], &b"a/b"[..]), (b"mtime", b"1.500000")]
1158
+ );
1159
+ assert!(parse_pax(b"99 path=a\n").is_err());
1160
+ assert!(parse_pax(b"9 path=a/b\n").is_err());
1161
+ assert!(parse_pax(b"x path=a\n").is_err());
1162
+ assert!(parse_pax(b"7 path\n").is_err());
1163
+ assert_eq!(parse_pax(b"").unwrap(), vec![]);
1164
+ }
1165
+
1166
+ #[test]
1167
+ fn reads_pax_times() {
1168
+ assert_eq!(pax_time(b"1700000000"), Some((1_700_000_000, 0)));
1169
+ assert_eq!(pax_time(b"1.5"), Some((1, 500_000_000)));
1170
+ assert_eq!(pax_time(b"1.123456789123"), Some((1, 123_456_789)));
1171
+ assert_eq!(pax_time(b"-1.25"), Some((-2, 750_000_000)));
1172
+ assert_eq!(pax_time(b"-0.5"), Some((-1, 500_000_000)));
1173
+ assert_eq!(pax_time(b"1.x"), None);
1174
+ assert_eq!(pax_time(b""), None);
1175
+ }
1176
+
1177
+ #[test]
1178
+ fn tells_compression_from_the_first_bytes() {
1179
+ assert_eq!(Compression::detect(&[0x1f, 0x8b, 8, 0]), Compression::Gzip);
1180
+ assert_eq!(
1181
+ Compression::detect(&[0x28, 0xb5, 0x2f, 0xfd, 0]),
1182
+ Compression::Zstd
1183
+ );
1184
+ assert_eq!(Compression::detect(b"\xfd7zXZ\0\0"), Compression::Xz);
1185
+ assert_eq!(Compression::detect(b"BZh91AY&SY"), Compression::Bzip2);
1186
+ // A file named like the start of a bzip2 stream is a file name.
1187
+ assert_eq!(Compression::detect(b"BZh9.txt\0\0"), Compression::None);
1188
+ assert_eq!(Compression::detect(b"hello.txt\0"), Compression::None);
1189
+ assert_eq!(Compression::detect(b""), Compression::None);
1190
+ }
1191
+
1192
+ #[test]
1193
+ fn walks_entries_and_skips_unread_data() {
1194
+ let mut tar = Vec::new();
1195
+ tar.extend(header(b"a.txt", b'0', 5));
1196
+ tar.extend(padded(b"hello"));
1197
+ tar.extend(header(b"dir/", b'5', 0));
1198
+ tar.extend(header(b"dir/b.txt", b'0', 600));
1199
+ tar.extend(padded(&[7u8; 600]));
1200
+ tar.extend([0u8; 2 * BLOCK]);
1201
+ assert_eq!(names(tar.clone()).unwrap(), ["a.txt", "dir/", "dir/b.txt"]);
1202
+
1203
+ let mut state = reader(tar);
1204
+ let first = state.next().unwrap().unwrap();
1205
+ assert_eq!((first.kind, first.size, first.mode), (Kind::File, 5, 0o644));
1206
+ let mut data = [0u8; 5];
1207
+ state.read_data(&mut data).unwrap();
1208
+ assert_eq!(&data, b"hello");
1209
+ assert_eq!(state.next().unwrap().unwrap().kind, Kind::Directory);
1210
+ assert_eq!(state.next().unwrap().unwrap().size, 600);
1211
+ assert!(state.next().unwrap().is_none());
1212
+ assert!(state.next().unwrap().is_none());
1213
+ }
1214
+
1215
+ #[test]
1216
+ fn applies_long_names_and_extended_headers() {
1217
+ let long = vec![b'n'; 300];
1218
+ let mut tar = Vec::new();
1219
+ let mut name = long.clone();
1220
+ name.push(0);
1221
+ tar.extend(header(b"././@LongLink", b'L', name.len() as u64));
1222
+ tar.extend(padded(&name));
1223
+ tar.extend(header(b"short", b'0', 0));
1224
+ let pax = b"21 path=from/pax.txt\n10 size=3\n30 mtime=1700000001.250000000\n";
1225
+ tar.extend(header(b"PaxHeader", b'x', pax.len() as u64));
1226
+ tar.extend(padded(pax));
1227
+ tar.extend(header(b"ignored", b'0', 0));
1228
+ tar.extend(padded(b"abc"));
1229
+ tar.extend([0u8; 2 * BLOCK]);
1230
+
1231
+ let mut state = reader(tar);
1232
+ assert_eq!(state.next().unwrap().unwrap().name, long);
1233
+ let second = state.next().unwrap().unwrap();
1234
+ assert_eq!(second.name, b"from/pax.txt");
1235
+ assert_eq!(second.size, 3);
1236
+ assert_eq!(
1237
+ (second.mtime_sec, second.mtime_nsec),
1238
+ (1_700_000_001, 250_000_000)
1239
+ );
1240
+ assert!(state.next().unwrap().is_none());
1241
+ }
1242
+
1243
+ #[test]
1244
+ fn a_long_name_cut_at_a_slash_is_still_a_file() {
1245
+ // 99 bytes and a slash fill the header's name field exactly.
1246
+ let mut full = vec![b'd'; 99];
1247
+ full.extend(b"/file.txt");
1248
+ let mut name = full.clone();
1249
+ name.push(0);
1250
+ let mut tar = Vec::new();
1251
+ tar.extend(header(b"././@LongLink", b'L', name.len() as u64));
1252
+ tar.extend(padded(&name));
1253
+ tar.extend(header(&full[..100], b'0', 600));
1254
+ tar.extend(padded(&[7u8; 600]));
1255
+ tar.extend(header(b"old/", b'0', 0));
1256
+ tar.extend(header(b"after", b'0', 0));
1257
+ tar.extend([0u8; 2 * BLOCK]);
1258
+
1259
+ let mut state = reader(tar);
1260
+ let first = state.next().unwrap().unwrap();
1261
+ assert_eq!(
1262
+ (first.name, first.kind, first.size),
1263
+ (full, Kind::File, 600)
1264
+ );
1265
+ assert_eq!(state.next().unwrap().unwrap().kind, Kind::Directory);
1266
+ assert_eq!(state.next().unwrap().unwrap().name, b"after");
1267
+ assert!(state.next().unwrap().is_none());
1268
+ }
1269
+
1270
+ #[test]
1271
+ fn a_link_or_directory_has_no_data_whatever_its_size_says() {
1272
+ let mut tar = Vec::new();
1273
+ tar.extend(header(b"link", b'2', 4096));
1274
+ tar.extend(header(b"dir/", b'5', 4096));
1275
+ tar.extend(header(b"after", b'0', 0));
1276
+ tar.extend([0u8; 2 * BLOCK]);
1277
+ assert_eq!(names(tar).unwrap(), ["link", "dir/", "after"]);
1278
+ }
1279
+
1280
+ #[test]
1281
+ fn joins_the_ustar_prefix() {
1282
+ let mut block = header(b"file.txt", b'0', 0);
1283
+ block[345..351].copy_from_slice(b"a/deep");
1284
+ seal(&mut block);
1285
+ let mut tar = block.to_vec();
1286
+ tar.extend([0u8; 2 * BLOCK]);
1287
+ assert_eq!(names(tar).unwrap(), ["a/deep/file.txt"]);
1288
+ }
1289
+
1290
+ #[test]
1291
+ fn refuses_what_is_not_a_whole_archive() {
1292
+ let invalid = |bytes: Vec<u8>| match names(bytes) {
1293
+ Err(Fail::Invalid(why)) => why,
1294
+ other => panic!("expected Invalid, got {other:?}"),
1295
+ };
1296
+ assert_eq!(invalid(Vec::new()), "not a tar archive");
1297
+ assert_eq!(invalid(b"hello".to_vec()), "not a tar archive");
1298
+ assert_eq!(invalid(vec![0u8; BLOCK]), "not a tar archive");
1299
+ let mut zeros_then = vec![0u8; BLOCK];
1300
+ zeros_then.extend([b'x'; BLOCK]);
1301
+ assert_eq!(invalid(zeros_then), "not a tar archive");
1302
+ // Its end marker alone: an archive of nothing.
1303
+ assert!(names(vec![0u8; 2 * BLOCK]).unwrap().is_empty());
1304
+ assert!(names(vec![0u8; 20 * BLOCK]).unwrap().is_empty());
1305
+ assert_eq!(invalid(vec![b'x'; BLOCK]), "not a tar archive");
1306
+
1307
+ let mut cut = header(b"a.txt", b'0', 1000).to_vec();
1308
+ cut.extend([1u8; 600]);
1309
+ assert_eq!(invalid(cut), "the archive is cut short");
1310
+
1311
+ let mut bad = header(b"a.txt", b'0', 0).to_vec();
1312
+ let mut second = header(b"b.txt", b'0', 0);
1313
+ second[0] = b'c';
1314
+ bad.extend(second);
1315
+ assert!(invalid(bad).starts_with("a header's checksum does not match"));
1316
+
1317
+ let mut huge = header(b"x", b'x', META_MAX + 1).to_vec();
1318
+ huge.extend([0u8; BLOCK]);
1319
+ assert!(invalid(huge).contains("over the"));
1320
+
1321
+ // An end of input on a block boundary, with no end marker, is an end.
1322
+ assert_eq!(
1323
+ names(header(b"a.txt", b'0', 0).to_vec()).unwrap(),
1324
+ ["a.txt"]
1325
+ );
1326
+ }
1327
+
1328
+ #[test]
1329
+ fn zeros_after_a_compressed_stream_are_padding() {
1330
+ let mut tar = header(b"a.txt", b'0', 5).to_vec();
1331
+ tar.extend(padded(b"hello"));
1332
+ tar.extend([0u8; 2 * BLOCK]);
1333
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1334
+ io::Write::write_all(&mut gz, &tar).unwrap();
1335
+ let gz = gz.finish().unwrap();
1336
+ let mut bz = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
1337
+ io::Write::write_all(&mut bz, &tar).unwrap();
1338
+ let bz = bz.finish().unwrap();
1339
+
1340
+ for packed in [gz, bz] {
1341
+ let mut zeros = packed.clone();
1342
+ zeros.extend([0u8; 3000]);
1343
+ assert_eq!(names(zeros).unwrap(), ["a.txt"]);
1344
+
1345
+ // A second stream after the padding is more of the same.
1346
+ let mut twice = packed.clone();
1347
+ twice.extend([0u8; 100]);
1348
+ twice.extend(&packed);
1349
+ assert_eq!(names(twice).unwrap(), ["a.txt"]);
1350
+
1351
+ let mut junk = packed.clone();
1352
+ junk.extend([0u8; 100]);
1353
+ junk.extend(b"not a stream");
1354
+ assert!(matches!(names(junk), Err(Fail::Io(_))));
1355
+
1356
+ // A checksum that does not hold is still found.
1357
+ let mut bad = packed.clone();
1358
+ let at = bad.len() - 6;
1359
+ bad[at] ^= 0xff;
1360
+ assert!(matches!(names(bad), Err(Fail::Io(_))));
1361
+ }
1362
+ }
1363
+
1364
+ #[test]
1365
+ fn a_name_with_a_nul_is_refused() {
1366
+ for pax in [&b"16 path=a\0b.txt\n"[..], b"16 linkpath=a\0b\n"] {
1367
+ let mut tar = header(b"PaxHeader", b'x', pax.len() as u64).to_vec();
1368
+ tar.extend(padded(pax));
1369
+ tar.extend(header(b"x", b'0', 0));
1370
+ tar.extend([0u8; 2 * BLOCK]);
1371
+ assert!(matches!(names(tar), Err(Fail::Invalid(_))));
1372
+ }
1373
+ }
1374
+
1375
+ #[test]
1376
+ fn refuses_sparse_and_multi_volume() {
1377
+ for flag in *b"SM" {
1378
+ let mut tar = header(b"x", flag, 0).to_vec();
1379
+ tar.extend([0u8; 2 * BLOCK]);
1380
+ assert!(matches!(names(tar), Err(Fail::Unsupported(_))));
1381
+ }
1382
+ let pax = b"22 GNU.sparse.major=1\n";
1383
+ let mut tar = header(b"PaxHeader", b'x', pax.len() as u64).to_vec();
1384
+ tar.extend(padded(pax));
1385
+ tar.extend(header(b"x", b'0', 0));
1386
+ assert!(matches!(names(tar), Err(Fail::Unsupported(_))));
1387
+ }
1388
+
1389
+ #[test]
1390
+ fn stops_at_the_ratio_and_input_limits() {
1391
+ let mut tar = header(b"zeros", b'0', 8 << 20).to_vec();
1392
+ tar.extend(vec![0u8; 8 << 20]);
1393
+ tar.extend([0u8; 2 * BLOCK]);
1394
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1395
+ io::Write::write_all(&mut gz, &tar).unwrap();
1396
+ let gz = gz.finish().unwrap();
1397
+
1398
+ let mut state = reader(gz.clone());
1399
+ assert_eq!(state.compression, Compression::Gzip);
1400
+ state.max_ratio = Some(100.0);
1401
+ state.next().unwrap();
1402
+ assert!(matches!(state.next(), Err(Fail::Ratio(ratio, _)) if ratio > 100.0));
1403
+
1404
+ let mut state = reader(gz);
1405
+ state.max_input = Some(1024);
1406
+ assert!(matches!(state.next(), Err(Fail::Input(_, 1024))));
1407
+ }
1408
+
1409
+ #[test]
1410
+ fn property_any_bytes_are_survived() {
1411
+ let mut rng = Rng::new(21);
1412
+ for _ in 0..CASES {
1413
+ // Random bytes, and a real archive with bytes of it changed.
1414
+ let bytes = if rng.below(2) == 0 {
1415
+ rng.bytes(3 * BLOCK)
1416
+ } else {
1417
+ let pax = b"12 path=a/b\n";
1418
+ let mut tar = header(b"PaxHeader", b'x', pax.len() as u64).to_vec();
1419
+ tar.extend(padded(pax));
1420
+ tar.extend(header(b"a.txt", b'0', 700));
1421
+ tar.extend(padded(&[1u8; 700]));
1422
+ tar.extend([0u8; 2 * BLOCK]);
1423
+ for _ in 0..rng.below(4) {
1424
+ let at = rng.below(tar.len());
1425
+ tar[at] = rng.next() as u8;
1426
+ }
1427
+ tar.truncate(rng.below(tar.len() + 1));
1428
+ tar
1429
+ };
1430
+ let mut state = reader(bytes);
1431
+ while let Ok(Some(meta)) = state.next() {
1432
+ let mut data = vec![0u8; meta.size.min(4096) as usize];
1433
+ if state.read_data(&mut data).is_err() {
1434
+ break;
1435
+ }
1436
+ }
1437
+ }
1438
+ }
1439
+
1440
+ #[test]
1441
+ fn property_any_header_fields_are_survived() {
1442
+ let mut rng = Rng::new(22);
1443
+ for _ in 0..CASES {
1444
+ let mut block = [0u8; BLOCK];
1445
+ for b in block.iter_mut() {
1446
+ *b = rng.next() as u8;
1447
+ }
1448
+ seal(&mut block);
1449
+ let _ = parse_header(&block);
1450
+ let _ = parse_pax(&rng.bytes(64));
1451
+ let _ = pax_time(&rng.bytes(24));
1452
+ }
1453
+ }
1454
+ }