Merge pull request #127 from Team-LJY/features/sevenzip-create
LZMA2 7z 생성과 형식 선택 지원
- 작성자
- LeeJunyoung
- 작성 시각
- 커밋
23eb52d0f31aae84929bdbd0d72481ba5b714133
변경된 파일 35개
+2,016-82변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1,90 @@ | ||
| 1 | 추가: # 7z 생성 설계와 작업자 계약안 | |
| 2 | 추가: | |
| 3 | 추가: 상태: frontend 계약 동의와 독립 설계 리뷰 뒤 공용 타입, 앱 화면과 backend 작성기를 구현했다. [앱 계약 승인](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732)과 [설계 리뷰](https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903282961)는 03ca5c5 기준이며 구현 승인을 뜻하지 않는다. 실제 작성기는 LZMA2/non-solid/비암호화를 처리하며 solid 또는 암호 요청만 질문과 파일 접근 전에 UnsupportedFeature로 끝낸다. Linux의 독립 7-Zip과 Zipelo 왕복 및 실패 시험은 수행했으며 Windows/Wayland 실제 생성 통합 검증과 구현 독립 리뷰는 남았다. [PLANS 8.9](PLANS.md#89-7z-만들기)와 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다. | |
| 4 | 추가: | |
| 5 | 추가: ## 1. 이번 지원 범위 | |
| 6 | 추가: | |
| 7 | 추가: - 생성 형식은 단일 .7z이고 기본 압축은 LZMA2다. 일반 파일, 한글을 포함한 UTF-8 상대 이름, 빈 파일과 모든 폴더 항목을 보존한다. 원본 폴더를 지정하면 그 이름 아래의 상대 구조를 보존한다. | |
| 8 | 추가: - non-solid로 고정한다. 데이터가 있는 파일마다 독립된 LZMA2 coder와 pack stream을 만들고 파일 사이에 사전을 공유하지 않는다. 파일을 골라 풀 때 선행 파일을 처리하지 않으며 여러 파일의 압축률 최적화는 후속 범위다. | |
| 9 | 추가: - 본문 암호화와 헤더 암호화는 지원하지 않는다. 파일명도 공개된다. 암호가 필요한 사용자는 기존 AES ZIP 생성을 사용한다. 7z를 선택한 상태에서 암호를 무시하거나 ZIP으로 바꾸어 저장하지 않는다. | |
| 10 | 추가: - solid, 암호화, 분할 생성, SFX, 기존 아카이브 수정, 필터 체인과 사용자 지정 사전/스레드/압축 등급은 이번 범위에서 제외한다. 링크와 특수 파일을 일반 파일로 변환하지 않는다. RAR 제외 결정을 유지한다. | |
| 11 | 추가: - 파일 내용과 상대 경로, 빈 파일/폴더 구조가 보존 대상이다. 원본 소유자, ACL, xattr와 모든 시각/실행 권한의 복원 및 생성 바이트의 재현성은 약속하지 않는다. | |
| 12 | 추가: | |
| 13 | 추가: ## 2. 라이브러리 선택과 고지 | |
| 14 | 추가: | |
| 15 | 추가: 선택안은 이미 고정된 lzma-rust2 =0.25.0을 유지하고 std,xz에 encoder 기능만 더하는 것이다. 이 구현에서 해당 기능을 활성화했으며 lockfile 패키지는 추가하지 않았다. 컨테이너는 아래의 좁은 7z 작성기를 자체 MIT 코드로 구현한다. 압축 알고리즘 자체를 새로 구현하거나 외부 7z 명령을 제품에서 호출하지 않는다. | |
| 16 | 추가: | |
| 17 | 추가: - [lzma-rust2 manifest](https://docs.rs/crate/lzma-rust2/latest/source/Cargo.toml.orig)는 열람 시 0.25.0, Apache-2.0을 명시한다. encoder 기능은 별도 전이 의존성이 없는 기능이며 Rust 인코더를 활성화한다. liblzma는 upstream 개발 의존성이므로 제품에 넣지 않는다. default-features=false와 기존 기능을 명시적으로 유지하며 optimization과 다중 스레드 작성기는 사용하지 않는다. [라이선스 원문](https://docs.rs/crate/lzma-rust2/latest/source/LICENSE)을 함께 확인했다. | |
| 18 | 추가: - [sevenz-rust2 manifest](https://docs.rs/crate/sevenz-rust2/latest/source/Cargo.toml.orig)는 열람 시 0.24.1, Apache-2.0이며 compress만 활성화하는 컨테이너 작성기 후보다. util의 경로 재귀 수집 대신 검증된 핸들을 넘겨야 한다. 이 버전은 lzma-rust2 0.23 계열을 요구하므로 현재 0.25.0과 중복될 수 있고 crc32fast 등도 추가된다. 넓은 작성기 대신 기존 입력/예산/취소 정책에 맞춘 작은 컨테이너를 우선 검토한다. 이는 크기나 성능을 측정해 얻은 결론은 아니다. | |
| 19 | 추가: - 기존 sevenz-rust는 후보에서 제외한다. [RUSTSEC-2026-0246](https://rustsec.org/advisories/RUSTSEC-2026-0246.html)은 유지보수 중단을, [RUSTSEC-2026-0245](https://rustsec.org/advisories/RUSTSEC-2026-0245.html)는 그 패키지의 해제 API 경로 이탈을 알린다. 이 권고는 이름이 다른 sevenz-rust2나 lzma-rust2의 취약점 유무를 판정하는 근거가 아니다. | |
| 20 | 추가: - 2026-11-14 OSV의 패키지/버전 조회는 권고를 반환하지 않았고 RustSec 패키지명 검색 결과도 없었다. 전체 최신 의존성 권고 DB 감사는 하지 않았다. 새 encoder 실행 시험은 아래 검증 범위를 따른다. 구현 PR에서 고정 버전과 실제 기능 트리의 RustSec 권고 적용 여부를 다시 확인하고 확인 불가 항목을 기록한다. 후보 선택만으로 취약점 부재나 배포 적합성을 선언하지 않는다. | |
| 21 | 추가: - 도입 PR에는 선택 이유와 정확한 활성 기능을 적는다. packaging/licenses.py의 실제 작업자 Cargo.lock 고지에 lzma-rust2의 버전, Apache 원문과 원문 해시가 포함되는지 회귀로 확인한다. encoder 추가 전후의 전이 의존성을 비교하고 새 원문이 빠지면 배포 검증을 실패시킨다. 고지 생성기의 공용 변경이 필요하면 담당 범위를 합의한 뒤 수정한다. 이 구현에서는 기존 패키지의 encoder 기능만 켰으며 실제 고지 원문과 해시 및 기능 제한 회귀를 실행한다. | |
| 22 | 추가: | |
| 23 | 추가: ## 3. 작성기와 헤더 | |
| 24 | 추가: | |
| 25 | 추가: - 입력 수집은 create_sources::Plan과 Source, 검증한 파일 핸들 및 spool::Snapshot을 재사용한다. 라이브러리에 원본 경로를 넘겨 다시 열거나 자체 디렉터리 탐색을 시키지 않는다. 원본은 읽기 전용으로 열며 사용자가 고른 출력 경로를 쓰기/자르기로 직접 열지 않는다. | |
| 26 | 추가: - 단일 스레드 Lzma2Writer를 사용하고 preset 1에서 사전을 1 MiB로 명시한다. 사용자 옵션으로 확대하지 않는다. 새 인코더는 이전 파일의 상태를 유지하지 않는다. [upstream 작성기와 메모리 추정 API](https://docs.rs/crate/lzma-rust2/latest/source/src/enc/lzma2_writer.rs)를 근거로 인코더 생성 전 추정치의 KiB를 checked 연산으로 바꾸고 32 MiB 이내인지 확인한다. 실제 RSS 목표와는 구분한다. | |
| 27 | 추가: - 시그니처/StartHeader와 CRC, PackInfo, UnpackInfo, SubStreamsInfo, FilesInfo 및 EOF의 비압축 NextHeader를 작성한다. LZMA2 coder ID는 0x21이며 실제 사전 설정과 맞는 속성을 쓴다. 각 데이터 스트림의 압축/원본 크기와 CRC32를 기록한다. CRC32는 이미 사용하는 zlib-rs를 재사용한다. 오프셋, 길이 합계와 헤더 길이는 u64 checked 연산으로 처리한다. | |
| 28 | 추가: - 파일명은 유효한 UTF-8 계획에서 UTF-16LE로 변환한다. 빈 파일/폴더에는 데이터 스트림을 만들지 않고 EmptyStream과 EmptyFile 구분 및 디렉터리 속성을 기록한다. 원본 파일이 없고 빈 폴더만 있는 묶음도 유효하게 작성한다. 빈 원본 목록 자체는 InvalidRequest로 거부한다. | |
| 29 | 추가: - [공식 7z 형식 안내](https://www.7-zip.org/7z.html)와 기존 seven_zip.rs 해독기가 처리하는 기본 구조만 사용한다. encoded header, external metadata, additional streams와 anti 항목은 생성하지 않는다. LZMA2 내부의 비압축 청크는 허용하지만 별도 Copy 압축 선택은 추가하지 않는다. | |
| 30 | 추가: - finish와 헤더 패치의 모든 오류를 반환하고 성공 여부를 Drop에 의존하지 않는다. 완성한 비공개 파일을 기존 7z 구조 검사기로 열어 시작/다음 헤더 CRC, 스트림 범위와 계획의 이름/종류/길이를 대조한 뒤 게시한다. 이 검사는 전체 payload를 다시 해독하는 무결성 검증을 뜻하지 않는다. 전체 해독과 원본 해시 대조는 아래 수용 시험에서 수행한다. | |
| 31 | 추가: - 지원 부분의 헤더를 직접 유지하는 비용은 남는다. 계약 동의 후 첫 구현에서 독립 도구의 기본/빈 항목 호환과 인코더 메모리/취소 경계를 먼저 검증한다. 통과하지 않으면 지원 범위를 몰래 바꾸지 않고 이 PR에서 후보 및 계약을 다시 협의한다. | |
| 32 | 추가: | |
| 33 | 추가: ## 4. 작업자와 앱 계약안 | |
| 34 | 추가: | |
| 35 | 추가: 현재 기준은 과거 C# 문서가 아닌 [작업자 README](../experiments/rust-archive-worker/README.md), protocol.rs, wire.rs와 contract.json이다. 아래 확장 계약은 합의되었고 공용 타입과 바이트 인코딩은 반영했다. 작업자와 앱 연동의 구현 상태는 위 상태 및 contract.json의 seven_zip_create.status로 구분한다. | |
| 36 | 추가: | |
| 37 | 추가: ### 요청과 바이트 순서 | |
| 38 | 추가: | |
| 39 | 추가: - Action과 ActionKind 끝에 CreateSevenZip=4를 추가한다. List=0, Extract=1, CreateZip=2, Preview=3과 기존 Format::SevenZip=4는 유지한다. 프레임 ZAW1의 version=1, 32바이트 헤더, 1 MiB 본문 상한과 종류 번호는 바꾸지 않는다. | |
| 40 | 추가: - 새 action의 필드 순서는 sources:Vec<Source>, output_file:NativePath, method:SevenZipMethod, solid:bool, encryption:Encryption이다. Source는 기존 path:NativePath, archive_name:UTF-8 String 순서다. Vec/String의 u32 길이, 정수 little-endian과 NativePath 인코딩도 유지한다. sources와 NativePath 벡터의 기존 32,768개 상한, String의 32,768 UTF-8 바이트 상한과 전체 프레임 상한을 유지하며 자원 승인으로 전송 상한을 늘리지 않는다. | |
| 41 | 추가: - SevenZipMethod는 별도 u8 enum으로 Lzma2=0만 정의한다. ZIP의 Method(Store=0, Deflate=1)는 변경하지 않는다. solid의 지원 값은 false이고 encryption은 기존 None=0만 지원한다. 기존 Aes256=1과 solid=true를 구조상 유효한 요청으로 받더라도 Accepted 뒤 UnsupportedFeature로 끝내며, 원본 탐색, 자원 질문, 암호 질문과 출력 생성은 시작하지 않는다. 알 수 없는 enum/bool 값과 잔여 본문은 기존대로 Protocol이다. | |
| 42 | 추가: - 일반 Start(kind 1)와 StartGuarded(kind 6, interactive=false)에 허용한다. StartInteractive와 interactive=true에는 허용하지 않는다. 앱은 기본 생성 요청부터 기존 큰 작업 승인 경로인 StartGuarded를 사용한다. 제한을 낮추는 기존 Start 호출은 자원 질문 없이 유지한다. | |
| 43 | 추가: - output_file은 사용자가 고른 절대 파일 경로다. 형식은 action으로 결정하며 확장자로 ZIP 생성에 우회하지 않는다. 앱의 운영체제 기본 저장 창은 .7z 형식을 제안한다. 기존 목적지가 있으면 ZIP 생성과 같이 Conflict로 중단하며 이 단계에서는 덮어쓰기 질문/승인이나 자동 이름 변경을 추가하지 않는다. | |
| 44 | 추가: - 구버전 앱/작업자는 새 action을 거부할 수 있다. 앱과 작업자를 같은 빌드로 배포하고 실패 시 ZIP/일반 Start/다른 작업자에 자동 재시도하지 않는다. 계약 동의 뒤 공용 타입, codec, contract.json과 앱 변환을 함께 갱신한다. | |
| 45 | 추가: | |
| 46 | 추가: ### 이벤트와 완료 판단 | |
| 47 | 추가: | |
| 48 | 추가: - Accepted.action과 ResourceRequired.action에 CreateSevenZip=4를 사용한다. 이 action의 Accepted.encryption은 false다. 기존 ZIP 및 다른 action의 암호 capability 의미는 유지한다. 새 메시지, 오류 코드와 별도 대형 결과 전송은 추가하지 않는다. | |
| 49 | 추가: - 기존 ResourceRequired/Reply, Progress, Output, Cancel/CancelAck와 Terminal을 사용한다. 7z 생성에는 PasswordRequired와 ConflictRequired를 보내지 않는다. 질문 응답의 job_id/challenge_id/scope와 오래된 응답 거부 규칙을 유지한다. | |
| 50 | 추가: - Scan은 계획 수집, Read는 스냅샷 입력, Write는 인코딩/스테이징/목적지 복사, Verify는 헤더/계획 검사, Commit은 게시 단계다. 원본 합계가 확정되면 읽기의 total_bytes에 사용한다. 압축 결과 길이나 검증 총량을 모르면 None으로 두고 진행률을 추측하지 않는다. 단계별 바이트를 원본 크기에 중복 합산하지 않는다. | |
| 51 | 추가: - 정상 Output은 entry_id=None, relative_name=실제 목적지 기본 이름, disposition=Created 한 개다. 그 전에는 내부 파일마다 Output을 보내지 않는다. 정상 Terminal은 Completed, error=None, publication=Complete, created_count=1이며 정리 및 플랫폼 내구성은 실제 결과를 따른다. | |
| 52 | 추가: - 게시 전 실패/취소에는 정상 Output이 없어야 하며 publication=None, created_count=0이다. 작업 소유 목적지 임시 파일의 정리가 실패하면 기존 PartialRetained 및 retained_partial_count/cleanup으로 실제 이름을 보고한다. 게시 후 동기화/정리 실패와 불명확한 게시에는 기존 Failed, Uncertain/CommitUncertain 및 실제 출력 집계를 유지한다. 성공이나 파일 부재를 합성하지 않는다. | |
| 53 | 추가: - 앱은 일치하는 Terminal, stdout/stderr EOF와 소유 자식 회수를 모두 확인한 뒤 결과를 확정한다. CancelAck는 취소 완료가 아니며 게시 직전 cutoff 뒤의 TooLate와 실제 게시 결과를 우선한다. 작업자 사망이나 늦은 취소로 저장 완료를 취소 또는 자동 rollback으로 바꾸지 않는다. | |
| 54 | 추가: | |
| 55 | 추가: ## 5. 입력, 자원과 취소 | |
| 56 | 추가: | |
| 57 | 추가: - ZIP과 같은 원본 계획을 사용한다. 파일/폴더 모두 항목 수에 포함하며 파일 논리 바이트 합계에 min(limits.input,limits.output)을 적용한다. 기본은 16 GiB/10,000개, 유효한 자원 승인 뒤에는 요청한 ceiling 안에서 최대 64 GiB/200,000개다. 압축된 생성물 길이를 논리 원본 합계 대신 승인 기준으로 삼지 않는다. | |
| 58 | 추가: - 기존 64개 경로 구성 요소, 승인 전 8 MiB/32,768 노드 및 승인 뒤 64 MiB/262,144 노드 메타데이터 예산을 유지한다. UTF-16 이름, 스트림 정보, CRC와 오프셋 배열 및 헤더 버퍼도 할당 전에 예산에 반영한다. 입력 전체나 파일 전체를 메모리 배열에 담지 않고 현재 파일만 64 KiB 이하로 복사한다. | |
| 59 | 추가: - Plan의 경로 안전, 이름/접두 경로 및 대소문자 충돌, 원본 객체/종류/크기/수정 시각 대조를 재사용한다. 심볼릭 링크, reparse point, 특수 파일과 안전하지 않은 이름은 전체 작업을 거부한다. 탐색 뒤 교체와 감지된 변경은 SourceChanged다. 전체 폴더 트리의 원자적 스냅샷이나 같은 길이/시각으로 위장한 모든 변경 감지를 약속하지 않는다. | |
| 60 | 추가: - 원본 사본, 압축 결과와 게시용 복사본의 동시 공간을 볼륨별로 계산한다. LZMA2 청크는 최소 1바이트의 원본당 최대 3바이트 순증과 종료 1바이트를 허용하는 4*길이+1의 보수적 상한을 checked 연산으로 검사하고 각 실제 쓰기 전에도 여유 공간을 확인한다. 사전 확인은 공간 예약이 아니며 ENOSPC는 DiskFull, 그 밖의 저장 오류는 Io로 유지한다. 생성물 및 디스크 공간을 원본 바이트 예산과 혼동하지 않는다. | |
| 61 | 추가: - 승인 전 전체 300초, 승인 뒤 실제 진행이 없는 60초와 질문 응답 대기 300초 정책을 유지한다. 성공한 읽기/압축 쓰기/헤더 처리/계획 검증과 정리만 실제 활동으로 기록한다. 단순 check나 UI 알림으로 시간을 연장하지 않는다. | |
| 62 | 추가: - 입력 청크, 인코더 출력, 파일 경계, finish 전후, 헤더 seek/패치와 게시 직전에 취소 및 부모 생존을 확인한다. 압축 출력 Writer에도 감시기를 연결해 라이브러리 내부 쓰기 오류의 원인을 보존한다. 단일 스레드 인코더 한 호출 안의 CPU 처리와 OS 블로킹 I/O를 즉시 강제 중단한다고 보장하지 않는다. 부모/취소 확인 간격과 작은 파일 다수의 응답성도 시험한다. | |
| 63 | 추가: - 1 MiB 사전의 대표 1 GiB 표본에서 기존 64 MiB 피크 RSS 목표를 측정한다. 큰 작업 허용은 인코더 사전/스레드를 늘리는 승인이 아니며 프로세스 전체 메모리의 강제 상한을 뜻하지 않는다. | |
| 64 | 추가: | |
| 65 | 추가: ## 6. 저장과 정리 | |
| 66 | 추가: | |
| 67 | 추가: 1. 목적지 부모를 기존 Dir로 고정하고 경로/기존 목적지를 사전 검사한다. 원본과 같은 이름, 기존 파일/링크에는 쓰지 않는다. | |
| 68 | 추가: 2. 원본 계획과 소스 스냅샷을 만들고 비공개 spool 임시 파일에 완성된 7z를 작성한다. finish, 구조 검사와 Plan::verify가 실패하면 게시하지 않는다. | |
| 69 | 추가: 3. 완성 길이에 맞춰 목적지 공간을 확인하고 기존 publish_reader_steps의 새 파일 경로(replace=None)에 전달한다. 파일 sync와 close 오류를 확인한 뒤 배타적으로 게시한다. 사전검사 뒤 나타난 목적지도 Conflict로 거부한다. | |
| 70 | 추가: 4. 게시 직전에도 계획과 취소를 확인한다. 원본 폴더 안에 저장할 때는 게시 임시 파일 부모의 객체 ID를 계획과 대조하고, 그 폴더만 수정 시각 대신 원래 자식 목록을 다시 확인한다. 원래 목록은 탐색 때 이미 예산에 반영한 이름을 보존한다. 게시자가 열린 파일에서 기록한 정확한 임시 이름과 객체 ID 하나만 제외하며, 같은 접두 이름의 사용자 파일, 원본 추가/누락/이름 변경과 기존 항목의 객체/종류/크기/수정 시각 변경은 거부한다. 열거 전후 폴더 시각이 바뀌어도 거부한다. 확인과 게시 사이의 원자적 트랜잭션이나 잠깐 추가됐다 사라진 항목까지 감지한다고 약속하지 않는다. 게시 후 부모 sync와 정리 결과를 실제 내구성/부분 출력으로 보고한다. 불명확한 결과를 덮어 재시도하지 않는다. | |
| 71 | 추가: 5. 비공개 입력/생성물은 핸들을 닫아 제거하고 목적지 임시 파일만 기존 소유 확인 정책으로 정리한다. 무관한 파일이나 이미 게시한 파일을 삭제하지 않는다. 강제 종료/전원 손실 뒤 자동 정리까지 보장하지 않는다. | |
| 72 | 추가: | |
| 73 | 추가: ## 7. 구현 후 수용 시험 | |
| 74 | 추가: | |
| 75 | 추가: 아래는 수용 시험 기준이다. Linux에서 새 정수/비트맵과 인코딩 경계, 독립 7-Zip 26.00/Zipelo의 한글/보조 평면 이름 및 빈 구조 왕복, 취소/쓰기/finish/헤더 seek와 패치/게시 실패를 검증했다. 1 GiB 대표 생성은 11,168 KiB RSS와 약 20.8초를 기록했다. 이는 단일 표본 측정이며 모든 입력의 성능이나 OS 강제 상한이 아니다. 전체 local, 라이선스 시험과 플랫폼별 수행 결과는 PR 본문과 tests/work/7zc의 로그를 따른다. 71aa755의 Windows/Wayland 실제 생성 통합은 PR 본문에 기록되어 있다. 내부 저장 오탐 수정 뒤의 GUI 실기는 재실행하지 않았으며 독립 재리뷰는 남았다. 시험 코드는 루트 tests/에만 두며 일회성 자료, 도구, 캐시와 로그는 tests/work/7zc 한 곳에 모은다. TMPDIR과 CARGO_TARGET_DIR을 그 하위에 명시하고 사본 안에 작업 폴더나 빌드 캐시를 다시 만들지 않는다. PR 병합/종료 뒤 담당자가 정리한다. | |
| 76 | 추가: | |
| 77 | 추가: - 일반 파일, 압축되는/난수 내용, 한글 및 여러 단계 경로, 혼합 파일/폴더, 빈 파일, 빈 폴더, 빈 폴더만 있는 묶음과 여러 최상위 원본을 만든다. Zipelo 목록/해제와 독립 7-Zip의 테스트/목록/해제를 각각 실행해 상대 경로, 항목 종류, 파일 크기와 SHA256을 원본 manifest와 대조한다. 압축 아카이브 바이트 자체의 일치는 요구하지 않는다. | |
| 78 | 추가: - 독립 설계 리뷰의 후속 기준으로 MainStreamsInfo/kEnd 계층, 32바이트 기준 NextHeaderOffset, 가변 UINT64와 고정 REAL_UINT64 구분을 확인한다. EmptyFile 비트 수는 전체 파일 수가 아닌 empty stream 수이며 혼합 빈 항목 7/8/9개와 정수 경계 127/128, 16383/16384를 포함한다. | |
| 79 | 추가: - 독립 도구의 상세 목록으로 LZMA2, non-solid와 비암호화를 확인한다. 헤더/스트림 CRC와 작은 경계, 64 KiB 경계, 4 GiB 크기/오프셋 인코딩 및 비압축 헤더 상한을 시험한다. 큰 수치는 축소 상한/메타데이터 표본 검증과 실제 대용량 실행을 구분한다. | |
| 80 | 추가: - 자원 기본/승인 경계, 거부와 취소, 파일/폴더 수 합산, 메타데이터 및 산술 오버플로, 위험 경로, 링크/특수 파일, 원본/부모 교체, 목적지 새 파일 출현과 기존 파일 보존을 검증한다. 파일 크기와 무관하게 큰 배열이 생기지 않는지 확인한다. | |
| 81 | 추가: - 캡처/압축/finish/헤더 패치/게시 직전 취소, 부모 종료, 임시/목적지 디스크 부족, write/seek/sync/close/게시/정리 실패를 주입한다. 게시 전에는 완성 파일이 없어야 하며 실패/취소를 Completed로 표시하지 않아야 한다. 게시 뒤 실패와 강제 종료에서는 실제 게시 및 정리 상태를 대조한다. | |
| 82 | 추가: - codec 양방향 및 잘린 본문/알 수 없는 tag/잔여 필드, solid/암호화 미지원, 암호/충돌 질문 부재, 구버전 거부의 무자동재시도, job/challenge/sequence/종료 중복과 EOF/자식 회수 오류를 시험한다. 기존 ZIP의 Store/Deflate/AES 생성과 해제는 회귀를 유지한다. | |
| 83 | 추가: - 최종 구현에서 python3 tests/ci/run_rust.py local 결과와 라이선스 고지 시험, 메모리/취소 근거를 PR 본문에 적는다. Linux 시험과 Windows 교차 빌드를 Windows 실제 실행과 구분한다. Windows와 Wayland의 기본 파일/폴더 선택, 형식 선택과 저장, 미지원 암호 안내, 큰 작업 허용, 취소와 실패 화면은 별도로 확인한다. | |
| 84 | 추가: | |
| 85 | 추가: ## 8. 합의와 담당 인계 | |
| 86 | 추가: | |
| 87 | 추가: - 하나는 이 계약과 backend 작성기, 공용 타입/codec 및 작업자 회귀를 담당한다. 히나타의 계약 동의와 카논의 설계 리뷰가 확인되어 공용 타입 인계 단계에 착수했다. 실제 작성기를 반영했으며 새 파일로 Windows/Wayland 통합 검증을 인계한다. | |
| 88 | 추가: - 계약 동의 뒤 공용 타입 반영 커밋을 히나타에게 전달한다. 히나타는 기존 생성 화면의 ZIP/7z 형식 선택, .7z 기본 저장 형식, 암호/방식 선택 제한, 새 ActionKind 변환과 수신 검증을 담당한다. 화면이 바뀌는 구현 PR에 --ui-scenario 목록/시험과 docs/ui-scenario-guide.md를 함께 갱신한다. 별도 디자인 변경이나 애니메이션을 추가하지 않는다. | |
| 89 | 추가: - 카논의 설계와 실패 경계 리뷰는 완료되었으며 구현 후 독립 7-Zip 호환 검증 및 재리뷰는 별도 요청한다. 도구 버전/옵션, 원본과 해제 manifest 및 플랫폼별 실행 범위를 남긴다. 도구를 제품에 번들하지 않는다. | |
| 90 | 추가: - 설계 문서의 정적 검토와 링크/공백 검사는 제품 빌드나 호환 검증이 아니다. 이번 backend 추가분은 UI 변경 없음이다. 같은 PR의 형식 선택과 시나리오는 이미 반영되었고 71aa755에서 Windows/Wayland 실제 파일 통합을 확인했다. 내부 저장 오탐 수정 뒤 독립 재리뷰가 끝날 때까지 초안을 유지한다. |
| @@ -181,3 +181,14 @@ Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전 | ||
| 181 | 181 | - split-source-changed: 목록 이후 조각 변경 시 다시 열기 안내. |
| 182 | 182 | |
| 183 | 183 | 운영체제 기본 열기 창에서 같은 폴더의 첫 조각 `.7z.001`을 선택한다. 분할 묶음은 최대 999개이며 목록 열람 성공은 전체 데이터 무결성 검증 완료를 뜻하지 않는다. 실제 분할 파일 처리는 작업자 구현 후 독립 도구 표본으로 확인한다. Windows와 Wayland에서 첫 조각 선택, 누락 이름, .001 재시도 안내와 닫기를 확인하며, 위 디자인 상황은 실제 파일 검증을 대신하지 않는다. |
| 184 | 추가: | |
| 185 | 추가: ## 7z 만들기 상황 | |
| 186 | 추가: | |
| 187 | 추가: - create-sevenzip: 기존 만들기 창의 ZIP/7z 선택, LZMA2 고정과 암호 미지원 안내. | |
| 188 | 추가: - create-sevenzip-progress: 7z 생성 진행과 취소 버튼. | |
| 189 | 추가: - create-sevenzip-complete: 7z 파일의 저장 완료와 실제 저장 경로. | |
| 190 | 추가: - create-sevenzip-error: 7z 저장 실패와 재시도. | |
| 191 | 추가: - create-sevenzip-cancelled: 게시 전 취소 완료와 출력 없음. | |
| 192 | 추가: - create-sevenzip-resource: 7z 생성의 큰 작업 허용 질문. | |
| 193 | 추가: | |
| 194 | 추가: 7z를 선택하면 입력한 ZIP 암호와 실행 취소 기록을 지우며, ZIP으로 돌아와도 암호를 복원하지 않는다. 기본 저장 창은 .7z를 제안하며 암호가 필요하면 ZIP을 선택한다. 이 상황들은 가짜 작업자로 화면을 구성하므로 실제 7z 생성과 독립 도구 호환 시험을 대신하지 않는다. |
| @@ -11,7 +11,7 @@ png = "=0.18.1" | ||
| 11 | 11 | zune-jpeg = { package = "zipelo-jpeg", path = "vendor/zune-jpeg", default-features = false, features = ["std"] } |
| 12 | 12 | zune-core = { version = "=0.5.3", default-features = false, features = ["std"] } |
| 13 | 13 | bzip2 = "=0.6.1" |
| 14 | 삭제: lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] } | |
| 14 | 추가: lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz", "encoder"] } | |
| 15 | 15 | aes = { version = "=0.8.4", features = ["zeroize"] } |
| 16 | 16 | hmac = "=0.12.1" |
| 17 | 17 | pbkdf2 = { version = "=0.12.2", default-features = false, features = ["hmac"] } |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # Rust archive worker |
| 2 | 2 | |
| 3 | 삭제: 별도 프로세스의 stdin/stdout으로 revision 3 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다. | |
| 3 | 추가: 별도 프로세스의 stdin/stdout으로 revision 3 요청을 처리합니다. 제품 앱이 공유 codec으로 연결하며 프로세스 분리는 OS sandbox를 뜻하지 않습니다. 기존 작업의 암호 기능은 capability=true이며 ZipCrypto 해제, WinZip AES-256 AE-1/AE-2 해제와 AE-2 생성을 지원합니다. | |
| 4 | 4 | |
| 5 | 5 | - ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다. |
| 6 | 6 | - ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다. |
| @@ -49,7 +49,7 @@ XZ의 헤더, 인덱스, 푸터 CRC와 역방향 크기 및 전체 선언 해제 | ||
| 49 | 49 | 의존성 선택 근거는 다음과 같습니다. |
| 50 | 50 | |
| 51 | 51 | - [bzip2 0.6.1](https://docs.rs/crate/bzip2/0.6.1/source/Cargo.toml)은 MIT OR Apache-2.0이며 기본 백엔드가 Rust 구현인 libbz2-rs-sys입니다. 고정 lockfile은 libbz2-rs-sys 0.2.6(bzip2-1.0.6 자유 라이선스)을 선택하고 Rust 할당자를 사용합니다. C 구현인 bzip2-sys 기능과 stdio/C 할당자는 활성화하지 않습니다. |
| 52 | 삭제: - [lzma-rust2 0.25.0](https://docs.rs/lzma-rust2/latest/lzma_rust2/struct.XzReader.html)은 Apache-2.0의 Rust 구현입니다. std와 xz만 활성화해 인코더와 다중 스레드 구현을 제외하고 사전 할당 전 메모리 제한을 적용합니다. CRC와 인덱스 레코드 개수를 검증하며 연결 스트림을 끝까지 읽습니다. 레코드별 크기는 작업자가 별도로 대조합니다. | |
| 52 | 추가: - [lzma-rust2 0.25.0](https://docs.rs/lzma-rust2/latest/lzma_rust2/struct.XzReader.html)은 Apache-2.0의 Rust 구현입니다. TAR.XZ에는 std와 xz를 사용하며 7z 생성을 위해 encoder도 활성화합니다. optimization 기본 기능은 끄고 사전 할당 전 메모리 제한을 적용합니다. CRC와 인덱스 레코드 개수를 검증하며 연결 스트림을 끝까지 읽습니다. 레코드별 크기는 작업자가 별도로 대조합니다. | |
| 53 | 53 | - 두 라이브러리와 새 전이 의존성의 원문은 Cargo 체크섬을 대조하는 기존 packaging/licenses.py가 고지에 자동 포함합니다. tests/release-packages/test_compressed_tar_licenses.py는 실제 고지에 세 압축 라이브러리의 원문과 해시가 포함되고 C 압축 백엔드가 없는지 확인합니다. |
| 54 | 54 | - 2026-11-13 [RUSTSEC-2023-0004](https://rustsec.org/advisories/RUSTSEC-2023-0004.html)의 bzip2 DoS 권고와 수정 범위(>=0.4.4)를 확인했습니다. 고정 lockfile의 bzip2 0.6.1은 수정 범위에 해당하므로 이 권고의 영향을 받지 않습니다. 새 전이 sha2 0.11.1은 RUSTSEC-2021-0100의 수정 범위(>=0.9.8)에 해당합니다. 전체 최신 DB 자동 감사와 취약점 부재를 보장하는 확인은 수행하지 않았습니다. |
| 55 | 55 | |
| @@ -69,6 +69,20 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 69 | 69 | |
| 70 | 70 | 7z의 Copy/LZMA/LZMA2 입력과 solid 출력은 고정 버퍼와 임시 파일로 처리합니다. 모든 폴더와 하위 스트림의 CRC와 크기 검증이 끝난 뒤 기존 게시 경로를 사용합니다. ZIP 생성의 압축 및 AES 처리도 64 KiB 버퍼를 사용하며 여유 공간 사전 검사와 실제 쓰기의 DiskFull 구분을 적용합니다. 공간 예약을 보장하지 않으므로 다른 프로세스와의 경쟁으로 쓰기가 실패할 수 있습니다. |
| 71 | 71 | |
| 72 | 추가: ## 7z 생성 | |
| 73 | 추가: | |
| 74 | 추가: [합의된 설계](../../docs/sevenzip-create-design.md)의 단일 .7z 작성을 구현했습니다. 압축 방식은 LZMA2, 1 MiB 사전과 non-solid이며 본문/헤더 암호화, 분할 생성과 SFX는 지원하지 않습니다. 원본 파일과 폴더, 한글 및 UTF-16 보조 평면 이름, 빈 파일과 빈 폴더를 보존합니다. RAR 제외 정책은 유지합니다. | |
| 75 | 추가: | |
| 76 | 추가: - Action과 ActionKind의 CreateSevenZip tag는 4입니다. 필드 순서는 sources:Vec<Source>, output_file:NativePath, method:SevenZipMethod, solid:bool, encryption:Encryption이며 SevenZipMethod는 Lzma2=0입니다. 기존 ZIP 태그/프레임은 유지합니다. Start 또는 StartGuarded(interactive=false)만 허용하며 전송 상한은 자원 승인으로 확대하지 않습니다. | |
| 77 | 추가: - Accepted.encryption=false입니다. solid=true 또는 Aes256은 Accepted 뒤 자원/암호/충돌 질문이나 파일 접근 전에 UnsupportedFeature로 끝납니다. 빈 원본 목록은 InvalidRequest입니다. ZIP이나 구버전으로 자동 우회하지 않습니다. | |
| 78 | 추가: - 기존 소스 계획과 검증한 핸들로 파일별 스냅샷을 캡처하고 독립 LZMA2 스트림을 만듭니다. 비압축 NextHeader와 CRC를 기록하고 기존 구조 검사기로 이름/종류/크기를 대조합니다. 계획의 메타데이터 예산에 UTF-16 헤더, 검증용 사본과 스트림 배열을 함께 반영합니다. 실제 payload 전체 해독은 수용 시험에서 별도로 수행합니다. | |
| 79 | 추가: - 기존 16 GiB/10,000개 및 승인 뒤 최대 64 GiB/200,000개 정책을 따르며 메타데이터 상한은 독립적입니다. 순차 복사 버퍼는 64 KiB이고 인코더 추정 메모리가 32 MiB를 넘으면 거부합니다. 파일별 패킹 상한은 upstream 청크 분기를 보수적으로 계산한 4*원본 길이+1이며 캡처와 새 패킹, 헤더의 동시 임시 공간을 사전 검사합니다. 압축되는 입력도 이 보수적 검사로 공간 부족이 될 수 있습니다. 실제 쓰기와 목적지 복사도 별도로 공간을 검사하며 공간을 예약하지는 않습니다. | |
| 80 | 추가: - finish와 헤더 seek/패치 오류를 전파하고 Drop으로 성공을 결정하지 않습니다. 게시용 복사/sync/close 뒤 실제 게시 직전에 원본 계획을 다시 확인하며 배타적 게시만 사용합니다. 기존 목적지나 사전 검사 뒤 나타난 파일은 보존합니다. 전체 폴더의 원자적 스냅샷이나 게시와 원본 재검증의 원자성을 보장하지 않습니다. | |
| 81 | 추가: - Scan/Read/Write/Verify/Commit 진행과 기존 취소, 부모 생존/시간 제한을 사용합니다. 인코더 출력에서도 취소를 확인하지만 단일 CPU 호출이나 블로킹 OS I/O를 즉시 중단하지는 않습니다. 생성물 하나의 Output Created와 Complete/created_count=1만 성공입니다. 게시 후 오류와 실제 내구성/정리 상태를 그대로 보고하며 앱은 Terminal, 양쪽 EOF와 자식 회수까지 확인합니다. | |
| 82 | 추가: - lzma-rust2 =0.25.0의 std,xz,encoder만 사용합니다. encoder 기능은 추가 전이 의존성이 없고 Apache-2.0 원문은 기존 packaging/licenses.py 고지에 포함합니다. tests/release-packages/test_compressed_tar_licenses.py에서 실제 원문과 해시, 고정 버전 및 기능을 확인합니다. 기본/optimization 기능과 liblzma 개발 의존성은 제품에 포함하지 않습니다. | |
| 83 | 추가: - 2026-11-14 OSV에 lzma-rust2 0.25.0을 조회했을 때 알려진 권고가 반환되지 않았습니다. RustSec 패키지명 검색도 결과가 없었으며 전체 의존성 감사나 취약점 부재를 뜻하지 않습니다. 정확한 질의와 결과는 PR의 검증 기록에 남깁니다. | |
| 84 | 추가: - tests/rust-archive-worker/seven_zip_create_fields.rs와 seven_zip_create_runtime.rs는 정수/비트맵/버퍼 경계, 원본/목적지 변경, 자원 승인, 취소와 저장 실패를 검사합니다. ZIPELO_TEST_7ZIP에 독립 7-Zip 실행 파일을 지정하면 실제 test/list/extract와 SHA256/구조 대조도 수행합니다. 도구를 지정하지 않은 실행은 독립 7-Zip 검증 근거가 아닙니다. 1 GiB 메모리 회귀는 Linux에서 실행합니다. Windows/Wayland 실제 생성 통합 검증과 독립 리뷰는 별도입니다. | |
| 85 | 추가: | |
| 72 | 86 | ## ZIP 생성 입력 |
| 73 | 87 | |
| 74 | 88 | 원본에 일반 파일과 폴더를 함께 지정할 수 있습니다. 각 archive_name을 최상위 이름으로 쓰고 폴더 안의 상대 경로와 빈 폴더를 보존합니다. 재귀 수집된 파일과 폴더 모두 항목 수 한도에 포함하며 파일 크기 합계에는 기존 16 GiB 기본 한도를 적용합니다. 이름 충돌과 한도는 암호 요청 전에 검사합니다. |
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | "archive_names": "Separate validated UTF-8 relative names; entry IDs are opaque ordinal u32, not paths." |
| 27 | 27 | }, |
| 28 | 28 | "commands": { |
| 29 | 삭제: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list.", | |
| 29 | 추가: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list. CreateSevenZip{sources:[Source{path:NativePath,archive_name:UTF8}],output_file:NativePath,method:SevenZipMethod,solid:bool,encryption:Encryption} appends action tag 4. Shared types, codec and the LZMA2 non-solid writer are implemented. Unsupported solid/encryption options fail after Accepted before file access or questions.", | |
| 30 | 30 | "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.", |
| 31 | 31 | "Cancel": "Matching header job_id and empty body; command header sequence identifies the request. See CancelAck. Request acceptance is separate from final outcome. EOF alone is not successful cancellation.", |
| 32 | 32 | "StartInteractive": "Kind 4, body identical to Start with action restricted to Extract. Exactly one initial Start or StartInteractive. Invalid non-Extract action is rejected by the shared encoder and decoder. Opt in to interactive regular-file conflicts; never retry through legacy Start or an older worker automatically. Worker runtime supports the agreed choices; client activation and native UI integration are verified separately.", |
| @@ -35,7 +35,7 @@ | ||
| 35 | 35 | "ResourceReply": "Kind 7: challenge_id:u64,scope:ResourceScope,allow:bool. Frame job_id and exact outstanding challenge_id/scope must match once. Reject premature, stale, duplicate and cross-kind replies as Protocol. False cancels the job without further processing." |
| 36 | 36 | }, |
| 37 | 37 | "events": { |
| 38 | 삭제: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.", | |
| 38 | 추가: "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation. CreateSevenZip explicitly reports encryption=false; existing action capabilities are unchanged.", | |
| 39 | 39 | "Entry": "entry_id, name, kind File|Directory|Link|Other, declared sizes, encrypted; ordinal u32 IDs belong to this List job only until its ListEnd token and Completed Terminal are confirmed. Metadata only, no CRC success claim.", |
| 40 | 40 | "ListEnd": "entry_count:u32 and list_id:ListId for a complete listing. Entry IDs are deterministic zero-based ordinals in archive traversal order. App associates this token with this job entries only after Completed Terminal, both stream EOFs and successful child wait/exit.", |
| 41 | 41 | "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.", |
| @@ -239,5 +239,33 @@ | ||
| 239 | 239 | "metadata": "Only after a valid ResourceReply(allow=true) for this job, select 64 MiB MetadataBudget and 262144 nodes, including ZIP/TAR/7z parsing, decoded 7z headers, XZ index/block bounds, member/path validation, implicit output parents and source planning. Legacy Start/StartInteractive, unapproved guarded jobs and slice APIs keep 8 MiB and 32768 nodes. Merely requesting expanded ceilings does not grant a larger budget. Names and source paths still consume checked byte budgets and implicit parents consume nodes, so long/deep paths can hit the metadata cap before 200000 entries. Approved source-path/pending-name copies consume bytes without duplicating their entry node. Expanded metadata jobs do not retain a universal 64 MiB RSS target.", |
| 240 | 240 | "client": "Normal app jobs use StartGuarded with the existing 16 GiB and 10000-entry limits. Known selection/file estimates request expanded ceilings before processing. After a Limit result, offer an explicit expanded retry only after Terminal, both EOFs and child reap, with Publication::None, zero created/partial counts and complete cleanup. Retry uses a new job ID and requires fresh approval; existing or uncertain output instead shows the saved location and detailed result. App output records, including implicit parent directories, grow to 262144 nodes after any valid resource approval. Catalog entries grow to 200000 only for jobs granted the entries scope. Unapproved output records and catalogs without an entries grant retain their existing 100000 caps. Resource approval, ratio, retry and partial-output UI scenarios, tests and docs/ui-scenario-guide.md are implemented. Native Windows/Wayland verification remains separate.", |
| 241 | 241 | "tests": "Use numeric 16/64 GiB and 10000/200000 policy boundaries, scaled worker limits, a compressed 257 MiB zero stream, and a virtual clock for the 60-second stall. Include client approval/retry tests in tests/rust-app-ui/guarded.rs and real-worker flows in tests/rust-app-real-worker/guarded_flows.rs. Do not write 64 GiB in tests." |
| 242 | 추가: }, | |
| 243 | 추가: "action_tags": { | |
| 244 | 추가: "List": 0, | |
| 245 | 추가: "Extract": 1, | |
| 246 | 추가: "CreateZip": 2, | |
| 247 | 추가: "Preview": 3, | |
| 248 | 추가: "CreateSevenZip": 4 | |
| 249 | 추가: }, | |
| 250 | 추가: "seven_zip_method_tags": { | |
| 251 | 추가: "Lzma2": 0 | |
| 252 | 추가: }, | |
| 253 | 추가: "seven_zip_create": { | |
| 254 | 추가: "status": "worker-implemented; frontend-integrated; real-file-native-integration-and-independent-review-pending", | |
| 255 | 추가: "agreement": { | |
| 256 | 추가: "frontend_message_id": "770f1004-0a2b-4fc6-aafd-7f705c8f6c9e", | |
| 257 | 추가: "frontend_review": "https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903269732", | |
| 258 | 추가: "design_review": "https://github.com/Team-LJY/zipelo/pull/127#pullrequestreview-5903282961" | |
| 259 | 추가: }, | |
| 260 | 추가: "request": "Append Action::CreateSevenZip and ActionKind::CreateSevenZip=4. Field order: sources:Vec<Source>,output_file:NativePath,method:SevenZipMethod(u8 Lzma2=0),solid:bool,encryption:Encryption(u8 None=0,Aes256=1). Source remains path:NativePath,archive_name:UTF8. Preserve ZIP Method Store=0,Deflate=1, all previous tags, frame version and fields.", | |
| 261 | 추가: "admission": "Start and StartGuarded(interactive=false) are valid. Shared encoder and decoder reject StartInteractive and guarded interactive=true. Sources, native path vectors and strings retain the 32768 item/UTF8-byte bounds and the 1 MiB frame bound even with an expanded ceiling. No automatic fallback to ZIP, Start or an older worker.", | |
| 262 | 추가: "options": "Target support is single-file .7z with LZMA2, non-solid and no body/header encryption. Structurally valid solid=true or Aes256 requests must fail UnsupportedFeature after Accepted, before source enumeration, resource/password/conflict questions or outputs. Unknown enum/bool tags and trailing fields are protocol errors.", | |
| 263 | 추가: "implementation_boundary": "LZMA2 non-solid creation is implemented. Shared source planning, 64 KiB snapshots and writes, private staging, checked header metadata and exclusive publication are used. Unsupported solid/encryption options fail before admission and file access. Native UI real-file integration and independent review remain separate.", | |
| 264 | 추가: "events": "Accepted.action and future ResourceRequired.action use tag 4; Accepted.encryption=false. Future writer reuses Progress Scan/Read/Write/Verify/Commit and guarded resource approval. Unknown totals remain None. No PasswordRequired or ConflictRequired. Exactly one normal Output Created for the published archive, entry_id=None and relative_name=actual destination leaf; not one Output per archive member.", | |
| 265 | 추가: "publication": "Future writer uses ZIP source planning, consistency checks, private file-backed staging and exclusive publication (replace=None). Existing or newly appeared destination returns Conflict without overwrite. Completed requires publication Complete and created_count=1. Prepublication failure/cancel has publication None and zero created/retained counts unless owned temporary cleanup actually failed. Preserve actual postpublication errors, durability, cleanup and uncertain state.", | |
| 266 | 추가: "lifecycle": "Reuse Cancel/CancelAck/Terminal and matching job/challenge/sequence validation. CancelAck is not completion; app requires Terminal, both stream EOFs and owned child wait. No synthetic rollback after publication.", | |
| 267 | 추가: "dependencies": "Existing lzma-rust2 =0.25.0 enables std,xz,encoder with default features disabled. No new lockfile package; encoder=[] adds no transitive dependency. Apache-2.0 originals and hashes are checked through packaging/licenses.py. OSV query on 2026-11-14 returned no advisory for this package/version; this is not a full dependency audit or a vulnerability-free claim.", | |
| 268 | 추가: "design": "docs/sevenzip-create-design.md", | |
| 269 | 추가: "validation": "Round-trip SHA256 and structure in Zipelo and independent 7-Zip 26.00 with ZIPELO_TEST_7ZIP set; 1 GiB creation RSS regression; cancellation, metadata/byte limits, encoder finish/header write/seek/patch failures, destination write/sync and postpublication sync failures. Results and platform limits are recorded in PR127." | |
| 242 | 270 | } |
| 243 | 271 | } |
| @@ -53,6 +53,9 @@ impl MetadataBudget { | ||
| 53 | 53 | self.nodes = nodes; |
| 54 | 54 | Ok(()) |
| 55 | 55 | } |
| 56 | 추가: pub(crate) fn charge_bytes(&mut self, bytes: usize, limits: MetadataLimits) -> Result<()> { | |
| 57 | 추가: self.charge_cost(bytes, 0, limits) | |
| 58 | 추가: } | |
| 56 | 59 | pub(crate) fn charge(&mut self, name: &str) -> Result<()> { |
| 57 | 60 | self.charge_with(name, MetadataLimits::default()) |
| 58 | 61 | } |
| @@ -180,6 +180,7 @@ pub(super) struct Planned { | ||
| 180 | 180 | path: PathBuf, |
| 181 | 181 | object: SourceObject, |
| 182 | 182 | modified: Option<SystemTime>, |
| 183 | 추가: children: Vec<String>, | |
| 183 | 184 | } |
| 184 | 185 | impl Planned { |
| 185 | 186 | pub fn open(&self) -> Result<Input> { |
| @@ -196,6 +197,56 @@ impl Planned { | ||
| 196 | 197 | && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory) |
| 197 | 198 | && (metadata.is_dir() || metadata.len() == self.member.entry.size)) |
| 198 | 199 | } |
| 200 | 추가: fn verify_with_temporary( | |
| 201 | 추가: &self, | |
| 202 | 추가: temporary: &filesystem::PublicationTemp, | |
| 203 | 추가: check: &mut impl crate::resources::Monitor, | |
| 204 | 추가: ) -> Result<()> { | |
| 205 | 추가: let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 206 | 추가: let before = input.file.metadata().map_err(crate::space::io_error)?; | |
| 207 | 추가: if !before.is_dir() || filesystem::object(&input.file)? != self.object { | |
| 208 | 추가: return Err(ErrorCode::SourceChanged); | |
| 209 | 추가: } | |
| 210 | 추가: // 게시 임시 파일의 부모만 시각 대신 원래 항목과 소유 객체를 대조함. | |
| 211 | 추가: let mut count = 0; | |
| 212 | 추가: let mut found = false; | |
| 213 | 추가: for entry in input.children(&self.path)? { | |
| 214 | 추가: check.check()?; | |
| 215 | 추가: let name = entry.map_err(crate::space::io_error)?.file_name(); | |
| 216 | 추가: let name = name.to_str().ok_or(ErrorCode::SourceChanged)?; | |
| 217 | 추가: if name == temporary.name { | |
| 218 | 추가: let child = input | |
| 219 | 추가: .open_child(&self.path, name) | |
| 220 | 추가: .map_err(|_| ErrorCode::SourceChanged)?; | |
| 221 | 추가: if found | |
| 222 | 추가: || !child | |
| 223 | 추가: .file | |
| 224 | 추가: .metadata() | |
| 225 | 추가: .map_err(crate::space::io_error)? | |
| 226 | 추가: .is_file() | |
| 227 | 추가: || filesystem::object(&child.file)? != temporary.object | |
| 228 | 추가: { | |
| 229 | 추가: return Err(ErrorCode::SourceChanged); | |
| 230 | 추가: } | |
| 231 | 추가: found = true; | |
| 232 | 추가: } else if self | |
| 233 | 추가: .children | |
| 234 | 추가: .binary_search_by(|leaf| leaf.as_str().cmp(name)) | |
| 235 | 추가: .is_ok() | |
| 236 | 추가: { | |
| 237 | 추가: count += 1; | |
| 238 | 추가: } else { | |
| 239 | 추가: return Err(ErrorCode::SourceChanged); | |
| 240 | 추가: } | |
| 241 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 242 | 추가: } | |
| 243 | 추가: let after = input.file.metadata().map_err(crate::space::io_error)?; | |
| 244 | 추가: if !found || count != self.children.len() || before.modified().ok() != after.modified().ok() | |
| 245 | 추가: { | |
| 246 | 추가: return Err(ErrorCode::SourceChanged); | |
| 247 | 추가: } | |
| 248 | 추가: Ok(()) | |
| 249 | 추가: } | |
| 199 | 250 | } |
| 200 | 251 | pub(super) struct Plan { |
| 201 | 252 | pub items: Vec<Planned>, |
| @@ -283,6 +334,7 @@ impl Plan { | ||
| 283 | 334 | None, |
| 284 | 335 | )?; |
| 285 | 336 | crate::resources::completed(Ok(()), check)?; |
| 337 | 추가: let index = self.items.len(); | |
| 286 | 338 | self.items.push(Planned { |
| 287 | 339 | member: Member { |
| 288 | 340 | entry: Entry { |
| @@ -302,6 +354,7 @@ impl Plan { | ||
| 302 | 354 | path: path.clone(), |
| 303 | 355 | object: crate::resources::completed(filesystem::object(&input.file), check)?, |
| 304 | 356 | modified: metadata.modified().ok(), |
| 357 | 추가: children: Vec::new(), | |
| 305 | 358 | }); |
| 306 | 359 | if directory { |
| 307 | 360 | let mut children = Vec::new(); |
| @@ -328,13 +381,21 @@ impl Plan { | ||
| 328 | 381 | crate::resources::completed(Ok(()), check)?; |
| 329 | 382 | } |
| 330 | 383 | children.sort(); |
| 331 | 삭제: for leaf in children { | |
| 332 | 삭제: let child = crate::resources::completed(input.open_child(&path, &leaf), check)?; | |
| 333 | 삭제: self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?; | |
| 384 | 추가: for leaf in &children { | |
| 385 | 추가: let child = crate::resources::completed(input.open_child(&path, leaf), check)?; | |
| 386 | 추가: self.visit(path.join(leaf), format!("{name}/{leaf}"), child, check)?; | |
| 334 | 387 | } |
| 388 | 추가: self.items[index].children = children; | |
| 335 | 389 | } |
| 336 | 390 | Ok(()) |
| 337 | 391 | } |
| 392 | 추가: pub fn reserve_metadata( | |
| 393 | 추가: &mut self, | |
| 394 | 추가: bytes: usize, | |
| 395 | 추가: check: &impl crate::resources::Monitor, | |
| 396 | 추가: ) -> Result<()> { | |
| 397 | 추가: self.budget.charge_bytes(bytes, check.metadata_limits()) | |
| 398 | 추가: } | |
| 338 | 399 | pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> { |
| 339 | 400 | for item in &self.items { |
| 340 | 401 | check.check()?; |
| @@ -343,6 +404,22 @@ impl Plan { | ||
| 343 | 404 | } |
| 344 | 405 | Ok(()) |
| 345 | 406 | } |
| 407 | 추가: pub fn verify_for_publication( | |
| 408 | 추가: &self, | |
| 409 | 추가: temporary: &filesystem::PublicationTemp, | |
| 410 | 추가: check: &mut impl crate::resources::Monitor, | |
| 411 | 추가: ) -> Result<()> { | |
| 412 | 추가: for item in &self.items { | |
| 413 | 추가: check.check()?; | |
| 414 | 추가: if item.member.entry.kind == EntryKind::Directory && item.object == temporary.parent { | |
| 415 | 추가: item.verify_with_temporary(temporary, check)?; | |
| 416 | 추가: } else { | |
| 417 | 추가: item.open()?; | |
| 418 | 추가: } | |
| 419 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 420 | 추가: } | |
| 421 | 추가: Ok(()) | |
| 422 | 추가: } | |
| 346 | 423 | } |
| 347 | 424 | |
| 348 | 425 | #[cfg(test)] |
| @@ -615,7 +615,7 @@ pub(crate) fn directory_with( | ||
| 615 | 615 | check: &mut impl Monitor, |
| 616 | 616 | ) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 617 | 617 | directory_steps(root, name, &mut |step| match step { |
| 618 | 삭제: PublishStep::Check | PublishStep::Commit => check.check(), | |
| 618 | 추가: PublishStep::Check | PublishStep::Commit(_) => check.check(), | |
| 619 | 619 | PublishStep::Activity => check.activity(), |
| 620 | 620 | }) |
| 621 | 621 | } |
| @@ -629,7 +629,7 @@ pub(crate) fn directory_steps( | ||
| 629 | 629 | if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() { |
| 630 | 630 | return Ok((false, Durability::NotApplicable, None)); |
| 631 | 631 | } |
| 632 | 삭제: check(PublishStep::Commit)?; | |
| 632 | 추가: check(PublishStep::Commit(None))?; | |
| 633 | 633 | d.child(&leaf, true)?.ok_or(ErrorCode::Io)?; |
| 634 | 634 | let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err(); |
| 635 | 635 | Ok(match d.sync_checked() { |
| @@ -684,14 +684,19 @@ pub fn publish_reader_mode( | ||
| 684 | 684 | ) -> Published { |
| 685 | 685 | publish_reader_steps(root, name, data, length, replace, &mut |step| match step { |
| 686 | 686 | PublishStep::Check => check(false), |
| 687 | 삭제: PublishStep::Commit => check(true), | |
| 687 | 추가: PublishStep::Commit(_) => check(true), | |
| 688 | 688 | PublishStep::Activity => Ok(()), |
| 689 | 689 | }) |
| 690 | 690 | } |
| 691 | 추가: pub(crate) struct PublicationTemp { | |
| 692 | 추가: pub parent: SourceObject, | |
| 693 | 추가: pub name: String, | |
| 694 | 추가: pub object: SourceObject, | |
| 695 | 추가: } | |
| 691 | 696 | pub(crate) enum PublishStep { |
| 692 | 697 | Check, |
| 693 | 698 | Activity, |
| 694 | 삭제: Commit, | |
| 699 | 추가: Commit(Option<PublicationTemp>), | |
| 695 | 700 | } |
| 696 | 701 | struct PublicationMonitor<'a, F>(&'a mut F); |
| 697 | 702 | impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> { |
| @@ -744,7 +749,13 @@ pub(crate) fn publish_reader_steps( | ||
| 744 | 749 | crate::space::io_error(e) |
| 745 | 750 | } |
| 746 | 751 | })?; |
| 752 | 추가: let mut temporary = None; | |
| 747 | 753 | let written = (|| { |
| 754 | 추가: temporary = Some(PublicationTemp { | |
| 755 | 추가: parent: object(dir.handle())?, | |
| 756 | 추가: name: temp.clone(), | |
| 757 | 추가: object: object(&file)?, | |
| 758 | 추가: }); | |
| 748 | 759 | completed(Ok(()), &mut PublicationMonitor(check))?; |
| 749 | 760 | completed( |
| 750 | 761 | crate::space::ensure(&file, length), |
| @@ -780,7 +791,7 @@ pub(crate) fn publish_reader_steps( | ||
| 780 | 791 | &mut PublicationMonitor(check), |
| 781 | 792 | ); |
| 782 | 793 | let mut finish = written.and(closed).and_then(|_| { |
| 783 | 삭제: check(PublishStep::Commit)?; | |
| 794 | 추가: check(PublishStep::Commit(temporary))?; | |
| 784 | 795 | // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함. |
| 785 | 796 | if let Some(expected) = replace { |
| 786 | 797 | if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref() |
| @@ -11,6 +11,7 @@ pub mod protocol; | ||
| 11 | 11 | pub mod resources; |
| 12 | 12 | pub mod runtime; |
| 13 | 13 | mod seven_zip; |
| 14 | 추가: mod seven_zip_create; | |
| 14 | 15 | mod space; |
| 15 | 16 | mod split_seven_zip; |
| 16 | 17 | mod spool; |
| @@ -201,6 +201,10 @@ pub enum Method { | ||
| 201 | 201 | Deflate, |
| 202 | 202 | } |
| 203 | 203 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 204 | 추가: pub enum SevenZipMethod { | |
| 205 | 추가: Lzma2, | |
| 206 | 추가: } | |
| 207 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 204 | 208 | pub enum Encryption { |
| 205 | 209 | None, |
| 206 | 210 | Aes256, |
| @@ -233,6 +237,13 @@ pub enum Action { | ||
| 233 | 237 | entry_id: u32, |
| 234 | 238 | list_id: ListId, |
| 235 | 239 | }, |
| 240 | 추가: CreateSevenZip { | |
| 241 | 추가: sources: Vec<Source>, | |
| 242 | 추가: output_file: NativePath, | |
| 243 | 추가: method: SevenZipMethod, | |
| 244 | 추가: solid: bool, | |
| 245 | 추가: encryption: Encryption, | |
| 246 | 추가: }, | |
| 236 | 247 | } |
| 237 | 248 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 238 | 249 | pub enum ActionKind { |
| @@ -240,6 +251,7 @@ pub enum ActionKind { | ||
| 240 | 251 | Extract, |
| 241 | 252 | CreateZip, |
| 242 | 253 | Preview, |
| 254 | 추가: CreateSevenZip, | |
| 243 | 255 | } |
| 244 | 256 | impl Action { |
| 245 | 257 | pub fn kind(&self) -> ActionKind { |
| @@ -248,6 +260,7 @@ impl Action { | ||
| 248 | 260 | Self::Extract { .. } => ActionKind::Extract, |
| 249 | 261 | Self::CreateZip { .. } => ActionKind::CreateZip, |
| 250 | 262 | Self::Preview { .. } => ActionKind::Preview, |
| 263 | 추가: Self::CreateSevenZip { .. } => ActionKind::CreateSevenZip, | |
| 251 | 264 | } |
| 252 | 265 | } |
| 253 | 266 | } |
| @@ -8,6 +8,15 @@ pub trait Monitor { | ||
| 8 | 8 | crate::archive::MetadataLimits::default() |
| 9 | 9 | } |
| 10 | 10 | fn check(&mut self) -> Result<()>; |
| 11 | 추가: fn progress( | |
| 12 | 추가: &mut self, | |
| 13 | 추가: _stage: Stage, | |
| 14 | 추가: _bytes: u64, | |
| 15 | 추가: _total: Option<u64>, | |
| 16 | 추가: _entries: u32, | |
| 17 | 추가: ) -> Result<()> { | |
| 18 | 추가: self.check() | |
| 19 | 추가: } | |
| 11 | 20 | fn activity(&mut self) -> Result<()> { |
| 12 | 21 | self.check() |
| 13 | 22 | } |
| @@ -41,6 +41,7 @@ struct Job<W> { | ||
| 41 | 41 | remaining_choice: Option<ConflictChoice>, |
| 42 | 42 | source_group: Option<crate::split_seven_zip::Group>, |
| 43 | 43 | source_verified_for_publication: bool, |
| 44 | 추가: creation_plan: Option<crate::create::Plan>, | |
| 44 | 45 | started: Instant, |
| 45 | 46 | terminal: Terminal, |
| 46 | 47 | parent: crate::parent::Parent, |
| @@ -283,8 +284,19 @@ impl<W: Write> Job<W> { | ||
| 283 | 284 | self.source_group = Some(group); |
| 284 | 285 | self.split_result(result) |
| 285 | 286 | } |
| 286 | 삭제: fn verify_before_publication(&mut self) -> Result<()> { | |
| 287 | 추가: fn verify_before_publication( | |
| 288 | 추가: &mut self, | |
| 289 | 추가: temporary: Option<&filesystem::PublicationTemp>, | |
| 290 | 추가: ) -> Result<()> { | |
| 287 | 291 | if !self.source_verified_for_publication { |
| 292 | 추가: if let Some(plan) = self.creation_plan.take() { | |
| 293 | 추가: let result = match temporary { | |
| 294 | 추가: Some(temporary) => plan.verify_for_publication(temporary, self), | |
| 295 | 추가: None => plan.verify(self), | |
| 296 | 추가: }; | |
| 297 | 추가: self.creation_plan = Some(plan); | |
| 298 | 추가: result?; | |
| 299 | 추가: } | |
| 288 | 300 | self.verify_split()?; |
| 289 | 301 | self.source_verified_for_publication = true; |
| 290 | 302 | } |
| @@ -294,8 +306,11 @@ impl<W: Write> Job<W> { | ||
| 294 | 306 | match step { |
| 295 | 307 | filesystem::PublishStep::Check => self.check(), |
| 296 | 308 | filesystem::PublishStep::Activity => completed(Ok(()), self), |
| 297 | 삭제: filesystem::PublishStep::Commit => { | |
| 298 | 삭제: self.verify_before_publication()?; | |
| 309 | 추가: filesystem::PublishStep::Commit(temporary) => { | |
| 310 | 추가: self.verify_before_publication(temporary.as_ref())?; | |
| 311 | 추가: if let Some(plan) = &self.creation_plan { | |
| 312 | 추가: self.progress(Stage::Commit, 0, None, plan.items.len() as u32)?; | |
| 313 | 추가: } | |
| 299 | 314 | if last { self.cutoff() } else { self.check() } |
| 300 | 315 | } |
| 301 | 316 | } |
| @@ -545,9 +560,23 @@ impl<W: Write> Job<W> { | ||
| 545 | 560 | let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); |
| 546 | 561 | self.event(Message::Accepted { |
| 547 | 562 | action: start.action.kind(), |
| 548 | 삭제: encryption: true, | |
| 563 | 추가: encryption: !matches!(start.action, Action::CreateSevenZip { .. }), | |
| 549 | 564 | })?; |
| 550 | 565 | self.check()?; |
| 566 | 추가: if let Action::CreateSevenZip { | |
| 567 | 추가: sources, | |
| 568 | 추가: solid, | |
| 569 | 추가: encryption, | |
| 570 | 추가: .. | |
| 571 | 추가: } = &start.action | |
| 572 | 추가: { | |
| 573 | 추가: if *solid || *encryption != Encryption::None { | |
| 574 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 575 | 추가: } | |
| 576 | 추가: if sources.is_empty() { | |
| 577 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 578 | 추가: } | |
| 579 | 추가: } | |
| 551 | 580 | if let Some(budget) = &self.budget { |
| 552 | 581 | let scope = ResourceScope { |
| 553 | 582 | output: budget.ceiling.output > budget.soft.output, |
| @@ -865,7 +894,7 @@ impl<W: Write> Job<W> { | ||
| 865 | 894 | )?; |
| 866 | 895 | } |
| 867 | 896 | // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함. |
| 868 | 삭제: self.verify_before_publication()?; | |
| 897 | 추가: self.verify_before_publication(None)?; | |
| 869 | 898 | if !self.interactive || self.terminal.created_count != 0 { |
| 870 | 899 | self.terminal.publication = Publication::Complete; |
| 871 | 900 | } |
| @@ -921,12 +950,50 @@ impl<W: Write> Job<W> { | ||
| 921 | 950 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 922 | 951 | self.terminal.publication = Publication::Complete; |
| 923 | 952 | } |
| 953 | 추가: Action::CreateSevenZip { | |
| 954 | 추가: sources, | |
| 955 | 추가: output_file, | |
| 956 | 추가: .. | |
| 957 | 추가: } => { | |
| 958 | 추가: let output = output_file.to_path()?; | |
| 959 | 추가: let leaf = output | |
| 960 | 추가: .file_name() | |
| 961 | 추가: .and_then(|n| n.to_str()) | |
| 962 | 추가: .ok_or(ErrorCode::InvalidRequest)?; | |
| 963 | 추가: let name = archive::valid_name(leaf, false)?; | |
| 964 | 추가: let root = completed( | |
| 965 | 추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), | |
| 966 | 추가: self, | |
| 967 | 추가: )?; | |
| 968 | 추가: filesystem::preflight_mode_with( | |
| 969 | 추가: &root, | |
| 970 | 추가: &[(name.clone(), EntryKind::File)], | |
| 971 | 추가: false, | |
| 972 | 추가: self, | |
| 973 | 추가: )?; | |
| 974 | 추가: self.progress(Stage::Scan, 0, None, 0)?; | |
| 975 | 추가: let mut plan = crate::create::plan(&sources, limits, self)?; | |
| 976 | 추가: let (mut data, length) = crate::seven_zip_create::archive(&mut plan, limits, self)?; | |
| 977 | 추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; | |
| 978 | 추가: self.creation_plan = Some(plan); | |
| 979 | 추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?; | |
| 980 | 추가: self.terminal.publication = Publication::Complete; | |
| 981 | 추가: } | |
| 924 | 982 | } |
| 925 | 983 | self.cutoff()?; |
| 926 | 984 | Ok(()) |
| 927 | 985 | } |
| 928 | 986 | } |
| 929 | 987 | impl<W: Write> Monitor for Job<W> { |
| 988 | 추가: fn progress( | |
| 989 | 추가: &mut self, | |
| 990 | 추가: stage: Stage, | |
| 991 | 추가: bytes: u64, | |
| 992 | 추가: total: Option<u64>, | |
| 993 | 추가: entries: u32, | |
| 994 | 추가: ) -> Result<()> { | |
| 995 | 추가: Job::progress(self, stage, bytes, total, entries) | |
| 996 | 추가: } | |
| 930 | 997 | fn metadata_limits(&self) -> archive::MetadataLimits { |
| 931 | 998 | self.budget |
| 932 | 999 | .as_ref() |
| @@ -1108,6 +1175,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 1108 | 1175 | remaining_choice: None, |
| 1109 | 1176 | source_group: None, |
| 1110 | 1177 | source_verified_for_publication: false, |
| 1178 | 추가: creation_plan: None, | |
| 1111 | 1179 | parent, |
| 1112 | 1180 | started: Instant::now(), |
| 1113 | 1181 | terminal: Terminal { |
| @@ -0,0 +1,453 @@ | ||
| 1 | 추가: use crate::{create::Plan, protocol::*, resources::Monitor, spool}; | |
| 2 | 추가: use lzma_rust2::{Lzma2Options, Lzma2Writer}; | |
| 3 | 추가: use std::{ | |
| 4 | 추가: fs::File, | |
| 5 | 추가: io::{Read, Seek, SeekFrom, Write}, | |
| 6 | 추가: time::{Duration, Instant}, | |
| 7 | 추가: }; | |
| 8 | 추가: use zlib_rs::crc32::crc32; | |
| 9 | 추가: | |
| 10 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 11 | 추가: const DICTIONARY: u32 = 1024 * 1024; | |
| 12 | 추가: const DICTIONARY_PROPERTY: u8 = 16; | |
| 13 | 추가: | |
| 14 | 추가: fn io<T>(value: std::io::Result<T>) -> Result<T> { | |
| 15 | 추가: value.map_err(crate::space::io_error) | |
| 16 | 추가: } | |
| 17 | 추가: fn options() -> Result<Lzma2Options> { | |
| 18 | 추가: let mut options = Lzma2Options::with_preset(1); | |
| 19 | 추가: options.lzma_options.dict_size = DICTIONARY; | |
| 20 | 추가: let memory = u64::from(options.lzma_options.get_memory_usage()) | |
| 21 | 추가: .checked_mul(1024) | |
| 22 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 23 | 추가: if memory > 32 * 1024 * 1024 { | |
| 24 | 추가: return Err(ErrorCode::Limit); | |
| 25 | 추가: } | |
| 26 | 추가: Ok(options) | |
| 27 | 추가: } | |
| 28 | 추가: fn packed_bound(length: u64) -> Result<u64> { | |
| 29 | 추가: // 한 바이트 이상인 청크의 최대 순증 3바이트와 마지막 종료 바이트를 포함함. | |
| 30 | 추가: length | |
| 31 | 추가: .checked_mul(4) | |
| 32 | 추가: .and_then(|n| n.checked_add(1)) | |
| 33 | 추가: .ok_or(ErrorCode::Limit) | |
| 34 | 추가: } | |
| 35 | 추가: | |
| 36 | 추가: #[derive(Clone, Copy)] | |
| 37 | 추가: struct Stream { | |
| 38 | 추가: size: u64, | |
| 39 | 추가: packed: u64, | |
| 40 | 추가: crc: u32, | |
| 41 | 추가: packed_crc: u32, | |
| 42 | 추가: } | |
| 43 | 추가: struct Sink<'a, M> { | |
| 44 | 추가: file: &'a mut File, | |
| 45 | 추가: check: &'a mut M, | |
| 46 | 추가: error: Option<ErrorCode>, | |
| 47 | 추가: written: u64, | |
| 48 | 추가: bound: u64, | |
| 49 | 추가: crc: u32, | |
| 50 | 추가: base: u64, | |
| 51 | 추가: entries: u32, | |
| 52 | 추가: reported: Instant, | |
| 53 | 추가: } | |
| 54 | 추가: impl<M: Monitor> Write for Sink<'_, M> { | |
| 55 | 추가: fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { | |
| 56 | 추가: let result = (|| { | |
| 57 | 추가: self.check.check()?; | |
| 58 | 추가: let bytes = &bytes[..bytes.len().min(65_536)]; | |
| 59 | 추가: let end = self | |
| 60 | 추가: .written | |
| 61 | 추가: .checked_add(bytes.len() as u64) | |
| 62 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 63 | 추가: if end > self.bound { | |
| 64 | 추가: return Err(ErrorCode::Limit); | |
| 65 | 추가: } | |
| 66 | 추가: crate::space::ensure(self.file, bytes.len() as u64)?; | |
| 67 | 추가: let n = io(self.file.write(bytes))?; | |
| 68 | 추가: self.written += n as u64; | |
| 69 | 추가: self.crc = crc32(self.crc, &bytes[..n]); | |
| 70 | 추가: if n != 0 { | |
| 71 | 추가: crate::resources::completed(Ok(()), self.check)?; | |
| 72 | 추가: if self.reported.elapsed() >= Duration::from_millis(100) { | |
| 73 | 추가: self.check.progress( | |
| 74 | 추가: Stage::Write, | |
| 75 | 추가: self.base + self.written, | |
| 76 | 추가: None, | |
| 77 | 추가: self.entries, | |
| 78 | 추가: )?; | |
| 79 | 추가: self.reported = Instant::now(); | |
| 80 | 추가: } | |
| 81 | 추가: } | |
| 82 | 추가: Ok(n) | |
| 83 | 추가: })(); | |
| 84 | 추가: result.map_err(|error| { | |
| 85 | 추가: self.error = Some(error); | |
| 86 | 추가: std::io::Error::other("7z stream write failed") | |
| 87 | 추가: }) | |
| 88 | 추가: } | |
| 89 | 추가: fn flush(&mut self) -> std::io::Result<()> { | |
| 90 | 추가: self.file.flush() | |
| 91 | 추가: } | |
| 92 | 추가: } | |
| 93 | 추가: fn pack( | |
| 94 | 추가: input: &mut File, | |
| 95 | 추가: length: u64, | |
| 96 | 추가: output: &mut File, | |
| 97 | 추가: entries: u32, | |
| 98 | 추가: check: &mut impl Monitor, | |
| 99 | 추가: ) -> Result<Stream> { | |
| 100 | 추가: let settings = options()?; | |
| 101 | 추가: let base = io(output.stream_position())? | |
| 102 | 추가: .checked_sub(32) | |
| 103 | 추가: .ok_or(ErrorCode::Internal)?; | |
| 104 | 추가: let mut sink = Sink { | |
| 105 | 추가: file: output, | |
| 106 | 추가: check, | |
| 107 | 추가: error: None, | |
| 108 | 추가: written: 0, | |
| 109 | 추가: bound: packed_bound(length)?, | |
| 110 | 추가: crc: 0, | |
| 111 | 추가: base, | |
| 112 | 추가: entries, | |
| 113 | 추가: reported: Instant::now(), | |
| 114 | 추가: }; | |
| 115 | 추가: let result = (|| { | |
| 116 | 추가: io(input.rewind())?; | |
| 117 | 추가: let mut input = input.take(length); | |
| 118 | 추가: let mut encoder = Lzma2Writer::new(&mut sink, settings); | |
| 119 | 추가: let mut buffer = [0; 65_536]; | |
| 120 | 추가: let mut read = 0u64; | |
| 121 | 추가: let mut crc = 0; | |
| 122 | 추가: loop { | |
| 123 | 추가: encoder.inner_mut().check.check()?; | |
| 124 | 추가: let n = io(input.read(&mut buffer))?; | |
| 125 | 추가: if n == 0 { | |
| 126 | 추가: break; | |
| 127 | 추가: } | |
| 128 | 추가: crate::resources::completed(Ok(()), encoder.inner_mut().check)?; | |
| 129 | 추가: read = read.checked_add(n as u64).ok_or(ErrorCode::Limit)?; | |
| 130 | 추가: crc = crc32(crc, &buffer[..n]); | |
| 131 | 추가: io(encoder.write_all(&buffer[..n]))?; | |
| 132 | 추가: } | |
| 133 | 추가: if read != length { | |
| 134 | 추가: return Err(ErrorCode::SourceChanged); | |
| 135 | 추가: } | |
| 136 | 추가: encoder.inner_mut().check.check()?; | |
| 137 | 추가: io(encoder.finish())?; | |
| 138 | 추가: Ok(crc) | |
| 139 | 추가: })(); | |
| 140 | 추가: if let Some(error) = sink.error { | |
| 141 | 추가: return Err(error); | |
| 142 | 추가: } | |
| 143 | 추가: let crc = result?; | |
| 144 | 추가: sink.check.check()?; | |
| 145 | 추가: sink.check | |
| 146 | 추가: .progress(Stage::Write, base + sink.written, None, entries)?; | |
| 147 | 추가: Ok(Stream { | |
| 148 | 추가: size: length, | |
| 149 | 추가: packed: sink.written, | |
| 150 | 추가: crc, | |
| 151 | 추가: packed_crc: sink.crc, | |
| 152 | 추가: }) | |
| 153 | 추가: } | |
| 154 | 추가: | |
| 155 | 추가: struct Header(Vec<u8>); | |
| 156 | 추가: impl Header { | |
| 157 | 추가: fn new(capacity: usize) -> Result<Self> { | |
| 158 | 추가: let mut bytes = Vec::new(); | |
| 159 | 추가: bytes | |
| 160 | 추가: .try_reserve_exact(capacity) | |
| 161 | 추가: .map_err(|_| ErrorCode::Limit)?; | |
| 162 | 추가: Ok(Self(bytes)) | |
| 163 | 추가: } | |
| 164 | 추가: fn put(&mut self, bytes: &[u8]) { | |
| 165 | 추가: self.0.extend_from_slice(bytes); | |
| 166 | 추가: } | |
| 167 | 추가: fn integer(&mut self, value: u64) { | |
| 168 | 추가: for extra in 0..8 { | |
| 169 | 추가: if value < (1u64 << (7 * (extra + 1))) { | |
| 170 | 추가: let prefix = if extra == 0 { 0 } else { 0xffu8 << (8 - extra) }; | |
| 171 | 추가: self.0.push(prefix | (value >> (8 * extra)) as u8); | |
| 172 | 추가: self.put(&value.to_le_bytes()[..extra]); | |
| 173 | 추가: return; | |
| 174 | 추가: } | |
| 175 | 추가: } | |
| 176 | 추가: self.0.push(0xff); | |
| 177 | 추가: self.put(&value.to_le_bytes()); | |
| 178 | 추가: } | |
| 179 | 추가: fn property(&mut self, id: u8, size: usize) { | |
| 180 | 추가: self.0.push(id); | |
| 181 | 추가: self.integer(size as u64); | |
| 182 | 추가: } | |
| 183 | 추가: fn bits(&mut self, values: impl Iterator<Item = bool>) { | |
| 184 | 추가: let mut byte = 0; | |
| 185 | 추가: let mut used = 0; | |
| 186 | 추가: for value in values { | |
| 187 | 추가: if value { | |
| 188 | 추가: byte |= 0x80 >> used; | |
| 189 | 추가: } | |
| 190 | 추가: used += 1; | |
| 191 | 추가: if used == 8 { | |
| 192 | 추가: self.0.push(byte); | |
| 193 | 추가: byte = 0; | |
| 194 | 추가: used = 0; | |
| 195 | 추가: } | |
| 196 | 추가: } | |
| 197 | 추가: if used != 0 { | |
| 198 | 추가: self.0.push(byte); | |
| 199 | 추가: } | |
| 200 | 추가: } | |
| 201 | 추가: } | |
| 202 | 추가: fn empty(item: &crate::create_sources::Planned) -> bool { | |
| 203 | 추가: item.member.entry.size == 0 | |
| 204 | 추가: } | |
| 205 | 추가: fn header( | |
| 206 | 추가: plan: &Plan, | |
| 207 | 추가: streams: &[Stream], | |
| 208 | 추가: names: usize, | |
| 209 | 추가: capacity: usize, | |
| 210 | 추가: check: &mut impl Monitor, | |
| 211 | 추가: ) -> Result<Header> { | |
| 212 | 추가: let mut out = Header::new(capacity)?; | |
| 213 | 추가: out.put(&[1]); | |
| 214 | 추가: if !streams.is_empty() { | |
| 215 | 추가: out.put(&[4, 6, 0]); | |
| 216 | 추가: out.integer(streams.len() as u64); | |
| 217 | 추가: out.put(&[9]); | |
| 218 | 추가: for stream in streams { | |
| 219 | 추가: out.integer(stream.packed); | |
| 220 | 추가: check.check()?; | |
| 221 | 추가: } | |
| 222 | 추가: out.put(&[10, 1]); | |
| 223 | 추가: for stream in streams { | |
| 224 | 추가: out.put(&stream.packed_crc.to_le_bytes()); | |
| 225 | 추가: } | |
| 226 | 추가: out.put(&[0, 7, 11]); | |
| 227 | 추가: out.integer(streams.len() as u64); | |
| 228 | 추가: out.put(&[0]); | |
| 229 | 추가: for _ in streams { | |
| 230 | 추가: out.put(&[1, 0x21, 0x21, 1, DICTIONARY_PROPERTY]); | |
| 231 | 추가: check.check()?; | |
| 232 | 추가: } | |
| 233 | 추가: out.put(&[12]); | |
| 234 | 추가: for stream in streams { | |
| 235 | 추가: out.integer(stream.size); | |
| 236 | 추가: } | |
| 237 | 추가: out.put(&[10, 1]); | |
| 238 | 추가: for stream in streams { | |
| 239 | 추가: out.put(&stream.crc.to_le_bytes()); | |
| 240 | 추가: } | |
| 241 | 추가: out.put(&[0, 8, 0, 0]); | |
| 242 | 추가: } | |
| 243 | 추가: out.put(&[5]); | |
| 244 | 추가: out.integer(plan.items.len() as u64); | |
| 245 | 추가: let empties = plan.items.iter().filter(|p| empty(p)).count(); | |
| 246 | 추가: if empties != 0 { | |
| 247 | 추가: out.property(14, plan.items.len().div_ceil(8)); | |
| 248 | 추가: out.bits(plan.items.iter().map(empty)); | |
| 249 | 추가: out.property(15, empties.div_ceil(8)); | |
| 250 | 추가: out.bits( | |
| 251 | 추가: plan.items | |
| 252 | 추가: .iter() | |
| 253 | 추가: .filter(|p| empty(p)) | |
| 254 | 추가: .map(|p| p.member.entry.kind == EntryKind::File), | |
| 255 | 추가: ); | |
| 256 | 추가: } | |
| 257 | 추가: out.property(17, names.checked_add(1).ok_or(ErrorCode::Limit)?); | |
| 258 | 추가: out.put(&[0]); | |
| 259 | 추가: for item in &plan.items { | |
| 260 | 추가: for unit in item | |
| 261 | 추가: .member | |
| 262 | 추가: .entry | |
| 263 | 추가: .name | |
| 264 | 추가: .encode_utf16() | |
| 265 | 추가: .chain(std::iter::once(0)) | |
| 266 | 추가: { | |
| 267 | 추가: out.put(&unit.to_le_bytes()); | |
| 268 | 추가: } | |
| 269 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 270 | 추가: } | |
| 271 | 추가: out.property( | |
| 272 | 추가: 21, | |
| 273 | 추가: plan.items | |
| 274 | 추가: .len() | |
| 275 | 추가: .checked_mul(4) | |
| 276 | 추가: .and_then(|n| n.checked_add(2)) | |
| 277 | 추가: .ok_or(ErrorCode::Limit)?, | |
| 278 | 추가: ); | |
| 279 | 추가: out.put(&[1, 0]); | |
| 280 | 추가: for item in &plan.items { | |
| 281 | 추가: let attributes: u32 = if item.member.entry.kind == EntryKind::Directory { | |
| 282 | 추가: 0x10 | |
| 283 | 추가: } else { | |
| 284 | 추가: 0x20 | |
| 285 | 추가: }; | |
| 286 | 추가: out.put(&attributes.to_le_bytes()); | |
| 287 | 추가: check.check()?; | |
| 288 | 추가: } | |
| 289 | 추가: out.put(&[0, 0]); | |
| 290 | 추가: if out.0.len() > capacity { | |
| 291 | 추가: return Err(ErrorCode::Internal); | |
| 292 | 추가: } | |
| 293 | 추가: Ok(out) | |
| 294 | 추가: } | |
| 295 | 추가: fn write(output: &mut File, bytes: &[u8], check: &mut impl Monitor) -> Result<()> { | |
| 296 | 추가: for chunk in bytes.chunks(65_536) { | |
| 297 | 추가: check.check()?; | |
| 298 | 추가: crate::space::ensure(output, chunk.len() as u64)?; | |
| 299 | 추가: io(output.write_all(chunk))?; | |
| 300 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 301 | 추가: } | |
| 302 | 추가: Ok(()) | |
| 303 | 추가: } | |
| 304 | 추가: struct Verify<'a, M>(&'a mut M); | |
| 305 | 추가: impl<M: Monitor> Monitor for Verify<'_, M> { | |
| 306 | 추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits { | |
| 307 | 추가: self.0.metadata_limits() | |
| 308 | 추가: } | |
| 309 | 추가: fn check(&mut self) -> Result<()> { | |
| 310 | 추가: self.0.check() | |
| 311 | 추가: } | |
| 312 | 추가: fn activity(&mut self) -> Result<()> { | |
| 313 | 추가: self.0.activity() | |
| 314 | 추가: } | |
| 315 | 추가: } | |
| 316 | 추가: | |
| 317 | 추가: pub(crate) fn archive( | |
| 318 | 추가: plan: &mut Plan, | |
| 319 | 추가: limits: Limits, | |
| 320 | 추가: check: &mut impl Monitor, | |
| 321 | 추가: ) -> Result<(File, u64)> { | |
| 322 | 추가: if plan.items.is_empty() { | |
| 323 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 324 | 추가: } | |
| 325 | 추가: let mut names = 0usize; | |
| 326 | 추가: let mut total = 0u64; | |
| 327 | 추가: for item in &plan.items { | |
| 328 | 추가: check.check()?; | |
| 329 | 추가: names = item | |
| 330 | 추가: .member | |
| 331 | 추가: .entry | |
| 332 | 추가: .name | |
| 333 | 추가: .encode_utf16() | |
| 334 | 추가: .count() | |
| 335 | 추가: .checked_add(1) | |
| 336 | 추가: .and_then(|n| n.checked_mul(2)) | |
| 337 | 추가: .and_then(|n| names.checked_add(n)) | |
| 338 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 339 | 추가: total = total | |
| 340 | 추가: .checked_add(item.member.entry.size) | |
| 341 | 추가: .filter(|n| *n <= limits.input.min(limits.output)) | |
| 342 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 343 | 추가: } | |
| 344 | 추가: let capacity = plan | |
| 345 | 추가: .items | |
| 346 | 추가: .len() | |
| 347 | 추가: .checked_mul(96) | |
| 348 | 추가: .and_then(|n| n.checked_add(names)) | |
| 349 | 추가: .and_then(|n| n.checked_add(128)) | |
| 350 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 351 | 추가: // 헤더 두 사본, 검증 목록과 스트림 배열을 기존 계획 예산에 함께 반영함. | |
| 352 | 추가: let metadata = capacity | |
| 353 | 추가: .checked_mul(3) | |
| 354 | 추가: .and_then(|n| n.checked_add(plan.items.len().checked_mul(256)?)) | |
| 355 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 356 | 추가: plan.reserve_metadata(metadata, check)?; | |
| 357 | 추가: let mut streams = Vec::new(); | |
| 358 | 추가: streams | |
| 359 | 추가: .try_reserve_exact(plan.items.len()) | |
| 360 | 추가: .map_err(|_| ErrorCode::Limit)?; | |
| 361 | 추가: let mut output = spool::temporary()?; | |
| 362 | 추가: write(&mut output, &[0; 32], check)?; | |
| 363 | 추가: let mut read = 0u64; | |
| 364 | 추가: for (index, source) in plan.items.iter().enumerate() { | |
| 365 | 추가: check.check()?; | |
| 366 | 추가: let length = source.member.entry.size; | |
| 367 | 추가: let mut input = crate::resources::completed(source.open(), check)?; | |
| 368 | 추가: if !empty(source) { | |
| 369 | 추가: let required = length | |
| 370 | 추가: .checked_add(packed_bound(length)?) | |
| 371 | 추가: .and_then(|n| n.checked_add(capacity as u64)) | |
| 372 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 373 | 추가: crate::space::ensure(&output, required)?; | |
| 374 | 추가: check.progress(Stage::Read, read, Some(total), index as u32)?; | |
| 375 | 추가: let mut snapshot = spool::Snapshot::capture_reporting( | |
| 376 | 추가: &mut input.file, | |
| 377 | 추가: length, | |
| 378 | 추가: &mut |step| match step { | |
| 379 | 추가: spool::Step::Check => check.check(), | |
| 380 | 추가: spool::Step::Activity => crate::resources::completed(Ok(()), check), | |
| 381 | 추가: spool::Step::Read { bytes, .. } => { | |
| 382 | 추가: check.progress(Stage::Read, read + bytes, Some(total), index as u32) | |
| 383 | 추가: } | |
| 384 | 추가: }, | |
| 385 | 추가: )?; | |
| 386 | 추가: if snapshot.len != length { | |
| 387 | 추가: return Err(ErrorCode::SourceChanged); | |
| 388 | 추가: } | |
| 389 | 추가: check.progress( | |
| 390 | 추가: Stage::Write, | |
| 391 | 추가: io(output.stream_position())? - 32, | |
| 392 | 추가: None, | |
| 393 | 추가: index as u32, | |
| 394 | 추가: )?; | |
| 395 | 추가: streams.push(pack( | |
| 396 | 추가: &mut snapshot.file, | |
| 397 | 추가: length, | |
| 398 | 추가: &mut output, | |
| 399 | 추가: index as u32, | |
| 400 | 추가: check, | |
| 401 | 추가: )?); | |
| 402 | 추가: read += length; | |
| 403 | 추가: } | |
| 404 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 405 | 추가: } | |
| 406 | 추가: let at = io(output.stream_position())?; | |
| 407 | 추가: let header = header(plan, &streams, names, capacity, check)?; | |
| 408 | 추가: let mut start = [0; 32]; | |
| 409 | 추가: start[..8].copy_from_slice(b"7z\xbc\xaf\x27\x1c\x00\x04"); | |
| 410 | 추가: start[12..20].copy_from_slice(&at.checked_sub(32).ok_or(ErrorCode::Internal)?.to_le_bytes()); | |
| 411 | 추가: start[20..28].copy_from_slice(&(header.0.len() as u64).to_le_bytes()); | |
| 412 | 추가: start[28..32].copy_from_slice(&crc32(0, &header.0).to_le_bytes()); | |
| 413 | 추가: let crc = crc32(0, &start[12..]); | |
| 414 | 추가: start[8..12].copy_from_slice(&crc.to_le_bytes()); | |
| 415 | 추가: write(&mut output, &header.0, check)?; | |
| 416 | 추가: drop(header); | |
| 417 | 추가: let length = io(output.stream_position())?; | |
| 418 | 추가: check.check()?; | |
| 419 | 추가: io(output.seek(SeekFrom::Start(0)))?; | |
| 420 | 추가: write(&mut output, &start, check)?; | |
| 421 | 추가: check.progress(Stage::Verify, 0, None, plan.items.len() as u32)?; | |
| 422 | 추가: let catalog = crate::seven_zip::open( | |
| 423 | 추가: &mut output, | |
| 424 | 추가: length, | |
| 425 | 추가: Limits { | |
| 426 | 추가: input: length, | |
| 427 | 추가: ..limits | |
| 428 | 추가: }, | |
| 429 | 추가: false, | |
| 430 | 추가: &mut Verify(check), | |
| 431 | 추가: )?; | |
| 432 | 추가: if catalog.members.len() != plan.items.len() { | |
| 433 | 추가: return Err(ErrorCode::Integrity); | |
| 434 | 추가: } | |
| 435 | 추가: for (actual, expected) in catalog.members.iter().zip(&plan.items) { | |
| 436 | 추가: let expected = &expected.member.entry; | |
| 437 | 추가: if actual.entry.name != expected.name | |
| 438 | 추가: || actual.entry.kind != expected.kind | |
| 439 | 추가: || actual.entry.size != expected.size | |
| 440 | 추가: { | |
| 441 | 추가: return Err(ErrorCode::Integrity); | |
| 442 | 추가: } | |
| 443 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 444 | 추가: } | |
| 445 | 추가: drop(catalog); | |
| 446 | 추가: plan.verify(check)?; | |
| 447 | 추가: io(output.rewind())?; | |
| 448 | 추가: Ok((output, length)) | |
| 449 | 추가: } | |
| 450 | 추가: | |
| 451 | 추가: #[cfg(test)] | |
| 452 | 추가: #[path = "../../../tests/rust-archive-worker/seven_zip_create_fields.rs"] | |
| 453 | 추가: mod tests; |
| @@ -139,7 +139,7 @@ impl Snapshot { | ||
| 139 | 139 | Step::Read { .. } => check.check(), |
| 140 | 140 | }) |
| 141 | 141 | } |
| 142 | 삭제: fn capture_reporting( | |
| 142 | 추가: pub(crate) fn capture_reporting( | |
| 143 | 143 | source: &mut File, |
| 144 | 144 | limit: u64, |
| 145 | 145 | step: &mut impl FnMut(Step) -> Result<()>, |
| @@ -137,8 +137,9 @@ macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wir | ||
| 137 | 137 | } }; } |
| 138 | 138 | enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4}); |
| 139 | 139 | enumeration!(Method{Store=0,Deflate=1}); |
| 140 | 추가: enumeration!(SevenZipMethod{Lzma2=0}); | |
| 140 | 141 | enumeration!(Encryption{None=0,Aes256=1}); |
| 141 | 삭제: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3}); | |
| 142 | 추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4}); | |
| 142 | 143 | enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1}); |
| 143 | 144 | enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); |
| 144 | 145 | enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); |
| @@ -385,6 +386,20 @@ impl Wire for Action { | ||
| 385 | 386 | entry_id.enc(e)?; |
| 386 | 387 | list_id.enc(e) |
| 387 | 388 | } |
| 389 | 추가: Self::CreateSevenZip { | |
| 390 | 추가: sources, | |
| 391 | 추가: output_file, | |
| 392 | 추가: method, | |
| 393 | 추가: solid, | |
| 394 | 추가: encryption, | |
| 395 | 추가: } => { | |
| 396 | 추가: 4u8.enc(e)?; | |
| 397 | 추가: sources.enc(e)?; | |
| 398 | 추가: output_file.enc(e)?; | |
| 399 | 추가: method.enc(e)?; | |
| 400 | 추가: solid.enc(e)?; | |
| 401 | 추가: encryption.enc(e) | |
| 402 | 추가: } | |
| 388 | 403 | } |
| 389 | 404 | } |
| 390 | 405 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| @@ -410,6 +425,13 @@ impl Wire for Action { | ||
| 410 | 425 | entry_id: Wire::dec(d)?, |
| 411 | 426 | list_id: Wire::dec(d)?, |
| 412 | 427 | }), |
| 428 | 추가: 4 => Ok(Self::CreateSevenZip { | |
| 429 | 추가: sources: Wire::dec(d)?, | |
| 430 | 추가: output_file: Wire::dec(d)?, | |
| 431 | 추가: method: Wire::dec(d)?, | |
| 432 | 추가: solid: Wire::dec(d)?, | |
| 433 | 추가: encryption: Wire::dec(d)?, | |
| 434 | 추가: }), | |
| 413 | 435 | _ => Err(invalid()), |
| 414 | 436 | } |
| 415 | 437 | } |
| @@ -8,6 +8,7 @@ pub enum Purpose { | ||
| 8 | 8 | Destination, |
| 9 | 9 | Retry, |
| 10 | 10 | SaveZip, |
| 11 | 추가: SaveSevenZip, | |
| 11 | 12 | SaveGzip, |
| 12 | 13 | RetryGzip, |
| 13 | 14 | } |
| @@ -110,6 +111,7 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 110 | 111 | let filters = match request.purpose { |
| 111 | 112 | Purpose::Open => archive_filters(), |
| 112 | 113 | Purpose::SaveZip => vec![("ZIP 압축파일", vec!["zip".into()])], |
| 114 | 추가: Purpose::SaveSevenZip => vec![("7z 압축파일", vec!["7z".into()])], | |
| 113 | 115 | _ => Vec::new(), |
| 114 | 116 | } |
| 115 | 117 | .into_iter() |
| @@ -128,18 +130,22 @@ fn choose_portal(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 128 | 130 | .collect::<Vec<_>>(); |
| 129 | 131 | portal_response(pollster::block_on(async move { |
| 130 | 132 | let selected = match request.purpose { |
| 131 | 삭제: Purpose::SaveZip | Purpose::SaveGzip | Purpose::RetryGzip => SaveFileRequest::default() | |
| 132 | 삭제: .title(if request.purpose == Purpose::SaveZip { | |
| 133 | 삭제: "ZIP 파일 저장" | |
| 134 | 삭제: } else { | |
| 135 | 삭제: "압축 해제 파일 저장" | |
| 136 | 삭제: }) | |
| 137 | 삭제: .current_name(Some(request.file_name.as_str())) | |
| 138 | 삭제: .filters(filters) | |
| 139 | 삭제: .current_folder::<&PathBuf>(Some(&request.directory))? | |
| 140 | 삭제: .send() | |
| 141 | 삭제: .await? | |
| 142 | 삭제: .response()?, | |
| 133 | 추가: Purpose::SaveZip | Purpose::SaveSevenZip | Purpose::SaveGzip | Purpose::RetryGzip => { | |
| 134 | 추가: SaveFileRequest::default() | |
| 135 | 추가: .title(if request.purpose == Purpose::SaveSevenZip { | |
| 136 | 추가: "7z 파일 저장" | |
| 137 | 추가: } else if request.purpose == Purpose::SaveZip { | |
| 138 | 추가: "ZIP 파일 저장" | |
| 139 | 추가: } else { | |
| 140 | 추가: "압축 해제 파일 저장" | |
| 141 | 추가: }) | |
| 142 | 추가: .current_name(Some(request.file_name.as_str())) | |
| 143 | 추가: .filters(filters) | |
| 144 | 추가: .current_folder::<&PathBuf>(Some(&request.directory))? | |
| 145 | 추가: .send() | |
| 146 | 추가: .await? | |
| 147 | 추가: .response()? | |
| 148 | 추가: } | |
| 143 | 149 | purpose => OpenFileRequest::default() |
| 144 | 150 | .title(match purpose { |
| 145 | 151 | Purpose::Open => "압축파일 열기", |
| @@ -194,6 +200,12 @@ fn choose_native(request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> | ||
| 194 | 200 | .set_file_name(request.file_name) |
| 195 | 201 | .save_file() |
| 196 | 202 | .map(|path| vec![path]), |
| 203 | 추가: Purpose::SaveSevenZip => dialog | |
| 204 | 추가: .set_title("7z 파일 저장") | |
| 205 | 추가: .set_file_name(request.file_name) | |
| 206 | 추가: .add_filter("7z 압축파일", &["7z"]) | |
| 207 | 추가: .save_file() | |
| 208 | 추가: .map(|path| vec![path]), | |
| 197 | 209 | Purpose::SaveZip => dialog |
| 198 | 210 | .set_title("ZIP 파일 저장") |
| 199 | 211 | .set_file_name(request.file_name) |
| @@ -201,6 +201,24 @@ fn start_to_wire(start: ui::Start) -> wire::Start { | ||
| 201 | 201 | entry_id, |
| 202 | 202 | list_id: list_to_wire(list_id), |
| 203 | 203 | }, |
| 204 | 추가: ui::Start::CreateSevenZip { | |
| 205 | 추가: sources, | |
| 206 | 추가: output_file, | |
| 207 | 추가: } => wire::Action::CreateSevenZip { | |
| 208 | 추가: sources: sources | |
| 209 | 추가: .into_iter() | |
| 210 | 추가: .map(|(path, archive_name)| wire::Source { | |
| 211 | 추가: path: wire::NativePath::from_path(&crate::archive_path::worker_path(&path)), | |
| 212 | 추가: archive_name, | |
| 213 | 추가: }) | |
| 214 | 추가: .collect(), | |
| 215 | 추가: output_file: wire::NativePath::from_path(&crate::archive_path::worker_path( | |
| 216 | 추가: &output_file, | |
| 217 | 추가: )), | |
| 218 | 추가: method: wire::SevenZipMethod::Lzma2, | |
| 219 | 추가: solid: false, | |
| 220 | 추가: encryption: wire::Encryption::None, | |
| 221 | 추가: }, | |
| 204 | 222 | ui::Start::CreateZip { |
| 205 | 223 | sources, |
| 206 | 224 | output_file, |
| @@ -22,7 +22,7 @@ use std::{ | ||
| 22 | 22 | const WORK_WIDTH: f32 = 480.0; |
| 23 | 23 | const CREATE_WIDTH: f32 = 560.0; |
| 24 | 24 | /// 처음 열 때의 높이. 그다음부터는 내용 높이에 맞춤. |
| 25 | 삭제: const CREATE_MIN_HEIGHT: f32 = 300.0; | |
| 25 | 추가: const CREATE_MIN_HEIGHT: f32 = 560.0; | |
| 26 | 26 | const CREATE_LIST_HEIGHT: f32 = 288.0; |
| 27 | 27 | |
| 28 | 28 | /// ZIP 만들기 창 목록의 한 행. 디스크에서 읽은 파일이나 폴더임. |
| @@ -208,6 +208,7 @@ pub struct ArchiveApp { | ||
| 208 | 208 | create: bool, |
| 209 | 209 | selected_only: bool, |
| 210 | 210 | method: Method, |
| 211 | 추가: seven_zip: bool, | |
| 211 | 212 | dialogs: Box<dyn Dialogs>, |
| 212 | 213 | picker: Option<(Purpose, std::sync::mpsc::Receiver<DialogAnswer>)>, |
| 213 | 214 | preview_open: bool, |
| @@ -277,6 +278,7 @@ impl ArchiveApp { | ||
| 277 | 278 | create: false, |
| 278 | 279 | selected_only: false, |
| 279 | 280 | method: Method::Deflate, |
| 281 | 추가: seven_zip: false, | |
| 280 | 282 | dialogs: Box::new(NativeDialogs), |
| 281 | 283 | picker: None, |
| 282 | 284 | preview_open: false, |
| @@ -342,7 +344,7 @@ impl ArchiveApp { | ||
| 342 | 344 | pub fn show_create(&mut self, encrypted: bool) { |
| 343 | 345 | if !self.model.busy() { |
| 344 | 346 | self.create = true; |
| 345 | 삭제: self.aes256 = encrypted; | |
| 347 | 추가: self.aes256 = encrypted && !self.seven_zip; | |
| 346 | 348 | self.ui_error = None; |
| 347 | 349 | } |
| 348 | 350 | } |
| @@ -517,7 +519,11 @@ impl ArchiveApp { | ||
| 517 | 519 | } else { |
| 518 | 520 | first.file_stem() |
| 519 | 521 | }; |
| 520 | 삭제: self.zip_name = format!("{}.zip", name.unwrap_or_default().to_string_lossy()); | |
| 522 | 추가: self.zip_name = format!( | |
| 523 | 추가: "{}.{}", | |
| 524 | 추가: name.unwrap_or_default().to_string_lossy(), | |
| 525 | 추가: if self.seven_zip { "7z" } else { "zip" } | |
| 526 | 추가: ); | |
| 521 | 527 | } |
| 522 | 528 | } |
| 523 | 529 | for path in paths { |
| @@ -596,11 +602,12 @@ impl ArchiveApp { | ||
| 596 | 602 | if self.sources.is_empty() { |
| 597 | 603 | return; |
| 598 | 604 | } |
| 599 | 삭제: if !self.zip_name.to_ascii_lowercase().ends_with(".zip") { | |
| 600 | 삭제: self.zip_name.push_str(".zip"); | |
| 605 | 추가: let extension = if self.seven_zip { ".7z" } else { ".zip" }; | |
| 606 | 추가: if !self.zip_name.to_ascii_lowercase().ends_with(extension) { | |
| 607 | 추가: self.zip_name.push_str(extension); | |
| 601 | 608 | } |
| 602 | 609 | if !valid_leaf(&self.zip_name) { |
| 603 | 삭제: self.ui_error = Some("ZIP 파일 이름을 확인하세요".into()); | |
| 610 | 추가: self.ui_error = Some("압축파일 이름을 확인하세요".into()); | |
| 604 | 611 | return; |
| 605 | 612 | } |
| 606 | 613 | let output_file = self.zip_folder.join(&self.zip_name); |
| @@ -619,6 +626,15 @@ impl ArchiveApp { | ||
| 619 | 626 | }; |
| 620 | 627 | sources.push((path.clone(), name.to_owned())); |
| 621 | 628 | } |
| 629 | 추가: if self.seven_zip | |
| 630 | 추가: && (self.aes256 | |
| 631 | 추가: || !self.zip_password.is_empty() | |
| 632 | 추가: || !self.zip_password_confirm.is_empty()) | |
| 633 | 추가: { | |
| 634 | 추가: self.ui_error = | |
| 635 | 추가: Some("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요".into()); | |
| 636 | 추가: return; | |
| 637 | 추가: } | |
| 622 | 638 | if !self.zip_password_ready() { |
| 623 | 639 | self.ui_error = Some("두 암호가 같은지 확인하세요".into()); |
| 624 | 640 | return; |
| @@ -627,12 +643,20 @@ impl ArchiveApp { | ||
| 627 | 643 | self.directories.clear(); |
| 628 | 644 | // 암호는 ZIP 만들기 창에서 받아 두었다가 작업자가 요청하면 넘김. |
| 629 | 645 | let password = self.aes256.then(|| std::mem::take(&mut self.zip_password)); |
| 630 | 삭제: if self.start(Start::CreateZip { | |
| 631 | 삭제: sources, | |
| 632 | 삭제: output_file, | |
| 633 | 삭제: method: self.method, | |
| 634 | 삭제: aes256: self.aes256, | |
| 635 | 삭제: }) { | |
| 646 | 추가: let request = if self.seven_zip { | |
| 647 | 추가: Start::CreateSevenZip { | |
| 648 | 추가: sources, | |
| 649 | 추가: output_file, | |
| 650 | 추가: } | |
| 651 | 추가: } else { | |
| 652 | 추가: Start::CreateZip { | |
| 653 | 추가: sources, | |
| 654 | 추가: output_file, | |
| 655 | 추가: method: self.method, | |
| 656 | 추가: aes256: self.aes256, | |
| 657 | 추가: } | |
| 658 | 추가: }; | |
| 659 | 추가: if self.start(request) { | |
| 636 | 660 | self.create = false; |
| 637 | 661 | self.create_win = WorkWindow::default(); |
| 638 | 662 | self.clear_zip_password(); |
| @@ -657,7 +681,7 @@ impl ArchiveApp { | ||
| 657 | 681 | _ => purpose, |
| 658 | 682 | }; |
| 659 | 683 | let directory = match purpose { |
| 660 | 삭제: Purpose::SaveZip => self.zip_folder.clone(), | |
| 684 | 추가: Purpose::SaveZip | Purpose::SaveSevenZip => self.zip_folder.clone(), | |
| 661 | 685 | Purpose::Destination | Purpose::SaveGzip => self |
| 662 | 686 | .model |
| 663 | 687 | .archive |
| @@ -769,8 +793,8 @@ impl ArchiveApp { | ||
| 769 | 793 | } |
| 770 | 794 | } |
| 771 | 795 | // 저장 위치를 고르는 사이 ZIP 만들기 창을 닫았으면 아무 작업도 시작하지 않음. |
| 772 | 삭제: Purpose::SaveZip if !self.create => {} | |
| 773 | 삭제: Purpose::SaveZip => { | |
| 796 | 추가: Purpose::SaveZip | Purpose::SaveSevenZip if !self.create => {} | |
| 797 | 추가: Purpose::SaveZip | Purpose::SaveSevenZip => { | |
| 774 | 798 | if let Some(name) = path.file_name().and_then(|name| name.to_str()) { |
| 775 | 799 | self.zip_name = name.to_owned(); |
| 776 | 800 | self.zip_folder = path.parent().unwrap_or(Path::new("/")).to_path_buf(); |
| @@ -799,7 +823,13 @@ impl ArchiveApp { | ||
| 799 | 823 | } |
| 800 | 824 | self.extract_selection(selection); |
| 801 | 825 | } |
| 826 | 추가: Start::CreateSevenZip { .. } => { | |
| 827 | 추가: self.set_seven_zip(true); | |
| 828 | 추가: self.create = true; | |
| 829 | 추가: self.begin_zip(); | |
| 830 | 추가: } | |
| 802 | 831 | Start::CreateZip { aes256, .. } => { |
| 832 | 추가: self.set_seven_zip(false); | |
| 803 | 833 | self.create = true; |
| 804 | 834 | if aes256 { |
| 805 | 835 | // 암호는 보관하지 않으므로 ZIP 만들기 창에서 다시 받음. |
| @@ -1867,7 +1897,10 @@ impl ArchiveApp { | ||
| 1867 | 1897 | let title = if self.model.busy() { |
| 1868 | 1898 | present::activity_text( |
| 1869 | 1899 | &self.model, |
| 1870 | 삭제: matches!(self.last_request, Some(Start::CreateZip { .. })), | |
| 1900 | 추가: matches!( | |
| 1901 | 추가: self.last_request, | |
| 1902 | 추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. }) | |
| 1903 | 추가: ), | |
| 1871 | 1904 | ) |
| 1872 | 1905 | .to_owned() |
| 1873 | 1906 | } else { |
| @@ -1959,7 +1992,10 @@ impl ArchiveApp { | ||
| 1959 | 1992 | if error.starts_with("암호는") { |
| 1960 | 1993 | error.as_str() |
| 1961 | 1994 | } else { |
| 1962 | 삭제: if matches!(self.last_request, Some(Start::CreateZip { .. })) { | |
| 1995 | 추가: if matches!( | |
| 1996 | 추가: self.last_request, | |
| 1997 | 추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. }) | |
| 1998 | 추가: ) { | |
| 1963 | 1999 | "저장 위치와 추가한 항목을 확인하세요" |
| 1964 | 2000 | } else { |
| 1965 | 2001 | "풀 위치와 선택한 항목을 확인하세요" |
| @@ -1977,7 +2013,10 @@ impl ArchiveApp { | ||
| 1977 | 2013 | }); |
| 1978 | 2014 | return; |
| 1979 | 2015 | } |
| 1980 | 삭제: let creating = matches!(self.last_request, Some(Start::CreateZip { .. })); | |
| 2016 | 추가: let creating = matches!( | |
| 2017 | 추가: self.last_request, | |
| 2018 | 추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. }) | |
| 2019 | 추가: ); | |
| 1981 | 2020 | let cancelling = self.model.cancellation_requested() || self.model.cancel.is_some(); |
| 1982 | 2021 | let title = present::activity_text(&self.model, creating); |
| 1983 | 2022 | ui.strong(title); |
| @@ -2034,7 +2073,10 @@ impl ArchiveApp { | ||
| 2034 | 2073 | fn result(&mut self, ui: &mut egui::Ui) { |
| 2035 | 2074 | let t = self.model.terminal.clone(); |
| 2036 | 2075 | let listing = matches!(self.last_request, Some(Start::List { .. })); |
| 2037 | 삭제: let creating = matches!(self.last_request, Some(Start::CreateZip { .. })); | |
| 2076 | 추가: let creating = matches!( | |
| 2077 | 추가: self.last_request, | |
| 2078 | 추가: Some(Start::CreateZip { .. } | Start::CreateSevenZip { .. }) | |
| 2079 | 추가: ); | |
| 2038 | 2080 | let resolved_targets = present::resolved_targets( |
| 2039 | 2081 | self.targets.as_ref(), |
| 2040 | 2082 | &self.model.entries, |
| @@ -2087,7 +2129,11 @@ impl ArchiveApp { | ||
| 2087 | 2129 | self.model.confirmed && t.as_ref().is_some_and(|t| t.outcome == Outcome::Cancelled); |
| 2088 | 2130 | let title = if success { |
| 2089 | 2131 | if creating { |
| 2090 | 삭제: "ZIP 파일을 만들었습니다" | |
| 2132 | 추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) { | |
| 2133 | 추가: "7z 파일을 만들었습니다" | |
| 2134 | 추가: } else { | |
| 2135 | 추가: "ZIP 파일을 만들었습니다" | |
| 2136 | 추가: } | |
| 2091 | 2137 | } else if skipped > 0 && t.as_ref().is_some_and(|t| t.created_count == 0) { |
| 2092 | 2138 | "모든 파일을 건너뛰었습니다" |
| 2093 | 2139 | } else { |
| @@ -2098,7 +2144,11 @@ impl ArchiveApp { | ||
| 2098 | 2144 | } else if listing { |
| 2099 | 2145 | "압축파일을 열지 못했습니다" |
| 2100 | 2146 | } else if creating { |
| 2101 | 삭제: "ZIP 파일을 만들지 못했습니다" | |
| 2147 | 추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) { | |
| 2148 | 추가: "7z 파일을 만들지 못했습니다" | |
| 2149 | 추가: } else { | |
| 2150 | 추가: "ZIP 파일을 만들지 못했습니다" | |
| 2151 | 추가: } | |
| 2102 | 2152 | } else { |
| 2103 | 2153 | "압축을 풀지 못했습니다" |
| 2104 | 2154 | }; |
| @@ -2136,9 +2186,10 @@ impl ArchiveApp { | ||
| 2136 | 2186 | .show(ui, |ui| { |
| 2137 | 2187 | if success && t.as_ref().is_some_and(|t| t.created_count > 0) { |
| 2138 | 2188 | let path = match self.last_request.as_ref() { |
| 2139 | 삭제: Some(Start::CreateZip { output_file, .. }) => { | |
| 2140 | 삭제: output_file.display().to_string() | |
| 2141 | 삭제: } | |
| 2189 | 추가: Some( | |
| 2190 | 추가: Start::CreateZip { output_file, .. } | |
| 2191 | 추가: | Start::CreateSevenZip { output_file, .. }, | |
| 2192 | 추가: ) => output_file.display().to_string(), | |
| 2142 | 2193 | _ => format!("{} 폴더에 저장했습니다.", self.destination.display()), |
| 2143 | 2194 | }; |
| 2144 | 2195 | theme::bounded_text(ui, &path, ui.available_width()); |
| @@ -2204,7 +2255,11 @@ impl ArchiveApp { | ||
| 2204 | 2255 | ) |
| 2205 | 2256 | { |
| 2206 | 2257 | ui.label(if creating { |
| 2207 | 삭제: "ZIP 파일을 만들지 않았습니다" | |
| 2258 | 추가: if matches!(self.last_request, Some(Start::CreateSevenZip { .. })) { | |
| 2259 | 추가: "7z 파일을 만들지 않았습니다" | |
| 2260 | 추가: } else { | |
| 2261 | 추가: "ZIP 파일을 만들지 않았습니다" | |
| 2262 | 추가: } | |
| 2208 | 2263 | } else { |
| 2209 | 2264 | "아무 파일도 풀지 않았습니다" |
| 2210 | 2265 | }); |
| @@ -2376,9 +2431,10 @@ impl ArchiveApp { | ||
| 2376 | 2431 | } |
| 2377 | 2432 | if folder { |
| 2378 | 2433 | let path = match self.last_request.as_ref() { |
| 2379 | 삭제: Some(Start::CreateZip { output_file, .. }) => { | |
| 2380 | 삭제: output_file.parent().unwrap_or(Path::new("/")) | |
| 2381 | 삭제: } | |
| 2434 | 추가: Some( | |
| 2435 | 추가: Start::CreateZip { output_file, .. } | |
| 2436 | 추가: | Start::CreateSevenZip { output_file, .. }, | |
| 2437 | 추가: ) => output_file.parent().unwrap_or(Path::new("/")), | |
| 2382 | 2438 | _ => self.destination.as_path(), |
| 2383 | 2439 | }; |
| 2384 | 2440 | match present::folder_command(path).spawn() { |
| @@ -2432,7 +2488,11 @@ impl ArchiveApp { | ||
| 2432 | 2488 | let modal = egui::Modal::new(egui::Id::unique("create-zip")).show(ctx, |ui| { |
| 2433 | 2489 | ui.set_width((ctx.content_rect().width() - 64.0).min(CREATE_WIDTH)); |
| 2434 | 2490 | ui.horizontal(|ui| { |
| 2435 | 삭제: ui.heading("ZIP 만들기"); | |
| 2491 | 추가: ui.heading(if self.seven_zip { | |
| 2492 | 추가: "7z 만들기" | |
| 2493 | 추가: } else { | |
| 2494 | 추가: "ZIP 만들기" | |
| 2495 | 추가: }); | |
| 2436 | 2496 | ui.with_layout(Layout::right_to_left(Align::Center), |ui| { |
| 2437 | 2497 | let button = theme::icon_button(ui, "닫기", theme::CLOSE, true); |
| 2438 | 2498 | close = button.clicked(); |
| @@ -2448,7 +2508,11 @@ impl ArchiveApp { | ||
| 2448 | 2508 | return; |
| 2449 | 2509 | } |
| 2450 | 2510 | let id = egui::ViewportId::from_hash_of("archive-create"); |
| 2451 | 삭제: let title = "ZIP 만들기 — Zipelo"; | |
| 2511 | 추가: let title = if self.seven_zip { | |
| 2512 | 추가: "7z 만들기 — Zipelo" | |
| 2513 | 추가: } else { | |
| 2514 | 추가: "ZIP 만들기 — Zipelo" | |
| 2515 | 추가: }; | |
| 2452 | 2516 | let custom_frame = self.custom_frame; |
| 2453 | 2517 | if !self.create_win.open { |
| 2454 | 2518 | self.create_win.height = self.create_win.height.max(CREATE_MIN_HEIGHT); |
| @@ -2531,7 +2595,38 @@ impl ArchiveApp { | ||
| 2531 | 2595 | .inner |
| 2532 | 2596 | } |
| 2533 | 2597 | |
| 2598 | 추가: fn set_seven_zip(&mut self, selected: bool) { | |
| 2599 | 추가: if self.seven_zip == selected { | |
| 2600 | 추가: return; | |
| 2601 | 추가: } | |
| 2602 | 추가: self.seven_zip = selected; | |
| 2603 | 추가: self.aes256 = false; | |
| 2604 | 추가: self.clear_zip_password(); | |
| 2605 | 추가: self.ui_error = None; | |
| 2606 | 추가: let name = self.zip_name.clone(); | |
| 2607 | 추가: let lower = name.to_ascii_lowercase(); | |
| 2608 | 추가: let stem = if lower.ends_with(".zip") { | |
| 2609 | 추가: &name[..name.len() - 4] | |
| 2610 | 추가: } else if lower.ends_with(".7z") { | |
| 2611 | 추가: &name[..name.len() - 3] | |
| 2612 | 추가: } else { | |
| 2613 | 추가: &name | |
| 2614 | 추가: }; | |
| 2615 | 추가: self.zip_name = format!("{stem}{}", if selected { ".7z" } else { ".zip" }); | |
| 2616 | 추가: } | |
| 2617 | 추가: | |
| 2534 | 2618 | fn create_contents(&mut self, ui: &mut egui::Ui) -> bool { |
| 2619 | 추가: let mut selected = self.seven_zip; | |
| 2620 | 추가: ui.horizontal(|ui| { | |
| 2621 | 추가: ui.label("형식"); | |
| 2622 | 추가: ui.selectable_value(&mut selected, false, "ZIP"); | |
| 2623 | 추가: ui.selectable_value(&mut selected, true, "7z"); | |
| 2624 | 추가: if selected { | |
| 2625 | 추가: ui.label("LZMA2"); | |
| 2626 | 추가: } | |
| 2627 | 추가: }); | |
| 2628 | 추가: self.set_seven_zip(selected); | |
| 2629 | 추가: | |
| 2535 | 2630 | let rows = self.create_rows(); |
| 2536 | 2631 | let root = self.create_root(); |
| 2537 | 2632 | |
| @@ -2670,6 +2765,10 @@ impl ArchiveApp { | ||
| 2670 | 2765 | } |
| 2671 | 2766 | |
| 2672 | 2767 | // 암호: 체크하면 바로 아래에 암호와 암호 확인 칸을 보여 줌. |
| 2768 | 추가: if self.seven_zip { | |
| 2769 | 추가: ui.label("7z는 암호를 지원하지 않습니다. 암호가 필요하면 ZIP을 선택하세요"); | |
| 2770 | 추가: return false; | |
| 2771 | 추가: } | |
| 2673 | 2772 | let check = ui.checkbox(&mut self.aes256, "암호로 보호하기"); |
| 2674 | 2773 | theme::pointer(&check); |
| 2675 | 2774 | theme::focus(&check); |
| @@ -2743,7 +2842,11 @@ impl ArchiveApp { | ||
| 2743 | 2842 | }) |
| 2744 | 2843 | .inner; |
| 2745 | 2844 | if compress { |
| 2746 | 삭제: self.open_picker(Purpose::SaveZip); | |
| 2845 | 추가: self.open_picker(if self.seven_zip { | |
| 2846 | 추가: Purpose::SaveSevenZip | |
| 2847 | 추가: } else { | |
| 2848 | 추가: Purpose::SaveZip | |
| 2849 | 추가: }); | |
| 2747 | 2850 | } |
| 2748 | 2851 | cancel |
| 2749 | 2852 | } |
| @@ -2769,6 +2872,7 @@ impl ArchiveApp { | ||
| 2769 | 2872 | ActionKind::List => "압축파일 목록 열기", |
| 2770 | 2873 | ActionKind::Extract => "압축 해제", |
| 2771 | 2874 | ActionKind::CreateZip => "ZIP 만들기", |
| 2875 | 추가: ActionKind::CreateSevenZip => "7z 만들기", | |
| 2772 | 2876 | ActionKind::Preview => "파일 미리보기", |
| 2773 | 2877 | }); |
| 2774 | 2878 | if question.scope.ratio { |
| @@ -69,6 +69,10 @@ pub enum Start { | ||
| 69 | 69 | entry_id: u32, |
| 70 | 70 | list_id: ListId, |
| 71 | 71 | }, |
| 72 | 추가: CreateSevenZip { | |
| 73 | 추가: sources: Vec<(PathBuf, String)>, | |
| 74 | 추가: output_file: PathBuf, | |
| 75 | 추가: }, | |
| 72 | 76 | CreateZip { |
| 73 | 77 | sources: Vec<(PathBuf, String)>, |
| 74 | 78 | output_file: PathBuf, |
| @@ -476,7 +480,8 @@ impl Model { | ||
| 476 | 480 | } |
| 477 | 481 | } |
| 478 | 482 | pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool { |
| 479 | 삭제: let expanded = self.needs_expansion(&start); | |
| 483 | 추가: let expanded = | |
| 484 | 추가: matches!(start, Start::CreateSevenZip { .. }) || self.needs_expansion(&start); | |
| 480 | 485 | self.begin_with_limits(start, factory, expanded) |
| 481 | 486 | } |
| 482 | 487 | pub fn estimated_usage(&self) -> ResourceUsage { |
| @@ -513,7 +518,7 @@ impl Model { | ||
| 513 | 518 | .iter() |
| 514 | 519 | .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?)); |
| 515 | 520 | } |
| 516 | 삭제: Start::CreateZip { sources, .. } => { | |
| 521 | 추가: Start::CreateZip { sources, .. } | Start::CreateSevenZip { sources, .. } => { | |
| 517 | 522 | usage.estimated_bytes = sources.iter().try_fold(0u64, |sum, (path, _)| { |
| 518 | 523 | let m = std::fs::symlink_metadata(path).ok()?; |
| 519 | 524 | if !m.is_file() { |
| @@ -643,6 +648,10 @@ impl Model { | ||
| 643 | 648 | sources, |
| 644 | 649 | output_file, |
| 645 | 650 | .. |
| 651 | 추가: } | |
| 652 | 추가: | Start::CreateSevenZip { | |
| 653 | 추가: sources, | |
| 654 | 추가: output_file, | |
| 646 | 655 | } => { |
| 647 | 656 | !sources.is_empty() |
| 648 | 657 | && output_file.is_absolute() |
| @@ -1100,6 +1109,9 @@ impl Model { | ||
| 1100 | 1109 | } |
| 1101 | 1110 | } |
| 1102 | 1111 | Event::Accepted { encryption } => { |
| 1112 | 추가: if matches!(run.start, Start::CreateSevenZip { .. }) && encryption { | |
| 1113 | 추가: self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into()); | |
| 1114 | 추가: } | |
| 1103 | 1115 | if run.accepted { |
| 1104 | 1116 | self.error = Some("작업 승인 중복".into()); |
| 1105 | 1117 | } |
| @@ -1144,7 +1156,8 @@ impl Model { | ||
| 1144 | 1156 | if run.cancel_sequence.is_some() { |
| 1145 | 1157 | return; |
| 1146 | 1158 | } |
| 1147 | 삭제: if self.challenge.is_some() | |
| 1159 | 추가: if matches!(run.start, Start::CreateSevenZip { .. }) | |
| 1160 | 추가: || self.challenge.is_some() | |
| 1148 | 1161 | || self.resource.is_some() |
| 1149 | 1162 | || challenge_id <= run.last_challenge |
| 1150 | 1163 | || self.conflict.is_some() |
| @@ -1163,6 +1176,7 @@ impl Model { | ||
| 1163 | 1176 | Start::List { .. } => ActionKind::List, |
| 1164 | 1177 | Start::Extract { .. } => ActionKind::Extract, |
| 1165 | 1178 | Start::CreateZip { .. } => ActionKind::CreateZip, |
| 1179 | 추가: Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip, | |
| 1166 | 1180 | Start::Preview { .. } => ActionKind::Preview, |
| 1167 | 1181 | }; |
| 1168 | 1182 | let hard = Limits { |
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | import importlib.util |
| 4 | 4 | from pathlib import Path |
| 5 | 5 | import unittest |
| 6 | 추가: import tomllib | |
| 6 | 7 | |
| 7 | 8 | |
| 8 | 9 | ROOT = Path(__file__).resolve().parents[2] |
| @@ -12,6 +13,17 @@ SPEC.loader.exec_module(LICENSES) | ||
| 12 | 13 | |
| 13 | 14 | |
| 14 | 15 | class CompressedTarLicenses(unittest.TestCase): |
| 16 | 추가: def test_seven_zip_encoder_reuses_pure_rust_package(self): | |
| 17 | 추가: manifest = ROOT / "experiments/rust-archive-worker/Cargo.toml" | |
| 18 | 추가: dependency = tomllib.loads(manifest.read_text())["dependencies"]["lzma-rust2"] | |
| 19 | 추가: self.assertEqual(dependency["version"], "=0.25.0") | |
| 20 | 추가: self.assertFalse(dependency["default-features"]) | |
| 21 | 추가: self.assertEqual(set(dependency["features"]), {"std", "xz", "encoder"}) | |
| 22 | 추가: package = next(p for p in LICENSES.metadata(manifest) if p["name"] == "lzma-rust2") | |
| 23 | 추가: original = tomllib.loads((Path(package["manifest_path"]).parent / "Cargo.toml.orig").read_text()) | |
| 24 | 추가: self.assertEqual(original["features"]["encoder"], []) | |
| 25 | 추가: self.assertEqual(original["package"]["license"], "Apache-2.0") | |
| 26 | 추가: | |
| 15 | 27 | def test_registry_originals_are_in_generated_worker_notice(self): |
| 16 | 28 | manifest = ROOT / "experiments/rust-archive-worker/Cargo.toml" |
| 17 | 29 | records = LICENSES.inventory([manifest]) |
| @@ -236,6 +236,11 @@ impl Connection for CaptureConnection { | ||
| 236 | 236 | durability: Durability::NotApplicable, |
| 237 | 237 | cleanup: Cleanup::Complete, |
| 238 | 238 | }), |
| 239 | 추가: Start::CreateSevenZip { output_file, .. } => { | |
| 240 | 추가: self.create_name = | |
| 241 | 추가: Some(output_file.file_name().unwrap().to_string_lossy().into()); | |
| 242 | 추가: self.finish(false); | |
| 243 | 추가: } | |
| 239 | 244 | Start::CreateZip { |
| 240 | 245 | output_file, |
| 241 | 246 | aes256, |
| @@ -107,3 +107,36 @@ fn volume_problem_adapter_preserves_native_filename_and_rejects_other_actions() | ||
| 107 | 107 | Some(ui::ErrorCode::MissingVolume) |
| 108 | 108 | ); |
| 109 | 109 | } |
| 110 | 추가: | |
| 111 | 추가: #[test] | |
| 112 | 추가: fn sevenzip_creation_adapter_preserves_paths_and_fixed_options() { | |
| 113 | 추가: let source = std::env::current_dir().unwrap().join("원본"); | |
| 114 | 추가: let output = source.with_file_name("결과.7z"); | |
| 115 | 추가: let converted = start_to_wire(ui::Start::CreateSevenZip { | |
| 116 | 추가: sources: vec![(source.clone(), "원본".into())], | |
| 117 | 추가: output_file: output.clone(), | |
| 118 | 추가: }); | |
| 119 | 추가: match converted.action { | |
| 120 | 추가: wire::Action::CreateSevenZip { | |
| 121 | 추가: sources, | |
| 122 | 추가: output_file, | |
| 123 | 추가: method, | |
| 124 | 추가: solid, | |
| 125 | 추가: encryption, | |
| 126 | 추가: } => { | |
| 127 | 추가: assert_eq!(sources[0].archive_name, "원본"); | |
| 128 | 추가: assert_eq!( | |
| 129 | 추가: sources[0].path, | |
| 130 | 추가: wire::NativePath::from_path(&crate::archive_path::worker_path(&source)) | |
| 131 | 추가: ); | |
| 132 | 추가: assert_eq!( | |
| 133 | 추가: output_file, | |
| 134 | 추가: wire::NativePath::from_path(&crate::archive_path::worker_path(&output)) | |
| 135 | 추가: ); | |
| 136 | 추가: assert_eq!(method, wire::SevenZipMethod::Lzma2); | |
| 137 | 추가: assert!(!solid); | |
| 138 | 추가: assert_eq!(encryption, wire::Encryption::None); | |
| 139 | 추가: } | |
| 140 | 추가: other => panic!("잘못된 생성 형식: {other:?}"), | |
| 141 | 추가: } | |
| 142 | 추가: } |
| @@ -636,3 +636,49 @@ fn native_picker_lowers_child_windows_and_restores_their_position_and_level() { | ||
| 636 | 636 | } |
| 637 | 637 | } |
| 638 | 638 | } |
| 639 | 추가: | |
| 640 | 추가: #[test] | |
| 641 | 추가: fn sevenzip_selection_clears_zip_password_and_sends_only_supported_options() { | |
| 642 | 추가: let scratch = Folder::new(); | |
| 643 | 추가: let factory = FakeFactory::default(); | |
| 644 | 추가: let (mut app, ctx) = create_from_folder(&scratch, &factory); | |
| 645 | 추가: policy_click(&ctx, &mut app, "암호로 보호하기"); | |
| 646 | 추가: text(&ctx, &mut app, "zip-password-input", "previous-secret"); | |
| 647 | 추가: text(&ctx, &mut app, "zip-password-confirm", "previous-secret"); | |
| 648 | 추가: policy_click(&ctx, &mut app, "7z"); | |
| 649 | 추가: let shown = policy_render(&ctx, &mut app, vec![]); | |
| 650 | 추가: assert!(shown.iter().any(|(s, _)| s == "LZMA2")); | |
| 651 | 추가: assert!(!shown.iter().any(|(s, _)| s == "암호 확인")); | |
| 652 | 추가: policy_click(&ctx, &mut app, "ZIP"); | |
| 653 | 추가: policy_click(&ctx, &mut app, "암호로 보호하기"); | |
| 654 | 추가: policy_click(&ctx, &mut app, "압축하기"); | |
| 655 | 추가: assert_eq!(factory.state.borrow().starts.len(), 1); | |
| 656 | 추가: policy_click(&ctx, &mut app, "7z"); | |
| 657 | 추가: let dialogs = TestDialogs::default(); | |
| 658 | 추가: app.set_dialogs(Box::new(dialogs.clone())); | |
| 659 | 추가: policy_click(&ctx, &mut app, "압축하기"); | |
| 660 | 추가: let state = dialogs.0.borrow(); | |
| 661 | 추가: let save = state.requests.last().unwrap(); | |
| 662 | 추가: assert_eq!(save.purpose, Purpose::SaveSevenZip); | |
| 663 | 추가: assert_eq!(save.file_name, "photos.7z"); | |
| 664 | 추가: assert!(matches!(factory.state.borrow().starts.last(), | |
| 665 | 추가: Some(Start::CreateSevenZip { sources, output_file }) | |
| 666 | 추가: if sources.len() == 1 && sources[0].1 == "photos" && output_file.ends_with("photos.7z"))); | |
| 667 | 추가: assert!(!factory.state.borrow().password_seen); | |
| 668 | 추가: } | |
| 669 | 추가: | |
| 670 | 추가: #[test] | |
| 671 | 추가: fn cancelling_sevenzip_save_keeps_selected_format_without_starting() { | |
| 672 | 추가: let scratch = Folder::new(); | |
| 673 | 추가: let factory = FakeFactory::default(); | |
| 674 | 추가: let (mut app, ctx) = create_from_folder(&scratch, &factory); | |
| 675 | 추가: policy_click(&ctx, &mut app, "7z"); | |
| 676 | 추가: let dialogs = TestDialogs::default(); | |
| 677 | 추가: dialogs.0.borrow_mut().cancel_save = true; | |
| 678 | 추가: app.set_dialogs(Box::new(dialogs)); | |
| 679 | 추가: policy_click(&ctx, &mut app, "압축하기"); | |
| 680 | 추가: assert_eq!(factory.state.borrow().starts.len(), 1); | |
| 681 | 추가: let shown = policy_render(&ctx, &mut app, vec![]); | |
| 682 | 추가: assert!(shown.iter().any(|(s, _)| s == "7z 만들기")); | |
| 683 | 추가: assert!(shown.iter().any(|(s, _)| s == "LZMA2")); | |
| 684 | 추가: } |
| @@ -23,7 +23,8 @@ impl Dialogs for TestDialogs { | ||
| 23 | 23 | if let Some(answer) = state.answers.pop_front() { |
| 24 | 24 | return Ok(answer); |
| 25 | 25 | } |
| 26 | 삭제: if request.purpose == Purpose::SaveZip && !state.cancel_save { | |
| 26 | 추가: if matches!(request.purpose, Purpose::SaveZip | Purpose::SaveSevenZip) && !state.cancel_save | |
| 27 | 추가: { | |
| 27 | 28 | let name = state.save_name.take().unwrap_or(request.file_name); |
| 28 | 29 | return Ok(Some(vec![request.directory.join(name)])); |
| 29 | 30 | } |
| @@ -875,3 +875,81 @@ mod presentation; | ||
| 875 | 875 | mod windows_paths; |
| 876 | 876 | |
| 877 | 877 | mod guarded; |
| 878 | 추가: | |
| 879 | 추가: #[test] | |
| 880 | 추가: fn sevenzip_creation_rejects_password_prompts_and_encrypted_acceptance() { | |
| 881 | 추가: for encrypted in [false, true] { | |
| 882 | 추가: let mut f = FakeFactory::default(); | |
| 883 | 추가: f.state.borrow_mut().manual = true; | |
| 884 | 추가: let mut m = Model::default(); | |
| 885 | 추가: assert!(m.begin( | |
| 886 | 추가: Start::CreateSevenZip { | |
| 887 | 추가: sources: vec![(path("source"), "source".into())], | |
| 888 | 추가: output_file: path("output.7z"), | |
| 889 | 추가: }, | |
| 890 | 추가: &mut f | |
| 891 | 추가: )); | |
| 892 | 추가: f.state.borrow_mut().frame(Event::Accepted { | |
| 893 | 추가: encryption: encrypted, | |
| 894 | 추가: }); | |
| 895 | 추가: if !encrypted { | |
| 896 | 추가: f.state.borrow_mut().frame(Event::PasswordRequired { | |
| 897 | 추가: challenge_id: 1, | |
| 898 | 추가: attempt: 1, | |
| 899 | 추가: encrypt: true, | |
| 900 | 추가: }); | |
| 901 | 추가: } | |
| 902 | 추가: for _ in 0..10 { | |
| 903 | 추가: m.poll(); | |
| 904 | 추가: } | |
| 905 | 추가: assert!(m.error.is_some()); | |
| 906 | 추가: assert!(m.challenge.is_none()); | |
| 907 | 추가: } | |
| 908 | 추가: } | |
| 909 | 추가: | |
| 910 | 추가: #[test] | |
| 911 | 추가: fn sevenzip_creation_waits_for_both_eofs_and_child_reap() { | |
| 912 | 추가: let mut f = FakeFactory::default(); | |
| 913 | 추가: f.state.borrow_mut().manual = true; | |
| 914 | 추가: let mut m = Model::default(); | |
| 915 | 추가: assert!(m.begin( | |
| 916 | 추가: Start::CreateSevenZip { | |
| 917 | 추가: sources: vec![(path("source"), "source".into())], | |
| 918 | 추가: output_file: path("output.7z"), | |
| 919 | 추가: }, | |
| 920 | 추가: &mut f | |
| 921 | 추가: )); | |
| 922 | 추가: { | |
| 923 | 추가: let mut s = f.state.borrow_mut(); | |
| 924 | 추가: s.frame(Event::Accepted { encryption: false }); | |
| 925 | 추가: s.frame(Event::Output { | |
| 926 | 추가: entry_id: None, | |
| 927 | 추가: relative_name: "output.7z".into(), | |
| 928 | 추가: disposition: Disposition::Created, | |
| 929 | 추가: }); | |
| 930 | 추가: s.frame(Event::Terminal(Terminal { | |
| 931 | 추가: outcome: Outcome::Completed, | |
| 932 | 추가: error: None, | |
| 933 | 추가: publication: Publication::Complete, | |
| 934 | 추가: created_count: 1, | |
| 935 | 추가: retained_partial_count: 0, | |
| 936 | 추가: durability: Durability::Synced, | |
| 937 | 추가: cleanup: Cleanup::Complete, | |
| 938 | 추가: })); | |
| 939 | 추가: } | |
| 940 | 추가: m.poll(); | |
| 941 | 추가: assert!(!m.confirmed); | |
| 942 | 추가: f.state.borrow_mut().queue.push_back(HostEvent::StdoutEof); | |
| 943 | 추가: m.poll(); | |
| 944 | 추가: assert!(!m.confirmed); | |
| 945 | 추가: f.state.borrow_mut().queue.push_back(HostEvent::StderrEof); | |
| 946 | 추가: m.poll(); | |
| 947 | 추가: assert!(!m.confirmed); | |
| 948 | 추가: f.state | |
| 949 | 추가: .borrow_mut() | |
| 950 | 추가: .queue | |
| 951 | 추가: .push_back(HostEvent::Exited { success: true }); | |
| 952 | 추가: pump(&mut m); | |
| 953 | 추가: assert!(m.confirmed); | |
| 954 | 추가: assert!(m.error.is_none()); | |
| 955 | 추가: } |
| @@ -140,6 +140,12 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() { | ||
| 140 | 140 | "extract-unsynced" => "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다", |
| 141 | 141 | "source-changed" => "압축파일 다시 열기", |
| 142 | 142 | "gzip-conflict" => "다른 이름으로 저장", |
| 143 | 추가: "create-sevenzip" => "7z는 암호를 지원하지 않습니다", | |
| 144 | 추가: "create-sevenzip-progress" => "파일을 저장하는 중", | |
| 145 | 추가: "create-sevenzip-complete" => "7z 파일을 만들었습니다", | |
| 146 | 추가: "create-sevenzip-error" => "7z 파일을 만들지 못했습니다", | |
| 147 | 추가: "create-sevenzip-cancelled" => "작업을 취소했습니다", | |
| 148 | 추가: "create-sevenzip-resource" => "큰 작업을 허용할까요?", | |
| 143 | 149 | "create-error" => "ZIP 파일을 만들지 못했습니다", |
| 144 | 150 | "password-create" => "암호 확인", |
| 145 | 151 | "folder" => "바다.jpg", |
| @@ -21,6 +21,13 @@ macro_rules! catalog { | ||
| 21 | 21 | } |
| 22 | 22 | |
| 23 | 23 | catalog! { |
| 24 | 추가: "create-sevenzip" => "7z 형식 선택과 LZMA2 및 암호 미지원 안내", | |
| 25 | 추가: "create-sevenzip-progress" => "7z 만들기 진행과 취소", | |
| 26 | 추가: "create-sevenzip-complete" => "7z 만들기 완료", | |
| 27 | 추가: "create-sevenzip-error" => "7z 만들기 저장 실패", | |
| 28 | 추가: "create-sevenzip-cancelled" => "7z 만들기 취소 완료", | |
| 29 | 추가: "create-sevenzip-resource" => "7z 만들기의 큰 작업 승인", | |
| 30 | 추가: | |
| 24 | 31 | "split-archive" => "분할 7z 목록과 미리보기 비활성화", |
| 25 | 32 | "split-first-volume" => "첫 조각의 정확한 파일명 안내", |
| 26 | 33 | "split-missing-volume" => "누락 조각 파일명과 재시도 안내", |
| @@ -511,7 +518,7 @@ impl Scenario { | ||
| 511 | 518 | } |
| 512 | 519 | return app; |
| 513 | 520 | } |
| 514 | 삭제: "create" | "create-encrypted" => { | |
| 521 | 추가: "create" | "create-encrypted" | "create-sevenzip" => { | |
| 515 | 522 | app.sources = vec![base.join("읽어주세요.txt"), base.join("사진")]; |
| 516 | 523 | app.scenario_sources = Some(std::rc::Rc::new(vec![ |
| 517 | 524 | SourceRow { |
| @@ -526,10 +533,12 @@ impl Scenario { | ||
| 526 | 533 | }, |
| 527 | 534 | ])); |
| 528 | 535 | app.show_create(self.name == "create-encrypted"); |
| 536 | 추가: app.set_seven_zip(self.name == "create-sevenzip"); | |
| 529 | 537 | return app; |
| 530 | 538 | } |
| 531 | 539 | _ => {} |
| 532 | 540 | } |
| 541 | 추가: let seven_zip = self.name.starts_with("create-sevenzip"); | |
| 533 | 542 | let creating = self.name.starts_with("create-") || self.name == "password-create"; |
| 534 | 543 | let listing_error = matches!(self.name, "unsupported" | "damaged"); |
| 535 | 544 | if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") { |
| @@ -544,7 +553,12 @@ impl Scenario { | ||
| 544 | 553 | }]; |
| 545 | 554 | app.gzip_name = "여행 자료".into(); |
| 546 | 555 | } |
| 547 | 삭제: let request = if creating { | |
| 556 | 추가: let request = if seven_zip { | |
| 557 | 추가: Start::CreateSevenZip { | |
| 558 | 추가: sources: vec![(base.join("사진"), "사진".into())], | |
| 559 | 추가: output_file: base.join("여행 자료.7z"), | |
| 560 | 추가: } | |
| 561 | 추가: } else if creating { | |
| 548 | 562 | Start::CreateZip { |
| 549 | 563 | sources: vec![(base.join("사진"), "사진".into())], |
| 550 | 564 | output_file: base.join("여행 자료.zip"), |
| @@ -564,7 +578,12 @@ impl Scenario { | ||
| 564 | 578 | } |
| 565 | 579 | }; |
| 566 | 580 | app.targets = Some(if creating { |
| 567 | 삭제: BTreeSet::from(["여행 자료.zip".into()]) | |
| 581 | 추가: BTreeSet::from([if seven_zip { | |
| 582 | 추가: "여행 자료.7z" | |
| 583 | 추가: } else { | |
| 584 | 추가: "여행 자료.zip" | |
| 585 | 추가: } | |
| 586 | 추가: .into()]) | |
| 568 | 587 | } else if matches!(self.name, "gzip-conflict" | "gzip-conflict-choice") { |
| 569 | 588 | BTreeSet::from(["여행 자료".into()]) |
| 570 | 589 | } else { |
| @@ -588,13 +607,19 @@ impl Scenario { | ||
| 588 | 607 | assert!(app.start(request)); |
| 589 | 608 | { |
| 590 | 609 | let mut state = state.borrow_mut(); |
| 591 | 삭제: state.frame(Event::Accepted { encryption: true }); | |
| 610 | 추가: state.frame(Event::Accepted { | |
| 611 | 추가: encryption: !seven_zip, | |
| 612 | 추가: }); | |
| 592 | 613 | match self.name { |
| 593 | 삭제: "resource-approval" | "resource-ratio" => { | |
| 594 | 삭제: let expanded = self.name == "resource-approval"; | |
| 614 | 추가: "resource-approval" | "resource-ratio" | "create-sevenzip-resource" => { | |
| 615 | 추가: let expanded = self.name != "resource-ratio"; | |
| 595 | 616 | state.frame(Event::ResourceRequired(ResourceChallenge { |
| 596 | 617 | id: 1, |
| 597 | 삭제: action: ActionKind::Extract, | |
| 618 | 추가: action: if seven_zip { | |
| 619 | 추가: ActionKind::CreateSevenZip | |
| 620 | 추가: } else { | |
| 621 | 추가: ActionKind::Extract | |
| 622 | 추가: }, | |
| 598 | 623 | scope: ResourceScope { |
| 599 | 624 | output: expanded, |
| 600 | 625 | entries: expanded, |
| @@ -723,7 +748,10 @@ impl Scenario { | ||
| 723 | 748 | encrypt: self.name == "password-create", |
| 724 | 749 | }) |
| 725 | 750 | } |
| 726 | 삭제: "extract-complete" | "create-complete" | "extract-unsynced" => { | |
| 751 | 추가: "extract-complete" | |
| 752 | 추가: | "create-complete" | |
| 753 | 추가: | "create-sevenzip-complete" | |
| 754 | 추가: | "extract-unsynced" => { | |
| 727 | 755 | let names = app.targets.as_ref().unwrap(); |
| 728 | 756 | for name in names { |
| 729 | 757 | state.frame(Event::Output { |
| @@ -751,7 +779,9 @@ impl Scenario { | ||
| 751 | 779 | HostEvent::Exited { success: true }, |
| 752 | 780 | ]); |
| 753 | 781 | } |
| 754 | 삭제: "extract-cancelled" => state.finish(Outcome::Cancelled, Publication::None), | |
| 782 | 추가: "extract-cancelled" | "create-sevenzip-cancelled" => { | |
| 783 | 추가: state.finish(Outcome::Cancelled, Publication::None) | |
| 784 | 추가: } | |
| 755 | 785 | "extract-partial" | "extract-uncertain" => { |
| 756 | 786 | let partial = self.name == "extract-partial"; |
| 757 | 787 | if partial { |
| @@ -780,14 +810,19 @@ impl Scenario { | ||
| 780 | 810 | HostEvent::Exited { success: true }, |
| 781 | 811 | ]); |
| 782 | 812 | } |
| 783 | 삭제: "conflict" | "gzip-conflict" | "unsupported" | "damaged" | "source-changed" | |
| 784 | 삭제: | "create-error" => { | |
| 813 | 추가: "conflict" | |
| 814 | 추가: | "gzip-conflict" | |
| 815 | 추가: | "unsupported" | |
| 816 | 추가: | "damaged" | |
| 817 | 추가: | "source-changed" | |
| 818 | 추가: | "create-error" | |
| 819 | 추가: | "create-sevenzip-error" => { | |
| 785 | 820 | state.frame(Event::Terminal(Terminal { |
| 786 | 821 | outcome: Outcome::Failed, |
| 787 | 822 | error: Some(match self.name { |
| 788 | 823 | "conflict" | "gzip-conflict" => ErrorCode::Conflict, |
| 789 | 824 | "source-changed" => ErrorCode::SourceChanged, |
| 790 | 삭제: "create-error" => ErrorCode::DiskFull, | |
| 825 | 추가: "create-error" | "create-sevenzip-error" => ErrorCode::DiskFull, | |
| 791 | 826 | "unsupported" => ErrorCode::UnsupportedFormat, |
| 792 | 827 | _ => ErrorCode::Integrity, |
| 793 | 828 | }), |
| @@ -4,8 +4,9 @@ static NEXT: AtomicU64 = AtomicU64::new(0); | ||
| 4 | 4 | struct Scratch(PathBuf); |
| 5 | 5 | impl Scratch { |
| 6 | 6 | fn new() -> Self { |
| 7 | 삭제: let root = | |
| 8 | 삭제: Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-archive-worker/runs"); | |
| 7 | 추가: let root = std::env::var_os("TMPDIR") | |
| 8 | 추가: .map(PathBuf::from) | |
| 9 | 추가: .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")); | |
| 9 | 10 | fs::create_dir_all(&root).unwrap(); |
| 10 | 11 | let path = root.join(format!( |
| 11 | 12 | "sources-{}-{}", |
| @@ -105,3 +106,80 @@ fn pinned_directory_enumeration_does_not_follow_replacement_link() { | ||
| 105 | 106 | assert!(input.open_child(&path, "secret").is_err()); |
| 106 | 107 | assert!(matches!(Input::open(&path), Err(ErrorCode::UnsafePath))); |
| 107 | 108 | } |
| 109 | 추가: | |
| 110 | 추가: #[test] | |
| 111 | 추가: fn publication_exception_requires_the_exact_parent_name_and_temporary_object() { | |
| 112 | 추가: for mismatch in [ | |
| 113 | 추가: "parent", | |
| 114 | 추가: "name", | |
| 115 | 추가: "object", | |
| 116 | 추가: "missing", | |
| 117 | 추가: "replacement", | |
| 118 | 추가: "directory", | |
| 119 | 추가: ] { | |
| 120 | 추가: let s = Scratch::new(); | |
| 121 | 추가: fs::create_dir(s.0.join("folder")).unwrap(); | |
| 122 | 추가: fs::write(s.0.join("folder/source"), b"original").unwrap(); | |
| 123 | 추가: let plan = Plan::new(&[s.source("folder")], Limits::default(), &mut || Ok(())).unwrap(); | |
| 124 | 추가: let path = s.0.join("folder/.zipelo-owned.tmp"); | |
| 125 | 추가: fs::write(&path, b"archive").unwrap(); | |
| 126 | 추가: let mut temporary = filesystem::PublicationTemp { | |
| 127 | 추가: parent: filesystem::object(&Input::open(&s.0.join("folder")).unwrap().file).unwrap(), | |
| 128 | 추가: name: ".zipelo-owned.tmp".into(), | |
| 129 | 추가: object: filesystem::object(&Input::open(&path).unwrap().file).unwrap(), | |
| 130 | 추가: }; | |
| 131 | 추가: assert_eq!(plan.verify(&mut || Ok(())), Err(ErrorCode::SourceChanged)); | |
| 132 | 추가: assert_eq!( | |
| 133 | 추가: plan.verify_for_publication(&temporary, &mut || Ok(())), | |
| 134 | 추가: Ok(()) | |
| 135 | 추가: ); | |
| 136 | 추가: match mismatch { | |
| 137 | 추가: "parent" => temporary.parent = temporary.object.clone(), | |
| 138 | 추가: "name" => temporary.name = ".zipelo-other.tmp".into(), | |
| 139 | 추가: "object" => temporary.object = temporary.parent.clone(), | |
| 140 | 추가: "missing" => fs::remove_file(&path).unwrap(), | |
| 141 | 추가: "replacement" => { | |
| 142 | 추가: fs::rename(&path, s.0.join("owned")).unwrap(); | |
| 143 | 추가: fs::write(&path, b"foreign").unwrap(); | |
| 144 | 추가: } | |
| 145 | 추가: "directory" => { | |
| 146 | 추가: fs::rename(s.0.join("folder"), s.0.join("previous")).unwrap(); | |
| 147 | 추가: fs::create_dir(s.0.join("folder")).unwrap(); | |
| 148 | 추가: } | |
| 149 | 추가: _ => unreachable!(), | |
| 150 | 추가: } | |
| 151 | 추가: assert_eq!( | |
| 152 | 추가: plan.verify_for_publication(&temporary, &mut || Ok(())), | |
| 153 | 추가: Err(ErrorCode::SourceChanged), | |
| 154 | 추가: "{mismatch}" | |
| 155 | 추가: ); | |
| 156 | 추가: } | |
| 157 | 추가: } | |
| 158 | 추가: | |
| 159 | 추가: #[test] | |
| 160 | 추가: fn publication_directory_enumeration_remains_cancellable() { | |
| 161 | 추가: let s = Scratch::new(); | |
| 162 | 추가: fs::create_dir(s.0.join("folder")).unwrap(); | |
| 163 | 추가: for index in 0..20 { | |
| 164 | 추가: fs::write(s.0.join(format!("folder/{index}")), b"x").unwrap(); | |
| 165 | 추가: } | |
| 166 | 추가: let plan = Plan::new(&[s.source("folder")], Limits::default(), &mut || Ok(())).unwrap(); | |
| 167 | 추가: let path = s.0.join("folder/.zipelo-owned.tmp"); | |
| 168 | 추가: fs::write(&path, b"archive").unwrap(); | |
| 169 | 추가: let temporary = filesystem::PublicationTemp { | |
| 170 | 추가: parent: filesystem::object(&Input::open(&s.0.join("folder")).unwrap().file).unwrap(), | |
| 171 | 추가: name: ".zipelo-owned.tmp".into(), | |
| 172 | 추가: object: filesystem::object(&Input::open(&path).unwrap().file).unwrap(), | |
| 173 | 추가: }; | |
| 174 | 추가: let mut calls = 0; | |
| 175 | 추가: let result = plan.verify_for_publication(&temporary, &mut || { | |
| 176 | 추가: calls += 1; | |
| 177 | 추가: if calls == 12 { | |
| 178 | 추가: Err(ErrorCode::None) | |
| 179 | 추가: } else { | |
| 180 | 추가: Ok(()) | |
| 181 | 추가: } | |
| 182 | 추가: }); | |
| 183 | 추가: assert_eq!(result, Err(ErrorCode::None)); | |
| 184 | 추가: assert_eq!(calls, 12); | |
| 185 | 추가: } |
| @@ -1625,3 +1625,7 @@ mod compressed_tar; | ||
| 1625 | 1625 | mod guarded; |
| 1626 | 1626 | |
| 1627 | 1627 | mod split_runtime; |
| 1628 | 추가: | |
| 1629 | 추가: mod seven_zip_create; | |
| 1630 | 추가: | |
| 1631 | 추가: mod seven_zip_create_runtime; |
| @@ -412,7 +412,7 @@ fn preview_action_kind_keeps_all_existing_tags() { | ||
| 412 | 412 | matches!(decoded(&bytes), Message::Accepted { action: actual, encryption: true } if actual == action) |
| 413 | 413 | ); |
| 414 | 414 | } |
| 415 | 삭제: reject_decode(&raw(100, &[4, 1])); | |
| 415 | 추가: reject_decode(&raw(100, &[5, 1])); | |
| 416 | 416 | reject_decode(&raw(8, &[])); |
| 417 | 417 | reject_decode(&raw(114, &[])); |
| 418 | 418 | } |
| @@ -0,0 +1,413 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: | |
| 3 | 추가: fn request(windows: bool) -> Action { | |
| 4 | 추가: let (source, output_file) = if windows { | |
| 5 | 추가: ( | |
| 6 | 추가: NativePath::Windows("C:\\s".encode_utf16().collect()), | |
| 7 | 추가: NativePath::Windows("C:\\o.7z".encode_utf16().collect()), | |
| 8 | 추가: ) | |
| 9 | 추가: } else { | |
| 10 | 추가: ( | |
| 11 | 추가: NativePath::Unix(b"/s".to_vec()), | |
| 12 | 추가: NativePath::Unix(b"/o.7z".to_vec()), | |
| 13 | 추가: ) | |
| 14 | 추가: }; | |
| 15 | 추가: Action::CreateSevenZip { | |
| 16 | 추가: sources: vec![Source { | |
| 17 | 추가: path: source, | |
| 18 | 추가: archive_name: "한글".to_owned(), | |
| 19 | 추가: }], | |
| 20 | 추가: output_file, | |
| 21 | 추가: method: SevenZipMethod::Lzma2, | |
| 22 | 추가: solid: false, | |
| 23 | 추가: encryption: Encryption::None, | |
| 24 | 추가: } | |
| 25 | 추가: } | |
| 26 | 추가: | |
| 27 | 추가: fn start(action: Action) -> Start { | |
| 28 | 추가: Start { | |
| 29 | 추가: action, | |
| 30 | 추가: limits: Limits::default(), | |
| 31 | 추가: } | |
| 32 | 추가: } | |
| 33 | 추가: | |
| 34 | 추가: fn guarded(start: Start) -> GuardedStart { | |
| 35 | 추가: GuardedStart { | |
| 36 | 추가: ceiling: Limits { | |
| 37 | 추가: input: start.limits.input, | |
| 38 | 추가: output: 64 * 1024 * 1024 * 1024, | |
| 39 | 추가: entries: 200_000, | |
| 40 | 추가: }, | |
| 41 | 추가: start, | |
| 42 | 추가: interactive: false, | |
| 43 | 추가: } | |
| 44 | 추가: } | |
| 45 | 추가: | |
| 46 | 추가: fn encode(message: &Message) -> Vec<u8> { | |
| 47 | 추가: let mut bytes = Vec::new(); | |
| 48 | 추가: Writer::new(&mut bytes, 17).send(message).unwrap(); | |
| 49 | 추가: bytes | |
| 50 | 추가: } | |
| 51 | 추가: | |
| 52 | 추가: fn decode(bytes: &[u8]) -> Message { | |
| 53 | 추가: let mut reader = Reader::new(bytes); | |
| 54 | 추가: let (job, sequence, message) = reader.read().unwrap().unwrap(); | |
| 55 | 추가: assert_eq!((job, sequence), (17, 0)); | |
| 56 | 추가: assert!(reader.read().unwrap().is_none()); | |
| 57 | 추가: message | |
| 58 | 추가: } | |
| 59 | 추가: | |
| 60 | 추가: fn raw(kind: u16, body: &[u8]) -> Vec<u8> { | |
| 61 | 추가: let mut bytes = b"ZAW1\x01\x00".to_vec(); | |
| 62 | 추가: bytes.extend(kind.to_le_bytes()); | |
| 63 | 추가: bytes.extend((body.len() as u32).to_le_bytes()); | |
| 64 | 추가: bytes.extend([0; 4]); | |
| 65 | 추가: bytes.extend(17u64.to_le_bytes()); | |
| 66 | 추가: bytes.extend(0u64.to_le_bytes()); | |
| 67 | 추가: bytes.extend(body); | |
| 68 | 추가: bytes | |
| 69 | 추가: } | |
| 70 | 추가: | |
| 71 | 추가: fn reject_encode(message: Message) { | |
| 72 | 추가: let mut bytes = Vec::new(); | |
| 73 | 추가: assert_eq!( | |
| 74 | 추가: Writer::new(&mut bytes, 17) | |
| 75 | 추가: .send(&message) | |
| 76 | 추가: .unwrap_err() | |
| 77 | 추가: .kind(), | |
| 78 | 추가: std::io::ErrorKind::InvalidData | |
| 79 | 추가: ); | |
| 80 | 추가: assert!(bytes.is_empty()); | |
| 81 | 추가: } | |
| 82 | 추가: | |
| 83 | 추가: fn reject_decode(bytes: &[u8]) { | |
| 84 | 추가: assert_eq!( | |
| 85 | 추가: Reader::new(bytes).read().unwrap_err().kind(), | |
| 86 | 추가: std::io::ErrorKind::InvalidData | |
| 87 | 추가: ); | |
| 88 | 추가: } | |
| 89 | 추가: | |
| 90 | 추가: #[test] | |
| 91 | 추가: fn request_preserves_agreed_field_order_and_native_encodings() { | |
| 92 | 추가: for windows in [false, true] { | |
| 93 | 추가: let start = start(request(windows)); | |
| 94 | 추가: assert_eq!(start.action.kind(), ActionKind::CreateSevenZip); | |
| 95 | 추가: let mut expected = vec![4, 1, 0, 0, 0]; | |
| 96 | 추가: if windows { | |
| 97 | 추가: expected.extend(b"\x02\x04\x00\x00\x00C\x00:\x00\\\x00s\x00"); | |
| 98 | 추가: } else { | |
| 99 | 추가: expected.extend(b"\x01\x02\x00\x00\x00/s"); | |
| 100 | 추가: } | |
| 101 | 추가: expected.extend(b"\x06\x00\x00\x00\xed\x95\x9c\xea\xb8\x80"); | |
| 102 | 추가: if windows { | |
| 103 | 추가: expected.extend(b"\x02\x07\x00\x00\x00C\x00:\x00\\\x00o\x00.\x007\x00z\x00"); | |
| 104 | 추가: } else { | |
| 105 | 추가: expected.extend(b"\x01\x05\x00\x00\x00/o.7z"); | |
| 106 | 추가: } | |
| 107 | 추가: expected.extend([0, 0, 0]); | |
| 108 | 추가: expected.extend(u64::MAX.to_le_bytes()); | |
| 109 | 추가: expected.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes()); | |
| 110 | 추가: expected.extend(10_000u32.to_le_bytes()); | |
| 111 | 추가: let bytes = encode(&Message::Start(start.clone())); | |
| 112 | 추가: assert_eq!(bytes, raw(1, &expected)); | |
| 113 | 추가: match decode(&bytes) { | |
| 114 | 추가: Message::Start(actual) => assert_eq!(actual, start), | |
| 115 | 추가: other => panic!("{other:?}"), | |
| 116 | 추가: } | |
| 117 | 추가: let guarded = guarded(start); | |
| 118 | 추가: assert!(guarded.valid()); | |
| 119 | 추가: expected.extend(u64::MAX.to_le_bytes()); | |
| 120 | 추가: expected.extend((64u64 * 1024 * 1024 * 1024).to_le_bytes()); | |
| 121 | 추가: expected.extend(200_000u32.to_le_bytes()); | |
| 122 | 추가: expected.push(0); | |
| 123 | 추가: let bytes = encode(&Message::StartGuarded(guarded.clone())); | |
| 124 | 추가: assert_eq!(bytes, raw(6, &expected)); | |
| 125 | 추가: match decode(&bytes) { | |
| 126 | 추가: Message::StartGuarded(actual) => assert_eq!(actual, guarded), | |
| 127 | 추가: other => panic!("{other:?}"), | |
| 128 | 추가: } | |
| 129 | 추가: } | |
| 130 | 추가: } | |
| 131 | 추가: | |
| 132 | 추가: #[test] | |
| 133 | 추가: fn unsupported_options_remain_structurally_valid_without_silent_conversion() { | |
| 134 | 추가: for solid in [false, true] { | |
| 135 | 추가: for encryption in [Encryption::None, Encryption::Aes256] { | |
| 136 | 추가: let mut action = request(false); | |
| 137 | 추가: if let Action::CreateSevenZip { | |
| 138 | 추가: solid: actual_solid, | |
| 139 | 추가: encryption: actual_encryption, | |
| 140 | 추가: .. | |
| 141 | 추가: } = &mut action | |
| 142 | 추가: { | |
| 143 | 추가: *actual_solid = solid; | |
| 144 | 추가: *actual_encryption = encryption; | |
| 145 | 추가: } | |
| 146 | 추가: let start = start(action); | |
| 147 | 추가: match decode(&encode(&Message::Start(start.clone()))) { | |
| 148 | 추가: Message::Start(actual) => assert_eq!(actual, start), | |
| 149 | 추가: other => panic!("{other:?}"), | |
| 150 | 추가: } | |
| 151 | 추가: } | |
| 152 | 추가: } | |
| 153 | 추가: } | |
| 154 | 추가: | |
| 155 | 추가: #[test] | |
| 156 | 추가: fn creation_never_accepts_interactive_conflict_requests() { | |
| 157 | 추가: let start = start(request(false)); | |
| 158 | 추가: reject_encode(Message::StartInteractive(start.clone())); | |
| 159 | 추가: let bytes = encode(&Message::Start(start.clone())); | |
| 160 | 추가: reject_decode(&raw(4, &bytes[32..])); | |
| 161 | 추가: let mut guarded = guarded(start); | |
| 162 | 추가: guarded.interactive = true; | |
| 163 | 추가: assert!(!guarded.valid()); | |
| 164 | 추가: reject_encode(Message::StartGuarded(guarded)); | |
| 165 | 추가: let mut bytes = encode(&Message::StartGuarded(self::guarded(self::start(request( | |
| 166 | 추가: false, | |
| 167 | 추가: ))))); | |
| 168 | 추가: *bytes.last_mut().unwrap() = 1; | |
| 169 | 추가: reject_decode(&bytes); | |
| 170 | 추가: } | |
| 171 | 추가: | |
| 172 | 추가: #[test] | |
| 173 | 추가: fn truncated_unknown_and_trailing_creation_fields_are_rejected() { | |
| 174 | 추가: for windows in [false, true] { | |
| 175 | 추가: let bytes = encode(&Message::Start(start(request(windows)))); | |
| 176 | 추가: let body = &bytes[32..]; | |
| 177 | 추가: for length in 0..body.len() { | |
| 178 | 추가: reject_decode(&raw(1, &body[..length])); | |
| 179 | 추가: } | |
| 180 | 추가: let mut trailing = body.to_vec(); | |
| 181 | 추가: trailing.push(0); | |
| 182 | 추가: reject_decode(&raw(1, &trailing)); | |
| 183 | 추가: let method = body.len() - 20 - 3; | |
| 184 | 추가: for (at, value) in [(0, 5), (method, 1), (method + 1, 2), (method + 2, 2)] { | |
| 185 | 추가: let mut body = body.to_vec(); | |
| 186 | 추가: body[at] = value; | |
| 187 | 추가: reject_decode(&raw(1, &body)); | |
| 188 | 추가: } | |
| 189 | 추가: } | |
| 190 | 추가: } | |
| 191 | 추가: | |
| 192 | 추가: #[test] | |
| 193 | 추가: fn guarded_approval_never_expands_source_vector_string_or_path_wire_limits() { | |
| 194 | 추가: let mut action = request(false); | |
| 195 | 추가: if let Action::CreateSevenZip { sources, .. } = &mut action { | |
| 196 | 추가: sources[0].archive_name = "a".repeat(32_768); | |
| 197 | 추가: } | |
| 198 | 추가: let guarded = guarded(start(action.clone())); | |
| 199 | 추가: assert!(matches!( | |
| 200 | 추가: decode(&encode(&Message::StartGuarded(guarded))), | |
| 201 | 추가: Message::StartGuarded(_) | |
| 202 | 추가: )); | |
| 203 | 추가: if let Action::CreateSevenZip { sources, .. } = &mut action { | |
| 204 | 추가: sources[0].archive_name.push('a'); | |
| 205 | 추가: } | |
| 206 | 추가: reject_encode(Message::StartGuarded(self::guarded(start(action)))); | |
| 207 | 추가: for windows in [false, true] { | |
| 208 | 추가: let mut action = request(windows); | |
| 209 | 추가: if let Action::CreateSevenZip { sources, .. } = &mut action { | |
| 210 | 추가: sources[0].path = if windows { | |
| 211 | 추가: NativePath::Windows(vec![b'a' as u16; 32_769]) | |
| 212 | 추가: } else { | |
| 213 | 추가: NativePath::Unix(vec![b'a'; 32_769]) | |
| 214 | 추가: }; | |
| 215 | 추가: } | |
| 216 | 추가: reject_encode(Message::StartGuarded(self::guarded(start(action)))); | |
| 217 | 추가: } | |
| 218 | 추가: let mut action = request(false); | |
| 219 | 추가: if let Action::CreateSevenZip { sources, .. } = &mut action { | |
| 220 | 추가: *sources = vec![sources[0].clone(); 32_769]; | |
| 221 | 추가: } | |
| 222 | 추가: reject_encode(Message::StartGuarded(self::guarded(start(action)))); | |
| 223 | 추가: let bytes = encode(&Message::StartGuarded(self::guarded(start(request(false))))); | |
| 224 | 추가: for at in [1, 6, 12] { | |
| 225 | 추가: let mut body = bytes[32..].to_vec(); | |
| 226 | 추가: body[at..at + 4].copy_from_slice(&32_769u32.to_le_bytes()); | |
| 227 | 추가: reject_decode(&raw(6, &body)); | |
| 228 | 추가: } | |
| 229 | 추가: } | |
| 230 | 추가: | |
| 231 | 추가: #[test] | |
| 232 | 추가: fn action_kind_events_keep_existing_tags_and_append_creation_tag_four() { | |
| 233 | 추가: for (tag, action) in [ | |
| 234 | 추가: ActionKind::List, | |
| 235 | 추가: ActionKind::Extract, | |
| 236 | 추가: ActionKind::CreateZip, | |
| 237 | 추가: ActionKind::Preview, | |
| 238 | 추가: ActionKind::CreateSevenZip, | |
| 239 | 추가: ] | |
| 240 | 추가: .into_iter() | |
| 241 | 추가: .enumerate() | |
| 242 | 추가: { | |
| 243 | 추가: let encryption = action != ActionKind::CreateSevenZip; | |
| 244 | 추가: let bytes = encode(&Message::Accepted { action, encryption }); | |
| 245 | 추가: assert_eq!(bytes, raw(100, &[tag as u8, u8::from(encryption)])); | |
| 246 | 추가: assert!( | |
| 247 | 추가: matches!(decode(&bytes), Message::Accepted { action: actual, encryption: value } if actual == action && value == encryption) | |
| 248 | 추가: ); | |
| 249 | 추가: let scope = ResourceScope { | |
| 250 | 추가: entries: true, | |
| 251 | 추가: ..ResourceScope::default() | |
| 252 | 추가: }; | |
| 253 | 추가: let bytes = encode(&Message::ResourceRequired { | |
| 254 | 추가: challenge_id: 23, | |
| 255 | 추가: action, | |
| 256 | 추가: scope, | |
| 257 | 추가: usage: ResourceUsage::default(), | |
| 258 | 추가: soft_limits: Limits::default(), | |
| 259 | 추가: ceiling: guarded(start(request(false))).ceiling, | |
| 260 | 추가: }); | |
| 261 | 추가: assert_eq!(bytes[32 + 8], tag as u8); | |
| 262 | 추가: assert!( | |
| 263 | 추가: matches!(decode(&bytes), Message::ResourceRequired { action: actual, scope: value, .. } if actual == action && value == scope) | |
| 264 | 추가: ); | |
| 265 | 추가: let mut body = bytes[32..].to_vec(); | |
| 266 | 추가: body[8] = 5; | |
| 267 | 추가: reject_decode(&raw(110, &body)); | |
| 268 | 추가: } | |
| 269 | 추가: reject_decode(&raw(100, &[5, 0])); | |
| 270 | 추가: } | |
| 271 | 추가: | |
| 272 | 추가: #[test] | |
| 273 | 추가: fn zip_methods_and_existing_request_bytes_stay_independent() { | |
| 274 | 추가: for (tag, method) in [(0, Method::Store), (1, Method::Deflate)] { | |
| 275 | 추가: let action = Action::CreateZip { | |
| 276 | 추가: sources: Vec::new(), | |
| 277 | 추가: output_file: NativePath::Unix(b"/a.zip".to_vec()), | |
| 278 | 추가: method, | |
| 279 | 추가: encryption: Encryption::Aes256, | |
| 280 | 추가: }; | |
| 281 | 추가: let start = start(action); | |
| 282 | 추가: let mut body = b"\x02\x00\x00\x00\x00\x01\x06\x00\x00\x00/a.zip".to_vec(); | |
| 283 | 추가: body.extend([tag, 1]); | |
| 284 | 추가: body.extend(u64::MAX.to_le_bytes()); | |
| 285 | 추가: body.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes()); | |
| 286 | 추가: body.extend(10_000u32.to_le_bytes()); | |
| 287 | 추가: assert_eq!(encode(&Message::Start(start.clone())), raw(1, &body)); | |
| 288 | 추가: assert!(matches!(decode(&raw(1, &body)), Message::Start(actual) if actual == start)); | |
| 289 | 추가: body[16] = 2; | |
| 290 | 추가: reject_decode(&raw(1, &body)); | |
| 291 | 추가: } | |
| 292 | 추가: } | |
| 293 | 추가: | |
| 294 | 추가: struct Temporary(PathBuf); | |
| 295 | 추가: impl Temporary { | |
| 296 | 추가: fn new() -> Self { | |
| 297 | 추가: let root = std::env::var_os("TMPDIR") | |
| 298 | 추가: .map(PathBuf::from) | |
| 299 | 추가: .unwrap_or_else(|| { | |
| 300 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp") | |
| 301 | 추가: }); | |
| 302 | 추가: fs::create_dir_all(&root).unwrap(); | |
| 303 | 추가: let path = root.canonicalize().unwrap().join(format!( | |
| 304 | 추가: "zipelo-seven-create-{}-{}", | |
| 305 | 추가: std::process::id(), | |
| 306 | 추가: NEXT.fetch_add(1, Ordering::Relaxed) | |
| 307 | 추가: )); | |
| 308 | 추가: fs::create_dir(&path).unwrap(); | |
| 309 | 추가: Self(path) | |
| 310 | 추가: } | |
| 311 | 추가: fn run(&self, message: Message) -> Vec<Message> { | |
| 312 | 추가: let output = self.0.join("saved.7z"); | |
| 313 | 추가: fs::write(&output, b"existing user data").unwrap(); | |
| 314 | 추가: let bytes = encode(&message); | |
| 315 | 추가: let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker")) | |
| 316 | 추가: .env("TMPDIR", self.0.join("unavailable-temp")) | |
| 317 | 추가: .env("TMP", self.0.join("unavailable-temp")) | |
| 318 | 추가: .env("TEMP", self.0.join("unavailable-temp")) | |
| 319 | 추가: .stdin(Stdio::piped()) | |
| 320 | 추가: .stdout(Stdio::piped()) | |
| 321 | 추가: .stderr(Stdio::piped()) | |
| 322 | 추가: .spawn() | |
| 323 | 추가: .unwrap(); | |
| 324 | 추가: child.stdin.take().unwrap().write_all(&bytes).unwrap(); | |
| 325 | 추가: let output = child.wait_with_output().unwrap(); | |
| 326 | 추가: assert!(output.status.success(), "{:?}", output.stderr); | |
| 327 | 추가: assert!(output.stderr.is_empty()); | |
| 328 | 추가: let mut reader = Reader::new(output.stdout.as_slice()); | |
| 329 | 추가: let mut events = Vec::new(); | |
| 330 | 추가: while let Some((job, _, message)) = reader.read().unwrap() { | |
| 331 | 추가: assert_eq!(job, 17); | |
| 332 | 추가: events.push(message); | |
| 333 | 추가: } | |
| 334 | 추가: assert_eq!( | |
| 335 | 추가: fs::read(self.0.join("saved.7z")).unwrap(), | |
| 336 | 추가: b"existing user data" | |
| 337 | 추가: ); | |
| 338 | 추가: assert_eq!(fs::read_dir(&self.0).unwrap().count(), 1); | |
| 339 | 추가: events | |
| 340 | 추가: } | |
| 341 | 추가: } | |
| 342 | 추가: impl Drop for Temporary { | |
| 343 | 추가: fn drop(&mut self) { | |
| 344 | 추가: fs::remove_dir_all(&self.0).expect("7z 생성 시험 임시 폴더 정리에 실패함"); | |
| 345 | 추가: } | |
| 346 | 추가: } | |
| 347 | 추가: | |
| 348 | 추가: #[test] | |
| 349 | 추가: fn unsupported_options_fail_before_questions_or_file_access() { | |
| 350 | 추가: let temporary = Temporary::new(); | |
| 351 | 추가: for solid in [false, true] { | |
| 352 | 추가: for encryption in [Encryption::None, Encryption::Aes256] { | |
| 353 | 추가: if !solid && encryption == Encryption::None { | |
| 354 | 추가: continue; | |
| 355 | 추가: } | |
| 356 | 추가: for kind in [1, 6, 7] { | |
| 357 | 추가: let action = Action::CreateSevenZip { | |
| 358 | 추가: sources: vec![Source { | |
| 359 | 추가: path: NativePath::from_path(&temporary.0.join("missing/source")), | |
| 360 | 추가: archive_name: "source".to_owned(), | |
| 361 | 추가: }], | |
| 362 | 추가: output_file: NativePath::from_path(&temporary.0.join("saved.7z")), | |
| 363 | 추가: method: SevenZipMethod::Lzma2, | |
| 364 | 추가: solid, | |
| 365 | 추가: encryption, | |
| 366 | 추가: }; | |
| 367 | 추가: let start = start(action); | |
| 368 | 추가: let message = if kind == 1 { | |
| 369 | 추가: Message::Start(start) | |
| 370 | 추가: } else { | |
| 371 | 추가: let mut guarded = guarded(start); | |
| 372 | 추가: if kind == 7 { | |
| 373 | 추가: guarded.ceiling = guarded.start.limits; | |
| 374 | 추가: } | |
| 375 | 추가: Message::StartGuarded(guarded) | |
| 376 | 추가: }; | |
| 377 | 추가: let events = temporary.run(message); | |
| 378 | 추가: assert_eq!(events.len(), 2, "{events:?}"); | |
| 379 | 추가: assert!(matches!( | |
| 380 | 추가: events[0], | |
| 381 | 추가: Message::Accepted { | |
| 382 | 추가: action: ActionKind::CreateSevenZip, | |
| 383 | 추가: encryption: false | |
| 384 | 추가: } | |
| 385 | 추가: )); | |
| 386 | 추가: let terminal = terminal(&events); | |
| 387 | 추가: assert_eq!(terminal.outcome, Outcome::Failed); | |
| 388 | 추가: assert_eq!(terminal.error, ErrorCode::UnsupportedFeature); | |
| 389 | 추가: assert_eq!(terminal.publication, Publication::None); | |
| 390 | 추가: assert_eq!(terminal.created_count, 0); | |
| 391 | 추가: assert_eq!(terminal.retained_partial_count, 0); | |
| 392 | 추가: assert_eq!(terminal.cleanup, Cleanup::Complete); | |
| 393 | 추가: assert_eq!(terminal.durability, Durability::NotApplicable); | |
| 394 | 추가: } | |
| 395 | 추가: } | |
| 396 | 추가: } | |
| 397 | 추가: } | |
| 398 | 추가: | |
| 399 | 추가: #[test] | |
| 400 | 추가: fn existing_runtime_encryption_capability_is_preserved() { | |
| 401 | 추가: let temporary = Temporary::new(); | |
| 402 | 추가: let events = temporary.run(Message::Start(start(Action::List { | |
| 403 | 추가: archive: NativePath::from_path(&temporary.0.join("missing.zip")), | |
| 404 | 추가: }))); | |
| 405 | 추가: assert!(matches!( | |
| 406 | 추가: events[0], | |
| 407 | 추가: Message::Accepted { | |
| 408 | 추가: action: ActionKind::List, | |
| 409 | 추가: encryption: true | |
| 410 | 추가: } | |
| 411 | 추가: )); | |
| 412 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Failed); | |
| 413 | 추가: } |
| @@ -0,0 +1,47 @@ | ||
| 1 | 추가: #define _GNU_SOURCE | |
| 2 | 추가: #include <dlfcn.h> | |
| 3 | 추가: #include <errno.h> | |
| 4 | 추가: #include <stdlib.h> | |
| 5 | 추가: #include <string.h> | |
| 6 | 추가: #include <unistd.h> | |
| 7 | 추가: | |
| 8 | 추가: static int archive_fd = -1; | |
| 9 | 추가: static int finished; | |
| 10 | 추가: static ssize_t (*original_write)(int, const void *, size_t); | |
| 11 | 추가: static off64_t (*original_seek)(int, off64_t, int); | |
| 12 | 추가: | |
| 13 | 추가: __attribute__((constructor)) static void initialize(void) { | |
| 14 | 추가: original_write = dlsym(RTLD_NEXT, "write"); | |
| 15 | 추가: original_seek = dlsym(RTLD_NEXT, "lseek64"); | |
| 16 | 추가: } | |
| 17 | 추가: | |
| 18 | 추가: ssize_t write(int fd, const void *data, size_t count) { | |
| 19 | 추가: const unsigned char *bytes = data; | |
| 20 | 추가: if (archive_fd < 0 && count == 32 && !memcmp(bytes, (unsigned char[32]){0}, 32)) { | |
| 21 | 추가: archive_fd = fd; | |
| 22 | 추가: return original_write(fd, data, count); | |
| 23 | 추가: } | |
| 24 | 추가: const char *fault = getenv("ZIPELO_7Z_FAULT"); | |
| 25 | 추가: if (fd == archive_fd && fault) { | |
| 26 | 추가: if (!strcmp(fault, "encode-full")) { errno = ENOSPC; return -1; } | |
| 27 | 추가: if (count == 1 && bytes[0] == 0) { | |
| 28 | 추가: finished = 1; | |
| 29 | 추가: if (!strcmp(fault, "finish-full")) { errno = ENOSPC; return -1; } | |
| 30 | 추가: } | |
| 31 | 추가: if (!strcmp(fault, "header-write") && finished && count > 1 && bytes[0] == 1) { | |
| 32 | 추가: errno = EIO; return -1; | |
| 33 | 추가: } | |
| 34 | 추가: if (!strcmp(fault, "header-patch") && count == 32 && !memcmp(bytes, "7z", 2)) { | |
| 35 | 추가: errno = EIO; return -1; | |
| 36 | 추가: } | |
| 37 | 추가: } | |
| 38 | 추가: return original_write(fd, data, count); | |
| 39 | 추가: } | |
| 40 | 추가: | |
| 41 | 추가: off64_t lseek64(int fd, off64_t offset, int whence) { | |
| 42 | 추가: const char *fault = getenv("ZIPELO_7Z_FAULT"); | |
| 43 | 추가: if (fd == archive_fd && finished && fault && !strcmp(fault, "header-seek") && offset == 0 && whence == SEEK_SET) { | |
| 44 | 추가: errno = EIO; return -1; | |
| 45 | 추가: } | |
| 46 | 추가: return original_seek(fd, offset, whence); | |
| 47 | 추가: } |
| @@ -0,0 +1,167 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: | |
| 3 | 추가: #[test] | |
| 4 | 추가: fn uint64_boundaries_match_the_seven_zip_encoding() { | |
| 5 | 추가: for (value, expected) in [ | |
| 6 | 추가: (0, vec![0]), | |
| 7 | 추가: (127, vec![0x7f]), | |
| 8 | 추가: (128, vec![0x80, 0x80]), | |
| 9 | 추가: (16_383, vec![0xbf, 0xff]), | |
| 10 | 추가: (16_384, vec![0xc0, 0, 0x40]), | |
| 11 | 추가: (u32::MAX as u64, vec![0xf0, 0xff, 0xff, 0xff, 0xff]), | |
| 12 | 추가: (1u64 << 32, vec![0xf1, 0, 0, 0, 0]), | |
| 13 | 추가: (1u64 << 56, vec![0xff, 0, 0, 0, 0, 0, 0, 0, 1]), | |
| 14 | 추가: (u64::MAX, vec![0xff; 9]), | |
| 15 | 추가: ] { | |
| 16 | 추가: let mut header = Header::new(9).unwrap(); | |
| 17 | 추가: header.integer(value); | |
| 18 | 추가: assert_eq!(header.0, expected, "{value}"); | |
| 19 | 추가: } | |
| 20 | 추가: } | |
| 21 | 추가: | |
| 22 | 추가: #[test] | |
| 23 | 추가: fn bitmap_boundaries_keep_only_the_empty_stream_subset() { | |
| 24 | 추가: for (count, expected) in [(7, vec![0xaa]), (8, vec![0xaa]), (9, vec![0xaa, 0x80])] { | |
| 25 | 추가: let mut header = Header::new(2).unwrap(); | |
| 26 | 추가: header.bits((0..count).map(|n| n % 2 == 0)); | |
| 27 | 추가: assert_eq!(header.0, expected); | |
| 28 | 추가: } | |
| 29 | 추가: let mut header = Header::new(2).unwrap(); | |
| 30 | 추가: header.bits([true, false, false, true, true, false, true, false, true].into_iter()); | |
| 31 | 추가: assert_eq!(header.0, [0x9a, 0x80]); | |
| 32 | 추가: } | |
| 33 | 추가: | |
| 34 | 추가: #[test] | |
| 35 | 추가: fn encoder_dictionary_memory_and_packed_bound_are_checked() { | |
| 36 | 추가: let settings = options().unwrap(); | |
| 37 | 추가: assert_eq!(settings.lzma_options.dict_size, 1_048_576); | |
| 38 | 추가: assert!(settings.lzma_options.get_memory_usage() <= 32 * 1024); | |
| 39 | 추가: assert_eq!( | |
| 40 | 추가: (2 | (DICTIONARY_PROPERTY as u32 & 1)) << (DICTIONARY_PROPERTY / 2 + 11), | |
| 41 | 추가: DICTIONARY | |
| 42 | 추가: ); | |
| 43 | 추가: assert_eq!(packed_bound(0), Ok(1)); | |
| 44 | 추가: assert_eq!(packed_bound(65_536), Ok(262_145)); | |
| 45 | 추가: assert_eq!(packed_bound(u64::MAX / 4), Ok(u64::MAX - 2)); | |
| 46 | 추가: assert_eq!(packed_bound(u64::MAX / 4 + 1), Err(ErrorCode::Limit)); | |
| 47 | 추가: } | |
| 48 | 추가: | |
| 49 | 추가: #[test] | |
| 50 | 추가: fn encoding_preserves_source_crc_and_respects_stream_boundaries() { | |
| 51 | 추가: use lzma_rust2::Lzma2Reader; | |
| 52 | 추가: for size in [1, 65_535, 65_536, 65_537, 131_081] { | |
| 53 | 추가: let expected: Vec<u8> = (0..size).map(|n| ((n * 73 + n / 17) % 251) as u8).collect(); | |
| 54 | 추가: let mut input = spool::temporary().unwrap(); | |
| 55 | 추가: input.write_all(&expected).unwrap(); | |
| 56 | 추가: let mut output = spool::temporary().unwrap(); | |
| 57 | 추가: output.write_all(&[0; 32]).unwrap(); | |
| 58 | 추가: let stream = pack(&mut input, size as u64, &mut output, 0, &mut || Ok(())).unwrap(); | |
| 59 | 추가: assert_eq!(stream.size, size as u64); | |
| 60 | 추가: assert_eq!(stream.crc, crc32(0, &expected)); | |
| 61 | 추가: assert!(stream.packed <= packed_bound(size as u64).unwrap()); | |
| 62 | 추가: output.seek(SeekFrom::Start(32)).unwrap(); | |
| 63 | 추가: let mut actual = Vec::new(); | |
| 64 | 추가: Lzma2Reader::new(output.take(stream.packed), DICTIONARY, None) | |
| 65 | 추가: .read_to_end(&mut actual) | |
| 66 | 추가: .unwrap(); | |
| 67 | 추가: assert_eq!(actual, expected); | |
| 68 | 추가: } | |
| 69 | 추가: } | |
| 70 | 추가: | |
| 71 | 추가: #[test] | |
| 72 | 추가: fn monitored_encoder_output_preserves_cancellation_error() { | |
| 73 | 추가: let mut file = spool::temporary().unwrap(); | |
| 74 | 추가: let mut check = || Err(ErrorCode::None); | |
| 75 | 추가: let mut sink = Sink { | |
| 76 | 추가: file: &mut file, | |
| 77 | 추가: check: &mut check, | |
| 78 | 추가: error: None, | |
| 79 | 추가: written: 0, | |
| 80 | 추가: bound: 1, | |
| 81 | 추가: crc: 0, | |
| 82 | 추가: base: 0, | |
| 83 | 추가: entries: 0, | |
| 84 | 추가: reported: Instant::now(), | |
| 85 | 추가: }; | |
| 86 | 추가: assert!(sink.write_all(b"x").is_err()); | |
| 87 | 추가: assert_eq!(sink.error, Some(ErrorCode::None)); | |
| 88 | 추가: assert_eq!(sink.written, 0); | |
| 89 | 추가: } | |
| 90 | 추가: | |
| 91 | 추가: #[test] | |
| 92 | 추가: fn every_encoding_checkpoint_preserves_cooperative_cancellation() { | |
| 93 | 추가: struct Stop { | |
| 94 | 추가: at: usize, | |
| 95 | 추가: seen: usize, | |
| 96 | 추가: } | |
| 97 | 추가: impl Monitor for Stop { | |
| 98 | 추가: fn check(&mut self) -> Result<()> { | |
| 99 | 추가: self.seen += 1; | |
| 100 | 추가: if self.at == self.seen { | |
| 101 | 추가: Err(ErrorCode::None) | |
| 102 | 추가: } else { | |
| 103 | 추가: Ok(()) | |
| 104 | 추가: } | |
| 105 | 추가: } | |
| 106 | 추가: } | |
| 107 | 추가: let mut input = spool::temporary().unwrap(); | |
| 108 | 추가: input.write_all(b"checkpoint").unwrap(); | |
| 109 | 추가: let mut maximum = Stop { | |
| 110 | 추가: at: usize::MAX, | |
| 111 | 추가: seen: 0, | |
| 112 | 추가: }; | |
| 113 | 추가: let mut output = spool::temporary().unwrap(); | |
| 114 | 추가: output.write_all(&[0; 32]).unwrap(); | |
| 115 | 추가: pack(&mut input, 10, &mut output, 0, &mut maximum).unwrap(); | |
| 116 | 추가: for at in 1..=maximum.seen { | |
| 117 | 추가: let mut output = spool::temporary().unwrap(); | |
| 118 | 추가: output.write_all(&[0; 32]).unwrap(); | |
| 119 | 추가: let result = pack(&mut input, 10, &mut output, 0, &mut Stop { at, seen: 0 }); | |
| 120 | 추가: assert!(matches!(result, Err(ErrorCode::None)), "checkpoint {at}"); | |
| 121 | 추가: } | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: #[test] | |
| 125 | 추가: fn header_metadata_is_charged_before_source_capture() { | |
| 126 | 추가: use std::path::PathBuf; | |
| 127 | 추가: let root = std::env::var_os("TMPDIR") | |
| 128 | 추가: .map(PathBuf::from) | |
| 129 | 추가: .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")); | |
| 130 | 추가: std::fs::create_dir_all(&root).unwrap(); | |
| 131 | 추가: let root = root | |
| 132 | 추가: .canonicalize() | |
| 133 | 추가: .unwrap() | |
| 134 | 추가: .join(format!("7zc-budget-{}", std::process::id())); | |
| 135 | 추가: std::fs::create_dir(&root).unwrap(); | |
| 136 | 추가: let path = root.join("empty"); | |
| 137 | 추가: std::fs::write(&path, b"").unwrap(); | |
| 138 | 추가: let mut plan = Plan::new( | |
| 139 | 추가: &[Source { | |
| 140 | 추가: path: NativePath::from_path(&path), | |
| 141 | 추가: archive_name: "empty".into(), | |
| 142 | 추가: }], | |
| 143 | 추가: Limits::default(), | |
| 144 | 추가: &mut || Ok(()), | |
| 145 | 추가: ) | |
| 146 | 추가: .unwrap(); | |
| 147 | 추가: struct Tiny; | |
| 148 | 추가: impl Monitor for Tiny { | |
| 149 | 추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits { | |
| 150 | 추가: crate::archive::MetadataLimits { | |
| 151 | 추가: bytes: 1, | |
| 152 | 추가: ..Default::default() | |
| 153 | 추가: } | |
| 154 | 추가: } | |
| 155 | 추가: fn check(&mut self) -> Result<()> { | |
| 156 | 추가: Ok(()) | |
| 157 | 추가: } | |
| 158 | 추가: fn progress(&mut self, _: Stage, _: u64, _: Option<u64>, _: u32) -> Result<()> { | |
| 159 | 추가: panic!("헤더 예산 검사 전 캡처가 시작됨") | |
| 160 | 추가: } | |
| 161 | 추가: } | |
| 162 | 추가: assert!(matches!( | |
| 163 | 추가: archive(&mut plan, Limits::default(), &mut Tiny), | |
| 164 | 추가: Err(ErrorCode::Limit) | |
| 165 | 추가: )); | |
| 166 | 추가: std::fs::remove_dir_all(root).unwrap(); | |
| 167 | 추가: } |
| @@ -0,0 +1,61 @@ | ||
| 1 | 추가: """1 GiB 입력의 7z 작성 메모리와 게시 결과를 검증함.""" | |
| 2 | 추가: | |
| 3 | 추가: import json | |
| 4 | 추가: import os | |
| 5 | 추가: from pathlib import Path | |
| 6 | 추가: import struct | |
| 7 | 추가: import subprocess | |
| 8 | 추가: import sys | |
| 9 | 추가: import tempfile | |
| 10 | 추가: import time | |
| 11 | 추가: | |
| 12 | 추가: | |
| 13 | 추가: def native(path): | |
| 14 | 추가: value = os.fsencode(path) | |
| 15 | 추가: return b"\x01" + struct.pack("<I", len(value)) + value | |
| 16 | 추가: | |
| 17 | 추가: | |
| 18 | 추가: with tempfile.TemporaryDirectory(prefix="7zc-memory-", dir=os.environ["TMPDIR"]) as temporary: | |
| 19 | 추가: root = Path(temporary) | |
| 20 | 추가: source = root / "source" | |
| 21 | 추가: with source.open("xb") as output: | |
| 22 | 추가: output.truncate(1024 * 1024 * 1024) | |
| 23 | 추가: archive = root / "result.7z" | |
| 24 | 추가: body = b"\x04" + struct.pack("<I", 1) + native(source) | |
| 25 | 추가: body += struct.pack("<I", 11) + b"payload.bin" + native(archive) | |
| 26 | 추가: body += b"\x00\x00\x00" + struct.pack("<QQI", 2**64 - 1, 16 * 1024**3, 10000) | |
| 27 | 추가: frame = b"ZAW1" + struct.pack("<HHIIQQ", 1, 1, len(body), 0, 17, 0) + body | |
| 28 | 추가: started = time.monotonic() | |
| 29 | 추가: result = subprocess.run( | |
| 30 | 추가: ["/usr/bin/time", "-f", "%M", "-o", str(root / "rss"), sys.argv[1]], | |
| 31 | 추가: input=frame, capture_output=True, timeout=180, | |
| 32 | 추가: env={**os.environ, "TMPDIR": str(root), "TMP": str(root), "TEMP": str(root)}, | |
| 33 | 추가: ) | |
| 34 | 추가: assert result.returncode == 0, result.stderr | |
| 35 | 추가: assert not result.stderr, result.stderr | |
| 36 | 추가: at = 0 | |
| 37 | 추가: terminal = None | |
| 38 | 추가: outputs = 0 | |
| 39 | 추가: while at < len(result.stdout): | |
| 40 | 추가: magic, version, kind, size, reserved, job, sequence = struct.unpack_from("<4sHHIIQQ", result.stdout, at) | |
| 41 | 추가: assert (magic, version, reserved, job) == (b"ZAW1", 1, 0, 17) | |
| 42 | 추가: at += 32 | |
| 43 | 추가: payload = result.stdout[at:at + size] | |
| 44 | 추가: assert len(payload) == size | |
| 45 | 추가: at += size | |
| 46 | 추가: if kind == 105: | |
| 47 | 추가: outputs += 1 | |
| 48 | 추가: if kind == 106: | |
| 49 | 추가: assert at == len(result.stdout) | |
| 50 | 추가: terminal = payload | |
| 51 | 추가: assert terminal[:3] == b"\x00\x00\x02", terminal | |
| 52 | 추가: assert struct.unpack_from("<QQ", terminal, 3) == (1, 0) | |
| 53 | 추가: assert outputs == 1 and archive.is_file() | |
| 54 | 추가: rss = int((root / "rss").read_text()) | |
| 55 | 추가: assert rss <= 64 * 1024, rss | |
| 56 | 추가: print(json.dumps({ | |
| 57 | 추가: "seven_zip_creation_input_bytes": source.stat().st_size, | |
| 58 | 추가: "archive_bytes": archive.stat().st_size, | |
| 59 | 추가: "peak_rss_kib": rss, | |
| 60 | 추가: "elapsed_seconds": round(time.monotonic() - started, 3), | |
| 61 | 추가: })) |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기