team-ljyzipelo

공개

ZIP64 호환 표본과 목록 해제 회귀 시험 추가

작성자
코노모리 카논
작성 시각
커밋
b2fe2b8096756163f5dc0b419a9f24778a1cfcd0
부모
09de05b
이 시점의 파일 보기

변경된 파일 7개

+603-0
추가tests/rust-zip64-compat/.gitignore+2-0
@@ -0,0 +1,2 @@
1추가: /runs/
2추가: /target/
추가tests/rust-zip64-compat/Cargo.lock+187-0
@@ -0,0 +1,187 @@
1추가: # This file is automatically @generated by Cargo.
2추가: # It is not intended for manual editing.
3추가: version = 4
4추가:
5추가: [[package]]
6추가: name = "aes"
7추가: version = "0.8.4"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
10추가: dependencies = [
11추가: "cfg-if",
12추가: "cipher",
13추가: "cpufeatures",
14추가: "zeroize",
15추가: ]
16추가:
17추가: [[package]]
18추가: name = "block-buffer"
19추가: version = "0.10.4"
20추가: source = "registry+https://github.com/rust-lang/crates.io-index"
21추가: checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
22추가: dependencies = [
23추가: "generic-array",
24추가: ]
25추가:
26추가: [[package]]
27추가: name = "cfg-if"
28추가: version = "1.0.5"
29추가: source = "registry+https://github.com/rust-lang/crates.io-index"
30추가: checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
31추가:
32추가: [[package]]
33추가: name = "cipher"
34추가: version = "0.4.4"
35추가: source = "registry+https://github.com/rust-lang/crates.io-index"
36추가: checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
37추가: dependencies = [
38추가: "crypto-common",
39추가: "inout",
40추가: ]
41추가:
42추가: [[package]]
43추가: name = "cpufeatures"
44추가: version = "0.2.17"
45추가: source = "registry+https://github.com/rust-lang/crates.io-index"
46추가: checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
47추가: dependencies = [
48추가: "libc",
49추가: ]
50추가:
51추가: [[package]]
52추가: name = "crypto-common"
53추가: version = "0.1.7"
54추가: source = "registry+https://github.com/rust-lang/crates.io-index"
55추가: checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
56추가: dependencies = [
57추가: "generic-array",
58추가: "typenum",
59추가: ]
60추가:
61추가: [[package]]
62추가: name = "digest"
63추가: version = "0.10.7"
64추가: source = "registry+https://github.com/rust-lang/crates.io-index"
65추가: checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
66추가: dependencies = [
67추가: "block-buffer",
68추가: "crypto-common",
69추가: "subtle",
70추가: ]
71추가:
72추가: [[package]]
73추가: name = "generic-array"
74추가: version = "0.14.7"
75추가: source = "registry+https://github.com/rust-lang/crates.io-index"
76추가: checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
77추가: dependencies = [
78추가: "typenum",
79추가: "version_check",
80추가: ]
81추가:
82추가: [[package]]
83추가: name = "hmac"
84추가: version = "0.12.1"
85추가: source = "registry+https://github.com/rust-lang/crates.io-index"
86추가: checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
87추가: dependencies = [
88추가: "digest",
89추가: ]
90추가:
91추가: [[package]]
92추가: name = "inout"
93추가: version = "0.1.4"
94추가: source = "registry+https://github.com/rust-lang/crates.io-index"
95추가: checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
96추가: dependencies = [
97추가: "generic-array",
98추가: ]
99추가:
100추가: [[package]]
101추가: name = "libc"
102추가: version = "0.2.191"
103추가: source = "registry+https://github.com/rust-lang/crates.io-index"
104추가: checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
105추가:
106추가: [[package]]
107추가: name = "pbkdf2"
108추가: version = "0.12.2"
109추가: source = "registry+https://github.com/rust-lang/crates.io-index"
110추가: checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
111추가: dependencies = [
112추가: "digest",
113추가: "hmac",
114추가: ]
115추가:
116추가: [[package]]
117추가: name = "sha1"
118추가: version = "0.10.7"
119추가: source = "registry+https://github.com/rust-lang/crates.io-index"
120추가: checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
121추가: dependencies = [
122추가: "cfg-if",
123추가: "cpufeatures",
124추가: "digest",
125추가: ]
126추가:
127추가: [[package]]
128추가: name = "sha2"
129추가: version = "0.10.9"
130추가: source = "registry+https://github.com/rust-lang/crates.io-index"
131추가: checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
132추가: dependencies = [
133추가: "cfg-if",
134추가: "cpufeatures",
135추가: "digest",
136추가: ]
137추가:
138추가: [[package]]
139추가: name = "subtle"
140추가: version = "2.6.1"
141추가: source = "registry+https://github.com/rust-lang/crates.io-index"
142추가: checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
143추가:
144추가: [[package]]
145추가: name = "typenum"
146추가: version = "1.20.1"
147추가: source = "registry+https://github.com/rust-lang/crates.io-index"
148추가: checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
149추가:
150추가: [[package]]
151추가: name = "version_check"
152추가: version = "0.9.5"
153추가: source = "registry+https://github.com/rust-lang/crates.io-index"
154추가: checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
155추가:
156추가: [[package]]
157추가: name = "zeroize"
158추가: version = "1.9.1"
159추가: source = "registry+https://github.com/rust-lang/crates.io-index"
160추가: checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
161추가:
162추가: [[package]]
163추가: name = "zipelo-archive-worker"
164추가: version = "0.1.0"
165추가: dependencies = [
166추가: "aes",
167추가: "hmac",
168추가: "pbkdf2",
169추가: "sha1",
170추가: "sha2",
171추가: "subtle",
172추가: "zeroize",
173추가: "zlib-rs",
174추가: ]
175추가:
176추가: [[package]]
177추가: name = "zipelo-zip64-compat"
178추가: version = "0.1.0"
179추가: dependencies = [
180추가: "zipelo-archive-worker",
181추가: ]
182추가:
183추가: [[package]]
184추가: name = "zlib-rs"
185추가: version = "0.6.8"
186추가: source = "registry+https://github.com/rust-lang/crates.io-index"
187추가: checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
추가tests/rust-zip64-compat/Cargo.toml+22-0
@@ -0,0 +1,22 @@
1추가: [package]
2추가: name = "zipelo-zip64-compat"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: license = "MIT"
6추가: publish = false
7추가: autotests = false
8추가:
9추가: [workspace]
10추가:
11추가: [dependencies]
12추가: zipelo-archive-worker = { path = "../../experiments/rust-archive-worker" }
13추가:
14추가: [[bin]]
15추가: name = "zip64-test-worker"
16추가: path = "worker.rs"
17추가: test = false
18추가: bench = false
19추가:
20추가: [[test]]
21추가: name = "zip64_corpus"
22추가: path = "corpus.rs"
추가tests/rust-zip64-compat/README.md+51-0
@@ -0,0 +1,51 @@
1추가: # ZIP64 호환 표본
2추가:
3추가: PR74의 스트리밍 작업자를 실제 자식 프로세스로 실행해 모든 표본의 목록과 해제를 확인함.
4추가: 제품 구현 변경 없이 별도 시험 crate에서 공개 runtime과 wire codec을 사용함.
5추가: 표본과 결과는 실행 시 runs/에 생성하며 저장소에는 압축파일을 넣지 않음.
6추가:
7추가: ## 구성
8추가:
9추가: 총 1066개이며 모든 기대 결과는 목록과 해제 성공임.
10추가:
11추가: - 원본 5개: Python 일반 ZIP, Python force_zip64의 탐색 가능/불가능 출력, libarchive zip64=1, Info-ZIP -fz 일반 파일 출력.
12추가: - 필드 조합 1024개: 중앙 디렉터리의 원래 크기, 압축 크기, 로컬 오프셋, 시작 디스크 번호 16조합과 EOCD의 현재 디스크, 중앙 시작 디스크, 디스크 내 항목 수, 전체 항목 수, 중앙 크기, 중앙 오프셋 64조합의 곱.
13추가: - 로컬 크기 두 필드가 함께 확장된 중앙 필드 조합 16개.
14추가: - ZIP64 종료 레코드 없이 중앙 필드만 확장한 조합 16개.
15추가: - 기존 회귀 표본 5개: 260바이트 강제 ZIP64, 서명 유무별 오프셋 전용 32비트 디스크립터, EOCD 디스크 번호 확장, 중앙 시작 디스크 번호 확장.
16추가:
17추가: fields-cXX-eYY의 마스크 비트는 위 필드 나열 순서이며 최하위 비트부터 적용함.
18추가: 디스크 번호의 실제 값은 항상 0이고 항목 수는 1임.
19추가: 4 GiB 파일을 만들지 않고 sentinel을 사용해 작은 값의 확장 표현을 검사함.
20추가: 실제 4 GiB 초과 오프셋, 다중 볼륨, 암호 ZIP은 이 묶음의 범위가 아님.
21추가:
22추가: [APPNOTE 6.3.10](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)의
23추가: 4.4.13, 4.4.19~4.4.24, 4.5.3을 기준으로 대응 필드가 sentinel인 경우에만
24추가: 중앙 ZIP64 확장값을 순서대로 넣음. 로컬 크기 확장은 두 크기 값을 함께 넣음.
25추가: 도구 원본과 수동 필드 변형은 provenance.json에서 구분함.
26추가: Info-ZIP은 -fz와 stdout을 함께 사용할 때 이 환경에서 손상된 종료 레코드를 만들므로
27추가: 정상 일반 파일 출력에 -fz를 적용함.
28추가:
29추가: ## 실행과 판정
30추가:
31추가: Linux에서 Python 3, Info-ZIP zip, 시스템 libarchive가 필요함.
32추가: 누락된 도구나 참조 판독 실패는 성공으로 건너뛰지 않음.
33추가: 제품의 추가 의존성은 없음.
34추가:
35추가: ```sh
36추가: cargo +1.99.1 test --manifest-path tests/rust-zip64-compat/Cargo.toml --locked -- --nocapture
37추가: python3 tests/ci/run_rust.py local
38추가: ```
39추가:
40추가: 지정 실행기는 tests/*/Cargo.toml을 검색하므로 별도 실행기 설정 없이 포함됨.
41추가: Windows 교차 빌드는 수행하지만 이 표본 실행 시험은 Linux 전용임.
42추가:
43추가: Python zipfile로 전체 표본의 내용과 CRC를 먼저 확인함.
44추가: 작업자 목록의 이름, 크기, ListId와 해제 결과의 전체 바이트, 게시 수, 정리 상태를 확인함.
45추가: 일부 표본이 실패해도 나머지를 계속 실행하고 마지막에 시험을 실패시킴.
46추가: runs/<실행 ID>/results.tsv에 모든 표본의 목록/해제 결과가 남음.
47추가: 같은 위치의 corpus/provenance.json에는 도구 버전과 표본 출처가 남음.
48추가:
49추가: ZIPELO_ZIP64_WORKER 환경 변수로 비교할 작업자 실행 파일을 지정할 수 있음.
50추가: 기본값은 같은 worker 의존성으로 빌드한 zip64-test-worker임.
51추가: 이 환경 변수는 시험 코드에만 적용되며 제품 작업자에는 적용되지 않음.
추가tests/rust-zip64-compat/corpus.rs+161-0
@@ -0,0 +1,161 @@
1추가: #![cfg(target_os = "linux")]
2추가:
3추가: use std::{
4추가: fs,
5추가: io::Write,
6추가: path::{Path, PathBuf},
7추가: process::{Command, Stdio},
8추가: time::{SystemTime, UNIX_EPOCH},
9추가: };
10추가: use zipelo_archive_worker::{
11추가: protocol::*,
12추가: wire::{Reader, Writer},
13추가: };
14추가:
15추가: fn execute(action: Action) -> Vec<Message> {
16추가: let mut request = Vec::new();
17추가: Writer::new(&mut request, 17)
18추가: .send(&Message::Start(Start {
19추가: action,
20추가: limits: Limits::default(),
21추가: }))
22추가: .unwrap();
23추가: let worker = std::env::var_os("ZIPELO_ZIP64_WORKER")
24추가: .unwrap_or_else(|| env!("CARGO_BIN_EXE_zip64-test-worker").into());
25추가: let mut child = Command::new(worker)
26추가: .stdin(Stdio::piped())
27추가: .stdout(Stdio::piped())
28추가: .stderr(Stdio::piped())
29추가: .spawn()
30추가: .unwrap();
31추가: child.stdin.take().unwrap().write_all(&request).unwrap();
32추가: let output = child.wait_with_output().unwrap();
33추가: assert!(output.status.success(), "{:?}", output.stderr);
34추가: assert!(output.stderr.is_empty());
35추가: let mut reader = Reader::new(output.stdout.as_slice());
36추가: let mut events = Vec::new();
37추가: while let Some((job, _, event)) = reader.read().unwrap() {
38추가: assert_eq!(job, 17);
39추가: assert!(!matches!(events.last(), Some(Message::Terminal(_))));
40추가: events.push(event);
41추가: }
42추가: assert!(matches!(events.last(), Some(Message::Terminal(_))));
43추가: events
44추가: }
45추가:
46추가: fn terminal(events: &[Message]) -> &Terminal {
47추가: match events.last().unwrap() {
48추가: Message::Terminal(value) => value,
49추가: _ => unreachable!(),
50추가: }
51추가: }
52추가:
53추가: fn directory(path: &Path) {
54추가: use std::os::unix::fs::DirBuilderExt;
55추가: fs::DirBuilder::new().mode(0o700).create(path).unwrap();
56추가: }
57추가:
58추가: #[test]
59추가: fn zip64_tool_and_field_corpus_lists_and_extracts() {
60추가: let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
61추가: let runs = root.join("runs");
62추가: fs::create_dir_all(&runs).unwrap();
63추가: let scratch = runs.join(format!(
64추가: "{}-{}",
65추가: std::process::id(),
66추가: SystemTime::now()
67추가: .duration_since(UNIX_EPOCH)
68추가: .unwrap()
69추가: .as_nanos()
70추가: ));
71추가: directory(&scratch);
72추가: let corpus = scratch.join("corpus");
73추가: assert!(
74추가: Command::new("python3")
75추가: .arg(root.join("generate.py"))
76추가: .arg(&corpus)
77추가: .status()
78추가: .unwrap()
79추가: .success()
80추가: );
81추가: let mut report = String::from("case\tlist\textract\n");
82추가: let mut failures = Vec::new();
83추가: let manifest = fs::read_to_string(corpus.join("cases.tsv")).unwrap();
84추가: let mut count = 0;
85추가: for line in manifest.lines() {
86추가: let columns: Vec<_> = line.split('\t').collect();
87추가: assert_eq!(columns.len(), 3);
88추가: let (id, name, hex) = (columns[0], columns[1], columns[2]);
89추가: let expected: Vec<_> = (0..hex.len())
90추가: .step_by(2)
91추가: .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
92추가: .collect();
93추가: let archive = NativePath::from_path(&corpus.join(format!("{id}.zip")));
94추가: let listed = execute(Action::List {
95추가: archive: archive.clone(),
96추가: });
97추가: let list_id = listed.iter().find_map(|event| match event {
98추가: Message::ListEnd {
99추가: entry_count: 1,
100추가: list_id,
101추가: } => Some(list_id.clone()),
102추가: _ => None,
103추가: });
104추가: let entries: Vec<_> = listed
105추가: .iter()
106추가: .filter_map(|event| match event {
107추가: Message::Entry(entry) => Some(entry),
108추가: _ => None,
109추가: })
110추가: .collect();
111추가: let list_ok = terminal(&listed).outcome == Outcome::Completed
112추가: && terminal(&listed).error == ErrorCode::None
113추가: && list_id.is_some()
114추가: && entries.len() == 1
115추가: && entries[0].name == name
116추가: && entries[0].size == expected.len() as u64;
117추가: let destination = scratch.join(id);
118추가: directory(&destination);
119추가: let extracted = execute(Action::Extract {
120추가: archive,
121추가: destination: NativePath::from_path(&destination),
122추가: selection: Selection::All,
123추가: list_id,
124추가: gzip_output_name: None,
125추가: });
126추가: let end = terminal(&extracted);
127추가: let extract_ok = end.outcome == Outcome::Completed
128추가: && end.error == ErrorCode::None
129추가: && end.publication == Publication::Complete
130추가: && end.cleanup == Cleanup::Complete
131추가: && end.created_count == 1
132추가: && end.retained_partial_count == 0
133추가: && fs::read(destination.join(name)).ok().as_deref() == Some(expected.as_slice())
134추가: && fs::read_dir(&destination).unwrap().count() == 1;
135추가: report.push_str(&format!(
136추가: "{id}\t{}:{:?}\t{}:{:?}\n",
137추가: if list_ok { "PASS" } else { "FAIL" },
138추가: terminal(&listed).error,
139추가: if extract_ok { "PASS" } else { "FAIL" },
140추가: end.error
141추가: ));
142추가: if !list_ok || !extract_ok {
143추가: failures.push(id.to_owned());
144추가: }
145추가: count += 1;
146추가: }
147추가: assert_eq!(count, 1066);
148추가: fs::write(scratch.join("results.tsv"), report).unwrap();
149추가: println!(
150추가: "ZIP64 corpus: {count} cases, {} failed; {}",
151추가: failures.len(),
152추가: scratch.display()
153추가: );
154추가: assert!(
155추가: failures.is_empty(),
156추가: "실패 {}개, 앞 12개: {:?}; 전체 결과: {}",
157추가: failures.len(),
158추가: &failures[..failures.len().min(12)],
159추가: scratch.join("results.tsv").display()
160추가: );
161추가: }
추가tests/rust-zip64-compat/generate.py+175-0
@@ -0,0 +1,175 @@
1추가: """세 도구의 ZIP64 원본과 단일 볼륨 확장 필드 조합을 생성함."""
2추가: import ctypes as c
3추가: import importlib.util
4추가: import io
5추가: import json
6추가: from pathlib import Path
7추가: import struct
8추가: import subprocess
9추가: import sys
10추가: import zipfile
11추가:
12추가: NAME = "payload.bin"
13추가: PAYLOAD = b"ZIP64 corpus payload\n"
14추가:
15추가:
16추가: def module(name, path):
17추가: spec = importlib.util.spec_from_file_location(name, path)
18추가: result = importlib.util.module_from_spec(spec)
19추가: spec.loader.exec_module(result)
20추가: return result
21추가:
22추가:
23추가: def python_zip(force=False, pipe=False):
24추가: class Pipe(io.BytesIO):
25추가: def seek(self, *args):
26추가: raise io.UnsupportedOperation()
27추가:
28추가: output = Pipe() if pipe else io.BytesIO()
29추가: with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
30추가: with archive.open(NAME, "w", force_zip64=force) as target:
31추가: target.write(PAYLOAD)
32추가: return output.getvalue()
33추가:
34추가:
35추가: def libarchive_zip():
36추가: reference = module(
37추가: "archive_reference",
38추가: Path(__file__).resolve().parents[1] / "rust-archive-worker/seven_zip_reference.py",
39추가: )
40추가: lib = reference.library()
41추가: lib.archive_write_set_format_zip.argtypes = [c.c_void_p]
42추가: lib.archive_write_set_format_zip.restype = c.c_int
43추가: lib.archive_version_string.restype = c.c_char_p
44추가: archive = lib.archive_write_new()
45추가: buffer = c.create_string_buffer(65536)
46추가: used = c.c_size_t()
47추가: entry = lib.archive_entry_new()
48추가:
49추가: def check(value):
50추가: assert value == 0, lib.archive_error_string(archive)
51추가:
52추가: try:
53추가: check(lib.archive_write_set_format_zip(archive))
54추가: check(lib.archive_write_set_format_option(archive, b"zip", b"zip64", b"1"))
55추가: check(lib.archive_write_set_format_option(archive, b"zip", b"compression", b"store"))
56추가: check(lib.archive_write_open_memory(archive, buffer, len(buffer), c.byref(used)))
57추가: lib.archive_entry_set_pathname(entry, NAME.encode())
58추가: lib.archive_entry_set_filetype(entry, 0o100000)
59추가: lib.archive_entry_set_perm(entry, 0o600)
60추가: lib.archive_entry_set_size(entry, len(PAYLOAD))
61추가: lib.archive_entry_set_mtime(entry, 0, 0)
62추가: check(lib.archive_write_header(archive, entry))
63추가: assert lib.archive_write_data(archive, PAYLOAD, len(PAYLOAD)) == len(PAYLOAD)
64추가: check(lib.archive_write_close(archive))
65추가: return buffer.raw[:used.value], lib.archive_version_string().decode()
66추가: finally:
67추가: lib.archive_entry_free(entry)
68추가: lib.archive_write_free(archive)
69추가:
70추가:
71추가: def variant(original, central_mask, end_mask, local64=False):
72추가: # 중앙 확장 필드는 원래 크기, 압축 크기, 오프셋, 디스크 순서임.
73추가: end = bytearray(original[-22:])
74추가: central_at = struct.unpack_from("<I", end, 16)[0]
75추가: body = bytearray(original[:central_at])
76추가: central = bytearray(original[central_at:-22])
77추가: assert struct.unpack_from("<H", central, 30)[0] == 0
78추가: assert struct.unpack_from("<H", central, 32)[0] == 0
79추가: if local64:
80추가: name_len = struct.unpack_from("<H", body, 26)[0]
81추가: packed, size = struct.unpack_from("<II", body, 18)
82추가: struct.pack_into("<II", body, 18, 0xffffffff, 0xffffffff)
83추가: struct.pack_into("<H", body, 28, 20)
84추가: body[30 + name_len:30 + name_len] = struct.pack("<HHQQ", 1, 16, size, packed)
85추가: struct.pack_into("<H", body, 4, 45)
86추가: struct.pack_into("<H", central, 6, 45)
87추가: extra = bytearray()
88추가: for bit, offset, field_type in [(0, 24, "I"), (1, 20, "I"), (2, 42, "I"), (3, 34, "H")]:
89추가: if central_mask & (1 << bit):
90추가: value = struct.unpack_from("<" + field_type, central, offset)[0]
91추가: struct.pack_into("<" + field_type, central, offset, 0xffff if bit == 3 else 0xffffffff)
92추가: extra += struct.pack("<I" if bit == 3 else "<Q", value)
93추가: if extra:
94추가: central += struct.pack("<HH", 1, len(extra)) + extra
95추가: struct.pack_into("<H", central, 30, len(extra) + 4)
96추가: central_at = len(body)
97추가: directory = body + central
98추가: record = struct.pack(
99추가: "<4sQHHIIQQQQ", b"PK\x06\x06", 44, 45, 45, 0, 0, 1, 1, len(central), central_at
100추가: )
101추가: locator = struct.pack("<4sIQI", b"PK\x06\x07", 0, len(directory), 1)
102추가: struct.pack_into("<II", end, 12, len(central), central_at)
103추가: # EOCD의 디스크 두 필드, 항목 수 두 필드, 크기와 오프셋을 독립 확장함.
104추가: for bit, offset, field_type in [(0, 4, "H"), (1, 6, "H"), (2, 8, "H"),
105추가: (3, 10, "H"), (4, 12, "I"), (5, 16, "I")]:
106추가: if end_mask & (1 << bit):
107추가: struct.pack_into("<" + field_type, end, offset, 0xffff if field_type == "H" else 0xffffffff)
108추가: return bytes(directory + record + locator + end)
109추가:
110추가:
111추가: def generate(root):
112추가: root = Path(root)
113추가: root.mkdir(mode=0o700, parents=True, exist_ok=False)
114추가: cases = []
115추가:
116추가: def add(identifier, data, producer, payload=PAYLOAD):
117추가: path = root / (identifier + ".zip")
118추가: path.write_bytes(data)
119추가: with zipfile.ZipFile(path) as reference:
120추가: names = reference.namelist()
121추가: assert len(names) == 1
122추가: assert reference.read(names[0]) == payload, identifier
123추가: assert reference.testzip() is None, identifier
124추가: cases.append((identifier, names[0], payload.hex(), producer))
125추가:
126추가: original = python_zip()
127추가: add("python-classic", original, "Python zipfile")
128추가: add("python-force-local", python_zip(True), "Python zipfile force_zip64")
129추가: add("python-force-descriptor", python_zip(True, True), "Python zipfile force_zip64 unseekable")
130추가: native, version = libarchive_zip()
131추가: assert b"PK\x06\x07" in native
132추가: add("libarchive-force", native, version + " zip64=1")
133추가: (root / NAME).write_bytes(PAYLOAD)
134추가: subprocess.run(
135추가: ["zip", "-q", "-fz", "infozip-native.zip", NAME],
136추가: cwd=root, capture_output=True, check=True,
137추가: )
138추가: info = (root / "infozip-native.zip").read_bytes()
139추가: assert struct.unpack_from("<II", info, 18) == (0xffffffff, 0xffffffff)
140추가: assert b"PK\x06\x07" in info
141추가: add("infozip-force", info, "Info-ZIP -fz regular file")
142추가: for central in range(16):
143추가: for end in range(64):
144추가: add(f"fields-c{central:02x}-e{end:02x}", variant(original, central, end),
145추가: "Python zipfile + APPNOTE field substitution")
146추가: add(f"local64-c{central:02x}", variant(original, central, 0, True),
147추가: "Python zipfile + local size pair + central field substitution")
148추가: expanded = variant(original, central, 0)
149추가: add(f"central-only-c{central:02x}", expanded[:-98] + expanded[-22:],
150추가: "Python zipfile + central fields without ZIP64 end records")
151추가: previous = module(
152추가: "previous_zip64",
153추가: Path(__file__).resolve().parents[1] / "rust-archive-worker/hardening_cases.py",
154추가: )
155추가: for kind in ["locator64", "offset64-descriptor", "offset64-descriptor-unsigned"]:
156추가: directory = root / kind
157추가: directory.mkdir()
158추가: previous.generate(directory, kind, 20)
159추가: add("previous-" + kind, (directory / "input").read_bytes(), "PR74 regression", bytes(20))
160추가: add("previous-eocd-disk", variant(original, 0, 3), "EOCD disk sentinel regression")
161추가: add("previous-central-disk", variant(original, 8, 0), "central disk sentinel regression")
162추가: (root / "cases.tsv").write_text(
163추가: "".join("\t".join(row[:3]) + "\n" for row in cases), encoding="utf-8"
164추가: )
165추가: (root / "provenance.json").write_text(json.dumps({
166추가: "python": sys.version,
167추가: "libarchive": version,
168추가: "infozip": subprocess.check_output(["zip", "-v"], text=True).splitlines()[:3],
169추가: "cases": [{"id": row[0], "producer": row[3]} for row in cases],
170추가: }, indent=4) + "\n", encoding="utf-8")
171추가: print(f"Python reference CRC/content: {len(cases)} passed")
172추가:
173추가:
174추가: if __name__ == "__main__":
175추가: generate(sys.argv[1])
추가tests/rust-zip64-compat/worker.rs+5-0
@@ -0,0 +1,5 @@
1추가: fn main() {
2추가: if zipelo_archive_worker::runtime::serve(std::io::stdin(), std::io::stdout()).is_err() {
3추가: std::process::exit(2);
4추가: }
5추가: }