대용량 해제 스트리밍과 작업자 정리를 보강함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
65ada9b151789cf19e2fb6baa314f54872ff7bb5- 부모
- 93039f3
변경된 파일 16개
+1,964-83| @@ -1,26 +1,36 @@ | ||
| 1 | 1 | # Rust archive worker |
| 2 | 2 | |
| 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 생성을 지원합니다. | |
| 4 | 4 | |
| 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의 별도 메모리 상한을 유지합니다. | |
| 7 | 7 | - 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다. |
| 8 | 8 | - GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다. |
| 9 | 삭제: - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 메모리 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. | |
| 9 | 추가: - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. | |
| 10 | 10 | - 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다. |
| 11 | 11 | - 파일 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를 유지하고 입력/출력 기본 한도를 변경하는 안에 frontend/backend가 공동 합의했습니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다. | |
| 17 | 추가: | |
| 18 | 추가: - ZIP은 각 항목의 압축 payload 바이트에서 암호 framing을 뺀 값을 분모로 1000:1을 적용합니다. 선언 크기를 먼저 검사하고 실제 해제 크기, CRC와 AES 인증을 다시 확인합니다. GZ는 연결된 각 멤버의 실제 소비 바이트(헤더와 trailer 포함)와 해제 바이트로 비율을 검사하므로 뒤에 붙인 멤버가 앞의 폭탄 비율을 희석하지 않습니다. 연결 멤버 전체 해제량도 총량 한도에 포함하며 TAR.GZ의 헤더와 padding도 계산합니다. u64 누계/offset은 checked 연산, 비율 비교는 u128을 사용합니다. | |
| 19 | 추가: - 입력과 검증된 해제 내용은 임시 파일에 저장합니다. 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 외의 시스템 메모리를 사용합니다. | |
| 20 | 추가: - 64 MiB는 ZIP/TAR/GZ/TAR.GZ 해제 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 7z와 생성은 이 RSS 목표에 포함하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다. | |
| 21 | 추가: - 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만으로 취소하지 않습니다. | |
| 22 | 추가: - 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와 게시 중 정지를 주입하고 앱 강제 종료 후 작업자 종료/회수와 부분 출력 제거를 확인합니다. 이 시험을 위해 실제 공유 디스크를 채우거나 제품용 환경 변수 우회를 추가하지 않습니다. | |
| 13 | 23 | |
| 14 | 24 | ## 7z 해제 |
| 15 | 25 | |
| 16 | 26 | 비암호화 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)입니다. |
| 17 | 27 | |
| 18 | 28 | - 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다. |
| 19 | 삭제: - 입력/출력/항목/이름의 기존 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다. | |
| 29 | 추가: - 입력 64 MiB/출력 128 MiB와 기존 항목/이름 한도를 별도로 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다. | |
| 20 | 30 | - 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다. |
| 21 | 31 | - solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다. |
| 22 | 32 | - 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다. |
| 23 | 삭제: - 히나타 님과 합의한 확장은 Format::SevenZip=4뿐입니다. 기존 값 0~3과 필드, 메시지 tag, 프레임 version은 유지합니다. 구버전 앱은 값 4를 거부하므로 앱 Format과 양방향 변환도 갱신해야 합니다. 이 백엔드 변경은 frontend 코드를 수정하지 않습니다. | |
| 33 | 추가: - 형식 확장은 히나타 님과 합의한 Format::SevenZip=4입니다. 기존 값 0~3과 필드, 메시지 tag, 프레임 version은 유지합니다. 구버전 앱은 값 4를 거부하므로 앱 Format과 양방향 변환도 갱신해야 합니다. 이 백엔드 변경은 frontend 코드를 수정하지 않습니다. | |
| 24 | 34 | |
| 25 | 35 | ## 암호 ZIP |
| 26 | 36 | |
| @@ -29,7 +39,7 @@ | ||
| 29 | 39 | - [ZipCrypto](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)는 기존 파일 해제만 지원합니다. 보안성이 약하며 암호학적 인증이 없습니다. 12바이트 헤더 검사 후 압축 스트림, 크기와 CRC를 확인합니다. 새 암호 ZIP은 AES-256만 생성합니다. |
| 30 | 40 | - 목록은 암호 없이 표시합니다. 해제 시 한 번 입력한 암호를 ZIP 전체에 적용하며 WrongPassword일 때 새 challenge_id로 최대 3회 요청합니다. 항목마다 다른 암호인 ZIP은 지원하지 않습니다. 헤더 확인값이 우연히 일치한 잘못된 암호는 Integrity로 끝날 수 있습니다. 인증 실패 후에는 다시 요청하거나 쓰지 않습니다. |
| 31 | 41 | - 생성은 PasswordPurpose::Encrypt로 한 번 요청하며 빈 암호는 거부합니다. 암호는 최대 1024 UTF-8 바이트입니다. 대기 중 Cancel도 처리하고, 답변 없이 입력 EOF가 오면 Protocol로 종료합니다. 기존 300초 작업 제한에 암호 입력 대기 시간도 포함됩니다. |
| 32 | 삭제: - salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 임시 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리 복사본과 전체 평문 메모리의 완전 소거를 보장하지 않습니다. | |
| 42 | 추가: - salt는 Linux /dev/urandom 또는 Windows BCryptGenRandom에서 얻으며 실패 시 생성을 중단합니다. 암호, 파생 키와 메모리 복호화 버퍼는 zeroize로 정리하고 AES 키 일정의 zeroize 기능을 켭니다. HMAC 내부 상태, OS 메모리/페이지 캐시 복사본과 임시 저장소의 평문에 대한 완전 소거를 보장하지 않습니다. 임시 평문 파일은 작업 종료 시 닫아 제거하며 보안 삭제를 뜻하지 않습니다. | |
| 33 | 43 | - Python hashlib/hmac과 OpenSSL로 만든 AES 표본 4개, Info-ZIP으로 만든 ZipCrypto 표본 2개를 tests/ 아래에 보관합니다. 생성한 AES ZIP도 Linux에서 독립 Python/OpenSSL 검증기로 확인합니다. OpenSSL/Info-ZIP은 시험 도구이며 제품 의존성이 아닙니다. |
| 34 | 44 | |
| 35 | 45 | ## 공유 codec |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 삭제: "status": "frontend-conditions-addressed-codec-not-implemented", | |
| 2 | 추가: "status": "implemented-streaming-runtime", | |
| 3 | 3 | "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.", | |
| 5 | 5 | "frame": { |
| 6 | 6 | "magic": "ZAW1", |
| 7 | 7 | "header_bytes": 32, |
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | "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." |
| 32 | 32 | }, |
| 33 | 33 | "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.", | |
| 35 | 35 | "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.", |
| 36 | 36 | "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.", |
| 37 | 37 | "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.", |
| @@ -73,17 +73,9 @@ | ||
| 73 | 73 | "CRC/size/stream-end validation precedes committed output events; preserve commit/durability/cleanup distinctions." |
| 74 | 74 | ], |
| 75 | 75 | "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." | |
| 79 | 78 | ], |
| 80 | 삭제: "performed": { | |
| 81 | 삭제: "implementation": false, | |
| 82 | 삭제: "cargo_build": false, | |
| 83 | 삭제: "tests": false, | |
| 84 | 삭제: "worker_runs": false, | |
| 85 | 삭제: "remote_branch_or_pr": false | |
| 86 | 삭제: }, | |
| 87 | 79 | "crypto": { |
| 88 | 80 | "rustcrypto_allowed": true, |
| 89 | 81 | "approval_message_id": "2966b0ad-a3e0-49b8-aef8-fb51c4e1c5a5", |
| @@ -93,7 +85,8 @@ | ||
| 93 | 85 | "revision": 2, |
| 94 | 86 | "coordination": { |
| 95 | 87 | "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" | |
| 97 | 90 | }, |
| 98 | 91 | "list_identity": { |
| 99 | 92 | "ListId": { |
| @@ -148,5 +141,21 @@ | ||
| 148 | 141 | "agreement_message_id": "5a36fd89-af36-42be-9f79-bca39415e84d", |
| 149 | 142 | "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.", |
| 150 | 143 | "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId." |
| 151 | 삭제: } | |
| 144 | 추가: }, | |
| 145 | 추가: "streaming_limits": { | |
| 146 | 추가: "agreement": "Frontend/backend revision 2 agreement on 2026-11-11; field order, tags and frame encoding unchanged.", | |
| 147 | 추가: "default_input_bytes": 18446744073709551615, | |
| 148 | 추가: "default_output_bytes": 17179869184, | |
| 149 | 추가: "default_entries": 10000, | |
| 150 | 추가: "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.", | |
| 151 | 추가: "zip_ratio": "For each ZIP entry, declared output and actual decoded bytes are bounded by 1000 times compressed payload bytes, excluding ZipCrypto/AES framing. Zero packed bytes permit only zero output. ZIP metadata is checked before allocation/decode; size and CRC/HMAC must also match.", | |
| 152 | 추가: "gzip_ratio": "For each complete GZip member, verified decoded bytes are at most 1000 times actual consumed member bytes, including its header/trailer. Concatenating a low-ratio member cannot dilute an excessive member. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota. During decoding the complete source length is an additional conservative ratio ceiling.", | |
| 153 | 추가: "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.", | |
| 154 | 추가: "arithmetic": "Checked u64 offsets/totals; ratio comparison uses u128(output) <= u128(input) * 1000 without u64 multiplication overflow.", | |
| 155 | 추가: "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.", | |
| 156 | 추가: "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 Io and closes/removes unpublished data.", | |
| 157 | 추가: "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.", | |
| 158 | 추가: "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." | |
| 159 | 추가: }, | |
| 160 | 추가: "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim." | |
| 152 | 161 | } |
| @@ -205,7 +205,7 @@ fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> | ||
| 205 | 205 | } |
| 206 | 206 | Ok(result) |
| 207 | 207 | } |
| 208 | 삭제: fn tar_string(b: &[u8]) -> Result<String> { | |
| 208 | 추가: pub(crate) fn tar_string(b: &[u8]) -> Result<String> { | |
| 209 | 209 | let n = b.iter().position(|v| *v == 0).unwrap_or(b.len()); |
| 210 | 210 | if b[n..].iter().any(|v| *v != 0) { |
| 211 | 211 | return Err(ErrorCode::Integrity); |
| @@ -214,7 +214,7 @@ fn tar_string(b: &[u8]) -> Result<String> { | ||
| 214 | 214 | .map(str::to_owned) |
| 215 | 215 | .map_err(|_| ErrorCode::UnsupportedFeature) |
| 216 | 216 | } |
| 217 | 삭제: fn octal(b: &[u8]) -> Result<u64> { | |
| 217 | 추가: pub(crate) fn octal(b: &[u8]) -> Result<u64> { | |
| 218 | 218 | if b.first().is_some_and(|x| x & 128 != 0) { |
| 219 | 219 | return Err(ErrorCode::UnsupportedFeature); |
| 220 | 220 | } |
| @@ -315,11 +315,11 @@ fn tar( | ||
| 315 | 315 | Ok(members) |
| 316 | 316 | } |
| 317 | 317 | #[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, | |
| 321 | 321 | } |
| 322 | 삭제: fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> { | |
| 322 | 추가: pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> { | |
| 323 | 323 | let mut at = 0; |
| 324 | 324 | let mut found = None; |
| 325 | 325 | while at < extra.len() { |
| @@ -576,7 +576,11 @@ pub fn parse_with_password( | ||
| 576 | 576 | password: Option<&[u8]>, |
| 577 | 577 | check: &mut impl FnMut() -> Result<()>, |
| 578 | 578 | ) -> 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 { | |
| 580 | 584 | return Err(ErrorCode::Limit); |
| 581 | 585 | } |
| 582 | 586 | if input.starts_with(b"7z\xbc\xaf\x27\x1c") { |
| @@ -668,6 +672,10 @@ pub fn create_zip_with_password( | ||
| 668 | 672 | password: Option<&[u8]>, |
| 669 | 673 | check: &mut impl FnMut() -> Result<()>, |
| 670 | 674 | ) -> Result<Vec<u8>> { |
| 675 | 추가: if !limits.valid() { | |
| 676 | 추가: return Err(ErrorCode::Limit); | |
| 677 | 추가: } | |
| 678 | 추가: let limits = limits.legacy(); | |
| 671 | 679 | if members.len() > limits.entries as usize || members.len() >= 65535 { |
| 672 | 680 | return Err(ErrorCode::Limit); |
| 673 | 681 | } |
| @@ -87,7 +87,7 @@ pub(crate) fn aes_encrypt( | ||
| 87 | 87 | result.extend(&mac[..10]); |
| 88 | 88 | Ok(result) |
| 89 | 89 | } |
| 90 | 삭제: fn random(bytes: &mut [u8]) -> Result<()> { | |
| 90 | 추가: pub(crate) fn random(bytes: &mut [u8]) -> Result<()> { | |
| 91 | 91 | #[cfg(target_os = "linux")] |
| 92 | 92 | { |
| 93 | 93 | use std::io::Read; |
| @@ -144,16 +144,8 @@ pub(crate) fn zipcrypto_decrypt( | ||
| 144 | 144 | return Err(ErrorCode::Integrity); |
| 145 | 145 | } |
| 146 | 146 | 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 | 삭제: } | |
| 155 | 147 | for &byte in password { |
| 156 | 삭제: update(&mut key, byte); | |
| 148 | 추가: zip_update(&mut key, byte); | |
| 157 | 149 | } |
| 158 | 150 | let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12)); |
| 159 | 151 | for (index, &byte) in packed.iter().enumerate() { |
| @@ -162,7 +154,7 @@ pub(crate) fn zipcrypto_decrypt( | ||
| 162 | 154 | } |
| 163 | 155 | let temp = key[2] | 2; |
| 164 | 156 | let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8); |
| 165 | 삭제: update(&mut key, plain); | |
| 157 | 추가: zip_update(&mut key, plain); | |
| 166 | 158 | if index == 11 && plain != verifier { |
| 167 | 159 | return Err(ErrorCode::WrongPassword); |
| 168 | 160 | } |
| @@ -172,3 +164,134 @@ pub(crate) fn zipcrypto_decrypt( | ||
| 172 | 164 | } |
| 173 | 165 | Ok(out) |
| 174 | 166 | } |
| 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 | 추가: } |
| @@ -439,6 +439,22 @@ pub fn publish( | ||
| 439 | 439 | name: &str, |
| 440 | 440 | data: &[u8], |
| 441 | 441 | check: &mut impl FnMut(bool) -> Result<()>, |
| 442 | 추가: ) -> Published { | |
| 443 | 추가: publish_reader( | |
| 444 | 추가: root, | |
| 445 | 추가: name, | |
| 446 | 추가: &mut std::io::Cursor::new(data), | |
| 447 | 추가: data.len() as u64, | |
| 448 | 추가: check, | |
| 449 | 추가: ) | |
| 450 | 추가: } | |
| 451 | 추가: | |
| 452 | 추가: pub fn publish_reader( | |
| 453 | 추가: root: &Dir, | |
| 454 | 추가: name: &str, | |
| 455 | 추가: data: &mut impl Read, | |
| 456 | 추가: length: u64, | |
| 457 | 추가: check: &mut impl FnMut(bool) -> Result<()>, | |
| 442 | 458 | ) -> Published { |
| 443 | 459 | let mut result = Published { |
| 444 | 460 | created: false, |
| @@ -457,11 +473,25 @@ pub fn publish( | ||
| 457 | 473 | std::process::id(), |
| 458 | 474 | TEMP.fetch_add(1, Ordering::Relaxed) |
| 459 | 475 | ); |
| 460 | 삭제: let mut file = dir.create(&temp).map_err(|_| ErrorCode::Conflict)?; | |
| 476 | 추가: let mut file = dir.create(&temp).map_err(|e| { | |
| 477 | 추가: if e.kind() == std::io::ErrorKind::AlreadyExists { | |
| 478 | 추가: ErrorCode::Conflict | |
| 479 | 추가: } else { | |
| 480 | 추가: ErrorCode::Io | |
| 481 | 추가: } | |
| 482 | 추가: })?; | |
| 461 | 483 | let written = (|| { |
| 462 | 삭제: for chunk in data.chunks(65536) { | |
| 484 | 추가: let mut buffer = zeroize::Zeroizing::new([0; 65536]); | |
| 485 | 추가: let mut remaining = length; | |
| 486 | 추가: while remaining != 0 { | |
| 463 | 487 | check(false)?; |
| 464 | 삭제: file.write_all(chunk).map_err(|_| ErrorCode::Io)?; | |
| 488 | 추가: let count = remaining.min(buffer.len() as u64) as usize; | |
| 489 | 추가: let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?; | |
| 490 | 추가: if n == 0 { | |
| 491 | 추가: return Err(ErrorCode::Io); | |
| 492 | 추가: } | |
| 493 | 추가: file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?; | |
| 494 | 추가: remaining -= n as u64; | |
| 465 | 495 | } |
| 466 | 496 | file.sync_all().map_err(|_| ErrorCode::Io) |
| 467 | 497 | })(); |
| @@ -2,7 +2,10 @@ pub mod archive; | ||
| 2 | 2 | mod crypto; |
| 3 | 3 | pub mod filesystem; |
| 4 | 4 | mod lzma; |
| 5 | 추가: mod parent; | |
| 5 | 6 | pub mod protocol; |
| 6 | 7 | pub mod runtime; |
| 7 | 8 | mod seven_zip; |
| 9 | 추가: mod spool; | |
| 10 | 추가: mod streaming; | |
| 8 | 11 | pub mod wire; |
| @@ -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; |
| @@ -57,13 +57,21 @@ pub struct Limits { | ||
| 57 | 57 | impl Default for Limits { |
| 58 | 58 | fn default() -> Self { |
| 59 | 59 | Self { |
| 60 | 삭제: input: 64 * 1024 * 1024, | |
| 61 | 삭제: output: 128 * 1024 * 1024, | |
| 60 | 추가: input: u64::MAX, | |
| 61 | 추가: output: 16 * 1024 * 1024 * 1024, | |
| 62 | 62 | entries: 10_000, |
| 63 | 63 | } |
| 64 | 64 | } |
| 65 | 65 | } |
| 66 | 66 | impl 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 | 추가: | |
| 67 | 75 | pub fn valid(self) -> bool { |
| 68 | 76 | let hard = Self::default(); |
| 69 | 77 | self.input > 0 |
| @@ -6,7 +6,7 @@ use crate::{ | ||
| 6 | 6 | }; |
| 7 | 7 | use std::{ |
| 8 | 8 | collections::BTreeSet, |
| 9 | 삭제: io::{Read, Write}, | |
| 9 | 추가: io::{Read, Seek, SeekFrom, Write}, | |
| 10 | 10 | sync::{Arc, Condvar, Mutex}, |
| 11 | 11 | time::{Duration, Instant}, |
| 12 | 12 | }; |
| @@ -27,6 +27,7 @@ struct Job<W> { | ||
| 27 | 27 | next_challenge: u64, |
| 28 | 28 | started: Instant, |
| 29 | 29 | terminal: Terminal, |
| 30 | 추가: parent: crate::parent::Parent, | |
| 30 | 31 | } |
| 31 | 32 | impl<W: Write> Job<W> { |
| 32 | 33 | fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> { |
| @@ -45,6 +46,7 @@ impl<W: Write> Job<W> { | ||
| 45 | 46 | }) |
| 46 | 47 | .map_err(|_| ErrorCode::Io)?; |
| 47 | 48 | loop { |
| 49 | 추가: self.parent.check()?; | |
| 48 | 50 | if let Some(error) = state.fault { |
| 49 | 51 | return Err(error); |
| 50 | 52 | } |
| @@ -76,6 +78,7 @@ impl<W: Write> Job<W> { | ||
| 76 | 78 | }) |
| 77 | 79 | } |
| 78 | 80 | fn check(&mut self) -> Result<()> { |
| 81 | 추가: self.parent.check()?; | |
| 79 | 82 | if self.started.elapsed() > Duration::from_secs(300) { |
| 80 | 83 | return Err(ErrorCode::Limit); |
| 81 | 84 | } |
| @@ -118,15 +121,33 @@ impl<W: Write> Job<W> { | ||
| 118 | 121 | data: &[u8], |
| 119 | 122 | id: Option<u32>, |
| 120 | 123 | last: bool, |
| 124 | 추가: ) -> Result<()> { | |
| 125 | 추가: self.output_reader( | |
| 126 | 추가: root, | |
| 127 | 추가: name, | |
| 128 | 추가: &mut std::io::Cursor::new(data), | |
| 129 | 추가: data.len() as u64, | |
| 130 | 추가: id, | |
| 131 | 추가: last, | |
| 132 | 추가: ) | |
| 133 | 추가: } | |
| 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, | |
| 121 | 142 | ) -> Result<()> { |
| 122 | 143 | self.check()?; |
| 123 | 144 | self.progress( |
| 124 | 145 | Stage::Write, |
| 125 | 146 | 0, |
| 126 | 삭제: Some(data.len() as u64), | |
| 147 | 추가: Some(length), | |
| 127 | 148 | self.terminal.created_count as u32, |
| 128 | 149 | )?; |
| 129 | 삭제: let p = filesystem::publish(root, name, data, &mut |commit| { | |
| 150 | 추가: let p = filesystem::publish_reader(root, name, data, length, &mut |commit| { | |
| 130 | 151 | if commit && last { |
| 131 | 152 | self.cutoff() |
| 132 | 153 | } else { |
| @@ -194,8 +215,8 @@ impl<W: Write> Job<W> { | ||
| 194 | 215 | let extract = matches!(start.action, Action::Extract { .. }); |
| 195 | 216 | let path = source.to_path()?; |
| 196 | 217 | 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())?; | |
| 199 | 220 | if let Action::Extract { |
| 200 | 221 | list_id: Some(expected), |
| 201 | 222 | .. |
| @@ -203,25 +224,26 @@ impl<W: Write> Job<W> { | ||
| 203 | 224 | { |
| 204 | 225 | if expected.catalog_version != 1 |
| 205 | 226 | || expected.source_object != snapshot.object |
| 206 | 삭제: || expected.archive_bytes != snapshot.bytes.len() as u64 | |
| 227 | 추가: || expected.archive_bytes != snapshot.len | |
| 207 | 228 | || expected.archive_sha256 != snapshot.hash |
| 208 | 229 | { |
| 209 | 230 | return Err(ErrorCode::SourceChanged); |
| 210 | 231 | } |
| 211 | 232 | } |
| 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(), | |
| 217 | 241 | )?; |
| 218 | 삭제: let mut catalog = | |
| 219 | 삭제: archive::parse(&snapshot.bytes, start.limits, false, &mut || self.check())?; | |
| 220 | 242 | let list_id = ListId { |
| 221 | 243 | catalog_version: 1, |
| 222 | 244 | format: catalog.format, |
| 223 | 245 | source_object: snapshot.object, |
| 224 | 삭제: archive_bytes: snapshot.bytes.len() as u64, | |
| 246 | 추가: archive_bytes: snapshot.len, | |
| 225 | 247 | archive_sha256: snapshot.hash, |
| 226 | 248 | }; |
| 227 | 249 | if !extract { |
| @@ -270,25 +292,28 @@ impl<W: Write> Job<W> { | ||
| 270 | 292 | return Err(ErrorCode::UnsafePath); |
| 271 | 293 | } |
| 272 | 294 | 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; | |
| 295 | 추가: if matches!(catalog.format, Format::Zip | Format::SevenZip) { | |
| 296 | 추가: for attempt in 1..=3 { | |
| 297 | 추가: let secret = if encrypted { | |
| 298 | 추가: Some(self.password(PasswordPurpose::Decrypt, attempt)?) | |
| 299 | 추가: } else { | |
| 300 | 추가: None | |
| 301 | 추가: }; | |
| 302 | 추가: match crate::streaming::Catalog::open( | |
| 303 | 추가: &mut snapshot.file, | |
| 304 | 추가: snapshot.len, | |
| 305 | 추가: start.limits, | |
| 306 | 추가: true, | |
| 307 | 추가: secret.as_ref().map(|s| s.0.as_slice()), | |
| 308 | 추가: &mut || self.check(), | |
| 309 | 추가: ) { | |
| 310 | 추가: Ok(decoded) => { | |
| 311 | 추가: catalog = decoded; | |
| 312 | 추가: break; | |
| 313 | 추가: } | |
| 314 | 추가: Err(ErrorCode::WrongPassword) if attempt < 3 => continue, | |
| 315 | 추가: Err(error) => return Err(error), | |
| 289 | 316 | } |
| 290 | 삭제: Err(ErrorCode::WrongPassword) if attempt < 3 => continue, | |
| 291 | 삭제: Err(error) => return Err(error), | |
| 292 | 317 | } |
| 293 | 318 | } |
| 294 | 319 | if catalog.format == Format::Gzip { |
| @@ -303,6 +328,8 @@ impl<W: Write> Job<W> { | ||
| 303 | 328 | return Err(ErrorCode::InvalidRequest); |
| 304 | 329 | } |
| 305 | 330 | let root = Dir::root(&destination.to_path()?)?; |
| 331 | 추가: let offsets = catalog.offsets; | |
| 332 | 추가: let mut data = catalog.data; | |
| 306 | 333 | let members = catalog |
| 307 | 334 | .members |
| 308 | 335 | .into_iter() |
| @@ -345,10 +372,13 @@ impl<W: Write> Job<W> { | ||
| 345 | 372 | } |
| 346 | 373 | } |
| 347 | 374 | for (index, m) in files.iter().enumerate() { |
| 348 | 삭제: self.output( | |
| 375 | 추가: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) | |
| 376 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 377 | 추가: self.output_reader( | |
| 349 | 378 | &root, |
| 350 | 379 | &m.entry.name, |
| 351 | 삭제: &m.data, | |
| 380 | 추가: &mut (&mut data).take(m.entry.size), | |
| 381 | 추가: m.entry.size, | |
| 352 | 382 | Some(m.entry.entry_id), |
| 353 | 383 | index + 1 == files.len(), |
| 354 | 384 | )?; |
| @@ -362,7 +392,8 @@ impl<W: Write> Job<W> { | ||
| 362 | 392 | method, |
| 363 | 393 | encryption, |
| 364 | 394 | } => { |
| 365 | 삭제: if sources.len() > start.limits.entries as usize { | |
| 395 | 추가: let limits = start.limits.legacy(); | |
| 396 | 추가: if sources.len() > limits.entries as usize { | |
| 366 | 397 | return Err(ErrorCode::Limit); |
| 367 | 398 | } |
| 368 | 399 | let mut members = Vec::new(); |
| @@ -372,7 +403,7 @@ impl<W: Write> Job<W> { | ||
| 372 | 403 | let name = archive::valid_name(&source.archive_name, false)?; |
| 373 | 404 | let snapshot = filesystem::snapshot( |
| 374 | 405 | &source.path.to_path()?, |
| 375 | 삭제: start.limits.input - consumed, | |
| 406 | 추가: limits.input - consumed, | |
| 376 | 407 | &mut || self.check(), |
| 377 | 408 | )?; |
| 378 | 409 | consumed += snapshot.bytes.len() as u64; |
| @@ -400,7 +431,7 @@ impl<W: Write> Job<W> { | ||
| 400 | 431 | let bytes = archive::create_zip_with_password( |
| 401 | 432 | &members, |
| 402 | 433 | method, |
| 403 | 삭제: start.limits, | |
| 434 | 추가: limits, | |
| 404 | 435 | secret.as_ref().map(|s| s.0.as_slice()), |
| 405 | 436 | &mut || self.check(), |
| 406 | 437 | )?; |
| @@ -424,6 +455,8 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 424 | 455 | input: R, |
| 425 | 456 | output: W, |
| 426 | 457 | ) -> std::io::Result<()> { |
| 458 | 추가: let parent = crate::parent::Parent::capture() | |
| 459 | 추가: .map_err(|_| std::io::Error::other("worker parent unavailable"))?; | |
| 427 | 460 | let mut reader = Reader::new(input); |
| 428 | 461 | let (job, _, message) = reader |
| 429 | 462 | .read()? |
| @@ -517,6 +550,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 517 | 550 | state: Arc::clone(&state), |
| 518 | 551 | wake, |
| 519 | 552 | next_challenge: 0, |
| 553 | 추가: parent, | |
| 520 | 554 | started: Instant::now(), |
| 521 | 555 | terminal: Terminal { |
| 522 | 556 | outcome: Outcome::Completed, |
| @@ -0,0 +1,145 @@ | ||
| 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 | 추가: if let Ok(file) = OpenOptions::new() | |
| 17 | 추가: .read(true) | |
| 18 | 추가: .write(true) | |
| 19 | 추가: .custom_flags(0x410000 | 0x80) | |
| 20 | 추가: .mode(0o600) | |
| 21 | 추가: .open(std::env::temp_dir()) | |
| 22 | 추가: { | |
| 23 | 추가: return Ok(file); | |
| 24 | 추가: } | |
| 25 | 추가: let mut random = [0; 16]; | |
| 26 | 추가: crate::crypto::random(&mut random)?; | |
| 27 | 추가: let name = random | |
| 28 | 추가: .iter() | |
| 29 | 추가: .map(|b| format!("{b:02x}")) | |
| 30 | 추가: .collect::<String>(); | |
| 31 | 추가: let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp")); | |
| 32 | 추가: let file = OpenOptions::new() | |
| 33 | 추가: .read(true) | |
| 34 | 추가: .write(true) | |
| 35 | 추가: .create_new(true) | |
| 36 | 추가: .mode(0o600) | |
| 37 | 추가: .custom_flags(0x20000) | |
| 38 | 추가: .open(&path) | |
| 39 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 40 | 추가: std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?; | |
| 41 | 추가: use std::os::unix::fs::MetadataExt; | |
| 42 | 추가: if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 { | |
| 43 | 추가: return Err(ErrorCode::Io); | |
| 44 | 추가: } | |
| 45 | 추가: Ok(file) | |
| 46 | 추가: } | |
| 47 | 추가: #[cfg(windows)] | |
| 48 | 추가: { | |
| 49 | 추가: use std::os::windows::fs::OpenOptionsExt; | |
| 50 | 추가: let mut random = [0; 16]; | |
| 51 | 추가: crate::crypto::random(&mut random)?; | |
| 52 | 추가: let name = random | |
| 53 | 추가: .iter() | |
| 54 | 추가: .map(|b| format!("{b:02x}")) | |
| 55 | 추가: .collect::<String>(); | |
| 56 | 추가: OpenOptions::new() | |
| 57 | 추가: .read(true) | |
| 58 | 추가: .write(true) | |
| 59 | 추가: .create_new(true) | |
| 60 | 추가: .share_mode(0) | |
| 61 | 추가: .access_mode(0xc0010000) | |
| 62 | 추가: .custom_flags(0x04000000 | 0x00200000) | |
| 63 | 추가: .attributes(0x100) | |
| 64 | 추가: .open(std::env::temp_dir().join(format!("zipelo-{name}.tmp"))) | |
| 65 | 추가: .map_err(|_| ErrorCode::Io) | |
| 66 | 추가: } | |
| 67 | 추가: } | |
| 68 | 추가: | |
| 69 | 추가: pub(crate) struct Snapshot { | |
| 70 | 추가: pub file: File, | |
| 71 | 추가: pub len: u64, | |
| 72 | 추가: pub object: SourceObject, | |
| 73 | 추가: pub hash: [u8; 32], | |
| 74 | 추가: } | |
| 75 | 추가: impl Snapshot { | |
| 76 | 추가: pub fn open(path: &Path, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Self> { | |
| 77 | 추가: let mut options = OpenOptions::new(); | |
| 78 | 추가: options.read(true); | |
| 79 | 추가: #[cfg(unix)] | |
| 80 | 추가: { | |
| 81 | 추가: use std::os::unix::fs::OpenOptionsExt; | |
| 82 | 추가: options.custom_flags(0x20000 | 0x800); | |
| 83 | 추가: } | |
| 84 | 추가: #[cfg(windows)] | |
| 85 | 추가: { | |
| 86 | 추가: use std::os::windows::fs::OpenOptionsExt; | |
| 87 | 추가: options.share_mode(1); | |
| 88 | 추가: } | |
| 89 | 추가: let mut source = options.open(path).map_err(|_| ErrorCode::Io)?; | |
| 90 | 추가: let before = source.metadata().map_err(|_| ErrorCode::Io)?; | |
| 91 | 추가: if !before.is_file() { | |
| 92 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 93 | 추가: } | |
| 94 | 추가: let mut prefix = [0; 6]; | |
| 95 | 추가: let prefix_len = before.len().min(prefix.len() as u64) as usize; | |
| 96 | 추가: source | |
| 97 | 추가: .read_exact(&mut prefix[..prefix_len]) | |
| 98 | 추가: .map_err(|_| ErrorCode::SourceChanged)?; | |
| 99 | 추가: let limit = if prefix == *b"7z\xbc\xaf\x27\x1c" { | |
| 100 | 추가: limit.min(64 * 1024 * 1024) | |
| 101 | 추가: } else { | |
| 102 | 추가: limit | |
| 103 | 추가: }; | |
| 104 | 추가: if before.len() > limit { | |
| 105 | 추가: return Err(ErrorCode::Limit); | |
| 106 | 추가: } | |
| 107 | 추가: source.rewind().map_err(|_| ErrorCode::Io)?; | |
| 108 | 추가: let object = filesystem::object(&source)?; | |
| 109 | 추가: let mut file = temporary()?; | |
| 110 | 추가: let mut buffer = [0; 65536]; | |
| 111 | 추가: let mut hash = Sha256::new(); | |
| 112 | 추가: let mut len = 0u64; | |
| 113 | 추가: loop { | |
| 114 | 추가: check()?; | |
| 115 | 추가: let n = source.read(&mut buffer).map_err(|_| ErrorCode::Io)?; | |
| 116 | 추가: if n == 0 { | |
| 117 | 추가: break; | |
| 118 | 추가: } | |
| 119 | 추가: len = len | |
| 120 | 추가: .checked_add(n as u64) | |
| 121 | 추가: .filter(|n| *n <= limit) | |
| 122 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 123 | 추가: file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?; | |
| 124 | 추가: hash.update(&buffer[..n]); | |
| 125 | 추가: } | |
| 126 | 추가: let after = source.metadata().map_err(|_| ErrorCode::Io)?; | |
| 127 | 추가: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 128 | 추가: if filesystem::object(&named)? != object | |
| 129 | 추가: || filesystem::object(&source)? != object | |
| 130 | 추가: || before.len() != len | |
| 131 | 추가: || after.len() != len | |
| 132 | 추가: || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file() | |
| 133 | 추가: || before.modified().ok() != after.modified().ok() | |
| 134 | 추가: { | |
| 135 | 추가: return Err(ErrorCode::SourceChanged); | |
| 136 | 추가: } | |
| 137 | 추가: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io)?; | |
| 138 | 추가: Ok(Self { | |
| 139 | 추가: file, | |
| 140 | 추가: len, | |
| 141 | 추가: object, | |
| 142 | 추가: hash: hash.finalize().into(), | |
| 143 | 추가: }) | |
| 144 | 추가: } | |
| 145 | 추가: } |
| @@ -0,0 +1,712 @@ | ||
| 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 | 추가: pub(crate) const RATIO: u64 = 1000; | |
| 17 | 추가: | |
| 18 | 추가: pub(crate) fn ratio(output: u64, input: u64) -> Result<()> { | |
| 19 | 추가: if output as u128 > input as u128 * RATIO as u128 { | |
| 20 | 추가: Err(ErrorCode::Limit) | |
| 21 | 추가: } else { | |
| 22 | 추가: Ok(()) | |
| 23 | 추가: } | |
| 24 | 추가: } | |
| 25 | 추가: fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> { | |
| 26 | 추가: file.seek(SeekFrom::Start(offset)) | |
| 27 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 28 | 추가: file.read_exact(bytes).map_err(|_| ErrorCode::Integrity) | |
| 29 | 추가: } | |
| 30 | 추가: fn bytes(file: &mut File, offset: u64, size: usize) -> Result<Vec<u8>> { | |
| 31 | 추가: let mut result = vec![0; size]; | |
| 32 | 추가: at(file, offset, &mut result)?; | |
| 33 | 추가: Ok(result) | |
| 34 | 추가: } | |
| 35 | 추가: fn u16at(b: &[u8], at: usize) -> u16 { | |
| 36 | 추가: u16::from_le_bytes(b[at..at + 2].try_into().unwrap()) | |
| 37 | 추가: } | |
| 38 | 추가: fn u32at(b: &[u8], at: usize) -> u32 { | |
| 39 | 추가: u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) | |
| 40 | 추가: } | |
| 41 | 추가: fn u64at(b: &[u8], at: usize) -> u64 { | |
| 42 | 추가: u64::from_le_bytes(b[at..at + 8].try_into().unwrap()) | |
| 43 | 추가: } | |
| 44 | 추가: fn add(a: u64, b: u64) -> Result<u64> { | |
| 45 | 추가: a.checked_add(b).ok_or(ErrorCode::Integrity) | |
| 46 | 추가: } | |
| 47 | 추가: fn io<T>(v: std::io::Result<T>) -> Result<T> { | |
| 48 | 추가: v.map_err(|_| ErrorCode::Io) | |
| 49 | 추가: } | |
| 50 | 추가: | |
| 51 | 추가: pub(crate) struct Catalog { | |
| 52 | 추가: pub format: Format, | |
| 53 | 추가: pub members: Vec<Member>, | |
| 54 | 추가: pub offsets: Vec<u64>, | |
| 55 | 추가: pub data: File, | |
| 56 | 추가: } | |
| 57 | 추가: impl Catalog { | |
| 58 | 추가: pub fn open( | |
| 59 | 추가: source: &mut File, | |
| 60 | 추가: len: u64, | |
| 61 | 추가: limits: Limits, | |
| 62 | 추가: decode: bool, | |
| 63 | 추가: password: Option<&[u8]>, | |
| 64 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 65 | 추가: ) -> Result<Self> { | |
| 66 | 추가: let mut magic = [0; 6]; | |
| 67 | 추가: let n = len.min(6) as usize; | |
| 68 | 추가: at(source, 0, &mut magic[..n])?; | |
| 69 | 추가: if magic.starts_with(b"7z\xbc\xaf\x27\x1c") { | |
| 70 | 추가: let bounded = limits.legacy(); | |
| 71 | 추가: if len > bounded.input { | |
| 72 | 추가: return Err(ErrorCode::Limit); | |
| 73 | 추가: } | |
| 74 | 추가: let input = bytes(source, 0, len as usize)?; | |
| 75 | 추가: let catalog = archive::parse_with_password(&input, bounded, decode, password, check)?; | |
| 76 | 추가: let mut data = spool::temporary()?; | |
| 77 | 추가: let mut members = catalog.members; | |
| 78 | 추가: let mut offsets = Vec::new(); | |
| 79 | 추가: for m in &mut members { | |
| 80 | 추가: offsets.push(io(data.stream_position())?); | |
| 81 | 추가: io(data.write_all(&m.data))?; | |
| 82 | 추가: m.data.clear(); | |
| 83 | 추가: m.data.shrink_to_fit(); | |
| 84 | 추가: } | |
| 85 | 추가: return Ok(Self { | |
| 86 | 추가: format: Format::SevenZip, | |
| 87 | 추가: members, | |
| 88 | 추가: offsets, | |
| 89 | 추가: data, | |
| 90 | 추가: }); | |
| 91 | 추가: } | |
| 92 | 추가: if magic.starts_with(b"PK\x03\x04") | |
| 93 | 추가: || magic.starts_with(b"PK\x05\x06") | |
| 94 | 추가: || magic.starts_with(b"PK\x06\x06") | |
| 95 | 추가: { | |
| 96 | 추가: return zip(source, len, limits, decode, password, check); | |
| 97 | 추가: } | |
| 98 | 추가: if magic.starts_with(&[31, 139]) { | |
| 99 | 추가: let mut data = spool::temporary()?; | |
| 100 | 추가: io(source.rewind())?; | |
| 101 | 추가: let expanded = inflate( | |
| 102 | 추가: source, | |
| 103 | 추가: len, | |
| 104 | 추가: true, | |
| 105 | 추가: limits.output, | |
| 106 | 추가: Some(len), | |
| 107 | 추가: &mut data, | |
| 108 | 추가: check, | |
| 109 | 추가: )? | |
| 110 | 추가: .0; | |
| 111 | 추가: let mut header = [0; 512]; | |
| 112 | 추가: if expanded >= 512 { | |
| 113 | 추가: at(&mut data, 0, &mut header)?; | |
| 114 | 추가: if matches!(&header[257..263], b"ustar\0" | b"ustar ") { | |
| 115 | 추가: return tar(data, expanded, limits, Format::TarGzip, check); | |
| 116 | 추가: } | |
| 117 | 추가: } | |
| 118 | 추가: return Ok(Self { | |
| 119 | 추가: format: Format::Gzip, | |
| 120 | 추가: members: vec![Member { | |
| 121 | 추가: entry: Entry { | |
| 122 | 추가: entry_id: 0, | |
| 123 | 추가: name: "GZip stream".to_owned(), | |
| 124 | 추가: kind: EntryKind::File, | |
| 125 | 추가: size: expanded, | |
| 126 | 추가: compressed_size: len, | |
| 127 | 추가: encrypted: false, | |
| 128 | 추가: }, | |
| 129 | 추가: data: Vec::new(), | |
| 130 | 추가: }], | |
| 131 | 추가: offsets: vec![0], | |
| 132 | 추가: data, | |
| 133 | 추가: }); | |
| 134 | 추가: } | |
| 135 | 추가: if len >= 512 { | |
| 136 | 추가: return tar(io(source.try_clone())?, len, limits, Format::Tar, check); | |
| 137 | 추가: } | |
| 138 | 추가: Err(ErrorCode::UnsupportedFormat) | |
| 139 | 추가: } | |
| 140 | 추가: } | |
| 141 | 추가: | |
| 142 | 추가: fn tar( | |
| 143 | 추가: mut data: File, | |
| 144 | 추가: len: u64, | |
| 145 | 추가: limits: Limits, | |
| 146 | 추가: format: Format, | |
| 147 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 148 | 추가: ) -> Result<Catalog> { | |
| 149 | 추가: let mut cursor = 0u64; | |
| 150 | 추가: let mut total = 0u64; | |
| 151 | 추가: let mut members = Vec::new(); | |
| 152 | 추가: let mut offsets = Vec::new(); | |
| 153 | 추가: let mut metadata = MetadataBudget::default(); | |
| 154 | 추가: loop { | |
| 155 | 추가: check()?; | |
| 156 | 추가: let mut header = [0; 512]; | |
| 157 | 추가: if add(cursor, 512)? > len { | |
| 158 | 추가: return Err(ErrorCode::Integrity); | |
| 159 | 추가: } | |
| 160 | 추가: at(&mut data, cursor, &mut header)?; | |
| 161 | 추가: if header.iter().all(|b| *b == 0) { | |
| 162 | 추가: if add(cursor, 1024)? > len || len % 512 != 0 { | |
| 163 | 추가: return Err(ErrorCode::Integrity); | |
| 164 | 추가: } | |
| 165 | 추가: let mut buffer = Zeroizing::new([0; CHUNK]); | |
| 166 | 추가: let mut remaining = len - cursor - 512; | |
| 167 | 추가: while remaining != 0 { | |
| 168 | 추가: check()?; | |
| 169 | 추가: let n = remaining.min(CHUNK as u64) as usize; | |
| 170 | 추가: io(data.read_exact(&mut buffer[..n]))?; | |
| 171 | 추가: if buffer[..n].iter().any(|b| *b != 0) { | |
| 172 | 추가: return Err(ErrorCode::Integrity); | |
| 173 | 추가: } | |
| 174 | 추가: remaining -= n as u64; | |
| 175 | 추가: } | |
| 176 | 추가: break; | |
| 177 | 추가: } | |
| 178 | 추가: if members.len() >= limits.entries as usize { | |
| 179 | 추가: return Err(ErrorCode::Limit); | |
| 180 | 추가: } | |
| 181 | 추가: let sum = header | |
| 182 | 추가: .iter() | |
| 183 | 추가: .enumerate() | |
| 184 | 추가: .map(|(i, b)| { | |
| 185 | 추가: if (148..156).contains(&i) { | |
| 186 | 추가: 32 | |
| 187 | 추가: } else { | |
| 188 | 추가: *b as u64 | |
| 189 | 추가: } | |
| 190 | 추가: }) | |
| 191 | 추가: .sum::<u64>(); | |
| 192 | 추가: if sum != archive::octal(&header[148..156])? { | |
| 193 | 추가: return Err(ErrorCode::Integrity); | |
| 194 | 추가: } | |
| 195 | 추가: let mut name = archive::tar_string(&header[..100])?; | |
| 196 | 추가: if matches!(&header[257..263], b"ustar\0" | b"ustar ") { | |
| 197 | 추가: let prefix = archive::tar_string(&header[345..500])?; | |
| 198 | 추가: if !prefix.is_empty() { | |
| 199 | 추가: name = format!("{prefix}/{name}"); | |
| 200 | 추가: } | |
| 201 | 추가: } else if header[257..263].iter().any(|b| *b != 0) { | |
| 202 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 203 | 추가: } | |
| 204 | 추가: let kind = match header[156] { | |
| 205 | 추가: 0 | b'0' => EntryKind::File, | |
| 206 | 추가: b'5' => EntryKind::Directory, | |
| 207 | 추가: b'1' | b'2' => EntryKind::Link, | |
| 208 | 추가: b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature), | |
| 209 | 추가: _ => EntryKind::Other, | |
| 210 | 추가: }; | |
| 211 | 추가: let size = archive::octal(&header[124..136])?; | |
| 212 | 추가: if kind != EntryKind::File && size != 0 { | |
| 213 | 추가: return Err(ErrorCode::Integrity); | |
| 214 | 추가: } | |
| 215 | 추가: total = total | |
| 216 | 추가: .checked_add(size) | |
| 217 | 추가: .filter(|n| *n <= limits.output) | |
| 218 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 219 | 추가: let start = add(cursor, 512)?; | |
| 220 | 추가: cursor = add( | |
| 221 | 추가: start, | |
| 222 | 추가: size.checked_add(511).ok_or(ErrorCode::Integrity)? / 512 * 512, | |
| 223 | 추가: )?; | |
| 224 | 추가: if cursor > len { | |
| 225 | 추가: return Err(ErrorCode::Integrity); | |
| 226 | 추가: } | |
| 227 | 추가: metadata.charge(&name)?; | |
| 228 | 추가: let name = archive::valid_name(&name, kind == EntryKind::Directory)?; | |
| 229 | 추가: offsets.push(start); | |
| 230 | 추가: members.push(Member { | |
| 231 | 추가: entry: Entry { | |
| 232 | 추가: entry_id: members.len() as u32, | |
| 233 | 추가: name, | |
| 234 | 추가: kind, | |
| 235 | 추가: size, | |
| 236 | 추가: compressed_size: size, | |
| 237 | 추가: encrypted: false, | |
| 238 | 추가: }, | |
| 239 | 추가: data: Vec::new(), | |
| 240 | 추가: }); | |
| 241 | 추가: } | |
| 242 | 추가: archive::validate_members(&members)?; | |
| 243 | 추가: Ok(Catalog { | |
| 244 | 추가: format, | |
| 245 | 추가: members, | |
| 246 | 추가: offsets, | |
| 247 | 추가: data, | |
| 248 | 추가: }) | |
| 249 | 추가: } | |
| 250 | 추가: | |
| 251 | 추가: // 각 ZIP 항목과 각 GZip 멤버의 실제 해제량에 압축비와 누적 총량을 적용함. | |
| 252 | 추가: fn inflate( | |
| 253 | 추가: input: &mut impl Read, | |
| 254 | 추가: length: u64, | |
| 255 | 추가: gzip: bool, | |
| 256 | 추가: limit: u64, | |
| 257 | 추가: ratio_base: Option<u64>, | |
| 258 | 추가: output: &mut File, | |
| 259 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 260 | 추가: ) -> Result<(u64, u32)> { | |
| 261 | 추가: let mut remaining = length; | |
| 262 | 추가: let mut buffer = Zeroizing::new([0; CHUNK]); | |
| 263 | 추가: let mut plain = Zeroizing::new([0; CHUNK]); | |
| 264 | 추가: let mut have = 0; | |
| 265 | 추가: let mut used = 0; | |
| 266 | 추가: let mut total = 0u64; | |
| 267 | 추가: let mut crc = 0; | |
| 268 | 추가: loop { | |
| 269 | 추가: let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); | |
| 270 | 추가: loop { | |
| 271 | 추가: check()?; | |
| 272 | 추가: if used == have && remaining != 0 { | |
| 273 | 추가: have = input | |
| 274 | 추가: .read(&mut buffer[..remaining.min(CHUNK as u64) as usize]) | |
| 275 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 276 | 추가: if have == 0 { | |
| 277 | 추가: return Err(ErrorCode::Integrity); | |
| 278 | 추가: } | |
| 279 | 추가: remaining -= have as u64; | |
| 280 | 추가: used = 0; | |
| 281 | 추가: } | |
| 282 | 추가: let a = stream.total_in(); | |
| 283 | 추가: let b = stream.total_out(); | |
| 284 | 추가: let status = stream | |
| 285 | 추가: .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush) | |
| 286 | 추가: .map_err(|_| ErrorCode::Integrity)?; | |
| 287 | 추가: used += (stream.total_in() - a) as usize; | |
| 288 | 추가: let n = (stream.total_out() - b) as usize; | |
| 289 | 추가: total = total | |
| 290 | 추가: .checked_add(n as u64) | |
| 291 | 추가: .filter(|n| *n <= limit) | |
| 292 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 293 | 추가: if let Some(base) = ratio_base { | |
| 294 | 추가: ratio(total, base)?; | |
| 295 | 추가: } | |
| 296 | 추가: crc = crc32(crc, &plain[..n]); | |
| 297 | 추가: io(output.write_all(&plain[..n]))?; | |
| 298 | 추가: if status == Status::StreamEnd { | |
| 299 | 추가: if gzip { | |
| 300 | 추가: ratio(stream.total_out(), stream.total_in())?; | |
| 301 | 추가: } | |
| 302 | 추가: break; | |
| 303 | 추가: } | |
| 304 | 추가: if a == stream.total_in() && b == stream.total_out() { | |
| 305 | 추가: return Err(ErrorCode::Integrity); | |
| 306 | 추가: } | |
| 307 | 추가: } | |
| 308 | 추가: if remaining == 0 && used == have { | |
| 309 | 추가: break; | |
| 310 | 추가: } | |
| 311 | 추가: if !gzip { | |
| 312 | 추가: return Err(ErrorCode::Integrity); | |
| 313 | 추가: } | |
| 314 | 추가: } | |
| 315 | 추가: Ok((total, crc)) | |
| 316 | 추가: } | |
| 317 | 추가: | |
| 318 | 추가: struct Packed { | |
| 319 | 추가: offset: u64, | |
| 320 | 추가: size: u64, | |
| 321 | 추가: method: u16, | |
| 322 | 추가: crc: Option<u32>, | |
| 323 | 추가: flags: u16, | |
| 324 | 추가: verifier: u8, | |
| 325 | 추가: aes: bool, | |
| 326 | 추가: } | |
| 327 | 추가: | |
| 328 | 추가: fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> { | |
| 329 | 추가: let mut at = 0; | |
| 330 | 추가: let mut aes = Vec::new(); | |
| 331 | 추가: let mut large = None; | |
| 332 | 추가: while at < bytes.len() { | |
| 333 | 추가: if bytes.len() - at < 4 { | |
| 334 | 추가: return Err(ErrorCode::Integrity); | |
| 335 | 추가: } | |
| 336 | 추가: let tag = u16at(bytes, at); | |
| 337 | 추가: let len = u16at(bytes, at + 2) as usize; | |
| 338 | 추가: let end = at + 4 + len; | |
| 339 | 추가: if end > bytes.len() { | |
| 340 | 추가: return Err(ErrorCode::Integrity); | |
| 341 | 추가: } | |
| 342 | 추가: if tag == 1 { | |
| 343 | 추가: if large.is_some() { | |
| 344 | 추가: return Err(ErrorCode::Integrity); | |
| 345 | 추가: } | |
| 346 | 추가: large = Some(bytes[at + 4..end].to_vec()); | |
| 347 | 추가: } else { | |
| 348 | 추가: aes.extend_from_slice(&bytes[at..end]); | |
| 349 | 추가: } | |
| 350 | 추가: at = end; | |
| 351 | 추가: } | |
| 352 | 추가: Ok((archive::aes_extra(&aes)?, large)) | |
| 353 | 추가: } | |
| 354 | 추가: fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> { | |
| 355 | 추가: if value != u32::MAX { | |
| 356 | 추가: return Ok(value as u64); | |
| 357 | 추가: } | |
| 358 | 추가: if extra.len() < 8 { | |
| 359 | 추가: return Err(ErrorCode::Integrity); | |
| 360 | 추가: } | |
| 361 | 추가: let result = u64at(extra, 0); | |
| 362 | 추가: *extra = &extra[8..]; | |
| 363 | 추가: Ok(result) | |
| 364 | 추가: } | |
| 365 | 추가: fn zip( | |
| 366 | 추가: source: &mut File, | |
| 367 | 추가: len: u64, | |
| 368 | 추가: limits: Limits, | |
| 369 | 추가: decode: bool, | |
| 370 | 추가: password: Option<&[u8]>, | |
| 371 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 372 | 추가: ) -> Result<Catalog> { | |
| 373 | 추가: if len < 22 { | |
| 374 | 추가: return Err(ErrorCode::Integrity); | |
| 375 | 추가: } | |
| 376 | 추가: let tail_at = len.saturating_sub(65557); | |
| 377 | 추가: let tail = bytes(source, tail_at, (len - tail_at) as usize)?; | |
| 378 | 추가: let end = (0..=tail.len() - 22) | |
| 379 | 추가: .rev() | |
| 380 | 추가: .find(|&i| { | |
| 381 | 추가: &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len() | |
| 382 | 추가: }) | |
| 383 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 384 | 추가: let h = &tail[end..]; | |
| 385 | 추가: if u16at(h, 4) != 0 || u16at(h, 6) != 0 { | |
| 386 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 387 | 추가: } | |
| 388 | 추가: let mut count = u16at(h, 10) as u64; | |
| 389 | 추가: if count != u16at(h, 8) as u64 { | |
| 390 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 391 | 추가: } | |
| 392 | 추가: let mut central_size = u32at(h, 12) as u64; | |
| 393 | 추가: let mut central = u32at(h, 16) as u64; | |
| 394 | 추가: let mut central_end = tail_at + end as u64; | |
| 395 | 추가: if count == u16::MAX as u64 || central_size == u32::MAX as u64 || central == u32::MAX as u64 { | |
| 396 | 추가: if central_end < 20 { | |
| 397 | 추가: return Err(ErrorCode::Integrity); | |
| 398 | 추가: } | |
| 399 | 추가: let locator = bytes(source, central_end - 20, 20)?; | |
| 400 | 추가: if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 { | |
| 401 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 402 | 추가: } | |
| 403 | 추가: let offset = u64at(&locator, 8); | |
| 404 | 추가: if add(offset, 56)? > central_end - 20 { | |
| 405 | 추가: return Err(ErrorCode::Integrity); | |
| 406 | 추가: } | |
| 407 | 추가: let large = bytes(source, offset, 56)?; | |
| 408 | 추가: if &large[..4] != b"PK\x06\x06" | |
| 409 | 추가: || u64at(&large, 4) < 44 | |
| 410 | 추가: || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20 | |
| 411 | 추가: { | |
| 412 | 추가: return Err(ErrorCode::Integrity); | |
| 413 | 추가: } | |
| 414 | 추가: if u32at(&large, 16) != 0 | |
| 415 | 추가: || u32at(&large, 20) != 0 | |
| 416 | 추가: || u64at(&large, 24) != u64at(&large, 32) | |
| 417 | 추가: { | |
| 418 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 419 | 추가: } | |
| 420 | 추가: let (n, size, start) = (u64at(&large, 32), u64at(&large, 40), u64at(&large, 48)); | |
| 421 | 추가: if (count != u16::MAX as u64 && count != n) | |
| 422 | 추가: || (central_size != u32::MAX as u64 && central_size != size) | |
| 423 | 추가: || (central != u32::MAX as u64 && central != start) | |
| 424 | 추가: { | |
| 425 | 추가: return Err(ErrorCode::Integrity); | |
| 426 | 추가: } | |
| 427 | 추가: (count, central_size, central, central_end) = (n, size, start, offset); | |
| 428 | 추가: } | |
| 429 | 추가: if count > limits.entries as u64 { | |
| 430 | 추가: return Err(ErrorCode::Limit); | |
| 431 | 추가: } | |
| 432 | 추가: if add(central, central_size)? != central_end { | |
| 433 | 추가: return Err(ErrorCode::Integrity); | |
| 434 | 추가: } | |
| 435 | 추가: let mut cursor = central; | |
| 436 | 추가: let mut total = 0u64; | |
| 437 | 추가: let mut metadata = MetadataBudget::default(); | |
| 438 | 추가: let mut members = Vec::new(); | |
| 439 | 추가: let mut packed = Vec::new(); | |
| 440 | 추가: let mut spans = Vec::new(); | |
| 441 | 추가: for id in 0..count { | |
| 442 | 추가: check()?; | |
| 443 | 추가: if add(cursor, 46)? > central_end { | |
| 444 | 추가: return Err(ErrorCode::Integrity); | |
| 445 | 추가: } | |
| 446 | 추가: let h = bytes(source, cursor, 46)?; | |
| 447 | 추가: if &h[..4] != b"PK\x01\x02" { | |
| 448 | 추가: return Err(ErrorCode::Integrity); | |
| 449 | 추가: } | |
| 450 | 추가: let flags = u16at(&h, 8); | |
| 451 | 추가: let method = u16at(&h, 10); | |
| 452 | 추가: if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(&h, 34) != 0 { | |
| 453 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 454 | 추가: } | |
| 455 | 추가: let crc = u32at(&h, 16); | |
| 456 | 추가: let (nn, ne, nc) = ( | |
| 457 | 추가: u16at(&h, 28) as u64, | |
| 458 | 추가: u16at(&h, 30) as u64, | |
| 459 | 추가: u16at(&h, 32) as u64, | |
| 460 | 추가: ); | |
| 461 | 추가: let next = add(cursor, 46 + nn + ne + nc)?; | |
| 462 | 추가: if next > central_end { | |
| 463 | 추가: return Err(ErrorCode::Integrity); | |
| 464 | 추가: } | |
| 465 | 추가: if nn > 4096 { | |
| 466 | 추가: return Err(ErrorCode::UnsafePath); | |
| 467 | 추가: } | |
| 468 | 추가: let raw = bytes(source, cursor + 46, nn as usize)?; | |
| 469 | 추가: if flags & 0x0800 == 0 && !raw.is_ascii() { | |
| 470 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 471 | 추가: } | |
| 472 | 추가: let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?; | |
| 473 | 추가: let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?; | |
| 474 | 추가: let central_zip64 = large.is_some(); | |
| 475 | 추가: let mut large = large.as_deref().unwrap_or(&[]); | |
| 476 | 추가: let size = large_value(u32at(&h, 24), &mut large)?; | |
| 477 | 추가: let compressed = large_value(u32at(&h, 20), &mut large)?; | |
| 478 | 추가: let local = large_value(u32at(&h, 42), &mut large)?; | |
| 479 | 추가: if u16at(&h, 34) == 65535 && (large.len() < 4 || u32at(large, 0) != 0) { | |
| 480 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 481 | 추가: } | |
| 482 | 추가: let encrypted = flags & 1 != 0; | |
| 483 | 추가: if (method == 99) != aes.is_some() | |
| 484 | 추가: || (method == 99 && !encrypted) | |
| 485 | 추가: || (aes.is_some_and(|a| a.version == 2) && crc != 0) | |
| 486 | 추가: { | |
| 487 | 추가: return Err(ErrorCode::Integrity); | |
| 488 | 추가: } | |
| 489 | 추가: let overhead = if !encrypted { | |
| 490 | 추가: 0 | |
| 491 | 추가: } else if aes.is_some() { | |
| 492 | 추가: 28 | |
| 493 | 추가: } else { | |
| 494 | 추가: 12 | |
| 495 | 추가: }; | |
| 496 | 추가: let payload = compressed | |
| 497 | 추가: .checked_sub(overhead) | |
| 498 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 499 | 추가: ratio(size, payload)?; | |
| 500 | 추가: total = total | |
| 501 | 추가: .checked_add(size) | |
| 502 | 추가: .filter(|n| *n <= limits.output) | |
| 503 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 504 | 추가: let mode = u32at(&h, 38) >> 16; | |
| 505 | 추가: let kind = match mode & 0xf000 { | |
| 506 | 추가: 0xa000 => EntryKind::Link, | |
| 507 | 추가: 0x4000 => EntryKind::Directory, | |
| 508 | 추가: 0 | 0x8000 => { | |
| 509 | 추가: if name.ends_with('/') { | |
| 510 | 추가: EntryKind::Directory | |
| 511 | 추가: } else { | |
| 512 | 추가: EntryKind::File | |
| 513 | 추가: } | |
| 514 | 추가: } | |
| 515 | 추가: _ => EntryKind::Other, | |
| 516 | 추가: }; | |
| 517 | 추가: if kind == EntryKind::Directory && size != 0 { | |
| 518 | 추가: return Err(ErrorCode::Integrity); | |
| 519 | 추가: } | |
| 520 | 추가: metadata.charge(name)?; | |
| 521 | 추가: let name = archive::valid_name(name, kind == EntryKind::Directory)?; | |
| 522 | 추가: if add(local, 30)? > central { | |
| 523 | 추가: return Err(ErrorCode::Integrity); | |
| 524 | 추가: } | |
| 525 | 추가: let lh = bytes(source, local, 30)?; | |
| 526 | 추가: if &lh[..4] != b"PK\x03\x04" | |
| 527 | 추가: || u16at(&lh, 6) != flags | |
| 528 | 추가: || u16at(&lh, 8) != method | |
| 529 | 추가: || u16at(&lh, 10) != u16at(&h, 12) | |
| 530 | 추가: { | |
| 531 | 추가: return Err(ErrorCode::Integrity); | |
| 532 | 추가: } | |
| 533 | 추가: let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64); | |
| 534 | 추가: let start = add(local, 30 + ln + le)?; | |
| 535 | 추가: if start > central || ln != nn { | |
| 536 | 추가: return Err(ErrorCode::Integrity); | |
| 537 | 추가: } | |
| 538 | 추가: if bytes(source, local + 30, ln as usize)? != raw { | |
| 539 | 추가: return Err(ErrorCode::Integrity); | |
| 540 | 추가: } | |
| 541 | 추가: let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?; | |
| 542 | 추가: if local_aes != aes { | |
| 543 | 추가: return Err(ErrorCode::Integrity); | |
| 544 | 추가: } | |
| 545 | 추가: let zip64 = central_zip64 | |
| 546 | 추가: || local_large.is_some() | |
| 547 | 추가: || u32at(&h, 20) == u32::MAX | |
| 548 | 추가: || u32at(&h, 24) == u32::MAX | |
| 549 | 추가: || u32at(&lh, 18) == u32::MAX | |
| 550 | 추가: || u32at(&lh, 22) == u32::MAX; | |
| 551 | 추가: if flags & 8 == 0 { | |
| 552 | 추가: let mut values = local_large.as_deref().unwrap_or(&[]); | |
| 553 | 추가: let local_size = large_value(u32at(&lh, 22), &mut values)?; | |
| 554 | 추가: let local_compressed = large_value(u32at(&lh, 18), &mut values)?; | |
| 555 | 추가: if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed { | |
| 556 | 추가: return Err(ErrorCode::Integrity); | |
| 557 | 추가: } | |
| 558 | 추가: } | |
| 559 | 추가: let mut stop = add(start, compressed)?; | |
| 560 | 추가: if stop > central { | |
| 561 | 추가: return Err(ErrorCode::Integrity); | |
| 562 | 추가: } | |
| 563 | 추가: if flags & 8 != 0 { | |
| 564 | 추가: let descriptor_len = if zip64 { 20 } else { 12 }; | |
| 565 | 추가: if add(stop, descriptor_len)? > central { | |
| 566 | 추가: return Err(ErrorCode::Integrity); | |
| 567 | 추가: } | |
| 568 | 추가: let signature = bytes(source, stop, 4)?; | |
| 569 | 추가: if signature == b"PK\x07\x08" { | |
| 570 | 추가: stop = add(stop, 4)?; | |
| 571 | 추가: } | |
| 572 | 추가: if add(stop, descriptor_len)? > central { | |
| 573 | 추가: return Err(ErrorCode::Integrity); | |
| 574 | 추가: } | |
| 575 | 추가: let d = bytes(source, stop, descriptor_len as usize)?; | |
| 576 | 추가: let (pc, ps) = if zip64 { | |
| 577 | 추가: (u64at(&d, 4), u64at(&d, 12)) | |
| 578 | 추가: } else { | |
| 579 | 추가: (u32at(&d, 4) as u64, u32at(&d, 8) as u64) | |
| 580 | 추가: }; | |
| 581 | 추가: if u32at(&d, 0) != crc || pc != compressed || ps != size { | |
| 582 | 추가: return Err(ErrorCode::Integrity); | |
| 583 | 추가: } | |
| 584 | 추가: stop += descriptor_len; | |
| 585 | 추가: } | |
| 586 | 추가: spans.push((local, stop)); | |
| 587 | 추가: packed.push(Packed { | |
| 588 | 추가: offset: start, | |
| 589 | 추가: size: compressed, | |
| 590 | 추가: method: aes.map_or(method, |a| a.method), | |
| 591 | 추가: crc: if aes.is_some_and(|a| a.version == 2) { | |
| 592 | 추가: None | |
| 593 | 추가: } else { | |
| 594 | 추가: Some(crc) | |
| 595 | 추가: }, | |
| 596 | 추가: flags, | |
| 597 | 추가: verifier: if flags & 8 != 0 { | |
| 598 | 추가: (u16at(&h, 12) >> 8) as u8 | |
| 599 | 추가: } else { | |
| 600 | 추가: (crc >> 24) as u8 | |
| 601 | 추가: }, | |
| 602 | 추가: aes: aes.is_some(), | |
| 603 | 추가: }); | |
| 604 | 추가: members.push(Member { | |
| 605 | 추가: entry: Entry { | |
| 606 | 추가: entry_id: id as u32, | |
| 607 | 추가: name, | |
| 608 | 추가: kind, | |
| 609 | 추가: size, | |
| 610 | 추가: compressed_size: compressed, | |
| 611 | 추가: encrypted, | |
| 612 | 추가: }, | |
| 613 | 추가: data: Vec::new(), | |
| 614 | 추가: }); | |
| 615 | 추가: cursor = next; | |
| 616 | 추가: } | |
| 617 | 추가: if cursor != central_end { | |
| 618 | 추가: return Err(ErrorCode::Integrity); | |
| 619 | 추가: } | |
| 620 | 추가: spans.sort_unstable(); | |
| 621 | 추가: let mut next = 0; | |
| 622 | 추가: for (a, b) in spans { | |
| 623 | 추가: if a != next { | |
| 624 | 추가: return Err(ErrorCode::Integrity); | |
| 625 | 추가: } | |
| 626 | 추가: next = b; | |
| 627 | 추가: } | |
| 628 | 추가: if next != central { | |
| 629 | 추가: return Err(ErrorCode::Integrity); | |
| 630 | 추가: } | |
| 631 | 추가: archive::validate_members(&members)?; | |
| 632 | 추가: let mut data = spool::temporary()?; | |
| 633 | 추가: let mut offsets = Vec::new(); | |
| 634 | 추가: for (member, packed) in members.iter().zip(packed) { | |
| 635 | 추가: check()?; | |
| 636 | 추가: offsets.push(io(data.stream_position())?); | |
| 637 | 추가: if !decode { | |
| 638 | 추가: continue; | |
| 639 | 추가: } | |
| 640 | 추가: let (decoder, start, length) = if packed.flags & 1 != 0 { | |
| 641 | 추가: crypto::Decryptor::prepare( | |
| 642 | 추가: source, | |
| 643 | 추가: packed.offset, | |
| 644 | 추가: packed.size, | |
| 645 | 추가: password.ok_or(ErrorCode::WrongPassword)?, | |
| 646 | 추가: packed.aes, | |
| 647 | 추가: packed.verifier, | |
| 648 | 추가: check, | |
| 649 | 추가: )? | |
| 650 | 추가: } else { | |
| 651 | 추가: (crypto::Decryptor::Plain, packed.offset, packed.size) | |
| 652 | 추가: }; | |
| 653 | 추가: io(source.seek(SeekFrom::Start(start)))?; | |
| 654 | 추가: let mut reader = Decoded { | |
| 655 | 추가: reader: source.take(length), | |
| 656 | 추가: decoder, | |
| 657 | 추가: }; | |
| 658 | 추가: let (size, crc) = if packed.method == 8 { | |
| 659 | 추가: inflate( | |
| 660 | 추가: &mut reader, | |
| 661 | 추가: length, | |
| 662 | 추가: false, | |
| 663 | 추가: member.entry.size, | |
| 664 | 추가: Some(length), | |
| 665 | 추가: &mut data, | |
| 666 | 추가: check, | |
| 667 | 추가: )? | |
| 668 | 추가: } else { | |
| 669 | 추가: let mut buffer = Zeroizing::new([0; CHUNK]); | |
| 670 | 추가: let mut total = 0u64; | |
| 671 | 추가: let mut crc = 0; | |
| 672 | 추가: loop { | |
| 673 | 추가: check()?; | |
| 674 | 추가: let n = io(reader.read(&mut buffer[..]))?; | |
| 675 | 추가: if n == 0 { | |
| 676 | 추가: break; | |
| 677 | 추가: } | |
| 678 | 추가: total = total | |
| 679 | 추가: .checked_add(n as u64) | |
| 680 | 추가: .filter(|n| *n <= member.entry.size) | |
| 681 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 682 | 추가: crc = crc32(crc, &buffer[..n]); | |
| 683 | 추가: io(data.write_all(&buffer[..n]))?; | |
| 684 | 추가: } | |
| 685 | 추가: (total, crc) | |
| 686 | 추가: }; | |
| 687 | 추가: if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) { | |
| 688 | 추가: return Err(ErrorCode::Integrity); | |
| 689 | 추가: } | |
| 690 | 추가: } | |
| 691 | 추가: Ok(Catalog { | |
| 692 | 추가: format: Format::Zip, | |
| 693 | 추가: members, | |
| 694 | 추가: offsets, | |
| 695 | 추가: data, | |
| 696 | 추가: }) | |
| 697 | 추가: } | |
| 698 | 추가: struct Decoded<R> { | |
| 699 | 추가: reader: R, | |
| 700 | 추가: decoder: crypto::Decryptor, | |
| 701 | 추가: } | |
| 702 | 추가: impl<R: Read> Read for Decoded<R> { | |
| 703 | 추가: fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> { | |
| 704 | 추가: let n = self.reader.read(output)?; | |
| 705 | 추가: self.decoder.apply(&mut output[..n]); | |
| 706 | 추가: Ok(n) | |
| 707 | 추가: } | |
| 708 | 추가: } | |
| 709 | 추가: | |
| 710 | 추가: #[cfg(test)] | |
| 711 | 추가: #[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"] | |
| 712 | 추가: mod bounds; |
| @@ -0,0 +1,462 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use std::{fs::File, io::Read}; | |
| 3 | 추가: | |
| 4 | 추가: fn generate(s: &Scratch, kind: &str, size: u64) { | |
| 5 | 추가: assert!( | |
| 6 | 추가: Command::new("python3") | |
| 7 | 추가: .arg( | |
| 8 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 9 | 추가: .join("../../tests/rust-archive-worker/hardening_cases.py") | |
| 10 | 추가: ) | |
| 11 | 추가: .arg(&s.0) | |
| 12 | 추가: .arg(kind) | |
| 13 | 추가: .arg(size.to_string()) | |
| 14 | 추가: .status() | |
| 15 | 추가: .unwrap() | |
| 16 | 추가: .success() | |
| 17 | 추가: ); | |
| 18 | 추가: } | |
| 19 | 추가: fn start(s: &Scratch, gzip: bool, output: u64) -> Start { | |
| 20 | 추가: fs::DirBuilder::new().create(s.0.join("output")).unwrap(); | |
| 21 | 추가: #[cfg(unix)] | |
| 22 | 추가: { | |
| 23 | 추가: use std::os::unix::fs::PermissionsExt; | |
| 24 | 추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap(); | |
| 25 | 추가: } | |
| 26 | 추가: Start { | |
| 27 | 추가: action: Action::Extract { | |
| 28 | 추가: archive: s.path("input"), | |
| 29 | 추가: destination: s.path("output"), | |
| 30 | 추가: selection: Selection::All, | |
| 31 | 추가: list_id: None, | |
| 32 | 추가: gzip_output_name: gzip.then(|| "payload.bin".to_owned()), | |
| 33 | 추가: }, | |
| 34 | 추가: limits: Limits { | |
| 35 | 추가: output, | |
| 36 | 추가: ..Limits::default() | |
| 37 | 추가: }, | |
| 38 | 추가: } | |
| 39 | 추가: } | |
| 40 | 추가: fn assert_zero_file(path: &std::path::Path, length: u64) { | |
| 41 | 추가: let mut file = File::open(path).unwrap(); | |
| 42 | 추가: assert_eq!(file.metadata().unwrap().len(), length); | |
| 43 | 추가: let mut buffer = [0; 65536]; | |
| 44 | 추가: let mut total = 0; | |
| 45 | 추가: loop { | |
| 46 | 추가: let n = file.read(&mut buffer).unwrap(); | |
| 47 | 추가: if n == 0 { | |
| 48 | 추가: break; | |
| 49 | 추가: } | |
| 50 | 추가: assert!(buffer[..n].iter().all(|b| *b == 0)); | |
| 51 | 추가: total += n as u64; | |
| 52 | 추가: } | |
| 53 | 추가: assert_eq!(total, length); | |
| 54 | 추가: } | |
| 55 | 추가: #[test] | |
| 56 | 추가: fn streaming_defaults_and_legacy_seven_zip_caps() { | |
| 57 | 추가: assert_eq!(Limits::default().input, u64::MAX); | |
| 58 | 추가: assert_eq!(Limits::default().output, 16 * 1024 * 1024 * 1024); | |
| 59 | 추가: assert!( | |
| 60 | 추가: !Limits { | |
| 61 | 추가: output: 16 * 1024 * 1024 * 1024 + 1, | |
| 62 | 추가: ..Limits::default() | |
| 63 | 추가: } | |
| 64 | 추가: .valid() | |
| 65 | 추가: ); | |
| 66 | 추가: let s = Scratch::new(); | |
| 67 | 추가: let file = File::create(s.0.join("input")).unwrap(); | |
| 68 | 추가: (&file).write_all(b"7z\xbc\xaf\x27\x1c").unwrap(); | |
| 69 | 추가: file.set_len(1024 * 1024 * 1024).unwrap(); | |
| 70 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 71 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Limit); | |
| 72 | 추가: assert_eq!(terminal(&events).created_count, 0); | |
| 73 | 추가: } | |
| 74 | 추가: #[test] | |
| 75 | 추가: fn streaming_zip64_local_headers_and_chunk_boundaries() { | |
| 76 | 추가: let s = Scratch::new(); | |
| 77 | 추가: generate(&s, "zip64", 9 * 1024 * 1024 + 13); | |
| 78 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 79 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 80 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 9 * 1024 * 1024 + 13); | |
| 81 | 추가: } | |
| 82 | 추가: #[test] | |
| 83 | 추가: fn streaming_ratio_rejects_bomb_without_publication() { | |
| 84 | 추가: let s = Scratch::new(); | |
| 85 | 추가: generate(&s, "bomb", 16 * 1024 * 1024); | |
| 86 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 87 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); | |
| 88 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 89 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 90 | 추가: } | |
| 91 | 추가: #[test] | |
| 92 | 추가: fn streaming_tar_and_gzip_truncation_never_publish() { | |
| 93 | 추가: for kind in ["tar", "targz", "gzip"] { | |
| 94 | 추가: let s = Scratch::new(); | |
| 95 | 추가: generate(&s, kind, 1024 * 1024 + 1); | |
| 96 | 추가: let file = fs::OpenOptions::new() | |
| 97 | 추가: .write(true) | |
| 98 | 추가: .open(s.0.join("input")) | |
| 99 | 추가: .unwrap(); | |
| 100 | 추가: file.set_len(file.metadata().unwrap().len() - 1).unwrap(); | |
| 101 | 추가: let events = execute(start(&s, kind == "gzip", Limits::default().output)); | |
| 102 | 추가: assert_eq!( | |
| 103 | 추가: terminal(&events).outcome, | |
| 104 | 추가: Outcome::Failed, | |
| 105 | 추가: "{kind}: {events:?}" | |
| 106 | 추가: ); | |
| 107 | 추가: assert_eq!(terminal(&events).created_count, 0); | |
| 108 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 109 | 추가: } | |
| 110 | 추가: } | |
| 111 | 추가: | |
| 112 | 추가: #[test] | |
| 113 | 추가: fn zip64_directory_and_descriptor_interoperate() { | |
| 114 | 추가: for kind in ["central64", "descriptor64"] { | |
| 115 | 추가: let s = Scratch::new(); | |
| 116 | 추가: generate(&s, kind, 65536 + 19); | |
| 117 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 118 | 추가: assert_eq!( | |
| 119 | 추가: terminal(&events).outcome, | |
| 120 | 추가: Outcome::Completed, | |
| 121 | 추가: "{kind}: {events:?}" | |
| 122 | 추가: ); | |
| 123 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19); | |
| 124 | 추가: } | |
| 125 | 추가: } | |
| 126 | 추가: #[test] | |
| 127 | 추가: fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() { | |
| 128 | 추가: for (kind, error) in [ | |
| 129 | 추가: ("central64-size-overflow", ErrorCode::Limit), | |
| 130 | 추가: ("central64-offset-overflow", ErrorCode::Integrity), | |
| 131 | 추가: ] { | |
| 132 | 추가: let s = Scratch::new(); | |
| 133 | 추가: generate(&s, kind, 1024); | |
| 134 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 135 | 추가: assert_eq!(terminal(&events).error, error, "{kind}: {events:?}"); | |
| 136 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 137 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 138 | 추가: } | |
| 139 | 추가: } | |
| 140 | 추가: #[test] | |
| 141 | 추가: fn gzip_ratio_is_per_member_even_with_low_ratio_suffix() { | |
| 142 | 추가: let s = Scratch::new(); | |
| 143 | 추가: generate(&s, "gzip-bomb-joined", 16 * 1024 * 1024); | |
| 144 | 추가: let events = execute(start(&s, true, Limits::default().output)); | |
| 145 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); | |
| 146 | 추가: assert_eq!(terminal(&events).created_count, 0); | |
| 147 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 148 | 추가: } | |
| 149 | 추가: #[test] | |
| 150 | 추가: fn streamed_aes_counter_survives_many_read_chunks() { | |
| 151 | 추가: let s = Scratch::new(); | |
| 152 | 추가: generate(&s, "store", 2 * 1024 * 1024 + 17); | |
| 153 | 추가: fs::rename(s.0.join("input"), s.0.join("source")).unwrap(); | |
| 154 | 추가: let events = interactive( | |
| 155 | 추가: Start { | |
| 156 | 추가: action: Action::CreateZip { | |
| 157 | 추가: sources: vec![Source { | |
| 158 | 추가: path: s.path("source"), | |
| 159 | 추가: archive_name: "payload.bin".to_owned(), | |
| 160 | 추가: }], | |
| 161 | 추가: output_file: s.path("input"), | |
| 162 | 추가: method: Method::Store, | |
| 163 | 추가: encryption: Encryption::Aes256, | |
| 164 | 추가: }, | |
| 165 | 추가: limits: Limits::default(), | |
| 166 | 추가: }, | |
| 167 | 추가: |id, _, _| password_reply(id, TEST_PASSWORD), | |
| 168 | 추가: ); | |
| 169 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 170 | 추가: let events = interactive(start(&s, false, Limits::default().output), |id, _, _| { | |
| 171 | 추가: password_reply(id, TEST_PASSWORD) | |
| 172 | 추가: }); | |
| 173 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 174 | 추가: let mut source = File::open(s.0.join("source")).unwrap(); | |
| 175 | 추가: let mut output = File::open(s.0.join("output/payload.bin")).unwrap(); | |
| 176 | 추가: let mut a = [0; 65536]; | |
| 177 | 추가: let mut b = [0; 65536]; | |
| 178 | 추가: loop { | |
| 179 | 추가: let n = source.read(&mut a).unwrap(); | |
| 180 | 추가: output.read_exact(&mut b[..n]).unwrap(); | |
| 181 | 추가: assert_eq!(a[..n], b[..n]); | |
| 182 | 추가: if n == 0 { | |
| 183 | 추가: break; | |
| 184 | 추가: } | |
| 185 | 추가: } | |
| 186 | 추가: assert_eq!( | |
| 187 | 추가: source.metadata().unwrap().len(), | |
| 188 | 추가: output.metadata().unwrap().len() | |
| 189 | 추가: ); | |
| 190 | 추가: } | |
| 191 | 추가: | |
| 192 | 추가: #[cfg(target_os = "linux")] | |
| 193 | 추가: mod linux { | |
| 194 | 추가: use super::*; | |
| 195 | 추가: use std::{ | |
| 196 | 추가: os::raw::c_long, | |
| 197 | 추가: time::{Duration, Instant}, | |
| 198 | 추가: }; | |
| 199 | 추가: #[repr(C)] | |
| 200 | 추가: #[derive(Default)] | |
| 201 | 추가: struct Usage { | |
| 202 | 추가: user: [c_long; 2], | |
| 203 | 추가: system: [c_long; 2], | |
| 204 | 추가: max_rss: c_long, | |
| 205 | 추가: rest: [c_long; 13], | |
| 206 | 추가: } | |
| 207 | 추가: unsafe extern "C" { | |
| 208 | 추가: fn wait4(pid: i32, status: *mut i32, options: i32, usage: *mut Usage) -> i32; | |
| 209 | 추가: fn prctl(option: i32, ...) -> i32; | |
| 210 | 추가: fn kill(pid: i32, signal: i32) -> i32; | |
| 211 | 추가: } | |
| 212 | 추가: fn command() -> Command { | |
| 213 | 추가: let worker = std::env::var_os("ZIPELO_BASELINE_WORKER") | |
| 214 | 추가: .map(PathBuf::from) | |
| 215 | 추가: .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_zipelo-archive-worker"))); | |
| 216 | 추가: Command::new(worker) | |
| 217 | 추가: } | |
| 218 | 추가: fn staging(s: &Scratch) -> PathBuf { | |
| 219 | 추가: use std::os::unix::fs::DirBuilderExt; | |
| 220 | 추가: let path = s.0.join("staging"); | |
| 221 | 추가: fs::DirBuilder::new().mode(0o700).create(&path).unwrap(); | |
| 222 | 추가: path | |
| 223 | 추가: } | |
| 224 | 추가: fn spawn(s: &Scratch, mut start: Start, mode: Option<&str>) -> std::process::Child { | |
| 225 | 추가: if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() { | |
| 226 | 추가: start.limits = Limits { | |
| 227 | 추가: input: 64 * 1024 * 1024, | |
| 228 | 추가: output: 128 * 1024 * 1024, | |
| 229 | 추가: entries: 10000, | |
| 230 | 추가: }; | |
| 231 | 추가: } | |
| 232 | 추가: let mut cmd = command(); | |
| 233 | 추가: cmd.env("TMPDIR", staging(s)) | |
| 234 | 추가: .stdin(Stdio::piped()) | |
| 235 | 추가: .stdout(File::create(s.0.join("events")).unwrap()) | |
| 236 | 추가: .stderr(File::create(s.0.join("stderr")).unwrap()); | |
| 237 | 추가: if let Some(mode) = mode { | |
| 238 | 추가: cmd.env("LD_PRELOAD", shim(s)) | |
| 239 | 추가: .env("ZIPELO_TEST_FAULT", mode) | |
| 240 | 추가: .env("ZIPELO_TEST_MARKER", s.0.join("paused")) | |
| 241 | 추가: .env("ZIPELO_TEST_RELEASE", s.0.join("release")); | |
| 242 | 추가: } | |
| 243 | 추가: let mut child = cmd.spawn().unwrap(); | |
| 244 | 추가: Writer::new(child.stdin.take().unwrap(), 17) | |
| 245 | 추가: .send(&Message::Start(start)) | |
| 246 | 추가: .unwrap(); | |
| 247 | 추가: child | |
| 248 | 추가: } | |
| 249 | 추가: fn wait(pid: u32) -> (i32, u64) { | |
| 250 | 추가: let deadline = Instant::now() + Duration::from_secs(320); | |
| 251 | 추가: loop { | |
| 252 | 추가: let mut status = 0; | |
| 253 | 추가: let mut usage = Usage::default(); | |
| 254 | 추가: let r = unsafe { wait4(pid as i32, &mut status, 1, &mut usage) }; | |
| 255 | 추가: if r == pid as i32 { | |
| 256 | 추가: return (status, usage.max_rss as u64 * 1024); | |
| 257 | 추가: } | |
| 258 | 추가: assert!( | |
| 259 | 추가: r >= 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted | |
| 260 | 추가: ); | |
| 261 | 추가: if Instant::now() > deadline { | |
| 262 | 추가: unsafe { | |
| 263 | 추가: kill(pid as i32, 9); | |
| 264 | 추가: wait4(pid as i32, &mut status, 0, &mut usage); | |
| 265 | 추가: } | |
| 266 | 추가: panic!("worker timeout"); | |
| 267 | 추가: } | |
| 268 | 추가: std::thread::sleep(Duration::from_millis(10)); | |
| 269 | 추가: } | |
| 270 | 추가: } | |
| 271 | 추가: fn events(s: &Scratch) -> Vec<Message> { | |
| 272 | 추가: assert!(fs::read(s.0.join("stderr")).unwrap().is_empty()); | |
| 273 | 추가: let mut reader = Reader::new(File::open(s.0.join("events")).unwrap()); | |
| 274 | 추가: let mut result = Vec::new(); | |
| 275 | 추가: while let Some((_, _, message)) = reader.read().unwrap() { | |
| 276 | 추가: result.push(message); | |
| 277 | 추가: } | |
| 278 | 추가: result | |
| 279 | 추가: } | |
| 280 | 추가: fn shim(s: &Scratch) -> PathBuf { | |
| 281 | 추가: let path = s.0.join("io_fault.so"); | |
| 282 | 추가: assert!( | |
| 283 | 추가: Command::new("cc") | |
| 284 | 추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"]) | |
| 285 | 추가: .arg( | |
| 286 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 287 | 추가: .join("../../tests/rust-archive-worker/io_fault.c") | |
| 288 | 추가: ) | |
| 289 | 추가: .arg("-ldl") | |
| 290 | 추가: .arg("-o") | |
| 291 | 추가: .arg(&path) | |
| 292 | 추가: .status() | |
| 293 | 추가: .unwrap() | |
| 294 | 추가: .success() | |
| 295 | 추가: ); | |
| 296 | 추가: path | |
| 297 | 추가: } | |
| 298 | 추가: #[test] | |
| 299 | 추가: fn gigabyte_formats_stay_below_64_mib_peak_rss() { | |
| 300 | 추가: let mut measurements = Vec::new(); | |
| 301 | 추가: for kind in ["store", "deflate", "tar", "gzip", "targz"] { | |
| 302 | 추가: let s = Scratch::new(); | |
| 303 | 추가: generate(&s, kind, 1024 * 1024 * 1024); | |
| 304 | 추가: let request = start(&s, kind == "gzip", Limits::default().output); | |
| 305 | 추가: let child = spawn(&s, request, None); | |
| 306 | 추가: let (status, rss) = wait(child.id()); | |
| 307 | 추가: assert_eq!(status, 0, "{kind}"); | |
| 308 | 추가: let events = events(&s); | |
| 309 | 추가: assert_eq!( | |
| 310 | 추가: terminal(&events).outcome, | |
| 311 | 추가: Outcome::Completed, | |
| 312 | 추가: "{kind}: {events:?}" | |
| 313 | 추가: ); | |
| 314 | 추가: assert_eq!(terminal(&events).publication, Publication::Complete); | |
| 315 | 추가: assert!(rss <= 64 * 1024 * 1024, "{kind}: RSS {rss}"); | |
| 316 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024); | |
| 317 | 추가: measurements.push(format!("{kind}: {rss}")); | |
| 318 | 추가: } | |
| 319 | 추가: println!( | |
| 320 | 추가: "1 GiB extraction peak RSS bytes: {}", | |
| 321 | 추가: measurements.join(", ") | |
| 322 | 추가: ); | |
| 323 | 추가: fs::write( | |
| 324 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/ci/streaming-rss.log"), | |
| 325 | 추가: measurements.join("\n") + "\n", | |
| 326 | 추가: ) | |
| 327 | 추가: .unwrap(); | |
| 328 | 추가: } | |
| 329 | 추가: #[test] | |
| 330 | 추가: fn enospc_at_create_or_after_partial_write_cleans_output() { | |
| 331 | 추가: for mode in ["create-full", "full", "stage-full"] { | |
| 332 | 추가: let s = Scratch::new(); | |
| 333 | 추가: generate(&s, "store", 1024 * 1024); | |
| 334 | 추가: fs::write(s.0.join("preserve"), b"original").unwrap(); | |
| 335 | 추가: let request = start(&s, false, Limits::default().output); | |
| 336 | 추가: let child = spawn(&s, request, Some(mode)); | |
| 337 | 추가: assert_eq!(wait(child.id()).0, 0); | |
| 338 | 추가: let events = events(&s); | |
| 339 | 추가: let t = terminal(&events); | |
| 340 | 추가: assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}"); | |
| 341 | 추가: assert_eq!(t.publication, Publication::None); | |
| 342 | 추가: assert_eq!(t.retained_partial_count, 0); | |
| 343 | 추가: assert_eq!(t.cleanup, Cleanup::Complete); | |
| 344 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 345 | 추가: assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original"); | |
| 346 | 추가: } | |
| 347 | 추가: } | |
| 348 | 추가: #[test] | |
| 349 | 추가: fn anonymous_tempfile_fallback_unlinks_before_use() { | |
| 350 | 추가: let s = Scratch::new(); | |
| 351 | 추가: generate(&s, "store", 1024 * 1024); | |
| 352 | 추가: let request = start(&s, false, Limits::default().output); | |
| 353 | 추가: let child = spawn(&s, request, Some("fallback")); | |
| 354 | 추가: assert_eq!(wait(child.id()).0, 0); | |
| 355 | 추가: let events = events(&s); | |
| 356 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 357 | 추가: assert!(s.0.join("paused").exists()); | |
| 358 | 추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0); | |
| 359 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024); | |
| 360 | 추가: } | |
| 361 | 추가: struct Subreaper(i32); | |
| 362 | 추가: impl Subreaper { | |
| 363 | 추가: fn new() -> Self { | |
| 364 | 추가: let mut old = 0; | |
| 365 | 추가: assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0); | |
| 366 | 추가: assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0); | |
| 367 | 추가: Self(old) | |
| 368 | 추가: } | |
| 369 | 추가: } | |
| 370 | 추가: impl Drop for Subreaper { | |
| 371 | 추가: fn drop(&mut self) { | |
| 372 | 추가: assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0); | |
| 373 | 추가: } | |
| 374 | 추가: } | |
| 375 | 추가: #[test] | |
| 376 | 추가: fn orphan_app_helper() { | |
| 377 | 추가: let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else { | |
| 378 | 추가: return; | |
| 379 | 추가: }; | |
| 380 | 추가: let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path))); | |
| 381 | 추가: let mut request = Start { | |
| 382 | 추가: action: Action::Extract { | |
| 383 | 추가: archive: s.path("input"), | |
| 384 | 추가: destination: s.path("output"), | |
| 385 | 추가: selection: Selection::All, | |
| 386 | 추가: list_id: None, | |
| 387 | 추가: gzip_output_name: None, | |
| 388 | 추가: }, | |
| 389 | 추가: limits: Limits::default(), | |
| 390 | 추가: }; | |
| 391 | 추가: if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() { | |
| 392 | 추가: request.limits = Limits { | |
| 393 | 추가: input: 64 * 1024 * 1024, | |
| 394 | 추가: output: 128 * 1024 * 1024, | |
| 395 | 추가: entries: 10000, | |
| 396 | 추가: }; | |
| 397 | 추가: } | |
| 398 | 추가: let mut cmd = command(); | |
| 399 | 추가: cmd.env("TMPDIR", staging(&s)) | |
| 400 | 추가: .stdin(Stdio::piped()) | |
| 401 | 추가: .stdout(File::create(s.0.join("events")).unwrap()) | |
| 402 | 추가: .stderr(File::create(s.0.join("stderr")).unwrap()) | |
| 403 | 추가: .env("LD_PRELOAD", s.0.join("io_fault.so")) | |
| 404 | 추가: .env("ZIPELO_TEST_FAULT", "pause") | |
| 405 | 추가: .env("ZIPELO_TEST_MARKER", s.0.join("paused")) | |
| 406 | 추가: .env("ZIPELO_TEST_RELEASE", s.0.join("release")); | |
| 407 | 추가: let mut child = cmd.spawn().unwrap(); | |
| 408 | 추가: fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap(); | |
| 409 | 추가: let mut writer = Writer::new(child.stdin.take().unwrap(), 17); | |
| 410 | 추가: writer.send(&Message::Start(request)).unwrap(); | |
| 411 | 추가: loop { | |
| 412 | 추가: std::thread::sleep(Duration::from_millis(20)); | |
| 413 | 추가: } | |
| 414 | 추가: } | |
| 415 | 추가: #[test] | |
| 416 | 추가: fn app_death_stops_worker_and_removes_partial_temp() { | |
| 417 | 추가: let _guard = Subreaper::new(); | |
| 418 | 추가: let s = Scratch::new(); | |
| 419 | 추가: generate(&s, "store", 1024 * 1024); | |
| 420 | 추가: let _ = start(&s, false, Limits::default().output); | |
| 421 | 추가: shim(&s); | |
| 422 | 추가: let mut helper = Command::new(std::env::current_exe().unwrap()) | |
| 423 | 추가: .args([ | |
| 424 | 추가: "--exact", | |
| 425 | 추가: "hardening::linux::orphan_app_helper", | |
| 426 | 추가: "--nocapture", | |
| 427 | 추가: ]) | |
| 428 | 추가: .env("ZIPELO_TEST_APP_HELPER", &s.0) | |
| 429 | 추가: .stdout(Stdio::null()) | |
| 430 | 추가: .stderr(Stdio::null()) | |
| 431 | 추가: .spawn() | |
| 432 | 추가: .unwrap(); | |
| 433 | 추가: let deadline = Instant::now() + Duration::from_secs(20); | |
| 434 | 추가: while !s.0.join("paused").exists() { | |
| 435 | 추가: if Instant::now() > deadline { | |
| 436 | 추가: helper.kill().unwrap(); | |
| 437 | 추가: helper.wait().unwrap(); | |
| 438 | 추가: if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) { | |
| 439 | 추가: unsafe { | |
| 440 | 추가: kill(pid.parse().unwrap(), 9); | |
| 441 | 추가: } | |
| 442 | 추가: wait(pid.trim().parse().unwrap()); | |
| 443 | 추가: } | |
| 444 | 추가: panic!("worker did not reach publication"); | |
| 445 | 추가: } | |
| 446 | 추가: std::thread::sleep(Duration::from_millis(10)); | |
| 447 | 추가: } | |
| 448 | 추가: let pid = fs::read_to_string(s.0.join("worker.pid")) | |
| 449 | 추가: .unwrap() | |
| 450 | 추가: .parse::<u32>() | |
| 451 | 추가: .unwrap(); | |
| 452 | 추가: helper.kill().unwrap(); | |
| 453 | 추가: helper.wait().unwrap(); | |
| 454 | 추가: fs::write(s.0.join("release"), b"").unwrap(); | |
| 455 | 추가: assert_eq!(wait(pid).0, 0); | |
| 456 | 추가: let events = events(&s); | |
| 457 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}"); | |
| 458 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 459 | 추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete); | |
| 460 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 461 | 추가: } | |
| 462 | 추가: } |
| @@ -0,0 +1,97 @@ | ||
| 1 | 추가: """공용 생성기의 고정 버퍼를 재사용해 스트리밍 회귀 표본을 만듦.""" | |
| 2 | 추가: import gzip | |
| 3 | 추가: import importlib.util | |
| 4 | 추가: from pathlib import Path | |
| 5 | 추가: import sys | |
| 6 | 추가: import struct | |
| 7 | 추가: import io | |
| 8 | 추가: import tarfile | |
| 9 | 추가: import zipfile | |
| 10 | 추가: | |
| 11 | 추가: spec = importlib.util.spec_from_file_location( | |
| 12 | 추가: "large_fixtures", Path(__file__).resolve().parents[1] / "large-archive-fixtures/generate.py" | |
| 13 | 추가: ) | |
| 14 | 추가: fixtures = importlib.util.module_from_spec(spec) | |
| 15 | 추가: spec.loader.exec_module(fixtures) | |
| 16 | 추가: | |
| 17 | 추가: | |
| 18 | 추가: def generate(directory, kind, size): | |
| 19 | 추가: directory = Path(directory) | |
| 20 | 추가: output = directory / "input" | |
| 21 | 추가: if kind.startswith("central64"): | |
| 22 | 추가: data = io.BytesIO() | |
| 23 | 추가: with zipfile.ZipFile(data, "w", compression=zipfile.ZIP_STORED) as archive: | |
| 24 | 추가: archive.writestr(fixtures.NAME, bytes(size)) | |
| 25 | 추가: original = data.getvalue() | |
| 26 | 추가: end = original[-22:] | |
| 27 | 추가: central_at = struct.unpack_from("<I", end, 16)[0] | |
| 28 | 추가: central = bytearray(original[central_at:-22]) | |
| 29 | 추가: name_len = struct.unpack_from("<H", central, 28)[0] | |
| 30 | 추가: struct.pack_into("<III", central, 16, struct.unpack_from("<I", central, 16)[0], 0xffffffff, 0xffffffff) | |
| 31 | 추가: struct.pack_into("<H", central, 30, 28) | |
| 32 | 추가: struct.pack_into("<I", central, 42, 0xffffffff) | |
| 33 | 추가: declared = (1 << 64) - 1 if kind == "central64-size-overflow" else size | |
| 34 | 추가: offset = (1 << 64) - 1 if kind == "central64-offset-overflow" else 0 | |
| 35 | 추가: central = central[:46 + name_len] + struct.pack("<HHQQQ", 1, 24, declared, size, offset) | |
| 36 | 추가: directory = original[:central_at] + central | |
| 37 | 추가: record = struct.pack("<4sQHHIIQQQQ", b"PK\x06\x06", 44, 45, 45, 0, 0, 1, 1, len(central), central_at) | |
| 38 | 추가: locator = struct.pack("<4sIQI", b"PK\x06\x07", 0, len(directory), 1) | |
| 39 | 추가: end = struct.pack("<4sHHHHIIH", b"PK\x05\x06", 0, 0, 65535, 65535, 0xffffffff, 0xffffffff, 0) | |
| 40 | 추가: output.write_bytes(directory + record + locator + end) | |
| 41 | 추가: if kind == "central64": | |
| 42 | 추가: with zipfile.ZipFile(output) as reference: | |
| 43 | 추가: assert reference.read(fixtures.NAME) == bytes(size) | |
| 44 | 추가: elif kind == "descriptor64": | |
| 45 | 추가: class Pipe(io.BytesIO): | |
| 46 | 추가: def seekable(self): | |
| 47 | 추가: return False | |
| 48 | 추가: def seek(self, *args): | |
| 49 | 추가: raise io.UnsupportedOperation() | |
| 50 | 추가: data = Pipe() | |
| 51 | 추가: with zipfile.ZipFile(data, "w", compression=zipfile.ZIP_STORED) as archive: | |
| 52 | 추가: with archive.open(fixtures.NAME, "w", force_zip64=True) as target: | |
| 53 | 추가: target.write(bytes(size)) | |
| 54 | 추가: output.write_bytes(data.getvalue()) | |
| 55 | 추가: with zipfile.ZipFile(output) as reference: | |
| 56 | 추가: assert reference.read(fixtures.NAME) == bytes(size) | |
| 57 | 추가: elif kind == "gzip-bomb-joined": | |
| 58 | 추가: with output.open("xb") as raw: | |
| 59 | 추가: for level in (6, 0): | |
| 60 | 추가: with gzip.GzipFile(fileobj=raw, mode="wb", compresslevel=level, mtime=0) as target: | |
| 61 | 추가: source = fixtures.ZeroStream(size) | |
| 62 | 추가: while chunk := source.read(fixtures.CHUNK): | |
| 63 | 추가: target.write(chunk) | |
| 64 | 추가: elif kind == "store": | |
| 65 | 추가: fixtures.write_zip(output, size, False) | |
| 66 | 추가: elif kind in ("deflate", "bomb", "zip64"): | |
| 67 | 추가: info = zipfile.ZipInfo(fixtures.NAME) | |
| 68 | 추가: info.file_size = size | |
| 69 | 추가: info.compress_type = zipfile.ZIP_DEFLATED | |
| 70 | 추가: info._compresslevel = 6 if kind == "bomb" else 1 | |
| 71 | 추가: with zipfile.ZipFile(output, "x") as archive: | |
| 72 | 추가: with archive.open(info, "w", force_zip64=(kind == "zip64")) as target: | |
| 73 | 추가: source = fixtures.ZeroStream(size) | |
| 74 | 추가: while chunk := source.read(fixtures.CHUNK): | |
| 75 | 추가: target.write(chunk) | |
| 76 | 추가: else: | |
| 77 | 추가: with output.open("xb") as raw: | |
| 78 | 추가: if kind == "tar": | |
| 79 | 추가: target = raw | |
| 80 | 추가: else: | |
| 81 | 추가: target = gzip.GzipFile(filename="", fileobj=raw, mode="wb", compresslevel=1, mtime=0) | |
| 82 | 추가: if kind in ("tar", "targz"): | |
| 83 | 추가: info = tarfile.TarInfo(fixtures.NAME) | |
| 84 | 추가: info.size = size | |
| 85 | 추가: info.mode = 0o600 | |
| 86 | 추가: target.write(info.tobuf(format=tarfile.USTAR_FORMAT)) | |
| 87 | 추가: source = fixtures.ZeroStream(size) | |
| 88 | 추가: while chunk := source.read(fixtures.CHUNK): | |
| 89 | 추가: target.write(chunk) | |
| 90 | 추가: if kind in ("tar", "targz"): | |
| 91 | 추가: target.write(bytes((-size) % 512 + 1024)) | |
| 92 | 추가: if target is not raw: | |
| 93 | 추가: target.close() | |
| 94 | 추가: | |
| 95 | 추가: | |
| 96 | 추가: if __name__ == "__main__": | |
| 97 | 추가: generate(sys.argv[1], sys.argv[2], int(sys.argv[3])) |
| @@ -0,0 +1,85 @@ | ||
| 1 | 추가: #define _GNU_SOURCE | |
| 2 | 추가: #include <dlfcn.h> | |
| 3 | 추가: #include <errno.h> | |
| 4 | 추가: #include <fcntl.h> | |
| 5 | 추가: #include <stdarg.h> | |
| 6 | 추가: #include <stdlib.h> | |
| 7 | 추가: #include <string.h> | |
| 8 | 추가: #include <stdio.h> | |
| 9 | 추가: #include <unistd.h> | |
| 10 | 추가: | |
| 11 | 추가: static ssize_t (*real_write)(int, const void *, size_t); | |
| 12 | 추가: static int (*real_openat)(int, const char *, int, ...); | |
| 13 | 추가: static int (*real_open64)(const char *, int, ...); | |
| 14 | 추가: static int started; | |
| 15 | 추가: | |
| 16 | 추가: __attribute__((constructor)) static void initialize(void) { | |
| 17 | 추가: real_write = dlsym(RTLD_NEXT, "write"); | |
| 18 | 추가: real_openat = dlsym(RTLD_NEXT, "openat"); | |
| 19 | 추가: real_open64 = dlsym(RTLD_NEXT, "open64"); | |
| 20 | 추가: } | |
| 21 | 추가: | |
| 22 | 추가: static int output_file(int fd) { | |
| 23 | 추가: char link[64], path[4096]; | |
| 24 | 추가: snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); | |
| 25 | 추가: ssize_t count = readlink(link, path, sizeof(path) - 1); | |
| 26 | 추가: if (count < 0) return 0; | |
| 27 | 추가: path[count] = 0; | |
| 28 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 29 | 추가: if (fault && !strcmp(fault, "stage-full")) return strstr(path, "/#") && strstr(path, "(deleted)"); | |
| 30 | 추가: return strstr(path, "/.zipelo-") != NULL; | |
| 31 | 추가: } | |
| 32 | 추가: | |
| 33 | 추가: int openat(int fd, const char *path, int flags, ...) { | |
| 34 | 추가: mode_t mode = 0; | |
| 35 | 추가: if (flags & O_CREAT) { | |
| 36 | 추가: va_list args; | |
| 37 | 추가: va_start(args, flags); | |
| 38 | 추가: mode = va_arg(args, unsigned int); | |
| 39 | 추가: va_end(args); | |
| 40 | 추가: } | |
| 41 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 42 | 추가: if (fault && !strcmp(fault, "create-full") && !strncmp(path, ".zipelo-", 8)) { | |
| 43 | 추가: errno = ENOSPC; | |
| 44 | 추가: return -1; | |
| 45 | 추가: } | |
| 46 | 추가: return real_openat(fd, path, flags, mode); | |
| 47 | 추가: } | |
| 48 | 추가: | |
| 49 | 추가: int open64(const char *path, int flags, ...) { | |
| 50 | 추가: mode_t mode = 0; | |
| 51 | 추가: if ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE)) { | |
| 52 | 추가: va_list args; | |
| 53 | 추가: va_start(args, flags); | |
| 54 | 추가: mode = va_arg(args, unsigned int); | |
| 55 | 추가: va_end(args); | |
| 56 | 추가: } | |
| 57 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 58 | 추가: if (fault && !strcmp(fault, "fallback") && ((flags & O_TMPFILE) == O_TMPFILE)) { | |
| 59 | 추가: int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600); | |
| 60 | 추가: if (marker >= 0) close(marker); | |
| 61 | 추가: errno = EOPNOTSUPP; | |
| 62 | 추가: return -1; | |
| 63 | 추가: } | |
| 64 | 추가: return real_open64(path, flags, mode); | |
| 65 | 추가: } | |
| 66 | 추가: | |
| 67 | 추가: ssize_t write(int fd, const void *bytes, size_t count) { | |
| 68 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 69 | 추가: if (!fault || !output_file(fd)) return real_write(fd, bytes, count); | |
| 70 | 추가: if (!strcmp(fault, "full") || !strcmp(fault, "stage-full")) { | |
| 71 | 추가: if (!started++) return real_write(fd, bytes, count < 7 ? count : 7); | |
| 72 | 추가: errno = ENOSPC; | |
| 73 | 추가: return -1; | |
| 74 | 추가: } | |
| 75 | 추가: if (!strcmp(fault, "pause") && !started++) { | |
| 76 | 추가: const char *marker = getenv("ZIPELO_TEST_MARKER"); | |
| 77 | 추가: const char *release = getenv("ZIPELO_TEST_RELEASE"); | |
| 78 | 추가: int signal_fd = real_openat(AT_FDCWD, marker, O_CREAT | O_EXCL | O_WRONLY, 0600); | |
| 79 | 추가: if (signal_fd < 0) { errno = EIO; return -1; } | |
| 80 | 추가: close(signal_fd); | |
| 81 | 추가: for (int i = 0; i < 1000 && access(release, F_OK); i++) usleep(10000); | |
| 82 | 추가: if (access(release, F_OK)) { errno = EIO; return -1; } | |
| 83 | 추가: } | |
| 84 | 추가: return real_write(fd, bytes, count); | |
| 85 | 추가: } |
| @@ -1550,3 +1550,5 @@ fn seven_zip_reference_reader_accepts_synthetic_fixtures() { | ||
| 1550 | 1550 | .success() |
| 1551 | 1551 | ); |
| 1552 | 1552 | } |
| 1553 | 추가: | |
| 1554 | 추가: mod hardening; |
| @@ -0,0 +1,18 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: | |
| 3 | 추가: #[test] | |
| 4 | 추가: fn ratio_boundaries_do_not_overflow() { | |
| 5 | 추가: assert!(ratio(0, 0).is_ok()); | |
| 6 | 추가: assert_eq!(ratio(1, 0), Err(ErrorCode::Limit)); | |
| 7 | 추가: for compressed in [1, 17, 65536, 16 * 1024 * 1024] { | |
| 8 | 추가: assert!(ratio(compressed * 1000, compressed).is_ok()); | |
| 9 | 추가: assert_eq!( | |
| 10 | 추가: ratio(compressed * 1000 + 1, compressed), | |
| 11 | 추가: Err(ErrorCode::Limit) | |
| 12 | 추가: ); | |
| 13 | 추가: } | |
| 14 | 추가: assert!(ratio(u64::MAX, u64::MAX).is_ok()); | |
| 15 | 추가: assert!(ratio(u64::MAX, u64::MAX / 1000 + 1).is_ok()); | |
| 16 | 추가: assert_eq!(ratio(u64::MAX, u64::MAX / 1000), Err(ErrorCode::Limit)); | |
| 17 | 추가: assert_eq!(add(u64::MAX, 1), Err(ErrorCode::Integrity)); | |
| 18 | 추가: } |