Merge pull request #121 from Team-LJY/features/large-archive-limits
대용량 작업 승인과 작업자 자원 감시를 추가한다
- 작성자
- LeeJunyoung
- 작성 시각
- 커밋
690274c7ac54c0ce57938f69da1dab2862d6b40b
변경된 파일 45개
+1,113-300변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -109,10 +109,37 @@ python3 tests/ci/run_rust.py local | ||
| 109 | 109 | - extract-renamed: 실제 저장된 새 이름을 표시합니다. 이름 변경 결과만으로 저장 성공을 판정하지 않고 별도의 생성 보고와 완료 집계가 일치해야 합니다. |
| 110 | 110 | - extract-rename-failed: 새 이름을 정한 뒤 실제 생성 보고 없이 I/O 오류가 난 결과입니다. 실패 원인과 "아무 파일도 풀지 않았습니다"를 표시하고 "이름 바꿔 저장" 완료 안내는 표시하지 않아야 합니다. 일부 파일이 저장된 뒤 실패한 경우에도 생성 보고가 있는 이름만 저장 완료로 표시합니다. |
| 111 | 111 | |
| 112 | 삭제: 실제 추출은 revision 3의 StartInteractive를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기는 기존 Start를 유지합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다. | |
| 112 | 추가: 실제 추출은 revision 3의 StartGuarded에 interactive=true를 보내며 ZIP, 7z, TAR 계열과 단일 GZ의 파일 충돌에 같은 선택 창을 사용합니다. 목록 읽기와 ZIP 만들기도 StartGuarded로 자원을 감시하며 충돌 질문은 추출에만 사용합니다. 위 명령은 실제 파일을 쓰지 않는 개발용 화면 미리보기입니다. 파일 기반 버튼 연동은 tests/rust-app-real-worker/conflict_flows.rs에서 확인하며, 운영체제별 실제 창 확인은 별도입니다. | |
| 113 | 113 | |
| 114 | 114 | TAR.BZ2와 TAR.XZ의 자동 해제 폴더 이름은 미리보기에 표시되지 않는다. tests/rust-app-ui/presentation.rs의 이름 시험과 tests/rust-app-real-worker/compressed_tar_flows.rs의 실제 작업자 시험에서 복합 확장자 제거와 해제 결과를 확인한다. |
| 115 | 115 | |
| 116 | 추가: ## 큰 작업의 승인과 재시도 | |
| 117 | 추가: | |
| 118 | 추가: - resource-approval: 목록에서 큰 작업임을 확인한 뒤 처리 전 승인을 묻는 화면 | |
| 119 | 추가: - resource-ratio: 압축률 경고와 미확인 예상값을 표시하는 화면 | |
| 120 | 추가: - resource-retry: 출력 없이 한도에 걸린 뒤 주 창 안의 모달에서 "한도를 늘려 다시 시도"를 고르는 화면 | |
| 121 | 추가: - resource-partial: 일부 파일을 저장한 뒤 한도에 걸려 주 창 안의 모달에서 저장 위치를 안내하는 화면 | |
| 122 | 추가: | |
| 123 | 추가: 일반 작업은 16 GiB와 10,000개 한도를 유지하며 압축률을 감시합니다. | |
| 124 | 추가: 목록이나 선택한 일반 파일의 크기로 한도 초과를 알면 처리 전에 작업자가 확대 승인을 묻습니다. | |
| 125 | 추가: 미리 알 수 없는 폴더 내부와 압축파일은 기본 한도로 시작합니다. | |
| 126 | 추가: 출력이 없고 임시 파일 정리와 작업자 종료가 확인된 한도 오류에서만 확대 재시도를 제공합니다. | |
| 127 | 추가: 확대 재시도를 선택해도 작업자의 승인 질문에서 "이 작업 허용"을 눌러야 진행합니다. | |
| 128 | 추가: 이미 저장되거나 일부 남은 파일, 저장 상태나 정리가 불확실한 작업은 확대 재시도를 제공하지 않습니다. | |
| 129 | 추가: | |
| 130 | 추가: 승인은 해당 작업과 질문 범위에만 적용합니다. 예상값, 실제값과 저장 볼륨의 여유 공간은 구분하며 | |
| 131 | 추가: 확인하지 못한 값은 "미확인"으로 표시합니다. 여유 공간은 예약이나 모든 볼륨의 합계가 아닙니다. | |
| 132 | 추가: 승인 후에도 상한과 공간 검사를 유지합니다. 취소 버튼과 Escape는 승인 대기 중 작업을 취소합니다. | |
| 133 | 추가: Enter만으로 허용하지 않습니다. 기존 작업자로 자동 재시도하지 않습니다. | |
| 134 | 추가: 미리보기는 입력과 파일 쓰기를 막으며 실제 64 GiB 작업을 수행하지 않습니다. | |
| 135 | 추가: | |
| 136 | 추가: 승인된 작업의 목록 한도는 200,000개입니다. 출력 기록에는 압축파일에 따로 적혀 있지 않은 | |
| 137 | 추가: 상위 폴더도 포함되므로 작업자 메타데이터 정책과 같은 262,144개 노드까지 보관합니다. | |
| 138 | 추가: 기본 작업의 출력 기록 한도는 100,000개를 유지합니다. 이 기록 정책 수정은 화면 요소를 바꾸지 않습니다. | |
| 139 | 추가: | |
| 140 | 추가: 한도 초과 결과는 별도 운영체제 창 대신 주 창 안의 모달로 표시합니다. Wayland에서도 파일 경로로 실행한 직후 Alt+Tab 없이 결과와 재시도 버튼이 보여야 합니다. "확인"으로 닫으며, 일부 출력이 남은 경우 확대 재시도는 제공하지 않습니다. | |
| 141 | 추가: | |
| 142 | 추가: 큰 작업을 허용한 뒤 파일 충돌이 발견되면 승인 창을 닫고 충돌 선택 창을 표시합니다. 승인과 충돌 질문은 동시에 표시하지 않으며, 같은 작업의 질문 번호를 이어서 검증합니다. | |
| 116 | 143 | ## 설치 프로그램의 제거 안내 |
| 117 | 144 | |
| 118 | 145 | Windows NSIS 제거 프로그램은 앱과 별도의 실행 파일입니다. 이번 제거 안내는 Uninstall.exe 실행 후 확인 화면 앞에 표시되며 [기본 앱 설정 열기]로 Windows 설정을 엽니다. --ui-scenario uninstall-windows와 uninstall-settings-error로 안내 문구를 확인합니다. Ubuntu 터미널 안내는 uninstall-ubuntu-missing과 uninstall-ubuntu-unknown-user로 확인합니다. 이 네 상황은 외부 설치 프로그램과 터미널의 문구를 egui에 재현한 읽기 전용 미리보기이며, NSIS의 실제 배치나 운영체제 창 모양을 재현하지 않습니다. 버튼은 설정을 열거나 제거를 실행하지 않습니다. 다른 운영체제에서도 같은 안내를 확인할 수 있습니다. |
| @@ -4,8 +4,9 @@ | ||
| 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 한도를 유지합니다. | |
| 8 | 삭제: - 경로 깊이는 64개 구성 요소, 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다. | |
| 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 | 추가: - 경로 깊이는 64개 구성 요소이며 승인 전 이름/출력 계획 메타데이터 예산은 8 MiB, 출력 계획 노드는 32,768개로 제한합니다. 유효한 StartGuarded 자원 승인 후에만 각각 64 MiB와 262,144개로 확대합니다. 이름 복제와 인덱스 비용을 보수적으로 계산해 할당 전에 Limit으로 거부합니다. | |
| 9 | 추가: - 선택 ID 전송은 Start와 StartInteractive 및 항목 상한을 늘리지 않은 StartGuarded에서 기존 32,768개를 유지합니다. 항목 상한을 늘린 StartGuarded는 32,768개와 요청 ceiling.entries 중 큰 값까지 전송하며 최대 200,000개입니다. 전송만으로 승인이 성립하지 않으며 실제 처리는 일치하는 ResourceReply 허용 뒤에 시작합니다. 경로/문자열, 생성 원본 벡터와 프레임 한도는 확대하지 않습니다. | |
| 9 | 10 | - GZip 내부 형식은 완전한 USTAR magic이 있을 때만 TAR로 판별합니다. magic이 없는 영값 데이터는 길이와 무관하게 raw GZip으로 유지하며 명시 출력명이 필요합니다. |
| 10 | 11 | - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 임시 파일 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. |
| 11 | 12 | - 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다. |
| @@ -16,7 +17,7 @@ | ||
| 16 | 17 | |
| 17 | 18 | revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도를 유지하고, 히나타 님과 합의한 공간 부족 오류 DiskFull(tag 13)을 추가합니다. 구버전 앱은 새 tag를 거부하므로 앱 오류 변환과 화면 매핑을 작업자와 함께 갱신해야 합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다. |
| 18 | 19 | |
| 19 | 삭제: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다. | |
| 20 | 추가: - 기존 Start와 StartInteractive는 압축비를 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다. | |
| 20 | 21 | - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. 기존 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 | 22 | - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 오류 문구는 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"이며, detail 문자열을 오류 판정에 사용하지 않습니다. |
| 22 | 23 | - 입력과 검증된 해제 내용은 임시 파일에 저장합니다. 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 외의 시스템 메모리를 사용합니다. |
| @@ -29,7 +30,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도 | ||
| 29 | 30 | 비암호화 7z의 단일 입력/출력 coder인 Copy, LZMA와 LZMA2를 Rust 코드로 해독합니다. solid substream, 빈 파일/디렉터리, UTF-16LE 이름과 한 단계 압축 헤더를 처리합니다. 추가 라이브러리나 제품 외부 명령을 사용하지 않습니다. 형식 근거는 [7z 명세](https://www.7-zip.org/7z.html)와 [LZMA SDK 명세 안내](https://www.7-zip.org/sdk.html)입니다. |
| 30 | 31 | |
| 31 | 32 | - 시작 헤더/다음 헤더 CRC, packed/folder/substream CRC가 있을 때 해당 CRC와 크기, 스트림의 끝을 검증합니다. 경로, 충돌과 모든 선택 내용 검증이 끝난 뒤 기존 안전 게시 경로로 넘깁니다. 목록은 데이터 CRC 검증 성공을 뜻하지 않습니다. |
| 32 | 삭제: - 기본 입력 한도 u64::MAX, 해제 총량 16 GiB와 기존 항목/이름 한도를 적용합니다. 압축 해제된 헤더도 최대 8 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 최근 8 MiB 사전만 메모리에 두고 더 먼 참조는 임시 파일에서 읽습니다. 먼 거리 참조가 많은 파일은 추가 디스크 I/O가 발생합니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다. | |
| 33 | 추가: - 기본 입력 한도 u64::MAX, 해제 총량 16 GiB와 기존 항목/이름 한도를 적용합니다. 압축 해제된 헤더는 승인 전 최대 8 MiB, 승인 후 최대 64 MiB이고 헤더 중첩은 한 단계입니다. 사전은 최대 64 MiB, LZMA의 lc+lp는 최대 4입니다. 최근 8 MiB 사전만 메모리에 두고 더 먼 참조는 임시 파일에서 읽습니다. 먼 거리 참조가 많은 파일은 추가 디스크 I/O가 발생합니다. 해독 중 checkpoint에서 취소와 시간 한도를 확인합니다. | |
| 33 | 34 | - 암호화 7z, 다중 coder 필터 체인(BCJ/BCJ2/Delta 등), PPMd/BZip2, 분할/SFX, external metadata, additional streams와 anti 항목은 미지원입니다. 링크, reparse point와 특수 Unix 항목은 거부합니다. 지원하지 않는 구조를 성공으로 처리하지 않습니다. |
| 34 | 35 | - solid 그룹의 압축 크기는 첫 substream에만 기록하고 나머지는 0으로 표시합니다. 각 파일의 정확한 비압축 크기는 유지합니다. |
| 35 | 36 | - 합성 표본은 Python 표준 lzma로 생성합니다. 별도로 시스템 libarchive가 만든 LZMA1/LZMA2 표본을 해제하고, 합성 표본도 libarchive 읽기 API로 검사합니다. libarchive는 Linux 시험의 독립 참조 도구이며 제품 의존성이 아닙니다. 시험 도구와 표본은 tests/rust-archive-worker 아래에 있습니다. |
| @@ -39,7 +40,7 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도 | ||
| 39 | 40 | |
| 40 | 41 | TAR.BZ2와 TAR.XZ는 확장자가 아닌 BZh 및 XZ 매직으로 판별하고 비공개 임시 파일로 먼저 해제합니다. 연결된 BZip2/XZ 스트림은 하나의 TAR로 합치며 XZ의 4바이트 정렬 스트림 패딩도 허용합니다. 빈 TAR, USTAR 이름과 빈 폴더를 지원하지만 독립 BZ2/XZ 데이터 파일은 TAR가 아니면 거부합니다. |
| 41 | 42 | |
| 42 | 삭제: 해제 총량은 TAR 헤더와 패딩을 포함해 기존 16 GiB 이하이며 요청으로 낮출 수 있습니다. 64 KiB씩 실제 해제량을 확인하고 기록 전에 임시 저장소의 공간을 검사합니다. XZ는 블록별 LZMA2 디코더 메모리 32 MiB, 인덱스 8 MiB, 스트림 수와 스트림당 블록 수 각각 32,768을 상한으로 둡니다. 이 상한을 넘는 정상 파일도 Limit로 거부합니다. 해제 전체와 TAR 경로, 항목 종류 및 이름 충돌을 검증하기 전에는 목적지에 게시하지 않습니다. 출력 공간 검사, 안전한 충돌 처리, 취소와 300초 시간 제한도 기존 흐름을 사용합니다. | |
| 43 | 추가: 해제 총량은 TAR 헤더와 패딩을 포함해 기존 16 GiB 이하이며 요청으로 낮출 수 있습니다. 64 KiB씩 실제 해제량을 확인하고 기록 전에 임시 저장소의 공간을 검사합니다. XZ는 블록별 LZMA2 디코더 메모리 32 MiB, 인덱스는 승인 전 8 MiB, 승인 후 64 MiB이며 스트림 수와 스트림당 블록 수는 각각 승인 전 32,768개, 승인 후 262,144개를 상한으로 둡니다. 이 상한을 넘는 정상 파일도 Limit로 거부합니다. 해제 전체와 TAR 경로, 항목 종류 및 이름 충돌을 검증하기 전에는 목적지에 게시하지 않습니다. 출력 공간 검사, 안전한 충돌 처리, 취소와 300초 시간 제한도 기존 흐름을 사용합니다. | |
| 43 | 44 | |
| 44 | 45 | XZ의 헤더, 인덱스, 푸터 CRC와 역방향 크기 및 전체 선언 해제량을 확인하고 실제 해제량과 비교합니다. 각 블록의 헤더와 LZMA2 청크 경계를 따라 압축 길이와 해제량을 인덱스 레코드 및 선택적 헤더 크기와 대조하므로 다른 블록이나 연결 스트림의 크기 변조가 상쇄되어도 Integrity로 거부합니다. 지원하는 BCJ와 Delta 필터는 길이를 보존합니다. 이 사전 검사는 payload를 해제하거나 할당하지 않으며 기존 디코더가 청크 내용과 데이터 블록의 CRC32/CRC64/SHA256 검사를 수행한 뒤에만 게시합니다. [XZ 명세 4.3절](https://tukaani.org/xz/xz-file-format.txt)의 블록별 Unpadded Size와 Uncompressed Size 검사를 적용합니다. XZ의 Check=None도 형식대로 허용하므로 데이터 체크섬이 없는 파일의 내용 무결성을 보장하지 않습니다. TAR의 PAX/GNU 확장, 링크와 특수 항목의 기존 제한도 유지합니다. |
| 45 | 46 | |
| @@ -76,11 +77,11 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 76 | 77 | |
| 77 | 78 | ## 공유 codec |
| 78 | 79 | |
| 79 | 삭제: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`에서 구현 상태를 구분합니다. | |
| 80 | 추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 3 원문이며 `extract_conflicts.status`와 `guarded_resources.status`에서 구현 및 화면 연동 상태를 구분합니다. | |
| 80 | 81 | |
| 81 | 82 | 헤더는 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 | 83 | |
| 83 | 삭제: - kind: Start=1, Password=2, Cancel=3, StartInteractive=4, ConflictReply=5, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107, ConflictRequired=108, ConflictResolved=109입니다. 새 kind의 런타임 지원 상태는 아래 revision 3 절을 따릅니다. | |
| 84 | 추가: - kind: Start=1, Password=2, Cancel=3, StartInteractive=4, ConflictReply=5, StartGuarded=6, ResourceReply=7, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107, ConflictRequired=108, ConflictResolved=109, ResourceRequired=110입니다. 충돌 및 자원 승인의 지원 상태는 아래 계약 절을 따릅니다. | |
| 84 | 85 | - body 필드는 `protocol.rs` 선언 순서입니다. enum은 선언 순서의 u8 tag이며 NativePath/SourceObject만 Unix=1, Windows=2입니다. bool/Option은 0 또는 1입니다. String/Vec는 u32 길이 뒤 원소를 저장하며 String은 UTF-8 바이트 길이입니다. `[u8; N]`은 길이 없이 N바이트입니다. action variant의 필드는 선언 순서를 사용합니다. Start는 action 뒤 limits(input u64, output u64, entries u32)입니다. |
| 85 | 86 | - Password의 비밀 값은 Debug에 노출되지 않습니다. 암호 작업은 PasswordRequired의 challenge_id와 일치하는 Password를 한 번 받습니다. 오래된 ID, 중복 또는 요청 전 암호는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다. |
| 86 | 87 | - CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다. |
| @@ -101,6 +102,26 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 101 | 102 | |
| 102 | 103 | 교체 동작의 근거는 [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 | 104 | |
| 105 | 추가: ## 큰 작업의 명시적 승인 계약 | |
| 106 | 추가: | |
| 107 | 추가: `StartGuarded`는 기존 요청과 분리된 선택적 확장입니다. 작업자와 앱의 요청 및 승인 화면 연동이 구현됐으며 `--ui-scenario` 상황, 시험과 [가이드](../../docs/ui-scenario-guide.md)도 반영됐습니다. 기존 `Start`와 `StartInteractive` 요청에는 자원 질문을 보내지 않습니다. 구버전 작업자가 새 요청을 거부하면 자동 재시도하지 않습니다. | |
| 108 | 추가: | |
| 109 | 추가: - kind 6의 본문은 `GuardedStart { start: Start, ceiling: Limits, interactive: bool }` 순서입니다. start.limits는 기존 16 GiB 및 10,000개 이하이고 ceiling은 이를 늘리되 64 GiB 및 200,000개 이하입니다. 입력 한도는 동일해야 합니다. interactive는 Extract에서만 허용하며 기존 암호와 충돌 처리를 함께 사용합니다. | |
| 110 | 추가: - 작업자는 Accepted 뒤, 입력 캡처와 소스 탐색 전에 요청된 상한 확대 범위를 확인합니다. 입력 사본 작성부터 300초를 넘을 수 있으므로 승인을 먼저 받습니다. 이때 예상량과 실제량은 아직 미확인(None)이고 임시 저장 볼륨의 여유 공간을 알립니다. 허용 전에는 확대 한도가 적용되지 않으며 거부하면 Cancelled로 끝납니다. 앱의 일반 작업은 기존 16 GiB 및 10,000개 한도의 `StartGuarded`를 사용해 압축률을 감시합니다. 기존 `Start` 호출도 유지합니다. | |
| 111 | 추가: - 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으로 바꾸지 않습니다. 여유 공간은 관찰 중인 저장 볼륨의 값이며 공간 예약이나 모든 볼륨의 합계가 아닙니다. | |
| 112 | 추가: - kind 7의 `ResourceReply`는 challenge_id u64, scope, allow bool입니다. 프레임의 작업 ID, 현재 질문 ID와 요청한 scope가 모두 일치하는 응답 한 개만 허용합니다. 중복, 오래된 응답과 다른 종류의 질문 응답은 Protocol입니다. 승인은 해당 작업의 해당 범위에만 적용하며 재사용하지 않습니다. | |
| 113 | 추가: - 해제량이 256 MiB 이상이고 압축률이 1,000배를 초과하면 ratio 범위를 별도로 묻습니다. ZIP은 항목별 크기와 전체 payload 합계, 7z는 solid 폴더와 전체, 압축 TAR와 GZip은 스트림 전체의 크기로 검사합니다. 예상량과 실제량을 구분하고 u128 곱셈으로 비교합니다. 승인 중에는 추가 해제와 쓰기를 멈추며 취소는 별도 제어 읽기에서 처리합니다. | |
| 114 | 추가: - 승인 후에도 64 GiB와 200,000개 정책 상한, 메타데이터와 사전 예산, 경로 및 무결성, 임시 저장소와 목적지 공간 검사를 적용합니다. ZIP 생성은 원본 논리 크기 합계를 제한하며 ZIP 구조와 암호화로 늘어나는 저장 공간을 별도로 계산합니다. 이미 게시한 출력은 실패나 취소 시 유지하고 게시 및 정리 상태를 보고합니다. | |
| 115 | 추가: - 승인된 작업은 전체 300초 대신 진행이 60초 동안 없을 때 Limit로 중단합니다. 성공한 읽기, 해독, 쓰기와 항목별 메타데이터 및 경로 검사를 공통 완료 함수로 기록합니다. 사전검사, 기존 폴더 조회와 생성, ZIP 헤더와 중앙 목록 기록, 목록 전송, 이름 후보와 덮어쓰기 재검사, 게시와 임시 파일 정리도 포함하며 반복 check와 UI 진행 알림만으로는 기한을 늘리지 않습니다. 한 단계 자체가 60초 이상 멈추면 완료 시에도 Limit로 처리하고 이미 만들어진 출력 집계와 정리는 유지합니다. 암호, 충돌과 자원 질문은 한 번에 하나이며 각 응답 대기는 300초입니다. 유효한 응답 뒤에는 사용자 대기 시간을 제외하고 정체 감시를 재개합니다. 기존 요청의 전체 300초 제한은 유지합니다. OS의 블로킹 I/O를 강제로 중단하는 보장은 아닙니다. | |
| 116 | 추가: | |
| 117 | 추가: 메타데이터 정책은 유효한 자원 승인 여부로 선택하며 요청의 ceiling만 늘려서는 확대되지 않습니다. 7z 압축 헤더 해독은 이 메타데이터 예산으로만 감시하며 파일 출력량과 압축률 집계에는 합치지 않습니다. 헤더 처리 중에도 취소와 진행 시각 감시는 유지하고 실제 파일 데이터에는 기존 출력량과 압축률 검사를 적용합니다. 원본 계획의 경로와 대기 이름은 확대 작업에서 같은 항목의 복사 비용으로 계산하고 노드를 중복 가산하지 않습니다. 이름 및 원본 경로의 바이트 비용과 암묵적 상위 폴더 노드는 계속 계산하므로 긴 경로나 많은 상위 폴더가 있으면 항목 200,000개 이전에도 Limit로 중단될 수 있습니다. 승인 전과 기존 slice API의 메타데이터 한도 및 계산 방식은 유지합니다. 기존 대용량 회귀의 64 MiB RSS 목표는 기본 메타데이터 정책의 측정값이며 확대 작업 전체의 메모리 상한을 뜻하지 않습니다. | |
| 118 | 추가: | |
| 119 | 추가: 앱은 목록이나 선택한 일반 파일의 크기로 한도 초과를 알 수 있으면 처리 전에 확대 승인을 요청합니다. 미확인 폴더 내부와 압축파일은 기본 한도로 시작합니다. 한도 오류 뒤 Terminal, 양쪽 EOF와 자식 회수가 확인되고 게시 없음, 생성 및 부분 잔존 0개, 정리 완료일 때만 "한도를 늘려 다시 시도"를 제공합니다. 선택하면 새 작업 ID로 시작해 다시 승인을 받습니다. 이미 출력이 있거나 결과가 불확실하면 확대 재시도 대신 저장 위치와 상세 결과를 안내합니다. 유효한 자원 승인 후에는 암묵적 상위 폴더를 포함한 앱 출력 기록 상한이 262,144개 노드로 늘어납니다. 목록은 항목 확대를 승인한 작업에서만 200,000개까지 받습니다. 자원 승인 전 출력 기록과 항목 확대 승인 전 목록은 기존 100,000개 상한을 유지합니다. | |
| 120 | 추가: | |
| 121 | 추가: 작업자의 짧은 이름 빈 ZIP 항목 200,000개 목록 시험과 앱 승인 및 재시도 시험을 반영했습니다. `resource-approval`, `resource-ratio`, `resource-retry`, `resource-partial` 상황과 가이드도 추가됐습니다. Windows와 Wayland의 실제 화면 및 입력 검증은 별도로 남아 있습니다. | |
| 122 | 추가: | |
| 123 | 추가: 시험은 실제 64 GiB를 쓰지 않고 수치 경계와 축소한 limits/ceiling을 사용합니다. `resource_budget.rs`는 16 GiB 아래/경계/초과, 64 GiB 초과, 10,000개 및 200,000개 경계, 압축률 경계와 가상 시계의 60초 정체를 검사합니다. `item_progress.rs`는 기존 빈 폴더 8개를 포함해 각 단계를 가상 10초씩 늦춘 실제 작업자와 단일 60초 정체의 출력 집계 및 정리를 검사합니다. `metadata_policy.rs`는 축소한 바이트와 노드 예산, 원본 계획과 암묵적 폴더 계산을 확인합니다. `guarded.rs`는 승인 전 메타데이터 거부, 승인 뒤 200,000개 목록, 실제 작업자 승인/거부, 오래된 응답, 암호/충돌 순서, 승인 뒤 공간 실패, 여러 형식과 작은 고압축 입력의 경고 및 취소를 검사합니다. | |
| 124 | 추가: | |
| 104 | 125 | ## 검증과 의존성 |
| 105 | 126 | |
| 106 | 127 | 시험은 `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.", |
| @@ -162,13 +165,13 @@ | ||
| 162 | 165 | "gzip_ratio": "No compression-ratio rejection, including concatenated members. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota.", |
| 163 | 166 | "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.", |
| 164 | 167 | "arithmetic": "Checked u64 offsets and totals; free-space block-to-byte conversion uses u128 to avoid multiplication overflow.", |
| 165 | 삭제: "memory_target": "ZIP/TAR/GZ/TAR.GZ/7z List/Extract and ZIP creation: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. Metadata budget remains 8 MiB.", | |
| 168 | 추가: "memory_target": "ZIP/TAR/GZ/TAR.GZ/7z List/Extract and ZIP creation: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. The 64 MiB RSS regression target uses the default 8 MiB metadata policy; approved expanded metadata jobs may use more RSS.", | |
| 166 | 169 | "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with DiskFull and closes/removes unpublished data.", |
| 167 | 170 | "legacy": "The slice parser keeps 64 MiB input /128 MiB output caps; the slice ZIP builder keeps 128 MiB source/result caps. Runtime 7z and ZIP creation use streaming file paths.", |
| 168 | 171 | "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard.", |
| 169 | 172 | "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Legacy Start groups remaining staging and selected output logical bytes by volume before ZIP/7z decoding and before publication. StartInteractive checks required staging before choices, then checks only the current non-skipped output at its resolved name immediately before publication; do not charge undecided or skipped files to the destination. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Insufficient space returns DiskFull tag 13. Query failure and other I/O errors retain Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.", |
| 170 | 173 | "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure.", |
| 171 | 삭제: "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers remain limited to 8 MiB. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.", | |
| 174 | 추가: "seven_zip": "Copy, LZMA and LZMA2 use file-backed solid output with checked declared/actual output totals. Encoded headers are limited to the active metadata policy: 8 MiB before a valid resource grant, 64 MiB after it. Dictionary size remains at most 64 MiB; only the last 8 MiB is cached in memory and older dictionary bytes are read from the temporary output.", | |
| 172 | 175 | "create_zip": "The sum of source logical bytes cannot exceed min(input,output) quotas. output defaults to 16 GiB of uncompressed source content; ZIP container/encryption overhead may exceed that logical content quota. Capture one immutable source at a time, stream Store/Deflate and optional AES-256 through 64 KiB buffers, then publish the completed ZIP without replacing existing files. Emit ZIP64 sizes/offsets only when their 32-bit fields would overflow or equal the sentinel. Check staging and destination free space; StorageFull maps to DiskFull tag 13 and other I/O failures retain Io tag 8." |
| 173 | 176 | }, |
| 174 | 177 | "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim.", |
| @@ -199,7 +202,7 @@ | ||
| 199 | 202 | "agreement": "Proposed semantic extension under manager task 82093f56-73b7-4be4-ba6d-2597ffc2c6f7; frontend joint agreement is pending. Revision 2 fields, encoding, numeric quotas and error tags are unchanged.", |
| 200 | 203 | "roots": "Each source may be a regular file or directory. archive_name names that root inside the ZIP; directory descendants retain relative paths and every directory, including empty directories, gets a trailing-slash ZIP entry.", |
| 201 | 204 | "links": "Reject the whole job with UnsafePath for symbolic links, Windows reparse points, special files or unsafe/non-UTF-8 descendant names. Do not skip entries or follow external links. Open each path component without following links; enumerate pinned directories.", |
| 202 | 삭제: "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Preserve 8 MiB metadata and 64-component name limits. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.", | |
| 205 | 추가: "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Keep 64-component names and the active metadata budget. Legacy/unapproved plans retain 8 MiB and 32768 nodes; resource-approved plans use 64 MiB and 262144 nodes. In approved source plans, path and pending-name copies consume bytes but share their entry node. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.", | |
| 203 | 206 | "consistency": "Capture each file from its validated open handle. Compare planned object identity, kind, size and modification time before capture and check planned objects again before publishing the completed ZIP; detected changes fail SourceChanged. This is not an atomic snapshot of an entire directory tree.", |
| 204 | 207 | "encryption": "AES-256 protects file contents using the existing AE-2 encoding. Directory entries are stored as zero-byte unencrypted directory records; entry names remain visible, as with other ZIP entries." |
| 205 | 208 | }, |
| @@ -222,5 +225,19 @@ | ||
| 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-and-client-implemented; native Windows/Wayland verification 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 and aggregate payload totals, 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 | 추가: "metadata": "Only after a valid ResourceReply(allow=true) for this job, select 64 MiB MetadataBudget and 262144 nodes, including ZIP/TAR/7z parsing, decoded 7z headers, XZ index/block bounds, member/path validation, implicit output parents and source planning. Legacy Start/StartInteractive, unapproved guarded jobs and slice APIs keep 8 MiB and 32768 nodes. Merely requesting expanded ceilings does not grant a larger budget. Names and source paths still consume checked byte budgets and implicit parents consume nodes, so long/deep paths can hit the metadata cap before 200000 entries. Approved source-path/pending-name copies consume bytes without duplicating their entry node. Expanded metadata jobs do not retain a universal 64 MiB RSS target.", | |
| 240 | 추가: "client": "Normal app jobs use StartGuarded with the existing 16 GiB and 10000-entry limits. Known selection/file estimates request expanded ceilings before processing. After a Limit result, offer an explicit expanded retry only after Terminal, both EOFs and child reap, with Publication::None, zero created/partial counts and complete cleanup. Retry uses a new job ID and requires fresh approval; existing or uncertain output instead shows the saved location and detailed result. App output records, including implicit parent directories, grow to 262144 nodes after any valid resource approval. Catalog entries grow to 200000 only for jobs granted the entries scope. Unapproved output records and catalogs without an entries grant retain their existing 100000 caps. Resource approval, ratio, retry and partial-output UI scenarios, tests and docs/ui-scenario-guide.md are implemented. Native Windows/Wayland verification remains separate.", | |
| 241 | 추가: "tests": "Use numeric 16/64 GiB and 10000/200000 policy boundaries, scaled worker limits, a compressed 257 MiB zero stream, and a virtual clock for the 60-second stall. Include client approval/retry tests in tests/rust-app-ui/guarded.rs and real-worker flows in tests/rust-app-real-worker/guarded_flows.rs. Do not write 64 GiB in tests." | |
| 225 | 242 | } |
| 226 | 243 | } |
| @@ -7,30 +7,74 @@ pub const MAX_PATH_DEPTH: usize = 64; | ||
| 7 | 7 | pub const MAX_METADATA_BYTES: usize = 8 * 1024 * 1024; |
| 8 | 8 | pub const MAX_OUTPUT_NODES: usize = 32_768; |
| 9 | 9 | |
| 10 | 추가: #[derive(Clone, Copy, Debug, Eq, PartialEq)] | |
| 11 | 추가: pub struct MetadataLimits { | |
| 12 | 추가: pub(crate) bytes: usize, | |
| 13 | 추가: pub(crate) nodes: usize, | |
| 14 | 추가: pub(crate) enlarged: bool, | |
| 15 | 추가: } | |
| 16 | 추가: impl Default for MetadataLimits { | |
| 17 | 추가: fn default() -> Self { | |
| 18 | 추가: Self { | |
| 19 | 추가: bytes: MAX_METADATA_BYTES, | |
| 20 | 추가: nodes: MAX_OUTPUT_NODES, | |
| 21 | 추가: enlarged: false, | |
| 22 | 추가: } | |
| 23 | 추가: } | |
| 24 | 추가: } | |
| 25 | 추가: impl MetadataLimits { | |
| 26 | 추가: pub(crate) fn approved() -> Self { | |
| 27 | 추가: Self { | |
| 28 | 추가: bytes: 64 * 1024 * 1024, | |
| 29 | 추가: nodes: 262_144, | |
| 30 | 추가: enlarged: true, | |
| 31 | 추가: } | |
| 32 | 추가: } | |
| 33 | 추가: } | |
| 34 | 추가: | |
| 10 | 35 | #[derive(Default)] |
| 11 | 36 | pub(crate) struct MetadataBudget { |
| 12 | 37 | bytes: usize, |
| 13 | 38 | nodes: usize, |
| 14 | 39 | } |
| 15 | 40 | impl MetadataBudget { |
| 41 | 추가: fn charge_cost(&mut self, bytes: usize, nodes: usize, limits: MetadataLimits) -> Result<()> { | |
| 42 | 추가: let bytes = self | |
| 43 | 추가: .bytes | |
| 44 | 추가: .checked_add(bytes) | |
| 45 | 추가: .filter(|n| *n <= limits.bytes) | |
| 46 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 47 | 추가: let nodes = self | |
| 48 | 추가: .nodes | |
| 49 | 추가: .checked_add(nodes) | |
| 50 | 추가: .filter(|n| *n <= limits.nodes) | |
| 51 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 52 | 추가: self.bytes = bytes; | |
| 53 | 추가: self.nodes = nodes; | |
| 54 | 추가: Ok(()) | |
| 55 | 추가: } | |
| 16 | 56 | pub(crate) fn charge(&mut self, name: &str) -> Result<()> { |
| 57 | 추가: self.charge_with(name, MetadataLimits::default()) | |
| 58 | 추가: } | |
| 59 | 추가: pub(crate) fn charge_with(&mut self, name: &str, limits: MetadataLimits) -> Result<()> { | |
| 17 | 60 | // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함. |
| 18 | 61 | let cost = name |
| 19 | 62 | .len() |
| 20 | 63 | .checked_mul(4) |
| 21 | 64 | .and_then(|n| n.checked_add(256)) |
| 22 | 65 | .ok_or(ErrorCode::Limit)?; |
| 23 | 삭제: self.bytes = self | |
| 24 | 삭제: .bytes | |
| 25 | 삭제: .checked_add(cost) | |
| 26 | 삭제: .filter(|n| *n <= MAX_METADATA_BYTES) | |
| 27 | 삭제: .ok_or(ErrorCode::Limit)?; | |
| 28 | 삭제: self.nodes = self | |
| 29 | 삭제: .nodes | |
| 30 | 삭제: .checked_add(1) | |
| 31 | 삭제: .filter(|n| *n <= MAX_OUTPUT_NODES) | |
| 32 | 삭제: .ok_or(ErrorCode::Limit)?; | |
| 33 | 삭제: Ok(()) | |
| 66 | 추가: self.charge_cost(cost, 1, limits) | |
| 67 | 추가: } | |
| 68 | 추가: pub(crate) fn charge_copy(&mut self, name: &str, limits: MetadataLimits) -> Result<()> { | |
| 69 | 추가: if !limits.enlarged { | |
| 70 | 추가: return self.charge_with(name, limits); | |
| 71 | 추가: } | |
| 72 | 추가: // 확대 계획의 경로와 대기 이름은 기존 항목 노드에 속한 복사 비용임. | |
| 73 | 추가: self.charge_cost( | |
| 74 | 추가: name.len().checked_mul(4).ok_or(ErrorCode::Limit)?, | |
| 75 | 추가: 0, | |
| 76 | 추가: limits, | |
| 77 | 추가: ) | |
| 34 | 78 | } |
| 35 | 79 | } |
| 36 | 80 | |
| @@ -99,44 +143,61 @@ pub fn valid_name(name: &str, directory: bool) -> Result<String> { | ||
| 99 | 143 | Ok(name.to_owned()) |
| 100 | 144 | } |
| 101 | 145 | pub fn validate_members(members: &[Member]) -> Result<()> { |
| 146 | 추가: validate_members_with(members, &mut || Ok(())) | |
| 147 | 추가: } | |
| 148 | 추가: pub(crate) fn validate_members_with( | |
| 149 | 추가: members: &[Member], | |
| 150 | 추가: check: &mut impl crate::resources::Monitor, | |
| 151 | 추가: ) -> Result<()> { | |
| 102 | 152 | let mut names = BTreeMap::<String, bool>::new(); |
| 103 | 153 | let mut budget = MetadataBudget::default(); |
| 104 | 154 | for member in members { |
| 105 | 삭제: budget.charge(&member.entry.name)?; | |
| 155 | 추가: check.check()?; | |
| 156 | 추가: budget.charge_with(&member.entry.name, check.metadata_limits())?; | |
| 106 | 157 | let directory = member.entry.kind == EntryKind::Directory; |
| 107 | 158 | let name = valid_name(&member.entry.name, directory)?.to_lowercase(); |
| 108 | 159 | if names.insert(name, directory).is_some() { |
| 109 | 160 | return Err(ErrorCode::Conflict); |
| 110 | 161 | } |
| 162 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 111 | 163 | } |
| 112 | 164 | for name in names.keys() { |
| 165 | 추가: check.check()?; | |
| 113 | 166 | let mut parent = name.as_str(); |
| 114 | 167 | while let Some((p, _)) = parent.rsplit_once('/') { |
| 115 | 168 | if names.get(p) == Some(&false) { |
| 116 | 169 | return Err(ErrorCode::Conflict); |
| 117 | 170 | } |
| 118 | 171 | parent = p; |
| 172 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 119 | 173 | } |
| 174 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 120 | 175 | } |
| 121 | 176 | Ok(()) |
| 122 | 177 | } |
| 123 | 삭제: pub(crate) fn output_directories(members: &[Member]) -> Result<BTreeSet<String>> { | |
| 124 | 삭제: validate_members(members)?; | |
| 178 | 추가: pub(crate) fn output_directories( | |
| 179 | 추가: members: &[Member], | |
| 180 | 추가: check: &mut impl crate::resources::Monitor, | |
| 181 | 추가: ) -> Result<BTreeSet<String>> { | |
| 182 | 추가: validate_members_with(members, check)?; | |
| 125 | 183 | let mut budget = MetadataBudget::default(); |
| 126 | 184 | let mut dirs = BTreeSet::new(); |
| 127 | 185 | for member in members { |
| 128 | 삭제: budget.charge(&member.entry.name)?; | |
| 186 | 추가: check.check()?; | |
| 187 | 추가: budget.charge_with(&member.entry.name, check.metadata_limits())?; | |
| 129 | 188 | if member.entry.kind == EntryKind::Directory && !dirs.contains(member.entry.name.as_str()) { |
| 130 | 189 | dirs.insert(member.entry.name.clone()); |
| 131 | 190 | } |
| 132 | 191 | let mut name = member.entry.name.as_str(); |
| 133 | 192 | while let Some((parent, _)) = name.rsplit_once('/') { |
| 134 | 193 | if !dirs.contains(parent) { |
| 135 | 삭제: budget.charge(parent)?; | |
| 194 | 추가: budget.charge_with(parent, check.metadata_limits())?; | |
| 136 | 195 | dirs.insert(parent.to_owned()); |
| 137 | 196 | } |
| 138 | 197 | name = parent; |
| 198 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 139 | 199 | } |
| 200 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 140 | 201 | } |
| 141 | 202 | Ok(dirs) |
| 142 | 203 | } |
| @@ -158,13 +219,13 @@ fn inflate( | ||
| 158 | 219 | input: &[u8], |
| 159 | 220 | gzip: bool, |
| 160 | 221 | limit: u64, |
| 161 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 222 | 추가: check: &mut impl crate::resources::Monitor, | |
| 162 | 223 | ) -> Result<(Vec<u8>, usize)> { |
| 163 | 224 | let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); |
| 164 | 225 | let mut out = Vec::new(); |
| 165 | 226 | let mut buffer = [0; 65536]; |
| 166 | 227 | loop { |
| 167 | 삭제: check()?; | |
| 228 | 추가: check.check()?; | |
| 168 | 229 | let before_in = stream.total_in(); |
| 169 | 230 | let before_out = stream.total_out(); |
| 170 | 231 | let status = stream |
| @@ -184,7 +245,11 @@ fn inflate( | ||
| 184 | 245 | } |
| 185 | 246 | } |
| 186 | 247 | } |
| 187 | 삭제: fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 248 | 추가: fn gzip( | |
| 249 | 추가: input: &[u8], | |
| 250 | 추가: limits: Limits, | |
| 251 | 추가: check: &mut impl crate::resources::Monitor, | |
| 252 | 추가: ) -> Result<Vec<u8>> { | |
| 188 | 253 | let mut at = 0; |
| 189 | 254 | let mut result = Vec::new(); |
| 190 | 255 | while at < input.len() { |
| @@ -230,14 +295,14 @@ fn tar( | ||
| 230 | 295 | input: &[u8], |
| 231 | 296 | limits: Limits, |
| 232 | 297 | decode: bool, |
| 233 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 298 | 추가: check: &mut impl crate::resources::Monitor, | |
| 234 | 299 | ) -> Result<Vec<Member>> { |
| 235 | 300 | let mut at = 0; |
| 236 | 301 | let mut members = Vec::new(); |
| 237 | 302 | let mut total = 0u64; |
| 238 | 303 | let mut metadata = MetadataBudget::default(); |
| 239 | 304 | loop { |
| 240 | 삭제: check()?; | |
| 305 | 추가: check.check()?; | |
| 241 | 306 | let header = part(input, at, 512)?; |
| 242 | 307 | if header.iter().all(|b| *b == 0) { |
| 243 | 308 | if part(input, at + 512, 512)?.iter().any(|b| *b != 0) |
| @@ -394,7 +459,7 @@ fn zip( | ||
| 394 | 459 | limits: Limits, |
| 395 | 460 | decode: bool, |
| 396 | 461 | password: Option<&[u8]>, |
| 397 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 462 | 추가: check: &mut impl crate::resources::Monitor, | |
| 398 | 463 | ) -> Result<Vec<Member>> { |
| 399 | 464 | if input.len() < 22 { |
| 400 | 465 | return Err(ErrorCode::Integrity); |
| @@ -432,7 +497,7 @@ fn zip( | ||
| 432 | 497 | let mut total = 0u64; |
| 433 | 498 | let mut metadata = MetadataBudget::default(); |
| 434 | 499 | for id in 0..count { |
| 435 | 삭제: check()?; | |
| 500 | 추가: check.check()?; | |
| 436 | 501 | let h = part(input, at, 46)?; |
| 437 | 502 | if &h[..4] != b"PK\x01\x02" { |
| 438 | 503 | return Err(ErrorCode::Integrity); |
| @@ -604,7 +669,7 @@ pub fn parse( | ||
| 604 | 669 | input: &[u8], |
| 605 | 670 | limits: Limits, |
| 606 | 671 | decode: bool, |
| 607 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 672 | 추가: check: &mut impl crate::resources::Monitor, | |
| 608 | 673 | ) -> Result<Catalog> { |
| 609 | 674 | parse_with_password(input, limits, decode, None, check) |
| 610 | 675 | } |
| @@ -613,7 +678,7 @@ pub fn parse_with_password( | ||
| 613 | 678 | limits: Limits, |
| 614 | 679 | decode: bool, |
| 615 | 680 | password: Option<&[u8]>, |
| 616 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 681 | 추가: check: &mut impl crate::resources::Monitor, | |
| 617 | 682 | ) -> Result<Catalog> { |
| 618 | 683 | if !limits.valid() { |
| 619 | 684 | return Err(ErrorCode::Limit); |
| @@ -666,12 +731,16 @@ pub fn parse_with_password( | ||
| 666 | 731 | } |
| 667 | 732 | Err(ErrorCode::UnsupportedFormat) |
| 668 | 733 | } |
| 669 | 삭제: fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 734 | 추가: fn deflate( | |
| 735 | 추가: input: &[u8], | |
| 736 | 추가: limit: u64, | |
| 737 | 추가: check: &mut impl crate::resources::Monitor, | |
| 738 | 추가: ) -> Result<Vec<u8>> { | |
| 670 | 739 | let mut stream = Deflate::new(6, false, 15); |
| 671 | 740 | let mut output = Vec::new(); |
| 672 | 741 | let mut buffer = [0; 65536]; |
| 673 | 742 | loop { |
| 674 | 삭제: check()?; | |
| 743 | 추가: check.check()?; | |
| 675 | 744 | let a = stream.total_in(); |
| 676 | 745 | let b = stream.total_out(); |
| 677 | 746 | let status = stream |
| @@ -700,7 +769,7 @@ pub fn create_zip( | ||
| 700 | 769 | members: &[Member], |
| 701 | 770 | method: Method, |
| 702 | 771 | limits: Limits, |
| 703 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 772 | 추가: check: &mut impl crate::resources::Monitor, | |
| 704 | 773 | ) -> Result<Vec<u8>> { |
| 705 | 774 | create_zip_with_password(members, method, limits, None, check) |
| 706 | 775 | } |
| @@ -709,7 +778,7 @@ pub fn create_zip_with_password( | ||
| 709 | 778 | method: Method, |
| 710 | 779 | limits: Limits, |
| 711 | 780 | password: Option<&[u8]>, |
| 712 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 781 | 추가: check: &mut impl crate::resources::Monitor, | |
| 713 | 782 | ) -> Result<Vec<u8>> { |
| 714 | 783 | if !limits.valid() { |
| 715 | 784 | return Err(ErrorCode::Limit); |
| @@ -723,7 +792,7 @@ pub fn create_zip_with_password( | ||
| 723 | 792 | let mut cd = Vec::new(); |
| 724 | 793 | let mut total = 0u64; |
| 725 | 794 | for m in members { |
| 726 | 삭제: check()?; | |
| 795 | 추가: check.check()?; | |
| 727 | 796 | total = total |
| 728 | 797 | .checked_add(m.data.len() as u64) |
| 729 | 798 | .filter(|n| *n <= limits.output) |
| @@ -808,3 +877,7 @@ pub fn create_zip_with_password( | ||
| 808 | 877 | bounded_append(&mut out, &end, limits.output)?; |
| 809 | 878 | Ok(out) |
| 810 | 879 | } |
| 880 | 추가: | |
| 881 | 추가: #[cfg(test)] | |
| 882 | 추가: #[path = "../../../tests/rust-archive-worker/metadata_policy.rs"] | |
| 883 | 추가: mod metadata_tests; |
| @@ -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,22 @@ 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 | 추가: crate::resources::completed(Ok(()), &mut **self.check.borrow_mut()) | |
| 51 | 추가: .map_err(|e| io::Error::other(InputError(e)))?; | |
| 52 | 추가: } | |
| 53 | 추가: Ok(n) | |
| 42 | 54 | } |
| 43 | 55 | } |
| 44 | 56 | |
| @@ -60,14 +72,26 @@ pub(crate) fn decode( | ||
| 60 | 72 | source: &mut File, |
| 61 | 73 | compression: Compression, |
| 62 | 74 | limit: u64, |
| 63 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 75 | 추가: check: &mut impl crate::resources::Monitor, | |
| 64 | 76 | ) -> Result<(File, u64)> { |
| 65 | 삭제: check()?; | |
| 77 | 추가: check.check()?; | |
| 66 | 78 | let expected = if matches!(compression, Compression::Xz) { |
| 67 | 79 | Some(xz_layout(source, limit, check)?) |
| 68 | 80 | } else { |
| 69 | 81 | None |
| 70 | 82 | }; |
| 83 | 추가: let packed_length = source.metadata().map_err(space::io_error)?.len(); | |
| 84 | 추가: if let Some(expected) = expected { | |
| 85 | 추가: check.observe( | |
| 86 | 추가: ResourceUsage { | |
| 87 | 추가: estimated_bytes: Some(expected), | |
| 88 | 추가: compressed_bytes: Some(packed_length), | |
| 89 | 추가: ratio_output_bytes: Some(expected), | |
| 90 | 추가: ..ResourceUsage::default() | |
| 91 | 추가: }, | |
| 92 | 추가: Some(source), | |
| 93 | 추가: )?; | |
| 94 | 추가: } | |
| 71 | 95 | source.rewind().map_err(space::io_error)?; |
| 72 | 96 | let mut output = spool::temporary()?; |
| 73 | 97 | let check = RefCell::new(check); |
| @@ -88,7 +112,7 @@ pub(crate) fn decode( | ||
| 88 | 112 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 89 | 113 | let mut total = 0u64; |
| 90 | 114 | loop { |
| 91 | 삭제: (check.borrow_mut())()?; | |
| 115 | 추가: check.borrow_mut().check()?; | |
| 92 | 116 | let count = reader.read(&mut buffer[..]).map_err(decode_error)?; |
| 93 | 117 | if count == 0 { |
| 94 | 118 | break; |
| @@ -97,13 +121,24 @@ pub(crate) fn decode( | ||
| 97 | 121 | .checked_add(count as u64) |
| 98 | 122 | .filter(|total| *total <= limit) |
| 99 | 123 | .ok_or(ErrorCode::Limit)?; |
| 124 | 추가: check.borrow_mut().observe( | |
| 125 | 추가: ResourceUsage { | |
| 126 | 추가: actual_bytes: Some(total), | |
| 127 | 추가: compressed_bytes: Some(packed_length), | |
| 128 | 추가: ratio_output_bytes: Some(total), | |
| 129 | 추가: ..ResourceUsage::default() | |
| 130 | 추가: }, | |
| 131 | 추가: Some(&output), | |
| 132 | 추가: )?; | |
| 133 | 추가: crate::resources::completed(Ok(()), &mut **check.borrow_mut())?; | |
| 100 | 134 | // 전체 검증 전에는 비공개 임시 파일에만 기록함. |
| 101 | 135 | space::ensure(&output, count as u64)?; |
| 102 | 삭제: output | |
| 103 | 삭제: .write_all(&buffer[..count]) | |
| 104 | 삭제: .map_err(space::io_error)?; | |
| 136 | 추가: crate::resources::completed( | |
| 137 | 추가: output.write_all(&buffer[..count]).map_err(space::io_error), | |
| 138 | 추가: &mut **check.borrow_mut(), | |
| 139 | 추가: )?; | |
| 105 | 140 | } |
| 106 | 삭제: (check.borrow_mut())()?; | |
| 141 | 추가: check.borrow_mut().check()?; | |
| 107 | 142 | if expected.is_some_and(|expected| expected != total) { |
| 108 | 143 | return Err(ErrorCode::Integrity); |
| 109 | 144 | } |
| @@ -114,9 +149,9 @@ fn read_at( | ||
| 114 | 149 | source: &mut File, |
| 115 | 150 | offset: u64, |
| 116 | 151 | bytes: &mut [u8], |
| 117 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 152 | 추가: check: &mut impl crate::resources::Monitor, | |
| 118 | 153 | ) -> Result<()> { |
| 119 | 삭제: check()?; | |
| 154 | 추가: check.check()?; | |
| 120 | 155 | source |
| 121 | 156 | .seek(std::io::SeekFrom::Start(offset)) |
| 122 | 157 | .map_err(space::io_error)?; |
| @@ -126,7 +161,8 @@ fn read_at( | ||
| 126 | 161 | } else { |
| 127 | 162 | ErrorCode::Io |
| 128 | 163 | } |
| 129 | 삭제: }) | |
| 164 | 추가: })?; | |
| 165 | 추가: crate::resources::completed(Ok(()), check) | |
| 130 | 166 | } |
| 131 | 167 | |
| 132 | 168 | fn vli(bytes: &[u8], cursor: &mut usize) -> Result<u64> { |
| @@ -150,7 +186,7 @@ fn lzma2_size( | ||
| 150 | 186 | mut at: u64, |
| 151 | 187 | end: u64, |
| 152 | 188 | expected: u64, |
| 153 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 189 | 추가: check: &mut impl crate::resources::Monitor, | |
| 154 | 190 | ) -> Result<()> { |
| 155 | 191 | let mut size = 0u64; |
| 156 | 192 | while at < end { |
| @@ -202,7 +238,7 @@ fn xz_block( | ||
| 202 | 238 | unpadded: u64, |
| 203 | 239 | size: u64, |
| 204 | 240 | check_size: u64, |
| 205 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 241 | 추가: check: &mut impl crate::resources::Monitor, | |
| 206 | 242 | ) -> Result<()> { |
| 207 | 243 | let mut header = [0; 1024]; |
| 208 | 244 | read_at(source, start, &mut header[..1], check)?; |
| @@ -262,7 +298,11 @@ fn xz_block( | ||
| 262 | 298 | } |
| 263 | 299 | |
| 264 | 300 | // 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함. |
| 265 | 삭제: fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<u64> { | |
| 301 | 추가: fn xz_layout( | |
| 302 | 추가: source: &mut File, | |
| 303 | 추가: limit: u64, | |
| 304 | 추가: check: &mut impl crate::resources::Monitor, | |
| 305 | 추가: ) -> Result<u64> { | |
| 266 | 306 | use zlib_rs::crc32::crc32; |
| 267 | 307 | let mut end = source.metadata().map_err(space::io_error)?.len(); |
| 268 | 308 | let mut total = 0u64; |
| @@ -278,7 +318,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 278 | 318 | end = at; |
| 279 | 319 | } |
| 280 | 320 | streams += 1; |
| 281 | 삭제: if streams > crate::archive::MAX_OUTPUT_NODES { | |
| 321 | 추가: if streams > check.metadata_limits().nodes { | |
| 282 | 322 | return Err(ErrorCode::Limit); |
| 283 | 323 | } |
| 284 | 324 | let footer_at = end.checked_sub(12).ok_or(ErrorCode::Integrity)?; |
| @@ -290,7 +330,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 290 | 330 | return Err(ErrorCode::Integrity); |
| 291 | 331 | } |
| 292 | 332 | let index_len = (u64::from(u32::from_le_bytes(footer[4..8].try_into().unwrap())) + 1) * 4; |
| 293 | 삭제: if index_len > crate::archive::MAX_METADATA_BYTES as u64 { | |
| 333 | 추가: if index_len > check.metadata_limits().bytes as u64 { | |
| 294 | 334 | return Err(ErrorCode::Limit); |
| 295 | 335 | } |
| 296 | 336 | if index_len < 8 { |
| @@ -310,13 +350,13 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 310 | 350 | } |
| 311 | 351 | let mut cursor = 1; |
| 312 | 352 | let count = vli(&index[..data_end], &mut cursor)?; |
| 313 | 삭제: if count > crate::archive::MAX_OUTPUT_NODES as u64 { | |
| 353 | 추가: if count > check.metadata_limits().nodes as u64 { | |
| 314 | 354 | return Err(ErrorCode::Limit); |
| 315 | 355 | } |
| 316 | 356 | let mut blocks = 0u64; |
| 317 | 357 | let mut records = Vec::new(); |
| 318 | 358 | for _ in 0..count { |
| 319 | 삭제: check()?; | |
| 359 | 추가: check.check()?; | |
| 320 | 360 | let unpadded = vli(&index[..data_end], &mut cursor)?; |
| 321 | 361 | let size = vli(&index[..data_end], &mut cursor)?; |
| 322 | 362 | if unpadded == 0 { |
| @@ -330,6 +370,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 330 | 370 | .filter(|total| *total <= limit) |
| 331 | 371 | .ok_or(ErrorCode::Limit)?; |
| 332 | 372 | records.push((unpadded, size)); |
| 373 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 333 | 374 | } |
| 334 | 375 | if data_end - cursor > 3 || index[cursor..data_end].iter().any(|byte| *byte != 0) { |
| 335 | 376 | return Err(ErrorCode::Integrity); |
| @@ -357,6 +398,7 @@ fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<( | ||
| 357 | 398 | for (unpadded, size) in records { |
| 358 | 399 | xz_block(source, block_at, unpadded, size, check_size, check)?; |
| 359 | 400 | block_at += (unpadded + 3) & !3; |
| 401 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 360 | 402 | } |
| 361 | 403 | end = start; |
| 362 | 404 | } |
| @@ -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,14 +52,17 @@ 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 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 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; |
| 65 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 63 | 66 | } |
| 64 | 67 | if size != length { |
| 65 | 68 | return Err(ErrorCode::SourceChanged); |
| @@ -68,12 +71,12 @@ fn pack( | ||
| 68 | 71 | } |
| 69 | 72 | let mut stream = Deflate::new(6, false, 15); |
| 70 | 73 | loop { |
| 71 | 삭제: check()?; | |
| 74 | 추가: check.check()?; | |
| 72 | 75 | let n = io(input.read(&mut buffer[..]))?; |
| 73 | 76 | crc = crc32(crc, &buffer[..n]); |
| 74 | 77 | let mut used = 0; |
| 75 | 78 | loop { |
| 76 | 삭제: check()?; | |
| 79 | 추가: check.check()?; | |
| 77 | 80 | let a = stream.total_in(); |
| 78 | 81 | let b = stream.total_out(); |
| 79 | 82 | let status = stream |
| @@ -89,7 +92,11 @@ fn pack( | ||
| 89 | 92 | .map_err(|_| ErrorCode::Internal)?; |
| 90 | 93 | used += (stream.total_in() - a) as usize; |
| 91 | 94 | let written = (stream.total_out() - b) as usize; |
| 95 | 추가: crate::space::ensure(output, written as u64)?; | |
| 92 | 96 | io(output.write_all(&encoded[..written]))?; |
| 97 | 추가: if used != 0 || written != 0 { | |
| 98 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 99 | 추가: } | |
| 93 | 100 | size = size.checked_add(written as u64).ok_or(ErrorCode::Limit)?; |
| 94 | 101 | if status == Status::StreamEnd { |
| 95 | 102 | if stream.total_in() != length { |
| @@ -110,7 +117,7 @@ pub(crate) use crate::create_sources::Plan; | ||
| 110 | 117 | pub(crate) fn plan( |
| 111 | 118 | sources: &[Source], |
| 112 | 119 | limits: Limits, |
| 113 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 120 | 추가: check: &mut impl crate::resources::Monitor, | |
| 114 | 121 | ) -> Result<Plan> { |
| 115 | 122 | Plan::new(sources, limits, check) |
| 116 | 123 | } |
| @@ -119,7 +126,7 @@ pub(crate) fn zip( | ||
| 119 | 126 | method: Method, |
| 120 | 127 | limits: Limits, |
| 121 | 128 | password: Option<&[u8]>, |
| 122 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 129 | 추가: check: &mut impl crate::resources::Monitor, | |
| 123 | 130 | ) -> Result<(File, u64)> { |
| 124 | 131 | let mut output = spool::temporary()?; |
| 125 | 132 | let mut central = Vec::new(); |
| @@ -130,13 +137,13 @@ pub(crate) fn zip( | ||
| 130 | 137 | let directory = member.entry.kind == EntryKind::Directory; |
| 131 | 138 | let method = if directory { Method::Store } else { method }; |
| 132 | 139 | let password = if directory { None } else { password }; |
| 133 | 삭제: check()?; | |
| 140 | 추가: check.check()?; | |
| 134 | 141 | let remaining = limits |
| 135 | 142 | .input |
| 136 | 143 | .min(limits.output) |
| 137 | 144 | .checked_sub(total) |
| 138 | 145 | .ok_or(ErrorCode::Limit)?; |
| 139 | 삭제: let mut input = source.open()?; | |
| 146 | 추가: let mut input = crate::resources::completed(source.open(), check)?; | |
| 140 | 147 | let mut snapshot = if directory { |
| 141 | 148 | None |
| 142 | 149 | } else { |
| @@ -217,6 +224,7 @@ pub(crate) fn zip( | ||
| 217 | 224 | header.extend(name); |
| 218 | 225 | header.extend(extra); |
| 219 | 226 | io(output.write_all(&header))?; |
| 227 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 220 | 228 | io(packed.rewind())?; |
| 221 | 229 | if let Some(password) = password { |
| 222 | 230 | crate::crypto::aes_encrypt_file( |
| @@ -229,12 +237,14 @@ pub(crate) fn zip( | ||
| 229 | 237 | } else { |
| 230 | 238 | let mut buffer = Zeroizing::new([0; 65536]); |
| 231 | 239 | loop { |
| 232 | 삭제: check()?; | |
| 240 | 추가: check.check()?; | |
| 233 | 241 | let n = io(packed.read(&mut buffer[..]))?; |
| 234 | 242 | if n == 0 { |
| 235 | 243 | break; |
| 236 | 244 | } |
| 245 | 추가: crate::space::ensure(&output, n as u64)?; | |
| 237 | 246 | io(output.write_all(&buffer[..n]))?; |
| 247 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 238 | 248 | } |
| 239 | 249 | } |
| 240 | 250 | let mut extra = zip64_extra(length, packed_size, Some(offset)); |
| @@ -276,14 +286,21 @@ pub(crate) fn zip( | ||
| 276 | 286 | ); |
| 277 | 287 | central.extend(name); |
| 278 | 288 | central.extend(extra); |
| 289 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 279 | 290 | } |
| 280 | 삭제: check()?; | |
| 291 | 추가: check.check()?; | |
| 281 | 292 | let at = io(output.stream_position())?; |
| 282 | 293 | crate::space::ensure(&output, central.len() as u64 + 98)?; |
| 283 | 삭제: io(output.write_all(¢ral))?; | |
| 294 | 추가: if !central.is_empty() { | |
| 295 | 추가: crate::resources::completed(io(output.write_all(¢ral)), check)?; | |
| 296 | 추가: } | |
| 284 | 297 | let large_at = io(output.stream_position())?; |
| 285 | 298 | let mut end = Vec::new(); |
| 286 | 삭제: if have_zip64 || at >= u32::MAX as u64 || central.len() >= u32::MAX as usize { | |
| 299 | 추가: if have_zip64 | |
| 300 | 추가: || plan.items.len() >= u16::MAX as usize | |
| 301 | 추가: || at >= u32::MAX as u64 | |
| 302 | 추가: || central.len() >= u32::MAX as usize | |
| 303 | 추가: { | |
| 287 | 304 | end.extend(b"PK\x06\x06"); |
| 288 | 305 | put64(&mut end, 44); |
| 289 | 306 | put16(&mut end, 45); |
| @@ -316,7 +333,7 @@ pub(crate) fn zip( | ||
| 316 | 333 | put32(&mut end, at as u32); |
| 317 | 334 | put16(&mut end, 0); |
| 318 | 335 | } |
| 319 | 삭제: io(output.write_all(&end))?; | |
| 336 | 추가: crate::resources::completed(io(output.write_all(&end)), check)?; | |
| 320 | 337 | plan.verify(check)?; |
| 321 | 338 | let size = io(output.stream_position())?; |
| 322 | 339 | io(output.rewind())?; |
| @@ -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,26 +214,32 @@ 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); |
| 221 | 221 | } |
| 222 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 222 | 223 | } |
| 223 | 224 | for source in sources { |
| 224 | 225 | let path = source.path.to_path()?; |
| 225 | 삭제: let input = Input::open(&path)?; | |
| 226 | 추가: let input = crate::resources::completed(Input::open(&path), check)?; | |
| 226 | 227 | plan.visit(path, source.archive_name.clone(), input, check)?; |
| 227 | 228 | } |
| 228 | 229 | let members = plan |
| 229 | 230 | .items |
| 230 | 231 | .iter() |
| 231 | 삭제: .map(|p| Member { | |
| 232 | 삭제: entry: p.member.entry.clone(), | |
| 233 | 삭제: data: Vec::new(), | |
| 232 | 추가: .map(|p| { | |
| 233 | 추가: crate::resources::completed( | |
| 234 | 추가: Ok(Member { | |
| 235 | 추가: entry: p.member.entry.clone(), | |
| 236 | 추가: data: Vec::new(), | |
| 237 | 추가: }), | |
| 238 | 추가: check, | |
| 239 | 추가: ) | |
| 234 | 240 | }) |
| 235 | 삭제: .collect::<Vec<_>>(); | |
| 236 | 삭제: archive::validate_members(&members)?; | |
| 241 | 추가: .collect::<Result<Vec<_>>>()?; | |
| 242 | 추가: archive::validate_members_with(&members, check)?; | |
| 237 | 243 | Ok(plan) |
| 238 | 244 | } |
| 239 | 245 | fn visit( |
| @@ -241,23 +247,36 @@ impl Plan { | ||
| 241 | 247 | path: PathBuf, |
| 242 | 248 | name: String, |
| 243 | 249 | input: Input, |
| 244 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 250 | 추가: check: &mut impl crate::resources::Monitor, | |
| 245 | 251 | ) -> Result<()> { |
| 246 | 삭제: check()?; | |
| 252 | 추가: check.check()?; | |
| 247 | 253 | if self.items.len() >= self.limits.entries as usize { |
| 248 | 254 | return Err(ErrorCode::Limit); |
| 249 | 255 | } |
| 250 | 삭제: let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?; | |
| 256 | 추가: let metadata: Metadata = crate::resources::completed( | |
| 257 | 추가: input.file.metadata().map_err(crate::space::io_error), | |
| 258 | 추가: check, | |
| 259 | 추가: )?; | |
| 251 | 260 | let directory = metadata.is_dir(); |
| 252 | 261 | let name = archive::valid_name(&name, directory)?; |
| 253 | 삭제: self.budget.charge(&name)?; | |
| 254 | 삭제: self.budget.charge(&path.to_string_lossy())?; | |
| 262 | 추가: self.budget.charge_with(&name, check.metadata_limits())?; | |
| 263 | 추가: self.budget | |
| 264 | 추가: .charge_copy(&path.to_string_lossy(), check.metadata_limits())?; | |
| 255 | 265 | let size = if directory { 0 } else { metadata.len() }; |
| 256 | 266 | self.total = self |
| 257 | 267 | .total |
| 258 | 268 | .checked_add(size) |
| 259 | 269 | .filter(|n| *n <= self.limits.input.min(self.limits.output)) |
| 260 | 270 | .ok_or(ErrorCode::Limit)?; |
| 271 | 추가: check.observe( | |
| 272 | 추가: ResourceUsage { | |
| 273 | 추가: estimated_bytes: Some(self.total), | |
| 274 | 추가: actual_entries: Some(self.items.len() as u32 + 1), | |
| 275 | 추가: ..ResourceUsage::default() | |
| 276 | 추가: }, | |
| 277 | 추가: None, | |
| 278 | 추가: )?; | |
| 279 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 261 | 280 | self.items.push(Planned { |
| 262 | 281 | member: Member { |
| 263 | 282 | entry: Entry { |
| @@ -275,13 +294,13 @@ impl Plan { | ||
| 275 | 294 | data: Vec::new(), |
| 276 | 295 | }, |
| 277 | 296 | path: path.clone(), |
| 278 | 삭제: object: filesystem::object(&input.file)?, | |
| 297 | 추가: object: crate::resources::completed(filesystem::object(&input.file), check)?, | |
| 279 | 298 | modified: metadata.modified().ok(), |
| 280 | 299 | }); |
| 281 | 300 | if directory { |
| 282 | 301 | let mut children = Vec::new(); |
| 283 | 302 | for entry in input.children(&path)? { |
| 284 | 삭제: check()?; | |
| 303 | 추가: check.check()?; | |
| 285 | 304 | if self.items.len() + children.len() >= self.limits.entries as usize { |
| 286 | 305 | return Err(ErrorCode::Limit); |
| 287 | 306 | } |
| @@ -290,21 +309,31 @@ impl Plan { | ||
| 290 | 309 | .file_name() |
| 291 | 310 | .into_string() |
| 292 | 311 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 293 | 삭제: self.budget.charge(&leaf)?; | |
| 312 | 추가: self.budget.charge_copy(&leaf, check.metadata_limits())?; | |
| 294 | 313 | children.push(leaf); |
| 314 | 추가: check.observe( | |
| 315 | 추가: ResourceUsage { | |
| 316 | 추가: estimated_bytes: Some(self.total), | |
| 317 | 추가: estimated_entries: Some((self.items.len() + children.len()) as u32), | |
| 318 | 추가: ..ResourceUsage::default() | |
| 319 | 추가: }, | |
| 320 | 추가: None, | |
| 321 | 추가: )?; | |
| 322 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 295 | 323 | } |
| 296 | 324 | children.sort(); |
| 297 | 325 | for leaf in children { |
| 298 | 삭제: let child = input.open_child(&path, &leaf)?; | |
| 326 | 추가: let child = crate::resources::completed(input.open_child(&path, &leaf), check)?; | |
| 299 | 327 | self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?; |
| 300 | 328 | } |
| 301 | 329 | } |
| 302 | 330 | Ok(()) |
| 303 | 331 | } |
| 304 | 삭제: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> { | |
| 332 | 추가: pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> { | |
| 305 | 333 | for item in &self.items { |
| 306 | 삭제: check()?; | |
| 334 | 추가: check.check()?; | |
| 307 | 335 | item.open()?; |
| 336 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 308 | 337 | } |
| 309 | 338 | Ok(()) |
| 310 | 339 | } |
| @@ -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 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 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 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 337 | 340 | } |
| 338 | 341 | output |
| 339 | 342 | .write_all(&mac.finalize().into_bytes()[..10]) |
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | use crate::archive::valid_name; |
| 2 | 2 | use crate::protocol::*; |
| 3 | 추가: use crate::resources::{Monitor, completed}; | |
| 3 | 4 | use sha2::{Digest, Sha256}; |
| 4 | 5 | use std::fs::{File, OpenOptions}; |
| 5 | 6 | use std::io::{Read, Write}; |
| @@ -90,7 +91,7 @@ pub fn object(file: &File) -> Result<SourceObject> { | ||
| 90 | 91 | pub fn snapshot( |
| 91 | 92 | path: &Path, |
| 92 | 93 | limit: u64, |
| 93 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 94 | 추가: check: &mut impl crate::resources::Monitor, | |
| 94 | 95 | ) -> Result<Snapshot> { |
| 95 | 96 | let mut options = OpenOptions::new(); |
| 96 | 97 | options.read(true); |
| @@ -117,7 +118,7 @@ pub fn snapshot( | ||
| 117 | 118 | let mut hash = Sha256::new(); |
| 118 | 119 | let mut buffer = [0; 65536]; |
| 119 | 120 | loop { |
| 120 | 삭제: check()?; | |
| 121 | 추가: check.check()?; | |
| 121 | 122 | let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?; |
| 122 | 123 | if n == 0 { |
| 123 | 124 | break; |
| @@ -128,6 +129,7 @@ pub fn snapshot( | ||
| 128 | 129 | bytes.try_reserve(n).map_err(|_| ErrorCode::Limit)?; |
| 129 | 130 | bytes.extend_from_slice(&buffer[..n]); |
| 130 | 131 | hash.update(&buffer[..n]); |
| 132 | 추가: completed(Ok(()), check)?; | |
| 131 | 133 | } |
| 132 | 134 | let after = file.metadata().map_err(|_| ErrorCode::Io)?; |
| 133 | 135 | let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?; |
| @@ -493,12 +495,17 @@ mod platform { | ||
| 493 | 495 | #[cfg(not(any(target_os = "linux", windows)))] |
| 494 | 496 | compile_error!("Archive worker supports Linux and Windows only"); |
| 495 | 497 | pub use platform::Dir; |
| 496 | 삭제: fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> { | |
| 498 | 추가: fn parent_with( | |
| 499 | 추가: root: &Dir, | |
| 500 | 추가: name: &str, | |
| 501 | 추가: create: bool, | |
| 502 | 추가: check: &mut impl Monitor, | |
| 503 | 추가: ) -> Result<Option<(Dir, String)>> { | |
| 497 | 504 | let mut parts = name.split('/').collect::<Vec<_>>(); |
| 498 | 505 | let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?; |
| 499 | 506 | let mut d = root.duplicate()?; |
| 500 | 507 | for p in parts { |
| 501 | 삭제: match d.child(p, create)? { | |
| 508 | 추가: match completed(d.child(p, create), check)? { | |
| 502 | 509 | Some(child) => d = child, |
| 503 | 510 | None => return Ok(None), |
| 504 | 511 | } |
| @@ -506,25 +513,46 @@ fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> | ||
| 506 | 513 | Ok(Some((d, leaf.to_owned()))) |
| 507 | 514 | } |
| 508 | 515 | pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> { |
| 516 | 추가: existing_with(root, name, &mut || Ok(())) | |
| 517 | 추가: } | |
| 518 | 추가: pub(crate) fn existing_with( | |
| 519 | 추가: root: &Dir, | |
| 520 | 추가: name: &str, | |
| 521 | 추가: check: &mut impl Monitor, | |
| 522 | 추가: ) -> Result<Option<Existing>> { | |
| 509 | 523 | valid_name(name, false)?; |
| 510 | 삭제: match parent(root, name, false)? { | |
| 524 | 추가: let result = match parent_with(root, name, false, check)? { | |
| 511 | 525 | Some((dir, leaf)) => dir.existing(&leaf), |
| 512 | 526 | None => Ok(None), |
| 513 | 삭제: } | |
| 527 | 추가: }; | |
| 528 | 추가: completed(result, check) | |
| 514 | 529 | } |
| 515 | 530 | pub fn unused(root: &Dir, name: &str) -> Result<bool> { |
| 531 | 추가: unused_with(root, name, &mut || Ok(())) | |
| 532 | 추가: } | |
| 533 | 추가: pub(crate) fn unused_with(root: &Dir, name: &str, check: &mut impl Monitor) -> Result<bool> { | |
| 516 | 534 | valid_name(name, false)?; |
| 517 | 삭제: match parent(root, name, false)? { | |
| 535 | 추가: let result = match parent_with(root, name, false, check)? { | |
| 518 | 536 | Some((dir, leaf)) => dir.absent(&leaf), |
| 519 | 537 | None => Ok(true), |
| 520 | 삭제: } | |
| 538 | 추가: }; | |
| 539 | 추가: completed(result, check) | |
| 521 | 540 | } |
| 522 | 541 | pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { |
| 523 | 542 | preflight_mode(root, names, false) |
| 524 | 543 | } |
| 525 | 544 | pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> { |
| 545 | 추가: preflight_mode_with(root, names, interactive, &mut || Ok(())) | |
| 546 | 추가: } | |
| 547 | 추가: pub(crate) fn preflight_mode_with( | |
| 548 | 추가: root: &Dir, | |
| 549 | 추가: names: &[(String, EntryKind)], | |
| 550 | 추가: interactive: bool, | |
| 551 | 추가: check: &mut impl Monitor, | |
| 552 | 추가: ) -> Result<()> { | |
| 526 | 553 | for (name, kind) in names { |
| 527 | 삭제: if let Some((d, leaf)) = parent(root, name, false)? { | |
| 554 | 추가: check.check()?; | |
| 555 | 추가: if let Some((d, leaf)) = parent_with(root, name, false, check)? { | |
| 528 | 556 | if *kind == EntryKind::Directory { |
| 529 | 557 | let _ = d.child(&leaf, false)?; |
| 530 | 558 | } else if interactive { |
| @@ -533,13 +561,15 @@ pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bo | ||
| 533 | 561 | return Err(ErrorCode::Conflict); |
| 534 | 562 | } |
| 535 | 563 | } |
| 564 | 추가: completed(Ok(()), check)?; | |
| 536 | 565 | } |
| 537 | 566 | Ok(()) |
| 538 | 567 | } |
| 539 | 삭제: pub(crate) fn preflight_space( | |
| 568 | 추가: pub(crate) fn preflight_space_with( | |
| 540 | 569 | root: &Dir, |
| 541 | 570 | files: &[(String, u64)], |
| 542 | 571 | staging: Option<(&File, u64)>, |
| 572 | 추가: check: &mut impl Monitor, | |
| 543 | 573 | ) -> Result<()> { |
| 544 | 574 | let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new(); |
| 545 | 575 | let mut charge = |file: &File, bytes: u64| -> Result<()> { |
| @@ -556,7 +586,7 @@ pub(crate) fn preflight_space( | ||
| 556 | 586 | Ok(()) |
| 557 | 587 | }; |
| 558 | 588 | if let Some((file, bytes)) = staging { |
| 559 | 삭제: charge(file, bytes)?; | |
| 589 | 추가: completed(charge(file, bytes), check)?; | |
| 560 | 590 | } |
| 561 | 591 | for (name, size) in files { |
| 562 | 592 | valid_name(name, false)?; |
| @@ -564,26 +594,38 @@ pub(crate) fn preflight_space( | ||
| 564 | 594 | let mut parts = name.split('/').collect::<Vec<_>>(); |
| 565 | 595 | parts.pop(); |
| 566 | 596 | for part in parts { |
| 567 | 삭제: match parent.child(part, false)? { | |
| 597 | 추가: match completed(parent.child(part, false), check)? { | |
| 568 | 598 | Some(child) => parent = child, |
| 569 | 599 | None => break, |
| 570 | 600 | } |
| 571 | 601 | } |
| 572 | 삭제: charge(parent.handle(), *size)?; | |
| 602 | 추가: completed(charge(parent.handle(), *size), check)?; | |
| 573 | 603 | } |
| 574 | 604 | for (file, bytes) in volumes.values() { |
| 575 | 삭제: crate::space::ensure(file, *bytes)?; | |
| 605 | 추가: completed(crate::space::ensure(file, *bytes), check)?; | |
| 576 | 606 | } |
| 577 | 607 | Ok(()) |
| 578 | 608 | } |
| 579 | 609 | pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 580 | 삭제: let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?; | |
| 581 | 삭제: if d.child(&leaf, false)?.is_some() { | |
| 610 | 추가: directory_with(root, name, &mut || Ok(())) | |
| 611 | 추가: } | |
| 612 | 추가: pub(crate) fn directory_with( | |
| 613 | 추가: root: &Dir, | |
| 614 | 추가: name: &str, | |
| 615 | 추가: check: &mut impl Monitor, | |
| 616 | 추가: ) -> Result<(bool, Durability, Option<ErrorCode>)> { | |
| 617 | 추가: let (d, leaf) = parent_with(root, name, false, check)?.ok_or(ErrorCode::Io)?; | |
| 618 | 추가: if completed(d.child(&leaf, false), check)?.is_some() { | |
| 582 | 619 | return Ok((false, Durability::NotApplicable, None)); |
| 583 | 620 | } |
| 584 | 621 | d.child(&leaf, true)?.ok_or(ErrorCode::Io)?; |
| 622 | 추가: let progress_error = completed(Ok(()), check).err(); | |
| 585 | 623 | Ok(match d.sync_checked() { |
| 586 | 삭제: Ok(durability) => (true, durability, None), | |
| 624 | 추가: Ok(durability) => ( | |
| 625 | 추가: true, | |
| 626 | 추가: durability, | |
| 627 | 추가: progress_error.or_else(|| completed(Ok(()), check).err()), | |
| 628 | 추가: ), | |
| 587 | 629 | Err(error) => (true, Durability::Failed, Some(error)), |
| 588 | 630 | }) |
| 589 | 631 | } |
| @@ -627,6 +669,43 @@ pub fn publish_reader_mode( | ||
| 627 | 669 | length: u64, |
| 628 | 670 | replace: Option<&Existing>, |
| 629 | 671 | check: &mut impl FnMut(bool) -> Result<()>, |
| 672 | 추가: ) -> Published { | |
| 673 | 추가: publish_reader_steps(root, name, data, length, replace, &mut |step| match step { | |
| 674 | 추가: PublishStep::Check => check(false), | |
| 675 | 추가: PublishStep::Commit => check(true), | |
| 676 | 추가: PublishStep::Activity => Ok(()), | |
| 677 | 추가: }) | |
| 678 | 추가: } | |
| 679 | 추가: pub(crate) enum PublishStep { | |
| 680 | 추가: Check, | |
| 681 | 추가: Activity, | |
| 682 | 추가: Commit, | |
| 683 | 추가: } | |
| 684 | 추가: struct PublicationMonitor<'a, F>(&'a mut F); | |
| 685 | 추가: impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> { | |
| 686 | 추가: fn check(&mut self) -> Result<()> { | |
| 687 | 추가: self.0(PublishStep::Check) | |
| 688 | 추가: } | |
| 689 | 추가: fn activity(&mut self) -> Result<()> { | |
| 690 | 추가: self.0(PublishStep::Activity) | |
| 691 | 추가: } | |
| 692 | 추가: } | |
| 693 | 추가: fn publication_activity( | |
| 694 | 추가: finish: &mut Result<()>, | |
| 695 | 추가: check: &mut impl FnMut(PublishStep) -> Result<()>, | |
| 696 | 추가: ) { | |
| 697 | 추가: let progress = completed(Ok(()), &mut PublicationMonitor(check)); | |
| 698 | 추가: if finish.is_ok() { | |
| 699 | 추가: *finish = progress; | |
| 700 | 추가: } | |
| 701 | 추가: } | |
| 702 | 추가: pub(crate) fn publish_reader_steps( | |
| 703 | 추가: root: &Dir, | |
| 704 | 추가: name: &str, | |
| 705 | 추가: data: &mut impl Read, | |
| 706 | 추가: length: u64, | |
| 707 | 추가: replace: Option<&Existing>, | |
| 708 | 추가: check: &mut impl FnMut(PublishStep) -> Result<()>, | |
| 630 | 709 | ) -> Published { |
| 631 | 710 | let mut result = Published { |
| 632 | 711 | created: false, |
| @@ -639,7 +718,8 @@ pub fn publish_reader_mode( | ||
| 639 | 718 | }; |
| 640 | 719 | let prepared = (|| { |
| 641 | 720 | valid_name(name, false)?; |
| 642 | 삭제: let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?; | |
| 721 | 추가: let (dir, leaf) = | |
| 722 | 추가: parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?; | |
| 643 | 723 | let temp = format!( |
| 644 | 724 | ".zipelo-{}-{}.tmp", |
| 645 | 725 | std::process::id(), |
| @@ -653,30 +733,49 @@ pub fn publish_reader_mode( | ||
| 653 | 733 | } |
| 654 | 734 | })?; |
| 655 | 735 | let written = (|| { |
| 656 | 삭제: crate::space::ensure(&file, length)?; | |
| 736 | 추가: completed(Ok(()), &mut PublicationMonitor(check))?; | |
| 737 | 추가: completed( | |
| 738 | 추가: crate::space::ensure(&file, length), | |
| 739 | 추가: &mut PublicationMonitor(check), | |
| 740 | 추가: )?; | |
| 657 | 741 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 658 | 742 | let mut remaining = length; |
| 659 | 743 | while remaining != 0 { |
| 660 | 삭제: check(false)?; | |
| 744 | 추가: check(PublishStep::Check)?; | |
| 661 | 745 | let count = remaining.min(buffer.len() as u64) as usize; |
| 662 | 746 | let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?; |
| 663 | 747 | if n == 0 { |
| 664 | 748 | return Err(ErrorCode::Io); |
| 665 | 749 | } |
| 666 | 삭제: file.write_all(&buffer[..n]) | |
| 667 | 삭제: .map_err(crate::space::io_error)?; | |
| 750 | 추가: completed(Ok(()), &mut PublicationMonitor(check))?; | |
| 751 | 추가: completed( | |
| 752 | 추가: crate::space::ensure(&file, n as u64), | |
| 753 | 추가: &mut PublicationMonitor(check), | |
| 754 | 추가: )?; | |
| 755 | 추가: completed( | |
| 756 | 추가: file.write_all(&buffer[..n]).map_err(crate::space::io_error), | |
| 757 | 추가: &mut PublicationMonitor(check), | |
| 758 | 추가: )?; | |
| 668 | 759 | remaining -= n as u64; |
| 669 | 760 | } |
| 670 | 삭제: file.sync_all().map_err(crate::space::io_error) | |
| 761 | 추가: completed( | |
| 762 | 추가: file.sync_all().map_err(crate::space::io_error), | |
| 763 | 추가: &mut PublicationMonitor(check), | |
| 764 | 추가: ) | |
| 671 | 765 | })(); |
| 672 | 삭제: let closed = close(file).map_err(crate::space::io_error); | |
| 766 | 추가: let closed = completed( | |
| 767 | 추가: close(file).map_err(crate::space::io_error), | |
| 768 | 추가: &mut PublicationMonitor(check), | |
| 769 | 추가: ); | |
| 673 | 770 | let mut finish = written.and(closed).and_then(|_| { |
| 674 | 771 | if let Some(expected) = replace { |
| 675 | 삭제: if dir.existing(&leaf)?.as_ref() != Some(expected) { | |
| 772 | 추가: if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref() | |
| 773 | 추가: != Some(expected) | |
| 774 | 추가: { | |
| 676 | 775 | return Err(ErrorCode::Conflict); |
| 677 | 776 | } |
| 678 | 777 | } |
| 679 | 삭제: check(true) | |
| 778 | 추가: check(PublishStep::Commit) | |
| 680 | 779 | }); |
| 681 | 780 | let mut temp_consumed = false; |
| 682 | 781 | if finish.is_ok() { |
| @@ -689,8 +788,12 @@ pub fn publish_reader_mode( | ||
| 689 | 788 | Ok(()) => { |
| 690 | 789 | temp_consumed = replace.is_some(); |
| 691 | 790 | result.created = true; |
| 791 | 추가: publication_activity(&mut finish, check); | |
| 692 | 792 | match dir.sync_checked() { |
| 693 | 삭제: Ok(durability) => result.durability = durability, | |
| 793 | 추가: Ok(durability) => { | |
| 794 | 추가: result.durability = durability; | |
| 795 | 추가: publication_activity(&mut finish, check); | |
| 796 | 추가: } | |
| 694 | 797 | Err(error) => { |
| 695 | 798 | result.durability = Durability::Failed; |
| 696 | 799 | finish = Err(error); |
| @@ -707,21 +810,27 @@ pub fn publish_reader_mode( | ||
| 707 | 810 | } |
| 708 | 811 | } |
| 709 | 812 | } |
| 710 | 삭제: if !temp_consumed && !dir.remove(&temp) { | |
| 711 | 삭제: result.cleanup = Cleanup::Failed; | |
| 712 | 삭제: result.retained = 1; | |
| 713 | 삭제: result.retained_name = Some(match name.rsplit_once('/') { | |
| 714 | 삭제: Some((prefix, _)) => format!("{prefix}/{temp}"), | |
| 715 | 삭제: None => temp.clone(), | |
| 716 | 삭제: }); | |
| 717 | 삭제: if finish.is_ok() { | |
| 718 | 삭제: finish = Err(ErrorCode::Io); | |
| 813 | 추가: if !temp_consumed { | |
| 814 | 추가: if dir.remove(&temp) { | |
| 815 | 추가: publication_activity(&mut finish, check); | |
| 816 | 추가: } else { | |
| 817 | 추가: result.cleanup = Cleanup::Failed; | |
| 818 | 추가: result.retained = 1; | |
| 819 | 추가: result.retained_name = Some(match name.rsplit_once('/') { | |
| 820 | 추가: Some((prefix, _)) => format!("{prefix}/{temp}"), | |
| 821 | 추가: None => temp.clone(), | |
| 822 | 추가: }); | |
| 823 | 추가: if finish.is_ok() { | |
| 824 | 추가: finish = Err(ErrorCode::Io); | |
| 825 | 추가: } | |
| 719 | 826 | } |
| 720 | 827 | } |
| 721 | 828 | if result.created { |
| 722 | 829 | if let Err(error) = dir.sync_checked() { |
| 723 | 830 | result.durability = Durability::Failed; |
| 724 | 831 | finish = Err(error); |
| 832 | 추가: } else { | |
| 833 | 추가: publication_activity(&mut finish, check); | |
| 725 | 834 | } |
| 726 | 835 | } |
| 727 | 836 | finish |
| @@ -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 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 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 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 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,139 @@ | ||
| 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 metadata_limits(&self) -> crate::archive::MetadataLimits { | |
| 8 | 추가: crate::archive::MetadataLimits::default() | |
| 9 | 추가: } | |
| 10 | 추가: fn check(&mut self) -> Result<()>; | |
| 11 | 추가: fn activity(&mut self) -> Result<()> { | |
| 12 | 추가: self.check() | |
| 13 | 추가: } | |
| 14 | 추가: fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> { | |
| 15 | 추가: self.check() | |
| 16 | 추가: } | |
| 17 | 추가: } | |
| 18 | 추가: impl<F: FnMut() -> Result<()>> Monitor for F { | |
| 19 | 추가: fn check(&mut self) -> Result<()> { | |
| 20 | 추가: self() | |
| 21 | 추가: } | |
| 22 | 추가: } | |
| 23 | 추가: | |
| 24 | 추가: pub(crate) fn completed<T>(result: Result<T>, check: &mut impl Monitor) -> Result<T> { | |
| 25 | 추가: let value = result?; | |
| 26 | 추가: check.activity()?; | |
| 27 | 추가: Ok(value) | |
| 28 | 추가: } | |
| 29 | 추가: | |
| 30 | 추가: pub(crate) struct MetadataMonitor<'a, M>(pub &'a mut M); | |
| 31 | 추가: impl<M: Monitor> Monitor for MetadataMonitor<'_, M> { | |
| 32 | 추가: fn metadata_limits(&self) -> crate::archive::MetadataLimits { | |
| 33 | 추가: self.0.metadata_limits() | |
| 34 | 추가: } | |
| 35 | 추가: fn check(&mut self) -> Result<()> { | |
| 36 | 추가: self.0.check() | |
| 37 | 추가: } | |
| 38 | 추가: fn activity(&mut self) -> Result<()> { | |
| 39 | 추가: self.0.activity() | |
| 40 | 추가: } | |
| 41 | 추가: fn observe(&mut self, usage: ResourceUsage, _storage: Option<&std::fs::File>) -> Result<()> { | |
| 42 | 추가: self.check()?; | |
| 43 | 추가: // 압축 헤더는 메타데이터 상한만 적용하며 파일 출력량에 합치지 않음. | |
| 44 | 추가: if usage | |
| 45 | 추가: .estimated_bytes | |
| 46 | 추가: .into_iter() | |
| 47 | 추가: .chain(usage.actual_bytes) | |
| 48 | 추가: .any(|bytes| bytes > self.metadata_limits().bytes as u64) | |
| 49 | 추가: { | |
| 50 | 추가: return Err(ErrorCode::Limit); | |
| 51 | 추가: } | |
| 52 | 추가: Ok(()) | |
| 53 | 추가: } | |
| 54 | 추가: } | |
| 55 | 추가: | |
| 56 | 추가: pub(crate) struct Budget { | |
| 57 | 추가: pub soft: Limits, | |
| 58 | 추가: pub ceiling: Limits, | |
| 59 | 추가: pub granted: ResourceScope, | |
| 60 | 추가: } | |
| 61 | 추가: impl Budget { | |
| 62 | 추가: pub fn metadata_limits(&self) -> crate::archive::MetadataLimits { | |
| 63 | 추가: if self.granted.any() { | |
| 64 | 추가: crate::archive::MetadataLimits::approved() | |
| 65 | 추가: } else { | |
| 66 | 추가: crate::archive::MetadataLimits::default() | |
| 67 | 추가: } | |
| 68 | 추가: } | |
| 69 | 추가: pub fn required(&self, usage: ResourceUsage) -> Result<ResourceScope> { | |
| 70 | 추가: let bytes = usage | |
| 71 | 추가: .estimated_bytes | |
| 72 | 추가: .into_iter() | |
| 73 | 추가: .chain(usage.actual_bytes) | |
| 74 | 추가: .max(); | |
| 75 | 추가: let entries = usage | |
| 76 | 추가: .estimated_entries | |
| 77 | 추가: .into_iter() | |
| 78 | 추가: .chain(usage.actual_entries) | |
| 79 | 추가: .max(); | |
| 80 | 추가: if bytes.is_some_and(|n| n > self.ceiling.output) | |
| 81 | 추가: || entries.is_some_and(|n| n > self.ceiling.entries) | |
| 82 | 추가: { | |
| 83 | 추가: return Err(ErrorCode::Limit); | |
| 84 | 추가: } | |
| 85 | 추가: let ratio = match (usage.ratio_output_bytes, usage.compressed_bytes) { | |
| 86 | 추가: (Some(output), Some(input)) => { | |
| 87 | 추가: output >= 256 * 1024 * 1024 && u128::from(output) > u128::from(input) * 1000 | |
| 88 | 추가: } | |
| 89 | 추가: _ => false, | |
| 90 | 추가: }; | |
| 91 | 추가: Ok(ResourceScope { | |
| 92 | 추가: output: !self.granted.output && bytes.is_some_and(|n| n > self.soft.output), | |
| 93 | 추가: entries: !self.granted.entries && entries.is_some_and(|n| n > self.soft.entries), | |
| 94 | 추가: ratio: !self.granted.ratio && ratio, | |
| 95 | 추가: }) | |
| 96 | 추가: } | |
| 97 | 추가: pub fn grant(&mut self, scope: ResourceScope) { | |
| 98 | 추가: self.granted.output |= scope.output; | |
| 99 | 추가: self.granted.entries |= scope.entries; | |
| 100 | 추가: self.granted.ratio |= scope.ratio; | |
| 101 | 추가: } | |
| 102 | 추가: } | |
| 103 | 추가: | |
| 104 | 추가: pub(crate) struct Watchdog { | |
| 105 | 추가: last_activity: Duration, | |
| 106 | 추가: approved: bool, | |
| 107 | 추가: } | |
| 108 | 추가: impl Watchdog { | |
| 109 | 추가: pub fn new() -> Self { | |
| 110 | 추가: Self { | |
| 111 | 추가: last_activity: Duration::ZERO, | |
| 112 | 추가: approved: false, | |
| 113 | 추가: } | |
| 114 | 추가: } | |
| 115 | 추가: pub fn check(&self, elapsed: Duration) -> Result<()> { | |
| 116 | 추가: if if self.approved { | |
| 117 | 추가: elapsed.saturating_sub(self.last_activity) >= Duration::from_secs(60) | |
| 118 | 추가: } else { | |
| 119 | 추가: elapsed > Duration::from_secs(300) | |
| 120 | 추가: } { | |
| 121 | 추가: Err(ErrorCode::Limit) | |
| 122 | 추가: } else { | |
| 123 | 추가: Ok(()) | |
| 124 | 추가: } | |
| 125 | 추가: } | |
| 126 | 추가: pub fn activity(&mut self, elapsed: Duration) -> Result<()> { | |
| 127 | 추가: self.check(elapsed)?; | |
| 128 | 추가: self.last_activity = elapsed; | |
| 129 | 추가: Ok(()) | |
| 130 | 추가: } | |
| 131 | 추가: pub fn resume(&mut self, elapsed: Duration, approved: bool) { | |
| 132 | 추가: self.approved |= approved; | |
| 133 | 추가: self.last_activity = elapsed; | |
| 134 | 추가: } | |
| 135 | 추가: } | |
| 136 | 추가: | |
| 137 | 추가: #[cfg(test)] | |
| 138 | 추가: #[path = "../../../tests/rust-archive-worker/resource_budget.rs"] | |
| 139 | 추가: mod tests; |
| @@ -2,6 +2,7 @@ use crate::{ | ||
| 2 | 2 | archive, |
| 3 | 3 | filesystem::{self, Dir}, |
| 4 | 4 | protocol::*, |
| 5 | 추가: resources::{Budget, Monitor, Watchdog, completed}, | |
| 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 |
| @@ -151,9 +233,10 @@ impl<W: Write> Job<W> { | ||
| 151 | 233 | format!("{prefix}/{leaf}") |
| 152 | 234 | }; |
| 153 | 235 | archive::valid_name(&candidate, false)?; |
| 154 | 삭제: if !reserved.contains(&candidate.to_lowercase()) | |
| 155 | 삭제: && filesystem::unused(root, &candidate)? | |
| 156 | 삭제: { | |
| 236 | 추가: let unused = !reserved.contains(&candidate.to_lowercase()) | |
| 237 | 추가: && filesystem::unused_with(root, &candidate, self)?; | |
| 238 | 추가: completed(Ok(()), self)?; | |
| 239 | 추가: if unused { | |
| 157 | 240 | return Ok(candidate); |
| 158 | 241 | } |
| 159 | 242 | } |
| @@ -168,9 +251,6 @@ impl<W: Write> Job<W> { | ||
| 168 | 251 | } |
| 169 | 252 | fn check(&mut self) -> Result<()> { |
| 170 | 253 | self.parent.check()?; |
| 171 | 삭제: if self.started.elapsed() > Duration::from_secs(300) { | |
| 172 | 삭제: return Err(ErrorCode::Limit); | |
| 173 | 삭제: } | |
| 174 | 254 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 175 | 255 | if let Some(error) = state.fault { |
| 176 | 256 | return Err(error); |
| @@ -178,7 +258,7 @@ impl<W: Write> Job<W> { | ||
| 178 | 258 | if state.cancelled && state.phase == 0 { |
| 179 | 259 | return Err(ErrorCode::None); |
| 180 | 260 | } |
| 181 | 삭제: Ok(()) | |
| 261 | 추가: self.watchdog.check(self.started.elapsed()) | |
| 182 | 262 | } |
| 183 | 263 | fn cutoff(&mut self) -> Result<()> { |
| 184 | 264 | self.check()?; |
| @@ -220,11 +300,12 @@ impl<W: Write> Job<W> { | ||
| 220 | 300 | Some(length), |
| 221 | 301 | self.terminal.created_count as u32, |
| 222 | 302 | )?; |
| 223 | 삭제: let p = filesystem::publish_reader_mode(root, name, data, length, replace, &mut |commit| { | |
| 224 | 삭제: if commit && last { | |
| 225 | 삭제: self.cutoff() | |
| 226 | 삭제: } else { | |
| 227 | 삭제: self.check() | |
| 303 | 추가: let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| { | |
| 304 | 추가: match step { | |
| 305 | 추가: filesystem::PublishStep::Check => self.check(), | |
| 306 | 추가: filesystem::PublishStep::Activity => completed(Ok(()), self), | |
| 307 | 추가: filesystem::PublishStep::Commit if last => self.cutoff(), | |
| 308 | 추가: filesystem::PublishStep::Commit => self.check(), | |
| 228 | 309 | } |
| 229 | 310 | }); |
| 230 | 311 | self.terminal.retained_partial_count += p.retained; |
| @@ -266,17 +347,32 @@ impl<W: Write> Job<W> { | ||
| 266 | 347 | if let Some(error) = p.error { |
| 267 | 348 | return Err(error); |
| 268 | 349 | } |
| 350 | 추가: if p.created { | |
| 351 | 추가: completed(Ok(()), self)?; | |
| 352 | 추가: } | |
| 269 | 353 | Ok(()) |
| 270 | 354 | } |
| 271 | 355 | fn run(&mut self, start: Start) -> Result<()> { |
| 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::Activity => completed(Ok(()), self), | |
| 392 | 추가: crate::spool::Step::Read { bytes, total } => { | |
| 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, |
| @@ -330,12 +426,15 @@ impl<W: Write> Job<W> { | ||
| 330 | 426 | if !extract { |
| 331 | 427 | for member in &catalog.members { |
| 332 | 428 | self.check()?; |
| 333 | 삭제: self.event(Message::Entry(member.entry.clone()))?; | |
| 429 | 추가: completed(self.event(Message::Entry(member.entry.clone())), self)?; | |
| 334 | 430 | } |
| 335 | 삭제: self.event(Message::ListEnd { | |
| 336 | 삭제: entry_count: catalog.members.len() as u32, | |
| 337 | 삭제: list_id, | |
| 338 | 삭제: })?; | |
| 431 | 추가: completed( | |
| 432 | 추가: self.event(Message::ListEnd { | |
| 433 | 추가: entry_count: catalog.members.len() as u32, | |
| 434 | 추가: list_id, | |
| 435 | 추가: }), | |
| 436 | 추가: self, | |
| 437 | 추가: )?; | |
| 339 | 438 | } else if let Action::Extract { |
| 340 | 439 | destination, |
| 341 | 440 | selection, |
| @@ -353,24 +452,24 @@ impl<W: Write> Job<W> { | ||
| 353 | 452 | let selected = match selection { |
| 354 | 453 | Selection::All => None, |
| 355 | 454 | Selection::EntryIds(ids) => { |
| 356 | 삭제: let n = ids.len(); | |
| 357 | 삭제: let set = ids.into_iter().collect::<BTreeSet<_>>(); | |
| 358 | 삭제: if expected.is_none() | |
| 359 | 삭제: || set.is_empty() | |
| 360 | 삭제: || n != set.len() | |
| 361 | 삭제: || set.iter().any(|id| *id as usize >= catalog.members.len()) | |
| 362 | 삭제: { | |
| 455 | 추가: if expected.is_none() || ids.is_empty() { | |
| 363 | 456 | return Err(ErrorCode::InvalidRequest); |
| 364 | 457 | } |
| 458 | 추가: let mut set = BTreeSet::new(); | |
| 459 | 추가: for id in ids { | |
| 460 | 추가: if id as usize >= catalog.members.len() || !set.insert(id) { | |
| 461 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 462 | 추가: } | |
| 463 | 추가: completed(Ok(()), self)?; | |
| 464 | 추가: } | |
| 365 | 465 | Some(set) |
| 366 | 466 | } |
| 367 | 467 | }; |
| 368 | 삭제: if catalog | |
| 369 | 삭제: .members | |
| 370 | 삭제: .iter() | |
| 371 | 삭제: .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory)) | |
| 372 | 삭제: { | |
| 373 | 삭제: return Err(ErrorCode::UnsafePath); | |
| 468 | 추가: for member in &catalog.members { | |
| 469 | 추가: if !matches!(member.entry.kind, EntryKind::File | EntryKind::Directory) { | |
| 470 | 추가: return Err(ErrorCode::UnsafePath); | |
| 471 | 추가: } | |
| 472 | 추가: completed(Ok(()), self)?; | |
| 374 | 473 | } |
| 375 | 474 | if catalog.format == Format::Gzip { |
| 376 | 475 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| @@ -383,36 +482,33 @@ impl<W: Write> Job<W> { | ||
| 383 | 482 | } else if gzip_output_name.is_some() { |
| 384 | 483 | return Err(ErrorCode::InvalidRequest); |
| 385 | 484 | } |
| 386 | 삭제: let root = Dir::root(&destination.to_path()?)?; | |
| 387 | 삭제: let output_sizes = catalog | |
| 388 | 삭제: .members | |
| 389 | 삭제: .iter() | |
| 390 | 삭제: .filter(|m| { | |
| 391 | 삭제: m.entry.kind == EntryKind::File | |
| 392 | 삭제: && selected | |
| 393 | 삭제: .as_ref() | |
| 394 | 삭제: .is_none_or(|s| s.contains(&m.entry.entry_id)) | |
| 395 | 삭제: }) | |
| 396 | 삭제: .map(|m| (m.entry.name.clone(), m.entry.size)) | |
| 397 | 삭제: .collect::<Vec<_>>(); | |
| 398 | 삭제: let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) { | |
| 399 | 삭제: Some(( | |
| 400 | 삭제: &catalog.data, | |
| 401 | 삭제: catalog.members.iter().try_fold(0u64, |sum, m| { | |
| 402 | 삭제: sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit) | |
| 403 | 삭제: })?, | |
| 404 | 삭제: )) | |
| 405 | 삭제: } else { | |
| 406 | 삭제: None | |
| 407 | 삭제: }; | |
| 485 | 추가: let root = completed(Dir::root(&destination.to_path()?), self)?; | |
| 486 | 추가: let mut output_sizes = Vec::new(); | |
| 487 | 추가: let mut staged_total = 0u64; | |
| 488 | 추가: let mut encrypted = false; | |
| 489 | 추가: for member in &catalog.members { | |
| 490 | 추가: if member.entry.kind == EntryKind::File | |
| 491 | 추가: && selected | |
| 492 | 추가: .as_ref() | |
| 493 | 추가: .is_none_or(|s| s.contains(&member.entry.entry_id)) | |
| 494 | 추가: { | |
| 495 | 추가: output_sizes.push((member.entry.name.clone(), member.entry.size)); | |
| 496 | 추가: } | |
| 497 | 추가: staged_total = staged_total | |
| 498 | 추가: .checked_add(member.entry.size) | |
| 499 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 500 | 추가: encrypted |= member.entry.encrypted; | |
| 501 | 추가: completed(Ok(()), self)?; | |
| 502 | 추가: } | |
| 503 | 추가: let staged = matches!(catalog.format, Format::Zip | Format::SevenZip) | |
| 504 | 추가: .then_some((&catalog.data, staged_total)); | |
| 408 | 505 | // 선택 전에는 검증에 필요한 스테이징 공간만 계산함. |
| 409 | 506 | let initial_outputs = if self.interactive { |
| 410 | 507 | &[][..] |
| 411 | 508 | } else { |
| 412 | 509 | &output_sizes[..] |
| 413 | 510 | }; |
| 414 | 삭제: filesystem::preflight_space(&root, initial_outputs, staged)?; | |
| 415 | 삭제: let encrypted = catalog.members.iter().any(|m| m.entry.encrypted); | |
| 511 | 추가: filesystem::preflight_space_with(&root, initial_outputs, staged, self)?; | |
| 416 | 512 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 417 | 513 | for attempt in 1..=3 { |
| 418 | 514 | let secret = if encrypted { |
| @@ -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; |
| @@ -439,41 +535,46 @@ impl<W: Write> Job<W> { | ||
| 439 | 535 | } |
| 440 | 536 | let offsets = catalog.offsets; |
| 441 | 537 | let mut data = catalog.data; |
| 442 | 삭제: let members = catalog | |
| 443 | 삭제: .members | |
| 444 | 삭제: .into_iter() | |
| 445 | 삭제: .filter(|m| { | |
| 446 | 삭제: selected | |
| 447 | 삭제: .as_ref() | |
| 448 | 삭제: .is_none_or(|s| s.contains(&m.entry.entry_id)) | |
| 449 | 삭제: }) | |
| 450 | 삭제: .collect::<Vec<_>>(); | |
| 451 | 삭제: let dirs = archive::output_directories(&members)?; | |
| 538 | 추가: let mut members = Vec::new(); | |
| 539 | 추가: for member in catalog.members { | |
| 540 | 추가: if selected | |
| 541 | 추가: .as_ref() | |
| 542 | 추가: .is_none_or(|s| s.contains(&member.entry.entry_id)) | |
| 543 | 추가: { | |
| 544 | 추가: members.push(member); | |
| 545 | 추가: } | |
| 546 | 추가: completed(Ok(()), self)?; | |
| 547 | 추가: } | |
| 548 | 추가: let dirs = archive::output_directories(&members, self)?; | |
| 452 | 549 | let files = members |
| 453 | 550 | .iter() |
| 454 | 551 | .filter(|m| m.entry.kind == EntryKind::File) |
| 455 | 삭제: .collect::<Vec<_>>(); | |
| 552 | 추가: .map(|member| completed(Ok(member), self)) | |
| 553 | 추가: .collect::<Result<Vec<_>>>()?; | |
| 456 | 554 | let mut names = dirs |
| 457 | 555 | .iter() |
| 458 | 삭제: .map(|n| (n.clone(), EntryKind::Directory)) | |
| 459 | 삭제: .collect::<Vec<_>>(); | |
| 556 | 추가: .map(|name| completed(Ok((name.clone(), EntryKind::Directory)), self)) | |
| 557 | 추가: .collect::<Result<Vec<_>>>()?; | |
| 460 | 558 | names.extend( |
| 461 | 559 | files |
| 462 | 560 | .iter() |
| 463 | 삭제: .map(|m| (m.entry.name.clone(), EntryKind::File)), | |
| 561 | 추가: .map(|member| { | |
| 562 | 추가: completed(Ok((member.entry.name.clone(), EntryKind::File)), self) | |
| 563 | 추가: }) | |
| 564 | 추가: .collect::<Result<Vec<_>>>()?, | |
| 464 | 565 | ); |
| 465 | 삭제: filesystem::preflight_mode(&root, &names, self.interactive)?; | |
| 566 | 추가: filesystem::preflight_mode_with(&root, &names, self.interactive, self)?; | |
| 466 | 567 | if !self.interactive { |
| 467 | 삭제: filesystem::preflight_space(&root, &output_sizes, None)?; | |
| 568 | 추가: filesystem::preflight_space_with(&root, &output_sizes, None, self)?; | |
| 468 | 569 | } |
| 469 | 570 | let mut reserved = names |
| 470 | 571 | .iter() |
| 471 | 삭제: .map(|(name, _)| name.to_lowercase()) | |
| 472 | 삭제: .collect::<BTreeSet<_>>(); | |
| 572 | 추가: .map(|(name, _)| completed(Ok(name.to_lowercase()), self)) | |
| 573 | 추가: .collect::<Result<BTreeSet<_>>>()?; | |
| 473 | 574 | for name in dirs { |
| 474 | 575 | self.check()?; |
| 475 | 576 | let (created, durability, sync_error) = |
| 476 | 삭제: filesystem::directory(&root, &name)?; | |
| 577 | 추가: filesystem::directory_with(&root, &name, self)?; | |
| 477 | 578 | if created { |
| 478 | 579 | self.terminal.created_count += 1; |
| 479 | 580 | self.terminal.publication = Publication::Partial; |
| @@ -486,14 +587,18 @@ impl<W: Write> Job<W> { | ||
| 486 | 587 | if let Some(error) = sync_error { |
| 487 | 588 | return Err(error); |
| 488 | 589 | } |
| 590 | 추가: completed(Ok(()), self)?; | |
| 489 | 591 | } |
| 490 | 592 | } |
| 491 | 593 | for (index, m) in files.iter().enumerate() { |
| 492 | 삭제: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) | |
| 493 | 삭제: .map_err(|_| ErrorCode::Io)?; | |
| 594 | 추가: completed( | |
| 595 | 추가: data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) | |
| 596 | 추가: .map_err(|_| ErrorCode::Io), | |
| 597 | 추가: self, | |
| 598 | 추가: )?; | |
| 494 | 599 | self.check()?; |
| 495 | 600 | let existing = if self.interactive { |
| 496 | 삭제: filesystem::existing(&root, &m.entry.name)? | |
| 601 | 추가: filesystem::existing_with(&root, &m.entry.name, self)? | |
| 497 | 602 | } else { |
| 498 | 603 | None |
| 499 | 604 | }; |
| @@ -508,21 +613,25 @@ impl<W: Write> Job<W> { | ||
| 508 | 613 | } else if choice == ConflictChoice::Overwrite { |
| 509 | 614 | replace = Some(existing); |
| 510 | 615 | } |
| 511 | 삭제: self.event(Message::ConflictResolved { | |
| 512 | 삭제: entry_id: m.entry.entry_id, | |
| 513 | 삭제: relative_name: name.clone(), | |
| 514 | 삭제: choice, | |
| 515 | 삭제: })?; | |
| 616 | 추가: completed( | |
| 617 | 추가: self.event(Message::ConflictResolved { | |
| 618 | 추가: entry_id: m.entry.entry_id, | |
| 619 | 추가: relative_name: name.clone(), | |
| 620 | 추가: choice, | |
| 621 | 추가: }), | |
| 622 | 추가: self, | |
| 623 | 추가: )?; | |
| 516 | 624 | if choice == ConflictChoice::Skip { |
| 517 | 625 | continue; |
| 518 | 626 | } |
| 519 | 627 | } |
| 520 | 628 | if self.interactive { |
| 521 | 629 | // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함. |
| 522 | 삭제: filesystem::preflight_space( | |
| 630 | 추가: filesystem::preflight_space_with( | |
| 523 | 631 | &root, |
| 524 | 632 | &[(name.clone(), m.entry.size)], |
| 525 | 633 | None, |
| 634 | 추가: self, | |
| 526 | 635 | )?; |
| 527 | 636 | } |
| 528 | 637 | self.output_reader( |
| @@ -552,9 +661,17 @@ impl<W: Write> Job<W> { | ||
| 552 | 661 | .and_then(|n| n.to_str()) |
| 553 | 662 | .ok_or(ErrorCode::InvalidRequest)?; |
| 554 | 663 | let name = archive::valid_name(leaf, false)?; |
| 555 | 삭제: let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?; | |
| 556 | 삭제: filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?; | |
| 557 | 삭제: let members = crate::create::plan(&sources, start.limits, &mut || self.check())?; | |
| 664 | 추가: let root = completed( | |
| 665 | 추가: Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), | |
| 666 | 추가: self, | |
| 667 | 추가: )?; | |
| 668 | 추가: filesystem::preflight_mode_with( | |
| 669 | 추가: &root, | |
| 670 | 추가: &[(name.clone(), EntryKind::File)], | |
| 671 | 추가: false, | |
| 672 | 추가: self, | |
| 673 | 추가: )?; | |
| 674 | 추가: let members = crate::create::plan(&sources, limits, self)?; | |
| 558 | 675 | let secret = if encryption == Encryption::Aes256 { |
| 559 | 676 | let secret = self.password(PasswordPurpose::Encrypt, 1)?; |
| 560 | 677 | if secret.0.is_empty() { |
| @@ -567,11 +684,11 @@ impl<W: Write> Job<W> { | ||
| 567 | 684 | let (mut data, length) = crate::create::zip( |
| 568 | 685 | &members, |
| 569 | 686 | method, |
| 570 | 삭제: start.limits, | |
| 687 | 추가: limits, | |
| 571 | 688 | secret.as_ref().map(|s| s.0.as_slice()), |
| 572 | 삭제: &mut || self.check(), | |
| 689 | 추가: self, | |
| 573 | 690 | )?; |
| 574 | 삭제: filesystem::preflight_space(&root, &[(name.clone(), length)], None)?; | |
| 691 | 추가: filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; | |
| 575 | 692 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 576 | 693 | self.terminal.publication = Publication::Complete; |
| 577 | 694 | } |
| @@ -580,6 +697,32 @@ impl<W: Write> Job<W> { | ||
| 580 | 697 | Ok(()) |
| 581 | 698 | } |
| 582 | 699 | } |
| 700 | 추가: impl<W: Write> Monitor for Job<W> { | |
| 701 | 추가: fn metadata_limits(&self) -> archive::MetadataLimits { | |
| 702 | 추가: self.budget | |
| 703 | 추가: .as_ref() | |
| 704 | 추가: .map_or_else(archive::MetadataLimits::default, |b| b.metadata_limits()) | |
| 705 | 추가: } | |
| 706 | 추가: fn check(&mut self) -> Result<()> { | |
| 707 | 추가: Job::check(self) | |
| 708 | 추가: } | |
| 709 | 추가: fn activity(&mut self) -> Result<()> { | |
| 710 | 추가: self.check()?; | |
| 711 | 추가: self.watchdog.activity(self.started.elapsed()) | |
| 712 | 추가: } | |
| 713 | 추가: fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> { | |
| 714 | 추가: self.check()?; | |
| 715 | 추가: let Some(budget) = &self.budget else { | |
| 716 | 추가: return Ok(()); | |
| 717 | 추가: }; | |
| 718 | 추가: let scope = budget.required(usage)?; | |
| 719 | 추가: if !scope.any() { | |
| 720 | 추가: return Ok(()); | |
| 721 | 추가: } | |
| 722 | 추가: self.request_resource(scope, usage, storage) | |
| 723 | 추가: } | |
| 724 | 추가: } | |
| 725 | 추가: | |
| 583 | 726 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 584 | 727 | input: R, |
| 585 | 728 | output: W, |
| @@ -590,9 +733,17 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 590 | 733 | let (job, _, message) = reader |
| 591 | 734 | .read()? |
| 592 | 735 | .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), | |
| 736 | 추가: let (start, interactive, budget) = match message { | |
| 737 | 추가: Message::Start(start) => (start, false, None), | |
| 738 | 추가: Message::StartInteractive(start) => (start, true, None), | |
| 739 | 추가: Message::StartGuarded(guarded) if guarded.valid() => { | |
| 740 | 추가: let budget = Budget { | |
| 741 | 추가: soft: guarded.start.limits, | |
| 742 | 추가: ceiling: guarded.ceiling, | |
| 743 | 추가: granted: ResourceScope::default(), | |
| 744 | 추가: }; | |
| 745 | 추가: (guarded.start, guarded.interactive, Some(budget)) | |
| 746 | 추가: } | |
| 596 | 747 | _ => { |
| 597 | 748 | return Err(std::io::Error::new( |
| 598 | 749 | std::io::ErrorKind::InvalidData, |
| @@ -608,6 +759,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 608 | 759 | challenge: None, |
| 609 | 760 | conflict_reply: None, |
| 610 | 761 | password: None, |
| 762 | 추가: resource_reply: None, | |
| 611 | 763 | input_closed: false, |
| 612 | 764 | })); |
| 613 | 765 | let wake = Arc::new(Condvar::new()); |
| @@ -668,6 +820,24 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 668 | 820 | } |
| 669 | 821 | control_wake.notify_all(); |
| 670 | 822 | } |
| 823 | 추가: Message::ResourceReply { | |
| 824 | 추가: challenge_id, | |
| 825 | 추가: scope, | |
| 826 | 추가: allow, | |
| 827 | 추가: } => { | |
| 828 | 추가: if state.phase != 0 | |
| 829 | 추가: || state.challenge != Some(Challenge::Resource(challenge_id, scope)) | |
| 830 | 추가: || state.resource_reply.is_some() | |
| 831 | 추가: { | |
| 832 | 추가: state.fault = Some(ErrorCode::Protocol); | |
| 833 | 추가: } else { | |
| 834 | 추가: state.challenge = None; | |
| 835 | 추가: if !state.cancelled { | |
| 836 | 추가: state.resource_reply = Some(allow); | |
| 837 | 추가: } | |
| 838 | 추가: } | |
| 839 | 추가: control_wake.notify_all(); | |
| 840 | 추가: } | |
| 671 | 841 | Message::Cancel => { |
| 672 | 842 | let status = match state.phase { |
| 673 | 843 | 2 => CancelStatus::Finished, |
| @@ -703,6 +873,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 703 | 873 | wake, |
| 704 | 874 | next_challenge: 0, |
| 705 | 875 | interactive, |
| 876 | 추가: action: start.action.kind(), | |
| 877 | 추가: budget, | |
| 878 | 추가: watchdog: Watchdog::new(), | |
| 706 | 879 | remaining_choice: None, |
| 707 | 880 | parent, |
| 708 | 881 | started: Instant::now(), |
| @@ -733,6 +906,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 733 | 906 | state.challenge = None; |
| 734 | 907 | state.password = None; |
| 735 | 908 | state.conflict_reply = None; |
| 909 | 추가: state.resource_reply = None; | |
| 736 | 910 | if let Some(error) = state.fault.or(error) { |
| 737 | 911 | context.terminal.error = error; |
| 738 | 912 | context.terminal.outcome = if error == ErrorCode::None { |
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | use crate::{ |
| 2 | 삭제: archive::{MAX_METADATA_BYTES, Member, MetadataBudget, valid_name, validate_members}, | |
| 2 | 추가: archive::{Member, MetadataBudget, valid_name, validate_members_with}, | |
| 3 | 3 | protocol::*, |
| 4 | 4 | }; |
| 5 | 5 | use std::collections::BTreeSet; |
| @@ -96,13 +96,17 @@ struct Streams { | ||
| 96 | 96 | folders: Vec<Folder>, |
| 97 | 97 | } |
| 98 | 98 | impl Streams { |
| 99 | 삭제: fn read(r: &mut Reader<'_>, limits: Limits) -> Result<Self> { | |
| 99 | 추가: fn read( | |
| 100 | 추가: r: &mut Reader<'_>, | |
| 101 | 추가: limits: Limits, | |
| 102 | 추가: check: &mut impl crate::resources::Monitor, | |
| 103 | 추가: ) -> Result<Self> { | |
| 100 | 104 | r.expect(6)?; |
| 101 | 105 | let position = r.number(limits.input as usize)?; |
| 102 | 106 | let count = r.number(limits.entries as usize)?; |
| 103 | 107 | r.expect(9)?; |
| 104 | 108 | let packed = (0..count) |
| 105 | 삭제: .map(|_| r.number(limits.input as usize)) | |
| 109 | 추가: .map(|_| crate::resources::completed(r.number(limits.input as usize), check)) | |
| 106 | 110 | .collect::<Result<Vec<_>>>()?; |
| 107 | 111 | let mut tag = r.byte()?; |
| 108 | 112 | let packed_crcs = if tag == 10 { |
| @@ -157,6 +161,7 @@ impl Streams { | ||
| 157 | 161 | sizes: Vec::new(), |
| 158 | 162 | crcs: Vec::new(), |
| 159 | 163 | }); |
| 164 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 160 | 165 | } |
| 161 | 166 | r.expect(12)?; |
| 162 | 167 | let mut total = 0usize; |
| @@ -166,11 +171,13 @@ impl Streams { | ||
| 166 | 171 | .checked_add(folder.size) |
| 167 | 172 | .filter(|n| *n <= limits.output as usize) |
| 168 | 173 | .ok_or(ErrorCode::Limit)?; |
| 174 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 169 | 175 | } |
| 170 | 176 | let mut tag = r.byte()?; |
| 171 | 177 | if tag == 10 { |
| 172 | 178 | for (f, crc) in folders.iter_mut().zip(r.digests(num)?) { |
| 173 | 179 | f.crc = crc; |
| 180 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 174 | 181 | } |
| 175 | 182 | tag = r.byte()?; |
| 176 | 183 | } |
| @@ -190,6 +197,7 @@ impl Streams { | ||
| 190 | 197 | .checked_add(*n) |
| 191 | 198 | .filter(|n| *n <= limits.entries as usize) |
| 192 | 199 | .ok_or(ErrorCode::Limit)?; |
| 200 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 193 | 201 | } |
| 194 | 202 | tag = r.byte()?; |
| 195 | 203 | } |
| @@ -204,6 +212,7 @@ impl Streams { | ||
| 204 | 212 | .filter(|n| *n <= folder.size) |
| 205 | 213 | .ok_or(ErrorCode::Integrity)?; |
| 206 | 214 | folder.sizes.push(n); |
| 215 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 207 | 216 | } |
| 208 | 217 | if *count > 0 { |
| 209 | 218 | folder.sizes.push(folder.size - total); |
| @@ -229,6 +238,7 @@ impl Streams { | ||
| 229 | 238 | } else { |
| 230 | 239 | (0..*n).map(|_| digests.next().unwrap()).collect() |
| 231 | 240 | }; |
| 241 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 232 | 242 | } |
| 233 | 243 | if tag != 0 { |
| 234 | 244 | return Err(ErrorCode::Integrity); |
| @@ -237,6 +247,7 @@ impl Streams { | ||
| 237 | 247 | } else { |
| 238 | 248 | for f in &mut folders { |
| 239 | 249 | f.crcs.push(f.crc); |
| 250 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 240 | 251 | } |
| 241 | 252 | } |
| 242 | 253 | if tag != 0 { |
| @@ -254,6 +265,7 @@ impl Streams { | ||
| 254 | 265 | if *n == 0 && f.size != 0 { |
| 255 | 266 | return Err(ErrorCode::Integrity); |
| 256 | 267 | } |
| 268 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 257 | 269 | } |
| 258 | 270 | Ok(Self { |
| 259 | 271 | position, |
| @@ -266,7 +278,7 @@ impl Streams { | ||
| 266 | 278 | &self, |
| 267 | 279 | input: &mut std::fs::File, |
| 268 | 280 | data_end: u64, |
| 269 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 281 | 추가: check: &mut impl crate::resources::Monitor, | |
| 270 | 282 | ) -> Result<Vec<(u64, u64)>> { |
| 271 | 283 | let mut at = 32u64 |
| 272 | 284 | .checked_add(self.position as u64) |
| @@ -285,6 +297,7 @@ impl Streams { | ||
| 285 | 297 | } |
| 286 | 298 | ranges.push((at, size)); |
| 287 | 299 | at = end; |
| 300 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 288 | 301 | } |
| 289 | 302 | Ok(ranges) |
| 290 | 303 | } |
| @@ -293,16 +306,27 @@ impl Streams { | ||
| 293 | 306 | input: &mut std::fs::File, |
| 294 | 307 | ranges: &[(u64, u64)], |
| 295 | 308 | output: &mut std::fs::File, |
| 296 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 309 | 추가: check: &mut impl crate::resources::Monitor, | |
| 297 | 310 | ) -> Result<()> { |
| 298 | 311 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 299 | 312 | let total = self.folders.iter().try_fold(0u64, |sum, f| { |
| 300 | 삭제: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit) | |
| 313 | 추가: crate::resources::completed( | |
| 314 | 추가: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit), | |
| 315 | 추가: check, | |
| 316 | 추가: ) | |
| 301 | 317 | })?; |
| 302 | 318 | crate::space::ensure(output, total)?; |
| 303 | 319 | for (f, (start, size)) in self.folders.iter().zip(ranges) { |
| 304 | 삭제: check()?; | |
| 320 | 추가: check.check()?; | |
| 305 | 321 | let base = output.stream_position().map_err(crate::space::io_error)?; |
| 322 | 추가: check.observe( | |
| 323 | 추가: ResourceUsage { | |
| 324 | 추가: compressed_bytes: Some(*size), | |
| 325 | 추가: ratio_output_bytes: Some(f.size as u64), | |
| 326 | 추가: ..ResourceUsage::default() | |
| 327 | 추가: }, | |
| 328 | 추가: Some(output), | |
| 329 | 추가: )?; | |
| 306 | 330 | input |
| 307 | 331 | .seek(SeekFrom::Start(*start)) |
| 308 | 332 | .map_err(crate::space::io_error)?; |
| @@ -314,15 +338,17 @@ impl Streams { | ||
| 314 | 338 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 315 | 339 | let mut remaining = *size; |
| 316 | 340 | while remaining != 0 { |
| 317 | 삭제: check()?; | |
| 341 | 추가: check.check()?; | |
| 318 | 342 | let n = remaining.min(buffer.len() as u64) as usize; |
| 319 | 343 | input |
| 320 | 344 | .read_exact(&mut buffer[..n]) |
| 321 | 345 | .map_err(|_| ErrorCode::Integrity)?; |
| 346 | 추가: crate::space::ensure(output, n as u64)?; | |
| 322 | 347 | output |
| 323 | 348 | .write_all(&buffer[..n]) |
| 324 | 349 | .map_err(crate::space::io_error)?; |
| 325 | 350 | remaining -= n as u64; |
| 351 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 326 | 352 | } |
| 327 | 353 | } |
| 328 | 354 | [3, 1, 1] | [0x21] => crate::lzma::decode_stream( |
| @@ -358,10 +384,14 @@ impl Streams { | ||
| 358 | 384 | } |
| 359 | 385 | } |
| 360 | 386 | at = at.checked_add(*size as u64).ok_or(ErrorCode::Integrity)?; |
| 387 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 361 | 388 | } |
| 362 | 삭제: output | |
| 363 | 삭제: .seek(SeekFrom::Start(base + f.size as u64)) | |
| 364 | 삭제: .map_err(crate::space::io_error)?; | |
| 389 | 추가: crate::resources::completed( | |
| 390 | 추가: output | |
| 391 | 추가: .seek(SeekFrom::Start(base + f.size as u64)) | |
| 392 | 추가: .map_err(crate::space::io_error), | |
| 393 | 추가: check, | |
| 394 | 추가: )?; | |
| 365 | 395 | } |
| 366 | 396 | Ok(()) |
| 367 | 397 | } |
| @@ -370,7 +400,7 @@ fn digest( | ||
| 370 | 400 | file: &mut std::fs::File, |
| 371 | 401 | start: u64, |
| 372 | 402 | size: u64, |
| 373 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 403 | 추가: check: &mut impl crate::resources::Monitor, | |
| 374 | 404 | ) -> Result<u32> { |
| 375 | 405 | use std::io::{Read, Seek, SeekFrom}; |
| 376 | 406 | file.seek(SeekFrom::Start(start)) |
| @@ -379,12 +409,13 @@ fn digest( | ||
| 379 | 409 | let mut remaining = size; |
| 380 | 410 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 381 | 411 | while remaining != 0 { |
| 382 | 삭제: check()?; | |
| 412 | 추가: check.check()?; | |
| 383 | 413 | let n = remaining.min(buffer.len() as u64) as usize; |
| 384 | 414 | file.read_exact(&mut buffer[..n]) |
| 385 | 415 | .map_err(crate::space::io_error)?; |
| 386 | 416 | crc = crc32(crc, &buffer[..n]); |
| 387 | 417 | remaining -= n as u64; |
| 418 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 388 | 419 | } |
| 389 | 420 | Ok(crc) |
| 390 | 421 | } |
| @@ -392,6 +423,7 @@ fn files( | ||
| 392 | 423 | r: &mut Reader<'_>, |
| 393 | 424 | limits: Limits, |
| 394 | 425 | streams: Option<&Streams>, |
| 426 | 추가: check: &mut impl crate::resources::Monitor, | |
| 395 | 427 | ) -> Result<(Vec<Member>, Vec<usize>)> { |
| 396 | 428 | let count = r.number(limits.entries as usize)?; |
| 397 | 429 | let mut empty = vec![false; count]; |
| @@ -407,7 +439,7 @@ fn files( | ||
| 407 | 439 | if !seen.insert(property) { |
| 408 | 440 | return Err(ErrorCode::Integrity); |
| 409 | 441 | } |
| 410 | 삭제: let len = r.number(MAX_METADATA_BYTES)?; | |
| 442 | 추가: let len = r.number(check.metadata_limits().bytes)?; | |
| 411 | 443 | let mut value = Reader::new(r.take(len)?); |
| 412 | 444 | match property { |
| 413 | 445 | 14 => { |
| @@ -432,6 +464,7 @@ fn files( | ||
| 432 | 464 | let mut decoded = Vec::new(); |
| 433 | 465 | let mut budget = MetadataBudget::default(); |
| 434 | 466 | for _ in 0..count { |
| 467 | 추가: check.check()?; | |
| 435 | 468 | let mut units = Vec::new(); |
| 436 | 469 | loop { |
| 437 | 470 | let n = u16::from_le_bytes(value.take(2)?.try_into().unwrap()); |
| @@ -444,8 +477,9 @@ fn files( | ||
| 444 | 477 | units.push(n); |
| 445 | 478 | } |
| 446 | 479 | let name = String::from_utf16(&units).map_err(|_| ErrorCode::Integrity)?; |
| 447 | 삭제: budget.charge(&name)?; | |
| 480 | 추가: budget.charge_with(&name, check.metadata_limits())?; | |
| 448 | 481 | decoded.push(name); |
| 482 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 449 | 483 | } |
| 450 | 484 | names = Some(decoded); |
| 451 | 485 | } |
| @@ -458,6 +492,7 @@ fn files( | ||
| 458 | 492 | if set { |
| 459 | 493 | *attr = Some(u32::from_le_bytes(value.take(4)?.try_into().unwrap())); |
| 460 | 494 | } |
| 495 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 461 | 496 | } |
| 462 | 497 | } |
| 463 | 498 | 18..=20 => { |
| @@ -488,6 +523,7 @@ fn files( | ||
| 488 | 523 | for (folder, compressed) in streams.folders.iter().zip(&streams.packed) { |
| 489 | 524 | for (i, size) in folder.sizes.iter().enumerate() { |
| 490 | 525 | descriptions.push((*size, if i == 0 { *compressed } else { 0 })); |
| 526 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 491 | 527 | } |
| 492 | 528 | } |
| 493 | 529 | } |
| @@ -534,11 +570,12 @@ fn files( | ||
| 534 | 570 | }, |
| 535 | 571 | data: Vec::new(), |
| 536 | 572 | }); |
| 573 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 537 | 574 | } |
| 538 | 575 | if descriptions.next().is_some() { |
| 539 | 576 | return Err(ErrorCode::Integrity); |
| 540 | 577 | } |
| 541 | 삭제: validate_members(&members)?; | |
| 578 | 추가: validate_members_with(&members, check)?; | |
| 542 | 579 | Ok((members, stream_indices)) |
| 543 | 580 | } |
| 544 | 581 | pub(crate) fn open( |
| @@ -546,10 +583,10 @@ pub(crate) fn open( | ||
| 546 | 583 | length: u64, |
| 547 | 584 | limits: Limits, |
| 548 | 585 | decode: bool, |
| 549 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 586 | 추가: check: &mut impl crate::resources::Monitor, | |
| 550 | 587 | ) -> Result<crate::streaming::Catalog> { |
| 551 | 588 | use std::io::{Read, Seek, SeekFrom}; |
| 552 | 삭제: check()?; | |
| 589 | 추가: check.check()?; | |
| 553 | 590 | if length > limits.input { |
| 554 | 591 | return Err(ErrorCode::Limit); |
| 555 | 592 | } |
| @@ -569,7 +606,7 @@ pub(crate) fn open( | ||
| 569 | 606 | } |
| 570 | 607 | let offset = u64::from_le_bytes(header[12..20].try_into().unwrap()); |
| 571 | 608 | let len = u64::from_le_bytes(header[20..28].try_into().unwrap()); |
| 572 | 삭제: if len > MAX_METADATA_BYTES as u64 { | |
| 609 | 추가: if len > check.metadata_limits().bytes as u64 { | |
| 573 | 610 | return Err(ErrorCode::Limit); |
| 574 | 611 | } |
| 575 | 612 | let start = offset.checked_add(32).ok_or(ErrorCode::Integrity)?; |
| @@ -602,16 +639,21 @@ pub(crate) fn open( | ||
| 602 | 639 | if bytes[0] == 23 { |
| 603 | 640 | let mut r = Reader::new(&bytes[1..]); |
| 604 | 641 | let header_limits = Limits { |
| 605 | 삭제: output: MAX_METADATA_BYTES as u64, | |
| 642 | 추가: output: check.metadata_limits().bytes as u64, | |
| 606 | 643 | ..limits |
| 607 | 644 | }; |
| 608 | 삭제: let streams = Streams::read(&mut r, header_limits)?; | |
| 645 | 추가: let streams = Streams::read(&mut r, header_limits, check)?; | |
| 609 | 646 | r.end()?; |
| 610 | 647 | if streams.folders.len() != 1 || streams.folders[0].sizes.len() != 1 { |
| 611 | 648 | return Err(ErrorCode::UnsupportedFeature); |
| 612 | 649 | } |
| 613 | 650 | let ranges = streams.ranges(input, data_end, check)?; |
| 614 | 삭제: streams.decode_file(input, &ranges, &mut data, check)?; | |
| 651 | 추가: streams.decode_file( | |
| 652 | 추가: input, | |
| 653 | 추가: &ranges, | |
| 654 | 추가: &mut data, | |
| 655 | 추가: &mut crate::resources::MetadataMonitor(check), | |
| 656 | 추가: )?; | |
| 615 | 657 | data_end = 32u64 |
| 616 | 658 | .checked_add(streams.position as u64) |
| 617 | 659 | .ok_or(ErrorCode::Integrity)?; |
| @@ -627,7 +669,7 @@ pub(crate) fn open( | ||
| 627 | 669 | let mut tag = r.byte()?; |
| 628 | 670 | if tag == 2 { |
| 629 | 671 | while r.byte()? != 0 { |
| 630 | 삭제: let len = r.number(MAX_METADATA_BYTES)?; | |
| 672 | 추가: let len = r.number(check.metadata_limits().bytes)?; | |
| 631 | 673 | r.take(len)?; |
| 632 | 674 | } |
| 633 | 675 | tag = r.byte()?; |
| @@ -636,11 +678,11 @@ pub(crate) fn open( | ||
| 636 | 678 | return Err(ErrorCode::UnsupportedFeature); |
| 637 | 679 | } |
| 638 | 680 | if tag == 4 { |
| 639 | 삭제: streams = Some(Streams::read(&mut r, limits)?); | |
| 681 | 추가: streams = Some(Streams::read(&mut r, limits, check)?); | |
| 640 | 682 | tag = r.byte()?; |
| 641 | 683 | } |
| 642 | 684 | let (members, stream_indices) = if tag == 5 { |
| 643 | 삭제: let f = files(&mut r, limits, streams.as_ref())?; | |
| 685 | 추가: let f = files(&mut r, limits, streams.as_ref(), check)?; | |
| 644 | 686 | tag = r.byte()?; |
| 645 | 687 | f |
| 646 | 688 | } else { |
| @@ -650,6 +692,31 @@ pub(crate) fn open( | ||
| 650 | 692 | return Err(ErrorCode::Integrity); |
| 651 | 693 | } |
| 652 | 694 | r.end()?; |
| 695 | 추가: let total = members.iter().try_fold(0u64, |n, m| { | |
| 696 | 추가: crate::resources::completed(n.checked_add(m.entry.size).ok_or(ErrorCode::Limit), check) | |
| 697 | 추가: })?; | |
| 698 | 추가: let packed = streams | |
| 699 | 추가: .as_ref() | |
| 700 | 추가: .map(|s| { | |
| 701 | 추가: s.packed.iter().try_fold(0u64, |sum, size| { | |
| 702 | 추가: crate::resources::completed( | |
| 703 | 추가: sum.checked_add(*size as u64).ok_or(ErrorCode::Integrity), | |
| 704 | 추가: check, | |
| 705 | 추가: ) | |
| 706 | 추가: }) | |
| 707 | 추가: }) | |
| 708 | 추가: .transpose()?; | |
| 709 | 추가: check.observe( | |
| 710 | 추가: ResourceUsage { | |
| 711 | 추가: estimated_bytes: Some(total), | |
| 712 | 추가: estimated_entries: Some(members.len() as u32), | |
| 713 | 추가: compressed_bytes: packed, | |
| 714 | 추가: ratio_output_bytes: Some(total), | |
| 715 | 추가: ..ResourceUsage::default() | |
| 716 | 추가: }, | |
| 717 | 추가: Some(&data), | |
| 718 | 추가: )?; | |
| 719 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 653 | 720 | let mut offsets = vec![0; members.len()]; |
| 654 | 721 | if let Some(streams) = streams { |
| 655 | 722 | if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() { |
| @@ -662,6 +729,7 @@ pub(crate) fn open( | ||
| 662 | 729 | for size in &f.sizes { |
| 663 | 730 | offsets[ids.next().ok_or(ErrorCode::Integrity)?] = at; |
| 664 | 731 | at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?; |
| 732 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 665 | 733 | } |
| 666 | 734 | } |
| 667 | 735 | if at > limits.output { |
| @@ -682,7 +750,7 @@ pub(crate) fn parse( | ||
| 682 | 750 | input: &[u8], |
| 683 | 751 | limits: Limits, |
| 684 | 752 | decode: bool, |
| 685 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 753 | 추가: check: &mut impl crate::resources::Monitor, | |
| 686 | 754 | ) -> Result<Vec<Member>> { |
| 687 | 755 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 688 | 756 | let mut source = crate::spool::temporary()?; |
| @@ -703,6 +771,7 @@ pub(crate) fn parse( | ||
| 703 | 771 | .take(member.entry.size) |
| 704 | 772 | .read_to_end(&mut member.data) |
| 705 | 773 | .map_err(crate::space::io_error)?; |
| 774 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 706 | 775 | } |
| 707 | 776 | } |
| 708 | 777 | Ok(catalog.members) |
| @@ -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::{ |
| @@ -73,9 +73,23 @@ pub(crate) fn temporary() -> Result<File> { | ||
| 73 | 73 | #[derive(Clone, Copy, Debug)] |
| 74 | 74 | pub(crate) enum Step { |
| 75 | 75 | Check, |
| 76 | 추가: Activity, | |
| 76 | 77 | Read { bytes: u64, total: u64 }, |
| 77 | 78 | } |
| 78 | 79 | |
| 80 | 추가: struct Progress<'a, F>(&'a mut F); | |
| 81 | 추가: impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> { | |
| 82 | 추가: fn check(&mut self) -> Result<()> { | |
| 83 | 추가: self.0(Step::Check) | |
| 84 | 추가: } | |
| 85 | 추가: fn activity(&mut self) -> Result<()> { | |
| 86 | 추가: self.0(Step::Activity) | |
| 87 | 추가: } | |
| 88 | 추가: } | |
| 89 | 추가: fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> { | |
| 90 | 추가: crate::resources::completed(result, &mut Progress(step)) | |
| 91 | 추가: } | |
| 92 | 추가: | |
| 79 | 93 | pub(crate) struct Snapshot { |
| 80 | 94 | pub file: File, |
| 81 | 95 | pub len: u64, |
| @@ -101,24 +115,28 @@ impl Snapshot { | ||
| 101 | 115 | use std::os::windows::fs::OpenOptionsExt; |
| 102 | 116 | options.share_mode(1); |
| 103 | 117 | } |
| 104 | 삭제: let mut source = options.open(path).map_err(|_| ErrorCode::Io)?; | |
| 118 | 추가: let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?; | |
| 105 | 119 | let snapshot = Self::capture_reporting(&mut source, limit, step)?; |
| 106 | 삭제: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 120 | 추가: let named = completed( | |
| 121 | 추가: options.open(path).map_err(|_| ErrorCode::SourceChanged), | |
| 122 | 추가: step, | |
| 123 | 추가: )?; | |
| 107 | 124 | if filesystem::object(&named)? != snapshot.object |
| 108 | 125 | || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file() |
| 109 | 126 | { |
| 110 | 127 | return Err(ErrorCode::SourceChanged); |
| 111 | 128 | } |
| 112 | 삭제: Ok(snapshot) | |
| 129 | 추가: completed(Ok(snapshot), step) | |
| 113 | 130 | } |
| 114 | 131 | pub(crate) fn capture( |
| 115 | 132 | source: &mut File, |
| 116 | 133 | limit: u64, |
| 117 | 삭제: check: &mut impl FnMut() -> Result<()>, | |
| 134 | 추가: check: &mut impl crate::resources::Monitor, | |
| 118 | 135 | ) -> Result<Self> { |
| 119 | 136 | Self::capture_reporting(source, limit, &mut |step| match step { |
| 120 | 삭제: Step::Check => check(), | |
| 121 | 삭제: Step::Read { .. } => Ok(()), | |
| 137 | 추가: Step::Check => check.check(), | |
| 138 | 추가: Step::Activity => crate::resources::completed(Ok(()), check), | |
| 139 | 추가: Step::Read { .. } => check.check(), | |
| 122 | 140 | }) |
| 123 | 141 | } |
| 124 | 142 | fn capture_reporting( |
| @@ -126,7 +144,7 @@ impl Snapshot { | ||
| 126 | 144 | limit: u64, |
| 127 | 145 | step: &mut impl FnMut(Step) -> Result<()>, |
| 128 | 146 | ) -> Result<Self> { |
| 129 | 삭제: let before = source.metadata().map_err(|_| ErrorCode::Io)?; | |
| 147 | 추가: let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?; | |
| 130 | 148 | if !before.is_file() { |
| 131 | 149 | return Err(ErrorCode::InvalidRequest); |
| 132 | 150 | } |
| @@ -135,8 +153,8 @@ impl Snapshot { | ||
| 135 | 153 | } |
| 136 | 154 | source.rewind().map_err(|_| ErrorCode::Io)?; |
| 137 | 155 | let object = filesystem::object(&source)?; |
| 138 | 삭제: let mut file = temporary()?; | |
| 139 | 삭제: crate::space::ensure(&file, before.len())?; | |
| 156 | 추가: let mut file = completed(temporary(), step)?; | |
| 157 | 추가: completed(crate::space::ensure(&file, before.len()), step)?; | |
| 140 | 158 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 141 | 159 | let mut hash = Sha256::new(); |
| 142 | 160 | let mut len = 0u64; |
| @@ -144,7 +162,10 @@ impl Snapshot { | ||
| 144 | 162 | let mut reported = std::time::Instant::now(); |
| 145 | 163 | loop { |
| 146 | 164 | step(Step::Check)?; |
| 147 | 삭제: let n = source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io)?; | |
| 165 | 추가: let n = completed( | |
| 166 | 추가: source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io), | |
| 167 | 추가: step, | |
| 168 | 추가: )?; | |
| 148 | 169 | if n == 0 { |
| 149 | 170 | break; |
| 150 | 171 | } |
| @@ -152,8 +173,10 @@ impl Snapshot { | ||
| 152 | 173 | .checked_add(n as u64) |
| 153 | 174 | .filter(|n| *n <= limit) |
| 154 | 175 | .ok_or(ErrorCode::Limit)?; |
| 155 | 삭제: file.write_all(&buffer[..n]) | |
| 156 | 삭제: .map_err(crate::space::io_error)?; | |
| 176 | 추가: completed( | |
| 177 | 추가: file.write_all(&buffer[..n]).map_err(crate::space::io_error), | |
| 178 | 추가: step, | |
| 179 | 추가: )?; | |
| 157 | 180 | hash.update(&buffer[..n]); |
| 158 | 181 | // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림. |
| 159 | 182 | if reported.elapsed() >= std::time::Duration::from_millis(200) { |
| @@ -170,7 +193,10 @@ impl Snapshot { | ||
| 170 | 193 | { |
| 171 | 194 | return Err(ErrorCode::SourceChanged); |
| 172 | 195 | } |
| 173 | 삭제: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io)?; | |
| 196 | 추가: completed( | |
| 197 | 추가: file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io), | |
| 198 | 추가: step, | |
| 199 | 추가: )?; | |
| 174 | 200 | Ok(Self { |
| 175 | 201 | file, |
| 176 | 202 | len, |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기