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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +78 -0
- data/Cargo.lock +4 -1
- data/README.md +85 -44
- data/ext/ziperu/Cargo.toml +8 -1
- data/ext/ziperu/src/errors.rs +1 -0
- data/ext/ziperu/src/extract.rs +87 -699
- data/ext/ziperu/src/lib.rs +25 -0
- data/ext/ziperu/src/placer.rs +759 -0
- data/ext/ziperu/src/stream.rs +7 -1
- data/ext/ziperu/src/tar.rs +1454 -0
- data/ext/ziperu/src/tar_writer.rs +736 -0
- data/lib/ziperu/entry.rb +3 -38
- data/lib/ziperu/file/extraction.rb +11 -6
- data/lib/ziperu/ioextras.rb +7 -0
- data/lib/ziperu/link_safety.rb +43 -0
- data/lib/ziperu/tar/extraction.rb +399 -0
- data/lib/ziperu/tar/writer.rb +393 -0
- data/lib/ziperu/tar.rb +264 -0
- data/lib/ziperu/version.rb +1 -1
- data/lib/ziperu.rb +2 -0
- metadata +8 -1
|
@@ -0,0 +1,736 @@
|
|
|
1
|
+
//! `Ziperu::Native::TarWriter`: writes a tar archive front to back, to a
|
|
2
|
+
//! file or to any Ruby IO with `write` (a pipe, a socket, a response
|
|
3
|
+
//! body), plain or compressed with gzip, zstd, xz or bzip2.
|
|
4
|
+
//!
|
|
5
|
+
//! What is written is POSIX.1-2001 (pax) as GNU tar, bsdtar and Python
|
|
6
|
+
//! write it: a ustar header for every entry, and before it an extended
|
|
7
|
+
//! header only when something does not fit the ustar fields: a name or
|
|
8
|
+
//! link target over 100 bytes or not ASCII, a size of 8 GiB or more, a
|
|
9
|
+
//! time before 1970, an id over 2097151, an owner name over 32 bytes or
|
|
10
|
+
//! not ASCII. An archive of ordinary names is plain ustar, which every
|
|
11
|
+
//! reader takes.
|
|
12
|
+
//!
|
|
13
|
+
//! An entry's size goes in its header, ahead of its data, so it is fixed
|
|
14
|
+
//! when the entry starts: `write` refuses more than was declared, and the
|
|
15
|
+
//! next entry (or `close`) refuses to follow one that got less. Ruby
|
|
16
|
+
//! decides what each entry says; this side lays out the bytes.
|
|
17
|
+
//!
|
|
18
|
+
//! gzip and zstd streams are written with nothing of this machine in
|
|
19
|
+
//! them (no time, name or system in the gzip header), and a zstd frame
|
|
20
|
+
//! with its checksum, as the `zstd` command writes it: tar has no check
|
|
21
|
+
//! of its own on an entry's data.
|
|
22
|
+
|
|
23
|
+
use std::cell::{Cell, RefCell, RefMut};
|
|
24
|
+
use std::fs;
|
|
25
|
+
use std::io::{self, BufWriter, Read, Write};
|
|
26
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
27
|
+
use std::sync::Arc;
|
|
28
|
+
|
|
29
|
+
use magnus::{
|
|
30
|
+
gc::Marker, prelude::*, typed_data::DataTypeFunctions, value::Opaque, Error, RArray, RString,
|
|
31
|
+
Ruby, TypedData, Value,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
use crate::errors::{busy_error, io_error, ERROR};
|
|
35
|
+
use crate::gvl::maybe_without_gvl;
|
|
36
|
+
use crate::source::ruby_io_error;
|
|
37
|
+
|
|
38
|
+
const BLOCK: usize = 512;
|
|
39
|
+
const CHUNK: usize = 64 * 1024;
|
|
40
|
+
/// The name an extended header goes by, as Python writes it.
|
|
41
|
+
const PAX_NAME: &[u8] = b"././@PaxHeader";
|
|
42
|
+
|
|
43
|
+
/// Writes to a Ruby IO. Once detached it swallows everything: an encoder
|
|
44
|
+
/// dropped unfinished writes its last bytes from the GC's free, where no
|
|
45
|
+
/// Ruby object may be touched. A write that fails detaches it too, so
|
|
46
|
+
/// that an IO which raised is not handed the rest on the way out.
|
|
47
|
+
struct RubyWrite {
|
|
48
|
+
io: Opaque<Value>,
|
|
49
|
+
attached: Arc<AtomicBool>,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
impl Write for RubyWrite {
|
|
53
|
+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
54
|
+
if buf.is_empty() || !self.attached.load(Ordering::Acquire) {
|
|
55
|
+
return Ok(buf.len());
|
|
56
|
+
}
|
|
57
|
+
let ruby = Ruby::get().map_err(|e| io::Error::other(e.to_string()))?;
|
|
58
|
+
let io = ruby.get_inner(self.io);
|
|
59
|
+
let chunk = ruby.str_from_slice(buf);
|
|
60
|
+
if let Err(e) = io.funcall::<_, _, Value>("write", (chunk,)) {
|
|
61
|
+
self.attached.store(false, Ordering::Release);
|
|
62
|
+
return Err(ruby_io_error(e));
|
|
63
|
+
}
|
|
64
|
+
Ok(buf.len())
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
fn flush(&mut self) -> io::Result<()> {
|
|
68
|
+
Ok(())
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
type Out = Box<dyn Write + Send>;
|
|
73
|
+
|
|
74
|
+
/// The tar stream on its way out, through a codec or not.
|
|
75
|
+
enum Encoder {
|
|
76
|
+
Plain(Out),
|
|
77
|
+
Gzip(flate2::write::GzEncoder<Out>),
|
|
78
|
+
Zstd(zstd::stream::write::Encoder<'static, Out>),
|
|
79
|
+
Xz(Box<lzma_rust2::XzWriter<Out>>),
|
|
80
|
+
Bzip2(bzip2::write::BzEncoder<Out>),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
impl Encoder {
|
|
84
|
+
/// `level` is the codec's own scale, checked by Ruby; `None` is its
|
|
85
|
+
/// usual default.
|
|
86
|
+
fn new(out: Out, compression: &str, level: Option<u32>) -> io::Result<Self> {
|
|
87
|
+
Ok(match compression {
|
|
88
|
+
"none" => Encoder::Plain(out),
|
|
89
|
+
// No name and no time in the header, and no operating system
|
|
90
|
+
// (255 is "unknown"), so the same input gives the same bytes
|
|
91
|
+
// on every machine.
|
|
92
|
+
"gzip" => Encoder::Gzip(
|
|
93
|
+
flate2::GzBuilder::new()
|
|
94
|
+
.operating_system(255)
|
|
95
|
+
.write(out, flate2::Compression::new(level.unwrap_or(6))),
|
|
96
|
+
),
|
|
97
|
+
"zstd" => {
|
|
98
|
+
let mut encoder =
|
|
99
|
+
zstd::stream::write::Encoder::new(out, level.map_or(3, |l| l as i32))?;
|
|
100
|
+
encoder.include_checksum(true)?;
|
|
101
|
+
Encoder::Zstd(encoder)
|
|
102
|
+
}
|
|
103
|
+
"xz" => {
|
|
104
|
+
let options = lzma_rust2::XzOptions::with_preset(level.unwrap_or(6));
|
|
105
|
+
Encoder::Xz(Box::new(
|
|
106
|
+
lzma_rust2::XzWriter::new(out, options).map_err(io::Error::other)?,
|
|
107
|
+
))
|
|
108
|
+
}
|
|
109
|
+
"bzip2" => Encoder::Bzip2(bzip2::write::BzEncoder::new(
|
|
110
|
+
out,
|
|
111
|
+
bzip2::Compression::new(level.unwrap_or(6)),
|
|
112
|
+
)),
|
|
113
|
+
other => {
|
|
114
|
+
return Err(io::Error::new(
|
|
115
|
+
io::ErrorKind::InvalidInput,
|
|
116
|
+
format!("unknown compression {other:?}"),
|
|
117
|
+
))
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// Ends the compressed stream and flushes what is under it.
|
|
123
|
+
fn finish(self) -> io::Result<()> {
|
|
124
|
+
let mut out = match self {
|
|
125
|
+
Encoder::Plain(out) => out,
|
|
126
|
+
Encoder::Gzip(e) => e.finish()?,
|
|
127
|
+
Encoder::Zstd(e) => e.finish()?,
|
|
128
|
+
Encoder::Xz(e) => e.finish().map_err(io::Error::other)?,
|
|
129
|
+
Encoder::Bzip2(e) => e.finish()?,
|
|
130
|
+
};
|
|
131
|
+
out.flush()
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
impl Write for Encoder {
|
|
136
|
+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
137
|
+
match self {
|
|
138
|
+
Encoder::Plain(w) => w.write(buf),
|
|
139
|
+
Encoder::Gzip(w) => w.write(buf),
|
|
140
|
+
Encoder::Zstd(w) => w.write(buf),
|
|
141
|
+
Encoder::Xz(w) => w.write(buf),
|
|
142
|
+
Encoder::Bzip2(w) => w.write(buf),
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
fn flush(&mut self) -> io::Result<()> {
|
|
147
|
+
match self {
|
|
148
|
+
Encoder::Plain(w) => w.flush(),
|
|
149
|
+
Encoder::Gzip(w) => w.flush(),
|
|
150
|
+
Encoder::Zstd(w) => w.flush(),
|
|
151
|
+
Encoder::Xz(w) => w.flush(),
|
|
152
|
+
Encoder::Bzip2(w) => w.flush(),
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/// What one entry's header says.
|
|
158
|
+
struct Fields {
|
|
159
|
+
name: Vec<u8>,
|
|
160
|
+
link: Vec<u8>,
|
|
161
|
+
flag: u8,
|
|
162
|
+
size: u64,
|
|
163
|
+
mode: u32,
|
|
164
|
+
mtime: i64,
|
|
165
|
+
uid: u64,
|
|
166
|
+
gid: u64,
|
|
167
|
+
uname: Vec<u8>,
|
|
168
|
+
gname: Vec<u8>,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// Writes `value` into a numeric field as zero-padded octal and a NUL.
|
|
172
|
+
/// False, with the field left at zero, when it does not fit.
|
|
173
|
+
fn octal(field: &mut [u8], value: u64) -> bool {
|
|
174
|
+
let digits = field.len() - 1;
|
|
175
|
+
let fits = digits >= 22 || value < 1u64 << (3 * digits);
|
|
176
|
+
let text = format!("{:0digits$o}", if fits { value } else { 0 });
|
|
177
|
+
field[..digits].copy_from_slice(text.as_bytes());
|
|
178
|
+
field[digits] = 0;
|
|
179
|
+
fits
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/// Writes `value` into a text field; false when it has to go in an
|
|
183
|
+
/// extended header instead (too long, or not ASCII, which ustar does not
|
|
184
|
+
/// promise to carry). What fits of it is written either way.
|
|
185
|
+
fn text(field: &mut [u8], value: &[u8], directory: bool) -> bool {
|
|
186
|
+
let fits = value.len() <= field.len() && value.is_ascii();
|
|
187
|
+
let mut kept = &value[..value.len().min(field.len())];
|
|
188
|
+
// A cut name must not end in a slash, which marks a directory to a
|
|
189
|
+
// reader that has no use for the extended header.
|
|
190
|
+
while !fits && !directory && kept.ends_with(b"/") {
|
|
191
|
+
kept = &kept[..kept.len() - 1];
|
|
192
|
+
}
|
|
193
|
+
field[..kept.len()].copy_from_slice(kept);
|
|
194
|
+
fits
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/// The checksum of a header block: the sum of its bytes, the checksum
|
|
198
|
+
/// field itself counted as spaces.
|
|
199
|
+
fn seal(block: &mut [u8; BLOCK]) {
|
|
200
|
+
block[148..156].fill(b' ');
|
|
201
|
+
let sum: u32 = block.iter().map(|&b| u32::from(b)).sum();
|
|
202
|
+
block[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// One record of an extended header: "LENGTH KEY=VALUE\n", the length
|
|
206
|
+
/// counting itself.
|
|
207
|
+
fn pax_record(key: &str, value: &[u8]) -> Vec<u8> {
|
|
208
|
+
let body = key.len() + value.len() + 3;
|
|
209
|
+
let mut total = body;
|
|
210
|
+
loop {
|
|
211
|
+
let next = body + total.to_string().len();
|
|
212
|
+
if next == total {
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
total = next;
|
|
216
|
+
}
|
|
217
|
+
let mut record = format!("{total} {key}=").into_bytes();
|
|
218
|
+
record.extend_from_slice(value);
|
|
219
|
+
record.push(b'\n');
|
|
220
|
+
record
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// The header block for `fields`, and the records for what did not fit it.
|
|
224
|
+
fn ustar(fields: &Fields) -> ([u8; BLOCK], Vec<u8>) {
|
|
225
|
+
let mut block = [0u8; BLOCK];
|
|
226
|
+
let mut pax = Vec::new();
|
|
227
|
+
let directory = fields.flag == b'5';
|
|
228
|
+
if !text(&mut block[0..100], &fields.name, directory) {
|
|
229
|
+
pax.extend(pax_record("path", &fields.name));
|
|
230
|
+
}
|
|
231
|
+
octal(&mut block[100..108], u64::from(fields.mode & 0o7777));
|
|
232
|
+
if !octal(&mut block[108..116], fields.uid) {
|
|
233
|
+
pax.extend(pax_record("uid", fields.uid.to_string().as_bytes()));
|
|
234
|
+
}
|
|
235
|
+
if !octal(&mut block[116..124], fields.gid) {
|
|
236
|
+
pax.extend(pax_record("gid", fields.gid.to_string().as_bytes()));
|
|
237
|
+
}
|
|
238
|
+
if !octal(&mut block[124..136], fields.size) {
|
|
239
|
+
pax.extend(pax_record("size", fields.size.to_string().as_bytes()));
|
|
240
|
+
}
|
|
241
|
+
let mtime = u64::try_from(fields.mtime).ok();
|
|
242
|
+
if !mtime.is_some_and(|t| octal(&mut block[136..148], t)) {
|
|
243
|
+
octal(&mut block[136..148], 0);
|
|
244
|
+
pax.extend(pax_record("mtime", fields.mtime.to_string().as_bytes()));
|
|
245
|
+
}
|
|
246
|
+
block[156] = fields.flag;
|
|
247
|
+
if !text(&mut block[157..257], &fields.link, true) {
|
|
248
|
+
pax.extend(pax_record("linkpath", &fields.link));
|
|
249
|
+
}
|
|
250
|
+
block[257..263].copy_from_slice(b"ustar\0");
|
|
251
|
+
block[263..265].copy_from_slice(b"00");
|
|
252
|
+
if !text(&mut block[265..297], &fields.uname, true) {
|
|
253
|
+
pax.extend(pax_record("uname", &fields.uname));
|
|
254
|
+
}
|
|
255
|
+
if !text(&mut block[297..329], &fields.gname, true) {
|
|
256
|
+
pax.extend(pax_record("gname", &fields.gname));
|
|
257
|
+
}
|
|
258
|
+
octal(&mut block[329..337], 0);
|
|
259
|
+
octal(&mut block[337..345], 0);
|
|
260
|
+
seal(&mut block);
|
|
261
|
+
(block, pax)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/// Everything that goes ahead of an entry's data: an extended header and
|
|
265
|
+
/// its records when there are any, then the entry's own header.
|
|
266
|
+
fn headers(fields: &Fields) -> Vec<u8> {
|
|
267
|
+
let (block, pax) = ustar(fields);
|
|
268
|
+
let mut out = Vec::with_capacity(BLOCK);
|
|
269
|
+
if !pax.is_empty() {
|
|
270
|
+
let (extended, _) = ustar(&Fields {
|
|
271
|
+
name: PAX_NAME.to_vec(),
|
|
272
|
+
link: Vec::new(),
|
|
273
|
+
flag: b'x',
|
|
274
|
+
size: pax.len() as u64,
|
|
275
|
+
mode: 0o644,
|
|
276
|
+
mtime: fields.mtime.max(0),
|
|
277
|
+
uid: 0,
|
|
278
|
+
gid: 0,
|
|
279
|
+
uname: Vec::new(),
|
|
280
|
+
gname: Vec::new(),
|
|
281
|
+
});
|
|
282
|
+
out.extend_from_slice(&extended);
|
|
283
|
+
out.extend_from_slice(&pax);
|
|
284
|
+
out.resize(out.len() + padding_after(pax.len() as u64) as usize, 0);
|
|
285
|
+
}
|
|
286
|
+
out.extend_from_slice(&block);
|
|
287
|
+
out
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/// The zero bytes that bring `size` bytes of data up to a whole block.
|
|
291
|
+
fn padding_after(size: u64) -> u64 {
|
|
292
|
+
(BLOCK as u64 - size % BLOCK as u64) % BLOCK as u64
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/// Why writing stopped.
|
|
296
|
+
#[derive(Debug)]
|
|
297
|
+
enum Fail {
|
|
298
|
+
Io(io::Error),
|
|
299
|
+
/// A file to add could not be opened. Nothing was written for it, so
|
|
300
|
+
/// the archive can go on.
|
|
301
|
+
Open(io::Error),
|
|
302
|
+
/// The caller broke the format's terms; the archive cannot go on.
|
|
303
|
+
Usage(String),
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
impl From<io::Error> for Fail {
|
|
307
|
+
fn from(e: io::Error) -> Self {
|
|
308
|
+
Fail::Io(e)
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
struct State {
|
|
313
|
+
out: Encoder,
|
|
314
|
+
/// Data the current entry is still owed, and the padding after it.
|
|
315
|
+
remaining: u64,
|
|
316
|
+
padding: u64,
|
|
317
|
+
/// The current entry's name, for messages.
|
|
318
|
+
name: String,
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
impl State {
|
|
322
|
+
fn pad(&mut self) -> io::Result<()> {
|
|
323
|
+
let zeros = [0u8; BLOCK];
|
|
324
|
+
self.out.write_all(&zeros[..self.padding as usize])?;
|
|
325
|
+
self.padding = 0;
|
|
326
|
+
Ok(())
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/// The entry before must have had all its data.
|
|
330
|
+
fn settled(&self) -> Result<(), Fail> {
|
|
331
|
+
if self.remaining > 0 {
|
|
332
|
+
return Err(Fail::Usage(format!(
|
|
333
|
+
"entry '{}' is {} bytes short of the size its header gives",
|
|
334
|
+
self.name, self.remaining
|
|
335
|
+
)));
|
|
336
|
+
}
|
|
337
|
+
Ok(())
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
fn entry(&mut self, fields: &Fields) -> Result<(), Fail> {
|
|
341
|
+
self.settled()?;
|
|
342
|
+
self.out.write_all(&headers(fields))?;
|
|
343
|
+
self.name = String::from_utf8_lossy(&fields.name).into_owned();
|
|
344
|
+
self.remaining = fields.size;
|
|
345
|
+
self.padding = padding_after(fields.size);
|
|
346
|
+
if self.remaining == 0 {
|
|
347
|
+
self.pad()?;
|
|
348
|
+
}
|
|
349
|
+
Ok(())
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
fn write(&mut self, data: &[u8]) -> Result<(), Fail> {
|
|
353
|
+
if data.len() as u64 > self.remaining {
|
|
354
|
+
return Err(Fail::Usage(format!(
|
|
355
|
+
"entry '{}' was given {} bytes more than the size its header gives",
|
|
356
|
+
self.name,
|
|
357
|
+
data.len() as u64 - self.remaining
|
|
358
|
+
)));
|
|
359
|
+
}
|
|
360
|
+
for piece in data.chunks(CHUNK) {
|
|
361
|
+
crate::gvl::check()?;
|
|
362
|
+
self.out.write_all(piece)?;
|
|
363
|
+
}
|
|
364
|
+
self.remaining -= data.len() as u64;
|
|
365
|
+
if self.remaining == 0 {
|
|
366
|
+
self.pad()?;
|
|
367
|
+
}
|
|
368
|
+
Ok(())
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/// An entry for `fields` holding the file at `path`, which is opened
|
|
372
|
+
/// before anything is written. A file that has shrunk since its size
|
|
373
|
+
/// was taken is made up with zeros, as `tar` does, so the archive
|
|
374
|
+
/// stays whole; returns the bytes it gave.
|
|
375
|
+
fn add_file(&mut self, fields: &Fields, path: &str) -> Result<u64, Fail> {
|
|
376
|
+
self.settled()?;
|
|
377
|
+
let mut file = fs::File::open(path).map_err(Fail::Open)?;
|
|
378
|
+
self.entry(fields)?;
|
|
379
|
+
let mut buf = vec![0u8; CHUNK];
|
|
380
|
+
let mut given = 0u64;
|
|
381
|
+
while self.remaining > 0 {
|
|
382
|
+
crate::gvl::check()?;
|
|
383
|
+
let want = self.remaining.min(CHUNK as u64) as usize;
|
|
384
|
+
let n = file.read(&mut buf[..want])?;
|
|
385
|
+
if n == 0 {
|
|
386
|
+
buf.fill(0);
|
|
387
|
+
while self.remaining > 0 {
|
|
388
|
+
let step = self.remaining.min(CHUNK as u64) as usize;
|
|
389
|
+
self.out.write_all(&buf[..step])?;
|
|
390
|
+
self.remaining -= step as u64;
|
|
391
|
+
}
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
self.out.write_all(&buf[..n])?;
|
|
395
|
+
self.remaining -= n as u64;
|
|
396
|
+
given += n as u64;
|
|
397
|
+
}
|
|
398
|
+
self.pad()?;
|
|
399
|
+
Ok(given)
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/// The end marker, and the end of the compressed stream.
|
|
403
|
+
fn finish(mut self) -> Result<(), Fail> {
|
|
404
|
+
self.settled()?;
|
|
405
|
+
self.out.write_all(&[0u8; 2 * BLOCK])?;
|
|
406
|
+
self.out.finish()?;
|
|
407
|
+
Ok(())
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
#[derive(TypedData)]
|
|
412
|
+
#[magnus(class = "Ziperu::Native::TarWriter", free_immediately, mark)]
|
|
413
|
+
pub struct TarWriter {
|
|
414
|
+
inner: RefCell<Option<State>>,
|
|
415
|
+
/// The Ruby IO written to, if that is what the output is.
|
|
416
|
+
io: Option<Opaque<Value>>,
|
|
417
|
+
attached: Arc<AtomicBool>,
|
|
418
|
+
/// A write failed part-way: what reached the output is not known, so
|
|
419
|
+
/// nothing more is written to it.
|
|
420
|
+
failed: Cell<bool>,
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
impl DataTypeFunctions for TarWriter {
|
|
424
|
+
fn mark(&self, marker: &Marker) {
|
|
425
|
+
if let Some(io) = self.io {
|
|
426
|
+
marker.mark(io);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
impl Drop for TarWriter {
|
|
432
|
+
fn drop(&mut self) {
|
|
433
|
+
// Before the encoder is dropped: see `RubyWrite`.
|
|
434
|
+
self.attached.store(false, Ordering::Release);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
impl TarWriter {
|
|
439
|
+
/// `compression` is "none", "gzip", "zstd", "xz" or "bzip2"; `level`
|
|
440
|
+
/// the codec's own, nil for its default.
|
|
441
|
+
pub fn open_path(
|
|
442
|
+
ruby: &Ruby,
|
|
443
|
+
path: String,
|
|
444
|
+
compression: String,
|
|
445
|
+
level: Option<u32>,
|
|
446
|
+
) -> Result<Self, Error> {
|
|
447
|
+
// A new file and nothing else: the caller picks a name for the
|
|
448
|
+
// archive in the making, and what may stand there already (a
|
|
449
|
+
// link, left by someone who guessed it) is not written through.
|
|
450
|
+
let file = fs::OpenOptions::new()
|
|
451
|
+
.write(true)
|
|
452
|
+
.create_new(true)
|
|
453
|
+
.open(&path)
|
|
454
|
+
.map_err(|e| io_error(ruby, e))?;
|
|
455
|
+
Self::start(ruby, Box::new(file), None, &compression, level)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/// Any Ruby object with `write`; it is written forward only, and
|
|
459
|
+
/// neither flushed nor closed.
|
|
460
|
+
pub fn open_io(
|
|
461
|
+
ruby: &Ruby,
|
|
462
|
+
io: Value,
|
|
463
|
+
compression: String,
|
|
464
|
+
level: Option<u32>,
|
|
465
|
+
) -> Result<Self, Error> {
|
|
466
|
+
let opaque = Opaque::from(io);
|
|
467
|
+
let attached = Arc::new(AtomicBool::new(true));
|
|
468
|
+
let out = RubyWrite {
|
|
469
|
+
io: opaque,
|
|
470
|
+
attached: Arc::clone(&attached),
|
|
471
|
+
};
|
|
472
|
+
let mut writer = Self::start(ruby, Box::new(out), Some(opaque), &compression, level)?;
|
|
473
|
+
writer.attached = attached;
|
|
474
|
+
Ok(writer)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
fn start(
|
|
478
|
+
ruby: &Ruby,
|
|
479
|
+
out: Out,
|
|
480
|
+
io: Option<Opaque<Value>>,
|
|
481
|
+
compression: &str,
|
|
482
|
+
level: Option<u32>,
|
|
483
|
+
) -> Result<Self, Error> {
|
|
484
|
+
let out: Out = Box::new(BufWriter::with_capacity(CHUNK, out));
|
|
485
|
+
let out = Encoder::new(out, compression, level).map_err(|e| {
|
|
486
|
+
if e.kind() == io::ErrorKind::InvalidInput {
|
|
487
|
+
Error::new(ruby.exception_arg_error(), e.to_string())
|
|
488
|
+
} else {
|
|
489
|
+
io_error(ruby, e)
|
|
490
|
+
}
|
|
491
|
+
})?;
|
|
492
|
+
Ok(Self {
|
|
493
|
+
inner: RefCell::new(Some(State {
|
|
494
|
+
out,
|
|
495
|
+
remaining: 0,
|
|
496
|
+
padding: 0,
|
|
497
|
+
name: String::new(),
|
|
498
|
+
})),
|
|
499
|
+
io,
|
|
500
|
+
attached: Arc::new(AtomicBool::new(true)),
|
|
501
|
+
failed: Cell::new(false),
|
|
502
|
+
})
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
fn state(&self, ruby: &Ruby) -> Result<RefMut<'_, State>, Error> {
|
|
506
|
+
if self.failed.get() {
|
|
507
|
+
return Err(Error::new(
|
|
508
|
+
ruby.exception_io_error(),
|
|
509
|
+
"the tar writer failed earlier and cannot go on",
|
|
510
|
+
));
|
|
511
|
+
}
|
|
512
|
+
let guard = self
|
|
513
|
+
.inner
|
|
514
|
+
.try_borrow_mut()
|
|
515
|
+
.map_err(|_| busy_error(ruby, "tar writer"))?;
|
|
516
|
+
RefMut::filter_map(guard, Option::as_mut)
|
|
517
|
+
.map_err(|_| Error::new(ruby.exception_io_error(), "closed stream"))
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
fn raise(&self, ruby: &Ruby, fail: Fail) -> Error {
|
|
521
|
+
match fail {
|
|
522
|
+
Fail::Open(e) => io_error(ruby, e),
|
|
523
|
+
Fail::Usage(why) => {
|
|
524
|
+
self.failed.set(true);
|
|
525
|
+
Error::new(ruby.get_inner(&ERROR), why)
|
|
526
|
+
}
|
|
527
|
+
Fail::Io(e) => {
|
|
528
|
+
self.failed.set(true);
|
|
529
|
+
io_error(ruby, e)
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/// Runs `work` on the state, with the GVL released unless the output
|
|
535
|
+
/// is a Ruby IO. A failure is final.
|
|
536
|
+
fn run<T>(
|
|
537
|
+
&self,
|
|
538
|
+
ruby: &Ruby,
|
|
539
|
+
work: impl FnOnce(&mut State) -> Result<T, Fail>,
|
|
540
|
+
) -> Result<T, Error> {
|
|
541
|
+
let mut state = self.state(ruby)?;
|
|
542
|
+
let outcome = maybe_without_gvl(self.io.is_some(), || work(&mut state));
|
|
543
|
+
drop(state);
|
|
544
|
+
outcome.map_err(|fail| self.raise(ruby, fail))
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/// Starts an entry: `[name, link, flag, size, mode, mtime, uid, gid,
|
|
548
|
+
/// uname, gname]`, the names as bytes, `flag` the type's character
|
|
549
|
+
/// code, `mtime` in whole seconds.
|
|
550
|
+
pub fn entry(ruby: &Ruby, rb_self: &Self, spec: RArray) -> Result<(), Error> {
|
|
551
|
+
let fields = Self::fields(spec)?;
|
|
552
|
+
rb_self.run(ruby, |state| state.entry(&fields))
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
fn fields(spec: RArray) -> Result<Fields, Error> {
|
|
556
|
+
let bytes = |i: isize| -> Result<Vec<u8>, Error> {
|
|
557
|
+
let s: RString = spec.entry(i)?;
|
|
558
|
+
// SAFETY: the bytes are copied before any Ruby call can move
|
|
559
|
+
// or change the string.
|
|
560
|
+
Ok(unsafe { s.as_slice() }.to_vec())
|
|
561
|
+
};
|
|
562
|
+
Ok(Fields {
|
|
563
|
+
name: bytes(0)?,
|
|
564
|
+
link: bytes(1)?,
|
|
565
|
+
flag: spec.entry(2)?,
|
|
566
|
+
size: spec.entry(3)?,
|
|
567
|
+
mode: spec.entry(4)?,
|
|
568
|
+
mtime: spec.entry(5)?,
|
|
569
|
+
uid: spec.entry(6)?,
|
|
570
|
+
gid: spec.entry(7)?,
|
|
571
|
+
uname: bytes(8)?,
|
|
572
|
+
gname: bytes(9)?,
|
|
573
|
+
})
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/// Data for the current entry.
|
|
577
|
+
pub fn write(ruby: &Ruby, rb_self: &Self, data: RString) -> Result<usize, Error> {
|
|
578
|
+
// SAFETY: copied before the GVL is released or Ruby is called.
|
|
579
|
+
let data = unsafe { data.as_slice() }.to_vec();
|
|
580
|
+
rb_self.run(ruby, |state| state.write(&data))?;
|
|
581
|
+
Ok(data.len())
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/// An entry (`spec` as for `entry`) with the file at `path` for its
|
|
585
|
+
/// data. Returns how many bytes the file gave (see `State::add_file`).
|
|
586
|
+
/// A file that cannot be opened raises with nothing written.
|
|
587
|
+
pub fn add_file(ruby: &Ruby, rb_self: &Self, spec: RArray, path: String) -> Result<u64, Error> {
|
|
588
|
+
let fields = Self::fields(spec)?;
|
|
589
|
+
rb_self.run(ruby, |state| state.add_file(&fields, &path))
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/// Ends the archive. Nothing can be written afterwards.
|
|
593
|
+
pub fn close(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
|
|
594
|
+
rb_self.state(ruby)?;
|
|
595
|
+
let state = rb_self
|
|
596
|
+
.inner
|
|
597
|
+
.try_borrow_mut()
|
|
598
|
+
.map_err(|_| busy_error(ruby, "tar writer"))?
|
|
599
|
+
.take();
|
|
600
|
+
let Some(state) = state else {
|
|
601
|
+
return Ok(());
|
|
602
|
+
};
|
|
603
|
+
let outcome = maybe_without_gvl(rb_self.io.is_some(), || state.finish());
|
|
604
|
+
outcome.map_err(|fail| rb_self.raise(ruby, fail))
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/// Lets go of the output without ending the archive: what follows a
|
|
608
|
+
/// failure, when what was written is to be thrown away.
|
|
609
|
+
pub fn abandon(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
|
|
610
|
+
rb_self.attached.store(false, Ordering::Release);
|
|
611
|
+
rb_self
|
|
612
|
+
.inner
|
|
613
|
+
.try_borrow_mut()
|
|
614
|
+
.map_err(|_| busy_error(ruby, "tar writer"))?
|
|
615
|
+
.take();
|
|
616
|
+
Ok(())
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
#[cfg(test)]
|
|
621
|
+
mod tests {
|
|
622
|
+
use super::*;
|
|
623
|
+
|
|
624
|
+
fn fields(name: &[u8], flag: u8, size: u64) -> Fields {
|
|
625
|
+
Fields {
|
|
626
|
+
name: name.to_vec(),
|
|
627
|
+
link: Vec::new(),
|
|
628
|
+
flag,
|
|
629
|
+
size,
|
|
630
|
+
mode: 0o644,
|
|
631
|
+
mtime: 1_700_000_000,
|
|
632
|
+
uid: 0,
|
|
633
|
+
gid: 0,
|
|
634
|
+
uname: Vec::new(),
|
|
635
|
+
gname: Vec::new(),
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
#[test]
|
|
640
|
+
fn writes_numbers_that_fit_and_says_when_they_do_not() {
|
|
641
|
+
let mut field = [0xffu8; 8];
|
|
642
|
+
assert!(octal(&mut field, 0o644));
|
|
643
|
+
assert_eq!(&field, b"0000644\0");
|
|
644
|
+
assert!(octal(&mut field, 0o7777777));
|
|
645
|
+
assert!(!octal(&mut field, 0o10000000));
|
|
646
|
+
assert_eq!(&field, b"0000000\0");
|
|
647
|
+
let mut size = [0u8; 12];
|
|
648
|
+
assert!(octal(&mut size, (8 << 30) - 1));
|
|
649
|
+
assert_eq!(&size, b"77777777777\0");
|
|
650
|
+
assert!(!octal(&mut size, 8 << 30));
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
#[test]
|
|
654
|
+
fn a_record_counts_its_own_length() {
|
|
655
|
+
assert_eq!(
|
|
656
|
+
pax_record("path", b"a"),
|
|
657
|
+
b"9 path=a
|
|
658
|
+
"
|
|
659
|
+
);
|
|
660
|
+
// Nine bytes and one digit would make ten, which takes two digits.
|
|
661
|
+
assert_eq!(
|
|
662
|
+
pax_record("path", b"ab"),
|
|
663
|
+
b"11 path=ab
|
|
664
|
+
"
|
|
665
|
+
);
|
|
666
|
+
assert_eq!(
|
|
667
|
+
pax_record("p", b"abcd"),
|
|
668
|
+
b"9 p=abcd
|
|
669
|
+
"
|
|
670
|
+
);
|
|
671
|
+
for len in 0..1200 {
|
|
672
|
+
let record = pax_record("path", &vec![b'x'; len]);
|
|
673
|
+
let stated: usize =
|
|
674
|
+
std::str::from_utf8(&record[..record.iter().position(|&b| b == b' ').unwrap()])
|
|
675
|
+
.unwrap()
|
|
676
|
+
.parse()
|
|
677
|
+
.unwrap();
|
|
678
|
+
assert_eq!(stated, record.len(), "value of {len} bytes");
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
#[test]
|
|
683
|
+
fn an_ordinary_entry_is_one_ustar_block() {
|
|
684
|
+
let out = headers(&fields(b"dir/file.txt", b'0', 5));
|
|
685
|
+
assert_eq!(out.len(), BLOCK);
|
|
686
|
+
assert_eq!(&out[..12], b"dir/file.txt");
|
|
687
|
+
assert_eq!(&out[257..265], b"ustar\x0000");
|
|
688
|
+
assert_eq!(&out[124..136], b"00000000005\0");
|
|
689
|
+
let sum: u32 = out
|
|
690
|
+
.iter()
|
|
691
|
+
.enumerate()
|
|
692
|
+
.map(|(i, &b)| {
|
|
693
|
+
if (148..156).contains(&i) {
|
|
694
|
+
32
|
|
695
|
+
} else {
|
|
696
|
+
u32::from(b)
|
|
697
|
+
}
|
|
698
|
+
})
|
|
699
|
+
.sum();
|
|
700
|
+
assert_eq!(&out[148..156], format!("{sum:06o}\0 ").as_bytes());
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
#[test]
|
|
704
|
+
fn what_does_not_fit_goes_in_an_extended_header() {
|
|
705
|
+
let long = vec![b'n'; 150];
|
|
706
|
+
let out = headers(&fields(&long, b'0', 0));
|
|
707
|
+
assert_eq!(out.len(), 3 * BLOCK);
|
|
708
|
+
assert_eq!(out[156], b'x');
|
|
709
|
+
assert!(out[BLOCK..].starts_with(b"160 path=nnn"));
|
|
710
|
+
assert_eq!(out[2 * BLOCK + 156], b'0');
|
|
711
|
+
|
|
712
|
+
let mut f = fields("h\u{e9}llo".as_bytes(), b'0', 8 << 30);
|
|
713
|
+
f.mtime = -5;
|
|
714
|
+
f.uid = 3_000_000_000;
|
|
715
|
+
let out = headers(&f);
|
|
716
|
+
let records = String::from_utf8_lossy(&out[BLOCK..2 * BLOCK]).into_owned();
|
|
717
|
+
for wanted in [
|
|
718
|
+
"path=h\u{e9}llo\n",
|
|
719
|
+
"uid=3000000000\n",
|
|
720
|
+
"size=8589934592\n",
|
|
721
|
+
"mtime=-5\n",
|
|
722
|
+
] {
|
|
723
|
+
assert!(records.contains(wanted), "{wanted} in {records}");
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
#[test]
|
|
728
|
+
fn a_cut_name_does_not_end_in_a_slash() {
|
|
729
|
+
let mut name = vec![b'd'; 99];
|
|
730
|
+
name.extend(b"/file.txt");
|
|
731
|
+
let out = headers(&fields(&name, b'0', 0));
|
|
732
|
+
let block = &out[2 * BLOCK..];
|
|
733
|
+
assert_eq!(&block[..99], &name[..99]);
|
|
734
|
+
assert_eq!(block[99], 0);
|
|
735
|
+
}
|
|
736
|
+
}
|