ZIP32 손상 복구 작업자와 공용 계약을 구현함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
438a5cb22693ae03d9e989f073eeaaac55eea975- 부모
- c5fff77
변경된 파일 15개
+1,989-40| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | # ZIP 손상 복구 설계와 작업자 계약안 |
| 2 | 2 | |
| 3 | 삭제: 상태: 히나타가 8e178e0의 결과/경고 의미에 동의했고 카논이 d525c7c의 표본 대조를 마쳤다. 활성 wire의 MissingVolume=14와 초기 제안이 충돌해 복구 오류 태그를 15/16으로 정정 제안하며, 이 숫자의 재합의 전에는 제품 타입/codec을 활성화하지 않는다. 제품 구현은 시작하지 않았다. [PLANS 8.10](PLANS.md#810-손상-파일-복구)과 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다. 기계 판독용 제안은 [작업자 계약](../experiments/rust-archive-worker/contract.json)의 zip_recovery_proposal이다. 기존 revision 3, 활성 태그와 일반 목록/해제의 엄격한 무결성 검사를 바꾸지 않는다. | |
| 3 | 추가: 상태: 히나타가 결과/경고 의미와 오류 태그 15/16에 재동의했다. 공용 타입, codec과 ZIP32 복구 작업자를 구현했으며 frontend 연동과 독립 구현 리뷰는 남아 있다. [PLANS 8.10](PLANS.md#810-손상-파일-복구)과 [8.13](PLANS.md#813-진행과-완료-판단)을 따른다. [작업자 계약](../experiments/rust-archive-worker/contract.json)의 zip_recovery_proposal 키는 초기 문서와의 연결을 위해 유지하지만 status에 명시한 태그는 활성 상태다. Frame version 1, revision 3와 기존 태그 및 일반 목록/해제의 엄격한 검사는 유지한다. | |
| 4 | 추가: | |
| 5 | 추가: 결과 계약 [동의](https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904112564)와 오류 숫자 [재동의](https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904158997)를 확인했다. 초기 14/15 제안이 기존 MissingVolume=14와 충돌한 기록은 보존하며 실제 활성 값은 RecoveryIncomplete=15, RecoveryImpossible=16이다. | |
| 4 | 6 | |
| 5 | 7 | ## 1. 복구 범위와 한계 |
| 6 | 8 | |
| @@ -51,11 +53,11 @@ | ||
| 51 | 53 | |
| 52 | 54 | ## 4. 앱과 작업자 계약 제안 |
| 53 | 55 | |
| 54 | 삭제: 이 절의 숫자는 합의 전 제안이며 활성 codec에 아직 추가하지 않는다. Frame version=1, 32바이트 헤더, 1 MiB body, 방향별 sequence, 32768 문자열/벡터 전송 상한과 기존 revision 3를 유지한다. 기존 Preview kind 111~113과 VolumeProblem kind 114를 재사용하지 않는다. 실제 wire의 MissingVolume=14도 유지한다. 기존 contract.json의 error_tags 색인은 이 오류를 누락하므로 새 태그 검사는 문서 색인뿐 아니라 활성 wire와 대조한다. 초기 제안의 복구 오류 14/15는 충돌하므로 아래 15/16으로 정정하며 결과 의미와 다른 숫자는 동일하다. | |
| 56 | 추가: 이 절의 숫자와 결과 의미는 공동 합의되었고 공용 타입과 codec에 반영했다. Frame version=1, 32바이트 헤더, 1 MiB body, 방향별 sequence, 32768 문자열/벡터 전송 상한과 기존 revision 3를 유지한다. 기존 Preview kind 111~113과 VolumeProblem kind 114를 재사용하지 않는다. 실제 wire의 MissingVolume=14도 유지한다. 기존 contract.json의 error_tags 색인은 이 오류를 누락하므로 새 태그 검사는 문서 색인뿐 아니라 활성 wire와 대조한다. 초기 제안의 복구 오류 14/15는 충돌하여 아래 15/16으로 정정하고 재합의했다. 결과 의미와 다른 숫자는 동일하다. | |
| 55 | 57 | |
| 56 | 58 | ### 요청과 이벤트 |
| 57 | 59 | |
| 58 | 삭제: - Action::RecoverZip 및 ActionKind::RecoverZip=5를 제안한다. 요청 필드 순서는 archive:NativePath, output_file:NativePath다. Start(kind 1)와 StartGuarded(kind 6, interactive=false)에 허용하며 StartInteractive 및 interactive=true는 양쪽 codec에서 거부한다. Accepted.encryption=false이고 PasswordRequired/ConflictRequired를 보내지 않는다. 기존 ResourceRequired.action에 같은 새 태그를 사용한다. | |
| 60 | 추가: - Action::RecoverZip 및 ActionKind::RecoverZip=5를 사용한다. 요청 필드 순서는 archive:NativePath, output_file:NativePath다. Start(kind 1)와 StartGuarded(kind 6, interactive=false)에 허용하며 StartInteractive 및 interactive=true는 양쪽 codec에서 거부한다. Accepted.encryption=false이고 PasswordRequired/ConflictRequired를 보내지 않는다. 기존 ResourceRequired.action에 같은 새 태그를 사용한다. | |
| 59 | 61 | - RecoveryEntry(kind 115): candidate_id:u32, source_offset:u64, name:Option<UTF8>, kind:Option<EntryKind>, status:RecoveryStatus, reason:RecoveryReason, declared_size:Option<u64>, verified_size:Option<u64>, sha256:Option<[u8;32]> 순서다. 중앙 목록의 후보도 로컬 오프셋 순으로 정렬한 0 기반 ID를 한 번씩 보낸다. 일반 Entry/ListEnd/ListId나 preview 프레임은 보내지 않는다. |
| 60 | 62 | - RecoveryMode는 CentralDirectory=0, LocalChain=1이다. RecoveryStatus는 Verified=0, Lost=1, Unverified=2다. RecoveryReason은 None=0, HeaderRebuilt=1, Truncated=2, CrcMismatch=3, DecodeFailure=4, BoundaryUnknown=5, UnsupportedFeature=6, MetadataMissing=7이다. 유효 reason은 Verified에서 None/HeaderRebuilt/MetadataMissing, Lost에서 Truncated/CrcMismatch/DecodeFailure, Unverified에서 BoundaryUnknown/UnsupportedFeature/MetadataMissing다. 서로 모순되는 조합은 Protocol이다. |
| 61 | 63 | - Verified에는 확정된 이름이 필요하다. Verified 파일은 declared_size와 verified_size가 같고 SHA256을 가지며 Verified 폴더는 두 크기 0, 해시 None이다. Lost/Unverified에는 verified_size나 SHA256을 싣지 않는다. 불명 이름은 None이며 불명 크기를 0으로 만들지 않는다. kind는 Some(File)/Some(Directory)만 허용하고 판별 불가 후보는 None이다. Verified에는 확정된 kind가 필요하며 링크/특수 종류를 일반 파일로 위장하지 않는다. 이름은 평문 UI에서만 제한 길이로 렌더링하고 경로나 markup으로 실행하지 않는다. |
| @@ -78,7 +80,7 @@ | ||
| 78 | 80 | - 결과는 검증되어 포함됨, 유실됨, 무결성 미확인을 각각 표시하고 사유를 구분한다. 모르는 파일명/원래 총수는 알 수 없음으로 표시하며 유실 0개나 진행률 100%를 추측하지 않는다. 완전한 목록이 있을 때도 파일별 CRC 검증을 원본 진위 보증으로 표현하지 않는다. |
| 79 | 81 | - 정상 완료는 복구본 저장 완료, 부분 결과는 일부 항목만 복구함과 전체 목록/무결성 미확인 경고 및 실제 저장 위치를 보여준다. 복구 불가는 복구 가능한 항목 없음으로 구분한다. 세부 결과를 일반 파일 목록 선택과 섞지 않는다. |
| 80 | 82 | - 복구본은 일반 ZIP이며 별도 sidecar 보고서나 영구 인증서를 자동 생성하지 않는다. 이번 작업의 경고를 결과 화면과 명시적 복구본 열기 전환에 유지한다. 나중의 독립적인 일반 ZIP 목록은 원본에서 무엇이 유실됐는지 증명하지 않으며 완전 복구 판정으로 다시 사용하지 않는다. |
| 81 | 삭제: - frontend 구현 시 --ui-scenario에 복구 진행, 완전/부분/불가 결과, 미확인 목록, 취소, 저장 실패와 자원 질문을 추가하고 해당 시험 및 docs/ui-scenario-guide.md를 같은 PR에서 갱신한다. 이번 설계 PR 자체는 UI 변경 없음이다. | |
| 83 | 추가: - frontend 구현 시 --ui-scenario에 복구 진행, 완전/부분/불가 결과, 미확인 목록, 취소, 저장 실패와 자원 질문을 추가하고 해당 시험 및 docs/ui-scenario-guide.md를 같은 PR에서 갱신한다. 현재 backend 변경에는 UI 변경 없음이다. frontend의 화면/시나리오 연동은 같은 PR의 후속 작업이다. | |
| 82 | 84 | |
| 83 | 85 | ## 6. 손상 표본과 수용 기준 |
| 84 | 86 | |
| @@ -89,13 +91,20 @@ | ||
| 89 | 91 | - 모든 표본에서 원본의 작업 전/후 SHA256 및 실제 원본 바이트가 같아야 한다. 복구 가능한 파일은 손상 전 독립 기대 manifest와 비교하고 Zipelo 및 독립 도구로 복구본을 풀어 파일 해시/상대 구조를 대조한다. 새로 계산한 결과 해시만으로 원본과 같다고 판단하지 않는다. |
| 90 | 92 | - PK 바이트가 든 본문, 위조 EOCD/중앙 목록, 겹친 범위/잘못된 길이, UTF-8/한글/빈 항목, data descriptor 경계, ZIP64/암호/분할/SFX 제외, unsafe path/충돌/링크와 프레임/후보 수/메타데이터 제한을 포함한다. 이름 추측이나 본문 내 서명 재탐색 없이 실패/부분 결과가 결정돼야 한다. |
| 91 | 93 | - 취소/부모 종료/원본 변경, 기존 및 검증 중 나타난 목적지, 쓰기/close/sync/부모 sync/정리 오류를 주입하고 실제 파일/Terminal/Output/내구성과 맞는지 확인한다. 손상과 무관한 Limit/DiskFull 등을 Lost로 가려 게시해서는 안 된다. |
| 92 | 삭제: - 계약 동의 뒤 backend 회귀와 python3 tests/ci/run_rust.py local 전체 결과, frontend 화면/시나리오 시험, Windows/Wayland 실기 및 독립 구현 리뷰를 PR 본문에 기록한다. 이번 문서 작성에는 제품 실행/성능/복구 시험을 수행하지 않는다. | |
| 94 | 추가: - 계약 동의 뒤 backend 회귀와 python3 tests/ci/run_rust.py local 전체 결과, frontend 화면/시나리오 시험, Windows/Wayland 실기 및 독립 구현 리뷰를 PR 본문에 기록한다. 현재 직접 검증한 backend 회귀에는 6종 실제 작업자 복구와 독립 Python ZIP 검증, 원본 보존 및 실패 주입이 포함된다. 전체 local 결과와 미실행 Windows/Wayland 실기는 PR 본문에서 구분한다. 성능/RSS의 별도 복구 전용 대용량 실기는 아직 수행하지 않았다. | |
| 93 | 95 | |
| 94 | 96 | ## 7. 구현 순서와 문서 관리 |
| 95 | 97 | |
| 96 | 삭제: 1. 하나는 이 설계와 contract.json의 제안만 올린다. 히나타의 결과/경고 계약 동의를 확인하기 전 제품 타입/codec/탐색기/작성기를 바꾸지 않는다. 병행하는 카논의 표본 대조 리뷰는 설계와 구현 수용 시험에 반영한다. | |
| 97 | 삭제: 2. 동의 뒤 공용 타입/codec 커밋과 작업 경로를 전달하고 backend 구현과 frontend 결과 화면의 파일 범위를 나눈다. 프레임 숫자와 결과 조합이 바뀌면 다시 함께 합의한다. | |
| 98 | 추가: 1. 결과 계약과 오류 숫자의 재합의를 확인하여 제품 타입/codec/탐색기/작성기를 구현했다. 카논의 표본 대조 리뷰와 독립 기대 해시를 backend 수용 시험에 반영했다. | |
| 99 | 추가: 2. 공용 타입/codec과 backend 커밋 및 작업 경로를 전달하며 frontend 결과 화면과 해당 시나리오/시험은 히나타가 담당한다. 프레임 숫자와 결과 조합이 바뀌면 다시 함께 합의한다. | |
| 98 | 100 | 3. 표본 기대 결과를 변경할 필요가 생기면 작성자와 근거를 먼저 합의한다. 실패를 숨기려고 표본이나 기존 엄격한 파서를 약화하지 않는다. |
| 99 | 101 | 4. 구현/실기 증거가 모인 뒤에만 README/릴리스 노트의 실제 지원 범위를 갱신하고 총관리자의 리뷰/병합 절차를 따른다. 원본 수정과 모든 손상 복구 보장은 완료 기준에 포함하지 않는다. |
| 100 | 102 | |
| 101 | 103 | 작업 사본은 tests/work/zip-recovery/r이다. 캐시/임시/검증 자료는 사본 밖 tests/work/zip-recovery 한 곳에만 두고, 이후 실행 시 TMPDIR과 CARGO_TARGET_DIR을 그 하위로 지정한다. PR 병합/종료 뒤 만든 사람이 작업 폴더를 정리하며 진행 중인 다른 담당자 자료는 지우지 않는다. |
| 104 | 추가: | |
| 105 | 추가: ## 8. 구현과 검증 위치 | |
| 106 | 추가: | |
| 107 | 추가: - backend 탐색/검증/원본 재확인은 zip_recovery.rs, Store 출력은 create.rs의 ZIP64 필드/중앙 목록 마무리를 재사용한다. 검증된 payload는 하나의 비공개 spool로 모으고 손상 항목의 임시 바이트는 되돌린다. CRC 또는 디코더 실패 전에 처리한 바이트도 자원 사용량에 남긴다. | |
| 108 | 추가: - 결과 파일을 일반 streaming 판독기로 다시 검증하고 항목 SHA256을 대조한다. 이 재검증/복사는 논리 해제량을 중복 과금하지 않으며 취소와 실제 진행 검사는 유지한다. 원본 변경 검사는 마지막 게시 callback 안에서 수행한다. | |
| 109 | 추가: - 제품 회귀는 tests/rust-archive-worker/recovery.rs와 recovery_checks.rs에 있다. tests/ci/test_zip_recovery_contract.py의 텍스트 읽기는 UTF-8을 명시하며 기존 오류 및 새 태그를 실제 wire와 비교한다. 기존 시험의 미등록 태그 경계는 새 할당 뒤 값으로 조정했다. 긴 소켓 시험은 열린 출력 폴더의 proc fd 경로로 같은 객체를 만들어 SUN_LEN에 의존하지 않는다. | |
| 110 | 추가: - frontend의 메시지 처리, 결과 화면, --ui-scenario/가이드와 Windows/Wayland 실제 실행은 별도 담당 검증이며 backend 시험 통과로 완료를 대신 선언하지 않는다. |
| @@ -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. 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.", | |
| 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. RecoverZip{archive:NativePath,output_file:NativePath} appends action tag 5; Start and noninteractive StartGuarded only.", | |
| 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. CreateSevenZip explicitly reports encryption=false; existing action capabilities are unchanged.", | |
| 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. RecoverZip also reports encryption=false.", | |
| 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.", |
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | "Output": "entry_id:optional, relative_name, disposition Created|PartialRetained|Removed|CommitUncertain; only this job outputs.", |
| 44 | 44 | "Terminal": { |
| 45 | 45 | "outcome": "Completed|Failed|Cancelled", |
| 46 | 삭제: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull", | |
| 46 | 추가: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest|DiskFull|MissingVolume|RecoveryIncomplete|RecoveryImpossible", | |
| 47 | 47 | "publication": "None|Partial|Complete|Uncertain", |
| 48 | 48 | "created_count": "u64", |
| 49 | 49 | "retained_partial_count": "u64", |
| @@ -62,7 +62,51 @@ | ||
| 62 | 62 | }, |
| 63 | 63 | "ConflictRequired": "Kind 108: challenge_id:u64, entry_id:u32, relative_name:UTF8, incoming_size:u64, existing_size:u64. One ordinary-file conflict at a time, after complete archive integrity validation. All three choices are permitted; links and file/directory type conflicts remain rejected.", |
| 64 | 64 | "ConflictResolved": "Kind 109: entry_id:u32, relative_name:UTF8, choice:ConflictChoice(u8). Emit for every resolved conflict, including automatically applied choices. This records the action and resolved name, not successful publication; successful overwrite or rename also requires Output Created. Skip emits no Output Created.", |
| 65 | 삭제: "ResourceRequired": "Kind 110: challenge_id:u64,action:ActionKind,scope:ResourceScope,usage:ResourceUsage,soft_limits:Limits,ceiling:Limits. ResourceScope is output:bool,entries:bool,ratio:bool. ResourceUsage fields in order are estimated_bytes:Option<u64>,actual_bytes:Option<u64>,estimated_entries:Option<u32>,actual_entries:Option<u32>,compressed_bytes:Option<u64>,ratio_output_bytes:Option<u64>,available_bytes:Option<u64>. None is unknown, not zero." | |
| 65 | 추가: "ResourceRequired": "Kind 110: challenge_id:u64,action:ActionKind,scope:ResourceScope,usage:ResourceUsage,soft_limits:Limits,ceiling:Limits. ResourceScope is output:bool,entries:bool,ratio:bool. ResourceUsage fields in order are estimated_bytes:Option<u64>,actual_bytes:Option<u64>,estimated_entries:Option<u32>,actual_entries:Option<u32>,compressed_bytes:Option<u64>,ratio_output_bytes:Option<u64>,available_bytes:Option<u64>. None is unknown, not zero.", | |
| 66 | 추가: "RecoveryEntry": { | |
| 67 | 추가: "fields_in_order": [ | |
| 68 | 추가: "candidate_id:u32", | |
| 69 | 추가: "source_offset:u64", | |
| 70 | 추가: "name:Option<UTF8>", | |
| 71 | 추가: "kind:Option<EntryKind>", | |
| 72 | 추가: "status:RecoveryStatus", | |
| 73 | 추가: "reason:RecoveryReason", | |
| 74 | 추가: "declared_size:Option<u64>", | |
| 75 | 추가: "verified_size:Option<u64>", | |
| 76 | 추가: "sha256:Option<[u8;32]>" | |
| 77 | 추가: ], | |
| 78 | 추가: "constraints": "One stable zero-based ordinal per known candidate, ordered by source local offset, with no duplicates. IDs are not List EntryIds. Name is absent rather than invented if unknown; strings/frame budgets remain unchanged. Only Some(File), Some(Directory) or unknown None; Verified requires a known kind. Never invent a type for an unknown candidate. Verified file has exact sizes and SHA256, directory has size zero and no hash. Lost/Unverified have no verified_size or hash. Unknown enum/field combinations are Protocol. Findings before final result are not saved outputs. Verified requires a known name and equal declared/verified sizes; verified directories have both sizes zero and no hash. Validate the explicit status/reason matrix. Source offsets strictly increase and must fall within source_bytes at summary validation; sums use checked arithmetic.", | |
| 79 | 추가: "valid_reasons": { | |
| 80 | 추가: "Verified": [ | |
| 81 | 추가: "None", | |
| 82 | 추가: "HeaderRebuilt", | |
| 83 | 추가: "MetadataMissing" | |
| 84 | 추가: ], | |
| 85 | 추가: "Lost": [ | |
| 86 | 추가: "Truncated", | |
| 87 | 추가: "CrcMismatch", | |
| 88 | 추가: "DecodeFailure" | |
| 89 | 추가: ], | |
| 90 | 추가: "Unverified": [ | |
| 91 | 추가: "BoundaryUnknown", | |
| 92 | 추가: "UnsupportedFeature", | |
| 93 | 추가: "MetadataMissing" | |
| 94 | 추가: ] | |
| 95 | 추가: } | |
| 96 | 추가: }, | |
| 97 | 추가: "RecoveryEnd": { | |
| 98 | 추가: "fields_in_order": [ | |
| 99 | 추가: "mode:RecoveryMode", | |
| 100 | 추가: "source_bytes:u64", | |
| 101 | 추가: "source_sha256:[u8;32]", | |
| 102 | 추가: "known_entries:Option<u32>", | |
| 103 | 추가: "verified_entries:u32", | |
| 104 | 추가: "lost_entries:u32", | |
| 105 | 추가: "unverified_entries:u32", | |
| 106 | 추가: "unknown_loss:bool" | |
| 107 | 추가: ], | |
| 108 | 추가: "constraints": "At most one summary after completed analysis and before publication. Counts equal emitted findings. Only a central inventory with one-to-one contiguous complete local coverage has known_entries equal to the count sum and unknown_loss=false. Missing inventory, gaps or ambiguous spans give known_entries=None and unknown_loss=true, including in CentralDirectory mode. LocalChain always has None/true. Unknown bytes never create a fabricated candidate or zero loss claim. No ListEnd/ListId or ordinary Entry/preview frames for recovery. A summary alone is not success or proof that a file exists." | |
| 109 | 추가: } | |
| 66 | 110 | }, |
| 67 | 111 | "lifecycle": [ |
| 68 | 112 | "Exactly one Start or StartInteractive; no automatic retry or fallback. Password/Cancel remain readable during work. ConflictReply is accepted only for a matching outstanding interactive conflict.", |
| @@ -189,7 +233,10 @@ | ||
| 189 | 233 | "Internal": 10, |
| 190 | 234 | "SourceChanged": 11, |
| 191 | 235 | "InvalidRequest": 12, |
| 192 | 삭제: "DiskFull": 13 | |
| 236 | 추가: "DiskFull": 13, | |
| 237 | 추가: "MissingVolume": 14, | |
| 238 | 추가: "RecoveryIncomplete": 15, | |
| 239 | 추가: "RecoveryImpossible": 16 | |
| 193 | 240 | }, |
| 194 | 241 | "disk_full_extension": { |
| 195 | 242 | "agreement_message_id": "3b01f4c4-c9b4-4c72-a9a0-b3df39979ea1", |
| @@ -245,7 +292,8 @@ | ||
| 245 | 292 | "Extract": 1, |
| 246 | 293 | "CreateZip": 2, |
| 247 | 294 | "Preview": 3, |
| 248 | 삭제: "CreateSevenZip": 4 | |
| 295 | 추가: "CreateSevenZip": 4, | |
| 296 | 추가: "RecoverZip": 5 | |
| 249 | 297 | }, |
| 250 | 298 | "seven_zip_method_tags": { |
| 251 | 299 | "Lzma2": 0 |
| @@ -269,9 +317,9 @@ | ||
| 269 | 317 | "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." |
| 270 | 318 | }, |
| 271 | 319 | "zip_recovery_proposal": { |
| 272 | 삭제: "status": "proposal-only; frontend-agreed-result-semantics; awaiting-corrected-error-tag-agreement; no-product-implementation", | |
| 320 | 추가: "status": "jointly-agreed; shared-types-codec-and-worker-implemented; frontend-integration-and-independent-implementation-review-pending", | |
| 273 | 321 | "design": "docs/zip-recovery-design.md", |
| 274 | 삭제: "basis": "PLANS 8.10. Never modify the source; reconstruct only separately validated members into a new archive. Existing active tags and revision 3 remain unchanged until joint agreement.", | |
| 322 | 추가: "basis": "PLANS 8.10. Joint result/warning and corrected tag agreement complete. RecoverZip=5, RecoveryEntry/End=115/116 and errors 15/16 are active; preserve MissingVolume=14 and all other existing tags, frame version 1 and revision 3.", | |
| 275 | 323 | "request": { |
| 276 | 324 | "action": "RecoverZip", |
| 277 | 325 | "proposed_action_tag": 5, |
| @@ -371,7 +419,7 @@ | ||
| 371 | 419 | "source_and_publication": "Capture read-only through pinned safe handles into one private snapshot with full source SHA256. All parsing uses that snapshot. Revalidate source identity/length/metadata and full hash once before publication; detected changes abort SourceChanged. Never open the original or any preexisting destination for write/truncate. Same-path/hard-link/existing/newly appeared destination conflicts are never replaced. Reuse existing publication cutoff, fsync/close, owned temporary cleanup and post-verification destination checks.", |
| 372 | 420 | "resources": "Recovery-only source input cap is min(caller input quota, 4 GiB). More than 4 GiB is outside initial recovery support and returns UnsupportedFeature with no expanded retry; exceeding a lower caller quota keeps Limit. Resource approval cannot expand source input. Reuse existing 16 GiB/10000 decoded-byte/candidate defaults and explicit guarded ceilings up to 64 GiB/200000. Count lost/unverified candidates and bytes actually decoded before failure. Include result records, names, spans, staging indexes and implicit parents in metadata budgets before allocation: 8 MiB/32768 nodes, or 64 MiB/262144 after a valid grant. Use 64 KiB chunks, checked u64 ranges, bounded strings/frames, ZIP ratio challenges and the existing 300-second/60-second/parent lifetime policies. No per-byte candidate restarts. Disk accounting includes input snapshot, verified member spools, built ZIP and destination temp by actual volume; permission or advisory space checks do not reserve storage.", |
| 373 | 421 | "client": "Explicit recovery-copy action and native ZIP save dialog; never weaken or silently retry ordinary List/Extract. Show Verified/Lost/Unverified with typed reasons and distinguish unknown inventory from zero loss. Keep recovery findings separate from the ordinary catalog; read a saved copy in a new explicit job with a fresh ListId. Retain partial-warning context when opening a copy, and do not present an ordinary later ZIP listing as proof that all original data was recovered. Result details are job data, not an authenticated permanent recovery certificate.", |
| 374 | 삭제: "lifecycle": "Preserve job/sequence/challenge validation, resource approval, CancelAck and exactly one final Terminal. Confirm results only after matching Terminal, both EOFs and owned-child wait. No new security settings or dependency changes. Product implementation, UI scenarios and native integration require prior frontend agreement.", | |
| 422 | 추가: "lifecycle": "Preserve job/sequence/challenge validation, resource approval, CancelAck and exactly one final Terminal. Confirm results only after matching Terminal, both EOFs and owned-child wait. No new security settings or dependency changes. Frontend agreement is recorded; UI scenarios and native integration remain frontend work.", | |
| 375 | 423 | "fixtures": { |
| 376 | 424 | "basis_commit": "d525c7c23796b06048180c3b3d2bbaee8075989e", |
| 377 | 425 | "manifest": "tests/zip-recovery-fixtures/expectations.json", |
| @@ -385,6 +433,11 @@ | ||
| 385 | 433 | }, |
| 386 | 434 | "comparison": "Read-only comparison of fixture expectations, not worker execution. The intact-central broken-local-header.zip expects CentralDirectory, known_entries=6 and unknown_loss=false. The other damaged samples lack a usable central inventory and retain unknown_loss." |
| 387 | 435 | }, |
| 388 | 삭제: "tag_correction": "The initial error proposal reused live wire MissingVolume=14, omitted from the historical root error_tags index. Preserve MissingVolume=14 and propose RecoveryIncomplete=15 and RecoveryImpossible=16. Result semantics and all other proposed tags are unchanged. Await renewed frontend agreement before product types/codec activation." | |
| 436 | 추가: "tag_correction": "Initial errors 14/15 collided with live MissingVolume=14. Joint correction preserves MissingVolume=14 and activates RecoveryIncomplete=15 and RecoveryImpossible=16. Regression checks consult live wire, not only the historical contract index.", | |
| 437 | 추가: "agreement": { | |
| 438 | 추가: "frontend_result_review": "https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904112564", | |
| 439 | 추가: "frontend_corrected_tag_review": "https://github.com/Team-LJY/zipelo/pull/128#pullrequestreview-5904158997" | |
| 440 | 추가: }, | |
| 441 | 추가: "validation": "Backend tests cover all six damaged fixtures against independent expected SHA256, Python ZIP verification, source byte preservation, healthy/control rejection, exact Deflate/descriptor boundaries, input/output/candidate caps, source and destination changes, cancellation, staging/publication ENOSPC/IO/sync errors, and decoded bytes before errors. Full local/native results are recorded in PR128." | |
| 389 | 442 | } |
| 390 | 443 | } |
| @@ -288,6 +288,19 @@ pub(crate) fn zip( | ||
| 288 | 288 | central.extend(extra); |
| 289 | 289 | crate::resources::completed(Ok(()), check)?; |
| 290 | 290 | } |
| 291 | 추가: finish_directory(&mut output, ¢ral, plan.items.len(), have_zip64, check)?; | |
| 292 | 추가: plan.verify(check)?; | |
| 293 | 추가: let size = io(output.stream_position())?; | |
| 294 | 추가: io(output.rewind())?; | |
| 295 | 추가: Ok((output, size)) | |
| 296 | 추가: } | |
| 297 | 추가: fn finish_directory( | |
| 298 | 추가: output: &mut File, | |
| 299 | 추가: central: &[u8], | |
| 300 | 추가: count: usize, | |
| 301 | 추가: have_zip64: bool, | |
| 302 | 추가: check: &mut impl crate::resources::Monitor, | |
| 303 | 추가: ) -> Result<()> { | |
| 291 | 304 | check.check()?; |
| 292 | 305 | let at = io(output.stream_position())?; |
| 293 | 306 | crate::space::ensure(&output, central.len() as u64 + 98)?; |
| @@ -297,7 +310,7 @@ pub(crate) fn zip( | ||
| 297 | 310 | let large_at = io(output.stream_position())?; |
| 298 | 311 | let mut end = Vec::new(); |
| 299 | 312 | if have_zip64 |
| 300 | 삭제: || plan.items.len() >= u16::MAX as usize | |
| 313 | 추가: || count >= u16::MAX as usize | |
| 301 | 314 | || at >= u32::MAX as u64 |
| 302 | 315 | || central.len() >= u32::MAX as usize |
| 303 | 316 | { |
| @@ -307,8 +320,8 @@ pub(crate) fn zip( | ||
| 307 | 320 | put16(&mut end, 45); |
| 308 | 321 | put32(&mut end, 0); |
| 309 | 322 | put32(&mut end, 0); |
| 310 | 삭제: put64(&mut end, plan.items.len() as u64); | |
| 311 | 삭제: put64(&mut end, plan.items.len() as u64); | |
| 323 | 추가: put64(&mut end, count as u64); | |
| 324 | 추가: put64(&mut end, count as u64); | |
| 312 | 325 | put64(&mut end, central.len() as u64); |
| 313 | 326 | put64(&mut end, at); |
| 314 | 327 | end.extend(b"PK\x06\x07"); |
| @@ -327,17 +340,137 @@ pub(crate) fn zip( | ||
| 327 | 340 | end.extend(b"PK\x05\x06"); |
| 328 | 341 | put16(&mut end, 0); |
| 329 | 342 | put16(&mut end, 0); |
| 330 | 삭제: put16(&mut end, plan.items.len() as u16); | |
| 331 | 삭제: put16(&mut end, plan.items.len() as u16); | |
| 343 | 추가: put16(&mut end, count as u16); | |
| 344 | 추가: put16(&mut end, count as u16); | |
| 332 | 345 | put32(&mut end, central.len() as u32); |
| 333 | 346 | put32(&mut end, at as u32); |
| 334 | 347 | put16(&mut end, 0); |
| 335 | 348 | } |
| 336 | 349 | crate::resources::completed(io(output.write_all(&end)), check)?; |
| 337 | 삭제: plan.verify(check)?; | |
| 338 | 삭제: let size = io(output.stream_position())?; | |
| 350 | 추가: Ok(()) | |
| 351 | 추가: } | |
| 352 | 추가: | |
| 353 | 추가: pub(crate) fn recovered_zip( | |
| 354 | 추가: findings: &[RecoveryEntry], | |
| 355 | 추가: offsets: &[u64], | |
| 356 | 추가: input: &mut File, | |
| 357 | 추가: check: &mut impl crate::resources::Monitor, | |
| 358 | 추가: ) -> Result<(File, u64)> { | |
| 359 | 추가: if findings.len() != offsets.len() { | |
| 360 | 추가: return Err(ErrorCode::Internal); | |
| 361 | 추가: } | |
| 362 | 추가: let mut output = spool::temporary()?; | |
| 363 | 추가: let mut central = Vec::new(); | |
| 364 | 추가: let mut metadata = crate::archive::MetadataBudget::default(); | |
| 365 | 추가: let mut count = 0; | |
| 366 | 추가: let mut wide = false; | |
| 367 | 추가: let mut buffer = [0; 65536]; | |
| 368 | 추가: for (entry, offset) in findings.iter().zip(offsets) { | |
| 369 | 추가: if entry.status != RecoveryStatus::Verified { | |
| 370 | 추가: continue; | |
| 371 | 추가: } | |
| 372 | 추가: check.check()?; | |
| 373 | 추가: let directory = entry.kind == Some(EntryKind::Directory); | |
| 374 | 추가: let name = entry.name.as_ref().ok_or(ErrorCode::Internal)?; | |
| 375 | 추가: metadata.charge_with(name, check.metadata_limits())?; | |
| 376 | 추가: let name = if directory { | |
| 377 | 추가: format!("{name}/") | |
| 378 | 추가: } else { | |
| 379 | 추가: name.clone() | |
| 380 | 추가: }; | |
| 381 | 추가: let size = entry.verified_size.ok_or(ErrorCode::Internal)?; | |
| 382 | 추가: io(input.seek(std::io::SeekFrom::Start(*offset)))?; | |
| 383 | 추가: let mut left = size; | |
| 384 | 추가: let mut crc = 0; | |
| 385 | 추가: while left != 0 { | |
| 386 | 추가: check.check()?; | |
| 387 | 추가: let n = io(input.read(&mut buffer[..left.min(65536) as usize]))?; | |
| 388 | 추가: if n == 0 { | |
| 389 | 추가: return Err(ErrorCode::Internal); | |
| 390 | 추가: } | |
| 391 | 추가: crc = crc32(crc, &buffer[..n]); | |
| 392 | 추가: left -= n as u64; | |
| 393 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 394 | 추가: } | |
| 395 | 추가: let at = io(output.stream_position())?; | |
| 396 | 추가: let big = size >= u32::MAX as u64; | |
| 397 | 추가: wide |= big || at >= u32::MAX as u64; | |
| 398 | 추가: let ext = zip64_extra(size, size, None); | |
| 399 | 추가: let mut header = b"PK\x03\x04".to_vec(); | |
| 400 | 추가: for value in [if big { 45 } else { 20 }, 0x0800, 0, 0, 33] { | |
| 401 | 추가: put16(&mut header, value); | |
| 402 | 추가: } | |
| 403 | 추가: put32(&mut header, crc); | |
| 404 | 추가: for _ in 0..2 { | |
| 405 | 추가: put32(&mut header, if big { u32::MAX } else { size as u32 }); | |
| 406 | 추가: } | |
| 407 | 추가: put16(&mut header, name.len() as u16); | |
| 408 | 추가: put16(&mut header, ext.len() as u16); | |
| 409 | 추가: header.extend(name.as_bytes()); | |
| 410 | 추가: header.extend(ext); | |
| 411 | 추가: crate::space::ensure( | |
| 412 | 추가: &output, | |
| 413 | 추가: size.checked_add(header.len() as u64) | |
| 414 | 추가: .ok_or(ErrorCode::Limit)?, | |
| 415 | 추가: )?; | |
| 416 | 추가: crate::resources::completed(io(output.write_all(&header)), check)?; | |
| 417 | 추가: io(input.seek(std::io::SeekFrom::Start(*offset)))?; | |
| 418 | 추가: let mut left = size; | |
| 419 | 추가: while left != 0 { | |
| 420 | 추가: check.check()?; | |
| 421 | 추가: let n = io(input.read(&mut buffer[..left.min(65536) as usize]))?; | |
| 422 | 추가: if n == 0 { | |
| 423 | 추가: return Err(ErrorCode::Internal); | |
| 424 | 추가: } | |
| 425 | 추가: crate::space::ensure(&output, n as u64)?; | |
| 426 | 추가: crate::resources::completed(io(output.write_all(&buffer[..n])), check)?; | |
| 427 | 추가: left -= n as u64; | |
| 428 | 추가: } | |
| 429 | 추가: let ext = zip64_extra(size, size, Some(at)); | |
| 430 | 추가: central.extend(b"PK\x01\x02"); | |
| 431 | 추가: for value in [ | |
| 432 | 추가: 0x032d, | |
| 433 | 추가: if big || at >= u32::MAX as u64 { 45 } else { 20 }, | |
| 434 | 추가: 0x0800, | |
| 435 | 추가: 0, | |
| 436 | 추가: 0, | |
| 437 | 추가: 33, | |
| 438 | 추가: ] { | |
| 439 | 추가: put16(&mut central, value); | |
| 440 | 추가: } | |
| 441 | 추가: put32(&mut central, crc); | |
| 442 | 추가: for _ in 0..2 { | |
| 443 | 추가: put32(&mut central, if big { u32::MAX } else { size as u32 }); | |
| 444 | 추가: } | |
| 445 | 추가: put16(&mut central, name.len() as u16); | |
| 446 | 추가: put16(&mut central, ext.len() as u16); | |
| 447 | 추가: for _ in 0..3 { | |
| 448 | 추가: put16(&mut central, 0); | |
| 449 | 추가: } | |
| 450 | 추가: put32( | |
| 451 | 추가: &mut central, | |
| 452 | 추가: if directory { | |
| 453 | 추가: (0o40700 << 16) | 0x10 | |
| 454 | 추가: } else { | |
| 455 | 추가: 0o100600 << 16 | |
| 456 | 추가: }, | |
| 457 | 추가: ); | |
| 458 | 추가: put32( | |
| 459 | 추가: &mut central, | |
| 460 | 추가: if at >= u32::MAX as u64 { | |
| 461 | 추가: u32::MAX | |
| 462 | 추가: } else { | |
| 463 | 추가: at as u32 | |
| 464 | 추가: }, | |
| 465 | 추가: ); | |
| 466 | 추가: central.extend(name.as_bytes()); | |
| 467 | 추가: central.extend(ext); | |
| 468 | 추가: count += 1; | |
| 469 | 추가: } | |
| 470 | 추가: finish_directory(&mut output, ¢ral, count, wide, check)?; | |
| 471 | 추가: let len = io(output.stream_position())?; | |
| 339 | 472 | io(output.rewind())?; |
| 340 | 삭제: Ok((output, size)) | |
| 473 | 추가: Ok((output, len)) | |
| 341 | 474 | } |
| 342 | 475 | |
| 343 | 476 | #[cfg(test)] |
| @@ -17,3 +17,4 @@ mod split_seven_zip; | ||
| 17 | 17 | mod spool; |
| 18 | 18 | mod streaming; |
| 19 | 19 | pub mod wire; |
| 20 | 추가: mod zip_recovery; |
| @@ -237,6 +237,10 @@ pub enum Action { | ||
| 237 | 237 | entry_id: u32, |
| 238 | 238 | list_id: ListId, |
| 239 | 239 | }, |
| 240 | 추가: RecoverZip { | |
| 241 | 추가: archive: NativePath, | |
| 242 | 추가: output_file: NativePath, | |
| 243 | 추가: }, | |
| 240 | 244 | CreateSevenZip { |
| 241 | 245 | sources: Vec<Source>, |
| 242 | 246 | output_file: NativePath, |
| @@ -252,6 +256,7 @@ pub enum ActionKind { | ||
| 252 | 256 | CreateZip, |
| 253 | 257 | Preview, |
| 254 | 258 | CreateSevenZip, |
| 259 | 추가: RecoverZip, | |
| 255 | 260 | } |
| 256 | 261 | impl Action { |
| 257 | 262 | pub fn kind(&self) -> ActionKind { |
| @@ -261,6 +266,7 @@ impl Action { | ||
| 261 | 266 | Self::CreateZip { .. } => ActionKind::CreateZip, |
| 262 | 267 | Self::Preview { .. } => ActionKind::Preview, |
| 263 | 268 | Self::CreateSevenZip { .. } => ActionKind::CreateSevenZip, |
| 269 | 추가: Self::RecoverZip { .. } => ActionKind::RecoverZip, | |
| 264 | 270 | } |
| 265 | 271 | } |
| 266 | 272 | } |
| @@ -357,6 +363,8 @@ pub enum ErrorCode { | ||
| 357 | 363 | InvalidRequest, |
| 358 | 364 | DiskFull, |
| 359 | 365 | MissingVolume, |
| 366 | 추가: RecoveryIncomplete, | |
| 367 | 추가: RecoveryImpossible, | |
| 360 | 368 | } |
| 361 | 369 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 362 | 370 | pub enum VolumeProblemReason { |
| @@ -501,6 +509,8 @@ pub enum Message { | ||
| 501 | 509 | reason: VolumeProblemReason, |
| 502 | 510 | volume: NativePath, |
| 503 | 511 | }, |
| 512 | 추가: RecoveryEntry(RecoveryEntry), | |
| 513 | 추가: RecoveryEnd(RecoveryEnd), | |
| 504 | 514 | Terminal(Terminal), |
| 505 | 515 | CancelAck { |
| 506 | 516 | request_sequence: u64, |
| @@ -519,3 +529,124 @@ pub enum Message { | ||
| 519 | 529 | choice: ConflictChoice, |
| 520 | 530 | }, |
| 521 | 531 | } |
| 532 | 추가: | |
| 533 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 534 | 추가: pub enum RecoveryMode { | |
| 535 | 추가: CentralDirectory, | |
| 536 | 추가: LocalChain, | |
| 537 | 추가: } | |
| 538 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 539 | 추가: pub enum RecoveryStatus { | |
| 540 | 추가: Verified, | |
| 541 | 추가: Lost, | |
| 542 | 추가: Unverified, | |
| 543 | 추가: } | |
| 544 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 545 | 추가: pub enum RecoveryReason { | |
| 546 | 추가: None, | |
| 547 | 추가: HeaderRebuilt, | |
| 548 | 추가: Truncated, | |
| 549 | 추가: CrcMismatch, | |
| 550 | 추가: DecodeFailure, | |
| 551 | 추가: BoundaryUnknown, | |
| 552 | 추가: UnsupportedFeature, | |
| 553 | 추가: MetadataMissing, | |
| 554 | 추가: } | |
| 555 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 556 | 추가: pub struct RecoveryEntry { | |
| 557 | 추가: pub candidate_id: u32, | |
| 558 | 추가: pub source_offset: u64, | |
| 559 | 추가: pub name: Option<String>, | |
| 560 | 추가: pub kind: Option<EntryKind>, | |
| 561 | 추가: pub status: RecoveryStatus, | |
| 562 | 추가: pub reason: RecoveryReason, | |
| 563 | 추가: pub declared_size: Option<u64>, | |
| 564 | 추가: pub verified_size: Option<u64>, | |
| 565 | 추가: pub sha256: Option<[u8; 32]>, | |
| 566 | 추가: } | |
| 567 | 추가: impl RecoveryEntry { | |
| 568 | 추가: pub fn valid(&self) -> bool { | |
| 569 | 추가: if self.name.as_ref().is_some_and(|name| name.is_empty()) { | |
| 570 | 추가: return false; | |
| 571 | 추가: } | |
| 572 | 추가: if !matches!( | |
| 573 | 추가: self.kind, | |
| 574 | 추가: None | Some(EntryKind::File | EntryKind::Directory) | |
| 575 | 추가: ) { | |
| 576 | 추가: return false; | |
| 577 | 추가: } | |
| 578 | 추가: match self.status { | |
| 579 | 추가: RecoveryStatus::Verified => { | |
| 580 | 추가: if self.name.as_ref().is_none_or(|name| name.is_empty()) | |
| 581 | 추가: || !matches!( | |
| 582 | 추가: self.reason, | |
| 583 | 추가: RecoveryReason::None | |
| 584 | 추가: | RecoveryReason::HeaderRebuilt | |
| 585 | 추가: | RecoveryReason::MetadataMissing | |
| 586 | 추가: ) | |
| 587 | 추가: || self.declared_size.is_none() | |
| 588 | 추가: || self.declared_size != self.verified_size | |
| 589 | 추가: { | |
| 590 | 추가: return false; | |
| 591 | 추가: } | |
| 592 | 추가: match self.kind { | |
| 593 | 추가: Some(EntryKind::File) => self.sha256.is_some(), | |
| 594 | 추가: Some(EntryKind::Directory) => { | |
| 595 | 추가: self.declared_size == Some(0) && self.sha256.is_none() | |
| 596 | 추가: } | |
| 597 | 추가: _ => false, | |
| 598 | 추가: } | |
| 599 | 추가: } | |
| 600 | 추가: RecoveryStatus::Lost => { | |
| 601 | 추가: self.verified_size.is_none() | |
| 602 | 추가: && self.sha256.is_none() | |
| 603 | 추가: && matches!( | |
| 604 | 추가: self.reason, | |
| 605 | 추가: RecoveryReason::Truncated | |
| 606 | 추가: | RecoveryReason::CrcMismatch | |
| 607 | 추가: | RecoveryReason::DecodeFailure | |
| 608 | 추가: ) | |
| 609 | 추가: } | |
| 610 | 추가: RecoveryStatus::Unverified => { | |
| 611 | 추가: self.verified_size.is_none() | |
| 612 | 추가: && self.sha256.is_none() | |
| 613 | 추가: && matches!( | |
| 614 | 추가: self.reason, | |
| 615 | 추가: RecoveryReason::BoundaryUnknown | |
| 616 | 추가: | RecoveryReason::UnsupportedFeature | |
| 617 | 추가: | RecoveryReason::MetadataMissing | |
| 618 | 추가: ) | |
| 619 | 추가: } | |
| 620 | 추가: } | |
| 621 | 추가: } | |
| 622 | 추가: } | |
| 623 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 624 | 추가: pub struct RecoveryEnd { | |
| 625 | 추가: pub mode: RecoveryMode, | |
| 626 | 추가: pub source_bytes: u64, | |
| 627 | 추가: pub source_sha256: [u8; 32], | |
| 628 | 추가: pub known_entries: Option<u32>, | |
| 629 | 추가: pub verified_entries: u32, | |
| 630 | 추가: pub lost_entries: u32, | |
| 631 | 추가: pub unverified_entries: u32, | |
| 632 | 추가: pub unknown_loss: bool, | |
| 633 | 추가: } | |
| 634 | 추가: impl RecoveryEnd { | |
| 635 | 추가: pub fn valid(&self) -> bool { | |
| 636 | 추가: let total = self | |
| 637 | 추가: .verified_entries | |
| 638 | 추가: .checked_add(self.lost_entries) | |
| 639 | 추가: .and_then(|n| n.checked_add(self.unverified_entries)); | |
| 640 | 추가: let Some(total) = total else { | |
| 641 | 추가: return false; | |
| 642 | 추가: }; | |
| 643 | 추가: match (self.mode, self.known_entries, self.unknown_loss) { | |
| 644 | 추가: (RecoveryMode::CentralDirectory, Some(known), false) => known == total, | |
| 645 | 추가: (_, None, true) => true, | |
| 646 | 추가: _ => false, | |
| 647 | 추가: } | |
| 648 | 추가: } | |
| 649 | 추가: pub fn complete(&self) -> bool { | |
| 650 | 추가: self.valid() && !self.unknown_loss && self.lost_entries == 0 && self.unverified_entries == 0 | |
| 651 | 추가: } | |
| 652 | 추가: } |
| @@ -42,6 +42,7 @@ struct Job<W> { | ||
| 42 | 42 | source_group: Option<crate::split_seven_zip::Group>, |
| 43 | 43 | source_verified_for_publication: bool, |
| 44 | 44 | creation_plan: Option<crate::create::Plan>, |
| 45 | 추가: recovery: Option<crate::zip_recovery::Recovery>, | |
| 45 | 46 | started: Instant, |
| 46 | 47 | terminal: Terminal, |
| 47 | 48 | parent: crate::parent::Parent, |
| @@ -297,6 +298,11 @@ impl<W: Write> Job<W> { | ||
| 297 | 298 | self.creation_plan = Some(plan); |
| 298 | 299 | result?; |
| 299 | 300 | } |
| 301 | 추가: if let Some(mut recovery) = self.recovery.take() { | |
| 302 | 추가: let result = recovery.verify_source(self); | |
| 303 | 추가: self.recovery = Some(recovery); | |
| 304 | 추가: result?; | |
| 305 | 추가: } | |
| 300 | 306 | self.verify_split()?; |
| 301 | 307 | self.source_verified_for_publication = true; |
| 302 | 308 | } |
| @@ -560,7 +566,10 @@ impl<W: Write> Job<W> { | ||
| 560 | 566 | let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); |
| 561 | 567 | self.event(Message::Accepted { |
| 562 | 568 | action: start.action.kind(), |
| 563 | 삭제: encryption: !matches!(start.action, Action::CreateSevenZip { .. }), | |
| 569 | 추가: encryption: !matches!( | |
| 570 | 추가: start.action, | |
| 571 | 추가: Action::CreateSevenZip { .. } | Action::RecoverZip { .. } | |
| 572 | 추가: ), | |
| 564 | 573 | })?; |
| 565 | 574 | self.check()?; |
| 566 | 575 | if let Action::CreateSevenZip { |
| @@ -589,6 +598,46 @@ impl<W: Write> Job<W> { | ||
| 589 | 598 | } |
| 590 | 599 | } |
| 591 | 600 | match start.action { |
| 601 | 추가: Action::RecoverZip { | |
| 602 | 추가: archive: source, | |
| 603 | 추가: output_file, | |
| 604 | 추가: } => { | |
| 605 | 추가: let source = source.to_path()?; | |
| 606 | 추가: let output = output_file.to_path()?; | |
| 607 | 추가: let leaf = output | |
| 608 | 추가: .file_name() | |
| 609 | 추가: .and_then(|n| n.to_str()) | |
| 610 | 추가: .ok_or(ErrorCode::InvalidRequest)?; | |
| 611 | 추가: let name = archive::valid_name(leaf, false)?; | |
| 612 | 추가: let root = completed( | |
| 613 | 추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), | |
| 614 | 추가: self, | |
| 615 | 추가: )?; | |
| 616 | 추가: filesystem::preflight_mode_with( | |
| 617 | 추가: &root, | |
| 618 | 추가: &[(name.clone(), EntryKind::File)], | |
| 619 | 추가: false, | |
| 620 | 추가: self, | |
| 621 | 추가: )?; | |
| 622 | 추가: self.progress(Stage::Scan, 0, None, 0)?; | |
| 623 | 추가: let mut recovery = crate::zip_recovery::Recovery::open(&source, limits, self)?; | |
| 624 | 추가: for finding in &recovery.findings { | |
| 625 | 추가: self.event(Message::RecoveryEntry(finding.clone()))?; | |
| 626 | 추가: } | |
| 627 | 추가: self.event(Message::RecoveryEnd(recovery.summary.clone()))?; | |
| 628 | 추가: if recovery.summary.verified_entries == 0 { | |
| 629 | 추가: return Err(ErrorCode::RecoveryImpossible); | |
| 630 | 추가: } | |
| 631 | 추가: let incomplete = !recovery.summary.complete(); | |
| 632 | 추가: let (mut data, length) = recovery.build(limits, self)?; | |
| 633 | 추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; | |
| 634 | 추가: self.recovery = Some(recovery); | |
| 635 | 추가: self.output_reader(&root, &name, &mut data, length, None, true, None)?; | |
| 636 | 추가: self.terminal.publication = Publication::Complete; | |
| 637 | 추가: if incomplete { | |
| 638 | 추가: return Err(ErrorCode::RecoveryIncomplete); | |
| 639 | 추가: } | |
| 640 | 추가: } | |
| 592 | 641 | Action::List { |
| 593 | 642 | archive: ref source, |
| 594 | 643 | } |
| @@ -1176,6 +1225,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 1176 | 1225 | source_group: None, |
| 1177 | 1226 | source_verified_for_publication: false, |
| 1178 | 1227 | creation_plan: None, |
| 1228 | 추가: recovery: None, | |
| 1179 | 1229 | parent, |
| 1180 | 1230 | started: Instant::now(), |
| 1181 | 1231 | terminal: Terminal { |
| @@ -139,13 +139,16 @@ enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4}); | ||
| 139 | 139 | enumeration!(Method{Store=0,Deflate=1}); |
| 140 | 140 | enumeration!(SevenZipMethod{Lzma2=0}); |
| 141 | 141 | enumeration!(Encryption{None=0,Aes256=1}); |
| 142 | 삭제: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4}); | |
| 142 | 추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4,RecoverZip=5}); | |
| 143 | 추가: enumeration!(RecoveryMode{CentralDirectory=0,LocalChain=1}); | |
| 144 | 추가: enumeration!(RecoveryStatus{Verified=0,Lost=1,Unverified=2}); | |
| 145 | 추가: enumeration!(RecoveryReason{None=0,HeaderRebuilt=1,Truncated=2,CrcMismatch=3,DecodeFailure=4,BoundaryUnknown=5,UnsupportedFeature=6,MetadataMissing=7}); | |
| 143 | 146 | enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1}); |
| 144 | 147 | enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); |
| 145 | 148 | enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); |
| 146 | 149 | enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3}); |
| 147 | 150 | enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2}); |
| 148 | 삭제: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13,MissingVolume=14}); | |
| 151 | 추가: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13,MissingVolume=14,RecoveryIncomplete=15,RecoveryImpossible=16}); | |
| 149 | 152 | enumeration!(VolumeProblemReason{FirstVolumeRequired=0,MissingVolume=1,IncompleteSet=2}); |
| 150 | 153 | enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3}); |
| 151 | 154 | enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3}); |
| @@ -212,6 +215,72 @@ impl Wire for PreviewInfo { | ||
| 212 | 215 | Ok(info) |
| 213 | 216 | } |
| 214 | 217 | } |
| 218 | 추가: impl Wire for RecoveryEntry { | |
| 219 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 220 | 추가: if !self.valid() { | |
| 221 | 추가: return Err(invalid()); | |
| 222 | 추가: } | |
| 223 | 추가: self.candidate_id.enc(e)?; | |
| 224 | 추가: self.source_offset.enc(e)?; | |
| 225 | 추가: self.name.enc(e)?; | |
| 226 | 추가: self.kind.enc(e)?; | |
| 227 | 추가: self.status.enc(e)?; | |
| 228 | 추가: self.reason.enc(e)?; | |
| 229 | 추가: self.declared_size.enc(e)?; | |
| 230 | 추가: self.verified_size.enc(e)?; | |
| 231 | 추가: self.sha256.enc(e)?; | |
| 232 | 추가: Ok(()) | |
| 233 | 추가: } | |
| 234 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 235 | 추가: let value = Self { | |
| 236 | 추가: candidate_id: Wire::dec(d)?, | |
| 237 | 추가: source_offset: Wire::dec(d)?, | |
| 238 | 추가: name: Wire::dec(d)?, | |
| 239 | 추가: kind: Wire::dec(d)?, | |
| 240 | 추가: status: Wire::dec(d)?, | |
| 241 | 추가: reason: Wire::dec(d)?, | |
| 242 | 추가: declared_size: Wire::dec(d)?, | |
| 243 | 추가: verified_size: Wire::dec(d)?, | |
| 244 | 추가: sha256: Wire::dec(d)?, | |
| 245 | 추가: }; | |
| 246 | 추가: if !value.valid() { | |
| 247 | 추가: return Err(invalid()); | |
| 248 | 추가: } | |
| 249 | 추가: Ok(value) | |
| 250 | 추가: } | |
| 251 | 추가: } | |
| 252 | 추가: impl Wire for RecoveryEnd { | |
| 253 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 254 | 추가: if !self.valid() { | |
| 255 | 추가: return Err(invalid()); | |
| 256 | 추가: } | |
| 257 | 추가: self.mode.enc(e)?; | |
| 258 | 추가: self.source_bytes.enc(e)?; | |
| 259 | 추가: self.source_sha256.enc(e)?; | |
| 260 | 추가: self.known_entries.enc(e)?; | |
| 261 | 추가: self.verified_entries.enc(e)?; | |
| 262 | 추가: self.lost_entries.enc(e)?; | |
| 263 | 추가: self.unverified_entries.enc(e)?; | |
| 264 | 추가: self.unknown_loss.enc(e)?; | |
| 265 | 추가: Ok(()) | |
| 266 | 추가: } | |
| 267 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 268 | 추가: let value = Self { | |
| 269 | 추가: mode: Wire::dec(d)?, | |
| 270 | 추가: source_bytes: Wire::dec(d)?, | |
| 271 | 추가: source_sha256: Wire::dec(d)?, | |
| 272 | 추가: known_entries: Wire::dec(d)?, | |
| 273 | 추가: verified_entries: Wire::dec(d)?, | |
| 274 | 추가: lost_entries: Wire::dec(d)?, | |
| 275 | 추가: unverified_entries: Wire::dec(d)?, | |
| 276 | 추가: unknown_loss: Wire::dec(d)?, | |
| 277 | 추가: }; | |
| 278 | 추가: if !value.valid() { | |
| 279 | 추가: return Err(invalid()); | |
| 280 | 추가: } | |
| 281 | 추가: Ok(value) | |
| 282 | 추가: } | |
| 283 | 추가: } | |
| 215 | 284 | structure!(Source { path, archive_name }); |
| 216 | 285 | structure!(Start { action, limits }); |
| 217 | 286 | structure!(GuardedStart { |
| @@ -346,6 +415,14 @@ impl Wire for Selection { | ||
| 346 | 415 | impl Wire for Action { |
| 347 | 416 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 348 | 417 | match self { |
| 418 | 추가: Self::RecoverZip { | |
| 419 | 추가: archive, | |
| 420 | 추가: output_file, | |
| 421 | 추가: } => { | |
| 422 | 추가: 5u8.enc(e)?; | |
| 423 | 추가: archive.enc(e)?; | |
| 424 | 추가: output_file.enc(e) | |
| 425 | 추가: } | |
| 349 | 426 | Self::List { archive } => { |
| 350 | 427 | 0u8.enc(e)?; |
| 351 | 428 | archive.enc(e) |
| @@ -425,6 +502,10 @@ impl Wire for Action { | ||
| 425 | 502 | entry_id: Wire::dec(d)?, |
| 426 | 503 | list_id: Wire::dec(d)?, |
| 427 | 504 | }), |
| 505 | 추가: 5 => Ok(Self::RecoverZip { | |
| 506 | 추가: archive: Wire::dec(d)?, | |
| 507 | 추가: output_file: Wire::dec(d)?, | |
| 508 | 추가: }), | |
| 428 | 509 | 4 => Ok(Self::CreateSevenZip { |
| 429 | 510 | sources: Wire::dec(d)?, |
| 430 | 511 | output_file: Wire::dec(d)?, |
| @@ -520,6 +601,9 @@ impl Message { | ||
| 520 | 601 | 110 |
| 521 | 602 | } |
| 522 | 603 | Self::Accepted { action, encryption } => { |
| 604 | 추가: if *action == ActionKind::RecoverZip && *encryption { | |
| 605 | 추가: return Err(invalid()); | |
| 606 | 추가: } | |
| 523 | 607 | action.enc(&mut e)?; |
| 524 | 608 | encryption.enc(&mut e)?; |
| 525 | 609 | 100 |
| @@ -607,6 +691,14 @@ impl Message { | ||
| 607 | 691 | volume.enc(&mut e)?; |
| 608 | 692 | 114 |
| 609 | 693 | } |
| 694 | 추가: Self::RecoveryEntry(v) => { | |
| 695 | 추가: v.enc(&mut e)?; | |
| 696 | 추가: 115 | |
| 697 | 추가: } | |
| 698 | 추가: Self::RecoveryEnd(v) => { | |
| 699 | 추가: v.enc(&mut e)?; | |
| 700 | 추가: 116 | |
| 701 | 추가: } | |
| 610 | 702 | Self::Terminal(v) => { |
| 611 | 703 | if v.detail.len() > 4096 { |
| 612 | 704 | return Err(invalid()); |
| @@ -717,10 +809,16 @@ impl Message { | ||
| 717 | 809 | soft_limits: Wire::dec(&mut d)?, |
| 718 | 810 | ceiling: Wire::dec(&mut d)?, |
| 719 | 811 | }, |
| 720 | 삭제: 100 => Self::Accepted { | |
| 721 | 삭제: action: Wire::dec(&mut d)?, | |
| 722 | 삭제: encryption: Wire::dec(&mut d)?, | |
| 723 | 삭제: }, | |
| 812 | 추가: 100 => { | |
| 813 | 추가: let action = Wire::dec(&mut d)?; | |
| 814 | 추가: let encryption = Wire::dec(&mut d)?; | |
| 815 | 추가: if action == ActionKind::RecoverZip && encryption { | |
| 816 | 추가: return Err(invalid()); | |
| 817 | 추가: } | |
| 818 | 추가: Self::Accepted { action, encryption } | |
| 819 | 추가: } | |
| 820 | 추가: 115 => Self::RecoveryEntry(Wire::dec(&mut d)?), | |
| 821 | 추가: 116 => Self::RecoveryEnd(Wire::dec(&mut d)?), | |
| 724 | 822 | 101 => Self::Entry(Wire::dec(&mut d)?), |
| 725 | 823 | 102 => Self::ListEnd { |
| 726 | 824 | entry_count: Wire::dec(&mut d)?, |
| @@ -0,0 +1,761 @@ | ||
| 1 | 추가: use crate::{ | |
| 2 | 추가: archive::{self, Member, MetadataBudget}, | |
| 3 | 추가: create_sources::Input, | |
| 4 | 추가: filesystem, | |
| 5 | 추가: protocol::*, | |
| 6 | 추가: resources::{Monitor, completed}, | |
| 7 | 추가: spool, | |
| 8 | 추가: }; | |
| 9 | 추가: use sha2::{Digest, Sha256}; | |
| 10 | 추가: use std::{ | |
| 11 | 추가: fs::File, | |
| 12 | 추가: io::{Read, Seek, SeekFrom, Write}, | |
| 13 | 추가: path::{Path, PathBuf}, | |
| 14 | 추가: time::SystemTime, | |
| 15 | 추가: }; | |
| 16 | 추가: use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32}; | |
| 17 | 추가: | |
| 18 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 19 | 추가: const INPUT_CAP: u64 = 4 * 1024 * 1024 * 1024; | |
| 20 | 추가: fn io<T>(value: std::io::Result<T>) -> Result<T> { | |
| 21 | 추가: value.map_err(crate::space::io_error) | |
| 22 | 추가: } | |
| 23 | 추가: fn add(a: u64, b: u64) -> Result<u64> { | |
| 24 | 추가: a.checked_add(b).ok_or(ErrorCode::Integrity) | |
| 25 | 추가: } | |
| 26 | 추가: fn u16at(b: &[u8], i: usize) -> u16 { | |
| 27 | 추가: u16::from_le_bytes(b[i..i + 2].try_into().unwrap()) | |
| 28 | 추가: } | |
| 29 | 추가: fn u32at(b: &[u8], i: usize) -> u32 { | |
| 30 | 추가: u32::from_le_bytes(b[i..i + 4].try_into().unwrap()) | |
| 31 | 추가: } | |
| 32 | 추가: fn bytes(source: &mut File, offset: u64, size: usize, end: u64) -> Result<Vec<u8>> { | |
| 33 | 추가: if add(offset, size as u64)? > end { | |
| 34 | 추가: return Err(ErrorCode::Integrity); | |
| 35 | 추가: } | |
| 36 | 추가: io(source.seek(SeekFrom::Start(offset)))?; | |
| 37 | 추가: let mut data = vec![0; size]; | |
| 38 | 추가: io(source.read_exact(&mut data))?; | |
| 39 | 추가: Ok(data) | |
| 40 | 추가: } | |
| 41 | 추가: fn extra(data: &[u8]) -> Result<()> { | |
| 42 | 추가: let mut at = 0; | |
| 43 | 추가: while at < data.len() { | |
| 44 | 추가: if data.len() - at < 4 { | |
| 45 | 추가: return Err(ErrorCode::Integrity); | |
| 46 | 추가: } | |
| 47 | 추가: let tag = u16at(data, at); | |
| 48 | 추가: let size = u16at(data, at + 2) as usize; | |
| 49 | 추가: if matches!(tag, 1 | 0x0017 | 0x0018) { | |
| 50 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 51 | 추가: } | |
| 52 | 추가: at = at | |
| 53 | 추가: .checked_add(4 + size) | |
| 54 | 추가: .filter(|n| *n <= data.len()) | |
| 55 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 56 | 추가: } | |
| 57 | 추가: Ok(()) | |
| 58 | 추가: } | |
| 59 | 추가: struct Candidate { | |
| 60 | 추가: finding: RecoveryEntry, | |
| 61 | 추가: start: u64, | |
| 62 | 추가: stop: u64, | |
| 63 | 추가: packed: u64, | |
| 64 | 추가: crc: u32, | |
| 65 | 추가: method: u16, | |
| 66 | 추가: supported: bool, | |
| 67 | 추가: boundary: bool, | |
| 68 | 추가: repaired: bool, | |
| 69 | 추가: } | |
| 70 | 추가: fn declared(size: u32, packed: u32) -> Result<(u64, u64)> { | |
| 71 | 추가: if size == u32::MAX || packed == u32::MAX { | |
| 72 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 73 | 추가: } | |
| 74 | 추가: Ok((u64::from(size), u64::from(packed))) | |
| 75 | 추가: } | |
| 76 | 추가: fn named(raw: &[u8], flags: u16, ext: &[u8], kind: EntryKind) -> Result<String> { | |
| 77 | 추가: if !matches!(kind, EntryKind::File | EntryKind::Directory) { | |
| 78 | 추가: return Err(ErrorCode::UnsafePath); | |
| 79 | 추가: } | |
| 80 | 추가: let name = archive::zip_name(raw, flags, ext)?; | |
| 81 | 추가: archive::valid_name(&name, kind == EntryKind::Directory) | |
| 82 | 추가: } | |
| 83 | 추가: fn candidate( | |
| 84 | 추가: offset: u64, | |
| 85 | 추가: name: String, | |
| 86 | 추가: kind: EntryKind, | |
| 87 | 추가: size: u64, | |
| 88 | 추가: packed: u64, | |
| 89 | 추가: crc: u32, | |
| 90 | 추가: method: u16, | |
| 91 | 추가: flags: u16, | |
| 92 | 추가: ) -> Candidate { | |
| 93 | 추가: Candidate { | |
| 94 | 추가: finding: RecoveryEntry { | |
| 95 | 추가: candidate_id: 0, | |
| 96 | 추가: source_offset: offset, | |
| 97 | 추가: name: Some(name), | |
| 98 | 추가: kind: Some(kind), | |
| 99 | 추가: status: RecoveryStatus::Unverified, | |
| 100 | 추가: reason: RecoveryReason::BoundaryUnknown, | |
| 101 | 추가: declared_size: Some(size), | |
| 102 | 추가: verified_size: None, | |
| 103 | 추가: sha256: None, | |
| 104 | 추가: }, | |
| 105 | 추가: start: 0, | |
| 106 | 추가: stop: offset, | |
| 107 | 추가: packed, | |
| 108 | 추가: crc, | |
| 109 | 추가: method, | |
| 110 | 추가: supported: flags & !0x080e == 0 && matches!(method, 0 | 8), | |
| 111 | 추가: boundary: false, | |
| 112 | 추가: repaired: false, | |
| 113 | 추가: } | |
| 114 | 추가: } | |
| 115 | 추가: fn charge( | |
| 116 | 추가: metadata: &mut MetadataBudget, | |
| 117 | 추가: name_len: usize, | |
| 118 | 추가: extra_len: usize, | |
| 119 | 추가: check: &mut impl Monitor, | |
| 120 | 추가: ) -> Result<()> { | |
| 121 | 추가: if name_len > 4096 { | |
| 122 | 추가: return Err(ErrorCode::UnsafePath); | |
| 123 | 추가: } | |
| 124 | 추가: metadata.charge_bytes( | |
| 125 | 추가: name_len | |
| 126 | 추가: .checked_mul(8) | |
| 127 | 추가: .and_then(|n| n.checked_add(extra_len + 1024)) | |
| 128 | 추가: .ok_or(ErrorCode::Limit)?, | |
| 129 | 추가: check.metadata_limits(), | |
| 130 | 추가: ) | |
| 131 | 추가: } | |
| 132 | 추가: fn central( | |
| 133 | 추가: source: &mut File, | |
| 134 | 추가: len: u64, | |
| 135 | 추가: limits: Limits, | |
| 136 | 추가: check: &mut impl Monitor, | |
| 137 | 추가: ) -> Result<Option<(Vec<Candidate>, bool)>> { | |
| 138 | 추가: if len < 22 { | |
| 139 | 추가: return Ok(None); | |
| 140 | 추가: } | |
| 141 | 추가: let mut metadata = MetadataBudget::default(); | |
| 142 | 추가: metadata.charge_bytes(len.min(65557) as usize, check.metadata_limits())?; | |
| 143 | 추가: let tail_at = len.saturating_sub(65557); | |
| 144 | 추가: let tail = bytes(source, tail_at, (len - tail_at) as usize, len)?; | |
| 145 | 추가: let Some(end) = (0..=tail.len() - 22).rev().find(|&i| { | |
| 146 | 추가: &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len() | |
| 147 | 추가: }) else { | |
| 148 | 추가: return Ok(None); | |
| 149 | 추가: }; | |
| 150 | 추가: let h = &tail[end..]; | |
| 151 | 추가: let count = u16at(h, 10) as u32; | |
| 152 | 추가: if u16at(h, 4) != 0 | |
| 153 | 추가: || u16at(h, 6) != 0 | |
| 154 | 추가: || u16at(h, 8) as u32 != count | |
| 155 | 추가: || count == u16::MAX as u32 | |
| 156 | 추가: || u32at(h, 12) == u32::MAX | |
| 157 | 추가: || u32at(h, 16) == u32::MAX | |
| 158 | 추가: { | |
| 159 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 160 | 추가: } | |
| 161 | 추가: let cd = u32at(h, 16) as u64; | |
| 162 | 추가: let cd_end = tail_at + end as u64; | |
| 163 | 추가: if cd_end >= 20 && bytes(source, cd_end - 20, 4, len)? == b"PK\x06\x07" { | |
| 164 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 165 | 추가: } | |
| 166 | 추가: if add(cd, u32at(h, 12) as u64)? != cd_end { | |
| 167 | 추가: return Err(ErrorCode::Integrity); | |
| 168 | 추가: } | |
| 169 | 추가: if count > limits.entries { | |
| 170 | 추가: return Err(ErrorCode::Limit); | |
| 171 | 추가: } | |
| 172 | 추가: check.observe( | |
| 173 | 추가: ResourceUsage { | |
| 174 | 추가: estimated_entries: Some(count), | |
| 175 | 추가: ..ResourceUsage::default() | |
| 176 | 추가: }, | |
| 177 | 추가: Some(source), | |
| 178 | 추가: )?; | |
| 179 | 추가: let mut items = Vec::new(); | |
| 180 | 추가: let mut at = cd; | |
| 181 | 추가: for _ in 0..count { | |
| 182 | 추가: check.check()?; | |
| 183 | 추가: let h = bytes(source, at, 46, cd_end)?; | |
| 184 | 추가: if &h[..4] != b"PK\x01\x02" { | |
| 185 | 추가: return Err(ErrorCode::Integrity); | |
| 186 | 추가: } | |
| 187 | 추가: if u16at(&h, 34) != 0 || u32at(&h, 42) == u32::MAX { | |
| 188 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 189 | 추가: } | |
| 190 | 추가: let flags = u16at(&h, 8); | |
| 191 | 추가: if flags & 0x2040 != 0 { | |
| 192 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 193 | 추가: } | |
| 194 | 추가: let nn = u16at(&h, 28) as usize; | |
| 195 | 추가: let ne = u16at(&h, 30) as usize; | |
| 196 | 추가: let next = add(at, 46 + nn as u64 + ne as u64 + u16at(&h, 32) as u64)?; | |
| 197 | 추가: if next > cd_end { | |
| 198 | 추가: return Err(ErrorCode::Integrity); | |
| 199 | 추가: } | |
| 200 | 추가: charge(&mut metadata, nn, ne, check)?; | |
| 201 | 추가: let raw = bytes(source, at + 46, nn, cd_end)?; | |
| 202 | 추가: let ext = bytes(source, at + 46 + nn as u64, ne, cd_end)?; | |
| 203 | 추가: extra(&ext)?; | |
| 204 | 추가: let (size, packed) = declared(u32at(&h, 24), u32at(&h, 20))?; | |
| 205 | 추가: let unix_kind = (u32at(&h, 38) >> 16) & 0xf000; | |
| 206 | 추가: let kind = match unix_kind { | |
| 207 | 추가: 0 | 0x8000 => { | |
| 208 | 추가: if raw.ends_with(b"/") { | |
| 209 | 추가: EntryKind::Directory | |
| 210 | 추가: } else { | |
| 211 | 추가: EntryKind::File | |
| 212 | 추가: } | |
| 213 | 추가: } | |
| 214 | 추가: 0x4000 => EntryKind::Directory, | |
| 215 | 추가: _ => return Err(ErrorCode::UnsafePath), | |
| 216 | 추가: }; | |
| 217 | 추가: let name = named(&raw, flags, &ext, kind)?; | |
| 218 | 추가: metadata.charge_with(&name, check.metadata_limits())?; | |
| 219 | 추가: let offset = u32at(&h, 42) as u64; | |
| 220 | 추가: let mut item = candidate( | |
| 221 | 추가: offset, | |
| 222 | 추가: name, | |
| 223 | 추가: kind, | |
| 224 | 추가: size, | |
| 225 | 추가: packed, | |
| 226 | 추가: u32at(&h, 16), | |
| 227 | 추가: u16at(&h, 10), | |
| 228 | 추가: flags, | |
| 229 | 추가: ); | |
| 230 | 추가: if add(offset, 30)? > cd { | |
| 231 | 추가: return Err(ErrorCode::Integrity); | |
| 232 | 추가: } | |
| 233 | 추가: let local = bytes(source, offset, 30, cd)?; | |
| 234 | 추가: declared(u32at(&local, 22), u32at(&local, 18))?; | |
| 235 | 추가: let ln = u16at(&local, 26) as usize; | |
| 236 | 추가: let le = u16at(&local, 28) as usize; | |
| 237 | 추가: charge(&mut metadata, ln, le, check)?; | |
| 238 | 추가: let start = add(offset, 30 + ln as u64 + le as u64)?; | |
| 239 | 추가: if start > cd { | |
| 240 | 추가: return Err(ErrorCode::Integrity); | |
| 241 | 추가: } | |
| 242 | 추가: let local_raw = bytes(source, offset + 30, ln, cd)?; | |
| 243 | 추가: let local_extra = bytes(source, offset + 30 + ln as u64, le, cd)?; | |
| 244 | 추가: extra(&local_extra)?; | |
| 245 | 추가: let mut stop = add(start, packed)?; | |
| 246 | 추가: if stop > cd { | |
| 247 | 추가: return Err(ErrorCode::Integrity); | |
| 248 | 추가: } | |
| 249 | 추가: item.start = start; | |
| 250 | 추가: item.boundary = | |
| 251 | 추가: raw == local_raw && flags == u16at(&local, 6) && item.method == u16at(&local, 8); | |
| 252 | 추가: item.repaired = &local[..4] != b"PK\x03\x04" | |
| 253 | 추가: || (flags & 8 == 0 | |
| 254 | 추가: && (u32at(&local, 14) != item.crc | |
| 255 | 추가: || u32at(&local, 18) as u64 != packed | |
| 256 | 추가: || u32at(&local, 22) as u64 != size)); | |
| 257 | 추가: if flags & 8 != 0 { | |
| 258 | 추가: let descriptor = bytes(source, stop, 12, cd)?; | |
| 259 | 추가: let skip = if &descriptor[..4] == b"PK\x07\x08" { | |
| 260 | 추가: 4 | |
| 261 | 추가: } else { | |
| 262 | 추가: 0 | |
| 263 | 추가: }; | |
| 264 | 추가: let d = bytes(source, stop + skip, 12, cd)?; | |
| 265 | 추가: if u32at(&d, 0) != item.crc | |
| 266 | 추가: || u32at(&d, 4) as u64 != packed | |
| 267 | 추가: || u32at(&d, 8) as u64 != size | |
| 268 | 추가: { | |
| 269 | 추가: item.boundary = false; | |
| 270 | 추가: } | |
| 271 | 추가: stop = add(stop, 12 + skip)?; | |
| 272 | 추가: } | |
| 273 | 추가: item.stop = stop; | |
| 274 | 추가: if kind == EntryKind::Directory && size != 0 { | |
| 275 | 추가: item.boundary = false; | |
| 276 | 추가: } | |
| 277 | 추가: items.push(item); | |
| 278 | 추가: at = next; | |
| 279 | 추가: completed(Ok(()), check)?; | |
| 280 | 추가: } | |
| 281 | 추가: if at != cd_end { | |
| 282 | 추가: return Err(ErrorCode::Integrity); | |
| 283 | 추가: } | |
| 284 | 추가: items.sort_by_key(|c| c.finding.source_offset); | |
| 285 | 추가: let mut cursor = 0; | |
| 286 | 추가: let mut complete = true; | |
| 287 | 추가: for c in &items { | |
| 288 | 추가: if c.finding.source_offset < cursor { | |
| 289 | 추가: return Err(ErrorCode::Integrity); | |
| 290 | 추가: } | |
| 291 | 추가: complete &= c.finding.source_offset == cursor && c.boundary; | |
| 292 | 추가: cursor = c.stop; | |
| 293 | 추가: } | |
| 294 | 추가: complete &= cursor == cd; | |
| 295 | 추가: Ok(Some((items, complete))) | |
| 296 | 추가: } | |
| 297 | 추가: fn local( | |
| 298 | 추가: source: &mut File, | |
| 299 | 추가: len: u64, | |
| 300 | 추가: limits: Limits, | |
| 301 | 추가: check: &mut impl Monitor, | |
| 302 | 추가: ) -> Result<Vec<Candidate>> { | |
| 303 | 추가: let mut at = 0; | |
| 304 | 추가: let mut items = Vec::new(); | |
| 305 | 추가: let mut metadata = MetadataBudget::default(); | |
| 306 | 추가: while at < len { | |
| 307 | 추가: check.check()?; | |
| 308 | 추가: if len - at < 30 { | |
| 309 | 추가: break; | |
| 310 | 추가: } | |
| 311 | 추가: let h = bytes(source, at, 30, len)?; | |
| 312 | 추가: if &h[..4] != b"PK\x03\x04" { | |
| 313 | 추가: if at == 0 | |
| 314 | 추가: && (h.starts_with(b"MZ") | |
| 315 | 추가: || h.starts_with(b"PK\x07\x08") | |
| 316 | 추가: || h.starts_with(b"PK\x06")) | |
| 317 | 추가: { | |
| 318 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 319 | 추가: } | |
| 320 | 추가: break; | |
| 321 | 추가: } | |
| 322 | 추가: let count = u32::try_from(items.len() + 1).map_err(|_| ErrorCode::Limit)?; | |
| 323 | 추가: if count > limits.entries { | |
| 324 | 추가: return Err(ErrorCode::Limit); | |
| 325 | 추가: } | |
| 326 | 추가: check.observe( | |
| 327 | 추가: ResourceUsage { | |
| 328 | 추가: actual_entries: Some(count), | |
| 329 | 추가: ..ResourceUsage::default() | |
| 330 | 추가: }, | |
| 331 | 추가: Some(source), | |
| 332 | 추가: )?; | |
| 333 | 추가: let flags = u16at(&h, 6); | |
| 334 | 추가: if flags & 0x2040 != 0 { | |
| 335 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 336 | 추가: } | |
| 337 | 추가: let nn = u16at(&h, 26) as usize; | |
| 338 | 추가: let ne = u16at(&h, 28) as usize; | |
| 339 | 추가: charge(&mut metadata, nn, ne, check)?; | |
| 340 | 추가: let start = add(at, 30 + nn as u64 + ne as u64)?; | |
| 341 | 추가: if start > len { | |
| 342 | 추가: break; | |
| 343 | 추가: } | |
| 344 | 추가: let raw = bytes(source, at + 30, nn, len)?; | |
| 345 | 추가: let ext = bytes(source, at + 30 + nn as u64, ne, len)?; | |
| 346 | 추가: extra(&ext)?; | |
| 347 | 추가: let kind = if raw.ends_with(b"/") { | |
| 348 | 추가: EntryKind::Directory | |
| 349 | 추가: } else { | |
| 350 | 추가: EntryKind::File | |
| 351 | 추가: }; | |
| 352 | 추가: let name = named(&raw, flags, &ext, kind)?; | |
| 353 | 추가: metadata.charge_with(&name, check.metadata_limits())?; | |
| 354 | 추가: let (size, packed) = declared(u32at(&h, 22), u32at(&h, 18))?; | |
| 355 | 추가: let mut c = candidate( | |
| 356 | 추가: at, | |
| 357 | 추가: name, | |
| 358 | 추가: kind, | |
| 359 | 추가: size, | |
| 360 | 추가: packed, | |
| 361 | 추가: u32at(&h, 14), | |
| 362 | 추가: u16at(&h, 8), | |
| 363 | 추가: flags, | |
| 364 | 추가: ); | |
| 365 | 추가: c.start = start; | |
| 366 | 추가: c.stop = add(start, packed)?; | |
| 367 | 추가: if flags & 8 != 0 { | |
| 368 | 추가: c.finding.declared_size = None; | |
| 369 | 추가: items.push(c); | |
| 370 | 추가: break; | |
| 371 | 추가: } | |
| 372 | 추가: c.boundary = true; | |
| 373 | 추가: let next = c.stop; | |
| 374 | 추가: items.push(c); | |
| 375 | 추가: if next > len { | |
| 376 | 추가: break; | |
| 377 | 추가: } | |
| 378 | 추가: at = next; | |
| 379 | 추가: completed(Ok(()), check)?; | |
| 380 | 추가: } | |
| 381 | 추가: Ok(items) | |
| 382 | 추가: } | |
| 383 | 추가: | |
| 384 | 추가: pub(crate) struct Recovery { | |
| 385 | 추가: source: Input, | |
| 386 | 추가: path: PathBuf, | |
| 387 | 추가: modified: Option<SystemTime>, | |
| 388 | 추가: pub snapshot: spool::Snapshot, | |
| 389 | 추가: pub findings: Vec<RecoveryEntry>, | |
| 390 | 추가: pub summary: RecoveryEnd, | |
| 391 | 추가: pub data: File, | |
| 392 | 추가: pub offsets: Vec<u64>, | |
| 393 | 추가: } | |
| 394 | 추가: impl Recovery { | |
| 395 | 추가: pub fn open(path: &Path, limits: Limits, check: &mut impl Monitor) -> Result<Self> { | |
| 396 | 추가: let mut source = completed(Input::open(path), check)?; | |
| 397 | 추가: let meta = io(source.file.metadata())?; | |
| 398 | 추가: if !meta.is_file() { | |
| 399 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 400 | 추가: } | |
| 401 | 추가: if meta.len() > INPUT_CAP { | |
| 402 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 403 | 추가: } | |
| 404 | 추가: let prefix = bytes(&mut source.file, 0, meta.len().min(4) as usize, meta.len())?; | |
| 405 | 추가: if prefix.starts_with(b"MZ") | |
| 406 | 추가: || prefix.starts_with(b"PK\x07\x08") | |
| 407 | 추가: || prefix.starts_with(b"PK\x06") | |
| 408 | 추가: { | |
| 409 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 410 | 추가: } | |
| 411 | 추가: let mut snapshot = | |
| 412 | 추가: spool::Snapshot::capture(&mut source.file, limits.input.min(INPUT_CAP), check)?; | |
| 413 | 추가: let named = completed(Input::open(path), check)?; | |
| 414 | 추가: if filesystem::object(&named.file)? != snapshot.object { | |
| 415 | 추가: return Err(ErrorCode::SourceChanged); | |
| 416 | 추가: } | |
| 417 | 추가: let discovered = central(&mut snapshot.file, snapshot.len, limits, check); | |
| 418 | 추가: let (mut candidates, mode, known) = match discovered { | |
| 419 | 추가: Ok(Some((items, complete))) => (items, RecoveryMode::CentralDirectory, complete), | |
| 420 | 추가: Ok(None) | Err(ErrorCode::Integrity) => ( | |
| 421 | 추가: local(&mut snapshot.file, snapshot.len, limits, check)?, | |
| 422 | 추가: RecoveryMode::LocalChain, | |
| 423 | 추가: false, | |
| 424 | 추가: ), | |
| 425 | 추가: Err(error) => return Err(error), | |
| 426 | 추가: }; | |
| 427 | 추가: let mut names = Vec::new(); | |
| 428 | 추가: let mut budget = MetadataBudget::default(); | |
| 429 | 추가: for (id, c) in candidates.iter_mut().enumerate() { | |
| 430 | 추가: c.finding.candidate_id = id as u32; | |
| 431 | 추가: let name = c.finding.name.as_ref().ok_or(ErrorCode::Internal)?; | |
| 432 | 추가: budget.charge_with(name, check.metadata_limits())?; | |
| 433 | 추가: names.push(Member { | |
| 434 | 추가: entry: Entry { | |
| 435 | 추가: entry_id: id as u32, | |
| 436 | 추가: name: name.clone(), | |
| 437 | 추가: kind: c.finding.kind.unwrap(), | |
| 438 | 추가: size: c.finding.declared_size.unwrap_or(0), | |
| 439 | 추가: compressed_size: c.packed, | |
| 440 | 추가: encrypted: false, | |
| 441 | 추가: }, | |
| 442 | 추가: data: Vec::new(), | |
| 443 | 추가: }); | |
| 444 | 추가: } | |
| 445 | 추가: archive::validate_members_with(&names, check)?; | |
| 446 | 추가: drop(names); | |
| 447 | 추가: let mut data = spool::temporary()?; | |
| 448 | 추가: let mut findings = Vec::new(); | |
| 449 | 추가: let mut offsets = Vec::new(); | |
| 450 | 추가: let mut used = 0u64; | |
| 451 | 추가: let mut verified = 0; | |
| 452 | 추가: let mut lost = 0; | |
| 453 | 추가: let mut unverified = 0; | |
| 454 | 추가: let mut repaired = false; | |
| 455 | 추가: for c in candidates { | |
| 456 | 추가: check.check()?; | |
| 457 | 추가: let base = io(data.stream_position())?; | |
| 458 | 추가: offsets.push(base); | |
| 459 | 추가: let mut finding = c.finding; | |
| 460 | 추가: if !c.boundary { | |
| 461 | 추가: finding.reason = RecoveryReason::BoundaryUnknown; | |
| 462 | 추가: } else if !c.supported { | |
| 463 | 추가: finding.reason = RecoveryReason::UnsupportedFeature; | |
| 464 | 추가: } else if c.stop > snapshot.len { | |
| 465 | 추가: finding.status = RecoveryStatus::Lost; | |
| 466 | 추가: finding.reason = RecoveryReason::Truncated; | |
| 467 | 추가: } else { | |
| 468 | 추가: let size = finding.declared_size.ok_or(ErrorCode::Internal)?; | |
| 469 | 추가: if used.checked_add(size).is_none_or(|n| n > limits.output) { | |
| 470 | 추가: return Err(ErrorCode::Limit); | |
| 471 | 추가: } | |
| 472 | 추가: check.observe( | |
| 473 | 추가: ResourceUsage { | |
| 474 | 추가: estimated_bytes: Some(used + size), | |
| 475 | 추가: actual_entries: Some(finding.candidate_id + 1), | |
| 476 | 추가: compressed_bytes: Some(c.packed), | |
| 477 | 추가: ratio_output_bytes: Some(size), | |
| 478 | 추가: ..ResourceUsage::default() | |
| 479 | 추가: }, | |
| 480 | 추가: Some(&data), | |
| 481 | 추가: )?; | |
| 482 | 추가: io(snapshot.file.seek(SeekFrom::Start(c.start)))?; | |
| 483 | 추가: let decoded = decode( | |
| 484 | 추가: &mut snapshot.file, | |
| 485 | 추가: c.packed, | |
| 486 | 추가: c.method, | |
| 487 | 추가: size, | |
| 488 | 추가: &mut data, | |
| 489 | 추가: &mut used, | |
| 490 | 추가: limits, | |
| 491 | 추가: check, | |
| 492 | 추가: ); | |
| 493 | 추가: match decoded { | |
| 494 | 추가: Ok((length, crc, hash)) | |
| 495 | 추가: if length == size | |
| 496 | 추가: && crc == c.crc | |
| 497 | 추가: && (finding.kind != Some(EntryKind::Directory) || size == 0) => | |
| 498 | 추가: { | |
| 499 | 추가: finding.status = RecoveryStatus::Verified; | |
| 500 | 추가: finding.reason = if c.repaired { | |
| 501 | 추가: RecoveryReason::HeaderRebuilt | |
| 502 | 추가: } else if mode == RecoveryMode::LocalChain { | |
| 503 | 추가: RecoveryReason::MetadataMissing | |
| 504 | 추가: } else { | |
| 505 | 추가: RecoveryReason::None | |
| 506 | 추가: }; | |
| 507 | 추가: finding.verified_size = Some(size); | |
| 508 | 추가: finding.sha256 = if finding.kind == Some(EntryKind::File) { | |
| 509 | 추가: Some(hash) | |
| 510 | 추가: } else { | |
| 511 | 추가: None | |
| 512 | 추가: }; | |
| 513 | 추가: } | |
| 514 | 추가: Ok((length, _, _)) => { | |
| 515 | 추가: finding.status = RecoveryStatus::Lost; | |
| 516 | 추가: finding.reason = if length == size { | |
| 517 | 추가: RecoveryReason::CrcMismatch | |
| 518 | 추가: } else { | |
| 519 | 추가: RecoveryReason::DecodeFailure | |
| 520 | 추가: }; | |
| 521 | 추가: } | |
| 522 | 추가: Err(ErrorCode::Integrity) => { | |
| 523 | 추가: finding.status = RecoveryStatus::Lost; | |
| 524 | 추가: finding.reason = RecoveryReason::DecodeFailure; | |
| 525 | 추가: } | |
| 526 | 추가: Err(error) => return Err(error), | |
| 527 | 추가: } | |
| 528 | 추가: if finding.status != RecoveryStatus::Verified { | |
| 529 | 추가: io(data.set_len(base))?; | |
| 530 | 추가: io(data.seek(SeekFrom::Start(base)))?; | |
| 531 | 추가: } | |
| 532 | 추가: } | |
| 533 | 추가: repaired |= c.repaired; | |
| 534 | 추가: match finding.status { | |
| 535 | 추가: RecoveryStatus::Verified => verified += 1, | |
| 536 | 추가: RecoveryStatus::Lost => lost += 1, | |
| 537 | 추가: RecoveryStatus::Unverified => unverified += 1, | |
| 538 | 추가: } | |
| 539 | 추가: check.progress(Stage::Verify, used, None, finding.candidate_id + 1)?; | |
| 540 | 추가: findings.push(finding); | |
| 541 | 추가: } | |
| 542 | 추가: if known && verified as usize == findings.len() && !repaired { | |
| 543 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 544 | 추가: } | |
| 545 | 추가: let summary = RecoveryEnd { | |
| 546 | 추가: mode, | |
| 547 | 추가: source_bytes: snapshot.len, | |
| 548 | 추가: source_sha256: snapshot.hash, | |
| 549 | 추가: known_entries: if known { | |
| 550 | 추가: Some(findings.len() as u32) | |
| 551 | 추가: } else { | |
| 552 | 추가: None | |
| 553 | 추가: }, | |
| 554 | 추가: verified_entries: verified, | |
| 555 | 추가: lost_entries: lost, | |
| 556 | 추가: unverified_entries: unverified, | |
| 557 | 추가: unknown_loss: !known, | |
| 558 | 추가: }; | |
| 559 | 추가: Ok(Self { | |
| 560 | 추가: source, | |
| 561 | 추가: path: path.to_owned(), | |
| 562 | 추가: modified: meta.modified().ok(), | |
| 563 | 추가: snapshot, | |
| 564 | 추가: findings, | |
| 565 | 추가: summary, | |
| 566 | 추가: data, | |
| 567 | 추가: offsets, | |
| 568 | 추가: }) | |
| 569 | 추가: } | |
| 570 | 추가: pub fn build(&mut self, limits: Limits, check: &mut impl Monitor) -> Result<(File, u64)> { | |
| 571 | 추가: let (mut output, len) = | |
| 572 | 추가: crate::create::recovered_zip(&self.findings, &self.offsets, &mut self.data, check)?; | |
| 573 | 추가: let mut replay = Replay(check); | |
| 574 | 추가: let mut catalog = | |
| 575 | 추가: crate::streaming::Catalog::open(&mut output, len, limits, true, None, &mut replay)?; | |
| 576 | 추가: if catalog.format != Format::Zip | |
| 577 | 추가: || catalog.members.len() != self.summary.verified_entries as usize | |
| 578 | 추가: { | |
| 579 | 추가: return Err(ErrorCode::Integrity); | |
| 580 | 추가: } | |
| 581 | 추가: for ((member, offset), finding) in catalog.members.iter().zip(&catalog.offsets).zip( | |
| 582 | 추가: self.findings | |
| 583 | 추가: .iter() | |
| 584 | 추가: .filter(|e| e.status == RecoveryStatus::Verified), | |
| 585 | 추가: ) { | |
| 586 | 추가: if Some(&member.entry.name) != finding.name.as_ref() | |
| 587 | 추가: || Some(member.entry.kind) != finding.kind | |
| 588 | 추가: || Some(member.entry.size) != finding.verified_size | |
| 589 | 추가: { | |
| 590 | 추가: return Err(ErrorCode::Integrity); | |
| 591 | 추가: } | |
| 592 | 추가: if member.entry.kind == EntryKind::File { | |
| 593 | 추가: io(catalog.data.seek(SeekFrom::Start(*offset)))?; | |
| 594 | 추가: let mut input = (&mut catalog.data).take(member.entry.size); | |
| 595 | 추가: let mut hash = Sha256::new(); | |
| 596 | 추가: let mut buffer = [0; 65536]; | |
| 597 | 추가: loop { | |
| 598 | 추가: replay.check()?; | |
| 599 | 추가: let n = completed(io(input.read(&mut buffer)), &mut replay)?; | |
| 600 | 추가: if n == 0 { | |
| 601 | 추가: break; | |
| 602 | 추가: } | |
| 603 | 추가: hash.update(&buffer[..n]); | |
| 604 | 추가: } | |
| 605 | 추가: if input.limit() != 0 || Some(<[u8; 32]>::from(hash.finalize())) != finding.sha256 { | |
| 606 | 추가: return Err(ErrorCode::Integrity); | |
| 607 | 추가: } | |
| 608 | 추가: } | |
| 609 | 추가: } | |
| 610 | 추가: io(output.rewind())?; | |
| 611 | 추가: Ok((output, len)) | |
| 612 | 추가: } | |
| 613 | 추가: pub fn verify_source(&mut self, check: &mut impl Monitor) -> Result<()> { | |
| 614 | 추가: let mut named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 615 | 추가: let before = io(named.file.metadata())?; | |
| 616 | 추가: let pinned = io(self.source.file.metadata())?; | |
| 617 | 추가: if filesystem::object(&named.file)? != self.snapshot.object | |
| 618 | 추가: || before.len() != self.snapshot.len | |
| 619 | 추가: || before.modified().ok() != self.modified | |
| 620 | 추가: || pinned.len() != self.snapshot.len | |
| 621 | 추가: || pinned.modified().ok() != self.modified | |
| 622 | 추가: { | |
| 623 | 추가: return Err(ErrorCode::SourceChanged); | |
| 624 | 추가: } | |
| 625 | 추가: let mut hash = Sha256::new(); | |
| 626 | 추가: let mut buffer = [0; 65536]; | |
| 627 | 추가: let mut length = 0; | |
| 628 | 추가: loop { | |
| 629 | 추가: check.check()?; | |
| 630 | 추가: let n = completed(io(named.file.read(&mut buffer)), check)?; | |
| 631 | 추가: if n == 0 { | |
| 632 | 추가: break; | |
| 633 | 추가: } | |
| 634 | 추가: length = add(length, n as u64)?; | |
| 635 | 추가: hash.update(&buffer[..n]); | |
| 636 | 추가: check.progress( | |
| 637 | 추가: Stage::Verify, | |
| 638 | 추가: length, | |
| 639 | 추가: Some(self.snapshot.len), | |
| 640 | 추가: self.findings.len() as u32, | |
| 641 | 추가: )?; | |
| 642 | 추가: } | |
| 643 | 추가: let after = io(named.file.metadata())?; | |
| 644 | 추가: let current = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 645 | 추가: if length != self.snapshot.len | |
| 646 | 추가: || <[u8; 32]>::from(hash.finalize()) != self.snapshot.hash | |
| 647 | 추가: || after.len() != self.snapshot.len | |
| 648 | 추가: || after.modified().ok() != self.modified | |
| 649 | 추가: || filesystem::object(¤t.file)? != self.snapshot.object | |
| 650 | 추가: { | |
| 651 | 추가: return Err(ErrorCode::SourceChanged); | |
| 652 | 추가: } | |
| 653 | 추가: Ok(()) | |
| 654 | 추가: } | |
| 655 | 추가: } | |
| 656 | 추가: fn decode( | |
| 657 | 추가: input: &mut File, | |
| 658 | 추가: length: u64, | |
| 659 | 추가: method: u16, | |
| 660 | 추가: declared: u64, | |
| 661 | 추가: output: &mut File, | |
| 662 | 추가: used: &mut u64, | |
| 663 | 추가: limits: Limits, | |
| 664 | 추가: check: &mut impl Monitor, | |
| 665 | 추가: ) -> Result<(u64, u32, [u8; 32])> { | |
| 666 | 추가: let mut input = input.take(length); | |
| 667 | 추가: let mut stream = Inflate::new(false, 15); | |
| 668 | 추가: let mut buffer = [0; 65536]; | |
| 669 | 추가: let mut plain = [0; 65536]; | |
| 670 | 추가: let mut have = 0; | |
| 671 | 추가: let mut at = 0; | |
| 672 | 추가: let mut total = 0u64; | |
| 673 | 추가: let mut crc = 0; | |
| 674 | 추가: let mut hash = Sha256::new(); | |
| 675 | 추가: loop { | |
| 676 | 추가: check.check()?; | |
| 677 | 추가: if at == have && input.limit() != 0 { | |
| 678 | 추가: have = completed(io(input.read(&mut buffer)), check)?; | |
| 679 | 추가: at = 0; | |
| 680 | 추가: if have == 0 { | |
| 681 | 추가: return Err(ErrorCode::Integrity); | |
| 682 | 추가: } | |
| 683 | 추가: } | |
| 684 | 추가: let (n, status, consumed, corrupt) = if method == 0 { | |
| 685 | 추가: plain[..have].copy_from_slice(&buffer[..have]); | |
| 686 | 추가: ( | |
| 687 | 추가: have, | |
| 688 | 추가: if input.limit() == 0 { | |
| 689 | 추가: Status::StreamEnd | |
| 690 | 추가: } else { | |
| 691 | 추가: Status::Ok | |
| 692 | 추가: }, | |
| 693 | 추가: have, | |
| 694 | 추가: false, | |
| 695 | 추가: ) | |
| 696 | 추가: } else { | |
| 697 | 추가: let before_in = stream.total_in(); | |
| 698 | 추가: let before_out = stream.total_out(); | |
| 699 | 추가: let status = stream.decompress(&buffer[at..have], &mut plain, InflateFlush::NoFlush); | |
| 700 | 추가: let corrupt = status.is_err(); | |
| 701 | 추가: ( | |
| 702 | 추가: (stream.total_out() - before_out) as usize, | |
| 703 | 추가: status.unwrap_or(Status::Ok), | |
| 704 | 추가: (stream.total_in() - before_in) as usize, | |
| 705 | 추가: corrupt, | |
| 706 | 추가: ) | |
| 707 | 추가: }; | |
| 708 | 추가: at += consumed; | |
| 709 | 추가: total = total.checked_add(n as u64).ok_or(ErrorCode::Limit)?; | |
| 710 | 추가: *used = used | |
| 711 | 추가: .checked_add(n as u64) | |
| 712 | 추가: .filter(|n| *n <= limits.output) | |
| 713 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 714 | 추가: check.observe( | |
| 715 | 추가: ResourceUsage { | |
| 716 | 추가: actual_bytes: Some(*used), | |
| 717 | 추가: compressed_bytes: Some(length), | |
| 718 | 추가: ratio_output_bytes: Some(total), | |
| 719 | 추가: ..ResourceUsage::default() | |
| 720 | 추가: }, | |
| 721 | 추가: Some(output), | |
| 722 | 추가: )?; | |
| 723 | 추가: if corrupt || total > declared { | |
| 724 | 추가: return Err(ErrorCode::Integrity); | |
| 725 | 추가: } | |
| 726 | 추가: crc = crc32(crc, &plain[..n]); | |
| 727 | 추가: hash.update(&plain[..n]); | |
| 728 | 추가: crate::space::ensure(output, n as u64)?; | |
| 729 | 추가: completed(io(output.write_all(&plain[..n])), check)?; | |
| 730 | 추가: if status == Status::StreamEnd { | |
| 731 | 추가: if input.limit() != 0 || at != have { | |
| 732 | 추가: return Err(ErrorCode::Integrity); | |
| 733 | 추가: } | |
| 734 | 추가: break; | |
| 735 | 추가: } | |
| 736 | 추가: if n == 0 && consumed == 0 { | |
| 737 | 추가: return Err(ErrorCode::Integrity); | |
| 738 | 추가: } | |
| 739 | 추가: } | |
| 740 | 추가: Ok((total, crc, hash.finalize().into())) | |
| 741 | 추가: } | |
| 742 | 추가: | |
| 743 | 추가: struct Replay<'a, M>(&'a mut M); | |
| 744 | 추가: impl<M: Monitor> Monitor for Replay<'_, M> { | |
| 745 | 추가: fn metadata_limits(&self) -> archive::MetadataLimits { | |
| 746 | 추가: self.0.metadata_limits() | |
| 747 | 추가: } | |
| 748 | 추가: fn check(&mut self) -> Result<()> { | |
| 749 | 추가: self.0.check() | |
| 750 | 추가: } | |
| 751 | 추가: fn activity(&mut self) -> Result<()> { | |
| 752 | 추가: self.0.activity() | |
| 753 | 추가: } | |
| 754 | 추가: fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&File>) -> Result<()> { | |
| 755 | 추가: self.0.check() | |
| 756 | 추가: } | |
| 757 | 추가: } | |
| 758 | 추가: | |
| 759 | 추가: #[cfg(test)] | |
| 760 | 추가: #[path = "../../../tests/rust-archive-worker/recovery_checks.rs"] | |
| 761 | 추가: mod tests; |
| @@ -31,8 +31,8 @@ class ZipRecoveryContractTests(unittest.TestCase): | ||
| 31 | 31 | @classmethod |
| 32 | 32 | def setUpClass(cls): |
| 33 | 33 | worker = ROOT / "experiments" / "rust-archive-worker" |
| 34 | 삭제: cls.wire = (worker / "src" / "wire.rs").read_text() | |
| 35 | 삭제: cls.contract = json.loads((worker / "contract.json").read_text()) | |
| 34 | 추가: cls.wire = (worker / "src" / "wire.rs").read_text(encoding="utf-8") | |
| 35 | 추가: cls.contract = json.loads((worker / "contract.json").read_text(encoding="utf-8")) | |
| 36 | 36 | cls.proposal = cls.contract["zip_recovery_proposal"] |
| 37 | 37 | |
| 38 | 38 | def test_error_tags_are_checked_against_live_wire(self): |
| @@ -542,7 +542,10 @@ fn links_and_special_entries_are_not_interactive() { | ||
| 542 | 542 | 0 => symlink(s.0.join("outside"), s.0.join("output/a")).unwrap(), |
| 543 | 543 | 1 => symlink(s.0.join("missing"), s.0.join("output/a")).unwrap(), |
| 544 | 544 | _ => { |
| 545 | 삭제: listener = UnixListener::bind(s.0.join("output/a")).unwrap(); | |
| 545 | 추가: use std::os::fd::AsRawFd; | |
| 546 | 추가: let directory = fs::File::open(s.0.join("output")).unwrap(); | |
| 547 | 추가: listener = UnixListener::bind(format!("/proc/self/fd/{}/a", directory.as_raw_fd())) | |
| 548 | 추가: .unwrap(); | |
| 546 | 549 | let _ = &listener; |
| 547 | 550 | } |
| 548 | 551 | } |
| @@ -1601,7 +1601,7 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() { | ||
| 1601 | 1601 | assert_eq!(bytes[33], tag as u8); |
| 1602 | 1602 | let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2; |
| 1603 | 1603 | assert_eq!(terminal(&[decoded]).error, error); |
| 1604 | 삭제: bytes[33] = 15; | |
| 1604 | 추가: bytes[33] = 17; | |
| 1605 | 1605 | assert!(Reader::new(bytes.as_slice()).read().is_err()); |
| 1606 | 1606 | } |
| 1607 | 1607 | } |
| @@ -1629,3 +1629,5 @@ mod split_runtime; | ||
| 1629 | 1629 | mod seven_zip_create; |
| 1630 | 1630 | |
| 1631 | 1631 | mod seven_zip_create_runtime; |
| 1632 | 추가: | |
| 1633 | 추가: mod recovery; |
| @@ -0,0 +1,497 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use sha2::{Digest, Sha256}; | |
| 3 | 추가: | |
| 4 | 추가: fn start(s: &Scratch) -> Start { | |
| 5 | 추가: Start { | |
| 6 | 추가: action: Action::RecoverZip { | |
| 7 | 추가: archive: s.path("damaged.zip"), | |
| 8 | 추가: output_file: s.path("recovered.zip"), | |
| 9 | 추가: }, | |
| 10 | 추가: limits: Limits::default(), | |
| 11 | 추가: } | |
| 12 | 추가: } | |
| 13 | 추가: fn hash(data: &[u8]) -> String { | |
| 14 | 추가: format!("{:x}", Sha256::digest(data)) | |
| 15 | 추가: } | |
| 16 | 추가: fn recovery_end(events: &[Message]) -> &RecoveryEnd { | |
| 17 | 추가: events | |
| 18 | 추가: .iter() | |
| 19 | 추가: .find_map(|e| { | |
| 20 | 추가: if let Message::RecoveryEnd(end) = e { | |
| 21 | 추가: Some(end) | |
| 22 | 추가: } else { | |
| 23 | 추가: None | |
| 24 | 추가: } | |
| 25 | 추가: }) | |
| 26 | 추가: .unwrap() | |
| 27 | 추가: } | |
| 28 | 추가: #[test] | |
| 29 | 추가: fn six_damaged_corpora_preserve_source_and_independent_expected_hashes() { | |
| 30 | 추가: let cases: &[(&str, &[u8], usize, bool)] = &[ | |
| 31 | 추가: ( | |
| 32 | 추가: "broken-local-header.zip", | |
| 33 | 추가: include_bytes!("../zip-recovery-fixtures/broken-local-header.zip"), | |
| 34 | 추가: 6, | |
| 35 | 추가: true, | |
| 36 | 추가: ), | |
| 37 | 추가: ( | |
| 38 | 추가: "missing-directory.zip", | |
| 39 | 추가: include_bytes!("../zip-recovery-fixtures/missing-directory.zip"), | |
| 40 | 추가: 6, | |
| 41 | 추가: false, | |
| 42 | 추가: ), | |
| 43 | 추가: ( | |
| 44 | 추가: "broken-eocd.zip", | |
| 45 | 추가: include_bytes!("../zip-recovery-fixtures/broken-eocd.zip"), | |
| 46 | 추가: 6, | |
| 47 | 추가: false, | |
| 48 | 추가: ), | |
| 49 | 추가: ( | |
| 50 | 추가: "middle-truncated.zip", | |
| 51 | 추가: include_bytes!("../zip-recovery-fixtures/middle-truncated.zip"), | |
| 52 | 추가: 4, | |
| 53 | 추가: false, | |
| 54 | 추가: ), | |
| 55 | 추가: ( | |
| 56 | 추가: "body-corrupt.zip", | |
| 57 | 추가: include_bytes!("../zip-recovery-fixtures/body-corrupt.zip"), | |
| 58 | 추가: 5, | |
| 59 | 추가: false, | |
| 60 | 추가: ), | |
| 61 | 추가: ( | |
| 62 | 추가: "unrecoverable.zip", | |
| 63 | 추가: include_bytes!("../zip-recovery-fixtures/unrecoverable.zip"), | |
| 64 | 추가: 0, | |
| 65 | 추가: false, | |
| 66 | 추가: ), | |
| 67 | 추가: ]; | |
| 68 | 추가: let expected = [ | |
| 69 | 추가: ( | |
| 70 | 추가: "hello.txt", | |
| 71 | 추가: "29020da72fa4030c58e0303f558b922f6ed5b6766600e67d79e0abf13971f9da", | |
| 72 | 추가: ), | |
| 73 | 추가: ( | |
| 74 | 추가: "한글/자료.txt", | |
| 75 | 추가: "3fd2605633caf264a9cf9eb1fc23abc4a60b3191fc808a6a0f71863c64690be5", | |
| 76 | 추가: ), | |
| 77 | 추가: ( | |
| 78 | 추가: "empty.txt", | |
| 79 | 추가: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", | |
| 80 | 추가: ), | |
| 81 | 추가: ( | |
| 82 | 추가: "empty-dir", | |
| 83 | 추가: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", | |
| 84 | 추가: ), | |
| 85 | 추가: ( | |
| 86 | 추가: "middle.bin", | |
| 87 | 추가: "785b0751fc2c53dc14a4ce3d800e69ef9ce1009eb327ccf458afe09c242c26c9", | |
| 88 | 추가: ), | |
| 89 | 추가: ( | |
| 90 | 추가: "after.txt", | |
| 91 | 추가: "7ea5f891c2d1be8db73893862b433f6680e33e11a7246baeea0addd8d296975c", | |
| 92 | 추가: ), | |
| 93 | 추가: ]; | |
| 94 | 추가: for &(sample, input, count, complete) in cases { | |
| 95 | 추가: let s = Scratch::new(); | |
| 96 | 추가: fs::write(s.0.join("damaged.zip"), input).unwrap(); | |
| 97 | 추가: let events = execute(start(&s)); | |
| 98 | 추가: let t = terminal(&events); | |
| 99 | 추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input); | |
| 100 | 추가: let end = recovery_end(&events); | |
| 101 | 추가: assert_eq!(end.source_sha256, <[u8; 32]>::from(Sha256::digest(input))); | |
| 102 | 추가: assert_eq!(end.verified_entries as usize, count); | |
| 103 | 추가: assert_eq!(end.unknown_loss, !complete); | |
| 104 | 추가: assert_eq!(end.known_entries, if complete { Some(6) } else { None }); | |
| 105 | 추가: assert!(!events.iter().any(|e| matches!( | |
| 106 | 추가: e, | |
| 107 | 추가: Message::Entry(_) | |
| 108 | 추가: | Message::ListEnd { .. } | |
| 109 | 추가: | Message::PasswordRequired { .. } | |
| 110 | 추가: | Message::ConflictRequired { .. } | |
| 111 | 추가: ))); | |
| 112 | 추가: assert!(matches!( | |
| 113 | 추가: events[0], | |
| 114 | 추가: Message::Accepted { | |
| 115 | 추가: action: ActionKind::RecoverZip, | |
| 116 | 추가: encryption: false | |
| 117 | 추가: } | |
| 118 | 추가: )); | |
| 119 | 추가: if count == 0 { | |
| 120 | 추가: assert_eq!(t.error, ErrorCode::RecoveryImpossible); | |
| 121 | 추가: assert_eq!(t.publication, Publication::None); | |
| 122 | 추가: assert!(!s.0.join("recovered.zip").exists()); | |
| 123 | 추가: continue; | |
| 124 | 추가: } | |
| 125 | 추가: assert_eq!( | |
| 126 | 추가: t.error, | |
| 127 | 추가: if complete { | |
| 128 | 추가: ErrorCode::None | |
| 129 | 추가: } else { | |
| 130 | 추가: ErrorCode::RecoveryIncomplete | |
| 131 | 추가: } | |
| 132 | 추가: ); | |
| 133 | 추가: assert_eq!( | |
| 134 | 추가: t.outcome, | |
| 135 | 추가: if complete { | |
| 136 | 추가: Outcome::Completed | |
| 137 | 추가: } else { | |
| 138 | 추가: Outcome::Failed | |
| 139 | 추가: } | |
| 140 | 추가: ); | |
| 141 | 추가: assert_eq!(t.created_count, 1); | |
| 142 | 추가: assert_eq!(t.publication, Publication::Complete); | |
| 143 | 추가: let bytes = fs::read(s.0.join("recovered.zip")).unwrap(); | |
| 144 | 추가: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap(); | |
| 145 | 추가: assert_eq!(catalog.members.len(), count); | |
| 146 | 추가: for member in &catalog.members { | |
| 147 | 추가: let (_, sha) = expected | |
| 148 | 추가: .iter() | |
| 149 | 추가: .find(|(name, _)| *name == member.entry.name) | |
| 150 | 추가: .unwrap(); | |
| 151 | 추가: assert_eq!(&hash(&member.data), sha); | |
| 152 | 추가: } | |
| 153 | 추가: let checker = PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 154 | 추가: .join("../../tests/zip-recovery-fixtures/verify.py"); | |
| 155 | 추가: let checked = Command::new("python3") | |
| 156 | 추가: .arg("-B") | |
| 157 | 추가: .arg(checker) | |
| 158 | 추가: .arg("--recovered") | |
| 159 | 추가: .arg(sample) | |
| 160 | 추가: .arg(s.0.join("recovered.zip")) | |
| 161 | 추가: .output() | |
| 162 | 추가: .unwrap(); | |
| 163 | 추가: assert!(checked.status.success(), "{:?}", checked); | |
| 164 | 추가: let findings: Vec<_> = events | |
| 165 | 추가: .iter() | |
| 166 | 추가: .filter_map(|e| { | |
| 167 | 추가: if let Message::RecoveryEntry(f) = e { | |
| 168 | 추가: Some(f) | |
| 169 | 추가: } else { | |
| 170 | 추가: None | |
| 171 | 추가: } | |
| 172 | 추가: }) | |
| 173 | 추가: .collect(); | |
| 174 | 추가: for (i, f) in findings.iter().enumerate() { | |
| 175 | 추가: assert_eq!(f.candidate_id, i as u32); | |
| 176 | 추가: assert!(f.valid()); | |
| 177 | 추가: assert!(f.source_offset < end.source_bytes); | |
| 178 | 추가: if i > 0 { | |
| 179 | 추가: assert!(findings[i - 1].source_offset < f.source_offset); | |
| 180 | 추가: } | |
| 181 | 추가: } | |
| 182 | 추가: if count == 4 { | |
| 183 | 추가: assert!( | |
| 184 | 추가: !findings | |
| 185 | 추가: .iter() | |
| 186 | 추가: .any(|f| f.name.as_deref() == Some("after.txt")) | |
| 187 | 추가: ); | |
| 188 | 추가: } | |
| 189 | 추가: if count == 5 { | |
| 190 | 추가: assert!(findings.iter().any( | |
| 191 | 추가: |f| f.name.as_deref() == Some("middle.bin") && f.status == RecoveryStatus::Lost | |
| 192 | 추가: )); | |
| 193 | 추가: } | |
| 194 | 추가: } | |
| 195 | 추가: } | |
| 196 | 추가: #[test] | |
| 197 | 추가: fn healthy_source_and_existing_destination_are_never_rewritten() { | |
| 198 | 추가: let s = Scratch::new(); | |
| 199 | 추가: let bytes = include_bytes!("../zip-recovery-fixtures/control.zip"); | |
| 200 | 추가: fs::write(s.0.join("damaged.zip"), bytes).unwrap(); | |
| 201 | 추가: let events = execute(start(&s)); | |
| 202 | 추가: assert_eq!(terminal(&events).error, ErrorCode::InvalidRequest); | |
| 203 | 추가: assert!(!s.0.join("recovered.zip").exists()); | |
| 204 | 추가: fs::write(s.0.join("recovered.zip"), b"keep").unwrap(); | |
| 205 | 추가: let events = execute(start(&s)); | |
| 206 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Conflict); | |
| 207 | 추가: assert_eq!(fs::read(s.0.join("recovered.zip")).unwrap(), b"keep"); | |
| 208 | 추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), bytes); | |
| 209 | 추가: } | |
| 210 | 추가: #[test] | |
| 211 | 추가: fn lower_input_output_and_candidate_quotas_leave_no_artifact() { | |
| 212 | 추가: for kind in 0..3 { | |
| 213 | 추가: let s = Scratch::new(); | |
| 214 | 추가: fs::write( | |
| 215 | 추가: s.0.join("damaged.zip"), | |
| 216 | 추가: include_bytes!("../zip-recovery-fixtures/missing-directory.zip"), | |
| 217 | 추가: ) | |
| 218 | 추가: .unwrap(); | |
| 219 | 추가: let mut request = start(&s); | |
| 220 | 추가: match kind { | |
| 221 | 추가: 0 => request.limits.input = 100, | |
| 222 | 추가: 1 => request.limits.output = 100, | |
| 223 | 추가: _ => request.limits.entries = 2, | |
| 224 | 추가: } | |
| 225 | 추가: let events = execute(request); | |
| 226 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Limit); | |
| 227 | 추가: assert!(!s.0.join("recovered.zip").exists()); | |
| 228 | 추가: } | |
| 229 | 추가: } | |
| 230 | 추가: #[test] | |
| 231 | 추가: fn unsafe_names_unsupported_input_and_payload_signatures_do_not_trigger_scanning() { | |
| 232 | 추가: let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip"); | |
| 233 | 추가: for kind in 0..4 { | |
| 234 | 추가: let s = Scratch::new(); | |
| 235 | 추가: let mut bytes = original.to_vec(); | |
| 236 | 추가: let expected = match kind { | |
| 237 | 추가: 0 => { | |
| 238 | 추가: bytes[30..39].copy_from_slice(b"../x.txt/"); | |
| 239 | 추가: ErrorCode::UnsafePath | |
| 240 | 추가: } | |
| 241 | 추가: 1 => { | |
| 242 | 추가: bytes[18..22].copy_from_slice(&u32::MAX.to_le_bytes()); | |
| 243 | 추가: ErrorCode::UnsupportedFeature | |
| 244 | 추가: } | |
| 245 | 추가: 2 => { | |
| 246 | 추가: bytes[..2].copy_from_slice(b"MZ"); | |
| 247 | 추가: ErrorCode::UnsupportedFeature | |
| 248 | 추가: } | |
| 249 | 추가: _ => { | |
| 250 | 추가: bytes[39..43].copy_from_slice(b"PK\x03\x04"); | |
| 251 | 추가: ErrorCode::RecoveryIncomplete | |
| 252 | 추가: } | |
| 253 | 추가: }; | |
| 254 | 추가: fs::write(s.0.join("damaged.zip"), &bytes).unwrap(); | |
| 255 | 추가: let events = execute(start(&s)); | |
| 256 | 추가: assert_eq!(terminal(&events).error, expected); | |
| 257 | 추가: if kind == 3 { | |
| 258 | 추가: assert_eq!(recovery_end(&events).verified_entries, 5); | |
| 259 | 추가: } else { | |
| 260 | 추가: assert!(!s.0.join("recovered.zip").exists()); | |
| 261 | 추가: } | |
| 262 | 추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), bytes); | |
| 263 | 추가: } | |
| 264 | 추가: } | |
| 265 | 추가: #[test] | |
| 266 | 추가: fn recovery_wire_rejects_interactive_modes_invalid_hashes_and_summary_overflow() { | |
| 267 | 추가: let s = Scratch::new(); | |
| 268 | 추가: let request = start(&s); | |
| 269 | 추가: assert!( | |
| 270 | 추가: Writer::new(Vec::new(), 17) | |
| 271 | 추가: .send(&Message::StartInteractive(request.clone())) | |
| 272 | 추가: .is_err() | |
| 273 | 추가: ); | |
| 274 | 추가: let guarded = GuardedStart { | |
| 275 | 추가: start: request, | |
| 276 | 추가: ceiling: Limits::default(), | |
| 277 | 추가: interactive: true, | |
| 278 | 추가: }; | |
| 279 | 추가: assert!(!guarded.valid()); | |
| 280 | 추가: assert!( | |
| 281 | 추가: Writer::new(Vec::new(), 17) | |
| 282 | 추가: .send(&Message::StartGuarded(guarded)) | |
| 283 | 추가: .is_err() | |
| 284 | 추가: ); | |
| 285 | 추가: let good = RecoveryEntry { | |
| 286 | 추가: candidate_id: 0, | |
| 287 | 추가: source_offset: 0, | |
| 288 | 추가: name: Some("ok".into()), | |
| 289 | 추가: kind: Some(EntryKind::File), | |
| 290 | 추가: status: RecoveryStatus::Verified, | |
| 291 | 추가: reason: RecoveryReason::HeaderRebuilt, | |
| 292 | 추가: declared_size: Some(0), | |
| 293 | 추가: verified_size: Some(0), | |
| 294 | 추가: sha256: Some([0; 32]), | |
| 295 | 추가: }; | |
| 296 | 추가: let mut bytes = Vec::new(); | |
| 297 | 추가: Writer::new(&mut bytes, 17) | |
| 298 | 추가: .send(&Message::RecoveryEntry(good.clone())) | |
| 299 | 추가: .unwrap(); | |
| 300 | 추가: assert_eq!(u16::from_le_bytes(bytes[6..8].try_into().unwrap()), 115); | |
| 301 | 추가: assert!( | |
| 302 | 추가: matches!(Reader::new(bytes.as_slice()).read().unwrap().unwrap().2,Message::RecoveryEntry(f) if f==good) | |
| 303 | 추가: ); | |
| 304 | 추가: let mut bad = good; | |
| 305 | 추가: bad.sha256 = None; | |
| 306 | 추가: assert!( | |
| 307 | 추가: Writer::new(Vec::new(), 17) | |
| 308 | 추가: .send(&Message::RecoveryEntry(bad)) | |
| 309 | 추가: .is_err() | |
| 310 | 추가: ); | |
| 311 | 추가: let summary = RecoveryEnd { | |
| 312 | 추가: mode: RecoveryMode::LocalChain, | |
| 313 | 추가: source_bytes: 10, | |
| 314 | 추가: source_sha256: [0; 32], | |
| 315 | 추가: known_entries: None, | |
| 316 | 추가: verified_entries: u32::MAX, | |
| 317 | 추가: lost_entries: 1, | |
| 318 | 추가: unverified_entries: 0, | |
| 319 | 추가: unknown_loss: true, | |
| 320 | 추가: }; | |
| 321 | 추가: assert!(!summary.valid()); | |
| 322 | 추가: assert!( | |
| 323 | 추가: Writer::new(Vec::new(), 17) | |
| 324 | 추가: .send(&Message::RecoveryEnd(summary)) | |
| 325 | 추가: .is_err() | |
| 326 | 추가: ); | |
| 327 | 추가: } | |
| 328 | 추가: | |
| 329 | 추가: #[cfg(target_os = "linux")] | |
| 330 | 추가: fn shim(s: &Scratch) -> PathBuf { | |
| 331 | 추가: let library = s.0.join("fault.so"); | |
| 332 | 추가: assert!( | |
| 333 | 추가: Command::new("cc") | |
| 334 | 추가: .args(["-shared", "-fPIC", "-O2"]) | |
| 335 | 추가: .arg( | |
| 336 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 337 | 추가: .join("../../tests/rust-archive-worker/io_fault.c") | |
| 338 | 추가: ) | |
| 339 | 추가: .arg("-ldl") | |
| 340 | 추가: .arg("-o") | |
| 341 | 추가: .arg(&library) | |
| 342 | 추가: .status() | |
| 343 | 추가: .unwrap() | |
| 344 | 추가: .success() | |
| 345 | 추가: ); | |
| 346 | 추가: library | |
| 347 | 추가: } | |
| 348 | 추가: #[cfg(target_os = "linux")] | |
| 349 | 추가: #[test] | |
| 350 | 추가: fn recovery_disk_errors_preserve_publication_truth_and_source() { | |
| 351 | 추가: for mode in [ | |
| 352 | 추가: "temp-full", | |
| 353 | 추가: "codec-full", | |
| 354 | 추가: "create-full", | |
| 355 | 추가: "full", | |
| 356 | 추가: "write-io", | |
| 357 | 추가: "sync-full", | |
| 358 | 추가: "dir-sync-full", | |
| 359 | 추가: ] { | |
| 360 | 추가: let s = Scratch::new(); | |
| 361 | 추가: let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip"); | |
| 362 | 추가: fs::write(s.0.join("damaged.zip"), original).unwrap(); | |
| 363 | 추가: let mut command = s.worker(); | |
| 364 | 추가: command | |
| 365 | 추가: .env("LD_PRELOAD", shim(&s)) | |
| 366 | 추가: .env("ZIPELO_TEST_FAULT", mode) | |
| 367 | 추가: .env("ZIPELO_TEST_MARKER", s.0.join("marker")) | |
| 368 | 추가: .stdin(Stdio::piped()) | |
| 369 | 추가: .stdout(Stdio::piped()) | |
| 370 | 추가: .stderr(Stdio::piped()); | |
| 371 | 추가: let mut child = command.spawn().unwrap(); | |
| 372 | 추가: Writer::new(child.stdin.take().unwrap(), 17) | |
| 373 | 추가: .send(&Message::Start(start(&s))) | |
| 374 | 추가: .unwrap(); | |
| 375 | 추가: let output = child.wait_with_output().unwrap(); | |
| 376 | 추가: assert!(output.status.success()); | |
| 377 | 추가: assert!(output.stderr.is_empty()); | |
| 378 | 추가: let mut reader = Reader::new(output.stdout.as_slice()); | |
| 379 | 추가: let mut events = Vec::new(); | |
| 380 | 추가: while let Some((_, _, event)) = reader.read().unwrap() { | |
| 381 | 추가: events.push(event); | |
| 382 | 추가: } | |
| 383 | 추가: let t = terminal(&events); | |
| 384 | 추가: assert_eq!(t.outcome, Outcome::Failed, "{mode}: {events:?}"); | |
| 385 | 추가: assert_eq!( | |
| 386 | 추가: t.error, | |
| 387 | 추가: if mode == "write-io" { | |
| 388 | 추가: ErrorCode::Io | |
| 389 | 추가: } else { | |
| 390 | 추가: ErrorCode::DiskFull | |
| 391 | 추가: }, | |
| 392 | 추가: "{mode}: {events:?}" | |
| 393 | 추가: ); | |
| 394 | 추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), original); | |
| 395 | 추가: assert_eq!(s.0.join("recovered.zip").exists(), mode == "dir-sync-full"); | |
| 396 | 추가: assert_eq!(t.created_count, u64::from(mode == "dir-sync-full")); | |
| 397 | 추가: assert!(!fs::read_dir(&s.0).unwrap().any(|e| { | |
| 398 | 추가: e.unwrap() | |
| 399 | 추가: .file_name() | |
| 400 | 추가: .to_string_lossy() | |
| 401 | 추가: .starts_with(".zipelo-") | |
| 402 | 추가: })); | |
| 403 | 추가: } | |
| 404 | 추가: } | |
| 405 | 추가: #[cfg(target_os = "linux")] | |
| 406 | 추가: #[test] | |
| 407 | 추가: fn recovery_publication_rechecks_source_destination_and_cancel() { | |
| 408 | 추가: use std::time::{Duration, Instant}; | |
| 409 | 추가: struct Running(std::process::Child); | |
| 410 | 추가: impl Drop for Running { | |
| 411 | 추가: fn drop(&mut self) { | |
| 412 | 추가: let _ = self.0.kill(); | |
| 413 | 추가: let _ = self.0.wait(); | |
| 414 | 추가: } | |
| 415 | 추가: } | |
| 416 | 추가: for mode in 0..3 { | |
| 417 | 추가: let s = Scratch::new(); | |
| 418 | 추가: let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip"); | |
| 419 | 추가: fs::write(s.0.join("damaged.zip"), original).unwrap(); | |
| 420 | 추가: let marker = s.0.join("marker"); | |
| 421 | 추가: let release = s.0.join("release"); | |
| 422 | 추가: let mut cmd = s.worker(); | |
| 423 | 추가: cmd.env("LD_PRELOAD", shim(&s)) | |
| 424 | 추가: .env("ZIPELO_TEST_FAULT", "pause") | |
| 425 | 추가: .env("ZIPELO_TEST_MARKER", &marker) | |
| 426 | 추가: .env("ZIPELO_TEST_RELEASE", &release) | |
| 427 | 추가: .stdin(Stdio::piped()) | |
| 428 | 추가: .stdout(Stdio::piped()) | |
| 429 | 추가: .stderr(Stdio::piped()); | |
| 430 | 추가: let mut child = Running(cmd.spawn().unwrap()); | |
| 431 | 추가: let mut writer = Writer::new(child.0.stdin.take().unwrap(), 17); | |
| 432 | 추가: writer.send(&Message::Start(start(&s))).unwrap(); | |
| 433 | 추가: let until = Instant::now() + Duration::from_secs(10); | |
| 434 | 추가: while !marker.exists() { | |
| 435 | 추가: assert!(Instant::now() < until); | |
| 436 | 추가: std::thread::sleep(Duration::from_millis(5)); | |
| 437 | 추가: } | |
| 438 | 추가: let mut reader = Reader::new(child.0.stdout.take().unwrap()); | |
| 439 | 추가: let mut events = Vec::new(); | |
| 440 | 추가: let mut expected = original.to_vec(); | |
| 441 | 추가: if mode == 0 { | |
| 442 | 추가: expected[40] ^= 1; | |
| 443 | 추가: fs::write(s.0.join("damaged.zip"), &expected).unwrap(); | |
| 444 | 추가: } | |
| 445 | 추가: if mode == 1 { | |
| 446 | 추가: fs::write(s.0.join("recovered.zip"), b"user save").unwrap(); | |
| 447 | 추가: } | |
| 448 | 추가: if mode == 2 { | |
| 449 | 추가: writer.send(&Message::Cancel).unwrap(); | |
| 450 | 추가: loop { | |
| 451 | 추가: let event = reader.read().unwrap().unwrap().2; | |
| 452 | 추가: let ack = matches!( | |
| 453 | 추가: event, | |
| 454 | 추가: Message::CancelAck { | |
| 455 | 추가: status: CancelStatus::Requested, | |
| 456 | 추가: .. | |
| 457 | 추가: } | |
| 458 | 추가: ); | |
| 459 | 추가: events.push(event); | |
| 460 | 추가: if ack { | |
| 461 | 추가: break; | |
| 462 | 추가: } | |
| 463 | 추가: } | |
| 464 | 추가: } | |
| 465 | 추가: fs::write(&release, b"go").unwrap(); | |
| 466 | 추가: while let Some((_, _, event)) = reader.read().unwrap() { | |
| 467 | 추가: events.push(event); | |
| 468 | 추가: } | |
| 469 | 추가: drop(writer); | |
| 470 | 추가: assert!(child.0.wait().unwrap().success()); | |
| 471 | 추가: let t = terminal(&events); | |
| 472 | 추가: assert_eq!( | |
| 473 | 추가: t.error, | |
| 474 | 추가: match mode { | |
| 475 | 추가: 0 => ErrorCode::SourceChanged, | |
| 476 | 추가: 1 => ErrorCode::Conflict, | |
| 477 | 추가: _ => ErrorCode::None, | |
| 478 | 추가: } | |
| 479 | 추가: ); | |
| 480 | 추가: assert_eq!( | |
| 481 | 추가: t.outcome, | |
| 482 | 추가: if mode == 2 { | |
| 483 | 추가: Outcome::Cancelled | |
| 484 | 추가: } else { | |
| 485 | 추가: Outcome::Failed | |
| 486 | 추가: } | |
| 487 | 추가: ); | |
| 488 | 추가: assert_eq!(t.created_count, 0); | |
| 489 | 추가: assert_eq!(t.publication, Publication::None); | |
| 490 | 추가: assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), expected); | |
| 491 | 추가: if mode == 1 { | |
| 492 | 추가: assert_eq!(fs::read(s.0.join("recovered.zip")).unwrap(), b"user save"); | |
| 493 | 추가: } else { | |
| 494 | 추가: assert!(!s.0.join("recovered.zip").exists()); | |
| 495 | 추가: } | |
| 496 | 추가: } | |
| 497 | 추가: } |
| @@ -0,0 +1,211 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use std::sync::atomic::{AtomicU64, Ordering}; | |
| 3 | 추가: struct Scratch(PathBuf); | |
| 4 | 추가: static NEXT: AtomicU64 = AtomicU64::new(0); | |
| 5 | 추가: impl Scratch { | |
| 6 | 추가: fn new(bytes: &[u8]) -> Self { | |
| 7 | 추가: let dir = std::env::temp_dir().canonicalize().unwrap().join(format!( | |
| 8 | 추가: "rec-{}-{}", | |
| 9 | 추가: std::process::id(), | |
| 10 | 추가: NEXT.fetch_add(1, Ordering::Relaxed) | |
| 11 | 추가: )); | |
| 12 | 추가: std::fs::create_dir(&dir).unwrap(); | |
| 13 | 추가: std::fs::write(dir.join("source.zip"), bytes).unwrap(); | |
| 14 | 추가: Self(dir) | |
| 15 | 추가: } | |
| 16 | 추가: fn path(&self) -> PathBuf { | |
| 17 | 추가: self.0.join("source.zip") | |
| 18 | 추가: } | |
| 19 | 추가: } | |
| 20 | 추가: impl Drop for Scratch { | |
| 21 | 추가: fn drop(&mut self) { | |
| 22 | 추가: std::fs::remove_dir_all(&self.0).unwrap(); | |
| 23 | 추가: } | |
| 24 | 추가: } | |
| 25 | 추가: #[cfg(unix)] | |
| 26 | 추가: #[test] | |
| 27 | 추가: fn publication_recheck_rejects_content_metadata_and_object_changes() { | |
| 28 | 추가: let bytes = include_bytes!("../zip-recovery-fixtures/missing-directory.zip"); | |
| 29 | 추가: for mode in 0..3 { | |
| 30 | 추가: let s = Scratch::new(bytes); | |
| 31 | 추가: let mut recovery = Recovery::open(&s.path(), Limits::default(), &mut || Ok(())).unwrap(); | |
| 32 | 추가: match mode { | |
| 33 | 추가: 0 => { | |
| 34 | 추가: let mut changed = bytes.to_vec(); | |
| 35 | 추가: changed[40] ^= 1; | |
| 36 | 추가: std::fs::write(s.path(), changed).unwrap(); | |
| 37 | 추가: } | |
| 38 | 추가: 1 => { | |
| 39 | 추가: std::fs::OpenOptions::new() | |
| 40 | 추가: .write(true) | |
| 41 | 추가: .open(s.path()) | |
| 42 | 추가: .unwrap() | |
| 43 | 추가: .set_len(10) | |
| 44 | 추가: .unwrap(); | |
| 45 | 추가: } | |
| 46 | 추가: _ => { | |
| 47 | 추가: std::fs::rename(s.path(), s.0.join("old")).unwrap(); | |
| 48 | 추가: std::fs::write(s.path(), bytes).unwrap(); | |
| 49 | 추가: } | |
| 50 | 추가: } | |
| 51 | 추가: assert_eq!( | |
| 52 | 추가: recovery.verify_source(&mut || Ok(())), | |
| 53 | 추가: Err(ErrorCode::SourceChanged) | |
| 54 | 추가: ); | |
| 55 | 추가: } | |
| 56 | 추가: } | |
| 57 | 추가: #[test] | |
| 58 | 추가: fn unchanged_source_recheck_succeeds_without_rewriting_original() { | |
| 59 | 추가: let bytes = include_bytes!("../zip-recovery-fixtures/broken-local-header.zip"); | |
| 60 | 추가: let s = Scratch::new(bytes); | |
| 61 | 추가: let mut recovery = Recovery::open(&s.path(), Limits::default(), &mut || Ok(())).unwrap(); | |
| 62 | 추가: recovery.verify_source(&mut || Ok(())).unwrap(); | |
| 63 | 추가: assert_eq!(std::fs::read(s.path()).unwrap(), bytes); | |
| 64 | 추가: } | |
| 65 | 추가: #[test] | |
| 66 | 추가: fn four_gibibyte_input_cap_is_checked_before_capture() { | |
| 67 | 추가: let s = Scratch::new(&[]); | |
| 68 | 추가: std::fs::OpenOptions::new() | |
| 69 | 추가: .write(true) | |
| 70 | 추가: .open(s.path()) | |
| 71 | 추가: .unwrap() | |
| 72 | 추가: .set_len(INPUT_CAP + 1) | |
| 73 | 추가: .unwrap(); | |
| 74 | 추가: assert!(matches!( | |
| 75 | 추가: Recovery::open(&s.path(), Limits::default(), &mut || Ok(())), | |
| 76 | 추가: Err(ErrorCode::UnsupportedFeature) | |
| 77 | 추가: )); | |
| 78 | 추가: } | |
| 79 | 추가: #[test] | |
| 80 | 추가: fn failed_crc_still_consumes_decoded_byte_budget() { | |
| 81 | 추가: struct Usage(u64); | |
| 82 | 추가: impl Monitor for Usage { | |
| 83 | 추가: fn check(&mut self) -> Result<()> { | |
| 84 | 추가: Ok(()) | |
| 85 | 추가: } | |
| 86 | 추가: fn observe(&mut self, usage: ResourceUsage, _storage: Option<&File>) -> Result<()> { | |
| 87 | 추가: self.0 = self.0.max(usage.actual_bytes.unwrap_or(0)); | |
| 88 | 추가: Ok(()) | |
| 89 | 추가: } | |
| 90 | 추가: } | |
| 91 | 추가: let s = Scratch::new(include_bytes!("../zip-recovery-fixtures/body-corrupt.zip")); | |
| 92 | 추가: let mut usage = Usage(0); | |
| 93 | 추가: let recovery = Recovery::open(&s.path(), Limits::default(), &mut usage).unwrap(); | |
| 94 | 추가: assert_eq!(usage.0, 1521); | |
| 95 | 추가: assert_eq!(recovery.data.metadata().unwrap().len(), 497); | |
| 96 | 추가: assert_eq!(recovery.summary.lost_entries, 1); | |
| 97 | 추가: } | |
| 98 | 추가: #[test] | |
| 99 | 추가: fn deflate_truncation_and_trailing_bytes_are_not_verified() { | |
| 100 | 추가: for length in [36, 38] { | |
| 101 | 추가: let mut input = spool::temporary().unwrap(); | |
| 102 | 추가: input | |
| 103 | 추가: .write_all(include_bytes!("../zip-recovery-fixtures/control.zip")) | |
| 104 | 추가: .unwrap(); | |
| 105 | 추가: input.seek(SeekFrom::Start(112)).unwrap(); | |
| 106 | 추가: let mut output = spool::temporary().unwrap(); | |
| 107 | 추가: let mut used = 0; | |
| 108 | 추가: assert!(matches!( | |
| 109 | 추가: decode( | |
| 110 | 추가: &mut input, | |
| 111 | 추가: length, | |
| 112 | 추가: 8, | |
| 113 | 추가: 432, | |
| 114 | 추가: &mut output, | |
| 115 | 추가: &mut used, | |
| 116 | 추가: Limits::default(), | |
| 117 | 추가: &mut || Ok(()) | |
| 118 | 추가: ), | |
| 119 | 추가: Err(ErrorCode::Integrity) | |
| 120 | 추가: )); | |
| 121 | 추가: } | |
| 122 | 추가: } | |
| 123 | 추가: #[test] | |
| 124 | 추가: fn cooperative_cancel_before_decode_preserves_source() { | |
| 125 | 추가: let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip"); | |
| 126 | 추가: let s = Scratch::new(original); | |
| 127 | 추가: let mut count = 0; | |
| 128 | 추가: assert!(matches!( | |
| 129 | 추가: Recovery::open(&s.path(), Limits::default(), &mut || { | |
| 130 | 추가: count += 1; | |
| 131 | 추가: if count > 15 { | |
| 132 | 추가: Err(ErrorCode::None) | |
| 133 | 추가: } else { | |
| 134 | 추가: Ok(()) | |
| 135 | 추가: } | |
| 136 | 추가: }), | |
| 137 | 추가: Err(ErrorCode::None) | |
| 138 | 추가: )); | |
| 139 | 추가: assert_eq!(std::fs::read(s.path()).unwrap(), original); | |
| 140 | 추가: } | |
| 141 | 추가: #[test] | |
| 142 | 추가: fn signed_and_unsigned_descriptors_require_exact_central_evidence() { | |
| 143 | 추가: let source = include_bytes!("../zip-recovery-fixtures/control.zip"); | |
| 144 | 추가: for signed in [false, true] { | |
| 145 | 추가: let mut bytes = source[..65].to_vec(); | |
| 146 | 추가: bytes[..4].copy_from_slice(b"BAD!"); | |
| 147 | 추가: bytes[6..8].copy_from_slice(&8u16.to_le_bytes()); | |
| 148 | 추가: bytes[14..26].fill(0); | |
| 149 | 추가: if signed { | |
| 150 | 추가: bytes.extend(b"PK\x07\x08"); | |
| 151 | 추가: } | |
| 152 | 추가: bytes.extend(&source[14..26]); | |
| 153 | 추가: let cd = bytes.len() as u32; | |
| 154 | 추가: let mut central = source[1372..1427].to_vec(); | |
| 155 | 추가: central[8..10].copy_from_slice(&8u16.to_le_bytes()); | |
| 156 | 추가: bytes.extend(¢ral); | |
| 157 | 추가: let mut end = source[source.len() - 22..].to_vec(); | |
| 158 | 추가: end[8..10].copy_from_slice(&1u16.to_le_bytes()); | |
| 159 | 추가: end[10..12].copy_from_slice(&1u16.to_le_bytes()); | |
| 160 | 추가: end[12..16].copy_from_slice(&55u32.to_le_bytes()); | |
| 161 | 추가: end[16..20].copy_from_slice(&cd.to_le_bytes()); | |
| 162 | 추가: bytes.extend(&end); | |
| 163 | 추가: let s = Scratch::new(&bytes); | |
| 164 | 추가: let recovery = Recovery::open(&s.path(), Limits::default(), &mut || Ok(())).unwrap(); | |
| 165 | 추가: assert_eq!(recovery.summary.verified_entries, 1); | |
| 166 | 추가: assert!(recovery.summary.complete()); | |
| 167 | 추가: assert_eq!(recovery.findings[0].reason, RecoveryReason::HeaderRebuilt); | |
| 168 | 추가: } | |
| 169 | 추가: } | |
| 170 | 추가: | |
| 171 | 추가: #[test] | |
| 172 | 추가: fn decoder_error_bytes_are_charged_before_reporting_loss() { | |
| 173 | 추가: let original = &include_bytes!("../zip-recovery-fixtures/control.zip")[112..149]; | |
| 174 | 추가: let mut probe = None; | |
| 175 | 추가: 'search: for at in 0..original.len() { | |
| 176 | 추가: for bit in 0..8 { | |
| 177 | 추가: let mut damaged = original.to_vec(); | |
| 178 | 추가: damaged[at] ^= 1 << bit; | |
| 179 | 추가: let mut stream = Inflate::new(false, 15); | |
| 180 | 추가: let mut plain = [0; 65536]; | |
| 181 | 추가: if stream | |
| 182 | 추가: .decompress(&damaged, &mut plain, InflateFlush::NoFlush) | |
| 183 | 추가: .is_err() | |
| 184 | 추가: && stream.total_out() > 0 | |
| 185 | 추가: { | |
| 186 | 추가: probe = Some((damaged, stream.total_out())); | |
| 187 | 추가: break 'search; | |
| 188 | 추가: } | |
| 189 | 추가: } | |
| 190 | 추가: } | |
| 191 | 추가: let (bytes, count) = probe.expect("오류 전에 디코딩된 표본이 필요함"); | |
| 192 | 추가: let mut input = spool::temporary().unwrap(); | |
| 193 | 추가: input.write_all(&bytes).unwrap(); | |
| 194 | 추가: input.rewind().unwrap(); | |
| 195 | 추가: let mut output = spool::temporary().unwrap(); | |
| 196 | 추가: let mut used = 0; | |
| 197 | 추가: assert!(matches!( | |
| 198 | 추가: decode( | |
| 199 | 추가: &mut input, | |
| 200 | 추가: bytes.len() as u64, | |
| 201 | 추가: 8, | |
| 202 | 추가: 65536, | |
| 203 | 추가: &mut output, | |
| 204 | 추가: &mut used, | |
| 205 | 추가: Limits::default(), | |
| 206 | 추가: &mut || Ok(()) | |
| 207 | 추가: ), | |
| 208 | 추가: Err(ErrorCode::Integrity) | |
| 209 | 추가: )); | |
| 210 | 추가: assert_eq!(used, count); | |
| 211 | 추가: } |
| @@ -263,10 +263,10 @@ fn action_kind_events_keep_existing_tags_and_append_creation_tag_four() { | ||
| 263 | 263 | matches!(decode(&bytes), Message::ResourceRequired { action: actual, scope: value, .. } if actual == action && value == scope) |
| 264 | 264 | ); |
| 265 | 265 | let mut body = bytes[32..].to_vec(); |
| 266 | 삭제: body[8] = 5; | |
| 266 | 추가: body[8] = 6; | |
| 267 | 267 | reject_decode(&raw(110, &body)); |
| 268 | 268 | } |
| 269 | 삭제: reject_decode(&raw(100, &[5, 0])); | |
| 269 | 추가: reject_decode(&raw(100, &[6, 0])); | |
| 270 | 270 | } |
| 271 | 271 | |
| 272 | 272 | #[test] |
| @@ -375,7 +375,7 @@ fn volume_problem_keeps_native_path_limits_and_strict_body_lengths() { | ||
| 375 | 375 | } |
| 376 | 376 | |
| 377 | 377 | #[test] |
| 378 | 삭제: fn missing_volume_terminal_uses_tag_14_and_rejects_unknown_tag_15() { | |
| 378 | 추가: fn missing_volume_terminal_uses_tag_14_and_rejects_unknown_tag_17() { | |
| 379 | 379 | let message = Message::Terminal(Terminal { |
| 380 | 380 | outcome: Outcome::Failed, |
| 381 | 381 | error: ErrorCode::MissingVolume, |
| @@ -390,6 +390,6 @@ fn missing_volume_terminal_uses_tag_14_and_rejects_unknown_tag_15() { | ||
| 390 | 390 | assert_eq!(&bytes[6..8], &106u16.to_le_bytes()); |
| 391 | 391 | assert_eq!(bytes[33], 14); |
| 392 | 392 | assert!(matches!(decoded(&bytes), Message::Terminal(t) if t.error == ErrorCode::MissingVolume)); |
| 393 | 삭제: bytes[33] = 15; | |
| 393 | 추가: bytes[33] = 17; | |
| 394 | 394 | reject_decode(&bytes); |
| 395 | 395 | } |