분리된 ZIP 작업자와 안전 게시 경로를 추가함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
9d8182a5c6c99ab3aba7fe873b4ddd7d5b8d2c93- 부모
- ee76385
변경된 파일 22개
+2,264-0| @@ -0,0 +1,138 @@ | ||
| 1 | 추가: # 엔진 검토와 백엔드 기반 상태 | |
| 2 | 추가: | |
| 3 | 추가: ## 적용 범위 | |
| 4 | 추가: | |
| 5 | 추가: Zipelo 자체 코드는 MIT 방침이다. 외부 엔진은 아직 채택하지 않았으며 엔진 파일이나 패키지를 프로젝트에 추가하지 않았다. 암호화 RAR와 구형 솔리드 RAR는 검증 중이며 제품 미지원으로 확정하지 않는다. | |
| 6 | 추가: | |
| 7 | 추가: 이번 기록은 SharpCompress 0.50.7의 소스, 패키징 설정과 공개 패키지 목록 및 고지를 대조하고 unar/XADMaster의 공식 소스와 Windows 배포 근거를 추가 확인한 결과다. 최신 버전이나 바이너리 실행 검증 완료를 의미하지 않는다. | |
| 8 | 추가: | |
| 9 | 추가: ## SharpCompress 0.50.7 | |
| 10 | 추가: | |
| 11 | 추가: ### 공개 패키지 실물 확인 | |
| 12 | 추가: | |
| 13 | 추가: 2026-11-09에 [공식 NuGet 패키지](https://api.nuget.org/v3-flatcontainer/sharpcompress/0.50.7/sharpcompress.0.50.7.nupkg)를 메모리로 내려받아 ZIP 항목 목록과 nuspec, README만 읽었다. 디스크에 저장하거나 압축을 풀지 않았고 DLL 로드, 설치와 코드 실행은 하지 않았다. | |
| 14 | 추가: | |
| 15 | 추가: - 크기: 6,702,991바이트. | |
| 16 | 추가: - SHA-256: `115f4157740c6690b0315d3dea7fa900e9eaccd395b4cee8019c1fbbf94923de`. | |
| 17 | 추가: - 항목은 12개다. `_rels/.rels`, `SharpCompress.nuspec`, `README.md`, `[Content_Types].xml`, `package/services/metadata/core-properties/nuget.psmdcp`, `.signature.p7s`와 아래 DLL 6개다. | |
| 18 | 추가: - DLL 경로는 `lib/{net10.0,net48,net6.0,net8.0,netstandard2.0,netstandard2.1}/SharpCompress.dll`이다. | |
| 19 | 추가: - 별도 `LICENSE.txt`, NOTICE, C# 소스, `reference/unrar` 또는 네이티브 unrar DLL은 항목 목록에 없다. DLL 내부의 포함 디버그 정보와 소스는 조사하지 않았으므로 바이너리에 관련 구현이 없다는 의미는 아니다. | |
| 20 | 추가: - 서명 파일은 존재하지만 인증서 신뢰 체인이나 패키지 서명을 검증하지 않았다. 위 해시는 이번에 읽은 바이트를 식별하며 진위 검증 완료를 뜻하지 않는다. | |
| 21 | 추가: | |
| 22 | 추가: nuspec은 버전 0.50.7, MIT license expression, Adam Hathcock의 2025년 저작권, 저장소 커밋 `b4af8afe6683d019d504954a3b4e4f18b06e2cd6`을 기록한다. [0.50.7 태그의 커밋](https://github.com/adamhathcock/sharpcompress/commit/b4af8afe6683d019d504954a3b4e4f18b06e2cd6)과 이 값이 일치한다. 메타데이터의 소스 연결은 확인했지만 재현 빌드로 DLL 동일성을 검증하지 않았다. 최신 버전이라는 의미도 아니다. | |
| 23 | 추가: | |
| 24 | 추가: ### 패키징과 고지 | |
| 25 | 추가: | |
| 26 | 추가: [프로젝트 설정](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/SharpCompress.csproj)은 같은 대상 프레임워크 6개와 MIT를 선언하고 README를 패키지 루트에 추가한다. [Directory.Build.props](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/Directory.Build.props), [배포 워크플로](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/.github/workflows/nuget-release.yml), [빌드 프로그램](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/build/Program.cs)의 pack 대상도 해당 C# 프로젝트다. 읽은 설정에 reference/unrar의 C++ 프로젝트를 빌드하거나 패키지에 넣는 경로는 없다. DLL의 embedded debug 설정이 있어 외부 파일 목록만으로 내부 정보를 모두 판단하면 안 된다. | |
| 27 | 추가: | |
| 28 | 추가: 실물 nuspec에서 net6.0, net8.0, net10.0은 외부 패키지 의존성이 없다. net48, netstandard2.0, netstandard2.1은 Microsoft.Bcl.AsyncInterfaces와 System.Text.Encoding.CodePages 8.0.0 이상을 요구한다. Zipelo의 현재 net10.0 가정에서는 이 구형 대상 의존성이 선택되지 않는다. 구형 대상으로 바꾸면 실제 해결된 버전과 전이 의존성의 라이선스를 별도 확인해야 한다. 이번에는 의존 패키지를 다운로드하거나 고지 전체를 감사하지 않았다. | |
| 29 | 추가: | |
| 30 | 추가: 실물 README에는 XZ.NET, managed-lzma, ZstdSharp의 출처와 Bouncy Castle 저작권 및 허가 고지가 들어 있다. [태그 README](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/README.md)에서도 이 내용을 확인했다. [루트 LICENSE.txt](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/LICENSE.txt)는 Adam Hathcock의 2014년 MIT 고지다. nuspec의 MIT 링크만으로 저작권자별 고지를 대체하지 말고, 배포 채택 시 적용되는 원문과 포함 코드별 고지를 함께 보존해야 한다. 이 README의 출처 목록을 완전한 구성요소 목록으로 간주하지 않는다. | |
| 31 | 추가: | |
| 32 | 추가: ### RAR 구현 출처에서 새로 확인한 근거 | |
| 33 | 추가: | |
| 34 | 추가: 중요한 추가 발견은 제한 표기가 참고 자료 밖의 실제 C# 소스에도 있다는 점이다. | |
| 35 | 추가: | |
| 36 | 추가: - [UnpackV1/Unpack15.cs 1~8행](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack15.cs#L1-L8)과 [Unpack20.cs 1~8행](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Compressors/Rar/UnpackV1/Unpack20.cs#L1-L8)은 innoSysTec, Edmund Wagner의 출처를 적고 junrar 소스와 바이너리에 unrar 라이선스가 적용되며 RAR 압축 알고리즘 재구현에 사용하지 못한다고 명시한다. | |
| 37 | 추가: - 해당 파일은 C# 프로젝트 디렉터리 아래의 partial Unpack 구현이다. 읽은 프로젝트 설정에는 이 파일의 컴파일 제외가 없으며, [RarReader.cs](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Readers/Rar/RarReader.cs#L19-L21)는 UnpackV1과 UnpackV2017을 생성한다. 같은 파일 128~140행은 RAR 종류에 따라 두 구현으로 연결한다. 따라서 참고 파일이 우연히 저장소에 있다는 우려보다 구체적인 근거가 있다. 실제 컴파일과 역어셈블 검증은 하지 않았다. | |
| 38 | 추가: - [UnpackV2017/notes.txt](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Compressors/Rar/UnpackV2017/notes.txt)는 C에서 C#으로의 자료형 대응을 기록한다. [Unpack.unpack_cpp.cs](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Compressors/Rar/UnpackV2017/Unpack.unpack_cpp.cs)와 [reference/unrar/unpack.cpp](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/reference/unrar/unpack.cpp)의 생성자와 Init 부분에는 같은 초기화 순서, 분기와 주석이 확인된다. 이식 관계를 뒷받침하는 정황이지만 어느 커밋에서 어떤 허가로 이식했는지까지 입증하지는 않는다. | |
| 39 | 추가: - [reference/unrar/license.txt](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/reference/unrar/license.txt)는 RAR 압축 알고리즘 재구현 금지와 수정 소스 재배포 고지 조건을 포함한다. 상업적 사용 자체를 금지하는 조건과는 구분해야 한다. | |
| 40 | 추가: | |
| 41 | 추가: 판단: reference/unrar 원본 파일은 확인한 NuGet 패키지 목록에 없지만, 이를 근거로 실제 RAR 구현과 무관한 단순 참고 자료라고 단정할 수 없다. 루트 MIT 선언과 개별 구현의 추가 제한 표기 사이에 해결해야 할 불일치가 있다. 별도 재라이선스 허가, 권리자의 예외 허가 또는 제한 없는 재구현을 증명하는 근거는 이번 확인 범위에서 찾지 못했다. 반대로 이 표기만으로 SharpCompress 전체의 법적 조건이나 모든 파일의 권리를 단정하지 않는다. | |
| 42 | 추가: | |
| 43 | 추가: ### 기능과 채택 권고 | |
| 44 | 추가: | |
| 45 | 추가: [형식 문서](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/docs/FORMATS.md)와 [RAR Reader 테스트](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/tests/SharpCompress.Test/Rar/RarReaderTests.cs)에는 RAR/RAR5 암호화 데이터와 헤더, 분할, 솔리드 사례가 있다. 솔리드는 Reader 경로를 요구한다. 테스트 존재를 확인했으며 실행하지 않았다. 암호화, 분할, 솔리드를 동시에 사용하는 모든 조합의 지원 근거로 확대하지 않는다. | |
| 46 | 추가: | |
| 47 | 추가: SharpCompress 0.50.7은 기능 검증 후보로 남기되, 사용 목적에 제한이 없는 배포물이라는 요구에 맞는 엔진으로 채택하지 않는 것이 현재 권고다. 제한 표기가 실제 구현에도 발견됐으므로 단순히 reference 디렉터리를 제외하거나 루트 MIT 고지만 넣는 방법으로 해결되었다고 판단하면 안 된다. | |
| 48 | 추가: | |
| 49 | 추가: 대안은 다음처럼 조건을 구분한다. | |
| 50 | 추가: | |
| 51 | 추가: - RAR를 제외한 7-Zip과 libarchive 조합은 기존 후보를 유지한다. [7-Zip 제외 빌드 설명](https://github.com/ip7z/7zip/blob/main/DOC/readme.txt)과 libarchive 3.8.11의 [RAR](https://github.com/libarchive/libarchive/blob/v3.8.11/libarchive/archive_read_support_format_rar.c), [RAR5](https://github.com/libarchive/libarchive/blob/v3.8.11/libarchive/archive_read_support_format_rar5.c) 검토 기준으로 암호화 RAR 공백이 있어 전체 요구 충족안은 아니다. 이번에 이 엔진들을 실행하거나 재감사하지 않았다. | |
| 52 | 추가: - 전체 7-Zip 구성은 암호화 RAR의 기술적 비교 대상이지만 unRAR 추가 제한이 있어 용도 제한 없는 배포 요구의 해결책으로 권고하지 않는다. 별도 프로세스나 선택 설치로 옮기는 것만으로 사용자 요구와 라이선스 문제가 해소되었다고 표시하지 않는다. | |
| 53 | 추가: - 암호화 RAR의 요구를 유지하려면 출처와 권리 관계가 입증된 구현을 확보하거나 다른 구현을 검증해야 한다. 이번 조사로 기능과 라이선스를 모두 충족한다고 확정할 대안은 확보하지 못했다. 외부 저자에게 연락하지 않았다. | |
| 54 | 추가: | |
| 55 | 추가: 다음 판단에 필요한 것은 이식 코드의 권리와 고지 근거, 최종 선택 바이너리와 소스의 대응 검증, 암호화/분할/솔리드 조합별 해시 비교 및 실패 동작, 자원과 취소 검증이다. 암호화 RAR를 제품 미지원으로 확정하지 않는다. 사용자에게 MIT를 다시 선택받을 필요도 없다. 요구를 충족할 근거가 확보되지 않은 상태에서 출시 범위를 줄이는 결정은 별도로 다뤄야 한다. | |
| 56 | 추가: | |
| 57 | 추가: ## unar/XADMaster 추가 검토 | |
| 58 | 추가: | |
| 59 | 추가: ### 확인 대상과 배포 상태 | |
| 60 | 추가: | |
| 61 | 추가: 2026-11-09에 공식 자료를 한 차례 추가 확인했다. 아래 기능과 개별 파일 고지는 [XADMaster v1.10.8](https://github.com/MacPaw/XADMaster/releases/tag/v1.10.8), 커밋 `881e0ec25e249c9ad5bbc1b6782ae8dcdf48a6ed` 기준이다. 조회한 공식 릴리스 목록에서 가장 최근 공개 릴리스는 2023-10-12의 v1.10.8이며 이 릴리스에는 업로드된 바이너리 자산이 없다. 이것을 공식 사이트의 Windows ZIP과 같은 버전이라고 간주하지 않는다. | |
| 62 | 추가: | |
| 63 | 추가: 유지보수 상태는 별도로 현재 master 커밋 `7cb9ee0abbb163f261e4cb74501e15067032319c`와 워크플로를 읽었다. 이 커밋은 2026-09-21의 저작권 표기 변경 병합이다. 저장소 활동이 있다는 사실과 Windows 제품의 유지보수 및 호환성이 입증됐다는 주장은 구분한다. [현재 소스 기준점](https://github.com/MacPaw/XADMaster/commit/7cb9ee0abbb163f261e4cb74501e15067032319c) | |
| 64 | 추가: | |
| 65 | 추가: ### RAR 기능 근거와 조합의 한계 | |
| 66 | 추가: | |
| 67 | 추가: 소스에 처리 경로가 있다는 판단이며 Zipelo나 Windows에서의 실행 통과를 뜻하지 않는다. | |
| 68 | 추가: | |
| 69 | 추가: - 구형 RAR 데이터 암호: [XADRARParser.m 766~785행](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADRARParser.m#L766)은 버전별 CryptHandle과 AES 입력을 선택한다. 헤더 암호는 같은 파일 473~484행의 `MHD_PASSWORD` 분기에서 AES 핸들로 블록을 읽는다. 올바른 암호가 필요하다. | |
| 70 | 추가: - 구형 RAR 분할과 솔리드: 같은 파일 130행 이후의 볼륨 이름 탐색, 753~769행의 조각 입력 결합, 723~741행의 솔리드 스트림 경로가 있다. 압축 버전 15, 20/26, 29/36을 각각 RAR15/20/30 핸들에 연결한다. 아주 오래된 별도 서명에는 미구현 TODO가 남아 있어 모든 역사적 RAR 형식을 보장하지 않는다. | |
| 71 | 추가: - RAR5 헤더 암호: [XADRAR5Parser.m 241~258행](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADRAR5Parser.m#L241)은 암호화 헤더에서 암호와 salt로 키를 만들고, 669~673행은 그 키와 IV로 헤더를 복호화한다. 파일 데이터 암호는 430~460행의 추가 필드와 831~848행의 AES 입력 경로로 처리한다. 암호화 버전이 0이 아니면 명시적으로 거부한다. | |
| 72 | 추가: - RAR5 분할과 솔리드: 같은 파일 101행 이후의 볼륨 탐색, 304~340행의 솔리드 스트림 축적, 819~834행의 RAR50 핸들 및 조각 입력 결합이 있다. v1.10.8 릴리스 설명에도 솔리드 RAR5 안의 디렉터리 처리 수정이 기록되어 있다. | |
| 73 | 추가: - 조합 위험: RAR5 `volumesForHandle`은 먼저 `isPartOfMultiVolume`을 호출한다. 613~658행의 `readMasterHeaderFromHandle`은 첫 블록이 Main이 아니면 빈 결과를 반환하고, 911~917행의 호출자는 이를 비분할로 판정한다. [테스트 107~110행](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADMasterTests/XADRAR5ParserTests.m#L107)도 첫 블록이 Encryption이면 비분할로 보는 것을 기대한다. 따라서 헤더 암호화 RAR5의 자동 조각 탐색에 공백이 있을 수 있다는 소스 기반 추론이다. 실제 샘플이나 명시적 다중 입력 경로로 재현하지 않았으므로 모든 입력 방식이 실패한다고 단정하지 않는다. | |
| 74 | 추가: - 확인한 [구형 RAR 테스트](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADMasterTests/RAR/XADRARParserTests.m)는 이름 파싱 중심이며 RAR5 테스트는 가변 정수, 분할 판별과 SFX 인식 중심이다. 이 두 파일은 데이터 암호, 헤더 암호, 분할, 솔리드의 전체 조합에 대한 추출 해시 검증 근거가 아니다. 테스트를 실행하지 않았다. | |
| 75 | 추가: | |
| 76 | 추가: ### 실제 빌드 대상의 고지 확인 | |
| 77 | 추가: | |
| 78 | 추가: 루트 [LICENSE](https://github.com/MacPaw/XADMaster/blob/v1.10.8/LICENSE)는 LGPL 2.1 원문이다. 루트 표기만 보지 않고 v1.10.8의 `XADRAR*.m`, `XADRAR*.h`, `RAR*.c`, `RAR*.h`에 해당하는 32개 파일의 고지와 제한 관련 문구를 확인했다. 모두 LGPL 2.1 또는 이후 버전의 고지를 포함하며, 이 범위에서 SharpCompress의 Unpack15/20과 같은 unRAR의 RAR 압축 알고리즘 재구현 금지 문구는 발견하지 못했다. [RAR15 구현](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADRAR15Handle.m#L1), [RAR30 구현](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADRAR30Handle.m#L1), [RAR50 구현](https://github.com/MacPaw/XADMaster/blob/v1.10.8/XADRAR50Handle.m#L1), [RAR 가상 머신](https://github.com/MacPaw/XADMaster/blob/v1.10.8/RARVirtualMachine.c#L1) | |
| 79 | 추가: | |
| 80 | 추가: [Makefile.common 105~117행과 181~183행](https://github.com/MacPaw/XADMaster/blob/v1.10.8/Makefile.common#L105)은 이 RAR 구현을 라이브러리 소스 목록에 넣는다. [Makefile.windows](https://github.com/MacPaw/XADMaster/blob/v1.10.8/Makefile.windows#L71)도 이 공통 목록을 포함한다. 따라서 확인한 고지는 참고 자료만의 고지가 아니라 빌드 대상 구현의 고지다. 다만 소스 목록과 실제 배포 바이너리의 동일성은 빌드나 역어셈블로 확인하지 않았다. | |
| 81 | 추가: | |
| 82 | 추가: 라이선스 감사가 완료됐다는 뜻은 아니다. 공통 목록에는 Crypto, PPMd, libxad 등도 있다. 예를 들어 [Crypto/aes.h](https://github.com/MacPaw/XADMaster/blob/v1.10.8/Crypto/aes.h#L1)는 Brian Gladman의 소스 및 바이너리 고지 유지 조건을, [Crypto/sha.c](https://github.com/MacPaw/XADMaster/blob/v1.10.8/Crypto/sha.c#L1)는 Aaron Gifford의 BSD 계열 고지와 보증 부인 및 홍보 시 이름 사용 제한을 포함한다. 이를 unRAR의 용도 제한과 혼동하지 않는다. 모든 포함 코드, UniversalDetector, GNUstep/Objective-C 런타임, zlib/bzip2와 배포 DLL의 버전별 고지를 전수 대조하지 않았다. 코드 이력 전체의 독립 구현 또는 권리 관계도 증명하지 않았다. | |
| 83 | 추가: | |
| 84 | 추가: 채택 시 Zipelo 자체 MIT와 외부 LGPL을 구분해야 한다. LGPL 적용 소스와 수정 내역, 원문 고지를 제공하고 링크 및 배포 방식에 맞는 교체나 재연결 조건을 충족해야 한다. 외부 코드를 MIT로 다시 표시하지 않는다. 고지 보존 의무가 있는 자유 라이선스와 사용 목적 자체를 제한하는 조항은 별개다. | |
| 85 | 추가: | |
| 86 | 추가: ### Windows 유지보수 판단 | |
| 87 | 추가: | |
| 88 | 추가: [공식 명령행 도구 안내](https://theunarchiver.com/command-line)는 Windows용 unar/lsar ZIP 링크를 제공하지만 Windows 버전이 오래되었다고 직접 적고 있다. 이 페이지는 macOS의 Cocotron 교차 컴파일을 설명한다. 반면 현재 저장소의 [Makefile.windows](https://github.com/MacPaw/XADMaster/blob/7cb9ee0abbb163f261e4cb74501e15067032319c/Makefile.windows)는 GCC, 고정 GNUstep 경로와 GNUstep 기반 링크 설정을 사용한다. 페이지의 바이너리 제작 방식과 저장소의 이 Makefile을 같은 배포 경로로 단정할 수 없다. | |
| 89 | 추가: | |
| 90 | 추가: - 해당 Makefile의 경로별 마지막 커밋은 [2012-10-29](https://github.com/MacPaw/XADMaster/commit/a0f05d6161efce36f06b17badf500dd03a149f8a)이며 libcrypto 의존 제거를 기록한다. 공식 웹페이지의 OpenSSL 설치 설명을 현재 모든 빌드의 필수 의존성으로 옮기면 부정확하다. | |
| 91 | 추가: - 현재 트리의 워크플로 네 개를 읽었다. [Linux 빌드](https://github.com/MacPaw/XADMaster/blob/7cb9ee0abbb163f261e4cb74501e15067032319c/.github/workflows/main.yml)와 [macOS 테스트](https://github.com/MacPaw/XADMaster/blob/7cb9ee0abbb163f261e4cb74501e15067032319c/.github/workflows/macos-tests.yml), Ubuntu 기반 CodeQL 및 big-endian 검사는 있으나 Windows 실행 작업은 확인하지 못했다. 워크플로 존재만 확인했으며 실행 결과를 검증하지 않았다. | |
| 92 | 추가: - 공식 Windows ZIP은 다운로드하지 않았다. 버전, x64 여부, 서명, 포함 DLL 고지, 소스 대응과 Windows 11 호환성은 미확인이다. 오래된 바이너리 링크나 Makefile의 존재만으로 유지보수되는 Windows x64 구성이 확보됐다고 판단하지 않는다. | |
| 93 | 추가: | |
| 94 | 추가: ### SharpCompress 제한 범위 보충 | |
| 95 | 추가: | |
| 96 | 추가: 앞에서 확인한 UnpackV1/Unpack15.cs와 Unpack20.cs는 구형 RAR 디코더의 partial 클래스다. [RarReader의 선택 경로](https://github.com/adamhathcock/sharpcompress/blob/0.50.7/src/SharpCompress/Readers/Rar/RarReader.cs#L128)는 `IsRarV3` 항목을 UnpackV1로, 나머지를 UnpackV2017로 보낸다. 일반 프로젝트에 두 구현이 포함되므로 RAR5만 사용하는 사용자 흐름으로 바꾸는 것과 제한 표기가 있는 소스를 바이너리에서 제거하는 것은 다르다. | |
| 97 | 추가: | |
| 98 | 추가: 직접 제한을 확인한 두 파일만으로 ZIP/7Z와 RAR5 전체의 법적 조건을 일괄 판정하지 않는다. 동시에 V2017에도 이식 정황이 있고 다른 공용 코드의 의존 관계와 권리 근거는 미확인이다. UnpackV1 또는 reference/unrar만 삭제한 빌드를 자유로운 구성이라고 추천할 근거는 없다. 제거 후 컴파일, 기능과 전체 포함 코드의 고지를 검증한 적도 없다. | |
| 99 | 추가: | |
| 100 | 추가: ### 조사 종료와 필요한 선택 | |
| 101 | 추가: | |
| 102 | 추가: 이번 추가 후보 조사는 여기서 마친다. XADMaster는 확인한 RAR 파일의 LGPL 고지와 기능 코드 측면에서 가능성이 있는 후보지만, 유지보수되는 Windows 배포 구성, 전체 의존성 고지와 암호화 조합 동작까지 검증된 채택안은 확보하지 못했다. 암호화 RAR가 자유 라이선스로 원천적으로 불가능하다는 결론도 아니다. | |
| 103 | 추가: | |
| 104 | 추가: 사용자의 결정이 필요한 절충안은 다음 세 가지다. 이번 기록에서 어느 것도 확정하지 않았다. | |
| 105 | 추가: | |
| 106 | 추가: 1. 자유 라이선스와 암호화 RAR 요구를 모두 유지하고, Windows 이식 및 유지보수, 의존성 감사와 조합별 실증에 추가 일정과 개발 범위를 배정한다. XADMaster는 이 경우의 기술 검증 후보이며 성공이나 소요 기간은 보장하지 않는다. | |
| 107 | 추가: 2. 자유 라이선스 구성을 우선 출시하고, 아직 검증되지 않은 암호화 RAR 및 구형 솔리드 RAR의 첫 출시 지원을 보류한다. 기존 요구 축소이므로 명시적 선택이 필요하며 지금 미지원으로 바꾸지 않는다. | |
| 108 | 추가: 3. 암호화 RAR 지원을 우선하여 unRAR 용도 제한이 있는 외부 구성요소의 포함을 허용한다. Zipelo 자체 MIT는 유지하되 배포물 전체가 용도 제한 없는 오픈소스라는 조건을 변경하는 선택이다. 해당 엔진의 실행, 보안과 배포 조건 검증은 별도로 남는다. | |
| 109 | 추가: | |
| 110 | 추가: 실제 수행은 공식 소스, 라이선스, 릴리스와 빌드 설정 열람 및 이 문서 수정뿐이다. 설치, 엔진 실행, Windows 빌드, 샘플 추출, 성능 및 취약점 적용성 검증, 외부 연락과 업로드는 하지 않았다. 기존 src/와 tests/를 수정하지 않았고 브랜치 전환, 커밋과 푸시도 하지 않았다. | |
| 111 | 추가: | |
| 112 | 추가: ## 코어 구현 경계 | |
| 113 | 추가: | |
| 114 | 추가: `src/Zipelo.Core`는 UI와 일치하는 .NET 10 대상이며 외부 패키지 참조가 없다. UI 파일과 빌드 시작점은 수정하지 않았다. | |
| 115 | 추가: | |
| 116 | 추가: | 구성 | 구현 내용 | 남은 제한 | | |
| 117 | 추가: | --- | --- | --- | | |
| 118 | 추가: | ArchiveJob | 단일 실행, 기능 조회, 읽기 전용 입력 요구, 오류 코드, 정리 후 종료 이벤트 | 실제 IPC와 별도 프로세스 실행 없음 | | |
| 119 | 추가: | EngineContext | 항목 메타데이터, 목록과 출력 상태 구분, 복사와 검증 콜백, 암호 사용 범위와 폐기 | 실제 압축 엔진 없음. 어댑터는 시작한 비동기 작업을 모두 기다려야 함 | | |
| 120 | 추가: | OutputPathPolicy | 절대 경로와 경로 이탈, ADS, 예약 이름, 끝의 점과 공백 차단 | 문자열 검사만 구현. 실제 링크와 junction 및 경로 교체 경쟁 방어가 아님 | | |
| 121 | 추가: | JobBudget | 항목 수, 실제 처리 바이트, 출력 바이트, 경과 시간 누적 및 초과 상태 유지 | 메모리와 CPU 강제 제한 없음. 시간과 취소 검사는 협력 방식 | | |
| 122 | 추가: | IOutputTransaction | 임시 파일 생성, 게시, 정리 계약 | 안전한 Windows 저장 구현 없음. UnavailableOutput은 명시적 실패 | | |
| 123 | 추가: | |
| 124 | 추가: 출력은 임시 상태인 Staged와 게시 완료인 Extracted를 구분한다. CRC 또는 인증의 Passed, Failed, NotChecked, Unavailable은 출력 성공과 별개다. 검증 실패 또는 작업 오류 시 게시하지 않으며, 정리가 끝난 뒤 종료를 보고한다. 저장 계층은 원본과 기존 파일을 보존하고 작업 소유 임시 출력만 정리해야 한다. 코어 인터페이스만으로 파일시스템 안전성이 입증되지는 않는다. | |
| 125 | 추가: | |
| 126 | 추가: 입력은 호출자가 읽기 전용으로 열고 수명을 관리한다. 코어는 쓰기 가능한 입력 스트림을 거부한다. 다른 프로세스가 원본을 수정하는 문제까지 차단하지 않으므로 Windows 호스트의 공유 모드와 원본 해시 검증이 필요하다. 외부 엔진은 신뢰된 어댑터로 취급하며 인터페이스 자체가 샌드박스는 아니다. | |
| 127 | 추가: | |
| 128 | 추가: 목록 작업은 ListEntryAsync, 추출 작업은 WriteEntryAsync에 각 항목을 한 번 전달한다. 해제 결과를 복사한 바이트는 코어가 차감한다. 중간 TAR, 솔리드 선행 해제와 복구 재시도처럼 출력되지 않는 처리량은 엔진이 같은 Budget.ChargeProcessed에 보고해야 한다. 별도 프로세스 감독자가 비협력 엔진의 시간 초과, 메모리 초과와 취소를 강제하는 구현은 후속 작업이다. | |
| 129 | 추가: | |
| 130 | 추가: 암호는 작업 ID와 요청 ID가 있는 콜백으로 요청하고 SecureString 수명을 코어가 관리한다. 콜백이 null을 반환하면 작업을 취소한다. 로그, 명령행, 환경변수와 영구 설정 경로는 만들지 않았다. 엔진이 암호를 복사하거나 메모리에 남기는 문제까지 해결되었다는 의미는 아니다. | |
| 131 | 추가: | |
| 132 | 추가: ## 검증과 연동 | |
| 133 | 추가: | |
| 134 | 추가: - `dotnet build src/Zipelo.Core/Zipelo.Core.csproj -c Release`는 dotnet 명령 부재로 종료 코드 127을 반환했다. 컴파일 성공으로 보고하지 않는다. | |
| 135 | 추가: - 소스 검토와 프로젝트 XML 및 공백 검사를 수행했다. 7개 작성 파일에서 공백 및 지정 금지 문자 문제를 발견하지 않았다. 실제 C# 실행, 회귀 테스트, 엔진 샘플, Windows 파일시스템 검증은 미실행이다. | |
| 136 | 추가: - 테스트 코드는 프로젝트 루트 tests/에만 추가한다. 회귀 담당자는 경로 거부, 대소문자 및 상하위 출력 충돌, 예산 경계와 초과 후 재시도, 암호 취소와 횟수 제한, 검증 실패 시 미게시, 정리 실패 결과를 검증할 수 있다. | |
| 137 | 추가: - UI의 IArchiveWorkspace와 코어 계약은 아직 연결되지 않았다. UI 어댑터는 오류 코드와 항목별 검증 상태를 보존하고, 엔진 및 안전한 출력 저장 계층이 없으면 사용 가능으로 표시하지 않아야 한다. | |
| 138 | 추가: - 공유 브랜치 docs/initial-project-plan은 보존했다. 구현 변경을 features/ 계열 브랜치로 분리하는 작업은 공유 작업자와 조율 후 수행해야 한다. 커밋이나 외부 게시를 하지 않았다. |
| @@ -0,0 +1,76 @@ | ||
| 1 | 추가: # 비암호화 ZIP 해제와 새 폴더 게시 | |
| 2 | 추가: | |
| 3 | 추가: ## 상태 | |
| 4 | 추가: | |
| 5 | 추가: 메모리 해제와 Windows/Linux x64 새 폴더 게시 소스를 작성함. NewFolderPublisher의 구현 진입점은 연결했지만 일반 UI의 SupportsSafeExtraction=false와 Extract capability 미노출은 유지함. 로컬 .NET SDK가 없어 이번 C# 컴파일과 실제 게시 실행은 미검증임. 이전 Windows 62개 통과는 단일 ZIP 파일 게시에 관한 보고이며 새 폴더 게시의 증거가 아님. | |
| 6 | 추가: | |
| 7 | 추가: Windows는 로컬 NTFS와 아래 쓰기 ACL 조건에 한정함. Linux는 ext4/XFS, openat2/statx/renameat2와 아래 소유자/모드 조건에 한정함. Ubuntu 24.04/26.04 LTS의 실제 실행은 각각 별도 검증해야 함. 조건이 확인되지 않으면 OutputUnavailable로 실패하며 다른 경로 API로 우회하지 않음. | |
| 8 | 추가: | |
| 9 | 추가: ## UI와 검증 진입점 | |
| 10 | 추가: | |
| 11 | 추가: - ZipWorkerClient.ExtractAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token): 읽기 전용 스트림의 현재 위치부터 입력을 복사하고 별도 작업자에 전달함. 원본 스트림 수명은 호출자가 소유함. 입력 파일과 출력 디렉터리 경로를 작업자에게 전달하지 않음. | |
| 12 | 추가: - ZipWorkerResult의 기존 Job/CreatedZip 생성자와 기존 ListAsync/CreateAsync 계약을 유지함. 선택적 ExtractedEntries 속성을 추가함. 성공한 해제에서 CreatedZip=null, ExtractedEntries는 빈 배열 또는 ZipExtractedEntry(ArchiveEntry Entry, byte[] Content, uint Crc32) 목록임. 실패에서는 생성물과 해제 목록 모두 null임. | |
| 13 | 추가: - 메모리 해제 성공은 Job.State=Completed, Job.Error=None이며 각 항목은 Staged/Passed/None임. 이는 디스크에 저장 완료됐다는 뜻이 아님. ExtractedEntries와 Job.Entries는 같은 순서와 메타데이터를 가져야 함. 디렉터리 항목은 끝 슬래시를 제외한 이름, 길이 0, 빈 Content, CRC 0으로 전달함. | |
| 14 | 추가: - SupportsMemoryExtraction은 작업자 파일의 존재 여부만 표시함. 일반 UI 해제 활성화나 검증 완료 표시는 아님. 구버전 작업자는 실패 응답으로 처리되므로 앱과 작업자 산출물을 함께 배치해야 함. | |
| 15 | 추가: - NewFolderPublisher.PublishAsync(ZipWorkerResult result, string destinationPath, CancellationToken token): 사용자가 선택한 부모 아래 새 폴더의 전체 절대 경로를 받음. 예를 들어 선택 부모가 C:\output이고 새 이름이 result이면 C:\output\result를 전달함. 이미 있는 파일/폴더와 병합하거나 덮어쓰지 않음. 원본 ZIP 안의 문자열을 이 목적지로 사용하면 안 됨. | |
| 16 | 추가: - 반환형은 기존 ZipPublicationResult임. Published=true만 저장 완료이며 Error, CleanupFailed와 NativeFailure/CleanupNativeFailure를 분리해 표시함. CleanupFailed의 TemporaryFileName은 이번 작업이 만든 임시 폴더 이름임. 이름을 근거로 자동 재귀 삭제하면 안 됨. | |
| 17 | 추가: - NewFolderPublisher.IsSupportedPlatform은 Windows/Linux x64에서 true임. 구현 진입 가능 여부이며 대상 파일시스템, 권한 조건, 검증 완료 또는 일반 UI 활성화를 의미하지 않음. API 호출 때 지원 조건을 다시 검사함. | |
| 18 | 추가: - ZipPublicationResult에 선택적 PosixError/CleanupPosixError를 추가함. 각각 주 실패/정리 실패의 errno이며 경로를 포함하지 않음. 기존 Windows 진단 필드는 유지함. | |
| 19 | 추가: | |
| 20 | 추가: ## 형식과 무결성 | |
| 21 | 추가: | |
| 22 | 추가: 초기 지원은 ZIP32 단일 디스크의 저장(method 0)/Deflate(method 8), ASCII 또는 UTF-8 이름, 일반 파일과 디렉터리임. 암호, 분할, ZIP64, SFX/앞부분 데이터, 미해석 추가 필드, 다른 creator OS, Deflate64 등은 실패 폐쇄함. 확장 필드는 링크 의미가 없는 0x5455 타임스탬프만 무시하고 나머지는 거부함. Unix/ASi hardlink 메타데이터도 따라서 거부함. 형식 확대나 암호/복구의 최종 미지원을 결정한 것이 아님. | |
| 23 | 추가: | |
| 24 | 추가: 작업자는 중앙/로컬 헤더의 이름, 방식, 플래그, CRC와 크기 및 데이터 디스크립터를 대조함. 레코드의 범위를 검사하고 중복/겹침/간격을 거부함. 외부 속성의 symlink, FIFO 및 기타 특수 타입, reparse 속성을 거부함. 일반 파일과 디렉터리 이름은 현재 OS 정책으로 검사하며 전체 목록에서 중복, 파일-폴더 조상 충돌을 검사한 후 해제함. Windows에서는 대소문자만 다른 이름도 충돌임. Linux에서는 합법적 콜론, 역슬래시, CON 같은 이름과 대소문자를 보존함. Linux에서 역슬래시는 경로 구분자가 아님. | |
| 25 | 추가: | |
| 26 | 추가: .NET 10.0.0 ZipArchiveEntry의 GetDataDecompressor/OpenInReadModeGetDataCompressor 소스는 압축 범위와 헤더의 해제 크기를 디코더에 전달하고 CRC를 비교하지 않음. Crc32 속성은 기록된 필드이지 검증 결과가 아님. 따라서 해제에는 선언 길이 제한을 넘겨주지 않는 공개 DeflateStream을 사용하고 실제 EOF까지 읽어 길이와 CRC-32를 직접 비교함. 헤더 길이만 작게 바꾸고 CRC를 유지한 자료도 성공으로 처리하지 않음. | |
| 27 | 추가: | |
| 28 | 추가: 작업자 시작 때 System.IO.Compression.UseStrictValidation을 켜서 .NET 10 Deflate의 비어 있지 않은 미완성 입력을 거부함. 완전히 빈 Deflate 입력은 별도 거부함. 이 스위치의 동작은 아래 고정 버전 소스 근거이며 실제 런타임 업데이트 시 재검증해야 함. 검증 범위는 헤더 일관성, 디코딩한 실제 길이와 ZIP CRC임. CRC는 암호학적 진위 검증이 아니며 Deflate 내부의 모든 패딩/뒤따르는 비트의 정규형까지 검증한다고 주장하지 않음. | |
| 29 | 추가: | |
| 30 | 추가: 모든 항목이 통과할 때만 해제 목록을 전달함. 한 항목이라도 손상/예산/경로 검증에 실패하면 부분 성공이나 앞선 항목을 공개하지 않음. 호스트는 받은 메타데이터, 경로, CRC와 길이를 다시 확인하고 게시 시 바이트를 복사함. UI에서 ZIP 파싱이나 압축 해제를 수행하지 않음. 호출 중 DTO나 배열을 변경하지 않는 것이 호출자 계약임. | |
| 31 | 추가: | |
| 32 | 추가: ## 예산과 원본 보존 | |
| 33 | 추가: | |
| 34 | 추가: 입력 ZIP 16 MiB, 실제 해제 바이트 누적 16 MiB, 프레임 32 MiB, 아카이브 항목 1024개, 경로 깊이 32, 암묵적 디렉터리 포함 노드 4096개를 넘으면 실패함. JobLimits의 더 작은 한도도 적용함. JobBudget은 입력 ZIP 크기와 실제 해제 읽기량을 MaxProcessedBytes에 합산하며 실제 출력마다 MaxOutputBytes를 누적함. 파일별 한도가 전체 한도를 대체하지 않음. 이 수치는 개발 한도이며 대용량/경량성 보장이 아님. | |
| 35 | 추가: | |
| 36 | 추가: 부모는 입력에 쓰기나 자르기를 하지 않고 작업자는 복사된 메모리 입력만 읽음. 사용자 원본 경로를 출력 대상으로 다시 열지 않음. 외부 프로세스의 원본 변경을 감시하는 기능은 없으므로 호출자는 읽기 전용 파일 핸들과 적절한 공유 모드를 사용해야 함. 원본 해시 불변의 실제 증명은 담당 테스트의 실행 결과로 별도 기록해야 함. | |
| 37 | 추가: | |
| 38 | 추가: 파싱/해제 중 취소와 시간 초과는 기존 클라이언트의 프로세스 종료 확인을 거침. 게시 단계는 제한된 메모리 결과만 쓰며 각 쓰기/읽기와 최종 게시 직전에 취소를 확인함. 네이티브 파일 I/O의 강제 시간 제한, Job Object/cgroup 격리와 네트워크 차단은 여전히 없음. | |
| 39 | 추가: | |
| 40 | 추가: ## 위협 범위와 쓰기 경계 | |
| 41 | 추가: | |
| 42 | 추가: 악성 ZIP 경로/타입/링크, 기존 결과 충돌, 다른 계정의 경로 교체와 정상 동시 작업을 대상으로 함. 이미 실행 중인 같은 사용자 권한의 악성 프로그램, 관리자/SYSTEM/root, 커널 또는 파일시스템 자체의 침해는 방어한다고 주장하지 않음. 같은 사용자 프로그램은 이번 작업의 무작위 임시 트리에 들어가서 이름/내용/권한을 의도적으로 바꾸지 않아야 함. 정상 동시 게시 작업은 서로 다른 UUID 임시 이름을 쓰며 최종 이름 충돌은 OS의 덮어쓰기 금지 연산으로 결정함. | |
| 43 | 추가: | |
| 44 | 추가: 부모 핸들이 가리키는 디렉터리 객체를 선택 경계로 삼음. Linux에서 조상 경로가 이동해도 쓰기가 교체된 디렉터리로 전환되지 않음. 문자열 경로가 계속 같은 객체를 가리킨다는 보장은 없으며 외부 이동 후에는 사용자가 지정했던 텍스트 경로로 결과가 보이지 않을 수 있음. 기존 ACL/소유자/모드를 수정하거나 권한을 올리지 않음. | |
| 45 | 추가: | |
| 46 | 추가: ## Windows 게시 | |
| 47 | 추가: | |
| 48 | 추가: 드라이브 루트부터 부모까지 reparse를 거부하고 삭제 공유 없는 핸들로 고정함. 로컬 NTFS만 허용함. 임시 루트와 각 하위 노드는 보유 부모 핸들 상대 FILE_CREATE로 새로 생성하고 파일 ID, 타입, 링크 수, 소유자와 DACL을 읽음. 쓰기 가능한 SID는 현재 사용자, SYSTEM, Administrators만 허용함. 선택 부모도 생성 전 같은 ACL 검사를 통과해야 하며 소유자도 같은 집합에 속해야 함. NULL DACL, 해석하지 않는 ACE/조건부 ACE, 타 계정의 쓰기 허용은 실패 폐쇄함. 읽기 전용 ACE와 상속 전용 CREATOR OWNER는 허용하되 실제 생성된 각 노드를 다시 검사함. 부모에서 상속된 ACL을 변경하지 않으므로 공유 쓰기 폴더에서는 거부될 수 있음. | |
| 49 | 추가: | |
| 50 | 추가: 파일은 배타적 핸들에 쓴 뒤 flush, 길이와 전체 바이트 읽기 비교를 수행함. 최종 검증은 모든 핸들의 ID/ACL/타입과 각 디렉터리의 실제 자식 이름 집합을 대조함. 알 수 없는 항목이 있으면 게시하지 않음. 이름 열거만으로 원자적 보안을 보장하는 것이 아니라 외부 계정의 쓰기를 배제한 ACL 조건과 함께 사용함. | |
| 51 | 추가: | |
| 52 | 추가: NTFS는 열린 자식 파일이 있는 디렉터리 rename을 제한하므로 검증 후 자식 핸들을 닫고 루트 핸들만 유지함. 루트를 NtSetInformationFile(FileRenameInformation)로 동일 부모 아래 새 이름에 게시하며 ReplaceIfExists=false를 유지함. 실패 시 닫힌 자식은 보유 루트부터 상대적으로 다시 열고 저장된 파일 ID와 비교한 후에만 핸들 삭제를 수행함. 교체된 항목이나 모르는 항목은 삭제하지 않으며 정리 실패를 별도로 반환함. 기존 노드 병합, 경로 기반 재귀 삭제는 없음. | |
| 53 | 추가: | |
| 54 | 추가: ## Linux 게시 | |
| 55 | 추가: | |
| 56 | 추가: openat2(RESOLVE_NO_SYMLINKS)로 부모를 열고 fstatfs로 ext4/XFS를 확인함. 부모 소유자가 현재 euid이고 그룹/기타 쓰기가 없는 경우만 허용함. 다른 계정이 부모 항목을 교체할 수 있는 공용 디렉터리는 거부함. 새 임시 디렉터리는 mkdirat 0700, 파일은 openat2 O_CREAT|O_EXCL 0600으로 생성함. umask는 권한을 줄일 수 있지만 넓히지 않음. 이후 작업은 보유 디렉터리 fd 상대, RESOLVE_BENEATH|NO_SYMLINKS|NO_MAGICLINKS로 수행함. | |
| 57 | 추가: | |
| 58 | 추가: 각 노드의 statx 장치/ inode, 타입, uid/모드와 일반 파일 링크 수 1을 확인함. 쓰기/flush/전체 바이트 재읽기 뒤 getdents64 이름 집합을 비교하고 디렉터리 fsync 후 renameat2(RENAME_NOREPLACE)로 게시함. 루트 이름과 보유 inode의 일치를 게시 직전에 확인함. 파일시스템이 해당 연산을 지원하지 않으면 우회하지 않음. | |
| 59 | 추가: | |
| 60 | 추가: 정리는 소유 노드 목록의 역순으로 수행함. 부모 핸들, 이름과 inode를 다시 비교한 뒤 unlinkat하며 디렉터리는 AT_REMOVEDIR로 빈 경우만 제거함. compare/unlink 자체가 원자적이라는 주장은 하지 않음. 타 계정 쓰기가 배제된 부모와 0700 임시 트리가 안전 조건이며 같은 uid가 의도적으로 임시 트리를 바꾸는 상황은 범위 밖임. mkdirat 후 fd 확보에 실패하면 소유 inode가 확정되지 않으므로 임의로 이름을 삭제하지 않고 CleanupFailed를 반환함. | |
| 61 | 추가: | |
| 62 | 추가: ## 실제 검증과 남은 조건 | |
| 63 | 추가: | |
| 64 | 추가: 이번 변경은 소스 검토 단계임. 실제 C# 컴파일, Windows NTFS에서 자식 핸들 종료 후 rename과 충돌 뒤 재열기 정리, ACL 거부, 링크/경합/취소, Ubuntu 각 LTS ext4/XFS 실행은 미검증임. 테스트 담당자가 기존 실패 폐쇄 상태 검사와 차단된 8개 게시 사례를 새 조건에 맞춰 연결해야 함. 공개 capability나 일반 UI 해제를 활성화하지 않음. | |
| 65 | 추가: | |
| 66 | 추가: 강제 종료/전원 손실 시 임시 트리가 남을 수 있음. 게시 후 부모 디렉터리 fsync나 전원 장애 복구 트랜잭션까지 보장하지 않음. 실패 정리에서 모르는 노드, 변경된 ID 또는 OS 오류가 발견되면 기존 자료 보존을 우선해 잔존을 보고함. 네이티브 I/O의 강제 시간 제한과 실제 경합 검증도 남아 있음. | |
| 67 | 추가: | |
| 68 | 추가: 공식 근거: | |
| 69 | 추가: | |
| 70 | 추가: - [.NET 10.0.0 ZipArchiveEntry 소스](https://raw.githubusercontent.com/dotnet/runtime/v10.0.0/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs) | |
| 71 | 추가: - [.NET 10.0.0 DeflateStream 소스](https://raw.githubusercontent.com/dotnet/runtime/v10.0.0/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs) | |
| 72 | 추가: - [ZIP Crc32 속성](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.crc32?view=net-10.0) | |
| 73 | 추가: - [Native rename의 부모 핸들과 덮어쓰기 정책](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information) | |
| 74 | 추가: - [핸들 보안 설명자 읽기](https://learn.microsoft.com/en-us/windows/win32/api/aclapi/nf-aclapi-getsecurityinfo) | |
| 75 | 추가: - [Linux openat2 경계](https://man7.org/linux/man-pages/man2/openat2.2.html) | |
| 76 | 추가: - [Linux renameat2 덮어쓰기 금지](https://man7.org/linux/man-pages/man2/rename.2.html) |
| @@ -0,0 +1,83 @@ | ||
| 1 | 추가: # OS 정책과 단일 ZIP 게시 API | |
| 2 | 추가: | |
| 3 | 추가: ## 상태와 범위 | |
| 4 | 추가: | |
| 5 | 추가: Windows x64와 Ubuntu 24.04/26.04 LTS x64용 소스를 추가한 상태임. 담당자 보고 기준 2026-11-09T13:59:27.796888Z Windows 스냅샷은 빌드 경고/오류 0, C# 57/60 통과이며 게시 관련 3개가 실패함. 이후 아래 Windows 게시 수정은 로컬 SDK 부재로 컴파일과 실제 실행을 검증하지 못했음. Ubuntu 두 LTS에서의 C# 실행 검증도 남아 있음. | |
| 6 | 추가: | |
| 7 | 추가: 이 API는 사용자가 저장 대화상자에서 명시적으로 선택한 단일 새 파일에 이미 생성된 ZIP 바이트를 게시함. 임의 압축 항목을 경로별로 해제하는 출력 트랜잭션과 별개임. Extract capability, 안전한 해제, 미리보기와 복구는 계속 비활성임. IPC 메시지와 기존 ListAsync/CreateAsync 시그니처는 유지함. | |
| 8 | 추가: | |
| 9 | 추가: ## 파일명과 작업자 경로 | |
| 10 | 추가: | |
| 11 | 추가: Core의 `OutputPathPolicy.Validate(string, FileNamePolicy)` 오버로드와 `CurrentPolicy`, `Comparer`, `Comparison`을 추가함. 기존 단일 인수 Validate는 Windows 사전 정책을 유지하여 명시적 Windows 경로 검사의 호환성을 보존함. EngineContext와 ZIP 생성 어댑터는 현재 OS 정책을 명시적으로 사용함. | |
| 12 | 추가: | |
| 13 | 추가: - Windows: 기존 예약명, ADS, 끝의 공백/마침표, NFC와 금지 문자 검사를 유지함. 대소문자를 구분하지 않는 충돌 검사이며 대소문자만 다른 파일을 조용히 합치지 않고 오류로 반환함. Windows의 선택적 디렉터리별 대소문자 구분 기능은 아직 지원하지 않음. | |
| 14 | 추가: - Linux: 구분자는 슬래시만 사용함. 역슬래시, 콜론, 예약명처럼 보이는 이름, 끝 공백/마침표, 제어 문자와 비NFC 이름을 Windows 규칙으로 거부하거나 바꾸지 않음. 대소문자는 Ordinal로 구분하며 A와 a를 별도 항목으로 보존함. 절대 경로, 빈 세그먼트, .과 .., NUL, 세그먼트당 UTF-8 255바이트 초과는 거부함. 잘못된 UTF-16과 비UTF-8 원시 파일명은 지원하지 않음. | |
| 15 | 추가: - 생성 항목명은 실행 OS의 정책을 사용함. Linux에서 합법적인 이름의 ZIP을 다른 OS에서도 같은 방식으로 해제할 수 있다는 보장은 아님. 목록 표시 이름은 안전한 출력 경로 승인을 뜻하지 않음. | |
| 16 | 추가: | |
| 17 | 추가: `WorkerPlatform.ExecutableName`은 Windows에서 Zipelo.Worker.exe, Linux에서 Zipelo.Worker임. `WorkerPlatform.GetWorkerPath(string applicationDirectory)`는 절대 앱 폴더 아래 worker 디렉터리를 사용함. 작업 디렉터리나 압축파일 폴더를 탐색하지 않음. UI 담당자는 각 프로젝트에서 이 진입점을 사용할 수 있음. Linux 실행 권한과 실제 배포 파일 배치는 설치/빌드 담당 범위이며 이 작업에서 권한을 변경하지 않음. | |
| 18 | 추가: | |
| 19 | 추가: ## 공개 API와 UI 연결 | |
| 20 | 추가: | |
| 21 | 추가: `Task<ZipPublicationResult> NewZipPublisher.PublishAsync(ZipWorkerResult result, string destinationPath, CancellationToken token)` | |
| 22 | 추가: | |
| 23 | 추가: `ZipPublicationResult(bool Published, ArchiveError Error, bool CleanupFailed, string? TemporaryFileName = null)` | |
| 24 | 추가: | |
| 25 | 추가: CreateAsync가 반환한 성공 결과와 사용자가 고른 절대 목적지를 전달함. 임의 생성한 DTO나 작업자가 제공한 경로를 사용자 선택으로 간주하지 않음. API는 생성 ZIP을 다시 파싱하거나 CRC 검증하지 않음. 성공 상태와 생성 바이트 유무, 16 MiB 한도를 확인함. 호출자는 배열을 호출 중 변경하지 않아야 하며 API는 첫 await 전에 복사본을 확보함. 원래 JobResult는 메모리 생성 결과로 유지하고 게시 결과를 별도로 UI에 반영함. | |
| 26 | 추가: | |
| 27 | 추가: Published=true일 때만 저장 완료를 표시함. 기존 파일, 기존 symlink, 기존 hardlink와 원본 입력 경로에 게시하면 덮어쓰지 않고 실패함. 별도의 출력 파일을 새 inode로 만들기 때문에 기존 입력 inode를 쓰기나 자르기로 열지 않음. 입력 파일 경로 자체를 API가 받거나 원본의 외부 변경을 감시하는 것은 아님. | |
| 28 | 추가: | |
| 29 | 추가: Published=false이면 Error를 표시함. CleanupFailed=true이면 일반 실패와 별도로 임시 파일 정리 실패를 알려야 함. Windows에서 제공되는 TemporaryFileName은 원래 선택한 부모 폴더 내 작업 소유 임시 이름임. 임의 경로 재삭제를 자동 시도하지 않음. 늦은 취소가 실제 게시 성공을 취소로 바꾸지 않으므로 결과의 Published를 우선함. | |
| 30 | 추가: | |
| 31 | 추가: `NewZipPublisher.IsSupportedPlatform`과 클라이언트의 `SupportsFilePublication`은 Windows/Linux x64 구현 경로가 있다는 뜻임. 해당 LTS, 파일시스템 또는 앱 배포물에서 검증 완료라는 뜻이 아니며 필요한 네이티브 기능이 없으면 호출이 실패함. UI 활성화 전 해당 플랫폼의 빌드와 저장 회귀 검증이 필요함. | |
| 32 | 추가: | |
| 33 | 추가: ## Windows 구현 | |
| 34 | 추가: | |
| 35 | 추가: 로컬 고정/이동식 드라이브의 일반 절대 경로만 받음. UNC, 네트워크 드라이브와 사용자 지정 장치 경로는 실패함. 루트부터 각 디렉터리를 핸들로 열고 닫지 않은 상태로 유지함. 자식 열기는 NtCreateFile의 RootDirectory 상대 열기를 사용하고 reparse point를 따라가지 않으며 디렉터리 속성과 reparse 태그를 검사함. 디렉터리 핸들은 삭제 공유를 허용하지 않음. 문자열 검사 후 경로로 다시 파일을 여는 방식이 아님. | |
| 36 | 추가: | |
| 37 | 추가: 같은 부모 핸들 아래 .zipelo-UUID.tmp를 FILE_CREATE와 배타 공유로 생성함. 기존 파일을 열거나 덮어쓰는 disposition을 사용하지 않음. 데이터 쓰기와 FlushToDisk를 마친 뒤 NtSetInformationFile의 FileRenameInformation(10)을 적용하고 RootDirectory를 고정한 부모 핸들로 지정함. ReplaceIfExists=false로 목적지가 있으면 실패함. | |
| 38 | 추가: | |
| 39 | 추가: 게시 전 실패와 취소는 보유 임시 파일 핸들에 FileDispositionInfo를 설정하고 닫아 제거함. 정리 실패는 CleanupFailed로 보고함. 프로세스 강제 종료나 전원 손실에서는 이름 있는 임시 파일이 남을 수 있으며 자동 복구/청소는 아직 없음. 디스크 전체의 전원 손실 내구성이나 디렉터리 메타데이터까지 flush한 트랜잭션을 약속하지 않음. | |
| 40 | 추가: | |
| 41 | 추가: junction, symlink, 부모 교체, 기존 목적지, 공유 위반, FAT/NTFS/ReFS 차이와 네이티브 구조체 배치는 Windows에서 실제 검증해야 함. 구현이 있다는 이유만으로 이 시험을 통과했다고 표시하지 않음. | |
| 42 | 추가: | |
| 43 | 추가: ## Linux 구현 | |
| 44 | 추가: | |
| 45 | 추가: x64 openat2를 RESOLVE_NO_SYMLINKS로 호출하여 모든 부모 경로의 symlink/magic link를 거부하고 선택된 디렉터리를 고정함. 디렉터리 fd 아래 O_TMPFILE로 이름 없는 파일을 생성하고 0600 이하 권한을 사용함. 기존 권한이나 보안 설정을 바꾸지 않음. 데이터 쓰기와 파일 fsync 후 커널 procfs의 /proc/self/fd/N을 linkat으로 같은 디렉터리 fd의 최종 이름에 연결함. 목적지가 존재하면 EEXIST로 실패하며 그 링크를 따라가지 않음. | |
| 46 | 추가: | |
| 47 | 추가: openat2, O_TMPFILE, linkat 또는 procfs가 없는 환경과 파일시스템에서는 실패함. 이름 있는 임시 파일이나 단순 File.Move 방식으로 우회하지 않음. 게시 전 실패/취소/프로세스 종료는 이름 없는 inode의 마지막 fd가 닫히면서 제거됨. 게시 성공 후에는 늦은 취소로 삭제하지 않음. | |
| 48 | 추가: | |
| 49 | 추가: fd를 연 뒤 부모 경로가 교체되더라도 새 경로로 다시 찾아가서 쓰지 않음. Linux는 열린 디렉터리의 이름 변경 자체를 막지 않으므로 게시 위치는 처음 고정한 디렉터리 inode임. 다른 프로세스가 그 폴더를 이동했다면 원래 경로 문자열과 현재 위치가 달라질 수 있음. API는 이 경우 원래 경로 문자열에 저장됐다고 보장하지 않음. 임의 마운트 변경 권한을 가진 공격자나 파일시스템 구현 자체의 악성 동작까지 격리하는 보안 경계는 아님. | |
| 50 | 추가: | |
| 51 | 추가: 링크 생성 뒤 부모 디렉터리 fsync는 수행하지 않으므로 정전 후 파일명의 영속성까지 보장하지 않음. 각 LTS의 기본 파일시스템에서 정상 게시, symlink 부모/목적지, hardlink 목적지, 경로 교체, 취소와 미지원 파일시스템을 별도로 검증해야 함. | |
| 52 | 추가: | |
| 53 | 추가: ## 자원 제한과 미완성 | |
| 54 | 추가: | |
| 55 | 추가: 기존 작업자의 16 MiB 입력/생성물, 32 MiB 프레임, 항목 수, 작업 시간 제한은 유지함. 게시 과정은 생성물을 한 번 더 메모리에 복사하고 파일에 씀. 총 프로세스 메모리 상한이나 OS 수준 CPU/메모리 격리는 아님. Windows Job Object/제한 토큰, Linux rlimit/cgroup/seccomp와 네트워크 차단은 미구현임. 작업자와 게시 API 모두 현재 사용자 권한에서 실행함. | |
| 56 | 추가: | |
| 57 | 추가: 게시 취소는 쓰기 사이와 최종 게시 직전에 검사함. 네이티브 open, flush, rename/link 호출을 강제 중단하는 별도 프로세스는 없으므로 OS I/O가 멈추면 즉시 취소 완료를 보장하지 않음. UI는 await 종료 전에 저장 작업을 취소 완료로 표시하면 안 됨. | |
| 58 | 추가: | |
| 59 | 추가: ## 검증 근거와 연결 자료 | |
| 60 | 추가: | |
| 61 | 추가: 이 라운드에서는 소스 열람, 프로젝트/문서 정합성 확인만 수행함. UI와 tests는 수정하지 않음. 회귀 담당자가 검증할 정확한 대상은 OS별 Validate 오버로드, EngineContext 충돌 비교, WorkerPlatform 경로와 PublishAsync임. 기존 Windows 전용 테스트를 Linux 정책의 정답으로 사용하지 말고 정책 인수를 명시하거나 OS별 기대를 분리해야 함. | |
| 62 | 추가: | |
| 63 | 추가: 공식 API 근거: | |
| 64 | 추가: | |
| 65 | 추가: - [NtCreateFile의 상대 디렉터리 핸들과 생성 disposition](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile) | |
| 66 | 추가: - [FILE_RENAME_INFO의 RootDirectory와 ReplaceIfExists](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_rename_info) | |
| 67 | 추가: - [FILE_DISPOSITION_INFO](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_disposition_info) | |
| 68 | 추가: - [openat2의 심볼릭 링크 거부](https://man7.org/linux/man-pages/man2/openat2.2.html) | |
| 69 | 추가: - [O_TMPFILE과 fd 기반 linkat 게시](https://man7.org/linux/man-pages/man2/open.2.html) | |
| 70 | 추가: - [RandomAccess.FlushToDisk](https://learn.microsoft.com/en-us/dotnet/api/system.io.randomaccess.flushtodisk?view=net-10.0) | |
| 71 | 추가: | |
| 72 | 추가: ## Windows 게시 실패 수정과 재검증 대기 | |
| 73 | 추가: | |
| 74 | 추가: 2026-11-09T13:59:27.796888Z 스냅샷의 Windows 실행 결과는 담당자 보고 기준 C# 60개 중 57개 통과, 게시 관련 3개 실패임. 임시 파일 쓰기와 flush 이후 Win32 SetFileInformationByHandle 게시가 실패했으며, 실패 후 임시 파일 제거와 기존 sentinel 보존은 확인됐다고 보고됨. 당시 Win32 오류 숫자가 보존되지 않아 특정 원인을 확정할 수 없음. | |
| 75 | 추가: | |
| 76 | 추가: 수정은 Win32 게시 호출을 부모 핸들 상대 이름 계약이 명시된 NtSetInformationFile로 바꾸는 것임. Win32 FileRenameInfo(3)와 Native FileRenameInformation(10)을 혼용하지 않음. FILE_RENAME_INFORMATION은 x64에서 Flags=0, RootDirectory=8, FileNameLength=16, FileName=20 바이트 오프셋이며 구조체 크기 24바이트임. 버퍼는 구조체 크기와 UTF-16 이름 바이트 수를 더해 할당하고 0으로 초기화함. 이름 길이는 종료 NUL을 제외하며 이름 뒤 공간도 0임. DELETE 권한, 동기 파일 핸들, 부모의 traverse/read-attributes 권한, 삭제 공유 금지, reparse 검사와 덮어쓰기 금지를 유지함. 경로 문자열로 다시 열거나 절대 경로로 게시하는 fallback은 없음. | |
| 77 | 추가: | |
| 78 | 추가: 기존 ZipPublicationResult 생성자와 deconstruction은 유지하고 NativeFailure 및 CleanupNativeFailure init 속성을 추가함. PublicationNativeFailure는 고정 Operation 문자열, uint Win32Error, 선택적 int NtStatus만 포함함. NT 호출은 반환 상태를 즉시 보존하고 RtlNtStatusToDosError로 변환함. Win32 호출은 실패 직후 GetLastPInvokeError를 읽음. 주 실패와 정리 실패 진단을 분리하며 사용자 경로, 생성물, 비밀번호, OS 메시지는 넣지 않음. 80/183은 기존과 동일하게 OutputConflict이며 다른 네이티브 실패는 OutputUnavailable임. UI가 새 속성을 사용하지 않아도 기존 Error 및 CleanupFailed 처리는 유지됨. | |
| 79 | 추가: | |
| 80 | 추가: 이 수정은 로컬 SDK 부재로 C# 컴파일과 Windows 실행을 하지 못했음. 원인이 확정되거나 게시가 통과했다고 표시하지 않음. 재검증에서 새 파일의 정확한 바이트, 기존 파일/원본/최종 링크 충돌 보존, 부모 링크 거부, 실패/취소 정리와 네이티브 오류 진단을 확인해야 함. Ubuntu 코드는 변경하지 않았고 Ubuntu 각 LTS 실행 검증도 별도로 남아 있음. 생성 UI의 일반 배포 활성화와 해제 비활성 정책은 유지함. | |
| 81 | 추가: | |
| 82 | 추가: - [Native rename의 부모 핸들, DELETE 권한과 버퍼 계약](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information) | |
| 83 | 추가: - [NtSetInformationFile의 정보 클래스와 NTSTATUS 반환](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationfile) |
| @@ -0,0 +1,65 @@ | ||
| 1 | 추가: # 기본 ZIP 작업자와 런타임 | |
| 2 | 추가: | |
| 3 | 추가: ## 후속 OS 정책과 파일 게시 | |
| 4 | 추가: | |
| 5 | 추가: 이 문서의 최초 구현 이후 [OS 정책과 단일 ZIP 게시 API](ZIP_PUBLICATION.md)를 추가함. 현재 코드의 SupportsFilePublication은 Windows/Linux x64 게시 구현 여부를 반환하며, 기존의 항상 false 설명은 최초 구현 기록임. CreateAsync 자체는 계속 메모리 생성만 수행함. 실제 새 파일 저장은 별도 NewZipPublisher.PublishAsync가 담당하며 플랫폼별 실행 검증은 남아 있음. Extract는 계속 비활성임. | |
| 6 | 추가: | |
| 7 | 추가: ## 현재 범위 | |
| 8 | 추가: | |
| 9 | 추가: 외부 패키지 없이 .NET 10의 System.IO.Compression을 사용하는 초기 구현임. 기존 Core 공개 시그니처는 유지하며, 후속 변경에서 OS별 경로 정책을 분리함. 실제 C# 빌드와 실행 검증은 이 문서 작성 환경에서 하지 못했으며, 아래 동작은 구현된 코드의 계약임. 기존 29개 테스트의 Windows 통과 보고는 이번 새 작업자의 검증 결과가 아님. | |
| 10 | 추가: | |
| 11 | 추가: - `src/Zipelo.Runtime`: UI가 호출할 클라이언트와 길이가 제한된 IPC 프레임을 제공함. | |
| 12 | 추가: - `src/Zipelo.Worker`: 작업 한 건마다 별도 프로세스에서 ZIP 파싱과 생성을 수행함. UI는 ZipArchive를 실행하지 않음. | |
| 13 | 추가: - 목록은 ZIP 메타데이터만 읽으며 항목 ID를 중앙 디렉터리 순서로 생성함. 같은 이름의 항목도 ID로 구분함. 이름은 표시 데이터이며 안전한 출력 경로로 승인된 것이 아님. | |
| 14 | 추가: - 생성은 읽기 전용 입력 스트림과 명시한 항목 이름으로 실제 ZIP 바이트를 생성함. 폴더 재귀 탐색과 빈 폴더 생성은 없음. 빈 입력 목록은 거부함. | |
| 15 | 추가: - 생성물은 메모리에만 존재함. 디스크에 ZIP 파일을 저장한 결과가 아니며, UI에서 저장 완료로 표시하면 안 됨. | |
| 16 | 추가: - 추출, 검증, 복구, 미리보기, 암호화와 분할 생성은 지원 능력에 포함하지 않음. 이 초기 구현의 범위이며 제품 전체의 최종 지원 범위를 줄이는 결정이 아님. | |
| 17 | 추가: | |
| 18 | 추가: ## UI 진입점 | |
| 19 | 추가: | |
| 20 | 추가: `Zipelo.Runtime.ZipWorkerClient(string workerPath, string? dotnetHostPath = null)`을 사용함. 작업자와 선택적인 dotnet 호스트 경로는 모두 앱이 정한 신뢰할 수 있는 절대 경로여야 함. 압축파일 내용이나 사용자 입력을 실행 파일 경로로 사용하지 않음. | |
| 21 | 추가: | |
| 22 | 추가: apphost 예시는 앱 폴더 아래 `worker/Zipelo.Worker.exe`임. DLL 방식은 `Zipelo.Worker.dll`과 설치된 dotnet 호스트의 절대 경로를 함께 전달함. DLL, deps.json, runtimeconfig.json과 프로젝트 의존 DLL을 포함한 전체 빌드 출력이 필요함. 런타임 자동 탐색, 다운로드, 설치는 수행하지 않음. `IsAvailable`은 파일 존재 조건이며 실제 실행 성공 검증이 아님. | |
| 23 | 추가: | |
| 24 | 추가: - `ListAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token)` | |
| 25 | 추가: - `CreateAsync(Guid jobId, IReadOnlyList<ZipCreateInput> inputs, JobLimits limits, ZipCreationOptions? options, CancellationToken token)` | |
| 26 | 추가: - `ZipCreateInput(string EntryName, Stream Content)` | |
| 27 | 추가: - `ZipCreationOptions(bool Encrypt = false, long? SplitVolumeBytes = null)` | |
| 28 | 추가: - `ZipWorkerResult(JobResult Job, byte[]? CreatedZip)` | |
| 29 | 추가: | |
| 30 | 추가: 입력 스트림은 읽기 가능하고 쓰기 불가능해야 함. 현재 위치부터 끝까지 읽으며 호출자가 스트림 수명을 관리함. 호스트는 파일을 읽기 전용으로 열어야 하며 사용자 선택 원본을 수정하지 않아야 함. 스트림 복사 중 원본이 외부에서 바뀌지 않는다는 보장은 호스트의 파일 열기 정책에 달려 있음. 파일 경로는 작업자에 전달하지 않음. 목록 API에는 파일 확장자가 없으므로 JAR 제외 정책은 파일 선택을 담당하는 UI에서 적용해야 함. | |
| 31 | 추가: | |
| 32 | 추가: `Capabilities`는 작업자 파일이 없으면 빈 목록이며, 있으면 `EngineCapability("zip", List)`와 `EngineCapability("zip", Create)`임. 여기서 Create는 ZIP 바이트 생성 능력임. `SupportsEncryption`, `SupportsSplitVolumes`, `SupportsSafeExtraction`은 false임. 후속 추가된 `SupportsFilePublication`은 Windows/Linux x64 게시 구현 여부이며 OS별 실행 검증 완료를 뜻하지 않음. 생성 저장 버튼은 Create만 보고 활성화하지 말고 FilePublication도 확인해야 함. | |
| 33 | 추가: | |
| 34 | 추가: 암호화 또는 분할 생성 옵션은 입력을 읽기 전에 UnsupportedOperation으로 거부함. 암호화 항목을 발견한 목록 요청도 UnsupportedOperation으로 종료함. 분할 ZIP을 연결하거나 볼륨을 찾아 읽지 않음. 읽을 수 없는 분할 또는 손상 ZIP은 .NET이 거부하며 InvalidDataException은 IntegrityFailure로 전달함. 각 분할 변종을 구분하는 별도 파서는 없음. | |
| 35 | 추가: | |
| 36 | 추가: 반환값의 Job.State, Job.Error, Job.Entries를 함께 사용함. 실패 전에 수집한 목록은 있을 수 있지만 완전한 목록이나 검증 성공을 뜻하지 않음. 실시간 진행 이벤트와 암호 콜백은 아직 IPC에 없음. UI는 작업 중 상태를 유지하되 가짜 백분율이나 암호 요청을 만들지 않음. | |
| 37 | 추가: | |
| 38 | 추가: ## 자원과 결과 계약 | |
| 39 | 추가: | |
| 40 | 추가: 원본 입력 합계와 ZIP 생성물은 각각 최대 16 MiB, IPC 프레임은 32 MiB, 입력 개수와 목록 항목은 1024개, 항목 이름은 1024자로 제한함. JobLimits가 더 작으면 그 예산을 적용함. 요청 시간은 5분 이하여야 하며 호스트의 제한 시간은 입력 복사, 프로세스 실행, 응답 수신과 종료 대기를 포함함. | |
| 41 | 추가: | |
| 42 | 추가: 작업자는 기존 ArchiveJob과 EngineContext를 사용함. 목록은 ZIP 입력 바이트를 처리 예산에 누적함. 생성은 원본 바이트와 최종 ZIP의 출력 전달 바이트를 처리 예산에 누적하며 ZIP 바이트를 출력 예산에 반영함. 생성 시 입력 항목마다 Listed 결과를 남기고 최종 archive.zip 항목 하나를 더 등록하므로 MaxEntries에는 입력 수 + 1이 필요함. 더 낮은 한도에서는 전체 작업이 실패하고 생성물을 반환하지 않음. | |
| 43 | 추가: | |
| 44 | 추가: 생성 완료의 artifact 항목은 기존 Core의 Extracted 값으로 반환되지만 여기서는 메모리 트랜잭션 확정을 뜻함. 디스크 해제 또는 저장을 뜻하지 않음. 모든 항목의 검증 결과는 NotChecked이며 CRC나 인증 검증을 통과했다고 표시하지 않음. .NET 10의 읽기 완료만으로 CRC 검증을 보장할 수 없음. [공식 CRC32 변경 설명](https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/11/ziparchive-entry-crc32-validation), [암호화 여부 API](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchiveentry.isencrypted?view=net-10.0) | |
| 45 | 추가: | |
| 46 | 추가: 외부 취소는 Cancelled, 호스트 시간 초과는 BudgetExceeded로 반환함. 응답 반환 전에 실행 중 작업자 프로세스 트리를 종료하고 실제 종료를 기다림. 종료 확인 자체가 실패하면 예외를 숨기지 않으므로 UI는 예외 경로에서도 화면 상태를 복구해야 함. 메모리 생성물은 응답이 완전히 전달되기 전의 취소에서 폐기할 수 있으며 이미 게시된 외부 파일은 없음. | |
| 47 | 추가: | |
| 48 | 추가: 프로세스 분리는 보안 샌드박스가 아님. 현재 사용자 권한으로 실행하며 Windows Job Object, 제한 토큰, OS 메모리 제한, 네트워크 차단은 구현하지 않음. 프레임과 입력 한도는 전체 프로세스 메모리 상한이 아니며 JSON과 메모리 복사, ZIP 메타데이터의 추가 할당이 있음. UI는 작업을 중복 시작하지 않아야 함. Worker 실행 파일 무결성과 배포 폴더 신뢰는 호스트 책임임. | |
| 49 | 추가: | |
| 50 | 추가: ## 실패 폐쇄 출력 | |
| 51 | 추가: | |
| 52 | 추가: Windows 핸들 기반 경로 고정과 단일 ZIP 새 파일 게시는 후속 구현되어 담당자의 실행 검증을 거쳤으나, 새 폴더 게시와 OS별 경합 방어의 실제 검증은 아직 남아 있음. 초기 구현에는 출력 트랜잭션과 공개 해제 진입점이 없었으나 아래 메모리 해제 확장과 새 게시 API가 후속 추가됨. 일반 UI의 Extract capability는 계속 비활성임. 문자열 경로 검사는 ZIP 생성 항목 이름에만 사용하며 파일시스템 안전성의 증거로 사용하지 않음. | |
| 53 | 추가: | |
| 54 | 추가: CreatedZip을 일반 File.WriteAllBytes로 사용자 목적지에 저장하지 않음. 후속 추가된 NewZipPublisher.PublishAsync를 사용하며, 구체적인 계약과 OS별 검증 공백은 [게시 API 문서](ZIP_PUBLICATION.md)에 기록함. | |
| 55 | 추가: | |
| 56 | 추가: ## 확인과 다음 검증 | |
| 57 | 추가: | |
| 58 | 추가: 로컬에서는 새 프로젝트 XML, 참조 경로, 공백과 변경 범위, 기존 Core와의 메서드 시그니처를 정적으로 대조함. Linux PATH에 dotnet, csc, mcs가 없어 컴파일과 실제 ZIP 실행은 하지 않음. Desktop과 tests는 담당자가 별도로 변경하며 이 작업에서는 수정하지 않음. 기존 브랜치를 보존하고 커밋, 설치, 외부 업로드와 VM 접속은 하지 않음. | |
| 59 | 추가: | |
| 60 | 추가: Windows 검증에서는 Worker와 Runtime을 먼저 빌드하고 전체 작업자 출력을 앱의 worker 폴더로 배치한 뒤 목록을 확인해야 함. 총괄이 실행 환경과 복사를 조율함. 필요한 회귀 사례는 정상 ZIP 목록, 중복 이름의 서로 다른 ID, 빈 ZIP, 암호화 및 손상 ZIP 오류, 명시한 이름의 생성물 재열람과 바이트 대조, 생성 암호와 분할 옵션 거부, 대소문자와 부모/자식 이름 충돌, 입력/출력/항목/시간 한도, 취소 후 프로세스 소멸, 누락된 작업자 및 비정상 종료, 생성 실패 시 CreatedZip 없음, Extract 거부임. 이 문서는 실행 통과를 주장하지 않음. | |
| 61 | 추가: | |
| 62 | 추가: | |
| 63 | 추가: ## 메모리 해제 확장 | |
| 64 | 추가: | |
| 65 | 추가: ExtractAsync와 선택적 ExtractedEntries 결과를 추가함. 경로, 타입, 실제 길이와 CRC 검증은 별도 작업자에서 수행하며 기존 List/Create 계약은 유지함. 일반 해제 capability와 SupportsSafeExtraction은 비활성임. 새 폴더 게시 API는 Windows NTFS의 신뢰 가능한 쓰기 ACL, Linux ext4/XFS의 현재 사용자 소유와 외부 쓰기 금지 조건에서만 실행함. 핸들 상대 생성, 전체 바이트 검증, 덮어쓰기 금지 게시와 소유 항목 정리를 구현했으며 실제 C# 실행은 미검증임. 정확한 제한과 검증 대기는 [ZIP_EXTRACTION.md](ZIP_EXTRACTION.md)를 따름. |
| @@ -0,0 +1,205 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using System.Text; | |
| 3 | 추가: using Microsoft.Win32.SafeHandles; | |
| 4 | 추가: using Zipelo.Core; | |
| 5 | 추가: | |
| 6 | 추가: namespace Zipelo.Runtime; | |
| 7 | 추가: | |
| 8 | 추가: internal sealed class LinuxFolderPublication : PendingFolderPublication | |
| 9 | 추가: { | |
| 10 | 추가: private readonly SafeFileHandle parent; | |
| 11 | 추가: private readonly uint user = GetEffectiveUser(); | |
| 12 | 추가: private string parentIdentity = ""; | |
| 13 | 추가: private bool unboundCreation; | |
| 14 | 추가: internal int? NativeError { get; private set; } | |
| 15 | 추가: internal int? CleanupError { get; private set; } | |
| 16 | 추가: | |
| 17 | 추가: internal LinuxFolderPublication(string path) => parent = Open(-100, path, 0x90000, 0, 0x04); | |
| 18 | 추가: | |
| 19 | 추가: internal override void Initialize() | |
| 20 | 추가: { | |
| 21 | 추가: var system = new byte[256]; | |
| 22 | 추가: if (Fstatfs(parent, system) != 0) { ThrowLast(); } | |
| 23 | 추가: // 로컬 ext4, XFS만 초기 구현 대상으로 삼음. FUSE와 네트워크 FS는 거부함. | |
| 24 | 추가: if (BitConverter.ToInt64(system, 0) is not (0xEF53 or 0x58465342)) | |
| 25 | 추가: { | |
| 26 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 27 | 추가: } | |
| 28 | 추가: parentIdentity = Inspect(parent, true); | |
| 29 | 추가: AddRoot(Create(parent, TemporaryName, true)); | |
| 30 | 추가: } | |
| 31 | 추가: | |
| 32 | 추가: protected override SafeFileHandle Create(SafeFileHandle directory, string name, bool folder) | |
| 33 | 추가: { | |
| 34 | 추가: if (folder) | |
| 35 | 추가: { | |
| 36 | 추가: // 기존 권한은 변경하지 않고 새 디렉터리를 0700 이하로 생성함. | |
| 37 | 추가: if (Mkdirat(directory, name, 0x1C0) != 0) { ThrowLast(); } | |
| 38 | 추가: unboundCreation = true; | |
| 39 | 추가: var handle = Open(directory.DangerousGetHandle().ToInt32(), name, 0x90000, 0, 0x0E); | |
| 40 | 추가: unboundCreation = false; | |
| 41 | 추가: return handle; | |
| 42 | 추가: } | |
| 43 | 추가: return Open(directory.DangerousGetHandle().ToInt32(), name, 0x800C2, 0x180, 0x0E); | |
| 44 | 추가: } | |
| 45 | 추가: | |
| 46 | 추가: protected override string Inspect(SafeFileHandle handle, bool directory) | |
| 47 | 추가: { | |
| 48 | 추가: var status = Stat(handle, "", 0x1100); | |
| 49 | 추가: var mode = BitConverter.ToUInt16(status, 28); | |
| 50 | 추가: if ((mode & 0xF000) != (directory ? 0x4000 : 0x8000) || | |
| 51 | 추가: BitConverter.ToUInt32(status, 20) != user || (mode & 0x12) != 0 || | |
| 52 | 추가: (!directory && BitConverter.ToUInt32(status, 16) != 1)) | |
| 53 | 추가: { | |
| 54 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 55 | 추가: } | |
| 56 | 추가: return Identity(status); | |
| 57 | 추가: } | |
| 58 | 추가: | |
| 59 | 추가: private static string Identity(byte[] status) | |
| 60 | 추가: => $"{BitConverter.ToUInt32(status, 136):X8}:{BitConverter.ToUInt32(status, 140):X8}:{BitConverter.ToUInt64(status, 32):X16}"; | |
| 61 | 추가: | |
| 62 | 추가: private byte[] Stat(SafeFileHandle directory, string name, int flags) | |
| 63 | 추가: { | |
| 64 | 추가: var status = new byte[256]; | |
| 65 | 추가: if (Statx(directory, name, flags, 0x7FF, status) != 0) { ThrowLast(); } | |
| 66 | 추가: if ((BitConverter.ToUInt32(status, 0) & 0x10F) != 0x10F) | |
| 67 | 추가: { | |
| 68 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 69 | 추가: } | |
| 70 | 추가: return status; | |
| 71 | 추가: } | |
| 72 | 추가: | |
| 73 | 추가: protected override void VerifyChildren(Node node, IReadOnlyCollection<string> names) | |
| 74 | 추가: { | |
| 75 | 추가: using var enumeration = Open(node.Handle.DangerousGetHandle().ToInt32(), ".", 0x90000, 0, 0x0E); | |
| 76 | 추가: var buffer = new byte[65536]; | |
| 77 | 추가: var remaining = new HashSet<string>(names, StringComparer.Ordinal); | |
| 78 | 추가: while (true) | |
| 79 | 추가: { | |
| 80 | 추가: var count = Getdents64(217, enumeration, buffer, (uint)buffer.Length); | |
| 81 | 추가: if (count < 0) { ThrowLast(); } | |
| 82 | 추가: if (count == 0) { break; } | |
| 83 | 추가: for (var offset = 0; offset < count;) | |
| 84 | 추가: { | |
| 85 | 추가: if (count - offset < 20) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 86 | 추가: var size = BitConverter.ToUInt16(buffer, offset + 16); | |
| 87 | 추가: if (size < 20 || size > count - offset) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 88 | 추가: var end = Array.IndexOf(buffer, (byte)0, offset + 19, size - 19); | |
| 89 | 추가: if (end < 0) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 90 | 추가: var name = new UTF8Encoding(false, true).GetString(buffer, offset + 19, end - offset - 19); | |
| 91 | 추가: if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 92 | 추가: offset += size; | |
| 93 | 추가: } | |
| 94 | 추가: } | |
| 95 | 추가: if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 96 | 추가: } | |
| 97 | 추가: | |
| 98 | 추가: private void RequireName(Node node) | |
| 99 | 추가: { | |
| 100 | 추가: var container = node.Parent?.Handle ?? parent; | |
| 101 | 추가: if (Inspect(container, true) != (node.Parent?.Identity ?? parentIdentity) || | |
| 102 | 추가: Identity(Stat(container, node.Name, 0x100)) != node.Identity) | |
| 103 | 추가: { | |
| 104 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 105 | 추가: } | |
| 106 | 추가: } | |
| 107 | 추가: | |
| 108 | 추가: internal override void Publish(string leaf, CancellationToken token) | |
| 109 | 추가: { | |
| 110 | 추가: RequireName(Root); | |
| 111 | 추가: foreach (var node in Owned.Where(node => node.Directory)) | |
| 112 | 추가: { | |
| 113 | 추가: token.ThrowIfCancellationRequested(); | |
| 114 | 추가: if (Fsync(node.Handle) != 0) { ThrowLast(); } | |
| 115 | 추가: } | |
| 116 | 추가: token.ThrowIfCancellationRequested(); | |
| 117 | 추가: // RENAME_NOREPLACE가 없는 커널/FS에서는 대체 경로 없이 실패함. | |
| 118 | 추가: if (Renameat2(parent, TemporaryName, parent, leaf, 1) != 0) { ThrowLast(); } | |
| 119 | 추가: } | |
| 120 | 추가: | |
| 121 | 추가: internal override bool Abort() | |
| 122 | 추가: { | |
| 123 | 추가: var success = !unboundCreation; | |
| 124 | 추가: for (var index = Owned.Count - 1; index >= 0; index--) | |
| 125 | 추가: { | |
| 126 | 추가: var node = Owned[index]; | |
| 127 | 추가: try | |
| 128 | 추가: { | |
| 129 | 추가: RequireName(node); | |
| 130 | 추가: if (Unlinkat(node.Parent?.Handle ?? parent, node.Name, node.Directory ? 0x200 : 0) != 0) | |
| 131 | 추가: { | |
| 132 | 추가: CleanupError ??= Marshal.GetLastPInvokeError(); | |
| 133 | 추가: success = false; | |
| 134 | 추가: } | |
| 135 | 추가: } | |
| 136 | 추가: catch (PosixPublicationException failure) { success = false; CleanupError ??= failure.NativeError; } | |
| 137 | 추가: catch { success = false; } | |
| 138 | 추가: } | |
| 139 | 추가: return success; | |
| 140 | 추가: } | |
| 141 | 추가: | |
| 142 | 추가: public override void Dispose() { DisposeOwned(); parent.Dispose(); } | |
| 143 | 추가: | |
| 144 | 추가: private SafeFileHandle Open(int directory, string name, ulong flags, ulong mode, ulong resolve) | |
| 145 | 추가: { | |
| 146 | 추가: var how = new OpenHow { Flags = flags, Mode = mode, Resolve = resolve }; | |
| 147 | 추가: var descriptor = Openat2(437, directory, name, ref how, 24); | |
| 148 | 추가: if (descriptor < 0) { ThrowLast(); } | |
| 149 | 추가: if (descriptor < 3) | |
| 150 | 추가: { | |
| 151 | 추가: var duplicate = Fcntl((int)descriptor, 1030, 3); | |
| 152 | 추가: var error = Marshal.GetLastPInvokeError(); | |
| 153 | 추가: Close((int)descriptor); | |
| 154 | 추가: if (duplicate < 0) { Fail(error); } | |
| 155 | 추가: descriptor = duplicate; | |
| 156 | 추가: } | |
| 157 | 추가: return new SafeFileHandle((nint)descriptor, true); | |
| 158 | 추가: } | |
| 159 | 추가: | |
| 160 | 추가: private void ThrowLast() => Fail(Marshal.GetLastPInvokeError()); | |
| 161 | 추가: private void Fail(int error) | |
| 162 | 추가: { | |
| 163 | 추가: NativeError = error; | |
| 164 | 추가: throw new PosixPublicationException(error switch | |
| 165 | 추가: { | |
| 166 | 추가: 17 => ArchiveError.OutputConflict, | |
| 167 | 추가: 40 => ArchiveError.UnsafePath, | |
| 168 | 추가: _ => ArchiveError.OutputUnavailable | |
| 169 | 추가: }, error); | |
| 170 | 추가: } | |
| 171 | 추가: | |
| 172 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 173 | 추가: private struct OpenHow { internal ulong Flags; internal ulong Mode; internal ulong Resolve; } | |
| 174 | 추가: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] | |
| 175 | 추가: private static extern long Openat2(long syscall, int directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, | |
| 176 | 추가: ref OpenHow how, nuint size); | |
| 177 | 추가: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] | |
| 178 | 추가: private static extern long Getdents64(long syscall, SafeFileHandle directory, [Out] byte[] buffer, uint size); | |
| 179 | 추가: [DllImport("libc", EntryPoint = "statx", SetLastError = true)] | |
| 180 | 추가: private static extern int Statx(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, | |
| 181 | 추가: int flags, uint mask, [Out] byte[] status); | |
| 182 | 추가: [DllImport("libc", EntryPoint = "fstatfs", SetLastError = true)] | |
| 183 | 추가: private static extern int Fstatfs(SafeFileHandle directory, [Out] byte[] status); | |
| 184 | 추가: [DllImport("libc", EntryPoint = "mkdirat", SetLastError = true)] | |
| 185 | 추가: private static extern int Mkdirat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, uint mode); | |
| 186 | 추가: [DllImport("libc", EntryPoint = "renameat2", SetLastError = true)] | |
| 187 | 추가: private static extern int Renameat2(SafeFileHandle sourceDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string source, | |
| 188 | 추가: SafeFileHandle targetDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string target, uint flags); | |
| 189 | 추가: [DllImport("libc", EntryPoint = "unlinkat", SetLastError = true)] | |
| 190 | 추가: private static extern int Unlinkat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int flags); | |
| 191 | 추가: [DllImport("libc", EntryPoint = "fsync", SetLastError = true)] | |
| 192 | 추가: private static extern int Fsync(SafeFileHandle file); | |
| 193 | 추가: [DllImport("libc", EntryPoint = "geteuid")] | |
| 194 | 추가: private static extern uint GetEffectiveUser(); | |
| 195 | 추가: [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)] | |
| 196 | 추가: private static extern int Fcntl(int descriptor, int command, int minimum); | |
| 197 | 추가: [DllImport("libc", EntryPoint = "close")] | |
| 198 | 추가: private static extern int Close(int descriptor); | |
| 199 | 추가: } | |
| 200 | 추가: | |
| 201 | 추가: internal sealed class PosixPublicationException(ArchiveError code, int error) : Exception(code.ToString()) | |
| 202 | 추가: { | |
| 203 | 추가: internal ArchiveError Code { get; } = code; | |
| 204 | 추가: internal int NativeError { get; } = error; | |
| 205 | 추가: } |
| @@ -0,0 +1,98 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using Microsoft.Win32.SafeHandles; | |
| 3 | 추가: using Zipelo.Core; | |
| 4 | 추가: | |
| 5 | 추가: namespace Zipelo.Runtime; | |
| 6 | 추가: | |
| 7 | 추가: internal sealed class LinuxPublication : PendingPublication | |
| 8 | 추가: { | |
| 9 | 추가: private readonly SafeFileHandle directory; | |
| 10 | 추가: private readonly SafeFileHandle file; | |
| 11 | 추가: | |
| 12 | 추가: private LinuxPublication(SafeFileHandle directory, SafeFileHandle file) | |
| 13 | 추가: { | |
| 14 | 추가: this.directory = directory; | |
| 15 | 추가: this.file = file; | |
| 16 | 추가: } | |
| 17 | 추가: | |
| 18 | 추가: internal override SafeFileHandle Handle => file; | |
| 19 | 추가: | |
| 20 | 추가: internal static LinuxPublication Create(string parent) | |
| 21 | 추가: { | |
| 22 | 추가: // x64 syscall 번호를 사용함. 호출 전 공통 API에서 아키텍처를 제한함. | |
| 23 | 추가: var how = new OpenHow { Flags = 0x80000 | 0x10000, Mode = 0, Resolve = 0x04 }; | |
| 24 | 추가: var descriptor = OpenAt2(437, -100, parent, ref how, (nuint)Marshal.SizeOf<OpenHow>()); | |
| 25 | 추가: var directory = OwnDescriptor(checked((int)descriptor)); | |
| 26 | 추가: try | |
| 27 | 추가: { | |
| 28 | 추가: // O_TMPFILE | O_RDWR | O_CLOEXEC, 생성 권한은 0600 이하임. | |
| 29 | 추가: var file = OwnDescriptor(OpenAt(directory, ".", 0x410000 | 2 | 0x80000, 0x180)); | |
| 30 | 추가: return new(directory, file); | |
| 31 | 추가: } | |
| 32 | 추가: catch { directory.Dispose(); throw; } | |
| 33 | 추가: } | |
| 34 | 추가: | |
| 35 | 추가: internal override void Publish(string leaf) | |
| 36 | 추가: { | |
| 37 | 추가: // 커널 procfs의 보유 fd를 연결하며 새 목적지 링크는 덮어쓰지 않음. | |
| 38 | 추가: var descriptorPath = $"/proc/self/fd/{file.DangerousGetHandle().ToInt64()}"; | |
| 39 | 추가: if (LinkAt(-100, descriptorPath, directory, leaf, 0x400) != 0) { ThrowLastError(); } | |
| 40 | 추가: } | |
| 41 | 추가: | |
| 42 | 추가: // 이름 없는 임시 inode는 마지막 핸들이 닫힐 때 제거됨. | |
| 43 | 추가: internal override bool Abort() => true; | |
| 44 | 추가: | |
| 45 | 추가: public override void Dispose() | |
| 46 | 추가: { | |
| 47 | 추가: file.Dispose(); | |
| 48 | 추가: directory.Dispose(); | |
| 49 | 추가: } | |
| 50 | 추가: | |
| 51 | 추가: private static SafeFileHandle OwnDescriptor(int descriptor) | |
| 52 | 추가: { | |
| 53 | 추가: if (descriptor < 0) { ThrowLastError(); } | |
| 54 | 추가: if (descriptor < 3) | |
| 55 | 추가: { | |
| 56 | 추가: var duplicate = DuplicateDescriptor(descriptor, 1030, 3); | |
| 57 | 추가: var error = Marshal.GetLastPInvokeError(); | |
| 58 | 추가: Close(descriptor); | |
| 59 | 추가: if (duplicate < 0) { throw Error(error); } | |
| 60 | 추가: descriptor = duplicate; | |
| 61 | 추가: } | |
| 62 | 추가: return new SafeFileHandle((nint)descriptor, ownsHandle: true); | |
| 63 | 추가: } | |
| 64 | 추가: | |
| 65 | 추가: private static void ThrowLastError() => throw Error(Marshal.GetLastPInvokeError()); | |
| 66 | 추가: private static ArchiveException Error(int error) => new(error switch | |
| 67 | 추가: { | |
| 68 | 추가: 17 => ArchiveError.OutputConflict, | |
| 69 | 추가: 40 => ArchiveError.UnsafePath, | |
| 70 | 추가: _ => ArchiveError.OutputUnavailable | |
| 71 | 추가: }); | |
| 72 | 추가: | |
| 73 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 74 | 추가: private struct OpenHow | |
| 75 | 추가: { | |
| 76 | 추가: internal ulong Flags; | |
| 77 | 추가: internal ulong Mode; | |
| 78 | 추가: internal ulong Resolve; | |
| 79 | 추가: } | |
| 80 | 추가: | |
| 81 | 추가: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] | |
| 82 | 추가: private static extern long OpenAt2(long number, int directory, | |
| 83 | 추가: [MarshalAs(UnmanagedType.LPUTF8Str)] string path, ref OpenHow how, nuint size); | |
| 84 | 추가: | |
| 85 | 추가: [DllImport("libc", EntryPoint = "openat", SetLastError = true)] | |
| 86 | 추가: private static extern int OpenAt(SafeFileHandle directory, | |
| 87 | 추가: [MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags, uint mode); | |
| 88 | 추가: | |
| 89 | 추가: [DllImport("libc", EntryPoint = "linkat", SetLastError = true)] | |
| 90 | 추가: private static extern int LinkAt(int oldDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath, | |
| 91 | 추가: SafeFileHandle newDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath, int flags); | |
| 92 | 추가: | |
| 93 | 추가: [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)] | |
| 94 | 추가: private static extern int DuplicateDescriptor(int descriptor, int command, int minimum); | |
| 95 | 추가: | |
| 96 | 추가: [DllImport("libc", EntryPoint = "close")] | |
| 97 | 추가: private static extern int Close(int descriptor); | |
| 98 | 추가: } |
| @@ -0,0 +1,76 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: | |
| 4 | 추가: namespace Zipelo.Runtime; | |
| 5 | 추가: | |
| 6 | 추가: public static class NewFolderPublisher | |
| 7 | 추가: { | |
| 8 | 추가: // 구현 진입 가능 여부임. 일반 UI 활성화나 OS 검증 완료를 뜻하지 않음. | |
| 9 | 추가: public static bool IsSupportedPlatform => RuntimeInformation.ProcessArchitecture == Architecture.X64 && | |
| 10 | 추가: (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()); | |
| 11 | 추가: | |
| 12 | 추가: public static async Task<ZipPublicationResult> PublishAsync(ZipWorkerResult result, | |
| 13 | 추가: string destinationPath, CancellationToken token) | |
| 14 | 추가: { | |
| 15 | 추가: PendingFolderPublication? pending = null; | |
| 16 | 추가: var published = false; | |
| 17 | 추가: var error = ArchiveError.None; | |
| 18 | 추가: var cleanupFailed = false; | |
| 19 | 추가: int? posixError = null; | |
| 20 | 추가: string? temporaryName = null; | |
| 21 | 추가: PublicationNativeFailure? nativeFailure = null; | |
| 22 | 추가: PublicationNativeFailure? cleanupNativeFailure = null; | |
| 23 | 추가: try | |
| 24 | 추가: { | |
| 25 | 추가: token.ThrowIfCancellationRequested(); | |
| 26 | 추가: if (!IsSupportedPlatform) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 27 | 추가: var entries = ZipExtraction.ValidateResult(result, token, snapshot: true); | |
| 28 | 추가: if (!Path.IsPathFullyQualified(destinationPath)) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 29 | 추가: var fullPath = Path.GetFullPath(destinationPath); | |
| 30 | 추가: if (OperatingSystem.IsLinux()) { _ = OutputPathPolicy.Validate(fullPath[1..], FileNamePolicy.Linux); } | |
| 31 | 추가: var parent = Path.GetDirectoryName(fullPath); | |
| 32 | 추가: var leaf = Path.GetFileName(fullPath); | |
| 33 | 추가: if (parent is null || OutputPathPolicy.Validate(leaf, OutputPathPolicy.CurrentPolicy).Count != 1) | |
| 34 | 추가: { | |
| 35 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 36 | 추가: } | |
| 37 | 추가: pending = OperatingSystem.IsWindows() ? new WindowsFolderPublication(parent) : new LinuxFolderPublication(parent); | |
| 38 | 추가: pending.Initialize(); | |
| 39 | 추가: foreach (var entry in entries) { await pending.WriteAsync(entry, token).ConfigureAwait(false); } | |
| 40 | 추가: pending.Verify(token); | |
| 41 | 추가: token.ThrowIfCancellationRequested(); | |
| 42 | 추가: pending.Publish(leaf, token); | |
| 43 | 추가: published = true; | |
| 44 | 추가: } | |
| 45 | 추가: catch (OperationCanceledException) when (token.IsCancellationRequested) { error = ArchiveError.Cancelled; } | |
| 46 | 추가: catch (PublicationNativeException failure) { error = failure.Code; nativeFailure = failure.Failure; } | |
| 47 | 추가: catch (PosixPublicationException failure) { error = failure.Code; posixError = failure.NativeError; } | |
| 48 | 추가: catch (ArchiveException failure) { error = failure.Code; } | |
| 49 | 추가: catch (ArgumentException) { error = ArchiveError.UnsafePath; } | |
| 50 | 추가: catch { error = ArchiveError.OutputUnavailable; } | |
| 51 | 추가: finally | |
| 52 | 추가: { | |
| 53 | 추가: if (pending is not null) | |
| 54 | 추가: { | |
| 55 | 추가: if (!published) | |
| 56 | 추가: { | |
| 57 | 추가: try { cleanupFailed = !pending.Abort(); } | |
| 58 | 추가: catch { cleanupFailed = true; } | |
| 59 | 추가: if (cleanupFailed) | |
| 60 | 추가: { | |
| 61 | 추가: temporaryName = pending.TemporaryName; | |
| 62 | 추가: cleanupNativeFailure = pending.CleanupNativeFailure; | |
| 63 | 추가: } | |
| 64 | 추가: } | |
| 65 | 추가: pending.Dispose(); | |
| 66 | 추가: } | |
| 67 | 추가: } | |
| 68 | 추가: return new(published, error, cleanupFailed, temporaryName) | |
| 69 | 추가: { | |
| 70 | 추가: NativeFailure = nativeFailure, | |
| 71 | 추가: CleanupNativeFailure = cleanupNativeFailure, | |
| 72 | 추가: PosixError = posixError, | |
| 73 | 추가: CleanupPosixError = (pending as LinuxFolderPublication)?.CleanupError | |
| 74 | 추가: }; | |
| 75 | 추가: } | |
| 76 | 추가: } |
| @@ -0,0 +1,123 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using Microsoft.Win32.SafeHandles; | |
| 3 | 추가: using Zipelo.Core; | |
| 4 | 추가: | |
| 5 | 추가: namespace Zipelo.Runtime; | |
| 6 | 추가: | |
| 7 | 추가: public sealed record ZipPublicationResult(bool Published, ArchiveError Error, bool CleanupFailed, | |
| 8 | 추가: string? TemporaryFileName = null) | |
| 9 | 추가: { | |
| 10 | 추가: public int? PosixError { get; init; } | |
| 11 | 추가: public int? CleanupPosixError { get; init; } | |
| 12 | 추가: public PublicationNativeFailure? NativeFailure { get; init; } | |
| 13 | 추가: public PublicationNativeFailure? CleanupNativeFailure { get; init; } | |
| 14 | 추가: } | |
| 15 | 추가: | |
| 16 | 추가: // 경로와 OS 오류 메시지 없이 고정 API 이름과 숫자 코드만 전달함. | |
| 17 | 추가: public sealed record PublicationNativeFailure(string Operation, uint Win32Error, int? NtStatus = null); | |
| 18 | 추가: | |
| 19 | 추가: internal sealed class PublicationNativeException(ArchiveError code, PublicationNativeFailure failure) | |
| 20 | 추가: : Exception(code.ToString()) | |
| 21 | 추가: { | |
| 22 | 추가: internal ArchiveError Code { get; } = code; | |
| 23 | 추가: internal PublicationNativeFailure Failure { get; } = failure; | |
| 24 | 추가: } | |
| 25 | 추가: | |
| 26 | 추가: public static class NewZipPublisher | |
| 27 | 추가: { | |
| 28 | 추가: // 구현 대상 여부임. OS별 실행 검증 완료나 대상 파일시스템 지원을 뜻하지 않음. | |
| 29 | 추가: public static bool IsSupportedPlatform => RuntimeInformation.ProcessArchitecture == Architecture.X64 && | |
| 30 | 추가: (OperatingSystem.IsWindows() || OperatingSystem.IsLinux()); | |
| 31 | 추가: | |
| 32 | 추가: public static async Task<ZipPublicationResult> PublishAsync(ZipWorkerResult result, | |
| 33 | 추가: string destinationPath, CancellationToken token) | |
| 34 | 추가: { | |
| 35 | 추가: PendingPublication? pending = null; | |
| 36 | 추가: var published = false; | |
| 37 | 추가: var error = ArchiveError.None; | |
| 38 | 추가: var cleanupFailed = false; | |
| 39 | 추가: string? temporaryFileName = null; | |
| 40 | 추가: PublicationNativeFailure? nativeFailure = null; | |
| 41 | 추가: PublicationNativeFailure? cleanupNativeFailure = null; | |
| 42 | 추가: try | |
| 43 | 추가: { | |
| 44 | 추가: token.ThrowIfCancellationRequested(); | |
| 45 | 추가: if (!IsSupportedPlatform) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 46 | 추가: var bytes = result.CreatedZip; | |
| 47 | 추가: if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None || | |
| 48 | 추가: bytes is null || bytes.Length == 0) | |
| 49 | 추가: { | |
| 50 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 51 | 추가: } | |
| 52 | 추가: if (bytes.Length > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 53 | 추가: if (!Path.IsPathFullyQualified(destinationPath)) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 54 | 추가: var fullPath = Path.GetFullPath(destinationPath); | |
| 55 | 추가: if (OperatingSystem.IsLinux()) | |
| 56 | 추가: { | |
| 57 | 추가: _ = OutputPathPolicy.Validate(fullPath[1..], FileNamePolicy.Linux); | |
| 58 | 추가: } | |
| 59 | 추가: var parent = Path.GetDirectoryName(fullPath); | |
| 60 | 추가: var leaf = Path.GetFileName(fullPath); | |
| 61 | 추가: if (parent is null || OutputPathPolicy.Validate(leaf, OutputPathPolicy.CurrentPolicy).Count != 1) | |
| 62 | 추가: { | |
| 63 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 64 | 추가: } | |
| 65 | 추가: // 호출자가 생성물 배열을 이후 변경해도 쓰는 내용이 달라지지 않도록 복사함. | |
| 66 | 추가: var snapshot = bytes.ToArray(); | |
| 67 | 추가: pending = OperatingSystem.IsWindows() ? WindowsPublication.Create(parent) : LinuxPublication.Create(parent); | |
| 68 | 추가: for (var offset = 0; offset < snapshot.Length; offset += 65536) | |
| 69 | 추가: { | |
| 70 | 추가: token.ThrowIfCancellationRequested(); | |
| 71 | 추가: var count = Math.Min(65536, snapshot.Length - offset); | |
| 72 | 추가: await RandomAccess.WriteAsync(pending.Handle, snapshot.AsMemory(offset, count), offset, token) | |
| 73 | 추가: .ConfigureAwait(false); | |
| 74 | 추가: } | |
| 75 | 추가: RandomAccess.FlushToDisk(pending.Handle); | |
| 76 | 추가: token.ThrowIfCancellationRequested(); | |
| 77 | 추가: pending.Publish(leaf); | |
| 78 | 추가: // 게시 성공 이후의 늦은 취소는 이미 존재하는 새 파일을 취소 결과로 바꾸지 않음. | |
| 79 | 추가: published = true; | |
| 80 | 추가: } | |
| 81 | 추가: catch (OperationCanceledException) when (token.IsCancellationRequested) { error = ArchiveError.Cancelled; } | |
| 82 | 추가: catch (PublicationNativeException failure) | |
| 83 | 추가: { | |
| 84 | 추가: error = failure.Code; | |
| 85 | 추가: nativeFailure = failure.Failure; | |
| 86 | 추가: } | |
| 87 | 추가: catch (ArchiveException failure) { error = failure.Code; } | |
| 88 | 추가: catch (ArgumentException) { error = ArchiveError.UnsafePath; } | |
| 89 | 추가: catch { error = ArchiveError.OutputUnavailable; } | |
| 90 | 추가: finally | |
| 91 | 추가: { | |
| 92 | 추가: if (pending is not null) | |
| 93 | 추가: { | |
| 94 | 추가: if (!published) | |
| 95 | 추가: { | |
| 96 | 추가: try { cleanupFailed = !pending.Abort(); } | |
| 97 | 추가: catch { cleanupFailed = true; } | |
| 98 | 추가: if (cleanupFailed) | |
| 99 | 추가: { | |
| 100 | 추가: temporaryFileName = pending.TemporaryFileName; | |
| 101 | 추가: cleanupNativeFailure = pending.CleanupNativeFailure; | |
| 102 | 추가: } | |
| 103 | 추가: } | |
| 104 | 추가: pending.Dispose(); | |
| 105 | 추가: } | |
| 106 | 추가: } | |
| 107 | 추가: return new(published, error, cleanupFailed, temporaryFileName) | |
| 108 | 추가: { | |
| 109 | 추가: NativeFailure = nativeFailure, | |
| 110 | 추가: CleanupNativeFailure = cleanupNativeFailure | |
| 111 | 추가: }; | |
| 112 | 추가: } | |
| 113 | 추가: } | |
| 114 | 추가: | |
| 115 | 추가: internal abstract class PendingPublication : IDisposable | |
| 116 | 추가: { | |
| 117 | 추가: internal abstract SafeFileHandle Handle { get; } | |
| 118 | 추가: internal virtual string? TemporaryFileName => null; | |
| 119 | 추가: internal virtual PublicationNativeFailure? CleanupNativeFailure => null; | |
| 120 | 추가: internal abstract void Publish(string leaf); | |
| 121 | 추가: internal abstract bool Abort(); | |
| 122 | 추가: public abstract void Dispose(); | |
| 123 | 추가: } |
| @@ -0,0 +1,100 @@ | ||
| 1 | 추가: using Microsoft.Win32.SafeHandles; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: | |
| 4 | 추가: namespace Zipelo.Runtime; | |
| 5 | 추가: | |
| 6 | 추가: internal abstract class PendingFolderPublication : IDisposable | |
| 7 | 추가: { | |
| 8 | 추가: protected sealed class Node(string name, Node? parent, SafeFileHandle handle, bool directory, string identity) | |
| 9 | 추가: { | |
| 10 | 추가: internal string Name { get; } = name; | |
| 11 | 추가: internal Node? Parent { get; } = parent; | |
| 12 | 추가: internal SafeFileHandle Handle { get; set; } = handle; | |
| 13 | 추가: internal bool Directory { get; } = directory; | |
| 14 | 추가: internal string Identity { get; } = identity; | |
| 15 | 추가: } | |
| 16 | 추가: | |
| 17 | 추가: protected readonly List<Node> Owned = []; | |
| 18 | 추가: private readonly Dictionary<string, Node> folders = new(OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy)); | |
| 19 | 추가: internal string TemporaryName { get; } = $".zipelo-{Guid.NewGuid():N}.tmp"; | |
| 20 | 추가: internal PublicationNativeFailure? CleanupNativeFailure { get; set; } | |
| 21 | 추가: protected Node Root => Owned[0]; | |
| 22 | 추가: protected abstract SafeFileHandle Create(SafeFileHandle parent, string name, bool directory); | |
| 23 | 추가: protected abstract string Inspect(SafeFileHandle handle, bool directory); | |
| 24 | 추가: protected abstract void VerifyChildren(Node node, IReadOnlyCollection<string> names); | |
| 25 | 추가: internal abstract void Initialize(); | |
| 26 | 추가: internal abstract void Publish(string leaf, CancellationToken token); | |
| 27 | 추가: internal abstract bool Abort(); | |
| 28 | 추가: public abstract void Dispose(); | |
| 29 | 추가: | |
| 30 | 추가: protected void AddRoot(SafeFileHandle handle) | |
| 31 | 추가: { | |
| 32 | 추가: // 검사 실패도 호출자의 Abort가 생성 핸들을 정리하도록 먼저 기록함. | |
| 33 | 추가: var root = new Node(TemporaryName, null, handle, true, ""); | |
| 34 | 추가: Owned.Add(root); | |
| 35 | 추가: var verified = new Node(TemporaryName, null, handle, true, Inspect(handle, true)); | |
| 36 | 추가: Owned[0] = verified; | |
| 37 | 추가: folders.Add("", verified); | |
| 38 | 추가: } | |
| 39 | 추가: | |
| 40 | 추가: internal async Task WriteAsync(ZipExtractedEntry item, CancellationToken token) | |
| 41 | 추가: { | |
| 42 | 추가: var segments = OutputPathPolicy.Validate(item.Entry.Name, OutputPathPolicy.CurrentPolicy); | |
| 43 | 추가: var parent = Root; | |
| 44 | 추가: for (var index = 0; index < segments.Count; index++) | |
| 45 | 추가: { | |
| 46 | 추가: token.ThrowIfCancellationRequested(); | |
| 47 | 추가: var path = string.Join('/', segments.Take(index + 1)); | |
| 48 | 추가: var directory = index < segments.Count - 1 || item.Entry.Kind == EntryKind.Directory; | |
| 49 | 추가: if (directory && folders.TryGetValue(path, out var existing)) { parent = existing; continue; } | |
| 50 | 추가: var handle = Create(parent.Handle, segments[index], directory); | |
| 51 | 추가: var node = new Node(segments[index], parent, handle, directory, ""); | |
| 52 | 추가: Owned.Add(node); | |
| 53 | 추가: node = new Node(node.Name, parent, handle, directory, Inspect(handle, directory)); | |
| 54 | 추가: Owned[^1] = node; | |
| 55 | 추가: if (directory) | |
| 56 | 추가: { | |
| 57 | 추가: folders.Add(path, node); | |
| 58 | 추가: parent = node; | |
| 59 | 추가: continue; | |
| 60 | 추가: } | |
| 61 | 추가: var buffer = new byte[65536]; | |
| 62 | 추가: for (var offset = 0; offset < item.Content.Length; offset += buffer.Length) | |
| 63 | 추가: { | |
| 64 | 추가: token.ThrowIfCancellationRequested(); | |
| 65 | 추가: var count = Math.Min(buffer.Length, item.Content.Length - offset); | |
| 66 | 추가: await RandomAccess.WriteAsync(handle, item.Content.AsMemory(offset, count), offset, token).ConfigureAwait(false); | |
| 67 | 추가: } | |
| 68 | 추가: RandomAccess.FlushToDisk(handle); | |
| 69 | 추가: if (RandomAccess.GetLength(handle) != item.Content.Length) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 70 | 추가: for (var offset = 0; offset < item.Content.Length;) | |
| 71 | 추가: { | |
| 72 | 추가: var count = await RandomAccess.ReadAsync(handle, buffer.AsMemory(0, | |
| 73 | 추가: Math.Min(buffer.Length, item.Content.Length - offset)), offset, token).ConfigureAwait(false); | |
| 74 | 추가: if (count == 0 || !buffer.AsSpan(0, count).SequenceEqual(item.Content.AsSpan(offset, count))) | |
| 75 | 추가: { | |
| 76 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 77 | 추가: } | |
| 78 | 추가: offset += count; | |
| 79 | 추가: } | |
| 80 | 추가: } | |
| 81 | 추가: } | |
| 82 | 추가: | |
| 83 | 추가: internal void Verify(CancellationToken token) | |
| 84 | 추가: { | |
| 85 | 추가: foreach (var node in Owned) | |
| 86 | 추가: { | |
| 87 | 추가: token.ThrowIfCancellationRequested(); | |
| 88 | 추가: if (Inspect(node.Handle, node.Directory) != node.Identity) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 89 | 추가: if (node.Directory) | |
| 90 | 추가: { | |
| 91 | 추가: VerifyChildren(node, Owned.Where(child => child.Parent == node).Select(child => child.Name).ToArray()); | |
| 92 | 추가: } | |
| 93 | 추가: } | |
| 94 | 추가: } | |
| 95 | 추가: | |
| 96 | 추가: protected void DisposeOwned() | |
| 97 | 추가: { | |
| 98 | 추가: for (var index = Owned.Count - 1; index >= 0; index--) { Owned[index].Handle.Dispose(); } | |
| 99 | 추가: } | |
| 100 | 추가: } |
| @@ -0,0 +1,145 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using System.Security.AccessControl; | |
| 3 | 추가: using System.Security.Principal; | |
| 4 | 추가: using System.Text; | |
| 5 | 추가: using Microsoft.Win32.SafeHandles; | |
| 6 | 추가: using Zipelo.Core; | |
| 7 | 추가: | |
| 8 | 추가: namespace Zipelo.Runtime; | |
| 9 | 추가: | |
| 10 | 추가: internal static class WindowsFolderGuard | |
| 11 | 추가: { | |
| 12 | 추가: internal static void RequireNtfs(SafeFileHandle handle) | |
| 13 | 추가: { | |
| 14 | 추가: var name = new StringBuilder(32); | |
| 15 | 추가: if (!GetVolumeInformationByHandleW(handle, null, 0, out _, out _, out _, name, name.Capacity)) | |
| 16 | 추가: { | |
| 17 | 추가: ThrowLast("GetVolumeInformationByHandleW"); | |
| 18 | 추가: } | |
| 19 | 추가: if (name.ToString() != "NTFS") { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 20 | 추가: } | |
| 21 | 추가: | |
| 22 | 추가: internal static string Inspect(SafeFileHandle handle, bool directory) | |
| 23 | 추가: { | |
| 24 | 추가: var attributes = Query(handle, 9, 8); | |
| 25 | 추가: var flags = BitConverter.ToUInt32(attributes, 0); | |
| 26 | 추가: if ((flags & 0x400) != 0 || ((flags & 0x10) != 0) != directory) | |
| 27 | 추가: { | |
| 28 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 29 | 추가: } | |
| 30 | 추가: var standard = Query(handle, 1, 24); | |
| 31 | 추가: if (standard[20] != 0 || (!directory && BitConverter.ToUInt32(standard, 16) != 1)) | |
| 32 | 추가: { | |
| 33 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 34 | 추가: } | |
| 35 | 추가: RequirePrivateWriters(handle); | |
| 36 | 추가: return Convert.ToHexString(Query(handle, 18, 24)); | |
| 37 | 추가: } | |
| 38 | 추가: | |
| 39 | 추가: internal static void RequirePrivateWriters(SafeFileHandle handle) | |
| 40 | 추가: { | |
| 41 | 추가: if (!OperatingSystem.IsWindows()) { throw new PlatformNotSupportedException(); } | |
| 42 | 추가: var error = GetSecurityInfo(handle, 1, 5, out _, out _, out _, out _, out var descriptor); | |
| 43 | 추가: if (error != 0) { throw Native("GetSecurityInfo", error); } | |
| 44 | 추가: try | |
| 45 | 추가: { | |
| 46 | 추가: var bytes = new byte[checked((int)GetSecurityDescriptorLength(descriptor))]; | |
| 47 | 추가: Marshal.Copy(descriptor, bytes, 0, bytes.Length); | |
| 48 | 추가: var security = new RawSecurityDescriptor(bytes, 0); | |
| 49 | 추가: using var identity = WindowsIdentity.GetCurrent(); | |
| 50 | 추가: var trusted = new HashSet<string>(StringComparer.Ordinal) { "S-1-5-18", "S-1-5-32-544" }; | |
| 51 | 추가: if (identity.User is { } user) { trusted.Add(user.Value); } | |
| 52 | 추가: if (security.Owner is null || !trusted.Contains(security.Owner.Value) || security.DiscretionaryAcl is null) | |
| 53 | 추가: { | |
| 54 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 55 | 추가: } | |
| 56 | 추가: foreach (GenericAce ace in security.DiscretionaryAcl) | |
| 57 | 추가: { | |
| 58 | 추가: if (ace is not CommonAce common || common.IsCallback) | |
| 59 | 추가: { | |
| 60 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 61 | 추가: } | |
| 62 | 추가: if (common.AceQualifier == AceQualifier.AccessDenied) { continue; } | |
| 63 | 추가: if (common.AceQualifier != AceQualifier.AccessAllowed) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 64 | 추가: // 알 수 없는 쓰기 권한과 상속 전용 쓰기 ACE도 보수적으로 거부함. | |
| 65 | 추가: const uint mutation = 0x520D0156; | |
| 66 | 추가: if ((unchecked((uint)common.AccessMask) & mutation) == 0 || trusted.Contains(common.SecurityIdentifier.Value)) { continue; } | |
| 67 | 추가: if ((common.AceFlags & AceFlags.InheritOnly) != 0 && | |
| 68 | 추가: common.SecurityIdentifier.IsWellKnown(WellKnownSidType.CreatorOwnerSid)) { continue; } | |
| 69 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 70 | 추가: } | |
| 71 | 추가: } | |
| 72 | 추가: finally { LocalFree(descriptor); } | |
| 73 | 추가: } | |
| 74 | 추가: | |
| 75 | 추가: internal static void VerifyChildren(SafeFileHandle directory, IReadOnlyCollection<string> names) | |
| 76 | 추가: { | |
| 77 | 추가: var remaining = new HashSet<string>(names, StringComparer.OrdinalIgnoreCase); | |
| 78 | 추가: var buffer = Marshal.AllocHGlobal(65536); | |
| 79 | 추가: try | |
| 80 | 추가: { | |
| 81 | 추가: var restart = true; | |
| 82 | 추가: while (true) | |
| 83 | 추가: { | |
| 84 | 추가: var status = NtQueryDirectoryFile(directory, 0, 0, 0, out var io, buffer, 65536, 12, false, 0, restart); | |
| 85 | 추가: restart = false; | |
| 86 | 추가: if (status == unchecked((int)0x80000006)) { break; } | |
| 87 | 추가: if (status != 0) { throw Native("NtQueryDirectoryFile", RtlNtStatusToDosError(status), status); } | |
| 88 | 추가: var length = checked((int)io.Information); | |
| 89 | 추가: var offset = 0; | |
| 90 | 추가: do | |
| 91 | 추가: { | |
| 92 | 추가: if (offset < 0 || offset > length - 12) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 93 | 추가: var next = Marshal.ReadInt32(buffer, offset); | |
| 94 | 추가: var size = Marshal.ReadInt32(buffer, offset + 8); | |
| 95 | 추가: if (size < 0 || size % 2 != 0 || size > length - offset - 12) | |
| 96 | 추가: { | |
| 97 | 추가: throw new ArchiveException(ArchiveError.OutputUnavailable); | |
| 98 | 추가: } | |
| 99 | 추가: var name = Marshal.PtrToStringUni(buffer + offset + 12, size / 2)!; | |
| 100 | 추가: if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 101 | 추가: if (next == 0) { break; } | |
| 102 | 추가: if (next < 12 + size) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 103 | 추가: offset = checked(offset + next); | |
| 104 | 추가: } while (true); | |
| 105 | 추가: } | |
| 106 | 추가: if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 107 | 추가: } | |
| 108 | 추가: finally { Marshal.FreeHGlobal(buffer); } | |
| 109 | 추가: } | |
| 110 | 추가: | |
| 111 | 추가: private static byte[] Query(SafeFileHandle handle, int kind, int size) | |
| 112 | 추가: { | |
| 113 | 추가: var bytes = new byte[size]; | |
| 114 | 추가: if (!GetFileInformationByHandleEx(handle, kind, bytes, (uint)size)) { ThrowLast("GetFileInformationByHandleEx"); } | |
| 115 | 추가: return bytes; | |
| 116 | 추가: } | |
| 117 | 추가: | |
| 118 | 추가: private static void ThrowLast(string operation) => throw Native(operation, unchecked((uint)Marshal.GetLastPInvokeError())); | |
| 119 | 추가: private static PublicationNativeException Native(string operation, uint error, int? status = null) | |
| 120 | 추가: => new(ArchiveError.OutputUnavailable, new(operation, error, status)); | |
| 121 | 추가: | |
| 122 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 123 | 추가: private struct IoStatusBlock { internal nint Status; internal nuint Information; } | |
| 124 | 추가: | |
| 125 | 추가: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | |
| 126 | 추가: [return: MarshalAs(UnmanagedType.Bool)] | |
| 127 | 추가: private static extern bool GetVolumeInformationByHandleW(SafeFileHandle handle, StringBuilder? volume, int volumeSize, | |
| 128 | 추가: out uint serial, out uint maximumComponent, out uint flags, StringBuilder fileSystem, int fileSystemSize); | |
| 129 | 추가: [DllImport("kernel32.dll", SetLastError = true)] | |
| 130 | 추가: [return: MarshalAs(UnmanagedType.Bool)] | |
| 131 | 추가: private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle, int kind, [Out] byte[] information, uint size); | |
| 132 | 추가: [DllImport("advapi32.dll")] | |
| 133 | 추가: private static extern uint GetSecurityInfo(SafeFileHandle handle, int kind, uint information, | |
| 134 | 추가: out nint owner, out nint group, out nint dacl, out nint sacl, out nint descriptor); | |
| 135 | 추가: [DllImport("advapi32.dll")] | |
| 136 | 추가: private static extern uint GetSecurityDescriptorLength(nint descriptor); | |
| 137 | 추가: [DllImport("kernel32.dll")] | |
| 138 | 추가: private static extern nint LocalFree(nint memory); | |
| 139 | 추가: [DllImport("ntdll.dll")] | |
| 140 | 추가: private static extern int NtQueryDirectoryFile(SafeFileHandle handle, nint completionEvent, nint routine, nint context, | |
| 141 | 추가: out IoStatusBlock status, nint buffer, uint length, int kind, [MarshalAs(UnmanagedType.U1)] bool single, | |
| 142 | 추가: nint filter, [MarshalAs(UnmanagedType.U1)] bool restart); | |
| 143 | 추가: [DllImport("ntdll.dll")] | |
| 144 | 추가: private static extern uint RtlNtStatusToDosError(int status); | |
| 145 | 추가: } |
| @@ -0,0 +1,80 @@ | ||
| 1 | 추가: using Microsoft.Win32.SafeHandles; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: | |
| 4 | 추가: namespace Zipelo.Runtime; | |
| 5 | 추가: | |
| 6 | 추가: internal sealed class WindowsFolderPublication(string parent) : PendingFolderPublication | |
| 7 | 추가: { | |
| 8 | 추가: private readonly List<SafeFileHandle> ancestors = WindowsPublication.OpenParent(parent, readSecurity: true); | |
| 9 | 추가: | |
| 10 | 추가: internal override void Initialize() | |
| 11 | 추가: { | |
| 12 | 추가: WindowsFolderGuard.RequireNtfs(ancestors[^1]); | |
| 13 | 추가: WindowsFolderGuard.RequirePrivateWriters(ancestors[^1]); | |
| 14 | 추가: AddRoot(Create(ancestors[^1], TemporaryName, true)); | |
| 15 | 추가: } | |
| 16 | 추가: | |
| 17 | 추가: protected override SafeFileHandle Create(SafeFileHandle directory, string name, bool folder) | |
| 18 | 추가: => WindowsPublication.OpenRelative(directory, name, create: true, directory: folder, read: !folder); | |
| 19 | 추가: | |
| 20 | 추가: protected override string Inspect(SafeFileHandle handle, bool directory) | |
| 21 | 추가: => WindowsFolderGuard.Inspect(handle, directory); | |
| 22 | 추가: | |
| 23 | 추가: protected override void VerifyChildren(Node node, IReadOnlyCollection<string> names) | |
| 24 | 추가: => WindowsFolderGuard.VerifyChildren(node.Handle, names); | |
| 25 | 추가: | |
| 26 | 추가: internal override void Publish(string leaf, CancellationToken token) | |
| 27 | 추가: { | |
| 28 | 추가: // NTFS는 열린 자식 파일을 가진 디렉터리 rename을 허용하지 않음. | |
| 29 | 추가: // ACL 검증으로 다른 계정의 쓰기를 배제한 트리에서만 자식 핸들을 닫음. | |
| 30 | 추가: for (var index = Owned.Count - 1; index > 0; index--) | |
| 31 | 추가: { | |
| 32 | 추가: token.ThrowIfCancellationRequested(); | |
| 33 | 추가: Owned[index].Handle.Dispose(); | |
| 34 | 추가: } | |
| 35 | 추가: token.ThrowIfCancellationRequested(); | |
| 36 | 추가: WindowsPublication.Rename(Root.Handle, ancestors[^1], leaf); | |
| 37 | 추가: } | |
| 38 | 추가: | |
| 39 | 추가: private SafeFileHandle Reopen(Node node) | |
| 40 | 추가: { | |
| 41 | 추가: if (!node.Handle.IsClosed) { return node.Handle; } | |
| 42 | 추가: if (node.Parent is null) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 43 | 추가: var handle = WindowsPublication.OpenRelative(Reopen(node.Parent), node.Name, | |
| 44 | 추가: create: false, directory: node.Directory, reopenOwned: true); | |
| 45 | 추가: try | |
| 46 | 추가: { | |
| 47 | 추가: if (Inspect(handle, node.Directory) != node.Identity) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 48 | 추가: node.Handle = handle; | |
| 49 | 추가: return handle; | |
| 50 | 추가: } | |
| 51 | 추가: catch { handle.Dispose(); throw; } | |
| 52 | 추가: } | |
| 53 | 추가: | |
| 54 | 추가: internal override bool Abort() | |
| 55 | 추가: { | |
| 56 | 추가: var success = true; | |
| 57 | 추가: // 삭제 대상은 소유 핸들 또는 같은 파일 ID로 재확인한 핸들뿐임. | |
| 58 | 추가: for (var index = Owned.Count - 1; index >= 0; index--) | |
| 59 | 추가: { | |
| 60 | 추가: try | |
| 61 | 추가: { | |
| 62 | 추가: if (!WindowsPublication.DeleteOwned(Reopen(Owned[index]), out var failure)) | |
| 63 | 추가: { | |
| 64 | 추가: success = false; | |
| 65 | 추가: CleanupNativeFailure ??= failure; | |
| 66 | 추가: } | |
| 67 | 추가: } | |
| 68 | 추가: catch (PublicationNativeException failure) { success = false; CleanupNativeFailure ??= failure.Failure; } | |
| 69 | 추가: catch { success = false; } | |
| 70 | 추가: finally { Owned[index].Handle.Dispose(); } | |
| 71 | 추가: } | |
| 72 | 추가: return success; | |
| 73 | 추가: } | |
| 74 | 추가: | |
| 75 | 추가: public override void Dispose() | |
| 76 | 추가: { | |
| 77 | 추가: DisposeOwned(); | |
| 78 | 추가: for (var index = ancestors.Count - 1; index >= 0; index--) { ancestors[index].Dispose(); } | |
| 79 | 추가: } | |
| 80 | 추가: } |
| @@ -0,0 +1,260 @@ | ||
| 1 | 추가: using System.Runtime.InteropServices; | |
| 2 | 추가: using System.Text; | |
| 3 | 추가: using Microsoft.Win32.SafeHandles; | |
| 4 | 추가: using Zipelo.Core; | |
| 5 | 추가: | |
| 6 | 추가: namespace Zipelo.Runtime; | |
| 7 | 추가: | |
| 8 | 추가: internal sealed class WindowsPublication : PendingPublication | |
| 9 | 추가: { | |
| 10 | 추가: private readonly List<SafeFileHandle> directories; | |
| 11 | 추가: private readonly SafeFileHandle file; | |
| 12 | 추가: private readonly string temporaryName; | |
| 13 | 추가: private PublicationNativeFailure? cleanupNativeFailure; | |
| 14 | 추가: | |
| 15 | 추가: private WindowsPublication(List<SafeFileHandle> directories, SafeFileHandle file, string temporaryName) | |
| 16 | 추가: { | |
| 17 | 추가: this.directories = directories; | |
| 18 | 추가: this.file = file; | |
| 19 | 추가: this.temporaryName = temporaryName; | |
| 20 | 추가: } | |
| 21 | 추가: | |
| 22 | 추가: internal override SafeFileHandle Handle => file; | |
| 23 | 추가: internal override string TemporaryFileName => temporaryName; | |
| 24 | 추가: internal override PublicationNativeFailure? CleanupNativeFailure => cleanupNativeFailure; | |
| 25 | 추가: | |
| 26 | 추가: internal static List<SafeFileHandle> OpenParent(string parent, bool readSecurity = false) | |
| 27 | 추가: { | |
| 28 | 추가: var root = Path.GetPathRoot(parent); | |
| 29 | 추가: if (root is null || root.Length != 3 || !char.IsAsciiLetter(root[0]) || root[1] != ':' || root[2] != '\\') | |
| 30 | 추가: { | |
| 31 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 32 | 추가: } | |
| 33 | 추가: // UNC, 장치 경로와 네트워크 드라이브는 초기 게시 구현에서 제외함. | |
| 34 | 추가: if (GetDriveType(root) is not (2 or 3)) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 35 | 추가: var relative = parent[root.Length..]; | |
| 36 | 추가: var segments = relative.Length == 0 ? Array.Empty<string>() : | |
| 37 | 추가: OutputPathPolicy.Validate(relative, FileNamePolicy.Windows).ToArray(); | |
| 38 | 추가: var directories = new List<SafeFileHandle>(); | |
| 39 | 추가: try | |
| 40 | 추가: { | |
| 41 | 추가: var rootHandle = CreateFile(root, readSecurity ? 0x001200A0u : 0x001000A0u, 3, nint.Zero, 3, 0x02200000, nint.Zero); | |
| 42 | 추가: if (rootHandle.IsInvalid) | |
| 43 | 추가: { | |
| 44 | 추가: var error = unchecked((uint)Marshal.GetLastPInvokeError()); | |
| 45 | 추가: rootHandle.Dispose(); | |
| 46 | 추가: throw Error("CreateFileW", error); | |
| 47 | 추가: } | |
| 48 | 추가: directories.Add(rootHandle); | |
| 49 | 추가: RequireDirectory(rootHandle); | |
| 50 | 추가: foreach (var segment in segments) | |
| 51 | 추가: { | |
| 52 | 추가: var directory = OpenRelative(directories[^1], segment, create: false, readSecurity: readSecurity); | |
| 53 | 추가: directories.Add(directory); | |
| 54 | 추가: RequireDirectory(directory); | |
| 55 | 추가: } | |
| 56 | 추가: return directories; | |
| 57 | 추가: } | |
| 58 | 추가: catch | |
| 59 | 추가: { | |
| 60 | 추가: for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); } | |
| 61 | 추가: throw; | |
| 62 | 추가: } | |
| 63 | 추가: } | |
| 64 | 추가: | |
| 65 | 추가: internal static WindowsPublication Create(string parent) | |
| 66 | 추가: { | |
| 67 | 추가: var directories = OpenParent(parent); | |
| 68 | 추가: try | |
| 69 | 추가: { | |
| 70 | 추가: var temporaryName = $".zipelo-{Guid.NewGuid():N}.tmp"; | |
| 71 | 추가: var file = OpenRelative(directories[^1], temporaryName, create: true); | |
| 72 | 추가: return new(directories, file, temporaryName); | |
| 73 | 추가: } | |
| 74 | 추가: catch | |
| 75 | 추가: { | |
| 76 | 추가: for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); } | |
| 77 | 추가: throw; | |
| 78 | 추가: } | |
| 79 | 추가: } | |
| 80 | 추가: | |
| 81 | 추가: internal override void Publish(string leaf) => Rename(file, directories[^1], leaf); | |
| 82 | 추가: | |
| 83 | 추가: internal static void Rename(SafeFileHandle file, SafeFileHandle parent, string leaf) | |
| 84 | 추가: { | |
| 85 | 추가: var name = Encoding.Unicode.GetBytes(leaf); | |
| 86 | 추가: // FILE_RENAME_INFORMATION의 x64 배치와 후행 패딩을 포함함. 덮어쓰기 플래그는 0임. | |
| 87 | 추가: const int fileNameOffset = 20; | |
| 88 | 추가: var size = checked(Marshal.SizeOf<RenameInformation>() + name.Length); | |
| 89 | 추가: var buffer = Marshal.AllocHGlobal(size); | |
| 90 | 추가: try | |
| 91 | 추가: { | |
| 92 | 추가: Marshal.Copy(new byte[size], 0, buffer, size); | |
| 93 | 추가: Marshal.WriteIntPtr(buffer, 8, parent.DangerousGetHandle()); | |
| 94 | 추가: Marshal.WriteInt32(buffer, 16, name.Length); | |
| 95 | 추가: Marshal.Copy(name, 0, buffer + fileNameOffset, name.Length); | |
| 96 | 추가: // Win32 경로 변환을 거치지 않고 보유 부모 핸들에 상대적으로 게시함. | |
| 97 | 추가: var status = NtSetInformationFile(file, out _, buffer, (uint)size, 10); | |
| 98 | 추가: if (status < 0) | |
| 99 | 추가: { | |
| 100 | 추가: throw Error("NtSetInformationFile.FileRenameInformation", RtlNtStatusToDosError(status), status); | |
| 101 | 추가: } | |
| 102 | 추가: } | |
| 103 | 추가: finally { Marshal.FreeHGlobal(buffer); } | |
| 104 | 추가: } | |
| 105 | 추가: | |
| 106 | 추가: internal override bool Abort() => DeleteOwned(file, out cleanupNativeFailure); | |
| 107 | 추가: | |
| 108 | 추가: internal static bool DeleteOwned(SafeFileHandle file, out PublicationNativeFailure? failure) | |
| 109 | 추가: { | |
| 110 | 추가: failure = null; | |
| 111 | 추가: var buffer = Marshal.AllocHGlobal(1); | |
| 112 | 추가: try | |
| 113 | 추가: { | |
| 114 | 추가: // 작업 소유 핸들에 삭제를 표시함. 경로를 다시 열거나 삭제하지 않음. | |
| 115 | 추가: Marshal.WriteByte(buffer, 1); | |
| 116 | 추가: if (SetFileInformation(file, 4, buffer, 1)) { return true; } | |
| 117 | 추가: var error = unchecked((uint)Marshal.GetLastPInvokeError()); | |
| 118 | 추가: failure = new("SetFileInformationByHandle.FileDispositionInfo", error); | |
| 119 | 추가: return false; | |
| 120 | 추가: } | |
| 121 | 추가: finally { Marshal.FreeHGlobal(buffer); } | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: public override void Dispose() | |
| 125 | 추가: { | |
| 126 | 추가: file.Dispose(); | |
| 127 | 추가: for (var index = directories.Count - 1; index >= 0; index--) { directories[index].Dispose(); } | |
| 128 | 추가: } | |
| 129 | 추가: | |
| 130 | 추가: internal static SafeFileHandle OpenRelative(SafeFileHandle parent, string name, bool create, | |
| 131 | 추가: bool directory = false, bool read = false, bool reopenOwned = false, bool readSecurity = false) | |
| 132 | 추가: { | |
| 133 | 추가: var nameBuffer = Marshal.StringToHGlobalUni(name); | |
| 134 | 추가: var unicodeBuffer = Marshal.AllocHGlobal(Marshal.SizeOf<UnicodeString>()); | |
| 135 | 추가: try | |
| 136 | 추가: { | |
| 137 | 추가: var unicode = new UnicodeString | |
| 138 | 추가: { | |
| 139 | 추가: Length = checked((ushort)(name.Length * 2)), | |
| 140 | 추가: MaximumLength = checked((ushort)((name.Length + 1) * 2)), | |
| 141 | 추가: Buffer = nameBuffer | |
| 142 | 추가: }; | |
| 143 | 추가: Marshal.StructureToPtr(unicode, unicodeBuffer, false); | |
| 144 | 추가: var attributes = new ObjectAttributes | |
| 145 | 추가: { | |
| 146 | 추가: Length = Marshal.SizeOf<ObjectAttributes>(), | |
| 147 | 추가: RootDirectory = parent.DangerousGetHandle(), | |
| 148 | 추가: ObjectName = unicodeBuffer, | |
| 149 | 추가: Attributes = 0x1040 | |
| 150 | 추가: }; | |
| 151 | 추가: // 디렉터리는 삭제 공유 없이 고정하고 최종 reparse point도 따라가지 않음. | |
| 152 | 추가: var access = reopenOwned ? 0x001300A1u : !create ? 0x001000A0u : directory ? 0x001300A3u : read ? 0xC0110000u : 0x40110000u; | |
| 153 | 추가: if (readSecurity) { access |= 0x20000; } | |
| 154 | 추가: var options = 0x00200020u | (directory ? 1u : create ? 0x40u : 0u); | |
| 155 | 추가: var status = NtCreateFile(out var handle, access, | |
| 156 | 추가: ref attributes, out _, nint.Zero, create && !directory ? 0x100u : 0u, (create || reopenOwned) ? 0u : 3u, | |
| 157 | 추가: create ? 2u : 1u, options, nint.Zero, 0); | |
| 158 | 추가: if (status < 0) | |
| 159 | 추가: { | |
| 160 | 추가: handle.Dispose(); | |
| 161 | 추가: throw Error("NtCreateFile", RtlNtStatusToDosError(status), status); | |
| 162 | 추가: } | |
| 163 | 추가: return handle; | |
| 164 | 추가: } | |
| 165 | 추가: finally | |
| 166 | 추가: { | |
| 167 | 추가: Marshal.FreeHGlobal(unicodeBuffer); | |
| 168 | 추가: Marshal.FreeHGlobal(nameBuffer); | |
| 169 | 추가: } | |
| 170 | 추가: } | |
| 171 | 추가: | |
| 172 | 추가: private static void RequireDirectory(SafeFileHandle handle) | |
| 173 | 추가: { | |
| 174 | 추가: if (!GetFileInformation(handle, 9, out var info, (uint)Marshal.SizeOf<AttributeTagInfo>())) { ThrowLastError("GetFileInformationByHandleEx"); } | |
| 175 | 추가: if ((info.Attributes & 0x10) == 0 || (info.Attributes & 0x400) != 0) | |
| 176 | 추가: { | |
| 177 | 추가: throw new ArchiveException(ArchiveError.UnsafePath); | |
| 178 | 추가: } | |
| 179 | 추가: } | |
| 180 | 추가: | |
| 181 | 추가: private static void ThrowLastError(string operation) | |
| 182 | 추가: { | |
| 183 | 추가: var error = unchecked((uint)Marshal.GetLastPInvokeError()); | |
| 184 | 추가: throw Error(operation, error); | |
| 185 | 추가: } | |
| 186 | 추가: | |
| 187 | 추가: private static PublicationNativeException Error(string operation, uint error, int? status = null) => new( | |
| 188 | 추가: error is 80 or 183 ? ArchiveError.OutputConflict : ArchiveError.OutputUnavailable, | |
| 189 | 추가: new(operation, error, status)); | |
| 190 | 추가: | |
| 191 | 추가: [StructLayout(LayoutKind.Explicit, Size = 24)] | |
| 192 | 추가: private struct RenameInformation | |
| 193 | 추가: { | |
| 194 | 추가: [FieldOffset(0)] internal uint Flags; | |
| 195 | 추가: [FieldOffset(8)] internal nint RootDirectory; | |
| 196 | 추가: [FieldOffset(16)] internal uint FileNameLength; | |
| 197 | 추가: [FieldOffset(20)] internal ushort FirstCharacter; | |
| 198 | 추가: } | |
| 199 | 추가: | |
| 200 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 201 | 추가: private struct UnicodeString | |
| 202 | 추가: { | |
| 203 | 추가: internal ushort Length; | |
| 204 | 추가: internal ushort MaximumLength; | |
| 205 | 추가: internal nint Buffer; | |
| 206 | 추가: } | |
| 207 | 추가: | |
| 208 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 209 | 추가: private struct ObjectAttributes | |
| 210 | 추가: { | |
| 211 | 추가: internal int Length; | |
| 212 | 추가: internal nint RootDirectory; | |
| 213 | 추가: internal nint ObjectName; | |
| 214 | 추가: internal uint Attributes; | |
| 215 | 추가: internal nint SecurityDescriptor; | |
| 216 | 추가: internal nint SecurityQualityOfService; | |
| 217 | 추가: } | |
| 218 | 추가: | |
| 219 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 220 | 추가: private struct IoStatusBlock | |
| 221 | 추가: { | |
| 222 | 추가: internal nint Status; | |
| 223 | 추가: internal nuint Information; | |
| 224 | 추가: } | |
| 225 | 추가: | |
| 226 | 추가: [StructLayout(LayoutKind.Sequential)] | |
| 227 | 추가: private struct AttributeTagInfo | |
| 228 | 추가: { | |
| 229 | 추가: internal uint Attributes; | |
| 230 | 추가: internal uint ReparseTag; | |
| 231 | 추가: } | |
| 232 | 추가: | |
| 233 | 추가: [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] | |
| 234 | 추가: private static extern SafeFileHandle CreateFile(string path, uint access, uint share, nint security, | |
| 235 | 추가: uint disposition, uint flags, nint template); | |
| 236 | 추가: | |
| 237 | 추가: [DllImport("kernel32.dll", EntryPoint = "GetDriveTypeW", CharSet = CharSet.Unicode)] | |
| 238 | 추가: private static extern uint GetDriveType(string root); | |
| 239 | 추가: | |
| 240 | 추가: [DllImport("kernel32.dll", EntryPoint = "GetFileInformationByHandleEx", SetLastError = true)] | |
| 241 | 추가: [return: MarshalAs(UnmanagedType.Bool)] | |
| 242 | 추가: private static extern bool GetFileInformation(SafeFileHandle file, int informationClass, | |
| 243 | 추가: out AttributeTagInfo information, uint size); | |
| 244 | 추가: | |
| 245 | 추가: [DllImport("kernel32.dll", EntryPoint = "SetFileInformationByHandle", SetLastError = true)] | |
| 246 | 추가: [return: MarshalAs(UnmanagedType.Bool)] | |
| 247 | 추가: private static extern bool SetFileInformation(SafeFileHandle file, int informationClass, nint information, uint size); | |
| 248 | 추가: | |
| 249 | 추가: [DllImport("ntdll.dll")] | |
| 250 | 추가: private static extern int NtCreateFile(out SafeFileHandle file, uint access, ref ObjectAttributes attributes, | |
| 251 | 추가: out IoStatusBlock status, nint allocationSize, uint fileAttributes, uint share, uint disposition, | |
| 252 | 추가: uint options, nint extendedAttributes, uint extendedAttributesLength); | |
| 253 | 추가: | |
| 254 | 추가: [DllImport("ntdll.dll")] | |
| 255 | 추가: private static extern int NtSetInformationFile(SafeFileHandle file, out IoStatusBlock status, | |
| 256 | 추가: nint information, uint size, int informationClass); | |
| 257 | 추가: | |
| 258 | 추가: [DllImport("ntdll.dll")] | |
| 259 | 추가: private static extern uint RtlNtStatusToDosError(int status); | |
| 260 | 추가: } |
| @@ -0,0 +1,16 @@ | ||
| 1 | 추가: namespace Zipelo.Runtime; | |
| 2 | 추가: | |
| 3 | 추가: public static class WorkerPlatform | |
| 4 | 추가: { | |
| 5 | 추가: public static string ExecutableName => OperatingSystem.IsWindows() ? "Zipelo.Worker.exe" : | |
| 6 | 추가: OperatingSystem.IsLinux() ? "Zipelo.Worker" : throw new PlatformNotSupportedException(); | |
| 7 | 추가: | |
| 8 | 추가: public static string GetWorkerPath(string applicationDirectory) | |
| 9 | 추가: { | |
| 10 | 추가: if (!Path.IsPathFullyQualified(applicationDirectory)) | |
| 11 | 추가: { | |
| 12 | 추가: throw new ArgumentException("앱 설치 폴더의 절대 경로가 필요함", nameof(applicationDirectory)); | |
| 13 | 추가: } | |
| 14 | 추가: return Path.Combine(applicationDirectory, "worker", ExecutableName); | |
| 15 | 추가: } | |
| 16 | 추가: } |
| @@ -0,0 +1,63 @@ | ||
| 1 | 추가: using System.Buffers.Binary; | |
| 2 | 추가: using System.Runtime.CompilerServices; | |
| 3 | 추가: using System.Text.Json; | |
| 4 | 추가: using Zipelo.Core; | |
| 5 | 추가: | |
| 6 | 추가: [assembly: InternalsVisibleTo("Zipelo.Worker")] | |
| 7 | 추가: | |
| 8 | 추가: namespace Zipelo.Runtime; | |
| 9 | 추가: | |
| 10 | 추가: public sealed record ZipCreateInput(string EntryName, Stream Content); | |
| 11 | 추가: public sealed record ZipCreationOptions(bool Encrypt = false, long? SplitVolumeBytes = null); | |
| 12 | 추가: | |
| 13 | 추가: // ZIP 바이트의 메모리 전달 결과임. 디스크 저장이나 해제 완료를 뜻하지 않음. | |
| 14 | 추가: public sealed record ZipWorkerResult(JobResult Job, byte[]? CreatedZip) | |
| 15 | 추가: { | |
| 16 | 추가: // 해제된 바이트는 메모리 검증 결과임. 디스크 게시 성공을 뜻하지 않음. | |
| 17 | 추가: public IReadOnlyList<ZipExtractedEntry>? ExtractedEntries { get; init; } | |
| 18 | 추가: } | |
| 19 | 추가: | |
| 20 | 추가: internal sealed record WorkerRequest(Guid JobId, ArchiveAction Action, byte[][] Inputs, string[] Names, JobLimits Limits); | |
| 21 | 추가: | |
| 22 | 추가: internal static class WorkerProtocol | |
| 23 | 추가: { | |
| 24 | 추가: internal const int MaxDataBytes = 16 * 1024 * 1024; | |
| 25 | 추가: internal const int MaxFrameBytes = 32 * 1024 * 1024; | |
| 26 | 추가: internal const int MaxEntries = 1024; | |
| 27 | 추가: internal const int MaxNameLength = 1024; | |
| 28 | 추가: | |
| 29 | 추가: internal static void ValidateLimits(JobLimits limits) | |
| 30 | 추가: { | |
| 31 | 추가: _ = new JobBudget(limits); | |
| 32 | 추가: if (limits.MaxDuration > TimeSpan.FromMinutes(5)) | |
| 33 | 추가: { | |
| 34 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 35 | 추가: } | |
| 36 | 추가: } | |
| 37 | 추가: | |
| 38 | 추가: internal static ZipWorkerResult Failure(Guid id, ArchiveError error) => new( | |
| 39 | 추가: new(id, error == ArchiveError.Cancelled ? JobState.Cancelled : JobState.Failed, | |
| 40 | 추가: Array.Empty<EntryResult>(), error), null); | |
| 41 | 추가: | |
| 42 | 추가: internal static async Task WriteAsync<T>(Stream stream, T value, CancellationToken token) | |
| 43 | 추가: { | |
| 44 | 추가: var payload = JsonSerializer.SerializeToUtf8Bytes(value); | |
| 45 | 추가: if (payload.Length > MaxFrameBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 46 | 추가: var header = new byte[4]; | |
| 47 | 추가: BinaryPrimitives.WriteInt32LittleEndian(header, payload.Length); | |
| 48 | 추가: await stream.WriteAsync(header, token).ConfigureAwait(false); | |
| 49 | 추가: await stream.WriteAsync(payload, token).ConfigureAwait(false); | |
| 50 | 추가: await stream.FlushAsync(token).ConfigureAwait(false); | |
| 51 | 추가: } | |
| 52 | 추가: | |
| 53 | 추가: internal static async Task<T> ReadAsync<T>(Stream stream, CancellationToken token) | |
| 54 | 추가: { | |
| 55 | 추가: var header = new byte[4]; | |
| 56 | 추가: await stream.ReadExactlyAsync(header, token).ConfigureAwait(false); | |
| 57 | 추가: var length = BinaryPrimitives.ReadInt32LittleEndian(header); | |
| 58 | 추가: if (length <= 0 || length > MaxFrameBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 59 | 추가: var payload = new byte[length]; | |
| 60 | 추가: await stream.ReadExactlyAsync(payload, token).ConfigureAwait(false); | |
| 61 | 추가: return JsonSerializer.Deserialize<T>(payload) ?? throw new ArchiveException(ArchiveError.EngineFailure); | |
| 62 | 추가: } | |
| 63 | 추가: } |
| @@ -0,0 +1,89 @@ | ||
| 1 | 추가: using Zipelo.Core; | |
| 2 | 추가: | |
| 3 | 추가: namespace Zipelo.Runtime; | |
| 4 | 추가: | |
| 5 | 추가: public sealed record ZipExtractedEntry(ArchiveEntry Entry, byte[] Content, uint Crc32); | |
| 6 | 추가: | |
| 7 | 추가: internal static class ZipExtraction | |
| 8 | 추가: { | |
| 9 | 추가: internal static void ValidatePaths(IReadOnlyList<ArchiveEntry> entries) | |
| 10 | 추가: { | |
| 11 | 추가: if (entries.Count > WorkerProtocol.MaxEntries) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 12 | 추가: var comparer = OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy); | |
| 13 | 추가: var explicitPaths = new HashSet<string>(comparer); | |
| 14 | 추가: var nodes = new Dictionary<string, EntryKind>(comparer); | |
| 15 | 추가: var ids = new HashSet<string>(StringComparer.Ordinal); | |
| 16 | 추가: foreach (var entry in entries) | |
| 17 | 추가: { | |
| 18 | 추가: if (entry is null || string.IsNullOrEmpty(entry.Id) || !ids.Add(entry.Id) || | |
| 19 | 추가: entry.Kind is not (EntryKind.File or EntryKind.Directory) || entry.DeclaredSize is null or < 0) | |
| 20 | 추가: { | |
| 21 | 추가: throw new ArchiveException(ArchiveError.UnsupportedEntry); | |
| 22 | 추가: } | |
| 23 | 추가: if (entry.Name.Length > WorkerProtocol.MaxNameLength) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 24 | 추가: var segments = OutputPathPolicy.Validate(entry.Name, OutputPathPolicy.CurrentPolicy); | |
| 25 | 추가: if (segments.Count > 32) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 26 | 추가: var path = string.Join('/', segments); | |
| 27 | 추가: if (!explicitPaths.Add(path)) { throw new ArchiveException(ArchiveError.OutputConflict); } | |
| 28 | 추가: for (var index = 0; index < segments.Count; index++) | |
| 29 | 추가: { | |
| 30 | 추가: var prefix = string.Join('/', segments.Take(index + 1)); | |
| 31 | 추가: var kind = index == segments.Count - 1 ? entry.Kind : EntryKind.Directory; | |
| 32 | 추가: if (nodes.TryGetValue(prefix, out var existing) && (existing != kind || kind == EntryKind.File)) | |
| 33 | 추가: { | |
| 34 | 추가: throw new ArchiveException(ArchiveError.OutputConflict); | |
| 35 | 추가: } | |
| 36 | 추가: nodes[prefix] = kind; | |
| 37 | 추가: if (nodes.Count > 4096) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 38 | 추가: } | |
| 39 | 추가: } | |
| 40 | 추가: } | |
| 41 | 추가: | |
| 42 | 추가: internal static ZipExtractedEntry[] ValidateResult(ZipWorkerResult result, CancellationToken token, bool snapshot) | |
| 43 | 추가: { | |
| 44 | 추가: if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None || | |
| 45 | 추가: result.CreatedZip is not null || result.ExtractedEntries is null || | |
| 46 | 추가: result.ExtractedEntries.Count != result.Job.Entries.Count) | |
| 47 | 추가: { | |
| 48 | 추가: throw new ArchiveException(ArchiveError.EngineFailure); | |
| 49 | 추가: } | |
| 50 | 추가: var items = result.ExtractedEntries.ToArray(); | |
| 51 | 추가: ValidatePaths(items.Select(item => item.Entry).ToArray()); | |
| 52 | 추가: long total = 0; | |
| 53 | 추가: for (var index = 0; index < items.Length; index++) | |
| 54 | 추가: { | |
| 55 | 추가: token.ThrowIfCancellationRequested(); | |
| 56 | 추가: var item = items[index]; | |
| 57 | 추가: var report = result.Job.Entries[index]; | |
| 58 | 추가: if (item.Content is null || report.Entry != item.Entry || report.Error != ArchiveError.None || | |
| 59 | 추가: report.Verification != VerificationState.Passed || report.Outcome != EntryOutcome.Staged || | |
| 60 | 추가: item.Entry.DeclaredSize != item.Content.LongLength || | |
| 61 | 추가: (item.Entry.Kind == EntryKind.Directory && item.Content.Length != 0)) | |
| 62 | 추가: { | |
| 63 | 추가: throw new ArchiveException(ArchiveError.EngineFailure); | |
| 64 | 추가: } | |
| 65 | 추가: total += item.Content.Length; | |
| 66 | 추가: if (total > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 67 | 추가: var bytes = snapshot ? item.Content.ToArray() : item.Content; | |
| 68 | 추가: var crc = uint.MaxValue; | |
| 69 | 추가: for (var offset = 0; offset < bytes.Length; offset += 65536) | |
| 70 | 추가: { | |
| 71 | 추가: token.ThrowIfCancellationRequested(); | |
| 72 | 추가: crc = UpdateCrc(crc, bytes.AsSpan(offset, Math.Min(65536, bytes.Length - offset))); | |
| 73 | 추가: } | |
| 74 | 추가: if (~crc != item.Crc32) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 75 | 추가: items[index] = item with { Content = bytes }; | |
| 76 | 추가: } | |
| 77 | 추가: return items; | |
| 78 | 추가: } | |
| 79 | 추가: | |
| 80 | 추가: internal static uint UpdateCrc(uint crc, ReadOnlySpan<byte> bytes) | |
| 81 | 추가: { | |
| 82 | 추가: foreach (var value in bytes) | |
| 83 | 추가: { | |
| 84 | 추가: crc ^= value; | |
| 85 | 추가: for (var bit = 0; bit < 8; bit++) { crc = (crc >> 1) ^ ((crc & 1) != 0 ? 0xEDB88320u : 0u); } | |
| 86 | 추가: } | |
| 87 | 추가: return crc; | |
| 88 | 추가: } | |
| 89 | 추가: } |
| @@ -0,0 +1,179 @@ | ||
| 1 | 추가: using System.Diagnostics; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: | |
| 4 | 추가: namespace Zipelo.Runtime; | |
| 5 | 추가: | |
| 6 | 추가: public sealed class ZipWorkerClient | |
| 7 | 추가: { | |
| 8 | 추가: private readonly string workerPath; | |
| 9 | 추가: private readonly string? dotnetHostPath; | |
| 10 | 추가: private static readonly IReadOnlyCollection<EngineCapability> Supported = Array.AsReadOnly(new[] | |
| 11 | 추가: { | |
| 12 | 추가: new EngineCapability("zip", ArchiveAction.List), | |
| 13 | 추가: new EngineCapability("zip", ArchiveAction.Create) | |
| 14 | 추가: }); | |
| 15 | 추가: | |
| 16 | 추가: // 호출자가 신뢰하는 앱 배포 경로만 전달함. 압축파일에서 실행 경로를 얻지 않음. | |
| 17 | 추가: public ZipWorkerClient(string workerPath, string? dotnetHostPath = null) | |
| 18 | 추가: { | |
| 19 | 추가: if (!Path.IsPathFullyQualified(workerPath) || | |
| 20 | 추가: (dotnetHostPath is not null && !Path.IsPathFullyQualified(dotnetHostPath))) | |
| 21 | 추가: { | |
| 22 | 추가: throw new ArgumentException("작업자와 호스트의 절대 경로가 필요함"); | |
| 23 | 추가: } | |
| 24 | 추가: this.workerPath = workerPath; | |
| 25 | 추가: this.dotnetHostPath = dotnetHostPath; | |
| 26 | 추가: } | |
| 27 | 추가: | |
| 28 | 추가: public bool IsAvailable => File.Exists(workerPath) && | |
| 29 | 추가: (!workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || | |
| 30 | 추가: (dotnetHostPath is not null && File.Exists(dotnetHostPath))); | |
| 31 | 추가: public IReadOnlyCollection<EngineCapability> Capabilities => IsAvailable ? Supported : Array.Empty<EngineCapability>(); | |
| 32 | 추가: public bool SupportsEncryption => false; | |
| 33 | 추가: public bool SupportsSplitVolumes => false; | |
| 34 | 추가: public bool SupportsSafeExtraction => false; | |
| 35 | 추가: public bool SupportsFilePublication => NewZipPublisher.IsSupportedPlatform; | |
| 36 | 추가: | |
| 37 | 추가: // 입력은 읽기 전용 스트림의 현재 위치부터 복사하며 수명은 호출자가 소유함. | |
| 38 | 추가: public Task<ZipWorkerResult> ListAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token) | |
| 39 | 추가: => ExecuteAsync(jobId, ArchiveAction.List, new[] { zip }, Array.Empty<string>(), limits, token); | |
| 40 | 추가: | |
| 41 | 추가: public Task<ZipWorkerResult> ExtractAsync(Guid jobId, Stream zip, JobLimits limits, CancellationToken token) | |
| 42 | 추가: => ExecuteAsync(jobId, ArchiveAction.Extract, new[] { zip }, Array.Empty<string>(), limits, token); | |
| 43 | 추가: | |
| 44 | 추가: // 일반 UI 해제 능력은 OS별 저장 검증 뒤에 별도로 활성화함. | |
| 45 | 추가: public bool SupportsMemoryExtraction => IsAvailable; | |
| 46 | 추가: | |
| 47 | 추가: public Task<ZipWorkerResult> CreateAsync(Guid jobId, IReadOnlyList<ZipCreateInput> inputs, | |
| 48 | 추가: JobLimits limits, ZipCreationOptions? options, CancellationToken token) | |
| 49 | 추가: { | |
| 50 | 추가: ArgumentNullException.ThrowIfNull(inputs); | |
| 51 | 추가: if (options is { Encrypt: true } || options?.SplitVolumeBytes is not null) | |
| 52 | 추가: { | |
| 53 | 추가: return Task.FromResult(WorkerProtocol.Failure(jobId, ArchiveError.UnsupportedOperation)); | |
| 54 | 추가: } | |
| 55 | 추가: return ExecuteAsync(jobId, ArchiveAction.Create, inputs.Select(input => input.Content).ToArray(), | |
| 56 | 추가: inputs.Select(input => input.EntryName).ToArray(), limits, token); | |
| 57 | 추가: } | |
| 58 | 추가: | |
| 59 | 추가: private async Task<ZipWorkerResult> ExecuteAsync(Guid jobId, ArchiveAction action, | |
| 60 | 추가: IReadOnlyList<Stream> inputs, string[] names, JobLimits limits, CancellationToken token) | |
| 61 | 추가: { | |
| 62 | 추가: Process? process = null; | |
| 63 | 추가: var started = false; | |
| 64 | 추가: Task? drain = null; | |
| 65 | 추가: using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); | |
| 66 | 추가: try | |
| 67 | 추가: { | |
| 68 | 추가: if (jobId == Guid.Empty) { throw new ArchiveException(ArchiveError.UnsupportedOperation); } | |
| 69 | 추가: WorkerProtocol.ValidateLimits(limits); | |
| 70 | 추가: deadline.CancelAfter(limits.MaxDuration); | |
| 71 | 추가: var operationToken = deadline.Token; | |
| 72 | 추가: operationToken.ThrowIfCancellationRequested(); | |
| 73 | 추가: if (!IsAvailable) { throw new ArchiveException(ArchiveError.EngineUnavailable); } | |
| 74 | 추가: if (inputs.Count == 0 || inputs.Count > WorkerProtocol.MaxEntries || | |
| 75 | 추가: names.Any(name => name is null || name.Length > WorkerProtocol.MaxNameLength)) | |
| 76 | 추가: { | |
| 77 | 추가: throw new ArchiveException(ArchiveError.BudgetExceeded); | |
| 78 | 추가: } | |
| 79 | 추가: | |
| 80 | 추가: var copies = new byte[inputs.Count][]; | |
| 81 | 추가: long total = 0; | |
| 82 | 추가: var buffer = new byte[64 * 1024]; | |
| 83 | 추가: for (var index = 0; index < inputs.Count; index++) | |
| 84 | 추가: { | |
| 85 | 추가: var source = inputs[index]; | |
| 86 | 추가: if (source is null || !source.CanRead || source.CanWrite) | |
| 87 | 추가: { | |
| 88 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 89 | 추가: } | |
| 90 | 추가: using var copy = new MemoryStream(); | |
| 91 | 추가: int count; | |
| 92 | 추가: while ((count = await source.ReadAsync(buffer, operationToken).ConfigureAwait(false)) != 0) | |
| 93 | 추가: { | |
| 94 | 추가: total += count; | |
| 95 | 추가: if (total > WorkerProtocol.MaxDataBytes || total > limits.MaxProcessedBytes) | |
| 96 | 추가: { | |
| 97 | 추가: throw new ArchiveException(ArchiveError.BudgetExceeded); | |
| 98 | 추가: } | |
| 99 | 추가: copy.Write(buffer, 0, count); | |
| 100 | 추가: } | |
| 101 | 추가: copies[index] = copy.ToArray(); | |
| 102 | 추가: } | |
| 103 | 추가: | |
| 104 | 추가: var start = new ProcessStartInfo | |
| 105 | 추가: { | |
| 106 | 추가: FileName = workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? dotnetHostPath! : workerPath, | |
| 107 | 추가: UseShellExecute = false, | |
| 108 | 추가: CreateNoWindow = true, | |
| 109 | 추가: RedirectStandardInput = true, | |
| 110 | 추가: RedirectStandardOutput = true, | |
| 111 | 추가: RedirectStandardError = true | |
| 112 | 추가: }; | |
| 113 | 추가: if (workerPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { start.ArgumentList.Add(workerPath); } | |
| 114 | 추가: process = new Process { StartInfo = start }; | |
| 115 | 추가: if (!process.Start()) { throw new ArchiveException(ArchiveError.EngineUnavailable); } | |
| 116 | 추가: // stderr는 보관하거나 UI에 노출하지 않고 배출함. | |
| 117 | 추가: started = true; | |
| 118 | 추가: drain = process.StandardError.BaseStream.CopyToAsync(Stream.Null, operationToken); | |
| 119 | 추가: await WorkerProtocol.WriteAsync(process.StandardInput.BaseStream, | |
| 120 | 추가: new WorkerRequest(jobId, action, copies, names, limits), operationToken).ConfigureAwait(false); | |
| 121 | 추가: process.StandardInput.Close(); | |
| 122 | 추가: var result = await WorkerProtocol.ReadAsync<ZipWorkerResult>(process.StandardOutput.BaseStream, operationToken) | |
| 123 | 추가: .ConfigureAwait(false); | |
| 124 | 추가: await process.WaitForExitAsync(operationToken).ConfigureAwait(false); | |
| 125 | 추가: await drain.ConfigureAwait(false); | |
| 126 | 추가: if (process.ExitCode != 0 || result.Job.JobId != jobId || | |
| 127 | 추가: result.Job.State is not (JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed) || | |
| 128 | 추가: (result.Job.State == JobState.Completed && result.Job.Error != ArchiveError.None) || | |
| 129 | 추가: result.Job.Entries.Count > WorkerProtocol.MaxEntries + 1 || | |
| 130 | 추가: result.CreatedZip?.Length > WorkerProtocol.MaxDataBytes || | |
| 131 | 추가: (action == ArchiveAction.Create && result.Job.State == JobState.Completed && result.CreatedZip is null) || | |
| 132 | 추가: (result.CreatedZip is not null && (action != ArchiveAction.Create || result.Job.State != JobState.Completed))) | |
| 133 | 추가: { | |
| 134 | 추가: throw new ArchiveException(ArchiveError.EngineFailure); | |
| 135 | 추가: } | |
| 136 | 추가: if (action == ArchiveAction.Extract && result.Job.State == JobState.Completed) | |
| 137 | 추가: { | |
| 138 | 추가: _ = ZipExtraction.ValidateResult(result, operationToken, snapshot: false); | |
| 139 | 추가: } | |
| 140 | 추가: else if (result.ExtractedEntries is not null) | |
| 141 | 추가: { | |
| 142 | 추가: throw new ArchiveException(ArchiveError.EngineFailure); | |
| 143 | 추가: } | |
| 144 | 추가: return result; | |
| 145 | 추가: } | |
| 146 | 추가: catch (OperationCanceledException) when (deadline.IsCancellationRequested) | |
| 147 | 추가: { | |
| 148 | 추가: return WorkerProtocol.Failure(jobId, token.IsCancellationRequested ? ArchiveError.Cancelled : ArchiveError.BudgetExceeded); | |
| 149 | 추가: } | |
| 150 | 추가: catch (ArchiveException failure) { return WorkerProtocol.Failure(jobId, failure.Code); } | |
| 151 | 추가: catch (ArgumentException) { return WorkerProtocol.Failure(jobId, ArchiveError.UnsupportedOperation); } | |
| 152 | 추가: catch { return WorkerProtocol.Failure(jobId, ArchiveError.EngineFailure); } | |
| 153 | 추가: finally | |
| 154 | 추가: { | |
| 155 | 추가: if (process is not null) | |
| 156 | 추가: { | |
| 157 | 추가: try | |
| 158 | 추가: { | |
| 159 | 추가: // 취소 응답 전에 실제 작업자 종료를 기다림. 종료 실패를 성공으로 숨기지 않음. | |
| 160 | 추가: if (started && !process.HasExited) | |
| 161 | 추가: { | |
| 162 | 추가: process.Kill(entireProcessTree: true); | |
| 163 | 추가: await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); | |
| 164 | 추가: } | |
| 165 | 추가: } | |
| 166 | 추가: finally | |
| 167 | 추가: { | |
| 168 | 추가: deadline.Cancel(); | |
| 169 | 추가: if (drain is not null) | |
| 170 | 추가: { | |
| 171 | 추가: try { await drain.ConfigureAwait(false); } | |
| 172 | 추가: catch { } | |
| 173 | 추가: } | |
| 174 | 추가: process.Dispose(); | |
| 175 | 추가: } | |
| 176 | 추가: } | |
| 177 | 추가: } | |
| 178 | 추가: } | |
| 179 | 추가: } |
| @@ -0,0 +1,11 @@ | ||
| 1 | 추가: <Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 추가: <PropertyGroup> | |
| 3 | 추가: <TargetFramework>net10.0</TargetFramework> | |
| 4 | 추가: <Nullable>enable</Nullable> | |
| 5 | 추가: <ImplicitUsings>enable</ImplicitUsings> | |
| 6 | 추가: <TreatWarningsAsErrors>true</TreatWarningsAsErrors> | |
| 7 | 추가: </PropertyGroup> | |
| 8 | 추가: <ItemGroup> | |
| 9 | 추가: <ProjectReference Include="../Zipelo.Core/Zipelo.Core.csproj" /> | |
| 10 | 추가: </ItemGroup> | |
| 11 | 추가: </Project> |
| @@ -0,0 +1,83 @@ | ||
| 1 | 추가: using Zipelo.Core; | |
| 2 | 추가: using Zipelo.Runtime; | |
| 3 | 추가: | |
| 4 | 추가: namespace Zipelo.Worker; | |
| 5 | 추가: | |
| 6 | 추가: internal sealed class BoundedMemoryStream(long limit) : MemoryStream | |
| 7 | 추가: { | |
| 8 | 추가: private void CheckWrite(int count) | |
| 9 | 추가: { | |
| 10 | 추가: if (count < 0 || Position > limit - count) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 11 | 추가: } | |
| 12 | 추가: | |
| 13 | 추가: public override void Write(byte[] buffer, int offset, int count) | |
| 14 | 추가: { | |
| 15 | 추가: CheckWrite(count); | |
| 16 | 추가: base.Write(buffer, offset, count); | |
| 17 | 추가: } | |
| 18 | 추가: | |
| 19 | 추가: public override void Write(ReadOnlySpan<byte> buffer) | |
| 20 | 추가: { | |
| 21 | 추가: CheckWrite(buffer.Length); | |
| 22 | 추가: base.Write(buffer); | |
| 23 | 추가: } | |
| 24 | 추가: | |
| 25 | 추가: public override void WriteByte(byte value) | |
| 26 | 추가: { | |
| 27 | 추가: CheckWrite(1); | |
| 28 | 추가: base.WriteByte(value); | |
| 29 | 추가: } | |
| 30 | 추가: | |
| 31 | 추가: public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) | |
| 32 | 추가: { | |
| 33 | 추가: token.ThrowIfCancellationRequested(); | |
| 34 | 추가: Write(buffer, offset, count); | |
| 35 | 추가: return Task.CompletedTask; | |
| 36 | 추가: } | |
| 37 | 추가: | |
| 38 | 추가: public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) | |
| 39 | 추가: { | |
| 40 | 추가: token.ThrowIfCancellationRequested(); | |
| 41 | 추가: Write(buffer.Span); | |
| 42 | 추가: return ValueTask.CompletedTask; | |
| 43 | 추가: } | |
| 44 | 추가: | |
| 45 | 추가: public override void SetLength(long value) | |
| 46 | 추가: { | |
| 47 | 추가: if (value < 0 || value > limit) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 48 | 추가: base.SetLength(value); | |
| 49 | 추가: } | |
| 50 | 추가: } | |
| 51 | 추가: | |
| 52 | 추가: // 디스크 저장 없이 단일 ZIP 생성물을 메모리에 확정함. | |
| 53 | 추가: internal sealed class BoundedMemoryOutput : IOutputTransaction | |
| 54 | 추가: { | |
| 55 | 추가: private BoundedMemoryStream? pending; | |
| 56 | 추가: public byte[]? CommittedBytes { get; private set; } | |
| 57 | 추가: | |
| 58 | 추가: public ValueTask<Stream> CreateFileAsync(IReadOnlyList<string> segments, CancellationToken token) | |
| 59 | 추가: { | |
| 60 | 추가: token.ThrowIfCancellationRequested(); | |
| 61 | 추가: if (pending is not null || segments.Count != 1 || segments[0] != "archive.zip") | |
| 62 | 추가: { | |
| 63 | 추가: throw new ArchiveException(ArchiveError.OutputConflict); | |
| 64 | 추가: } | |
| 65 | 추가: pending = new BoundedMemoryStream(WorkerProtocol.MaxDataBytes); | |
| 66 | 추가: return ValueTask.FromResult<Stream>(pending); | |
| 67 | 추가: } | |
| 68 | 추가: | |
| 69 | 추가: public ValueTask CommitAsync(CancellationToken token) | |
| 70 | 추가: { | |
| 71 | 추가: token.ThrowIfCancellationRequested(); | |
| 72 | 추가: if (pending is null) { throw new ArchiveException(ArchiveError.OutputUnavailable); } | |
| 73 | 추가: CommittedBytes = pending.ToArray(); | |
| 74 | 추가: return ValueTask.CompletedTask; | |
| 75 | 추가: } | |
| 76 | 추가: | |
| 77 | 추가: public ValueTask DisposeAsync() | |
| 78 | 추가: { | |
| 79 | 추가: pending?.Dispose(); | |
| 80 | 추가: pending = null; | |
| 81 | 추가: return ValueTask.CompletedTask; | |
| 82 | 추가: } | |
| 83 | 추가: } |
| @@ -0,0 +1,106 @@ | ||
| 1 | 추가: using System.IO.Compression; | |
| 2 | 추가: using Zipelo.Core; | |
| 3 | 추가: using Zipelo.Runtime; | |
| 4 | 추가: | |
| 5 | 추가: namespace Zipelo.Worker; | |
| 6 | 추가: | |
| 7 | 추가: // 압축 파싱은 작업자에서만 수행함. UI에서 이 구현을 직접 참조하지 않음. | |
| 8 | 추가: internal sealed class BuiltInZipEngine(string[] names, long outputLimit) : IArchiveEngine | |
| 9 | 추가: { | |
| 10 | 추가: public IReadOnlyCollection<EngineCapability> Capabilities { get; } = Array.AsReadOnly(new[] | |
| 11 | 추가: { | |
| 12 | 추가: new EngineCapability("zip", ArchiveAction.List), | |
| 13 | 추가: new EngineCapability("zip", ArchiveAction.Create) | |
| 14 | 추가: }); | |
| 15 | 추가: | |
| 16 | 추가: public async Task ExecuteAsync(ArchiveAction action, IReadOnlyList<Stream> inputs, | |
| 17 | 추가: EngineContext context, CancellationToken token) | |
| 18 | 추가: { | |
| 19 | 추가: try | |
| 20 | 추가: { | |
| 21 | 추가: if (action == ArchiveAction.List) | |
| 22 | 추가: { | |
| 23 | 추가: if (inputs.Count != 1) { throw new ArchiveException(ArchiveError.UnsupportedOperation); } | |
| 24 | 추가: context.Budget.ChargeProcessed(inputs[0].Length, token); | |
| 25 | 추가: using var archive = new ZipArchive(inputs[0], ZipArchiveMode.Read, leaveOpen: true); | |
| 26 | 추가: if (archive.Entries.Count > WorkerProtocol.MaxEntries) | |
| 27 | 추가: { | |
| 28 | 추가: throw new ArchiveException(ArchiveError.BudgetExceeded); | |
| 29 | 추가: } | |
| 30 | 추가: for (var index = 0; index < archive.Entries.Count; index++) | |
| 31 | 추가: { | |
| 32 | 추가: context.Budget.Check(token); | |
| 33 | 추가: var entry = archive.Entries[index]; | |
| 34 | 추가: if (entry.FullName.Length > WorkerProtocol.MaxNameLength) | |
| 35 | 추가: { | |
| 36 | 추가: throw new ArchiveException(ArchiveError.BudgetExceeded); | |
| 37 | 추가: } | |
| 38 | 추가: if (entry.IsEncrypted) { throw new ArchiveException(ArchiveError.UnsupportedOperation); } | |
| 39 | 추가: var unixType = (entry.ExternalAttributes >> 16) & 0xF000; | |
| 40 | 추가: var kind = unixType == 0xA000 ? EntryKind.SymbolicLink : | |
| 41 | 추가: entry.FullName.EndsWith('/') || unixType == 0x4000 ? EntryKind.Directory : | |
| 42 | 추가: unixType is 0 or 0x8000 ? EntryKind.File : EntryKind.Other; | |
| 43 | 추가: // 목록은 내용의 CRC나 경로 안전성을 검증한 결과가 아님. | |
| 44 | 추가: await context.ListEntryAsync(new($"entry-{index}", entry.FullName, kind, entry.Length)) | |
| 45 | 추가: .ConfigureAwait(false); | |
| 46 | 추가: } | |
| 47 | 추가: return; | |
| 48 | 추가: } | |
| 49 | 추가: if (action != ArchiveAction.Create || inputs.Count != names.Length) | |
| 50 | 추가: { | |
| 51 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 52 | 추가: } | |
| 53 | 추가: | |
| 54 | 추가: var normalized = ValidateNames(names); | |
| 55 | 추가: using var zip = new BoundedMemoryStream(Math.Min(outputLimit, WorkerProtocol.MaxDataBytes)); | |
| 56 | 추가: using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true)) | |
| 57 | 추가: { | |
| 58 | 추가: var buffer = new byte[64 * 1024]; | |
| 59 | 추가: for (var index = 0; index < inputs.Count; index++) | |
| 60 | 추가: { | |
| 61 | 추가: context.Budget.Check(token); | |
| 62 | 추가: await context.ListEntryAsync(new($"source-{index}", normalized[index], EntryKind.File, inputs[index].Length)) | |
| 63 | 추가: .ConfigureAwait(false); | |
| 64 | 추가: var entry = archive.CreateEntry(normalized[index], CompressionLevel.Optimal); | |
| 65 | 추가: await using var destination = entry.Open(); | |
| 66 | 추가: int count; | |
| 67 | 추가: while ((count = await inputs[index].ReadAsync(buffer, token).ConfigureAwait(false)) != 0) | |
| 68 | 추가: { | |
| 69 | 추가: context.Budget.ChargeProcessed(count, token); | |
| 70 | 추가: await destination.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false); | |
| 71 | 추가: } | |
| 72 | 추가: } | |
| 73 | 추가: } | |
| 74 | 추가: context.Budget.Check(token); | |
| 75 | 추가: zip.Position = 0; | |
| 76 | 추가: await context.WriteEntryAsync(new("artifact", "archive.zip", EntryKind.File, zip.Length), zip, | |
| 77 | 추가: _ => ValueTask.FromResult(VerificationState.NotChecked)).ConfigureAwait(false); | |
| 78 | 추가: } | |
| 79 | 추가: catch (InvalidDataException) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 80 | 추가: } | |
| 81 | 추가: | |
| 82 | 추가: private static string[] ValidateNames(string[] names) | |
| 83 | 추가: { | |
| 84 | 추가: var normalized = new string[names.Length]; | |
| 85 | 추가: var policy = OutputPathPolicy.CurrentPolicy; | |
| 86 | 추가: var comparison = OutputPathPolicy.Comparison(policy); | |
| 87 | 추가: var seen = new HashSet<string>(OutputPathPolicy.Comparer(policy)); | |
| 88 | 추가: for (var index = 0; index < names.Length; index++) | |
| 89 | 추가: { | |
| 90 | 추가: if (names[index].Length > WorkerProtocol.MaxNameLength) | |
| 91 | 추가: { | |
| 92 | 추가: throw new ArchiveException(ArchiveError.BudgetExceeded); | |
| 93 | 추가: } | |
| 94 | 추가: var name = string.Join('/', OutputPathPolicy.Validate(names[index], policy)); | |
| 95 | 추가: if (seen.Any(existing => existing.Equals(name, comparison) || | |
| 96 | 추가: existing.StartsWith(name + "/", comparison) || | |
| 97 | 추가: name.StartsWith(existing + "/", comparison))) | |
| 98 | 추가: { | |
| 99 | 추가: throw new ArchiveException(ArchiveError.OutputConflict); | |
| 100 | 추가: } | |
| 101 | 추가: seen.Add(name); | |
| 102 | 추가: normalized[index] = name; | |
| 103 | 추가: } | |
| 104 | 추가: return normalized; | |
| 105 | 추가: } | |
| 106 | 추가: } |
| @@ -0,0 +1,55 @@ | ||
| 1 | 추가: using Zipelo.Core; | |
| 2 | 추가: using Zipelo.Runtime; | |
| 3 | 추가: using Zipelo.Worker; | |
| 4 | 추가: | |
| 5 | 추가: // 요청 한 건을 처리하고 종료함. 경로나 암호를 명령행으로 받지 않음. | |
| 6 | 추가: if (args.Length != 0) { return 2; } | |
| 7 | 추가: AppContext.SetSwitch("System.IO.Compression.UseStrictValidation", true); | |
| 8 | 추가: using var lifetime = new CancellationTokenSource(TimeSpan.FromMinutes(5)); | |
| 9 | 추가: var id = Guid.Empty; | |
| 10 | 추가: ZipWorkerResult response; | |
| 11 | 추가: try | |
| 12 | 추가: { | |
| 13 | 추가: var request = await WorkerProtocol.ReadAsync<WorkerRequest>(Console.OpenStandardInput(), lifetime.Token); | |
| 14 | 추가: id = request.JobId; | |
| 15 | 추가: WorkerProtocol.ValidateLimits(request.Limits); | |
| 16 | 추가: if (id == Guid.Empty || request.Inputs is null || request.Names is null || | |
| 17 | 추가: request.Inputs.Length == 0 || request.Inputs.Length > WorkerProtocol.MaxEntries || | |
| 18 | 추가: request.Inputs.Any(input => input is null) || | |
| 19 | 추가: request.Inputs.Sum(input => (long)input.Length) > WorkerProtocol.MaxDataBytes || | |
| 20 | 추가: request.Names.Any(name => name is null || name.Length > WorkerProtocol.MaxNameLength) || | |
| 21 | 추가: (request.Action is ArchiveAction.List or ArchiveAction.Extract && (request.Inputs.Length != 1 || request.Names.Length != 0)) || | |
| 22 | 추가: (request.Action == ArchiveAction.Create && request.Names.Length != request.Inputs.Length)) | |
| 23 | 추가: { | |
| 24 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 25 | 추가: } | |
| 26 | 추가: if (request.Action == ArchiveAction.Extract) | |
| 27 | 추가: { | |
| 28 | 추가: response = ZipExtractor.Extract(request, lifetime.Token); | |
| 29 | 추가: } | |
| 30 | 추가: else | |
| 31 | 추가: { | |
| 32 | 추가: var inputs = request.Inputs.Select(input => (Stream)new MemoryStream(input, writable: false)).ToArray(); | |
| 33 | 추가: try | |
| 34 | 추가: { | |
| 35 | 추가: var output = new BoundedMemoryOutput(); | |
| 36 | 추가: var result = await new ArchiveJob(id, request.Limits).ExecuteAsync(request.Action, "zip", | |
| 37 | 추가: new BuiltInZipEngine(request.Names, request.Limits.MaxOutputBytes), inputs, output, | |
| 38 | 추가: (_, _) => throw new ArchiveException(ArchiveError.UnsupportedOperation), null, lifetime.Token); | |
| 39 | 추가: response = new(result, result.State == JobState.Completed ? output.CommittedBytes : null); | |
| 40 | 추가: } | |
| 41 | 추가: finally | |
| 42 | 추가: { | |
| 43 | 추가: foreach (var input in inputs) { input.Dispose(); } | |
| 44 | 추가: } | |
| 45 | 추가: } | |
| 46 | 추가: } | |
| 47 | 추가: catch (ArchiveException failure) { response = WorkerProtocol.Failure(id, failure.Code); } | |
| 48 | 추가: catch (OperationCanceledException) { response = WorkerProtocol.Failure(id, ArchiveError.BudgetExceeded); } | |
| 49 | 추가: catch { response = WorkerProtocol.Failure(id, ArchiveError.EngineFailure); } | |
| 50 | 추가: try | |
| 51 | 추가: { | |
| 52 | 추가: await WorkerProtocol.WriteAsync(Console.OpenStandardOutput(), response, lifetime.Token); | |
| 53 | 추가: return 0; | |
| 54 | 추가: } | |
| 55 | 추가: catch { return 1; } |
| @@ -0,0 +1,201 @@ | ||
| 1 | 추가: using System.Buffers.Binary; | |
| 2 | 추가: using System.IO.Compression; | |
| 3 | 추가: using System.Text; | |
| 4 | 추가: using Zipelo.Core; | |
| 5 | 추가: using Zipelo.Runtime; | |
| 6 | 추가: | |
| 7 | 추가: namespace Zipelo.Worker; | |
| 8 | 추가: | |
| 9 | 추가: // 초기 해제는 단일 디스크 ZIP32의 저장/Deflate 방식만 허용함. | |
| 10 | 추가: internal static class ZipExtractor | |
| 11 | 추가: { | |
| 12 | 추가: private sealed record Item(ArchiveEntry Entry, uint Crc, int Start, int Packed, int Method); | |
| 13 | 추가: | |
| 14 | 추가: internal static ZipWorkerResult Extract(WorkerRequest request, CancellationToken token) | |
| 15 | 추가: { | |
| 16 | 추가: try | |
| 17 | 추가: { | |
| 18 | 추가: var budget = new JobBudget(request.Limits); | |
| 19 | 추가: var bytes = request.Inputs.Single(); | |
| 20 | 추가: budget.ChargeProcessed(bytes.Length, token); | |
| 21 | 추가: var items = Parse(bytes, budget, token); | |
| 22 | 추가: ZipExtraction.ValidatePaths(items.Select(item => item.Entry).ToArray()); | |
| 23 | 추가: var outputs = new List<ZipExtractedEntry>(); | |
| 24 | 추가: long total = 0; | |
| 25 | 추가: var buffer = new byte[65536]; | |
| 26 | 추가: foreach (var item in items) | |
| 27 | 추가: { | |
| 28 | 추가: budget.Check(token); | |
| 29 | 추가: using var packed = new MemoryStream(bytes, item.Start, item.Packed, writable: false); | |
| 30 | 추가: using Stream decoded = item.Method == 0 ? packed : new DeflateStream(packed, CompressionMode.Decompress); | |
| 31 | 추가: using var output = new MemoryStream(); | |
| 32 | 추가: var crc = uint.MaxValue; | |
| 33 | 추가: int count; | |
| 34 | 추가: while ((count = decoded.Read(buffer, 0, buffer.Length)) != 0) | |
| 35 | 추가: { | |
| 36 | 추가: budget.ChargeProcessed(count, token); | |
| 37 | 추가: budget.ReserveOutput(count, token); | |
| 38 | 추가: total += count; | |
| 39 | 추가: if (total > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 40 | 추가: if (output.Length + count > item.Entry.DeclaredSize) | |
| 41 | 추가: { | |
| 42 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 43 | 추가: } | |
| 44 | 추가: crc = ZipExtraction.UpdateCrc(crc, buffer.AsSpan(0, count)); | |
| 45 | 추가: output.Write(buffer, 0, count); | |
| 46 | 추가: } | |
| 47 | 추가: budget.Check(token); | |
| 48 | 추가: if (output.Length != item.Entry.DeclaredSize || ~crc != item.Crc) | |
| 49 | 추가: { | |
| 50 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 51 | 추가: } | |
| 52 | 추가: outputs.Add(new(item.Entry, output.ToArray(), item.Crc)); | |
| 53 | 추가: } | |
| 54 | 추가: var reports = outputs.Select(item => new EntryResult(item.Entry, EntryOutcome.Staged, | |
| 55 | 추가: VerificationState.Passed, ArchiveError.None)).ToArray(); | |
| 56 | 추가: budget.Check(token); | |
| 57 | 추가: return new(new(request.JobId, JobState.Completed, reports, ArchiveError.None), null) | |
| 58 | 추가: { | |
| 59 | 추가: ExtractedEntries = outputs.ToArray() | |
| 60 | 추가: }; | |
| 61 | 추가: } | |
| 62 | 추가: catch (InvalidDataException) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 63 | 추가: catch (DecoderFallbackException) { throw new ArchiveException(ArchiveError.UnsafePath); } | |
| 64 | 추가: catch (OverflowException) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 65 | 추가: } | |
| 66 | 추가: | |
| 67 | 추가: private static Item[] Parse(byte[] data, JobBudget budget, CancellationToken token) | |
| 68 | 추가: { | |
| 69 | 추가: int U16(int offset) => BinaryPrimitives.ReadUInt16LittleEndian(Slice(data, offset, 2)); | |
| 70 | 추가: uint U32(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(Slice(data, offset, 4)); | |
| 71 | 추가: int Size(int offset) => checked((int)U32(offset)); | |
| 72 | 추가: var end = data.Length - 22; | |
| 73 | 추가: while (end >= Math.Max(0, data.Length - 65557)) | |
| 74 | 추가: { | |
| 75 | 추가: if (U32(end) == 0x06054B50 && end + 22 + U16(end + 20) == data.Length) { break; } | |
| 76 | 추가: end--; | |
| 77 | 추가: } | |
| 78 | 추가: if (end < Math.Max(0, data.Length - 65557)) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 79 | 추가: if (U16(end + 4) != 0 || U16(end + 6) != 0 || U16(end + 8) != U16(end + 10) || U16(end + 10) == 65535) | |
| 80 | 추가: { | |
| 81 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 82 | 추가: } | |
| 83 | 추가: var count = U16(end + 10); | |
| 84 | 추가: if (count > WorkerProtocol.MaxEntries) { throw new ArchiveException(ArchiveError.BudgetExceeded); } | |
| 85 | 추가: var central = Size(end + 16); | |
| 86 | 추가: if ((long)central + Size(end + 12) != end) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 87 | 추가: var cursor = central; | |
| 88 | 추가: var items = new List<Item>(); | |
| 89 | 추가: var ranges = new List<(int Start, int End)>(); | |
| 90 | 추가: for (var index = 0; index < count; index++) | |
| 91 | 추가: { | |
| 92 | 추가: budget.AddEntry(token); | |
| 93 | 추가: _ = Slice(data, cursor, 46); | |
| 94 | 추가: if (U32(cursor) != 0x02014B50) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 95 | 추가: var creator = U16(cursor + 4) >> 8; | |
| 96 | 추가: var flags = U16(cursor + 8); | |
| 97 | 추가: var method = U16(cursor + 10); | |
| 98 | 추가: if (creator is not (0 or 3) || U16(cursor + 6) > 20 || U16(cursor + 34) != 0 || | |
| 99 | 추가: (flags & ~0x080E) != 0 || method is not (0 or 8)) | |
| 100 | 추가: { | |
| 101 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 102 | 추가: } | |
| 103 | 추가: var crc = U32(cursor + 16); | |
| 104 | 추가: var packed = Size(cursor + 20); | |
| 105 | 추가: var unpacked = Size(cursor + 24); | |
| 106 | 추가: if (method == 8 && packed < 2) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 107 | 추가: var nameLength = U16(cursor + 28); | |
| 108 | 추가: var extraLength = U16(cursor + 30); | |
| 109 | 추가: var nameBytes = Slice(data, cursor + 46, nameLength); | |
| 110 | 추가: if ((flags & 0x0800) == 0 && nameBytes.IndexOfAnyInRange((byte)128, (byte)255) >= 0) | |
| 111 | 추가: { | |
| 112 | 추가: throw new ArchiveException(ArchiveError.UnsupportedOperation); | |
| 113 | 추가: } | |
| 114 | 추가: var name = new UTF8Encoding(false, true).GetString(nameBytes); | |
| 115 | 추가: var attributes = U32(cursor + 38); | |
| 116 | 추가: var unixType = (attributes >> 16) & 0xF000; | |
| 117 | 추가: if (unixType is not (0 or 0x8000 or 0x4000) || (attributes & 0x400) != 0) | |
| 118 | 추가: { | |
| 119 | 추가: throw new ArchiveException(ArchiveError.UnsupportedEntry); | |
| 120 | 추가: } | |
| 121 | 추가: var directory = name.EndsWith('/'); | |
| 122 | 추가: if ((unixType == 0x4000 || (attributes & 0x10) != 0) && !directory || | |
| 123 | 추가: directory && (unixType == 0x8000 || unpacked != 0 || crc != 0)) | |
| 124 | 추가: { | |
| 125 | 추가: throw new ArchiveException(ArchiveError.UnsupportedEntry); | |
| 126 | 추가: } | |
| 127 | 추가: var path = directory ? name[..^1] : name; | |
| 128 | 추가: var entry = new ArchiveEntry($"entry-{index}", path, directory ? EntryKind.Directory : EntryKind.File, unpacked); | |
| 129 | 추가: CheckExtra(Slice(data, cursor + 46 + nameLength, extraLength)); | |
| 130 | 추가: var local = Size(cursor + 42); | |
| 131 | 추가: _ = Slice(data, local, 30); | |
| 132 | 추가: if (U32(local) != 0x04034B50 || U16(local + 4) != U16(cursor + 6) || | |
| 133 | 추가: U16(local + 6) != flags || U16(local + 8) != method || U16(local + 26) != nameLength || | |
| 134 | 추가: !Slice(data, local + 30, nameLength).SequenceEqual(nameBytes)) | |
| 135 | 추가: { | |
| 136 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 137 | 추가: } | |
| 138 | 추가: if ((flags & 8) == 0 && (U32(local + 14) != crc || Size(local + 18) != packed || Size(local + 22) != unpacked)) | |
| 139 | 추가: { | |
| 140 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 141 | 추가: } | |
| 142 | 추가: if ((flags & 8) != 0 && ((U32(local + 14) != 0 && U32(local + 14) != crc) || | |
| 143 | 추가: (U32(local + 18) != 0 && Size(local + 18) != packed) || | |
| 144 | 추가: (U32(local + 22) != 0 && Size(local + 22) != unpacked))) | |
| 145 | 추가: { | |
| 146 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 147 | 추가: } | |
| 148 | 추가: var localExtra = U16(local + 28); | |
| 149 | 추가: CheckExtra(Slice(data, local + 30 + nameLength, localExtra)); | |
| 150 | 추가: var start = checked(local + 30 + nameLength + localExtra); | |
| 151 | 추가: var finish = checked(start + packed); | |
| 152 | 추가: _ = Slice(data, start, packed); | |
| 153 | 추가: if ((flags & 8) != 0) | |
| 154 | 추가: { | |
| 155 | 추가: var descriptor = finish; | |
| 156 | 추가: if (U32(descriptor) == 0x08074B50) { descriptor += 4; } | |
| 157 | 추가: if (U32(descriptor) != crc || Size(descriptor + 4) != packed || Size(descriptor + 8) != unpacked) | |
| 158 | 추가: { | |
| 159 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 160 | 추가: } | |
| 161 | 추가: finish = checked(descriptor + 12); | |
| 162 | 추가: } | |
| 163 | 추가: if (finish > central) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 164 | 추가: ranges.Add((local, finish)); | |
| 165 | 추가: items.Add(new(entry, crc, start, packed, method)); | |
| 166 | 추가: cursor = checked(cursor + 46 + nameLength + extraLength + U16(cursor + 32)); | |
| 167 | 추가: } | |
| 168 | 추가: if (cursor != end) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 169 | 추가: var next = 0; | |
| 170 | 추가: foreach (var range in ranges.OrderBy(range => range.Start)) | |
| 171 | 추가: { | |
| 172 | 추가: if (range.Start != next) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 173 | 추가: next = range.End; | |
| 174 | 추가: } | |
| 175 | 추가: if (next != central) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 176 | 추가: return items.ToArray(); | |
| 177 | 추가: } | |
| 178 | 추가: | |
| 179 | 추가: private static ReadOnlySpan<byte> Slice(byte[] bytes, int offset, int length) | |
| 180 | 추가: { | |
| 181 | 추가: if (offset < 0 || length < 0 || offset > bytes.Length - length) | |
| 182 | 추가: { | |
| 183 | 추가: throw new ArchiveException(ArchiveError.IntegrityFailure); | |
| 184 | 추가: } | |
| 185 | 추가: return bytes.AsSpan(offset, length); | |
| 186 | 추가: } | |
| 187 | 추가: | |
| 188 | 추가: private static void CheckExtra(ReadOnlySpan<byte> bytes) | |
| 189 | 추가: { | |
| 190 | 추가: // 링크 의미를 가진 Unix/ASi 등 미해석 확장 필드는 수용하지 않음. | |
| 191 | 추가: while (!bytes.IsEmpty) | |
| 192 | 추가: { | |
| 193 | 추가: if (bytes.Length < 4) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 194 | 추가: var id = BinaryPrimitives.ReadUInt16LittleEndian(bytes); | |
| 195 | 추가: var size = BinaryPrimitives.ReadUInt16LittleEndian(bytes[2..]); | |
| 196 | 추가: if (size > bytes.Length - 4) { throw new ArchiveException(ArchiveError.IntegrityFailure); } | |
| 197 | 추가: if (id != 0x5455) { throw new ArchiveException(ArchiveError.UnsupportedEntry); } | |
| 198 | 추가: bytes = bytes[(4 + size)..]; | |
| 199 | 추가: } | |
| 200 | 추가: } | |
| 201 | 추가: } |
| @@ -0,0 +1,12 @@ | ||
| 1 | 추가: <Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 추가: <PropertyGroup> | |
| 3 | 추가: <OutputType>Exe</OutputType> | |
| 4 | 추가: <TargetFramework>net10.0</TargetFramework> | |
| 5 | 추가: <Nullable>enable</Nullable> | |
| 6 | 추가: <ImplicitUsings>enable</ImplicitUsings> | |
| 7 | 추가: <TreatWarningsAsErrors>true</TreatWarningsAsErrors> | |
| 8 | 추가: </PropertyGroup> | |
| 9 | 추가: <ItemGroup> | |
| 10 | 추가: <ProjectReference Include="../Zipelo.Runtime/Zipelo.Runtime.csproj" /> | |
| 11 | 추가: </ItemGroup> | |
| 12 | 추가: </Project> |