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