대용량 작업 승인과 자원 감시를 추가한다
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
b719523146fab432a6a55881e1e63357f7d830fa- 부모
- a5f11f7
변경된 파일 22개
+1,455-123| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | - ZIP32/ZIP64 Store/Deflate 목록과 해제, ZIP32/ZIP64 생성, 기본 TAR/USTAR, GZ, TAR.GZ, TAR.BZ2, TAR.XZ, 비암호화 7z 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. 다중 볼륨, UTF-8로 해석할 수 없는 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다. |
| 6 | 6 | - ZIP 이름: UTF-8 플래그(비트 11)가 있으면 이름이 UTF-8이어야 하며 아니면 Integrity입니다. 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075, 버전 1)를 우선 쓰고, 다음으로 UTF-8로 유효한 이름 바이트를 그대로 씁니다(Linux/macOS 도구의 기본 동작). CRC가 다르거나 버전이 다른 확장 필드는 무시합니다. 그 밖의 CP437/CP949 등 레거시 이름은 코드 페이지를 추측하지 않고 UnsupportedFeature로 거부합니다. 어느 경로로 얻은 이름이든 같은 경로 안전성 검사와 충돌 검사를 거칩니다. |
| 7 | 삭제: - ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다. | |
| 7 | 추가: - ZIP/TAR/GZ/TAR.GZ/7z 목록과 해제는 입력 기본 한도 u64::MAX, 해제 총량 16 GiB, 항목 10,000개입니다. 기존 Start와 StartInteractive의 limits는 이 값을 낮출 수 있습니다. 별도 StartGuarded의 승인 흐름은 아래 절을 따릅니다. 64 KiB 버퍼와 임시 파일로 입력과 검증 완료 payload를 처리해 모든 출력의 CRC, 크기와 경로를 게시 전에 검사합니다. checkpoint마다 취소, 부모 프로세스 생존과 300초 한도를 확인합니다. ZIP 생성은 원본을 하나씩 스냅샷으로 읽어 스트리밍으로 압축하며 원본 크기 합계에 16 GiB 한도를 적용합니다. ZIP64 크기와 오프셋은 필요한 항목에만 기록합니다. slice 기반 archive parser는 입력 64 MiB/출력 128 MiB, slice ZIP builder는 원본 및 결과 128 MiB 한도를 유지합니다. | |
| 8 | 8 | - 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다. |
| 9 | 9 | - GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다. |
| 10 | 10 | - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. |
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다. |
| 18 | 18 | |
| 19 | 삭제: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다. | |
| 19 | 추가: - 기존 Start와 StartInteractive는 압축비를 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다. | |
| 20 | 20 | - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 기존 Start는 ZIP/7z 해제 전에 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. StartInteractive는 선택 전에는 무결성 검증에 필요한 임시 해제 공간만 확인하고, 선택 뒤 건너뛰지 않은 파일의 실제 저장 이름으로 게시 직전 공간을 확인합니다. 따라서 목적지 공간이 부족해도 충돌 파일을 전부 건너뛰거나 질문 중 취소할 수 있습니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 공간 부족은 DiskFull(13), 조회 실패와 권한 등 다른 I/O 오류는 Io(8)로 반환합니다. 실제 생성/쓰기/동기화의 공간 부족에도 같은 구분을 적용합니다. Windows의 공간 부족 코드 39와 112는 [공식 오류 목록](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)을 따릅니다. |
| 21 | 21 | - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다. |
| 22 | 22 | - 입력과 검증된 해제 내용은 임시 파일에 저장합니다. Linux는 [O_TMPFILE](https://man7.org/linux/man-pages/man2/open.2.html), 이를 지원하지 않는 Linux 파일시스템에서는 0600 난수 파일을 배타적으로 만든 즉시 unlink하고 링크 수 0을 확인합니다. Windows는 배타적 [DELETE_ON_CLOSE 파일](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)을 사용합니다. 마지막 핸들이 닫히면 제거되며 임시 파일명에 아카이브 내부 이름을 사용하지 않습니다. 디스크에는 입력 사본, 해제 내용과 현재 출력 임시 파일이 동시에 필요할 수 있습니다. 임시 폴더가 tmpfs이면 해당 파일 내용은 프로세스 RSS 외의 시스템 메모리를 사용합니다. |
| @@ -76,7 +76,7 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 76 | 76 | |
| 77 | 77 | ## 공유 codec |
| 78 | 78 | |
| 79 | 삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`에서 구현 상태를 구분합니다. | |
| 79 | 추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`와 `guarded_resources.status`에서 구현 및 화면 연동 상태를 구분합니다. | |
| 80 | 80 | |
| 81 | 81 | 헤더는 ZAW1, version u16=1, kind u16, body length u32, reserved u32=0, job ID u64, sequence u64의 32바이트입니다. 양방향 sequence는 각각 0부터 시작합니다. body는 최대 1 MiB이며 한 방향당 최대 1,000,000프레임입니다. 잘린 프레임, 알 수 없는 tag, 잔여 payload, 잘못된 ID/sequence를 거부합니다. |
| 82 | 82 | |
| @@ -101,6 +101,22 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 101 | 101 | |
| 102 | 102 | 교체 동작의 근거는 [Linux rename](https://man7.org/linux/man-pages/man2/rename.2.html)과 [Microsoft MoveFileExW](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw)입니다. |
| 103 | 103 | |
| 104 | 추가: ## 큰 작업의 명시적 승인 계약 | |
| 105 | 추가: | |
| 106 | 추가: `StartGuarded`는 기존 요청과 분리된 선택적 확장입니다. 작업자 구현만 포함하며 앱에서 새 요청과 승인 화면을 사용하는 연동, `--ui-scenario` 및 가이드 갱신은 frontend 범위입니다. 기존 앱의 요청에는 새 질문을 보내지 않습니다. 구버전 작업자가 새 요청을 거부하면 자동 재시도하지 않습니다. | |
| 107 | 추가: | |
| 108 | 추가: - kind 6의 본문은 `GuardedStart { start: Start, ceiling: Limits, interactive: bool }` 순서입니다. start.limits는 기존 16 GiB 및 10,000개 이하이고 ceiling은 이를 늘리되 64 GiB 및 200,000개 이하입니다. 입력 한도는 동일해야 합니다. interactive는 Extract에서만 허용하며 기존 암호와 충돌 처리를 함께 사용합니다. | |
| 109 | 추가: - 작업자는 Accepted 뒤, 입력 캡처와 소스 탐색 전에 요청된 상한 확대 범위를 확인합니다. 입력 사본 작성부터 300초를 넘을 수 있으므로 승인을 먼저 받습니다. 이때 예상량과 실제량은 아직 미확인(None)이고 임시 저장 볼륨의 여유 공간을 알립니다. 허용 전에는 확대 한도가 적용되지 않으며 거부하면 Cancelled로 끝납니다. 작은 기존 작업은 Start를 계속 사용할 수 있습니다. | |
| 110 | 추가: - kind 110의 `ResourceRequired`는 challenge_id, action, scope, usage, soft_limits, ceiling 순서입니다. `ResourceScope`는 output, entries, ratio의 bool 세 개입니다. `ResourceUsage`는 estimated_bytes, actual_bytes, estimated_entries, actual_entries, compressed_bytes, ratio_output_bytes, available_bytes 순서이며 모두 Option입니다. 바이트는 u64, 항목 수는 u32입니다. 미확인은 0으로 바꾸지 않습니다. 여유 공간은 관찰 중인 저장 볼륨의 값이며 공간 예약이나 모든 볼륨의 합계가 아닙니다. | |
| 111 | 추가: - kind 7의 `ResourceReply`는 challenge_id u64, scope, allow bool입니다. 프레임의 작업 ID, 현재 질문 ID와 요청한 scope가 모두 일치하는 응답 한 개만 허용합니다. 중복, 오래된 응답과 다른 종류의 질문 응답은 Protocol입니다. 승인은 해당 작업의 해당 범위에만 적용하며 재사용하지 않습니다. | |
| 112 | 추가: - 해제량이 256 MiB 이상이고 압축률이 1,000배를 초과하면 ratio 범위를 별도로 묻습니다. ZIP은 항목별, 7z는 solid 폴더와 전체, 압축 TAR와 GZip은 스트림 전체의 크기로 검사합니다. 예상량과 실제량을 구분하고 u128 곱셈으로 비교합니다. 승인 중에는 추가 해제와 쓰기를 멈추며 취소는 별도 제어 읽기에서 처리합니다. | |
| 113 | 추가: - 승인 후에도 64 GiB와 200,000개 정책 상한, 메타데이터와 사전 예산, 경로 및 무결성, 임시 저장소와 목적지 공간 검사를 적용합니다. ZIP 생성은 원본 논리 크기 합계를 제한하며 ZIP 구조와 암호화로 늘어나는 저장 공간을 별도로 계산합니다. 이미 게시한 출력은 실패나 취소 시 유지하고 게시 및 정리 상태를 보고합니다. | |
| 114 | 추가: - 승인된 작업은 전체 300초 대신 진행이 60초 동안 없을 때 Limit로 중단합니다. 실제 읽기, 해독, 쓰기와 메타데이터 수집만 진행으로 계산하며 반복 check 호출은 기한을 늘리지 않습니다. 암호, 충돌과 자원 질문은 한 번에 하나이며 각 응답 대기는 300초입니다. 유효한 응답 뒤에는 사용자 대기 시간을 제외하고 정체 감시를 재개합니다. 기존 요청의 전체 300초 제한은 유지합니다. OS의 블로킹 I/O를 강제로 중단하는 보장은 아닙니다. | |
| 115 | 추가: | |
| 116 | 추가: 현재 남은 제약: 기존 8 MiB 메타데이터 예산과 32,768개 노드 상한을 유지하므로 실제 항목 200,000개까지 처리할 수 있다는 뜻은 아닙니다. 소스 경로도 이 예산을 사용합니다. 메타데이터 저장 방식과 예산 결정, 정확한 codec 인계 검토 및 화면 연동 전까지 초안을 유지합니다. | |
| 117 | 추가: | |
| 118 | 추가: 시험은 실제 64 GiB를 쓰지 않고 수치 경계와 축소한 limits/ceiling을 사용합니다. `resource_budget.rs`는 16 GiB 아래/경계/초과, 64 GiB 초과, 10,000개 및 200,000개 경계, 압축률 경계와 가상 시계의 60초 정체를 검사합니다. `guarded.rs`는 실제 작업자 승인/거부, 오래된 응답, 암호/충돌 순서, 승인 뒤 공간 실패, 여러 형식과 작은 고압축 입력의 경고 및 취소를 검사합니다. | |
| 119 | 추가: | |
| 104 | 120 | ## 검증과 의존성 |
| 105 | 121 | |
| 106 | 122 | 시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다. |
| @@ -30,7 +30,9 @@ | ||
| 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.", |
| 33 | 삭제: "ConflictReply": "Kind 5: challenge_id:u64, choice:ConflictChoice(u8), apply_to_remaining:bool. Match the one outstanding conflict challenge exactly once. Applying to remaining affects only later regular-file conflicts in this job." | |
| 33 | 추가: "ConflictReply": "Kind 5: challenge_id:u64, choice:ConflictChoice(u8), apply_to_remaining:bool. Match the one outstanding conflict challenge exactly once. Applying to remaining affects only later regular-file conflicts in this job.", | |
| 34 | 추가: "StartGuarded": "Kind 6: GuardedStart{start:Start,ceiling:Limits,interactive:bool}. Start limits keep legacy maxima. ceiling.input must equal start.limits.input; ceiling.output and entries may increase up to 64 GiB and 200000. interactive is valid only for Extract. No resource expansion takes effect before a matching ResourceReply. New workers never emit guarded challenges for Start or StartInteractive; older workers reject kind 6 without fallback.", | |
| 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." | |
| 34 | 36 | }, |
| 35 | 37 | "events": { |
| 36 | 38 | "Accepted": "Action and capabilities; encryption capability is true for implemented ZipCrypto extraction and WinZip AES-256 extraction/creation.", |
| @@ -59,7 +61,8 @@ | ||
| 59 | 61 | "ordering": "Each well-formed Cancel consumed before Terminal is acknowledged once before Terminal. Terminal is the last worker protocol frame. A Cancel racing with Terminal/exit may remain unread and have no acknowledgement; app uses Terminal plus EOF and wait, never synthesizes a worker acknowledgement or successful cancellation." |
| 60 | 62 | }, |
| 61 | 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.", |
| 62 | 삭제: "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." | |
| 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." | |
| 63 | 66 | }, |
| 64 | 67 | "lifecycle": [ |
| 65 | 68 | "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.", |
| @@ -222,5 +225,18 @@ | ||
| 222 | 225 | "implementation_boundary": "Worker supports StartInteractive extraction. Frontend activation and native Windows/Wayland integration require separate verification. Existing Start remains exclusive and aborts on file conflicts.", |
| 223 | 226 | "target_revalidation": "Before replacement compare parent and file native identities, size and modification time with the question-time observation. Detected changes fail Conflict. This is not atomic compare-and-replace against concurrent writes by the same account.", |
| 224 | 227 | "disk_space": "Required input capture and complete integrity staging checks remain before conflict questions. Defer destination space checks until the current choice is resolved. Skip has no destination byte charge; overwrite, rename and non-conflicting files are checked immediately before their publication. Preserve legacy Start aggregate preflight, limits, per-write checks and partial-output reporting." |
| 228 | 추가: }, | |
| 229 | 추가: "guarded_resources": { | |
| 230 | 추가: "status": "worker-implemented; frontend activation and exact wire handoff review pending", | |
| 231 | 추가: "agreement": "Frontend flow agreement 6fe5a494-7d5a-4bda-a7d3-831fb43e9238 and manager policy b3a743d2-10de-495c-8fdb-ecf2a5f3b453. Frame version 1, revision 3 messages and enum tags remain unchanged; this is an explicit opt-in extension.", | |
| 232 | 추가: "admission": "After Accepted, request the output and/or entries scopes that ceiling increases above Start limits before capturing input or planning sources. Usage estimates and actuals are unknown at this point; report current staging-volume free space. The caller must show the requested ceilings and unknown values, not invent estimates. An earlier confirmation is needed because input capture itself can exceed 300 seconds. Each granted scope is confined to this job.", | |
| 233 | 추가: "ratio": "Request ratio scope separately when expanded bytes are at least 256 MiB and strictly exceed compressed bytes times 1000. Check ZIP members, 7z solid folders and totals, and complete compressed TAR/GZip streams. Use u128 arithmetic; unknown compressed length does not become zero. No ratio warning for legacy requests.", | |
| 234 | 추가: "accounting": "Monitor declared catalog sums and counts, real decoded bytes, per-stream ratios and source-plan sums. Decoders must match verified declared lengths before publication. For compressed TAR/GZip the expanded stream includes headers/padding. ZIP creation ceiling counts source logical bytes; ZIP/container/encryption overhead is separately space-checked.", | |
| 235 | 추가: "disk": "Continue staging/destination volume preflight and per-chunk space checks after approval. available_bytes is advisory free space on the current observation storage volume, not a reservation or all-volume total. Unknown storage is None. Preserve DiskFull, partial publication, durability and cleanup semantics.", | |
| 236 | 추가: "waiting": "One resource, password or conflict challenge at a time. Pause processing while waiting; control reader remains live for Cancel. Response EOF fails Protocol. Guarded challenge wait is limited to 300 seconds per question; reset the inactivity clock after a valid reply, excluding the human wait.", | |
| 237 | 추가: "time": "Legacy and unapproved jobs retain their whole-job 300-second deadline. After the first resource grant, use a 60-second inactivity deadline measured only from actual read/decode/write/metadata progress, not repeated cancellation checks or outgoing heartbeats. Cooperative checkpoints cannot forcibly interrupt a blocked OS call.", | |
| 238 | 추가: "hard_ceiling": "Output/source bytes <=64 GiB and entries<=200000, including after approval. Caller may lower both ceilings for normal operation or scaled tests. Input quota cannot be expanded. Existing path, metadata, dictionary, frame and source-identity limits remain independent.", | |
| 239 | 추가: "open_constraint": "The unchanged 8 MiB MetadataBudget and 32768 node cap currently prevent reaching 200000 entries, and source paths consume the same budget. Metadata storage/budget policy requires a manager decision before claiming support for 200000 real entries. Keep the PR draft until this and frontend activation are resolved.", | |
| 240 | 추가: "tests": "Use numeric 16/64 GiB and 10000/200000 policy boundaries, scaled worker limits, a compressed 257 MiB zero stream, and a virtual clock for the 60-second stall. Do not write 64 GiB in tests." | |
| 225 | 241 | } |
| 226 | 242 | } |
| @@ -158,13 +158,13 @@ fn inflate( | ||
| 158 | 158 | input: &[u8], |
| 159 | 159 | gzip: bool, |
| 160 | 160 | limit: u64, |
| 161 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 161 | 추가: check: &mut impl crate::resources::Monitor, | |
| 162 | 162 | ) -> Result<(Vec<u8>, usize)> { |
| 163 | 163 | let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); |
| 164 | 164 | let mut out = Vec::new(); |
| 165 | 165 | let mut buffer = [0; 65536]; |
| 166 | 166 | loop { |
| 167 | 삭제: check()?; | |
| 167 | 추가: check.check()?; | |
| 168 | 168 | let before_in = stream.total_in(); |
| 169 | 169 | let before_out = stream.total_out(); |
| 170 | 170 | let status = stream |
| @@ -184,7 +184,11 @@ fn inflate( | ||
| 184 | 184 | } |
| 185 | 185 | } |
| 186 | 186 | } |
| 187 | 삭제: fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 187 | 추가: fn gzip( | |
| 188 | 추가: input: &[u8], | |
| 189 | 추가: limits: Limits, | |
| 190 | 추가: check: &mut impl crate::resources::Monitor, | |
| 191 | 추가: ) -> Result<Vec<u8>> { | |
| 188 | 192 | let mut at = 0; |
| 189 | 193 | let mut result = Vec::new(); |
| 190 | 194 | while at < input.len() { |
| @@ -230,14 +234,14 @@ fn tar( | ||
| 230 | 234 | input: &[u8], |
| 231 | 235 | limits: Limits, |
| 232 | 236 | decode: bool, |
| 233 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 237 | 추가: check: &mut impl crate::resources::Monitor, | |
| 234 | 238 | ) -> Result<Vec<Member>> { |
| 235 | 239 | let mut at = 0; |
| 236 | 240 | let mut members = Vec::new(); |
| 237 | 241 | let mut total = 0u64; |
| 238 | 242 | let mut metadata = MetadataBudget::default(); |
| 239 | 243 | loop { |
| 240 | 삭제: check()?; | |
| 244 | 추가: check.check()?; | |
| 241 | 245 | let header = part(input, at, 512)?; |
| 242 | 246 | if header.iter().all(|b| *b == 0) { |
| 243 | 247 | if part(input, at + 512, 512)?.iter().any(|b| *b != 0) |
| @@ -394,7 +398,7 @@ fn zip( | ||
| 394 | 398 | limits: Limits, |
| 395 | 399 | decode: bool, |
| 396 | 400 | password: Option<&[u8]>, |
| 397 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 401 | 추가: check: &mut impl crate::resources::Monitor, | |
| 398 | 402 | ) -> Result<Vec<Member>> { |
| 399 | 403 | if input.len() < 22 { |
| 400 | 404 | return Err(ErrorCode::Integrity); |
| @@ -432,7 +436,7 @@ fn zip( | ||
| 432 | 436 | let mut total = 0u64; |
| 433 | 437 | let mut metadata = MetadataBudget::default(); |
| 434 | 438 | for id in 0..count { |
| 435 | 삭제: check()?; | |
| 439 | 추가: check.check()?; | |
| 436 | 440 | let h = part(input, at, 46)?; |
| 437 | 441 | if &h[..4] != b"PK\x01\x02" { |
| 438 | 442 | return Err(ErrorCode::Integrity); |
| @@ -604,7 +608,7 @@ pub fn parse( | ||
| 604 | 608 | input: &[u8], |
| 605 | 609 | limits: Limits, |
| 606 | 610 | decode: bool, |
| 607 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 611 | 추가: check: &mut impl crate::resources::Monitor, | |
| 608 | 612 | ) -> Result<Catalog> { |
| 609 | 613 | parse_with_password(input, limits, decode, None, check) |
| 610 | 614 | } |
| @@ -613,7 +617,7 @@ pub fn parse_with_password( | ||
| 613 | 617 | limits: Limits, |
| 614 | 618 | decode: bool, |
| 615 | 619 | password: Option<&[u8]>, |
| 616 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 620 | 추가: check: &mut impl crate::resources::Monitor, | |
| 617 | 621 | ) -> Result<Catalog> { |
| 618 | 622 | if !limits.valid() { |
| 619 | 623 | return Err(ErrorCode::Limit); |
| @@ -666,12 +670,16 @@ pub fn parse_with_password( | ||
| 666 | 670 | } |
| 667 | 671 | Err(ErrorCode::UnsupportedFormat) |
| 668 | 672 | } |
| 669 | 삭제: fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 673 | 추가: fn deflate( | |
| 674 | 추가: input: &[u8], | |
| 675 | 추가: limit: u64, | |
| 676 | 추가: check: &mut impl crate::resources::Monitor, | |
| 677 | 추가: ) -> Result<Vec<u8>> { | |
| 670 | 678 | let mut stream = Deflate::new(6, false, 15); |
| 671 | 679 | let mut output = Vec::new(); |
| 672 | 680 | let mut buffer = [0; 65536]; |
| 673 | 681 | loop { |
| 674 | 삭제: check()?; | |
| 682 | 추가: check.check()?; | |
| 675 | 683 | let a = stream.total_in(); |
| 676 | 684 | let b = stream.total_out(); |
| 677 | 685 | let status = stream |
| @@ -700,7 +708,7 @@ pub fn create_zip( | ||
| 700 | 708 | members: &[Member], |
| 701 | 709 | method: Method, |
| 702 | 710 | limits: Limits, |
| 703 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 711 | 추가: check: &mut impl crate::resources::Monitor, | |
| 704 | 712 | ) -> Result<Vec<u8>> { |
| 705 | 713 | create_zip_with_password(members, method, limits, None, check) |
| 706 | 714 | } |
| @@ -709,7 +717,7 @@ pub fn create_zip_with_password( | ||
| 709 | 717 | method: Method, |
| 710 | 718 | limits: Limits, |
| 711 | 719 | password: Option<&[u8]>, |
| 712 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 720 | 추가: check: &mut impl crate::resources::Monitor, | |
| 713 | 721 | ) -> Result<Vec<u8>> { |
| 714 | 722 | if !limits.valid() { |
| 715 | 723 | return Err(ErrorCode::Limit); |
| @@ -723,7 +731,7 @@ pub fn create_zip_with_password( | ||
| 723 | 731 | let mut cd = Vec::new(); |
| 724 | 732 | let mut total = 0u64; |
| 725 | 733 | for m in members { |
| 726 | 삭제: check()?; | |
| 734 | 추가: check.check()?; | |
| 727 | 735 | total = total |
| 728 | 736 | .checked_add(m.data.len() as u64) |
| 729 | 737 | .filter(|n| *n <= limits.output) |
| @@ -1,4 +1,7 @@ | ||
| 1 | 삭제: use crate::{protocol::ErrorCode, space, spool}; | |
| 1 | 추가: use crate::{ | |
| 2 | 추가: protocol::{ErrorCode, ResourceUsage}, | |
| 3 | 추가: space, spool, | |
| 4 | 추가: }; | |
| 2 | 5 | use std::{ |
| 3 | 6 | cell::RefCell, |
| 4 | 7 | fs::File, |
| @@ -32,13 +35,24 @@ struct CheckedInput<'a, F> { | ||
| 32 | 35 | check: &'a RefCell<&'a mut F>, |
| 33 | 36 | } |
| 34 | 37 | |
| 35 | 삭제: impl<F: FnMut() -> Result<()>> Read for CheckedInput<'_, F> { | |
| 38 | 추가: impl<F: crate::resources::Monitor> Read for CheckedInput<'_, F> { | |
| 36 | 39 | fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> { |
| 37 | 삭제: (self.check.borrow_mut())().map_err(|error| io::Error::other(InputError(error)))?; | |
| 40 | 추가: self.check | |
| 41 | 추가: .borrow_mut() | |
| 42 | 추가: .check() | |
| 43 | 추가: .map_err(|error| io::Error::other(InputError(error)))?; | |
| 38 | 44 | let count = buffer.len().min(CHUNK); |
| 39 | 삭제: self.file | |
| 45 | 추가: let n = self | |
| 46 | 추가: .file | |
| 40 | 47 | .read(&mut buffer[..count]) |
| 41 | 삭제: .map_err(|_| io::Error::other(InputError(ErrorCode::Io))) | |
| 48 | 추가: .map_err(|_| io::Error::other(InputError(ErrorCode::Io)))?; | |
| 49 | 추가: if n != 0 { | |
| 50 | 추가: self.check | |
| 51 | 추가: .borrow_mut() | |
| 52 | 추가: .activity() | |
| 53 | 추가: .map_err(|e| io::Error::other(InputError(e)))?; | |
| 54 | 추가: } | |
| 55 | 추가: Ok(n) | |
| 42 | 56 | } |
| 43 | 57 | } |
| 44 | 58 | |
| @@ -60,14 +74,26 @@ pub(crate) fn decode( | ||
| 60 | 74 | source: &mut File, |
| 61 | 75 | compression: Compression, |
| 62 | 76 | limit: u64, |
| 63 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 77 | 추가: check: &mut impl crate::resources::Monitor, | |
| 64 | 78 | ) -> Result<(File, u64)> { |
| 65 | 삭제: check()?; | |
| 79 | 추가: check.check()?; | |
| 66 | 80 | let expected = if matches!(compression, Compression::Xz) { |
| 67 | 81 | Some(xz_layout(source, limit, check)?) |
| 68 | 82 | } else { |
| 69 | 83 | None |
| 70 | 84 | }; |
| 85 | 추가: let packed_length = source.metadata().map_err(space::io_error)?.len(); | |
| 86 | 추가: if let Some(expected) = expected { | |
| 87 | 추가: check.observe( | |
| 88 | 추가: ResourceUsage { | |
| 89 | 추가: estimated_bytes: Some(expected), | |
| 90 | 추가: compressed_bytes: Some(packed_length), | |
| 91 | 추가: ratio_output_bytes: Some(expected), | |
| 92 | 추가: ..ResourceUsage::default() | |
| 93 | 추가: }, | |
| 94 | 추가: Some(source), | |
| 95 | 추가: )?; | |
| 96 | 추가: } | |
| 71 | 97 | source.rewind().map_err(space::io_error)?; |
| 72 | 98 | let mut output = spool::temporary()?; |
| 73 | 99 | let check = RefCell::new(check); |
| @@ -88,7 +114,7 @@ pub(crate) fn decode( | ||
| 88 | 114 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 89 | 115 | let mut total = 0u64; |
| 90 | 116 | loop { |
| 91 | 삭제: (check.borrow_mut())()?; | |
| 117 | 추가: check.borrow_mut().check()?; | |
| 92 | 118 | let count = reader.read(&mut buffer[..]).map_err(decode_error)?; |
| 93 | 119 | if count == 0 { |
| 94 | 120 | break; |
| @@ -97,13 +123,23 @@ pub(crate) fn decode( | ||
| 97 | 123 | .checked_add(count as u64) |
| 98 | 124 | .filter(|total| *total <= limit) |
| 99 | 125 | .ok_or(ErrorCode::Limit)?; |
| 126 | 추가: check.borrow_mut().observe( | |
| 127 | 추가: ResourceUsage { | |
| 128 | 추가: actual_bytes: Some(total), | |
| 129 | 추가: compressed_bytes: Some(packed_length), | |
| 130 | 추가: ratio_output_bytes: Some(total), | |
| 131 | 추가: ..ResourceUsage::default() | |
| 132 | 추가: }, | |
| 133 | 추가: Some(&output), | |
| 134 | 추가: )?; | |
| 135 | 추가: check.borrow_mut().activity()?; | |
| 100 | 136 | // 전체 검증 전에는 비공개 임시 파일에만 기록함. |
| 101 | 137 | space::ensure(&output, count as u64)?; |
| 102 | 138 | output |
| 103 | 139 | .write_all(&buffer[..count]) |
| 104 | 140 | .map_err(space::io_error)?; |
| 105 | 141 | } |
| 106 | 삭제: (check.borrow_mut())()?; | |
| 142 | 추가: check.borrow_mut().check()?; | |
| 107 | 143 | if expected.is_some_and(|expected| expected != total) { |
| 108 | 144 | return Err(ErrorCode::Integrity); |
| 109 | 145 | } |
| @@ -114,9 +150,9 @@ fn read_at( | ||
| 114 | 150 | source: &mut File, |
| 115 | 151 | offset: u64, |
| 116 | 152 | bytes: &mut [u8], |
| 117 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 153 | 추가: check: &mut impl crate::resources::Monitor, | |
| 118 | 154 | ) -> Result<()> { |
| 119 | 삭제: check()?; | |
| 155 | 추가: check.check()?; | |
| 120 | 156 | source |
| 121 | 157 | .seek(std::io::SeekFrom::Start(offset)) |
| 122 | 158 | .map_err(space::io_error)?; |
| @@ -126,7 +162,8 @@ fn read_at( | ||
| 126 | 162 | } else { |
| 127 | 163 | ErrorCode::Io |
| 128 | 164 | } |
| 129 | 삭제: }) | |
| 165 | 추가: })?; | |
| 166 | 추가: check.activity() | |
| 130 | 167 | } |
| 131 | 168 | |
| 132 | 169 | fn vli(bytes: &[u8], cursor: &mut usize) -> Result<u64> { |
| @@ -150,7 +187,7 @@ fn lzma2_size( | ||
| 150 | 187 | mut at: u64, |
| 151 | 188 | end: u64, |
| 152 | 189 | expected: u64, |
| 153 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 190 | 추가: check: &mut impl crate::resources::Monitor, | |
| 154 | 191 | ) -> Result<()> { |
| 155 | 192 | let mut size = 0u64; |
| 156 | 193 | while at < end { |
| @@ -202,7 +239,7 @@ fn xz_block( | ||
| 202 | 239 | unpadded: u64, |
| 203 | 240 | size: u64, |
| 204 | 241 | check_size: u64, |
| 205 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 242 | 추가: check: &mut impl crate::resources::Monitor, | |
| 206 | 243 | ) -> Result<()> { |
| 207 | 244 | let mut header = [0; 1024]; |
| 208 | 245 | read_at(source, start, &mut header[..1], check)?; |
| @@ -262,7 +299,11 @@ fn xz_block( | ||
| 262 | 299 | } |
| 263 | 300 | |
| 264 | 301 | // 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함. |
| 265 | 삭제: fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<u64> { | |
| 302 | 추가: fn xz_layout( | |
| 303 | 추가: source: &mut File, | |
| 304 | 추가: limit: u64, | |
| 305 | 추가: check: &mut impl crate::resources::Monitor, | |
| 306 | 추가: ) -> Result<u64> { | |
| 266 | 307 | use zlib_rs::crc32::crc32; |
| 267 | 308 | let mut end = source.metadata().map_err(space::io_error)?.len(); |
| 268 | 309 | let mut total = 0u64; |
| @@ -316,7 +357,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 316 | 357 | let mut blocks = 0u64; |
| 317 | 358 | let mut records = Vec::new(); |
| 318 | 359 | for _ in 0..count { |
| 319 | 삭제: check()?; | |
| 360 | 추가: check.check()?; | |
| 320 | 361 | let unpadded = vli(&index[..data_end], &mut cursor)?; |
| 321 | 362 | let size = vli(&index[..data_end], &mut cursor)?; |
| 322 | 363 | if unpadded == 0 { |
| @@ -42,7 +42,7 @@ fn pack( | ||
| 42 | 42 | length: u64, |
| 43 | 43 | method: Method, |
| 44 | 44 | output: &mut File, |
| 45 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 45 | 추가: check: &mut impl crate::resources::Monitor, | |
| 46 | 46 | ) -> Result<(u64, u32)> { |
| 47 | 47 | io(input.rewind())?; |
| 48 | 48 | let mut input = input.take(length); |
| @@ -52,11 +52,13 @@ fn pack( | ||
| 52 | 52 | let mut size = 0u64; |
| 53 | 53 | if method == Method::Store { |
| 54 | 54 | loop { |
| 55 | 삭제: check()?; | |
| 55 | 추가: check.check()?; | |
| 56 | 56 | let n = io(input.read(&mut buffer[..]))?; |
| 57 | 57 | if n == 0 { |
| 58 | 58 | break; |
| 59 | 59 | } |
| 60 | 추가: check.activity()?; | |
| 61 | 추가: crate::space::ensure(output, n as u64)?; | |
| 60 | 62 | crc = crc32(crc, &buffer[..n]); |
| 61 | 63 | io(output.write_all(&buffer[..n]))?; |
| 62 | 64 | size += n as u64; |
| @@ -68,12 +70,12 @@ fn pack( | ||
| 68 | 70 | } |
| 69 | 71 | let mut stream = Deflate::new(6, false, 15); |
| 70 | 72 | loop { |
| 71 | 삭제: check()?; | |
| 73 | 추가: check.check()?; | |
| 72 | 74 | let n = io(input.read(&mut buffer[..]))?; |
| 73 | 75 | crc = crc32(crc, &buffer[..n]); |
| 74 | 76 | let mut used = 0; |
| 75 | 77 | loop { |
| 76 | 삭제: check()?; | |
| 78 | 추가: check.check()?; | |
| 77 | 79 | let a = stream.total_in(); |
| 78 | 80 | let b = stream.total_out(); |
| 79 | 81 | let status = stream |
| @@ -89,7 +91,11 @@ fn pack( | ||
| 89 | 91 | .map_err(|_| ErrorCode::Internal)?; |
| 90 | 92 | used += (stream.total_in() - a) as usize; |
| 91 | 93 | let written = (stream.total_out() - b) as usize; |
| 94 | 추가: crate::space::ensure(output, written as u64)?; | |
| 92 | 95 | io(output.write_all(&encoded[..written]))?; |
| 96 | 추가: if used != 0 || written != 0 { | |
| 97 | 추가: check.activity()?; | |
| 98 | 추가: } | |
| 93 | 99 | size = size.checked_add(written as u64).ok_or(ErrorCode::Limit)?; |
| 94 | 100 | if status == Status::StreamEnd { |
| 95 | 101 | if stream.total_in() != length { |
| @@ -110,7 +116,7 @@ pub(crate) use crate::create_sources::Plan; | ||
| 110 | 116 | pub(crate) fn plan( |
| 111 | 117 | sources: &[Source], |
| 112 | 118 | limits: Limits, |
| 113 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 119 | 추가: check: &mut impl crate::resources::Monitor, | |
| 114 | 120 | ) -> Result<Plan> { |
| 115 | 121 | Plan::new(sources, limits, check) |
| 116 | 122 | } |
| @@ -119,7 +125,7 @@ pub(crate) fn zip( | ||
| 119 | 125 | method: Method, |
| 120 | 126 | limits: Limits, |
| 121 | 127 | password: Option<&[u8]>, |
| 122 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 128 | 추가: check: &mut impl crate::resources::Monitor, | |
| 123 | 129 | ) -> Result<(File, u64)> { |
| 124 | 130 | let mut output = spool::temporary()?; |
| 125 | 131 | let mut central = Vec::new(); |
| @@ -130,7 +136,7 @@ pub(crate) fn zip( | ||
| 130 | 136 | let directory = member.entry.kind == EntryKind::Directory; |
| 131 | 137 | let method = if directory { Method::Store } else { method }; |
| 132 | 138 | let password = if directory { None } else { password }; |
| 133 | 삭제: check()?; | |
| 139 | 추가: check.check()?; | |
| 134 | 140 | let remaining = limits |
| 135 | 141 | .input |
| 136 | 142 | .min(limits.output) |
| @@ -229,12 +235,14 @@ pub(crate) fn zip( | ||
| 229 | 235 | } else { |
| 230 | 236 | let mut buffer = Zeroizing::new([0; 65536]); |
| 231 | 237 | loop { |
| 232 | 삭제: check()?; | |
| 238 | 추가: check.check()?; | |
| 233 | 239 | let n = io(packed.read(&mut buffer[..]))?; |
| 234 | 240 | if n == 0 { |
| 235 | 241 | break; |
| 236 | 242 | } |
| 243 | 추가: crate::space::ensure(&output, n as u64)?; | |
| 237 | 244 | io(output.write_all(&buffer[..n]))?; |
| 245 | 추가: check.activity()?; | |
| 238 | 246 | } |
| 239 | 247 | } |
| 240 | 248 | let mut extra = zip64_extra(length, packed_size, Some(offset)); |
| @@ -277,13 +285,17 @@ pub(crate) fn zip( | ||
| 277 | 285 | central.extend(name); |
| 278 | 286 | central.extend(extra); |
| 279 | 287 | } |
| 280 | 삭제: check()?; | |
| 288 | 추가: check.check()?; | |
| 281 | 289 | let at = io(output.stream_position())?; |
| 282 | 290 | crate::space::ensure(&output, central.len() as u64 + 98)?; |
| 283 | 291 | io(output.write_all(¢ral))?; |
| 284 | 292 | let large_at = io(output.stream_position())?; |
| 285 | 293 | let mut end = Vec::new(); |
| 286 | 삭제: if have_zip64 || at >= u32::MAX as u64 || central.len() >= u32::MAX as usize { | |
| 294 | 추가: if have_zip64 | |
| 295 | 추가: || plan.items.len() >= u16::MAX as usize | |
| 296 | 추가: || at >= u32::MAX as u64 | |
| 297 | 추가: || central.len() >= u32::MAX as usize | |
| 298 | 추가: { | |
| 287 | 299 | end.extend(b"PK\x06\x06"); |
| 288 | 300 | put64(&mut end, 44); |
| 289 | 301 | put16(&mut end, 45); |
| @@ -201,7 +201,7 @@ impl Plan { | ||
| 201 | 201 | pub fn new( |
| 202 | 202 | sources: &[Source], |
| 203 | 203 | limits: Limits, |
| 204 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 204 | 추가: check: &mut impl crate::resources::Monitor, | |
| 205 | 205 | ) -> Result<Self> { |
| 206 | 206 | if sources.len() > limits.entries as usize { |
| 207 | 207 | return Err(ErrorCode::Limit); |
| @@ -214,7 +214,7 @@ impl Plan { | ||
| 214 | 214 | }; |
| 215 | 215 | let mut roots = std::collections::BTreeSet::new(); |
| 216 | 216 | for source in sources { |
| 217 | 삭제: check()?; | |
| 217 | 추가: check.check()?; | |
| 218 | 218 | let name = archive::valid_name(&source.archive_name, false)?; |
| 219 | 219 | if !roots.insert(name.to_lowercase()) { |
| 220 | 220 | return Err(ErrorCode::Conflict); |
| @@ -241,9 +241,9 @@ impl Plan { | ||
| 241 | 241 | path: PathBuf, |
| 242 | 242 | name: String, |
| 243 | 243 | input: Input, |
| 244 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 244 | 추가: check: &mut impl crate::resources::Monitor, | |
| 245 | 245 | ) -> Result<()> { |
| 246 | 삭제: check()?; | |
| 246 | 추가: check.check()?; | |
| 247 | 247 | if self.items.len() >= self.limits.entries as usize { |
| 248 | 248 | return Err(ErrorCode::Limit); |
| 249 | 249 | } |
| @@ -258,6 +258,15 @@ impl Plan { | ||
| 258 | 258 | .checked_add(size) |
| 259 | 259 | .filter(|n| *n <= self.limits.input.min(self.limits.output)) |
| 260 | 260 | .ok_or(ErrorCode::Limit)?; |
| 261 | 추가: check.observe( | |
| 262 | 추가: ResourceUsage { | |
| 263 | 추가: estimated_bytes: Some(self.total), | |
| 264 | 추가: actual_entries: Some(self.items.len() as u32 + 1), | |
| 265 | 추가: ..ResourceUsage::default() | |
| 266 | 추가: }, | |
| 267 | 추가: None, | |
| 268 | 추가: )?; | |
| 269 | 추가: check.activity()?; | |
| 261 | 270 | self.items.push(Planned { |
| 262 | 271 | member: Member { |
| 263 | 272 | entry: Entry { |
| @@ -281,7 +290,7 @@ impl Plan { | ||
| 281 | 290 | if directory { |
| 282 | 291 | let mut children = Vec::new(); |
| 283 | 292 | for entry in input.children(&path)? { |
| 284 | 삭제: check()?; | |
| 293 | 추가: check.check()?; | |
| 285 | 294 | if self.items.len() + children.len() >= self.limits.entries as usize { |
| 286 | 295 | return Err(ErrorCode::Limit); |
| 287 | 296 | } |
| @@ -292,6 +301,15 @@ impl Plan { | ||
| 292 | 301 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 293 | 302 | self.budget.charge(&leaf)?; |
| 294 | 303 | children.push(leaf); |
| 304 | 추가: check.observe( | |
| 305 | 추가: ResourceUsage { | |
| 306 | 추가: estimated_bytes: Some(self.total), | |
| 307 | 추가: estimated_entries: Some((self.items.len() + children.len()) as u32), | |
| 308 | 추가: ..ResourceUsage::default() | |
| 309 | 추가: }, | |
| 310 | 추가: None, | |
| 311 | 추가: )?; | |
| 312 | 추가: check.activity()?; | |
| 295 | 313 | } |
| 296 | 314 | children.sort(); |
| 297 | 315 | for leaf in children { |
| @@ -301,10 +319,11 @@ impl Plan { | ||
| 301 | 319 | } |
| 302 | 320 | Ok(()) |
| 303 | 321 | } |
| 304 | 삭제: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> { | |
| 322 | 추가: pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> { | |
| 305 | 323 | for item in &self.items { |
| 306 | 삭제: check()?; | |
| 324 | 추가: check.check()?; | |
| 307 | 325 | item.open()?; |
| 326 | 추가: check.activity()?; | |
| 308 | 327 | } |
| 309 | 328 | Ok(()) |
| 310 | 329 | } |
| @@ -16,11 +16,11 @@ fn keys(password: &[u8], salt: &[u8]) -> Zeroizing<[u8; 66]> { | ||
| 16 | 16 | pbkdf2::pbkdf2_hmac::<Sha1>(password, salt, 1000, result.as_mut()); |
| 17 | 17 | result |
| 18 | 18 | } |
| 19 | 삭제: fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl FnMut() -> Result<()>) -> Result<()> { | |
| 19 | 추가: fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl crate::resources::Monitor) -> Result<()> { | |
| 20 | 20 | let cipher = Aes256::new_from_slice(key).map_err(|_| ErrorCode::Internal)?; |
| 21 | 21 | for (index, chunk) in bytes.chunks_mut(16).enumerate() { |
| 22 | 22 | if index % 4096 == 0 { |
| 23 | 삭제: check()?; | |
| 23 | 추가: check.check()?; | |
| 24 | 24 | } |
| 25 | 25 | // WinZip은 1부터 시작하는 리틀엔디언 카운터를 사용함. |
| 26 | 26 | let mut block = ((index as u128) + 1).to_le_bytes().into(); |
| @@ -35,11 +35,11 @@ fn ctr(bytes: &mut [u8], key: &[u8], check: &mut impl FnMut() -> Result<()>) -> | ||
| 35 | 35 | fn authenticate( |
| 36 | 36 | key: &[u8], |
| 37 | 37 | bytes: &[u8], |
| 38 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 38 | 추가: check: &mut impl crate::resources::Monitor, | |
| 39 | 39 | ) -> Result<Sha1Mac> { |
| 40 | 40 | let mut mac = <Sha1Mac as Mac>::new_from_slice(key).map_err(|_| ErrorCode::Internal)?; |
| 41 | 41 | for chunk in bytes.chunks(65536) { |
| 42 | 삭제: check()?; | |
| 42 | 추가: check.check()?; | |
| 43 | 43 | mac.update(chunk); |
| 44 | 44 | } |
| 45 | 45 | Ok(mac) |
| @@ -47,12 +47,12 @@ fn authenticate( | ||
| 47 | 47 | pub(crate) fn aes_decrypt( |
| 48 | 48 | packed: &[u8], |
| 49 | 49 | password: &[u8], |
| 50 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 50 | 추가: check: &mut impl crate::resources::Monitor, | |
| 51 | 51 | ) -> Result<Zeroizing<Vec<u8>>> { |
| 52 | 52 | if packed.len() < 28 { |
| 53 | 53 | return Err(ErrorCode::Integrity); |
| 54 | 54 | } |
| 55 | 삭제: check()?; | |
| 55 | 추가: check.check()?; | |
| 56 | 56 | let key = keys(password, &packed[..16]); |
| 57 | 57 | if !bool::from(key[64..].ct_eq(&packed[16..18])) { |
| 58 | 58 | return Err(ErrorCode::WrongPassword); |
| @@ -69,9 +69,9 @@ pub(crate) fn aes_decrypt( | ||
| 69 | 69 | pub(crate) fn aes_encrypt( |
| 70 | 70 | packed: &[u8], |
| 71 | 71 | password: &[u8], |
| 72 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 72 | 추가: check: &mut impl crate::resources::Monitor, | |
| 73 | 73 | ) -> Result<Vec<u8>> { |
| 74 | 삭제: check()?; | |
| 74 | 추가: check.check()?; | |
| 75 | 75 | let mut salt = [0; 16]; |
| 76 | 76 | random(&mut salt)?; |
| 77 | 77 | let key = keys(password, &salt); |
| @@ -138,7 +138,7 @@ pub(crate) fn zipcrypto_decrypt( | ||
| 138 | 138 | packed: &[u8], |
| 139 | 139 | password: &[u8], |
| 140 | 140 | verifier: u8, |
| 141 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 141 | 추가: check: &mut impl crate::resources::Monitor, | |
| 142 | 142 | ) -> Result<Zeroizing<Vec<u8>>> { |
| 143 | 143 | if packed.len() < 12 { |
| 144 | 144 | return Err(ErrorCode::Integrity); |
| @@ -150,7 +150,7 @@ pub(crate) fn zipcrypto_decrypt( | ||
| 150 | 150 | let mut out = Zeroizing::new(Vec::with_capacity(packed.len() - 12)); |
| 151 | 151 | for (index, &byte) in packed.iter().enumerate() { |
| 152 | 152 | if index % 65536 == 0 { |
| 153 | 삭제: check()?; | |
| 153 | 추가: check.check()?; | |
| 154 | 154 | } |
| 155 | 155 | let temp = key[2] | 2; |
| 156 | 156 | let plain = byte ^ ((temp.wrapping_mul(temp ^ 1) >> 8) as u8); |
| @@ -191,7 +191,7 @@ impl Decryptor { | ||
| 191 | 191 | password: &[u8], |
| 192 | 192 | aes: bool, |
| 193 | 193 | verifier: u8, |
| 194 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 194 | 추가: check: &mut impl crate::resources::Monitor, | |
| 195 | 195 | ) -> Result<(Self, u64, u64)> { |
| 196 | 196 | use std::io::{Read, Seek, SeekFrom}; |
| 197 | 197 | file.seek(SeekFrom::Start(offset)) |
| @@ -212,12 +212,13 @@ impl Decryptor { | ||
| 212 | 212 | let mut remaining = length - 28; |
| 213 | 213 | let mut buffer = [0; 65536]; |
| 214 | 214 | while remaining != 0 { |
| 215 | 삭제: check()?; | |
| 215 | 추가: check.check()?; | |
| 216 | 216 | let n = remaining.min(buffer.len() as u64) as usize; |
| 217 | 217 | file.read_exact(&mut buffer[..n]) |
| 218 | 218 | .map_err(|_| ErrorCode::Integrity)?; |
| 219 | 219 | mac.update(&buffer[..n]); |
| 220 | 220 | remaining -= n as u64; |
| 221 | 추가: check.activity()?; | |
| 221 | 222 | } |
| 222 | 223 | let mut tag = [0; 10]; |
| 223 | 224 | file.read_exact(&mut tag) |
| @@ -301,10 +302,10 @@ pub(crate) fn aes_encrypt_file( | ||
| 301 | 302 | length: u64, |
| 302 | 303 | output: &mut std::fs::File, |
| 303 | 304 | password: &[u8], |
| 304 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 305 | 추가: check: &mut impl crate::resources::Monitor, | |
| 305 | 306 | ) -> Result<()> { |
| 306 | 307 | use std::io::{Read, Write}; |
| 307 | 삭제: check()?; | |
| 308 | 추가: check.check()?; | |
| 308 | 309 | let mut salt = [0; 16]; |
| 309 | 310 | random(&mut salt)?; |
| 310 | 311 | let key = keys(password, &salt); |
| @@ -323,17 +324,19 @@ pub(crate) fn aes_encrypt_file( | ||
| 323 | 324 | let mut remaining = length; |
| 324 | 325 | let mut buffer = Zeroizing::new([0; 65536]); |
| 325 | 326 | while remaining != 0 { |
| 326 | 삭제: check()?; | |
| 327 | 추가: check.check()?; | |
| 327 | 328 | let n = remaining.min(buffer.len() as u64) as usize; |
| 328 | 329 | input |
| 329 | 330 | .read_exact(&mut buffer[..n]) |
| 330 | 331 | .map_err(crate::space::io_error)?; |
| 331 | 332 | cipher.apply(&mut buffer[..n]); |
| 332 | 333 | mac.update(&buffer[..n]); |
| 334 | 추가: crate::space::ensure(output, n as u64)?; | |
| 333 | 335 | output |
| 334 | 336 | .write_all(&buffer[..n]) |
| 335 | 337 | .map_err(crate::space::io_error)?; |
| 336 | 338 | remaining -= n as u64; |
| 339 | 추가: check.activity()?; | |
| 337 | 340 | } |
| 338 | 341 | output |
| 339 | 342 | .write_all(&mac.finalize().into_bytes()[..10]) |
| @@ -90,7 +90,7 @@ pub fn object(file: &File) -> Result<SourceObject> { | ||
| 90 | 90 | pub fn snapshot( |
| 91 | 91 | path: &Path, |
| 92 | 92 | limit: u64, |
| 93 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 93 | 추가: check: &mut impl crate::resources::Monitor, | |
| 94 | 94 | ) -> Result<Snapshot> { |
| 95 | 95 | let mut options = OpenOptions::new(); |
| 96 | 96 | options.read(true); |
| @@ -117,7 +117,7 @@ pub fn snapshot( | ||
| 117 | 117 | let mut hash = Sha256::new(); |
| 118 | 118 | let mut buffer = [0; 65536]; |
| 119 | 119 | loop { |
| 120 | 삭제: check()?; | |
| 120 | 추가: check.check()?; | |
| 121 | 121 | let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?; |
| 122 | 122 | if n == 0 { |
| 123 | 123 | break; |
| @@ -663,6 +663,7 @@ pub fn publish_reader_mode( | ||
| 663 | 663 | if n == 0 { |
| 664 | 664 | return Err(ErrorCode::Io); |
| 665 | 665 | } |
| 666 | 추가: crate::space::ensure(&file, n as u64)?; | |
| 666 | 667 | file.write_all(&buffer[..n]) |
| 667 | 668 | .map_err(crate::space::io_error)?; |
| 668 | 669 | remaining -= n as u64; |
| @@ -7,6 +7,7 @@ pub mod filesystem; | ||
| 7 | 7 | mod lzma; |
| 8 | 8 | mod parent; |
| 9 | 9 | pub mod protocol; |
| 10 | 추가: pub mod resources; | |
| 10 | 11 | pub mod runtime; |
| 11 | 12 | mod seven_zip; |
| 12 | 13 | mod space; |
| @@ -26,6 +26,7 @@ impl<'a> History<'a> { | ||
| 26 | 26 | } |
| 27 | 27 | fn flush(&mut self) -> Result<()> { |
| 28 | 28 | use std::io::Write; |
| 29 | 추가: crate::space::ensure(self.file, self.pending.len() as u64)?; | |
| 29 | 30 | self.file |
| 30 | 31 | .write_all(&self.pending) |
| 31 | 32 | .map_err(crate::space::io_error)?; |
| @@ -405,13 +406,25 @@ impl Model { | ||
| 405 | 406 | dictionary: usize, |
| 406 | 407 | target: u64, |
| 407 | 408 | eos: bool, |
| 408 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 409 | 추가: check: &mut impl crate::resources::Monitor, | |
| 409 | 410 | ) -> Result<()> { |
| 410 | 411 | let mut range = Range::new(input, length)?; |
| 411 | 412 | let mut next_check = out.len(); |
| 412 | 413 | while out.len() < target { |
| 413 | 414 | if out.len() >= next_check { |
| 414 | 삭제: check()?; | |
| 415 | 추가: check.check()?; | |
| 416 | 추가: if out.len() > next_check.saturating_sub(65536) { | |
| 417 | 추가: check.activity()?; | |
| 418 | 추가: } | |
| 419 | 추가: check.observe( | |
| 420 | 추가: crate::protocol::ResourceUsage { | |
| 421 | 추가: actual_bytes: Some( | |
| 422 | 추가: out.base.checked_add(out.len()).ok_or(ErrorCode::Limit)?, | |
| 423 | 추가: ), | |
| 424 | 추가: ..crate::protocol::ResourceUsage::default() | |
| 425 | 추가: }, | |
| 426 | 추가: Some(out.file), | |
| 427 | 추가: )?; | |
| 415 | 428 | next_check = out.len() + 65536; |
| 416 | 429 | } |
| 417 | 430 | if self.symbol(&mut range, out, history, dictionary, target)? { |
| @@ -442,7 +455,7 @@ pub(crate) fn decode_stream( | ||
| 442 | 455 | lzma2: bool, |
| 443 | 456 | size: u64, |
| 444 | 457 | output: &mut std::fs::File, |
| 445 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 458 | 추가: check: &mut impl crate::resources::Monitor, | |
| 446 | 459 | ) -> Result<()> { |
| 447 | 460 | use std::io::{BufReader, Read}; |
| 448 | 461 | crate::space::ensure(output, size)?; |
| @@ -492,8 +505,9 @@ pub(crate) fn decode_stream( | ||
| 492 | 505 | let mut need_state = true; |
| 493 | 506 | let mut model: Option<Model> = None; |
| 494 | 507 | loop { |
| 495 | 삭제: check()?; | |
| 508 | 추가: check.check()?; | |
| 496 | 509 | let control = byte(&mut reader)?; |
| 510 | 추가: check.activity()?; | |
| 497 | 511 | if control == 0 { |
| 498 | 512 | let mut extra = [0]; |
| 499 | 513 | if reader.read(&mut extra).map_err(crate::space::io_error)? != 0 || out.len() != size { |
| @@ -82,6 +82,44 @@ impl Limits { | ||
| 82 | 82 | && self.entries <= hard.entries |
| 83 | 83 | } |
| 84 | 84 | } |
| 85 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 86 | 추가: pub struct GuardedStart { | |
| 87 | 추가: pub start: Start, | |
| 88 | 추가: pub ceiling: Limits, | |
| 89 | 추가: pub interactive: bool, | |
| 90 | 추가: } | |
| 91 | 추가: impl GuardedStart { | |
| 92 | 추가: pub fn valid(&self) -> bool { | |
| 93 | 추가: self.start.limits.valid() | |
| 94 | 추가: && self.ceiling.input == self.start.limits.input | |
| 95 | 추가: && self.ceiling.output >= self.start.limits.output | |
| 96 | 추가: && self.ceiling.output <= 64 * 1024 * 1024 * 1024 | |
| 97 | 추가: && self.ceiling.entries >= self.start.limits.entries | |
| 98 | 추가: && self.ceiling.entries <= 200_000 | |
| 99 | 추가: && (!self.interactive || matches!(self.start.action, Action::Extract { .. })) | |
| 100 | 추가: } | |
| 101 | 추가: } | |
| 102 | 추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 103 | 추가: pub struct ResourceScope { | |
| 104 | 추가: pub output: bool, | |
| 105 | 추가: pub entries: bool, | |
| 106 | 추가: pub ratio: bool, | |
| 107 | 추가: } | |
| 108 | 추가: impl ResourceScope { | |
| 109 | 추가: pub fn any(self) -> bool { | |
| 110 | 추가: self.output || self.entries || self.ratio | |
| 111 | 추가: } | |
| 112 | 추가: } | |
| 113 | 추가: #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | |
| 114 | 추가: pub struct ResourceUsage { | |
| 115 | 추가: pub estimated_bytes: Option<u64>, | |
| 116 | 추가: pub actual_bytes: Option<u64>, | |
| 117 | 추가: pub estimated_entries: Option<u32>, | |
| 118 | 추가: pub actual_entries: Option<u32>, | |
| 119 | 추가: pub compressed_bytes: Option<u64>, | |
| 120 | 추가: pub ratio_output_bytes: Option<u64>, | |
| 121 | 추가: pub available_bytes: Option<u64>, | |
| 122 | 추가: } | |
| 85 | 123 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 86 | 124 | pub enum Format { |
| 87 | 125 | Zip, |
| @@ -292,6 +330,20 @@ pub enum Message { | ||
| 292 | 330 | }, |
| 293 | 331 | Cancel, |
| 294 | 332 | StartInteractive(Start), |
| 333 | 추가: StartGuarded(GuardedStart), | |
| 334 | 추가: ResourceReply { | |
| 335 | 추가: challenge_id: u64, | |
| 336 | 추가: scope: ResourceScope, | |
| 337 | 추가: allow: bool, | |
| 338 | 추가: }, | |
| 339 | 추가: ResourceRequired { | |
| 340 | 추가: challenge_id: u64, | |
| 341 | 추가: action: ActionKind, | |
| 342 | 추가: scope: ResourceScope, | |
| 343 | 추가: usage: ResourceUsage, | |
| 344 | 추가: soft_limits: Limits, | |
| 345 | 추가: ceiling: Limits, | |
| 346 | 추가: }, | |
| 295 | 347 | ConflictReply { |
| 296 | 348 | challenge_id: u64, |
| 297 | 349 | choice: ConflictChoice, |
| @@ -0,0 +1,97 @@ | ||
| 1 | 추가: use crate::protocol::*; | |
| 2 | 추가: use std::time::Duration; | |
| 3 | 추가: | |
| 4 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 5 | 추가: | |
| 6 | 추가: pub trait Monitor { | |
| 7 | 추가: fn check(&mut self) -> Result<()>; | |
| 8 | 추가: fn activity(&mut self) -> Result<()> { | |
| 9 | 추가: self.check() | |
| 10 | 추가: } | |
| 11 | 추가: fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> { | |
| 12 | 추가: self.check() | |
| 13 | 추가: } | |
| 14 | 추가: } | |
| 15 | 추가: impl<F: FnMut() -> Result<()>> Monitor for F { | |
| 16 | 추가: fn check(&mut self) -> Result<()> { | |
| 17 | 추가: self() | |
| 18 | 추가: } | |
| 19 | 추가: } | |
| 20 | 추가: | |
| 21 | 추가: pub(crate) struct Budget { | |
| 22 | 추가: pub soft: Limits, | |
| 23 | 추가: pub ceiling: Limits, | |
| 24 | 추가: pub granted: ResourceScope, | |
| 25 | 추가: } | |
| 26 | 추가: impl Budget { | |
| 27 | 추가: pub fn required(&self, usage: ResourceUsage) -> Result<ResourceScope> { | |
| 28 | 추가: let bytes = usage | |
| 29 | 추가: .estimated_bytes | |
| 30 | 추가: .into_iter() | |
| 31 | 추가: .chain(usage.actual_bytes) | |
| 32 | 추가: .max(); | |
| 33 | 추가: let entries = usage | |
| 34 | 추가: .estimated_entries | |
| 35 | 추가: .into_iter() | |
| 36 | 추가: .chain(usage.actual_entries) | |
| 37 | 추가: .max(); | |
| 38 | 추가: if bytes.is_some_and(|n| n > self.ceiling.output) | |
| 39 | 추가: || entries.is_some_and(|n| n > self.ceiling.entries) | |
| 40 | 추가: { | |
| 41 | 추가: return Err(ErrorCode::Limit); | |
| 42 | 추가: } | |
| 43 | 추가: let ratio = match (usage.ratio_output_bytes, usage.compressed_bytes) { | |
| 44 | 추가: (Some(output), Some(input)) => { | |
| 45 | 추가: output >= 256 * 1024 * 1024 && u128::from(output) > u128::from(input) * 1000 | |
| 46 | 추가: } | |
| 47 | 추가: _ => false, | |
| 48 | 추가: }; | |
| 49 | 추가: Ok(ResourceScope { | |
| 50 | 추가: output: !self.granted.output && bytes.is_some_and(|n| n > self.soft.output), | |
| 51 | 추가: entries: !self.granted.entries && entries.is_some_and(|n| n > self.soft.entries), | |
| 52 | 추가: ratio: !self.granted.ratio && ratio, | |
| 53 | 추가: }) | |
| 54 | 추가: } | |
| 55 | 추가: pub fn grant(&mut self, scope: ResourceScope) { | |
| 56 | 추가: self.granted.output |= scope.output; | |
| 57 | 추가: self.granted.entries |= scope.entries; | |
| 58 | 추가: self.granted.ratio |= scope.ratio; | |
| 59 | 추가: } | |
| 60 | 추가: } | |
| 61 | 추가: | |
| 62 | 추가: pub(crate) struct Watchdog { | |
| 63 | 추가: last_activity: Duration, | |
| 64 | 추가: approved: bool, | |
| 65 | 추가: } | |
| 66 | 추가: impl Watchdog { | |
| 67 | 추가: pub fn new() -> Self { | |
| 68 | 추가: Self { | |
| 69 | 추가: last_activity: Duration::ZERO, | |
| 70 | 추가: approved: false, | |
| 71 | 추가: } | |
| 72 | 추가: } | |
| 73 | 추가: pub fn check(&self, elapsed: Duration) -> Result<()> { | |
| 74 | 추가: if if self.approved { | |
| 75 | 추가: elapsed.saturating_sub(self.last_activity) >= Duration::from_secs(60) | |
| 76 | 추가: } else { | |
| 77 | 추가: elapsed > Duration::from_secs(300) | |
| 78 | 추가: } { | |
| 79 | 추가: Err(ErrorCode::Limit) | |
| 80 | 추가: } else { | |
| 81 | 추가: Ok(()) | |
| 82 | 추가: } | |
| 83 | 추가: } | |
| 84 | 추가: pub fn activity(&mut self, elapsed: Duration) -> Result<()> { | |
| 85 | 추가: self.check(elapsed)?; | |
| 86 | 추가: self.last_activity = elapsed; | |
| 87 | 추가: Ok(()) | |
| 88 | 추가: } | |
| 89 | 추가: pub fn resume(&mut self, elapsed: Duration, approved: bool) { | |
| 90 | 추가: self.approved |= approved; | |
| 91 | 추가: self.last_activity = elapsed; | |
| 92 | 추가: } | |
| 93 | 추가: } | |
| 94 | 추가: | |
| 95 | 추가: #[cfg(test)] | |
| 96 | 추가: #[path = "../../../tests/rust-archive-worker/resource_budget.rs"] | |
| 97 | 추가: mod tests; |
| @@ -2,6 +2,7 @@ use crate::{ | ||
| 2 | 2 | archive, |
| 3 | 3 | filesystem::{self, Dir}, |
| 4 | 4 | protocol::*, |
| 5 | 추가: resources::{Budget, Monitor, Watchdog}, | |
| 5 | 6 | wire::{Reader, Writer}, |
| 6 | 7 | }; |
| 7 | 8 | use std::{ |
| @@ -16,6 +17,7 @@ type Result<T> = std::result::Result<T, ErrorCode>; | ||
| 16 | 17 | enum Challenge { |
| 17 | 18 | Password(u64), |
| 18 | 19 | Conflict(u64), |
| 20 | 추가: Resource(u64, ResourceScope), | |
| 19 | 21 | } |
| 20 | 22 | struct State<W> { |
| 21 | 23 | writer: Writer<W>, |
| @@ -25,6 +27,7 @@ struct State<W> { | ||
| 25 | 27 | challenge: Option<Challenge>, |
| 26 | 28 | conflict_reply: Option<(ConflictChoice, bool)>, |
| 27 | 29 | password: Option<Secret>, |
| 30 | 추가: resource_reply: Option<bool>, | |
| 28 | 31 | input_closed: bool, |
| 29 | 32 | } |
| 30 | 33 | struct Job<W> { |
| @@ -32,12 +35,79 @@ struct Job<W> { | ||
| 32 | 35 | wake: Arc<Condvar>, |
| 33 | 36 | next_challenge: u64, |
| 34 | 37 | interactive: bool, |
| 38 | 추가: action: ActionKind, | |
| 39 | 추가: budget: Option<Budget>, | |
| 40 | 추가: watchdog: Watchdog, | |
| 35 | 41 | remaining_choice: Option<ConflictChoice>, |
| 36 | 42 | started: Instant, |
| 37 | 43 | terminal: Terminal, |
| 38 | 44 | parent: crate::parent::Parent, |
| 39 | 45 | } |
| 40 | 46 | impl<W: Write> Job<W> { |
| 47 | 추가: fn request_resource( | |
| 48 | 추가: &mut self, | |
| 49 | 추가: scope: ResourceScope, | |
| 50 | 추가: mut usage: ResourceUsage, | |
| 51 | 추가: storage: Option<&std::fs::File>, | |
| 52 | 추가: ) -> Result<()> { | |
| 53 | 추가: let budget = self.budget.as_ref().ok_or(ErrorCode::Internal)?; | |
| 54 | 추가: let (soft_limits, ceiling) = (budget.soft, budget.ceiling); | |
| 55 | 추가: if let Some(file) = storage { | |
| 56 | 추가: usage.available_bytes = | |
| 57 | 추가: Some(crate::space::available(file)?.min(u64::MAX as u128) as u64); | |
| 58 | 추가: } | |
| 59 | 추가: self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; | |
| 60 | 추가: let id = self.next_challenge; | |
| 61 | 추가: let state_ref = Arc::clone(&self.state); | |
| 62 | 추가: let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; | |
| 63 | 추가: if state.challenge.is_some() { | |
| 64 | 추가: return Err(ErrorCode::Internal); | |
| 65 | 추가: } | |
| 66 | 추가: state.challenge = Some(Challenge::Resource(id, scope)); | |
| 67 | 추가: state | |
| 68 | 추가: .writer | |
| 69 | 추가: .send(&Message::ResourceRequired { | |
| 70 | 추가: challenge_id: id, | |
| 71 | 추가: action: self.action, | |
| 72 | 추가: scope, | |
| 73 | 추가: usage, | |
| 74 | 추가: soft_limits, | |
| 75 | 추가: ceiling, | |
| 76 | 추가: }) | |
| 77 | 추가: .map_err(|_| ErrorCode::Io)?; | |
| 78 | 추가: let waiting = Instant::now(); | |
| 79 | 추가: loop { | |
| 80 | 추가: self.parent.check()?; | |
| 81 | 추가: if let Some(error) = state.fault { | |
| 82 | 추가: return Err(error); | |
| 83 | 추가: } | |
| 84 | 추가: if state.cancelled { | |
| 85 | 추가: return Err(ErrorCode::None); | |
| 86 | 추가: } | |
| 87 | 추가: if let Some(allow) = state.resource_reply.take() { | |
| 88 | 추가: if !allow { | |
| 89 | 추가: return Err(ErrorCode::None); | |
| 90 | 추가: } | |
| 91 | 추가: self.budget | |
| 92 | 추가: .as_mut() | |
| 93 | 추가: .ok_or(ErrorCode::Internal)? | |
| 94 | 추가: .grant(scope); | |
| 95 | 추가: self.watchdog.resume(self.started.elapsed(), true); | |
| 96 | 추가: return Ok(()); | |
| 97 | 추가: } | |
| 98 | 추가: if state.input_closed { | |
| 99 | 추가: return Err(ErrorCode::Protocol); | |
| 100 | 추가: } | |
| 101 | 추가: if waiting.elapsed() >= Duration::from_secs(300) { | |
| 102 | 추가: return Err(ErrorCode::Limit); | |
| 103 | 추가: } | |
| 104 | 추가: state = self | |
| 105 | 추가: .wake | |
| 106 | 추가: .wait_timeout(state, Duration::from_millis(50)) | |
| 107 | 추가: .map_err(|_| ErrorCode::Internal)? | |
| 108 | 추가: .0; | |
| 109 | 추가: } | |
| 110 | 추가: } | |
| 41 | 111 | fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> { |
| 42 | 112 | self.check()?; |
| 43 | 113 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| @@ -53,6 +123,7 @@ impl<W: Write> Job<W> { | ||
| 53 | 123 | purpose, |
| 54 | 124 | }) |
| 55 | 125 | .map_err(|_| ErrorCode::Io)?; |
| 126 | 추가: let waiting = Instant::now(); | |
| 56 | 127 | loop { |
| 57 | 128 | self.parent.check()?; |
| 58 | 129 | if let Some(error) = state.fault { |
| @@ -62,12 +133,17 @@ impl<W: Write> Job<W> { | ||
| 62 | 133 | return Err(ErrorCode::None); |
| 63 | 134 | } |
| 64 | 135 | if let Some(secret) = state.password.take() { |
| 136 | 추가: self.watchdog.resume(self.started.elapsed(), false); | |
| 65 | 137 | return Ok(secret); |
| 66 | 138 | } |
| 67 | 139 | if state.input_closed { |
| 68 | 140 | return Err(ErrorCode::Protocol); |
| 69 | 141 | } |
| 70 | 삭제: if self.started.elapsed() > Duration::from_secs(300) { | |
| 142 | 추가: if if self.budget.is_some() { | |
| 143 | 추가: waiting.elapsed() >= Duration::from_secs(300) | |
| 144 | 추가: } else { | |
| 145 | 추가: self.started.elapsed() > Duration::from_secs(300) | |
| 146 | 추가: } { | |
| 71 | 147 | return Err(ErrorCode::Limit); |
| 72 | 148 | } |
| 73 | 149 | state = self |
| @@ -98,6 +174,7 @@ impl<W: Write> Job<W> { | ||
| 98 | 174 | existing_size, |
| 99 | 175 | }) |
| 100 | 176 | .map_err(|_| ErrorCode::Io)?; |
| 177 | 추가: let waiting = Instant::now(); | |
| 101 | 178 | loop { |
| 102 | 179 | self.parent.check()?; |
| 103 | 180 | if let Some(error) = state.fault { |
| @@ -110,12 +187,17 @@ impl<W: Write> Job<W> { | ||
| 110 | 187 | if apply { |
| 111 | 188 | self.remaining_choice = Some(choice); |
| 112 | 189 | } |
| 190 | 추가: self.watchdog.resume(self.started.elapsed(), false); | |
| 113 | 191 | return Ok(choice); |
| 114 | 192 | } |
| 115 | 193 | if state.input_closed { |
| 116 | 194 | return Err(ErrorCode::Protocol); |
| 117 | 195 | } |
| 118 | 삭제: if self.started.elapsed() > Duration::from_secs(300) { | |
| 196 | 추가: if if self.budget.is_some() { | |
| 197 | 추가: waiting.elapsed() >= Duration::from_secs(300) | |
| 198 | 추가: } else { | |
| 199 | 추가: self.started.elapsed() > Duration::from_secs(300) | |
| 200 | 추가: } { | |
| 119 | 201 | return Err(ErrorCode::Limit); |
| 120 | 202 | } |
| 121 | 203 | state = self |
| @@ -168,9 +250,6 @@ impl<W: Write> Job<W> { | ||
| 168 | 250 | } |
| 169 | 251 | fn check(&mut self) -> Result<()> { |
| 170 | 252 | self.parent.check()?; |
| 171 | 삭제: if self.started.elapsed() > Duration::from_secs(300) { | |
| 172 | 삭제: return Err(ErrorCode::Limit); | |
| 173 | 삭제: } | |
| 174 | 253 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 175 | 254 | if let Some(error) = state.fault { |
| 176 | 255 | return Err(error); |
| @@ -178,7 +257,7 @@ impl<W: Write> Job<W> { | ||
| 178 | 257 | if state.cancelled && state.phase == 0 { |
| 179 | 258 | return Err(ErrorCode::None); |
| 180 | 259 | } |
| 181 | 삭제: Ok(()) | |
| 260 | 추가: self.watchdog.check(self.started.elapsed()) | |
| 182 | 261 | } |
| 183 | 262 | fn cutoff(&mut self) -> Result<()> { |
| 184 | 263 | self.check()?; |
| @@ -220,7 +299,12 @@ impl<W: Write> Job<W> { | ||
| 220 | 299 | Some(length), |
| 221 | 300 | self.terminal.created_count as u32, |
| 222 | 301 | )?; |
| 302 | 추가: let mut first_chunk = true; | |
| 223 | 303 | let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| { |
| 304 | 추가: if !first_chunk { | |
| 305 | 추가: self.activity()?; | |
| 306 | 추가: } | |
| 307 | 추가: first_chunk = false; | |
| 224 | 308 | if commit && last { |
| 225 | 309 | self.cutoff() |
| 226 | 310 | } else { |
| @@ -272,11 +356,23 @@ impl<W: Write> Job<W> { | ||
| 272 | 356 | if !start.limits.valid() { |
| 273 | 357 | return Err(ErrorCode::InvalidRequest); |
| 274 | 358 | } |
| 359 | 추가: let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); | |
| 275 | 360 | self.event(Message::Accepted { |
| 276 | 361 | action: start.action.kind(), |
| 277 | 362 | encryption: true, |
| 278 | 363 | })?; |
| 279 | 364 | self.check()?; |
| 365 | 추가: if let Some(budget) = &self.budget { | |
| 366 | 추가: let scope = ResourceScope { | |
| 367 | 추가: output: budget.ceiling.output > budget.soft.output, | |
| 368 | 추가: entries: budget.ceiling.entries > budget.soft.entries, | |
| 369 | 추가: ratio: false, | |
| 370 | 추가: }; | |
| 371 | 추가: if scope.any() { | |
| 372 | 추가: let temporary = crate::spool::temporary()?; | |
| 373 | 추가: self.request_resource(scope, ResourceUsage::default(), Some(&temporary))?; | |
| 374 | 추가: } | |
| 375 | 추가: } | |
| 280 | 376 | match start.action { |
| 281 | 377 | Action::List { |
| 282 | 378 | archive: ref source, |
| @@ -288,16 +384,16 @@ impl<W: Write> Job<W> { | ||
| 288 | 384 | let extract = matches!(start.action, Action::Extract { .. }); |
| 289 | 385 | let path = source.to_path()?; |
| 290 | 386 | self.progress(Stage::Read, 0, None, 0)?; |
| 291 | 삭제: let mut snapshot = crate::spool::Snapshot::open_reporting( | |
| 292 | 삭제: &path, | |
| 293 | 삭제: start.limits.input, | |
| 294 | 삭제: &mut |step| match step { | |
| 295 | 삭제: crate::spool::Step::Check => self.check(), | |
| 296 | 삭제: crate::spool::Step::Read { bytes, total } => { | |
| 297 | 삭제: self.progress(Stage::Read, bytes, Some(total), 0) | |
| 387 | 추가: let mut snapshot = | |
| 388 | 추가: crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| { | |
| 389 | 추가: match step { | |
| 390 | 추가: crate::spool::Step::Check => self.check(), | |
| 391 | 추가: crate::spool::Step::Read { bytes, total } => { | |
| 392 | 추가: self.activity()?; | |
| 393 | 추가: self.progress(Stage::Read, bytes, Some(total), 0) | |
| 394 | 추가: } | |
| 298 | 395 | } |
| 299 | 삭제: }, | |
| 300 | 삭제: )?; | |
| 396 | 추가: })?; | |
| 301 | 397 | if let Action::Extract { |
| 302 | 398 | list_id: Some(expected), |
| 303 | 399 | .. |
| @@ -315,10 +411,10 @@ impl<W: Write> Job<W> { | ||
| 315 | 411 | let mut catalog = crate::streaming::Catalog::open( |
| 316 | 412 | &mut snapshot.file, |
| 317 | 413 | snapshot.len, |
| 318 | 삭제: start.limits, | |
| 414 | 추가: limits, | |
| 319 | 415 | false, |
| 320 | 416 | None, |
| 321 | 삭제: &mut || self.check(), | |
| 417 | 추가: self, | |
| 322 | 418 | )?; |
| 323 | 419 | let list_id = ListId { |
| 324 | 420 | catalog_version: 1, |
| @@ -423,10 +519,10 @@ impl<W: Write> Job<W> { | ||
| 423 | 519 | match crate::streaming::Catalog::open( |
| 424 | 520 | &mut snapshot.file, |
| 425 | 521 | snapshot.len, |
| 426 | 삭제: start.limits, | |
| 522 | 추가: limits, | |
| 427 | 523 | true, |
| 428 | 524 | secret.as_ref().map(|s| s.0.as_slice()), |
| 429 | 삭제: &mut || self.check(), | |
| 525 | 추가: self, | |
| 430 | 526 | ) { |
| 431 | 527 | Ok(decoded) => { |
| 432 | 528 | catalog = decoded; |
| @@ -554,7 +650,7 @@ impl<W: Write> Job<W> { | ||
| 554 | 650 | let name = archive::valid_name(leaf, false)?; |
| 555 | 651 | let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?; |
| 556 | 652 | filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?; |
| 557 | 삭제: let members = crate::create::plan(&sources, start.limits, &mut || self.check())?; | |
| 653 | 추가: let members = crate::create::plan(&sources, limits, self)?; | |
| 558 | 654 | let secret = if encryption == Encryption::Aes256 { |
| 559 | 655 | let secret = self.password(PasswordPurpose::Encrypt, 1)?; |
| 560 | 656 | if secret.0.is_empty() { |
| @@ -567,9 +663,9 @@ impl<W: Write> Job<W> { | ||
| 567 | 663 | let (mut data, length) = crate::create::zip( |
| 568 | 664 | &members, |
| 569 | 665 | method, |
| 570 | 삭제: start.limits, | |
| 666 | 추가: limits, | |
| 571 | 667 | secret.as_ref().map(|s| s.0.as_slice()), |
| 572 | 삭제: &mut || self.check(), | |
| 668 | 추가: self, | |
| 573 | 669 | )?; |
| 574 | 670 | filesystem::preflight_space(&root, &[(name.clone(), length)], None)?; |
| 575 | 671 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| @@ -580,6 +676,27 @@ impl<W: Write> Job<W> { | ||
| 580 | 676 | Ok(()) |
| 581 | 677 | } |
| 582 | 678 | } |
| 679 | 추가: impl<W: Write> Monitor for Job<W> { | |
| 680 | 추가: fn check(&mut self) -> Result<()> { | |
| 681 | 추가: Job::check(self) | |
| 682 | 추가: } | |
| 683 | 추가: fn activity(&mut self) -> Result<()> { | |
| 684 | 추가: self.check()?; | |
| 685 | 추가: self.watchdog.activity(self.started.elapsed()) | |
| 686 | 추가: } | |
| 687 | 추가: fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> { | |
| 688 | 추가: self.check()?; | |
| 689 | 추가: let Some(budget) = &self.budget else { | |
| 690 | 추가: return Ok(()); | |
| 691 | 추가: }; | |
| 692 | 추가: let scope = budget.required(usage)?; | |
| 693 | 추가: if !scope.any() { | |
| 694 | 추가: return Ok(()); | |
| 695 | 추가: } | |
| 696 | 추가: self.request_resource(scope, usage, storage) | |
| 697 | 추가: } | |
| 698 | 추가: } | |
| 699 | 추가: | |
| 583 | 700 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 584 | 701 | input: R, |
| 585 | 702 | output: W, |
| @@ -590,9 +707,17 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 590 | 707 | let (job, _, message) = reader |
| 591 | 708 | .read()? |
| 592 | 709 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 593 | 삭제: let (start, interactive) = match message { | |
| 594 | 삭제: Message::Start(start) => (start, false), | |
| 595 | 삭제: Message::StartInteractive(start) => (start, true), | |
| 710 | 추가: let (start, interactive, budget) = match message { | |
| 711 | 추가: Message::Start(start) => (start, false, None), | |
| 712 | 추가: Message::StartInteractive(start) => (start, true, None), | |
| 713 | 추가: Message::StartGuarded(guarded) if guarded.valid() => { | |
| 714 | 추가: let budget = Budget { | |
| 715 | 추가: soft: guarded.start.limits, | |
| 716 | 추가: ceiling: guarded.ceiling, | |
| 717 | 추가: granted: ResourceScope::default(), | |
| 718 | 추가: }; | |
| 719 | 추가: (guarded.start, guarded.interactive, Some(budget)) | |
| 720 | 추가: } | |
| 596 | 721 | _ => { |
| 597 | 722 | return Err(std::io::Error::new( |
| 598 | 723 | std::io::ErrorKind::InvalidData, |
| @@ -608,6 +733,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 608 | 733 | challenge: None, |
| 609 | 734 | conflict_reply: None, |
| 610 | 735 | password: None, |
| 736 | 추가: resource_reply: None, | |
| 611 | 737 | input_closed: false, |
| 612 | 738 | })); |
| 613 | 739 | let wake = Arc::new(Condvar::new()); |
| @@ -668,6 +794,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 668 | 794 | } |
| 669 | 795 | control_wake.notify_all(); |
| 670 | 796 | } |
| 797 | 추가: Message::ResourceReply { | |
| 798 | 추가: challenge_id, | |
| 799 | 추가: scope, | |
| 800 | 추가: allow, | |
| 801 | 추가: } => { | |
| 802 | 추가: if state.phase != 0 | |
| 803 | 추가: || state.challenge != Some(Challenge::Resource(challenge_id, scope)) | |
| 804 | 추가: || state.resource_reply.is_some() | |
| 805 | 추가: { | |
| 806 | 추가: state.fault = Some(ErrorCode::Protocol); | |
| 807 | 추가: } else { | |
| 808 | 추가: state.challenge = None; | |
| 809 | 추가: if !state.cancelled { | |
| 810 | 추가: state.resource_reply = Some(allow); | |
| 811 | 추가: } | |
| 812 | 추가: } | |
| 813 | 추가: control_wake.notify_all(); | |
| 814 | 추가: } | |
| 671 | 815 | Message::Cancel => { |
| 672 | 816 | let status = match state.phase { |
| 673 | 817 | 2 => CancelStatus::Finished, |
| @@ -703,6 +847,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 703 | 847 | wake, |
| 704 | 848 | next_challenge: 0, |
| 705 | 849 | interactive, |
| 850 | 추가: action: start.action.kind(), | |
| 851 | 추가: budget, | |
| 852 | 추가: watchdog: Watchdog::new(), | |
| 706 | 853 | remaining_choice: None, |
| 707 | 854 | parent, |
| 708 | 855 | started: Instant::now(), |
| @@ -733,6 +880,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 733 | 880 | state.challenge = None; |
| 734 | 881 | state.password = None; |
| 735 | 882 | state.conflict_reply = None; |
| 883 | 추가: state.resource_reply = None; | |
| 736 | 884 | if let Some(error) = state.fault.or(error) { |
| 737 | 885 | context.terminal.error = error; |
| 738 | 886 | context.terminal.outcome = if error == ErrorCode::None { |
| @@ -266,7 +266,7 @@ impl Streams { | ||
| 266 | 266 | &self, |
| 267 | 267 | input: &mut std::fs::File, |
| 268 | 268 | data_end: u64, |
| 269 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 269 | 추가: check: &mut impl crate::resources::Monitor, | |
| 270 | 270 | ) -> Result<Vec<(u64, u64)>> { |
| 271 | 271 | let mut at = 32u64 |
| 272 | 272 | .checked_add(self.position as u64) |
| @@ -293,7 +293,7 @@ impl Streams { | ||
| 293 | 293 | input: &mut std::fs::File, |
| 294 | 294 | ranges: &[(u64, u64)], |
| 295 | 295 | output: &mut std::fs::File, |
| 296 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 296 | 추가: check: &mut impl crate::resources::Monitor, | |
| 297 | 297 | ) -> Result<()> { |
| 298 | 298 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 299 | 299 | let total = self.folders.iter().try_fold(0u64, |sum, f| { |
| @@ -301,8 +301,16 @@ impl Streams { | ||
| 301 | 301 | })?; |
| 302 | 302 | crate::space::ensure(output, total)?; |
| 303 | 303 | for (f, (start, size)) in self.folders.iter().zip(ranges) { |
| 304 | 삭제: check()?; | |
| 304 | 추가: check.check()?; | |
| 305 | 305 | let base = output.stream_position().map_err(crate::space::io_error)?; |
| 306 | 추가: check.observe( | |
| 307 | 추가: ResourceUsage { | |
| 308 | 추가: compressed_bytes: Some(*size), | |
| 309 | 추가: ratio_output_bytes: Some(f.size as u64), | |
| 310 | 추가: ..ResourceUsage::default() | |
| 311 | 추가: }, | |
| 312 | 추가: Some(output), | |
| 313 | 추가: )?; | |
| 306 | 314 | input |
| 307 | 315 | .seek(SeekFrom::Start(*start)) |
| 308 | 316 | .map_err(crate::space::io_error)?; |
| @@ -314,15 +322,17 @@ impl Streams { | ||
| 314 | 322 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 315 | 323 | let mut remaining = *size; |
| 316 | 324 | while remaining != 0 { |
| 317 | 삭제: check()?; | |
| 325 | 추가: check.check()?; | |
| 318 | 326 | let n = remaining.min(buffer.len() as u64) as usize; |
| 319 | 327 | input |
| 320 | 328 | .read_exact(&mut buffer[..n]) |
| 321 | 329 | .map_err(|_| ErrorCode::Integrity)?; |
| 330 | 추가: crate::space::ensure(output, n as u64)?; | |
| 322 | 331 | output |
| 323 | 332 | .write_all(&buffer[..n]) |
| 324 | 333 | .map_err(crate::space::io_error)?; |
| 325 | 334 | remaining -= n as u64; |
| 335 | 추가: check.activity()?; | |
| 326 | 336 | } |
| 327 | 337 | } |
| 328 | 338 | [3, 1, 1] | [0x21] => crate::lzma::decode_stream( |
| @@ -370,7 +380,7 @@ fn digest( | ||
| 370 | 380 | file: &mut std::fs::File, |
| 371 | 381 | start: u64, |
| 372 | 382 | size: u64, |
| 373 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 383 | 추가: check: &mut impl crate::resources::Monitor, | |
| 374 | 384 | ) -> Result<u32> { |
| 375 | 385 | use std::io::{Read, Seek, SeekFrom}; |
| 376 | 386 | file.seek(SeekFrom::Start(start)) |
| @@ -379,12 +389,13 @@ fn digest( | ||
| 379 | 389 | let mut remaining = size; |
| 380 | 390 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 381 | 391 | while remaining != 0 { |
| 382 | 삭제: check()?; | |
| 392 | 추가: check.check()?; | |
| 383 | 393 | let n = remaining.min(buffer.len() as u64) as usize; |
| 384 | 394 | file.read_exact(&mut buffer[..n]) |
| 385 | 395 | .map_err(crate::space::io_error)?; |
| 386 | 396 | crc = crc32(crc, &buffer[..n]); |
| 387 | 397 | remaining -= n as u64; |
| 398 | 추가: check.activity()?; | |
| 388 | 399 | } |
| 389 | 400 | Ok(crc) |
| 390 | 401 | } |
| @@ -546,10 +557,10 @@ pub(crate) fn open( | ||
| 546 | 557 | length: u64, |
| 547 | 558 | limits: Limits, |
| 548 | 559 | decode: bool, |
| 549 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 560 | 추가: check: &mut impl crate::resources::Monitor, | |
| 550 | 561 | ) -> Result<crate::streaming::Catalog> { |
| 551 | 562 | use std::io::{Read, Seek, SeekFrom}; |
| 552 | 삭제: check()?; | |
| 563 | 추가: check.check()?; | |
| 553 | 564 | if length > limits.input { |
| 554 | 565 | return Err(ErrorCode::Limit); |
| 555 | 566 | } |
| @@ -650,6 +661,28 @@ pub(crate) fn open( | ||
| 650 | 661 | return Err(ErrorCode::Integrity); |
| 651 | 662 | } |
| 652 | 663 | r.end()?; |
| 664 | 추가: let total = members.iter().try_fold(0u64, |n, m| { | |
| 665 | 추가: n.checked_add(m.entry.size).ok_or(ErrorCode::Limit) | |
| 666 | 추가: })?; | |
| 667 | 추가: let packed = streams | |
| 668 | 추가: .as_ref() | |
| 669 | 추가: .map(|s| { | |
| 670 | 추가: s.packed.iter().try_fold(0u64, |sum, size| { | |
| 671 | 추가: sum.checked_add(*size as u64).ok_or(ErrorCode::Integrity) | |
| 672 | 추가: }) | |
| 673 | 추가: }) | |
| 674 | 추가: .transpose()?; | |
| 675 | 추가: check.observe( | |
| 676 | 추가: ResourceUsage { | |
| 677 | 추가: estimated_bytes: Some(total), | |
| 678 | 추가: estimated_entries: Some(members.len() as u32), | |
| 679 | 추가: compressed_bytes: packed, | |
| 680 | 추가: ratio_output_bytes: Some(total), | |
| 681 | 추가: ..ResourceUsage::default() | |
| 682 | 추가: }, | |
| 683 | 추가: Some(&data), | |
| 684 | 추가: )?; | |
| 685 | 추가: check.activity()?; | |
| 653 | 686 | let mut offsets = vec![0; members.len()]; |
| 654 | 687 | if let Some(streams) = streams { |
| 655 | 688 | if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() { |
| @@ -682,7 +715,7 @@ pub(crate) fn parse( | ||
| 682 | 715 | input: &[u8], |
| 683 | 716 | limits: Limits, |
| 684 | 717 | decode: bool, |
| 685 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 718 | 추가: check: &mut impl crate::resources::Monitor, | |
| 686 | 719 | ) -> Result<Vec<Member>> { |
| 687 | 720 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 688 | 721 | let mut source = crate::spool::temporary()?; |
| @@ -19,7 +19,7 @@ pub(crate) fn ensure(file: &File, bytes: u64) -> Result<()> { | ||
| 19 | 19 | } |
| 20 | 20 | |
| 21 | 21 | #[cfg(all(target_os = "linux", target_pointer_width = "64"))] |
| 22 | 삭제: fn available(file: &File) -> Result<u128> { | |
| 22 | 추가: pub(crate) fn available(file: &File) -> Result<u128> { | |
| 23 | 23 | use std::os::fd::AsRawFd; |
| 24 | 24 | #[repr(C)] |
| 25 | 25 | #[derive(Default)] |
| @@ -48,12 +48,12 @@ fn available(file: &File) -> Result<u128> { | ||
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | #[cfg(all(target_os = "linux", not(target_pointer_width = "64")))] |
| 51 | 삭제: fn available(_: &File) -> Result<u128> { | |
| 51 | 추가: pub(crate) fn available(_: &File) -> Result<u128> { | |
| 52 | 52 | Err(ErrorCode::UnsupportedFeature) |
| 53 | 53 | } |
| 54 | 54 | |
| 55 | 55 | #[cfg(windows)] |
| 56 | 삭제: fn available(file: &File) -> Result<u128> { | |
| 56 | 추가: pub(crate) fn available(file: &File) -> Result<u128> { | |
| 57 | 57 | use std::{ |
| 58 | 58 | ffi::OsString, |
| 59 | 59 | os::windows::{ |
| @@ -114,11 +114,11 @@ impl Snapshot { | ||
| 114 | 114 | pub(crate) fn capture( |
| 115 | 115 | source: &mut File, |
| 116 | 116 | limit: u64, |
| 117 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 117 | 추가: check: &mut impl crate::resources::Monitor, | |
| 118 | 118 | ) -> Result<Self> { |
| 119 | 119 | Self::capture_reporting(source, limit, &mut |step| match step { |
| 120 | 삭제: Step::Check => check(), | |
| 121 | 삭제: Step::Read { .. } => Ok(()), | |
| 120 | 추가: Step::Check => check.check(), | |
| 121 | 추가: Step::Read { .. } => check.activity(), | |
| 122 | 122 | }) |
| 123 | 123 | } |
| 124 | 124 | fn capture_reporting( |
| @@ -52,7 +52,7 @@ impl Catalog { | ||
| 52 | 52 | limits: Limits, |
| 53 | 53 | decode: bool, |
| 54 | 54 | password: Option<&[u8]>, |
| 55 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 55 | 추가: check: &mut impl crate::resources::Monitor, | |
| 56 | 56 | ) -> Result<Self> { |
| 57 | 57 | let mut magic = [0; 6]; |
| 58 | 58 | let n = len.min(6) as usize; |
| @@ -121,7 +121,7 @@ fn tar( | ||
| 121 | 121 | len: u64, |
| 122 | 122 | limits: Limits, |
| 123 | 123 | format: Format, |
| 124 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 124 | 추가: check: &mut impl crate::resources::Monitor, | |
| 125 | 125 | ) -> Result<Catalog> { |
| 126 | 126 | let mut cursor = 0u64; |
| 127 | 127 | let mut total = 0u64; |
| @@ -129,7 +129,7 @@ fn tar( | ||
| 129 | 129 | let mut offsets = Vec::new(); |
| 130 | 130 | let mut metadata = MetadataBudget::default(); |
| 131 | 131 | loop { |
| 132 | 삭제: check()?; | |
| 132 | 추가: check.check()?; | |
| 133 | 133 | let mut header = [0; 512]; |
| 134 | 134 | if add(cursor, 512)? > len { |
| 135 | 135 | return Err(ErrorCode::Integrity); |
| @@ -142,13 +142,14 @@ fn tar( | ||
| 142 | 142 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 143 | 143 | let mut remaining = len - cursor - 512; |
| 144 | 144 | while remaining != 0 { |
| 145 | 삭제: check()?; | |
| 145 | 추가: check.check()?; | |
| 146 | 146 | let n = remaining.min(CHUNK as u64) as usize; |
| 147 | 147 | io(data.read_exact(&mut buffer[..n]))?; |
| 148 | 148 | if buffer[..n].iter().any(|b| *b != 0) { |
| 149 | 149 | return Err(ErrorCode::Integrity); |
| 150 | 150 | } |
| 151 | 151 | remaining -= n as u64; |
| 152 | 추가: check.activity()?; | |
| 152 | 153 | } |
| 153 | 154 | break; |
| 154 | 155 | } |
| @@ -193,6 +194,15 @@ fn tar( | ||
| 193 | 194 | .checked_add(size) |
| 194 | 195 | .filter(|n| *n <= limits.output) |
| 195 | 196 | .ok_or(ErrorCode::Limit)?; |
| 197 | 추가: check.observe( | |
| 198 | 추가: ResourceUsage { | |
| 199 | 추가: estimated_bytes: Some(total), | |
| 200 | 추가: actual_entries: Some(members.len() as u32 + 1), | |
| 201 | 추가: ..ResourceUsage::default() | |
| 202 | 추가: }, | |
| 203 | 추가: Some(&data), | |
| 204 | 추가: )?; | |
| 205 | 추가: check.activity()?; | |
| 196 | 206 | let start = add(cursor, 512)?; |
| 197 | 207 | cursor = add( |
| 198 | 208 | start, |
| @@ -232,8 +242,9 @@ fn inflate( | ||
| 232 | 242 | gzip: bool, |
| 233 | 243 | limit: u64, |
| 234 | 244 | output: &mut File, |
| 235 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 245 | 추가: check: &mut impl crate::resources::Monitor, | |
| 236 | 246 | ) -> Result<(u64, u32)> { |
| 247 | 추가: let base = io(output.stream_position())?; | |
| 237 | 248 | let mut remaining = length; |
| 238 | 249 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 239 | 250 | let mut plain = Zeroizing::new([0; CHUNK]); |
| @@ -244,7 +255,7 @@ fn inflate( | ||
| 244 | 255 | loop { |
| 245 | 256 | let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); |
| 246 | 257 | loop { |
| 247 | 삭제: check()?; | |
| 258 | 추가: check.check()?; | |
| 248 | 259 | if used == have && remaining != 0 { |
| 249 | 260 | have = input |
| 250 | 261 | .read(&mut buffer[..remaining.min(CHUNK as u64) as usize]) |
| @@ -266,6 +277,18 @@ fn inflate( | ||
| 266 | 277 | .checked_add(n as u64) |
| 267 | 278 | .filter(|n| *n <= limit) |
| 268 | 279 | .ok_or(ErrorCode::Limit)?; |
| 280 | 추가: check.observe( | |
| 281 | 추가: ResourceUsage { | |
| 282 | 추가: actual_bytes: Some(base.checked_add(total).ok_or(ErrorCode::Limit)?), | |
| 283 | 추가: compressed_bytes: Some(length), | |
| 284 | 추가: ratio_output_bytes: Some(total), | |
| 285 | 추가: ..ResourceUsage::default() | |
| 286 | 추가: }, | |
| 287 | 추가: Some(output), | |
| 288 | 추가: )?; | |
| 289 | 추가: if n != 0 { | |
| 290 | 추가: check.activity()?; | |
| 291 | 추가: } | |
| 269 | 292 | crc = crc32(crc, &plain[..n]); |
| 270 | 293 | crate::space::ensure(output, n as u64)?; |
| 271 | 294 | io(output.write_all(&plain[..n]))?; |
| @@ -398,7 +421,7 @@ fn zip( | ||
| 398 | 421 | limits: Limits, |
| 399 | 422 | decode: bool, |
| 400 | 423 | password: Option<&[u8]>, |
| 401 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 424 | 추가: check: &mut impl crate::resources::Monitor, | |
| 402 | 425 | ) -> Result<Catalog> { |
| 403 | 426 | if len < 22 { |
| 404 | 427 | return Err(ErrorCode::Integrity); |
| @@ -463,6 +486,13 @@ fn zip( | ||
| 463 | 486 | if count > limits.entries as u64 { |
| 464 | 487 | return Err(ErrorCode::Limit); |
| 465 | 488 | } |
| 489 | 추가: check.observe( | |
| 490 | 추가: ResourceUsage { | |
| 491 | 추가: estimated_entries: Some(count as u32), | |
| 492 | 추가: ..ResourceUsage::default() | |
| 493 | 추가: }, | |
| 494 | 추가: Some(source), | |
| 495 | 추가: )?; | |
| 466 | 496 | if add(central, central_size)? != central_end { |
| 467 | 497 | return Err(ErrorCode::Integrity); |
| 468 | 498 | } |
| @@ -473,7 +503,7 @@ fn zip( | ||
| 473 | 503 | let mut packed = Vec::new(); |
| 474 | 504 | let mut spans = Vec::new(); |
| 475 | 505 | for id in 0..count { |
| 476 | 삭제: check()?; | |
| 506 | 추가: check.check()?; | |
| 477 | 507 | if add(cursor, 46)? > central_end { |
| 478 | 508 | return Err(ErrorCode::Integrity); |
| 479 | 509 | } |
| @@ -532,6 +562,17 @@ fn zip( | ||
| 532 | 562 | .checked_add(size) |
| 533 | 563 | .filter(|n| *n <= limits.output) |
| 534 | 564 | .ok_or(ErrorCode::Limit)?; |
| 565 | 추가: check.observe( | |
| 566 | 추가: ResourceUsage { | |
| 567 | 추가: estimated_bytes: Some(total), | |
| 568 | 추가: estimated_entries: Some(count as u32), | |
| 569 | 추가: compressed_bytes: Some(compressed - overhead), | |
| 570 | 추가: ratio_output_bytes: Some(size), | |
| 571 | 추가: ..ResourceUsage::default() | |
| 572 | 추가: }, | |
| 573 | 추가: Some(source), | |
| 574 | 추가: )?; | |
| 575 | 추가: check.activity()?; | |
| 535 | 576 | let mode = u32at(&h, 38) >> 16; |
| 536 | 577 | let kind = match mode & 0xf000 { |
| 537 | 578 | 0xa000 => EntryKind::Link, |
| @@ -654,7 +695,7 @@ fn zip( | ||
| 654 | 695 | } |
| 655 | 696 | let mut offsets = Vec::new(); |
| 656 | 697 | for (member, packed) in members.iter().zip(packed) { |
| 657 | 삭제: check()?; | |
| 698 | 추가: check.check()?; | |
| 658 | 699 | offsets.push(io(data.stream_position())?); |
| 659 | 700 | if !decode { |
| 660 | 701 | continue; |
| @@ -691,7 +732,7 @@ fn zip( | ||
| 691 | 732 | let mut total = 0u64; |
| 692 | 733 | let mut crc = 0; |
| 693 | 734 | loop { |
| 694 | 삭제: check()?; | |
| 735 | 추가: check.check()?; | |
| 695 | 736 | let n = io(reader.read(&mut buffer[..]))?; |
| 696 | 737 | if n == 0 { |
| 697 | 738 | break; |
| @@ -700,6 +741,8 @@ fn zip( | ||
| 700 | 741 | .checked_add(n as u64) |
| 701 | 742 | .filter(|n| *n <= member.entry.size) |
| 702 | 743 | .ok_or(ErrorCode::Integrity)?; |
| 744 | 추가: check.activity()?; | |
| 745 | 추가: crate::space::ensure(&data, n as u64)?; | |
| 703 | 746 | crc = crc32(crc, &buffer[..n]); |
| 704 | 747 | io(data.write_all(&buffer[..n]))?; |
| 705 | 748 | } |
| @@ -158,6 +158,25 @@ structure!(ListId { | ||
| 158 | 158 | }); |
| 159 | 159 | structure!(Source { path, archive_name }); |
| 160 | 160 | structure!(Start { action, limits }); |
| 161 | 추가: structure!(GuardedStart { | |
| 162 | 추가: start, | |
| 163 | 추가: ceiling, | |
| 164 | 추가: interactive | |
| 165 | 추가: }); | |
| 166 | 추가: structure!(ResourceScope { | |
| 167 | 추가: output, | |
| 168 | 추가: entries, | |
| 169 | 추가: ratio | |
| 170 | 추가: }); | |
| 171 | 추가: structure!(ResourceUsage { | |
| 172 | 추가: estimated_bytes, | |
| 173 | 추가: actual_bytes, | |
| 174 | 추가: estimated_entries, | |
| 175 | 추가: actual_entries, | |
| 176 | 추가: compressed_bytes, | |
| 177 | 추가: ratio_output_bytes, | |
| 178 | 추가: available_bytes | |
| 179 | 추가: }); | |
| 161 | 180 | structure!(Entry { |
| 162 | 181 | entry_id, |
| 163 | 182 | name, |
| @@ -341,6 +360,39 @@ impl Message { | ||
| 341 | 360 | apply_to_remaining.enc(&mut e)?; |
| 342 | 361 | 5 |
| 343 | 362 | } |
| 363 | 추가: Self::StartGuarded(v) => { | |
| 364 | 추가: if !v.valid() { | |
| 365 | 추가: return Err(invalid()); | |
| 366 | 추가: } | |
| 367 | 추가: v.enc(&mut e)?; | |
| 368 | 추가: 6 | |
| 369 | 추가: } | |
| 370 | 추가: Self::ResourceReply { | |
| 371 | 추가: challenge_id, | |
| 372 | 추가: scope, | |
| 373 | 추가: allow, | |
| 374 | 추가: } => { | |
| 375 | 추가: challenge_id.enc(&mut e)?; | |
| 376 | 추가: scope.enc(&mut e)?; | |
| 377 | 추가: allow.enc(&mut e)?; | |
| 378 | 추가: 7 | |
| 379 | 추가: } | |
| 380 | 추가: Self::ResourceRequired { | |
| 381 | 추가: challenge_id, | |
| 382 | 추가: action, | |
| 383 | 추가: scope, | |
| 384 | 추가: usage, | |
| 385 | 추가: soft_limits, | |
| 386 | 추가: ceiling, | |
| 387 | 추가: } => { | |
| 388 | 추가: challenge_id.enc(&mut e)?; | |
| 389 | 추가: action.enc(&mut e)?; | |
| 390 | 추가: scope.enc(&mut e)?; | |
| 391 | 추가: usage.enc(&mut e)?; | |
| 392 | 추가: soft_limits.enc(&mut e)?; | |
| 393 | 추가: ceiling.enc(&mut e)?; | |
| 394 | 추가: 110 | |
| 395 | 추가: } | |
| 344 | 396 | Self::Accepted { action, encryption } => { |
| 345 | 397 | action.enc(&mut e)?; |
| 346 | 398 | encryption.enc(&mut e)?; |
| @@ -460,6 +512,26 @@ impl Message { | ||
| 460 | 512 | choice: Wire::dec(&mut d)?, |
| 461 | 513 | apply_to_remaining: Wire::dec(&mut d)?, |
| 462 | 514 | }, |
| 515 | 추가: 6 => { | |
| 516 | 추가: let start = GuardedStart::dec(&mut d)?; | |
| 517 | 추가: if !start.valid() { | |
| 518 | 추가: return Err(invalid()); | |
| 519 | 추가: } | |
| 520 | 추가: Self::StartGuarded(start) | |
| 521 | 추가: } | |
| 522 | 추가: 7 => Self::ResourceReply { | |
| 523 | 추가: challenge_id: Wire::dec(&mut d)?, | |
| 524 | 추가: scope: Wire::dec(&mut d)?, | |
| 525 | 추가: allow: Wire::dec(&mut d)?, | |
| 526 | 추가: }, | |
| 527 | 추가: 110 => Self::ResourceRequired { | |
| 528 | 추가: challenge_id: Wire::dec(&mut d)?, | |
| 529 | 추가: action: Wire::dec(&mut d)?, | |
| 530 | 추가: scope: Wire::dec(&mut d)?, | |
| 531 | 추가: usage: Wire::dec(&mut d)?, | |
| 532 | 추가: soft_limits: Wire::dec(&mut d)?, | |
| 533 | 추가: ceiling: Wire::dec(&mut d)?, | |
| 534 | 추가: }, | |
| 463 | 535 | 100 => Self::Accepted { |
| 464 | 536 | action: Wire::dec(&mut d)?, |
| 465 | 537 | encryption: Wire::dec(&mut d)?, |
| @@ -0,0 +1,554 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: use std::{io::Read, process::Child, sync::mpsc, time::Duration}; | |
| 3 | 추가: | |
| 4 | 추가: struct Running(Child); | |
| 5 | 추가: impl Drop for Running { | |
| 6 | 추가: fn drop(&mut self) { | |
| 7 | 추가: let _ = self.0.kill(); | |
| 8 | 추가: let _ = self.0.wait(); | |
| 9 | 추가: } | |
| 10 | 추가: } | |
| 11 | 추가: fn run( | |
| 12 | 추가: s: &Scratch, | |
| 13 | 추가: start: GuardedStart, | |
| 14 | 추가: respond: impl FnMut(&Message) -> Option<Vec<Message>>, | |
| 15 | 추가: ) -> Vec<Message> { | |
| 16 | 추가: run_fault(s, start, None, respond) | |
| 17 | 추가: } | |
| 18 | 추가: fn run_fault( | |
| 19 | 추가: s: &Scratch, | |
| 20 | 추가: start: GuardedStart, | |
| 21 | 추가: fault: Option<&str>, | |
| 22 | 추가: mut respond: impl FnMut(&Message) -> Option<Vec<Message>>, | |
| 23 | 추가: ) -> Vec<Message> { | |
| 24 | 추가: let mut command = s.worker(); | |
| 25 | 추가: #[cfg(target_os = "linux")] | |
| 26 | 추가: if let Some(fault) = fault { | |
| 27 | 추가: let shim = s.0.join("io_fault.so"); | |
| 28 | 추가: assert!( | |
| 29 | 추가: Command::new("cc") | |
| 30 | 추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"]) | |
| 31 | 추가: .arg( | |
| 32 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 33 | 추가: .join("../../tests/rust-archive-worker/io_fault.c") | |
| 34 | 추가: ) | |
| 35 | 추가: .args(["-ldl", "-o"]) | |
| 36 | 추가: .arg(&shim) | |
| 37 | 추가: .status() | |
| 38 | 추가: .unwrap() | |
| 39 | 추가: .success() | |
| 40 | 추가: ); | |
| 41 | 추가: command | |
| 42 | 추가: .env("LD_PRELOAD", shim) | |
| 43 | 추가: .env("ZIPELO_TEST_FAULT", fault) | |
| 44 | 추가: .env("ZIPELO_TEST_MARKER", s.0.join("marker")); | |
| 45 | 추가: } | |
| 46 | 추가: #[cfg(not(target_os = "linux"))] | |
| 47 | 추가: assert!(fault.is_none()); | |
| 48 | 추가: let mut child = Running( | |
| 49 | 추가: command | |
| 50 | 추가: .stdin(Stdio::piped()) | |
| 51 | 추가: .stdout(Stdio::piped()) | |
| 52 | 추가: .stderr(Stdio::piped()) | |
| 53 | 추가: .spawn() | |
| 54 | 추가: .unwrap(), | |
| 55 | 추가: ); | |
| 56 | 추가: let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17)); | |
| 57 | 추가: writer | |
| 58 | 추가: .as_mut() | |
| 59 | 추가: .unwrap() | |
| 60 | 추가: .send(&Message::StartGuarded(start)) | |
| 61 | 추가: .unwrap(); | |
| 62 | 추가: let stdout = child.0.stdout.take().unwrap(); | |
| 63 | 추가: let mut stderr = child.0.stderr.take().unwrap(); | |
| 64 | 추가: let (send, receive) = mpsc::channel(); | |
| 65 | 추가: let reader = std::thread::spawn(move || { | |
| 66 | 추가: let mut reader = Reader::new(stdout); | |
| 67 | 추가: loop { | |
| 68 | 추가: let frame = reader.read(); | |
| 69 | 추가: let done = !matches!(frame, Ok(Some(_))); | |
| 70 | 추가: if send.send(frame).is_err() || done { | |
| 71 | 추가: break; | |
| 72 | 추가: } | |
| 73 | 추가: } | |
| 74 | 추가: }); | |
| 75 | 추가: let mut events = Vec::new(); | |
| 76 | 추가: loop { | |
| 77 | 추가: let Some((job, _, event)) = receive | |
| 78 | 추가: .recv_timeout(Duration::from_secs(20)) | |
| 79 | 추가: .expect("worker timeout") | |
| 80 | 추가: .unwrap() | |
| 81 | 추가: else { | |
| 82 | 추가: break; | |
| 83 | 추가: }; | |
| 84 | 추가: assert_eq!(job, 17); | |
| 85 | 추가: if let Some(messages) = respond(&event) { | |
| 86 | 추가: if messages.is_empty() { | |
| 87 | 추가: writer = None; | |
| 88 | 추가: } else { | |
| 89 | 추가: for message in messages { | |
| 90 | 추가: writer.as_mut().unwrap().send(&message).unwrap(); | |
| 91 | 추가: } | |
| 92 | 추가: } | |
| 93 | 추가: } | |
| 94 | 추가: let done = matches!(event, Message::Terminal(_)); | |
| 95 | 추가: events.push(event); | |
| 96 | 추가: if done { | |
| 97 | 추가: writer = None; | |
| 98 | 추가: } | |
| 99 | 추가: } | |
| 100 | 추가: assert!(child.0.wait().unwrap().success(), "{events:?}"); | |
| 101 | 추가: let mut errors = Vec::new(); | |
| 102 | 추가: stderr.read_to_end(&mut errors).unwrap(); | |
| 103 | 추가: assert!(errors.is_empty(), "{errors:?}"); | |
| 104 | 추가: reader.join().unwrap(); | |
| 105 | 추가: assert!(matches!(events.last(), Some(Message::Terminal(_)))); | |
| 106 | 추가: events | |
| 107 | 추가: } | |
| 108 | 추가: fn request(s: &Scratch, output: u64, ceiling: u64) -> GuardedStart { | |
| 109 | 추가: GuardedStart { | |
| 110 | 추가: start: Start { | |
| 111 | 추가: action: Action::Extract { | |
| 112 | 추가: archive: s.path("input"), | |
| 113 | 추가: destination: s.path("output"), | |
| 114 | 추가: selection: Selection::All, | |
| 115 | 추가: list_id: None, | |
| 116 | 추가: gzip_output_name: None, | |
| 117 | 추가: }, | |
| 118 | 추가: limits: Limits { | |
| 119 | 추가: output, | |
| 120 | 추가: ..Limits::default() | |
| 121 | 추가: }, | |
| 122 | 추가: }, | |
| 123 | 추가: ceiling: Limits { | |
| 124 | 추가: output: ceiling, | |
| 125 | 추가: entries: 200_000, | |
| 126 | 추가: ..Limits::default() | |
| 127 | 추가: }, | |
| 128 | 추가: interactive: false, | |
| 129 | 추가: } | |
| 130 | 추가: } | |
| 131 | 추가: fn setup() -> Scratch { | |
| 132 | 추가: let s = Scratch::new(); | |
| 133 | 추가: fs::write(s.0.join("input"), include_bytes!("fixtures/deflate.zip")).unwrap(); | |
| 134 | 추가: fs::create_dir(s.0.join("output")).unwrap(); | |
| 135 | 추가: #[cfg(unix)] | |
| 136 | 추가: { | |
| 137 | 추가: use std::os::unix::fs::PermissionsExt; | |
| 138 | 추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap(); | |
| 139 | 추가: } | |
| 140 | 추가: s | |
| 141 | 추가: } | |
| 142 | 추가: fn approve(event: &Message) -> Option<Vec<Message>> { | |
| 143 | 추가: if let Message::ResourceRequired { | |
| 144 | 추가: challenge_id, | |
| 145 | 추가: scope, | |
| 146 | 추가: .. | |
| 147 | 추가: } = event | |
| 148 | 추가: { | |
| 149 | 추가: Some(vec![Message::ResourceReply { | |
| 150 | 추가: challenge_id: *challenge_id, | |
| 151 | 추가: scope: *scope, | |
| 152 | 추가: allow: true, | |
| 153 | 추가: }]) | |
| 154 | 추가: } else { | |
| 155 | 추가: None | |
| 156 | 추가: } | |
| 157 | 추가: } | |
| 158 | 추가: #[test] | |
| 159 | 추가: fn scaled_output_boundaries_and_approval() { | |
| 160 | 추가: for limit in [ | |
| 161 | 추가: PAYLOAD.len() as u64 + 1, | |
| 162 | 추가: PAYLOAD.len() as u64, | |
| 163 | 추가: PAYLOAD.len() as u64 - 1, | |
| 164 | 추가: ] { | |
| 165 | 추가: let s = setup(); | |
| 166 | 추가: let events = run(&s, request(&s, limit, 64), approve); | |
| 167 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 168 | 추가: assert_eq!( | |
| 169 | 추가: events | |
| 170 | 추가: .iter() | |
| 171 | 추가: .filter(|e| matches!(e, Message::ResourceRequired { .. })) | |
| 172 | 추가: .count(), | |
| 173 | 추가: 1 | |
| 174 | 추가: ); | |
| 175 | 추가: assert_eq!( | |
| 176 | 추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(), | |
| 177 | 추가: PAYLOAD | |
| 178 | 추가: ); | |
| 179 | 추가: } | |
| 180 | 추가: } | |
| 181 | 추가: #[test] | |
| 182 | 추가: fn decline_cancel_and_eof_publish_nothing() { | |
| 183 | 추가: for mode in 0..3 { | |
| 184 | 추가: let s = setup(); | |
| 185 | 추가: let events = run(&s, request(&s, 16, 64), |event| { | |
| 186 | 추가: if let Message::ResourceRequired { | |
| 187 | 추가: challenge_id, | |
| 188 | 추가: scope, | |
| 189 | 추가: usage, | |
| 190 | 추가: .. | |
| 191 | 추가: } = event | |
| 192 | 추가: { | |
| 193 | 추가: assert_eq!(usage.estimated_bytes, None); | |
| 194 | 추가: assert_eq!(usage.actual_bytes, None); | |
| 195 | 추가: assert!(usage.available_bytes.is_some()); | |
| 196 | 추가: Some(match mode { | |
| 197 | 추가: 0 => vec![Message::ResourceReply { | |
| 198 | 추가: challenge_id: *challenge_id, | |
| 199 | 추가: scope: *scope, | |
| 200 | 추가: allow: false, | |
| 201 | 추가: }], | |
| 202 | 추가: 1 => vec![Message::Cancel], | |
| 203 | 추가: _ => vec![], | |
| 204 | 추가: }) | |
| 205 | 추가: } else { | |
| 206 | 추가: None | |
| 207 | 추가: } | |
| 208 | 추가: }); | |
| 209 | 추가: assert_eq!( | |
| 210 | 추가: terminal(&events).outcome, | |
| 211 | 추가: if mode == 2 { | |
| 212 | 추가: Outcome::Failed | |
| 213 | 추가: } else { | |
| 214 | 추가: Outcome::Cancelled | |
| 215 | 추가: }, | |
| 216 | 추가: "{events:?}" | |
| 217 | 추가: ); | |
| 218 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 219 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 220 | 추가: if mode == 1 { | |
| 221 | 추가: assert!(events.iter().any(|e| matches!( | |
| 222 | 추가: e, | |
| 223 | 추가: Message::CancelAck { | |
| 224 | 추가: status: CancelStatus::Requested, | |
| 225 | 추가: .. | |
| 226 | 추가: } | |
| 227 | 추가: ))); | |
| 228 | 추가: } | |
| 229 | 추가: } | |
| 230 | 추가: } | |
| 231 | 추가: #[test] | |
| 232 | 추가: fn stale_duplicate_wrong_scope_and_premature_replies_are_rejected() { | |
| 233 | 추가: for mode in 0..4 { | |
| 234 | 추가: let s = setup(); | |
| 235 | 추가: let events = run(&s, request(&s, 16, 64), |event| { | |
| 236 | 추가: if mode == 3 && matches!(event, Message::Accepted { .. }) { | |
| 237 | 추가: return Some(vec![Message::ResourceReply { | |
| 238 | 추가: challenge_id: 99, | |
| 239 | 추가: scope: ResourceScope::default(), | |
| 240 | 추가: allow: true, | |
| 241 | 추가: }]); | |
| 242 | 추가: } | |
| 243 | 추가: if let Message::ResourceRequired { | |
| 244 | 추가: challenge_id, | |
| 245 | 추가: scope, | |
| 246 | 추가: .. | |
| 247 | 추가: } = event | |
| 248 | 추가: { | |
| 249 | 추가: let reply = |id, scope| Message::ResourceReply { | |
| 250 | 추가: challenge_id: id, | |
| 251 | 추가: scope, | |
| 252 | 추가: allow: true, | |
| 253 | 추가: }; | |
| 254 | 추가: Some(match mode { | |
| 255 | 추가: 0 => vec![reply(challenge_id + 1, *scope)], | |
| 256 | 추가: 1 => vec![reply(*challenge_id, ResourceScope::default())], | |
| 257 | 추가: 2 => vec![reply(*challenge_id, *scope), reply(*challenge_id, *scope)], | |
| 258 | 추가: _ => vec![], | |
| 259 | 추가: }) | |
| 260 | 추가: } else { | |
| 261 | 추가: None | |
| 262 | 추가: } | |
| 263 | 추가: }); | |
| 264 | 추가: assert_eq!( | |
| 265 | 추가: terminal(&events).error, | |
| 266 | 추가: ErrorCode::Protocol, | |
| 267 | 추가: "{mode}: {events:?}" | |
| 268 | 추가: ); | |
| 269 | 추가: assert_eq!(terminal(&events).publication, Publication::None); | |
| 270 | 추가: } | |
| 271 | 추가: } | |
| 272 | 추가: #[test] | |
| 273 | 추가: fn ceiling_bytes_and_entries_cannot_be_approved_away() { | |
| 274 | 추가: for entries in [false, true] { | |
| 275 | 추가: let s = setup(); | |
| 276 | 추가: let mut start = request(&s, 1, 16); | |
| 277 | 추가: if entries { | |
| 278 | 추가: start.start.limits.output = 64; | |
| 279 | 추가: start.ceiling.output = 64; | |
| 280 | 추가: start.start.limits.entries = 1; | |
| 281 | 추가: start.ceiling.entries = 2; | |
| 282 | 추가: let members = (0..3) | |
| 283 | 추가: .map(|id| archive::Member { | |
| 284 | 추가: entry: Entry { | |
| 285 | 추가: entry_id: id, | |
| 286 | 추가: name: format!("empty{id}"), | |
| 287 | 추가: kind: EntryKind::File, | |
| 288 | 추가: size: 0, | |
| 289 | 추가: compressed_size: 0, | |
| 290 | 추가: encrypted: false, | |
| 291 | 추가: }, | |
| 292 | 추가: data: Vec::new(), | |
| 293 | 추가: }) | |
| 294 | 추가: .collect::<Vec<_>>(); | |
| 295 | 추가: let zip = | |
| 296 | 추가: archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())) | |
| 297 | 추가: .unwrap(); | |
| 298 | 추가: fs::write(s.0.join("input"), zip).unwrap(); | |
| 299 | 추가: } | |
| 300 | 추가: let mut approved = false; | |
| 301 | 추가: let events = run(&s, start, |event| { | |
| 302 | 추가: if matches!(event, Message::ResourceRequired { .. }) { | |
| 303 | 추가: approved = true; | |
| 304 | 추가: } | |
| 305 | 추가: approve(event) | |
| 306 | 추가: }); | |
| 307 | 추가: assert!(approved); | |
| 308 | 추가: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); | |
| 309 | 추가: assert_eq!(terminal(&events).created_count, 0); | |
| 310 | 추가: } | |
| 311 | 추가: } | |
| 312 | 추가: #[test] | |
| 313 | 추가: fn entries_have_a_separate_approval() { | |
| 314 | 추가: let s = setup(); | |
| 315 | 추가: let mut start = request(&s, 64, 64); | |
| 316 | 추가: start.start.limits.entries = 1; | |
| 317 | 추가: start.ceiling.entries = 3; | |
| 318 | 추가: let events = run(&s, start, |event| { | |
| 319 | 추가: if let Message::ResourceRequired { scope, .. } = event { | |
| 320 | 추가: assert!(scope.entries); | |
| 321 | 추가: assert!(!scope.output); | |
| 322 | 추가: } | |
| 323 | 추가: approve(event) | |
| 324 | 추가: }); | |
| 325 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 326 | 추가: } | |
| 327 | 추가: #[test] | |
| 328 | 추가: fn resource_then_password_then_conflict_use_distinct_questions() { | |
| 329 | 추가: let s = setup(); | |
| 330 | 추가: fs::write( | |
| 331 | 추가: s.0.join("input"), | |
| 332 | 추가: include_bytes!("fixtures/aes2-deflate.zip"), | |
| 333 | 추가: ) | |
| 334 | 추가: .unwrap(); | |
| 335 | 추가: fs::create_dir_all(s.0.join("output/folder")).unwrap(); | |
| 336 | 추가: fs::write(s.0.join("output/payload.bin"), b"old").unwrap(); | |
| 337 | 추가: let mut start = request(&s, 16, 8192); | |
| 338 | 추가: start.interactive = true; | |
| 339 | 추가: let mut ids = Vec::new(); | |
| 340 | 추가: let events = run(&s, start, |event| match event { | |
| 341 | 추가: Message::ResourceRequired { challenge_id, .. } => { | |
| 342 | 추가: ids.push(*challenge_id); | |
| 343 | 추가: approve(event) | |
| 344 | 추가: } | |
| 345 | 추가: Message::PasswordRequired { challenge_id, .. } => { | |
| 346 | 추가: ids.push(*challenge_id); | |
| 347 | 추가: Some(vec![Message::Password { | |
| 348 | 추가: challenge_id: *challenge_id, | |
| 349 | 추가: secret: Secret(TEST_PASSWORD.to_vec()), | |
| 350 | 추가: }]) | |
| 351 | 추가: } | |
| 352 | 추가: Message::ConflictRequired { challenge_id, .. } => { | |
| 353 | 추가: ids.push(*challenge_id); | |
| 354 | 추가: Some(vec![Message::ConflictReply { | |
| 355 | 추가: challenge_id: *challenge_id, | |
| 356 | 추가: choice: ConflictChoice::Overwrite, | |
| 357 | 추가: apply_to_remaining: false, | |
| 358 | 추가: }]) | |
| 359 | 추가: } | |
| 360 | 추가: _ => None, | |
| 361 | 추가: }); | |
| 362 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 363 | 추가: assert!(ids.len() >= 3, "{events:?}"); | |
| 364 | 추가: assert!(ids.windows(2).all(|w| w[0] < w[1])); | |
| 365 | 추가: } | |
| 366 | 추가: #[test] | |
| 367 | 추가: fn create_source_total_is_approved_before_password() { | |
| 368 | 추가: let s = setup(); | |
| 369 | 추가: fs::write(s.0.join("source"), b"12345678").unwrap(); | |
| 370 | 추가: let mut start = request(&s, 7, 8); | |
| 371 | 추가: start.start.action = Action::CreateZip { | |
| 372 | 추가: sources: vec![Source { | |
| 373 | 추가: path: s.path("source"), | |
| 374 | 추가: archive_name: "source".into(), | |
| 375 | 추가: }], | |
| 376 | 추가: output_file: s.path("new.zip"), | |
| 377 | 추가: method: Method::Store, | |
| 378 | 추가: encryption: Encryption::Aes256, | |
| 379 | 추가: }; | |
| 380 | 추가: let mut approved = false; | |
| 381 | 추가: let events = run(&s, start, |event| match event { | |
| 382 | 추가: Message::ResourceRequired { action, .. } => { | |
| 383 | 추가: assert_eq!(*action, ActionKind::CreateZip); | |
| 384 | 추가: approved = true; | |
| 385 | 추가: approve(event) | |
| 386 | 추가: } | |
| 387 | 추가: Message::PasswordRequired { challenge_id, .. } => { | |
| 388 | 추가: assert!(approved); | |
| 389 | 추가: Some(vec![Message::Password { | |
| 390 | 추가: challenge_id: *challenge_id, | |
| 391 | 추가: secret: Secret(b"secret".to_vec()), | |
| 392 | 추가: }]) | |
| 393 | 추가: } | |
| 394 | 추가: _ => None, | |
| 395 | 추가: }); | |
| 396 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 397 | 추가: assert!(s.0.join("new.zip").exists()); | |
| 398 | 추가: } | |
| 399 | 추가: #[test] | |
| 400 | 추가: fn guarded_wire_round_trip_and_invalid_ceiling() { | |
| 401 | 추가: let s = setup(); | |
| 402 | 추가: let start = request(&s, 16, 64); | |
| 403 | 추가: let mut bytes = Vec::new(); | |
| 404 | 추가: Writer::new(&mut bytes, 17) | |
| 405 | 추가: .send(&Message::StartGuarded(start.clone())) | |
| 406 | 추가: .unwrap(); | |
| 407 | 추가: assert_eq!(&bytes[6..8], &6u16.to_le_bytes()); | |
| 408 | 추가: match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 { | |
| 409 | 추가: Message::StartGuarded(decoded) => assert_eq!(decoded, start), | |
| 410 | 추가: other => panic!("{other:?}"), | |
| 411 | 추가: } | |
| 412 | 추가: let mut invalid = start; | |
| 413 | 추가: invalid.ceiling.output = 64 * 1024 * 1024 * 1024 + 1; | |
| 414 | 추가: assert!(!invalid.valid()); | |
| 415 | 추가: assert!( | |
| 416 | 추가: Writer::new(Vec::new(), 17) | |
| 417 | 추가: .send(&Message::StartGuarded(invalid)) | |
| 418 | 추가: .is_err() | |
| 419 | 추가: ); | |
| 420 | 추가: let mut reply = Vec::new(); | |
| 421 | 추가: Writer::new(&mut reply, 17) | |
| 422 | 추가: .send(&Message::ResourceReply { | |
| 423 | 추가: challenge_id: 4, | |
| 424 | 추가: scope: ResourceScope { | |
| 425 | 추가: ratio: true, | |
| 426 | 추가: ..ResourceScope::default() | |
| 427 | 추가: }, | |
| 428 | 추가: allow: true, | |
| 429 | 추가: }) | |
| 430 | 추가: .unwrap(); | |
| 431 | 추가: assert_eq!(&reply[6..8], &7u16.to_le_bytes()); | |
| 432 | 추가: reply[43] = 2; | |
| 433 | 추가: assert!(Reader::new(reply.as_slice()).read().is_err()); | |
| 434 | 추가: } | |
| 435 | 추가: | |
| 436 | 추가: fn generate(s: &Scratch, case: &str) { | |
| 437 | 추가: let result = Command::new("python3") | |
| 438 | 추가: .arg( | |
| 439 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 440 | 추가: .join("../../tests/rust-archive-worker/guarded_cases.py"), | |
| 441 | 추가: ) | |
| 442 | 추가: .arg(&s.0) | |
| 443 | 추가: .arg(case) | |
| 444 | 추가: .output() | |
| 445 | 추가: .unwrap(); | |
| 446 | 추가: assert!( | |
| 447 | 추가: result.status.success(), | |
| 448 | 추가: "{}", | |
| 449 | 추가: String::from_utf8_lossy(&result.stderr) | |
| 450 | 추가: ); | |
| 451 | 추가: } | |
| 452 | 추가: #[test] | |
| 453 | 추가: fn compressed_formats_keep_limits_after_permission() { | |
| 454 | 추가: for kind in ["gz", "tar", "targz", "bz2", "xz", "7z"] { | |
| 455 | 추가: let s = setup(); | |
| 456 | 추가: match kind { | |
| 457 | 추가: "gz" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(), | |
| 458 | 추가: "tar" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap(), | |
| 459 | 추가: "targz" => { | |
| 460 | 추가: fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar.gz")).unwrap() | |
| 461 | 추가: } | |
| 462 | 추가: "bz2" | "xz" => generate(&s, kind), | |
| 463 | 추가: "7z" => fs::write( | |
| 464 | 추가: s.0.join("input"), | |
| 465 | 추가: fs::read( | |
| 466 | 추가: PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 467 | 추가: .join("../../tests/rust-archive-worker/fixtures/7z/copy.7z"), | |
| 468 | 추가: ) | |
| 469 | 추가: .unwrap(), | |
| 470 | 추가: ) | |
| 471 | 추가: .unwrap(), | |
| 472 | 추가: _ => unreachable!(), | |
| 473 | 추가: } | |
| 474 | 추가: let mut start = request(&s, 16, 65536); | |
| 475 | 추가: if kind == "gz" { | |
| 476 | 추가: if let Action::Extract { | |
| 477 | 추가: gzip_output_name, .. | |
| 478 | 추가: } = &mut start.start.action | |
| 479 | 추가: { | |
| 480 | 추가: *gzip_output_name = Some("payload".into()); | |
| 481 | 추가: } | |
| 482 | 추가: } | |
| 483 | 추가: let events = run(&s, start, approve); | |
| 484 | 추가: assert_eq!( | |
| 485 | 추가: terminal(&events).outcome, | |
| 486 | 추가: Outcome::Completed, | |
| 487 | 추가: "{kind}: {events:?}" | |
| 488 | 추가: ); | |
| 489 | 추가: } | |
| 490 | 추가: } | |
| 491 | 추가: #[test] | |
| 492 | 추가: fn small_high_ratio_stream_requires_another_scope_and_cancels_promptly() { | |
| 493 | 추가: let s = setup(); | |
| 494 | 추가: generate(&s, "bomb"); | |
| 495 | 추가: assert!(fs::metadata(s.0.join("input")).unwrap().len() < 1024 * 1024); | |
| 496 | 추가: let mut start = request(&s, 16 * 1024 * 1024 * 1024, 64 * 1024 * 1024 * 1024); | |
| 497 | 추가: if let Action::Extract { | |
| 498 | 추가: gzip_output_name, .. | |
| 499 | 추가: } = &mut start.start.action | |
| 500 | 추가: { | |
| 501 | 추가: *gzip_output_name = Some("payload".into()); | |
| 502 | 추가: } | |
| 503 | 추가: let mut ratio = false; | |
| 504 | 추가: let mut cancelled = None; | |
| 505 | 추가: let events = run(&s, start, |event| { | |
| 506 | 추가: if let Message::ResourceRequired { scope, usage, .. } = event { | |
| 507 | 추가: if scope.ratio { | |
| 508 | 추가: ratio = true; | |
| 509 | 추가: assert!(!scope.output && !scope.entries); | |
| 510 | 추가: assert!(usage.actual_bytes.unwrap() >= 256 * 1024 * 1024); | |
| 511 | 추가: assert!(usage.compressed_bytes.unwrap() < 1024 * 1024); | |
| 512 | 추가: cancelled = Some(std::time::Instant::now()); | |
| 513 | 추가: return Some(vec![Message::Cancel]); | |
| 514 | 추가: } | |
| 515 | 추가: } | |
| 516 | 추가: if matches!(event, Message::CancelAck { .. }) { | |
| 517 | 추가: assert!(cancelled.unwrap().elapsed() < Duration::from_secs(2)); | |
| 518 | 추가: } | |
| 519 | 추가: approve(event) | |
| 520 | 추가: }); | |
| 521 | 추가: assert!(ratio); | |
| 522 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}"); | |
| 523 | 추가: assert_eq!(terminal(&events).created_count, 0); | |
| 524 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 525 | 추가: } | |
| 526 | 추가: | |
| 527 | 추가: #[cfg(target_os = "linux")] | |
| 528 | 추가: #[test] | |
| 529 | 추가: fn disk_space_and_write_failures_remain_enforced_after_permission() { | |
| 530 | 추가: for fault in ["space-destination", "codec-full", "full"] { | |
| 531 | 추가: let s = setup(); | |
| 532 | 추가: let mut permitted = false; | |
| 533 | 추가: let events = run_fault(&s, request(&s, 16, 64), Some(fault), |event| { | |
| 534 | 추가: if matches!(event, Message::ResourceRequired { .. }) { | |
| 535 | 추가: permitted = true; | |
| 536 | 추가: } | |
| 537 | 추가: approve(event) | |
| 538 | 추가: }); | |
| 539 | 추가: assert!(permitted); | |
| 540 | 추가: assert_eq!( | |
| 541 | 추가: terminal(&events).error, | |
| 542 | 추가: ErrorCode::DiskFull, | |
| 543 | 추가: "{fault}: {events:?}" | |
| 544 | 추가: ); | |
| 545 | 추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete, "{events:?}"); | |
| 546 | 추가: assert!(!s.0.join("output/folder/hello.txt").exists()); | |
| 547 | 추가: assert!(!fs::read_dir(s.0.join("output")).unwrap().any(|e| { | |
| 548 | 추가: e.unwrap() | |
| 549 | 추가: .file_name() | |
| 550 | 추가: .to_string_lossy() | |
| 551 | 추가: .starts_with(".zipelo-") | |
| 552 | 추가: })); | |
| 553 | 추가: } | |
| 554 | 추가: } |
| @@ -0,0 +1,20 @@ | ||
| 1 | 추가: import bz2 | |
| 2 | 추가: import gzip | |
| 3 | 추가: import lzma | |
| 4 | 추가: from pathlib import Path | |
| 5 | 추가: import sys | |
| 6 | 추가: | |
| 7 | 추가: | |
| 8 | 추가: root = Path(sys.argv[1]) | |
| 9 | 추가: case = sys.argv[2] | |
| 10 | 추가: if case == "bomb": | |
| 11 | 추가: with gzip.open(root / "input", "wb", compresslevel=9) as output: | |
| 12 | 추가: block = bytes(1024 * 1024) | |
| 13 | 추가: for _ in range(257): | |
| 14 | 추가: output.write(block) | |
| 15 | 추가: elif case in {"bz2", "xz"}: | |
| 16 | 추가: source = Path(__file__).with_name("fixtures").joinpath("sample.tar").read_bytes() | |
| 17 | 추가: encode = bz2.compress if case == "bz2" else lzma.compress | |
| 18 | 추가: (root / "input").write_bytes(encode(source)) | |
| 19 | 추가: else: | |
| 20 | 추가: raise ValueError(case) |
| @@ -1615,3 +1615,5 @@ mod conflict_wire; | ||
| 1615 | 1615 | mod conflicts; |
| 1616 | 1616 | |
| 1617 | 1617 | mod compressed_tar; |
| 1618 | 추가: | |
| 1619 | 추가: mod guarded; |
| @@ -0,0 +1,180 @@ | ||
| 1 | 추가: use super::*; | |
| 2 | 추가: | |
| 3 | 추가: fn budget() -> Budget { | |
| 4 | 추가: Budget { | |
| 5 | 추가: soft: Limits::default(), | |
| 6 | 추가: ceiling: Limits { | |
| 7 | 추가: input: u64::MAX, | |
| 8 | 추가: output: 64 * 1024 * 1024 * 1024, | |
| 9 | 추가: entries: 200_000, | |
| 10 | 추가: }, | |
| 11 | 추가: granted: ResourceScope::default(), | |
| 12 | 추가: } | |
| 13 | 추가: } | |
| 14 | 추가: #[test] | |
| 15 | 추가: fn output_boundaries_and_absolute_ceiling() { | |
| 16 | 추가: let mut b = budget(); | |
| 17 | 추가: let soft = b.soft.output; | |
| 18 | 추가: for n in [soft - 1, soft] { | |
| 19 | 추가: assert!( | |
| 20 | 추가: !b.required(ResourceUsage { | |
| 21 | 추가: actual_bytes: Some(n), | |
| 22 | 추가: ..ResourceUsage::default() | |
| 23 | 추가: }) | |
| 24 | 추가: .unwrap() | |
| 25 | 추가: .any() | |
| 26 | 추가: ); | |
| 27 | 추가: } | |
| 28 | 추가: let usage = ResourceUsage { | |
| 29 | 추가: actual_bytes: Some(soft + 1), | |
| 30 | 추가: ..ResourceUsage::default() | |
| 31 | 추가: }; | |
| 32 | 추가: let scope = b.required(usage).unwrap(); | |
| 33 | 추가: assert_eq!( | |
| 34 | 추가: scope, | |
| 35 | 추가: ResourceScope { | |
| 36 | 추가: output: true, | |
| 37 | 추가: ..ResourceScope::default() | |
| 38 | 추가: } | |
| 39 | 추가: ); | |
| 40 | 추가: b.grant(scope); | |
| 41 | 추가: assert!(!b.required(usage).unwrap().any()); | |
| 42 | 추가: assert!( | |
| 43 | 추가: !b.required(ResourceUsage { | |
| 44 | 추가: actual_bytes: Some(b.ceiling.output), | |
| 45 | 추가: ..ResourceUsage::default() | |
| 46 | 추가: }) | |
| 47 | 추가: .unwrap() | |
| 48 | 추가: .any() | |
| 49 | 추가: ); | |
| 50 | 추가: assert_eq!( | |
| 51 | 추가: b.required(ResourceUsage { | |
| 52 | 추가: actual_bytes: Some(b.ceiling.output + 1), | |
| 53 | 추가: ..ResourceUsage::default() | |
| 54 | 추가: }), | |
| 55 | 추가: Err(ErrorCode::Limit) | |
| 56 | 추가: ); | |
| 57 | 추가: } | |
| 58 | 추가: #[test] | |
| 59 | 추가: fn entries_need_their_own_grant_and_keep_absolute_ceiling() { | |
| 60 | 추가: let mut b = budget(); | |
| 61 | 추가: b.grant(ResourceScope { | |
| 62 | 추가: output: true, | |
| 63 | 추가: ..ResourceScope::default() | |
| 64 | 추가: }); | |
| 65 | 추가: assert!( | |
| 66 | 추가: !b.required(ResourceUsage { | |
| 67 | 추가: estimated_entries: Some(10_000), | |
| 68 | 추가: ..ResourceUsage::default() | |
| 69 | 추가: }) | |
| 70 | 추가: .unwrap() | |
| 71 | 추가: .any() | |
| 72 | 추가: ); | |
| 73 | 추가: let usage = ResourceUsage { | |
| 74 | 추가: estimated_entries: Some(10_001), | |
| 75 | 추가: ..ResourceUsage::default() | |
| 76 | 추가: }; | |
| 77 | 추가: assert!(b.required(usage).unwrap().entries); | |
| 78 | 추가: b.grant(ResourceScope { | |
| 79 | 추가: entries: true, | |
| 80 | 추가: ..ResourceScope::default() | |
| 81 | 추가: }); | |
| 82 | 추가: assert!( | |
| 83 | 추가: !b.required(ResourceUsage { | |
| 84 | 추가: estimated_entries: Some(200_000), | |
| 85 | 추가: ..ResourceUsage::default() | |
| 86 | 추가: }) | |
| 87 | 추가: .unwrap() | |
| 88 | 추가: .any() | |
| 89 | 추가: ); | |
| 90 | 추가: assert_eq!( | |
| 91 | 추가: b.required(ResourceUsage { | |
| 92 | 추가: actual_entries: Some(200_001), | |
| 93 | 추가: ..ResourceUsage::default() | |
| 94 | 추가: }), | |
| 95 | 추가: Err(ErrorCode::Limit) | |
| 96 | 추가: ); | |
| 97 | 추가: } | |
| 98 | 추가: #[test] | |
| 99 | 추가: fn ratio_floor_boundary_unknown_and_zero_input() { | |
| 100 | 추가: let b = budget(); | |
| 101 | 추가: let usage = |output, input| ResourceUsage { | |
| 102 | 추가: ratio_output_bytes: Some(output), | |
| 103 | 추가: compressed_bytes: input, | |
| 104 | 추가: ..ResourceUsage::default() | |
| 105 | 추가: }; | |
| 106 | 추가: assert!( | |
| 107 | 추가: !b.required(usage(256 * 1024 * 1024 - 1, Some(1))) | |
| 108 | 추가: .unwrap() | |
| 109 | 추가: .ratio | |
| 110 | 추가: ); | |
| 111 | 추가: assert!(!b.required(usage(300_000_000, Some(300_000))).unwrap().ratio); | |
| 112 | 추가: assert!(b.required(usage(300_000_001, Some(300_000))).unwrap().ratio); | |
| 113 | 추가: assert!(b.required(usage(256 * 1024 * 1024, Some(0))).unwrap().ratio); | |
| 114 | 추가: assert!(!b.required(usage(256 * 1024 * 1024, None)).unwrap().ratio); | |
| 115 | 추가: assert!(!b.required(ResourceUsage::default()).unwrap().any()); | |
| 116 | 추가: } | |
| 117 | 추가: #[test] | |
| 118 | 추가: fn estimated_and_actual_totals_are_both_enforced() { | |
| 119 | 추가: let b = budget(); | |
| 120 | 추가: for usage in [ | |
| 121 | 추가: ResourceUsage { | |
| 122 | 추가: estimated_bytes: Some(b.soft.output + 1), | |
| 123 | 추가: actual_bytes: Some(0), | |
| 124 | 추가: ..ResourceUsage::default() | |
| 125 | 추가: }, | |
| 126 | 추가: ResourceUsage { | |
| 127 | 추가: estimated_bytes: Some(0), | |
| 128 | 추가: actual_bytes: Some(b.soft.output + 1), | |
| 129 | 추가: ..ResourceUsage::default() | |
| 130 | 추가: }, | |
| 131 | 추가: ] { | |
| 132 | 추가: assert!(b.required(usage).unwrap().output); | |
| 133 | 추가: } | |
| 134 | 추가: } | |
| 135 | 추가: #[test] | |
| 136 | 추가: fn idle_timeout_and_activity_use_virtual_time() { | |
| 137 | 추가: let mut w = Watchdog::new(); | |
| 138 | 추가: assert!(w.check(Duration::from_secs(300)).is_ok()); | |
| 139 | 추가: assert_eq!(w.check(Duration::from_secs(301)), Err(ErrorCode::Limit)); | |
| 140 | 추가: w.resume(Duration::from_secs(299), true); | |
| 141 | 추가: assert!(w.check(Duration::from_secs(358)).is_ok()); | |
| 142 | 추가: assert_eq!(w.check(Duration::from_secs(359)), Err(ErrorCode::Limit)); | |
| 143 | 추가: w.activity(Duration::from_secs(350)).unwrap(); | |
| 144 | 추가: assert!(w.check(Duration::from_secs(409)).is_ok()); | |
| 145 | 추가: assert_eq!(w.check(Duration::from_secs(410)), Err(ErrorCode::Limit)); | |
| 146 | 추가: } | |
| 147 | 추가: #[test] | |
| 148 | 추가: fn approved_progress_can_run_longer_than_five_minutes() { | |
| 149 | 추가: let mut w = Watchdog::new(); | |
| 150 | 추가: w.resume(Duration::ZERO, true); | |
| 151 | 추가: for t in (1..=3600).step_by(30) { | |
| 152 | 추가: w.activity(Duration::from_secs(t)).unwrap(); | |
| 153 | 추가: } | |
| 154 | 추가: assert!(w.check(Duration::from_secs(3600)).is_ok()); | |
| 155 | 추가: w.resume(Duration::from_secs(3900), false); | |
| 156 | 추가: assert!(w.check(Duration::from_secs(3959)).is_ok()); | |
| 157 | 추가: assert_eq!(w.check(Duration::from_secs(3960)), Err(ErrorCode::Limit)); | |
| 158 | 추가: } | |
| 159 | 추가: | |
| 160 | 추가: #[test] | |
| 161 | 추가: fn granted_entry_policy_keeps_independent_metadata_budget() { | |
| 162 | 추가: let mut b = budget(); | |
| 163 | 추가: b.grant(ResourceScope { | |
| 164 | 추가: entries: true, | |
| 165 | 추가: ..ResourceScope::default() | |
| 166 | 추가: }); | |
| 167 | 추가: assert!( | |
| 168 | 추가: !b.required(ResourceUsage { | |
| 169 | 추가: estimated_entries: Some(200_000), | |
| 170 | 추가: ..ResourceUsage::default() | |
| 171 | 추가: }) | |
| 172 | 추가: .unwrap() | |
| 173 | 추가: .any() | |
| 174 | 추가: ); | |
| 175 | 추가: let mut metadata = crate::archive::MetadataBudget::default(); | |
| 176 | 추가: for _ in 0..32768 { | |
| 177 | 추가: metadata.charge("").unwrap(); | |
| 178 | 추가: } | |
| 179 | 추가: assert_eq!(metadata.charge(""), Err(ErrorCode::Limit)); | |
| 180 | 추가: } |