tarzan 0.4.0

Random-access, seekable .tar.zst archives with an embedded table-of-contents index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Tests for TarzanReader::extract_member and verify_all/verify_member.

use std::io::Cursor;

use tarzan::{ExtractOptions, TarzanReader, VerifyStatus, WrapOptions};
use tempfile::tempdir;

fn make_tar<F: FnOnce(&mut tar::Builder<Vec<u8>>)>(f: F) -> Vec<u8> {
    let mut builder = tar::Builder::new(Vec::new());
    f(&mut builder);
    builder
        .into_inner()
        .expect("failed to finalise tar builder")
}

fn wrap_to_file(raw: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempdir().expect("tempdir");
    let path = dir.path().join("archive.tar.zst");
    let mut f = std::fs::File::create(&path).unwrap();
    tarzan::wrap(Cursor::new(raw), &mut f, WrapOptions::default()).expect("wrap");
    (dir, path)
}

fn single_file_tar(path: &str, content: &[u8]) -> Vec<u8> {
    make_tar(|b| {
        let mut h = tar::Header::new_gnu();
        h.set_path(path).unwrap();
        h.set_size(content.len() as u64);
        h.set_mode(0o644);
        h.set_uid(0);
        h.set_gid(0);
        h.set_mtime(0);
        h.set_cksum();
        b.append(&h, Cursor::new(content)).unwrap();
    })
}

#[test]
fn extract_member_returns_correct_bytes() {
    let content = b"hello from tarzan cat!";
    let raw = single_file_tar("hello.txt", content);
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let mut out = Vec::new();
    reader
        .extract_member("hello.txt", &mut out)
        .expect("extract");
    assert_eq!(out, content);
}

#[test]
fn extract_member_empty_file_yields_empty_bytes() {
    let raw = single_file_tar("empty.txt", b"");
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let mut out = Vec::new();
    reader
        .extract_member("empty.txt", &mut out)
        .expect("extract");
    assert!(out.is_empty());
}

#[test]
fn extract_member_binary_content_exact() {
    let content: Vec<u8> = (0u8..=255).collect();
    let raw = single_file_tar("binary.bin", &content);
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let mut out = Vec::new();
    reader
        .extract_member("binary.bin", &mut out)
        .expect("extract");
    assert_eq!(out, content);
}

#[test]
fn extract_member_second_entry_correct() {
    let raw = make_tar(|b| {
        for (name, content) in [("a.txt", b"aaaa".as_slice()), ("b.txt", b"bbbbbb")] {
            let mut h = tar::Header::new_gnu();
            h.set_path(name).unwrap();
            h.set_size(content.len() as u64);
            h.set_mode(0o644);
            h.set_uid(0);
            h.set_gid(0);
            h.set_mtime(0);
            h.set_cksum();
            b.append(&h, Cursor::new(content)).unwrap();
        }
    });
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");

    let mut out_a = Vec::new();
    reader
        .extract_member("a.txt", &mut out_a)
        .expect("extract a");
    assert_eq!(out_a, b"aaaa");

    let mut out_b = Vec::new();
    reader
        .extract_member("b.txt", &mut out_b)
        .expect("extract b");
    assert_eq!(out_b, b"bbbbbb");
}

#[test]
fn extract_member_checks_zstd_frame_trailer() {
    let raw = single_file_tar("hello.txt", b"hello from tarzan cat!");
    let (dir, path) = wrap_to_file(&raw);

    let reader = TarzanReader::open(&path).expect("open");
    let chunk = reader
        .members()
        .iter()
        .find(|m| m.path == "hello.txt")
        .expect("member present")
        .chunks[0]
        .clone();

    let mut archive = std::fs::read(&path).expect("read archive");
    let checksum_byte = (chunk.compressed_offset + chunk.compressed_size - 1) as usize;
    archive[checksum_byte] ^= 0xff;

    let corrupted_path = dir.path().join("corrupted.tar.zst");
    std::fs::write(&corrupted_path, archive).expect("write corrupted archive");

    let mut reader = TarzanReader::open(&corrupted_path).expect("open corrupted archive");
    let mut out = Vec::new();
    let result = reader.extract_member("hello.txt", &mut out);
    assert!(
        result.is_err(),
        "extract_member should reject a corrupted zstd frame trailer"
    );
}

#[test]
fn extract_member_missing_path_errors() {
    let raw = single_file_tar("exists.txt", b"data");
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let mut out = Vec::new();
    let result = reader.extract_member("does_not_exist.txt", &mut out);
    assert!(result.is_err(), "expected error for missing path");
}

#[test]
fn verify_all_passes_for_freshly_wrapped_archive() {
    let raw = make_tar(|b| {
        for (name, content) in [("a.txt", b"aaa".as_slice()), ("b.txt", b"bbb")] {
            let mut h = tar::Header::new_gnu();
            h.set_path(name).unwrap();
            h.set_size(content.len() as u64);
            h.set_mode(0o644);
            h.set_uid(0);
            h.set_gid(0);
            h.set_mtime(0);
            h.set_cksum();
            b.append(&h, Cursor::new(content)).unwrap();
        }
    });
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let results = reader.verify_all().expect("verify");

    assert!(!results.is_empty(), "expected at least one verify record");
    for r in &results {
        assert!(
            matches!(r.status, VerifyStatus::Ok),
            "expected Ok for {}; got mismatch or no-checksum",
            r.path
        );
    }
}

#[test]
fn verify_member_passes_for_specific_file() {
    let raw = single_file_tar("check.txt", b"verify me");
    let (_dir, path) = wrap_to_file(&raw);

    let mut reader = TarzanReader::open(&path).expect("open");
    let results = reader.verify_member("check.txt").expect("verify");

    assert!(!results.is_empty());
    assert!(matches!(results[0].status, VerifyStatus::Ok));
}

#[test]
fn content_sha256_matches_sha256sum() {
    use sha2::{Digest, Sha256};
    let content = b"this is the file body";
    let raw = single_file_tar("hello.txt", content);
    let (_dir, path) = wrap_to_file(&raw);

    let reader = TarzanReader::open(&path).expect("open");
    let m = reader
        .members()
        .iter()
        .find(|m| m.path == "hello.txt")
        .expect("member present");

    let recorded = m
        .content_sha256
        .as_ref()
        .expect("regular files must record content_sha256");
    let expected: String = Sha256::digest(content)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();
    assert_eq!(*recorded, expected);
}

#[test]
fn content_sha256_matches_for_large_member_spanning_chunks() {
    // chunk_size=4 KiB and a 16 KiB body forces the wrap into the large path
    // with multiple chunks; the streaming hasher must aggregate them correctly.
    use sha2::{Digest, Sha256};
    let content: Vec<u8> = (0..16 * 1024).map(|i| (i % 251) as u8).collect();
    let raw = single_file_tar("big.bin", &content);

    let dir = tempdir().expect("tempdir");
    let path = dir.path().join("archive.tar.zst");
    let f = std::fs::File::create(&path).unwrap();
    tarzan::wrap(
        Cursor::new(&raw),
        f,
        tarzan::WrapOptions::default().chunk_size(4 * 1024),
    )
    .expect("wrap");

    let reader = TarzanReader::open(&path).expect("open");
    let m = reader
        .members()
        .iter()
        .find(|m| m.path == "big.bin")
        .unwrap();
    assert!(m.chunks.len() > 1, "large member should span >1 chunk");

    let recorded = m.content_sha256.as_ref().expect("hash must be present");
    let expected: String = Sha256::digest(&content)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();
    assert_eq!(*recorded, expected);
}

#[test]
fn content_md5_matches_for_small_member() {
    let content = b"this is the file body";
    let raw = single_file_tar("hello.txt", content);
    let (_dir, path) = wrap_to_file(&raw);

    let reader = TarzanReader::open(&path).expect("open");
    let m = reader
        .members()
        .iter()
        .find(|m| m.path == "hello.txt")
        .expect("member present");

    let recorded = m
        .content_md5
        .as_ref()
        .expect("regular files must record content_md5");
    let expected = format!("{:x}", md5::compute(content));
    assert_eq!(*recorded, expected);
}

#[test]
fn content_md5_matches_for_large_member_spanning_chunks() {
    // chunk_size=4 KiB and a 16 KiB body forces the wrap into the large-member
    // streaming path; the md5::Context must accumulate all chunks correctly.
    let content: Vec<u8> = (0..16 * 1024).map(|i| (i % 251) as u8).collect();
    let raw = single_file_tar("big.bin", &content);

    let dir = tempdir().expect("tempdir");
    let path = dir.path().join("archive.tar.zst");
    let f = std::fs::File::create(&path).unwrap();
    tarzan::wrap(
        Cursor::new(&raw),
        f,
        tarzan::WrapOptions::default().chunk_size(4 * 1024),
    )
    .expect("wrap");

    let reader = TarzanReader::open(&path).expect("open");
    let m = reader
        .members()
        .iter()
        .find(|m| m.path == "big.bin")
        .unwrap();
    assert!(m.chunks.len() > 1, "large member should span >1 chunk");

    let recorded = m.content_md5.as_ref().expect("hash must be present");
    let expected = format!("{:x}", md5::compute(&content));
    assert_eq!(*recorded, expected);
}

// ── --skip-bad-chunks: corruption survival ───────────────────────────────────

/// Wraps three small files with a chunk size that forces each member into its
/// own zstd frame, returns the archive path and the corruption target's chunk
/// info. Each file's region (512-byte tar header + 512-byte padded content)
/// is 1024 bytes; chunk_size = 1500 makes the group flush after every
/// member, so a single zstd frame holds exactly one member.
fn wrap_three_isolated_files(
    dir: &std::path::Path,
) -> (std::path::PathBuf, tarzan::format::toc::ChunkInfo) {
    let raw = make_tar(|b| {
        for (i, name) in ["a.txt", "b.txt", "c.txt"].iter().enumerate() {
            // Distinct content per file so we can't get a false pass by
            // accidentally reading another file's bytes.
            let content: Vec<u8> = (0..100u8).map(|x| x.wrapping_add(i as u8 * 17)).collect();
            let mut h = tar::Header::new_gnu();
            h.set_path(name).unwrap();
            h.set_size(content.len() as u64);
            h.set_mode(0o644);
            h.set_uid(0);
            h.set_gid(0);
            h.set_mtime(0);
            h.set_cksum();
            b.append(&h, Cursor::new(content)).unwrap();
        }
    });
    let archive_path = dir.join("archive.tar.zst");
    let f = std::fs::File::create(&archive_path).unwrap();
    tarzan::wrap(
        Cursor::new(&raw),
        f,
        WrapOptions::default().chunk_size(1500),
    )
    .expect("wrap");

    let reader = TarzanReader::open(&archive_path).expect("open");
    let members: Vec<_> = reader.members().to_vec();
    let target = members.iter().find(|m| m.path == "b.txt").unwrap();
    assert_eq!(
        target.chunks.len(),
        1,
        "b.txt should be in exactly one chunk"
    );
    let a_off = members[0].chunks[0].compressed_offset;
    let b_off = target.chunks[0].compressed_offset;
    let c_off = members[2].chunks[0].compressed_offset;
    assert!(
        a_off != b_off && b_off != c_off,
        "test precondition: each of a/b/c.txt must be in its own frame; \
         got offsets a={a_off} b={b_off} c={c_off}"
    );

    (archive_path, target.chunks[0].clone())
}

fn clobber_frame(archive_path: &std::path::Path, chunk: &tarzan::format::toc::ChunkInfo) {
    let mut bytes = std::fs::read(archive_path).unwrap();
    let start = chunk.compressed_offset as usize;
    let end = start + chunk.compressed_size as usize;
    for b in &mut bytes[start..end] {
        *b = 0;
    }
    std::fs::write(archive_path, &bytes).unwrap();
}

#[test]
fn extract_without_skip_bad_chunks_fails_on_corrupted_frame() {
    let dir = tempdir().expect("tempdir");
    let (archive, b_chunk) = wrap_three_isolated_files(dir.path());
    clobber_frame(&archive, &b_chunk);

    let out = dir.path().join("out");
    let mut reader = TarzanReader::open(&archive).expect("open after corruption");
    let result = reader.extract_to_dir(&out, &ExtractOptions::default(), |_| {});
    assert!(
        result.is_err(),
        "extract should fail when a chunk is unreadable and skip_bad_chunks is off"
    );
}

#[test]
fn extract_with_skip_bad_chunks_recovers_good_files() {
    let dir = tempdir().expect("tempdir");
    let (archive, b_chunk) = wrap_three_isolated_files(dir.path());
    clobber_frame(&archive, &b_chunk);

    let out = dir.path().join("out");
    let mut reader = TarzanReader::open(&archive).expect("open after corruption");
    let opts = ExtractOptions {
        skip_bad_chunks: true,
        ..ExtractOptions::default()
    };
    reader
        .extract_to_dir(&out, &opts, |_| {})
        .expect("extract should succeed with --skip-bad-chunks");

    assert!(out.join("a.txt").exists(), "a.txt should be extracted");
    assert!(
        !out.join("b.txt").exists(),
        "b.txt should be removed after its chunk failed"
    );
    assert!(out.join("c.txt").exists(), "c.txt should be extracted");

    // The good files should contain the bytes we wrote during wrap.
    let a = std::fs::read(out.join("a.txt")).unwrap();
    let c = std::fs::read(out.join("c.txt")).unwrap();
    let expected_a: Vec<u8> = (0..100u8).collect();
    let expected_c: Vec<u8> = (0..100u8).map(|x| x.wrapping_add(34)).collect();
    assert_eq!(a, expected_a);
    assert_eq!(c, expected_c);
}