team-ljyzipelo

공개

Merge pull request #74 from Team-LJY/fix/worker-release-hardening

작업자 대용량 스트리밍 해제와 종료 정리 보강
작성자
LeeJunyoung
작성 시각
커밋
3b9b5910383295e5597be9b66edcfe444f9ff2ea
이 시점의 파일 보기

변경된 파일 37개

+2,139-112

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정experiments/rust-archive-worker/README.md+20-8
@@ -1,26 +1,38 @@
11# Rust archive worker
22
3삭제: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱 연결과 OS sandbox를 제공하는 단계는 아닙니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
3추가: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다.
44
5삭제: - ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다.
6삭제: - 입력은 최대 64 MiB, 해독/생성 출력은 최대 128 MiB, 항목은 최대 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 입력과 검증 완료 payload를 메모리에 보관해 모든 선택 출력의 CRC, 크기와 경로를 쓰기 전에 검사합니다. checkpoint마다 취소와 300초 한도를 확인합니다.
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의 별도 메모리 상한을 유지합니다.
77- 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다.
88- GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다.
9삭제: - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 메모리 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
9추가: - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다.
1010- 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다.
1111- 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다.
12삭제: - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 실파일 close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다.
12추가: - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 임시 파일 생성과 일부 쓰기 뒤 ENOSPC 주입 시험은 Linux에서 수행합니다. close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다.
13추가:
14추가: ## 스트리밍과 자원 정리
15추가:
16추가: revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다.
17추가:
18추가: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다.
19추가: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 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-)을 따릅니다.
20추가: - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다.
21추가: - 입력과 검증된 해제 내용은 임시 파일에 저장합니다. 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 목표에 포함하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다.
23추가: - 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만으로 취소하지 않습니다.
24추가: - 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와 게시 중 정지를 주입하고 앱 강제 종료 후 작업자 종료/회수와 부분 출력 제거를 확인합니다. 이 시험을 위해 실제 공유 디스크를 채우거나 제품용 환경 변수 우회를 추가하지 않습니다.
1325
1426## 7z 해제
1527
1628비암호화 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)입니다.
1729
1830- 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다.
19삭제: - 입력/출력/항목/이름의 기존 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
31추가: - 입력 64 MiB/출력 128 MiB와 기존 항목/이름 한도를 별도로 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다.
2032- 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다.
2133- solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다.
2234- 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다.
23삭제: - 히나타 님과 합의한 확장은 Format::SevenZip=4뿐입니다. 기존 값 0~3과 필드, 메시지 tag, 프레임 version은 유지합니다. 구버전 앱은 값 4를 거부하므로 앱 Format과 양방향 변환도 갱신해야 합니다. 이 백엔드 변경은 frontend 코드를 수정하지 않습니다.
35추가: - 형식 확장은 히나타 님과 합의한 Format::SevenZip=4입니다. 기존 값 0~3과 필드, 메시지 tag, 프레임 version은 유지합니다. 구버전 앱은 값 4를 거부하므로 앱 Format과 양방향 변환도 갱신해야 합니다. 이 백엔드 변경은 frontend 코드를 수정하지 않습니다.
2436
2537## 암호 ZIP
2638
@@ -29,7 +41,7 @@
2941- [ZipCrypto](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)는 기존 파일 해제만 지원합니다. 보안성이 약하며 암호학적 인증이 없습니다. 12바이트 헤더 검사 후 압축 스트림, 크기와 CRC를 확인합니다. 새 암호 ZIP은 AES-256만 생성합니다.
3042- 목록은 암호 없이 표시합니다. 해제 시 한 번 입력한 암호를 ZIP 전체에 적용하며 WrongPassword일 때 새 challenge_id로 최대 3회 요청합니다. 항목마다 다른 암호인 ZIP은 지원하지 않습니다. 헤더 확인값이 우연히 일치한 잘못된 암호는 Integrity로 끝날 수 있습니다. 인증 실패 후에는 다시 요청하거나 쓰지 않습니다.
3143- 생성은 PasswordPurpose::Encrypt로 한 번 요청하며 빈 암호는 거부합니다. 암호는 최대 1024 UTF-8 바이트입니다. 대기 중 Cancel도 처리하고, 답변 없이 입력 EOF가 오면 Protocol로 종료합니다. 기존 300초 작업 제한에 암호 입력 대기 시간도 포함됩니다.
32삭제: - salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 임시 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리 복사본과 전체 평문 메모리의 완전 소거를 보장하지 않습니다.
44추가: - salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 메모리 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리/페이지 캐시 복사본과 임시 저장소의 평문에 대한 완전 소거를 보장하지 않습니다. 임시 평문 파일은 작업 종료 시 닫아 제거하며 보안 삭제를 뜻하지 않습니다.
3345- Python hashlib/hmac과 OpenSSL로 만든 AES 표본 4개, Info-ZIP으로 만든 ZipCrypto 표본 2개를 tests/ 아래에 보관합니다. 생성한 AES ZIP도 Linux에서 독립 Python/OpenSSL 검증기로 확인합니다. OpenSSL/Info-ZIP은 시험 도구이며 제품 의존성이 아닙니다.
3446
3547## 공유 codec
수정experiments/rust-archive-worker/contract.json+50-15
@@ -1,7 +1,7 @@
11{
2삭제: "status": "frontend-conditions-addressed-codec-not-implemented",
2추가: "status": "implemented-streaming-runtime",
33 "version": 1,
4삭제: "scope": "One job per separately spawned Rust worker; shared std-only binary codec. Process separation is not an OS sandbox.",
4추가: "scope": "One job per separately spawned Rust worker; shared binary codec. Process separation is not an OS sandbox.",
55 "frame": {
66 "magic": "ZAW1",
77 "header_bytes": 32,
@@ -31,7 +31,7 @@
3131 "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation."
3232 },
3333 "events": {
34삭제: "Accepted": "Action and capabilities; encryption capability remains false until implementation and verification are complete.",
34추가: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.",
3535 "Entry": "entry_id, name, kind File|Directory|Link|Other, declared sizes, encrypted; ordinal u32 IDs belong to this List job only until its ListEnd token and Completed Terminal are confirmed. Metadata only, no CRC success claim.",
3636 "ListEnd": "entry_count:u32 and list_id:ListId for a complete listing. Entry IDs are deterministic zero-based ordinals in archive traversal order. App associates this token with this job entries only after Completed Terminal, both stream EOFs and successful child wait/exit.",
3737 "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.",
@@ -39,7 +39,7 @@
3939 "Output": "entry_id:optional, relative_name, disposition Created|PartialRetained|Removed|CommitUncertain; only this job outputs.",
4040 "Terminal": {
4141 "outcome": "Completed|Failed|Cancelled",
42삭제: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest",
42추가: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull",
4343 "publication": "None|Partial|Complete|Uncertain",
4444 "created_count": "u64",
4545 "retained_partial_count": "u64",
@@ -73,17 +73,9 @@
7373 "CRC/size/stream-end validation precedes committed output events; preserve commit/durability/cleanup distinctions."
7474 ],
7575 "pending": [
76삭제: "Frontend draft acceptance was conditional on these three clarifications, now specified. Shared codec and app/worker integration remain unimplemented and unverified.",
77삭제: "RustCrypto version selection, encryption implementation and verification; capability remains unavailable until complete.",
78삭제: "Actual Linux and Windows build/runtime results; neither claimed yet."
76추가: "7z streaming and ZIP creation streaming remain deferred with separate legacy quotas.",
77추가: "Windows native runtime, forced interruption of blocked OS I/O and a current full dependency advisory audit are not verified."
7978 ],
80삭제: "performed": {
81삭제: "implementation": false,
82삭제: "cargo_build": false,
83삭제: "tests": false,
84삭제: "worker_runs": false,
85삭제: "remote_branch_or_pr": false
86삭제: },
8779 "crypto": {
8880 "rustcrypto_allowed": true,
8981 "approval_message_id": "2966b0ad-a3e0-49b8-aef8-fb51c4e1c5a5",
@@ -93,7 +85,9 @@
9385 "revision": 2,
9486 "coordination": {
9587 "frontend_message_id": "41a0e5a5-27d0-437f-805d-d39313082096",
96삭제: "basis": "Frontend can use the draft subject to three clarifications. This revision specifies list identity, explicit raw GZip output naming and cancellation acknowledgement. It does not claim implementation or runtime verification."
88추가: "basis": "Revision 2 list identity, explicit raw GZip output naming and cancellation acknowledgement are implemented. Field order and tags remain unchanged.",
89추가: "streaming_frontend_message_id": "59142fd4-22d3-4dc5-a875-5347e1b054da",
90추가: "disk_full_frontend_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1"
9791 },
9892 "list_identity": {
9993 "ListId": {
@@ -148,5 +142,46 @@
148142 "agreement_message_id": "5a36fd89-af36-42be-9f79-bca39415e84d",
149143 "compatibility": "Existing format values 0 through 3, fields, message tags and frame version stay unchanged. Older clients reject format 4. App Format and bidirectional conversion require an update.",
150144 "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId."
145추가: },
146추가: "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.",
148추가: "default_input_bytes": 18446744073709551615,
149추가: "default_output_bytes": 17179869184,
150추가: "default_entries": 10000,
151추가: "lower_limits": "Callers can lower the input, output and entry quotas. input=u64::MAX means no input-size quota; resource and duration checks still apply.",
152추가: "zip_ratio": "No compression-ratio rejection. Validate declared and actual output sizes, stream end, CRC and HMAC; sum of declared output sizes must fit output quota before decoding.",
153추가: "gzip_ratio": "No compression-ratio rejection, including concatenated members. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota.",
154추가: "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.",
155추가: "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.",
157추가: "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.",
159추가: "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.",
160추가: "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."
162추가: },
163추가: "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim.",
164추가: "error_tags": {
165추가: "None": 0,
166추가: "Integrity": 1,
167추가: "UnsupportedFormat": 2,
168추가: "UnsupportedFeature": 3,
169추가: "WrongPassword": 4,
170추가: "UnsafePath": 5,
171추가: "Conflict": 6,
172추가: "Limit": 7,
173추가: "Io": 8,
174추가: "Protocol": 9,
175추가: "Internal": 10,
176추가: "SourceChanged": 11,
177추가: "InvalidRequest": 12,
178추가: "DiskFull": 13
179추가: },
180추가: "disk_full_extension": {
181추가: "agreement_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1",
182추가: "compatibility": "Existing error tags 0 through 12, fields, message tags, revision 2 and frame version stay unchanged. Older clients reject error 13; app error mapping and worker must be updated together before integration.",
183추가: "mapping": "Insufficient preflight space and StorageFull I/O failures return DiskFull 13. Windows ERROR_HANDLE_DISK_FULL 39 and ERROR_DISK_FULL 112 also map to DiskFull. Query failure, permission errors and other I/O failures return Io 8. No error classification by localized detail text.",
184추가: "detail": "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
185추가: "publication": "Keep existing publication, durability and cleanup semantics. DiskFull does not imply rollback or absence of previously published outputs."
151186 }
152187}
수정experiments/rust-archive-worker/src/archive.rs+15-7
@@ -205,7 +205,7 @@ fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) ->
205205 }
206206 Ok(result)
207207}
208삭제: fn tar_string(b: &[u8]) -> Result<String> {
208추가: pub(crate) fn tar_string(b: &[u8]) -> Result<String> {
209209 let n = b.iter().position(|v| *v == 0).unwrap_or(b.len());
210210 if b[n..].iter().any(|v| *v != 0) {
211211 return Err(ErrorCode::Integrity);
@@ -214,7 +214,7 @@ fn tar_string(b: &[u8]) -> Result<String> {
214214 .map(str::to_owned)
215215 .map_err(|_| ErrorCode::UnsupportedFeature)
216216}
217삭제: fn octal(b: &[u8]) -> Result<u64> {
217추가: pub(crate) fn octal(b: &[u8]) -> Result<u64> {
218218 if b.first().is_some_and(|x| x & 128 != 0) {
219219 return Err(ErrorCode::UnsupportedFeature);
220220 }
@@ -315,11 +315,11 @@ fn tar(
315315 Ok(members)
316316}
317317#[derive(Clone, Copy, PartialEq, Eq)]
318삭제: struct AesExtra {
319삭제: version: u16,
320삭제: method: u16,
318추가: pub(crate) struct AesExtra {
319추가: pub version: u16,
320추가: pub method: u16,
321321}
322삭제: fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
322추가: pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
323323 let mut at = 0;
324324 let mut found = None;
325325 while at < extra.len() {
@@ -576,7 +576,11 @@ pub fn parse_with_password(
576576 password: Option<&[u8]>,
577577 check: &mut impl FnMut() -> Result<()>,
578578) -> Result<Catalog> {
579삭제: if !limits.valid() || input.len() as u64 > limits.input {
579추가: if !limits.valid() {
580추가: return Err(ErrorCode::Limit);
581추가: }
582추가: let limits = limits.legacy();
583추가: if input.len() as u64 > limits.input {
580584 return Err(ErrorCode::Limit);
581585 }
582586 if input.starts_with(b"7z\xbc\xaf\x27\x1c") {
@@ -668,6 +672,10 @@ pub fn create_zip_with_password(
668672 password: Option<&[u8]>,
669673 check: &mut impl FnMut() -> Result<()>,
670674) -> Result<Vec<u8>> {
675추가: if !limits.valid() {
676추가: return Err(ErrorCode::Limit);
677추가: }
678추가: let limits = limits.legacy();
671679 if members.len() > limits.entries as usize || members.len() >= 65535 {
672680 return Err(ErrorCode::Limit);
673681 }
수정experiments/rust-archive-worker/src/crypto.rs+134-11
@@ -87,7 +87,7 @@ pub(crate) fn aes_encrypt(
8787 result.extend(&mac[..10]);
8888 Ok(result)
8989}
90삭제: fn random(bytes: &mut [u8]) -> Result<()> {
90추가: pub(crate) fn random(bytes: &mut [u8]) -> Result<()> {
9191 #[cfg(target_os = "linux")]
9292 {
9393 use std::io::Read;
@@ -144,16 +144,8 @@ pub(crate) fn zipcrypto_decrypt(
144144 return Err(ErrorCode::Integrity);
145145 }
146146 let mut key = Zeroizing::new([0x12345678u32, 0x23456789, 0x34567890]);
147삭제: fn update(key: &mut [u32; 3], byte: u8) {
148삭제: key[0] = (key[0] >> 8) ^ CRC_TABLE[((key[0] as u8) ^ byte) as usize];
149삭제: key[1] = key[1]
150삭제: .wrapping_add(key[0] & 255)
151삭제: .wrapping_mul(134775813)
152삭제: .wrapping_add(1);
153삭제: key[2] = (key[2] >> 8) ^ CRC_TABLE[((key[2] as u8) ^ ((key[1] >> 24) as u8)) as usize];
154삭제: }
155147 for &byte in password {
156삭제: update(&mut key, byte);
148추가: zip_update(&mut key, byte);
157149 }
158150 let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12));
159151 for (index, &byte) in packed.iter().enumerate() {
@@ -162,7 +154,7 @@ pub(crate) fn zipcrypto_decrypt(
162154 }
163155 let temp = key[2] | 2;
164156 let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8);
165삭제: update(&mut key, plain);
157추가: zip_update(&mut key, plain);
166158 if index == 11 && plain != verifier {
167159 return Err(ErrorCode::WrongPassword);
168160 }
@@ -172,3 +164,134 @@ pub(crate) fn zipcrypto_decrypt(
172164 }
173165 Ok(out)
174166}
167추가:
168추가: pub(crate) enum Decryptor {
169추가: Plain,
170추가: Zip(Zeroizing<[u32; 3]>),
171추가: Aes {
172추가: cipher: Aes256,
173추가: counter: u128,
174추가: mask: [u8; 16],
175추가: used: usize,
176추가: },
177추가: }
178추가: fn zip_update(key: &mut [u32; 3], byte: u8) {
179추가: key[0] = (key[0] >> 8) ^ CRC_TABLE[((key[0] as u8) ^ byte) as usize];
180추가: key[1] = key[1]
181추가: .wrapping_add(key[0] & 255)
182추가: .wrapping_mul(134775813)
183추가: .wrapping_add(1);
184추가: key[2] = (key[2] >> 8) ^ CRC_TABLE[((key[2] as u8) ^ ((key[1] >> 24) as u8)) as usize];
185추가: }
186추가: impl Decryptor {
187추가: pub fn prepare(
188추가: file: &mut std::fs::File,
189추가: offset: u64,
190추가: length: u64,
191추가: password: &[u8],
192추가: aes: bool,
193추가: verifier: u8,
194추가: check: &mut impl FnMut() -> Result<()>,
195추가: ) -> Result<(Self, u64, u64)> {
196추가: use std::io::{Read, Seek, SeekFrom};
197추가: file.seek(SeekFrom::Start(offset))
198추가: .map_err(|_| ErrorCode::Io)?;
199추가: if aes {
200추가: if length < 28 {
201추가: return Err(ErrorCode::Integrity);
202추가: }
203추가: let mut header = [0; 18];
204추가: file.read_exact(&mut header)
205추가: .map_err(|_| ErrorCode::Integrity)?;
206추가: let key = keys(password, &header[..16]);
207추가: if !bool::from(key[64..].ct_eq(&header[16..])) {
208추가: return Err(ErrorCode::WrongPassword);
209추가: }
210추가: let mut mac =
211추가: <Sha1Mac as Mac>::new_from_slice(&key[32..64]).map_err(|_| ErrorCode::Internal)?;
212추가: let mut remaining = length - 28;
213추가: let mut buffer = [0; 65536];
214추가: while remaining != 0 {
215추가: check()?;
216추가: let n = remaining.min(buffer.len() as u64) as usize;
217추가: file.read_exact(&mut buffer[..n])
218추가: .map_err(|_| ErrorCode::Integrity)?;
219추가: mac.update(&buffer[..n]);
220추가: remaining -= n as u64;
221추가: }
222추가: let mut tag = [0; 10];
223추가: file.read_exact(&mut tag)
224추가: .map_err(|_| ErrorCode::Integrity)?;
225추가: mac.verify_truncated_left(&tag)
226추가: .map_err(|_| ErrorCode::Integrity)?;
227추가: let cipher = Aes256::new_from_slice(&key[..32]).map_err(|_| ErrorCode::Internal)?;
228추가: Ok((
229추가: Self::Aes {
230추가: cipher,
231추가: counter: 1,
232추가: mask: [0; 16],
233추가: used: 16,
234추가: },
235추가: offset + 18,
236추가: length - 28,
237추가: ))
238추가: } else {
239추가: if length < 12 {
240추가: return Err(ErrorCode::Integrity);
241추가: }
242추가: let mut key = Zeroizing::new([0x12345678, 0x23456789, 0x34567890]);
243추가: for &b in password {
244추가: zip_update(&mut key, b);
245추가: }
246추가: let mut decoder = Self::Zip(key);
247추가: let mut header = [0; 12];
248추가: file.read_exact(&mut header)
249추가: .map_err(|_| ErrorCode::Integrity)?;
250추가: decoder.apply(&mut header);
251추가: if header[11] != verifier {
252추가: return Err(ErrorCode::WrongPassword);
253추가: }
254추가: header.zeroize();
255추가: Ok((decoder, offset + 12, length - 12))
256추가: }
257추가: }
258추가: pub fn apply(&mut self, bytes: &mut [u8]) {
259추가: match self {
260추가: Self::Plain => {}
261추가: Self::Zip(key) => {
262추가: for byte in bytes {
263추가: let temp = key[2] | 2;
264추가: *byte ^= (temp.wrapping_mul(temp ^ 1) >> 8) as u8;
265추가: zip_update(key, *byte);
266추가: }
267추가: }
268추가: Self::Aes {
269추가: cipher,
270추가: counter,
271추가: mask,
272추가: used,
273추가: } => {
274추가: for byte in bytes {
275추가: if *used == 16 {
276추가: let mut block = counter.to_le_bytes().into();
277추가: cipher.encrypt_block(&mut block);
278추가: mask.copy_from_slice(&block);
279추가: block.as_mut_slice().zeroize();
280추가: *counter += 1;
281추가: *used = 0;
282추가: }
283추가: *byte ^= mask[*used];
284추가: *used += 1;
285추가: }
286추가: }
287추가: }
288추가: }
289추가: }
290추가: impl Drop for Decryptor {
291추가: fn drop(&mut self) {
292추가: if let Self::Aes { mask, counter, .. } = self {
293추가: mask.zeroize();
294추가: counter.zeroize();
295추가: }
296추가: }
297추가: }
수정experiments/rust-archive-worker/src/filesystem.rs+112-23
@@ -232,7 +232,7 @@ mod platform {
232232 let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?;
233233 // 고정 부모 안에 새 전용 디렉터리를 생성함.
234234 if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 {
235삭제: return Err(ErrorCode::Io);
235추가: return Err(crate::space::io_error(std::io::Error::last_os_error()));
236236 }
237237 let file = open(
238238 &self.file,
@@ -247,6 +247,9 @@ mod platform {
247247 Err(_) => Err(ErrorCode::UnsafePath),
248248 }
249249 }
250추가: pub(crate) fn handle(&self) -> &File {
251추가: &self.file
252추가: }
250253 pub fn duplicate(&self) -> Result<Self> {
251254 Ok(Self {
252255 file: self.file.try_clone().map_err(|_| ErrorCode::Io)?,
@@ -286,11 +289,11 @@ mod platform {
286289 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
287290 }
288291 pub fn sync(&self) -> Durability {
289삭제: if self.file.sync_all().is_ok() {
290삭제: Durability::Synced
291삭제: } else {
292삭제: Durability::Failed
293삭제: }
292추가: self.sync_checked().unwrap_or(Durability::Failed)
293추가: }
294추가: pub(crate) fn sync_checked(&self) -> Result<Durability> {
295추가: self.file.sync_all().map_err(crate::space::io_error)?;
296추가: Ok(Durability::Synced)
294297 }
295298 }
296299}
@@ -337,6 +340,9 @@ mod platform {
337340 }
338341 Ok(Self { path: p, locks })
339342 }
343추가: pub(crate) fn handle(&self) -> &File {
344추가: self.locks.last().unwrap()
345추가: }
340346 pub fn duplicate(&self) -> Result<Self> {
341347 Ok(Self {
342348 path: self.path.clone(),
@@ -355,7 +361,7 @@ mod platform {
355361 if !create {
356362 return Ok(None);
357363 }
358삭제: std::fs::create_dir(&p).map_err(|_| ErrorCode::Io)?;
364추가: std::fs::create_dir(&p).map_err(crate::space::io_error)?;
359365 }
360366 Err(_) => return Err(ErrorCode::Io),
361367 }
@@ -388,6 +394,9 @@ mod platform {
388394 pub fn sync(&self) -> Durability {
389395 Durability::Unconfirmed
390396 }
397추가: pub(crate) fn sync_checked(&self) -> Result<Durability> {
398추가: Ok(Durability::Unconfirmed)
399추가: }
391400 }
392401}
393402#[cfg(not(any(target_os = "linux", windows)))]
@@ -417,13 +426,56 @@ pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
417426 }
418427 Ok(())
419428}
420삭제: pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> {
429추가: pub(crate) fn preflight_space(
430추가: root: &Dir,
431추가: files: &[(String, u64)],
432추가: staging: Option<(&File, u64)>,
433추가: ) -> Result<()> {
434추가: let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
435추가: let mut charge = |file: &File, bytes: u64| -> Result<()> {
436추가: crate::space::ensure(file, bytes)?;
437추가: let volume = crate::space::volume(file)?;
438추가: if let Some((_, total)) = volumes.get_mut(&volume) {
439추가: *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?;
440추가: } else {
441추가: volumes.insert(
442추가: volume,
443추가: (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes),
444추가: );
445추가: }
446추가: Ok(())
447추가: };
448추가: if let Some((file, bytes)) = staging {
449추가: charge(file, bytes)?;
450추가: }
451추가: for (name, size) in files {
452추가: valid_name(name, false)?;
453추가: let mut parent = root.duplicate()?;
454추가: let mut parts = name.split('/').collect::<Vec<_>>();
455추가: parts.pop();
456추가: for part in parts {
457추가: match parent.child(part, false)? {
458추가: Some(child) => parent = child,
459추가: None => break,
460추가: }
461추가: }
462추가: charge(parent.handle(), *size)?;
463추가: }
464추가: for (file, bytes) in volumes.values() {
465추가: crate::space::ensure(file, *bytes)?;
466추가: }
467추가: Ok(())
468추가: }
469추가: pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
421470 let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
422471 if d.child(&leaf, false)?.is_some() {
423삭제: return Ok((false, Durability::NotApplicable));
472추가: return Ok((false, Durability::NotApplicable, None));
424473 }
425474 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
426삭제: Ok((true, d.sync()))
475추가: Ok(match d.sync_checked() {
476추가: Ok(durability) => (true, durability, None),
477추가: Err(error) => (true, Durability::Failed, Some(error)),
478추가: })
427479}
428480pub struct Published {
429481 pub created: bool,
@@ -439,6 +491,22 @@ pub fn publish(
439491 name: &str,
440492 data: &[u8],
441493 check: &mut impl FnMut(bool) -> Result<()>,
494추가: ) -> Published {
495추가: publish_reader(
496추가: root,
497추가: name,
498추가: &mut std::io::Cursor::new(data),
499추가: data.len() as u64,
500추가: check,
501추가: )
502추가: }
503추가:
504추가: pub fn publish_reader(
505추가: root: &Dir,
506추가: name: &str,
507추가: data: &mut impl Read,
508추가: length: u64,
509추가: check: &mut impl FnMut(bool) -> Result<()>,
442510) -> Published {
443511 let mut result = Published {
444512 created: false,
@@ -457,32 +525,51 @@ pub fn publish(
457525 std::process::id(),
458526 TEMP.fetch_add(1, Ordering::Relaxed)
459527 );
460삭제: let mut file = dir.create(&temp).map_err(|_| ErrorCode::Conflict)?;
528추가: let mut file = dir.create(&temp).map_err(|e| {
529추가: if e.kind() == std::io::ErrorKind::AlreadyExists {
530추가: ErrorCode::Conflict
531추가: } else {
532추가: crate::space::io_error(e)
533추가: }
534추가: })?;
461535 let written = (|| {
462삭제: for chunk in data.chunks(65536) {
536추가: crate::space::ensure(&file, length)?;
537추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]);
538추가: let mut remaining = length;
539추가: while remaining != 0 {
463540 check(false)?;
464삭제: file.write_all(chunk).map_err(|_| ErrorCode::Io)?;
541추가: let count = remaining.min(buffer.len() as u64) as usize;
542추가: let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
543추가: if n == 0 {
544추가: return Err(ErrorCode::Io);
545추가: }
546추가: file.write_all(&buffer[..n])
547추가: .map_err(crate::space::io_error)?;
548추가: remaining -= n as u64;
465549 }
466삭제: file.sync_all().map_err(|_| ErrorCode::Io)
550추가: file.sync_all().map_err(crate::space::io_error)
467551 })();
468삭제: let closed = close(file).map_err(|_| ErrorCode::Io);
552추가: let closed = close(file).map_err(crate::space::io_error);
469553 let mut finish = written.and(closed).and_then(|_| check(true));
470554 if finish.is_ok() {
471555 match dir.link(&temp, &leaf) {
472556 Ok(()) => {
473557 result.created = true;
474삭제: result.durability = dir.sync();
475삭제: if result.durability == Durability::Failed {
476삭제: finish = Err(ErrorCode::Io);
558추가: match dir.sync_checked() {
559추가: Ok(durability) => result.durability = durability,
560추가: Err(error) => {
561추가: result.durability = Durability::Failed;
562추가: finish = Err(error);
563추가: }
477564 }
478565 }
479566 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
480567 finish = Err(ErrorCode::Conflict)
481568 }
482삭제: Err(_) => {
569추가: Err(error) => {
483570 result.uncertain = true;
484571 result.durability = Durability::Unconfirmed;
485삭제: finish = Err(ErrorCode::Io);
572추가: finish = Err(crate::space::io_error(error));
486573 }
487574 }
488575 }
@@ -497,9 +584,11 @@ pub fn publish(
497584 finish = Err(ErrorCode::Io);
498585 }
499586 }
500삭제: if result.created && dir.sync() == Durability::Failed {
501삭제: result.durability = Durability::Failed;
502삭제: finish = Err(ErrorCode::Io);
587추가: if result.created {
588추가: if let Err(error) = dir.sync_checked() {
589추가: result.durability = Durability::Failed;
590추가: finish = Err(error);
591추가: }
503592 }
504593 finish
505594 })();
수정experiments/rust-archive-worker/src/lib.rs+4-0
@@ -2,7 +2,11 @@ pub mod archive;
22mod crypto;
33pub mod filesystem;
44mod lzma;
5추가: mod parent;
56pub mod protocol;
67pub mod runtime;
78mod seven_zip;
9추가: mod space;
10추가: mod spool;
11추가: mod streaming;
812pub mod wire;
추가experiments/rust-archive-worker/src/parent.rs+135-0
@@ -0,0 +1,135 @@
1추가: use crate::protocol::ErrorCode;
2추가: type Result<T> = std::result::Result<T, ErrorCode>;
3추가:
4추가: #[cfg(target_os = "linux")]
5추가: pub(crate) struct Parent(i32);
6추가: #[cfg(target_os = "linux")]
7추가: unsafe extern "C" {
8추가: fn getppid() -> i32;
9추가: }
10추가: #[cfg(target_os = "linux")]
11추가: impl Parent {
12추가: pub fn capture() -> Result<Self> {
13추가: let id = unsafe { getppid() };
14추가: if id <= 1 {
15추가: return Err(ErrorCode::Io);
16추가: }
17추가: Ok(Self(id))
18추가: }
19추가: pub fn check(&self) -> Result<()> {
20추가: if unsafe { getppid() } == self.0 {
21추가: Ok(())
22추가: } else {
23추가: Err(ErrorCode::Io)
24추가: }
25추가: }
26추가: }
27추가:
28추가: #[cfg(windows)]
29추가: mod windows {
30추가: use super::*;
31추가: use std::ffi::c_void;
32추가: type Handle = *mut c_void;
33추가: #[repr(C)]
34추가: struct Entry {
35추가: size: u32,
36추가: usage: u32,
37추가: pid: u32,
38추가: heap: usize,
39추가: module: u32,
40추가: threads: u32,
41추가: parent: u32,
42추가: priority: i32,
43추가: flags: u32,
44추가: executable: [u16; 260],
45추가: }
46추가: #[repr(C)]
47추가: #[derive(Default)]
48추가: struct Time {
49추가: low: u32,
50추가: high: u32,
51추가: }
52추가: unsafe extern "system" {
53추가: fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> Handle;
54추가: fn Process32FirstW(snapshot: Handle, entry: *mut Entry) -> i32;
55추가: fn Process32NextW(snapshot: Handle, entry: *mut Entry) -> i32;
56추가: fn GetCurrentProcessId() -> u32;
57추가: fn GetCurrentProcess() -> Handle;
58추가: fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
59추가: fn GetProcessTimes(
60추가: handle: Handle,
61추가: creation: *mut Time,
62추가: exit: *mut Time,
63추가: kernel: *mut Time,
64추가: user: *mut Time,
65추가: ) -> i32;
66추가: fn WaitForSingleObject(handle: Handle, milliseconds: u32) -> u32;
67추가: fn CloseHandle(handle: Handle) -> i32;
68추가: }
69추가: fn created(handle: Handle) -> Result<u64> {
70추가: let (mut c, mut e, mut k, mut u) = (
71추가: Time::default(),
72추가: Time::default(),
73추가: Time::default(),
74추가: Time::default(),
75추가: );
76추가: if unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } == 0 {
77추가: return Err(ErrorCode::Io);
78추가: }
79추가: Ok((c.high as u64) << 32 | c.low as u64)
80추가: }
81추가: pub(crate) struct Parent(Handle);
82추가: impl Parent {
83추가: pub fn capture() -> Result<Self> {
84추가: let snapshot = unsafe { CreateToolhelp32Snapshot(2, 0) };
85추가: if snapshot as isize == -1 {
86추가: return Err(ErrorCode::Io);
87추가: }
88추가: let mut entry: Entry = unsafe { std::mem::zeroed() };
89추가: entry.size = size_of::<Entry>() as u32;
90추가: let pid = unsafe { GetCurrentProcessId() };
91추가: let mut valid = unsafe { Process32FirstW(snapshot, &mut entry) };
92추가: let mut parent = 0;
93추가: while valid != 0 {
94추가: if entry.pid == pid {
95추가: parent = entry.parent;
96추가: break;
97추가: }
98추가: valid = unsafe { Process32NextW(snapshot, &mut entry) };
99추가: }
100추가: unsafe {
101추가: CloseHandle(snapshot);
102추가: }
103추가: if parent == 0 {
104추가: return Err(ErrorCode::Io);
105추가: }
106추가: let handle = unsafe { OpenProcess(0x100000 | 0x1000, 0, parent) };
107추가: if handle.is_null() {
108추가: return Err(ErrorCode::Io);
109추가: }
110추가: let guard = Self(handle);
111추가: // 부모 PID가 재사용된 경우 새 프로세스에 연결하지 않음.
112추가: if created(handle)? > created(unsafe { GetCurrentProcess() })? {
113추가: return Err(ErrorCode::Io);
114추가: }
115추가: guard.check()?;
116추가: Ok(guard)
117추가: }
118추가: pub fn check(&self) -> Result<()> {
119추가: if unsafe { WaitForSingleObject(self.0, 0) } == 258 {
120추가: Ok(())
121추가: } else {
122추가: Err(ErrorCode::Io)
123추가: }
124추가: }
125추가: }
126추가: impl Drop for Parent {
127추가: fn drop(&mut self) {
128추가: unsafe {
129추가: CloseHandle(self.0);
130추가: }
131추가: }
132추가: }
133추가: }
134추가: #[cfg(windows)]
135추가: pub(crate) use windows::Parent;
수정experiments/rust-archive-worker/src/protocol.rs+11-2
@@ -57,13 +57,21 @@ pub struct Limits {
5757impl Default for Limits {
5858 fn default() -> Self {
5959 Self {
60삭제: input: 64 * 1024 * 1024,
61삭제: output: 128 * 1024 * 1024,
60추가: input: u64::MAX,
61추가: output: 16 * 1024 * 1024 * 1024,
6262 entries: 10_000,
6363 }
6464 }
6565}
6666impl Limits {
67추가: pub(crate) fn legacy(self) -> Self {
68추가: Self {
69추가: input: self.input.min(64 * 1024 * 1024),
70추가: output: self.output.min(128 * 1024 * 1024),
71추가: entries: self.entries,
72추가: }
73추가: }
74추가:
6775 pub fn valid(self) -> bool {
6876 let hard = Self::default();
6977 self.input > 0
@@ -213,6 +221,7 @@ pub enum ErrorCode {
213221 Internal,
214222 SourceChanged,
215223 InvalidRequest,
224추가: DiskFull,
216225}
217226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218227pub enum Publication {
수정experiments/rust-archive-worker/src/runtime.rs+108-44
@@ -6,7 +6,7 @@ use crate::{
66};
77use std::{
88 collections::BTreeSet,
9삭제: io::{Read, Write},
9추가: io::{Read, Seek, SeekFrom, Write},
1010 sync::{Arc, Condvar, Mutex},
1111 time::{Duration, Instant},
1212};
@@ -27,6 +27,7 @@ struct Job<W> {
2727 next_challenge: u64,
2828 started: Instant,
2929 terminal: Terminal,
30추가: parent: crate::parent::Parent,
3031}
3132impl<W: Write> Job<W> {
3233 fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> {
@@ -45,6 +46,7 @@ impl<W: Write> Job<W> {
4546 })
4647 .map_err(|_| ErrorCode::Io)?;
4748 loop {
49추가: self.parent.check()?;
4850 if let Some(error) = state.fault {
4951 return Err(error);
5052 }
@@ -76,6 +78,7 @@ impl<W: Write> Job<W> {
7678 })
7779 }
7880 fn check(&mut self) -> Result<()> {
81추가: self.parent.check()?;
7982 if self.started.elapsed() > Duration::from_secs(300) {
8083 return Err(ErrorCode::Limit);
8184 }
@@ -118,15 +121,33 @@ impl<W: Write> Job<W> {
118121 data: &[u8],
119122 id: Option<u32>,
120123 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추가: }
134추가: fn output_reader(
135추가: &mut self,
136추가: root: &Dir,
137추가: name: &str,
138추가: data: &mut impl Read,
139추가: length: u64,
140추가: id: Option<u32>,
141추가: last: bool,
121142 ) -> Result<()> {
122143 self.check()?;
123144 self.progress(
124145 Stage::Write,
125146 0,
126삭제: Some(data.len() as u64),
147추가: Some(length),
127148 self.terminal.created_count as u32,
128149 )?;
129삭제: let p = filesystem::publish(root, name, data, &mut |commit| {
150추가: let p = filesystem::publish_reader(root, name, data, length, &mut |commit| {
130151 if commit && last {
131152 self.cutoff()
132153 } else {
@@ -194,8 +215,8 @@ impl<W: Write> Job<W> {
194215 let extract = matches!(start.action, Action::Extract { .. });
195216 let path = source.to_path()?;
196217 self.progress(Stage::Read, 0, None, 0)?;
197삭제: let snapshot =
198삭제: filesystem::snapshot(&path, start.limits.input, &mut || self.check())?;
218추가: let mut snapshot =
219추가: crate::spool::Snapshot::open(&path, start.limits.input, &mut || self.check())?;
199220 if let Action::Extract {
200221 list_id: Some(expected),
201222 ..
@@ -203,25 +224,26 @@ impl<W: Write> Job<W> {
203224 {
204225 if expected.catalog_version != 1
205226 || expected.source_object != snapshot.object
206삭제: || expected.archive_bytes != snapshot.bytes.len() as u64
227추가: || expected.archive_bytes != snapshot.len
207228 || expected.archive_sha256 != snapshot.hash
208229 {
209230 return Err(ErrorCode::SourceChanged);
210231 }
211232 }
212삭제: self.progress(
213삭제: Stage::Decode,
214삭제: snapshot.bytes.len() as u64,
215삭제: Some(snapshot.bytes.len() as u64),
216삭제: 0,
233추가: self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?;
234추가: let mut catalog = crate::streaming::Catalog::open(
235추가: &mut snapshot.file,
236추가: snapshot.len,
237추가: start.limits,
238추가: false,
239추가: None,
240추가: &mut || self.check(),
217241 )?;
218삭제: let mut catalog =
219삭제: archive::parse(&snapshot.bytes, start.limits, false, &mut || self.check())?;
220242 let list_id = ListId {
221243 catalog_version: 1,
222244 format: catalog.format,
223245 source_object: snapshot.object,
224삭제: archive_bytes: snapshot.bytes.len() as u64,
246추가: archive_bytes: snapshot.len,
225247 archive_sha256: snapshot.hash,
226248 };
227249 if !extract {
@@ -269,28 +291,6 @@ impl<W: Write> Job<W> {
269291 {
270292 return Err(ErrorCode::UnsafePath);
271293 }
272삭제: let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
273삭제: for attempt in 1..=3 {
274삭제: let secret = if encrypted {
275삭제: Some(self.password(PasswordPurpose::Decrypt, attempt)?)
276삭제: } else {
277삭제: None
278삭제: };
279삭제: match archive::parse_with_password(
280삭제: &snapshot.bytes,
281삭제: start.limits,
282삭제: true,
283삭제: secret.as_ref().map(|s| s.0.as_slice()),
284삭제: &mut || self.check(),
285삭제: ) {
286삭제: Ok(decoded) => {
287삭제: catalog = decoded;
288삭제: break;
289삭제: }
290삭제: Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
291삭제: Err(error) => return Err(error),
292삭제: }
293삭제: }
294294 if catalog.format == Format::Gzip {
295295 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
296296 let checked = archive::valid_name(&name, false)
@@ -303,6 +303,55 @@ impl<W: Write> Job<W> {
303303 return Err(ErrorCode::InvalidRequest);
304304 }
305305 let root = Dir::root(&destination.to_path()?)?;
306추가: let output_sizes = catalog
307추가: .members
308추가: .iter()
309추가: .filter(|m| {
310추가: m.entry.kind == EntryKind::File
311추가: && selected
312추가: .as_ref()
313추가: .is_none_or(|s| s.contains(&m.entry.entry_id))
314추가: })
315추가: .map(|m| (m.entry.name.clone(), m.entry.size))
316추가: .collect::<Vec<_>>();
317추가: let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) {
318추가: Some((
319추가: &catalog.data,
320추가: catalog.members.iter().try_fold(0u64, |sum, m| {
321추가: sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit)
322추가: })?,
323추가: ))
324추가: } else {
325추가: None
326추가: };
327추가: filesystem::preflight_space(&root, &output_sizes, staged)?;
328추가: let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
329추가: if matches!(catalog.format, Format::Zip | Format::SevenZip) {
330추가: for attempt in 1..=3 {
331추가: let secret = if encrypted {
332추가: Some(self.password(PasswordPurpose::Decrypt, attempt)?)
333추가: } else {
334추가: None
335추가: };
336추가: match crate::streaming::Catalog::open(
337추가: &mut snapshot.file,
338추가: snapshot.len,
339추가: start.limits,
340추가: true,
341추가: secret.as_ref().map(|s| s.0.as_slice()),
342추가: &mut || self.check(),
343추가: ) {
344추가: Ok(decoded) => {
345추가: catalog = decoded;
346추가: break;
347추가: }
348추가: Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
349추가: Err(error) => return Err(error),
350추가: }
351추가: }
352추가: }
353추가: let offsets = catalog.offsets;
354추가: let mut data = catalog.data;
306355 let members = catalog
307356 .members
308357 .into_iter()
@@ -327,9 +376,11 @@ impl<W: Write> Job<W> {
327376 .map(|m| (m.entry.name.clone(), EntryKind::File)),
328377 );
329378 filesystem::preflight(&root, &names)?;
379추가: filesystem::preflight_space(&root, &output_sizes, None)?;
330380 for name in dirs {
331381 self.check()?;
332삭제: let (created, durability) = filesystem::directory(&root, &name)?;
382추가: let (created, durability, sync_error) =
383추가: filesystem::directory(&root, &name)?;
333384 if created {
334385 self.terminal.created_count += 1;
335386 self.terminal.publication = Publication::Partial;
@@ -339,16 +390,19 @@ impl<W: Write> Job<W> {
339390 relative_name: name,
340391 disposition: Disposition::Created,
341392 })?;
342삭제: if durability == Durability::Failed {
343삭제: return Err(ErrorCode::Io);
393추가: if let Some(error) = sync_error {
394추가: return Err(error);
344395 }
345396 }
346397 }
347398 for (index, m) in files.iter().enumerate() {
348삭제: self.output(
399추가: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
400추가: .map_err(|_| ErrorCode::Io)?;
401추가: self.output_reader(
349402 &root,
350403 &m.entry.name,
351삭제: &m.data,
404추가: &mut (&mut data).take(m.entry.size),
405추가: m.entry.size,
352406 Some(m.entry.entry_id),
353407 index + 1 == files.len(),
354408 )?;
@@ -362,7 +416,8 @@ impl<W: Write> Job<W> {
362416 method,
363417 encryption,
364418 } => {
365삭제: if sources.len() > start.limits.entries as usize {
419추가: let limits = start.limits.legacy();
420추가: if sources.len() > limits.entries as usize {
366421 return Err(ErrorCode::Limit);
367422 }
368423 let mut members = Vec::new();
@@ -372,7 +427,7 @@ impl<W: Write> Job<W> {
372427 let name = archive::valid_name(&source.archive_name, false)?;
373428 let snapshot = filesystem::snapshot(
374429 &source.path.to_path()?,
375삭제: start.limits.input - consumed,
430추가: limits.input - consumed,
376431 &mut || self.check(),
377432 )?;
378433 consumed += snapshot.bytes.len() as u64;
@@ -400,7 +455,7 @@ impl<W: Write> Job<W> {
400455 let bytes = archive::create_zip_with_password(
401456 &members,
402457 method,
403삭제: start.limits,
458추가: limits,
404459 secret.as_ref().map(|s| s.0.as_slice()),
405460 &mut || self.check(),
406461 )?;
@@ -424,6 +479,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
424479 input: R,
425480 output: W,
426481) -> std::io::Result<()> {
482추가: let parent = crate::parent::Parent::capture()
483추가: .map_err(|_| std::io::Error::other("worker parent unavailable"))?;
427484 let mut reader = Reader::new(input);
428485 let (job, _, message) = reader
429486 .read()?
@@ -517,6 +574,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
517574 state: Arc::clone(&state),
518575 wake,
519576 next_challenge: 0,
577추가: parent,
520578 started: Instant::now(),
521579 terminal: Terminal {
522580 outcome: Outcome::Completed,
@@ -555,6 +613,12 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
555613 ErrorCode::None => "취소됨",
556614 ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원",
557615 ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함",
616추가: ErrorCode::DiskFull => {
617추가: "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
618추가: }
619추가: ErrorCode::Io => {
620추가: "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요"
621추가: }
558622 _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함",
559623 }
560624 .to_owned();
추가experiments/rust-archive-worker/src/space.rs+140-0
@@ -0,0 +1,140 @@
1추가: use crate::protocol::*;
2추가: use std::fs::File;
3추가:
4추가: type Result<T> = std::result::Result<T, ErrorCode>;
5추가:
6추가: pub(crate) fn volume(file: &File) -> Result<u64> {
7추가: Ok(match crate::filesystem::object(file)? {
8추가: SourceObject::Unix { device, .. } => device,
9추가: SourceObject::Windows { volume_serial, .. } => volume_serial,
10추가: })
11추가: }
12추가:
13추가: pub(crate) fn ensure(file: &File, bytes: u64) -> Result<()> {
14추가: if bytes == 0 || bytes as u128 <= available(file)? {
15추가: Ok(())
16추가: } else {
17추가: Err(ErrorCode::DiskFull)
18추가: }
19추가: }
20추가:
21추가: #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
22추가: fn available(file: &File) -> Result<u128> {
23추가: use std::os::fd::AsRawFd;
24추가: #[repr(C)]
25추가: #[derive(Default)]
26추가: struct Vfs {
27추가: block_size: u64,
28추가: fragment_size: u64,
29추가: blocks: u64,
30추가: free_blocks: u64,
31추가: available_blocks: u64,
32추가: files: u64,
33추가: free_files: u64,
34추가: available_files: u64,
35추가: filesystem_id: u64,
36추가: flags: u64,
37추가: name_max: u64,
38추가: reserved: [i32; 6],
39추가: }
40추가: unsafe extern "C" {
41추가: fn fstatvfs(fd: i32, value: *mut Vfs) -> i32;
42추가: }
43추가: let mut value = Vfs::default();
44추가: if unsafe { fstatvfs(file.as_raw_fd(), &mut value) } != 0 || value.fragment_size == 0 {
45추가: return Err(ErrorCode::Io);
46추가: }
47추가: Ok(value.available_blocks as u128 * value.fragment_size as u128)
48추가: }
49추가:
50추가: #[cfg(all(target_os = "linux", not(target_pointer_width = "64")))]
51추가: fn available(_: &File) -> Result<u128> {
52추가: Err(ErrorCode::UnsupportedFeature)
53추가: }
54추가:
55추가: #[cfg(windows)]
56추가: fn available(file: &File) -> Result<u128> {
57추가: use std::{
58추가: ffi::OsString,
59추가: os::windows::{
60추가: ffi::{OsStrExt, OsStringExt},
61추가: io::AsRawHandle,
62추가: },
63추가: path::PathBuf,
64추가: };
65추가: unsafe extern "system" {
66추가: fn GetFinalPathNameByHandleW(
67추가: handle: *mut std::ffi::c_void,
68추가: path: *mut u16,
69추가: capacity: u32,
70추가: flags: u32,
71추가: ) -> u32;
72추가: fn GetDiskFreeSpaceExW(
73추가: path: *const u16,
74추가: available: *mut u64,
75추가: total: *mut u64,
76추가: free: *mut u64,
77추가: ) -> i32;
78추가: }
79추가: let mut buffer = vec![0u16; 32768];
80추가: let mut length = unsafe {
81추가: GetFinalPathNameByHandleW(
82추가: file.as_raw_handle(),
83추가: buffer.as_mut_ptr(),
84추가: buffer.len() as u32,
85추가: 0,
86추가: )
87추가: };
88추가: if length == 0 {
89추가: length = unsafe {
90추가: GetFinalPathNameByHandleW(
91추가: file.as_raw_handle(),
92추가: buffer.as_mut_ptr(),
93추가: buffer.len() as u32,
94추가: 1,
95추가: )
96추가: };
97추가: }
98추가: if length == 0 || length as usize >= buffer.len() {
99추가: return Err(ErrorCode::Io);
100추가: }
101추가: let mut path = PathBuf::from(OsString::from_wide(&buffer[..length as usize]));
102추가: if !file.metadata().map_err(|_| ErrorCode::Io)?.is_dir() && !path.pop() {
103추가: return Err(ErrorCode::Io);
104추가: }
105추가: let mut wide: Vec<_> = path.as_os_str().encode_wide().collect();
106추가: if wide.last() != Some(&92) {
107추가: wide.push(92);
108추가: }
109추가: wide.push(0);
110추가: let mut free = 0;
111추가: if unsafe {
112추가: GetDiskFreeSpaceExW(
113추가: wide.as_ptr(),
114추가: &mut free,
115추가: std::ptr::null_mut(),
116추가: std::ptr::null_mut(),
117추가: )
118추가: } == 0
119추가: {
120추가: return Err(ErrorCode::Io);
121추가: }
122추가: Ok(free as u128)
123추가: }
124추가:
125추가: // 공간 부족만 전용 오류로 변환함.
126추가: pub(crate) fn io_error(error: std::io::Error) -> ErrorCode {
127추가: #[cfg(windows)]
128추가: if matches!(error.raw_os_error(), Some(39 | 112)) {
129추가: return ErrorCode::DiskFull;
130추가: }
131추가: if error.kind() == std::io::ErrorKind::StorageFull {
132추가: ErrorCode::DiskFull
133추가: } else {
134추가: ErrorCode::Io
135추가: }
136추가: }
137추가:
138추가: #[cfg(test)]
139추가: #[path = "../../../tests/rust-archive-worker/space_errors.rs"]
140추가: mod tests;
추가experiments/rust-archive-worker/src/spool.rs+151-0
@@ -0,0 +1,151 @@
1추가: use crate::{filesystem, protocol::*};
2추가: use sha2::{Digest, Sha256};
3추가: use std::{
4추가: fs::{File, OpenOptions},
5추가: io::{Read, Seek, SeekFrom, Write},
6추가: path::Path,
7추가: };
8추가:
9추가: type Result<T> = std::result::Result<T, ErrorCode>;
10추가:
11추가: pub(crate) fn temporary() -> Result<File> {
12추가: #[cfg(target_os = "linux")]
13추가: {
14추가: use std::os::unix::fs::OpenOptionsExt;
15추가: // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨.
16추가: match OpenOptions::new()
17추가: .read(true)
18추가: .write(true)
19추가: .custom_flags(0x410000 | 0x80)
20추가: .mode(0o600)
21추가: .open(std::env::temp_dir())
22추가: {
23추가: Ok(file) => return Ok(file),
24추가: Err(ref error) if error.kind() == std::io::ErrorKind::StorageFull => {
25추가: return Err(ErrorCode::DiskFull);
26추가: }
27추가: Err(_) => {}
28추가: }
29추가: let mut random = [0; 16];
30추가: crate::crypto::random(&mut random)?;
31추가: let name = random
32추가: .iter()
33추가: .map(|b| format!("{b:02x}"))
34추가: .collect::<String>();
35추가: let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp"));
36추가: let file = OpenOptions::new()
37추가: .read(true)
38추가: .write(true)
39추가: .create_new(true)
40추가: .mode(0o600)
41추가: .custom_flags(0x20000)
42추가: .open(&path)
43추가: .map_err(crate::space::io_error)?;
44추가: std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?;
45추가: use std::os::unix::fs::MetadataExt;
46추가: if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
47추가: return Err(ErrorCode::Io);
48추가: }
49추가: Ok(file)
50추가: }
51추가: #[cfg(windows)]
52추가: {
53추가: use std::os::windows::fs::OpenOptionsExt;
54추가: let mut random = [0; 16];
55추가: crate::crypto::random(&mut random)?;
56추가: let name = random
57추가: .iter()
58추가: .map(|b| format!("{b:02x}"))
59추가: .collect::<String>();
60추가: OpenOptions::new()
61추가: .read(true)
62추가: .write(true)
63추가: .create_new(true)
64추가: .share_mode(0)
65추가: .access_mode(0xc0010000)
66추가: .custom_flags(0x04000000 | 0x00200000)
67추가: .attributes(0x100)
68추가: .open(std::env::temp_dir().join(format!("zipelo-{name}.tmp")))
69추가: .map_err(crate::space::io_error)
70추가: }
71추가: }
72추가:
73추가: pub(crate) struct Snapshot {
74추가: pub file: File,
75추가: pub len: u64,
76추가: pub object: SourceObject,
77추가: pub hash: [u8; 32],
78추가: }
79추가: impl Snapshot {
80추가: pub fn open(path: &Path, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Self> {
81추가: let mut options = OpenOptions::new();
82추가: options.read(true);
83추가: #[cfg(unix)]
84추가: {
85추가: use std::os::unix::fs::OpenOptionsExt;
86추가: options.custom_flags(0x20000 | 0x800);
87추가: }
88추가: #[cfg(windows)]
89추가: {
90추가: use std::os::windows::fs::OpenOptionsExt;
91추가: options.share_mode(1);
92추가: }
93추가: let mut source = options.open(path).map_err(|_| ErrorCode::Io)?;
94추가: let before = source.metadata().map_err(|_| ErrorCode::Io)?;
95추가: if !before.is_file() {
96추가: return Err(ErrorCode::InvalidRequest);
97추가: }
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추가: };
108추가: if before.len() > limit {
109추가: return Err(ErrorCode::Limit);
110추가: }
111추가: source.rewind().map_err(|_| ErrorCode::Io)?;
112추가: let object = filesystem::object(&source)?;
113추가: let mut file = temporary()?;
114추가: crate::space::ensure(&file, before.len())?;
115추가: let mut buffer = [0; 65536];
116추가: let mut hash = Sha256::new();
117추가: let mut len = 0u64;
118추가: loop {
119추가: check()?;
120추가: let n = source.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
121추가: if n == 0 {
122추가: break;
123추가: }
124추가: len = len
125추가: .checked_add(n as u64)
126추가: .filter(|n| *n <= limit)
127추가: .ok_or(ErrorCode::Limit)?;
128추가: file.write_all(&buffer[..n])
129추가: .map_err(crate::space::io_error)?;
130추가: hash.update(&buffer[..n]);
131추가: }
132추가: let after = source.metadata().map_err(|_| ErrorCode::Io)?;
133추가: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
134추가: if filesystem::object(&named)? != object
135추가: || filesystem::object(&source)? != object
136추가: || before.len() != len
137추가: || after.len() != len
138추가: || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
139추가: || before.modified().ok() != after.modified().ok()
140추가: {
141추가: return Err(ErrorCode::SourceChanged);
142추가: }
143추가: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io)?;
144추가: Ok(Self {
145추가: file,
146추가: len,
147추가: object,
148추가: hash: hash.finalize().into(),
149추가: })
150추가: }
151추가: }
추가experiments/rust-archive-worker/src/streaming.rs+739-0
@@ -0,0 +1,739 @@
1추가: use crate::{
2추가: archive::{self, Member, MetadataBudget},
3추가: crypto,
4추가: protocol::*,
5추가: spool,
6추가: };
7추가: use std::{
8추가: fs::File,
9추가: io::{Read, Seek, SeekFrom, Write},
10추가: };
11추가: use zeroize::Zeroizing;
12추가: use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32};
13추가:
14추가: type Result<T> = std::result::Result<T, ErrorCode>;
15추가: const CHUNK: usize = 65536;
16추가: fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> {
17추가: file.seek(SeekFrom::Start(offset))
18추가: .map_err(|_| ErrorCode::Io)?;
19추가: file.read_exact(bytes).map_err(|_| ErrorCode::Integrity)
20추가: }
21추가: fn bytes(file: &mut File, offset: u64, size: usize) -> Result<Vec<u8>> {
22추가: let mut result = vec![0; size];
23추가: at(file, offset, &mut result)?;
24추가: Ok(result)
25추가: }
26추가: fn u16at(b: &[u8], at: usize) -> u16 {
27추가: u16::from_le_bytes(b[at..at + 2].try_into().unwrap())
28추가: }
29추가: fn u32at(b: &[u8], at: usize) -> u32 {
30추가: u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
31추가: }
32추가: fn u64at(b: &[u8], at: usize) -> u64 {
33추가: u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
34추가: }
35추가: fn add(a: u64, b: u64) -> Result<u64> {
36추가: a.checked_add(b).ok_or(ErrorCode::Integrity)
37추가: }
38추가: fn io<T>(v: std::io::Result<T>) -> Result<T> {
39추가: v.map_err(crate::space::io_error)
40추가: }
41추가:
42추가: pub(crate) struct Catalog {
43추가: pub format: Format,
44추가: pub members: Vec<Member>,
45추가: pub offsets: Vec<u64>,
46추가: pub data: File,
47추가: }
48추가: impl Catalog {
49추가: pub fn open(
50추가: source: &mut File,
51추가: len: u64,
52추가: limits: Limits,
53추가: decode: bool,
54추가: password: Option<&[u8]>,
55추가: check: &mut impl FnMut() -> Result<()>,
56추가: ) -> Result<Self> {
57추가: let mut magic = [0; 6];
58추가: let n = len.min(6) as usize;
59추가: at(source, 0, &mut magic[..n])?;
60추가: 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추가: });
82추가: }
83추가: if magic.starts_with(b"PK\x03\x04")
84추가: || magic.starts_with(b"PK\x05\x06")
85추가: || magic.starts_with(b"PK\x06\x06")
86추가: {
87추가: return zip(source, len, limits, decode, password, check);
88추가: }
89추가: if magic.starts_with(&[31, 139]) {
90추가: let mut data = spool::temporary()?;
91추가: io(source.rewind())?;
92추가: let expanded = inflate(source, len, true, limits.output, &mut data, check)?.0;
93추가: let mut header = [0; 512];
94추가: if expanded >= 512 {
95추가: at(&mut data, 0, &mut header)?;
96추가: if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
97추가: return tar(data, expanded, limits, Format::TarGzip, check);
98추가: }
99추가: }
100추가: return Ok(Self {
101추가: format: Format::Gzip,
102추가: members: vec![Member {
103추가: entry: Entry {
104추가: entry_id: 0,
105추가: name: "GZip stream".to_owned(),
106추가: kind: EntryKind::File,
107추가: size: expanded,
108추가: compressed_size: len,
109추가: encrypted: false,
110추가: },
111추가: data: Vec::new(),
112추가: }],
113추가: offsets: vec![0],
114추가: data,
115추가: });
116추가: }
117추가: if len >= 512 {
118추가: return tar(io(source.try_clone())?, len, limits, Format::Tar, check);
119추가: }
120추가: Err(ErrorCode::UnsupportedFormat)
121추가: }
122추가: }
123추가:
124추가: fn tar(
125추가: mut data: File,
126추가: len: u64,
127추가: limits: Limits,
128추가: format: Format,
129추가: check: &mut impl FnMut() -> Result<()>,
130추가: ) -> Result<Catalog> {
131추가: let mut cursor = 0u64;
132추가: let mut total = 0u64;
133추가: let mut members = Vec::new();
134추가: let mut offsets = Vec::new();
135추가: let mut metadata = MetadataBudget::default();
136추가: loop {
137추가: check()?;
138추가: let mut header = [0; 512];
139추가: if add(cursor, 512)? > len {
140추가: return Err(ErrorCode::Integrity);
141추가: }
142추가: at(&mut data, cursor, &mut header)?;
143추가: if header.iter().all(|b| *b == 0) {
144추가: if add(cursor, 1024)? > len || len % 512 != 0 {
145추가: return Err(ErrorCode::Integrity);
146추가: }
147추가: let mut buffer = Zeroizing::new([0; CHUNK]);
148추가: let mut remaining = len - cursor - 512;
149추가: while remaining != 0 {
150추가: check()?;
151추가: let n = remaining.min(CHUNK as u64) as usize;
152추가: io(data.read_exact(&mut buffer[..n]))?;
153추가: if buffer[..n].iter().any(|b| *b != 0) {
154추가: return Err(ErrorCode::Integrity);
155추가: }
156추가: remaining -= n as u64;
157추가: }
158추가: break;
159추가: }
160추가: if members.len() >= limits.entries as usize {
161추가: return Err(ErrorCode::Limit);
162추가: }
163추가: let sum = header
164추가: .iter()
165추가: .enumerate()
166추가: .map(|(i, b)| {
167추가: if (148..156).contains(&i) {
168추가: 32
169추가: } else {
170추가: *b as u64
171추가: }
172추가: })
173추가: .sum::<u64>();
174추가: if sum != archive::octal(&header[148..156])? {
175추가: return Err(ErrorCode::Integrity);
176추가: }
177추가: let mut name = archive::tar_string(&header[..100])?;
178추가: if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
179추가: let prefix = archive::tar_string(&header[345..500])?;
180추가: if !prefix.is_empty() {
181추가: name = format!("{prefix}/{name}");
182추가: }
183추가: } else if header[257..263].iter().any(|b| *b != 0) {
184추가: return Err(ErrorCode::UnsupportedFeature);
185추가: }
186추가: let kind = match header[156] {
187추가: 0 | b'0' => EntryKind::File,
188추가: b'5' => EntryKind::Directory,
189추가: b'1' | b'2' => EntryKind::Link,
190추가: b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
191추가: _ => EntryKind::Other,
192추가: };
193추가: let size = archive::octal(&header[124..136])?;
194추가: if kind != EntryKind::File && size != 0 {
195추가: return Err(ErrorCode::Integrity);
196추가: }
197추가: total = total
198추가: .checked_add(size)
199추가: .filter(|n| *n <= limits.output)
200추가: .ok_or(ErrorCode::Limit)?;
201추가: let start = add(cursor, 512)?;
202추가: cursor = add(
203추가: start,
204추가: size.checked_add(511).ok_or(ErrorCode::Integrity)? / 512 * 512,
205추가: )?;
206추가: if cursor > len {
207추가: return Err(ErrorCode::Integrity);
208추가: }
209추가: metadata.charge(&name)?;
210추가: let name = archive::valid_name(&name, kind == EntryKind::Directory)?;
211추가: offsets.push(start);
212추가: members.push(Member {
213추가: entry: Entry {
214추가: entry_id: members.len() as u32,
215추가: name,
216추가: kind,
217추가: size,
218추가: compressed_size: size,
219추가: encrypted: false,
220추가: },
221추가: data: Vec::new(),
222추가: });
223추가: }
224추가: archive::validate_members(&members)?;
225추가: Ok(Catalog {
226추가: format,
227추가: members,
228추가: offsets,
229추가: data,
230추가: })
231추가: }
232추가:
233추가: // ZIP 항목과 연결 GZip 스트림의 해제 총량을 제한함.
234추가: fn inflate(
235추가: input: &mut impl Read,
236추가: length: u64,
237추가: gzip: bool,
238추가: limit: u64,
239추가: output: &mut File,
240추가: check: &mut impl FnMut() -> Result<()>,
241추가: ) -> Result<(u64, u32)> {
242추가: let mut remaining = length;
243추가: let mut buffer = Zeroizing::new([0; CHUNK]);
244추가: let mut plain = Zeroizing::new([0; CHUNK]);
245추가: let mut have = 0;
246추가: let mut used = 0;
247추가: let mut total = 0u64;
248추가: let mut crc = 0;
249추가: loop {
250추가: let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
251추가: loop {
252추가: check()?;
253추가: if used == have && remaining != 0 {
254추가: have = input
255추가: .read(&mut buffer[..remaining.min(CHUNK as u64) as usize])
256추가: .map_err(|_| ErrorCode::Io)?;
257추가: if have == 0 {
258추가: return Err(ErrorCode::Integrity);
259추가: }
260추가: remaining -= have as u64;
261추가: used = 0;
262추가: }
263추가: let a = stream.total_in();
264추가: let b = stream.total_out();
265추가: let status = stream
266추가: .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush)
267추가: .map_err(|_| ErrorCode::Integrity)?;
268추가: used += (stream.total_in() - a) as usize;
269추가: let n = (stream.total_out() - b) as usize;
270추가: total = total
271추가: .checked_add(n as u64)
272추가: .filter(|n| *n <= limit)
273추가: .ok_or(ErrorCode::Limit)?;
274추가: crc = crc32(crc, &plain[..n]);
275추가: crate::space::ensure(output, n as u64)?;
276추가: io(output.write_all(&plain[..n]))?;
277추가: if status == Status::StreamEnd {
278추가: break;
279추가: }
280추가: if a == stream.total_in() && b == stream.total_out() {
281추가: return Err(ErrorCode::Integrity);
282추가: }
283추가: }
284추가: if remaining == 0 && used == have {
285추가: break;
286추가: }
287추가: if !gzip {
288추가: return Err(ErrorCode::Integrity);
289추가: }
290추가: }
291추가: Ok((total, crc))
292추가: }
293추가:
294추가: struct Packed {
295추가: offset: u64,
296추가: size: u64,
297추가: method: u16,
298추가: crc: Option<u32>,
299추가: flags: u16,
300추가: verifier: u8,
301추가: aes: bool,
302추가: }
303추가:
304추가: fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
305추가: let mut at = 0;
306추가: let mut aes = Vec::new();
307추가: let mut large = None;
308추가: while at < bytes.len() {
309추가: if bytes.len() - at < 4 {
310추가: return Err(ErrorCode::Integrity);
311추가: }
312추가: let tag = u16at(bytes, at);
313추가: let len = u16at(bytes, at + 2) as usize;
314추가: let end = at + 4 + len;
315추가: if end > bytes.len() {
316추가: return Err(ErrorCode::Integrity);
317추가: }
318추가: if tag == 1 {
319추가: if large.is_some() {
320추가: return Err(ErrorCode::Integrity);
321추가: }
322추가: large = Some(bytes[at + 4..end].to_vec());
323추가: } else {
324추가: aes.extend_from_slice(&bytes[at..end]);
325추가: }
326추가: at = end;
327추가: }
328추가: Ok((archive::aes_extra(&aes)?, large))
329추가: }
330추가: fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
331추가: if value != u32::MAX {
332추가: return Ok(value as u64);
333추가: }
334추가: if extra.len() < 8 {
335추가: return Err(ErrorCode::Integrity);
336추가: }
337추가: let result = u64at(extra, 0);
338추가: *extra = &extra[8..];
339추가: Ok(result)
340추가: }
341추가: fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
342추가: if value == maximum || value == large {
343추가: Ok(large)
344추가: } else {
345추가: Err(ErrorCode::Integrity)
346추가: }
347추가: }
348추가: fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
349추가: if value != u16::MAX {
350추가: return Ok(value as u32);
351추가: }
352추가: if extra.len() < 4 {
353추가: return Err(ErrorCode::Integrity);
354추가: }
355추가: let result = u32at(extra, 0);
356추가: *extra = &extra[4..];
357추가: Ok(result)
358추가: }
359추가: fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
360추가: if let Some(extra) = extra {
361추가: // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
362추가: if extra.len() < 16 {
363추가: return Err(ErrorCode::Integrity);
364추가: }
365추가: Ok((
366추가: expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
367추가: expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
368추가: ))
369추가: } else if size == u32::MAX || compressed == u32::MAX {
370추가: Err(ErrorCode::Integrity)
371추가: } else {
372추가: Ok((size as u64, compressed as u64))
373추가: }
374추가: }
375추가: fn descriptor_size(
376추가: bytes: &[u8],
377추가: crc: u32,
378추가: compressed: u64,
379추가: size: u64,
380추가: wide_required: bool,
381추가: ) -> Result<usize> {
382추가: // 일반 크기 헤더와 64비트 디스크립터를 함께 기록하는 도구도 있음.
383추가: if bytes.len() >= 20
384추가: && u32at(bytes, 0) == crc
385추가: && u64at(bytes, 4) == compressed
386추가: && u64at(bytes, 12) == size
387추가: {
388추가: return Ok(20);
389추가: }
390추가: if !wide_required
391추가: && bytes.len() >= 12
392추가: && u32at(bytes, 0) == crc
393추가: && u32at(bytes, 4) as u64 == compressed
394추가: && u32at(bytes, 8) as u64 == size
395추가: {
396추가: return Ok(12);
397추가: }
398추가: Err(ErrorCode::Integrity)
399추가: }
400추가: fn zip(
401추가: source: &mut File,
402추가: len: u64,
403추가: limits: Limits,
404추가: decode: bool,
405추가: password: Option<&[u8]>,
406추가: check: &mut impl FnMut() -> Result<()>,
407추가: ) -> Result<Catalog> {
408추가: if len < 22 {
409추가: return Err(ErrorCode::Integrity);
410추가: }
411추가: let tail_at = len.saturating_sub(65557);
412추가: let tail = bytes(source, tail_at, (len - tail_at) as usize)?;
413추가: let end = (0..=tail.len() - 22)
414추가: .rev()
415추가: .find(|&i| {
416추가: &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len()
417추가: })
418추가: .ok_or(ErrorCode::Integrity)?;
419추가: let h = &tail[end..];
420추가: let mut disk = u16at(h, 4) as u64;
421추가: let mut central_disk = u16at(h, 6) as u64;
422추가: let mut entries_on_disk = u16at(h, 8) as u64;
423추가: let mut count = u16at(h, 10) as u64;
424추가: let mut central_size = u32at(h, 12) as u64;
425추가: let mut central = u32at(h, 16) as u64;
426추가: let mut central_end = tail_at + end as u64;
427추가: let required_zip64 = [disk, central_disk, entries_on_disk, count].contains(&(u16::MAX as u64))
428추가: || central_size == u32::MAX as u64
429추가: || central == u32::MAX as u64;
430추가: let locator = if central_end >= 20 {
431추가: bytes(source, central_end - 20, 20)?
432추가: } else {
433추가: Vec::new()
434추가: };
435추가: // 중앙 디렉터리 주석의 동일 서명을 locator로 오인하지 않음
436추가: let has_locator =
437추가: locator.starts_with(b"PK\x06\x07") && add(central, central_size)? != central_end;
438추가: if required_zip64 || has_locator {
439추가: if locator.len() != 20 {
440추가: return Err(ErrorCode::Integrity);
441추가: }
442추가: if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
443추가: return Err(ErrorCode::UnsupportedFeature);
444추가: }
445추가: let offset = u64at(&locator, 8);
446추가: if add(offset, 56)? > central_end - 20 {
447추가: return Err(ErrorCode::Integrity);
448추가: }
449추가: let large = bytes(source, offset, 56)?;
450추가: if &large[..4] != b"PK\x06\x06"
451추가: || u64at(&large, 4) < 44
452추가: || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20
453추가: {
454추가: return Err(ErrorCode::Integrity);
455추가: }
456추가: // 각 필드의 확장값을 해석한 뒤 단일 디스크 조건을 검사함.
457추가: disk = expanded(disk, u16::MAX as u64, u32at(&large, 16) as u64)?;
458추가: central_disk = expanded(central_disk, u16::MAX as u64, u32at(&large, 20) as u64)?;
459추가: entries_on_disk = expanded(entries_on_disk, u16::MAX as u64, u64at(&large, 24))?;
460추가: count = expanded(count, u16::MAX as u64, u64at(&large, 32))?;
461추가: central_size = expanded(central_size, u32::MAX as u64, u64at(&large, 40))?;
462추가: central = expanded(central, u32::MAX as u64, u64at(&large, 48))?;
463추가: central_end = offset;
464추가: }
465추가: if disk != 0 || central_disk != 0 || entries_on_disk != count {
466추가: return Err(ErrorCode::UnsupportedFeature);
467추가: }
468추가: if count > limits.entries as u64 {
469추가: return Err(ErrorCode::Limit);
470추가: }
471추가: if add(central, central_size)? != central_end {
472추가: return Err(ErrorCode::Integrity);
473추가: }
474추가: let mut cursor = central;
475추가: let mut total = 0u64;
476추가: let mut metadata = MetadataBudget::default();
477추가: let mut members = Vec::new();
478추가: let mut packed = Vec::new();
479추가: let mut spans = Vec::new();
480추가: for id in 0..count {
481추가: check()?;
482추가: if add(cursor, 46)? > central_end {
483추가: return Err(ErrorCode::Integrity);
484추가: }
485추가: let h = bytes(source, cursor, 46)?;
486추가: if &h[..4] != b"PK\x01\x02" {
487추가: return Err(ErrorCode::Integrity);
488추가: }
489추가: let flags = u16at(&h, 8);
490추가: let method = u16at(&h, 10);
491추가: if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) {
492추가: return Err(ErrorCode::UnsupportedFeature);
493추가: }
494추가: let crc = u32at(&h, 16);
495추가: let (nn, ne, nc) = (
496추가: u16at(&h, 28) as u64,
497추가: u16at(&h, 30) as u64,
498추가: u16at(&h, 32) as u64,
499추가: );
500추가: let next = add(cursor, 46 + nn + ne + nc)?;
501추가: if next > central_end {
502추가: return Err(ErrorCode::Integrity);
503추가: }
504추가: if nn > 4096 {
505추가: return Err(ErrorCode::UnsafePath);
506추가: }
507추가: let raw = bytes(source, cursor + 46, nn as usize)?;
508추가: if flags & 0x0800 == 0 && !raw.is_ascii() {
509추가: return Err(ErrorCode::UnsupportedFeature);
510추가: }
511추가: let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?;
512추가: let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?;
513추가: let mut large = large.as_deref().unwrap_or(&[]);
514추가: let size = large_value(u32at(&h, 24), &mut large)?;
515추가: let compressed = large_value(u32at(&h, 20), &mut large)?;
516추가: let local = large_value(u32at(&h, 42), &mut large)?;
517추가: if disk_start(u16at(&h, 34), &mut large)? != 0 {
518추가: return Err(ErrorCode::UnsupportedFeature);
519추가: }
520추가: let encrypted = flags & 1 != 0;
521추가: if (method == 99) != aes.is_some()
522추가: || (method == 99 && !encrypted)
523추가: || (aes.is_some_and(|a| a.version == 2) && crc != 0)
524추가: {
525추가: return Err(ErrorCode::Integrity);
526추가: }
527추가: let overhead = if !encrypted {
528추가: 0
529추가: } else if aes.is_some() {
530추가: 28
531추가: } else {
532추가: 12
533추가: };
534추가: compressed
535추가: .checked_sub(overhead)
536추가: .ok_or(ErrorCode::Integrity)?;
537추가: total = total
538추가: .checked_add(size)
539추가: .filter(|n| *n <= limits.output)
540추가: .ok_or(ErrorCode::Limit)?;
541추가: let mode = u32at(&h, 38) >> 16;
542추가: let kind = match mode & 0xf000 {
543추가: 0xa000 => EntryKind::Link,
544추가: 0x4000 => EntryKind::Directory,
545추가: 0 | 0x8000 => {
546추가: if name.ends_with('/') {
547추가: EntryKind::Directory
548추가: } else {
549추가: EntryKind::File
550추가: }
551추가: }
552추가: _ => EntryKind::Other,
553추가: };
554추가: if kind == EntryKind::Directory && size != 0 {
555추가: return Err(ErrorCode::Integrity);
556추가: }
557추가: metadata.charge(name)?;
558추가: let name = archive::valid_name(name, kind == EntryKind::Directory)?;
559추가: if add(local, 30)? > central {
560추가: return Err(ErrorCode::Integrity);
561추가: }
562추가: let lh = bytes(source, local, 30)?;
563추가: if &lh[..4] != b"PK\x03\x04"
564추가: || u16at(&lh, 6) != flags
565추가: || u16at(&lh, 8) != method
566추가: || u16at(&lh, 10) != u16at(&h, 12)
567추가: {
568추가: return Err(ErrorCode::Integrity);
569추가: }
570추가: let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64);
571추가: let start = add(local, 30 + ln + le)?;
572추가: if start > central || ln != nn {
573추가: return Err(ErrorCode::Integrity);
574추가: }
575추가: if bytes(source, local + 30, ln as usize)? != raw {
576추가: return Err(ErrorCode::Integrity);
577추가: }
578추가: let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
579추가: if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) {
580추가: return Err(ErrorCode::Integrity);
581추가: }
582추가: let size_zip64 = u32at(&h, 20) == u32::MAX
583추가: || u32at(&h, 24) == u32::MAX
584추가: || u32at(&lh, 18) == u32::MAX
585추가: || u32at(&lh, 22) == u32::MAX
586추가: || local_large.is_some();
587추가: if flags & 8 == 0 {
588추가: let (local_size, local_compressed) =
589추가: local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?;
590추가: if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
591추가: return Err(ErrorCode::Integrity);
592추가: }
593추가: }
594추가: let mut stop = add(start, compressed)?;
595추가: if stop > central {
596추가: return Err(ErrorCode::Integrity);
597추가: }
598추가: if flags & 8 != 0 {
599추가: let descriptor_len = if size_zip64 { 20 } else { 12 };
600추가: if add(stop, descriptor_len)? > central {
601추가: return Err(ErrorCode::Integrity);
602추가: }
603추가: let signature = bytes(source, stop, 4)?;
604추가: if signature == b"PK\x07\x08" {
605추가: stop = add(stop, 4)?;
606추가: }
607추가: let d = bytes(source, stop, (central - stop).min(20) as usize)?;
608추가: let descriptor_len = descriptor_size(&d, crc, compressed, size, size_zip64)?;
609추가: stop = add(stop, descriptor_len as u64)?;
610추가: }
611추가: spans.push((local, stop));
612추가: packed.push(Packed {
613추가: offset: start,
614추가: size: compressed,
615추가: method: aes.map_or(method, |a| a.method),
616추가: crc: if aes.is_some_and(|a| a.version == 2) {
617추가: None
618추가: } else {
619추가: Some(crc)
620추가: },
621추가: flags,
622추가: verifier: if flags & 8 != 0 {
623추가: (u16at(&h, 12) >> 8) as u8
624추가: } else {
625추가: (crc >> 24) as u8
626추가: },
627추가: aes: aes.is_some(),
628추가: });
629추가: members.push(Member {
630추가: entry: Entry {
631추가: entry_id: id as u32,
632추가: name,
633추가: kind,
634추가: size,
635추가: compressed_size: compressed,
636추가: encrypted,
637추가: },
638추가: data: Vec::new(),
639추가: });
640추가: cursor = next;
641추가: }
642추가: if cursor != central_end {
643추가: return Err(ErrorCode::Integrity);
644추가: }
645추가: spans.sort_unstable();
646추가: let mut next = 0;
647추가: for (a, b) in spans {
648추가: if a != next {
649추가: return Err(ErrorCode::Integrity);
650추가: }
651추가: next = b;
652추가: }
653추가: if next != central {
654추가: return Err(ErrorCode::Integrity);
655추가: }
656추가: archive::validate_members(&members)?;
657추가: let mut data = spool::temporary()?;
658추가: if decode {
659추가: crate::space::ensure(&data, total)?;
660추가: }
661추가: let mut offsets = Vec::new();
662추가: for (member, packed) in members.iter().zip(packed) {
663추가: check()?;
664추가: offsets.push(io(data.stream_position())?);
665추가: if !decode {
666추가: continue;
667추가: }
668추가: let (decoder, start, length) = if packed.flags & 1 != 0 {
669추가: crypto::Decryptor::prepare(
670추가: source,
671추가: packed.offset,
672추가: packed.size,
673추가: password.ok_or(ErrorCode::WrongPassword)?,
674추가: packed.aes,
675추가: packed.verifier,
676추가: check,
677추가: )?
678추가: } else {
679추가: (crypto::Decryptor::Plain, packed.offset, packed.size)
680추가: };
681추가: io(source.seek(SeekFrom::Start(start)))?;
682추가: let mut reader = Decoded {
683추가: reader: source.take(length),
684추가: decoder,
685추가: };
686추가: let (size, crc) = if packed.method == 8 {
687추가: inflate(
688추가: &mut reader,
689추가: length,
690추가: false,
691추가: member.entry.size,
692추가: &mut data,
693추가: check,
694추가: )?
695추가: } else {
696추가: let mut buffer = Zeroizing::new([0; CHUNK]);
697추가: let mut total = 0u64;
698추가: let mut crc = 0;
699추가: loop {
700추가: check()?;
701추가: let n = io(reader.read(&mut buffer[..]))?;
702추가: if n == 0 {
703추가: break;
704추가: }
705추가: total = total
706추가: .checked_add(n as u64)
707추가: .filter(|n| *n <= member.entry.size)
708추가: .ok_or(ErrorCode::Integrity)?;
709추가: crc = crc32(crc, &buffer[..n]);
710추가: io(data.write_all(&buffer[..n]))?;
711추가: }
712추가: (total, crc)
713추가: };
714추가: if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) {
715추가: return Err(ErrorCode::Integrity);
716추가: }
717추가: }
718추가: Ok(Catalog {
719추가: format: Format::Zip,
720추가: members,
721추가: offsets,
722추가: data,
723추가: })
724추가: }
725추가: struct Decoded<R> {
726추가: reader: R,
727추가: decoder: crypto::Decryptor,
728추가: }
729추가: impl<R: Read> Read for Decoded<R> {
730추가: fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
731추가: let n = self.reader.read(output)?;
732추가: self.decoder.apply(&mut output[..n]);
733추가: Ok(n)
734추가: }
735추가: }
736추가:
737추가: #[cfg(test)]
738추가: #[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"]
739추가: mod bounds;
수정experiments/rust-archive-worker/src/wire.rs+1-1
@@ -133,7 +133,7 @@ enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
133133enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
134134enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
135135enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
136삭제: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12});
136추가: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13});
137137enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
138138enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
139139enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
수정experiments/rust-ui-memory-app/src/archive_process.rs+1-0
@@ -209,6 +209,7 @@ fn error_to_ui(error: wire::ErrorCode) -> Option<ui::ErrorCode> {
209209 wire::ErrorCode::Conflict => ui::ErrorCode::Conflict,
210210 wire::ErrorCode::Limit => ui::ErrorCode::Limit,
211211 wire::ErrorCode::Io => ui::ErrorCode::Io,
212추가: wire::ErrorCode::DiskFull => ui::ErrorCode::DiskFull,
212213 wire::ErrorCode::Protocol => ui::ErrorCode::Protocol,
213214 wire::ErrorCode::Internal => ui::ErrorCode::Internal,
214215 wire::ErrorCode::SourceChanged => ui::ErrorCode::SourceChanged,
수정experiments/rust-ui-memory-app/src/archive_ui.rs+7-1
@@ -128,6 +128,7 @@ pub enum ErrorCode {
128128 Conflict,
129129 Limit,
130130 Io,
131추가: DiskFull,
131132 Protocol,
132133 Internal,
133134 SourceChanged,
@@ -804,7 +805,12 @@ pub fn terminal_lines(t: &Terminal) -> Vec<String> {
804805 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
805806 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
806807 ErrorCode::Limit => "처리 한도를 초과했습니다",
807삭제: ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다",
808추가: ErrorCode::Io => {
809추가: "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
810추가: }
811추가: ErrorCode::DiskFull => {
812추가: "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
813추가: }
808814 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
809815 ErrorCode::Internal => "작업자 처리 오류입니다",
810816 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
추가tests/ci/test_large_archive_fixtures.py+93-0
@@ -0,0 +1,93 @@
1추가: import gzip
2추가: import importlib.util
3추가: import io
4추가: from pathlib import Path
5추가: import tarfile
6추가: import tempfile
7추가: import unittest
8추가: import zipfile
9추가:
10추가:
11추가: ROOT = Path(__file__).resolve().parents[2]
12추가: SPEC = importlib.util.spec_from_file_location(
13추가: "large_fixture_generator", ROOT / "tests/large-archive-fixtures/generate.py"
14추가: )
15추가: GENERATOR = importlib.util.module_from_spec(SPEC)
16추가: SPEC.loader.exec_module(GENERATOR)
17추가:
18추가:
19추가: class LargeArchiveFixtureTests(unittest.TestCase):
20추가: def test_boundary_archives_are_valid_and_expectations_straddle_limit(self):
21추가: with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch:
22추가: directory = Path(scratch) / "corpus"
23추가: manifest = GENERATOR.build(directory)
24추가: self.assertEqual(len(manifest["cases"]), 11)
25추가: self.assertFalse(manifest["worker_execution_verified"])
26추가: for name in ("boundary.zip", "boundary.tar.gz"):
27추가: artifact = manifest["artifacts"][name]
28추가: path = directory / name
29추가: self.assertEqual(GENERATOR.digest(path), artifact["sha256"])
30추가: if name.endswith(".zip"):
31추가: with zipfile.ZipFile(path) as archive:
32추가: self.assertIsNone(archive.testzip())
33추가: payload = archive.read(GENERATOR.NAME)
34추가: decoded = len(payload)
35추가: else:
36추가: data = gzip.decompress(path.read_bytes())
37추가: decoded = len(data)
38추가: with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as archive:
39추가: payload = archive.extractfile(GENERATOR.NAME).read()
40추가: self.assertEqual(payload, bytes(artifact["payload_bytes"]))
41추가: self.assertEqual(decoded, artifact["decoded_bytes"])
42추가: self.assertEqual(decoded, 65536)
43추가: self.assertGreater(decoded / artifact["archive_bytes"], 100)
44추가: for case in manifest["cases"]:
45추가: decoded = manifest["artifacts"][case["file"]]["decoded_bytes"]
46추가: exceeded = GENERATOR.violations(manifest["artifacts"][case["file"]], case["limits"])
47추가: self.assertEqual(exceeded, case["violated_limits"])
48추가: self.assertLessEqual(len(exceeded), 1)
49추가: self.assertEqual(case["limits"]["input"], 2 ** 64 - 1)
50추가: failed = bool(exceeded)
51추가: self.assertEqual(case["expected"]["error"], "Limit" if failed else "None")
52추가: self.assertEqual(case["expected"]["created_count"], 0 if failed else 1)
53추가:
54추가: def test_former_ratio_samples_all_expect_success(self):
55추가: with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch:
56추가: manifest = GENERATOR.build(Path(scratch) / "corpus")
57추가: for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)):
58추가: name = "ratio-" + suffix + ".gz"
59추가: artifact = manifest["artifacts"][name]
60추가: self.assertEqual(artifact["decoded_bytes"] - 1000 * artifact["ratio_input_bytes"], delta)
61추가: self.assertLess(artifact["decoded_bytes"], GENERATOR.OUTPUT_LIMIT)
62추가: case = next(c for c in manifest["cases"] if c["file"] == name)
63추가: self.assertEqual(case["expected"]["outcome"], "Completed")
64추가: self.assertIsNone(manifest["policy"]["ratio"])
65추가: payload = gzip.decompress((Path(scratch) / "corpus" / name).read_bytes())
66추가: self.assertEqual(payload, bytes(artifact["payload_bytes"]))
67추가:
68추가: def test_generator_rejects_existing_destination_without_changes(self):
69추가: with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch:
70추가: directory = Path(scratch)
71추가: marker = directory / "keep"
72추가: marker.write_bytes(b"preserve")
73추가: with self.assertRaises(FileExistsError):
74추가: GENERATOR.build(directory)
75추가: self.assertEqual(list(directory.iterdir()), [marker])
76추가: self.assertEqual(marker.read_bytes(), b"preserve")
77추가:
78추가: def test_generator_requires_project_test_directory(self):
79추가: with self.assertRaises(ValueError):
80추가: GENERATOR.build(ROOT / "outside-tests")
81추가:
82추가: def test_payload_source_enforces_bounded_reads(self):
83추가: source = GENERATOR.ZeroStream(GENERATOR.GIB)
84추가: with self.assertRaises(ValueError):
85추가: source.read()
86추가: with self.assertRaises(ValueError):
87추가: source.read(GENERATOR.CHUNK + 1)
88추가: self.assertEqual(source.read(GENERATOR.CHUNK), bytes(GENERATOR.CHUNK))
89추가: self.assertEqual(source.remaining, GENERATOR.GIB - GENERATOR.CHUNK)
90추가:
91추가:
92추가: if __name__ == "__main__":
93추가: unittest.main()
추가tests/large-archive-fixtures/.gitignore+1-0
@@ -0,0 +1 @@
1추가: /runs/
추가tests/large-archive-fixtures/README.md+35-0
@@ -0,0 +1,35 @@
1추가: # 대용량 압축파일 회귀 표본
2추가:
3추가: Python 표준 라이브러리로 실행할 때 합성 표본을 생성합니다. 생성 데이터는 커밋하지 않으며 읽기와 쓰기는 64 KiB로 나눕니다. revision 2의 입력 u64::MAX와 해제 총량 16 GiB를 사용합니다. 압축비는 거부 조건이 아닙니다.
4추가:
5추가: ## 독립된 경계
6추가:
7추가: - large-input.zip과 large-input.tar.gz: 1 GiB payload를 Store ZIP과 Gzip level 0의 TAR로 저장합니다. 압축파일 자체가 1 GiB 이상이며 다른 한도 이내이므로 실제 해제가 성공해야 합니다.
8추가: - output-only.zip: 유효한 ZIP64에 16 GiB + 1바이트를 level 1로 압축합니다. 해제 총량만 초과합니다. 압축비는 관측 정보입니다. 요청은 Failed/Limit으로 끝나고 출력이 없어야 합니다. Python 참조 판독기가 전체 16 GiB + 1바이트와 CRC를 스트리밍 검증합니다. 제품의 해당 크기 해제 성공을 검증하는 시험은 아닙니다.
9추가: - boundary.zip과 boundary.tar.gz: 실제 해제 크기 65536바이트에 요청 output을 65537, 65536, 65535로 설정해 경계 직전, 일치, 초과를 실제 해제로 검사합니다. TAR.GZ는 TAR 헤더와 패딩 및 종료 블록도 총량에 포함합니다.
10추가: - ratio-below.gz, ratio-equal.gz, ratio-above.gz: FEXTRA를 포함한 유효한 GZ 멤버 길이를 정확히 2000바이트로 맞춥니다. 해제 크기는 각각 1999999, 2000000, 2000001바이트로, 과거 1000:1 경계보다 정확히 1바이트 작음, 일치, 1바이트 큼입니다. 세 표본 모두 총량이 16 GiB보다 작으므로 정상 해제되어야 합니다.
11추가: - ratio-only.zip과 ratio-only.tar.gz: 16 MiB payload를 level 6으로 압축해 과거 비율 한도를 초과시킵니다. 두 표본 모두 정상 해제되어야 합니다. ZIP의 관측 비율 분모는 항목의 압축 payload, GZ의 분모는 헤더와 트레일러를 포함한 멤버 전체 바이트입니다.
12추가:
13추가: 생성 시 실제 archive_bytes, decoded_bytes, ratio_input_bytes와 요청 한도를 비교해 violated_limits가 정확히 일치하는지 검사합니다. 한 표본에서 여러 한도를 넘으면 생성을 실패시킵니다. 입력, 출력, 항목 수는 manifest의 실제 값이 모두 작업자 요청에 전달됩니다. 생성 결과만으로 검증 완료를 주장하지 않도록 worker_execution_verified=false를 기록합니다.
14추가:
15추가: ## 실행
16추가:
17추가: 저장소 루트에서 실행합니다. --large는 1 GiB 성공 2건과 16 GiB 초과 거부를 포함해 총 14건을 검사합니다. 생성을 포함한 기본 실행은 tests 안의 전용 임시 디렉터리를 쓰고 종료 시 정리합니다. 압축 표본, 입력 사본과 출력에 수 GiB의 임시 디스크 공간이 필요합니다.
18추가:
19추가: ```sh
20추가: python3 tests/ci/run_rust.py local
21추가: python3 tests/large-archive-fixtures/verify.py --large
22추가: ```
23추가:
24추가: CARGO_TARGET_DIR을 지정했다면 검증기도 같은 환경 값을 사용합니다. --probe와 --worker로 바이너리 경로를 따로 지정할 수도 있습니다. --large를 생략하면 작은 경계 및 고압축 호환성 11건만 검사합니다. 기본 local 실행에는 작은 표본의 참조 무결성, 경계 독립성과 생성기 경로 및 버퍼 제약 검사가 포함됩니다.
25추가:
26추가: 표본을 보존하려면 아래처럼 새 경로를 지정합니다. 기존 디렉터리는 생성기가 덮어쓰지 않으며, 검증기는 기존 expectations.json이 있으면 재사용합니다.
27추가:
28추가: ```sh
29추가: python3 tests/large-archive-fixtures/generate.py --large --output tests/large-archive-fixtures/runs/full
30추가: python3 tests/large-archive-fixtures/verify.py --large --directory tests/large-archive-fixtures/runs/full
31추가: ```
32추가:
33추가: 검증기는 전체 표본을 참조 판독기로 읽어 합성 내용, CRC와 TAR 구조를 확인한 후 실제 작업자의 종료 코드, Terminal, 오류, 게시 상태, Output 개수와 정리를 확인합니다. 성공 파일은 길이와 모든 바이트를 검사하며 거부한 경우 출력 폴더가 비어 있어야 합니다. 입력의 전후 SHA-256도 확인합니다. 작업자 피크 RSS, 디스크 부족과 고아 작업자 정리는 tests/rust-archive-worker/hardening.rs에서 별도로 검사합니다. Windows 실기는 별도 검증이 필요합니다.
34추가:
35추가: 압축비는 expectations.json의 거부 사유에서 제거했고 policy.ratio는 null입니다. 공간이 부족하면 실제 작업자는 기존 Io를 반환하므로, 성공 표본 검증에는 입력 사본과 해제 임시 파일 및 출력을 위한 여유 디스크가 필요합니다.
추가tests/large-archive-fixtures/generate.py+204-0
@@ -0,0 +1,204 @@
1추가: """고정 크기 버퍼로 새 스트리밍 한도의 독립 경계 표본을 생성함."""
2추가:
3추가: import argparse
4추가: import gzip
5추가: import hashlib
6추가: import io
7추가: import json
8추가: from pathlib import Path
9추가: import struct
10추가: import tarfile
11추가: import zipfile
12추가: import zlib
13추가:
14추가:
15추가: ROOT = Path(__file__).resolve().parents[2]
16추가: GIB = 1024 ** 3
17추가: CHUNK = 64 * 1024
18추가: INPUT_LIMIT = 2 ** 64 - 1
19추가: OUTPUT_LIMIT = 16 * GIB
20추가: NAME = "payload.bin"
21추가:
22추가:
23추가: class ZeroStream(io.RawIOBase):
24추가: def __init__(self, size):
25추가: self.remaining = size
26추가:
27추가: def read(self, size=-1):
28추가: if size < 0 or size > CHUNK:
29추가: raise ValueError("표본 읽기는 64 KiB 이하로 제한함")
30추가: count = min(size, self.remaining)
31추가: self.remaining -= count
32추가: return bytes(count)
33추가:
34추가:
35추가: def write_zip(path, size, compressed, level=6):
36추가: info = zipfile.ZipInfo(NAME, (1980, 1, 1, 0, 0, 0))
37추가: info.compress_type = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED
38추가: info._compresslevel = level
39추가: info.create_system = 3
40추가: info.external_attr = 0o100600 << 16
41추가: info.file_size = size
42추가: with zipfile.ZipFile(path, "x", compression=info.compress_type) as archive:
43추가: with archive.open(info, "w") as output:
44추가: source = ZeroStream(size)
45추가: while chunk := source.read(CHUNK):
46추가: output.write(chunk)
47추가:
48추가:
49추가: def tar_size(size):
50추가: return 512 + ((size + 511) // 512) * 512 + 1024
51추가:
52추가:
53추가: def write_targz(path, size, compressed):
54추가: info = tarfile.TarInfo(NAME)
55추가: info.size = size
56추가: info.mode = 0o600
57추가: info.mtime = 0
58추가: with path.open("xb") as raw:
59추가: with gzip.GzipFile(
60추가: filename="", mode="wb", fileobj=raw,
61추가: compresslevel=6 if compressed else 0, mtime=0,
62추가: ) as output:
63추가: output.write(info.tobuf(format=tarfile.USTAR_FORMAT))
64추가: source = ZeroStream(size)
65추가: while chunk := source.read(CHUNK):
66추가: output.write(chunk)
67추가: output.write(bytes((-size) % 512 + 1024))
68추가:
69추가:
70추가: def write_ratio_gzip(path, size, packed_size):
71추가: compressor = zlib.compressobj(level=6, wbits=-15)
72추가: source = ZeroStream(size)
73추가: crc = 0
74추가: chunks = []
75추가: while chunk := source.read(CHUNK):
76추가: crc = zlib.crc32(chunk, crc)
77추가: chunks.append(compressor.compress(chunk))
78추가: data = b"".join(chunks) + compressor.flush()
79추가: padding = packed_size - 20 - len(data)
80추가: assert 0 <= padding <= 65535
81추가: header = bytes.fromhex("1f8b08040000000000ff") + struct.pack("<H", padding)
82추가: with path.open("xb") as output:
83추가: output.write(header + bytes(padding) + data + struct.pack("<II", crc, size))
84추가: assert path.stat().st_size == packed_size
85추가:
86추가:
87추가: def digest(path):
88추가: value = hashlib.sha256()
89추가: with path.open("rb") as source:
90추가: while chunk := source.read(CHUNK):
91추가: value.update(chunk)
92추가: return value.hexdigest()
93추가:
94추가:
95추가: def violations(artifact, limits):
96추가: failed = []
97추가: if artifact["archive_bytes"] > limits["input"]:
98추가: failed.append("input")
99추가: if artifact["decoded_bytes"] > limits["output"]:
100추가: failed.append("output")
101추가: return failed
102추가:
103추가:
104추가: def build(directory, large=False):
105추가: directory = Path(directory).resolve()
106추가: directory.relative_to(ROOT / "tests")
107추가: directory.mkdir(mode=0o700, parents=True, exist_ok=False)
108추가: cases = []
109추가: artifacts = {}
110추가:
111추가: def add(name, size, compressed, category, boundaries, level=6, packed_size=None):
112추가: path = directory / name
113추가: if name.endswith(".zip"):
114추가: write_zip(path, size, compressed, level)
115추가: expanded = size
116추가: with zipfile.ZipFile(path) as archive:
117추가: ratio_input = archive.getinfo(NAME).compress_size
118추가: archive_format = "Zip"
119추가: elif name.endswith(".tar.gz"):
120추가: write_targz(path, size, compressed)
121추가: expanded = tar_size(size)
122추가: ratio_input = path.stat().st_size
123추가: archive_format = "TarGzip"
124추가: else:
125추가: write_ratio_gzip(path, size, packed_size)
126추가: expanded = size
127추가: ratio_input = path.stat().st_size
128추가: archive_format = "Gzip"
129추가: artifact = {
130추가: "format": archive_format,
131추가: "archive_bytes": path.stat().st_size,
132추가: "payload_bytes": size,
133추가: "decoded_bytes": expanded,
134추가: "ratio_input_bytes": ratio_input,
135추가: "sha256": digest(path),
136추가: }
137추가: artifacts[name] = artifact
138추가: for suffix, output_limit, exceeded in boundaries:
139추가: limits = {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000}
140추가: assert violations(artifact, limits) == exceeded, (name, suffix, artifact)
141추가: failed = bool(exceeded)
142추가: cases.append({
143추가: "id": name + "-" + suffix,
144추가: "file": name,
145추가: "category": category,
146추가: "limits": limits,
147추가: "violated_limits": exceeded,
148추가: "expected": {
149추가: "outcome": "Failed" if failed else "Completed",
150추가: "error": "Limit" if failed else "None",
151추가: "publication": "None" if failed else "Complete",
152추가: "created_count": 0 if failed else 1,
153추가: "retained_partial_count": 0,
154추가: "output_events": 0 if failed else 1,
155추가: },
156추가: })
157추가:
158추가: for name, size in (("boundary.zip", CHUNK), ("boundary.tar.gz", CHUNK - 1536)):
159추가: add(name, size, True, "output-boundary", [
160추가: ("below", CHUNK + 1, []),
161추가: ("equal", CHUNK, []),
162추가: ("above", CHUNK - 1, ["output"]),
163추가: ])
164추가: for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)):
165추가: add("ratio-" + suffix + ".gz", 2_000_000 + delta, True, "former-ratio-boundary", [
166추가: ("default", OUTPUT_LIMIT, []),
167추가: ], packed_size=2000)
168추가: for extension in ("zip", "tar.gz"):
169추가: add("ratio-only." + extension, 16 * 1024 ** 2, True, "high-ratio-success", [
170추가: ("default", OUTPUT_LIMIT, []),
171추가: ])
172추가: if large:
173추가: for extension in ("zip", "tar.gz"):
174추가: add("large-input." + extension, GIB, False, "large-input-success", [
175추가: ("default", OUTPUT_LIMIT, []),
176추가: ])
177추가: add("output-only.zip", OUTPUT_LIMIT + 1, True, "hard-output-limit", [
178추가: ("default", OUTPUT_LIMIT, ["output"]),
179추가: ], level=1)
180추가: manifest = {
181추가: "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": None},
182추가: "large": large,
183추가: "worker_execution_verified": False,
184추가: "generator_chunk_bytes": CHUNK,
185추가: "artifacts": artifacts,
186추가: "cases": cases,
187추가: }
188추가: (directory / "expectations.json").write_text(
189추가: json.dumps(manifest, ensure_ascii=False, indent=4) + "\n", encoding="utf-8"
190추가: )
191추가: return manifest
192추가:
193추가:
194추가: def main():
195추가: parser = argparse.ArgumentParser()
196추가: parser.add_argument("--output", required=True, type=Path, help="tests 아래의 새 디렉터리")
197추가: parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과 표본도 생성함")
198추가: args = parser.parse_args()
199추가: manifest = build(args.output, args.large)
200추가: print(f"{len(manifest['cases'])} cases: {args.output / 'expectations.json'}")
201추가:
202추가:
203추가: if __name__ == "__main__":
204추가: main()
추가tests/large-archive-fixtures/verify.py+133-0
@@ -0,0 +1,133 @@
1추가: """참조 판독기와 실제 작업자로 독립된 한도 기대값을 검사함."""
2추가:
3추가: import argparse
4추가: import gzip
5추가: import json
6추가: import os
7추가: from pathlib import Path
8추가: import signal
9추가: import subprocess
10추가: import tempfile
11추가: import tarfile
12추가: import zipfile
13추가:
14추가: from generate import CHUNK, NAME, ROOT, build, digest, violations
15추가:
16추가:
17추가: def check_payload(source, size):
18추가: remaining = size
19추가: while remaining:
20추가: chunk = source.read(min(CHUNK, remaining))
21추가: assert chunk and chunk == bytes(len(chunk))
22추가: remaining -= len(chunk)
23추가:
24추가:
25추가: def check_reference(path, artifact):
26추가: size = artifact["payload_bytes"]
27추가: if artifact["format"] == "Zip":
28추가: with zipfile.ZipFile(path) as archive:
29추가: assert archive.namelist() == [NAME]
30추가: info = archive.getinfo(NAME)
31추가: assert info.file_size == size
32추가: assert info.compress_size == artifact["ratio_input_bytes"]
33추가: with archive.open(NAME) as source:
34추가: check_payload(source, size)
35추가: assert source.read(1) == b""
36추가: else:
37추가: assert path.stat().st_size == artifact["ratio_input_bytes"]
38추가: with gzip.open(path, "rb") as source:
39추가: if artifact["format"] == "TarGzip":
40추가: header = source.read(512)
41추가: info = tarfile.TarInfo.frombuf(header, "utf-8", "strict")
42추가: assert info.name == NAME and info.size == size and info.isfile()
43추가: check_payload(source, size)
44추가: if artifact["format"] == "TarGzip":
45추가: tail_size = (-size) % 512 + 1024
46추가: assert source.read(tail_size) == bytes(tail_size)
47추가: assert source.read(1) == b""
48추가:
49추가:
50추가: def verify(directory, probe, worker, large=False):
51추가: directory = directory.resolve()
52추가: directory.relative_to(ROOT / "tests")
53추가: manifest = json.loads((directory / "expectations.json").read_text(encoding="utf-8"))
54추가: assert not large or manifest["large"]
55추가: for name, artifact in manifest["artifacts"].items():
56추가: assert (directory / name).stat().st_size == artifact["archive_bytes"]
57추가: assert digest(directory / name) == artifact["sha256"]
58추가: check_reference(directory / name, artifact)
59추가: print(f"REFERENCE {name}", flush=True)
60추가: results = []
61추가: for case in manifest["cases"]:
62추가: path = directory / case["file"]
63추가: artifact = manifest["artifacts"][case["file"]]
64추가: assert violations(artifact, case["limits"]) == case["violated_limits"]
65추가: before = path.stat()
66추가: with tempfile.TemporaryDirectory(prefix="case-", dir=directory) as scratch:
67추가: destination = Path(scratch) / "output"
68추가: staging = Path(scratch) / "staging"
69추가: destination.mkdir(mode=0o700)
70추가: staging.mkdir(mode=0o700)
71추가: command = [
72추가: str(probe.resolve()), str(worker.resolve()), str(path), str(destination),
73추가: str(case["limits"]["input"]), str(case["limits"]["output"]),
74추가: str(case["limits"]["entries"]), case["expected"]["outcome"],
75추가: str(artifact["payload_bytes"]), artifact["format"],
76추가: ]
77추가: environment = os.environ.copy()
78추가: environment["TMPDIR"] = str(staging)
79추가: environment["TMP"] = str(staging)
80추가: environment["TEMP"] = str(staging)
81추가: process = subprocess.Popen(
82추가: command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,
83추가: start_new_session=(os.name == "posix"),
84추가: )
85추가: try:
86추가: stdout, stderr = process.communicate(timeout=360)
87추가: except subprocess.TimeoutExpired:
88추가: if os.name == "posix":
89추가: os.killpg(process.pid, signal.SIGKILL)
90추가: else:
91추가: process.kill()
92추가: process.communicate()
93추가: raise
94추가: assert process.returncode == 0, (case["id"], stdout, stderr)
95추가: assert not list(staging.iterdir())
96추가: if case["expected"]["outcome"] == "Completed":
97추가: with (destination / NAME).open("rb") as source:
98추가: check_payload(source, artifact["payload_bytes"])
99추가: assert source.read(1) == b""
100추가: else:
101추가: assert not list(destination.iterdir())
102추가: after = path.stat()
103추가: assert (before.st_size, before.st_mtime_ns) == (after.st_size, after.st_mtime_ns)
104추가: results.append({"case": case["id"], "status": "passed"})
105추가: print(f"PASS {case['id']}", flush=True)
106추가: for name, artifact in manifest["artifacts"].items():
107추가: assert digest(directory / name) == artifact["sha256"]
108추가: return results
109추가:
110추가:
111추가: def main():
112추가: parser = argparse.ArgumentParser()
113추가: parser.add_argument("--directory", type=Path, help="기존 표본 또는 새 표본 경로")
114추가: parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과도 검사함")
115추가: target = Path(os.environ.get("CARGO_TARGET_DIR", ROOT / "tests/ci/target")) / "debug"
116추가: suffix = ".exe" if os.name == "nt" else ""
117추가: parser.add_argument("--probe", type=Path, default=target / ("zipelo-large-archive-probe" + suffix))
118추가: parser.add_argument("--worker", type=Path, default=target / ("zipelo-archive-worker" + suffix))
119추가: args = parser.parse_args()
120추가: assert args.probe.is_file() and args.worker.is_file(), "local 빌드를 먼저 실행해야 함"
121추가: if args.directory:
122추가: if not args.directory.exists():
123추가: build(args.directory, args.large)
124추가: verify(args.directory, args.probe, args.worker, args.large)
125추가: else:
126추가: with tempfile.TemporaryDirectory(prefix="fixture-", dir=ROOT / "tests/large-archive-fixtures") as scratch:
127추가: directory = Path(scratch) / "corpus"
128추가: build(directory, args.large)
129추가: verify(directory, args.probe, args.worker, args.large)
130추가:
131추가:
132추가: if __name__ == "__main__":
133추가: main()
수정tests/rust-app-real-worker/formats.rs+45-0
@@ -127,4 +127,49 @@ mod adapter {
127127 }
128128 }
129129 }
130추가: #[test]
131추가: fn disk_full_terminal_roundtrip_displays_space_guidance_and_preserves_cleanup() {
132추가: for (error, expected, guidance) in [
133추가: (
134추가: wire::ErrorCode::DiskFull,
135추가: ui::ErrorCode::DiskFull,
136추가: "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
137추가: ),
138추가: (
139추가: wire::ErrorCode::Io,
140추가: ui::ErrorCode::Io,
141추가: "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요",
142추가: ),
143추가: ] {
144추가: let message = wire::Message::Terminal(wire::Terminal {
145추가: outcome: wire::Outcome::Failed,
146추가: error,
147추가: publication: wire::Publication::Partial,
148추가: created_count: 2,
149추가: retained_partial_count: 0,
150추가: durability: wire::Durability::Synced,
151추가: cleanup: wire::Cleanup::Complete,
152추가: detail: "internal path must not appear".into(),
153추가: });
154추가: let mut frame = Vec::new();
155추가: codec::Writer::new(&mut frame, 99).send(&message).unwrap();
156추가: let (_, _, decoded) = codec::Reader::new(frame.as_slice())
157추가: .read()
158추가: .unwrap()
159추가: .unwrap();
160추가: let ui::Event::Terminal(terminal) = event_to_ui(decoded, None).unwrap() else {
161추가: panic!("종료 응답이 아님");
162추가: };
163추가: assert_eq!(terminal.error, Some(expected));
164추가: assert_eq!(terminal.outcome, ui::Outcome::Failed);
165추가: assert_eq!(terminal.publication, ui::Publication::Partial);
166추가: assert_eq!(terminal.created_count, 2);
167추가: assert_eq!(terminal.retained_partial_count, 0);
168추가: assert_eq!(terminal.cleanup, ui::Cleanup::Complete);
169추가: let lines = ui::terminal_lines(&terminal);
170추가: assert!(lines.iter().any(|line| line == guidance));
171추가: assert!(lines.iter().any(|line| line.contains("일부 파일 게시됨")));
172추가: assert!(!lines.iter().any(|line| line.contains("internal path")));
173추가: }
174추가: }
130175}
추가tests/rust-archive-worker/hardening.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/hardening_cases.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/io_fault.c

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-archive-worker/main.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/space_errors.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/streaming_bounds.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-large-archive-fixtures/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-large-archive-fixtures/Cargo.toml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-large-archive-fixtures/probe.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/.gitignore

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/Cargo.toml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/README.md

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/corpus.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/generate.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-zip64-compat/worker.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기