안전한 Rust 압축 작업자를 구현함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
aa5ecd50bd0509ec922329680facfe6acb671d5a- 부모
- 486fe9a
변경된 파일 29개
+2,764-0변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1 @@ | ||
| 1 | 추가: /target/ |
| @@ -0,0 +1,100 @@ | ||
| 1 | 추가: # This file is automatically @generated by Cargo. | |
| 2 | 추가: # It is not intended for manual editing. | |
| 3 | 추가: version = 4 | |
| 4 | 추가: | |
| 5 | 추가: [[package]] | |
| 6 | 추가: name = "block-buffer" | |
| 7 | 추가: version = "0.10.4" | |
| 8 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 9 | 추가: checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" | |
| 10 | 추가: dependencies = [ | |
| 11 | 추가: "generic-array", | |
| 12 | 추가: ] | |
| 13 | 추가: | |
| 14 | 추가: [[package]] | |
| 15 | 추가: name = "cfg-if" | |
| 16 | 추가: version = "1.0.5" | |
| 17 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 18 | 추가: checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" | |
| 19 | 추가: | |
| 20 | 추가: [[package]] | |
| 21 | 추가: name = "cpufeatures" | |
| 22 | 추가: version = "0.2.17" | |
| 23 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 24 | 추가: checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" | |
| 25 | 추가: dependencies = [ | |
| 26 | 추가: "libc", | |
| 27 | 추가: ] | |
| 28 | 추가: | |
| 29 | 추가: [[package]] | |
| 30 | 추가: name = "crypto-common" | |
| 31 | 추가: version = "0.1.7" | |
| 32 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 33 | 추가: checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" | |
| 34 | 추가: dependencies = [ | |
| 35 | 추가: "generic-array", | |
| 36 | 추가: "typenum", | |
| 37 | 추가: ] | |
| 38 | 추가: | |
| 39 | 추가: [[package]] | |
| 40 | 추가: name = "digest" | |
| 41 | 추가: version = "0.10.7" | |
| 42 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 43 | 추가: checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" | |
| 44 | 추가: dependencies = [ | |
| 45 | 추가: "block-buffer", | |
| 46 | 추가: "crypto-common", | |
| 47 | 추가: ] | |
| 48 | 추가: | |
| 49 | 추가: [[package]] | |
| 50 | 추가: name = "generic-array" | |
| 51 | 추가: version = "0.14.7" | |
| 52 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 53 | 추가: checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" | |
| 54 | 추가: dependencies = [ | |
| 55 | 추가: "typenum", | |
| 56 | 추가: "version_check", | |
| 57 | 추가: ] | |
| 58 | 추가: | |
| 59 | 추가: [[package]] | |
| 60 | 추가: name = "libc" | |
| 61 | 추가: version = "0.2.191" | |
| 62 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 63 | 추가: checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | |
| 64 | 추가: | |
| 65 | 추가: [[package]] | |
| 66 | 추가: name = "sha2" | |
| 67 | 추가: version = "0.10.9" | |
| 68 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 69 | 추가: checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" | |
| 70 | 추가: dependencies = [ | |
| 71 | 추가: "cfg-if", | |
| 72 | 추가: "cpufeatures", | |
| 73 | 추가: "digest", | |
| 74 | 추가: ] | |
| 75 | 추가: | |
| 76 | 추가: [[package]] | |
| 77 | 추가: name = "typenum" | |
| 78 | 추가: version = "1.20.1" | |
| 79 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 80 | 추가: checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" | |
| 81 | 추가: | |
| 82 | 추가: [[package]] | |
| 83 | 추가: name = "version_check" | |
| 84 | 추가: version = "0.9.5" | |
| 85 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 86 | 추가: checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" | |
| 87 | 추가: | |
| 88 | 추가: [[package]] | |
| 89 | 추가: name = "zipelo-archive-worker" | |
| 90 | 추가: version = "0.1.0" | |
| 91 | 추가: dependencies = [ | |
| 92 | 추가: "sha2", | |
| 93 | 추가: "zlib-rs", | |
| 94 | 추가: ] | |
| 95 | 추가: | |
| 96 | 추가: [[package]] | |
| 97 | 추가: name = "zlib-rs" | |
| 98 | 추가: version = "0.6.8" | |
| 99 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 100 | 추가: checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" |
| @@ -0,0 +1,17 @@ | ||
| 1 | 추가: [package] | |
| 2 | 추가: name = "zipelo-archive-worker" | |
| 3 | 추가: version = "0.1.0" | |
| 4 | 추가: edition = "2024" | |
| 5 | 추가: license = "MIT" | |
| 6 | 추가: publish = false | |
| 7 | 추가: autotests = false | |
| 8 | 추가: | |
| 9 | 추가: [dependencies] | |
| 10 | 추가: sha2 = "=0.10.9" | |
| 11 | 추가: zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] } | |
| 12 | 추가: | |
| 13 | 추가: [workspace] | |
| 14 | 추가: | |
| 15 | 추가: [[test]] | |
| 16 | 추가: name = "archive_worker" | |
| 17 | 추가: path = "../../tests/rust-archive-worker/main.rs" |
| @@ -0,0 +1,27 @@ | ||
| 1 | 추가: # Rust archive worker | |
| 2 | 추가: | |
| 3 | 추가: 별도 프로세스의 stdin/stdout으로 revision 2 요청을 처리합니다. 제품 앱 연결과 OS sandbox를 제공하는 단계는 아닙니다. 암호 기능은 capability=false이며 암호 ZIP 해제 및 AES 생성 요청은 UnsupportedFeature로 종료합니다. | |
| 4 | 추가: | |
| 5 | 추가: - ZIP32 Store/Deflate 목록, 해제, 생성, 기본 TAR/USTAR, GZ, TAR.GZ 해제를 지원합니다. GZ 연결 멤버는 하나의 논리 스트림으로 합칩니다. ZIP64, 다중 볼륨, 비 UTF-8 ZIP 이름, PAX/GNU 확장과 특수 항목 해제는 미지원입니다. | |
| 6 | 추가: - 입력은 최대 64 MiB, 해독/생성 출력은 최대 128 MiB, 항목은 최대 10,000개입니다. 요청 limits는 이 값을 낮출 수 있습니다. 입력과 검증 완료 payload를 메모리에 보관해 모든 선택 출력의 CRC, 크기와 경로를 쓰기 전에 검사합니다. checkpoint마다 취소와 300초 한도를 확인합니다. | |
| 7 | 추가: - ListId는 열린 파일 객체, 전체 입력 SHA-256과 catalog version에 연결됩니다. 입력을 다시 읽어 검증한 전용 메모리 스냅샷만 해독합니다. 불일치는 출력 전 SourceChanged이며 목록을 다시 열어야 합니다. 원본의 사후 변경 감시나 파일 잠금 보장은 아닙니다. | |
| 8 | 추가: - 출력 폴더는 미리 존재해야 합니다. Linux는 소유 UID가 같고 group/other 쓰기가 없는 폴더만 허용합니다. openat/O_NOFOLLOW로 디렉터리를 고정하고 새 임시 파일을 배타적으로 만든 뒤 hard link로 게시합니다. 기존 파일과 링크를 덮어쓰지 않습니다. Windows는 reparse point를 거부하고 부모 디렉터리 핸들에서 delete sharing을 제한합니다. | |
| 9 | 추가: - 파일 sync/close는 게시 전에 확인합니다. 게시 후 부모 sync와 임시 파일 정리 실패는 게시 사실과 따로 보고합니다. Windows의 디렉터리 내구성은 Unconfirmed입니다. hard link의 결과가 불명확하면 CommitUncertain/Uncertain이며 자동 재시도나 rollback은 없습니다. | |
| 10 | 추가: - 생성한 디렉터리와 게시한 파일은 취소 시 유지하고 Output으로 보고합니다. 실패한 임시 파일 정리는 실제 임시 이름과 PartialRetained로 보고합니다. 실파일 close/sync/link 장애 주입과 Windows 실기 검증은 아직 수행하지 않았습니다. | |
| 11 | 추가: | |
| 12 | 추가: ## 공유 codec | |
| 13 | 추가: | |
| 14 | 추가: `protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 의존성 없는 LE codec입니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다. | |
| 15 | 추가: | |
| 16 | 추가: 헤더는 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를 거부합니다. | |
| 17 | 추가: | |
| 18 | 추가: - kind: Start=1, Password=2, Cancel=3, Accepted=100, Entry=101, ListEnd=102, PasswordRequired=103, Progress=104, Output=105, Terminal=106, CancelAck=107입니다. | |
| 19 | 추가: - 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)입니다. | |
| 20 | 추가: - Password의 비밀 값은 Debug에 노출되지 않습니다. 이 버전은 PasswordRequired를 보내지 않으므로 들어온 Password는 Protocol 오류입니다. 비밀 값은 로그나 파일에 저장하지 않습니다. | |
| 21 | 추가: - CancelAck.request_sequence는 요청 헤더 sequence입니다. Requested, AlreadyRequested, TooLate, Finished는 최종 결과와 별개입니다. 종료와 경합한 요청은 읽히지 않아 응답이 없을 수 있습니다. Terminal은 마지막 프레임이며 Failed/Cancelled도 정상 전달 뒤 프로세스 exit=0입니다. 앱은 Terminal과 stdout/stderr EOF, child wait를 모두 확인해야 합니다. | |
| 22 | 추가: | |
| 23 | 추가: ## 검증과 의존성 | |
| 24 | 추가: | |
| 25 | 추가: 시험은 `tests/rust-archive-worker`에 있습니다. Python 표준 라이브러리로 만든 ZIP/TAR/GZ fixture와 실제 자식 프로세스를 사용합니다. 전체 검증 명령은 저장소 루트의 `python3 tests/ci/run_rust.py local`입니다. Windows 교차 빌드는 실제 Windows 실행 검증을 대신하지 않습니다. | |
| 26 | 추가: | |
| 27 | 추가: 직접 의존성은 기존 zlib-rs=0.6.8와 허용된 RustCrypto sha2=0.10.9입니다. 2026-11-11에 확인한 [zlib-rs RUSTSEC-2024-0401](https://rustsec.org/advisories/RUSTSEC-2024-0401.html)은 >=0.4.0, [sha2 RUSTSEC-2021-0100](https://rustsec.org/advisories/RUSTSEC-2021-0100.html)은 >=0.9.8을 수정 버전으로 명시합니다. 선택 버전은 이 수정 범위에 들어갑니다. 이는 전체 전이 의존성의 취약점 부재나 완전한 보안 감사를 의미하지 않습니다. |
| @@ -0,0 +1,140 @@ | ||
| 1 | 추가: { | |
| 2 | 추가: "status": "frontend-conditions-addressed-codec-not-implemented", | |
| 3 | 추가: "version": 1, | |
| 4 | 추가: "scope": "One job per separately spawned Rust worker; shared std-only binary codec. Process separation is not an OS sandbox.", | |
| 5 | 추가: "frame": { | |
| 6 | 추가: "magic": "ZAW1", | |
| 7 | 추가: "header_bytes": 32, | |
| 8 | 추가: "fields_le": [ | |
| 9 | 추가: "magic[4]", | |
| 10 | 추가: "version:u16=1", | |
| 11 | 추가: "kind:u16", | |
| 12 | 추가: "body_bytes:u32", | |
| 13 | 추가: "reserved:u32=0", | |
| 14 | 추가: "job_id:u64(nonzero)", | |
| 15 | 추가: "sequence:u64" | |
| 16 | 추가: ], | |
| 17 | 추가: "sequence": "Independent direction counters start0 and increase exactly once; reject duplicates, gaps and wrap.", | |
| 18 | 추가: "max_body_bytes": 1048576, | |
| 19 | 추가: "max_frames_per_job": 1000000, | |
| 20 | 추가: "payload": "Fixed enum tags and LE integers; length-prefix byte/string/vector values with allocation bounds; reject unknown tags and trailing fields." | |
| 21 | 추가: }, | |
| 22 | 추가: "paths": { | |
| 23 | 추가: "unix": "tag1 and exact native bytes", | |
| 24 | 추가: "windows": "tag2 and UTF-16LE units", | |
| 25 | 추가: "rules": "Platform encoding must match. Reject NUL and nonabsolute roots; Windows UNC/device paths unsupported. No lossy execution paths.", | |
| 26 | 추가: "archive_names": "Separate validated UTF-8 relative names; entry IDs are opaque ordinal u32, not paths." | |
| 27 | 추가: }, | |
| 28 | 추가: "commands": { | |
| 29 | 추가: "Start": "Exactly once: List{archive}, Extract{archive,destination,selection:All|EntryIds{ids:[u32]},list_id:optional<ListId>,gzip_output_name:optional<UTF8>}, CreateZip{sources:[source_path,archive_name],output_file,method:Store|Deflate,encryption:None|Aes256}. App supplies job_id; caller can lower worker hard limits. Extract destination is always an absolute output directory. EntryIds requires list_id; All may supply list_id to bind extraction to a displayed list.", | |
| 30 | 추가: "Password": "Matching outstanding challenge_id:u64 and max1024 UTF-8 bytes; never log, Debug, echo or persist secrets.", | |
| 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 | 추가: }, | |
| 33 | 추가: "events": { | |
| 34 | 추가: "Accepted": "Action and capabilities; encryption capability remains false until implementation and verification are complete.", | |
| 35 | 추가: "Entry": "entry_id, name, kind File|Directory|Link|Other, declared sizes, encrypted; ordinal u32 IDs belong to this List job only until its ListEnd token and Completed Terminal are confirmed. Metadata only, no CRC success claim.", | |
| 36 | 추가: "ListEnd": "entry_count:u32 and list_id:ListId for a complete listing. Entry IDs are deterministic zero-based ordinals in archive traversal order. App associates this token with this job entries only after Completed Terminal, both stream EOFs and successful child wait/exit.", | |
| 37 | 추가: "PasswordRequired": "challenge_id, attempt and purpose Decrypt|Encrypt; no secret diagnostics.", | |
| 38 | 추가: "Progress": "stage Scan|Read|Decode|Write|Verify|Commit, processed_bytes,total_bytes:optional,completed_entries; observational only.", | |
| 39 | 추가: "Output": "entry_id:optional, relative_name, disposition Created|PartialRetained|Removed|CommitUncertain; only this job outputs.", | |
| 40 | 추가: "Terminal": { | |
| 41 | 추가: "outcome": "Completed|Failed|Cancelled", | |
| 42 | 추가: "error": "None|Integrity|UnsupportedFormat|UnsupportedFeature|WrongPassword|UnsafePath|Conflict|Limit|Io|Protocol|Internal|SourceChanged|InvalidRequest", | |
| 43 | 추가: "publication": "None|Partial|Complete|Uncertain", | |
| 44 | 추가: "created_count": "u64", | |
| 45 | 추가: "retained_partial_count": "u64", | |
| 46 | 추가: "durability": "NotApplicable|Synced|Unconfirmed|Failed", | |
| 47 | 추가: "cleanup": "Complete|Failed|Unconfirmed", | |
| 48 | 추가: "detail": "Bounded local description, not a substitute for typed errors." | |
| 49 | 추가: }, | |
| 50 | 추가: "CancelAck": { | |
| 51 | 추가: "request_sequence": "u64: echoed Cancel command header sequence; separate from this event header sequence.", | |
| 52 | 추가: "status": "Requested|AlreadyRequested|TooLate|Finished", | |
| 53 | 추가: "Requested": "Cancellation flag was latched for the first time before the job cancellation cutoff. Cooperative request acceptance; not a guarantee of Cancelled, no outputs or rollback.", | |
| 54 | 추가: "AlreadyRequested": "Cancellation was already latched and the job can still observe it. The flag stays latched; no second request or reset.", | |
| 55 | 추가: "TooLate": "Final job completion/commit decision has been sealed so cancellation can no longer influence the outcome; final outcome may still be Failed or publication Uncertain. Previously created entries alone do not make a multi-entry job TooLate.", | |
| 56 | 추가: "Finished": "Business outcome has already been fixed, but Terminal has not yet been emitted. Does not establish success, EOF, child exit or reaping.", | |
| 57 | 추가: "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." | |
| 58 | 추가: } | |
| 59 | 추가: }, | |
| 60 | 추가: "lifecycle": [ | |
| 61 | 추가: "Start once; no automatic retry or overwrite. Password/Cancel remain readable during work.", | |
| 62 | 추가: "Parent drains both streams concurrently. Stdout is protocol only; stderr is bounded diagnostics without secrets.", | |
| 63 | 추가: "Exactly one Terminal ends business results and is the final worker protocol frame; CancelAck can precede but never follow it. Worker exits0 after delivered terminal, including Failed/Cancelled. Malformed protocol or crash can exit nonzero without terminal.", | |
| 64 | 추가: "App requires matching terminal, stdout/stderr EOF and owned child wait/exit before replacement/close. EOF/exit0 alone is not success.", | |
| 65 | 추가: "Lost/killed worker preserves observed outputs; unobserved commit/cleanup stays uncertain, never synthetic Cancelled/rollback/absent output.", | |
| 66 | 추가: "Cancellation retains completed outputs; cleanup removes only owned temporary files and reports any retained partial.", | |
| 67 | 추가: "Completed is not OS sandboxing or release evidence. No security-setting changes." | |
| 68 | 추가: ], | |
| 69 | 추가: "safe_output": [ | |
| 70 | 추가: "Reject absolute/dotdot/drive/UNC/device/reserved/alternate-stream names and case/path collisions before writes.", | |
| 71 | 추가: "Reject archive links/special entries on extraction. Do not follow output parent symlinks/reparse points.", | |
| 72 | 추가: "Create output files exclusively; never truncate or write pre-existing files. GZip FNAME does not choose destination.", | |
| 73 | 추가: "CRC/size/stream-end validation precedes committed output events; preserve commit/durability/cleanup distinctions." | |
| 74 | 추가: ], | |
| 75 | 추가: "pending": [ | |
| 76 | 추가: "Frontend draft acceptance was conditional on these three clarifications, now specified. Shared codec and app/worker integration remain unimplemented and unverified.", | |
| 77 | 추가: "RustCrypto version selection, encryption implementation and verification; capability remains unavailable until complete.", | |
| 78 | 추가: "Actual Linux and Windows build/runtime results; neither claimed yet." | |
| 79 | 추가: ], | |
| 80 | 추가: "performed": { | |
| 81 | 추가: "implementation": false, | |
| 82 | 추가: "cargo_build": false, | |
| 83 | 추가: "tests": false, | |
| 84 | 추가: "worker_runs": false, | |
| 85 | 추가: "remote_branch_or_pr": false | |
| 86 | 추가: }, | |
| 87 | 추가: "crypto": { | |
| 88 | 추가: "rustcrypto_allowed": true, | |
| 89 | 추가: "approval_message_id": "2966b0ad-a3e0-49b8-aef8-fb51c4e1c5a5", | |
| 90 | 추가: "implementation_verified": false, | |
| 91 | 추가: "policy": "Human approved pure Rust RustCrypto under MIT/Apache. No home-grown AES or password KDF; approval alone does not enable encryption capability." | |
| 92 | 추가: }, | |
| 93 | 추가: "revision": 2, | |
| 94 | 추가: "coordination": { | |
| 95 | 추가: "frontend_message_id": "41a0e5a5-27d0-437f-805d-d39313082096", | |
| 96 | 추가: "basis": "Frontend can use the draft subject to three clarifications. This revision specifies list identity, explicit raw GZip output naming and cancellation acknowledgement. It does not claim implementation or runtime verification." | |
| 97 | 추가: }, | |
| 98 | 추가: "list_identity": { | |
| 99 | 추가: "ListId": { | |
| 100 | 추가: "catalog_version": "u16=1; reject unsupported versions without remapping entry IDs.", | |
| 101 | 추가: "format": "ZIP|TAR|GZIP|TAR_GZIP; detected parser mode, not the filename extension.", | |
| 102 | 추가: "source_object": "Tagged native identity from the opened source handle: Unix{device:u64,inode:u64} or Windows{volume_serial:u64,file_id:[u8;16]}. Platform must match; unavailable reliable identity returns UnsupportedFeature.", | |
| 103 | 추가: "archive_bytes": "u64: exact complete compressed/source byte length, bounded by worker limits.", | |
| 104 | 추가: "archive_sha256": "[u8;32]: SHA-256 of every source byte, using the permitted RustCrypto implementation; not CRC or path/size/mtime alone." | |
| 105 | 추가: }, | |
| 106 | 추가: "capture": [ | |
| 107 | 추가: "Open the regular source file once and keep its handle. Copy through bounded reads into a private job-owned snapshot while computing full SHA-256. Check source handle identity, length and modification metadata before/after capture; detected mutation rejects the capture. Check the named source still resolves to the same object at the validation boundary.", | |
| 108 | 추가: "The completed private snapshot is the sole input to parsing and decoding for this job; never hash one file and later reopen the path to decode. Snapshot storage is bounded, exclusively owned and not writable through attacker-selected names. Failure to establish a stable private snapshot fails before creating destination outputs.", | |
| 109 | 추가: "List builds the deterministic catalog from that snapshot and returns its ListId only with successful ListEnd. A failed/cancelled/truncated listing provides no reusable selection token." | |
| 110 | 추가: ], | |
| 111 | 추가: "extract_validation": [ | |
| 112 | 추가: "Treat every supplied ListId and entry ID as untrusted. EntryIds without ListId, empty/duplicate IDs or IDs outside the recomputed catalog fail InvalidRequest before destination output creation.", | |
| 113 | 추가: "Capture the Extract source into a new private snapshot, recompute identity/length/SHA-256/format/catalog version and compare every ListId field before creating any destination output. A mismatch returns Terminal Failed/SourceChanged with publication None and zero created/retained outputs. The app invalidates the displayed selection and asks the user to reopen/list; no automatic extraction retry or ordinal remapping.", | |
| 114 | 추가: "When All supplies ListId, apply the same comparison. All without ListId means extract the current captured archive without claiming it matches any earlier listing.", | |
| 115 | 추가: "EntryIds refer to the recomputed catalog ordinals, never names supplied by the app; extract the selected members in archive traversal order. Link/special-entry and output path guards remain mandatory after identity validation." | |
| 116 | 추가: ], | |
| 117 | 추가: "boundary": "This binds extraction to verified snapshot bytes and observed native identity at capture/validation time. It is not authorization, a signed token, an exclusive filesystem lock or a promise to detect every external edit after capture or a byte-identical change-and-restore. Later source changes cannot change the bytes decoded from the private snapshot." | |
| 118 | 추가: }, | |
| 119 | 추가: "gzip_output": { | |
| 120 | 추가: "destination": "Always the output directory, never a full output filename.", | |
| 121 | 추가: "gzip_output_name": "Required Some(nonempty validated UTF-8 single leaf filename) for raw GZIP extraction, for both All and EntryIds. Reject absolute/drive/UNC/device/alternate-stream/reserved names, separators, dot/dotdot and invalid leaf names before creating outputs. Missing/invalid value returns InvalidRequest; no implicit basename or FNAME fallback.", | |
| 122 | 추가: "other_formats": "Must be None for ZIP, TAR and TAR_GZIP; reject Some as InvalidRequest rather than silently ignoring it. TAR_GZIP uses validated inner TAR member names.", | |
| 123 | 추가: "gzip_catalog": "Raw GZIP is one logical stream entry with entry_id0. Its listed display name is not an output path; entry selection still requires ListId.", | |
| 124 | 추가: "publication": "Resolve the supplied leaf under destination using the same no-follow and exclusive-create guards. Existing destination files return Conflict; never overwrite, rename to an automatic alternative or retry." | |
| 125 | 추가: }, | |
| 126 | 추가: "design_references": [ | |
| 127 | 추가: { | |
| 128 | 추가: "url": "https://docs.rs/sha2/latest/sha2/", | |
| 129 | 추가: "purpose": "RustCrypto SHA-256 implementation documentation; dependency version and advisories still require selection-time verification." | |
| 130 | 추가: }, | |
| 131 | 추가: { | |
| 132 | 추가: "url": "https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_info", | |
| 133 | 추가: "purpose": "Native Windows opened-file identity fields." | |
| 134 | 추가: }, | |
| 135 | 추가: { | |
| 136 | 추가: "url": "https://man7.org/linux/man-pages/man2/stat.2.html", | |
| 137 | 추가: "purpose": "Source metadata from the open file descriptor rather than a later path reopen." | |
| 138 | 추가: } | |
| 139 | 추가: ] | |
| 140 | 추가: } |
| @@ -0,0 +1,592 @@ | ||
| 1 | 추가: use crate::protocol::*; | |
| 2 | 추가: use std::collections::BTreeMap; | |
| 3 | 추가: use zlib_rs::{Deflate, DeflateFlush, Inflate, InflateFlush, Status, crc32::crc32}; | |
| 4 | 추가: | |
| 5 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 6 | 추가: #[derive(Debug)] | |
| 7 | 추가: pub struct Member { | |
| 8 | 추가: pub entry: Entry, | |
| 9 | 추가: pub data: Vec<u8>, | |
| 10 | 추가: } | |
| 11 | 추가: pub struct Catalog { | |
| 12 | 추가: pub format: Format, | |
| 13 | 추가: pub members: Vec<Member>, | |
| 14 | 추가: } | |
| 15 | 추가: fn part(b: &[u8], at: usize, n: usize) -> Result<&[u8]> { | |
| 16 | 추가: b.get(at..at.checked_add(n).ok_or(ErrorCode::Integrity)?) | |
| 17 | 추가: .ok_or(ErrorCode::Integrity) | |
| 18 | 추가: } | |
| 19 | 추가: fn u16at(b: &[u8], at: usize) -> Result<u16> { | |
| 20 | 추가: Ok(u16::from_le_bytes(part(b, at, 2)?.try_into().unwrap())) | |
| 21 | 추가: } | |
| 22 | 추가: fn u32at(b: &[u8], at: usize) -> Result<u32> { | |
| 23 | 추가: Ok(u32::from_le_bytes(part(b, at, 4)?.try_into().unwrap())) | |
| 24 | 추가: } | |
| 25 | 추가: | |
| 26 | 추가: pub fn valid_name(name: &str, directory: bool) -> Result<String> { | |
| 27 | 추가: let name = if directory { | |
| 28 | 추가: name.strip_suffix('/').unwrap_or(name) | |
| 29 | 추가: } else { | |
| 30 | 추가: name | |
| 31 | 추가: }; | |
| 32 | 추가: if name.is_empty() | |
| 33 | 추가: || name.len() > 4096 | |
| 34 | 추가: || name.starts_with('/') | |
| 35 | 추가: || name.contains('\\') | |
| 36 | 추가: || name | |
| 37 | 추가: .chars() | |
| 38 | 추가: .any(|c| c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|')) | |
| 39 | 추가: { | |
| 40 | 추가: return Err(ErrorCode::UnsafePath); | |
| 41 | 추가: } | |
| 42 | 추가: for component in name.split('/') { | |
| 43 | 추가: if component.is_empty() | |
| 44 | 추가: || matches!(component, "." | "..") | |
| 45 | 추가: || component.ends_with(['.', ' ']) | |
| 46 | 추가: || component.len() > 255 | |
| 47 | 추가: { | |
| 48 | 추가: return Err(ErrorCode::UnsafePath); | |
| 49 | 추가: } | |
| 50 | 추가: let stem = component.split('.').next().unwrap().to_ascii_uppercase(); | |
| 51 | 추가: if matches!( | |
| 52 | 추가: stem.as_str(), | |
| 53 | 추가: "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" | |
| 54 | 추가: ) || ["COM", "LPT"].iter().any(|p| { | |
| 55 | 추가: stem.strip_prefix(p).is_some_and(|n| { | |
| 56 | 추가: matches!( | |
| 57 | 추가: n, | |
| 58 | 추가: "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" | |
| 59 | 추가: ) | |
| 60 | 추가: }) | |
| 61 | 추가: }) { | |
| 62 | 추가: return Err(ErrorCode::UnsafePath); | |
| 63 | 추가: } | |
| 64 | 추가: } | |
| 65 | 추가: Ok(name.to_owned()) | |
| 66 | 추가: } | |
| 67 | 추가: pub fn validate_members(members: &[Member]) -> Result<()> { | |
| 68 | 추가: let mut names = BTreeMap::<String, bool>::new(); | |
| 69 | 추가: for member in members { | |
| 70 | 추가: let directory = member.entry.kind == EntryKind::Directory; | |
| 71 | 추가: let name = valid_name(&member.entry.name, directory)?.to_lowercase(); | |
| 72 | 추가: if names.insert(name, directory).is_some() { | |
| 73 | 추가: return Err(ErrorCode::Conflict); | |
| 74 | 추가: } | |
| 75 | 추가: } | |
| 76 | 추가: for name in names.keys() { | |
| 77 | 추가: let mut parent = name.as_str(); | |
| 78 | 추가: while let Some((p, _)) = parent.rsplit_once('/') { | |
| 79 | 추가: if names.get(p) == Some(&false) { | |
| 80 | 추가: return Err(ErrorCode::Conflict); | |
| 81 | 추가: } | |
| 82 | 추가: parent = p; | |
| 83 | 추가: } | |
| 84 | 추가: } | |
| 85 | 추가: Ok(()) | |
| 86 | 추가: } | |
| 87 | 추가: fn bounded_append(output: &mut Vec<u8>, data: &[u8], limit: u64) -> Result<()> { | |
| 88 | 추가: if (output.len() as u64) | |
| 89 | 추가: .checked_add(data.len() as u64) | |
| 90 | 추가: .is_none_or(|n| n > limit) | |
| 91 | 추가: { | |
| 92 | 추가: return Err(ErrorCode::Limit); | |
| 93 | 추가: } | |
| 94 | 추가: output | |
| 95 | 추가: .try_reserve(data.len()) | |
| 96 | 추가: .map_err(|_| ErrorCode::Limit)?; | |
| 97 | 추가: output.extend_from_slice(data); | |
| 98 | 추가: Ok(()) | |
| 99 | 추가: } | |
| 100 | 추가: fn inflate( | |
| 101 | 추가: input: &[u8], | |
| 102 | 추가: gzip: bool, | |
| 103 | 추가: limit: u64, | |
| 104 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 105 | 추가: ) -> Result<(Vec<u8>, usize)> { | |
| 106 | 추가: let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); | |
| 107 | 추가: let mut out = Vec::new(); | |
| 108 | 추가: let mut buffer = [0; 65536]; | |
| 109 | 추가: loop { | |
| 110 | 추가: check()?; | |
| 111 | 추가: let before_in = stream.total_in(); | |
| 112 | 추가: let before_out = stream.total_out(); | |
| 113 | 추가: let status = stream | |
| 114 | 추가: .decompress( | |
| 115 | 추가: &input[before_in as usize..], | |
| 116 | 추가: &mut buffer, | |
| 117 | 추가: InflateFlush::NoFlush, | |
| 118 | 추가: ) | |
| 119 | 추가: .map_err(|_| ErrorCode::Integrity)?; | |
| 120 | 추가: let written = (stream.total_out() - before_out) as usize; | |
| 121 | 추가: bounded_append(&mut out, &buffer[..written], limit)?; | |
| 122 | 추가: if status == Status::StreamEnd { | |
| 123 | 추가: return Ok((out, stream.total_in() as usize)); | |
| 124 | 추가: } | |
| 125 | 추가: if stream.total_in() == before_in && stream.total_out() == before_out { | |
| 126 | 추가: return Err(ErrorCode::Integrity); | |
| 127 | 추가: } | |
| 128 | 추가: } | |
| 129 | 추가: } | |
| 130 | 추가: fn gzip(input: &[u8], limits: Limits, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 131 | 추가: let mut at = 0; | |
| 132 | 추가: let mut result = Vec::new(); | |
| 133 | 추가: while at < input.len() { | |
| 134 | 추가: if !input[at..].starts_with(&[31, 139, 8]) { | |
| 135 | 추가: return Err(ErrorCode::Integrity); | |
| 136 | 추가: } | |
| 137 | 추가: let (out, used) = inflate( | |
| 138 | 추가: &input[at..], | |
| 139 | 추가: true, | |
| 140 | 추가: limits.output - result.len() as u64, | |
| 141 | 추가: check, | |
| 142 | 추가: )?; | |
| 143 | 추가: if used == 0 { | |
| 144 | 추가: return Err(ErrorCode::Integrity); | |
| 145 | 추가: } | |
| 146 | 추가: bounded_append(&mut result, &out, limits.output)?; | |
| 147 | 추가: at += used; | |
| 148 | 추가: } | |
| 149 | 추가: Ok(result) | |
| 150 | 추가: } | |
| 151 | 추가: fn tar_string(b: &[u8]) -> Result<String> { | |
| 152 | 추가: let n = b.iter().position(|v| *v == 0).unwrap_or(b.len()); | |
| 153 | 추가: if b[n..].iter().any(|v| *v != 0) { | |
| 154 | 추가: return Err(ErrorCode::Integrity); | |
| 155 | 추가: } | |
| 156 | 추가: std::str::from_utf8(&b[..n]) | |
| 157 | 추가: .map(str::to_owned) | |
| 158 | 추가: .map_err(|_| ErrorCode::UnsupportedFeature) | |
| 159 | 추가: } | |
| 160 | 추가: fn octal(b: &[u8]) -> Result<u64> { | |
| 161 | 추가: if b.first().is_some_and(|x| x & 128 != 0) { | |
| 162 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 163 | 추가: } | |
| 164 | 추가: let text = std::str::from_utf8(b) | |
| 165 | 추가: .map_err(|_| ErrorCode::Integrity)? | |
| 166 | 추가: .trim_matches(['\0', ' ']); | |
| 167 | 추가: if text.is_empty() { | |
| 168 | 추가: return Ok(0); | |
| 169 | 추가: } | |
| 170 | 추가: u64::from_str_radix(text, 8).map_err(|_| ErrorCode::Integrity) | |
| 171 | 추가: } | |
| 172 | 추가: fn tar( | |
| 173 | 추가: input: &[u8], | |
| 174 | 추가: limits: Limits, | |
| 175 | 추가: decode: bool, | |
| 176 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 177 | 추가: ) -> Result<Vec<Member>> { | |
| 178 | 추가: let mut at = 0; | |
| 179 | 추가: let mut members = Vec::new(); | |
| 180 | 추가: let mut total = 0u64; | |
| 181 | 추가: loop { | |
| 182 | 추가: check()?; | |
| 183 | 추가: let header = part(input, at, 512)?; | |
| 184 | 추가: if header.iter().all(|b| *b == 0) { | |
| 185 | 추가: if part(input, at + 512, 512)?.iter().any(|b| *b != 0) | |
| 186 | 추가: || input[at..].iter().any(|b| *b != 0) | |
| 187 | 추가: || input.len() % 512 != 0 | |
| 188 | 추가: { | |
| 189 | 추가: return Err(ErrorCode::Integrity); | |
| 190 | 추가: } | |
| 191 | 추가: break; | |
| 192 | 추가: } | |
| 193 | 추가: if members.len() >= limits.entries as usize { | |
| 194 | 추가: return Err(ErrorCode::Limit); | |
| 195 | 추가: } | |
| 196 | 추가: let expected = octal(&header[148..156])?; | |
| 197 | 추가: let checksum = header | |
| 198 | 추가: .iter() | |
| 199 | 추가: .enumerate() | |
| 200 | 추가: .map(|(i, b)| { | |
| 201 | 추가: if (148..156).contains(&i) { | |
| 202 | 추가: 32u64 | |
| 203 | 추가: } else { | |
| 204 | 추가: *b as u64 | |
| 205 | 추가: } | |
| 206 | 추가: }) | |
| 207 | 추가: .sum::<u64>(); | |
| 208 | 추가: if checksum != expected { | |
| 209 | 추가: return Err(ErrorCode::Integrity); | |
| 210 | 추가: } | |
| 211 | 추가: let mut name = tar_string(&header[..100])?; | |
| 212 | 추가: if &header[257..263] == b"ustar\0" || &header[257..263] == b"ustar " { | |
| 213 | 추가: let prefix = tar_string(&header[345..500])?; | |
| 214 | 추가: if !prefix.is_empty() { | |
| 215 | 추가: name = format!("{prefix}/{name}"); | |
| 216 | 추가: } | |
| 217 | 추가: } else if header[257..263].iter().any(|b| *b != 0) { | |
| 218 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 219 | 추가: } | |
| 220 | 추가: let kind = match header[156] { | |
| 221 | 추가: 0 | b'0' => EntryKind::File, | |
| 222 | 추가: b'5' => EntryKind::Directory, | |
| 223 | 추가: b'1' | b'2' => EntryKind::Link, | |
| 224 | 추가: b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature), | |
| 225 | 추가: _ => EntryKind::Other, | |
| 226 | 추가: }; | |
| 227 | 추가: let size = octal(&header[124..136])?; | |
| 228 | 추가: if kind != EntryKind::File && size != 0 { | |
| 229 | 추가: return Err(ErrorCode::Integrity); | |
| 230 | 추가: } | |
| 231 | 추가: total = total | |
| 232 | 추가: .checked_add(size) | |
| 233 | 추가: .filter(|n| *n <= limits.output) | |
| 234 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 235 | 추가: let size = usize::try_from(size).map_err(|_| ErrorCode::Limit)?; | |
| 236 | 추가: let bytes = part(input, at + 512, size)?; | |
| 237 | 추가: let name = valid_name(&name, kind == EntryKind::Directory)?; | |
| 238 | 추가: let data = if decode { bytes.to_vec() } else { Vec::new() }; | |
| 239 | 추가: members.push(Member { | |
| 240 | 추가: entry: Entry { | |
| 241 | 추가: entry_id: members.len() as u32, | |
| 242 | 추가: name, | |
| 243 | 추가: kind, | |
| 244 | 추가: size: size as u64, | |
| 245 | 추가: compressed_size: size as u64, | |
| 246 | 추가: encrypted: false, | |
| 247 | 추가: }, | |
| 248 | 추가: data, | |
| 249 | 추가: }); | |
| 250 | 추가: at = at | |
| 251 | 추가: .checked_add(512) | |
| 252 | 추가: .and_then(|n| n.checked_add(size.div_ceil(512) * 512)) | |
| 253 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 254 | 추가: } | |
| 255 | 추가: validate_members(&members)?; | |
| 256 | 추가: Ok(members) | |
| 257 | 추가: } | |
| 258 | 추가: fn zip( | |
| 259 | 추가: input: &[u8], | |
| 260 | 추가: limits: Limits, | |
| 261 | 추가: decode: bool, | |
| 262 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 263 | 추가: ) -> Result<Vec<Member>> { | |
| 264 | 추가: if input.len() < 22 { | |
| 265 | 추가: return Err(ErrorCode::Integrity); | |
| 266 | 추가: } | |
| 267 | 추가: let end = (input.len().saturating_sub(65557)..=input.len() - 22) | |
| 268 | 추가: .rev() | |
| 269 | 추가: .find(|&i| { | |
| 270 | 추가: input.get(i..i + 4) == Some(b"PK\x05\x06") | |
| 271 | 추가: && u16at(input, i + 20) | |
| 272 | 추가: .ok() | |
| 273 | 추가: .is_some_and(|n| i + 22 + n as usize == input.len()) | |
| 274 | 추가: }) | |
| 275 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 276 | 추가: let count = u16at(input, end + 10)? as usize; | |
| 277 | 추가: if u16at(input, end + 4)? != 0 | |
| 278 | 추가: || u16at(input, end + 6)? != 0 | |
| 279 | 추가: || count != u16at(input, end + 8)? as usize | |
| 280 | 추가: { | |
| 281 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 282 | 추가: } | |
| 283 | 추가: if count == 65535 || u32at(input, end + 12)? == u32::MAX || u32at(input, end + 16)? == u32::MAX | |
| 284 | 추가: { | |
| 285 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 286 | 추가: } | |
| 287 | 추가: if count > limits.entries as usize { | |
| 288 | 추가: return Err(ErrorCode::Limit); | |
| 289 | 추가: } | |
| 290 | 추가: let central = u32at(input, end + 16)? as usize; | |
| 291 | 추가: if central.checked_add(u32at(input, end + 12)? as usize) != Some(end) { | |
| 292 | 추가: return Err(ErrorCode::Integrity); | |
| 293 | 추가: } | |
| 294 | 추가: let mut at = central; | |
| 295 | 추가: let mut members = Vec::new(); | |
| 296 | 추가: let mut spans = Vec::new(); | |
| 297 | 추가: let mut total = 0u64; | |
| 298 | 추가: for id in 0..count { | |
| 299 | 추가: check()?; | |
| 300 | 추가: let h = part(input, at, 46)?; | |
| 301 | 추가: if &h[..4] != b"PK\x01\x02" { | |
| 302 | 추가: return Err(ErrorCode::Integrity); | |
| 303 | 추가: } | |
| 304 | 추가: let flags = u16at(h, 8)?; | |
| 305 | 추가: let method = u16at(h, 10)?; | |
| 306 | 추가: if flags & !0x080f != 0 || !matches!(method, 0 | 8) || u16at(h, 34)? != 0 { | |
| 307 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 308 | 추가: } | |
| 309 | 추가: let crc = u32at(h, 16)?; | |
| 310 | 추가: let compressed = u32at(h, 20)? as usize; | |
| 311 | 추가: let size = u32at(h, 24)? as usize; | |
| 312 | 추가: if compressed == u32::MAX as usize || size == u32::MAX as usize { | |
| 313 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 314 | 추가: } | |
| 315 | 추가: total = total | |
| 316 | 추가: .checked_add(size as u64) | |
| 317 | 추가: .filter(|n| *n <= limits.output) | |
| 318 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 319 | 추가: let name_len = u16at(h, 28)? as usize; | |
| 320 | 추가: let extra_len = u16at(h, 30)? as usize; | |
| 321 | 추가: let comment_len = u16at(h, 32)? as usize; | |
| 322 | 추가: let raw = part(input, at + 46, name_len)?; | |
| 323 | 추가: if flags & 0x0800 == 0 && !raw.is_ascii() { | |
| 324 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 325 | 추가: } | |
| 326 | 추가: let name = std::str::from_utf8(raw).map_err(|_| ErrorCode::Integrity)?; | |
| 327 | 추가: let mode = u32at(h, 38)? >> 16; | |
| 328 | 추가: let kind = match mode & 0xf000 { | |
| 329 | 추가: 0xa000 => EntryKind::Link, | |
| 330 | 추가: 0x4000 => EntryKind::Directory, | |
| 331 | 추가: 0 | 0x8000 => { | |
| 332 | 추가: if name.ends_with('/') { | |
| 333 | 추가: EntryKind::Directory | |
| 334 | 추가: } else { | |
| 335 | 추가: EntryKind::File | |
| 336 | 추가: } | |
| 337 | 추가: } | |
| 338 | 추가: _ => EntryKind::Other, | |
| 339 | 추가: }; | |
| 340 | 추가: let name = valid_name(name, kind == EntryKind::Directory)?; | |
| 341 | 추가: let local = u32at(h, 42)? as usize; | |
| 342 | 추가: let lh = part(input, local, 30)?; | |
| 343 | 추가: if &lh[..4] != b"PK\x03\x04" || u16at(lh, 6)? != flags || u16at(lh, 8)? != method { | |
| 344 | 추가: return Err(ErrorCode::Integrity); | |
| 345 | 추가: } | |
| 346 | 추가: let ln = u16at(lh, 26)? as usize; | |
| 347 | 추가: let le = u16at(lh, 28)? as usize; | |
| 348 | 추가: if part(input, local + 30, ln)? != raw { | |
| 349 | 추가: return Err(ErrorCode::Integrity); | |
| 350 | 추가: } | |
| 351 | 추가: if flags & 8 == 0 | |
| 352 | 추가: && (u32at(lh, 14)? != crc | |
| 353 | 추가: || u32at(lh, 18)? as usize != compressed | |
| 354 | 추가: || u32at(lh, 22)? as usize != size) | |
| 355 | 추가: { | |
| 356 | 추가: return Err(ErrorCode::Integrity); | |
| 357 | 추가: } | |
| 358 | 추가: let start = local | |
| 359 | 추가: .checked_add(30 + ln + le) | |
| 360 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 361 | 추가: let packed = part(input, start, compressed)?; | |
| 362 | 추가: let mut stop = start + compressed; | |
| 363 | 추가: if flags & 8 != 0 { | |
| 364 | 추가: if input.get(stop..stop + 4) == Some(b"PK\x07\x08") { | |
| 365 | 추가: stop += 4; | |
| 366 | 추가: } | |
| 367 | 추가: if u32at(input, stop)? != crc | |
| 368 | 추가: || u32at(input, stop + 4)? as usize != compressed | |
| 369 | 추가: || u32at(input, stop + 8)? as usize != size | |
| 370 | 추가: { | |
| 371 | 추가: return Err(ErrorCode::Integrity); | |
| 372 | 추가: } | |
| 373 | 추가: stop += 12; | |
| 374 | 추가: } | |
| 375 | 추가: if stop > central { | |
| 376 | 추가: return Err(ErrorCode::Integrity); | |
| 377 | 추가: } | |
| 378 | 추가: spans.push((local, stop)); | |
| 379 | 추가: let encrypted = flags & 1 != 0; | |
| 380 | 추가: let data = if decode && !encrypted { | |
| 381 | 추가: let bytes = if method == 0 { | |
| 382 | 추가: if compressed != size { | |
| 383 | 추가: return Err(ErrorCode::Integrity); | |
| 384 | 추가: } | |
| 385 | 추가: packed.to_vec() | |
| 386 | 추가: } else { | |
| 387 | 추가: let (out, used) = inflate(packed, false, size as u64, check)?; | |
| 388 | 추가: if used != compressed { | |
| 389 | 추가: return Err(ErrorCode::Integrity); | |
| 390 | 추가: } | |
| 391 | 추가: out | |
| 392 | 추가: }; | |
| 393 | 추가: if bytes.len() != size || crc32(0, &bytes) != crc { | |
| 394 | 추가: return Err(ErrorCode::Integrity); | |
| 395 | 추가: } | |
| 396 | 추가: bytes | |
| 397 | 추가: } else { | |
| 398 | 추가: Vec::new() | |
| 399 | 추가: }; | |
| 400 | 추가: if kind == EntryKind::Directory && size != 0 { | |
| 401 | 추가: return Err(ErrorCode::Integrity); | |
| 402 | 추가: } | |
| 403 | 추가: members.push(Member { | |
| 404 | 추가: entry: Entry { | |
| 405 | 추가: entry_id: id as u32, | |
| 406 | 추가: name, | |
| 407 | 추가: kind, | |
| 408 | 추가: size: size as u64, | |
| 409 | 추가: compressed_size: compressed as u64, | |
| 410 | 추가: encrypted, | |
| 411 | 추가: }, | |
| 412 | 추가: data, | |
| 413 | 추가: }); | |
| 414 | 추가: at = at | |
| 415 | 추가: .checked_add(46 + name_len + extra_len + comment_len) | |
| 416 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 417 | 추가: } | |
| 418 | 추가: if at != end { | |
| 419 | 추가: return Err(ErrorCode::Integrity); | |
| 420 | 추가: } | |
| 421 | 추가: spans.sort_unstable(); | |
| 422 | 추가: let mut next = 0; | |
| 423 | 추가: for (start, stop) in spans { | |
| 424 | 추가: if start != next { | |
| 425 | 추가: return Err(ErrorCode::Integrity); | |
| 426 | 추가: } | |
| 427 | 추가: next = stop; | |
| 428 | 추가: } | |
| 429 | 추가: if next != central { | |
| 430 | 추가: return Err(ErrorCode::Integrity); | |
| 431 | 추가: } | |
| 432 | 추가: validate_members(&members)?; | |
| 433 | 추가: Ok(members) | |
| 434 | 추가: } | |
| 435 | 추가: pub fn parse( | |
| 436 | 추가: input: &[u8], | |
| 437 | 추가: limits: Limits, | |
| 438 | 추가: decode: bool, | |
| 439 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 440 | 추가: ) -> Result<Catalog> { | |
| 441 | 추가: if !limits.valid() || input.len() as u64 > limits.input { | |
| 442 | 추가: return Err(ErrorCode::Limit); | |
| 443 | 추가: } | |
| 444 | 추가: if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") { | |
| 445 | 추가: return Ok(Catalog { | |
| 446 | 추가: format: Format::Zip, | |
| 447 | 추가: members: zip(input, limits, decode, check)?, | |
| 448 | 추가: }); | |
| 449 | 추가: } | |
| 450 | 추가: if input.starts_with(&[31, 139]) { | |
| 451 | 추가: let bytes = gzip(input, limits, check)?; | |
| 452 | 추가: if bytes.len() >= 512 | |
| 453 | 추가: && (bytes[257..262] == *b"ustar" || bytes[..512].iter().all(|b| *b == 0)) | |
| 454 | 추가: { | |
| 455 | 추가: return Ok(Catalog { | |
| 456 | 추가: format: Format::TarGzip, | |
| 457 | 추가: members: tar(&bytes, limits, decode, check)?, | |
| 458 | 추가: }); | |
| 459 | 추가: } | |
| 460 | 추가: let len = bytes.len() as u64; | |
| 461 | 추가: return Ok(Catalog { | |
| 462 | 추가: format: Format::Gzip, | |
| 463 | 추가: members: vec![Member { | |
| 464 | 추가: entry: Entry { | |
| 465 | 추가: entry_id: 0, | |
| 466 | 추가: name: "GZip stream".to_owned(), | |
| 467 | 추가: kind: EntryKind::File, | |
| 468 | 추가: size: len, | |
| 469 | 추가: compressed_size: input.len() as u64, | |
| 470 | 추가: encrypted: false, | |
| 471 | 추가: }, | |
| 472 | 추가: data: if decode { bytes } else { Vec::new() }, | |
| 473 | 추가: }], | |
| 474 | 추가: }); | |
| 475 | 추가: } | |
| 476 | 추가: if input.len() >= 512 { | |
| 477 | 추가: return Ok(Catalog { | |
| 478 | 추가: format: Format::Tar, | |
| 479 | 추가: members: tar(input, limits, decode, check)?, | |
| 480 | 추가: }); | |
| 481 | 추가: } | |
| 482 | 추가: Err(ErrorCode::UnsupportedFormat) | |
| 483 | 추가: } | |
| 484 | 추가: fn deflate(input: &[u8], limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<Vec<u8>> { | |
| 485 | 추가: let mut stream = Deflate::new(6, false, 15); | |
| 486 | 추가: let mut output = Vec::new(); | |
| 487 | 추가: let mut buffer = [0; 65536]; | |
| 488 | 추가: loop { | |
| 489 | 추가: check()?; | |
| 490 | 추가: let a = stream.total_in(); | |
| 491 | 추가: let b = stream.total_out(); | |
| 492 | 추가: let status = stream | |
| 493 | 추가: .compress(&input[a as usize..], &mut buffer, DeflateFlush::Finish) | |
| 494 | 추가: .map_err(|_| ErrorCode::Internal)?; | |
| 495 | 추가: bounded_append( | |
| 496 | 추가: &mut output, | |
| 497 | 추가: &buffer[..(stream.total_out() - b) as usize], | |
| 498 | 추가: limit, | |
| 499 | 추가: )?; | |
| 500 | 추가: if status == Status::StreamEnd { | |
| 501 | 추가: return Ok(output); | |
| 502 | 추가: } | |
| 503 | 추가: if a == stream.total_in() && b == stream.total_out() { | |
| 504 | 추가: return Err(ErrorCode::Internal); | |
| 505 | 추가: } | |
| 506 | 추가: } | |
| 507 | 추가: } | |
| 508 | 추가: fn put16(v: &mut Vec<u8>, n: u16) { | |
| 509 | 추가: v.extend(n.to_le_bytes()); | |
| 510 | 추가: } | |
| 511 | 추가: fn put32(v: &mut Vec<u8>, n: u32) { | |
| 512 | 추가: v.extend(n.to_le_bytes()); | |
| 513 | 추가: } | |
| 514 | 추가: pub fn create_zip( | |
| 515 | 추가: members: &[Member], | |
| 516 | 추가: method: Method, | |
| 517 | 추가: limits: Limits, | |
| 518 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 519 | 추가: ) -> Result<Vec<u8>> { | |
| 520 | 추가: if members.len() > limits.entries as usize || members.len() >= 65535 { | |
| 521 | 추가: return Err(ErrorCode::Limit); | |
| 522 | 추가: } | |
| 523 | 추가: validate_members(members)?; | |
| 524 | 추가: let mut out = Vec::new(); | |
| 525 | 추가: let mut cd = Vec::new(); | |
| 526 | 추가: let mut total = 0u64; | |
| 527 | 추가: for m in members { | |
| 528 | 추가: check()?; | |
| 529 | 추가: total = total | |
| 530 | 추가: .checked_add(m.data.len() as u64) | |
| 531 | 추가: .filter(|n| *n <= limits.output) | |
| 532 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 533 | 추가: if m.entry.kind != EntryKind::File { | |
| 534 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 535 | 추가: } | |
| 536 | 추가: let name = m.entry.name.as_bytes(); | |
| 537 | 추가: let crc = crc32(0, &m.data); | |
| 538 | 추가: let offset = out.len() as u32; | |
| 539 | 추가: let packed = match method { | |
| 540 | 추가: Method::Store => m.data.clone(), | |
| 541 | 추가: Method::Deflate => deflate(&m.data, limits.output, check)?, | |
| 542 | 추가: }; | |
| 543 | 추가: let method = match method { | |
| 544 | 추가: Method::Store => 0, | |
| 545 | 추가: Method::Deflate => 8, | |
| 546 | 추가: }; | |
| 547 | 추가: out.extend(b"PK\x03\x04"); | |
| 548 | 추가: put16(&mut out, 20); | |
| 549 | 추가: put16(&mut out, 0x0800); | |
| 550 | 추가: put16(&mut out, method); | |
| 551 | 추가: put16(&mut out, 0); | |
| 552 | 추가: put16(&mut out, 33); | |
| 553 | 추가: put32(&mut out, crc); | |
| 554 | 추가: put32(&mut out, packed.len() as u32); | |
| 555 | 추가: put32(&mut out, m.data.len() as u32); | |
| 556 | 추가: put16(&mut out, name.len() as u16); | |
| 557 | 추가: put16(&mut out, 0); | |
| 558 | 추가: out.extend(name); | |
| 559 | 추가: bounded_append(&mut out, &packed, limits.output)?; | |
| 560 | 추가: cd.extend(b"PK\x01\x02"); | |
| 561 | 추가: put16(&mut cd, 0x0314); | |
| 562 | 추가: put16(&mut cd, 20); | |
| 563 | 추가: put16(&mut cd, 0x0800); | |
| 564 | 추가: put16(&mut cd, method); | |
| 565 | 추가: put16(&mut cd, 0); | |
| 566 | 추가: put16(&mut cd, 33); | |
| 567 | 추가: put32(&mut cd, crc); | |
| 568 | 추가: put32(&mut cd, packed.len() as u32); | |
| 569 | 추가: put32(&mut cd, m.data.len() as u32); | |
| 570 | 추가: put16(&mut cd, name.len() as u16); | |
| 571 | 추가: put16(&mut cd, 0); | |
| 572 | 추가: put16(&mut cd, 0); | |
| 573 | 추가: put16(&mut cd, 0); | |
| 574 | 추가: put16(&mut cd, 0); | |
| 575 | 추가: put32(&mut cd, 0o100600 << 16); | |
| 576 | 추가: put32(&mut cd, offset); | |
| 577 | 추가: cd.extend(name); | |
| 578 | 추가: } | |
| 579 | 추가: let offset = out.len(); | |
| 580 | 추가: bounded_append(&mut out, &cd, limits.output)?; | |
| 581 | 추가: let mut end = Vec::new(); | |
| 582 | 추가: end.extend(b"PK\x05\x06"); | |
| 583 | 추가: put16(&mut end, 0); | |
| 584 | 추가: put16(&mut end, 0); | |
| 585 | 추가: put16(&mut end, members.len() as u16); | |
| 586 | 추가: put16(&mut end, members.len() as u16); | |
| 587 | 추가: put32(&mut end, cd.len() as u32); | |
| 588 | 추가: put32(&mut end, offset as u32); | |
| 589 | 추가: put16(&mut end, 0); | |
| 590 | 추가: bounded_append(&mut out, &end, limits.output)?; | |
| 591 | 추가: Ok(out) | |
| 592 | 추가: } |
| @@ -0,0 +1,508 @@ | ||
| 1 | 추가: use crate::archive::valid_name; | |
| 2 | 추가: use crate::protocol::*; | |
| 3 | 추가: use sha2::{Digest, Sha256}; | |
| 4 | 추가: use std::fs::{File, OpenOptions}; | |
| 5 | 추가: use std::io::{Read, Write}; | |
| 6 | 추가: #[cfg(windows)] | |
| 7 | 추가: use std::path::PathBuf; | |
| 8 | 추가: use std::path::{Component, Path}; | |
| 9 | 추가: use std::sync::atomic::{AtomicU64, Ordering}; | |
| 10 | 추가: | |
| 11 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 12 | 추가: static TEMP: AtomicU64 = AtomicU64::new(0); | |
| 13 | 추가: pub struct Snapshot { | |
| 14 | 추가: pub bytes: Vec<u8>, | |
| 15 | 추가: pub object: SourceObject, | |
| 16 | 추가: pub hash: [u8; 32], | |
| 17 | 추가: } | |
| 18 | 추가: #[cfg(unix)] | |
| 19 | 추가: pub fn object(file: &File) -> Result<SourceObject> { | |
| 20 | 추가: use std::os::unix::fs::MetadataExt; | |
| 21 | 추가: let m = file.metadata().map_err(|_| ErrorCode::Io)?; | |
| 22 | 추가: Ok(SourceObject::Unix { | |
| 23 | 추가: device: m.dev(), | |
| 24 | 추가: inode: m.ino(), | |
| 25 | 추가: }) | |
| 26 | 추가: } | |
| 27 | 추가: #[cfg(windows)] | |
| 28 | 추가: pub fn object(file: &File) -> Result<SourceObject> { | |
| 29 | 추가: use std::os::windows::io::AsRawHandle; | |
| 30 | 추가: #[repr(C)] | |
| 31 | 추가: struct Info { | |
| 32 | 추가: volume: u64, | |
| 33 | 추가: id: [u8; 16], | |
| 34 | 추가: } | |
| 35 | 추가: unsafe extern "system" { | |
| 36 | 추가: fn GetFileInformationByHandleEx( | |
| 37 | 추가: h: *mut std::ffi::c_void, | |
| 38 | 추가: class: u32, | |
| 39 | 추가: info: *mut std::ffi::c_void, | |
| 40 | 추가: size: u32, | |
| 41 | 추가: ) -> i32; | |
| 42 | 추가: } | |
| 43 | 추가: let mut info = Info { | |
| 44 | 추가: volume: 0, | |
| 45 | 추가: id: [0; 16], | |
| 46 | 추가: }; | |
| 47 | 추가: // 열린 핸들에 대해 고정 크기의 파일 식별 정보를 조회함. | |
| 48 | 추가: if unsafe { | |
| 49 | 추가: GetFileInformationByHandleEx( | |
| 50 | 추가: file.as_raw_handle(), | |
| 51 | 추가: 18, | |
| 52 | 추가: (&mut info as *mut Info).cast(), | |
| 53 | 추가: size_of::<Info>() as u32, | |
| 54 | 추가: ) | |
| 55 | 추가: } == 0 | |
| 56 | 추가: { | |
| 57 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 58 | 추가: } | |
| 59 | 추가: Ok(SourceObject::Windows { | |
| 60 | 추가: volume_serial: info.volume, | |
| 61 | 추가: file_id: info.id, | |
| 62 | 추가: }) | |
| 63 | 추가: } | |
| 64 | 추가: pub fn snapshot( | |
| 65 | 추가: path: &Path, | |
| 66 | 추가: limit: u64, | |
| 67 | 추가: check: &mut impl FnMut() -> Result<()>, | |
| 68 | 추가: ) -> Result<Snapshot> { | |
| 69 | 추가: let mut options = OpenOptions::new(); | |
| 70 | 추가: options.read(true); | |
| 71 | 추가: #[cfg(unix)] | |
| 72 | 추가: { | |
| 73 | 추가: use std::os::unix::fs::OpenOptionsExt; | |
| 74 | 추가: options.custom_flags(0x20000 | 0x800); | |
| 75 | 추가: } | |
| 76 | 추가: #[cfg(windows)] | |
| 77 | 추가: { | |
| 78 | 추가: use std::os::windows::fs::OpenOptionsExt; | |
| 79 | 추가: options.share_mode(1); | |
| 80 | 추가: } | |
| 81 | 추가: let mut file = options.open(path).map_err(|_| ErrorCode::Io)?; | |
| 82 | 추가: let before = file.metadata().map_err(|_| ErrorCode::Io)?; | |
| 83 | 추가: if !before.is_file() { | |
| 84 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 85 | 추가: } | |
| 86 | 추가: if before.len() > limit { | |
| 87 | 추가: return Err(ErrorCode::Limit); | |
| 88 | 추가: } | |
| 89 | 추가: let identity = object(&file)?; | |
| 90 | 추가: let mut bytes = Vec::new(); | |
| 91 | 추가: let mut hash = Sha256::new(); | |
| 92 | 추가: let mut buffer = [0; 65536]; | |
| 93 | 추가: loop { | |
| 94 | 추가: check()?; | |
| 95 | 추가: let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?; | |
| 96 | 추가: if n == 0 { | |
| 97 | 추가: break; | |
| 98 | 추가: } | |
| 99 | 추가: if bytes.len() as u64 + n as u64 > limit { | |
| 100 | 추가: return Err(ErrorCode::Limit); | |
| 101 | 추가: } | |
| 102 | 추가: bytes.try_reserve(n).map_err(|_| ErrorCode::Limit)?; | |
| 103 | 추가: bytes.extend_from_slice(&buffer[..n]); | |
| 104 | 추가: hash.update(&buffer[..n]); | |
| 105 | 추가: } | |
| 106 | 추가: let after = file.metadata().map_err(|_| ErrorCode::Io)?; | |
| 107 | 추가: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?; | |
| 108 | 추가: if !named | |
| 109 | 추가: .metadata() | |
| 110 | 추가: .map_err(|_| ErrorCode::SourceChanged)? | |
| 111 | 추가: .is_file() | |
| 112 | 추가: || object(&named)? != identity | |
| 113 | 추가: || object(&file)? != identity | |
| 114 | 추가: || before.len() != after.len() | |
| 115 | 추가: || after.len() != bytes.len() as u64 | |
| 116 | 추가: || before.modified().ok() != after.modified().ok() | |
| 117 | 추가: { | |
| 118 | 추가: return Err(ErrorCode::SourceChanged); | |
| 119 | 추가: } | |
| 120 | 추가: close(file).map_err(|_| ErrorCode::Io)?; | |
| 121 | 추가: Ok(Snapshot { | |
| 122 | 추가: bytes, | |
| 123 | 추가: object: identity, | |
| 124 | 추가: hash: hash.finalize().into(), | |
| 125 | 추가: }) | |
| 126 | 추가: } | |
| 127 | 추가: #[cfg(unix)] | |
| 128 | 추가: fn close(file: File) -> std::io::Result<()> { | |
| 129 | 추가: use std::os::unix::io::IntoRawFd; | |
| 130 | 추가: unsafe extern "C" { | |
| 131 | 추가: fn close(fd: i32) -> i32; | |
| 132 | 추가: } | |
| 133 | 추가: // 소유한 파일 디스크립터를 한 번만 닫음. | |
| 134 | 추가: if unsafe { close(file.into_raw_fd()) } == 0 { | |
| 135 | 추가: Ok(()) | |
| 136 | 추가: } else { | |
| 137 | 추가: Err(std::io::Error::last_os_error()) | |
| 138 | 추가: } | |
| 139 | 추가: } | |
| 140 | 추가: #[cfg(windows)] | |
| 141 | 추가: fn close(file: File) -> std::io::Result<()> { | |
| 142 | 추가: use std::os::windows::io::IntoRawHandle; | |
| 143 | 추가: unsafe extern "system" { | |
| 144 | 추가: fn CloseHandle(h: *mut std::ffi::c_void) -> i32; | |
| 145 | 추가: } | |
| 146 | 추가: // 소유한 핸들을 한 번만 닫음. | |
| 147 | 추가: if unsafe { CloseHandle(file.into_raw_handle()) } != 0 { | |
| 148 | 추가: Ok(()) | |
| 149 | 추가: } else { | |
| 150 | 추가: Err(std::io::Error::last_os_error()) | |
| 151 | 추가: } | |
| 152 | 추가: } | |
| 153 | 추가: #[cfg(target_os = "linux")] | |
| 154 | 추가: mod platform { | |
| 155 | 추가: use super::*; | |
| 156 | 추가: use std::ffi::CString; | |
| 157 | 추가: use std::os::unix::{ | |
| 158 | 추가: ffi::OsStrExt, | |
| 159 | 추가: fs::MetadataExt, | |
| 160 | 추가: io::{AsRawFd, FromRawFd}, | |
| 161 | 추가: }; | |
| 162 | 추가: unsafe extern "C" { | |
| 163 | 추가: fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32; | |
| 164 | 추가: fn mkdirat(fd: i32, path: *const i8, mode: u32) -> i32; | |
| 165 | 추가: fn linkat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8, flags: i32) -> i32; | |
| 166 | 추가: fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32; | |
| 167 | 추가: fn geteuid() -> u32; | |
| 168 | 추가: } | |
| 169 | 추가: pub struct Dir { | |
| 170 | 추가: file: File, | |
| 171 | 추가: } | |
| 172 | 추가: fn name(s: &std::ffi::OsStr) -> Result<CString> { | |
| 173 | 추가: CString::new(s.as_bytes()).map_err(|_| ErrorCode::UnsafePath) | |
| 174 | 추가: } | |
| 175 | 추가: fn open(parent: &File, s: &std::ffi::OsStr, flags: i32) -> std::io::Result<File> { | |
| 176 | 추가: let n = name(s).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; | |
| 177 | 추가: // 부모 핸들 기준으로 심볼릭 링크를 따르지 않고 열음. | |
| 178 | 추가: let fd = unsafe { | |
| 179 | 추가: openat( | |
| 180 | 추가: parent.as_raw_fd(), | |
| 181 | 추가: n.as_ptr(), | |
| 182 | 추가: flags | 0x80000 | 0x20000, | |
| 183 | 추가: 0o600u32, | |
| 184 | 추가: ) | |
| 185 | 추가: }; | |
| 186 | 추가: if fd < 0 { | |
| 187 | 추가: return Err(std::io::Error::last_os_error()); | |
| 188 | 추가: } | |
| 189 | 추가: Ok(unsafe { File::from_raw_fd(fd) }) | |
| 190 | 추가: } | |
| 191 | 추가: impl Dir { | |
| 192 | 추가: pub fn root(path: &Path) -> Result<Self> { | |
| 193 | 추가: if !path.is_absolute() { | |
| 194 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 195 | 추가: } | |
| 196 | 추가: let mut d = Self { | |
| 197 | 추가: file: File::open("/").map_err(|_| ErrorCode::Io)?, | |
| 198 | 추가: }; | |
| 199 | 추가: for c in path.components() { | |
| 200 | 추가: match c { | |
| 201 | 추가: Component::RootDir => {} | |
| 202 | 추가: Component::Normal(n) => { | |
| 203 | 추가: d = Self { | |
| 204 | 추가: file: open(&d.file, n, 0x10000).map_err(|_| ErrorCode::UnsafePath)?, | |
| 205 | 추가: } | |
| 206 | 추가: } | |
| 207 | 추가: _ => return Err(ErrorCode::UnsafePath), | |
| 208 | 추가: } | |
| 209 | 추가: } | |
| 210 | 추가: d.trusted()?; | |
| 211 | 추가: Ok(d) | |
| 212 | 추가: } | |
| 213 | 추가: fn trusted(&self) -> Result<()> { | |
| 214 | 추가: let m = self.file.metadata().map_err(|_| ErrorCode::Io)?; | |
| 215 | 추가: // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함. | |
| 216 | 추가: if !m.is_dir() || m.uid() != unsafe { geteuid() } || m.mode() & 0o022 != 0 { | |
| 217 | 추가: return Err(ErrorCode::UnsafePath); | |
| 218 | 추가: } | |
| 219 | 추가: Ok(()) | |
| 220 | 추가: } | |
| 221 | 추가: pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> { | |
| 222 | 추가: match open(&self.file, std::ffi::OsStr::new(n), 0x10000) { | |
| 223 | 추가: Ok(file) => { | |
| 224 | 추가: let d = Self { file }; | |
| 225 | 추가: d.trusted()?; | |
| 226 | 추가: Ok(Some(d)) | |
| 227 | 추가: } | |
| 228 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => { | |
| 229 | 추가: if !create { | |
| 230 | 추가: return Ok(None); | |
| 231 | 추가: } | |
| 232 | 추가: let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?; | |
| 233 | 추가: // 고정 부모 안에 새 전용 디렉터리를 생성함. | |
| 234 | 추가: if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 { | |
| 235 | 추가: return Err(ErrorCode::Io); | |
| 236 | 추가: } | |
| 237 | 추가: let file = open( | |
| 238 | 추가: &self.file, | |
| 239 | 추가: std::ffi::OsStr::new(n.to_str().unwrap()), | |
| 240 | 추가: 0x10000, | |
| 241 | 추가: ) | |
| 242 | 추가: .map_err(|_| ErrorCode::UnsafePath)?; | |
| 243 | 추가: let d = Self { file }; | |
| 244 | 추가: d.trusted()?; | |
| 245 | 추가: Ok(Some(d)) | |
| 246 | 추가: } | |
| 247 | 추가: Err(_) => Err(ErrorCode::UnsafePath), | |
| 248 | 추가: } | |
| 249 | 추가: } | |
| 250 | 추가: pub fn duplicate(&self) -> Result<Self> { | |
| 251 | 추가: Ok(Self { | |
| 252 | 추가: file: self.file.try_clone().map_err(|_| ErrorCode::Io)?, | |
| 253 | 추가: }) | |
| 254 | 추가: } | |
| 255 | 추가: pub fn absent(&self, n: &str) -> Result<bool> { | |
| 256 | 추가: match open(&self.file, std::ffi::OsStr::new(n), 0x200000) { | |
| 257 | 추가: Ok(_) => Ok(false), | |
| 258 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), | |
| 259 | 추가: Err(_) => Err(ErrorCode::Io), | |
| 260 | 추가: } | |
| 261 | 추가: } | |
| 262 | 추가: pub fn create(&self, n: &str) -> std::io::Result<File> { | |
| 263 | 추가: open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80) | |
| 264 | 추가: } | |
| 265 | 추가: pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> { | |
| 266 | 추가: let a = CString::new(from).unwrap(); | |
| 267 | 추가: let b = CString::new(to).unwrap(); | |
| 268 | 추가: // 배타적 hard link 게시로 기존 이름을 보존함. | |
| 269 | 추가: if unsafe { | |
| 270 | 추가: linkat( | |
| 271 | 추가: self.file.as_raw_fd(), | |
| 272 | 추가: a.as_ptr(), | |
| 273 | 추가: self.file.as_raw_fd(), | |
| 274 | 추가: b.as_ptr(), | |
| 275 | 추가: 0, | |
| 276 | 추가: ) | |
| 277 | 추가: } == 0 | |
| 278 | 추가: { | |
| 279 | 추가: Ok(()) | |
| 280 | 추가: } else { | |
| 281 | 추가: Err(std::io::Error::last_os_error()) | |
| 282 | 추가: } | |
| 283 | 추가: } | |
| 284 | 추가: pub fn remove(&self, n: &str) -> bool { | |
| 285 | 추가: let n = CString::new(n).unwrap(); | |
| 286 | 추가: unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 } | |
| 287 | 추가: } | |
| 288 | 추가: pub fn sync(&self) -> Durability { | |
| 289 | 추가: if self.file.sync_all().is_ok() { | |
| 290 | 추가: Durability::Synced | |
| 291 | 추가: } else { | |
| 292 | 추가: Durability::Failed | |
| 293 | 추가: } | |
| 294 | 추가: } | |
| 295 | 추가: } | |
| 296 | 추가: } | |
| 297 | 추가: #[cfg(windows)] | |
| 298 | 추가: mod platform { | |
| 299 | 추가: use super::*; | |
| 300 | 추가: use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; | |
| 301 | 추가: pub struct Dir { | |
| 302 | 추가: path: PathBuf, | |
| 303 | 추가: locks: Vec<File>, | |
| 304 | 추가: } | |
| 305 | 추가: fn lock(path: &Path) -> Result<File> { | |
| 306 | 추가: let f = OpenOptions::new() | |
| 307 | 추가: .access_mode(0x80) | |
| 308 | 추가: .share_mode(3) | |
| 309 | 추가: .custom_flags(0x02000000 | 0x00200000) | |
| 310 | 추가: .open(path) | |
| 311 | 추가: .map_err(|_| ErrorCode::UnsafePath)?; | |
| 312 | 추가: let m = f.metadata().map_err(|_| ErrorCode::Io)?; | |
| 313 | 추가: if !m.is_dir() || m.file_attributes() & 0x400 != 0 { | |
| 314 | 추가: return Err(ErrorCode::UnsafePath); | |
| 315 | 추가: } | |
| 316 | 추가: Ok(f) | |
| 317 | 추가: } | |
| 318 | 추가: impl Dir { | |
| 319 | 추가: pub fn root(path: &Path) -> Result<Self> { | |
| 320 | 추가: let mut p = PathBuf::new(); | |
| 321 | 추가: let mut locks = Vec::new(); | |
| 322 | 추가: for c in path.components() { | |
| 323 | 추가: match c { | |
| 324 | 추가: Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()), | |
| 325 | 추가: Component::Normal(n) => { | |
| 326 | 추가: if locks.is_empty() { | |
| 327 | 추가: locks.push(lock(&p)?); | |
| 328 | 추가: } | |
| 329 | 추가: p.push(n); | |
| 330 | 추가: locks.push(lock(&p)?); | |
| 331 | 추가: } | |
| 332 | 추가: _ => return Err(ErrorCode::UnsafePath), | |
| 333 | 추가: } | |
| 334 | 추가: } | |
| 335 | 추가: if locks.is_empty() { | |
| 336 | 추가: locks.push(lock(&p)?); | |
| 337 | 추가: } | |
| 338 | 추가: Ok(Self { path: p, locks }) | |
| 339 | 추가: } | |
| 340 | 추가: pub fn duplicate(&self) -> Result<Self> { | |
| 341 | 추가: Ok(Self { | |
| 342 | 추가: path: self.path.clone(), | |
| 343 | 추가: locks: self | |
| 344 | 추가: .locks | |
| 345 | 추가: .iter() | |
| 346 | 추가: .map(|f| f.try_clone().map_err(|_| ErrorCode::Io)) | |
| 347 | 추가: .collect::<Result<_>>()?, | |
| 348 | 추가: }) | |
| 349 | 추가: } | |
| 350 | 추가: pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> { | |
| 351 | 추가: let p = self.path.join(n); | |
| 352 | 추가: match std::fs::symlink_metadata(&p) { | |
| 353 | 추가: Ok(_) => {} | |
| 354 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => { | |
| 355 | 추가: if !create { | |
| 356 | 추가: return Ok(None); | |
| 357 | 추가: } | |
| 358 | 추가: std::fs::create_dir(&p).map_err(|_| ErrorCode::Io)?; | |
| 359 | 추가: } | |
| 360 | 추가: Err(_) => return Err(ErrorCode::Io), | |
| 361 | 추가: } | |
| 362 | 추가: let mut d = self.duplicate()?; | |
| 363 | 추가: d.locks.push(lock(&p)?); | |
| 364 | 추가: d.path = p; | |
| 365 | 추가: Ok(Some(d)) | |
| 366 | 추가: } | |
| 367 | 추가: pub fn absent(&self, n: &str) -> Result<bool> { | |
| 368 | 추가: match std::fs::symlink_metadata(self.path.join(n)) { | |
| 369 | 추가: Ok(_) => Ok(false), | |
| 370 | 추가: Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), | |
| 371 | 추가: Err(_) => Err(ErrorCode::Io), | |
| 372 | 추가: } | |
| 373 | 추가: } | |
| 374 | 추가: pub fn create(&self, n: &str) -> std::io::Result<File> { | |
| 375 | 추가: OpenOptions::new() | |
| 376 | 추가: .write(true) | |
| 377 | 추가: .create_new(true) | |
| 378 | 추가: .share_mode(0) | |
| 379 | 추가: .custom_flags(0x00200000) | |
| 380 | 추가: .open(self.path.join(n)) | |
| 381 | 추가: } | |
| 382 | 추가: pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> { | |
| 383 | 추가: std::fs::hard_link(self.path.join(a), self.path.join(b)) | |
| 384 | 추가: } | |
| 385 | 추가: pub fn remove(&self, n: &str) -> bool { | |
| 386 | 추가: std::fs::remove_file(self.path.join(n)).is_ok() | |
| 387 | 추가: } | |
| 388 | 추가: pub fn sync(&self) -> Durability { | |
| 389 | 추가: Durability::Unconfirmed | |
| 390 | 추가: } | |
| 391 | 추가: } | |
| 392 | 추가: } | |
| 393 | 추가: #[cfg(not(any(target_os = "linux", windows)))] | |
| 394 | 추가: compile_error!("Archive worker supports Linux and Windows only"); | |
| 395 | 추가: pub use platform::Dir; | |
| 396 | 추가: fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> { | |
| 397 | 추가: let mut parts = name.split('/').collect::<Vec<_>>(); | |
| 398 | 추가: let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?; | |
| 399 | 추가: let mut d = root.duplicate()?; | |
| 400 | 추가: for p in parts { | |
| 401 | 추가: match d.child(p, create)? { | |
| 402 | 추가: Some(child) => d = child, | |
| 403 | 추가: None => return Ok(None), | |
| 404 | 추가: } | |
| 405 | 추가: } | |
| 406 | 추가: Ok(Some((d, leaf.to_owned()))) | |
| 407 | 추가: } | |
| 408 | 추가: pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { | |
| 409 | 추가: for (name, kind) in names { | |
| 410 | 추가: if let Some((d, leaf)) = parent(root, name, false)? { | |
| 411 | 추가: if *kind == EntryKind::Directory { | |
| 412 | 추가: let _ = d.child(&leaf, false)?; | |
| 413 | 추가: } else if !d.absent(&leaf)? { | |
| 414 | 추가: return Err(ErrorCode::Conflict); | |
| 415 | 추가: } | |
| 416 | 추가: } | |
| 417 | 추가: } | |
| 418 | 추가: Ok(()) | |
| 419 | 추가: } | |
| 420 | 추가: pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> { | |
| 421 | 추가: let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?; | |
| 422 | 추가: if d.child(&leaf, false)?.is_some() { | |
| 423 | 추가: return Ok((false, Durability::NotApplicable)); | |
| 424 | 추가: } | |
| 425 | 추가: d.child(&leaf, true)?.ok_or(ErrorCode::Io)?; | |
| 426 | 추가: Ok((true, d.sync())) | |
| 427 | 추가: } | |
| 428 | 추가: pub struct Published { | |
| 429 | 추가: pub created: bool, | |
| 430 | 추가: pub uncertain: bool, | |
| 431 | 추가: pub error: Option<ErrorCode>, | |
| 432 | 추가: pub durability: Durability, | |
| 433 | 추가: pub cleanup: Cleanup, | |
| 434 | 추가: pub retained: u64, | |
| 435 | 추가: pub retained_name: Option<String>, | |
| 436 | 추가: } | |
| 437 | 추가: pub fn publish( | |
| 438 | 추가: root: &Dir, | |
| 439 | 추가: name: &str, | |
| 440 | 추가: data: &[u8], | |
| 441 | 추가: check: &mut impl FnMut(bool) -> Result<()>, | |
| 442 | 추가: ) -> Published { | |
| 443 | 추가: let mut result = Published { | |
| 444 | 추가: created: false, | |
| 445 | 추가: uncertain: false, | |
| 446 | 추가: error: None, | |
| 447 | 추가: durability: Durability::NotApplicable, | |
| 448 | 추가: cleanup: Cleanup::Complete, | |
| 449 | 추가: retained: 0, | |
| 450 | 추가: retained_name: None, | |
| 451 | 추가: }; | |
| 452 | 추가: let prepared = (|| { | |
| 453 | 추가: valid_name(name, false)?; | |
| 454 | 추가: let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?; | |
| 455 | 추가: let temp = format!( | |
| 456 | 추가: ".zipelo-{}-{}.tmp", | |
| 457 | 추가: std::process::id(), | |
| 458 | 추가: TEMP.fetch_add(1, Ordering::Relaxed) | |
| 459 | 추가: ); | |
| 460 | 추가: let mut file = dir.create(&temp).map_err(|_| ErrorCode::Conflict)?; | |
| 461 | 추가: let written = (|| { | |
| 462 | 추가: for chunk in data.chunks(65536) { | |
| 463 | 추가: check(false)?; | |
| 464 | 추가: file.write_all(chunk).map_err(|_| ErrorCode::Io)?; | |
| 465 | 추가: } | |
| 466 | 추가: file.sync_all().map_err(|_| ErrorCode::Io) | |
| 467 | 추가: })(); | |
| 468 | 추가: let closed = close(file).map_err(|_| ErrorCode::Io); | |
| 469 | 추가: let mut finish = written.and(closed).and_then(|_| check(true)); | |
| 470 | 추가: if finish.is_ok() { | |
| 471 | 추가: match dir.link(&temp, &leaf) { | |
| 472 | 추가: Ok(()) => { | |
| 473 | 추가: result.created = true; | |
| 474 | 추가: result.durability = dir.sync(); | |
| 475 | 추가: if result.durability == Durability::Failed { | |
| 476 | 추가: finish = Err(ErrorCode::Io); | |
| 477 | 추가: } | |
| 478 | 추가: } | |
| 479 | 추가: Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { | |
| 480 | 추가: finish = Err(ErrorCode::Conflict) | |
| 481 | 추가: } | |
| 482 | 추가: Err(_) => { | |
| 483 | 추가: result.uncertain = true; | |
| 484 | 추가: result.durability = Durability::Unconfirmed; | |
| 485 | 추가: finish = Err(ErrorCode::Io); | |
| 486 | 추가: } | |
| 487 | 추가: } | |
| 488 | 추가: } | |
| 489 | 추가: if !dir.remove(&temp) { | |
| 490 | 추가: result.cleanup = Cleanup::Failed; | |
| 491 | 추가: result.retained = 1; | |
| 492 | 추가: result.retained_name = Some(match name.rsplit_once('/') { | |
| 493 | 추가: Some((prefix, _)) => format!("{prefix}/{temp}"), | |
| 494 | 추가: None => temp.clone(), | |
| 495 | 추가: }); | |
| 496 | 추가: if finish.is_ok() { | |
| 497 | 추가: finish = Err(ErrorCode::Io); | |
| 498 | 추가: } | |
| 499 | 추가: } | |
| 500 | 추가: if result.created && dir.sync() == Durability::Failed { | |
| 501 | 추가: result.durability = Durability::Failed; | |
| 502 | 추가: finish = Err(ErrorCode::Io); | |
| 503 | 추가: } | |
| 504 | 추가: finish | |
| 505 | 추가: })(); | |
| 506 | 추가: result.error = prepared.err(); | |
| 507 | 추가: result | |
| 508 | 추가: } |
| @@ -0,0 +1,5 @@ | ||
| 1 | 추가: pub mod archive; | |
| 2 | 추가: pub mod filesystem; | |
| 3 | 추가: pub mod protocol; | |
| 4 | 추가: pub mod runtime; | |
| 5 | 추가: pub mod wire; |
| @@ -0,0 +1,7 @@ | ||
| 1 | 추가: fn main() { | |
| 2 | 추가: std::panic::set_hook(Box::new(|_| {})); | |
| 3 | 추가: if zipelo_archive_worker::runtime::serve(std::io::stdin(), std::io::stdout()).is_err() { | |
| 4 | 추가: eprintln!("작업자 통신 실패"); | |
| 5 | 추가: std::process::exit(2); | |
| 6 | 추가: } | |
| 7 | 추가: } |
| @@ -0,0 +1,308 @@ | ||
| 1 | 추가: use std::path::{Path, PathBuf}; | |
| 2 | 추가: | |
| 3 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 4 | 추가: pub enum NativePath { | |
| 5 | 추가: Unix(Vec<u8>), | |
| 6 | 추가: Windows(Vec<u16>), | |
| 7 | 추가: } | |
| 8 | 추가: impl NativePath { | |
| 9 | 추가: pub fn from_path(path: &Path) -> Self { | |
| 10 | 추가: #[cfg(unix)] | |
| 11 | 추가: { | |
| 12 | 추가: use std::os::unix::ffi::OsStrExt; | |
| 13 | 추가: Self::Unix(path.as_os_str().as_bytes().to_vec()) | |
| 14 | 추가: } | |
| 15 | 추가: #[cfg(windows)] | |
| 16 | 추가: { | |
| 17 | 추가: use std::os::windows::ffi::OsStrExt; | |
| 18 | 추가: Self::Windows(path.as_os_str().encode_wide().collect()) | |
| 19 | 추가: } | |
| 20 | 추가: } | |
| 21 | 추가: pub fn to_path(&self) -> Result<PathBuf, ErrorCode> { | |
| 22 | 추가: #[cfg(unix)] | |
| 23 | 추가: if let Self::Unix(bytes) = self { | |
| 24 | 추가: use std::os::unix::ffi::OsStringExt; | |
| 25 | 추가: if bytes.contains(&0) { | |
| 26 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 27 | 추가: } | |
| 28 | 추가: let path = PathBuf::from(std::ffi::OsString::from_vec(bytes.clone())); | |
| 29 | 추가: return if path.is_absolute() { | |
| 30 | 추가: Ok(path) | |
| 31 | 추가: } else { | |
| 32 | 추가: Err(ErrorCode::InvalidRequest) | |
| 33 | 추가: }; | |
| 34 | 추가: } | |
| 35 | 추가: #[cfg(windows)] | |
| 36 | 추가: if let Self::Windows(units) = self { | |
| 37 | 추가: use std::os::windows::ffi::OsStringExt; | |
| 38 | 추가: if units.contains(&0) { | |
| 39 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 40 | 추가: } | |
| 41 | 추가: let path = PathBuf::from(std::ffi::OsString::from_wide(units)); | |
| 42 | 추가: let text = path.to_string_lossy(); | |
| 43 | 추가: if path.is_absolute() && !text.starts_with("\\\\") && !text.starts_with("//") { | |
| 44 | 추가: return Ok(path); | |
| 45 | 추가: } | |
| 46 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 47 | 추가: } | |
| 48 | 추가: Err(ErrorCode::UnsupportedFeature) | |
| 49 | 추가: } | |
| 50 | 추가: } | |
| 51 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 52 | 추가: pub struct Limits { | |
| 53 | 추가: pub input: u64, | |
| 54 | 추가: pub output: u64, | |
| 55 | 추가: pub entries: u32, | |
| 56 | 추가: } | |
| 57 | 추가: impl Default for Limits { | |
| 58 | 추가: fn default() -> Self { | |
| 59 | 추가: Self { | |
| 60 | 추가: input: 64 * 1024 * 1024, | |
| 61 | 추가: output: 128 * 1024 * 1024, | |
| 62 | 추가: entries: 10_000, | |
| 63 | 추가: } | |
| 64 | 추가: } | |
| 65 | 추가: } | |
| 66 | 추가: impl Limits { | |
| 67 | 추가: pub fn valid(self) -> bool { | |
| 68 | 추가: let hard = Self::default(); | |
| 69 | 추가: self.input > 0 | |
| 70 | 추가: && self.input <= hard.input | |
| 71 | 추가: && self.output > 0 | |
| 72 | 추가: && self.output <= hard.output | |
| 73 | 추가: && self.entries > 0 | |
| 74 | 추가: && self.entries <= hard.entries | |
| 75 | 추가: } | |
| 76 | 추가: } | |
| 77 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 78 | 추가: pub enum Format { | |
| 79 | 추가: Zip, | |
| 80 | 추가: Tar, | |
| 81 | 추가: Gzip, | |
| 82 | 추가: TarGzip, | |
| 83 | 추가: } | |
| 84 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 85 | 추가: pub enum SourceObject { | |
| 86 | 추가: Unix { | |
| 87 | 추가: device: u64, | |
| 88 | 추가: inode: u64, | |
| 89 | 추가: }, | |
| 90 | 추가: Windows { | |
| 91 | 추가: volume_serial: u64, | |
| 92 | 추가: file_id: [u8; 16], | |
| 93 | 추가: }, | |
| 94 | 추가: } | |
| 95 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 96 | 추가: pub struct ListId { | |
| 97 | 추가: pub catalog_version: u16, | |
| 98 | 추가: pub format: Format, | |
| 99 | 추가: pub source_object: SourceObject, | |
| 100 | 추가: pub archive_bytes: u64, | |
| 101 | 추가: pub archive_sha256: [u8; 32], | |
| 102 | 추가: } | |
| 103 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 104 | 추가: pub enum Selection { | |
| 105 | 추가: All, | |
| 106 | 추가: EntryIds(Vec<u32>), | |
| 107 | 추가: } | |
| 108 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 109 | 추가: pub enum Method { | |
| 110 | 추가: Store, | |
| 111 | 추가: Deflate, | |
| 112 | 추가: } | |
| 113 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 114 | 추가: pub enum Encryption { | |
| 115 | 추가: None, | |
| 116 | 추가: Aes256, | |
| 117 | 추가: } | |
| 118 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 119 | 추가: pub struct Source { | |
| 120 | 추가: pub path: NativePath, | |
| 121 | 추가: pub archive_name: String, | |
| 122 | 추가: } | |
| 123 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 124 | 추가: pub enum Action { | |
| 125 | 추가: List { | |
| 126 | 추가: archive: NativePath, | |
| 127 | 추가: }, | |
| 128 | 추가: Extract { | |
| 129 | 추가: archive: NativePath, | |
| 130 | 추가: destination: NativePath, | |
| 131 | 추가: selection: Selection, | |
| 132 | 추가: list_id: Option<ListId>, | |
| 133 | 추가: gzip_output_name: Option<String>, | |
| 134 | 추가: }, | |
| 135 | 추가: CreateZip { | |
| 136 | 추가: sources: Vec<Source>, | |
| 137 | 추가: output_file: NativePath, | |
| 138 | 추가: method: Method, | |
| 139 | 추가: encryption: Encryption, | |
| 140 | 추가: }, | |
| 141 | 추가: } | |
| 142 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 143 | 추가: pub enum ActionKind { | |
| 144 | 추가: List, | |
| 145 | 추가: Extract, | |
| 146 | 추가: CreateZip, | |
| 147 | 추가: } | |
| 148 | 추가: impl Action { | |
| 149 | 추가: pub fn kind(&self) -> ActionKind { | |
| 150 | 추가: match self { | |
| 151 | 추가: Self::List { .. } => ActionKind::List, | |
| 152 | 추가: Self::Extract { .. } => ActionKind::Extract, | |
| 153 | 추가: Self::CreateZip { .. } => ActionKind::CreateZip, | |
| 154 | 추가: } | |
| 155 | 추가: } | |
| 156 | 추가: } | |
| 157 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 158 | 추가: pub struct Start { | |
| 159 | 추가: pub action: Action, | |
| 160 | 추가: pub limits: Limits, | |
| 161 | 추가: } | |
| 162 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 163 | 추가: pub enum EntryKind { | |
| 164 | 추가: File, | |
| 165 | 추가: Directory, | |
| 166 | 추가: Link, | |
| 167 | 추가: Other, | |
| 168 | 추가: } | |
| 169 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 170 | 추가: pub struct Entry { | |
| 171 | 추가: pub entry_id: u32, | |
| 172 | 추가: pub name: String, | |
| 173 | 추가: pub kind: EntryKind, | |
| 174 | 추가: pub size: u64, | |
| 175 | 추가: pub compressed_size: u64, | |
| 176 | 추가: pub encrypted: bool, | |
| 177 | 추가: } | |
| 178 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 179 | 추가: pub enum Stage { | |
| 180 | 추가: Scan, | |
| 181 | 추가: Read, | |
| 182 | 추가: Decode, | |
| 183 | 추가: Write, | |
| 184 | 추가: Verify, | |
| 185 | 추가: Commit, | |
| 186 | 추가: } | |
| 187 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 188 | 추가: pub enum Disposition { | |
| 189 | 추가: Created, | |
| 190 | 추가: PartialRetained, | |
| 191 | 추가: Removed, | |
| 192 | 추가: CommitUncertain, | |
| 193 | 추가: } | |
| 194 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 195 | 추가: pub enum Outcome { | |
| 196 | 추가: Completed, | |
| 197 | 추가: Failed, | |
| 198 | 추가: Cancelled, | |
| 199 | 추가: } | |
| 200 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 201 | 추가: pub enum ErrorCode { | |
| 202 | 추가: None, | |
| 203 | 추가: Integrity, | |
| 204 | 추가: UnsupportedFormat, | |
| 205 | 추가: UnsupportedFeature, | |
| 206 | 추가: WrongPassword, | |
| 207 | 추가: UnsafePath, | |
| 208 | 추가: Conflict, | |
| 209 | 추가: Limit, | |
| 210 | 추가: Io, | |
| 211 | 추가: Protocol, | |
| 212 | 추가: Internal, | |
| 213 | 추가: SourceChanged, | |
| 214 | 추가: InvalidRequest, | |
| 215 | 추가: } | |
| 216 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 217 | 추가: pub enum Publication { | |
| 218 | 추가: None, | |
| 219 | 추가: Partial, | |
| 220 | 추가: Complete, | |
| 221 | 추가: Uncertain, | |
| 222 | 추가: } | |
| 223 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 224 | 추가: pub enum Durability { | |
| 225 | 추가: NotApplicable, | |
| 226 | 추가: Synced, | |
| 227 | 추가: Unconfirmed, | |
| 228 | 추가: Failed, | |
| 229 | 추가: } | |
| 230 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 231 | 추가: pub enum Cleanup { | |
| 232 | 추가: Complete, | |
| 233 | 추가: Failed, | |
| 234 | 추가: Unconfirmed, | |
| 235 | 추가: } | |
| 236 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 237 | 추가: pub enum CancelStatus { | |
| 238 | 추가: Requested, | |
| 239 | 추가: AlreadyRequested, | |
| 240 | 추가: TooLate, | |
| 241 | 추가: Finished, | |
| 242 | 추가: } | |
| 243 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 244 | 추가: pub enum PasswordPurpose { | |
| 245 | 추가: Decrypt, | |
| 246 | 추가: Encrypt, | |
| 247 | 추가: } | |
| 248 | 추가: #[derive(Clone, Debug, PartialEq, Eq)] | |
| 249 | 추가: pub struct Terminal { | |
| 250 | 추가: pub outcome: Outcome, | |
| 251 | 추가: pub error: ErrorCode, | |
| 252 | 추가: pub publication: Publication, | |
| 253 | 추가: pub created_count: u64, | |
| 254 | 추가: pub retained_partial_count: u64, | |
| 255 | 추가: pub durability: Durability, | |
| 256 | 추가: pub cleanup: Cleanup, | |
| 257 | 추가: pub detail: String, | |
| 258 | 추가: } | |
| 259 | 추가: pub struct Secret(pub Vec<u8>); | |
| 260 | 추가: impl std::fmt::Debug for Secret { | |
| 261 | 추가: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 262 | 추가: f.write_str("[redacted]") | |
| 263 | 추가: } | |
| 264 | 추가: } | |
| 265 | 추가: impl Drop for Secret { | |
| 266 | 추가: fn drop(&mut self) { | |
| 267 | 추가: self.0.fill(0); | |
| 268 | 추가: } | |
| 269 | 추가: } | |
| 270 | 추가: #[derive(Debug)] | |
| 271 | 추가: pub enum Message { | |
| 272 | 추가: Start(Start), | |
| 273 | 추가: Password { | |
| 274 | 추가: challenge_id: u64, | |
| 275 | 추가: secret: Secret, | |
| 276 | 추가: }, | |
| 277 | 추가: Cancel, | |
| 278 | 추가: Accepted { | |
| 279 | 추가: action: ActionKind, | |
| 280 | 추가: encryption: bool, | |
| 281 | 추가: }, | |
| 282 | 추가: Entry(Entry), | |
| 283 | 추가: ListEnd { | |
| 284 | 추가: entry_count: u32, | |
| 285 | 추가: list_id: ListId, | |
| 286 | 추가: }, | |
| 287 | 추가: PasswordRequired { | |
| 288 | 추가: challenge_id: u64, | |
| 289 | 추가: attempt: u32, | |
| 290 | 추가: purpose: PasswordPurpose, | |
| 291 | 추가: }, | |
| 292 | 추가: Progress { | |
| 293 | 추가: stage: Stage, | |
| 294 | 추가: processed_bytes: u64, | |
| 295 | 추가: total_bytes: Option<u64>, | |
| 296 | 추가: completed_entries: u32, | |
| 297 | 추가: }, | |
| 298 | 추가: Output { | |
| 299 | 추가: entry_id: Option<u32>, | |
| 300 | 추가: relative_name: String, | |
| 301 | 추가: disposition: Disposition, | |
| 302 | 추가: }, | |
| 303 | 추가: Terminal(Terminal), | |
| 304 | 추가: CancelAck { | |
| 305 | 추가: request_sequence: u64, | |
| 306 | 추가: status: CancelStatus, | |
| 307 | 추가: }, | |
| 308 | 추가: } |
| @@ -0,0 +1,475 @@ | ||
| 1 | 추가: use crate::{ | |
| 2 | 추가: archive::{self, Member}, | |
| 3 | 추가: filesystem::{self, Dir}, | |
| 4 | 추가: protocol::*, | |
| 5 | 추가: wire::{Reader, Writer}, | |
| 6 | 추가: }; | |
| 7 | 추가: use std::{ | |
| 8 | 추가: collections::BTreeSet, | |
| 9 | 추가: io::{Read, Write}, | |
| 10 | 추가: sync::{Arc, Mutex}, | |
| 11 | 추가: time::{Duration, Instant}, | |
| 12 | 추가: }; | |
| 13 | 추가: | |
| 14 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 15 | 추가: struct State<W> { | |
| 16 | 추가: writer: Writer<W>, | |
| 17 | 추가: cancelled: bool, | |
| 18 | 추가: phase: u8, | |
| 19 | 추가: fault: Option<ErrorCode>, | |
| 20 | 추가: } | |
| 21 | 추가: struct Job<W> { | |
| 22 | 추가: state: Arc<Mutex<State<W>>>, | |
| 23 | 추가: started: Instant, | |
| 24 | 추가: terminal: Terminal, | |
| 25 | 추가: } | |
| 26 | 추가: impl<W: Write> Job<W> { | |
| 27 | 추가: fn event(&mut self, event: Message) -> Result<()> { | |
| 28 | 추가: let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; | |
| 29 | 추가: state.writer.send(&event).map_err(|_| { | |
| 30 | 추가: state.fault = Some(ErrorCode::Io); | |
| 31 | 추가: ErrorCode::Io | |
| 32 | 추가: }) | |
| 33 | 추가: } | |
| 34 | 추가: fn check(&mut self) -> Result<()> { | |
| 35 | 추가: if self.started.elapsed() > Duration::from_secs(300) { | |
| 36 | 추가: return Err(ErrorCode::Limit); | |
| 37 | 추가: } | |
| 38 | 추가: let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; | |
| 39 | 추가: if let Some(error) = state.fault { | |
| 40 | 추가: return Err(error); | |
| 41 | 추가: } | |
| 42 | 추가: if state.cancelled && state.phase == 0 { | |
| 43 | 추가: return Err(ErrorCode::None); | |
| 44 | 추가: } | |
| 45 | 추가: Ok(()) | |
| 46 | 추가: } | |
| 47 | 추가: fn cutoff(&mut self) -> Result<()> { | |
| 48 | 추가: self.check()?; | |
| 49 | 추가: let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; | |
| 50 | 추가: if state.phase == 0 && state.cancelled { | |
| 51 | 추가: return Err(ErrorCode::None); | |
| 52 | 추가: } | |
| 53 | 추가: state.phase = 1; | |
| 54 | 추가: Ok(()) | |
| 55 | 추가: } | |
| 56 | 추가: fn progress( | |
| 57 | 추가: &mut self, | |
| 58 | 추가: stage: Stage, | |
| 59 | 추가: bytes: u64, | |
| 60 | 추가: total: Option<u64>, | |
| 61 | 추가: entries: u32, | |
| 62 | 추가: ) -> Result<()> { | |
| 63 | 추가: self.event(Message::Progress { | |
| 64 | 추가: stage, | |
| 65 | 추가: processed_bytes: bytes, | |
| 66 | 추가: total_bytes: total, | |
| 67 | 추가: completed_entries: entries, | |
| 68 | 추가: }) | |
| 69 | 추가: } | |
| 70 | 추가: fn output( | |
| 71 | 추가: &mut self, | |
| 72 | 추가: root: &Dir, | |
| 73 | 추가: name: &str, | |
| 74 | 추가: data: &[u8], | |
| 75 | 추가: id: Option<u32>, | |
| 76 | 추가: last: bool, | |
| 77 | 추가: ) -> Result<()> { | |
| 78 | 추가: self.check()?; | |
| 79 | 추가: self.progress( | |
| 80 | 추가: Stage::Write, | |
| 81 | 추가: 0, | |
| 82 | 추가: Some(data.len() as u64), | |
| 83 | 추가: self.terminal.created_count as u32, | |
| 84 | 추가: )?; | |
| 85 | 추가: let p = filesystem::publish(root, name, data, &mut |commit| { | |
| 86 | 추가: if commit && last { | |
| 87 | 추가: self.cutoff() | |
| 88 | 추가: } else { | |
| 89 | 추가: self.check() | |
| 90 | 추가: } | |
| 91 | 추가: }); | |
| 92 | 추가: self.terminal.retained_partial_count += p.retained; | |
| 93 | 추가: if p.cleanup != Cleanup::Complete { | |
| 94 | 추가: self.terminal.cleanup = p.cleanup; | |
| 95 | 추가: } | |
| 96 | 추가: if p.created { | |
| 97 | 추가: self.terminal.created_count += 1; | |
| 98 | 추가: self.terminal.publication = Publication::Partial; | |
| 99 | 추가: self.terminal.durability = match (self.terminal.durability, p.durability) { | |
| 100 | 추가: (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, | |
| 101 | 추가: (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { | |
| 102 | 추가: Durability::Unconfirmed | |
| 103 | 추가: } | |
| 104 | 추가: _ => p.durability, | |
| 105 | 추가: }; | |
| 106 | 추가: self.event(Message::Output { | |
| 107 | 추가: entry_id: id, | |
| 108 | 추가: relative_name: name.to_owned(), | |
| 109 | 추가: disposition: Disposition::Created, | |
| 110 | 추가: })?; | |
| 111 | 추가: } | |
| 112 | 추가: if p.uncertain { | |
| 113 | 추가: self.terminal.publication = Publication::Uncertain; | |
| 114 | 추가: self.terminal.durability = Durability::Unconfirmed; | |
| 115 | 추가: self.event(Message::Output { | |
| 116 | 추가: entry_id: id, | |
| 117 | 추가: relative_name: name.to_owned(), | |
| 118 | 추가: disposition: Disposition::CommitUncertain, | |
| 119 | 추가: })?; | |
| 120 | 추가: } | |
| 121 | 추가: if p.retained != 0 { | |
| 122 | 추가: self.event(Message::Output { | |
| 123 | 추가: entry_id: id, | |
| 124 | 추가: relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?, | |
| 125 | 추가: disposition: Disposition::PartialRetained, | |
| 126 | 추가: })?; | |
| 127 | 추가: } | |
| 128 | 추가: if let Some(error) = p.error { | |
| 129 | 추가: return Err(error); | |
| 130 | 추가: } | |
| 131 | 추가: Ok(()) | |
| 132 | 추가: } | |
| 133 | 추가: fn run(&mut self, start: Start) -> Result<()> { | |
| 134 | 추가: if !start.limits.valid() { | |
| 135 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 136 | 추가: } | |
| 137 | 추가: self.event(Message::Accepted { | |
| 138 | 추가: action: start.action.kind(), | |
| 139 | 추가: encryption: false, | |
| 140 | 추가: })?; | |
| 141 | 추가: self.check()?; | |
| 142 | 추가: match start.action { | |
| 143 | 추가: Action::List { | |
| 144 | 추가: archive: ref source, | |
| 145 | 추가: } | |
| 146 | 추가: | Action::Extract { | |
| 147 | 추가: archive: ref source, | |
| 148 | 추가: .. | |
| 149 | 추가: } => { | |
| 150 | 추가: let extract = matches!(start.action, Action::Extract { .. }); | |
| 151 | 추가: let path = source.to_path()?; | |
| 152 | 추가: self.progress(Stage::Read, 0, None, 0)?; | |
| 153 | 추가: let snapshot = | |
| 154 | 추가: filesystem::snapshot(&path, start.limits.input, &mut || self.check())?; | |
| 155 | 추가: if let Action::Extract { | |
| 156 | 추가: list_id: Some(expected), | |
| 157 | 추가: .. | |
| 158 | 추가: } = &start.action | |
| 159 | 추가: { | |
| 160 | 추가: if expected.catalog_version != 1 | |
| 161 | 추가: || expected.source_object != snapshot.object | |
| 162 | 추가: || expected.archive_bytes != snapshot.bytes.len() as u64 | |
| 163 | 추가: || expected.archive_sha256 != snapshot.hash | |
| 164 | 추가: { | |
| 165 | 추가: return Err(ErrorCode::SourceChanged); | |
| 166 | 추가: } | |
| 167 | 추가: } | |
| 168 | 추가: self.progress( | |
| 169 | 추가: Stage::Decode, | |
| 170 | 추가: snapshot.bytes.len() as u64, | |
| 171 | 추가: Some(snapshot.bytes.len() as u64), | |
| 172 | 추가: 0, | |
| 173 | 추가: )?; | |
| 174 | 추가: let mut catalog = | |
| 175 | 추가: archive::parse(&snapshot.bytes, start.limits, extract, &mut || self.check())?; | |
| 176 | 추가: let list_id = ListId { | |
| 177 | 추가: catalog_version: 1, | |
| 178 | 추가: format: catalog.format, | |
| 179 | 추가: source_object: snapshot.object, | |
| 180 | 추가: archive_bytes: snapshot.bytes.len() as u64, | |
| 181 | 추가: archive_sha256: snapshot.hash, | |
| 182 | 추가: }; | |
| 183 | 추가: if !extract { | |
| 184 | 추가: for member in &catalog.members { | |
| 185 | 추가: self.check()?; | |
| 186 | 추가: self.event(Message::Entry(member.entry.clone()))?; | |
| 187 | 추가: } | |
| 188 | 추가: self.event(Message::ListEnd { | |
| 189 | 추가: entry_count: catalog.members.len() as u32, | |
| 190 | 추가: list_id, | |
| 191 | 추가: })?; | |
| 192 | 추가: } else if let Action::Extract { | |
| 193 | 추가: destination, | |
| 194 | 추가: selection, | |
| 195 | 추가: list_id: expected, | |
| 196 | 추가: gzip_output_name, | |
| 197 | 추가: .. | |
| 198 | 추가: } = start.action | |
| 199 | 추가: { | |
| 200 | 추가: if expected | |
| 201 | 추가: .as_ref() | |
| 202 | 추가: .is_some_and(|expected| *expected != list_id) | |
| 203 | 추가: { | |
| 204 | 추가: return Err(ErrorCode::SourceChanged); | |
| 205 | 추가: } | |
| 206 | 추가: let selected = match selection { | |
| 207 | 추가: Selection::All => None, | |
| 208 | 추가: Selection::EntryIds(ids) => { | |
| 209 | 추가: let n = ids.len(); | |
| 210 | 추가: let set = ids.into_iter().collect::<BTreeSet<_>>(); | |
| 211 | 추가: if expected.is_none() | |
| 212 | 추가: || set.is_empty() | |
| 213 | 추가: || n != set.len() | |
| 214 | 추가: || set.iter().any(|id| *id as usize >= catalog.members.len()) | |
| 215 | 추가: { | |
| 216 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 217 | 추가: } | |
| 218 | 추가: Some(set) | |
| 219 | 추가: } | |
| 220 | 추가: }; | |
| 221 | 추가: if catalog.members.iter().any(|m| m.entry.encrypted) { | |
| 222 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 223 | 추가: } | |
| 224 | 추가: if catalog | |
| 225 | 추가: .members | |
| 226 | 추가: .iter() | |
| 227 | 추가: .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory)) | |
| 228 | 추가: { | |
| 229 | 추가: return Err(ErrorCode::UnsafePath); | |
| 230 | 추가: } | |
| 231 | 추가: if catalog.format == Format::Gzip { | |
| 232 | 추가: let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; | |
| 233 | 추가: let checked = archive::valid_name(&name, false) | |
| 234 | 추가: .map_err(|_| ErrorCode::InvalidRequest)?; | |
| 235 | 추가: if checked.contains('/') { | |
| 236 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 237 | 추가: } | |
| 238 | 추가: catalog.members[0].entry.name = checked; | |
| 239 | 추가: } else if gzip_output_name.is_some() { | |
| 240 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 241 | 추가: } | |
| 242 | 추가: let root = Dir::root(&destination.to_path()?)?; | |
| 243 | 추가: let members = catalog | |
| 244 | 추가: .members | |
| 245 | 추가: .into_iter() | |
| 246 | 추가: .filter(|m| { | |
| 247 | 추가: selected | |
| 248 | 추가: .as_ref() | |
| 249 | 추가: .is_none_or(|s| s.contains(&m.entry.entry_id)) | |
| 250 | 추가: }) | |
| 251 | 추가: .collect::<Vec<_>>(); | |
| 252 | 추가: let mut dirs = BTreeSet::new(); | |
| 253 | 추가: let files = members | |
| 254 | 추가: .iter() | |
| 255 | 추가: .filter(|m| m.entry.kind == EntryKind::File) | |
| 256 | 추가: .collect::<Vec<_>>(); | |
| 257 | 추가: for m in &members { | |
| 258 | 추가: if m.entry.kind == EntryKind::Directory { | |
| 259 | 추가: dirs.insert(m.entry.name.clone()); | |
| 260 | 추가: } | |
| 261 | 추가: let mut name = m.entry.name.as_str(); | |
| 262 | 추가: while let Some((parent, _)) = name.rsplit_once('/') { | |
| 263 | 추가: dirs.insert(parent.to_owned()); | |
| 264 | 추가: name = parent; | |
| 265 | 추가: } | |
| 266 | 추가: } | |
| 267 | 추가: let mut names = dirs | |
| 268 | 추가: .iter() | |
| 269 | 추가: .map(|n| (n.clone(), EntryKind::Directory)) | |
| 270 | 추가: .collect::<Vec<_>>(); | |
| 271 | 추가: names.extend( | |
| 272 | 추가: files | |
| 273 | 추가: .iter() | |
| 274 | 추가: .map(|m| (m.entry.name.clone(), EntryKind::File)), | |
| 275 | 추가: ); | |
| 276 | 추가: archive::validate_members(&members)?; | |
| 277 | 추가: filesystem::preflight(&root, &names)?; | |
| 278 | 추가: for name in dirs { | |
| 279 | 추가: self.check()?; | |
| 280 | 추가: let (created, durability) = filesystem::directory(&root, &name)?; | |
| 281 | 추가: if created { | |
| 282 | 추가: self.terminal.created_count += 1; | |
| 283 | 추가: self.terminal.publication = Publication::Partial; | |
| 284 | 추가: self.terminal.durability = durability; | |
| 285 | 추가: self.event(Message::Output { | |
| 286 | 추가: entry_id: None, | |
| 287 | 추가: relative_name: name, | |
| 288 | 추가: disposition: Disposition::Created, | |
| 289 | 추가: })?; | |
| 290 | 추가: if durability == Durability::Failed { | |
| 291 | 추가: return Err(ErrorCode::Io); | |
| 292 | 추가: } | |
| 293 | 추가: } | |
| 294 | 추가: } | |
| 295 | 추가: for (index, m) in files.iter().enumerate() { | |
| 296 | 추가: self.output( | |
| 297 | 추가: &root, | |
| 298 | 추가: &m.entry.name, | |
| 299 | 추가: &m.data, | |
| 300 | 추가: Some(m.entry.entry_id), | |
| 301 | 추가: index + 1 == files.len(), | |
| 302 | 추가: )?; | |
| 303 | 추가: } | |
| 304 | 추가: self.terminal.publication = Publication::Complete; | |
| 305 | 추가: } | |
| 306 | 추가: } | |
| 307 | 추가: Action::CreateZip { | |
| 308 | 추가: sources, | |
| 309 | 추가: output_file, | |
| 310 | 추가: method, | |
| 311 | 추가: encryption, | |
| 312 | 추가: } => { | |
| 313 | 추가: if encryption != Encryption::None { | |
| 314 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 315 | 추가: } | |
| 316 | 추가: if sources.len() > start.limits.entries as usize { | |
| 317 | 추가: return Err(ErrorCode::Limit); | |
| 318 | 추가: } | |
| 319 | 추가: let mut members = Vec::new(); | |
| 320 | 추가: let mut consumed = 0; | |
| 321 | 추가: for source in sources { | |
| 322 | 추가: self.check()?; | |
| 323 | 추가: let name = archive::valid_name(&source.archive_name, false)?; | |
| 324 | 추가: let snapshot = filesystem::snapshot( | |
| 325 | 추가: &source.path.to_path()?, | |
| 326 | 추가: start.limits.input - consumed, | |
| 327 | 추가: &mut || self.check(), | |
| 328 | 추가: )?; | |
| 329 | 추가: consumed += snapshot.bytes.len() as u64; | |
| 330 | 추가: members.push(Member { | |
| 331 | 추가: entry: Entry { | |
| 332 | 추가: entry_id: members.len() as u32, | |
| 333 | 추가: name, | |
| 334 | 추가: kind: EntryKind::File, | |
| 335 | 추가: size: snapshot.bytes.len() as u64, | |
| 336 | 추가: compressed_size: 0, | |
| 337 | 추가: encrypted: false, | |
| 338 | 추가: }, | |
| 339 | 추가: data: snapshot.bytes, | |
| 340 | 추가: }); | |
| 341 | 추가: } | |
| 342 | 추가: let bytes = | |
| 343 | 추가: archive::create_zip(&members, method, start.limits, &mut || self.check())?; | |
| 344 | 추가: let output = output_file.to_path()?; | |
| 345 | 추가: let leaf = output | |
| 346 | 추가: .file_name() | |
| 347 | 추가: .and_then(|n| n.to_str()) | |
| 348 | 추가: .ok_or(ErrorCode::InvalidRequest)?; | |
| 349 | 추가: let name = archive::valid_name(leaf, false)?; | |
| 350 | 추가: let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?; | |
| 351 | 추가: filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?; | |
| 352 | 추가: self.output(&root, &name, &bytes, None, true)?; | |
| 353 | 추가: self.terminal.publication = Publication::Complete; | |
| 354 | 추가: } | |
| 355 | 추가: } | |
| 356 | 추가: self.cutoff()?; | |
| 357 | 추가: Ok(()) | |
| 358 | 추가: } | |
| 359 | 추가: } | |
| 360 | 추가: pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | |
| 361 | 추가: input: R, | |
| 362 | 추가: output: W, | |
| 363 | 추가: ) -> std::io::Result<()> { | |
| 364 | 추가: let mut reader = Reader::new(input); | |
| 365 | 추가: let (job, _, message) = reader | |
| 366 | 추가: .read()? | |
| 367 | 추가: .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; | |
| 368 | 추가: let Message::Start(start) = message else { | |
| 369 | 추가: return Err(std::io::Error::new( | |
| 370 | 추가: std::io::ErrorKind::InvalidData, | |
| 371 | 추가: "Start required", | |
| 372 | 추가: )); | |
| 373 | 추가: }; | |
| 374 | 추가: let state = Arc::new(Mutex::new(State { | |
| 375 | 추가: writer: Writer::new(output, job), | |
| 376 | 추가: cancelled: false, | |
| 377 | 추가: phase: 0, | |
| 378 | 추가: fault: None, | |
| 379 | 추가: })); | |
| 380 | 추가: let control = Arc::clone(&state); | |
| 381 | 추가: std::thread::spawn(move || { | |
| 382 | 추가: loop { | |
| 383 | 추가: let command = reader.read(); | |
| 384 | 추가: let Ok(Some((_, sequence, message))) = command else { | |
| 385 | 추가: if command.is_err() { | |
| 386 | 추가: if let Ok(mut state) = control.lock() { | |
| 387 | 추가: if state.phase < 2 { | |
| 388 | 추가: state.fault = Some(ErrorCode::Protocol); | |
| 389 | 추가: } | |
| 390 | 추가: } | |
| 391 | 추가: } | |
| 392 | 추가: break; | |
| 393 | 추가: }; | |
| 394 | 추가: let Ok(mut state) = control.lock() else { | |
| 395 | 추가: break; | |
| 396 | 추가: }; | |
| 397 | 추가: if state.phase == 3 { | |
| 398 | 추가: break; | |
| 399 | 추가: } | |
| 400 | 추가: match message { | |
| 401 | 추가: Message::Cancel => { | |
| 402 | 추가: let status = match state.phase { | |
| 403 | 추가: 2 => CancelStatus::Finished, | |
| 404 | 추가: 1 => CancelStatus::TooLate, | |
| 405 | 추가: _ if state.cancelled => CancelStatus::AlreadyRequested, | |
| 406 | 추가: _ => { | |
| 407 | 추가: state.cancelled = true; | |
| 408 | 추가: CancelStatus::Requested | |
| 409 | 추가: } | |
| 410 | 추가: }; | |
| 411 | 추가: if state | |
| 412 | 추가: .writer | |
| 413 | 추가: .send(&Message::CancelAck { | |
| 414 | 추가: request_sequence: sequence, | |
| 415 | 추가: status, | |
| 416 | 추가: }) | |
| 417 | 추가: .is_err() | |
| 418 | 추가: { | |
| 419 | 추가: state.fault = Some(ErrorCode::Io); | |
| 420 | 추가: break; | |
| 421 | 추가: } | |
| 422 | 추가: } | |
| 423 | 추가: _ => { | |
| 424 | 추가: state.fault = Some(ErrorCode::Protocol); | |
| 425 | 추가: break; | |
| 426 | 추가: } | |
| 427 | 추가: } | |
| 428 | 추가: } | |
| 429 | 추가: }); | |
| 430 | 추가: let mut context = Job { | |
| 431 | 추가: state: Arc::clone(&state), | |
| 432 | 추가: started: Instant::now(), | |
| 433 | 추가: terminal: Terminal { | |
| 434 | 추가: outcome: Outcome::Completed, | |
| 435 | 추가: error: ErrorCode::None, | |
| 436 | 추가: publication: Publication::None, | |
| 437 | 추가: created_count: 0, | |
| 438 | 추가: retained_partial_count: 0, | |
| 439 | 추가: durability: Durability::NotApplicable, | |
| 440 | 추가: cleanup: Cleanup::Complete, | |
| 441 | 추가: detail: String::new(), | |
| 442 | 추가: }, | |
| 443 | 추가: }; | |
| 444 | 추가: let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start))); | |
| 445 | 추가: let error = match result { | |
| 446 | 추가: Ok(r) => r.err(), | |
| 447 | 추가: Err(_) => { | |
| 448 | 추가: context.terminal.publication = Publication::Uncertain; | |
| 449 | 추가: context.terminal.cleanup = Cleanup::Unconfirmed; | |
| 450 | 추가: Some(ErrorCode::Internal) | |
| 451 | 추가: } | |
| 452 | 추가: }; | |
| 453 | 추가: let mut state = state | |
| 454 | 추가: .lock() | |
| 455 | 추가: .map_err(|_| std::io::Error::other("worker state poisoned"))?; | |
| 456 | 추가: state.phase = 2; | |
| 457 | 추가: if let Some(error) = state.fault.or(error) { | |
| 458 | 추가: context.terminal.error = error; | |
| 459 | 추가: context.terminal.outcome = if error == ErrorCode::None { | |
| 460 | 추가: Outcome::Cancelled | |
| 461 | 추가: } else { | |
| 462 | 추가: Outcome::Failed | |
| 463 | 추가: }; | |
| 464 | 추가: context.terminal.detail = match error { | |
| 465 | 추가: ErrorCode::None => "취소됨", | |
| 466 | 추가: ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", | |
| 467 | 추가: ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", | |
| 468 | 추가: _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", | |
| 469 | 추가: } | |
| 470 | 추가: .to_owned(); | |
| 471 | 추가: } | |
| 472 | 추가: state.writer.send(&Message::Terminal(context.terminal))?; | |
| 473 | 추가: state.phase = 3; | |
| 474 | 추가: Ok(()) | |
| 475 | 추가: } |
| @@ -0,0 +1,540 @@ | ||
| 1 | 추가: use crate::protocol::*; | |
| 2 | 추가: use std::io::{self, Read, Write}; | |
| 3 | 추가: | |
| 4 | 추가: pub const MAX_BODY: usize = 1_048_576; | |
| 5 | 추가: pub const MAX_FRAMES: u64 = 1_000_000; | |
| 6 | 추가: fn invalid() -> io::Error { | |
| 7 | 추가: io::Error::new(io::ErrorKind::InvalidData, "invalid worker frame") | |
| 8 | 추가: } | |
| 9 | 추가: struct Encoder { | |
| 10 | 추가: bytes: Vec<u8>, | |
| 11 | 추가: } | |
| 12 | 추가: impl Encoder { | |
| 13 | 추가: fn put(&mut self, b: &[u8]) -> io::Result<()> { | |
| 14 | 추가: if self | |
| 15 | 추가: .bytes | |
| 16 | 추가: .len() | |
| 17 | 추가: .checked_add(b.len()) | |
| 18 | 추가: .filter(|n| *n <= MAX_BODY) | |
| 19 | 추가: .is_none() | |
| 20 | 추가: { | |
| 21 | 추가: return Err(invalid()); | |
| 22 | 추가: } | |
| 23 | 추가: self.bytes.extend_from_slice(b); | |
| 24 | 추가: Ok(()) | |
| 25 | 추가: } | |
| 26 | 추가: } | |
| 27 | 추가: struct Decoder<'a> { | |
| 28 | 추가: bytes: &'a [u8], | |
| 29 | 추가: at: usize, | |
| 30 | 추가: } | |
| 31 | 추가: impl<'a> Decoder<'a> { | |
| 32 | 추가: fn take(&mut self, n: usize) -> io::Result<&'a [u8]> { | |
| 33 | 추가: let end = self.at.checked_add(n).ok_or_else(invalid)?; | |
| 34 | 추가: let b = self.bytes.get(self.at..end).ok_or_else(invalid)?; | |
| 35 | 추가: self.at = end; | |
| 36 | 추가: Ok(b) | |
| 37 | 추가: } | |
| 38 | 추가: } | |
| 39 | 추가: trait Wire: Sized { | |
| 40 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()>; | |
| 41 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self>; | |
| 42 | 추가: } | |
| 43 | 추가: macro_rules! integer { ($($t:ty),*) => { $(impl Wire for $t { | |
| 44 | 추가: fn enc(&self,e:&mut Encoder)->io::Result<()> { e.put(&self.to_le_bytes()) } | |
| 45 | 추가: fn dec(d:&mut Decoder<'_>)->io::Result<Self> { Ok(Self::from_le_bytes(d.take(size_of::<Self>())?.try_into().map_err(|_|invalid())?)) } | |
| 46 | 추가: })* }; } | |
| 47 | 추가: integer!(u8, u16, u32, u64); | |
| 48 | 추가: impl<const N: usize> Wire for [u8; N] { | |
| 49 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 50 | 추가: e.put(self) | |
| 51 | 추가: } | |
| 52 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 53 | 추가: d.take(N)?.try_into().map_err(|_| invalid()) | |
| 54 | 추가: } | |
| 55 | 추가: } | |
| 56 | 추가: impl Wire for bool { | |
| 57 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 58 | 추가: u8::from(*self).enc(e) | |
| 59 | 추가: } | |
| 60 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 61 | 추가: match u8::dec(d)? { | |
| 62 | 추가: 0 => Ok(false), | |
| 63 | 추가: 1 => Ok(true), | |
| 64 | 추가: _ => Err(invalid()), | |
| 65 | 추가: } | |
| 66 | 추가: } | |
| 67 | 추가: } | |
| 68 | 추가: impl<T: Wire> Wire for Option<T> { | |
| 69 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 70 | 추가: self.is_some().enc(e)?; | |
| 71 | 추가: if let Some(v) = self { | |
| 72 | 추가: v.enc(e)?; | |
| 73 | 추가: } | |
| 74 | 추가: Ok(()) | |
| 75 | 추가: } | |
| 76 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 77 | 추가: if bool::dec(d)? { | |
| 78 | 추가: Ok(Some(T::dec(d)?)) | |
| 79 | 추가: } else { | |
| 80 | 추가: Ok(None) | |
| 81 | 추가: } | |
| 82 | 추가: } | |
| 83 | 추가: } | |
| 84 | 추가: impl<T: Wire> Wire for Vec<T> { | |
| 85 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 86 | 추가: if self.len() > 32768 { | |
| 87 | 추가: return Err(invalid()); | |
| 88 | 추가: } | |
| 89 | 추가: (self.len() as u32).enc(e)?; | |
| 90 | 추가: for v in self { | |
| 91 | 추가: v.enc(e)?; | |
| 92 | 추가: } | |
| 93 | 추가: Ok(()) | |
| 94 | 추가: } | |
| 95 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 96 | 추가: let n = u32::dec(d)? as usize; | |
| 97 | 추가: if n > 32768 || n > d.bytes.len() - d.at { | |
| 98 | 추가: return Err(invalid()); | |
| 99 | 추가: } | |
| 100 | 추가: let mut v = Vec::new(); | |
| 101 | 추가: v.try_reserve(n).map_err(|_| invalid())?; | |
| 102 | 추가: for _ in 0..n { | |
| 103 | 추가: v.push(T::dec(d)?); | |
| 104 | 추가: } | |
| 105 | 추가: Ok(v) | |
| 106 | 추가: } | |
| 107 | 추가: } | |
| 108 | 추가: impl Wire for String { | |
| 109 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 110 | 추가: if self.len() > 32768 { | |
| 111 | 추가: return Err(invalid()); | |
| 112 | 추가: } | |
| 113 | 추가: (self.len() as u32).enc(e)?; | |
| 114 | 추가: e.put(self.as_bytes()) | |
| 115 | 추가: } | |
| 116 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 117 | 추가: let n = u32::dec(d)? as usize; | |
| 118 | 추가: if n > 32768 { | |
| 119 | 추가: return Err(invalid()); | |
| 120 | 추가: } | |
| 121 | 추가: String::from_utf8(d.take(n)?.to_vec()).map_err(|_| invalid()) | |
| 122 | 추가: } | |
| 123 | 추가: } | |
| 124 | 추가: macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wire for $t { | |
| 125 | 추가: fn enc(&self,e:&mut Encoder)->io::Result<()> { (match self {$(Self::$v=>$n,)*} as u8).enc(e) } | |
| 126 | 추가: fn dec(d:&mut Decoder<'_>)->io::Result<Self> { match u8::dec(d)? {$($n=>Ok(Self::$v),)*_=>Err(invalid())} } | |
| 127 | 추가: } }; } | |
| 128 | 추가: enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3}); | |
| 129 | 추가: enumeration!(Method{Store=0,Deflate=1}); | |
| 130 | 추가: enumeration!(Encryption{None=0,Aes256=1}); | |
| 131 | 추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2}); | |
| 132 | 추가: enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); | |
| 133 | 추가: enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); | |
| 134 | 추가: enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3}); | |
| 135 | 추가: enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2}); | |
| 136 | 추가: enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12}); | |
| 137 | 추가: enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3}); | |
| 138 | 추가: enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3}); | |
| 139 | 추가: enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2}); | |
| 140 | 추가: enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3}); | |
| 141 | 추가: enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1}); | |
| 142 | 추가: macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t { | |
| 143 | 추가: fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())} | |
| 144 | 추가: fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})} | |
| 145 | 추가: }};} | |
| 146 | 추가: structure!(Limits { | |
| 147 | 추가: input, | |
| 148 | 추가: output, | |
| 149 | 추가: entries | |
| 150 | 추가: }); | |
| 151 | 추가: structure!(ListId { | |
| 152 | 추가: catalog_version, | |
| 153 | 추가: format, | |
| 154 | 추가: source_object, | |
| 155 | 추가: archive_bytes, | |
| 156 | 추가: archive_sha256 | |
| 157 | 추가: }); | |
| 158 | 추가: structure!(Source { path, archive_name }); | |
| 159 | 추가: structure!(Start { action, limits }); | |
| 160 | 추가: structure!(Entry { | |
| 161 | 추가: entry_id, | |
| 162 | 추가: name, | |
| 163 | 추가: kind, | |
| 164 | 추가: size, | |
| 165 | 추가: compressed_size, | |
| 166 | 추가: encrypted | |
| 167 | 추가: }); | |
| 168 | 추가: structure!(Terminal { | |
| 169 | 추가: outcome, | |
| 170 | 추가: error, | |
| 171 | 추가: publication, | |
| 172 | 추가: created_count, | |
| 173 | 추가: retained_partial_count, | |
| 174 | 추가: durability, | |
| 175 | 추가: cleanup, | |
| 176 | 추가: detail | |
| 177 | 추가: }); | |
| 178 | 추가: impl Wire for NativePath { | |
| 179 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 180 | 추가: match self { | |
| 181 | 추가: Self::Unix(v) => { | |
| 182 | 추가: 1u8.enc(e)?; | |
| 183 | 추가: v.enc(e) | |
| 184 | 추가: } | |
| 185 | 추가: Self::Windows(v) => { | |
| 186 | 추가: 2u8.enc(e)?; | |
| 187 | 추가: v.enc(e) | |
| 188 | 추가: } | |
| 189 | 추가: } | |
| 190 | 추가: } | |
| 191 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 192 | 추가: match u8::dec(d)? { | |
| 193 | 추가: 1 => Ok(Self::Unix(Wire::dec(d)?)), | |
| 194 | 추가: 2 => Ok(Self::Windows(Wire::dec(d)?)), | |
| 195 | 추가: _ => Err(invalid()), | |
| 196 | 추가: } | |
| 197 | 추가: } | |
| 198 | 추가: } | |
| 199 | 추가: impl Wire for SourceObject { | |
| 200 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 201 | 추가: match self { | |
| 202 | 추가: Self::Unix { device, inode } => { | |
| 203 | 추가: 1u8.enc(e)?; | |
| 204 | 추가: device.enc(e)?; | |
| 205 | 추가: inode.enc(e) | |
| 206 | 추가: } | |
| 207 | 추가: Self::Windows { | |
| 208 | 추가: volume_serial, | |
| 209 | 추가: file_id, | |
| 210 | 추가: } => { | |
| 211 | 추가: 2u8.enc(e)?; | |
| 212 | 추가: volume_serial.enc(e)?; | |
| 213 | 추가: file_id.enc(e) | |
| 214 | 추가: } | |
| 215 | 추가: } | |
| 216 | 추가: } | |
| 217 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 218 | 추가: match u8::dec(d)? { | |
| 219 | 추가: 1 => Ok(Self::Unix { | |
| 220 | 추가: device: Wire::dec(d)?, | |
| 221 | 추가: inode: Wire::dec(d)?, | |
| 222 | 추가: }), | |
| 223 | 추가: 2 => Ok(Self::Windows { | |
| 224 | 추가: volume_serial: Wire::dec(d)?, | |
| 225 | 추가: file_id: Wire::dec(d)?, | |
| 226 | 추가: }), | |
| 227 | 추가: _ => Err(invalid()), | |
| 228 | 추가: } | |
| 229 | 추가: } | |
| 230 | 추가: } | |
| 231 | 추가: impl Wire for Selection { | |
| 232 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 233 | 추가: match self { | |
| 234 | 추가: Self::All => 0u8.enc(e), | |
| 235 | 추가: Self::EntryIds(ids) => { | |
| 236 | 추가: 1u8.enc(e)?; | |
| 237 | 추가: ids.enc(e) | |
| 238 | 추가: } | |
| 239 | 추가: } | |
| 240 | 추가: } | |
| 241 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 242 | 추가: match u8::dec(d)? { | |
| 243 | 추가: 0 => Ok(Self::All), | |
| 244 | 추가: 1 => Ok(Self::EntryIds(Wire::dec(d)?)), | |
| 245 | 추가: _ => Err(invalid()), | |
| 246 | 추가: } | |
| 247 | 추가: } | |
| 248 | 추가: } | |
| 249 | 추가: impl Wire for Action { | |
| 250 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 251 | 추가: match self { | |
| 252 | 추가: Self::List { archive } => { | |
| 253 | 추가: 0u8.enc(e)?; | |
| 254 | 추가: archive.enc(e) | |
| 255 | 추가: } | |
| 256 | 추가: Self::Extract { | |
| 257 | 추가: archive, | |
| 258 | 추가: destination, | |
| 259 | 추가: selection, | |
| 260 | 추가: list_id, | |
| 261 | 추가: gzip_output_name, | |
| 262 | 추가: } => { | |
| 263 | 추가: 1u8.enc(e)?; | |
| 264 | 추가: archive.enc(e)?; | |
| 265 | 추가: destination.enc(e)?; | |
| 266 | 추가: selection.enc(e)?; | |
| 267 | 추가: list_id.enc(e)?; | |
| 268 | 추가: gzip_output_name.enc(e) | |
| 269 | 추가: } | |
| 270 | 추가: Self::CreateZip { | |
| 271 | 추가: sources, | |
| 272 | 추가: output_file, | |
| 273 | 추가: method, | |
| 274 | 추가: encryption, | |
| 275 | 추가: } => { | |
| 276 | 추가: 2u8.enc(e)?; | |
| 277 | 추가: sources.enc(e)?; | |
| 278 | 추가: output_file.enc(e)?; | |
| 279 | 추가: method.enc(e)?; | |
| 280 | 추가: encryption.enc(e) | |
| 281 | 추가: } | |
| 282 | 추가: } | |
| 283 | 추가: } | |
| 284 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 285 | 추가: match u8::dec(d)? { | |
| 286 | 추가: 0 => Ok(Self::List { | |
| 287 | 추가: archive: Wire::dec(d)?, | |
| 288 | 추가: }), | |
| 289 | 추가: 1 => Ok(Self::Extract { | |
| 290 | 추가: archive: Wire::dec(d)?, | |
| 291 | 추가: destination: Wire::dec(d)?, | |
| 292 | 추가: selection: Wire::dec(d)?, | |
| 293 | 추가: list_id: Wire::dec(d)?, | |
| 294 | 추가: gzip_output_name: Wire::dec(d)?, | |
| 295 | 추가: }), | |
| 296 | 추가: 2 => Ok(Self::CreateZip { | |
| 297 | 추가: sources: Wire::dec(d)?, | |
| 298 | 추가: output_file: Wire::dec(d)?, | |
| 299 | 추가: method: Wire::dec(d)?, | |
| 300 | 추가: encryption: Wire::dec(d)?, | |
| 301 | 추가: }), | |
| 302 | 추가: _ => Err(invalid()), | |
| 303 | 추가: } | |
| 304 | 추가: } | |
| 305 | 추가: } | |
| 306 | 추가: impl Message { | |
| 307 | 추가: fn encode(&self) -> io::Result<(u16, Vec<u8>)> { | |
| 308 | 추가: let mut e = Encoder { bytes: Vec::new() }; | |
| 309 | 추가: let kind = match self { | |
| 310 | 추가: Self::Start(v) => { | |
| 311 | 추가: v.enc(&mut e)?; | |
| 312 | 추가: 1 | |
| 313 | 추가: } | |
| 314 | 추가: Self::Password { | |
| 315 | 추가: challenge_id, | |
| 316 | 추가: secret, | |
| 317 | 추가: } => { | |
| 318 | 추가: if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() { | |
| 319 | 추가: return Err(invalid()); | |
| 320 | 추가: } | |
| 321 | 추가: challenge_id.enc(&mut e)?; | |
| 322 | 추가: secret.0.enc(&mut e)?; | |
| 323 | 추가: 2 | |
| 324 | 추가: } | |
| 325 | 추가: Self::Cancel => 3, | |
| 326 | 추가: Self::Accepted { action, encryption } => { | |
| 327 | 추가: action.enc(&mut e)?; | |
| 328 | 추가: encryption.enc(&mut e)?; | |
| 329 | 추가: 100 | |
| 330 | 추가: } | |
| 331 | 추가: Self::Entry(v) => { | |
| 332 | 추가: v.enc(&mut e)?; | |
| 333 | 추가: 101 | |
| 334 | 추가: } | |
| 335 | 추가: Self::ListEnd { | |
| 336 | 추가: entry_count, | |
| 337 | 추가: list_id, | |
| 338 | 추가: } => { | |
| 339 | 추가: entry_count.enc(&mut e)?; | |
| 340 | 추가: list_id.enc(&mut e)?; | |
| 341 | 추가: 102 | |
| 342 | 추가: } | |
| 343 | 추가: Self::PasswordRequired { | |
| 344 | 추가: challenge_id, | |
| 345 | 추가: attempt, | |
| 346 | 추가: purpose, | |
| 347 | 추가: } => { | |
| 348 | 추가: challenge_id.enc(&mut e)?; | |
| 349 | 추가: attempt.enc(&mut e)?; | |
| 350 | 추가: purpose.enc(&mut e)?; | |
| 351 | 추가: 103 | |
| 352 | 추가: } | |
| 353 | 추가: Self::Progress { | |
| 354 | 추가: stage, | |
| 355 | 추가: processed_bytes, | |
| 356 | 추가: total_bytes, | |
| 357 | 추가: completed_entries, | |
| 358 | 추가: } => { | |
| 359 | 추가: stage.enc(&mut e)?; | |
| 360 | 추가: processed_bytes.enc(&mut e)?; | |
| 361 | 추가: total_bytes.enc(&mut e)?; | |
| 362 | 추가: completed_entries.enc(&mut e)?; | |
| 363 | 추가: 104 | |
| 364 | 추가: } | |
| 365 | 추가: Self::Output { | |
| 366 | 추가: entry_id, | |
| 367 | 추가: relative_name, | |
| 368 | 추가: disposition, | |
| 369 | 추가: } => { | |
| 370 | 추가: entry_id.enc(&mut e)?; | |
| 371 | 추가: relative_name.enc(&mut e)?; | |
| 372 | 추가: disposition.enc(&mut e)?; | |
| 373 | 추가: 105 | |
| 374 | 추가: } | |
| 375 | 추가: Self::Terminal(v) => { | |
| 376 | 추가: if v.detail.len() > 4096 { | |
| 377 | 추가: return Err(invalid()); | |
| 378 | 추가: } | |
| 379 | 추가: v.enc(&mut e)?; | |
| 380 | 추가: 106 | |
| 381 | 추가: } | |
| 382 | 추가: Self::CancelAck { | |
| 383 | 추가: request_sequence, | |
| 384 | 추가: status, | |
| 385 | 추가: } => { | |
| 386 | 추가: request_sequence.enc(&mut e)?; | |
| 387 | 추가: status.enc(&mut e)?; | |
| 388 | 추가: 107 | |
| 389 | 추가: } | |
| 390 | 추가: }; | |
| 391 | 추가: Ok((kind, e.bytes)) | |
| 392 | 추가: } | |
| 393 | 추가: fn decode(kind: u16, b: &[u8]) -> io::Result<Self> { | |
| 394 | 추가: let mut d = Decoder { bytes: b, at: 0 }; | |
| 395 | 추가: let m = match kind { | |
| 396 | 추가: 1 => Self::Start(Wire::dec(&mut d)?), | |
| 397 | 추가: 2 => { | |
| 398 | 추가: let challenge_id = Wire::dec(&mut d)?; | |
| 399 | 추가: let secret = Secret(Vec::<u8>::dec(&mut d)?); | |
| 400 | 추가: if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() { | |
| 401 | 추가: return Err(invalid()); | |
| 402 | 추가: } | |
| 403 | 추가: Self::Password { | |
| 404 | 추가: challenge_id, | |
| 405 | 추가: secret, | |
| 406 | 추가: } | |
| 407 | 추가: } | |
| 408 | 추가: 3 => Self::Cancel, | |
| 409 | 추가: 100 => Self::Accepted { | |
| 410 | 추가: action: Wire::dec(&mut d)?, | |
| 411 | 추가: encryption: Wire::dec(&mut d)?, | |
| 412 | 추가: }, | |
| 413 | 추가: 101 => Self::Entry(Wire::dec(&mut d)?), | |
| 414 | 추가: 102 => Self::ListEnd { | |
| 415 | 추가: entry_count: Wire::dec(&mut d)?, | |
| 416 | 추가: list_id: Wire::dec(&mut d)?, | |
| 417 | 추가: }, | |
| 418 | 추가: 103 => Self::PasswordRequired { | |
| 419 | 추가: challenge_id: Wire::dec(&mut d)?, | |
| 420 | 추가: attempt: Wire::dec(&mut d)?, | |
| 421 | 추가: purpose: Wire::dec(&mut d)?, | |
| 422 | 추가: }, | |
| 423 | 추가: 104 => Self::Progress { | |
| 424 | 추가: stage: Wire::dec(&mut d)?, | |
| 425 | 추가: processed_bytes: Wire::dec(&mut d)?, | |
| 426 | 추가: total_bytes: Wire::dec(&mut d)?, | |
| 427 | 추가: completed_entries: Wire::dec(&mut d)?, | |
| 428 | 추가: }, | |
| 429 | 추가: 105 => Self::Output { | |
| 430 | 추가: entry_id: Wire::dec(&mut d)?, | |
| 431 | 추가: relative_name: Wire::dec(&mut d)?, | |
| 432 | 추가: disposition: Wire::dec(&mut d)?, | |
| 433 | 추가: }, | |
| 434 | 추가: 106 => { | |
| 435 | 추가: let t = Terminal::dec(&mut d)?; | |
| 436 | 추가: if t.detail.len() > 4096 { | |
| 437 | 추가: return Err(invalid()); | |
| 438 | 추가: } | |
| 439 | 추가: Self::Terminal(t) | |
| 440 | 추가: } | |
| 441 | 추가: 107 => Self::CancelAck { | |
| 442 | 추가: request_sequence: Wire::dec(&mut d)?, | |
| 443 | 추가: status: Wire::dec(&mut d)?, | |
| 444 | 추가: }, | |
| 445 | 추가: _ => return Err(invalid()), | |
| 446 | 추가: }; | |
| 447 | 추가: if d.at != b.len() { | |
| 448 | 추가: return Err(invalid()); | |
| 449 | 추가: } | |
| 450 | 추가: Ok(m) | |
| 451 | 추가: } | |
| 452 | 추가: } | |
| 453 | 추가: pub struct Reader<R> { | |
| 454 | 추가: input: R, | |
| 455 | 추가: sequence: u64, | |
| 456 | 추가: job: Option<u64>, | |
| 457 | 추가: terminal: bool, | |
| 458 | 추가: } | |
| 459 | 추가: impl<R: Read> Reader<R> { | |
| 460 | 추가: pub fn new(input: R) -> Self { | |
| 461 | 추가: Self { | |
| 462 | 추가: input, | |
| 463 | 추가: sequence: 0, | |
| 464 | 추가: job: None, | |
| 465 | 추가: terminal: false, | |
| 466 | 추가: } | |
| 467 | 추가: } | |
| 468 | 추가: pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> { | |
| 469 | 추가: let mut h = [0u8; 32]; | |
| 470 | 추가: loop { | |
| 471 | 추가: match self.input.read(&mut h[..1]) { | |
| 472 | 추가: Ok(0) => return Ok(None), | |
| 473 | 추가: Ok(_) => break, | |
| 474 | 추가: Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, | |
| 475 | 추가: Err(e) => return Err(e), | |
| 476 | 추가: } | |
| 477 | 추가: } | |
| 478 | 추가: if self.terminal { | |
| 479 | 추가: return Err(invalid()); | |
| 480 | 추가: } | |
| 481 | 추가: self.input.read_exact(&mut h[1..])?; | |
| 482 | 추가: let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize; | |
| 483 | 추가: let job = u64::from_le_bytes(h[16..24].try_into().unwrap()); | |
| 484 | 추가: let seq = u64::from_le_bytes(h[24..32].try_into().unwrap()); | |
| 485 | 추가: if &h[..4] != b"ZAW1" | |
| 486 | 추가: || h[4..6] != 1u16.to_le_bytes() | |
| 487 | 추가: || h[12..16] != [0; 4] | |
| 488 | 추가: || len > MAX_BODY | |
| 489 | 추가: || job == 0 | |
| 490 | 추가: || self.job.is_some_and(|j| j != job) | |
| 491 | 추가: || seq != self.sequence | |
| 492 | 추가: || seq >= MAX_FRAMES | |
| 493 | 추가: { | |
| 494 | 추가: return Err(invalid()); | |
| 495 | 추가: } | |
| 496 | 추가: self.job = Some(job); | |
| 497 | 추가: self.sequence += 1; | |
| 498 | 추가: let mut b = vec![0; len]; | |
| 499 | 추가: self.input.read_exact(&mut b)?; | |
| 500 | 추가: let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?; | |
| 501 | 추가: self.terminal = matches!(message, Message::Terminal(_)); | |
| 502 | 추가: Ok(Some((job, seq, message))) | |
| 503 | 추가: } | |
| 504 | 추가: } | |
| 505 | 추가: pub struct Writer<W> { | |
| 506 | 추가: output: W, | |
| 507 | 추가: sequence: u64, | |
| 508 | 추가: job: u64, | |
| 509 | 추가: terminal: bool, | |
| 510 | 추가: } | |
| 511 | 추가: impl<W: Write> Writer<W> { | |
| 512 | 추가: pub fn new(output: W, job: u64) -> Self { | |
| 513 | 추가: Self { | |
| 514 | 추가: output, | |
| 515 | 추가: sequence: 0, | |
| 516 | 추가: job, | |
| 517 | 추가: terminal: false, | |
| 518 | 추가: } | |
| 519 | 추가: } | |
| 520 | 추가: pub fn send(&mut self, m: &Message) -> io::Result<()> { | |
| 521 | 추가: if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES { | |
| 522 | 추가: return Err(invalid()); | |
| 523 | 추가: } | |
| 524 | 추가: let (kind, b) = m.encode()?; | |
| 525 | 추가: let mut h = Vec::with_capacity(32); | |
| 526 | 추가: h.extend(b"ZAW1"); | |
| 527 | 추가: h.extend(1u16.to_le_bytes()); | |
| 528 | 추가: h.extend(kind.to_le_bytes()); | |
| 529 | 추가: h.extend((b.len() as u32).to_le_bytes()); | |
| 530 | 추가: h.extend(0u32.to_le_bytes()); | |
| 531 | 추가: h.extend(self.job.to_le_bytes()); | |
| 532 | 추가: h.extend(self.sequence.to_le_bytes()); | |
| 533 | 추가: self.output.write_all(&h)?; | |
| 534 | 추가: self.output.write_all(&b)?; | |
| 535 | 추가: self.output.flush()?; | |
| 536 | 추가: self.sequence += 1; | |
| 537 | 추가: self.terminal = matches!(m, Message::Terminal(_)); | |
| 538 | 추가: Ok(()) | |
| 539 | 추가: } | |
| 540 | 추가: } |
| @@ -0,0 +1 @@ | ||
| 1 | 추가: /runs/ |
바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기| @@ -0,0 +1,43 @@ | ||
| 1 | 추가: import gzip | |
| 2 | 추가: from io import BytesIO | |
| 3 | 추가: from pathlib import Path | |
| 4 | 추가: import tarfile | |
| 5 | 추가: import zipfile | |
| 6 | 추가: | |
| 7 | 추가: root = Path(__file__).resolve().parent / "fixtures" | |
| 8 | 추가: root.mkdir(exist_ok=True) | |
| 9 | 추가: payload = b"Zipelo worker interoperability\n" | |
| 10 | 추가: for method, label in ((zipfile.ZIP_STORED, "store"), (zipfile.ZIP_DEFLATED, "deflate")): | |
| 11 | 추가: with zipfile.ZipFile(root / f"{label}.zip", "w", compression=method) as archive: | |
| 12 | 추가: archive.writestr("folder/hello.txt", payload) | |
| 13 | 추가: archive.writestr("empty/", b"") | |
| 14 | 추가: for name in ("../escape.txt", "/absolute.txt", "C:/drive.txt", "CON.txt"): | |
| 15 | 추가: label = {"../escape.txt": "traversal", "/absolute.txt": "absolute", "C:/drive.txt": "drive", "CON.txt": "reserved"}[name] | |
| 16 | 추가: with zipfile.ZipFile(root / f"{label}.zip", "w") as archive: | |
| 17 | 추가: archive.writestr(name, payload) | |
| 18 | 추가: with zipfile.ZipFile(root / "link.zip", "w") as archive: | |
| 19 | 추가: entry = zipfile.ZipInfo("link") | |
| 20 | 추가: entry.create_system = 3 | |
| 21 | 추가: entry.external_attr = 0o120777 << 16 | |
| 22 | 추가: archive.writestr(entry, "../outside") | |
| 23 | 추가: with zipfile.ZipFile(root / "bomb.zip", "w", compression=zipfile.ZIP_DEFLATED) as archive: | |
| 24 | 추가: archive.writestr("bomb.txt", b"0" * 1048576) | |
| 25 | 추가: with zipfile.ZipFile(root / "collision.zip", "w") as archive: | |
| 26 | 추가: archive.writestr("A.txt", b"first") | |
| 27 | 추가: archive.writestr("a.txt", b"second") | |
| 28 | 추가: with zipfile.ZipFile(root / "parent-collision.zip", "w") as archive: | |
| 29 | 추가: archive.writestr("a", b"file") | |
| 30 | 추가: archive.writestr("a/b.txt", b"nested") | |
| 31 | 추가: stream = BytesIO() | |
| 32 | 추가: with tarfile.open(fileobj=stream, mode="w", format=tarfile.USTAR_FORMAT) as archive: | |
| 33 | 추가: entry = tarfile.TarInfo("folder/hello.txt") | |
| 34 | 추가: entry.size = len(payload) | |
| 35 | 추가: archive.addfile(entry, BytesIO(payload)) | |
| 36 | 추가: tar = stream.getvalue() | |
| 37 | 추가: (root / "sample.tar").write_bytes(tar) | |
| 38 | 추가: (root / "sample.tar.gz").write_bytes(gzip.compress(tar, mtime=0)) | |
| 39 | 추가: stream = BytesIO() | |
| 40 | 추가: with gzip.GzipFile(filename="../../untrusted-name", fileobj=stream, mode="wb", mtime=0) as archive: | |
| 41 | 추가: archive.write(payload) | |
| 42 | 추가: (root / "sample.gz").write_bytes(stream.getvalue()) | |
| 43 | 추가: (root / "concat.gz").write_bytes(gzip.compress(b"one", mtime=0) + gzip.compress(b"two", mtime=0)) |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기