team-ljyzipelo

공개

Merge pull request #78 from Team-LJY/features/7z-streaming

7z 해제와 ZIP 생성의 대용량 스트리밍 처리
작성자
LeeJunyoung
작성 시각
커밋
9159859b761135a6957a3c527b4aa31cae1802b3
이 시점의 파일 보기

변경된 파일 16개

+1,335-276
수정experiments/rust-archive-worker/Cargo.toml+4-0
@@ -21,3 +21,7 @@ zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allo
2121[[test]]
2222name = "archive_worker"
2323path = "../../tests/rust-archive-worker/main.rs"
24추가:
25추가: # 대용량 시험의 CRC와 Deflate에도 배포판의 최적화를 적용함.
26추가: [profile.dev.package.zlib-rs]
27추가: opt-level = 3
수정experiments/rust-archive-worker/README.md+8-4
@@ -2,8 +2,8 @@
22
33별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
44
5삭제: - ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
6삭제: - ZIP/TAR/GZ/TAR.GZ 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. 7z, ZIP 생성과 slice 기반 archive parser는 입력 64 MiB/출력 128 MiB의 별도 메모리 상한을 유지합니다.
5추가: - ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
6추가: - ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다.
77- 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
88- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
99- ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
@@ -19,7 +19,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
1919- 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. ZIP/7z 해제 전에는 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 공간 부족은 DiskFull(13), 조회 실패와 권한 등 다른 I/O 오류는 Io(8)로 반환합니다. 실제 생성/쓰기/동기화의 공간 부족에도 같은 구분을 적용합니다. Windows의 공간 부족 코드 39와 112는 [공식 오류 목록](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)을 따릅니다.
2020- 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
2121- 입력과 검증된 해제 내용은 임시 파일에 저장합니다. Linux는 [O_TMPFILE](https://man7.org/linux/man-pages/man2/open.2.html), 이를 지원하지 않는 Linux 파일시스템에서는 0600 난수 파일을 배타적으로 만든 즉시 unlink하고 링크 수 0을 확인합니다. Windows는 배타적 [DELETE_ON_CLOSE 파일](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)을 사용합니다. 마지막 핸들이 닫히면 제거되며 임시 파일명에 아카이브 내부 이름을 사용하지 않습니다. 디스크에는 입력 사본, 해제 내용과 현재 출력 임시 파일이 동시에 필요할 수 있습니다. 임시 폴더가 tmpfs이면 해당 파일 내용은 프로세스 RSS 외의 시스템 메모리를 사용합니다.
22삭제: - 64 MiB는 ZIP/TAR/GZ/TAR.GZ 해제 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 7z와 생성은 이 RSS 목표에 포함하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다.
22추가: - 64 MiB는 ZIP/TAR/GZ/TAR.GZ/7z 해제와 ZIP 생성 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다.
2323- Linux는 시작 시 부모 PID를 캡처하고 [getppid](https://man7.org/linux/man-pages/man2/getpid.2.html) 변경을 확인합니다. Windows는 부모 프로세스 핸들과 생성 시간을 확인한 뒤 [WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)로 생존을 검사합니다. 부모가 사라지면 checkpoint에서 Io로 중단하고 임시 출력을 정리합니다. 이미 게시한 파일/디렉터리는 유지하며 OS의 블로킹 I/O 강제 중단을 보장하지 않습니다. 기존 단발 요청을 위해 stdin EOF만으로 취소하지 않습니다.
2424- tests/rust-archive-worker/hardening.rs는 공용 대용량 생성기를 사용해 Store ZIP/Deflate ZIP/TAR/GZ/TAR.GZ의 1 GiB payload를 실행 시 생성하고 wait4의 ru_maxrss로 피크 RSS를 측정합니다. Linux의 시험 전용 LD_PRELOAD로 ENOSPC와 게시 중 정지를 주입하고 앱 강제 종료 후 작업자 종료/회수와 부분 출력 제거를 확인합니다. 이 시험을 위해 실제 공유 디스크를 채우거나 제품용 환경 변수 우회를 추가하지 않습니다.
2525
@@ -28,7 +28,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
2828비암호화 7z의 단일 입력/출력 coder인 Copy, LZMA와 LZMA2를 Rust 코드로 해독합니다. solid substream, 빈 파일/디렉터리, UTF-16LE 이름과 한 단계 압축 헤더를 처리합니다. 추가 라이브러리나 제품 외부 명령을 사용하지 않습니다. 형식 근거는 [7z 명세](https://www.7-zip.org/7z.html)와 [LZMA SDK 명세 안내](https://www.7-zip.org/sdk.html)입니다.
2929
3030- 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다.
31삭제: - 입력 64 MiB/출력 128 MiB와 기존 항목/이름 한도를 별도로 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
31추가: - 기본 입력 한도 u64::MAX, 해제 총량 16 GiB와 기존 항목/이름 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 최근 8 MiB 사전만 메모리에 두고 더 먼 참조는 임시 파일에서 읽습니다. 먼 거리 참조가 많은 파일은 추가 디스크 I/O가 발생합니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
3232- 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다.
3333- solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다.
3434- 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다.
@@ -44,6 +44,10 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
4444- salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 메모리 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리/페이지 캐시 복사본과 임시 저장소의 평문에 대한 완전 소거를 보장하지 않습니다. 임시 평문 파일은 작업 종료 시 닫아 제거하며 보안 삭제를 뜻하지 않습니다.
4545- Python hashlib/hmac과 OpenSSL로 만든 AES 표본 4개, Info-ZIP으로 만든 ZipCrypto 표본 2개를 tests/ 아래에 보관합니다. 생성한 AES ZIP도 Linux에서 독립 Python/OpenSSL 검증기로 확인합니다. OpenSSL/Info-ZIP은 시험 도구이며 제품 의존성이 아닙니다.
4646
47추가: 대용량 7z 표본은 Python LZMA로 실행 시 생성하고 Linux 시스템 libarchive의 스트리밍 판독으로 내용과 CRC를 먼저 확인합니다. libarchive는 시험에만 사용합니다.
48추가:
49추가: 7z의 Copy/LZMA/LZMA2 입력과 solid 출력은 고정 버퍼와 임시 파일로 처리합니다. 모든 폴더와 하위 스트림의 CRC와 크기 검증이 끝난 뒤 기존 게시 경로를 사용합니다. ZIP 생성의 압축 및 AES 처리도 64 KiB 버퍼를 사용하며 여유 공간 사전 검사와 실제 쓰기의 DiskFull 구분을 적용합니다. 공간 예약을 보장하지 않으므로 다른 프로세스와의 경쟁으로 쓰기가 실패할 수 있습니다.
50추가:
4751## 공유 codec
4852
4953`protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다.
수정experiments/rust-archive-worker/contract.json+6-5
@@ -73,7 +73,6 @@
7373 "CRC/size/stream-end validation precedes committed output events; preserve commit/durability/cleanup distinctions."
7474 ],
7575 "pending": [
76삭제: "7z streaming and ZIP creation streaming remain deferred with separate legacy quotas.",
7776 "Windows native runtime, forced interruption of blocked OS I/O and a current full dependency advisory audit are not verified."
7877 ],
7978 "crypto": {
@@ -144,7 +143,7 @@
144143 "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId."
145144 },
146145 "streaming_limits": {
147삭제: "agreement": "Revision 2 fields and frame encoding unchanged. Ratio-rejection removal and advisory disk-space checks follow manager decision d6bc0d37-89d1-4cd2-a00b-883b5eb23ec0. DiskFull tag 13 and preserving Io tag 8 for query/access failures were agreed with frontend in message 3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1.",
146추가: "agreement": "Revision 2 fields and frame encoding unchanged. Ratio-rejection removal and advisory disk-space checks follow manager decision d6bc0d37-89d1-4cd2-a00b-883b5eb23ec0. DiskFull tag 13 and preserving Io tag 8 for query/access failures were agreed with frontend in message 3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1. The 7z/CreateZip streaming extension follows manager task c4acbf18-0845-49a2-ae10-a92e7934042d; this extension was agreed with frontend in message 81b585cb-84be-494d-a953-1c8220300176 (PR 78 review 5864130366). Existing numeric quotas, frame fields and error tags remain unchanged.",
148147 "default_input_bytes": 18446744073709551615,
149148 "default_output_bytes": 17179869184,
150149 "default_entries": 10000,
@@ -153,12 +152,14 @@
153152 "gzip_ratio": "No compression-ratio rejection, including concatenated members. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota.",
154153 "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.",
155154 "arithmetic": "Checked u64 offsets and totals; free-space block-to-byte conversion uses u128 to avoid multiplication overflow.",
156삭제: "memory_target": "ZIP/TAR/GZ/TAR.GZ List/Extract: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. Metadata budget remains 8 MiB.",
155추가: "memory_target": "ZIP/TAR/GZ/TAR.GZ/7z List/Extract and ZIP creation: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. Metadata budget remains 8 MiB.",
157156 "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with DiskFull and closes/removes unpublished data.",
158삭제: "legacy": "7z and ZIP creation retain separate 64 MiB input /128 MiB output caps until their streaming implementation. The slice-based archive parser also retains these legacy memory bounds.",
157추가: "legacy": "The slice parser keeps 64 MiB input /128 MiB output caps; the slice ZIP builder keeps 128 MiB source/result caps. Runtime 7z and ZIP creation use streaming file paths.",
159158 "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard.",
160159 "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Before ZIP/7z decoding and before publication, group remaining staging and selected output logical bytes by volume. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Insufficient space returns DiskFull tag 13. Query failure and other I/O errors retain Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.",
161삭제: "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure."
160추가: "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure.",
161추가: "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers remain limited to 8 MiB. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.",
162추가: "create_zip": "The sum of source logical bytes cannot exceed min(input,output) quotas. output defaults to 16 GiB of uncompressed source content; ZIP container/encryption overhead may exceed that logical content quota. Capture one immutable source at a time, stream Store/Deflate and optional AES-256 through 64 KiB buffers, then publish the completed ZIP without replacing existing files. Emit ZIP64 sizes/offsets only when their 32-bit fields would overflow or equal the sentinel. Check staging and destination free space; StorageFull maps to DiskFull tag 13 and other I/O failures retain Io tag 8."
162163 },
163164 "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim.",
164165 "error_tags": {
추가experiments/rust-archive-worker/src/create.rs+333-0
@@ -0,0 +1,333 @@
1추가: use crate::{
2추가: archive::{self, Member, MetadataBudget},
3추가: protocol::*,
4추가: spool,
5추가: };
6추가: use std::{
7추가: fs::File,
8추가: io::{Read, Seek, Write},
9추가: };
10추가: use zeroize::Zeroizing;
11추가: use zlib_rs::{Deflate, DeflateFlush, Status, crc32::crc32};
12추가:
13추가: type Result<T> = std::result::Result<T, ErrorCode>;
14추가: fn io<T>(result: std::io::Result<T>) -> Result<T> {
15추가: result.map_err(crate::space::io_error)
16추가: }
17추가: fn put16(out: &mut Vec<u8>, value: u16) {
18추가: out.extend(value.to_le_bytes());
19추가: }
20추가: fn put32(out: &mut Vec<u8>, value: u32) {
21추가: out.extend(value.to_le_bytes());
22추가: }
23추가: fn put64(out: &mut Vec<u8>, value: u64) {
24추가: out.extend(value.to_le_bytes());
25추가: }
26추가:
27추가: fn zip64_extra(size: u64, packed: u64, offset: Option<u64>) -> Vec<u8> {
28추가: let mut values = Vec::new();
29추가: if size >= u32::MAX as u64 || packed >= u32::MAX as u64 {
30추가: put64(&mut values, size);
31추가: put64(&mut values, packed);
32추가: }
33추가: if let Some(offset) = offset.filter(|n| *n >= u32::MAX as u64) {
34추가: put64(&mut values, offset);
35추가: }
36추가: let mut extra = Vec::new();
37추가: if !values.is_empty() {
38추가: put16(&mut extra, 1);
39추가: put16(&mut extra, values.len() as u16);
40추가: extra.extend(values);
41추가: }
42추가: extra
43추가: }
44추가: fn pack(
45추가: input: &mut File,
46추가: length: u64,
47추가: method: Method,
48추가: output: &mut File,
49추가: check: &mut impl FnMut() -> Result<()>,
50추가: ) -> Result<(u64, u32)> {
51추가: io(input.rewind())?;
52추가: let mut input = input.take(length);
53추가: let mut buffer = Zeroizing::new([0; 65536]);
54추가: let mut encoded = Zeroizing::new([0; 65536]);
55추가: let mut crc = 0;
56추가: let mut size = 0u64;
57추가: if method == Method::Store {
58추가: loop {
59추가: check()?;
60추가: let n = io(input.read(&mut buffer[..]))?;
61추가: if n == 0 {
62추가: break;
63추가: }
64추가: crc = crc32(crc, &buffer[..n]);
65추가: io(output.write_all(&buffer[..n]))?;
66추가: size += n as u64;
67추가: }
68추가: if size != length {
69추가: return Err(ErrorCode::SourceChanged);
70추가: }
71추가: return Ok((size, crc));
72추가: }
73추가: let mut stream = Deflate::new(6, false, 15);
74추가: loop {
75추가: check()?;
76추가: let n = io(input.read(&mut buffer[..]))?;
77추가: crc = crc32(crc, &buffer[..n]);
78추가: let mut used = 0;
79추가: loop {
80추가: check()?;
81추가: let a = stream.total_in();
82추가: let b = stream.total_out();
83추가: let status = stream
84추가: .compress(
85추가: &buffer[used..n],
86추가: &mut encoded[..],
87추가: if n == 0 {
88추가: DeflateFlush::Finish
89추가: } else {
90추가: DeflateFlush::NoFlush
91추가: },
92추가: )
93추가: .map_err(|_| ErrorCode::Internal)?;
94추가: used += (stream.total_in() - a) as usize;
95추가: let written = (stream.total_out() - b) as usize;
96추가: io(output.write_all(&encoded[..written]))?;
97추가: size = size.checked_add(written as u64).ok_or(ErrorCode::Limit)?;
98추가: if status == Status::StreamEnd {
99추가: if stream.total_in() != length {
100추가: return Err(ErrorCode::SourceChanged);
101추가: }
102추가: return Ok((size, crc));
103추가: }
104추가: if used == n && n != 0 {
105추가: break;
106추가: }
107추가: if a == stream.total_in() && b == stream.total_out() {
108추가: return Err(ErrorCode::Internal);
109추가: }
110추가: }
111추가: }
112추가: }
113추가: pub(crate) fn plan(sources: &[Source], limits: Limits) -> Result<Vec<Member>> {
114추가: if sources.len() > limits.entries as usize {
115추가: return Err(ErrorCode::Limit);
116추가: }
117추가: let mut metadata = MetadataBudget::default();
118추가: let mut members = Vec::new();
119추가: for source in sources {
120추가: source.path.to_path()?;
121추가: let name = archive::valid_name(&source.archive_name, false)?;
122추가: metadata.charge(&name)?;
123추가: members.push(Member {
124추가: entry: Entry {
125추가: entry_id: members.len() as u32,
126추가: name,
127추가: kind: EntryKind::File,
128추가: size: 0,
129추가: compressed_size: 0,
130추가: encrypted: false,
131추가: },
132추가: data: Vec::new(),
133추가: });
134추가: }
135추가: archive::validate_members(&members)?;
136추가: Ok(members)
137추가: }
138추가: pub(crate) fn zip(
139추가: sources: &[Source],
140추가: members: &[Member],
141추가: method: Method,
142추가: limits: Limits,
143추가: password: Option<&[u8]>,
144추가: check: &mut impl FnMut() -> Result<()>,
145추가: ) -> Result<(File, u64)> {
146추가: let mut output = spool::temporary()?;
147추가: let mut central = Vec::new();
148추가: let mut total = 0u64;
149추가: let mut have_zip64 = false;
150추가: for (source, member) in sources.iter().zip(members) {
151추가: check()?;
152추가: let remaining = limits
153추가: .input
154추가: .min(limits.output)
155추가: .checked_sub(total)
156추가: .ok_or(ErrorCode::Limit)?;
157추가: let mut snapshot = spool::Snapshot::open(&source.path.to_path()?, remaining, check)?;
158추가: total = total
159추가: .checked_add(snapshot.len)
160추가: .filter(|n| *n <= limits.output)
161추가: .ok_or(ErrorCode::Limit)?;
162추가: // 압축 결과의 보수적 상한과 ZIP에 복사할 공간을 함께 확인함.
163추가: let bound = snapshot
164추가: .len
165추가: .checked_add(snapshot.len / 16383 * 5)
166추가: .and_then(|n| n.checked_add(131072))
167추가: .ok_or(ErrorCode::Limit)?;
168추가: crate::space::ensure(&output, bound.checked_mul(2).ok_or(ErrorCode::Limit)?)?;
169추가: let mut packed = spool::temporary()?;
170추가: let (packed_size, crc) =
171추가: pack(&mut snapshot.file, snapshot.len, method, &mut packed, check)?;
172추가: let packed_size = packed_size
173추가: .checked_add(if password.is_some() { 28 } else { 0 })
174추가: .ok_or(ErrorCode::Limit)?;
175추가: let offset = io(output.stream_position())?;
176추가: let name = member.entry.name.as_bytes();
177추가: let real_method = if method == Method::Store { 0 } else { 8 };
178추가: let flags = if password.is_some() { 0x0801 } else { 0x0800 };
179추가: let wide_sizes = snapshot.len >= u32::MAX as u64 || packed_size >= u32::MAX as u64;
180추가: let wide_offset = offset >= u32::MAX as u64;
181추가: have_zip64 |= wide_sizes || wide_offset;
182추가: let version = if password.is_some() {
183추가: 51
184추가: } else if wide_sizes || wide_offset {
185추가: 45
186추가: } else {
187추가: 20
188추가: };
189추가: let method = if password.is_some() { 99 } else { real_method };
190추가: let crc = if password.is_some() { 0 } else { crc };
191추가: let mut aes = Vec::new();
192추가: if password.is_some() {
193추가: put16(&mut aes, 0x9901);
194추가: put16(&mut aes, 7);
195추가: put16(&mut aes, 2);
196추가: aes.extend(b"AE");
197추가: aes.push(3);
198추가: put16(&mut aes, real_method);
199추가: }
200추가: let mut extra = zip64_extra(snapshot.len, packed_size, None);
201추가: extra.extend(&aes);
202추가: let mut header = Vec::new();
203추가: header.extend(b"PK\x03\x04");
204추가: for v in [version, flags, method, 0, 33] {
205추가: put16(&mut header, v);
206추가: }
207추가: put32(&mut header, crc);
208추가: put32(
209추가: &mut header,
210추가: if wide_sizes {
211추가: u32::MAX
212추가: } else {
213추가: packed_size as u32
214추가: },
215추가: );
216추가: put32(
217추가: &mut header,
218추가: if wide_sizes {
219추가: u32::MAX
220추가: } else {
221추가: snapshot.len as u32
222추가: },
223추가: );
224추가: put16(&mut header, name.len() as u16);
225추가: put16(&mut header, extra.len() as u16);
226추가: header.extend(name);
227추가: header.extend(extra);
228추가: io(output.write_all(&header))?;
229추가: io(packed.rewind())?;
230추가: if let Some(password) = password {
231추가: crate::crypto::aes_encrypt_file(
232추가: &mut packed,
233추가: packed_size - 28,
234추가: &mut output,
235추가: password,
236추가: check,
237추가: )?;
238추가: } else {
239추가: let mut buffer = Zeroizing::new([0; 65536]);
240추가: loop {
241추가: check()?;
242추가: let n = io(packed.read(&mut buffer[..]))?;
243추가: if n == 0 {
244추가: break;
245추가: }
246추가: io(output.write_all(&buffer[..n]))?;
247추가: }
248추가: }
249추가: let mut extra = zip64_extra(snapshot.len, packed_size, Some(offset));
250추가: extra.extend(&aes);
251추가: central.extend(b"PK\x01\x02");
252추가: put16(&mut central, 0x032d);
253추가: for v in [version, flags, method, 0, 33] {
254추가: put16(&mut central, v);
255추가: }
256추가: put32(&mut central, crc);
257추가: put32(
258추가: &mut central,
259추가: if wide_sizes {
260추가: u32::MAX
261추가: } else {
262추가: packed_size as u32
263추가: },
264추가: );
265추가: put32(
266추가: &mut central,
267추가: if wide_sizes {
268추가: u32::MAX
269추가: } else {
270추가: snapshot.len as u32
271추가: },
272추가: );
273추가: put16(&mut central, name.len() as u16);
274추가: put16(&mut central, extra.len() as u16);
275추가: for _ in 0..3 {
276추가: put16(&mut central, 0);
277추가: }
278추가: put32(&mut central, 0o100600 << 16);
279추가: put32(
280추가: &mut central,
281추가: if wide_offset { u32::MAX } else { offset as u32 },
282추가: );
283추가: central.extend(name);
284추가: central.extend(extra);
285추가: }
286추가: check()?;
287추가: let at = io(output.stream_position())?;
288추가: crate::space::ensure(&output, central.len() as u64 + 98)?;
289추가: io(output.write_all(&central))?;
290추가: let large_at = io(output.stream_position())?;
291추가: let mut end = Vec::new();
292추가: if have_zip64 || at >= u32::MAX as u64 || central.len() >= u32::MAX as usize {
293추가: end.extend(b"PK\x06\x06");
294추가: put64(&mut end, 44);
295추가: put16(&mut end, 45);
296추가: put16(&mut end, 45);
297추가: put32(&mut end, 0);
298추가: put32(&mut end, 0);
299추가: put64(&mut end, sources.len() as u64);
300추가: put64(&mut end, sources.len() as u64);
301추가: put64(&mut end, central.len() as u64);
302추가: put64(&mut end, at);
303추가: end.extend(b"PK\x06\x07");
304추가: put32(&mut end, 0);
305추가: put64(&mut end, large_at);
306추가: put32(&mut end, 1);
307추가: end.extend(b"PK\x05\x06");
308추가: put16(&mut end, 0);
309추가: put16(&mut end, 0);
310추가: put16(&mut end, u16::MAX);
311추가: put16(&mut end, u16::MAX);
312추가: put32(&mut end, u32::MAX);
313추가: put32(&mut end, u32::MAX);
314추가: put16(&mut end, 0);
315추가: } else {
316추가: end.extend(b"PK\x05\x06");
317추가: put16(&mut end, 0);
318추가: put16(&mut end, 0);
319추가: put16(&mut end, sources.len() as u16);
320추가: put16(&mut end, sources.len() as u16);
321추가: put32(&mut end, central.len() as u32);
322추가: put32(&mut end, at as u32);
323추가: put16(&mut end, 0);
324추가: }
325추가: io(output.write_all(&end))?;
326추가: let size = io(output.stream_position())?;
327추가: io(output.rewind())?;
328추가: Ok((output, size))
329추가: }
330추가:
331추가: #[cfg(test)]
332추가: #[path = "../../../tests/rust-archive-worker/create_zip_fields.rs"]
333추가: mod tests;
수정experiments/rust-archive-worker/src/crypto.rs+45-0
@@ -295,3 +295,48 @@ impl Drop for Decryptor {
295295 }
296296 }
297297}
298추가:
299추가: pub(crate) fn aes_encrypt_file(
300추가: input: &mut std::fs::File,
301추가: length: u64,
302추가: output: &mut std::fs::File,
303추가: password: &[u8],
304추가: check: &mut impl FnMut() -> Result<()>,
305추가: ) -> Result<()> {
306추가: use std::io::{Read, Write};
307추가: check()?;
308추가: let mut salt = [0; 16];
309추가: random(&mut salt)?;
310추가: let key = keys(password, &salt);
311추가: output.write_all(&salt).map_err(crate::space::io_error)?;
312추가: output
313추가: .write_all(&key[64..])
314추가: .map_err(crate::space::io_error)?;
315추가: let mut cipher = Decryptor::Aes {
316추가: cipher: Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?,
317추가: counter: 1,
318추가: mask: [0; 16],
319추가: used: 16,
320추가: };
321추가: let mut mac =
322추가: <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?;
323추가: let mut remaining = length;
324추가: let mut buffer = Zeroizing::new([0; 65536]);
325추가: while remaining != 0 {
326추가: check()?;
327추가: let n = remaining.min(buffer.len() as u64) as usize;
328추가: input
329추가: .read_exact(&mut buffer[..n])
330추가: .map_err(crate::space::io_error)?;
331추가: cipher.apply(&mut buffer[..n]);
332추가: mac.update(&buffer[..n]);
333추가: output
334추가: .write_all(&buffer[..n])
335추가: .map_err(crate::space::io_error)?;
336추가: remaining -= n as u64;
337추가: }
338추가: output
339추가: .write_all(&mac.finalize().into_bytes()[..10])
340추가: .map_err(crate::space::io_error)?;
341추가: Ok(())
342추가: }
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -1,4 +1,5 @@
11pub mod archive;
2추가: mod create;
23mod crypto;
34pub mod filesystem;
45mod lzma;
수정experiments/rust-archive-worker/src/lzma.rs+233-79
@@ -1,29 +1,156 @@
11use crate::protocol::ErrorCode;
2추가: use std::io::Read;
3추가: use zeroize::Zeroize;
4추가: // 최근 8 MiB만 메모리에 두고 더 먼 사전 참조는 임시 파일에서 읽음.
5추가: struct History<'a> {
6추가: file: &'a mut std::fs::File,
7추가: base: u64,
8추가: len: u64,
9추가: cache: zeroize::Zeroizing<Vec<u8>>,
10추가: pending: zeroize::Zeroizing<Vec<u8>>,
11추가: }
12추가: impl<'a> History<'a> {
13추가: fn new(file: &'a mut std::fs::File, dictionary: usize) -> Result<Self> {
14추가: use std::io::Seek;
15추가: let base = file.stream_position().map_err(crate::space::io_error)?;
16추가: Ok(Self {
17추가: file,
18추가: base,
19추가: len: 0,
20추가: cache: zeroize::Zeroizing::new(vec![0; dictionary.min(8 * 1024 * 1024)]),
21추가: pending: zeroize::Zeroizing::new(Vec::with_capacity(65536)),
22추가: })
23추가: }
24추가: fn len(&self) -> u64 {
25추가: self.len
26추가: }
27추가: fn flush(&mut self) -> Result<()> {
28추가: use std::io::Write;
29추가: self.file
30추가: .write_all(&self.pending)
31추가: .map_err(crate::space::io_error)?;
32추가: self.pending.as_mut_slice().zeroize();
33추가: self.pending.clear();
34추가: Ok(())
35추가: }
36추가: fn extend(&mut self, mut bytes: &[u8]) -> Result<()> {
37추가: while !bytes.is_empty() {
38추가: let at = (self.len % self.cache.len() as u64) as usize;
39추가: let n = bytes
40추가: .len()
41추가: .min(self.cache.len() - at)
42추가: .min(65536 - self.pending.len());
43추가: self.cache[at..at + n].copy_from_slice(&bytes[..n]);
44추가: self.pending.extend_from_slice(&bytes[..n]);
45추가: self.len = self.len.checked_add(n as u64).ok_or(ErrorCode::Limit)?;
46추가: bytes = &bytes[n..];
47추가: if self.pending.len() == 65536 {
48추가: self.flush()?;
49추가: }
50추가: }
51추가: Ok(())
52추가: }
53추가: fn push(&mut self, byte: u8) -> Result<()> {
54추가: self.extend(&[byte])
55추가: }
56추가: fn read_back(&mut self, distance: usize, bytes: &mut [u8]) -> Result<()> {
57추가: use std::io::{Read, Seek, SeekFrom};
58추가: if distance as u64 > self.len || bytes.len() > distance {
59추가: return Err(ErrorCode::Integrity);
60추가: }
61추가: if distance <= self.cache.len() {
62추가: let at = ((self.len - distance as u64) % self.cache.len() as u64) as usize;
63추가: let n = bytes.len().min(self.cache.len() - at);
64추가: bytes[..n].copy_from_slice(&self.cache[at..at + n]);
65추가: let rest = bytes.len() - n;
66추가: bytes[n..].copy_from_slice(&self.cache[..rest]);
67추가: } else {
68추가: self.flush()?;
69추가: self.file
70추가: .seek(SeekFrom::Start(self.base + self.len - distance as u64))
71추가: .map_err(crate::space::io_error)?;
72추가: self.file
73추가: .read_exact(bytes)
74추가: .map_err(crate::space::io_error)?;
75추가: self.file
76추가: .seek(SeekFrom::Start(self.base + self.len))
77추가: .map_err(crate::space::io_error)?;
78추가: }
79추가: Ok(())
80추가: }
81추가: fn previous(&mut self, history: u64, distance: u32, dictionary: usize) -> Result<u8> {
82추가: let distance = distance as usize + 1;
83추가: if distance > dictionary || distance as u64 > self.len - history {
84추가: return Err(ErrorCode::Integrity);
85추가: }
86추가: let mut value = [0];
87추가: self.read_back(distance, &mut value)?;
88추가: Ok(value[0])
89추가: }
90추가: fn copy(
91추가: &mut self,
92추가: history: u64,
93추가: distance: u32,
94추가: dictionary: usize,
95추가: length: usize,
96추가: ) -> Result<()> {
97추가: let distance = distance as usize + 1;
98추가: if distance > dictionary || distance as u64 > self.len - history {
99추가: return Err(ErrorCode::Integrity);
100추가: }
101추가: let mut buffer = zeroize::Zeroizing::new([0; 273]);
102추가: if distance == 1 {
103추가: let byte = self.previous(history, 0, dictionary)?;
104추가: buffer[..length].fill(byte);
105추가: return self.extend(&buffer[..length]);
106추가: }
107추가: let mut remaining = length;
108추가: while remaining != 0 {
109추가: let n = remaining.min(distance).min(buffer.len());
110추가: self.read_back(distance, &mut buffer[..n])?;
111추가: self.extend(&buffer[..n])?;
112추가: remaining -= n;
113추가: }
114추가: Ok(())
115추가: }
116추가: }
2117type Result<T> = std::result::Result<T, ErrorCode>;
3118const MAX_DICT: usize = 64 * 1024 * 1024;
4119struct Range<'a> {
5삭제: input: &'a [u8],
6삭제: at: usize,
120추가: input: &'a mut dyn Read,
121추가: at: u64,
122추가: length: u64,
7123 range: u32,
8124 code: u32,
9125}
10126impl<'a> Range<'a> {
11삭제: fn new(input: &'a [u8]) -> Result<Self> {
12삭제: if input.len() < 5 || input[0] != 0 {
127추가: fn new(input: &'a mut dyn Read, length: u64) -> Result<Self> {
128추가: let mut prefix = [0; 5];
129추가: input
130추가: .read_exact(&mut prefix)
131추가: .map_err(|_| ErrorCode::Integrity)?;
132추가: if length < 5 || prefix[0] != 0 {
13133 return Err(ErrorCode::Integrity);
14134 }
15135 Ok(Self {
16136 input,
17137 at: 5,
138추가: length,
18139 range: u32::MAX,
19삭제: code: u32::from_be_bytes(input[1..5].try_into().unwrap()),
140추가: code: u32::from_be_bytes(prefix[1..5].try_into().unwrap()),
20141 })
21142 }
22143 fn normalize(&mut self) -> Result<()> {
23144 if self.range < 1 << 24 {
24145 self.range <<= 8;
25삭제: self.code =
26삭제: (self.code << 8) | *self.input.get(self.at).ok_or(ErrorCode::Integrity)? as u32;
146추가: if self.at >= self.length {
147추가: return Err(ErrorCode::Integrity);
148추가: }
149추가: let mut byte = [0];
150추가: self.input
151추가: .read_exact(&mut byte)
152추가: .map_err(|_| ErrorCode::Integrity)?;
153추가: self.code = (self.code << 8) | byte[0] as u32;
27154 self.at += 1;
28155 }
29156 Ok(())
@@ -76,7 +203,7 @@ impl<'a> Range<'a> {
76203 Ok(value)
77204 }
78205 fn finished(&self) -> bool {
79삭제: self.code == 0 && self.at == self.input.len()
206추가: self.code == 0 && self.at == self.length
80207 }
81208}
82209struct Length {
@@ -158,35 +285,32 @@ impl Model {
158285 *self = Self::new(((self.pb * 5 + self.lp) * 9 + self.lc) as u8)?;
159286 Ok(())
160287 }
161삭제: fn previous(out: &[u8], history: usize, distance: u32, dictionary: usize) -> Result<u8> {
162삭제: let distance = distance as usize + 1;
163삭제: if distance > dictionary || distance > out.len() - history {
164삭제: return Err(ErrorCode::Integrity);
165삭제: }
166삭제: Ok(out[out.len() - distance])
167삭제: }
168288 fn symbol(
169289 &mut self,
170290 r: &mut Range<'_>,
171삭제: out: &mut Vec<u8>,
172삭제: history: usize,
291추가: out: &mut History<'_>,
292추가: history: u64,
173293 dictionary: usize,
174삭제: target: usize,
294추가: target: u64,
175295 ) -> Result<bool> {
176296 let pos = out.len() - history;
177삭제: let position = pos & ((1 << self.pb) - 1);
297추가: let position = pos as usize & ((1 << self.pb) - 1);
178298 let state = self.state;
179299 if r.bit(&mut self.matches[state][position])? == 0 {
180300 if out.len() >= target {
181301 return Err(ErrorCode::Integrity);
182302 }
183삭제: let previous = if pos == 0 { 0 } else { *out.last().unwrap() };
184삭제: let context =
185삭제: ((pos & ((1 << self.lp) - 1)) << self.lc) + (previous as usize >> (8 - self.lc));
303추가: let previous = if pos == 0 {
304추가: 0
305추가: } else {
306추가: out.previous(history, 0, dictionary)?
307추가: };
308추가: let context = (((pos as usize) & ((1 << self.lp) - 1)) << self.lc)
309추가: + (previous as usize >> (8 - self.lc));
186310 let p = &mut self.literal[context * 0x300..(context + 1) * 0x300];
187311 let mut symbol = 1;
188312 if state >= 7 {
189삭제: let mut matched = Self::previous(out, history, self.reps[0], dictionary)?;
313추가: let mut matched = out.previous(history, self.reps[0], dictionary)?;
190314 while symbol < 256 {
191315 let m = (matched >> 7) as usize;
192316 matched <<= 1;
@@ -200,7 +324,7 @@ impl Model {
200324 while symbol < 256 {
201325 symbol = (symbol << 1) | r.bit(&mut p[symbol])?;
202326 }
203삭제: out.push(symbol as u8);
327추가: out.push(symbol as u8)?;
204328 self.state = if state < 4 {
205329 0
206330 } else if state < 10 {
@@ -218,7 +342,8 @@ impl Model {
218342 if out.len() >= target {
219343 return Err(ErrorCode::Integrity);
220344 }
221삭제: out.push(Self::previous(out, history, self.reps[0], dictionary)?);
345추가: let byte = out.previous(history, self.reps[0], dictionary)?;
346추가: out.push(byte)?;
222347 return Ok(false);
223348 }
224349 } else {
@@ -261,25 +386,28 @@ impl Model {
261386 self.reps.rotate_right(1);
262387 self.reps[0] = distance;
263388 }
264삭제: if out.len().checked_add(length).is_none_or(|n| n > target) {
389추가: if out
390추가: .len()
391추가: .checked_add(length as u64)
392추가: .is_none_or(|n| n > target)
393추가: {
265394 return Err(ErrorCode::Integrity);
266395 }
267삭제: for _ in 0..length {
268삭제: out.push(Self::previous(out, history, self.reps[0], dictionary)?);
269삭제: }
396추가: out.copy(history, self.reps[0], dictionary, length)?;
270397 Ok(false)
271398 }
272399 fn decode(
273400 &mut self,
274삭제: input: &[u8],
275삭제: out: &mut Vec<u8>,
276삭제: history: usize,
401추가: input: &mut dyn Read,
402추가: length: u64,
403추가: out: &mut History<'_>,
404추가: history: u64,
277405 dictionary: usize,
278삭제: target: usize,
406추가: target: u64,
279407 eos: bool,
280408 check: &mut impl FnMut() -> Result<()>,
281409 ) -> Result<()> {
282삭제: let mut range = Range::new(input)?;
410추가: let mut range = Range::new(input, length)?;
283411 let mut next_check = out.len();
284412 while out.len() < target {
285413 if out.len() >= next_check {
@@ -307,53 +435,72 @@ fn dictionary(size: u64) -> Result<usize> {
307435 }
308436 Ok((size as usize).max(4096))
309437}
310삭제: pub(crate) fn decode(
311삭제: input: &[u8],
438추가: pub(crate) fn decode_stream(
439추가: input: &mut impl std::io::Read,
440추가: length: u64,
312441 properties: &[u8],
313442 lzma2: bool,
314삭제: size: usize,
443추가: size: u64,
444추가: output: &mut std::fs::File,
315445 check: &mut impl FnMut() -> Result<()>,
316삭제: ) -> Result<Vec<u8>> {
317삭제: let mut out = Vec::new();
318삭제: out.try_reserve_exact(size).map_err(|_| ErrorCode::Limit)?;
319삭제: if !lzma2 {
446추가: ) -> Result<()> {
447추가: use std::io::{BufReader, Read};
448추가: crate::space::ensure(output, size)?;
449추가: let dict = if !lzma2 {
320450 if properties.len() != 5 {
321451 return Err(ErrorCode::Integrity);
322452 }
323삭제: let dictionary =
324삭제: dictionary(u32::from_le_bytes(properties[1..5].try_into().unwrap()) as u64)?;
325삭제: Model::new(properties[0])?.decode(input, &mut out, 0, dictionary, size, true, check)?;
326삭제: return Ok(out);
327삭제: }
328삭제: if properties.len() != 1 || properties[0] > 40 {
329삭제: return Err(ErrorCode::Integrity);
330삭제: }
331삭제: let prop = properties[0] as u32;
332삭제: let dictionary = dictionary(if prop == 40 {
333삭제: u32::MAX as u64
453추가: dictionary(u32::from_le_bytes(properties[1..5].try_into().unwrap()) as u64)?
334454 } else {
335삭제: ((2 | (prop & 1)) as u64) << (prop / 2 + 11)
336삭제: })?;
337삭제: let mut at = 0;
455추가: if properties.len() != 1 || properties[0] > 40 {
456추가: return Err(ErrorCode::Integrity);
457추가: }
458추가: let prop = properties[0] as u32;
459추가: dictionary(if prop == 40 {
460추가: u32::MAX as u64
461추가: } else {
462추가: ((2 | (prop & 1)) as u64) << (prop / 2 + 11)
463추가: })?
464추가: };
465추가: let mut out = History::new(output, dict)?;
466추가: let mut reader = BufReader::with_capacity(65536, input.take(length));
467추가: if !lzma2 {
468추가: Model::new(properties[0])?.decode(
469추가: &mut reader,
470추가: length,
471추가: &mut out,
472추가: 0,
473추가: dict,
474추가: size,
475추가: true,
476추가: check,
477추가: )?;
478추가: return out.flush();
479추가: }
480추가: let byte = |r: &mut dyn Read| -> Result<u8> {
481추가: let mut b = [0];
482추가: r.read_exact(&mut b).map_err(|_| ErrorCode::Integrity)?;
483추가: Ok(b[0])
484추가: };
485추가: let word = |r: &mut dyn Read| -> Result<usize> {
486추가: let mut b = [0; 2];
487추가: r.read_exact(&mut b).map_err(|_| ErrorCode::Integrity)?;
488추가: Ok(u16::from_be_bytes(b) as usize + 1)
489추가: };
338490 let mut history = 0;
339491 let mut have_dictionary = false;
340492 let mut need_state = true;
341493 let mut model: Option<Model> = None;
342494 loop {
343495 check()?;
344삭제: let control = *input.get(at).ok_or(ErrorCode::Integrity)?;
345삭제: at += 1;
496추가: let control = byte(&mut reader)?;
346497 if control == 0 {
347삭제: if at != input.len() || out.len() != size {
498추가: let mut extra = [0];
499추가: if reader.read(&mut extra).map_err(crate::space::io_error)? != 0 || out.len() != size {
348500 return Err(ErrorCode::Integrity);
349501 }
350삭제: return Ok(out);
502추가: return out.flush();
351503 }
352삭제: let take16 = |at: &mut usize| -> Result<usize> {
353삭제: let bytes = input.get(*at..*at + 2).ok_or(ErrorCode::Integrity)?;
354삭제: *at += 2;
355삭제: Ok(u16::from_be_bytes(bytes.try_into().unwrap()) as usize + 1)
356삭제: };
357504 if control == 1 || control >= 0xe0 {
358505 history = out.len();
359506 have_dictionary = true;
@@ -362,21 +509,25 @@ pub(crate) fn decode(
362509 if !have_dictionary {
363510 return Err(ErrorCode::Integrity);
364511 }
365삭제: let unpacked = take16(&mut at)?;
512추가: let unpacked = word(&mut reader)?;
366513 if control <= 2 {
367삭제: let end = at.checked_add(unpacked).ok_or(ErrorCode::Integrity)?;
368삭제: if out.len().checked_add(unpacked).is_none_or(|n| n > size) {
369삭제: return Err(ErrorCode::Integrity);
370삭제: }
371삭제: out.extend_from_slice(input.get(at..end).ok_or(ErrorCode::Integrity)?);
372삭제: at = end;
514추가: let target = out
515추가: .len()
516추가: .checked_add(unpacked as u64)
517추가: .filter(|n| *n <= size)
518추가: .ok_or(ErrorCode::Integrity)?;
519추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
520추가: reader
521추가: .read_exact(&mut buffer[..unpacked])
522추가: .map_err(|_| ErrorCode::Integrity)?;
523추가: out.extend(&buffer[..unpacked])?;
524추가: debug_assert_eq!(out.len(), target);
373525 need_state = true;
374526 } else if control >= 0x80 {
375527 let unpacked = unpacked + ((control as usize & 31) << 16);
376삭제: let packed = take16(&mut at)?;
528추가: let packed = word(&mut reader)? as u64;
377529 if control >= 0xc0 {
378삭제: model = Some(Model::new(*input.get(at).ok_or(ErrorCode::Integrity)?)?);
379삭제: at += 1;
530추가: model = Some(Model::new(byte(&mut reader)?)?);
380531 }
381532 let model = model.as_mut().ok_or(ErrorCode::Integrity)?;
382533 if control >= 0xa0 {
@@ -384,25 +535,28 @@ pub(crate) fn decode(
384535 } else if need_state {
385536 return Err(ErrorCode::Integrity);
386537 }
387삭제: let end = at.checked_add(packed).ok_or(ErrorCode::Integrity)?;
388538 let target = out
389539 .len()
390삭제: .checked_add(unpacked)
540추가: .checked_add(unpacked as u64)
391541 .filter(|n| *n <= size)
392542 .ok_or(ErrorCode::Integrity)?;
393543 model.decode(
394삭제: input.get(at..end).ok_or(ErrorCode::Integrity)?,
544추가: &mut (&mut reader).take(packed),
545추가: packed,
395546 &mut out,
396547 history,
397삭제: dictionary,
548추가: dict,
398549 target,
399550 false,
400551 check,
401552 )?;
402삭제: at = end;
403553 need_state = false;
404554 } else {
405555 return Err(ErrorCode::Integrity);
406556 }
407557 }
408558}
559추가:
560추가: #[cfg(test)]
561추가: #[path = "../../../tests/rust-archive-worker/lzma_streaming.rs"]
562추가: mod tests;
수정experiments/rust-archive-worker/src/runtime.rs+15-56
@@ -1,5 +1,5 @@
11use crate::{
2삭제: archive::{self, Member},
2추가: archive,
33 filesystem::{self, Dir},
44 protocol::*,
55 wire::{Reader, Writer},
@@ -114,23 +114,6 @@ impl<W: Write> Job<W> {
114114 completed_entries: entries,
115115 })
116116 }
117삭제: fn output(
118삭제: &mut self,
119삭제: root: &Dir,
120삭제: name: &str,
121삭제: data: &[u8],
122삭제: id: Option<u32>,
123삭제: last: bool,
124삭제: ) -> Result<()> {
125삭제: self.output_reader(
126삭제: root,
127삭제: name,
128삭제: &mut std::io::Cursor::new(data),
129삭제: data.len() as u64,
130삭제: id,
131삭제: last,
132삭제: )
133삭제: }
134117 fn output_reader(
135118 &mut self,
136119 root: &Dir,
@@ -416,33 +399,15 @@ impl<W: Write> Job<W> {
416399 method,
417400 encryption,
418401 } => {
419삭제: let limits = start.limits.legacy();
420삭제: if sources.len() > limits.entries as usize {
421삭제: return Err(ErrorCode::Limit);
422삭제: }
423삭제: let mut members = Vec::new();
424삭제: let mut consumed = 0;
425삭제: for source in sources {
426삭제: self.check()?;
427삭제: let name = archive::valid_name(&source.archive_name, false)?;
428삭제: let snapshot = filesystem::snapshot(
429삭제: &source.path.to_path()?,
430삭제: limits.input - consumed,
431삭제: &mut || self.check(),
432삭제: )?;
433삭제: consumed += snapshot.bytes.len() as u64;
434삭제: members.push(Member {
435삭제: entry: Entry {
436삭제: entry_id: members.len() as u32,
437삭제: name,
438삭제: kind: EntryKind::File,
439삭제: size: snapshot.bytes.len() as u64,
440삭제: compressed_size: 0,
441삭제: encrypted: false,
442삭제: },
443삭제: data: snapshot.bytes,
444삭제: });
445삭제: }
402추가: let output = output_file.to_path()?;
403추가: let leaf = output
404추가: .file_name()
405추가: .and_then(|n| n.to_str())
406추가: .ok_or(ErrorCode::InvalidRequest)?;
407추가: let name = archive::valid_name(leaf, false)?;
408추가: let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
409추가: filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
410추가: let members = crate::create::plan(&sources, start.limits)?;
446411 let secret = if encryption == Encryption::Aes256 {
447412 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
448413 if secret.0.is_empty() {
@@ -452,22 +417,16 @@ impl<W: Write> Job<W> {
452417 } else {
453418 None
454419 };
455삭제: let bytes = archive::create_zip_with_password(
420추가: let (mut data, length) = crate::create::zip(
421추가: &sources,
456422 &members,
457423 method,
458삭제: limits,
424추가: start.limits,
459425 secret.as_ref().map(|s| s.0.as_slice()),
460426 &mut || self.check(),
461427 )?;
462삭제: let output = output_file.to_path()?;
463삭제: let leaf = output
464삭제: .file_name()
465삭제: .and_then(|n| n.to_str())
466삭제: .ok_or(ErrorCode::InvalidRequest)?;
467삭제: let name = archive::valid_name(leaf, false)?;
468삭제: let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
469삭제: filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
470삭제: self.output(&root, &name, &bytes, None, true)?;
428추가: filesystem::preflight_space(&root, &[(name.clone(), length)], None)?;
429추가: self.output_reader(&root, &name, &mut data, length, None, true)?;
471430 self.terminal.publication = Publication::Complete;
472431 }
473432 }
수정experiments/rust-archive-worker/src/seven_zip.rs+214-92
@@ -262,61 +262,131 @@ impl Streams {
262262 folders,
263263 })
264264 }
265삭제: fn bounds<'a>(&self, input: &'a [u8], data_end: usize) -> Result<Vec<&'a [u8]>> {
266삭제: let mut at = 32usize
267삭제: .checked_add(self.position)
265추가: fn ranges(
266추가: &self,
267추가: input: &mut std::fs::File,
268추가: data_end: u64,
269추가: check: &mut impl FnMut() -> Result<()>,
270추가: ) -> Result<Vec<(u64, u64)>> {
271추가: let mut at = 32u64
272추가: .checked_add(self.position as u64)
268273 .ok_or(ErrorCode::Integrity)?;
269삭제: let mut slices = Vec::new();
274추가: let mut ranges = Vec::new();
270275 for (size, expected) in self.packed.iter().zip(&self.packed_crcs) {
276추가: let size = *size as u64;
271277 let end = at
272삭제: .checked_add(*size)
273삭제: .filter(|end| *end <= data_end)
278추가: .checked_add(size)
279추가: .filter(|n| *n <= data_end)
274280 .ok_or(ErrorCode::Integrity)?;
275삭제: let bytes = input.get(at..end).ok_or(ErrorCode::Integrity)?;
276삭제: if expected.is_some_and(|crc| crc32(0, bytes) != crc) {
277삭제: return Err(ErrorCode::Integrity);
281추가: if let Some(expected) = expected {
282추가: if digest(input, at, size, check)? != *expected {
283추가: return Err(ErrorCode::Integrity);
284추가: }
278285 }
279삭제: slices.push(bytes);
286추가: ranges.push((at, size));
280287 at = end;
281288 }
282삭제: Ok(slices)
289추가: Ok(ranges)
283290 }
284삭제: fn decode(
291추가: fn decode_file(
285292 &self,
286삭제: packed: &[&[u8]],
293추가: input: &mut std::fs::File,
294추가: ranges: &[(u64, u64)],
295추가: output: &mut std::fs::File,
287296 check: &mut impl FnMut() -> Result<()>,
288삭제: ) -> Result<Vec<Vec<u8>>> {
289삭제: self.folders
290삭제: .iter()
291삭제: .zip(packed)
292삭제: .map(|(f, bytes)| {
293삭제: check()?;
294삭제: let out = match f.method.as_slice() {
295삭제: [0] => {
296삭제: if !f.properties.is_empty() || bytes.len() != f.size {
297삭제: return Err(ErrorCode::Integrity);
298삭제: }
299삭제: bytes.to_vec()
297추가: ) -> Result<()> {
298추가: use std::io::{Read, Seek, SeekFrom, Write};
299추가: let total = self.folders.iter().try_fold(0u64, |sum, f| {
300추가: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit)
301추가: })?;
302추가: crate::space::ensure(output, total)?;
303추가: for (f, (start, size)) in self.folders.iter().zip(ranges) {
304추가: check()?;
305추가: let base = output.stream_position().map_err(crate::space::io_error)?;
306추가: input
307추가: .seek(SeekFrom::Start(*start))
308추가: .map_err(crate::space::io_error)?;
309추가: match f.method.as_slice() {
310추가: [0] => {
311추가: if !f.properties.is_empty() || *size != f.size as u64 {
312추가: return Err(ErrorCode::Integrity);
313추가: }
314추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
315추가: let mut remaining = *size;
316추가: while remaining != 0 {
317추가: check()?;
318추가: let n = remaining.min(buffer.len() as u64) as usize;
319추가: input
320추가: .read_exact(&mut buffer[..n])
321추가: .map_err(|_| ErrorCode::Integrity)?;
322추가: output
323추가: .write_all(&buffer[..n])
324추가: .map_err(crate::space::io_error)?;
325추가: remaining -= n as u64;
300326 }
301삭제: [3, 1, 1] => crate::lzma::decode(bytes, &f.properties, false, f.size, check)?,
302삭제: [0x21] => crate::lzma::decode(bytes, &f.properties, true, f.size, check)?,
303삭제: _ => return Err(ErrorCode::UnsupportedFeature),
304삭제: };
305삭제: if f.crc.is_some_and(|crc| crc32(0, &out) != crc) {
306삭제: return Err(ErrorCode::Integrity);
307327 }
308삭제: let mut at = 0;
309삭제: for (size, crc) in f.sizes.iter().zip(&f.crcs) {
310삭제: let end = at + *size;
311삭제: if crc.is_some_and(|crc| crc32(0, &out[at..end]) != crc) {
328추가: [3, 1, 1] | [0x21] => crate::lzma::decode_stream(
329추가: input,
330추가: *size,
331추가: &f.properties,
332추가: f.method == [0x21],
333추가: f.size as u64,
334추가: output,
335추가: check,
336추가: )?,
337추가: _ => return Err(ErrorCode::UnsupportedFeature),
338추가: }
339추가: let single = f.sizes.len() == 1 && f.sizes[0] == f.size;
340추가: let folder_crc = if f.crc.is_some() || single && f.crcs[0].is_some() {
341추가: Some(digest(output, base, f.size as u64, check)?)
342추가: } else {
343추가: None
344추가: };
345추가: if f.crc.is_some() && f.crc != folder_crc {
346추가: return Err(ErrorCode::Integrity);
347추가: }
348추가: let mut at = base;
349추가: for (size, expected) in f.sizes.iter().zip(&f.crcs) {
350추가: if let Some(expected) = expected {
351추가: let actual = if single {
352추가: folder_crc.ok_or(ErrorCode::Internal)?
353추가: } else {
354추가: digest(output, at, *size as u64, check)?
355추가: };
356추가: if actual != *expected {
312357 return Err(ErrorCode::Integrity);
313358 }
314삭제: at = end;
315359 }
316삭제: Ok(out)
317삭제: })
318삭제: .collect()
360추가: at = at.checked_add(*size as u64).ok_or(ErrorCode::Integrity)?;
361추가: }
362추가: output
363추가: .seek(SeekFrom::Start(base + f.size as u64))
364추가: .map_err(crate::space::io_error)?;
365추가: }
366추가: Ok(())
367추가: }
368추가: }
369추가: fn digest(
370추가: file: &mut std::fs::File,
371추가: start: u64,
372추가: size: u64,
373추가: check: &mut impl FnMut() -> Result<()>,
374추가: ) -> Result<u32> {
375추가: use std::io::{Read, Seek, SeekFrom};
376추가: file.seek(SeekFrom::Start(start))
377추가: .map_err(crate::space::io_error)?;
378추가: let mut crc = 0;
379추가: let mut remaining = size;
380추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
381추가: while remaining != 0 {
382추가: check()?;
383추가: let n = remaining.min(buffer.len() as u64) as usize;
384추가: file.read_exact(&mut buffer[..n])
385추가: .map_err(crate::space::io_error)?;
386추가: crc = crc32(crc, &buffer[..n]);
387추가: remaining -= n as u64;
319388 }
389추가: Ok(crc)
320390}
321391fn files(
322392 r: &mut Reader<'_>,
@@ -471,14 +541,26 @@ fn files(
471541 validate_members(&members)?;
472542 Ok((members, stream_indices))
473543}
474삭제: pub(crate) fn parse(
475삭제: input: &[u8],
544추가: pub(crate) fn open(
545추가: input: &mut std::fs::File,
546추가: length: u64,
476547 limits: Limits,
477548 decode: bool,
478549 check: &mut impl FnMut() -> Result<()>,
479삭제: ) -> Result<Vec<Member>> {
550추가: ) -> Result<crate::streaming::Catalog> {
551추가: use std::io::{Read, Seek, SeekFrom};
480552 check()?;
481삭제: let header = input.get(..32).ok_or(ErrorCode::Integrity)?;
553추가: if length > limits.input {
554추가: return Err(ErrorCode::Limit);
555추가: }
556추가: input.rewind().map_err(crate::space::io_error)?;
557추가: let mut header = [0; 32];
558추가: input
559추가: .read_exact(&mut header)
560추가: .map_err(|_| ErrorCode::Integrity)?;
561추가: if &header[..6] != b"7z\xbc\xaf\x27\x1c" {
562추가: return Err(ErrorCode::Integrity);
563추가: }
482564 if header[6] != 0 || header[7] > 4 {
483565 return Err(ErrorCode::UnsupportedFeature);
484566 }
@@ -490,55 +572,61 @@ pub(crate) fn parse(
490572 if len > MAX_METADATA_BYTES as u64 {
491573 return Err(ErrorCode::Limit);
492574 }
493삭제: let start = usize::try_from(offset)
494삭제: .ok()
495삭제: .and_then(|n| n.checked_add(32))
496삭제: .ok_or(ErrorCode::Integrity)?;
497삭제: let end = start
498삭제: .checked_add(len as usize)
499삭제: .filter(|n| *n == input.len())
500삭제: .ok_or(ErrorCode::Integrity)?;
501삭제: let bytes = input.get(start..end).ok_or(ErrorCode::Integrity)?;
502삭제: if crc32(0, bytes) != u32::from_le_bytes(header[28..32].try_into().unwrap()) {
575추가: let start = offset.checked_add(32).ok_or(ErrorCode::Integrity)?;
576추가: if start.checked_add(len) != Some(length) {
503577 return Err(ErrorCode::Integrity);
504578 }
579추가: input
580추가: .seek(SeekFrom::Start(start))
581추가: .map_err(crate::space::io_error)?;
582추가: let mut bytes = vec![0; len as usize];
583추가: input
584추가: .read_exact(&mut bytes)
585추가: .map_err(|_| ErrorCode::Integrity)?;
586추가: if crc32(0, &bytes) != u32::from_le_bytes(header[28..32].try_into().unwrap()) {
587추가: return Err(ErrorCode::Integrity);
588추가: }
589추가: let mut data = crate::spool::temporary()?;
505590 if bytes.is_empty() {
506삭제: return if start == 32 {
507삭제: Ok(Vec::new())
508삭제: } else {
509삭제: Err(ErrorCode::Integrity)
510삭제: };
591추가: if start != 32 {
592추가: return Err(ErrorCode::Integrity);
593추가: }
594추가: return Ok(crate::streaming::Catalog {
595추가: format: Format::SevenZip,
596추가: members: Vec::new(),
597추가: offsets: Vec::new(),
598추가: data,
599추가: });
511600 }
512601 let mut data_end = start;
513삭제: let decoded_header;
514삭제: let bytes = if bytes[0] == 23 {
602추가: if bytes[0] == 23 {
515603 let mut r = Reader::new(&bytes[1..]);
516삭제: let mut header_limits = limits;
517삭제: header_limits.output = MAX_METADATA_BYTES as u64;
604추가: let header_limits = Limits {
605추가: output: MAX_METADATA_BYTES as u64,
606추가: ..limits
607추가: };
518608 let streams = Streams::read(&mut r, header_limits)?;
519609 r.end()?;
520610 if streams.folders.len() != 1 || streams.folders[0].sizes.len() != 1 {
521611 return Err(ErrorCode::UnsupportedFeature);
522612 }
523삭제: let packed = streams.bounds(input, data_end)?;
524삭제: decoded_header = streams
525삭제: .decode(&packed, check)?
526삭제: .pop()
613추가: let ranges = streams.ranges(input, data_end, check)?;
614추가: streams.decode_file(input, &ranges, &mut data, check)?;
615추가: data_end = 32u64
616추가: .checked_add(streams.position as u64)
527617 .ok_or(ErrorCode::Integrity)?;
528삭제: data_end = 32 + streams.position;
529삭제: &decoded_header
530삭제: } else {
531삭제: bytes
532삭제: };
533삭제: let mut r = Reader::new(bytes);
618추가: data.rewind().map_err(crate::space::io_error)?;
619추가: bytes.clear();
620추가: data.read_to_end(&mut bytes)
621추가: .map_err(crate::space::io_error)?;
622추가: data = crate::spool::temporary()?;
623추가: }
624추가: let mut r = Reader::new(&bytes);
534625 r.expect(1)?;
535626 let mut streams = None;
536627 let mut tag = r.byte()?;
537628 if tag == 2 {
538삭제: while {
539삭제: let tag = r.byte()?;
540삭제: tag != 0
541삭제: } {
629추가: while r.byte()? != 0 {
542630 let len = r.number(MAX_METADATA_BYTES)?;
543631 r.take(len)?;
544632 }
@@ -551,7 +639,7 @@ pub(crate) fn parse(
551639 streams = Some(Streams::read(&mut r, limits)?);
552640 tag = r.byte()?;
553641 }
554삭제: let (mut members, stream_indices) = if tag == 5 {
642추가: let (members, stream_indices) = if tag == 5 {
555643 let f = files(&mut r, limits, streams.as_ref())?;
556644 tag = r.byte()?;
557645 f
@@ -562,26 +650,60 @@ pub(crate) fn parse(
562650 return Err(ErrorCode::Integrity);
563651 }
564652 r.end()?;
653추가: let mut offsets = vec![0; members.len()];
565654 if let Some(streams) = streams {
566655 if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() {
567656 return Err(ErrorCode::Integrity);
568657 }
569삭제: let packed = streams.bounds(input, data_end)?;
570삭제: if decode {
571삭제: let output = streams.decode(&packed, check)?;
572삭제: let mut stream_files = stream_indices.into_iter();
573삭제: for (folder, bytes) in streams.folders.iter().zip(output) {
574삭제: let mut at = 0;
575삭제: for size in &folder.sizes {
576삭제: let member = &mut members[stream_files.next().ok_or(ErrorCode::Integrity)?];
577삭제: if member.entry.size as usize != *size {
578삭제: return Err(ErrorCode::Integrity);
579삭제: }
580삭제: member.data = bytes[at..at + size].to_vec();
581삭제: at += size;
582삭제: }
658추가: let ranges = streams.ranges(input, data_end, check)?;
659추가: let mut at = 0u64;
660추가: let mut ids = stream_indices.into_iter();
661추가: for f in &streams.folders {
662추가: for size in &f.sizes {
663추가: offsets[ids.next().ok_or(ErrorCode::Integrity)?] = at;
664추가: at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?;
583665 }
584666 }
667추가: if at > limits.output {
668추가: return Err(ErrorCode::Limit);
669추가: }
670추가: if decode {
671추가: streams.decode_file(input, &ranges, &mut data, check)?;
672추가: }
673추가: }
674추가: Ok(crate::streaming::Catalog {
675추가: format: Format::SevenZip,
676추가: members,
677추가: offsets,
678추가: data,
679추가: })
680추가: }
681추가: pub(crate) fn parse(
682추가: input: &[u8],
683추가: limits: Limits,
684추가: decode: bool,
685추가: check: &mut impl FnMut() -> Result<()>,
686추가: ) -> Result<Vec<Member>> {
687추가: use std::io::{Read, Seek, SeekFrom, Write};
688추가: let mut source = crate::spool::temporary()?;
689추가: crate::space::ensure(&source, input.len() as u64)?;
690추가: source.write_all(input).map_err(crate::space::io_error)?;
691추가: let mut catalog = open(&mut source, input.len() as u64, limits, decode, check)?;
692추가: if decode {
693추가: for (member, offset) in catalog.members.iter_mut().zip(catalog.offsets) {
694추가: catalog
695추가: .data
696추가: .seek(SeekFrom::Start(offset))
697추가: .map_err(crate::space::io_error)?;
698추가: member
699추가: .data
700추가: .try_reserve_exact(member.entry.size as usize)
701추가: .map_err(|_| ErrorCode::Limit)?;
702추가: (&mut catalog.data)
703추가: .take(member.entry.size)
704추가: .read_to_end(&mut member.data)
705추가: .map_err(crate::space::io_error)?;
706추가: }
585707 }
586삭제: Ok(members)
708추가: Ok(catalog.members)
587709}
수정experiments/rust-archive-worker/src/spool.rs+2-12
@@ -95,16 +95,6 @@ impl Snapshot {
9595 if !before.is_file() {
9696 return Err(ErrorCode::InvalidRequest);
9797 }
98삭제: let mut prefix = [0; 6];
99삭제: let prefix_len = before.len().min(prefix.len() as u64) as usize;
100삭제: source
101삭제: .read_exact(&mut prefix[..prefix_len])
102삭제: .map_err(|_| ErrorCode::SourceChanged)?;
103삭제: let limit = if prefix == *b"7z\xbc\xaf\x27\x1c" {
104삭제: limit.min(64 * 1024 * 1024)
105삭제: } else {
106삭제: limit
107삭제: };
10898 if before.len() > limit {
10999 return Err(ErrorCode::Limit);
110100 }
@@ -112,12 +102,12 @@ impl Snapshot {
112102 let object = filesystem::object(&source)?;
113103 let mut file = temporary()?;
114104 crate::space::ensure(&file, before.len())?;
115삭제: let mut buffer = [0; 65536];
105추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
116106 let mut hash = Sha256::new();
117107 let mut len = 0u64;
118108 loop {
119109 check()?;
120삭제: let n = source.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
110추가: let n = source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io)?;
121111 if n == 0 {
122112 break;
123113 }
수정experiments/rust-archive-worker/src/streaming.rs+1-21
@@ -58,27 +58,7 @@ impl Catalog {
5858 let n = len.min(6) as usize;
5959 at(source, 0, &mut magic[..n])?;
6060 if magic.starts_with(b"7z\xbc\xaf\x27\x1c") {
61삭제: let bounded = limits.legacy();
62삭제: if len > bounded.input {
63삭제: return Err(ErrorCode::Limit);
64삭제: }
65삭제: let input = bytes(source, 0, len as usize)?;
66삭제: let catalog = archive::parse_with_password(&input, bounded, decode, password, check)?;
67삭제: let mut data = spool::temporary()?;
68삭제: let mut members = catalog.members;
69삭제: let mut offsets = Vec::new();
70삭제: for m in &mut members {
71삭제: offsets.push(io(data.stream_position())?);
72삭제: io(data.write_all(&m.data))?;
73삭제: m.data.clear();
74삭제: m.data.shrink_to_fit();
75삭제: }
76삭제: return Ok(Self {
77삭제: format: Format::SevenZip,
78삭제: members,
79삭제: offsets,
80삭제: data,
81삭제: });
61추가: return crate::seven_zip::open(source, len, limits, decode, check);
8262 }
8363 if magic.starts_with(b"PK\x03\x04")
8464 || magic.starts_with(b"PK\x05\x06")
추가tests/rust-archive-worker/create_zip_fields.rs+23-0
@@ -0,0 +1,23 @@
1추가: use super::*;
2추가:
3추가: #[test]
4추가: fn zip64_sizes_and_offsets_preserve_u64_values() {
5추가: let boundary = u32::MAX as u64;
6추가: for size in [boundary, boundary + 1, 16 * 1024 * 1024 * 1024] {
7추가: let extra = zip64_extra(size, 17, Some(boundary + 7));
8추가: assert_eq!(&extra[..4], &[1, 0, 24, 0]);
9추가: assert_eq!(u64::from_le_bytes(extra[4..12].try_into().unwrap()), size);
10추가: assert_eq!(u64::from_le_bytes(extra[12..20].try_into().unwrap()), 17);
11추가: assert_eq!(
12추가: u64::from_le_bytes(extra[20..28].try_into().unwrap()),
13추가: boundary + 7
14추가: );
15추가: }
16추가: let extra = zip64_extra(17, 23, Some(boundary));
17추가: assert_eq!(&extra[..4], &[1, 0, 8, 0]);
18추가: assert_eq!(
19추가: u64::from_le_bytes(extra[4..12].try_into().unwrap()),
20추가: boundary
21추가: );
22추가: assert!(zip64_extra(boundary - 1, 23, Some(boundary - 1)).is_empty());
23추가: }
수정tests/rust-archive-worker/hardening.rs+301-5
@@ -2,6 +2,22 @@ use super::*;
22use std::{fs::File, io::Read};
33
44fn generate(s: &Scratch, kind: &str, size: u64) {
5추가: if let Some(method) = kind.strip_prefix("7z-") {
6추가: assert!(
7추가: Command::new("python3")
8추가: .arg(
9추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10추가: .join("../../tests/rust-archive-worker/seven_zip_large.py")
11추가: )
12추가: .arg(&s.0)
13추가: .arg(method)
14추가: .arg(size.to_string())
15추가: .status()
16추가: .unwrap()
17추가: .success()
18추가: );
19추가: return;
20추가: }
521 assert!(
622 Command::new("python3")
723 .arg(
@@ -53,7 +69,7 @@ fn assert_zero_file(path: &std::path::Path, length: u64) {
5369 assert_eq!(total, length);
5470}
5571#[test]
56삭제: fn streaming_defaults_and_legacy_seven_zip_caps() {
72추가: fn streaming_defaults_and_invalid_seven_zip_header() {
5773 assert_eq!(Limits::default().input, u64::MAX);
5874 assert_eq!(Limits::default().output, 16 * 1024 * 1024 * 1024);
5975 assert!(
@@ -66,9 +82,9 @@ fn streaming_defaults_and_legacy_seven_zip_caps() {
6682 let s = Scratch::new();
6783 let file = File::create(s.0.join("input")).unwrap();
6884 (&file).write_all(b"7z\xbc\xaf\x27\x1c").unwrap();
69삭제: file.set_len(1024 * 1024 * 1024).unwrap();
85추가: file.set_len(32).unwrap();
7086 let events = execute(start(&s, false, Limits::default().output));
71삭제: assert_eq!(terminal(&events).error, ErrorCode::Limit);
87추가: assert_eq!(terminal(&events).error, ErrorCode::Integrity);
7288 assert_eq!(terminal(&events).created_count, 0);
7389}
7490#[test]
@@ -254,7 +270,7 @@ fn gzip_high_ratio_members_extract_below_total_limit() {
254270#[test]
255271fn streamed_aes_counter_survives_many_read_chunks() {
256272 let s = Scratch::new();
257삭제: generate(&s, "store", 2 * 1024 * 1024 + 17);
273추가: generate(&s, "store", 129 * 1024 * 1024 + 17);
258274 fs::rename(s.0.join("input"), s.0.join("source")).unwrap();
259275 let events = interactive(
260276 Start {
@@ -294,6 +310,89 @@ fn streamed_aes_counter_survives_many_read_chunks() {
294310 );
295311}
296312
313추가: #[test]
314추가: fn seven_zip_output_total_rejects_before_decode() {
315추가: let s = Scratch::new();
316추가: let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
317추가: .join("../../tests/rust-archive-worker/seven_zip_large.py");
318추가: assert!(
319추가: Command::new("python3")
320추가: .arg(helper)
321추가: .arg(&s.0)
322추가: .arg("lzma2")
323추가: .arg("1024")
324추가: .arg((Limits::default().output + 1).to_string())
325추가: .status()
326추가: .unwrap()
327추가: .success()
328추가: );
329추가: let events = execute(start(&s, false, Limits::default().output));
330추가: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
331추가: assert_eq!(terminal(&events).publication, Publication::None);
332추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
333추가: }
334추가: #[test]
335추가: fn streamed_creation_limits_sum_source_bytes() {
336추가: for limit in [131071, 131072] {
337추가: let s = Scratch::new();
338추가: fs::write(s.0.join("a"), vec![0; 65536]).unwrap();
339추가: fs::write(s.0.join("b"), vec![0; 65536]).unwrap();
340추가: let events = execute(Start {
341추가: action: Action::CreateZip {
342추가: sources: vec![
343추가: Source {
344추가: path: s.path("a"),
345추가: archive_name: "a".into(),
346추가: },
347추가: Source {
348추가: path: s.path("b"),
349추가: archive_name: "b".into(),
350추가: },
351추가: ],
352추가: output_file: s.path("input"),
353추가: method: Method::Deflate,
354추가: encryption: Encryption::None,
355추가: },
356추가: limits: Limits {
357추가: output: limit,
358추가: ..Limits::default()
359추가: },
360추가: });
361추가: assert_eq!(
362추가: terminal(&events).error,
363추가: if limit == 131072 {
364추가: ErrorCode::None
365추가: } else {
366추가: ErrorCode::Limit
367추가: },
368추가: "{events:?}"
369추가: );
370추가: assert_eq!(s.0.join("input").exists(), limit == 131072);
371추가: }
372추가: }
373추가: #[test]
374추가: fn streamed_seven_zip_honors_exact_output_boundary() {
375추가: for limit in [65535, 65536] {
376추가: let s = Scratch::new();
377추가: generate(&s, "7z-lzma2", 65536);
378추가: let events = execute(start(&s, false, limit));
379추가: assert_eq!(
380추가: terminal(&events).error,
381추가: if limit == 65536 {
382추가: ErrorCode::None
383추가: } else {
384추가: ErrorCode::Limit
385추가: },
386추가: "{events:?}"
387추가: );
388추가: if limit == 65536 {
389추가: assert_zero_file(&s.0.join("output/payload.bin"), 65536);
390추가: } else {
391추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
392추가: }
393추가: }
394추가: }
395추가:
297396#[cfg(target_os = "linux")]
298397mod linux {
299398 use super::*;
@@ -400,6 +499,134 @@ mod linux {
400499 );
401500 path
402501 }
502추가:
503추가: #[test]
504추가: fn gigabyte_seven_zip_and_zip_creation_stay_below_64_mib() {
505추가: let mut measurements = Vec::new();
506추가: for method in ["copy", "lzma", "lzma2"] {
507추가: let s = Scratch::new();
508추가: generate(&s, &format!("7z-{method}"), 1024 * 1024 * 1024);
509추가: let request = start(&s, false, Limits::default().output);
510추가: let child = spawn(&s, request, None);
511추가: let (status, rss) = wait(child.id());
512추가: assert_eq!(status, 0, "{method}");
513추가: let events = events(&s);
514추가: assert_eq!(
515추가: terminal(&events).outcome,
516추가: Outcome::Completed,
517추가: "{method}: {events:?}"
518추가: );
519추가: assert_eq!(terminal(&events).publication, Publication::Complete);
520추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
521추가: assert_eq!(terminal(&events).created_count, 1);
522추가: assert!(rss <= 64 * 1024 * 1024, "{method}: RSS {rss}");
523추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
524추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
525추가: measurements.push(format!("7z-{method}: {rss}"));
526추가: }
527추가: for (method, length) in [
528추가: (Method::Store, 1u64 << 30),
529추가: (Method::Deflate, 1 << 30),
530추가: (Method::Deflate, (1 << 32) + 17),
531추가: ] {
532추가: let s = Scratch::new();
533추가: File::create(s.0.join("source"))
534추가: .unwrap()
535추가: .set_len(length)
536추가: .unwrap();
537추가: let request = Start {
538추가: action: Action::CreateZip {
539추가: sources: vec![Source {
540추가: path: s.path("source"),
541추가: archive_name: "payload.bin".into(),
542추가: }],
543추가: output_file: s.path("input"),
544추가: method,
545추가: encryption: Encryption::None,
546추가: },
547추가: limits: Limits::default(),
548추가: };
549추가: let child = spawn(&s, request, None);
550추가: let (status, rss) = wait(child.id());
551추가: assert_eq!(status, 0);
552추가: let created = events(&s);
553추가: assert_eq!(
554추가: terminal(&created).outcome,
555추가: Outcome::Completed,
556추가: "{method:?}: {created:?}"
557추가: );
558추가: assert!(rss <= 64 * 1024 * 1024, "{method:?}: RSS {rss}");
559추가: assert!(Command::new("python3").arg("-c").arg(
560추가: "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.getinfo('payload.bin').file_size==int(sys.argv[2]); assert z.testzip() is None"
561추가: ).arg(s.0.join("input")).arg(length.to_string()).status().unwrap().success());
562추가: fs::remove_dir(s.0.join("staging")).unwrap();
563추가: let request = start(&s, false, Limits::default().output);
564추가: let child = spawn(&s, request, None);
565추가: assert_eq!(wait(child.id()).0, 0);
566추가: assert_eq!(terminal(&events(&s)).outcome, Outcome::Completed);
567추가: assert_zero_file(&s.0.join("output/payload.bin"), length);
568추가: measurements.push(format!("create-{method:?}-{length}: {rss}"));
569추가: }
570추가: println!(
571추가: "1 GiB 7z/creation peak RSS bytes: {}",
572추가: measurements.join(", ")
573추가: );
574추가: fs::write(
575추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
576추가: .join("../../tests/ci/seven-zip-streaming-rss.log"),
577추가: measurements.join("\n") + "\n",
578추가: )
579추가: .unwrap();
580추가: }
581추가: #[test]
582추가: fn seven_zip_and_creation_disk_errors_cleanup_staging_and_partial_output() {
583추가: for create in [false, true] {
584추가: for mode in ["codec-full", "full", "space-destination", "space-error"] {
585추가: let s = Scratch::new();
586추가: let request = if create {
587추가: fs::write(s.0.join("source"), vec![0; 1024 * 1024]).unwrap();
588추가: Start {
589추가: action: Action::CreateZip {
590추가: sources: vec![Source {
591추가: path: s.path("source"),
592추가: archive_name: "payload.bin".into(),
593추가: }],
594추가: output_file: s.path("input"),
595추가: method: Method::Deflate,
596추가: encryption: Encryption::None,
597추가: },
598추가: limits: Limits::default(),
599추가: }
600추가: } else {
601추가: generate(&s, "7z-lzma2", 1024 * 1024);
602추가: start(&s, false, Limits::default().output)
603추가: };
604추가: let child = spawn(&s, request, Some(mode));
605추가: assert_eq!(wait(child.id()).0, 0);
606추가: let messages = events(&s);
607추가: let end = terminal(&messages);
608추가: assert_eq!(
609추가: end.error,
610추가: if mode == "space-error" {
611추가: ErrorCode::Io
612추가: } else {
613추가: ErrorCode::DiskFull
614추가: },
615추가: "{create} {mode}: {messages:?}"
616추가: );
617추가: assert_eq!(end.publication, Publication::None);
618추가: assert_eq!(end.retained_partial_count, 0);
619추가: assert_eq!(end.cleanup, Cleanup::Complete);
620추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
621추가: if create {
622추가: assert!(!s.0.join("input").exists());
623추가: } else {
624추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
625추가: }
626추가: }
627추가: }
628추가: }
629추가:
403630 #[test]
404631 fn gigabyte_formats_stay_below_64_mib_peak_rss() {
405632 let mut measurements = Vec::new();
@@ -443,7 +670,12 @@ mod linux {
443670 let s = Scratch::new();
444671 generate(&s, "store", 1024 * 1024);
445672 fs::write(s.0.join("preserve"), b"original").unwrap();
446삭제: let request = start(&s, false, Limits::default().output);
673추가: fs::create_dir(s.0.join("zipelo-source")).unwrap();
674추가: fs::rename(s.0.join("input"), s.0.join("zipelo-source/zipelo-input")).unwrap();
675추가: let mut request = start(&s, false, Limits::default().output);
676추가: if let Action::Extract { archive, .. } = &mut request.action {
677추가: *archive = s.path("zipelo-source/zipelo-input");
678추가: }
447679 let child = spawn(&s, request, Some(mode));
448680 assert_eq!(wait(child.id()).0, 0);
449681 let events = events(&s);
@@ -666,3 +898,67 @@ mod linux {
666898 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
667899 }
668900}
901추가:
902추가: #[test]
903추가: fn creation_validates_before_password_and_rejects_more_than_16_gib() {
904추가: let s = Scratch::new();
905추가: File::create(s.0.join("source"))
906추가: .unwrap()
907추가: .set_len(Limits::default().output + 1)
908추가: .unwrap();
909추가: let action = |sources, encryption| Start {
910추가: action: Action::CreateZip {
911추가: sources,
912추가: output_file: s.path("input"),
913추가: method: Method::Deflate,
914추가: encryption,
915추가: },
916추가: limits: Limits::default(),
917추가: };
918추가: let source = Source {
919추가: path: s.path("source"),
920추가: archive_name: "same".into(),
921추가: };
922추가: let rejected = execute(action(
923추가: vec![source.clone(), source.clone()],
924추가: Encryption::Aes256,
925추가: ));
926추가: assert_eq!(terminal(&rejected).error, ErrorCode::Conflict);
927추가: assert!(
928추가: !rejected
929추가: .iter()
930추가: .any(|e| matches!(e, Message::PasswordRequired { .. }))
931추가: );
932추가: let rejected = execute(action(vec![source], Encryption::None));
933추가: assert_eq!(terminal(&rejected).error, ErrorCode::Limit);
934추가: assert!(!s.0.join("input").exists());
935추가: }
936추가:
937추가: #[test]
938추가: fn streamed_empty_aes_members_round_trip() {
939추가: for method in [Method::Store, Method::Deflate] {
940추가: let s = Scratch::new();
941추가: File::create(s.0.join("source")).unwrap();
942추가: let events = interactive(
943추가: Start {
944추가: action: Action::CreateZip {
945추가: sources: vec![Source {
946추가: path: s.path("source"),
947추가: archive_name: "payload.bin".into(),
948추가: }],
949추가: output_file: s.path("input"),
950추가: method,
951추가: encryption: Encryption::Aes256,
952추가: },
953추가: limits: Limits::default(),
954추가: },
955추가: |id, _, _| password_reply(id, TEST_PASSWORD),
956추가: );
957추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
958추가: let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
959추가: password_reply(id, TEST_PASSWORD)
960추가: });
961추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
962추가: assert_zero_file(&s.0.join("output/payload.bin"), 0);
963추가: }
964추가: }
수정tests/rust-archive-worker/io_fault.c+13-2
@@ -16,6 +16,7 @@ static int (*real_open64)(const char *, int, ...);
1616static int (*real_fsync)(int);
1717static int (*real_fstatvfs)(int, struct statvfs *);
1818static int started;
19추가: static int snapshot_fd = -1;
1920
2021__attribute__((constructor)) static void initialize(void) {
2122 real_write = dlsym(RTLD_NEXT, "write");
@@ -32,7 +33,7 @@ static int output_file(int fd) {
3233 if (count < 0) return 0;
3334 path[count] = 0;
3435 const char *fault = getenv("ZIPELO_TEST_FAULT");
35삭제: if (fault && !strcmp(fault, "stage-full")) return strstr(path, "/#") && strstr(path, "(deleted)");
36추가: if (fault && (!strcmp(fault, "stage-full") || !strcmp(fault, "codec-full"))) return strstr(path, "/#") && strstr(path, "(deleted)");
3637 return strstr(path, "/.zipelo-") != NULL;
3738}
3839
@@ -62,8 +63,11 @@ int open64(const char *path, int flags, ...) {
6263 va_end(args);
6364 }
6465 const char *fault = getenv("ZIPELO_TEST_FAULT");
66추가: const char *name = strrchr(path, '/');
67추가: name = name ? name + 1 : path;
68추가: int named_temp = (flags & O_CREAT) && !strncmp(name, "zipelo-", 7);
6569 if (fault && !strcmp(fault, "temp-full")
66삭제: && (((flags & O_TMPFILE) == O_TMPFILE) || strstr(path, "/zipelo-"))) {
70추가: && (((flags & O_TMPFILE) == O_TMPFILE) || named_temp)) {
6771 errno = ENOSPC;
6872 return -1;
6973 }
@@ -79,6 +83,13 @@ int open64(const char *path, int flags, ...) {
7983ssize_t write(int fd, const void *bytes, size_t count) {
8084 const char *fault = getenv("ZIPELO_TEST_FAULT");
8185 if (!fault || !output_file(fd)) return real_write(fd, bytes, count);
86추가: if (!strcmp(fault, "codec-full")) {
87추가: if (snapshot_fd == -1) snapshot_fd = fd;
88추가: if (fd == snapshot_fd) return real_write(fd, bytes, count);
89추가: if (!started++) return real_write(fd, bytes, count < 7 ? count : 7);
90추가: errno = ENOSPC;
91추가: return -1;
92추가: }
8293 if (!strcmp(fault, "write-io")) { errno = EIO; return -1; }
8394 if (!strcmp(fault, "full") || !strcmp(fault, "stage-full")) {
8495 if (!started++) return real_write(fd, bytes, count < 7 ? count : 7);
추가tests/rust-archive-worker/lzma_streaming.rs+42-0
@@ -0,0 +1,42 @@
1추가: use super::*;
2추가: use std::io::{Read, Seek};
3추가:
4추가: #[test]
5추가: fn distant_dictionary_reads_and_overlap_preserve_history() {
6추가: let mut file = crate::spool::temporary().unwrap();
7추가: {
8추가: let mut out = History::new(&mut file, 64 * 1024 * 1024).unwrap();
9추가: for n in 0..144 {
10추가: out.extend(&vec![n as u8; 65536]).unwrap();
11추가: }
12추가: assert_eq!(
13추가: out.previous(0, 9 * 1024 * 1024 - 1, 64 * 1024 * 1024),
14추가: Ok(0)
15추가: );
16추가: out.copy(0, 9 * 1024 * 1024 - 1, 64 * 1024 * 1024, 273)
17추가: .unwrap();
18추가: assert_eq!(
19추가: out.previous(out.len(), 0, 64 * 1024 * 1024),
20추가: Err(ErrorCode::Integrity)
21추가: );
22추가: out.copy(0, 0, 64 * 1024 * 1024, 273).unwrap();
23추가: out.flush().unwrap();
24추가: }
25추가: file.rewind().unwrap();
26추가: let mut tail = [255; 546];
27추가: file.seek(std::io::SeekFrom::End(-546)).unwrap();
28추가: file.read_exact(&mut tail).unwrap();
29추가: assert_eq!(tail, [0; 546]);
30추가: }
31추가: #[test]
32추가: fn streaming_decoder_keeps_cancellation_error() {
33추가: let fixture = include_bytes!("fixtures/7z/lzma2.7z");
34추가: let mut file = crate::spool::temporary().unwrap();
35추가: let mut input = std::io::Cursor::new(&fixture[32..]);
36추가: assert_eq!(
37추가: decode_stream(&mut input, 100, &[0], true, 1000, &mut file, &mut || Err(
38추가: ErrorCode::None
39추가: )),
40추가: Err(ErrorCode::None)
41추가: );
42추가: }
추가tests/rust-archive-worker/seven_zip_large.py+94-0
@@ -0,0 +1,94 @@
1추가: """고정 버퍼로 대용량 7z 표본을 생성함."""
2추가: import lzma
3추가: from pathlib import Path
4추가: import shutil
5추가: import struct
6추가: import sys
7추가: import zlib
8추가:
9추가: from seven_zip_fixtures import integer, property_bytes, SIGNATURE
10추가:
11추가:
12추가: def generate(root, method, size, declared=None):
13추가: root = Path(root)
14추가: packed_path = root / "packed"
15추가: settings = {
16추가: "id": lzma.FILTER_LZMA2 if method == "lzma2" else lzma.FILTER_LZMA1,
17추가: "dict_size": 64 * 1024 * 1024,
18추가: }
19추가: compressor = None if method == "copy" else lzma.LZMACompressor(
20추가: format=lzma.FORMAT_RAW, filters=[settings]
21추가: )
22추가: crc = 0
23추가: packed_crc = 0
24추가: packed_size = 0
25추가: with packed_path.open("xb") as output:
26추가: remaining = size
27추가: while remaining:
28추가: chunk = bytes(min(65536, remaining))
29추가: crc = zlib.crc32(chunk, crc)
30추가: encoded = chunk if compressor is None else compressor.compress(chunk)
31추가: output.write(encoded)
32추가: packed_crc = zlib.crc32(encoded, packed_crc)
33추가: packed_size += len(encoded)
34추가: remaining -= len(chunk)
35추가: if compressor is not None:
36추가: encoded = compressor.flush()
37추가: output.write(encoded)
38추가: packed_crc = zlib.crc32(encoded, packed_crc)
39추가: packed_size += len(encoded)
40추가: if method == "copy":
41추가: coder = b"\x01\x00"
42추가: elif method == "lzma":
43추가: coder = b"\x23\x03\x01\x01\x05\x5d" + struct.pack("<I", 64 * 1024 * 1024)
44추가: else:
45추가: coder = b"\x21\x21\x01\x1c"
46추가: info = b"\x06\x00\x01\x09" + integer(packed_size)
47추가: info += b"\x0a\x01" + struct.pack("<I", packed_crc) + b"\x00"
48추가: info += b"\x07\x0b\x01\x00\x01" + coder + b"\x0c" + integer(size if declared is None else declared)
49추가: info += b"\x0a\x01" + struct.pack("<I", crc) + b"\x00\x08\x00\x00"
50추가: name = "payload.bin".encode("utf-16le") + b"\x00\x00"
51추가: header = b"\x01\x04" + info + b"\x05\x01" + property_bytes(17, b"\x00" + name) + b"\x00\x00"
52추가: start = struct.pack("<QQI", packed_size, len(header), zlib.crc32(header))
53추가: with (root / "input").open("xb") as output, packed_path.open("rb") as packed:
54추가: output.write(SIGNATURE + struct.pack("<I", zlib.crc32(start)) + start)
55추가: shutil.copyfileobj(packed, output, 65536)
56추가: output.write(header)
57추가: packed_path.unlink()
58추가: if declared is None and sys.platform == "linux":
59추가: verify_zero(root / "input", size)
60추가:
61추가:
62추가:
63추가: def verify_zero(path, size):
64추가: import ctypes as c
65추가: from seven_zip_reference import library
66추가: lib = library()
67추가: lib.archive_entry_size.argtypes = [c.c_void_p]
68추가: lib.archive_entry_size.restype = c.c_longlong
69추가: archive = lib.archive_read_new()
70추가: try:
71추가: assert lib.archive_read_support_filter_all(archive) == 0
72추가: assert lib.archive_read_support_format_7zip(archive) == 0
73추가: assert lib.archive_read_open_filename(archive, str(path).encode(), 65536) == 0
74추가: entry = c.c_void_p()
75추가: assert lib.archive_read_next_header(archive, c.byref(entry)) == 0
76추가: assert lib.archive_entry_pathname(entry) == b"payload.bin"
77추가: assert lib.archive_entry_size(entry) == size
78추가: buffer = c.create_string_buffer(65536)
79추가: total = 0
80추가: while True:
81추가: n = lib.archive_read_data(archive, buffer, len(buffer))
82추가: assert n >= 0, lib.archive_error_string(archive)
83추가: if not n:
84추가: break
85추가: assert buffer.raw[:n] == bytes(n)
86추가: total += n
87추가: assert total == size
88추가: assert lib.archive_read_next_header(archive, c.byref(entry)) == 1
89추가: finally:
90추가: lib.archive_read_free(archive)
91추가:
92추가: if __name__ == "__main__":
93추가: generate(sys.argv[1], sys.argv[2], int(sys.argv[3]),
94추가: int(sys.argv[4]) if len(sys.argv) > 4 else None)