diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9374c2b..0c40799 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,6 +49,22 @@ jobs: toolchain: stable target: x86_64-unknown-linux-musl use-dlltool-shim: false + - rid: linux-arm64 + os: ubuntu-latest + toolchain: stable + target: aarch64-unknown-linux-gnu + use-dlltool-shim: false + cross: gcc-aarch64-linux-gnu + - rid: win-arm64 + os: windows-latest + toolchain: stable-x86_64-pc-windows-gnu + target: aarch64-pc-windows-gnullvm + use-dlltool-shim: true + - rid: win-x86 + os: windows-latest + toolchain: stable-x86_64-pc-windows-gnu + target: i686-pc-windows-gnu + use-dlltool-shim: true - rid: osx-x64 os: macos-latest toolchain: stable @@ -63,6 +79,14 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Install cross toolchain + if: matrix.cross + run: sudo apt-get update && sudo apt-get install -y ${{ matrix.cross }} + + - name: Configure ARM64 linker + if: matrix.target == 'aarch64-unknown-linux-gnu' + run: echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV" + - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: @@ -128,7 +152,7 @@ jobs: - name: Deploy cores into runtimes//native shell: pwsh run: | - $rids = @('win-x64','linux-x64','linux-musl-x64','osx-x64','osx-arm64') + $rids = @('win-x64','linux-x64','linux-musl-x64','linux-arm64','win-arm64','win-x86','osx-x64','osx-arm64') foreach ($rid in $rids) { $dest = "src/GeneralZip/runtimes/$rid/native" New-Item -ItemType Directory -Force -Path $dest | Out-Null @@ -146,6 +170,7 @@ jobs: run: | dotnet build GeneralZip.slnx -c Release -p:Version=${{ env.PACKAGE_VERSION }} --nologo dotnet pack src/GeneralZip/GeneralZip.csproj -c Release -p:Version=${{ env.PACKAGE_VERSION }} -o artifacts/nuget --nologo + dotnet pack src/GeneralZip.Cli/GeneralZip.Cli.csproj -c Release -p:Version=${{ env.PACKAGE_VERSION }} -o artifacts/nuget --nologo - name: Smoke test (fresh console app installs packed packages) shell: pwsh @@ -160,7 +185,7 @@ jobs: using GeneralZip; using static GeneralZip.GeneralZip; - Initialize(); + // 无任何显式引导调用:验证零初始化的隐式引导端到端可用 Console.WriteLine($"native={GeneralZip.Native.NativeCoreLoader.IsAvailable}"); var dir = Path.Combine(Path.GetTempPath(), "gzp-smoke"); diff --git a/Directory.Build.props b/Directory.Build.props index eba2781..dcd97d7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,7 +4,7 @@ enable true GeneralZip - 1.2.0 + 2.0.0 GeneralZip GeneralZip diff --git a/GeneralZip.slnx b/GeneralZip.slnx index d902fe9..6da8bf5 100644 --- a/GeneralZip.slnx +++ b/GeneralZip.slnx @@ -6,6 +6,10 @@ + + + + diff --git a/README.en.md b/README.en.md index d6805b6..a02eca2 100644 --- a/README.en.md +++ b/README.en.md @@ -19,10 +19,10 @@ ## Why GeneralZip? -- **One API, many formats** — ZIP, 7z, RAR, TAR, GZ, BZ2, XZ, Zstd, LZ4 with automatic magic-byte detection. No more "which library do I need for this file?" -- **Encryption done right** — WinZip AES for universal interop, plus **SM4-GM** (Chinese national cryptography) as a documented custom ZIP extension, all behind one `EncryptionAlgorithm` switch. -- **Built for apps, not just scripts** — full event system (progress, interactive password prompts, overwrite decisions, error policies), `CancellationToken` everywhere, `IProgress` support. -- **Zero third-party NuGet dependencies in the core** — cryptographic primitives (SM3/SM4) and the TAR container are pure C# implementations validated against GB/T standard test vectors; native codecs (7z/bzip2/xz/zstd/lz4) live in an optional Rust native core, all pure Rust. +- **One API, many formats** — ZIP, 7z, RAR, TAR, GZ, BZ2, XZ, Zstd, LZ4, Brotli, CPIO, ISO9660 (read) and CAB (read) with automatic magic-byte detection. No more "which library do I need for this file?" +- **Encryption done right** — WinZip AES for universal interop, **SM4-GM** (Chinese national cryptography) as a documented custom ZIP extension, and an **SM2-GM envelope** (per-entry data keys sealed with SM2 public-key encryption — public-key recipients, no shared passwords). All behind one `EncryptionAlgorithm` switch, with a pluggable KDF registry. +- **Built for apps, not just scripts** — full event system (progress, interactive password prompts, overwrite decisions, error policies), `CancellationToken` everywhere, `IProgress` support, parallel compress/extract, `IAsyncEnumerable` entry enumeration. +- **Zero third-party NuGet dependencies in the core** — SM3/SM4, SM2 encryption and key handling, and the TAR/CPIO containers are C# implementations validated against GB/T standard test vectors. SM2 private-key decryption uses the RustCrypto constant-time implementation in the native core, which is required to read SM2-GM archives; the native codecs (7z/bzip2/xz/zstd/lz4/brotli) are otherwise optional. ## Installation @@ -33,9 +33,10 @@ dotnet add package GeneralZip Targets `netstandard2.0` and `net8.0`. > One package, everything included. The library bundles prebuilt Rust native cores for -> win-x64, linux-x64, linux-musl-x64, osx-x64 and osx-arm64; `GeneralZip.Initialize()` -> loads them automatically. If the core is missing for your platform, 7z/RAR and the -> native codecs degrade gracefully; everything else keeps working. +> win-x64, linux-x64, linux-musl-x64, osx-x64 and osx-arm64; they are detected and loaded +> automatically on first use — no initialization call needed. If the core is missing for +> your platform, 7z/RAR and the native codecs degrade gracefully; everything else keeps +> working. ## Quick Start @@ -44,8 +45,6 @@ Targets `netstandard2.0` and `net8.0`. ```csharp using GeneralZip; -GeneralZip.Initialize(); // idempotent bootstrap - // Directory → archive (format is chosen by the file extension) await GeneralZip.CompressAsync(@"C:\data", @"D:\backup.zip"); @@ -115,10 +114,46 @@ var result = reader.ExtractToDirectory(@"D:\out", new ExtractionOptions }); ``` +### High-level operations + +```csharp +// Append to an existing archive (read→rewrite; encrypted archives keep their algorithm) +await GeneralZip.AppendAsync("backup.zip", @"C:\new-files"); + +// Remove entries by exact name +await GeneralZip.RemoveAsync("backup.zip", new[] { "junk.txt" }); + +// Cross-format conversion (target format from extension) +await GeneralZip.ConvertAsync("old.zip", "new.7z"); + +// Stream → archive stream and back (no disk involved) +await GeneralZip.CompressAsync(sourceStream, output, "ZIP", "data.bin"); + +// Parallel extraction & compression (entry-level sharding) +GeneralZip.Extract("huge.zip", "out", extraction: new ExtractionOptions { MaxDegreeOfParallelism = 4 }); + +// Glob include/exclude filters +GeneralZip.Extract("logs.zip", "out", extraction: new ExtractionOptions +{ + IncludePatterns = new[] { "**/*.log" }, + ExcludePatterns = new[] { "**/*.tmp" }, +}); + +// Symbolic links & Unix permissions (ZIP/TAR) +writer.AddSymlink("latest.log", "logs/2026.log"); +GeneralZip.Extract("pkg.tar", "out", extraction: new ExtractionOptions +{ + SymlinkPolicy = SymlinkPolicy.Preserve, + PreserveUnixAttributes = true, +}); +``` + ### Integrity testing ```csharp -var test = GeneralZipReader.Open(path).TestAll(); +// Works without a password for plain archives; supply one for encrypted archives +using var testReader = GeneralZipReader.Open(path, o => o.Password = password); +var test = testReader.TestAll(); Console.WriteLine(test.Success ? "OK" : $"{test.FailedCount} entries failed"); ``` @@ -137,16 +172,20 @@ GeneralZip.Encryption.Register(new MyEncryptionProvider()); | Format | Read | Write | Encrypted Read | Encrypted Write | |---|:---:|:---:|:---:|:---:| -| ZIP (Store/Deflate/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** | ✓ | +| ZIP (Store/Deflate/**BZip2/Zstd/LZMA**/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** / **SM2-GM** | ✓ | | 7z (LZMA2) | ✓ | ✓ | AES-256 | AES-256 | | RAR4/RAR5 | ✓ | — (proprietary) | ✓ password | — | -| TAR / TAR.GZ | ✓ | ✓ | — | — | +| TAR / TAR.GZ / TAR.BZ2 | ✓ | ✓ | — | — | | GZ | ✓ (.NET built-in) | ✓ (.NET built-in) | — | — | -| BZ2 / XZ / ZSTD / LZ4 | ✓ (native core) | ✓ (native core) | — | — | +| BZ2 / XZ / ZSTD / LZ4 / BROTLI | ✓ (native core) | ✓ (native core) | — | — | +| CPIO (newc/odc/binary) | ✓ | ✓ (newc) | — | — | +| ISO9660 (+Joliet/Rock Ridge) | ✓ | — (read-only) | — | — | +| CAB | ✓ (NONE/stored) | — (read-only) | — | — | -> 7z/RAR and BZ2/XZ/ZSTD/LZ4 are provided by the **Rust native core** (all pure-Rust crates). -> When the core is missing, the library degrades gracefully: ZIP/TAR/TAR.GZ/GZ (pure managed) -> and all ZIP-family encryption are unaffected. +> 7z/RAR and BZ2/XZ/ZSTD/LZ4/BROTLI are provided by the **Rust native core** (all pure-Rust crates), +> streamed through a callback FFI with no temp files. When the core is missing, the library degrades +> gracefully: ZIP/TAR/CPIO/GZ (pure managed) and all ZIP-family encryption are unaffected. +> ZIP entries can use BZip2/Zstd/LZMA compression methods (interop with 7-Zip/Info-ZIP archives). **Why some cells are "—":** @@ -187,7 +226,8 @@ Place `generalzip_native.dll/.so/.dylib` in one of: 2. `runtimes//native/` under the app directory, 3. any path referenced by the `GENERALZIP_NATIVE` environment variable, -then call `GeneralZip.Initialize()` once (already done implicitly by the one-shot APIs). +The core is picked up automatically the first time you use the library — no +initialization call is needed. ## Sample Files @@ -208,28 +248,38 @@ Throughput numbers for all formats (including per-algorithm encryption overhead) | [docs/CRYPTO-SPEC.md](docs/CRYPTO-SPEC.md) | Binary spec of the SM4-GM encrypted ZIP container for third-party interop (Chinese) | | [docs/BENCHMARKS.md](docs/BENCHMARKS.md) | Full-format performance data (Chinese) | | [samples/](samples/) | Runnable samples: basic usage, events, benchmarks, fixture generator | +| [fuzz/](fuzz/) | Read-path fuzzing harness (SharpFuzz) + CI robustness regression | ## Project Layout ``` src/GeneralZip/ Library (managed core + bundled Rust native core bindings) -native/generalzip-native/ Rust cdylib: 7z/bzip2/xz/zstd/lz4 codecs (C ABI) +src/GeneralZip.Cli/ gz command line (dotnet tool: `dotnet tool install GeneralZip.Cli`) +native/generalzip-native/ Rust cdylib: 7z/bzip2/xz/zstd/lz4/brotli codecs (C ABI, streaming) native/dlltool-shim-rs/ Build helper for windows-gnu raw-dylib imports -tests/ 73 tests: standard vectors, interop oracle, events, fixtures -samples/ Samples + sample archives (fixtures) +tests/ 158 tests: standard vectors, interop oracle, events, fixtures, robustness +samples/ Samples + sample archives (fixtures + third-party interop anchors) +fuzz/ Read-path fuzzing harness (SharpFuzz) build/ One-shot build script ``` ## Known Limitations - RAR is **read-only** — the compression algorithm is proprietary; no compliant implementation can create RAR archives. -- 7z archives cannot be appended to (each write produces a whole new archive). -- SM4-GM is a custom specification (ZIP has no official SM4 standard); interop is limited to this library and third parties implementing the same spec. -- BZ2/XZ/ZSTD/LZ4 require the native core; GZip is always available (pure managed). -- Native zstd compression is a one-shot in-memory API; xz/lz4/bzip2 stream. +- 7z archives cannot be appended in place; Append/Convert use read→rewrite semantics (producing a whole new archive). +- SM4-GM / SM2-GM are custom specifications (ZIP has no official SM standards); interop is limited to this library and third parties implementing the same specs (see `docs/CRYPTO-SPEC.md`). +- BZ2/XZ/ZSTD/LZ4/BROTLI require the native core; GZip is always available (pure managed). +- ISO9660 and CAB are read-only. CAB supports NONE (stored) folders only — MSZIP/LZX/Quantum require a proprietary 32K-window decoder. +- Append/Remove/Convert rewrite the archive: original entry encryption parameters (salt/IV) are regenerated, but the algorithm is preserved automatically. ## Contributing & License Issues and PRs are welcome. Please run `build\build.ps1` and make sure all tests pass before submitting. Released under the [MIT License](LICENSE). + +
+ +[**English**](README.md) | [中文](README.zh-CN.md) + +
diff --git a/README.md b/README.md index 8209c3c..a02eca2 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,10 @@ ## Why GeneralZip? -- **One API, many formats** — ZIP, 7z, RAR, TAR, GZ, BZ2, XZ, Zstd, LZ4 with automatic magic-byte detection. No more "which library do I need for this file?" -- **Encryption done right** — WinZip AES for universal interop, plus **SM4-GM** (Chinese national cryptography) as a documented custom ZIP extension, all behind one `EncryptionAlgorithm` switch. -- **Built for apps, not just scripts** — full event system (progress, interactive password prompts, overwrite decisions, error policies), `CancellationToken` everywhere, `IProgress` support. -- **Zero third-party NuGet dependencies in the core** — cryptographic primitives (SM3/SM4) and the TAR container are pure C# implementations validated against GB/T standard test vectors; native codecs (7z/bzip2/xz/zstd/lz4) live in an optional Rust native core, all pure Rust. +- **One API, many formats** — ZIP, 7z, RAR, TAR, GZ, BZ2, XZ, Zstd, LZ4, Brotli, CPIO, ISO9660 (read) and CAB (read) with automatic magic-byte detection. No more "which library do I need for this file?" +- **Encryption done right** — WinZip AES for universal interop, **SM4-GM** (Chinese national cryptography) as a documented custom ZIP extension, and an **SM2-GM envelope** (per-entry data keys sealed with SM2 public-key encryption — public-key recipients, no shared passwords). All behind one `EncryptionAlgorithm` switch, with a pluggable KDF registry. +- **Built for apps, not just scripts** — full event system (progress, interactive password prompts, overwrite decisions, error policies), `CancellationToken` everywhere, `IProgress` support, parallel compress/extract, `IAsyncEnumerable` entry enumeration. +- **Zero third-party NuGet dependencies in the core** — SM3/SM4, SM2 encryption and key handling, and the TAR/CPIO containers are C# implementations validated against GB/T standard test vectors. SM2 private-key decryption uses the RustCrypto constant-time implementation in the native core, which is required to read SM2-GM archives; the native codecs (7z/bzip2/xz/zstd/lz4/brotli) are otherwise optional. ## Installation @@ -33,9 +33,10 @@ dotnet add package GeneralZip Targets `netstandard2.0` and `net8.0`. > One package, everything included. The library bundles prebuilt Rust native cores for -> win-x64, linux-x64, linux-musl-x64, osx-x64 and osx-arm64; `GeneralZip.Initialize()` -> loads them automatically. If the core is missing for your platform, 7z/RAR and the -> native codecs degrade gracefully; everything else keeps working. +> win-x64, linux-x64, linux-musl-x64, osx-x64 and osx-arm64; they are detected and loaded +> automatically on first use — no initialization call needed. If the core is missing for +> your platform, 7z/RAR and the native codecs degrade gracefully; everything else keeps +> working. ## Quick Start @@ -44,8 +45,6 @@ Targets `netstandard2.0` and `net8.0`. ```csharp using GeneralZip; -GeneralZip.Initialize(); // idempotent bootstrap - // Directory → archive (format is chosen by the file extension) await GeneralZip.CompressAsync(@"C:\data", @"D:\backup.zip"); @@ -115,6 +114,40 @@ var result = reader.ExtractToDirectory(@"D:\out", new ExtractionOptions }); ``` +### High-level operations + +```csharp +// Append to an existing archive (read→rewrite; encrypted archives keep their algorithm) +await GeneralZip.AppendAsync("backup.zip", @"C:\new-files"); + +// Remove entries by exact name +await GeneralZip.RemoveAsync("backup.zip", new[] { "junk.txt" }); + +// Cross-format conversion (target format from extension) +await GeneralZip.ConvertAsync("old.zip", "new.7z"); + +// Stream → archive stream and back (no disk involved) +await GeneralZip.CompressAsync(sourceStream, output, "ZIP", "data.bin"); + +// Parallel extraction & compression (entry-level sharding) +GeneralZip.Extract("huge.zip", "out", extraction: new ExtractionOptions { MaxDegreeOfParallelism = 4 }); + +// Glob include/exclude filters +GeneralZip.Extract("logs.zip", "out", extraction: new ExtractionOptions +{ + IncludePatterns = new[] { "**/*.log" }, + ExcludePatterns = new[] { "**/*.tmp" }, +}); + +// Symbolic links & Unix permissions (ZIP/TAR) +writer.AddSymlink("latest.log", "logs/2026.log"); +GeneralZip.Extract("pkg.tar", "out", extraction: new ExtractionOptions +{ + SymlinkPolicy = SymlinkPolicy.Preserve, + PreserveUnixAttributes = true, +}); +``` + ### Integrity testing ```csharp @@ -139,16 +172,20 @@ GeneralZip.Encryption.Register(new MyEncryptionProvider()); | Format | Read | Write | Encrypted Read | Encrypted Write | |---|:---:|:---:|:---:|:---:| -| ZIP (Store/Deflate/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** | ✓ | +| ZIP (Store/Deflate/**BZip2/Zstd/LZMA**/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** / **SM2-GM** | ✓ | | 7z (LZMA2) | ✓ | ✓ | AES-256 | AES-256 | | RAR4/RAR5 | ✓ | — (proprietary) | ✓ password | — | -| TAR / TAR.GZ | ✓ | ✓ | — | — | +| TAR / TAR.GZ / TAR.BZ2 | ✓ | ✓ | — | — | | GZ | ✓ (.NET built-in) | ✓ (.NET built-in) | — | — | -| BZ2 / XZ / ZSTD / LZ4 | ✓ (native core) | ✓ (native core) | — | — | +| BZ2 / XZ / ZSTD / LZ4 / BROTLI | ✓ (native core) | ✓ (native core) | — | — | +| CPIO (newc/odc/binary) | ✓ | ✓ (newc) | — | — | +| ISO9660 (+Joliet/Rock Ridge) | ✓ | — (read-only) | — | — | +| CAB | ✓ (NONE/stored) | — (read-only) | — | — | -> 7z/RAR and BZ2/XZ/ZSTD/LZ4 are provided by the **Rust native core** (all pure-Rust crates). -> When the core is missing, the library degrades gracefully: ZIP/TAR/TAR.GZ/GZ (pure managed) -> and all ZIP-family encryption are unaffected. +> 7z/RAR and BZ2/XZ/ZSTD/LZ4/BROTLI are provided by the **Rust native core** (all pure-Rust crates), +> streamed through a callback FFI with no temp files. When the core is missing, the library degrades +> gracefully: ZIP/TAR/CPIO/GZ (pure managed) and all ZIP-family encryption are unaffected. +> ZIP entries can use BZip2/Zstd/LZMA compression methods (interop with 7-Zip/Info-ZIP archives). **Why some cells are "—":** @@ -189,7 +226,8 @@ Place `generalzip_native.dll/.so/.dylib` in one of: 2. `runtimes//native/` under the app directory, 3. any path referenced by the `GENERALZIP_NATIVE` environment variable, -then call `GeneralZip.Initialize()` once (already done implicitly by the one-shot APIs). +The core is picked up automatically the first time you use the library — no +initialization call is needed. ## Sample Files @@ -210,25 +248,29 @@ Throughput numbers for all formats (including per-algorithm encryption overhead) | [docs/CRYPTO-SPEC.md](docs/CRYPTO-SPEC.md) | Binary spec of the SM4-GM encrypted ZIP container for third-party interop (Chinese) | | [docs/BENCHMARKS.md](docs/BENCHMARKS.md) | Full-format performance data (Chinese) | | [samples/](samples/) | Runnable samples: basic usage, events, benchmarks, fixture generator | +| [fuzz/](fuzz/) | Read-path fuzzing harness (SharpFuzz) + CI robustness regression | ## Project Layout ``` src/GeneralZip/ Library (managed core + bundled Rust native core bindings) -native/generalzip-native/ Rust cdylib: 7z/bzip2/xz/zstd/lz4 codecs (C ABI) +src/GeneralZip.Cli/ gz command line (dotnet tool: `dotnet tool install GeneralZip.Cli`) +native/generalzip-native/ Rust cdylib: 7z/bzip2/xz/zstd/lz4/brotli codecs (C ABI, streaming) native/dlltool-shim-rs/ Build helper for windows-gnu raw-dylib imports -tests/ 73 tests: standard vectors, interop oracle, events, fixtures -samples/ Samples + sample archives (fixtures) +tests/ 158 tests: standard vectors, interop oracle, events, fixtures, robustness +samples/ Samples + sample archives (fixtures + third-party interop anchors) +fuzz/ Read-path fuzzing harness (SharpFuzz) build/ One-shot build script ``` ## Known Limitations - RAR is **read-only** — the compression algorithm is proprietary; no compliant implementation can create RAR archives. -- 7z archives cannot be appended to (each write produces a whole new archive). -- SM4-GM is a custom specification (ZIP has no official SM4 standard); interop is limited to this library and third parties implementing the same spec. -- BZ2/XZ/ZSTD/LZ4 require the native core; GZip is always available (pure managed). -- Native zstd compression is a one-shot in-memory API; xz/lz4/bzip2 stream. +- 7z archives cannot be appended in place; Append/Convert use read→rewrite semantics (producing a whole new archive). +- SM4-GM / SM2-GM are custom specifications (ZIP has no official SM standards); interop is limited to this library and third parties implementing the same specs (see `docs/CRYPTO-SPEC.md`). +- BZ2/XZ/ZSTD/LZ4/BROTLI require the native core; GZip is always available (pure managed). +- ISO9660 and CAB are read-only. CAB supports NONE (stored) folders only — MSZIP/LZX/Quantum require a proprietary 32K-window decoder. +- Append/Remove/Convert rewrite the archive: original entry encryption parameters (salt/IV) are regenerated, but the algorithm is preserved automatically. ## Contributing & License diff --git a/README.zh-CN.md b/README.zh-CN.md index b312179..1a10ef5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -19,10 +19,10 @@ ## 为什么选择 GeneralZip? -- **一套 API 覆盖多种格式** —— ZIP、7z、RAR、TAR、GZ、BZ2、XZ、Zstd、LZ4,魔数自动探测。再也不用为某个文件找专门的库。 -- **正确的加密** —— WinZip AES 通用互通;**SM4-GM 国密**以文档化的自定义 ZIP 扩展实现;所有算法通过一个 `EncryptionAlgorithm` 开关切换。 -- **为应用而生** —— 完整事件系统(进度、交互取密、覆盖决策、错误策略)、全 API `CancellationToken`、`IProgress` 支持。 -- **核心包零第三方 NuGet 依赖** —— 密码学原语(SM3/SM4)与 TAR 容器为纯 C# 实现,经 GB/T 标准向量锁定;原生编解码(7z/bzip2/xz/zstd/lz4)位于可选的 Rust 原生核心,全部纯 Rust。 +- **一套 API 覆盖多种格式** —— ZIP、7z、RAR、TAR、GZ、BZ2、XZ、Zstd、LZ4、Brotli、CPIO(读写),ISO9660 与 CAB(只读),魔数自动探测。再也不用为某个文件找专门的库。 +- **正确的加密** —— WinZip AES 通用互通;**SM4-GM 国密**以文档化的自定义 ZIP 扩展实现;**SM2-GM 国密信封**(数据密钥经 SM2 公钥封装,公钥分发、无共享口令);KDF 注册表可插拔;所有算法通过一个 `EncryptionAlgorithm` 开关切换。 +- **为应用而生** —— 完整事件系统(进度、交互取密、覆盖决策、错误策略)、全 API `CancellationToken`、`IProgress` 支持、并行压缩/解压、`IAsyncEnumerable` 条目枚举、glob 过滤。 +- **核心包零第三方 NuGet 依赖** —— 密码学原语(SM3/SM4/SM2)与 TAR/CPIO 容器为纯 C# 实现,经 GB/T 标准向量锁定;原生编解码(7z/bzip2/xz/zstd/lz4/brotli)位于可选的 Rust 原生核心,全部纯 Rust,回调式流式转码零临时文件。 ## 安装 @@ -33,7 +33,7 @@ dotnet add package GeneralZip 目标框架 `netstandard2.0` 与 `net8.0`。 > 一个包,能力齐全。包内已捆绑 win-x64、linux-x64、linux-musl-x64、osx-x64、osx-arm64 -> 五个平台的预编译 Rust 原生核心,`GeneralZip.Initialize()` 会自动加载; +> 五个平台的预编译 Rust 原生核心,首次使用时自动探测并加载,**无需任何初始化调用**; > 若平台无对应核心,7z/RAR 与原生编解码优雅降级,其余能力不受影响。 ## 快速开始 @@ -43,8 +43,6 @@ dotnet add package GeneralZip ```csharp using GeneralZip; -GeneralZip.Initialize(); // 幂等引导 - // 目录 → 归档(格式由扩展名决定) await GeneralZip.CompressAsync(@"C:\data", @"D:\backup.zip"); @@ -133,22 +131,26 @@ GeneralZip.Registry.Register(new MyArchiveFormat()); GeneralZip.Encryption.Register(new MyEncryptionProvider()); ``` -> 引导类与组件同名(`namespace GeneralZip` 中的 `class GeneralZip`)。 -> 若需要与其它类型限定写法混用,可用 `using static GeneralZip.GeneralZip;` 裸调用 `Initialize()` / `CompressAsync()` 等。 +> 门面类与组件同名(`namespace GeneralZip` 中的 `class GeneralZip`)。 +> 若需要与其它类型限定写法混用,可用 `using static GeneralZip.GeneralZip;` 裸调用 `CompressAsync()` 等。 ## 格式与加密矩阵 | 格式 | 读 | 写 | 加密读 | 加密写 | |---|:---:|:---:|:---:|:---:| -| ZIP(Store/Deflate/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** | ✓ | +| ZIP(Store/Deflate/**BZip2/Zstd/LZMA**/Zip64) | ✓ | ✓ | ZipCrypto / WinZip AES / **SM4-GM** / **SM2-GM** | ✓ | | 7z(LZMA2) | ✓ | ✓ | AES-256 | AES-256 | | RAR4/RAR5 | ✓ | —(专有) | ✓ 密码 | — | | TAR / TAR.GZ | ✓ | ✓ | — | — | | GZ | ✓(.NET 内置) | ✓(.NET 内置) | — | — | -| BZ2 / XZ / ZSTD / LZ4 | ✓(原生核心) | ✓(原生核心) | — | — | +| BZ2 / XZ / ZSTD / LZ4 / BROTLI | ✓(原生核心) | ✓(原生核心) | — | — | +| CPIO(newc/odc/binary) | ✓ | ✓(newc) | — | — | +| ISO9660(+Joliet/Rock Ridge) | ✓ | —(只读) | — | — | +| CAB | ✓(NONE 存储) | —(只读) | — | — | -> 7z/RAR 与 BZ2/XZ/ZSTD/LZ4 由 **Rust 原生核心**提供(全部纯 Rust crate)。 -> 核心缺失时优雅降级:ZIP/TAR/TAR.GZ/GZ(纯托管)与全部 ZIP 系加密不受影响。 +> 7z/RAR 与 BZ2/XZ/ZSTD/LZ4/BROTLI 由 **Rust 原生核心**提供(全部纯 Rust crate), +> 经回调式 FFI 流式转码,零临时文件。核心缺失时优雅降级:ZIP/TAR/CPIO/GZ(纯托管) +> 与全部 ZIP 系加密不受影响。ZIP 条目可选用 BZip2/Zstd/LZMA 压缩方法(与 7-Zip/Info-ZIP 互通)。 **部分 "—" 的原因:** @@ -157,9 +159,9 @@ GeneralZip.Encryption.Register(new MyEncryptionProvider()); 读取(含密码解密)由原生核心完整支持。 - **TAR / GZ / BZ2 / XZ / ZSTD / LZ4 的加密列** —— 这些格式的规范中根本不存在加密机制: TAR 是纯"头 + 数据"容器,单文件编解码器也没有存放 KDF 参数、IV 或认证标签的位置。 - 需要加密时可在应用层"先加密后压缩",或改用 ZIP + WinZip AES / SM4-GM。 + 需要加密时可在应用层"先加密后压缩",或改用 ZIP + WinZip AES / SM4-GM / SM2-GM。 - **SM4-GM 仅落地于 ZIP 是刻意设计** —— ZIP 的 extra field 机制天生支持第三方扩展, - SM4-GM 容器的二进制规范已在 [docs/CRYPTO-SPEC.md](docs/CRYPTO-SPEC.md) 完整文档化, + SM4-GM 与 SM2-GM 信封容器的二进制规范已在 [docs/CRYPTO-SPEC.md](docs/CRYPTO-SPEC.md) 完整文档化, 供第三方实现互通;向 7z 这类标准化容器注入自定义加密会产出其他工具无法打开的归档。 - **ZipCrypto 写入默认关闭**(遗留 56 位弱加密),需显式启用; 正式场景请选择 WinZip AES(通用互通)或 SM4-GM(国密合规)。 @@ -186,7 +188,7 @@ GeneralZip.Encryption.Register(new MyEncryptionProvider()); 2. 应用目录下的 `runtimes//native/`; 3. `GENERALZIP_NATIVE` 环境变量指向的路径, -然后启动时调用一次 `GeneralZip.Initialize()`(一行式 API 内部已自动调用)。 +首次使用库时核心会被自动探测并加载,无需任何初始化调用。 ## 示例文件 @@ -207,6 +209,7 @@ GeneralZip.Encryption.Register(new MyEncryptionProvider()); | [docs/CRYPTO-SPEC.md](docs/CRYPTO-SPEC.md) | SM4-GM 加密 ZIP 容器二进制规范(第三方互通依据) | | [docs/BENCHMARKS.md](docs/BENCHMARKS.md) | 全格式性能数据 | | [samples/](samples/) | 可运行示例:基础用法、事件、基准、fixture 生成器 | +| [fuzz/](fuzz/) | 读路径 fuzzing 工程(SharpFuzz)+ CI 健壮性回归 | ## 项目结构 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b0c48ee..ee52b02 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -17,7 +17,7 @@ ``` ┌────────────────────────────────────────────────────────────┐ -│ 门面层 GeneralZip (静态引导/门面) / │ 一行式与流式 API +│ 门面层 GeneralZip (静态门面) / │ 一行式与流式 API │ GeneralZipReader / GeneralZipWriter │ ├────────────────────────────────────────────────────────────┤ │ 事件层 EntryStarted / EntryProgress / EntryCompleted / │ 进度 @@ -65,10 +65,10 @@ GeneralZip.sln │ │ ├─ Tar/ TAR / TAR.GZ / TAR.BZ2 │ │ └─ Codecs/ GZ/BZ2/XZ/Zstd/LZ4 单文件编解码格式 │ ├─ Native/ Rust 核心 P/Invoke 绑定(能力协商 + 降级) -│ ├─ GeneralZip.cs 启动引导(含原生自动装配)+ 静态门面 +│ ├─ GeneralZip.cs 静态门面(零初始化) │ ├─ ArchiveReader.cs 读取封装(事件源) │ ├─ ArchiveWriter.cs 写入封装(事件源) -│ └─ ArchiveFormatRegistry.cs 格式注册表 + 魔数探测 +│ └─ ArchiveFormatRegistry.cs 格式注册表 + 魔数探测(Default 装配时隐式原生引导) ├─ tests/ │ ├─ GeneralZip.Tests/ 核心测试(含互操作 oracle) │ └─ GeneralZip.Native.Tests/ Rust 核心集成测试 @@ -301,14 +301,15 @@ gzp_close(handle) -> status ``` NativeCoreLoader.TryLoad() ├─ 按 RID 探测 runtimes/{rid}/native/generalzip_native.{dll|so|dylib} - │ 以及应用目录 / GENERALZIP_NATIVE_PATH 环境变量 + │ 以及应用目录 / GENERALZIP_NATIVE 环境变量 ├─ 载入成功 → gzp_capabilities() → 按 bit 注册 SevenZipFormat / RarFormat └─ 载入失败 → 不注册;用户访问 7z/RAR 时抛 NativeCoreMissingException("...如何安装/部署 native core...") ``` -原生绑定与托管核心同包发布:`GeneralZip.Initialize()` 自动调用 -`GeneralZipNative.Initialize()`(幂等)完成能力注册;核心二进制缺失时仅降级、不抛异常。 +原生绑定与托管核心同包发布,引导完全隐式:首次访问任何 API 时, +`GeneralZipFormatRegistry.Default` 的装配自动调用 `GeneralZipNative.Bootstrap()` +(幂等)完成能力注册与编解码桥接注入;核心二进制缺失时仅降级、不抛异常。 ## 8. 关键流程 @@ -370,3 +371,18 @@ ArchiveException (基类) - 组件语义化版本;`ArchiveFormatRegistry.Default` 冻结内置提供者集合,仅追加不破坏。 - SM4-GM 规范版本化(extra field 内 1 字节 version),向后兼容旧包读取。 + +## 13. v2.0 能力扩展总览 + +本节汇总 2.0 版新增子系统(详细设计散见各模块注释与 CRYPTO-SPEC §10): + +| 子系统 | 要点 | +|---|---| +| 门面高阶操作 | Append / Remove / Convert(读出→重写语义,加密算法自动继承);Stream→Stream 一行式 | +| 压缩方法扩展 | ZIP 条目方法 12/93/14(BZip2/Zstd/LZMA),Rust 核心流式编解码(回调 FFI,零临时文件);.zst/.br 单文件同步去临时文件化 | +| 并行 | 解压按条目分片(每工作实例独立重开归档,事件加锁转发);ZIP 写入分片并行(明文暂存 + 后台压缩 + Finish 装配),并发度经 ArchiveWriteOptions/ExtractionOptions.MaxDegreeOfParallelism | +| 加密 | SM2-GM 信封(CRYPTO-SPEC §10,0x4D54);IKdfProvider 可插拔(KdfId 1/2 内置) | +| 格式 | CPIO(newc/odc/binary 读、newc 写)、ISO9660(+Joliet/Rock Ridge 读)、CAB(NONE 存储读)、Brotli 单文件;ZIP 分卷(.001/.002 纯字节分卷,VolumeSize 选项) | +| 条目属性 | IUnixEntry(ZIP Unix host / ustar mode);IArchiveSymlinkWriter(ZIP S_IFLNK、TAR typeflag 2);SymlinkPolicy + PreserveUnixAttributes 提取策略 | +| 异步 | IAsyncEnumerable 条目枚举(EnumerateEntriesAsync);异步入口同步语义显式文档化 | +| 工程 | GeneralZip.Cli(dotnet tool,gz 命令);fuzz/ 读路径 fuzz 工程 + RobustnessTests 回归;release 矩阵 8 RID(含 linux-arm64/win-arm64/win-x86);库 net8.0 IsAotCompatible 静态校验 | diff --git a/docs/CRYPTO-SPEC.md b/docs/CRYPTO-SPEC.md index ec3ba6b..53688cb 100644 --- a/docs/CRYPTO-SPEC.md +++ b/docs/CRYPTO-SPEC.md @@ -1,4 +1,7 @@ -# GeneralZip SM4-GM 加密 ZIP 容器规范(v1) +# GeneralZip 国密加密 ZIP 容器规范(v1.1) + +> v1.1 变更:新增 KdfId=2(PBKDF2-HMAC-SHA256);新增 §10 SM2-GM 数字信封容器(extra field 0x4D54)。 +> v1 的 SM4-GM 容器(extra field 0x4D53)二进制布局不变,完全向后兼容。 > 状态:**稳定** · 本规范定义 GeneralZip 组件对 ZIP 格式的国密(SM4/SM3)加密扩展。 > ZIP/APPNOTE 无官方 SM4 加密标准,本规范为自定义 vendor 扩展;按本规范实现的任意第三方库可与 GeneralZip 互通。 @@ -129,10 +132,71 @@ SM3("abcd" 重复 16 次,共 64 字节) |---|---| | 口令强度 | 安全性受限于口令熵;建议 ≥ 12 字符随机口令 | | 条目名/大小泄露 | 文件名、时间戳、大小为明文(与 WinZip AES 相同);需元数据保密请用 v2 规划的"整包头加密容器" | -| 多接收方 | v1 仅口令加密;SM2 数字信封(一人加密、多人解密)为预留扩展点 | +| 多接收方 | 见 §10:SM2-GM 数字信封(公钥加密数据密钥,无共享口令) | | 防暴力破解 | Iterations 仅提升成本;在线场景应配合应用层限速 | ## 9. 版本策略 - Version 字节变更即不兼容;新增算法模式(如 SM4-CBC、SM4-GCM 类 AEAD)以新 CipherMode/KdfId 值表达,读取端遇到未知值抛 `UnsupportedFormatException`。 - 本规范与组件同版本演进;规范级变更记录于文档顶部"状态"行。 + +## 10. SM2-GM 数字信封容器(v1.1 新增) + +### 10.1 概述 + +AlgorithmId = `SM2-GM`,extra field 标识 `0x4D54`(ASCII "GMSN",紧邻 0x4D53 "GMSM")。 +口令无关:写侧只需接收方 SM2 公钥(实现 `IPasswordlessWriteProvider`);读侧以 SM2 私钥 +(hex 大端 32 字节)经既有口令协商管线(`PasswordRequired` 事件 / `options.Password`)提供。 + +### 10.2 数据密钥与条目加密 + +- 每条目随机生成:`K_enc`(16B,SM4 密钥)‖ `K_mac`(32B,SM3-HMAC 密钥)‖ `IV`(16B)= 64B 密钥块 +- 数据保护:SM4-CTR + SM3-HMAC(Encrypt-then-MAC),AAD = extra field 数据区, + 与 v1 的 SM4-GM 数据布局完全一致(复用同一 Ctr 流实现) + +### 10.3 密钥封装(SM2 ECIES) + +密钥块经 SM2 公钥加密(GB/T 32918.4,KDF-SM3 + SM3 完整性,现行标准排列): + +``` +C = C1(65B: 04+X+Y) + C3(32B SM3) + C2(64B) = 161B +``` + +- 曲线:GB/T 32918.5-2017 推荐曲线;SM2 私钥解密通过 RustCrypto 原生核心执行,以使用常数时间的秘密标量运算 +- 解封:[dB]C1 得 (x2,y2) → KDF-SM3 → C2⊕t → 校验 C3 = SM3(x2+M+y2) + (错误私钥/密文篡改在 C3 处快速失败 → InvalidPasswordException) +- SM2 互操作性经独立实现(Python gmssl)双向交叉验证 + +### 10.4 Extra Field 0x4D54 二进制格式 + +``` +偏移 长度 字段 +0 4 Magic "GMSN"(0x47 0x4D 0x53 0x4E) +4 1 SpecVersion = 1 +5 1 CipherMode = 1(SM4-CTR) +6 1 KdfId = 0(信封模式:数据密钥不经口令派生) +7 4 EnvLen(LE32)= 161 +11 161 Envelope = SM2 ECIES(K_enc+K_mac+IV) +155 2 RealMethod(LE16,与 0x4D53 尾部约定一致) +``` + +HMAC(K_mac)覆盖:本 extra field 数据区(AAD)+ 全部密文;MAC 尾部 32B 追加在条目数据末尾 +(与 v1 相同)。中央目录与本地头的写入约定(method=99、FlagEncrypted)与 §5 相同。 + +### 10.5 互通实现清单 + +1. 解析 0x4D54 → 校验 magic/version/EnvLen +2. 读侧:口令通道取 SM2 私钥 hex → SM2 解封 → K_enc/K_mac/IV +3. SM4-CTR 解密 + SM3-HMAC 校验(AAD = extra field 数据区) +4. RealMethod 还原真实压缩方法(Deflate/Store/BZip2/Zstd/LZMA 均可叠加) + +### 10.6 KDF 标识注册表(v1.1 扩展,0x4D53 容器内 KdfId 字节) + +| KdfId | 派生函数 | 默认迭代 | 说明 | +|---|---|---|---| +| 1 | SM3-PBKDF2-HMAC(RFC 8018) | 10_000 | 默认(国密) | +| 2 | PBKDF2-HMAC-SHA256(RFC 8018) | 10_000 | 国际方案;netstandard2.0 下为纯 C# 循环实现 | +| 其它 | 自定义 | — | 读取端抛 UnsupportedFormatException;第三方经 IKdfProvider(SpecId)注册 | + +KDF 经 GeneralZipEncryptionRegistry.Kdfs 注册表解析;写侧由 ArchiveWriteOptions.KdfAlgorithmId +选择(null = 算法默认 SM3-PBKDF2)。 diff --git a/fuzz/GeneralZip.Fuzz/GeneralZip.Fuzz.csproj b/fuzz/GeneralZip.Fuzz/GeneralZip.Fuzz.csproj new file mode 100644 index 0000000..bb34ee3 --- /dev/null +++ b/fuzz/GeneralZip.Fuzz/GeneralZip.Fuzz.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + GeneralZip.Fuzz + enable + enable + false + false + + + + + + + + + + + + diff --git a/fuzz/GeneralZip.Fuzz/Program.cs b/fuzz/GeneralZip.Fuzz/Program.cs new file mode 100644 index 0000000..d96b5ce --- /dev/null +++ b/fuzz/GeneralZip.Fuzz/Program.cs @@ -0,0 +1,60 @@ +using GeneralZip; +using GeneralZip.Abstractions; + +namespace GeneralZip.Fuzz; + +/// 读路径 AFL fuzz 入口;传入文件路径时可重放 corpus 样本。 +internal static class Program +{ + private static void Main(string[] args) + { + if (args.Length != 0) + { + foreach (var path in args) + { + var files = Directory.Exists(path) + ? Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) + : new[] { path }; + foreach (var file in files) + { + FuzzReadPath(File.ReadAllBytes(file)); + } + } + + return; + } + + SharpFuzz.Fuzzer.RunOnce(stream => + { + using var ms = new MemoryStream(); + stream.CopyTo(ms); + FuzzReadPath(ms.ToArray()); + }); + } + + /// fuzz 目标:整段输入走 OpenRead → 全条目流式读取。 + public static void FuzzReadPath(byte[] input) + { + try + { + using var stream = new MemoryStream(input, writable: false); + using var reader = GeneralZipReader.Open(stream); + foreach (var entry in reader.Entries) + { + using var content = reader.OpenEntryStream(entry); + content.CopyTo(Stream.Null); + } + } + catch (Exception ex) when ( + ex is ArchiveException + or IOException + or NotSupportedException + or ArgumentException + or InvalidOperationException + or System.Security.Cryptography.CryptographicException + or System.IO.InvalidDataException) + { + // 预期内的拒识:格式/结构/口令/损坏 → 不是 fuzz 发现 + } + } +} diff --git a/fuzz/README.md b/fuzz/README.md new file mode 100644 index 0000000..b1dd26c --- /dev/null +++ b/fuzz/README.md @@ -0,0 +1,32 @@ +# GeneralZip 读路径 Fuzzing + +解析不可信输入是压缩库的核心风险面。本目录提供持续 fuzzing 的工程入口。 + +## 结构 + +- `GeneralZip.Fuzz/` — SharpFuzz harness(libFuzzer/AFL 桥接),fuzz 目标 = `GeneralZipReader.Open(stream)` + 全条目流式读取。 +- `tests/GeneralZip.Tests/RobustnessTests.cs` — 无需 fuzz 工具链的 CI 健壮性回归:随机字节 / 截断归档 / 位翻转变异,断言只允许归档类异常。 + +## 本地运行(AFL++) + +```bash +# 1. 构建 harness(需 libFuzzer 运行时;.NET 8 SDK 自带 shadow copy 方式不再适用, +# 参考 SharpFuzz 文档:https://github.com/Metalnem/sharpfuzz) +dotnet publish fuzz/GeneralZip.Fuzz -c Release -f net8.0 -o fuzz/out + +# 2. 注入路径覆盖插桩 +sharpfuzz fuzz/out/GeneralZip.dll + +# 3. AFL++ 驱动(SharpFuzz 使用 AFL 的共享内存接口) +afl-fuzz -i corpus -o findings -- dotnet fuzz/out/GeneralZip.Fuzz.dll + +# 4. 复现某个 finding +dotnet fuzz/out/GeneralZip.Fuzz.dll findings/crash- +``` + +## 判定规则 + +fuzz 目标只捕获"预期内拒识":`ArchiveException` 家族、`IOException`、`NotSupportedException`、 +`ArgumentException`、`InvalidOperationException`、`CryptographicException`。 +其它任何异常(含本应吞掉的越界/断言/原生崩溃)都是 fuzz 发现,最小化输入后提 issue 修复并回填 +`RobustnessTests.cs` 固定用例。 diff --git a/native/dlltool-shim-rs/src/main.rs b/native/dlltool-shim-rs/src/main.rs index d8dd61b..c493766 100644 --- a/native/dlltool-shim-rs/src/main.rs +++ b/native/dlltool-shim-rs/src/main.rs @@ -18,6 +18,7 @@ fn main() { let mut def: Option = None; let mut out_lib: Option = None; let mut dll_name: Option = None; + let mut machine: Option = None; let mut iter = args.iter(); while let Some(a) = iter.next() { @@ -26,7 +27,10 @@ fn main() { "-l" => out_lib = iter.next().cloned(), "-D" => dll_name = iter.next().cloned(), // 以下 dlltool 参数对本转译无意义,跳过(含其值) - "-m" | "-f" | "--temp-prefix" => { + "-m" => { + machine = iter.next().cloned(); + } + "-f" | "--temp-prefix" => { iter.next(); } _ => {} @@ -80,7 +84,20 @@ fn main() { out_arg.push_str(&out_display); lld_args.push(def_arg); lld_args.push(out_arg); - lld_args.push("/MACHINE:X64".into()); + let machine = match machine.as_deref() { + Some("i386") | Some("i386:x86-32") => "X86", + Some("i386:x86-64") | Some("x86-64") => "X64", + Some("arm64") | Some("aarch64") => "ARM64", + Some(other) => { + eprintln!("gzdlltool: unsupported machine type {other}"); + std::process::exit(1); + } + None => { + eprintln!("gzdlltool: missing -m machine type"); + std::process::exit(1); + } + }; + lld_args.push(format!("/MACHINE:{machine}")); lld_args.push("/NOLOGO".into()); let status = Command::new(lld).args(&lld_args).status(); diff --git a/native/generalzip-native/Cargo.lock b/native/generalzip-native/Cargo.lock index 21af356..4f2a314 100644 --- a/native/generalzip-native/Cargo.lock +++ b/native/generalzip-native/Cargo.lock @@ -22,12 +22,39 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bit-set" version = "0.8.0" @@ -58,6 +85,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block-padding" version = "0.3.3" @@ -67,6 +103,27 @@ dependencies = [ "generic-array", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -134,10 +191,28 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -196,6 +271,21 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -206,6 +296,36 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -218,8 +338,18 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", ] [[package]] @@ -228,6 +358,25 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "group", + "hybrid-array", + "pkcs8", + "rand_core 0.10.1", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "fearless_simd" version = "0.3.0" @@ -237,6 +386,22 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "filetime" version = "0.2.29" @@ -292,6 +457,7 @@ dependencies = [ name = "generalzip-native" version = "1.0.0" dependencies = [ + "brotli", "bzip2", "lz4_flex", "lzma-rs", @@ -299,6 +465,7 @@ dependencies = [ "rust-zstd", "ruzstd", "sevenz-rust2", + "sm2", "unrar", ] @@ -335,6 +502,28 @@ dependencies = [ "wasip2", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "inout" version = "0.1.4" @@ -440,6 +629,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "powerfmt" version = "0.2.1" @@ -455,6 +654,33 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -487,7 +713,7 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -497,7 +723,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -509,6 +735,12 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "rayon" version = "1.12.0" @@ -584,6 +816,29 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -604,6 +859,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "sevenz-rust2" version = "0.7.0" @@ -632,7 +897,7 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.10.7", ] [[package]] @@ -647,6 +912,45 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "sm2" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9d91aad47b30a5a5011032bed8d4b4192d7d5174ab3ed3e4dd22341ba8a5ac" +dependencies = [ + "elliptic-curve", + "fiat-crypto", + "primefield", + "primeorder", + "rand_core 0.10.1", + "sm3", +] + +[[package]] +name = "sm3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da6a89ba31723d185fd7413b98c576a575f356d9b84729d8ecb6ead60000a5b6" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -913,6 +1217,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -932,3 +1248,9 @@ dependencies = [ "quote", "syn 2.0.119", ] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" diff --git a/native/generalzip-native/Cargo.toml b/native/generalzip-native/Cargo.toml index 7bd67c1..8d76a25 100644 --- a/native/generalzip-native/Cargo.toml +++ b/native/generalzip-native/Cargo.toml @@ -23,7 +23,10 @@ ruzstd = "0.9" rust-zstd = "0.4" # bzip2 ≥0.6 默认后端即 libbz2-rs-sys(c2rust 转译的纯 Rust libbz2),无 C 工具链依赖 bzip2 = "0.6" +# brotli:纯 Rust 实现(单文件 .br 格式) +brotli = "8" unrar = { version = "0.5", optional = true } +sm2 = { version = "0.14", default-features = false, features = ["pke", "std"] } [profile.release] opt-level = 3 diff --git a/native/generalzip-native/src/lib.rs b/native/generalzip-native/src/lib.rs index 47d3115..fb1627d 100644 --- a/native/generalzip-native/src/lib.rs +++ b/native/generalzip-native/src/lib.rs @@ -11,6 +11,8 @@ mod caps; mod codecs; mod sevenz; +mod stream; +mod sm2; mod xz; #[cfg(feature = "rar")] diff --git a/native/generalzip-native/src/sm2.rs b/native/generalzip-native/src/sm2.rs new file mode 100644 index 0000000..b061688 --- /dev/null +++ b/native/generalzip-native/src/sm2.rs @@ -0,0 +1,95 @@ +use sm2::pke::DecryptingKey; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::slice; + +fn decrypt(private_key: &[u8], ciphertext: &[u8]) -> Result, i32> { + if private_key.len() != 32 || ciphertext.len() < 97 || ciphertext.len() > 1_048_576 { + return Err(crate::status::ERR_ARG); + } + + let key = DecryptingKey::from_slice(private_key).map_err(|_| crate::status::ERR_ARG)?; + key.decrypt(ciphertext) + .map_err(|_| crate::status::ERR_FORMAT) +} + +/// Decrypts an SM2 C1-C3-C2 ciphertext using the constant-time RustCrypto implementation. +#[no_mangle] +pub unsafe extern "system" fn gzp_sm2_decrypt( + private_key: *const u8, + private_key_len: u32, + ciphertext: *const u8, + ciphertext_len: u32, + output: *mut u8, + output_capacity: u32, + output_len: *mut u32, +) -> i32 { + if private_key.is_null() + || ciphertext.is_null() + || (output.is_null() && output_capacity != 0) + || output_len.is_null() + { + return crate::status::ERR_ARG; + } + if private_key_len != 32 || ciphertext_len < 97 || ciphertext_len > 1_048_576 { + return crate::status::ERR_ARG; + } + + unsafe { *output_len = 0 }; + let result = catch_unwind(AssertUnwindSafe(|| { + let private_key = unsafe { slice::from_raw_parts(private_key, private_key_len as usize) }; + let ciphertext = unsafe { slice::from_raw_parts(ciphertext, ciphertext_len as usize) }; + let plaintext = decrypt(private_key, ciphertext)?; + if plaintext.len() > output_capacity as usize { + return Err(crate::status::ERR_BUFFER); + } + + unsafe { + if !plaintext.is_empty() { + std::ptr::copy_nonoverlapping(plaintext.as_ptr(), output, plaintext.len()); + } + *output_len = plaintext.len() as u32; + } + Ok(()) + })); + + match result { + Ok(Ok(())) => crate::status::OK, + Ok(Err(code)) => code, + Err(_) => crate::status::ERR_PANIC, + } +} + +#[cfg(test)] +mod tests { + use super::decrypt; + + fn from_hex(text: &str) -> Vec { + text.as_bytes() + .chunks_exact(2) + .map(|pair| { + let digit = |b: u8| match b { + b'0'..=b'9' => b - b'0', + b'a'..=b'f' => b - b'a' + 10, + b'A'..=b'F' => b - b'A' + 10, + _ => panic!("invalid hex"), + }; + (digit(pair[0]) << 4) | digit(pair[1]) + }) + .collect() + } + + #[test] + fn decrypts_interop_anchor() { + let private_key = + from_hex("8c8b89335e42c636156ee63fd0c7afa0e1c1845b4a86feea77daef214b2b6cd8"); + let mut ciphertext = vec![0x04]; + ciphertext.extend(from_hex( + "28fb184b5a7a49cf8839fec53aba1d9987f8e9f8b540db4261d47a63e279950f26e590f7bd8a2178fd7983fef3da653d811b07058b1eb416debb0566085406773d6ade8f26c3200fcbedbe55ec731133b78cc8d437fa3582b9d24f6a50e1bfd9fb6e2c82fa8f58846a77b8c8fd6ca1cd4a9fd0a07e8d4c7c7108b2a96b14212382d8be6bd67f7ebd94a15f50600dc47d61", + )); + let plaintext = decrypt(&private_key, &ciphertext).unwrap(); + assert_eq!( + plaintext, + from_hex("676d73736c20696e7465726f7020616e63686f723a2047656e6572616c5a697020534d3220e9aa8ce8af81e59091e9878f") + ); + } +} diff --git a/native/generalzip-native/src/stream.rs b/native/generalzip-native/src/stream.rs new file mode 100644 index 0000000..2018fd7 --- /dev/null +++ b/native/generalzip-native/src/stream.rs @@ -0,0 +1,356 @@ +//! 流式编解码:经 C# 回调推拉的零临时文件转码。 +//! +//! 压缩(crun):Rust 经 `read_cb` 拉取明文(C# 侧读源流),编码器输出经 `write_cb` +//! 直接推回 C#(写入加密管道/目标流)。单调用跑完,天然支持取消与进度(回调内检查)。 +//! 解压(drun):对称地,Rust 经 `read_cb` 拉密文、经 `write_cb` 推明文。 +//! +//! 编解码器(纯 Rust):bzip2 / zstd / lz4 / xz / lzma-zip(ZIP method 14 框架)/ brotli。 +//! 边界纪律:回调返回负数视为失败并中止;任何 panic 经 catch_unwind 兜底。 + +use std::io::{self, BufReader, Read, Write}; +use std::os::raw::{c_char, c_int, c_void}; + +use crate::caps::{set_error, str_from_c_ptr}; +use crate::status; + +/// 读取回调:填 buf(≤cap),返回读取字节数;0 = EOF;负数 = 失败。 +pub type ReadCb = unsafe extern "system" fn(buf: *mut u8, cap: u32, user: *mut c_void) -> i32; +/// 写入回调:消费 buf(len 字节),0 = 成功;负数 = 失败。 +pub type WriteCb = unsafe extern "system" fn(buf: *const u8, len: u32, user: *mut c_void) -> i32; + +/// 回调适配的输入流(拉式)。 +struct CbReader { + read_cb: ReadCb, + user: *mut c_void, + eof: bool, +} + +impl Read for CbReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.eof || buf.is_empty() { + return Ok(0); + } + + let ret = unsafe { (self.read_cb)(buf.as_mut_ptr(), buf.len() as u32, self.user) }; + if ret > 0 { + Ok(ret as usize) + } else if ret == 0 { + self.eof = true; + Ok(0) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("read callback failed ({ret})"), + )) + } + } +} + +/// 回调适配的输出流(推式)。 +struct CbWriter { + write_cb: WriteCb, + user: *mut c_void, +} + +impl Write for CbWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + + let ret = unsafe { (self.write_cb)(buf.as_ptr(), buf.len() as u32, self.user) }; + if ret == 0 { + Ok(buf.len()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("write callback failed ({ret})"), + )) + } + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// 跳过输出流中 [from, to) 区间的字节(用于剥离 .lzma alone 头部的 size 字段)。 +struct SkippingWriter { + inner: W, + skip_from: u64, + skip_to: u64, + pos: u64, +} + +impl Write for SkippingWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + let mut written = 0usize; + while written < buf.len() { + let abs = self.pos; + if abs >= self.skip_from && abs < self.skip_to { + // 处于跳过区:静默丢弃到区间末或缓冲尾 + let advance = (self.skip_to - abs).min((buf.len() - written) as u64) as usize; + self.pos += advance as u64; + written += advance; + continue; + } + + // 连续可写段:写到跳过区起点或缓冲尾 + let seg_end = if abs < self.skip_from && (self.skip_from - abs) < (buf.len() - written) as u64 { + written + (self.skip_from - abs) as usize + } else { + buf.len() + }; + let n = self.inner.write(&buf[written..seg_end])?; + if n == 0 { + break; + } + + self.pos += n as u64; + written += n; + } + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + +/// 单字节回推流:多帧拼接解码时保留"偷看"到的下一帧首字节。 +struct PushbackReader<'a> { + inner: &'a mut dyn Read, + pushback: Option, +} + +impl Read for PushbackReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + + if let Some(b) = self.pushback.take() { + buf[0] = b; + return Ok(1); + } + + self.inner.read(buf) + } +} + +// ---------- 编解码器分发 ---------- + +fn compress_with(codec: &str, level: u32, input: &mut R, output: &mut W) -> io::Result<()> { + match codec { + "bzip2" => { + let mut encoder = bzip2::write::BzEncoder::new(output, bzip2::Compression::default()); + io::copy(input, &mut encoder)?; + encoder.finish().map(|_| ()) + } + "zstd" => { + let opts = rust_zstd::compress::CompressOptions { + level: clamp_zstd_level(level), + ..Default::default() + }; + let mut encoder = rust_zstd::compress::Encoder::new(output, opts); + io::copy(input, &mut encoder)?; + encoder.finish().map(|_| ()) + } + "lz4" => { + let mut encoder = lz4_flex::frame::FrameEncoder::new(output); + io::copy(input, &mut encoder)?; + encoder.finish().map(|_| ()).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string())) + } + "xz" => { + // lzma-rs 0.3 的压缩为纯字面量(无匹配),复用 xz.rs 的 lzma_rust2 编码路径 + let mut buffered = BufReader::new(input); + crate::xz::xz_encode(&mut buffered, output) + } + "lzma-zip" => { + // ZIP method 14 帧:ver(2) propsize(2) props(N) + LZMA1 流(带 EOPM) + // 输出 = 4B 头 + alone 头(props+dict+size)+ 流;剥离 alone 头中的 8B size 字段 + output.write_all(&[0x09, 0x16, 0x05, 0x00])?; + let mut skip = SkippingWriter { + inner: output, + skip_from: 5, + skip_to: 13, + pos: 0, + }; + let options = lzma_rs::compress::Options { + unpacked_size: lzma_rs::compress::UnpackedSize::WriteToHeader(None), // FFFF..FF + EOPM + }; + let mut buffered = BufReader::new(input); + lzma_rs::lzma_compress_with_options(&mut buffered, &mut skip, &options) + } + "brotli" => { + // CompressorWriter 在 Drop 时刷出终结块 + let mut encoder = brotli::CompressorWriter::new(output, 65536, clamp_brotli_level(level), 22); + io::copy(input, &mut encoder)?; + encoder.flush()?; + drop(encoder); + Ok(()) + } + other => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported codec id {other}"))), + } +} + +fn decompress_with(codec: &str, input: &mut R, output: &mut W) -> io::Result<()> { + match codec { + "bzip2" => { + let mut decoder = bzip2::read::BzDecoder::new(input); + io::copy(&mut decoder, output).map(|_| ()) + } + "zstd" => { + // 支持拼接多帧:单帧 EOF 后若输入未尽则续开新解码器 + let mut source = PushbackReader { inner: input, pushback: None }; + loop { + let mut decoder = rust_zstd::DecompressReader::new(&mut source); + let _ = io::copy(&mut decoder, output)?; + // 解码器 EOF:偷看一字节判断是否还有下一帧 + let mut probe = [0u8; 1]; + let n = source.read(&mut probe)?; + if n == 0 { + return Ok(()); + } + + source.pushback = Some(probe[0]); + } + } + "lz4" => { + let mut decoder = lz4_flex::frame::FrameDecoder::new(input); + io::copy(&mut decoder, output).map(|_| ()) + } + "xz" => { + let mut buffered = BufReader::new(input); + crate::xz::xz_decode(&mut buffered, output) + } + "lzma-zip" => { + // 重建 alone 头:props(N) + size=FFFF..FF,然后接剩余流(EOPM 结束) + let mut version = [0u8; 2]; + input.read_exact(&mut version)?; + let mut propsize_buf = [0u8; 2]; + input.read_exact(&mut propsize_buf)?; + let propsize = u16::from_le_bytes(propsize_buf) as usize; + let mut props = vec![0u8; propsize]; + input.read_exact(&mut props)?; + + let mut prefix = Vec::with_capacity(propsize + 8); + prefix.extend_from_slice(&props); + prefix.extend_from_slice(&0xFFFF_FFFF_FFFF_FFFF_u64.to_le_bytes()); + + let mut chained = prefix.chain(BufReader::new(input)); + lzma_rs::lzma_decompress(&mut chained, output).map_err(lzma_err) + } + "brotli" => { + let mut decoder = brotli::Decompressor::new(input, 65536); + io::copy(&mut decoder, output).map(|_| ()) + } + other => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported codec id {other}"))), + } +} + +/// lzma_rs 自有错误类型 → io::Error。 +fn lzma_err(e: lzma_rs::error::Error) -> io::Error { + io::Error::new(io::ErrorKind::Other, e.to_string()) +} + +fn clamp_zstd_level(level: u32) -> i32 { + if level == 0 { + 3 + } else { + (level as i32).clamp(1, 22) + } +} + +fn clamp_brotli_level(level: u32) -> u32 { + if level == 0 { + 9 + } else { + level.clamp(1, 11) + } +} + +// ---------- FFI ---------- + +/// 流式压缩:拉明文 → 推密文。返回 status;错误详情经 gzp_last_error。 +/// +/// # Safety +/// 指针与回调必须有效;回调不得重入本核心。 +#[no_mangle] +pub unsafe extern "system" fn gzp_codec_crun( + codec: *const c_char, + level: u32, + read_cb: ReadCb, + write_cb: WriteCb, + user: *mut c_void, +) -> c_int { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + crun_impl(codec, level, read_cb, write_cb, user) + })); + match result { + Ok(r) => r, + Err(_) => { + set_error("codec stream compress: internal panic"); + status::ERR_PANIC + } + } +} + +/// 流式解压:拉密文 → 推明文。 +/// +/// # Safety +/// 指针与回调必须有效;回调不得重入本核心。 +#[no_mangle] +pub unsafe extern "system" fn gzp_codec_drun( + codec: *const c_char, + read_cb: ReadCb, + write_cb: WriteCb, + user: *mut c_void, +) -> c_int { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + drun_impl(codec, read_cb, write_cb, user) + })); + match result { + Ok(r) => r, + Err(_) => { + set_error("codec stream decompress: internal panic"); + status::ERR_PANIC + } + } +} + +fn crun_impl(codec: *const c_char, level: u32, read_cb: ReadCb, write_cb: WriteCb, user: *mut c_void) -> c_int { + let name = match str_from_c_ptr(codec) { + Ok(p) => p.to_string(), + Err(e) => return e, + }; + + let mut input = CbReader { read_cb, user, eof: false }; + let mut output = CbWriter { write_cb, user }; + + match compress_with(&name, level, &mut input, &mut output) { + Ok(()) => status::OK, + Err(e) => { + set_error(format!("codec stream compress({name}): {e}")); + status::ERR_IO + } + } +} + +fn drun_impl(codec: *const c_char, read_cb: ReadCb, write_cb: WriteCb, user: *mut c_void) -> c_int { + let name = match str_from_c_ptr(codec) { + Ok(p) => p.to_string(), + Err(e) => return e, + }; + + let mut input = CbReader { read_cb, user, eof: false }; + let mut output = CbWriter { write_cb, user }; + + match decompress_with(&name, &mut input, &mut output) { + Ok(()) => status::OK, + Err(e) => { + set_error(format!("codec stream decompress({name}): {e}")); + status::ERR_IO + } + } +} diff --git a/samples/GeneralZip.Bench/Program.cs b/samples/GeneralZip.Bench/Program.cs index 408d8f6..0aae56b 100644 --- a/samples/GeneralZip.Bench/Program.cs +++ b/samples/GeneralZip.Bench/Program.cs @@ -16,8 +16,7 @@ var warmups = args.Length > 1 && int.TryParse(args[1], out var w) ? w : 1; var runs = args.Length > 2 && int.TryParse(args[2], out var r) ? r : 3; -var nativeOk = GeneralZipNative.Initialize(); -Initialize(); +var nativeOk = NativeCoreLoader.TryLoad(); Console.WriteLine($"GeneralZip benchmark native={(nativeOk ? "available" : "missing (skips 7z/BZ2/XZ/ZSTD/LZ4)")}"); Console.WriteLine($"Runtime: {Environment.Version} OS: {Environment.OSVersion.VersionString} Logical cores: {Environment.ProcessorCount}"); diff --git a/samples/GeneralZip.Fixtures/Program.cs b/samples/GeneralZip.Fixtures/Program.cs index 2e89462..2bdc8c3 100644 --- a/samples/GeneralZip.Fixtures/Program.cs +++ b/samples/GeneralZip.Fixtures/Program.cs @@ -14,8 +14,7 @@ // 用法: dotnet run -c Release // ===================================================================== -Initialize(); // 幂等引导(using static 裸调用) -var nativeOk = GeneralZipNative.Initialize(); +var nativeOk = NativeCoreLoader.TryLoad(); // 引导已隐式完成,此处仅探测核心可用性 var repoRoot = FindRepoRoot(); Env.FixturesDir = Path.Combine(repoRoot, "samples", "fixtures"); @@ -26,7 +25,7 @@ Console.WriteLine("Plaintext SHA-256:"); foreach (var (name, data) in Entries()) { - Console.WriteLine($" {name,-20} {Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()} ({data.Length}B)"); + Console.WriteLine($" {name,-20} {System.Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()} ({data.Length}B)"); } Console.WriteLine(); @@ -251,8 +250,8 @@ static void Verify(string fileName, string password) using var stream = reader.OpenEntryStream(entry); using var ms = new MemoryStream(); stream.CopyTo(ms); - var sha = Convert.ToHexString(SHA256.HashData(ms.ToArray())).ToLowerInvariant(); - var expected = Convert.ToHexString(SHA256.HashData(expectedData)).ToLowerInvariant(); + var sha = System.Convert.ToHexString(SHA256.HashData(ms.ToArray())).ToLowerInvariant(); + var expected = System.Convert.ToHexString(SHA256.HashData(expectedData)).ToLowerInvariant(); if (sha != expected) { throw new InvalidOperationException($"{fileName} content verification failed: {entry.FullName} (SHA-256 mismatch)"); diff --git a/samples/GeneralZip.Samples/Program.cs b/samples/GeneralZip.Samples/Program.cs index 8f2fc3d..c48fa9c 100644 --- a/samples/GeneralZip.Samples/Program.cs +++ b/samples/GeneralZip.Samples/Program.cs @@ -6,9 +6,8 @@ // 演示用口令:运行时拼接派生(避免源码硬编码;实际应用请从密钥管理服务/用户输入获取) static string DemoPassword(string label) => "GZ-" + label + "-Demo"; -// ===== 0) 启动引导:核心注册表 + 可选原生核心 ===== -Initialize(); // 幂等:确保内置格式/加密算法注册 -if (GeneralZipNative.Initialize()) // 可选:Rust 原生核心(7z/xz 能力;缺失时优雅降级) +// ===== 0) 原生核心状态展示(引导已隐式完成,无需手动调用) ===== +if (NativeCoreLoader.TryLoad()) // 可选:Rust 原生核心(7z/xz 能力;缺失时优雅降级) { Console.WriteLine($"[native core] v{GeneralZipNative.CoreVersion} loaded (7z/xz available)"); } @@ -31,9 +30,9 @@ await CompressAsync(src, zip, o => o.Level = CompressionLevelChoice.Optimal); Console.WriteLine($"[one-liner] compressed: {zip} ({new FileInfo(zip).Length}B, format {DetectFormat(zip)?.Name})"); -// ===== 1.5) 启动引导说明 ===== -// GeneralZip.Initialize() 为幂等引导入口(确保内置格式/算法注册,并自动加载内置 Rust 原生核心), -// 放在程序启动处调用一次即可;一行式 API 内部也会自动调用。 +// ===== 1.5) 引导说明 ===== +// GeneralZip 零初始化:内置格式/算法注册与 Rust 原生核心加载都在首次使用 API 时隐式完成 +//(Default 注册表装配时自动引导),核心缺失时优雅降级,纯托管能力不受影响。 // ===== 2) 国密 SM4 加密 ZIP(加密写 → 解密读) ===== var sm4Zip = Path.Combine(work, "secret-sm4.zip"); diff --git a/samples/fixtures/README.md b/samples/fixtures/README.md index 7b77290..4c27bb3 100644 --- a/samples/fixtures/README.md +++ b/samples/fixtures/README.md @@ -92,3 +92,18 @@ dotnet run -c Release --project samples/GeneralZip.Fixtures 生成器确定性:明文内容固定(文本 + 固定种子 LCG 二进制), 但加密归档本身含随机盐/IV,每次生成的归档字节不同——以明文 SHA-256 为准。 + +## 互操作锚点(`interop/` 子目录) + +以下归档由**独立实现**生成(py7zr、pycdlib、python zipfile、手写 GNU cpio newc), +GeneralZip 仅作为读取方 —— 这是跨实现兼容性的回归锚点,加密样例口令同上。 + +| 文件 | 生成方 | 说明 | +|---|---|---| +| `py7zr-sample.7z` | py7zr | 7z LZMA2,2 条目 | +| `py7zr-secret.7z` | py7zr | 7z AES-256 加密(演示口令) | +| `pycdlib-sample.iso` | pycdlib | ISO9660 + Joliet,含子目录 | +| `python-zip64.zip` | python zipfile | force_zip64 头部(sparse.bin 条目携带 Zip64 字段) | +| `gnu-cpio-newc.cpio` | 手写 newc | 含 S_IFLNK 符号链接条目 | + +由 `tests/GeneralZip.Tests/InteropFixtureTests.cs` 逐一校验。 diff --git a/samples/fixtures/interop/gnu-cpio-newc.cpio b/samples/fixtures/interop/gnu-cpio-newc.cpio new file mode 100644 index 0000000..b75a9bc Binary files /dev/null and b/samples/fixtures/interop/gnu-cpio-newc.cpio differ diff --git a/samples/fixtures/interop/py7zr-sample.7z b/samples/fixtures/interop/py7zr-sample.7z new file mode 100644 index 0000000..05e8a22 Binary files /dev/null and b/samples/fixtures/interop/py7zr-sample.7z differ diff --git a/samples/fixtures/interop/py7zr-secret.7z b/samples/fixtures/interop/py7zr-secret.7z new file mode 100644 index 0000000..d466f80 Binary files /dev/null and b/samples/fixtures/interop/py7zr-secret.7z differ diff --git a/samples/fixtures/interop/pycdlib-sample.iso b/samples/fixtures/interop/pycdlib-sample.iso new file mode 100644 index 0000000..260fe4a Binary files /dev/null and b/samples/fixtures/interop/pycdlib-sample.iso differ diff --git a/samples/fixtures/interop/python-zip64.zip b/samples/fixtures/interop/python-zip64.zip new file mode 100644 index 0000000..1371550 Binary files /dev/null and b/samples/fixtures/interop/python-zip64.zip differ diff --git a/src/GeneralZip.Cli/GeneralZip.Cli.csproj b/src/GeneralZip.Cli/GeneralZip.Cli.csproj new file mode 100644 index 0000000..b8e7a92 --- /dev/null +++ b/src/GeneralZip.Cli/GeneralZip.Cli.csproj @@ -0,0 +1,24 @@ + + + + Exe + net8.0 + GeneralZip.Cli + enable + enable + true + + true + gz + ../../artifacts + GeneralZip command line: cross-format compression (ZIP/7z/RAR/TAR/GZ/BZ2/XZ/Zstd/LZ4/Brotli/CPIO/ISO/CAB) with WinZip AES and Chinese national crypto (SM4-GM / SM2 envelope). dotnet tool install GeneralZip.Cli + zip;7z;rar;compression;archive;cli;tool;sm4;sm2;guomi;encryption;tar;gzip;zstd;lz4;bzip2;xz;brotli;cpio;iso;cab + true + true + + + + + + + diff --git a/src/GeneralZip.Cli/Program.cs b/src/GeneralZip.Cli/Program.cs new file mode 100644 index 0000000..2fc8c22 --- /dev/null +++ b/src/GeneralZip.Cli/Program.cs @@ -0,0 +1,455 @@ +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using GeneralZip.Cryptography; + +namespace GeneralZip.Cli; + +/// +/// GeneralZip 命令行工具(dotnet tool,命令名 gz)。 +/// 用法:gz <command> [args],命令:a(压缩) x(解压) t(测试) l(列表) c(转换) rm(删除) i(信息) detect keygen +/// +internal static class Program +{ + private static int Main(string[] args) + { + try + { + Console.OutputEncoding = Encoding.UTF8; + if (args.Length == 0 || args[0] is "-h" or "--help" or "help") + { + PrintHelp(); + return 0; + } + + if (args[0] is "--version" or "version") + { + var coreVersion = global::GeneralZip.Native.GeneralZipNative.CoreVersion ?? "(absent)"; + var corePath = global::GeneralZip.Native.GeneralZipNative.CorePath ?? "-"; + var version = global::GeneralZip.GeneralZip.Version; + Console.WriteLine($"gz (GeneralZip) {version}"); + Console.WriteLine($"native core: {coreVersion} @ {corePath}"); + return 0; + } + + return args[0] switch + { + "a" or "add" => CmdAdd(args[1..]), + "x" or "extract" => CmdExtract(args[1..]), + "t" or "test" => CmdTest(args[1..]), + "l" or "list" => CmdList(args[1..]), + "c" or "convert" => CmdConvert(args[1..]), + "rm" or "remove" => CmdRemove(args[1..]), + "i" or "info" => CmdInfo(args[1..]), + "detect" => CmdDetect(args[1..]), + "keygen" => CmdKeygen(args[1..]), + _ => Fail($"Unknown command: {args[0]} (try gz help)"), + }; + } + catch (Exception ex) + { + var original = Console.ForegroundColor; + try + { + Console.ForegroundColor = ConsoleColor.Red; + Console.Error.WriteLine($"error: {ex.Message}"); + } + finally + { + Console.ForegroundColor = original; + } + + return 1; + } + } + + private static int Fail(string message) + { + Console.Error.WriteLine(message); + return 2; + } + + private static void PrintHelp() + { + var cliVersion = global::GeneralZip.GeneralZip.Version; + Console.WriteLine($""" + gz (GeneralZip) {cliVersion} — cross-format compression CLI + + Usage: + gz a [-p ] [-e ] [-m ] [--level ] [-P ] [--volume ] [--parallel ] + gz x [-p ] [-g ] [-G ] [--parallel ] [--symlinks] + gz t [-p ] [--parallel ] + gz l [-p ] + gz c [-p ] [-w ] [-e ] + gz rm | -g [-p ] + gz i [-p ] + gz detect + gz keygen → SM2 key pair (private/public hex) + + Options: + -p password (or SM2 private key hex for SM2-GM archives) + -e encryption algorithm: WinZipAES256 (default) | SM4-GM | SM2-GM | ZipCrypto + -m zip method: Deflate | BZip2 | Zstd | Lzma + -P recipient SM2 public key hex (SM2-GM write) + -g include glob (x/rm), repeatable; -G exclude glob, repeatable + + Algorithms: WinZipAES128/256, SM4-GM (国密), SM2-GM envelope (国密信封), 7z AES-256, RAR (read), ZipCrypto (opt-in) + Formats: ZIP, 7z, RAR(read), TAR/GZ/BZ2, GZ, BZ2, XZ, ZSTD, LZ4, BROTLI, CPIO, ISO(read), CAB(read, stored) + """); + } + + private static (Dictionary options, List values) ParseArgs(string[] args) + { + var options = new Dictionary(); + var values = new List(); + for (var i = 0; i < args.Length; i++) + { + var arg = args[i]; + if (arg.StartsWith('-') && arg.Length >= 2 && arg != "--") + { + var name = arg.TrimStart('-'); + var value = "true"; + if (i + 1 < args.Length && !args[i + 1].StartsWith('-')) + { + value = args[++i]; + } + + options[name] = value; + } + else + { + values.Add(arg); + } + } + + return (options, values); + } + + private static void ApplyWriteOptions(string[] args, ArchiveWriteOptions o) + { + var (opts, _) = ParseArgs(args); + if (opts.TryGetValue("p", out var password)) + { + o.Password = password; + } + + if (opts.TryGetValue("e", out var algorithm)) + { + o.EncryptionAlgorithm = algorithm; + } + + if (opts.TryGetValue("P", out var publicKey)) + { + o.RecipientPublicKey = publicKey; + } + + if (opts.TryGetValue("m", out var method)) + { + o.ZipCompressionMethod = method switch + { + "Deflate" => ZipCompressionMethodChoice.Deflate, + "BZip2" => ZipCompressionMethodChoice.BZip2, + "Zstd" => ZipCompressionMethodChoice.Zstd, + "Lzma" => ZipCompressionMethodChoice.Lzma, + _ => throw new ArgumentException($"Unknown method: {method}"), + }; + } + + if (opts.TryGetValue("level", out var level)) + { + o.Level = level switch + { + "0" => CompressionLevelChoice.NoCompression, + "1" => CompressionLevelChoice.Fastest, + "3" => CompressionLevelChoice.SmallestSize, + _ => CompressionLevelChoice.Optimal, + }; + } + + if (opts.TryGetValue("volume", out var volume)) + { + o.VolumeSize = long.Parse(volume); + } + + if (opts.TryGetValue("parallel", out var parallel)) + { + o.MaxDegreeOfParallelism = int.Parse(parallel); + } + } + + private static string RequirePassword(string[] args) + { + var (opts, _) = ParseArgs(args); + return opts.TryGetValue("p", out var password) ? password : throw new ArgumentException("Password required (-p)"); + } + + // ---------- 命令 ---------- + + private static int CmdAdd(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 2) + { + return Fail("usage: gz a "); + } + + var archive = values[0]; + using var writer = GeneralZipWriter.CreateNew(archive, o => ApplyWriteOptions(args, o)); + + writer.EntryProgress += (_, e) => PrintProgress(e.Entry.FullName, e.BytesProcessed, e.BytesTotal); + writer.EntryCompleted += (_, e) => Console.WriteLine($" added {e.Entry.FullName}"); + + foreach (var source in values.Skip(1)) + { + if (File.Exists(source)) + { + writer.AddFile(source); + } + else if (Directory.Exists(source)) + { + writer.AddDirectory(source); + } + else + { + return Fail($"path not found: {source}"); + } + } + + writer.Finish(); + var fmt = writer.Format.Name; + Console.WriteLine($"{archive}: {fmt} done"); + return 0; + } + + private static long _lastPrint; + + private static void PrintProgress(string name, long bytes, long? total) + { + var now = Environment.TickCount64; + if (now - _lastPrint < 100 && total.HasValue) + { + return; // 节流 + } + + _lastPrint = now; + var pct = total.HasValue && total > 0 ? $"{100.0 * bytes / total:F0}%" : $"{bytes}B"; + Console.Write($"\r {name} {pct} "); + } + + private static int CmdExtract(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 2) + { + return Fail("usage: gz x "); + } + + var extraction = new ExtractionOptions(); + if (opts.TryGetValue("parallel", out var parallel)) + { + extraction.MaxDegreeOfParallelism = int.Parse(parallel); + } + + if (opts.TryGetValue("g", out var include)) + { + extraction.IncludePatterns = ParseArgs(args).options.Where(kv => kv.Key == "g").Select(kv => kv.Value).ToList(); + } + + if (opts.TryGetValue("G", out var exclude)) + { + extraction.ExcludePatterns = ParseArgs(args).options.Where(kv => kv.Key == "G").Select(kv => kv.Value).ToList(); + } + + if (opts.ContainsKey("symlinks")) + { + extraction.SymlinkPolicy = SymlinkPolicy.Preserve; + } + + extraction.PreserveUnixAttributes = true; + + var preset = opts.TryGetValue("p", out var password) ? password : null; + using var reader = GeneralZipReader.Open(values[0], preset != null + ? (Action)(o => o.Password = preset) + : null); + var result = reader.ExtractToDirectory(values[1], extraction); + Console.WriteLine($"{values[0]}: {result.ProcessedCount} extracted, {result.SkippedCount} skipped, {result.Failures.Count} failed"); + return result.Failures.Count == 0 ? 0 : 1; + } + + private static int CmdTest(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 1) + { + return Fail("usage: gz t "); + } + + var extraction = new ExtractionOptions { ErrorPolicy = ErrorPolicy.SkipAll }; + if (opts.TryGetValue("parallel", out var parallel)) + { + extraction.MaxDegreeOfParallelism = int.Parse(parallel); + } + + using var reader = GeneralZipReader.Open(values[0], o => + { + if (opts.TryGetValue("p", out var password)) + { + o.Password = password; + } + }); + var result = reader.TestAll(extraction); + Console.WriteLine(result.Success + ? $"{values[0]}: OK ({result.ProcessedCount} entries)" + : $"{values[0]}: {result.Failures.Count} FAILED"); + foreach (var failure in result.Failures) + { + Console.WriteLine($" {failure.EntryName}: {failure.Exception.Message}"); + } + + return result.Success ? 0 : 1; + } + + private static int CmdList(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 1) + { + return Fail("usage: gz l "); + } + + using var reader = GeneralZipReader.Open(values[0], o => + { + if (opts.TryGetValue("p", out var password)) + { + o.Password = password; + } + }); + + Console.WriteLine($"format={reader.Format.Name} entries={reader.Entries.Count} encrypted={reader.IsEncrypted}"); + foreach (var entry in reader.Entries) + { + var size = entry.Size >= 0 ? entry.Size.ToString() : "-"; + var comp = entry.CompressedSize >= 0 ? entry.CompressedSize.ToString() : "-"; + var enc = entry.IsEncrypted ? $" [{entry.EncryptionAlgorithm}]" : string.Empty; + var time = entry.LastWriteTime?.ToString("yyyy-MM-dd HH:mm") ?? "-"; + var mode = entry is IUnixEntry { UnixMode: { } m } + ? " mode=" + Convert.ToString(m & 0xFFF, 8).PadLeft(4, '0') + : string.Empty; + Console.WriteLine($"{(entry.IsDirectory ? "d" : "-")} {time} {size,12} {comp,12}{enc}{mode} {entry.FullName}"); + } + + return 0; + } + + private static int CmdConvert(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 2) + { + return Fail("usage: gz c "); + } + + global::GeneralZip.GeneralZip.Convert(values[0], values[1], o => + { + if (opts.TryGetValue("w", out var writePassword)) + { + o.Password = writePassword; + } + + if (opts.TryGetValue("e", out var algorithm)) + { + o.EncryptionAlgorithm = algorithm; + } + }, o => + { + if (opts.TryGetValue("p", out var password)) + { + o.Password = password; + } + }); + + Console.WriteLine($"{values[0]} → {values[1]}"); + return 0; + } + + private static int CmdRemove(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 1) + { + return Fail("usage: gz rm | -g "); + } + + var globs = opts.Where(kv => kv.Key == "g").Select(kv => kv.Value).ToList(); + global::GeneralZip.GeneralZip.Remove(values[0], + entryNames: values.Skip(1), + predicate: globs.Count > 0 + ? (Func)(e => globs.Any(g => GlobMatcher.IsMatch(e.FullName, g))) + : null); + + Console.WriteLine($"{values[0]} updated"); + return 0; + } + + private static int CmdInfo(string[] args) + { + var (opts, values) = ParseArgs(args); + if (values.Count < 1) + { + return Fail("usage: gz i "); + } + + var info = global::GeneralZip.GeneralZip.DetectFormat(values[0]); + Console.WriteLine($"format: {info?.Name ?? "unknown"}"); + if (info != null) + { + Console.WriteLine($"details: {info.Description}"); + } + + using var reader = GeneralZipReader.Open(values[0], o => + { + if (opts.TryGetValue("p", out var password)) + { + o.Password = password; + } + }); + + var files = reader.Entries.Count(e => !e.IsDirectory); + var dirs = reader.Entries.Count - files; + var totalSize = reader.Entries.Sum(e => Math.Max(0, e.Size)); + var totalComp = reader.Entries.Sum(e => Math.Max(0, e.CompressedSize)); + Console.WriteLine($"entries: {files} files, {dirs} dirs"); + Console.WriteLine($"size: {totalSize} → {totalComp}"); + Console.WriteLine($"encrypted: {(reader.IsEncrypted ? "yes" : "no")}"); + var nativeVersion = global::GeneralZip.Native.GeneralZipNative.CoreVersion ?? "(absent)"; + Console.WriteLine($"native: {nativeVersion}"); + return 0; + } + + private static int CmdDetect(string[] args) + { + if (args.Length < 1) + { + return Fail("usage: gz detect "); + } + + var info = global::GeneralZip.GeneralZip.DetectFormat(args[0]); + if (info == null) + { + Console.WriteLine("unknown"); + return 1; + } + + Console.WriteLine($"{info.Name} — {info.Description}"); + return 0; + } + + private static int CmdKeygen(string[] args) + { + var keyPair = Sm2KeyPair.Generate(); + Console.WriteLine($"private (hex): {keyPair.PrivateKeyHex}"); + Console.WriteLine($"public (hex): {keyPair.PublicKeyHex}"); + Console.WriteLine("Keep the private key safe; the public key is the SM2-GM recipient key (-P)."); + return 0; + } +} diff --git a/src/GeneralZip/Abstractions/ArchiveWriteOptions.cs b/src/GeneralZip/Abstractions/ArchiveWriteOptions.cs index b9938c0..d404fc7 100644 --- a/src/GeneralZip/Abstractions/ArchiveWriteOptions.cs +++ b/src/GeneralZip/Abstractions/ArchiveWriteOptions.cs @@ -13,12 +13,41 @@ public enum CompressionLevelChoice SmallestSize = 3, } +/// +/// ZIP 条目压缩方法(仅 ZIP 格式使用;其它格式忽略)。 +/// Auto = 空条目/NoCompression 用 Store,其余 Deflate。 +/// BZip2/Zstd/Lzma 需要 Rust 原生核心(缺失时抛 NativeCoreMissingException)。 +/// +public enum ZipCompressionMethodChoice +{ + Auto = 0, + Deflate = 1, + BZip2 = 2, + Zstd = 3, + Lzma = 4, +} + /// 创建归档的选项。 public sealed class ArchiveWriteOptions { /// 压缩级别。默认 Optimal。 public CompressionLevelChoice Level { get; set; } = CompressionLevelChoice.Optimal; + /// ZIP 条目压缩方法(其它格式忽略)。默认 Auto(Deflate)。 + public ZipCompressionMethodChoice ZipCompressionMethod { get; set; } = ZipCompressionMethodChoice.Auto; + + /// + /// 并行压缩的最大并发度(当前仅 ZIP 实现条目级分片并行:各条目压缩至独立临时分片, + /// Finish 时按序装配)。默认 1(顺序压缩);大于 1 的事件不保证条目顺序。 + /// + public int MaxDegreeOfParallelism { get; set; } = 1; + + /// + /// 分卷大小(字节)。大于 0 时输出为 x.zip.001/002/... 纯字节分卷(EOCD 落在末卷); + /// 读取端打开 x.zip.001 即自动拼接。默认 0 = 单文件。仅 ZIP 等顺序写入格式适用。 + /// + public long VolumeSize { get; set; } + /// 加密算法标识(注册表中的 AlgorithmId);null 表示不加密。 public string? EncryptionAlgorithm { get; set; } @@ -28,6 +57,17 @@ public sealed class ArchiveWriteOptions /// KDF 迭代次数(国密 SM4-GM 等支持自定义 KDF 的算法)。默认 10000。 public int KdfIterations { get; set; } = 10_000; + /// + /// KDF 算法标识(注册表 中的 KdfId, + /// 如 "SM3-PBKDF2"(默认)/ "PBKDF2-SHA256");null = 算法默认值。 + /// + public string? KdfAlgorithmId { get; set; } + + /// + /// 接收方 SM2 公钥(hex;"04||X||Y" 130 字符或 "X||Y" 128 字符)。SM2-GM 信封加密写路径必填。 + /// + public string? RecipientPublicKey { get; set; } + /// /// 直接注入加密提供者(优先于 查找注册表)。 /// 用于第三方自定义算法。 @@ -54,9 +94,14 @@ public sealed class ArchiveWriteOptions internal ArchiveWriteOptions CloneForFormat() => new() { Level = Level, + ZipCompressionMethod = ZipCompressionMethod, + MaxDegreeOfParallelism = MaxDegreeOfParallelism, + VolumeSize = VolumeSize, EncryptionAlgorithm = EncryptionAlgorithm, Password = Password, KdfIterations = KdfIterations, + KdfAlgorithmId = KdfAlgorithmId, + RecipientPublicKey = RecipientPublicKey, EntryNameEncoding = EntryNameEncoding, ArchiveComment = ArchiveComment, DefaultLastWriteTime = DefaultLastWriteTime, @@ -87,11 +132,29 @@ public sealed class ArchiveWriteOptions throw new NotSupportedException($"Encryption algorithm {provider.AlgorithmId} does not support writing"); } - if (Password == null) + // 写路径无需口令的算法(如 SM2-GM 信封,用接收方公钥加密数据密钥) + if (Password == null && provider is not IPasswordlessWriteProvider) { throw new ArgumentException($"Algorithm {provider.AlgorithmId} requires a password (options.Password)", nameof(Password)); } return provider; } + + /// 解析 KDF 提供者(KdfAlgorithmId → 注册表查找;未设置返回 null = 算法默认)。 + internal IKdfProvider? ResolveKdf(GeneralZipEncryptionRegistry registry) + { + if (KdfAlgorithmId == null) + { + return null; + } + + var kdf = registry.Kdfs.FindByName(KdfAlgorithmId); + if (kdf == null) + { + throw new UnsupportedFormatException($"Unregistered KDF algorithm: {KdfAlgorithmId}"); + } + + return kdf; + } } diff --git a/src/GeneralZip/Abstractions/EncryptionAbstractions.cs b/src/GeneralZip/Abstractions/EncryptionAbstractions.cs index 188d4fa..8f9cb66 100644 --- a/src/GeneralZip/Abstractions/EncryptionAbstractions.cs +++ b/src/GeneralZip/Abstractions/EncryptionAbstractions.cs @@ -8,24 +8,29 @@ namespace GeneralZip.Abstractions; public sealed class EncryptionWriteContext { public EncryptionWriteContext( - string password, + string? password, string entryName, uint? crc32, long? plainSize, ushort realCompressionMethod = 0, uint dosTime = 0, - int kdfIterations = 0) + int kdfIterations = 0, + IKdfProvider? kdf = null, + byte[]? recipientPublicKey = null) { - Password = password ?? throw new ArgumentNullException(nameof(password)); + Password = password; EntryName = entryName; Crc32 = crc32; PlainSize = plainSize; RealCompressionMethod = realCompressionMethod; DosTime = dosTime; KdfIterations = kdfIterations; + Kdf = kdf; + RecipientPublicKey = recipientPublicKey; } - public string Password { get; } + /// 口令。写路径无需口令的算法(IPasswordlessWriteProvider,如 SM2-GM 信封)为 null。 + public string? Password { get; } public string EntryName { get; } @@ -43,6 +48,12 @@ public EncryptionWriteContext( /// KDF 迭代次数(0 = 算法默认值)。 public int KdfIterations { get; } + + /// KDF 提供者(options.KdfAlgorithmId 解析结果;null = 算法默认 KDF)。 + public IKdfProvider? Kdf { get; } + + /// 接收方公钥(信封算法如 SM2-GM 需要;UTF-8 解码前为原始字节)。 + public byte[]? RecipientPublicKey { get; } } /// 读取侧加密上下文:条目密文与该算法在写入时登记的参数。 diff --git a/src/GeneralZip/Abstractions/ExtractionOptions.cs b/src/GeneralZip/Abstractions/ExtractionOptions.cs index 95258c3..df1b568 100644 --- a/src/GeneralZip/Abstractions/ExtractionOptions.cs +++ b/src/GeneralZip/Abstractions/ExtractionOptions.cs @@ -81,4 +81,29 @@ public sealed class ExtractionOptions /// 单条目复制缓冲区大小(字节)。默认 81920。 public int BufferSize { get; set; } = 81920; + + /// + /// 是否应用 Unix 权限位(;仅 Unix 平台生效,Windows 忽略)。 + /// 默认 false。 + /// + public bool PreserveUnixAttributes { get; set; } + + /// 符号链接条目处理策略。默认 。 + public SymlinkPolicy SymlinkPolicy { get; set; } = SymlinkPolicy.Skip; + + /// + /// 并行解压的最大并发度。默认 1(顺序解压,事件按条目顺序触发)。 + /// 大于 1 时按条目分片并行(要求归档以文件路径打开;条目顺序性事件不再保证顺序; + /// 交互式口令协商不可用——须预置 )。 + /// + public int MaxDegreeOfParallelism { get; set; } = 1; + + /// + /// Glob 包含模式(如 "photos/**/*.jpg"、"*.txt")。非空时仅解压匹配任一模式的条目。 + /// 与 并存:两者都需满足(AND 语义)。 + /// + public IReadOnlyList? IncludePatterns { get; set; } + + /// Glob 排除模式(如 "**/*.tmp");命中任一模式的条目被跳过(优先于包含模式判断)。 + public IReadOnlyList? ExcludePatterns { get; set; } } diff --git a/src/GeneralZip/Abstractions/IArchiveWriter.cs b/src/GeneralZip/Abstractions/IArchiveWriter.cs index 471cf63..8d8b918 100644 --- a/src/GeneralZip/Abstractions/IArchiveWriter.cs +++ b/src/GeneralZip/Abstractions/IArchiveWriter.cs @@ -41,6 +41,23 @@ public sealed class ArchiveEntryMetadata public string? Comment { get; set; } + /// + /// Unix 权限模式(st_mode,含类型位)。ZIP 以 Unix host(3)写入 ExternalAttributes, + /// TAR 写入 mode 字段;null = 不携带(ZIP 用 MS-DOS host,TAR 用 0644/0755 默认)。 + /// + public uint? UnixMode { get; set; } + /// 归档内不可见的外部源路径(供实现优化,如原生核心直接落盘文件);门面层设置。 public string? SourcePath { get; set; } + + /// 深拷贝(调用方可继续复用原对象)。 + public ArchiveEntryMetadata Clone() => new() + { + Size = Size, + LastWriteTime = LastWriteTime, + Crc32 = Crc32, + Comment = Comment, + UnixMode = UnixMode, + SourcePath = SourcePath, + }; } diff --git a/src/GeneralZip/Abstractions/KdfAbstractions.cs b/src/GeneralZip/Abstractions/KdfAbstractions.cs new file mode 100644 index 0000000..a233acc --- /dev/null +++ b/src/GeneralZip/Abstractions/KdfAbstractions.cs @@ -0,0 +1,33 @@ +using System; + +namespace GeneralZip.Abstractions; + +/// +/// 密钥派生函数(KDF)提供者。口令 → 密钥材料。 +/// 实现要求:无状态、线程安全;可经 GeneralZipEncryptionRegistry.Kdfs.Register 注册。 +/// SM4-GM 容器规范(CRYPTO-SPEC.md)在 extra field 中以 1 字节 +/// 标识 KDF:1 = SM3-PBKDF2(内置),2 = PBKDF2-HMAC-SHA256(内置),自定义算法请避开已占用值。 +/// +public interface IKdfProvider +{ + /// 容器规范中的 1 字节 KDF 标识(SM4-GM extra field 使用)。 + byte SpecId { get; } + + /// 注册表内的唯一标识名(如 "SM3-PBKDF2"、"PBKDF2-SHA256")。 + string KdfId { get; } + + /// 从口令派生 outputLength 字节的密钥材料。 + /// UTF-8 口令。 + /// 盐。 + /// 迭代/工作量参数(实现自行解释语义,0 = 实现默认值)。 + /// 输出字节数。 + byte[] Derive(string password, byte[] salt, int iterations, int outputLength); +} + +/// +/// 标记接口:写路径不需要口令的加密提供者(如 SM2-GM 信封:写侧只需接收方公钥)。 +/// 未实现本接口的提供者在 缺失时于解析期报错。 +/// +public interface IPasswordlessWriteProvider +{ +} diff --git a/src/GeneralZip/Abstractions/UnixAbstractions.cs b/src/GeneralZip/Abstractions/UnixAbstractions.cs new file mode 100644 index 0000000..f6becb7 --- /dev/null +++ b/src/GeneralZip/Abstractions/UnixAbstractions.cs @@ -0,0 +1,38 @@ +using System; + +namespace GeneralZip.Abstractions; + +/// +/// Unix 属性条目视图(可选能力接口):ZIP(Unix host 的 ExternalAttributes)与 +/// TAR(ustar mode 字段)在读取时实现。 +/// 符号链接判定: 类型位 (mode & 0xF000) == 0xA000; +/// 目标路径:(TAR 在头部携带;ZIP 等以条目内容承载,此处为 null)。 +/// +public interface IUnixEntry +{ + /// Unix st_mode(含文件类型位与权限位);格式未携带时为 null。 + uint? UnixMode { get; } + + /// 符号链接目标(条目为符号链接且格式在头部携带目标时);否则 null。 + string? SymlinkTarget { get; } +} + +/// +/// 符号链接写入能力(可选接口):ZIP(S_IFLNK 条目 + Unix ExternalAttributes)与 +/// TAR(typeflag '2' + linkname)实现。门面 依此分派。 +/// +public interface IArchiveSymlinkWriter +{ + /// 写入一个符号链接条目(target 为链接目标路径字符串)。 + void AddSymlink(string entryName, string target, ArchiveEntryMetadata metadata); +} + +/// 解压时的符号链接处理策略。 +public enum SymlinkPolicy +{ + /// 跳过符号链接条目(默认:防 zip-slip 类攻击的保守选择)。 + Skip = 0, + + /// 按条目创建符号链接(Windows 需要开发者模式/管理员权限;失败降级为普通文件写入目标路径文本)。 + Preserve = 1, +} diff --git a/src/GeneralZip/ArchiveFormatRegistry.cs b/src/GeneralZip/ArchiveFormatRegistry.cs index df5b65b..a738a79 100644 --- a/src/GeneralZip/ArchiveFormatRegistry.cs +++ b/src/GeneralZip/ArchiveFormatRegistry.cs @@ -27,10 +27,25 @@ internal GeneralZipFormatRegistry(bool populateBuiltins) Register(new Formats.Codecs.XzFormat()); Register(new Formats.Codecs.ZstdFormat()); Register(new Formats.Codecs.Lz4Format()); + Register(new Formats.Codecs.BrotliFormat()); + Register(new Formats.Cpio.CpioFormat()); + Register(new Formats.Iso.IsoFormat()); + Register(new Formats.Cab.CabFormat()); } } - public static GeneralZipFormatRegistry Default { get; } = new(populateBuiltins: true); + public static GeneralZipFormatRegistry Default { get; } = CreateDefault(); + + /// + /// 默认注册表装配:内置格式注册后即触发原生引导(幂等)。 + /// 原生核心在位时追加 7z/RAR 并注入编解码桥接;缺失时静默降级,纯托管能力不受影响。 + /// + private static GeneralZipFormatRegistry CreateDefault() + { + var registry = new GeneralZipFormatRegistry(populateBuiltins: true); + global::GeneralZip.Native.GeneralZipNative.Bootstrap(registry); + return registry; + } /// 注册格式提供者(重复注册同名格式将覆盖旧的)。 public void Register(IArchiveFormat format) diff --git a/src/GeneralZip/ArchiveReader.cs b/src/GeneralZip/ArchiveReader.cs index f9c8b2f..96095bc 100644 --- a/src/GeneralZip/ArchiveReader.cs +++ b/src/GeneralZip/ArchiveReader.cs @@ -15,10 +15,12 @@ namespace GeneralZip; public sealed class GeneralZipReader : IDisposable { private IArchiveReader _inner; - private FileStream? _ownedStream; // set when opened by path; closed on Dispose + private Stream? _ownedStream; // set when opened by path (or volume set); closed on Dispose private readonly ArchiveOpenOptions _options; private readonly PasswordGate _passwords; private EventHandler? _passwordRequired; + private readonly object _eventLock = new(); + private string? _sourcePath; // 并行解压时供工作实例按路径重开 private GeneralZipReader(ArchiveOpenOptions options) { @@ -51,6 +53,27 @@ public static GeneralZipReader Open( configure?.Invoke(options); options.SourceName = System.IO.Path.GetFileName(path); + // 分卷:x.zip.001 → 按序拼接 001/002/... 后按普通流探测 + var volumes = global::GeneralZip.Internal.SplitVolumeLocator.Resolve(path); + if (volumes != null) + { + var volumeStream = new global::GeneralZip.Internal.MultiVolumeStream(volumes); + GeneralZipReader? volumeReader = null; + try + { + volumeReader = new GeneralZipReader(options); + AttachCore(volumeReader, volumeStream, options, initialize, registry, path, formatName: null); + volumeReader._ownedStream = volumeStream; + return volumeReader; + } + catch + { + volumeReader?.Dispose(); + volumeStream.Dispose(); + throw; + } + } + var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); GeneralZipReader? reader = null; try @@ -60,6 +83,7 @@ public static GeneralZipReader Open( // Opening by path: the reader owns the FileStream. Format readers are created // with ownsStream:false, so the facade must close the stream on Dispose. reader._ownedStream = stream; + reader._sourcePath = path; return reader; } catch @@ -244,9 +268,21 @@ public ArchiveResult ExtractEntry( string destinationFilePath, ExtractionOptions? options = null, CancellationToken cancellationToken = default) + => ExtractEntryCore(entry, destinationFilePath, options, cancellationToken, testOnly: false); + + /// 完整性测试单个条目(不落盘)。并行 TestAll 的工作实例入口。 + internal ArchiveResult TestEntry(IArchiveEntry entry, ExtractionOptions? options, CancellationToken cancellationToken) + => ExtractEntryCore(entry, string.Empty, options, cancellationToken, testOnly: true); + + private ArchiveResult ExtractEntryCore( + IArchiveEntry entry, + string destinationFilePath, + ExtractionOptions? options, + CancellationToken cancellationToken, + bool testOnly) { if (entry == null) throw new ArgumentNullException(nameof(entry)); - if (destinationFilePath == null) throw new ArgumentNullException(nameof(destinationFilePath)); + if (!testOnly && destinationFilePath == null) throw new ArgumentNullException(nameof(destinationFilePath)); EnsureAttached(); options ??= new ExtractionOptions(); @@ -258,9 +294,14 @@ public ArchiveResult ExtractEntry( var relay = new EntryProgressRelay(this, entry, progress); var dummy = 0; - var outcome = ExtractOne(entry, destinationFilePath, options, cancellationToken, relay, progress, result, new List(), testOnly: false, ref dummy); + var failures = new List(); + var rootDirectory = testOnly + ? string.Empty + : Path.GetDirectoryName(Path.GetFullPath(destinationFilePath)) ?? Path.GetFullPath("."); + var outcome = ExtractOne(entry, destinationFilePath, rootDirectory, options, cancellationToken, relay, progress, result, failures, testOnly, ref dummy); progress.Finalize(entry.Size >= 0 ? entry.Size : relay.BytesProcessed); if (outcome == Outcome.Abort) result.Aborted = true; + result.Failures = failures; return result; } @@ -286,6 +327,11 @@ private ArchiveResult ExtractCore( Directory.CreateDirectory(destinationDirectory!); } + if (options.MaxDegreeOfParallelism > 1 && _inner.Entries.Count > 1) + { + return ExtractCoreParallel(destinationDirectory, options, cancellationToken, testOnly, result, failures); + } + long totalBytes = 0; var allKnown = true; foreach (var e in _inner.Entries) @@ -313,7 +359,15 @@ private ArchiveResult ExtractCore( continue; } - if (options.Filter != null && !options.Filter(entry)) + if (!testOnly && options.SymlinkPolicy == SymlinkPolicy.Skip && IsSymlink(entry)) + { + result.SkippedCount++; + progress.CompleteEntry(Math.Max(0, entry.Size)); + continue; + } + + if ((options.Filter != null && !options.Filter(entry)) + || !GlobMatcher.Matches(entry.FullName, options.IncludePatterns, options.ExcludePatterns)) { result.SkippedCount++; progress.CompleteEntry(Math.Max(0, entry.Size)); @@ -339,7 +393,7 @@ private ArchiveResult ExtractCore( var relay = new EntryProgressRelay(this, entry, progress); var retryCount = 0; - var outcome = ExtractOne(entry, targetPath, options, cancellationToken, relay, progress, result, failures, testOnly, ref retryCount); + var outcome = ExtractOne(entry, targetPath, destinationDirectory ?? string.Empty, options, cancellationToken, relay, progress, result, failures, testOnly, ref retryCount); if (outcome == Outcome.Abort) { result.Aborted = true; @@ -356,9 +410,197 @@ private ArchiveResult ExtractCore( private enum Outcome { Done, Abort } + // ---------- 并行解压 ---------- + + private ArchiveResult ExtractCoreParallel( + string? destinationDirectory, + ExtractionOptions options, + CancellationToken cancellationToken, + bool testOnly, + ArchiveResult result, + List failures) + { + if (_sourcePath == null) + { + throw new NotSupportedException( + "Parallel extraction requires the archive to be opened by path (GeneralZipReader.Open(path, ...)). " + + "Stream-based readers share one underlying stream and cannot be reopened per worker."); + } + + // 目录条目顺序创建(避免并发建目录竞态);文件条目按索引分片并行 + var fileEntries = new List<(IArchiveEntry Entry, int Index)>(); + for (var entryIndex = 0; entryIndex < _inner.Entries.Count; entryIndex++) + { + var entry = _inner.Entries[entryIndex]; + if (entry.IsDirectory) + { + if (!testOnly) + { + var dir = EntryPathResolver.Resolve(destinationDirectory!, entry, flatten: options.Flatten); + if (dir != null) Directory.CreateDirectory(dir); + } + + continue; + } + + if (!testOnly && options.SymlinkPolicy == SymlinkPolicy.Skip && IsSymlink(entry)) + { + result.SkippedCount++; + continue; + } + + if ((options.Filter != null && !options.Filter(entry)) + || !GlobMatcher.Matches(entry.FullName, options.IncludePatterns, options.ExcludePatterns)) + { + result.SkippedCount++; + continue; + } + + fileEntries.Add((entry, entryIndex)); + } + + if (fileEntries.Count == 0) + { + result.Failures = failures; + return result; + } + + var dop = Math.Min(options.MaxDegreeOfParallelism, fileEntries.Count); + var chunkSize = (fileEntries.Count + dop - 1) / dop; + var workerFailures = new List[dop]; + var exceptions = new List(); + + Parallel.For(0, dop, new ParallelOptions + { + MaxDegreeOfParallelism = dop, + CancellationToken = cancellationToken, + }, workerIndex => + { + var lo = workerIndex * chunkSize; + var hi = Math.Min(fileEntries.Count, lo + chunkSize); + if (lo >= hi) + { + workerFailures[workerIndex] = new List(); + return; + } + + try + { + using var worker = OpenWorkerReader(); + var localFailures = new List(); + long processed = 0; + long skipped = 0; + for (var i = lo; i < hi; i++) + { + var item = fileEntries[i]; + var entry = worker.Entries[item.Index]; + if (testOnly) + { + var testResult = worker.TestEntry(entry, options, cancellationToken); + processed += testResult.ProcessedCount; + if (testResult.Failures != null) localFailures.AddRange(testResult.Failures); + if (testResult.Aborted) result.Aborted = true; + continue; + } + + var targetPath = EntryPathResolver.Resolve(destinationDirectory!, entry, flatten: options.Flatten); + if (targetPath == null) + { + var ex = new ArchiveException("Unsafe entry path (absolute path or path traversal); extraction denied", entry.FullName); + RaiseEntryFailed(entry, ex); + localFailures.Add(new FailedEntry(entry.FullName, ex)); + continue; + } + + var workerResult = worker.ExtractEntry(entry, targetPath, options, cancellationToken); + processed += workerResult.ProcessedCount; + skipped += workerResult.SkippedCount; + if (workerResult.Failures != null) localFailures.AddRange(workerResult.Failures); + if (workerResult.Aborted) result.Aborted = true; + } + + workerFailures[workerIndex] = localFailures; + lock (result) + { + result.ProcessedCount += processed; + result.SkippedCount += skipped; + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + lock (exceptions) + { + exceptions.Add(ex); + } + } + }); + + foreach (var list in workerFailures) + { + if (list != null) + { + failures.AddRange(list); + } + } + + if (exceptions.Count > 0) + { + throw exceptions[0]; + } + + result.Failures = failures; + return result; + } + + /// 并行工作实例:按路径重开归档(预置口令随选项传入),事件转发至主实例(加锁串行化)。 + private GeneralZipReader OpenWorkerReader() + { + var preset = _options.Password ?? Password; + var worker = GeneralZipReader.Open(_sourcePath!, preset != null ? o => o.Password = preset : null); + + worker.EntryStarted += (_, args) => RaiseEntryStarted(args.Entry); + worker.EntryCompleted += (_, args) => RaiseEntryCompleted(args.Entry); + worker.EntryFailed += (_, args) => RaiseEntryFailed(args.Entry, args.Exception); + worker.EntryProgress += (_, args) => + { + lock (_eventLock) + { + EntryProgress?.Invoke(this, args); + } + }; + worker.OverallProgress += (_, progress) => + { + lock (_eventLock) + { + OverallProgress?.Invoke(this, progress); + } + }; + worker.OverwriteQuery += (_, args) => + { + lock (_eventLock) + { + OverwriteQuery?.Invoke(this, args); + } + }; + worker.ErrorReport += (_, args) => + { + lock (_eventLock) + { + ErrorReport?.Invoke(this, args); + } + }; + + return worker; + } + private Outcome ExtractOne( IArchiveEntry entry, string? targetPath, + string rootDirectory, ExtractionOptions options, CancellationToken cancellationToken, EntryProgressRelay relay, @@ -395,6 +637,11 @@ private Outcome ExtractOne( finalPath = EntryPathResolver.NextAvailableName(finalPath, options.MaxRenameAttempts); } + if (EntryPathResolver.ContainsReparsePoint(rootDirectory, finalPath!)) + { + throw new ArchiveException("Extraction path traverses a symbolic link or reparse point; extraction denied", entry.FullName); + } + var dir = Path.GetDirectoryName(finalPath); if (!string.IsNullOrEmpty(dir)) { @@ -402,21 +649,36 @@ private Outcome ExtractOne( } } - using (var source = _inner.OpenEntryStream(entry)) + var entryStream = _inner is ICancellableEntryStreamProvider cancellable + ? cancellable.OpenEntryStream(entry, cancellationToken) + : _inner.OpenEntryStream(entry); + using (var source = entryStream) { if (testOnly) { Drain(source, options.BufferSize, relay, cancellationToken); } + else if (TryCreateSymlink(source, entry, finalPath!, rootDirectory, options)) + { + // 符号链接条目:按策略创建链接(或降级为普通文件写入目标文本) + } else { CopyToFile(source, finalPath!, options.BufferSize, relay, cancellationToken); } } - if (!testOnly && options.PreserveTimestamps && entry.LastWriteTime.HasValue) + if (!testOnly) { - TrySetTimestamp(finalPath!, entry.LastWriteTime.Value); + if (options.PreserveTimestamps && entry.LastWriteTime.HasValue) + { + TrySetTimestamp(finalPath!, entry.LastWriteTime.Value); + } + + if (options.PreserveUnixAttributes && (entry as IUnixEntry)?.UnixMode is { } unixMode) + { + TrySetUnixMode(finalPath!, unixMode); + } } RaiseEntryCompleted(entry); @@ -551,15 +813,33 @@ private bool RaiseSafe(T args, Action raise, ExtractionOptions options) } } - private void RaiseEntryStarted(IArchiveEntry entry) => EntryStarted?.Invoke(this, new EntryEventArgs(entry)); + private void RaiseEntryStarted(IArchiveEntry entry) + { + lock (_eventLock) + { + EntryStarted?.Invoke(this, new EntryEventArgs(entry)); + } + } - private void RaiseEntryCompleted(IArchiveEntry entry) => EntryCompleted?.Invoke(this, new EntryEventArgs(entry)); + private void RaiseEntryCompleted(IArchiveEntry entry) + { + lock (_eventLock) + { + EntryCompleted?.Invoke(this, new EntryEventArgs(entry)); + } + } - private void RaiseEntryFailed(IArchiveEntry entry, Exception ex) => EntryFailed?.Invoke(this, new EntryFailedEventArgs(entry, ex)); + private void RaiseEntryFailed(IArchiveEntry entry, Exception ex) + { + lock (_eventLock) + { + EntryFailed?.Invoke(this, new EntryFailedEventArgs(entry, ex)); + } + } // ---------- IO ---------- - private static void CopyToFile(Stream source, string targetPath, int bufferSize, EntryProgressRelay relay, CancellationToken ct) + private static void CopyToFile(Stream source, string targetPath, int bufferSize, EntryProgressRelay? relay, CancellationToken ct) { using var target = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize, useAsync: false); var buffer = new byte[bufferSize]; @@ -568,18 +848,18 @@ private static void CopyToFile(Stream source, string targetPath, int bufferSize, { ct.ThrowIfCancellationRequested(); target.Write(buffer, 0, read); - relay.Report(read); + relay?.Report(read); } } - private static void Drain(Stream source, int bufferSize, EntryProgressRelay relay, CancellationToken ct) + private static void Drain(Stream source, int bufferSize, EntryProgressRelay? relay, CancellationToken ct) { var buffer = new byte[bufferSize]; int read; while ((read = source.Read(buffer, 0, buffer.Length)) > 0) { ct.ThrowIfCancellationRequested(); - relay.Report(read); + relay?.Report(read); } } @@ -595,6 +875,94 @@ private static void TrySetTimestamp(string path, DateTimeOffset time) } } + /// 应用 Unix 权限位(仅 Unix 平台的 net8+ 生效;失败不影响解压结果)。 + private static void TrySetUnixMode(string path, uint mode) + { +#if NET8_0_OR_GREATER + if (!OperatingSystem.IsLinux() && !OperatingSystem.IsMacOS()) + { + return; + } + + try + { + var perms = (System.IO.UnixFileMode)(mode & 0xFFF); + if (File.Exists(path)) + { + File.SetUnixFileMode(path, perms); + } + } + catch (Exception) + { + // 权限应用失败不影响解压结果 + } +#endif + } + + /// + /// 符号链接条目处理。返回 true 表示条目已按符号链接处理(无需常规复制)。 + /// 策略 Skip → 调用方按普通文件写入;策略 Preserve → 创建链接(失败降级为普通文件)。 + /// + private bool TryCreateSymlink(Stream source, IArchiveEntry entry, string targetPath, string rootDirectory, ExtractionOptions options) + { + var unix = entry as IUnixEntry; + var mode = unix?.UnixMode; + var isSymlink = mode.HasValue && (mode & 0xF000u) == 0xA000u; + if (!isSymlink) + { + return false; + } + + if (options.SymlinkPolicy != SymlinkPolicy.Preserve) + { + Drain(source, options.BufferSize, relay: null, default); + return true; + } + + // 链接目标:TAR 在头部携带;ZIP 等以条目内容承载 + string target; + if (unix!.SymlinkTarget != null) + { + target = unix.SymlinkTarget; + // ZIP/TAR 符号链接条目可能同时携带数据流:消耗掉以防流状态不一致 + Drain(source, options.BufferSize, relay: null, default); + } + else + { + using var ms = new MemoryStream(); + source.CopyTo(ms, options.BufferSize); + target = System.Text.Encoding.UTF8.GetString(ms.ToArray()); + } + + if (!EntryPathResolver.LinkTargetStaysWithinRoot(rootDirectory, targetPath, target)) + { + throw new ArchiveException("Symbolic link target escapes the extraction root", entry.FullName); + } + + try + { +#if NET8_0_OR_GREATER + File.CreateSymbolicLink(targetPath, target); +#else + // netstandard2.0 无托管符号链接 API:降级为普通文件 + File.WriteAllText(targetPath, target, System.Text.Encoding.UTF8); +#endif + return true; + } + catch (Exception) + { + // Windows 无开发者模式等场景:降级为普通文件写入目标文本 + File.WriteAllText(targetPath, target, System.Text.Encoding.UTF8); + return true; + } + } + + private static bool IsSymlink(IArchiveEntry entry) + { + var mode = (entry as IUnixEntry)?.UnixMode; + return mode.HasValue && (mode.Value & 0xF000u) == 0xA000u; + } + private void EnsureAttached() { if (_inner is NullInner) diff --git a/src/GeneralZip/ArchiveWriter.cs b/src/GeneralZip/ArchiveWriter.cs index dbffa18..3d99662 100644 --- a/src/GeneralZip/ArchiveWriter.cs +++ b/src/GeneralZip/ArchiveWriter.cs @@ -61,7 +61,10 @@ public static GeneralZipWriter CreateNew( var dir = Path.GetDirectoryName(Path.GetFullPath(archivePath)); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); - var stream = new FileStream(archivePath, FileMode.Create, FileAccess.Write, FileShare.None, 65536, useAsync: false); + var volumeSize = options.VolumeSize; + Stream stream = volumeSize > 0 + ? new global::GeneralZip.Internal.VolumeSplitStream(archivePath, volumeSize) + : new FileStream(archivePath, FileMode.Create, FileAccess.Write, FileShare.None, 65536, useAsync: false); try { var writer = OpenOnStreamCore(stream, format, options); @@ -125,14 +128,26 @@ private static GeneralZipWriter OpenOnStreamCore(Stream stream, IArchiveFormat f public void AddFile(string filePath, string? entryName = null) { using var content = OpenSourceFile(filePath, entryName, out var name, out var size, out var mtime); - AddEntryCore(name, content, size, mtime, CancellationToken.None); + var meta = new ArchiveEntryMetadata + { + Size = size, + LastWriteTime = mtime, + UnixMode = ProbeUnixMode(filePath), + }; + AddEntryCore(name, content, size, mtime, CancellationToken.None, meta); } /// 异步添加文件。 public async Task AddFileAsync(string filePath, string? entryName = null, CancellationToken cancellationToken = default) { using var content = OpenSourceFile(filePath, entryName, out var name, out var size, out var mtime); - await AddEntryCoreAsync(name, content, size, mtime, cancellationToken).ConfigureAwait(false); + var meta = new ArchiveEntryMetadata + { + Size = size, + LastWriteTime = mtime, + UnixMode = ProbeUnixMode(filePath), + }; + await AddEntryCoreAsync(name, content, size, mtime, cancellationToken, meta).ConfigureAwait(false); } /// @@ -156,6 +171,90 @@ public void AddStream(string entryName, Stream content, long? size = null, DateT AddEntryCore(entryName, content, size, lastWriteTime, CancellationToken.None); } + /// + /// 添加流内容为条目(完整元数据版):条目名/大小/时间戳/注释由 metadata 提供。 + /// 用于重打包等需要忠实保留原条目元数据的场景。 + /// + public void AddStream(string entryName, Stream content, ArchiveEntryMetadata metadata) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (content == null) throw new ArgumentNullException(nameof(content)); + if (metadata == null) throw new ArgumentNullException(nameof(metadata)); + + var meta = metadata.Clone(); + meta.Size = meta.Size < 0 ? -1 : meta.Size; + AddEntryCore(entryName, content, meta.Size >= 0 ? meta.Size : null, meta.LastWriteTime, CancellationToken.None, meta); + } + + public Task AddStreamAsync( + string entryName, + Stream content, + long? size = null, + DateTimeOffset? lastWriteTime = null, + CancellationToken cancellationToken = default) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (content == null) throw new ArgumentNullException(nameof(content)); + return Task.Run( + () => AddEntryCore(entryName, content, size, lastWriteTime, cancellationToken), + cancellationToken); + } + + internal Task AddStreamAsync( + string entryName, + Stream content, + ArchiveEntryMetadata metadata, + CancellationToken cancellationToken) + { + if (metadata == null) throw new ArgumentNullException(nameof(metadata)); + var meta = metadata.Clone(); + return Task.Run( + () => AddEntryCore(entryName, content, meta.Size >= 0 ? meta.Size : null, meta.LastWriteTime, cancellationToken, meta), + cancellationToken); + } + + /// + /// 写入一个目录占位条目(格式支持时;不支持目录概念的格式会忽略)。 + /// + public void AddDirectoryEntry(string entryName, DateTimeOffset? lastWriteTime = null) + => AddDirectoryEntry(entryName, new ArchiveEntryMetadata + { + LastWriteTime = lastWriteTime ?? _options.DefaultLastWriteTime ?? DateTimeOffset.Now, + }); + + internal void AddDirectoryEntry(string entryName, ArchiveEntryMetadata metadata) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (metadata == null) throw new ArgumentNullException(nameof(metadata)); + _inner.AddDirectoryEntry(entryName, metadata); + } + + /// + /// 写入符号链接条目。格式需支持符号链接(ZIP / TAR 实现;其它格式抛 NotSupportedException)。 + /// + /// 条目名。 + /// 链接目标路径(原样写入归档,不做解析)。 + /// 时间戳。 + public void AddSymlink(string entryName, string target, DateTimeOffset? lastWriteTime = null) + => AddSymlink(entryName, target, new ArchiveEntryMetadata + { + LastWriteTime = lastWriteTime ?? _options.DefaultLastWriteTime ?? DateTimeOffset.Now, + }); + + internal void AddSymlink(string entryName, string target, ArchiveEntryMetadata metadata) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (target == null) throw new ArgumentNullException(nameof(target)); + if (metadata == null) throw new ArgumentNullException(nameof(metadata)); + + if (_inner is not IArchiveSymlinkWriter symlinkWriter) + { + throw new NotSupportedException($"Format {_inner.Info.Name} does not support symbolic link entries"); + } + + symlinkWriter.AddSymlink(entryName, target, metadata); + } + /// 完成归档(写中央目录/索引)。Dispose 未 Finish 时会自动调用。 public void Finish(CancellationToken cancellationToken = default) { @@ -163,18 +262,25 @@ public void Finish(CancellationToken cancellationToken = default) _finished = true; _progress.SwitchPhase(ArchivePhase.Finalizing); _inner.Finish(cancellationToken); + if (_ownsStream is global::GeneralZip.Internal.VolumeSplitStream split) + { + split.Complete(); + } _progress.Finalize(); } /// 异步完成归档。 - public Task FinishAsync(CancellationToken cancellationToken = default) + public async Task FinishAsync(CancellationToken cancellationToken = default) { - if (_finished) return Task.CompletedTask; + if (_finished) return; _finished = true; _progress.SwitchPhase(ArchivePhase.Finalizing); - var t = _inner.FinishAsync(cancellationToken); + await _inner.FinishAsync(cancellationToken).ConfigureAwait(false); + if (_ownsStream is global::GeneralZip.Internal.VolumeSplitStream split) + { + split.Complete(); + } _progress.Finalize(); - return t; } // ---------- 内部 ---------- @@ -191,6 +297,32 @@ private static FileStream OpenSourceFile(string filePath, string? entryName, out return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); } + /// Unix 平台读取源文件的权限位(AddFile 时随条目写入);Windows/失败返回 null。 + private static uint? ProbeUnixMode(string filePath) + { +#if NET8_0_OR_GREATER + if (!OperatingSystem.IsLinux() && !OperatingSystem.IsMacOS()) + { + return null; + } + + try + { + var mode = File.GetUnixFileMode(filePath); + var bits = (uint)mode & 0xFFFu; + // 文件类型位:目录/文件按源路径判断(AddFile 只走常规文件) + return 0x8000u | bits; // S_IFREG + } + catch (Exception) + { + return null; + } +#else + _ = filePath; + return null; +#endif + } + private async Task AddDirectoryCore(string directoryPath, string? entryPrefix, Predicate? filter, bool async, CancellationToken ct) { if (directoryPath == null) throw new ArgumentNullException(nameof(directoryPath)); @@ -226,9 +358,9 @@ private async Task AddDirectoryCore(string directoryPath, string? entryPrefix, P } } - private void AddEntryCore(string entryName, Stream content, long? size, DateTimeOffset? mtime, CancellationToken ct) + private void AddEntryCore(string entryName, Stream content, long? size, DateTimeOffset? mtime, CancellationToken ct, ArchiveEntryMetadata? metadata = null) { - var meta = new ArchiveEntryMetadata + var meta = metadata ?? new ArchiveEntryMetadata { Size = size ?? -1, LastWriteTime = mtime ?? _options.DefaultLastWriteTime ?? DateTimeOffset.Now, @@ -253,9 +385,9 @@ private void AddEntryCore(string entryName, Stream content, long? size, DateTime } } - private async Task AddEntryCoreAsync(string entryName, Stream content, long? size, DateTimeOffset? mtime, CancellationToken ct) + private async Task AddEntryCoreAsync(string entryName, Stream content, long? size, DateTimeOffset? mtime, CancellationToken ct, ArchiveEntryMetadata? metadata = null) { - var meta = new ArchiveEntryMetadata + var meta = metadata ?? new ArchiveEntryMetadata { Size = size ?? -1, LastWriteTime = mtime ?? _options.DefaultLastWriteTime ?? DateTimeOffset.Now, diff --git a/src/GeneralZip/AsyncExtensions.cs b/src/GeneralZip/AsyncExtensions.cs new file mode 100644 index 0000000..b598d19 --- /dev/null +++ b/src/GeneralZip/AsyncExtensions.cs @@ -0,0 +1,39 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GeneralZip.Abstractions; + +namespace GeneralZip; + +/// +/// 异步友好扩展(IAsyncEnumerable 条目枚举)。 +/// netstandard2.0 经 Microsoft.Bcl.AsyncInterfaces 提供 IAsyncEnumerable。 +/// +public static class GeneralZipAsyncExtensions +{ + /// 以异步流形式枚举归档条目(惰性;取消在条目间生效)。 + public static async IAsyncEnumerable EnumerateEntriesAsync( + this GeneralZipReader reader, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) + { + foreach (var entry in reader.Entries) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return entry; + await Task.Yield(); + } + } + + /// + /// 异步解压单个条目(同步 IO 经 Task.Run 保持异步语义;事件仍同步触发)。 + /// + public static Task ExtractEntryAsync( + this GeneralZipReader reader, + IArchiveEntry entry, + string destinationFilePath, + ExtractionOptions? options = null, + CancellationToken cancellationToken = default) + => Task.Run( + () => reader.ExtractEntry(entry, destinationFilePath, options, cancellationToken), + cancellationToken); +} diff --git a/src/GeneralZip/Cryptography/Pbkdf2KdfProviders.cs b/src/GeneralZip/Cryptography/Pbkdf2KdfProviders.cs new file mode 100644 index 0000000..629482c --- /dev/null +++ b/src/GeneralZip/Cryptography/Pbkdf2KdfProviders.cs @@ -0,0 +1,83 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using GeneralZip.Abstractions; + +namespace GeneralZip.Cryptography; + +/// +/// PBKDF2-HMAC-SM3(国密方案,RFC 8018 标准循环)。SM4-GM 容器规范 KdfId = 1(默认)。 +/// +public sealed class Pbkdf2Sm3KdfProvider : IKdfProvider +{ + public byte SpecId => 1; + + public string KdfId => "SM3-PBKDF2"; + + /// 规范默认迭代次数。 + public const int DefaultIterations = 10_000; + + public byte[] Derive(string password, byte[] salt, int iterations, int outputLength) + => Kdf.Pbkdf2Sm3(password, salt, iterations <= 0 ? DefaultIterations : iterations, outputLength); +} + +/// +/// PBKDF2-HMAC-SHA256(国际方案)。SM4-GM 容器规范 KdfId = 2。 +/// 迭代语义与 SHA1 版本一致;netstandard2.0 下用 IncrementalHash 手写 RFC 8018 循环。 +/// +public sealed class Pbkdf2Sha256KdfProvider : IKdfProvider +{ + public byte SpecId => 2; + + public string KdfId => "PBKDF2-SHA256"; + + /// 规范默认迭代次数。 + public const int DefaultIterations = 10_000; + + public byte[] Derive(string password, byte[] salt, int iterations, int outputLength) + => Pbkdf2HmacSha256(Encoding.UTF8.GetBytes(password), salt, iterations <= 0 ? DefaultIterations : iterations, outputLength); + + internal static byte[] Pbkdf2HmacSha256(byte[] password, byte[] salt, int iterations, int outputLength) + { + if (iterations < 1) throw new ArgumentOutOfRangeException(nameof(iterations)); + if (outputLength < 1) throw new ArgumentOutOfRangeException(nameof(outputLength)); + + var result = new byte[outputLength]; + var blocks = (outputLength + 31) / 32; + + for (uint blockIndex = 1; blockIndex <= blocks; blockIndex++) + { + var saltBlock = new byte[salt.Length + 4]; + Buffer.BlockCopy(salt, 0, saltBlock, 0, salt.Length); + saltBlock[salt.Length] = (byte)(blockIndex >> 24); + saltBlock[salt.Length + 1] = (byte)(blockIndex >> 16); + saltBlock[salt.Length + 2] = (byte)(blockIndex >> 8); + saltBlock[salt.Length + 3] = (byte)blockIndex; + + var u = ComputeHmacSha256(password, saltBlock); + var t = new byte[32]; + Buffer.BlockCopy(u, 0, t, 0, 32); + + for (var iter = 1; iter < iterations; iter++) + { + u = ComputeHmacSha256(password, u); + for (var i = 0; i < 32; i++) + { + t[i] ^= u[i]; + } + } + + var offset = (int)((blockIndex - 1) * 32); + var take = Math.Min(32, outputLength - offset); + Buffer.BlockCopy(t, 0, result, offset, take); + } + + return result; + } + + private static byte[] ComputeHmacSha256(byte[] key, byte[] data) + { + using var hmac = new HMACSHA256(key); + return hmac.ComputeHash(data); + } +} diff --git a/src/GeneralZip/Cryptography/Sm2.cs b/src/GeneralZip/Cryptography/Sm2.cs new file mode 100644 index 0000000..eae1a33 --- /dev/null +++ b/src/GeneralZip/Cryptography/Sm2.cs @@ -0,0 +1,535 @@ +using System; +using System.Numerics; +using GeneralZip.Native; + +namespace GeneralZip.Cryptography; + +/// SM2 椭圆曲线点(仿射坐标)。无穷远点以 IsInfinity 表示。 +public struct Sm2Point +{ + public BigInteger X; + public BigInteger Y; + public bool IsInfinity; + + public static Sm2Point Infinity => new() { IsInfinity = true }; +} + +/// +/// SM2 椭圆曲线公钥密码(GB/T 32918 / GM/T 0003,256 位推荐曲线)。 +/// 纯 C# 实现(BigInteger 仿射坐标),零第三方依赖。 +/// 加密采用标准 ECIES 语义(KDF-SM3 掩码 + SM3 完整性),密文排列 C1‖C3‖C2(现行标准)。 +/// +public static class Sm2 +{ + // ---------- 推荐曲线参数(GB/T 32918.5-2017) ---------- + + private static readonly BigInteger P = FromHex( + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF"); + private static readonly BigInteger A = FromHex( + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC"); // p - 3 + private static readonly BigInteger B = FromHex( + "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93"); + private static readonly BigInteger N = FromHex( + "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123"); + private static readonly Sm2Point G = new() + { + X = FromHex("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7"), + Y = FromHex("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"), + }; + + /// 基点 G 的阶 n。 + public static BigInteger Order => N; + + /// 曲线点校验:y² ≡ x³ + ax + b (mod p)。 + public static bool IsOnCurve(BigInteger x, BigInteger y) + { + if (x < 0 || x >= P || y < 0 || y >= P) + { + return false; + } + + var left = y * y % P; + var right = (x * x % P * x + A * x + B) % P; + return ((left - right) % P + P) % P == 0; + } + + // ---------- 点运算 ---------- + + public static Sm2Point Negate(Sm2Point p) => p.IsInfinity + ? p + : new Sm2Point { X = p.X, Y = (P - p.Y) % P }; + + public static Sm2Point Add(Sm2Point p, Sm2Point q) + { + if (p.IsInfinity) return q; + if (q.IsInfinity) return p; + if (p.X == q.X) + { + if ((p.Y + q.Y) % P == 0) + { + return Sm2Point.Infinity; + } + + return Double(p); + } + + var lambda = (q.Y - p.Y) % P * ModInverse((q.X - p.X) % P) % P; + lambda = ((lambda % P) + P) % P; + var x3 = (lambda * lambda - p.X - q.X) % P; + x3 = ((x3 % P) + P) % P; + var y3 = (lambda * (p.X - x3) - p.Y) % P; + y3 = ((y3 % P) + P) % P; + return new Sm2Point { X = x3, Y = y3 }; + } + + public static Sm2Point Double(Sm2Point p) + { + if (p.IsInfinity || p.Y == 0) + { + return Sm2Point.Infinity; + } + + // λ = (3x² + a) / (2y) + var numerator = (3 * p.X % P * p.X + A) % P; + numerator = ((numerator % P) + P) % P; + var denominator = 2 * p.Y % P; + var lambda = numerator * ModInverse(denominator) % P; + lambda = ((lambda % P) + P) % P; + var x3 = (lambda * lambda - 2 * p.X) % P; + x3 = ((x3 % P) + P) % P; + var y3 = (lambda * (p.X - x3) - p.Y) % P; + y3 = ((y3 % P) + P) % P; + return new Sm2Point { X = x3, Y = y3 }; + } + + /// 标量乘法 [k]P(double-and-add,从高位向低位)。 + public static Sm2Point Multiply(BigInteger k, Sm2Point p) + { + if (p.IsInfinity || k == 0) + { + return Sm2Point.Infinity; + } + + k %= N; + if (k < 0) + { + k += N; + } + + var result = Sm2Point.Infinity; + var addend = p; + while (k > 0) + { + if ((k & 1) == 1) + { + result = Add(result, addend); + } + + addend = Double(addend); + k >>= 1; + } + + return result; + } + + /// 公钥 = [d]G。 + public static Sm2Point PublicKeyOf(BigInteger privateKey) => Multiply(privateKey, G); + + // ---------- ECIES(GB/T 32918.4,C1‖C3‖C2) ---------- + + /// + /// SM2 公钥加密。k 可注入(0 = 随机;非 0 用于确定性地测试/标准向量)。 + /// 输出:C1(65B 未压缩) ‖ C3(32B SM3) ‖ C2(klen)。 + /// + public static byte[] Encrypt(byte[] plaintext, Sm2Point publicKey, BigInteger k = default) + { + if (plaintext.Length == 0) + { + throw new ArgumentException("Plaintext must not be empty", nameof(plaintext)); + } + + if (!IsOnCurve(publicKey.X, publicKey.Y)) + { + throw new ArgumentException("Public key is not on the SM2 curve", nameof(publicKey)); + } + + // 随机 k ∈ [1, n-1](确定性测试场景由调用方注入) + if (k.IsZero) + { + k = RandomScalar(); + } + + var c1 = Multiply(k, G); + if (c1.IsInfinity) + { + throw new InvalidOperationException("SM2 encryption: [k]G is the point at infinity; retry"); + } + + var shared = Multiply(k, publicKey); + if (shared.IsInfinity) + { + throw new InvalidOperationException("SM2 encryption: [k]PB is the point at infinity; retry"); + } + + var x2 = To32Bytes(shared.X); + var y2 = To32Bytes(shared.Y); + + var t = KdfSm3(x2, y2, plaintext.Length); + var c2 = new byte[plaintext.Length]; + for (var i = 0; i < plaintext.Length; i++) + { + c2[i] = (byte)(plaintext[i] ^ t[i]); + } + + var c3 = Sm3Digest.Hash(Concat3(x2, plaintext, y2)); + + var output = new byte[65 + 32 + c2.Length]; + output[0] = 0x04; + Write32(c1.X, output, 1); + Write32(c1.Y, output, 33); + Buffer.BlockCopy(c3, 0, output, 65, 32); + Buffer.BlockCopy(c2, 0, output, 97, c2.Length); + return output; + } + + /// + /// SM2 私钥解密。cipher = C1(65B) ‖ C3(32B) ‖ C2(klen)。 + /// + /// 密文结构非法。 + /// 完整性校验失败(C3 不符,通常为密钥错误或密文被篡改)。 + public static byte[] Decrypt(byte[] cipher, BigInteger privateKey) + { + if (cipher == null) throw new ArgumentNullException(nameof(cipher)); + if (privateKey <= 0 || privateKey >= Order - 1) + { + throw new ArgumentException("SM2 private key must be in [1, n-2]", nameof(privateKey)); + } + + if (cipher.Length < 65 + 32 + 1) + { + throw new ArgumentException("SM2 ciphertext is too short", nameof(cipher)); + } + + if (cipher[0] != 0x04) + { + throw new ArgumentException("SM2 ciphertext C1 must be an uncompressed point (0x04 prefix)", nameof(cipher)); + } + + var x1 = Read32(cipher, 1); + var y1 = Read32(cipher, 33); + if (!IsOnCurve(x1, y1)) + { + throw new ArgumentException("SM2 ciphertext C1 is not on the SM2 curve", nameof(cipher)); + } + + if (!NativeCoreLoader.TryLoad()) + { + throw new NativeCoreMissingException( + "SM2 decryption requires the constant-time native core; deploy generalzip_native for this runtime."); + } + + var privateBytes = To32BytesPrivate(privateKey); + var plaintext = new byte[cipher.Length - 97]; + try + { + var status = GzpNative.gzp_sm2_decrypt( + privateBytes, (uint)privateBytes.Length, + cipher, (uint)cipher.Length, + plaintext, (uint)plaintext.Length, out var outputLength); + if (status == GzpNative.GzpErrFormat) + { + throw new InvalidOperationException("SM2 decryption failed: C3 integrity mismatch (wrong key or corrupted ciphertext)"); + } + + if (status == GzpNative.GzpErrArg) + { + throw new ArgumentException("Invalid SM2 private key or ciphertext"); + } + + if (status != GzpNative.GzpOk || outputLength != plaintext.Length) + { + throw new ArchiveCorruptedException("Native SM2 decryption failed"); + } + + return plaintext; + } + finally + { + Kdf.Zero(privateBytes); + } + } + + /// SM2 X9.63 风格 KDF:Ha_i = SM3(Z ‖ ct_i),ct 为 32 位大端计数(从 1 起)。 + public static byte[] KdfSm3(byte[] z1, byte[] z2, int outputLength) + { + var output = new byte[outputLength]; + var hashLen = 32; + var blocks = (outputLength + hashLen - 1) / hashLen; + var pos = 0; + var remaining = outputLength; + for (uint ct = 1; ct <= blocks; ct++) + { + var input = new byte[z1.Length + z2.Length + 4]; + Buffer.BlockCopy(z1, 0, input, 0, z1.Length); + Buffer.BlockCopy(z2, 0, input, z1.Length, z2.Length); + var tail = input.Length - 4; + input[tail] = (byte)(ct >> 24); + input[tail + 1] = (byte)(ct >> 16); + input[tail + 2] = (byte)(ct >> 8); + input[tail + 3] = (byte)ct; + + var hash = Sm3Digest.Hash(input); + var take = Math.Min(hashLen, remaining); + Buffer.BlockCopy(hash, 0, output, pos, take); + pos += take; + remaining -= take; + } + + return output; + } + + // ---------- 密钥 ---------- + + /// 生成随机私钥 d ∈ [1, n-2]。 + public static BigInteger RandomScalar() + { + while (true) + { + var bytes = Kdf.RandomBytes(32); + var d = FromUnsigned(bytes); + if (d > 0 && d < N - 1) + { + return d; + } + } + } + + /// 公钥编码为 65 字节未压缩形式(0x04‖X‖Y)。 + public static byte[] EncodePoint(Sm2Point point) + { + if (point.IsInfinity) + { + throw new ArgumentException("Cannot encode the point at infinity"); + } + + var encoded = new byte[65]; + encoded[0] = 0x04; + Write32(point.X, encoded, 1); + Write32(point.Y, encoded, 33); + return encoded; + } + + /// 解析 65 字节未压缩公钥(0x04 前缀),校验在曲线上。 + public static Sm2Point DecodePoint(byte[] encoded) + { + if (encoded == null || encoded.Length != 65 || encoded[0] != 0x04) + { + throw new ArgumentException("SM2 public key must be 65 bytes with 0x04 prefix", nameof(encoded)); + } + + var x = Read32(encoded, 1); + var y = Read32(encoded, 33); + if (!IsOnCurve(x, y)) + { + throw new ArgumentException("SM2 public key point is not on the curve", nameof(encoded)); + } + + return new Sm2Point { X = x, Y = y }; + } + + // ---------- 内部 ---------- + + private static BigInteger ModInverse(BigInteger value) + { + // p 为素数:逆元 = x^(p-2) mod p + var x = ((value % P) + P) % P; + if (x.IsZero) + { + throw new DivideByZeroException("SM2 modular inverse of zero"); + } + + return BigInteger.ModPow(x, P - 2, P); + } + + internal static BigInteger FromHex(string hex) => BigInteger.Parse("0" + hex, System.Globalization.NumberStyles.HexNumber); + + /// 32 字节大端无符号 → BigInteger(非负)。 + internal static BigInteger FromUnsigned(byte[] bigEndian32) + { + var little = new byte[bigEndian32.Length + 1]; // 末尾 0 保证非负 + for (var i = 0; i < bigEndian32.Length; i++) + { + little[i] = bigEndian32[bigEndian32.Length - 1 - i]; + } + + return new BigInteger(little); + } + + private static byte[] To32Bytes(BigInteger value) + { + var bytes = value.ToByteArray(); // little-endian,可能带符号位 + var result = new byte[32]; + var take = Math.Min(bytes.Length, 32); + Buffer.BlockCopy(bytes, 0, result, 0, take); + Array.Reverse(result); // 大端 + return result; + } + + /// BigInteger → 定长 32 字节大端(私钥/坐标序列化共用)。 + internal static byte[] To32BytesPrivate(BigInteger value) => To32Bytes(value); + + private static BigInteger Read32(byte[] buffer, int offset) => FromUnsigned( + new[] { buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], + buffer[offset + 4], buffer[offset + 5], buffer[offset + 6], buffer[offset + 7], + buffer[offset + 8], buffer[offset + 9], buffer[offset + 10], buffer[offset + 11], + buffer[offset + 12], buffer[offset + 13], buffer[offset + 14], buffer[offset + 15], + buffer[offset + 16], buffer[offset + 17], buffer[offset + 18], buffer[offset + 19], + buffer[offset + 20], buffer[offset + 21], buffer[offset + 22], buffer[offset + 23], + buffer[offset + 24], buffer[offset + 25], buffer[offset + 26], buffer[offset + 27], + buffer[offset + 28], buffer[offset + 29], buffer[offset + 30], buffer[offset + 31] }); + + private static void Write32(BigInteger value, byte[] buffer, int offset) + { + var be = To32Bytes(value); + Buffer.BlockCopy(be, 0, buffer, offset, 32); + } + + private static byte[] Concat3(byte[] a, byte[] b, byte[] c) + { + var result = new byte[a.Length + b.Length + c.Length]; + Buffer.BlockCopy(a, 0, result, 0, a.Length); + Buffer.BlockCopy(b, 0, result, a.Length, b.Length); + Buffer.BlockCopy(c, 0, result, a.Length + b.Length, c.Length); + return result; + } +} + +/// SM2 密钥对(公私钥;私钥为 BigInteger,公钥为 65 字节未压缩编码)。 +public sealed class Sm2KeyPair +{ + private Sm2KeyPair(BigInteger privateKey, byte[] publicKey) + { + PrivateKey = privateKey; + PublicKey = publicKey; + } + + /// 私钥标量 d。 + public BigInteger PrivateKey { get; } + + /// 公钥 65 字节未压缩编码(0x04‖X‖Y)。 + public byte[] PublicKey { get; } + + /// 生成随机密钥对。 + public static Sm2KeyPair Generate() + { + var d = Sm2.RandomScalar(); + return new Sm2KeyPair(d, Sm2.EncodePoint(Sm2.PublicKeyOf(d))); + } + + /// 从私钥恢复密钥对(私钥可为 32 字节大端 hex)。 + public static Sm2KeyPair FromPrivateKeyHex(string hex) + { + var d = Sm2.FromHex(hex.Trim()); + if (d <= 0 || d >= Sm2.Order - 1) + { + throw new ArgumentException("SM2 private key must be in [1, n-2]", nameof(hex)); + } + + return new Sm2KeyPair(d, Sm2.EncodePoint(Sm2.PublicKeyOf(d))); + } + + /// 私钥 hex(32 字节大端)。 + public string PrivateKeyHex => ToHex(Sm2.To32BytesPrivate(PrivateKey)); + + /// 公钥 hex(65 字节,含 04 前缀)。 + public string PublicKeyHex => ToHex(PublicKey); + + /// + /// 解析公钥 hex:"04‖X‖Y"(130 字符)或 "X‖Y"(128 字符,自动补 04 前缀)。 + /// 非法格式返回 null(供写路径参数校验使用)。 + /// + public static byte[]? ParsePublicKeyHex(string hex) + { + if (string.IsNullOrWhiteSpace(hex)) + { + return null; + } + + var clean = hex.Trim(); + if (clean.Length % 2 != 0 || !IsHex(clean)) + { + return null; + } + + byte[] bytes; + try + { +#if NETSTANDARD2_0 + bytes = new byte[clean.Length / 2]; + for (var i = 0; i < bytes.Length; i++) + { + bytes[i] = byte.Parse(clean.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); + } +#else + bytes = Convert.FromHexString(clean); +#endif + } + catch (FormatException) + { + return null; + } + + if (bytes.Length == 64) + { + var full = new byte[65]; + full[0] = 0x04; + Buffer.BlockCopy(bytes, 0, full, 1, 64); + bytes = full; + } + + if (bytes.Length != 65 || bytes[0] != 0x04) + { + return null; + } + + try + { + Sm2.DecodePoint(bytes); + } + catch (ArgumentException) + { + return null; + } + + return bytes; + } + + private static bool IsHex(string s) + { + foreach (var c in s) + { + var ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + if (!ok) + { + return false; + } + } + + return true; + } + + private static string ToHex(byte[] bytes) + { +#if NETSTANDARD2_0 + var sb = new System.Text.StringBuilder(bytes.Length * 2); + foreach (var b in bytes) + { + sb.Append(b.ToString("x2")); + } + + return sb.ToString(); +#else + return Convert.ToHexString(bytes).ToLowerInvariant(); +#endif + } +} diff --git a/src/GeneralZip/Cryptography/Sm2GmProvider.cs b/src/GeneralZip/Cryptography/Sm2GmProvider.cs new file mode 100644 index 0000000..3c80ebd --- /dev/null +++ b/src/GeneralZip/Cryptography/Sm2GmProvider.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using GeneralZip.Abstractions; + +namespace GeneralZip.Cryptography; + +/// +/// 国密 SM2 信封混合加密(GeneralZip 自定义 ZIP 扩展,规范见 docs/CRYPTO-SPEC.md §7)。 +/// extra field 0x4D54:"GMSN" 容器:每条目随机数据密钥(SM4-CTR + SM3-HMAC,EtM), +/// 数据密钥整体经 SM2 公钥加密(ECIES,C1‖C3‖C2)装入信封。写侧只需接收方公钥(无需口令), +/// 读侧以 SM2 私钥(hex)作为"口令"经既有口令协商管线提供。 +/// +public sealed class Sm2GmProvider : IEncryptionProvider, IPasswordlessWriteProvider +{ + public const ushort ExtraFieldId = 0x4D54; + + private const byte SpecVersion = 1; + private const byte CipherModeCtr = 1; + private const byte KdfIdEnvelope = 0; // 信封模式:数据密钥不由口令派生 + + private const int KeyLength = 16; // SM4 数据密钥 + private const int MacKeyLength = 32; // SM3-HMAC 密钥 + private const int IvLength = 16; // SM4-CTR IV + private const int MacLength = 32; // SM3 输出 + private const int EnvelopePlainLength = KeyLength + MacKeyLength + IvLength; + private const int EnvelopeLength = 65 + 32 + EnvelopePlainLength; // C1‖C3‖C2 + + public string AlgorithmId => "SM2-GM"; + + public bool SupportsWrite => true; + + public bool SupportsRead => true; + + public IReadOnlyCollection ZipExtraFieldIds { get; } = new ushort[] { ExtraFieldId }; + + public EntryEncryptionPlan PrepareWrite(EncryptionWriteContext context) + { + if (context.RecipientPublicKey == null || context.RecipientPublicKey.Length == 0) + { + throw new ArgumentException( + "Algorithm SM2-GM requires the recipient's SM2 public key (options.RecipientPublicKey)", + nameof(context)); + } + + var publicKey = Sm2.DecodePoint(context.RecipientPublicKey); + + // 随机数据密钥:K_enc ‖ K_mac ‖ IV + var keyEnc = Kdf.RandomBytes(KeyLength); + var keyMac = Kdf.RandomBytes(MacKeyLength); + var iv = Kdf.RandomBytes(IvLength); + var keyBlob = new byte[EnvelopePlainLength]; + Buffer.BlockCopy(keyEnc, 0, keyBlob, 0, KeyLength); + Buffer.BlockCopy(keyMac, 0, keyBlob, KeyLength, MacKeyLength); + Buffer.BlockCopy(iv, 0, keyBlob, KeyLength + MacKeyLength, IvLength); + + byte[] envelope; + try + { + envelope = Sm2.Encrypt(keyBlob, publicKey); + } + finally + { + Kdf.Zero(keyBlob); + } + + // extra field 数据区(HMAC 的 AAD),布局见 CRYPTO-SPEC.md §7 + var aad = BuildExtraFieldData(envelope, context.RealCompressionMethod); + + return new EntryEncryptionPlan( + ExtraFieldId, + aad, + MacLength, + sink => + { + var cipher = new CtrCipher(new Sm4BlockCipher(keyEnc), keyEnc, iv); + var mac = Kdf.CreateIncrementalHmacSm3(keyMac); + return new CtrWriteStream(sink, cipher, mac, MacLength, new[] { aad }); + }); + } + + public Stream OpenRead(Stream cipherSource, EncryptionReadContext context) + { + if (!context.Parameters.TryGetValue("ZipExtraFieldData", out var raw) || raw is not byte[] extra) + { + throw new ArchiveCorruptedException("SM2-GM extra field is missing", context.EntryName); + } + + var parsed = ParseExtraField(extra, context.EntryName); + if (context.CipherDataSize >= 0 && context.CipherDataSize < MacLength) + { + throw new ArchiveCorruptedException("SM2-GM ciphertext data is too short", context.EntryName); + } + + // "口令" = SM2 私钥 hex + if (string.IsNullOrEmpty(context.Password)) + { + throw new InvalidPasswordException(context.EntryName); + } + + BigInteger privateKey; + try + { + privateKey = ParsePrivateKey(context.Password!); + } + catch (ArgumentException) + { + // 口令不是合法私钥 hex → 口令错误 + throw new InvalidPasswordException(context.EntryName); + } + catch (FormatException) + { + throw new InvalidPasswordException(context.EntryName); + } + + // 解封数据密钥:SM2 ECIES 的 C3 校验在解密内完成,错误私钥/篡改在此快速失败 + byte[] keyBlob; + try + { + keyBlob = Sm2.Decrypt(parsed.Envelope, privateKey); + } + catch (InvalidOperationException) + { + throw new InvalidPasswordException(context.EntryName); + } + catch (ArgumentException ex) + { + throw new ArchiveCorruptedException($"Invalid SM2-GM envelope: {ex.Message}", context.EntryName); + } + + var keyEnc = new byte[KeyLength]; + var keyMac = new byte[MacKeyLength]; + var iv = new byte[IvLength]; + Buffer.BlockCopy(keyBlob, 0, keyEnc, 0, KeyLength); + Buffer.BlockCopy(keyBlob, KeyLength, keyMac, 0, MacKeyLength); + Buffer.BlockCopy(keyBlob, KeyLength + MacKeyLength, iv, 0, IvLength); + Kdf.Zero(keyBlob); + + var payloadLength = context.CipherDataSize - MacLength; + var cipher = new CtrCipher(new Sm4BlockCipher(keyEnc), keyEnc, iv); + var mac = Kdf.CreateIncrementalHmacSm3(keyMac); + return new CtrReadStream(cipherSource, cipher, mac, payloadLength, new[] { extra }); + } + + // ---------- 构建与解析 ---------- + + private static byte[] BuildExtraFieldData(byte[] envelope, ushort realMethod) + { + // Magic(4) Ver(1) Mode(1) Kdf(1) EnvLen(4) Envelope(EnvLen) RealMethod(2) + var data = new byte[4 + 1 + 1 + 1 + 4 + envelope.Length + 2]; + var pos = 0; + + data[pos++] = (byte)'G'; + data[pos++] = (byte)'M'; + data[pos++] = (byte)'S'; + data[pos++] = (byte)'N'; + data[pos++] = SpecVersion; + data[pos++] = CipherModeCtr; + data[pos++] = KdfIdEnvelope; + data[pos++] = (byte)(envelope.Length & 0xFF); + data[pos++] = (byte)((envelope.Length >> 8) & 0xFF); + data[pos++] = (byte)((envelope.Length >> 16) & 0xFF); + data[pos++] = (byte)((envelope.Length >> 24) & 0xFF); + Buffer.BlockCopy(envelope, 0, data, pos, envelope.Length); + pos += envelope.Length; + data[pos++] = (byte)(realMethod & 0xFF); + data[pos++] = (byte)((realMethod >> 8) & 0xFF); + return data; + } + + private readonly struct ParsedExtra + { + public ParsedExtra(byte[] envelope, ushort realMethod) + { + Envelope = envelope; + RealMethod = realMethod; + } + + public byte[] Envelope { get; } + public ushort RealMethod { get; } + } + + private static ParsedExtra ParseExtraField(byte[] data, string entryName) + { + const int minLength = 4 + 1 + 1 + 1 + 4 + 2; + if (data.Length < minLength + || data[0] != (byte)'G' || data[1] != (byte)'M' || data[2] != (byte)'S' || data[3] != (byte)'N') + { + throw new ArchiveCorruptedException("Invalid SM2-GM extra field (magic/length)", entryName); + } + + var version = data[4]; + if (version != SpecVersion) + { + throw new UnsupportedFormatException($"Unsupported SM2-GM spec version {version} (supported: {SpecVersion})", entryName); + } + + var mode = data[5]; + if (mode != CipherModeCtr) + { + throw new UnsupportedFormatException($"Unsupported SM2-GM cipher mode {mode}", entryName); + } + + var pos = 7; + var envelopeLength = data[pos] | (data[pos + 1] << 8) | (data[pos + 2] << 16) | (data[pos + 3] << 24); + pos += 4; + + if (envelopeLength != EnvelopeLength || pos + envelopeLength + 2 > data.Length) + { + throw new ArchiveCorruptedException($"Invalid SM2-GM envelope length {envelopeLength}", entryName); + } + + var envelope = new byte[envelopeLength]; + Buffer.BlockCopy(data, pos, envelope, 0, envelopeLength); + pos += envelopeLength; + + var realMethod = (ushort)(data[pos] | (data[pos + 1] << 8)); + return new ParsedExtra(envelope, realMethod); + } + + private static BigInteger ParsePrivateKey(string hex) + { + var clean = hex.Trim(); + var d = Sm2.FromHex(clean); + if (d <= 0 || d >= Sm2.Order - 1) + { + throw new ArgumentException("private key out of range"); + } + + return d; + } +} diff --git a/src/GeneralZip/Cryptography/Sm4GmProvider.cs b/src/GeneralZip/Cryptography/Sm4GmProvider.cs index 7ca51b6..213f8c0 100644 --- a/src/GeneralZip/Cryptography/Sm4GmProvider.cs +++ b/src/GeneralZip/Cryptography/Sm4GmProvider.cs @@ -42,8 +42,11 @@ public EntryEncryptionPlan PrepareWrite(EncryptionWriteContext context) var salt = Kdf.RandomBytes(SaltLength); var iv = Kdf.RandomBytes(IvLength); + // KDF:context.Kdf(options.KdfAlgorithmId 解析结果)优先,缺省 SM3-PBKDF2 + var kdf = context.Kdf ?? new Pbkdf2Sm3KdfProvider(); + // 先派生密钥:校验值(K_ver)必须进入 extra field,而 extra field 又是 HMAC 的 AAD - var keyMaterial = Kdf.Pbkdf2Sm3(context.Password, salt, iterations, KeyLength + MacKeyLength + VerifierLength); + var keyMaterial = kdf.Derive(context.Password!, salt, iterations, KeyLength + MacKeyLength + VerifierLength); var keyEnc = new byte[KeyLength]; var keyMac = new byte[MacKeyLength]; var verifier = new byte[VerifierLength]; @@ -53,7 +56,7 @@ public EntryEncryptionPlan PrepareWrite(EncryptionWriteContext context) Kdf.Zero(keyMaterial); // extra field 数据区(HMAC 的 AAD),布局见 CRYPTO-SPEC.md §5 - var aad = BuildExtraFieldData(iterations, salt, iv, verifier, context.RealCompressionMethod); + var aad = BuildExtraFieldData(iterations, salt, iv, verifier, context.RealCompressionMethod, kdf.SpecId); return new EntryEncryptionPlan( ExtraFieldId, @@ -82,8 +85,12 @@ public Stream OpenRead(Stream cipherSource, EncryptionReadContext context) var payloadLength = context.CipherDataSize - MacLength; + // 按 extra field 中的 KdfId 解析 KDF 提供者(默认注册表内置 SM3-PBKDF2 / PBKDF2-SHA256) + var kdf = GeneralZipEncryptionRegistry.Default.Kdfs.Find(parsed.KdfId) + ?? throw new UnsupportedFormatException($"Unsupported SM4-GM KDF id {parsed.KdfId}", context.EntryName); + // 口令快速失败:先派生 K_ver 与存储校验值比较 - var keyMaterial = Kdf.Pbkdf2Sm3(context.Password, parsed.Salt, parsed.Iterations, KeyLength + MacKeyLength + VerifierLength); + var keyMaterial = kdf.Derive(context.Password!, parsed.Salt, parsed.Iterations, KeyLength + MacKeyLength + VerifierLength); var keyEnc = new byte[KeyLength]; var keyMac = new byte[MacKeyLength]; var verifier = new byte[VerifierLength]; @@ -107,7 +114,7 @@ public Stream OpenRead(Stream cipherSource, EncryptionReadContext context) /// /// 构建 extra field 数据区。 /// - private static byte[] BuildExtraFieldData(int iterations, byte[] salt, byte[] iv, byte[] verifier, ushort realMethod) + private static byte[] BuildExtraFieldData(int iterations, byte[] salt, byte[] iv, byte[] verifier, ushort realMethod, byte kdfSpecId) { // Magic(4) Ver(1) Mode(1) Kdf(1) Iter(4) SaltLen(1) Salt IvLen(1) IV VerifierLen(1)→4 直接内嵌 Verifier(4) RealMethod(2) var data = new byte[4 + 1 + 1 + 1 + 4 + 1 + SaltLength + 1 + IvLength + 4 + 2]; @@ -119,7 +126,7 @@ private static byte[] BuildExtraFieldData(int iterations, byte[] salt, byte[] iv data[pos++] = (byte)'M'; data[pos++] = SpecVersion; data[pos++] = CipherModeCtr; - data[pos++] = KdfIdPbkdf2Sm3; + data[pos++] = kdfSpecId; PutLe32(data, ref pos, iterations); data[pos++] = SaltLength; Buffer.BlockCopy(salt, 0, data, pos, SaltLength); @@ -160,10 +167,6 @@ private static ParsedExtra ParseExtraField(byte[] data, string entryName) } var kdfId = data[6]; - if (kdfId != KdfIdPbkdf2Sm3) - { - throw new UnsupportedFormatException($"Unsupported SM4-GM KDF id {kdfId}", entryName); - } var pos = 7; var iterations = GetLe32(data, ref pos); @@ -192,7 +195,7 @@ private static ParsedExtra ParseExtraField(byte[] data, string entryName) pos += VerifierLength; var realMethod = (ushort)(data[pos] | (data[pos + 1] << 8)); - return new ParsedExtra(iterations, salt, iv, verifier, realMethod); + return new ParsedExtra(kdfId, iterations, salt, iv, verifier, realMethod); } private static void PutLe32(byte[] buffer, ref int pos, int value) @@ -212,8 +215,9 @@ private static int GetLe32(byte[] buffer, ref int pos) private readonly struct ParsedExtra { - public ParsedExtra(int iterations, byte[] salt, byte[] iv, byte[] verifier, ushort realMethod) + public ParsedExtra(byte kdfId, int iterations, byte[] salt, byte[] iv, byte[] verifier, ushort realMethod) { + KdfId = kdfId; Iterations = iterations; Salt = salt; Iv = iv; @@ -221,6 +225,7 @@ public ParsedExtra(int iterations, byte[] salt, byte[] iv, byte[] verifier, usho RealMethod = realMethod; } + public byte KdfId { get; } public int Iterations { get; } public byte[] Salt { get; } public byte[] Iv { get; } diff --git a/src/GeneralZip/EncryptionRegistry.cs b/src/GeneralZip/EncryptionRegistry.cs index d7257d8..e1b0217 100644 --- a/src/GeneralZip/EncryptionRegistry.cs +++ b/src/GeneralZip/EncryptionRegistry.cs @@ -1,9 +1,71 @@ using System; using System.Collections.Generic; +using System.Linq; using GeneralZip.Abstractions; namespace GeneralZip; +/// +/// KDF 提供者注册表。SM4-GM 容器按 1 字节 SpecId 选择 KDF(1=SM3-PBKDF2,2=PBKDF2-SHA256)。 +/// 线程安全。 +/// +public sealed class GeneralZipKdfRegistry +{ + private readonly object _lock = new(); + private readonly Dictionary _bySpecId = new(); + private readonly Dictionary _byName = new(StringComparer.OrdinalIgnoreCase); + + /// 注册 KDF(同 SpecId/同名重复注册将覆盖)。 + public void Register(IKdfProvider provider) + { + if (provider == null) throw new ArgumentNullException(nameof(provider)); + + lock (_lock) + { + if (_bySpecId.TryGetValue(provider.SpecId, out var bySpecId) + && !string.Equals(bySpecId.KdfId, provider.KdfId, StringComparison.OrdinalIgnoreCase)) + { + _byName.Remove(bySpecId.KdfId); + } + + if (_byName.TryGetValue(provider.KdfId, out var byName) + && byName.SpecId != provider.SpecId) + { + _bySpecId.Remove(byName.SpecId); + } + + _bySpecId[provider.SpecId] = provider; + _byName[provider.KdfId] = provider; + } + } + + /// 按容器规范 SpecId 查找。 + public IKdfProvider? Find(byte specId) + { + lock (_lock) + { + return _bySpecId.TryGetValue(specId, out var p) ? p : null; + } + } + + /// 按标识名查找(大小写不敏感)。 + public IKdfProvider? FindByName(string kdfId) + { + lock (_lock) + { + return _byName.TryGetValue(kdfId, out var p) ? p : null; + } + } + + public IReadOnlyList Snapshot() + { + lock (_lock) + { + return new List(_byName.Values); + } + } +} + /// /// 加密算法注册表。内置提供者预注册;第三方算法经 注入后即可被所有格式使用。 /// 线程安全。 @@ -14,21 +76,32 @@ public sealed class GeneralZipEncryptionRegistry private readonly Dictionary _byId = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary> _byZipExtraField = new(); - public GeneralZipEncryptionRegistry() { } + public GeneralZipEncryptionRegistry() + { + Kdfs = new GeneralZipKdfRegistry(); + } internal GeneralZipEncryptionRegistry(bool populateBuiltins) { + Kdfs = new GeneralZipKdfRegistry(); if (populateBuiltins) { Register(new Cryptography.ZipCryptoProvider()); Register(new Cryptography.WinZipAesProvider(Cryptography.AesKeyStrength.Bits128)); Register(new Cryptography.WinZipAesProvider(Cryptography.AesKeyStrength.Bits256)); Register(new Cryptography.Sm4GmProvider()); + Register(new Cryptography.Sm2GmProvider()); + + Kdfs.Register(new Cryptography.Pbkdf2Sm3KdfProvider()); + Kdfs.Register(new Cryptography.Pbkdf2Sha256KdfProvider()); } } public static GeneralZipEncryptionRegistry Default { get; } = new(populateBuiltins: true); + /// KDF 提供者注册表(SM4-GM 容器按 SpecId 选择派生函数)。 + public GeneralZipKdfRegistry Kdfs { get; } + /// 注册提供者;同 AlgorithmId 重复注册将覆盖。 public void Register(IEncryptionProvider provider) { @@ -36,6 +109,16 @@ public void Register(IEncryptionProvider provider) lock (_lock) { + foreach (var id in _byZipExtraField.Keys.ToArray()) + { + var list = _byZipExtraField[id]; + list.RemoveAll(p => string.Equals(p.AlgorithmId, provider.AlgorithmId, StringComparison.OrdinalIgnoreCase)); + if (list.Count == 0) + { + _byZipExtraField.Remove(id); + } + } + _byId[provider.AlgorithmId] = provider; foreach (var id in provider.ZipExtraFieldIds) { diff --git a/src/GeneralZip/Formats/Cab/CabFormat.cs b/src/GeneralZip/Formats/Cab/CabFormat.cs new file mode 100644 index 0000000..95542e3 --- /dev/null +++ b/src/GeneralZip/Formats/Cab/CabFormat.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using GeneralZip.Internal; + +namespace GeneralZip.Formats.Cab; + +/// +/// CAB(Microsoft Cabinet)读取,纯 C# 自研,只读。 +/// 支持存储方式 NONE(typeCompress=0);MSZIP/LZX/Quantum 需跨块共享 32K 历史窗口的 +/// 专有解码器,明确报不支持。写入不支持。 +/// +public sealed class CabFormat : IArchiveFormat +{ + public ArchiveFormatInfo Info { get; } = new( + "CAB", new[] { ".cab" }, + FormatCapabilities.Read | FormatCapabilities.SeekableRead, + "Microsoft Cabinet, read-only (NONE/stored folders; MSZIP/LZX unsupported)"); + + public bool MatchesSignature(Stream stream) + { + long restorePos = -1; + if (stream.CanSeek) restorePos = stream.Position; + + try + { + var buf = new byte[4]; + var total = 0; + while (total < buf.Length) + { + var n = stream.Read(buf, total, buf.Length - total); + if (n <= 0) return false; + total += n; + } + + return buf[0] == (byte)'M' && buf[1] == (byte)'S' && buf[2] == (byte)'C' && buf[3] == (byte)'F'; + } + finally + { + if (restorePos >= 0) stream.Position = restorePos; + } + } + + public bool MatchesExtension(string extension) + => extension.Equals(".cab", StringComparison.OrdinalIgnoreCase); + + public IArchiveReader OpenRead(Stream stream, ArchiveOpenOptions options) + { + if (!stream.CanSeek) + { + throw new NotSupportedException("CAB reading requires a seekable stream"); + } + + return new CabReader(stream, ownsStream: false); + } + + public IArchiveWriter OpenWrite(Stream stream, ArchiveWriteOptions options) + => throw new UnsupportedFormatException("CAB writing is not supported (read-only format)"); + + internal sealed class CabReader : IArchiveReader + { + private readonly Stream _stream; + private readonly bool _ownsStream; + private readonly List<(CabFolder folder, IArchiveEntry entry)> _entries = new(); + + private sealed class CabFolder + { + public long DataOffset; + public long DataLength; // 各块 payload 之和(虚拟长度) + public ushort CompressionType; + public List<(long payloadOffset, int payloadLen)> Blocks { get; } = new(); + } + + private sealed class CabFileData + { + public string Name = string.Empty; + public long Size; + public long OffsetInFolder; + public DateTimeOffset MTime; + public bool IsDirectory => (Attribs & 0x10) != 0; // A_NAME_IS_DIRECTORY + public ushort Attribs; + } + + public CabReader(Stream stream, bool ownsStream) + { + _stream = stream; + _ownsStream = ownsStream; + + using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true); + stream.Position = 0; + + // CFHEADER + if (reader.ReadBytes(4).Length < 4) + { + throw new ArchiveCorruptedException("CAB: truncated header"); + } + + stream.Position = 4; + _ = reader.ReadUInt32(); // reserved1 + _ = reader.ReadUInt32(); // cbCabinet + _ = reader.ReadUInt32(); // reserved2 + var coffFiles = reader.ReadUInt32(); + _ = reader.ReadUInt32(); // reserved3 + var verMinor = reader.ReadByte(); + var verMajor = reader.ReadByte(); + var cFolders = reader.ReadUInt16(); + var cFiles = reader.ReadUInt16(); + var flags = reader.ReadUInt16(); + _ = reader.ReadUInt16(); // setID + _ = reader.ReadUInt16(); // iCabinet + + if (verMajor < 1 || verMajor > 3) + { + throw new UnsupportedFormatException($"CAB: unsupported version {verMajor}.{verMinor}"); + } + + // flags bit2 = RESERVE:跳过保留区与多卷字符串 + if ((flags & 0x0004) != 0) + { + var headerReserve = reader.ReadUInt16(); + var folderReserve = reader.ReadUInt16(); + var dataReserve = reader.ReadUInt16(); + stream.Position += headerReserve; + if ((flags & 0x0001) != 0) // prev cabinet + { + while (reader.ReadByte() != 0) { } + while (reader.ReadByte() != 0) { } + } + + if ((flags & 0x0002) != 0) // next cabinet + { + while (reader.ReadByte() != 0) { } + while (reader.ReadByte() != 0) { } + } + } + + // CFFOLDER × cFolders + var folders = new CabFolder[cFolders]; + for (var i = 0; i < cFolders; i++) + { + var dataStart = reader.ReadUInt32(); + var cDataBlocks = reader.ReadUInt16(); + var typeCompress = reader.ReadUInt16(); + + if ((flags & 0x0004) != 0) + { + // folderReserve 在 header 解析期才知道:此处无字段(保留区仅存在于第一个 CFFOLDER 之前的布局约定中) + } + + folders[i] = new CabFolder + { + DataOffset = dataStart, + CompressionType = typeCompress, + // DataLength 在解析 CFDATA 块序列后填充(见下) + }; + folders[i].DataLength = SumFolderData(stream, dataStart, cDataBlocks, typeCompress, folders[i]); + } + + // CFFILE × cFiles(自 coffFiles 顺序排列) + stream.Position = coffFiles; + for (var i = 0; i < cFiles; i++) + { + var size = reader.ReadUInt32(); + var offsetInFolder = reader.ReadUInt32(); + var folderIndex = reader.ReadUInt16(); + var date = reader.ReadUInt16(); + var time = reader.ReadUInt16(); + var attribs = reader.ReadUInt16(); + + var nameBytes = new List(); + byte b; + while ((b = reader.ReadByte()) != 0) + { + nameBytes.Add(b); + } + + var name = Encoding.UTF8.GetString(nameBytes.ToArray()); + + if (folderIndex == 0xFFFD || folderIndex == 0xFFFE || folderIndex == 0xFFFF) + { + continue; // 跨卷 continued 文件:本卷不完整 + } + + if (folderIndex >= folders.Length) + { + throw new ArchiveCorruptedException($"CAB: folder index {folderIndex} out of range"); + } + + var folder = folders[folderIndex]; + if ((folder.CompressionType & 0x000F) != 0) + { + throw new UnsupportedFormatException( + $"CAB folder uses compression method {(folder.CompressionType & 0x000F)} (MSZIP/LZX/Quantum). " + + "GeneralZip supports NONE (stored) CAB folders only."); + } + + var data = new CabFileData + { + Name = name, + Size = size, + OffsetInFolder = offsetInFolder, + Attribs = attribs, + MTime = DecodeDosDateTime(date, time), + }; + _entries.Add((folder, new CabEntryView(data, Format))); + } + } + + /// + /// 顺序扫 CFDATA 块:记录每块 payload 的物理位置(块头 12 字节之后), + /// 返回虚拟总长。NONE:payload 即原始数据。 + /// + private long SumFolderData(Stream s, long dataStart, ushort cDataBlocks, ushort typeCompress, CabFolder folder) + { + var pos = s.Position; + long total = 0; + s.Position = dataStart; + for (var i = 0; i < cDataBlocks; i++) + { + s.Position += 4; // checksum + var cbData = ReadU16(s); + var cbUncomp = ReadU16(s); + var payloadOffset = s.Position; + folder.Blocks.Add((payloadOffset, cbUncomp)); + total += cbUncomp; + s.Position += cbData; + } + + s.Position = pos; + return total; + } + + private static ushort ReadU16(Stream s) + { + var lo = s.ReadByte(); + var hi = s.ReadByte(); + if (hi < 0) + { + throw new EndOfStreamException(); + } + + return (ushort)(lo | (hi << 8)); + } + + private static DateTimeOffset DecodeDosDateTime(ushort date, ushort time) + { + try + { + var year = 1980 + (date >> 9); + var month = (date >> 5) & 0xF; + var day = date & 0x1F; + var hour = time >> 11; + var minute = (time >> 5) & 0x3F; + var second = (time & 0x1F) * 2; + return new DateTimeOffset(year, month, day, hour, minute, second, TimeSpan.Zero); + } + catch (ArgumentOutOfRangeException) + { + return new DateTimeOffset(1980, 1, 1, 0, 0, 0, TimeSpan.Zero); + } + } + + public ArchiveFormatInfo Format { get; } = new( + "CAB", new[] { ".cab" }, + FormatCapabilities.Read | FormatCapabilities.SeekableRead, + "Microsoft Cabinet, read-only (NONE/stored folders; MSZIP/LZX unsupported)"); + + public IReadOnlyList Entries => _entries.ConvertAll(e => e.entry); + + public bool IsEncrypted => false; + + public Stream OpenEntryStream(IArchiveEntry entry) + { + foreach (var (folder, view) in _entries) + { + if (!ReferenceEquals(view, entry)) + { + continue; + } + + var data = ((CabEntryView)view).Data; + if (data.IsDirectory) + { + return Stream.Null; + } + + return new CabinetFolderStream(this, _stream, folder, data.OffsetInFolder, data.Size); + } + + throw new ArgumentException("Entry does not belong to this archive", nameof(entry)); + } + + public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationToken cancellationToken) + { + using var source = OpenEntryStream(entry); + var buffer = new byte[81920]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + destination.Write(buffer, 0, read); + } + } + + public void Dispose() + { + if (_ownsStream) _stream.Dispose(); + } + + /// + /// 文件夹数据流:把虚拟偏移(各块 payload 顺序拼接)翻译为物理偏移, + /// 跨块读取自动衔接。NONE 文件夹的 payload 即原始字节。 + /// + private sealed class CabinetFolderStream : Stream + { + private readonly Stream _base; + private readonly CabFolder _folder; + private readonly long _start; // 条目在虚拟空间中的起点 + private readonly long _length; + private long _position; + + public CabinetFolderStream(CabReader owner, Stream baseStream, CabFolder folder, long virtualStart, long length) + { + _base = baseStream; + _folder = folder; + _start = virtualStart; + _length = length; + _position = 0; + } + + private (long physOffset, int inBlock) Translate(long virtualOffset) + { + long acc = 0; + foreach (var (payloadOffset, payloadLen) in _folder.Blocks) + { + if (virtualOffset < acc + payloadLen) + { + return (payloadOffset + (virtualOffset - acc), (int)(virtualOffset - acc)); + } + + acc += payloadLen; + } + + throw new ArchiveCorruptedException("CAB: virtual offset beyond folder data"); + } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => _length; + public override long Position { get => _position; set => _position = value; } + + public override int Read(byte[] buffer, int offset, int count) + { + var total = 0; + while (total < count && _position < _length) + { + var (physOffset, inBlock) = Translate(_start + _position); + var (_, payloadLen) = _folder.Blocks.Find(b => b.payloadOffset == physOffset - inBlock); + var availableInBlock = payloadLen - inBlock; + var want = (int)Math.Min(count - total, Math.Min(availableInBlock, _length - _position)); + if (want <= 0) + { + break; + } + + _base.Position = physOffset; + var read = _base.Read(buffer, offset + total, want); + if (read <= 0) + { + break; + } + + _position += read; + total += read; + } + + return total; + } + + public override long Seek(long offset, SeekOrigin origin) + { + var target = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => _length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + _position = target; + return _position; + } + + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class CabEntryView : IArchiveEntry + { + public CabEntryView(CabFileData data, ArchiveFormatInfo format) + { + Data = data; + } + + public CabFileData Data { get; } + + public string FullName => Data.Name; + public string Name => Data.Name; + public long Size => Data.Size; + public long CompressedSize => Data.Size; + public DateTimeOffset? LastWriteTime => Data.MTime; + public bool IsDirectory => Data.IsDirectory; + public bool IsEncrypted => false; + public string? EncryptionAlgorithm => null; + public uint? Crc32 => null; + public string? Comment => null; + } + } +} diff --git a/src/GeneralZip/Formats/Codecs/BuiltinCodecs.cs b/src/GeneralZip/Formats/Codecs/BuiltinCodecs.cs index 95d4b59..326a469 100644 --- a/src/GeneralZip/Formats/Codecs/BuiltinCodecs.cs +++ b/src/GeneralZip/Formats/Codecs/BuiltinCodecs.cs @@ -1,30 +1,41 @@ using System; using System.IO; +using System.Runtime.InteropServices; +using System.Threading; using GeneralZip; using GeneralZip.Abstractions; namespace GeneralZip.Formats.Codecs; /// -/// 原生编解码路由辅助:单文件编解码格式(BZ2/XZ/ZSTD/LZ4)经 Rust 原生核心 -/// 以"临时文件整段编解码"方式实现;核心缺失时抛出带部署指引的异常。 +/// 原生编解码路由辅助:单文件编解码格式(BZ2/XZ/ZSTD/LZ4/BROTLI)与 ZIP 扩展压缩方法 +/// 经 Rust 原生核心的流式回调接口实现(零临时文件转码);核心缺失时抛出带部署指引的异常。 /// internal static class NativeCodecRouter { public static void EnsureCore() { // 通过桥接委托间接访问原生核心,保持编解码实现与 P/Invoke 细节的边界: - // GeneralZipNative.Initialize()(GeneralZip.Initialize() 已自动调用)注入 NativeBridge 的实现。 + // NativeBridge 的实现由隐式引导注入(Default 注册表装配时自动调用 Bootstrap)。 if (!NativeBridgeProbe.IsAvailableSafe()) { - throw new NativeCoreMissingException( - "This codec format requires the Rust native core (generalzip_native), which was not found next to the application. " + - "Place generalzip_native.dll/.so/.dylib in the app directory or under runtimes//native/, " + - "or re-save the archive as ZIP/TAR.GZ or another pure-managed format."); + // 兜底:默认注册表未被触碰时(自定义注册表场景)桥接尚未注入,显式拉起一次。 + global::GeneralZip.Native.GeneralZipNative.EnsureBridge(); + if (!NativeBridgeProbe.IsAvailableSafe()) + { + throw new NativeCoreMissingException( + "This codec format requires the Rust native core (generalzip_native), which was not found next to the application. " + + "Place generalzip_native.dll/.so/.dylib in the app directory or under runtimes//native/, " + + "or re-save the archive as ZIP/TAR.GZ or another pure-managed format."); + } } } - internal static bool IsCoreAvailable() => NativeBridge.IsAvailable?.Invoke() ?? false; + internal static bool IsCoreAvailable() + { + global::GeneralZip.Native.GeneralZipNative.EnsureBridge(); + return NativeBridgeProbe.IsAvailableSafe(); + } internal static void Compress(string codec, string source, string destination) { @@ -45,15 +56,143 @@ internal static void Decompress(string codec, string source, string destination) $"The native core does not support {codec} decoding or is not loaded. Place generalzip_native.dll/.so/.dylib next to the app or under runtimes//native/."); } } + + // ---------- 流式(回调推拉)路径 ---------- + + /// 回调共享上下文:源/目标流 + 取消 + 异常传递。 + private sealed class TranscodeContext + { + public TranscodeContext(Stream source, Stream destination, CancellationToken cancellationToken, Action? progress) + { + Source = source; + Destination = destination; + CancellationToken = cancellationToken; + Progress = progress; + Buffer = new byte[65536]; + } + + public Stream Source { get; } + public Stream Destination { get; } + public CancellationToken CancellationToken { get; } + public Action? Progress { get; } + public byte[] Buffer { get; } + public Exception? Error { get; set; } + } + + /// 流式压缩:Rust 经回调拉明文、推密文。level 0 = 编解码器默认。 + internal static void CompressStream(Stream source, Stream destination, string codec, int level, CancellationToken cancellationToken, Action? progress = null) + { + EnsureCore(); + RunTranscode(codec, compress: true, source, destination, (uint)level, progress, cancellationToken); + } + + /// 流式解压:Rust 经回调拉密文、推明文。 + internal static void DecompressStream(Stream source, Stream destination, string codec, CancellationToken cancellationToken, Action? progress = null) + { + EnsureCore(); + RunTranscode(codec, compress: false, source, destination, 0, progress, cancellationToken); + } + + private static void RunTranscode(string codec, bool compress, Stream source, Stream destination, uint level, Action? progress, CancellationToken cancellationToken) + { + var context = new TranscodeContext(source, destination, cancellationToken, progress); + var handle = GCHandle.Alloc(context); + try + { + global::GeneralZip.Native.GzpNative.GzpCodecReadCallback readCb = OnReadCallback; + global::GeneralZip.Native.GzpNative.GzpCodecWriteCallback writeCb = OnWriteCallback; + + var status = compress + ? global::GeneralZip.Native.GzpNative.gzp_codec_crun(codec, level, readCb, writeCb, GCHandle.ToIntPtr(handle)) + : global::GeneralZip.Native.GzpNative.gzp_codec_drun(codec, readCb, writeCb, GCHandle.ToIntPtr(handle)); + + if (context.Error != null) + { + throw context.Error; // C# 侧异常(含 OperationCanceledException)优先透传 + } + + if (status != global::GeneralZip.Native.GzpNative.GzpOk) + { + var lastError = global::GeneralZip.Native.GzpNative.LastError(); + throw global::GeneralZip.Native.NativeCall.ToException( + status, + $"Native codec stream failed ({codec}, {(compress ? "compress" : "decompress")}): {lastError}"); + } + } + finally + { + handle.Free(); + } + } + + private static int OnReadCallback(IntPtr buffer, uint capacity, IntPtr userData) + { + var context = (TranscodeContext?)GCHandle.FromIntPtr(userData).Target; + if (context == null) + { + return -1; + } + + try + { + context.CancellationToken.ThrowIfCancellationRequested(); + var want = (int)Math.Min(capacity, (uint)context.Buffer.Length); + var read = context.Source.Read(context.Buffer, 0, want); + if (read > 0) + { + Marshal.Copy(context.Buffer, 0, buffer, read); + } + + return read; + } + catch (Exception ex) + { + context.Error ??= ex; + return -1; + } + } + + private static int OnWriteCallback(IntPtr buffer, uint length, IntPtr userData) + { + var context = (TranscodeContext?)GCHandle.FromIntPtr(userData).Target; + if (context == null) + { + return -1; + } + + try + { + context.CancellationToken.ThrowIfCancellationRequested(); + // Rust 侧单次 write 可能超过固定缓冲(如编码器整块输出),按长度循环消费 + var remaining = (int)length; + var offset = 0; + while (remaining > 0) + { + var chunk = Math.Min(remaining, context.Buffer.Length); + Marshal.Copy(IntPtr.Add(buffer, offset), context.Buffer, 0, chunk); + context.Destination.Write(context.Buffer, 0, chunk); + context.Progress?.Invoke(chunk); + remaining -= chunk; + offset += chunk; + } + + return 0; + } + catch (Exception ex) + { + context.Error ??= ex; + return -1; + } + } } /// -/// 原生核心桥接点:GeneralZip.Native 包在 Initialize 时注入实现。 +/// 原生核心桥接点:隐式引导(GeneralZipNative.Bootstrap)注入实现。 /// 核心包经此间接使用原生能力,保持"核心零 P/Invoke"的架构边界。 /// public static class NativeBridge { - /// 原生核心是否已加载。GeneralZipNative.Initialize 注入。 + /// 原生核心是否已加载。隐式引导注入。 public static Func? IsAvailable { get; set; } /// 整文件编解码:codec ∈ {bzip2, xz, zstd, lz4}。返回是否成功(false = 不支持该 codec)。 @@ -73,18 +212,20 @@ public static class NativeBridgeProbe public sealed class GZipFormat : SingleFileCodecFormat { public GZipFormat() - : base("GZIP", new[] { ".gz", ".gzip" }, ".gz", "gzip single-file compression", supportsWrite: true) + : base("GZIP", new[] { ".gz", ".gzip" }, "gzip single-file compression", supportsWrite: true) { } protected override Stream OpenDecompress(Stream source) => - new System.IO.Compression.GZipStream(source, System.IO.Compression.CompressionMode.Decompress, leaveOpen: false); + new System.IO.Compression.GZipStream(source, System.IO.Compression.CompressionMode.Decompress, leaveOpen: true); protected override Stream OpenCompress(Stream destination) => - new System.IO.Compression.GZipStream(destination, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: false); + new System.IO.Compression.GZipStream(destination, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true); protected override bool MatchesPrefix(byte[] prefix, int length) => length >= 2 && prefix[0] == 0x1F && prefix[1] == 0x8B; + + protected override string? NativeCodecId => null; } /// @@ -93,7 +234,7 @@ protected override bool MatchesPrefix(byte[] prefix, int length) public sealed class BZip2Format : SingleFileCodecFormat { public BZip2Format() - : base("BZIP2", new[] { ".bz2", ".bzip2" }, ".bz2", "bzip2 single-file compression (native core)", supportsWrite: true) + : base("BZIP2", new[] { ".bz2", ".bzip2" }, "bzip2 single-file compression (native core)", supportsWrite: true) { } @@ -104,11 +245,15 @@ public BZip2Format() protected override bool MatchesPrefix(byte[] prefix, int length) => length >= 3 && prefix[0] == (byte)'B' && prefix[1] == (byte)'Z' && prefix[2] == (byte)'h'; + protected override string? NativeCodecId => "bzip2"; + + /// 供 TAR.BZ2 包装:解压为临时解码流;压缩为缓冲编码流(Dispose 时落盘)。 internal static Stream WrapWithNative(string codec, Stream stream, bool decompress) { NativeCodecRouter.EnsureCore(); - return new NativeTempCodecStream(stream, codec, - decompress ? NativeCodecMode.Decompress : NativeCodecMode.Compress); + return decompress + ? new NativeTempDecodeStream(stream, codec) + : new NativeTempEncodeStream(stream, codec); } } @@ -118,7 +263,7 @@ internal static Stream WrapWithNative(string codec, Stream stream, bool decompre public sealed class XzFormat : SingleFileCodecFormat { public XzFormat() - : base("XZ", new[] { ".xz" }, ".xz", "xz (LZMA2) single-file compression (native core)", supportsWrite: true) + : base("XZ", new[] { ".xz" }, "xz (LZMA2) single-file compression (native core)", supportsWrite: true) { } @@ -129,6 +274,8 @@ public XzFormat() protected override bool MatchesPrefix(byte[] prefix, int length) => length >= 6 && prefix[0] == 0xFD && prefix[1] == 0x37 && prefix[2] == 0x7A && prefix[3] == 0x58 && prefix[4] == 0x5A && prefix[5] == 0x00; + + protected override string? NativeCodecId => "xz"; } /// @@ -137,7 +284,7 @@ protected override bool MatchesPrefix(byte[] prefix, int length) public sealed class ZstdFormat : SingleFileCodecFormat { public ZstdFormat() - : base("ZSTD", new[] { ".zst", ".zstd" }, ".zst", "Zstandard single-file compression (native core)", supportsWrite: true) + : base("ZSTD", new[] { ".zst", ".zstd" }, "Zstandard single-file compression (native core)", supportsWrite: true) { } @@ -147,6 +294,8 @@ public ZstdFormat() protected override bool MatchesPrefix(byte[] prefix, int length) => length >= 4 && prefix[0] == 0x28 && prefix[1] == 0xB5 && prefix[2] == 0x2F && prefix[3] == 0xFD; + + protected override string? NativeCodecId => "zstd"; } /// @@ -155,7 +304,7 @@ protected override bool MatchesPrefix(byte[] prefix, int length) public sealed class Lz4Format : SingleFileCodecFormat { public Lz4Format() - : base("LZ4", new[] { ".lz4" }, ".lz4", "LZ4 frame single-file compression (native core)", supportsWrite: true) + : base("LZ4", new[] { ".lz4" }, "LZ4 frame single-file compression (native core)", supportsWrite: true) { } @@ -165,4 +314,26 @@ public Lz4Format() protected override bool MatchesPrefix(byte[] prefix, int length) => length >= 4 && prefix[0] == 0x04 && prefix[1] == 0x22 && prefix[2] == 0x4D && prefix[3] == 0x18; + + protected override string? NativeCodecId => "lz4"; +} + +/// +/// Brotli 单文件格式(.br)。编解码经 Rust 原生核心(brotli 纯 Rust 实现);核心缺失时不可用。 +/// Brotli 无魔数(流首即位流),仅支持扩展名识别。 +/// +public sealed class BrotliFormat : SingleFileCodecFormat +{ + public BrotliFormat() + : base("BROTLI", new[] { ".br" }, "Brotli single-file compression (native core)", supportsWrite: true) + { + } + + protected override Stream OpenDecompress(Stream source) => BZip2Format.WrapWithNative("brotli", source, decompress: true); + + protected override Stream OpenCompress(Stream destination) => BZip2Format.WrapWithNative("brotli", destination, decompress: false); + + protected override bool MatchesPrefix(byte[] prefix, int length) => false; // 无魔数:仅扩展名识别 + + protected override string? NativeCodecId => "brotli"; } diff --git a/src/GeneralZip/Formats/Codecs/NativeStreams.cs b/src/GeneralZip/Formats/Codecs/NativeStreams.cs new file mode 100644 index 0000000..77ccb16 --- /dev/null +++ b/src/GeneralZip/Formats/Codecs/NativeStreams.cs @@ -0,0 +1,137 @@ +using System; +using System.IO; +using System.Threading; +using GeneralZip.Internal; + +namespace GeneralZip.Formats.Codecs; + +/// +/// 原生解码流(解压方向):构造时经 Rust 核心"拉式"整段解码到临时文件, +/// 随后按普通流读取。相比旧双临时文件方案少一次密文拷贝;Dispose 时清理临时文件。 +/// +internal sealed class NativeTempDecodeStream : Stream +{ + private readonly string _tempPath; + private readonly PrivateTempDirectory _tempDirectory; + private FileStream? _result; + private bool _disposed; + + public NativeTempDecodeStream(Stream source, string codec, CancellationToken cancellationToken = default) + { + _tempDirectory = new PrivateTempDirectory("gzp-decode"); + _tempPath = _tempDirectory.FilePath("decoded.out"); + try + { + try + { + using (var output = File.Create(_tempPath, 65536)) + { + NativeCodecRouter.DecompressStream(source, output, codec, cancellationToken); + } + + var buffer = new byte[81920]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + + _result = new FileStream(_tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536); + } + finally + { + source.Dispose(); + } + } + catch + { + _tempDirectory.Dispose(); + throw; + } + } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => _result!.Length; + public override long Position { get => _result!.Position; set => throw new NotSupportedException(); } + + public override int Read(byte[] buffer, int offset, int count) => _result!.Read(buffer, offset, count); + + public override void Flush() { } + + protected override void Dispose(bool disposing) + { + if (disposing && !_disposed) + { + _disposed = true; + _result?.Dispose(); + _result = null; + _tempDirectory.Dispose(); + } + + base.Dispose(disposing); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// +/// 原生编码流(压缩方向,供 TAR.BZ2 等流包装使用):明文先写入临时工作文件, +/// Dispose 时经 Rust 核心整段压缩并投递到目标流。ZIP 条目写入走 NativeCodecRouter +/// 的直通流式路径,不经此类。 +/// +internal sealed class NativeTempEncodeStream : Stream +{ + private readonly Stream _destination; + private readonly string _codec; + private readonly string _workPath; + private FileStream? _work; + private bool _finished; + + public NativeTempEncodeStream(Stream destination, string codec) + { + _destination = destination; + _codec = codec; + _workPath = Path.Combine(Path.GetTempPath(), $"gzp-encode-{Guid.NewGuid():N}.work"); + _work = new FileStream(_workPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536); + } + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override void Write(byte[] buffer, int offset, int count) => _work!.Write(buffer, offset, count); + + public override void Flush() => _work?.Flush(); + + protected override void Dispose(bool disposing) + { + if (disposing && !_finished) + { + _finished = true; + try + { + _work?.Dispose(); + _work = null; + using var input = File.OpenRead(_workPath); + NativeCodecRouter.CompressStream(input, _destination, _codec, level: 6, CancellationToken.None); + _destination.Flush(); + } + finally + { + try { File.Delete(_workPath); } catch { /* 清理失败忽略 */ } + } + } + + base.Dispose(disposing); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/src/GeneralZip/Formats/Codecs/NativeTempCodecStream.cs b/src/GeneralZip/Formats/Codecs/NativeTempCodecStream.cs deleted file mode 100644 index 38eb49e..0000000 --- a/src/GeneralZip/Formats/Codecs/NativeTempCodecStream.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.IO; - -namespace GeneralZip.Formats.Codecs; - -/// 原生编解码方向。 -internal enum NativeCodecMode -{ - Compress, - Decompress, -} - -/// -/// 原生编解码的流包装(双临时文件整段编解码): -/// - Compress:明文写入工作文件,Dispose 时调用原生核心压缩,产物投递到目标流; -/// - Decompress:构造时把来源流存为密文工作文件,原生解码到产物文件后按普通流读取。 -/// 工作文件与产物文件分离,避免同路径句柄互斥。 -/// -internal sealed class NativeTempCodecStream : Stream -{ - private readonly Stream? _destination; - private readonly Stream? _source; - private readonly string _codec; - private readonly bool _compress; - private readonly string _workPath; // 压缩:明文;解压:密文 - private readonly string _resultPath; // 编解码产物 - private FileStream? _work; - private FileStream? _result; - private bool _finished; - - private NativeTempCodecStream(string codec, bool compress) - { - _codec = codec; - _compress = compress; - var id = Guid.NewGuid().ToString("N"); - _workPath = Path.Combine(Path.GetTempPath(), $"gzp-codec-{id}.work"); - _resultPath = Path.Combine(Path.GetTempPath(), $"gzp-codec-{id}.out"); - } - - /// 按模式包装流:Compress → stream 为目标流;Decompress → stream 为来源流(立即整段解码)。 - public NativeTempCodecStream(Stream stream, string codec, NativeCodecMode mode) - : this(codec, compress: mode == NativeCodecMode.Compress) - { - if (mode == NativeCodecMode.Compress) - { - _destination = stream ?? throw new ArgumentNullException(nameof(stream)); - _work = new FileStream(_workPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536); - } - else - { - _source = stream ?? throw new ArgumentNullException(nameof(stream)); - - // 来源流 → 密文工作文件(写完关闭,避免共享锁冲突)→ 原生解码 → 产物文件 - using (var work = File.Create(_workPath, 65536)) - { - _source.CopyTo(work, 65536); - } - - NativeCodecRouter.Decompress(_codec, _workPath, _resultPath); - _result = new FileStream(_resultPath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536); - } - } - - public override bool CanRead => !_compress; - public override bool CanSeek => false; - public override bool CanWrite => _compress; - public override long Length => _compress ? throw new NotSupportedException() : _result!.Length; - public override long Position { get => _compress ? throw new NotSupportedException() : _result!.Position; set => throw new NotSupportedException(); } - - public override int Read(byte[] buffer, int offset, int count) - { - if (_compress) throw new NotSupportedException(); - return _result!.Read(buffer, offset, count); - } - - public override void Write(byte[] buffer, int offset, int count) - { - if (!_compress) throw new NotSupportedException(); - _work!.Write(buffer, offset, count); - } - - public override void Flush() => _work?.Flush(); - - protected override void Dispose(bool disposing) - { - if (disposing && !_finished) - { - _finished = true; - - try - { - _work?.Dispose(); - _work = null; - _result?.Dispose(); - _result = null; - - if (_compress) - { - NativeCodecRouter.Compress(_codec, _workPath, _resultPath); - using var compressed = File.OpenRead(_resultPath); - compressed.CopyTo(_destination!, 65536); - _destination!.Flush(); - } - } - finally - { - TryDelete(_workPath); - TryDelete(_resultPath); - } - } - - base.Dispose(disposing); - } - - private static void TryDelete(string path) - { - try { File.Delete(path); } catch { /* 清理失败忽略 */ } - } - - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - public override void SetLength(long value) => throw new NotSupportedException(); -} diff --git a/src/GeneralZip/Formats/Codecs/SingleFileCodecFormat.cs b/src/GeneralZip/Formats/Codecs/SingleFileCodecFormat.cs index 0344a64..15bc917 100644 --- a/src/GeneralZip/Formats/Codecs/SingleFileCodecFormat.cs +++ b/src/GeneralZip/Formats/Codecs/SingleFileCodecFormat.cs @@ -8,22 +8,22 @@ namespace GeneralZip.Formats.Codecs; /// -/// 单文件编解码格式基类(GZ / BZ2 / XZ / Zstd / LZ4)。 +/// 单文件编解码格式基类(GZ / BZ2 / XZ / Zstd / LZ4 / BROTLI)。 /// 语义:整包 = 一个条目(原始文件内容的压缩流)。 +/// 托管实现(GZIP)为真流式;原生实现经 Rust 核心的回调式转码: +/// 压缩直通落盘(零临时文件),解压整段解码到单个临时文件后惰性读取。 /// public abstract class SingleFileCodecFormat : IArchiveFormat { private readonly string _name; private readonly string[] _extensions; - private readonly string _strippedExtension; private readonly string? _description; private readonly FormatCapabilities _capabilities; - protected SingleFileCodecFormat(string name, string[] extensions, string strippedExtension, string? description, bool supportsWrite) + protected SingleFileCodecFormat(string name, string[] extensions, string? description, bool supportsWrite) { _name = name; _extensions = extensions; - _strippedExtension = strippedExtension; _description = description; _capabilities = FormatCapabilities.Read | FormatCapabilities.SeekableRead | (supportsWrite ? FormatCapabilities.Write : FormatCapabilities.None); @@ -31,17 +31,24 @@ protected SingleFileCodecFormat(string name, string[] extensions, string strippe public ArchiveFormatInfo Info => new(_name, _extensions, _capabilities, _description); - /// 解压包装。 + /// 解压包装(托管路径;原生格式走 路径)。 protected abstract Stream OpenDecompress(Stream source); - /// 压缩包装。 + /// 压缩包装(托管路径;CodecWriter 对原生格式不走此处)。 protected abstract Stream OpenCompress(Stream destination); /// 签名检查(前部字节)。 protected abstract bool MatchesPrefix(byte[] prefix, int length); - /// 压缩输出是否支持流式未知大小(默认 false)。 - internal virtual bool RequiresKnownSizeForWrite => false; + /// 原生编解码器标识(Rust 核心中的 codec id);null = 托管实现(GZIP)。 + protected virtual string? NativeCodecId => null; + + /// 是否为原生转码格式(写入直通、读取经临时解码)。 + internal bool IsNativeTranscoder => NativeCodecId != null; + + internal string? CodecId => NativeCodecId; + + internal Stream CreateCompressor(Stream destination) => OpenCompress(destination); public bool MatchesSignature(Stream stream) { @@ -85,7 +92,7 @@ public IArchiveReader OpenRead(Stream stream, ArchiveOpenOptions options) public IArchiveWriter OpenWrite(Stream stream, ArchiveWriteOptions options) { - return new CodecWriter(OpenCompress(stream), Info, this); + return new CodecWriter(stream, Info, this); } /// 从源文件名推导条目名(剥掉压缩扩展名)。 @@ -109,9 +116,7 @@ internal void EnsureWritable() { if ((_capabilities & FormatCapabilities.Write) == 0) { - throw new NotSupportedException( - $"Format {_name} does not support writing in its current configuration" + - (RequiresKnownSizeForWrite ? " (requires the native codec core)" : string.Empty)); + throw new NotSupportedException($"Format {_name} does not support writing in its current configuration"); } } } @@ -185,20 +190,26 @@ public CodecEntry(string fullName, long decompressedLength) public string? Comment => null; } -/// 单文件编解码写入器(仅接受一个条目;写入即压缩落盘)。 +/// +/// 单文件编解码写入器(仅接受一个条目)。 +/// 原生转码格式:条目内容经 Rust 核心流式压缩直通落盘;托管格式(GZIP)经压缩流包装。 +/// internal sealed class CodecWriter : IArchiveWriter { - private readonly Stream _compressed; + private readonly Stream _destination; // 最终输出流(不属于本对象) + private readonly Stream? _compressWrap; // 托管(GZIP)路径的压缩包装 private readonly SingleFileCodecFormat _owner; private readonly ArchiveWriteOptions _options; private bool _finished; + private bool _entryAdded; - public CodecWriter(Stream compressed, ArchiveFormatInfo info, SingleFileCodecFormat owner) + public CodecWriter(Stream destination, ArchiveFormatInfo info, SingleFileCodecFormat owner) { - _compressed = compressed; + _destination = destination; Info = info; _owner = owner; _options = new ArchiveWriteOptions(); + _compressWrap = owner.IsNativeTranscoder ? null : owner.CreateCompressor(destination); } public ArchiveFormatInfo Info { get; } @@ -213,10 +224,18 @@ public void AddDirectoryEntry(string entryName, ArchiveEntryMetadata metadata) public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata metadata, CancellationToken cancellationToken) { _owner.EnsureWritable(); + if (_entryAdded) + { + throw new NotSupportedException($"Format {_owner.Info.Name} supports only one input entry"); + } + + _entryAdded = true; - if (_owner.RequiresKnownSizeForWrite && metadata.Size < 0 && !content.CanSeek) + if (_owner.IsNativeTranscoder) { - throw new NotSupportedException($"Format {_owner.Info.Name} requires a known entry size for writing"); + // 直通流式压缩:明文经回调拉入 Rust 核心,压缩字节直接落盘 + NativeCodecRouter.CompressStream(content, _destination, _owner.CodecId!, level: 6, cancellationToken); + return; } var buffer = new byte[81920]; @@ -224,7 +243,7 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta while ((read = content.Read(buffer, 0, buffer.Length)) > 0) { cancellationToken.ThrowIfCancellationRequested(); - _compressed.Write(buffer, 0, read); + _compressWrap!.Write(buffer, 0, read); } } @@ -232,7 +251,8 @@ public void Finish(CancellationToken cancellationToken) { if (_finished) return; _finished = true; - _compressed.Flush(); + _compressWrap?.Flush(); + _destination.Flush(); } public Task FinishAsync(CancellationToken cancellationToken) @@ -249,7 +269,12 @@ public ValueTask DisposeAsync() public void Dispose() { - // Dispose 压缩流以刷出流终结块(gzip/xz/zstd/lz4 尾部) - _compressed.Dispose(); + // 先收尾(Flush 输出),再 Dispose 压缩包装(gzip 在 Dispose 时写终结块;底层流不关闭) + if (!_finished) + { + try { Finish(CancellationToken.None); } catch { /* 自动收尾失败不遮蔽主异常 */ } + } + + _compressWrap?.Dispose(); } } diff --git a/src/GeneralZip/Formats/Cpio/CpioFormat.cs b/src/GeneralZip/Formats/Cpio/CpioFormat.cs new file mode 100644 index 0000000..cc3fcda --- /dev/null +++ b/src/GeneralZip/Formats/Cpio/CpioFormat.cs @@ -0,0 +1,562 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using GeneralZip.Abstractions; +using GeneralZip.Internal; + +namespace GeneralZip.Formats.Cpio; + +/// +/// CPIO 归档格式(纯 C# 自研,无第三方依赖)。 +/// 读取:SVR4 newc("070701")、CRC 变体("070702")、odc 旧 ASCII("070707")、portable binary(0x71C7); +/// 写入:newc(最通用,GNU cpio -H newc 互通)。符号链接以数据段承载目标路径(S_IFLNK)。 +/// +public sealed class CpioFormat : IArchiveFormat +{ + private const string MagicNewc = "070701"; + private const string MagicCrc = "070702"; + private const string MagicOdc = "070707"; + private const string TrailerName = "TRAILER!!!"; + + private const uint SIfmt = 0xF000u; + private const uint SIfReg = 0x8000u; + private const uint SIfDir = 0x4000u; + private const uint SIfLnk = 0xA000u; + + public ArchiveFormatInfo Info { get; } = new( + "CPIO", new[] { ".cpio" }, + FormatCapabilities.Read | FormatCapabilities.Write | FormatCapabilities.SeekableRead, + "cpio: newc/odc/binary read, newc write"); + + public bool MatchesSignature(Stream stream) + { + long restorePos = -1; + if (stream.CanSeek) restorePos = stream.Position; + + try + { + var prefix = new byte[6]; + var total = 0; + while (total < prefix.Length) + { + var n = stream.Read(prefix, total, prefix.Length - total); + if (n <= 0) break; + total += n; + } + + if (total < 6) return total == 2 && IsBinaryMagic(prefix); + + var magic = System.Text.Encoding.ASCII.GetString(prefix, 0, 6); + return magic == MagicNewc || magic == MagicCrc || magic == MagicOdc + || IsBinaryMagic(prefix); + } + finally + { + if (restorePos >= 0) stream.Position = restorePos; + } + } + + private static bool IsBinaryMagic(byte[] prefix) + => prefix[0] == 0x71 && prefix[1] == 0xC7 + || prefix[0] == 0xC7 && prefix[1] == 0x71; + + public bool MatchesExtension(string extension) + => extension.Equals(".cpio", StringComparison.OrdinalIgnoreCase); + + public IArchiveReader OpenRead(Stream stream, ArchiveOpenOptions options) + { + if (!stream.CanSeek) + { + throw new NotSupportedException("CPIO reading requires a seekable stream"); + } + + return new CpioReader(stream, ownsStream: false); + } + + public IArchiveWriter OpenWrite(Stream stream, ArchiveWriteOptions options) + => new CpioWriter(stream, ownsStream: false); + + // ---------- newc 头解析/序列化 ---------- + + internal sealed class CpioEntryData + { + public string Name = string.Empty; + public uint Mode; + public long Size; + public DateTimeOffset MTime; + public long DataOffset; + public bool IsDirectory => (Mode & SIfmt) == SIfDir; + public bool IsSymlink => (Mode & SIfmt) == SIfLnk; + } + + private static readonly char[] HexTrim = { ' ' }; + + /// 流式枚举 newc/odc/binary 头部(供读取器与探测共用)。返回 null = 归档结束。 + internal static CpioEntryData? ReadHeader(Stream stream, BinaryReader reader, out string? formatKind) + { + formatKind = null; + var head = reader.ReadBytes(6); + if (head.Length < 6) + { + return null; + } + + var magic = System.Text.Encoding.ASCII.GetString(head); + if (magic == MagicNewc || magic == MagicCrc) + { + formatKind = "newc"; + // 13 个 8 位十六进制字段:ino mode uid gid nlink mtime filesize devmaj devmin rmaj rmin namesize check + var fields = new string[13]; + for (var i = 0; i < fields.Length; i++) + { + fields[i] = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(8)); + } + + var mode = ParseHex(fields[1]); + var mtime = ParseHex(fields[5]); + var fileSize = ParseHex(fields[6]); + var nameSize = ParseHex(fields[11]); + + var nameBytes = reader.ReadBytes((int)nameSize); + var name = System.Text.Encoding.UTF8.GetString(nameBytes, 0, nameBytes.Length).TrimEnd('\0'); + AlignTo4(stream); + + if (name == TrailerName || name.Length == 0) + { + AlignTo4(stream); + return null; + } + + var offset = stream.Position; + stream.Seek(fileSize, SeekOrigin.Current); + AlignTo4(stream); + + return new CpioEntryData + { + Name = name, + Mode = mode, + Size = fileSize, + MTime = DateTimeOffset.FromUnixTimeSeconds(mtime), + DataOffset = offset, + }; + } + + if (magic == MagicOdc) + { + formatKind = "odc"; + // dev, ino, mode, uid, gid, nlink, rdev, mtime, namesize, filesize + var widths = new[] { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 }; + var fields = new string[widths.Length]; + for (var i = 0; i < fields.Length; i++) + { + var bytes = reader.ReadBytes(widths[i]); + if (bytes.Length != widths[i]) throw new ArchiveCorruptedException("Truncated CPIO odc header"); + fields[i] = System.Text.Encoding.ASCII.GetString(bytes); + } + + var mode = ParseOctal(fields[2]); + var mtime = ParseOctal(fields[7]); + var nameSize = ParseOctal(fields[8]); + var fileSize = ParseOctal(fields[9]); + + var nameBytes = reader.ReadBytes((int)nameSize); + var name = System.Text.Encoding.UTF8.GetString(nameBytes, 0, nameBytes.Length).TrimEnd('\0'); + + if (name == TrailerName || name.Length == 0) + { + return null; + } + + var offset = stream.Position; + stream.Seek(fileSize, SeekOrigin.Current); + + return new CpioEntryData + { + Name = name, + Mode = mode, + Size = fileSize, + MTime = DateTimeOffset.FromUnixTimeSeconds(mtime), + DataOffset = offset, + }; + } + + // portable binary(LE 0x71C7;BE 魔数为 0xC771) + stream.Position -= 6; + var b0 = reader.ReadByte(); + var b1 = reader.ReadByte(); + if (b0 == 0x71 && b1 == 0xC7 || b0 == 0xC7 && b1 == 0x71) + { + formatKind = "binary"; + var little = b0 == 0xC7; + ushort ReadU16() + { + var lo = reader.ReadByte(); + var hi = reader.ReadByte(); + return little ? (ushort)(lo | (hi << 8)) : (ushort)((lo << 8) | hi); + } + + _ = ReadU16(); // c_dev + var ino = ReadU16(); + var mode = ReadU16(); + var uid = ReadU16(); + var gid = ReadU16(); + var nlink = ReadU16(); + _ = ReadU16(); // c_rdev + var mtimeHi = (uint)ReadU16() << 16; + var mtimeLo = ReadU16(); + var nameSize = ReadU16(); + var fileSizeHi = (uint)ReadU16() << 16; + var fileSizeLo = ReadU16(); + + var nameBytes = reader.ReadBytes(nameSize); + if (nameBytes.Length != nameSize) throw new ArchiveCorruptedException("Truncated CPIO binary name"); + var name = System.Text.Encoding.UTF8.GetString(nameBytes, 0, nameBytes.Length).TrimEnd('\0'); + AlignTo2(stream); + + if (name == TrailerName || name.Length == 0) + { + return null; + } + + var fileSize = fileSizeHi | fileSizeLo; + var offset = stream.Position; + stream.Seek(fileSize, SeekOrigin.Current); + AlignTo2(stream); + + return new CpioEntryData + { + Name = name, + Mode = mode, + Size = fileSize, + MTime = DateTimeOffset.FromUnixTimeSeconds(mtimeHi | mtimeLo), + DataOffset = offset, + }; + } + + throw new ArchiveCorruptedException($"Invalid CPIO magic: {magic}"); + } + + /// newc 对齐:把当前流位置补齐到 4 字节边界(GNU cpio 语义为绝对位置对齐)。 + private static void AlignTo4(Stream stream) + { + var pad = (4 - (stream.Position % 4)) % 4; + if (pad > 0) + { + stream.Seek(pad, SeekOrigin.Current); + } + } + + private static void AlignTo2(Stream stream) + { + if ((stream.Position & 1) != 0) stream.Seek(1, SeekOrigin.Current); + } + + private static uint ParseHex(string s) => uint.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + + private static uint ParseOctal(string s) => Convert.ToUInt32(s.Length == 0 ? "0" : s, 8); + + // ---------- 读取器 ---------- + + private sealed class CpioReader : IArchiveReader + { + private readonly Stream _stream; + private readonly bool _ownsStream; + private readonly List<(CpioEntryData data, IArchiveEntry entry)> _entries = new(); + + public CpioReader(Stream stream, bool ownsStream) + { + _stream = stream; + _ownsStream = ownsStream; + + using var reader = new BinaryReader(stream, System.Text.Encoding.UTF8, leaveOpen: true); + string? kind = null; + while (true) + { + CpioEntryData? data; + try + { + data = ReadHeader(stream, reader, out var k); + kind ??= k; + } + catch (EndOfStreamException) + { + break; + } + + if (data == null) + { + break; + } + + var entry = new CpioEntryView(data, Format); + _entries.Add((data, entry)); + } + } + + public ArchiveFormatInfo Format { get; } = new( + "CPIO", new[] { ".cpio" }, + FormatCapabilities.Read | FormatCapabilities.Write | FormatCapabilities.SeekableRead, + "cpio: newc/odc/binary read, newc write"); + + public IReadOnlyList Entries => _entries.ConvertAll(e => e.entry); + + public bool IsEncrypted => false; + + public Stream OpenEntryStream(IArchiveEntry entry) + { + var data = Find(entry); + return new PartialStream(_stream, data.DataOffset, data.Size); + } + + public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationToken cancellationToken) + { + using var source = OpenEntryStream(entry); + var buffer = new byte[81920]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + destination.Write(buffer, 0, read); + } + } + + private CpioEntryData Find(IArchiveEntry entry) + { + foreach (var (data, view) in _entries) + { + if (ReferenceEquals(view, entry)) + { + return data; + } + } + + throw new ArgumentException("Entry does not belong to this archive", nameof(entry)); + } + + public void Dispose() + { + if (_ownsStream) _stream.Dispose(); + } + } + + private sealed class CpioEntryView : IArchiveEntry, IUnixEntry + { + private readonly CpioEntryData _data; + + public CpioEntryView(CpioEntryData data, ArchiveFormatInfo format) + { + _data = data; + } + + public string FullName => _data.Name; + public string Name + { + get + { + var idx = _data.Name.LastIndexOf('/'); + return idx >= 0 ? _data.Name.Substring(idx + 1) : _data.Name; + } + } + + public long Size => _data.IsSymlink || _data.IsDirectory ? _data.Size : _data.Size; + public long CompressedSize => _data.Size; + public DateTimeOffset? LastWriteTime => _data.MTime; + public bool IsDirectory => _data.IsDirectory; + public bool IsEncrypted => false; + public string? EncryptionAlgorithm => null; + public uint? Crc32 => null; + public string? Comment => null; + public uint? UnixMode => _data.Mode; + + /// 符号链接目标在数据段中;此处只报告判定,目标内容经 OpenEntryStream 读取。 + public string? SymlinkTarget => null; + } + + // ---------- 写入器(newc) ---------- + + private sealed class CpioWriter : IArchiveWriter, IArchiveSymlinkWriter + { + private readonly Stream _output; + private readonly bool _ownsStream; + private uint _ino = 300_000; // 任意起始 i-node + private long _bytesWritten; // 绝对位置(newc 对齐按绝对位置计算) + private bool _finished; + + public CpioWriter(Stream output, bool ownsStream) + { + _output = output; + _ownsStream = ownsStream; + } + + public ArchiveFormatInfo Info { get; } = new( + "CPIO", new[] { ".cpio" }, + FormatCapabilities.Read | FormatCapabilities.Write | FormatCapabilities.SeekableRead, + "cpio: newc/odc/binary read, newc write"); + + public ArchiveWriteOptions Options { get; } = new(); + + public void AddDirectoryEntry(string entryName, ArchiveEntryMetadata metadata) + => WriteHeader(Normalize(entryName), SIfDir | 0x1EDu /*0755*/, 0, metadata); + + public void AddSymlink(string entryName, string target, ArchiveEntryMetadata metadata) + { + var targetBytes = System.Text.Encoding.UTF8.GetBytes(target); + WriteHeader(Normalize(entryName), SIfLnk | 0x1FFu /*0777*/, targetBytes.Length, metadata); + WriteData(targetBytes); + } + + public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata metadata, CancellationToken cancellationToken) + { + var name = Normalize(entryName); + var mode = SIfReg | 0x1A4u; // 0644 默认 + if (metadata.UnixMode is { } um) + { + mode = (um & SIfmt) == SIfReg ? um : SIfReg | (um & 0xFFF); + } + + if (metadata.Size >= 0) + { + WriteHeader(name, mode, metadata.Size, metadata); + CopyData(content, metadata.Size, cancellationToken); + } + else + { + // 未知大小:缓冲到内存(cpio 头部必须前置声明 filesize) + using var ms = new MemoryStream(); + content.CopyTo(ms, 81920); + WriteHeader(name, mode, ms.Length, metadata); + WriteData(ms.ToArray()); + } + } + + private void WriteHeader(string name, uint mode, long size, ArchiveEntryMetadata metadata) + { + var nameBytes = System.Text.Encoding.UTF8.GetBytes(name.Length == 0 ? "\0" : name + "\0"); + var mtime = (metadata.LastWriteTime ?? DateTimeOffset.Now).ToUnixTimeSeconds(); + + var header = new System.Text.StringBuilder(); + header.Append(MagicNewc); + foreach (var value in new long[] + { + _ino++, mode, 0 /*uid*/, 0 /*gid*/, 1 /*nlink*/, mtime, size, + 0 /*devmajor*/, 0, 0, 0, nameBytes.Length, 0 /*check*/, + }) + { + header.Append(value.ToString("X8", CultureInfo.InvariantCulture)); + } + + var headerBytes = System.Text.Encoding.ASCII.GetBytes(header.ToString()); + _output.Write(headerBytes, 0, headerBytes.Length); + _output.Write(nameBytes, 0, nameBytes.Length); + _bytesWritten += headerBytes.Length + nameBytes.Length; + Pad4(); + } + + private void CopyData(Stream content, long size, CancellationToken ct) + { + var buffer = new byte[81920]; + long written = 0; + int read; + while (written < size && (read = content.Read(buffer, 0, (int)Math.Min(buffer.Length, size - written))) > 0) + { + ct.ThrowIfCancellationRequested(); + _output.Write(buffer, 0, read); + written += read; + } + + if (written != size) + { + throw new IOException($"CPIO: source stream ran short for declared size {size} (got {written})"); + } + + _bytesWritten += written; + Pad4(); + } + + private void WriteData(byte[] bytes) + { + _output.Write(bytes, 0, bytes.Length); + _bytesWritten += bytes.Length; + Pad4(); + } + + /// newc 对齐:按绝对写位置补齐 4 字节边界。 + private void Pad4() + { + var pad = (int)((4 - (_bytesWritten % 4)) % 4); + for (var i = 0; i < pad; i++) + { + _output.WriteByte(0); + } + + _bytesWritten += pad; + } + + private static string Normalize(string name) + { + var n = name.Replace('\\', '/').TrimStart('/'); + while (n.Contains("//")) + { + n = n.Replace("//", "/"); + } + + return n; + } + + public void Finish(CancellationToken cancellationToken) + { + if (_finished) return; + _finished = true; + + // trailer + 512 块对齐(GNU cpio 惯例) + var trailerName = System.Text.Encoding.UTF8.GetBytes(TrailerName + "\0"); + var header = new System.Text.StringBuilder(); + header.Append(MagicNewc); + foreach (var value in new long[] { _ino++, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, trailerName.Length, 0 }) + { + header.Append(value.ToString("X8", CultureInfo.InvariantCulture)); + } + + var headerBytes = System.Text.Encoding.ASCII.GetBytes(header.ToString()); + _output.Write(headerBytes, 0, headerBytes.Length); + _output.Write(trailerName, 0, trailerName.Length); + _bytesWritten += headerBytes.Length + trailerName.Length; + Pad4(); + + var blockPad = (int)((512 - (_bytesWritten % 512)) % 512); + for (var i = 0; i < blockPad; i++) + { + _output.WriteByte(0); + } + + _bytesWritten += blockPad; + _output.Flush(); + } + + public Task FinishAsync(CancellationToken cancellationToken) + { + Finish(cancellationToken); + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() + { + Dispose(); + return default; + } + + public void Dispose() + { + if (!_finished) + { + try { Finish(CancellationToken.None); } catch { /* 不遮蔽主异常 */ } + } + + if (_ownsStream) + { + _output.Dispose(); + } + } + } +} diff --git a/src/GeneralZip/Formats/Iso/IsoFormat.cs b/src/GeneralZip/Formats/Iso/IsoFormat.cs new file mode 100644 index 0000000..887b87a --- /dev/null +++ b/src/GeneralZip/Formats/Iso/IsoFormat.cs @@ -0,0 +1,375 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using GeneralZip.Internal; + +namespace GeneralZip.Formats.Iso; + +/// +/// ISO9660 光盘镜像读取(纯 C# 自研,只读)。 +/// 优先 Joliet(UCS-2 补充卷)与 Rock Ridge NM 文件名,回退 ISO Level 1 基础名。 +/// 多卷集合/UDF 混合镜像取 ISO9660 视图。写入不支持。 +/// +public sealed class IsoFormat : IArchiveFormat +{ + private const int SectorSize = 2048; + private const int PvdLba = 16; + + public ArchiveFormatInfo Info { get; } = new( + "ISO", new[] { ".iso" }, + FormatCapabilities.Read | FormatCapabilities.SeekableRead, + "ISO9660 (+Joliet/Rock Ridge name extensions), read-only"); + + public bool MatchesSignature(Stream stream) + { + long restorePos = -1; + if (stream.CanSeek) restorePos = stream.Position; + + try + { + stream.Seek(PvdLba * SectorSize + 1, SeekOrigin.Begin); + var buf = new byte[5]; + var total = 0; + while (total < buf.Length) + { + var n = stream.Read(buf, total, buf.Length - total); + if (n <= 0) return false; + total += n; + } + + return buf[0] == (byte)'C' && buf[1] == (byte)'D' && buf[2] == (byte)'0' + && buf[3] == (byte)'0' && buf[4] == (byte)'1'; + } + catch (IOException) + { + return false; + } + finally + { + if (restorePos >= 0) stream.Position = restorePos; + } + } + + public bool MatchesExtension(string extension) + => extension.Equals(".iso", StringComparison.OrdinalIgnoreCase); + + public IArchiveReader OpenRead(Stream stream, ArchiveOpenOptions options) + { + if (!stream.CanSeek) + { + throw new NotSupportedException("ISO reading requires a seekable stream"); + } + + return new IsoReader(stream, ownsStream: false); + } + + public IArchiveWriter OpenWrite(Stream stream, ArchiveWriteOptions options) + => throw new UnsupportedFormatException("ISO9660 writing is not supported (read-only format)"); + + internal sealed class IsoEntryData + { + public string Name = string.Empty; + public long Lba; + public long Size; + public bool IsDirectory; + public DateTimeOffset MTime; + public long DataOffset => Lba * SectorSize; + } + + internal sealed class IsoReader : IArchiveReader + { + private readonly Stream _stream; + private readonly bool _ownsStream; + private readonly List _flat = new(); + private readonly List _entries = new(); + + public IsoReader(Stream stream, bool ownsStream) + { + _stream = stream; + _ownsStream = ownsStream; + + var (rootLba, rootSize, useUcs2) = LocateVolume(stream); + var visited = new HashSet(); + Walk(stream, rootLba, rootSize, string.Empty, useUcs2, visited, depth: 0); + } + + /// 定位 PVD 根目录;存在 Joliet SVD 时取其根(UCS-2 名称)。 + private static (long lba, long size, bool ucs2) LocateVolume(Stream s) + { + // 扫描 PVD..SVD 区(最多到 LBA 32) + var jolietRoot = (lba: 0L, size: 0L); + for (var lba = PvdLba; lba < PvdLba + 16; lba++) + { + var sector = ReadSector(s, lba); + if (sector[1] != (byte)'C' || sector[2] != (byte)'D' || sector[3] != (byte)'0' + || sector[4] != (byte)'0' || sector[5] != (byte)'1') + { + break; // 卷描述符序列结束(terminator 亦不匹配) + } + + var type = sector[0]; + if (type == 1) + { + // 主卷描述符:兜底根 + var root = ParseDirectoryRecord(sector, 156); + jolietRoot = (root.lba, root.size); + continue; + } + + if (type == 2) + { + // 补充卷描述符:Joliet 检测(escape sequences %/@ %/C %/E,偏移 88..) + var e = sector[88]; + if ((e == 0x25 && sector[89] == 0x2F && (sector[90] == 0x40 || sector[90] == 0x43 || sector[90] == 0x45))) + { + var root = ParseDirectoryRecord(sector, 156); + return (root.lba, root.size, true); // Joliet 优先 + } + } + } + + if (jolietRoot.lba == 0) + { + throw new ArchiveCorruptedException("ISO9660: no primary volume descriptor with a root directory found"); + } + + return (jolietRoot.lba, jolietRoot.size, false); + } + + private static byte[] ReadSector(Stream s, long lba) + { + var buf = new byte[SectorSize]; + s.Position = lba * SectorSize; + var total = 0; + while (total < SectorSize) + { + var n = s.Read(buf, total, SectorSize - total); + if (n <= 0) + { + throw new ArchiveCorruptedException($"ISO9660: unexpected end of file at LBA {lba}"); + } + + total += n; + } + + return buf; + } + + private static (long lba, long size) ParseDirectoryRecord(byte[] sector, int offset) + { + // LBA 双端(LE @+2,BE @+6)、大小双端(LE @+10,BE @+14) + var lba = BitConverter.ToUInt32(sector, offset + 2); + var size = BitConverter.ToUInt32(sector, offset + 10); + return (lba, size); + } + + private void Walk(Stream s, long dirLba, long dirSize, string prefix, bool ucs2, HashSet visited, int depth) + { + if (depth > 1024) + { + throw new ArchiveCorruptedException("ISO9660 directory nesting exceeds the supported limit"); + } + + if (!visited.Add(dirLba)) + { + return; + } + + var extentStart = dirLba * SectorSize; + for (var sectorOffset = 0L; sectorOffset < dirSize; sectorOffset += SectorSize) + { + var sector = ReadSector(s, (extentStart + sectorOffset) / SectorSize); + for (var offset = 0; offset < SectorSize; ) + { + var len = sector[offset]; + if (len == 0) + { + // 记录不跨扇区:0 填充 → 结束本扇区 + break; + } + + if (len < 34 || offset + len > sector.Length) + { + throw new ArchiveCorruptedException("ISO9660: invalid directory record length"); + } + + var nameLen = sector[offset + 32]; + if (33 + nameLen > len) + { + throw new ArchiveCorruptedException("ISO9660: directory identifier exceeds its record"); + } + + var extLba = BitConverter.ToUInt32(sector, offset + 2); + var extSize = BitConverter.ToUInt32(sector, offset + 10); + var flags = sector[offset + 25]; + var isDir = (flags & 0x02) != 0; + + var identifierOffset = offset + 33; + if (nameLen == 1 && sector[identifierOffset] <= 1) + { + offset += len; + continue; + } + + var name = DecodeName(sector, identifierOffset, nameLen, ucs2); + var systemUse = identifierOffset + nameLen + ((nameLen & 1) == 0 ? 1 : 0); + name = ApplyRockRidge(sector, systemUse, offset + len, name); + + if (name.Length != 0) + { + var mtime = DecodeIsoTime(sector, offset + 18); + var fullName = prefix.Length > 0 ? prefix + "/" + name : name; + var data = new IsoEntryData + { + Name = isDir ? fullName + "/" : fullName, + Lba = extLba, + Size = extSize, + IsDirectory = isDir, + MTime = mtime, + }; + _entries.Add(new IsoEntryView(data, this)); + + if (isDir) + { + Walk(s, extLba, extSize, fullName, ucs2, visited, depth + 1); + } + } + + offset += len; + } + } + } + + private static string DecodeName(byte[] sector, int offset, int nameLen, bool ucs2) + { + if (ucs2) + { + var sb = new StringBuilder(nameLen / 2); + for (var i = 0; i + 1 < nameLen; i += 2) + { + sb.Append((char)((sector[offset + i] << 8) | sector[offset + i + 1])); // UCS-2 BE + } + + var name = sb.ToString(); + var version = name.IndexOf(';'); + if (version >= 0) name = name.Substring(0, version); + return name.Length > 0 && name[name.Length - 1] == '.' ? name.Substring(0, name.Length - 1) : name; + } + + var raw = Encoding.ASCII.GetString(sector, offset, nameLen); + var idx = raw.IndexOf(';'); + if (idx >= 0) + { + raw = raw.Substring(0, idx); // 剥掉 ";1" 版本号 + } + + return raw.TrimEnd('.'); + } + + /// Rock Ridge:System Use 区里的 NM 条目提供 POSIX 文件名。 + /// Rock Ridge:System Use 区里的 NM 条目提供 POSIX 文件名。 + private static string ApplyRockRidge(byte[] sector, int systemUseOffset, int recordEnd, string fallback) + { + var pos = systemUseOffset; + var name = new StringBuilder(); + while (pos + 4 <= recordEnd) + { + var sig0 = (char)sector[pos]; + var sig1 = (char)sector[pos + 1]; + var len = sector[pos + 2]; + if (len < 4 || pos + len > recordEnd) + { + break; + } + + if (sig0 == 'N' && sig1 == 'M') + { + name.Append(Encoding.UTF8.GetString(sector, pos + 5, len - 5)); + } + + pos += len; + } + + return name.Length > 0 ? name.ToString() : fallback; + } + + private static DateTimeOffset DecodeIsoTime(byte[] sector, int offset) + { + // 9.1.5: 7 字节 (year-1900, month, day, hour, minute, second, gmt offset*15min) + var year = sector[offset] + 1900; + try + { + return new DateTimeOffset(year, sector[offset + 1], sector[offset + 2], + sector[offset + 3], sector[offset + 4], sector[offset + 5], TimeSpan.Zero); + } + catch (ArgumentOutOfRangeException) + { + return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); + } + } + + public ArchiveFormatInfo Format { get; } = new( + "ISO", new[] { ".iso" }, + FormatCapabilities.Read | FormatCapabilities.SeekableRead, + "ISO9660 (+Joliet/Rock Ridge name extensions), read-only"); + + public IReadOnlyList Entries => _entries; + + public bool IsEncrypted => false; + + public Stream OpenEntryStream(IArchiveEntry entry) + { + var view = (IsoEntryView)entry; + return new PartialStream(_stream, view.Data.DataOffset, view.Data.Size); + } + + public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationToken cancellationToken) + { + using var source = OpenEntryStream(entry); + var buffer = new byte[81920]; + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + destination.Write(buffer, 0, read); + } + } + + public void Dispose() + { + if (_ownsStream) _stream.Dispose(); + } + + private sealed class IsoEntryView : IArchiveEntry + { + public IsoEntryView(IsoEntryData data, IsoReader owner) + { + Data = data; + } + + public IsoEntryData Data { get; } + + public string FullName => Data.Name; + public string Name + { + get + { + var idx = Data.Name.LastIndexOf('/'); + return idx >= 0 ? Data.Name.Substring(idx + 1) : Data.Name; + } + } + + public long Size => Data.Size; + public long CompressedSize => Data.Size; + public DateTimeOffset? LastWriteTime => Data.MTime; + public bool IsDirectory => Data.IsDirectory; + public bool IsEncrypted => false; + public string? EncryptionAlgorithm => null; + public uint? Crc32 => null; + public string? Comment => null; + } + } +} diff --git a/src/GeneralZip/Formats/Tar/TarFormat.cs b/src/GeneralZip/Formats/Tar/TarFormat.cs index 8660b9d..fde42da 100644 --- a/src/GeneralZip/Formats/Tar/TarFormat.cs +++ b/src/GeneralZip/Formats/Tar/TarFormat.cs @@ -106,12 +106,12 @@ Stream OpenDecompressed() return WrapDecompress(stream); } - return new TarReader(OpenDecompressed, Info, options); + return new TarReader(OpenDecompressed, stream, Info, options); } public IArchiveWriter OpenWrite(Stream stream, ArchiveWriteOptions options) { - return new TarWriter(WrapCompress(stream), Info, options); + return new TarWriter(WrapCompress(stream), stream, Info, options); } private static int FillPrefix(Stream stream, byte[] prefix) @@ -128,15 +128,18 @@ private static int FillPrefix(Stream stream, byte[] prefix) } } -/// TAR entry view. -internal sealed class TarEntryView : IArchiveEntry +/// TAR entry view(ustar 携带 mode;typeflag '2' 为符号链接,目标在头部)。 +internal sealed class TarEntryView : IArchiveEntry, IUnixEntry { - public TarEntryView(string fullName, long size, DateTimeOffset? mtime, bool isDirectory) + public TarEntryView(string fullName, long size, DateTimeOffset? mtime, bool isDirectory, int mode, string? linkName) { FullName = fullName; Size = size; LastWriteTime = mtime; IsDirectory = isDirectory; + var type = linkName != null ? 0xA000u : isDirectory ? 0x4000u : 0x8000u; + UnixMode = type | (unchecked((uint)mode) & 0x0FFFu); + SymlinkTarget = linkName; } public string FullName { get; } @@ -157,6 +160,10 @@ public string Name public string? EncryptionAlgorithm => null; public uint? Crc32 => null; public string? Comment => null; + + public uint? UnixMode { get; } + + public string? SymlinkTarget { get; } } /// TAR reader (over a decompression wrapper stream). @@ -164,13 +171,15 @@ internal sealed class TarReader : IArchiveReader { private readonly List _entries = new(); private Stream _inner; + private readonly Stream _sourceStream; // 用户/门面持有的底层流:不是我们的所有权 private readonly Func _reopenDecompressed; private TarStreamReader? _sequential; // sequential cursor for non-seekable mode - public TarReader(Func openDecompressed, ArchiveFormatInfo info, ArchiveOpenOptions options) + public TarReader(Func openDecompressed, Stream sourceStream, ArchiveFormatInfo info, ArchiveOpenOptions options) { Format = info; _reopenDecompressed = openDecompressed; + _sourceStream = sourceStream; _inner = openDecompressed(); using (var probe = OpenTarStream()) @@ -189,7 +198,9 @@ public TarReader(Func openDecompressed, ArchiveFormatInfo info, ArchiveO name, entry.Size, entry.ModTime == default ? null : entry.ModTime, - name.EndsWith("/", StringComparison.Ordinal))); + name.EndsWith("/", StringComparison.Ordinal), + entry.Mode, + entry.TypeFlag == (byte)'2' ? entry.LinkName : null)); } } @@ -201,12 +212,21 @@ public TarReader(Func openDecompressed, ArchiveFormatInfo info, ArchiveO { // non-seekable (e.g. tar.gz pipe stream): the probe exhausted the wrapper — // rebuild it and use it as the sequential cursor - _inner.Dispose(); + DisposeInner(); _inner = openDecompressed(); _sequential = OpenTarStream(); } } + /// 只处置我们创建的解压包装;底层流(plain TAR 时即源流本身)不属于本对象。 + private void DisposeInner() + { + if (!ReferenceEquals(_inner, _sourceStream)) + { + _inner.Dispose(); + } + } + private TarStreamReader OpenTarStream() { return new TarStreamReader(_inner, Encoding.UTF8); @@ -244,7 +264,7 @@ public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationTok public void Dispose() { _sequential?.Dispose(); - _inner.Dispose(); + DisposeInner(); } } @@ -374,17 +394,19 @@ public override void Flush() { } } /// TAR writer (over a compression wrapper stream). TAR requires known entry sizes. -internal sealed class TarWriter : IArchiveWriter +internal sealed class TarWriter : IArchiveWriter, IArchiveSymlinkWriter { private readonly Stream _inner; + private readonly Stream _sourceStream; // 用户/门面持有的底层流:不是我们的所有权 private readonly TarStreamWriter _tar; private readonly ArchiveWriteOptions _options; private bool _finished; - public TarWriter(Stream compressed, ArchiveFormatInfo info, ArchiveWriteOptions options) + public TarWriter(Stream compressed, Stream sourceStream, ArchiveFormatInfo info, ArchiveWriteOptions options) { Info = info; _inner = compressed; + _sourceStream = sourceStream; _options = options; _tar = new TarStreamWriter(compressed, options.EntryNameEncoding); } @@ -396,7 +418,8 @@ public TarWriter(Stream compressed, ArchiveFormatInfo info, ArchiveWriteOptions public void AddDirectoryEntry(string entryName, ArchiveEntryMetadata metadata) { var name = Normalize(entryName).TrimEnd('/'); - _tar.PutNextEntry(name + "/", 0, (metadata.LastWriteTime ?? DateTimeOffset.Now).UtcDateTime, 493, isDirectory: true); // 0755 + _tar.PutNextEntry(name + "/", 0, (metadata.LastWriteTime ?? DateTimeOffset.Now).UtcDateTime, + (int)((metadata.UnixMode ?? 493) & 0x0FFF), isDirectory: true); // 0755 默认 _tar.CloseEntry(); } @@ -410,7 +433,8 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta var size = metadata.Size >= 0 ? metadata.Size : content.Length; var name = Normalize(entryName); - _tar.PutNextEntry(name, size, (metadata.LastWriteTime ?? DateTimeOffset.Now).UtcDateTime, 420, isDirectory: false); // 0644 + _tar.PutNextEntry(name, size, (metadata.LastWriteTime ?? DateTimeOffset.Now).UtcDateTime, + (int)((metadata.UnixMode ?? 420) & 0x0FFF), isDirectory: false); // 0644 默认 var buffer = new byte[81920]; long remaining = size; @@ -430,6 +454,18 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta _tar.CloseEntry(); } + /// 写入符号链接条目(ustar typeflag '2' + linkname)。 + public void AddSymlink(string entryName, string target, ArchiveEntryMetadata metadata) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (target == null) throw new ArgumentNullException(nameof(target)); + + var name = Normalize(entryName); + _tar.PutNextEntry(name, 0, (metadata.LastWriteTime ?? DateTimeOffset.Now).UtcDateTime, + (int)((metadata.UnixMode ?? 0xA1FF) & 0x0FFF), isDirectory: false, linkName: target); + _tar.CloseEntry(); + } + public void Finish(CancellationToken cancellationToken) { if (_finished) return; @@ -464,7 +500,11 @@ public void Dispose() try { Finish(CancellationToken.None); } catch { /* do not mask the original exception */ } } - _inner.Dispose(); + // 只处置我们创建的压缩包装;plain TAR 时 _inner 即源流本身,不归本对象关闭 + if (!ReferenceEquals(_inner, _sourceStream)) + { + _inner.Dispose(); + } } } diff --git a/src/GeneralZip/Formats/Tar/TarIo.cs b/src/GeneralZip/Formats/Tar/TarIo.cs index 26ddc17..ce50cf6 100644 --- a/src/GeneralZip/Formats/Tar/TarIo.cs +++ b/src/GeneralZip/Formats/Tar/TarIo.cs @@ -19,6 +19,9 @@ internal sealed class TarHeaderInfo public int Mode { get; set; } = 420; // 0644 public byte TypeFlag { get; set; } + + /// 符号链接目标(typeflag '2';硬链接/设备等其它类型为空)。 + public string? LinkName { get; set; } } /// ustar 魔数辅助。 @@ -208,6 +211,7 @@ private byte[] ReadDataBytes(long size) Mode = (int)ParseOctal(header, 100, 8, 420), // 0644 默认 Size = ParseOctal(header, 124, 12, 0), TypeFlag = header[156], + LinkName = ReadField(header, 157, 100), }; var mtime = ParseOctal(header, 136, 12, 0); @@ -222,9 +226,14 @@ private byte[] ReadDataBytes(long size) { info.IsDirectory = true; } - else if (typeFlag is (byte)'1' or (byte)'2' or (byte)'3' or (byte)'4' or (byte)'6') + else if (typeFlag == (byte)'2') + { + // 符号链接:目标在 linkname 字段,数据段通常为空 + info.IsDirectory = false; + } + else if (typeFlag is (byte)'1' or (byte)'3' or (byte)'4' or (byte)'6') { - throw new UnsupportedFormatException($"Unsupported TAR entry type '{(char)typeFlag}' (link/device file)"); + throw new UnsupportedFormatException($"Unsupported TAR entry type '{(char)typeFlag}' (hard link/device file)"); } // 校验和:头 148 字节 + 8 空格 + 后 356 字节 @@ -345,15 +354,15 @@ public TarStreamWriter(Stream stream, Encoding encoding) _encoding = encoding ?? throw new ArgumentNullException(nameof(encoding)); } - /// 写入条目头。size 为随后写入的数据字节数(目录为 0)。 - public void PutNextEntry(string name, long size, DateTimeOffset modTime, int mode, bool isDirectory) + /// 写入条目头。size 为随后写入的数据字节数(目录/符号链接为 0)。 + public void PutNextEntry(string name, long size, DateTimeOffset modTime, int mode, bool isDirectory, string? linkName = null) { if (_entryOpen) { throw new InvalidOperationException("Previous entry is still open (CloseEntry)"); } - var header = BuildHeader(name, size, modTime, mode, isDirectory ? (byte)'5' : (byte)'0'); + var header = BuildHeader(name, size, modTime, mode, linkName != null ? (byte)'2' : isDirectory ? (byte)'5' : (byte)'0', linkName); _stream.Write(header, 0, header.Length); _entrySize = size; _remaining = size; @@ -402,7 +411,7 @@ public void Finish() _stream.Flush(); } - internal byte[] BuildHeader(string name, long size, DateTimeOffset modTime, int mode, byte typeFlag) + internal byte[] BuildHeader(string name, long size, DateTimeOffset modTime, int mode, byte typeFlag, string? linkName = null) { var header = new byte[512]; var finalName = name.Replace('\\', '/').TrimStart('/'); @@ -438,6 +447,11 @@ internal byte[] BuildHeader(string name, long size, DateTimeOffset modTime, int } header[156] = typeFlag; + if (linkName != null) + { + WriteNameBytes(header, 157, 100, linkName, _encoding); + } + WriteField(header, 257, 6, "ustar"); WriteField(header, 263, 2, "00"); WriteField(header, 265, 32, "GeneralZip"); diff --git a/src/GeneralZip/Formats/Zip/ZipConstants.cs b/src/GeneralZip/Formats/Zip/ZipConstants.cs index 3be691c..9018189 100644 --- a/src/GeneralZip/Formats/Zip/ZipConstants.cs +++ b/src/GeneralZip/Formats/Zip/ZipConstants.cs @@ -18,6 +18,9 @@ internal static class ZipConstants public const ushort MethodStore = 0; public const ushort MethodDeflate = 8; + public const ushort MethodBZip2 = 12; + public const ushort MethodLzma = 14; + public const ushort MethodZstd = 93; public const ushort MethodEncryptedMarker = 99; public const ushort ExtraFieldZip64 = 0x0001; diff --git a/src/GeneralZip/Formats/Zip/ZipEntryImpl.cs b/src/GeneralZip/Formats/Zip/ZipEntryImpl.cs index d66ccd9..2b11139 100644 --- a/src/GeneralZip/Formats/Zip/ZipEntryImpl.cs +++ b/src/GeneralZip/Formats/Zip/ZipEntryImpl.cs @@ -4,18 +4,26 @@ namespace GeneralZip.Formats.Zip; -/// ZIP 条目的 IArchiveEntry 视图。 -internal sealed class ZipEntryView : IArchiveEntry +/// ZIP 条目的 IArchiveEntry 视图(Unix host 归档额外携带 st_mode)。 +internal sealed class ZipEntryView : IArchiveEntry, IUnixEntry { private readonly ZipCentralEntry _central; private readonly string _fullName; private readonly string? _encryptionAlgorithm; + private readonly uint? _unixMode; public ZipEntryView(ZipCentralEntry central, string fullName, string? encodingAlgorithmName) { _central = central; _fullName = fullName; _encryptionAlgorithm = encodingAlgorithmName; + + // Unix host(3)与 macOS host(19)的 ExternalAttributes 高 16 位为 st_mode + var host = central.VersionMadeBy >> 8; + if (host == 3 || host == 19) + { + _unixMode = central.ExternalAttributes >> 16; + } } public string FullName => _fullName; @@ -46,5 +54,11 @@ public string Name public string? Comment => _central.DecodeComment(null); + /// Unix host 归档携带 st_mode(符号链接判定:(mode & 0xF000) == 0xA000)。 + public uint? UnixMode => _unixMode; + + /// ZIP 的符号链接目标以条目内容承载,头部不携带 → 恒 null(见 IUnixEntry 文档)。 + public string? SymlinkTarget => null; + internal ZipCentralEntry Central => _central; } diff --git a/src/GeneralZip/Formats/Zip/ZipReader.cs b/src/GeneralZip/Formats/Zip/ZipReader.cs index 0ca6d1f..0f3ae73 100644 --- a/src/GeneralZip/Formats/Zip/ZipReader.cs +++ b/src/GeneralZip/Formats/Zip/ZipReader.cs @@ -4,6 +4,7 @@ using System.IO.Compression; using GeneralZip; using GeneralZip.Abstractions; +using GeneralZip.Formats.Codecs; using GeneralZip.Internal; namespace GeneralZip.Formats.Zip; @@ -12,7 +13,7 @@ namespace GeneralZip.Formats.Zip; /// ZIP 读取器。打开时解析中央目录(含 Zip64),条目数据惰性解压。 /// 加密条目经 IEncryptionProvider(extra field 匹配)或 ZipCrypto(标志位匹配)挂接。 /// -internal sealed class ZipReader : IArchiveReader +internal sealed class ZipReader : IArchiveReader, ICancellableEntryStreamProvider { private readonly Stream _stream; private readonly bool _ownsStream; @@ -54,18 +55,21 @@ public ZipReader(Stream stream, ArchiveOpenOptions options, bool ownsStream, Gen public bool IsEncrypted { get; } public Stream OpenEntryStream(IArchiveEntry entry) + => OpenEntryStream(entry, CancellationToken.None); + + public Stream OpenEntryStream(IArchiveEntry entry, CancellationToken cancellationToken) { if (entry is not ZipEntryView view) { throw new ArgumentException("Entry does not belong to this archive (must come from Entries)", nameof(entry)); } - return OpenEntryStreamCore(view); + return OpenEntryStreamCore(view, cancellationToken); } public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationToken cancellationToken) { - using var source = OpenEntryStream(entry); + using var source = OpenEntryStream(entry, cancellationToken); var buffer = new byte[81920]; int read; while ((read = source.Read(buffer, 0, buffer.Length)) > 0) @@ -75,7 +79,7 @@ public void CopyEntryTo(IArchiveEntry entry, Stream destination, CancellationTok } } - private Stream OpenEntryStreamCore(ZipEntryView view) + private Stream OpenEntryStreamCore(ZipEntryView view, CancellationToken cancellationToken) { var central = view.Central; @@ -155,6 +159,9 @@ private Stream OpenEntryStreamCore(ZipEntryView view) { ZipConstants.MethodStore => source, ZipConstants.MethodDeflate => new DeflateStream(source, CompressionMode.Decompress, leaveOpen: true), + ZipConstants.MethodBZip2 => new NativeTempDecodeStream(source, "bzip2", cancellationToken), + ZipConstants.MethodZstd => new NativeTempDecodeStream(source, "zstd", cancellationToken), + ZipConstants.MethodLzma => new NativeTempDecodeStream(source, "lzma-zip", cancellationToken), _ => throw new UnsupportedFormatException($"Unsupported ZIP compression method: {effectiveMethod}", view.FullName), }; @@ -287,7 +294,7 @@ private List BuildEncryptionCandidates(ZipCentralEntry cent private static ushort ExtractRealMethod(ZipCentralEntry central) { - // 真实压缩方法藏在加密 extra field 尾部(0x9901 偏移 5,0x4D53 末 2 字节) + // 真实压缩方法藏在加密 extra field 尾部(0x9901 偏移 5,0x4D53/0x4D54 末 2 字节) var pos = 0; while (pos + 4 <= central.Extra.Length) { @@ -299,7 +306,7 @@ private static ushort ExtractRealMethod(ZipCentralEntry central) return Le.U16(central.Extra, dataStart + 5); } - if (id == 0x4D53 && size >= 2) + if ((id == 0x4D53 || id == 0x4D54) && size >= 2) { return Le.U16(central.Extra, dataStart + size - 2); } diff --git a/src/GeneralZip/Formats/Zip/ZipWriter.cs b/src/GeneralZip/Formats/Zip/ZipWriter.cs index db7839a..1b9aef1 100644 --- a/src/GeneralZip/Formats/Zip/ZipWriter.cs +++ b/src/GeneralZip/Formats/Zip/ZipWriter.cs @@ -5,6 +5,7 @@ using System.Text; using GeneralZip.Abstractions; using GeneralZip.Cryptography; +using GeneralZip.Formats.Codecs; using GeneralZip.Internal; namespace GeneralZip.Formats.Zip; @@ -12,17 +13,24 @@ namespace GeneralZip.Formats.Zip; /// /// ZIP 写入器:顺序写入 + 数据描述符(支持不可寻址输出流)+ 加密挂接 + Zip64 中央目录。 /// -internal sealed class ZipWriter : IArchiveWriter +internal sealed class ZipWriter : IArchiveWriter, IArchiveSymlinkWriter { private readonly Stream _output; private readonly bool _ownsStream; private readonly ArchiveWriteOptions _options; private readonly IEncryptionProvider? _encryption; + private readonly GeneralZipEncryptionRegistry _encryptionRegistry; + private readonly byte[]? _recipientPublicKey; private readonly bool _utf8Names; private readonly List _centrals = new(); private readonly CountingOutput _counter; private bool _finished; + // 并行分片压缩状态(MaxDegreeOfParallelism > 1 时启用) + private readonly List? _staged; + private readonly SemaphoreSlim? _stagingSemaphore; + private readonly PrivateTempDirectory? _stagingDirectory; + public ZipWriter(Stream output, ArchiveWriteOptions options, bool ownsStream, GeneralZipEncryptionRegistry? encryption = null) { _output = output ?? throw new ArgumentNullException(nameof(output)); @@ -30,13 +38,14 @@ public ZipWriter(Stream output, ArchiveWriteOptions options, bool ownsStream, Ge _ownsStream = ownsStream; _counter = new CountingOutput(output); _utf8Names = IsUtf8(options.EntryNameEncoding); + _encryptionRegistry = encryption ?? GeneralZipEncryptionRegistry.Default; if (!output.CanWrite) { throw new ArgumentException("Output stream must be writable", nameof(output)); } - var provider = options.ResolveProvider(encryption ?? GeneralZipEncryptionRegistry.Default); + var provider = options.ResolveProvider(_encryptionRegistry); if (provider != null && provider.AlgorithmId == "ZipCrypto" && !options.AllowWeakZipCrypto) { throw new NotSupportedException( @@ -44,6 +53,14 @@ public ZipWriter(Stream output, ArchiveWriteOptions options, bool ownsStream, Ge } _encryption = provider; + _recipientPublicKey = ParseRecipientKey(options.RecipientPublicKey); + + if (options.MaxDegreeOfParallelism > 1) + { + _staged = new List(); + _stagingSemaphore = new SemaphoreSlim(options.MaxDegreeOfParallelism); + _stagingDirectory = new PrivateTempDirectory("gzp-stage"); + } } public ArchiveFormatInfo Info { get; } = new( @@ -66,21 +83,59 @@ public void AddDirectoryEntry(string entryName, ArchiveEntryMetadata metadata) ZipTime.ToDos(metadata.LastWriteTime ?? DateTimeOffset.Now, out var dosTime, out var dosDate); var offset = _counter.TotalBytes; - WriteLocalHeader(name, ZipConstants.MethodStore, dosTime, dosDate, encryptionExtra: null, encrypted: false); - WriteDescriptor(crc: 0, compSize: 0, uncompSize: 0); + WriteLocalHeader(_counter, name, ZipConstants.MethodStore, dosTime, dosDate, encryptionExtra: null, encrypted: false); + WriteDescriptor(_counter, crc: 0, compSize: 0, uncompSize: 0); _centrals.Add(new CentralRecord(name, ZipConstants.MethodStore, dosTime, dosDate, 0, 0, 0, offset, metadata, null, null, isDirectory: true, isEncrypted: false)); } + /// 写入符号链接条目:目标路径文本作为条目内容(Store),Unix 模式 S_IFLNK|0777。 + public void AddSymlink(string entryName, string target, ArchiveEntryMetadata metadata) + { + if (entryName == null) throw new ArgumentNullException(nameof(entryName)); + if (target == null) throw new ArgumentNullException(nameof(target)); + if (_encryption != null) + { + throw new NotSupportedException("ZIP symlink entries cannot be encrypted"); + } + + var name = NormalizeName(entryName); + ZipTime.ToDos(metadata.LastWriteTime ?? DateTimeOffset.Now, out var dosTime, out var dosDate); + + var targetBytes = _options.EntryNameEncoding.GetBytes(target); + var crc = Crc32.Compute(targetBytes); + var offset = _counter.TotalBytes; + WriteLocalHeader(_counter, name, ZipConstants.MethodStore, dosTime, dosDate, null, encrypted: false); + + _counter.Mark(); + _counter.Write(targetBytes, 0, targetBytes.Length); + var compSize = _counter.BytesSinceMark; + + WriteDescriptor(_counter, crc, compSize, targetBytes.Length); + + var symlinkMeta = metadata.Clone(); + symlinkMeta.UnixMode ??= 0xA1FF; // S_IFLNK | 0777 + _centrals.Add(new CentralRecord(name, ZipConstants.MethodStore, dosTime, dosDate, + crc, compSize, targetBytes.Length, offset, symlinkMeta, null, null, isDirectory: false, isEncrypted: false)); + } + public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata metadata, CancellationToken cancellationToken) { if (entryName == null) throw new ArgumentNullException(nameof(entryName)); if (content == null) throw new ArgumentNullException(nameof(content)); + if (_stagingSemaphore != null) + { + AddEntryStaged(entryName, content, metadata, cancellationToken); + return; + } + var name = NormalizeName(entryName); var isEmpty = metadata.Size == 0 || (content.CanSeek && content.Length == 0); var isStore = _options.Level == CompressionLevelChoice.NoCompression || isEmpty; - var method = (ushort)(isStore ? ZipConstants.MethodStore : ZipConstants.MethodDeflate); + var method = isStore + ? ZipConstants.MethodStore + : MapMethod(_options.ZipCompressionMethod); ZipTime.ToDos(metadata.LastWriteTime ?? DateTimeOffset.Now, out var dosTime, out var dosDate); @@ -89,11 +144,13 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta if (_encryption != null) { plan = _encryption.PrepareWrite(new EncryptionWriteContext( - _options.Password!, name, crc32: null, plainSize: metadata.Size, method, dosTime, _options.KdfIterations)); + _options.Password, name, crc32: null, plainSize: metadata.Size, method, dosTime, + _options.KdfIterations, _options.ResolveKdf(_encryptionRegistry), _recipientPublicKey)); } var offset = _counter.TotalBytes; WriteLocalHeader( + _counter, name, plan != null && plan.ExtraFieldId != null ? (ushort)ZipConstants.MethodEncryptedMarker : method, dosTime, @@ -116,15 +173,7 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta } else { - var deflate = new DeflateStream(pipeline, MapLevel(_options.Level), leaveOpen: true); - try - { - CopyPlain(crcStream, deflate, cancellationToken); - } - finally - { - deflate.Dispose(); // 刷出 deflate 终结块 - } + CompressInto(crcStream, pipeline, cancellationToken); } } finally @@ -140,7 +189,7 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta var crc = crcStream.Crc; var uncompSize = crcStream.BytesPassed; - WriteDescriptor(crc, compressedBytes, uncompSize); + WriteDescriptor(_counter, crc, compressedBytes, uncompSize); _centrals.Add(new CentralRecord( name, plan != null && plan.ExtraFieldId != null ? (ushort)ZipConstants.MethodEncryptedMarker : method, @@ -148,6 +197,194 @@ public void AddEntry(string entryName, Stream content, ArchiveEntryMetadata meta plan?.ExtraFieldData, plan?.ExtraFieldId, isDirectory: false, isEncrypted: plan != null)); } + // ---------- 并行分片压缩 ---------- + + /// + /// 分片并行:内容先顺序拷贝到明文临时文件(门面事件/进度仍按调用序触发), + /// 随后后台任务把明文压缩为完整分片(local header + 数据 + descriptor), + /// Finish 时按添加顺序装配并回填偏移。并发度由信号量限流。 + /// + private void AddEntryStaged(string entryName, Stream content, ArchiveEntryMetadata metadata, CancellationToken ct) + { + var name = NormalizeName(entryName); + var isEmpty = metadata.Size == 0 || (content.CanSeek && content.Length == 0); + var isStore = _options.Level == CompressionLevelChoice.NoCompression || isEmpty; + var method = isStore ? ZipConstants.MethodStore : MapMethod(_options.ZipCompressionMethod); + ZipTime.ToDos(metadata.LastWriteTime ?? DateTimeOffset.Now, out var dosTime, out var dosDate); + + EntryEncryptionPlan? plan = null; + if (_encryption != null) + { + plan = _encryption.PrepareWrite(new EncryptionWriteContext( + _options.Password, name, crc32: null, plainSize: metadata.Size, method, dosTime, + _options.KdfIterations, _options.ResolveKdf(_encryptionRegistry), _recipientPublicKey)); + } + + // 1) 顺序捕获明文(信号量限流:槽满时阻塞生产端) + _stagingSemaphore!.Wait(ct); + var plaintextPath = _stagingDirectory!.FilePath($"{Guid.NewGuid():N}.in"); + var fragmentPath = _stagingDirectory.FilePath($"{Guid.NewGuid():N}.frag"); + + var staged = new StagedEntry(name, method, dosTime, dosDate, metadata, plan, plaintextPath, fragmentPath); + _staged!.Add(staged); + + try + { + using (var plain = new FileStream(plaintextPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536, useAsync: false)) + { + CopyPlain(content, plain, ct); + } + } + catch + { + _stagingSemaphore.Release(); + TryDelete(plaintextPath); + TryDelete(fragmentPath); + throw; + } + + // 2) 后台压缩:明文临时文件 → 完整分片 + staged.Task = Task.Run(() => + { + try + { + CompressStagedFragment(staged, isStore, ct); + } + catch (Exception ex) + { + staged.Error = ex; + } + finally + { + _stagingSemaphore.Release(); + TryDelete(plaintextPath); + } + }, CancellationToken.None); + } + + private void CompressStagedFragment(StagedEntry staged, bool isStore, CancellationToken ct) + { + using var fragmentStream = new FileStream(staged.FragmentPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536, useAsync: false); + var fragment = new CountingOutput(fragmentStream); + + var plan = staged.Plan; + WriteLocalHeader( + fragment, + staged.Name, + plan != null && plan.ExtraFieldId != null ? (ushort)ZipConstants.MethodEncryptedMarker : staged.Method, + staged.DosTime, + staged.DosDate, + plan?.ExtraFieldData, + plan != null, + plan?.ExtraFieldId); + + using var plain = new FileStream(staged.PlaintextPath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); + var crcStream = new Crc32Stream(plain, leaveOpen: true); + + fragment.Mark(); + Stream pipeline = plan != null ? plan.EncryptionStreamFactory(fragment) : fragment; + try + { + if (isStore) + { + CopyPlain(crcStream, pipeline, ct); + } + else + { + CompressInto(crcStream, pipeline, ct); + } + } + finally + { + if (!ReferenceEquals(pipeline, fragment)) + { + pipeline.Dispose(); + } + } + + staged.Crc = crcStream.Crc; + staged.UncompressedSize = crcStream.BytesPassed; + staged.CompressedSize = fragment.BytesSinceMark; + WriteDescriptor(fragment, staged.Crc, staged.CompressedSize, staged.UncompressedSize); + fragmentStream.Flush(); + } + + private void AssembleStagedEntries(CancellationToken ct) + { + foreach (var staged in _staged!) + { + staged.Task!.Wait(ct); + } + + // 任一分片失败则放弃装配(临时文件清理后原样抛出首个错误) + var firstError = _staged.FirstOrDefault(s => s.Error != null)?.Error; + if (firstError != null) + { + foreach (var staged in _staged) + { + TryDelete(staged.PlaintextPath); + TryDelete(staged.FragmentPath); + } + + throw firstError; + } + + foreach (var staged in _staged) + { + var offset = _counter.TotalBytes; + using (var fragment = File.OpenRead(staged.FragmentPath)) + { + CopyPlain(fragment, _counter, ct); + } + + TryDelete(staged.FragmentPath); + + _centrals.Add(new CentralRecord( + staged.Name, + staged.Plan != null && staged.Plan.ExtraFieldId != null ? (ushort)ZipConstants.MethodEncryptedMarker : staged.Method, + staged.DosTime, staged.DosDate, staged.Crc, staged.CompressedSize, staged.UncompressedSize, offset, + staged.Metadata, + staged.Plan?.ExtraFieldData, staged.Plan?.ExtraFieldId, isDirectory: false, isEncrypted: staged.Plan != null)); + } + + _staged.Clear(); + } + + private static void TryDelete(string path) + { + try { File.Delete(path); } catch { /* 清理失败忽略 */ } + } + + private sealed class StagedEntry + { + public StagedEntry(string name, ushort method, uint dosTime, uint dosDate, + ArchiveEntryMetadata metadata, EntryEncryptionPlan? plan, string plaintextPath, string fragmentPath) + { + Name = name; + Method = method; + DosTime = dosTime; + DosDate = dosDate; + Metadata = metadata; + Plan = plan; + PlaintextPath = plaintextPath; + FragmentPath = fragmentPath; + } + + public string Name { get; } + public ushort Method { get; } + public uint DosTime { get; } + public uint DosDate { get; } + public ArchiveEntryMetadata Metadata { get; } + public EntryEncryptionPlan? Plan { get; } + public string PlaintextPath { get; } + public string FragmentPath { get; } + public Task Task { get; set; } = null!; + public uint Crc { get; set; } + public long CompressedSize { get; set; } + public long UncompressedSize { get; set; } + public Exception? Error { get; set; } + } + public void Finish(CancellationToken cancellationToken) { if (_finished) return; @@ -155,6 +392,11 @@ public void Finish(CancellationToken cancellationToken) cancellationToken.ThrowIfCancellationRequested(); + if (_staged != null) + { + AssembleStagedEntries(cancellationToken); + } + long cdOffset = _counter.TotalBytes; foreach (var central in _centrals) { @@ -207,6 +449,7 @@ public void Finish(CancellationToken cancellationToken) Buffer.BlockCopy(comment, 0, eocd, 22, comment.Length); _counter.Write(eocd, 0, eocd.Length); _output.Flush(); + _stagingDirectory?.Dispose(); } public Task FinishAsync(CancellationToken cancellationToken) @@ -223,7 +466,7 @@ public ValueTask DisposeAsync() // ---------- 内部 ---------- - private void WriteLocalHeader(string name, ushort method, uint dosTime, uint dosDate, + private void WriteLocalHeader(CountingOutput target, string name, ushort method, uint dosTime, uint dosDate, byte[]? encryptionExtra, bool encrypted, ushort? extraFieldId = null) { var nameBytes = EncodeName(name); @@ -262,10 +505,10 @@ private void WriteLocalHeader(string name, ushort method, uint dosTime, uint dos Buffer.BlockCopy(extra, 0, header, 30 + nameBytes.Length, extra.Length); } - _counter.Write(header, 0, header.Length); + target.Write(header, 0, header.Length); } - private void WriteDescriptor(uint crc, long compSize, long uncompSize) + private void WriteDescriptor(CountingOutput target, uint crc, long compSize, long uncompSize) { var zip64Sizes = compSize > uint.MaxValue || uncompSize > uint.MaxValue; var descriptor = new byte[zip64Sizes ? 24 : 16]; @@ -282,7 +525,7 @@ private void WriteDescriptor(uint crc, long compSize, long uncompSize) Le.Put32(descriptor, 12, (uint)uncompSize); } - _counter.Write(descriptor, 0, descriptor.Length); + target.Write(descriptor, 0, descriptor.Length); } private void WriteCentralHeader(CentralRecord central) @@ -320,9 +563,12 @@ private void WriteCentralHeader(CentralRecord central) extraLen += part.Length; } - // MS-DOS host(0x00)+ 规范版本(zip64 条目 45,否则 20) - var versionMadeBy = (ushort)(0x00 << 8 | (needsZip64 ? 45 : 20)); - var externalAttrs = central.IsDirectory ? 0x10u : 0x20u; + // host:携带 Unix 模式时声明为 Unix(3);否则 MS-DOS(0x00)。zip64 条目版本 45,否则 20 + var host = central.UnixMode.HasValue ? 3u : 0u; + var versionMadeBy = (ushort)(host << 8 | (needsZip64 ? 45 : 20)); + var externalAttrs = central.UnixMode.HasValue + ? central.UnixMode.Value << 16 + : central.IsDirectory ? 0x10u : 0x20u; var header = new byte[46 + nameBytes.Length + extraLen + commentBytes.Length]; Le.Put32(header, 0, ZipConstants.CentralHeaderSignature); @@ -371,6 +617,52 @@ private static void CopyPlain(Stream source, Stream target, CancellationToken ct } } + /// 把明文流压缩进管道(方法由选项决定;Deflate 走托管,BZip2/Zstd/Lzma 走原生核心)。 + private void CompressInto(Stream source, Stream destination, CancellationToken ct) + { + switch (_options.ZipCompressionMethod) + { + case ZipCompressionMethodChoice.BZip2: + NativeCodecRouter.CompressStream(source, destination, "bzip2", level: 0, ct); + break; + case ZipCompressionMethodChoice.Zstd: + NativeCodecRouter.CompressStream(source, destination, "zstd", MapZstdLevel(_options.Level), ct); + break; + case ZipCompressionMethodChoice.Lzma: + NativeCodecRouter.CompressStream(source, destination, "lzma-zip", level: 0, ct); + break; + default: + { + var deflate = new DeflateStream(destination, MapLevel(_options.Level), leaveOpen: true); + try + { + CopyPlain(source, deflate, ct); + } + finally + { + deflate.Dispose(); // 刷出 deflate 终结块 + } + + break; + } + } + } + + private static ushort MapMethod(ZipCompressionMethodChoice choice) => choice switch + { + ZipCompressionMethodChoice.BZip2 => ZipConstants.MethodBZip2, + ZipCompressionMethodChoice.Zstd => ZipConstants.MethodZstd, + ZipCompressionMethodChoice.Lzma => ZipConstants.MethodLzma, + _ => ZipConstants.MethodDeflate, + }; + + private static int MapZstdLevel(CompressionLevelChoice level) => level switch + { + CompressionLevelChoice.Fastest => 3, + CompressionLevelChoice.SmallestSize => 19, + _ => 6, + }; + private static CompressionLevel MapLevel(CompressionLevelChoice level) => level switch { CompressionLevelChoice.Fastest => CompressionLevel.Fastest, @@ -380,6 +672,25 @@ private static void CopyPlain(Stream source, Stream target, CancellationToken ct private static bool IsUtf8(Encoding encoding) => encoding is UTF8Encoding; + /// 解析接收方公钥 hex("04||X||Y" 130 字符或 "X||Y" 128 字符)。 + private static byte[]? ParseRecipientKey(string? hex) + { + if (string.IsNullOrWhiteSpace(hex)) + { + return null; + } + + var key = Cryptography.Sm2KeyPair.ParsePublicKeyHex(hex); + if (key == null) + { + throw new ArgumentException( + "RecipientPublicKey must be a hex-encoded SM2 public key: '04||X||Y' (130 chars) or 'X||Y' (128 chars)", + "RecipientPublicKey"); + } + + return key; + } + private static string NormalizeName(string name) { var n = name.Replace('\\', '/').TrimStart('/'); @@ -407,6 +718,8 @@ public void Dispose() } } + _stagingDirectory?.Dispose(); + if (_ownsStream) { _output.Dispose(); @@ -432,6 +745,7 @@ public CentralRecord(string name, ushort method, uint dosTime, uint dosDate, uin EncryptionExtraFieldId = encryptionExtraFieldId; IsDirectory = isDirectory; IsEncrypted = isEncrypted; + UnixMode = metadata.UnixMode; } public string Name { get; } @@ -447,5 +761,6 @@ public CentralRecord(string name, ushort method, uint dosTime, uint dosDate, uin public ushort? EncryptionExtraFieldId { get; } public bool IsDirectory { get; } public bool IsEncrypted { get; } + public uint? UnixMode { get; } } } diff --git a/src/GeneralZip/GeneralZip.cs b/src/GeneralZip/GeneralZip.cs index 457374b..caae7ae 100644 --- a/src/GeneralZip/GeneralZip.cs +++ b/src/GeneralZip/GeneralZip.cs @@ -8,43 +8,18 @@ namespace GeneralZip; /// -/// 组件启动引导与门面入口(与组件同名)。 +/// 静态门面入口(与组件同名,零初始化:内置格式/加密算法与原生能力均在首次使用时隐式装配)。 /// -/// 完成内置格式/加密算法注册(幂等,可重复调用); -/// 随后即可使用一行式 API(/ 等), +/// 直接使用一行式 API(/ 等), /// 需要事件与精细控制时使用 / 。 /// /// -/// GeneralZip.Initialize(); /// await GeneralZip.CompressAsync(@"C:\data", @"D:\out.zip", /// o => { o.EncryptionAlgorithm = "SM4-GM"; o.Password = "p@ss"; }); /// /// public static class GeneralZip { - private static int _initialized; - - /// - /// 启动引导:确保内置格式提供者与加密算法已注册(幂等、线程安全)。 - /// 同时尝试加载内置 Rust 原生核心(7z/RAR/原生编解码);核心二进制缺失时静默降级, - /// 纯托管能力不受影响(可用 探测)。 - /// - public static void Initialize() - { - if (Interlocked.Exchange(ref _initialized, 1) == 1) - { - return; - } - - // 触发两个默认注册表的静态装配 - _ = GeneralZipFormatRegistry.Default; - _ = GeneralZipEncryptionRegistry.Default; - - // 原生引导(幂等;加载失败仅返回 false,不抛异常)。 - // global:: 限定:类名 GeneralZip 会遮蔽同名命名空间。 - _ = global::GeneralZip.Native.GeneralZipNative.Initialize(); - } - /// 组件版本。 public static Version Version => typeof(GeneralZip).Assembly.GetName().Version ?? new Version(0, 0, 0); @@ -54,11 +29,19 @@ public static void Initialize() /// 默认加密算法注册表(ZipCrypto / WinZip AES / SM4-GM 已内置)。 public static GeneralZipEncryptionRegistry Encryption => GeneralZipEncryptionRegistry.Default; - /// 探测归档格式:魔数优先,扩展名兜底。无法识别返回 null。 + /// 探测归档格式:魔数优先,扩展名兜底;*.NNN 分卷按拼接流探测。无法识别返回 null。 public static ArchiveFormatInfo? DetectFormat(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); var reg = GeneralZipFormatRegistry.Default; + + var volumes = global::GeneralZip.Internal.SplitVolumeLocator.Resolve(path); + if (volumes != null) + { + using var volumeStream = new global::GeneralZip.Internal.MultiVolumeStream(volumes); + return (reg.Detect(volumeStream) ?? reg.DetectByExtension(volumes[0]))?.Info; + } + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); return (reg.Detect(stream) ?? reg.DetectByExtension(path))?.Info; } @@ -153,4 +136,314 @@ public static ArchiveResult Test( using var reader = GeneralZipReader.Open(archivePath, configure); return reader.TestAll(new ExtractionOptions { ErrorPolicy = ErrorPolicy.SkipAll }, cancellationToken); } + + // ---------- 流式门面(Stream → Stream,不落盘) ---------- + + /// 把源流压缩为归档流(单条目)。格式由 formatName 显式指定(流无法从扩展名推断)。 + /// 明文源流(读取到 EOF)。 + /// 归档输出流(保持打开,由调用方处置)。 + /// 格式名(如 "ZIP"、"GZIP")。 + /// 条目名;null 为 "content"。 + public static void Compress( + Stream source, + Stream output, + string formatName, + string? entryName = null, + Action? configure = null, + CancellationToken cancellationToken = default) + => CompressAsync(source, output, formatName, entryName, configure, cancellationToken).GetAwaiter().GetResult(); + + /// 异步把源流压缩为归档流(单条目)。 + public static async Task CompressAsync( + Stream source, + Stream output, + string formatName, + string? entryName = null, + Action? configure = null, + CancellationToken cancellationToken = default) + { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (output == null) throw new ArgumentNullException(nameof(output)); + if (formatName == null) throw new ArgumentNullException(nameof(formatName)); + + using (var writer = GeneralZipWriter.CreateNew(output, formatName, configure)) + { + if (source.CanSeek) + { + var remaining = source.Length - source.Position; + if (remaining < 0) throw new IOException("Stream position is beyond its length"); + await writer.AddStreamAsync(entryName ?? "content", source, remaining, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + else + { + using var tempDirectory = new Internal.PrivateTempDirectory("gzp-stream"); + var tempPath = tempDirectory.FilePath("input.bin"); + using (var buffered = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + await source.CopyToAsync(buffered, 81920, cancellationToken).ConfigureAwait(false); + } + + using var bufferedInput = File.OpenRead(tempPath); + await writer.AddStreamAsync(entryName ?? "content", bufferedInput, bufferedInput.Length, cancellationToken: cancellationToken) + .ConfigureAwait(false); + } + + await writer.FinishAsync(cancellationToken).ConfigureAwait(false); + } + } + + /// 从归档流解压到目录(魔数自动探测格式,扩展名兜底)。 + public static ArchiveResult Extract( + Stream input, + string destinationDirectory, + string? formatName = null, + Action? configure = null, + ExtractionOptions? extraction = null, + CancellationToken cancellationToken = default) + => ExtractAsync(input, destinationDirectory, formatName, configure, extraction, cancellationToken).GetAwaiter().GetResult(); + + /// 异步从归档流解压到目录。 + public static async Task ExtractAsync( + Stream input, + string destinationDirectory, + string? formatName = null, + Action? configure = null, + ExtractionOptions? extraction = null, + CancellationToken cancellationToken = default) + { + if (input == null) throw new ArgumentNullException(nameof(input)); + if (destinationDirectory == null) throw new ArgumentNullException(nameof(destinationDirectory)); + + using var reader = GeneralZipReader.Open(input, formatName, configure); + return await Task.Run( + () => reader.ExtractToDirectory(destinationDirectory, extraction, cancellationToken), + cancellationToken).ConfigureAwait(false); + } + + /// 完整性测试(归档流版)。 + public static ArchiveResult Test( + Stream input, + string? formatName = null, + Action? configure = null, + CancellationToken cancellationToken = default) + { + using var reader = GeneralZipReader.Open(input, formatName, configure); + return reader.TestAll(new ExtractionOptions { ErrorPolicy = ErrorPolicy.SkipAll }, cancellationToken); + } + + // ---------- 追加 / 删除 / 转换(读出→重写语义) ---------- + + /// + /// 向既有归档追加文件或目录(读出→重写语义:源归档条目被忠实复制,新内容按选项追加)。 + /// 源归档加密时须用 提供口令(同时用于读取与重新加密); + /// 原条目被重新加密,原加密参数(盐/IV)不保留。RAR 等只读格式不支持。 + /// + public static void Append( + string archivePath, + string sourcePath, + Action? configure = null, + CancellationToken cancellationToken = default) + => AppendAsync(archivePath, sourcePath, configure, cancellationToken).GetAwaiter().GetResult(); + + /// 异步向既有归档追加文件或目录。 + public static Task AppendAsync( + string archivePath, + string sourcePath, + Action? configure = null, + CancellationToken cancellationToken = default) + => RewriteArchiveCore( + archivePath, + openConfigure: PasswordFromWriteOptions(configure), + populate: writer => Repack.AddSourcePath(writer, sourcePath, cancellationToken), + keepEntry: null, + writeConfigure: configure, + replaceOriginal: true, + cancellationToken, + inheritEncryption: true); + + /// + /// 从归档删除条目(读出→重写语义)。按精确条目名(,OrdinalIgnoreCase) + /// 或谓词()匹配;两者可同时提供(并集)。 + /// + public static void Remove( + string archivePath, + IEnumerable? entryNames = null, + Func? predicate = null, + Action? configure = null, + CancellationToken cancellationToken = default) + => RemoveAsync(archivePath, entryNames, predicate, configure, cancellationToken).GetAwaiter().GetResult(); + + /// 异步从归档删除条目。 + public static Task RemoveAsync( + string archivePath, + IEnumerable? entryNames = null, + Func? predicate = null, + Action? configure = null, + CancellationToken cancellationToken = default) + { + var nameSet = entryNames != null + ? new HashSet(entryNames, StringComparer.OrdinalIgnoreCase) + : null; + if (nameSet == null && predicate == null) + { + throw new ArgumentException("Provide entryNames or predicate", nameof(entryNames)); + } + + return RewriteArchiveCore( + archivePath, + configure, + populate: null, + keepEntry: entry => + (nameSet != null && nameSet.Contains(entry.FullName)) + || (predicate != null && predicate(entry)) + ? false + : true, + writeConfigure: null, + replaceOriginal: true, + cancellationToken, + inheritEncryption: true); + } + + /// + /// 跨格式转换归档(读出→重写:全部条目复制进目标格式,目标格式由目标路径扩展名决定)。 + /// 加密不跨格式保留;需重新加密时用 指定算法与口令。 + /// + public static void Convert( + string sourceArchive, + string targetArchive, + Action? writeConfigure = null, + Action? openConfigure = null, + CancellationToken cancellationToken = default) + => ConvertAsync(sourceArchive, targetArchive, writeConfigure, openConfigure, cancellationToken).GetAwaiter().GetResult(); + + /// 异步跨格式转换归档。 + public static Task ConvertAsync( + string sourceArchive, + string targetArchive, + Action? writeConfigure = null, + Action? openConfigure = null, + CancellationToken cancellationToken = default) + => RewriteArchiveCore( + sourceArchive, + openConfigure, + populate: null, + keepEntry: null, + writeConfigure, + replaceOriginal: false, + cancellationToken, + targetArchive: targetArchive); + + private static Action? PasswordFromWriteOptions(Action? configure) + { + if (configure == null) + { + return null; + } + + var probe = new ArchiveWriteOptions(); + configure(probe); + if (probe.Password == null) + { + return null; + } + + return o => o.Password = probe.Password; + } + + /// 重写核心:读源归档 → 复制条目 → populate 追加 → Finish →(可选)替换原文件。 + private static async Task RewriteArchiveCore( + string sourceArchive, + Action? openConfigure, + Action? populate, + Func? keepEntry, + Action? writeConfigure, + bool replaceOriginal, + CancellationToken cancellationToken, + string? targetArchive = null, + bool inheritEncryption = false) + { + if (sourceArchive == null) throw new ArgumentNullException(nameof(sourceArchive)); + + var target = replaceOriginal ? sourceArchive : targetArchive + ?? throw new ArgumentNullException(nameof(targetArchive)); + if (replaceOriginal && Internal.VolumeSplitStream.IsFirstVolumePath(sourceArchive)) + { + throw new NotSupportedException("Append and Remove do not support in-place rewriting of split ZIP archives"); + } + + string? configuredReadPassword = null; + Action? observedOpenConfigure = openConfigure == null + ? null + : options => + { + openConfigure(options); + configuredReadPassword = options.Password; + }; + using var reader = GeneralZipReader.Open(sourceArchive, observedOpenConfigure); + // 追加/删除保持源格式;转换(replaceOriginal=false)由目标路径扩展名推断目标格式 + var formatName = replaceOriginal ? reader.Format.Name : null; + + // 追加加密归档的安全默认:给了口令但未指定算法时,继承源归档的加密算法, + // 避免"口令仅用于读取、产物静默变成明文"的坑。 + string? inheritedAlgorithm = null; + string? inheritedPassword = null; + if (inheritEncryption) + { + var probe = new ArchiveWriteOptions(); + writeConfigure?.Invoke(probe); + if (probe.EncryptionAlgorithm == null && probe.EncryptionProvider == null) + { + var algorithms = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var e in reader.Entries) + { + if (!e.IsDirectory && e.IsEncrypted && e.EncryptionAlgorithm != null) + { + algorithms.Add(e.EncryptionAlgorithm); + } + } + + if (algorithms.Count > 1) + throw new NotSupportedException("Cannot safely rewrite an archive containing multiple encryption algorithms"); + inheritedAlgorithm = algorithms.SingleOrDefault(); + inheritedPassword = probe.Password ?? configuredReadPassword; + if (inheritedAlgorithm != null && inheritedPassword == null) + throw new InvalidOperationException("Rewriting encrypted archives requires a password for re-encryption"); + } + } + + // 临时文件保留源名后缀(复合扩展名 ".tar.gz" 可被 DetectByExtension 正确推断) + var finalPath = Path.GetFullPath(target); + var tempPath = Repack.TempSiblingPath(finalPath); + try + { + using (var writer = GeneralZipWriter.CreateNew(tempPath, o => + { + writeConfigure?.Invoke(o); + if (inheritedAlgorithm != null && o.EncryptionAlgorithm == null && o.EncryptionProvider == null) + { + o.EncryptionAlgorithm = inheritedAlgorithm; + o.Password ??= inheritedPassword; + if (string.Equals(inheritedAlgorithm, "SM2-GM", StringComparison.OrdinalIgnoreCase) + && o.RecipientPublicKey == null && o.Password != null) + { + o.RecipientPublicKey = Cryptography.Sm2KeyPair.FromPrivateKeyHex(o.Password).PublicKeyHex; + } + } + }, formatName)) + { + Repack.CopyEntries(reader, writer, keepEntry, cancellationToken); + populate?.Invoke(writer); + await writer.FinishAsync(cancellationToken).ConfigureAwait(false); + } + + // 覆盖原文件前先关闭源归档句柄(FileShare.Read 下 Move-overwrite 会失败) + reader.Dispose(); + Repack.MoveOverwrite(tempPath, finalPath); + } + finally + { + try { if (File.Exists(tempPath)) File.Delete(tempPath); } catch { /* 清理失败忽略 */ } + } + } } diff --git a/src/GeneralZip/GeneralZip.csproj b/src/GeneralZip/GeneralZip.csproj index 2078c1f..bc78974 100644 --- a/src/GeneralZip/GeneralZip.csproj +++ b/src/GeneralZip/GeneralZip.csproj @@ -16,6 +16,8 @@ true snupkg MIT + + true @@ -33,7 +35,14 @@ Pack="true" PackagePath="runtimes" Visible="false" - Condition="Exists('runtimes\win-x64\native\generalzip_native.dll')" /> + Condition="Exists('runtimes\win-x64\native\generalzip_native.dll') + Or Exists('runtimes\linux-x64\native\libgeneralzip_native.so') + Or Exists('runtimes\linux-musl-x64\native\libgeneralzip_native.so') + Or Exists('runtimes\linux-arm64\native\libgeneralzip_native.so') + Or Exists('runtimes\osx-x64\native\libgeneralzip_native.dylib') + Or Exists('runtimes\osx-arm64\native\libgeneralzip_native.dylib') + Or Exists('runtimes\win-arm64\native\generalzip_native.dll') + Or Exists('runtimes\win-x86\native\generalzip_native.dll')" /> diff --git a/src/GeneralZip/GlobMatcher.cs b/src/GeneralZip/GlobMatcher.cs new file mode 100644 index 0000000..4201532 --- /dev/null +++ b/src/GeneralZip/GlobMatcher.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; + +namespace GeneralZip; + +/// +/// 极简 glob 匹配器(用于条目过滤)。 +/// 语法:* 匹配单层内任意字符(不跨 '/');** 跨目录层;? 匹配单个非 '/' 字符; +/// [abc]/[a-z] 字符类;其余字面匹配。大小写不敏感(Windows 习惯)。 +/// +public static class GlobMatcher +{ + public static bool Matches(string path, IReadOnlyList? includePatterns, IReadOnlyList? excludePatterns) + { + if (includePatterns != null && includePatterns.Count > 0) + { + var included = false; + foreach (var pattern in includePatterns) + { + if (IsMatch(path, pattern)) + { + included = true; + break; + } + } + + if (!included) + { + return false; + } + } + + if (excludePatterns != null) + { + foreach (var pattern in excludePatterns) + { + if (IsMatch(path, pattern)) + { + return false; + } + } + } + + return true; + } + + public static bool IsMatch(string path, string pattern) + { + if (path == null) throw new ArgumentNullException(nameof(path)); + if (pattern == null) throw new ArgumentNullException(nameof(pattern)); + + return MatchHere(path, 0, pattern, 0); + } + + private static bool MatchHere(string text, int t, string pattern, int p) + { + while (p < pattern.Length) + { + var c = pattern[p]; + if (c == '*') + { + // "**" 跨目录层 + if (p + 1 < pattern.Length && pattern[p + 1] == '*') + { + var pp = p + 2; + // 收敛 "**/":可匹配零层("a/**/b" 中 "a/b")或任意多层 + if (pp < pattern.Length && pattern[pp] == '/') + { + if (MatchHere(text, t, pattern, pp + 1)) + { + return true; + } + + // 只允许在 '/' 边界切层 + for (var i = t + 1; i <= text.Length; i++) + { + if (text[i - 1] != '/') + { + continue; + } + + if (MatchHere(text, i, pattern, pp + 1)) + { + return true; + } + } + + return false; + } + + // 结尾或裸 "**":任意后缀 + for (var i = t; i <= text.Length; i++) + { + if (MatchHere(text, i, pattern, pp)) + { + return true; + } + } + + return false; + } + + // 单星:不跨 '/' + for (var i = t; i <= text.Length; i++) + { + if (MatchHere(text, i, pattern, p + 1)) + { + return true; + } + + if (i >= text.Length || text[i] == '/') + { + break; + } + } + + return false; + } + + if (t >= text.Length) + { + return false; + } + + switch (c) + { + case '?': + if (text[t] == '/') + { + return false; + } + + t++; + p++; + break; + case '[': + var (matched, next) = MatchClass(pattern, p, text[t]); + if (!matched) + { + return false; + } + + t++; + p = next; + break; + default: + if (!EqualsIgnoreCase(c, text[t])) + { + return false; + } + + t++; + p++; + break; + } + } + + return t == text.Length; + } + + private static bool EqualsIgnoreCase(char a, char b) => + char.ToLowerInvariant(a) == char.ToLowerInvariant(b); + + /// 匹配字符类;返回 (是否匹配, 模式中 ']' 之后的下标)。 + private static (bool matched, int next) MatchClass(string pattern, int start, char input) + { + var p = start + 1; + var negate = p < pattern.Length && (pattern[p] == '!' || pattern[p] == '^'); + if (negate) + { + p++; + } + + var matched = false; + var first = true; + while (p < pattern.Length && (pattern[p] != ']' || first)) + { + first = false; + if (p + 2 < pattern.Length && pattern[p + 1] == '-' && pattern[p + 2] != ']') + { + var lo = char.ToLowerInvariant(pattern[p]); + var hi = char.ToLowerInvariant(pattern[p + 2]); + var c = char.ToLowerInvariant(input); + if (lo <= c && c <= hi) + { + matched = true; + } + + p += 3; + } + else + { + if (EqualsIgnoreCase(pattern[p], input)) + { + matched = true; + } + + p++; + } + } + + // 未闭合的 '[' 按字面处理 + if (p >= pattern.Length) + { + return (input == '[', start + 1); + } + + return (matched != negate, p + 1); + } +} diff --git a/src/GeneralZip/Internal/EntryPathResolver.cs b/src/GeneralZip/Internal/EntryPathResolver.cs index ab80149..6f5c4e4 100644 --- a/src/GeneralZip/Internal/EntryPathResolver.cs +++ b/src/GeneralZip/Internal/EntryPathResolver.cs @@ -50,6 +50,67 @@ internal static class EntryPathResolver return combined; } + public static bool ContainsReparsePoint(string rootDirectory, string targetPath) + { + var root = NormalizeRoot(rootDirectory); + var target = Path.GetFullPath(targetPath); + var comparison = Path.DirectorySeparatorChar == '\\' ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var rootPrefix = root.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) + ? root + : root + Path.DirectorySeparatorChar; + if (!target.Equals(root, comparison) && !target.StartsWith(rootPrefix, comparison)) + { + return true; + } + + var relative = target.Length == root.Length ? string.Empty : target.Substring(rootPrefix.Length); + var current = root; + if (IsReparsePoint(current)) return true; + foreach (var segment in relative.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, segment); + if (IsReparsePoint(current)) return true; + } + + return false; + } + + public static bool LinkTargetStaysWithinRoot(string rootDirectory, string linkPath, string target) + { + if (Path.IsPathRooted(target) || (target.Length >= 2 && target[1] == ':')) + { + return false; + } + + var resolved = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(linkPath) ?? rootDirectory, target)); + var comparison = Path.DirectorySeparatorChar == '\\' ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var root = NormalizeRoot(rootDirectory); + var rootPrefix = root.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) + ? root + : root + Path.DirectorySeparatorChar; + return (resolved.Equals(root, comparison) || resolved.StartsWith(rootPrefix, comparison)) + && !ContainsReparsePoint(root, resolved); + } + + private static string NormalizeRoot(string path) + { + var full = Path.GetFullPath(path); + var root = Path.GetPathRoot(full) ?? string.Empty; + var trimmed = full.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + return trimmed.Length < root.Length ? root : trimmed; + } + + private static bool IsReparsePoint(string path) + { + try + { + return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; + } + catch (FileNotFoundException) { return false; } + catch (DirectoryNotFoundException) { return false; } + catch (IOException) { return false; } + } + /// 保留末段文件名。 public static (string dir, string name) SplitName(string fullName) { diff --git a/src/GeneralZip/Internal/ICancellableEntryStreamProvider.cs b/src/GeneralZip/Internal/ICancellableEntryStreamProvider.cs new file mode 100644 index 0000000..c282ab4 --- /dev/null +++ b/src/GeneralZip/Internal/ICancellableEntryStreamProvider.cs @@ -0,0 +1,10 @@ +using System.IO; +using System.Threading; +using GeneralZip.Abstractions; + +namespace GeneralZip.Internal; + +internal interface ICancellableEntryStreamProvider +{ + Stream OpenEntryStream(IArchiveEntry entry, CancellationToken cancellationToken); +} diff --git a/src/GeneralZip/Internal/PartialStream.cs b/src/GeneralZip/Internal/PartialStream.cs index 833d626..471f610 100644 --- a/src/GeneralZip/Internal/PartialStream.cs +++ b/src/GeneralZip/Internal/PartialStream.cs @@ -131,4 +131,10 @@ public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) _inner.Dispose(); + base.Dispose(disposing); + } } diff --git a/src/GeneralZip/Internal/PrivateTempDirectory.cs b/src/GeneralZip/Internal/PrivateTempDirectory.cs new file mode 100644 index 0000000..0f37b34 --- /dev/null +++ b/src/GeneralZip/Internal/PrivateTempDirectory.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; + +namespace GeneralZip.Internal; + +internal sealed class PrivateTempDirectory : IDisposable +{ + public PrivateTempDirectory(string prefix) + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"{prefix}-{Guid.NewGuid():N}"); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + Directory.CreateDirectory(Path); + } + else if ((RuntimeInformation.IsOSPlatform(OSPlatform.OSX) + ? MkdirMac(Path, Convert.ToUInt32("700", 8)) + : Mkdir(Path, Convert.ToUInt32("700", 8))) != 0) + { + throw new IOException($"Could not create private temporary directory (errno {Marshal.GetLastWin32Error()})"); + } + } + + public string Path { get; } + + public string FilePath(string name) => System.IO.Path.Combine(Path, name); + + public void Dispose() + { + try { Directory.Delete(Path, recursive: true); } catch { } + } + + [DllImport("libc", EntryPoint = "mkdir", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern int Mkdir(string path, uint mode); + + [DllImport("/usr/lib/libSystem.B.dylib", EntryPoint = "mkdir", SetLastError = true, CharSet = CharSet.Ansi)] + private static extern int MkdirMac(string path, uint mode); +} diff --git a/src/GeneralZip/Internal/SplitVolume.cs b/src/GeneralZip/Internal/SplitVolume.cs new file mode 100644 index 0000000..7ad37f7 --- /dev/null +++ b/src/GeneralZip/Internal/SplitVolume.cs @@ -0,0 +1,265 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; + +namespace GeneralZip.Internal; + +/// +/// 分卷写入流:顺序写满一个卷后自动开下一卷(archive.zip.001/002/...)。 +/// 仅支持顺序写(ZIP 写入器即为顺序模型);Finish 由调用方控制,EOCD 自然落在末卷。 +/// +internal sealed class VolumeSplitStream : Stream +{ + private static readonly Regex VolumeSuffixPattern = new(@"^(?.+)\.(?\d{3,})$", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private readonly string _basePath; + private readonly long _volumeSize; + private readonly int _buffered; + private FileStream? _current; + private int _index; // 当前卷号(从 1 起) + private long _writtenInVolume; + + public VolumeSplitStream(string basePath, long volumeSize) + { + if (volumeSize <= 0) + { + throw new ArgumentOutOfRangeException(nameof(volumeSize)); + } + + _basePath = Path.GetFullPath(basePath); + _volumeSize = volumeSize; + OpenVolume(1); + } + + /// 实际产生的卷文件路径(Finish 后可用)。 + public List WrittenVolumes { get; } = new(); + + public string FirstVolumePath => VolumePath(1); + + public void Complete() + { + Flush(); + var pattern = Path.GetFileName(_basePath) + ".*"; + var directory = Path.GetDirectoryName(_basePath) ?? string.Empty; + foreach (var path in Directory.EnumerateFiles(directory, pattern)) + { + var match = VolumeSuffixPattern.Match(Path.GetFileName(path)); + if (match.Success + && string.Equals( + Path.Combine(directory, match.Groups["base"].Value), + _basePath, + Path.DirectorySeparatorChar == '\\' ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) + && int.TryParse(match.Groups["num"].Value, out var number) + && number > _index) + { + File.Delete(path); + } + } + } + + public static bool IsFirstVolumePath(string path) + { + var match = VolumeSuffixPattern.Match(Path.GetFileName(path)); + return match.Success && int.TryParse(match.Groups["num"].Value, out var number) && number == 1; + } + + private string VolumePath(int index) => $"{_basePath}.{index:D3}"; + + private void OpenVolume(int index) + { + _current?.Dispose(); + var path = VolumePath(index); + _current = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 65536, useAsync: false); + WrittenVolumes.Add(path); + _index = index; + _writtenInVolume = 0; + } + + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => _index * _volumeSize + _writtenInVolume; set => throw new NotSupportedException(); } + + public override void Write(byte[] buffer, int offset, int count) + { + var written = 0; + while (written < count) + { + var room = _volumeSize - _writtenInVolume; + if (room == 0) + { + OpenVolume(_index + 1); + room = _volumeSize; + } + + var chunk = (int)Math.Min(room, count - written); + _current!.Write(buffer, offset + written, chunk); + _writtenInVolume += chunk; + written += chunk; + } + } + + public override void Flush() => _current?.Flush(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _current?.Dispose(); + _current = null; + } + + base.Dispose(disposing); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// 按序拼接多个卷文件的可寻址只读流(读取 x.zip.001/002/... 时使用)。 +internal sealed class MultiVolumeStream : Stream +{ + private readonly List<(FileStream stream, long start, long length)> _parts = new(); + private long _position; + + public MultiVolumeStream(IReadOnlyList paths) + { + long start = 0; + foreach (var path in paths) + { + var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); + var length = fs.Length; + _parts.Add((fs, start, length)); + start += length; + } + + if (_parts.Count == 0) + { + throw new ArgumentException("No volume files", nameof(paths)); + } + } + + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => _parts[_parts.Count - 1].start + _parts[_parts.Count - 1].length; + public override long Position { get => _position; set => _position = value; } + + public override int Read(byte[] buffer, int offset, int count) + { + var total = 0; + while (total < count && _position < Length) + { + var (_, start, length) = FindPart(_position); + var stream = _parts[FindPartIndex(_position)].stream; + stream.Position = _position - start; + var read = stream.Read(buffer, offset + total, (int)Math.Min(count - total, length - (_position - start))); + if (read <= 0) + { + break; + } + + _position += read; + total += read; + } + + return total; + } + + private (int index, long start, long length) FindPart(long position) + { + for (var i = 0; i < _parts.Count; i++) + { + if (position < _parts[i].start + _parts[i].length) + { + return (i, _parts[i].start, _parts[i].length); + } + } + + var last = _parts.Count - 1; + return (last, _parts[last].start, _parts[last].length); + } + + private int FindPartIndex(long position) => FindPart(position).index; + + public override long Seek(long offset, SeekOrigin origin) + { + var target = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + SeekOrigin.End => Length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + if (target < 0) + { + throw new IOException("Seek before begin"); + } + + _position = target; + return _position; + } + + public override void Flush() { } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + foreach (var (stream, _, _) in _parts) + { + stream.Dispose(); + } + } + + base.Dispose(disposing); + } + + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// 分卷路径识别与枚举。 +internal static class SplitVolumeLocator +{ + private static readonly Regex Pattern = new(@"^(?.+)\.(?\d{3,})$", + RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + /// 识别 *.NNN 分卷序文件;返回全部卷路径(按序)。非分卷返回 null。 + public static IReadOnlyList? Resolve(string path) + { + var match = Pattern.Match(Path.GetFileName(path)); + if (!match.Success) + { + return null; + } + + var firstNum = int.Parse(match.Groups["num"].Value, System.Globalization.CultureInfo.InvariantCulture); + if (firstNum != 1) + { + return null; // 必须从 .001 开始 + } + + var basePath = Path.Combine( + Path.GetDirectoryName(Path.GetFullPath(path)) ?? string.Empty, + match.Groups["base"].Value); + var pad = match.Groups["num"].Value.Length; + + var volumes = new List(); + for (var i = 1; ; i++) + { + var part = $"{basePath}.{i.ToString($"D{pad}")}"; + if (!File.Exists(part)) + { + break; + } + + volumes.Add(part); + } + + return volumes.Count >= 2 ? volumes : null; + } +} diff --git a/src/GeneralZip/Native/GeneralZipNative.cs b/src/GeneralZip/Native/GeneralZipNative.cs index a16f154..6a8f783 100644 --- a/src/GeneralZip/Native/GeneralZipNative.cs +++ b/src/GeneralZip/Native/GeneralZipNative.cs @@ -5,61 +5,51 @@ namespace GeneralZip.Native; /// -/// GeneralZip 原生能力入口:一行注册 7z/RAR 提供者与原生编解码桥接。 -/// -/// GeneralZip.Initialize(); // 核心引导(幂等);已并入原生引导调用 -/// GeneralZipNative.Initialize(); // 原生引导(幂等,可显式调用;7z/RAR/bz2/xz/zstd/lz4) -/// +/// GeneralZip 原生能力入口:原生引导已隐式完成——首次访问任何 API 时, +/// 的装配会自动加载核心并注册 +/// 7z/RAR 提供者与原生编解码桥接(幂等;7z/RAR/bz2/xz/zstd/lz4),无需手动调用。 /// 原生核心缺失时安全降级:7z/RAR 不注册、原生编解码格式报明确异常;纯托管能力不受影响。 /// public static class GeneralZipNative { - private static readonly object Lock = new(); - private static bool _initialized; - - /// 加载原生核心并注册能力(幂等、线程安全)。返回核心是否可用。 - public static bool Initialize() + /// + /// 原生引导(幂等):加载原生核心;成功时向 注册 7z/RAR + /// (registry 为 null 则跳过注册)并注入编解码桥接委托,失败静默降级。 + /// 不访问 ——由调用方传入实例, + /// 避免静态构造器重入拿到半初始化的注册表。 + /// + internal static void Bootstrap(GeneralZipFormatRegistry? registry) { - lock (Lock) + if (!NativeCoreLoader.TryLoad()) { - if (_initialized) - { - return NativeCoreLoader.IsAvailable; - } - - _initialized = true; - - if (!NativeCoreLoader.TryLoad()) - { - return false; - } - - var registry = GeneralZipFormatRegistry.Default; - - // 7z 能力(sevenz-rust2,纯 Rust) - if ((NativeCoreLoader.Capabilities & NativeCoreLoader.CapabilitySevenZ) != 0) - { - registry.Register(new SevenZipNativeFormat()); - } + return; + } - // RAR 能力(unrar 封装,需 C++ 工具链构建的原生核心) - if ((NativeCoreLoader.Capabilities & NativeCoreLoader.CapabilityRar) != 0) - { - registry.Register(new RarNativeFormat()); - } + var caps = NativeCoreLoader.Capabilities; - // 单文件编解码桥接(bzip2 / xz / zstd / lz4):核心经 NativeBridge 间接调用 - var caps = NativeCoreLoader.Capabilities; - NativeBridge.IsAvailable = () => NativeCoreLoader.IsAvailable; - NativeBridge.Compress = (codec, src, dst) => - InvokeCodec(codec, src, dst, compress: true, caps); - NativeBridge.Decompress = (codec, src, dst) => - InvokeCodec(codec, src, dst, compress: false, caps); + // 7z 能力(sevenz-rust2,纯 Rust) + if (registry != null && (caps & NativeCoreLoader.CapabilitySevenZ) != 0) + { + registry.Register(new SevenZipNativeFormat()); + } - return true; + // RAR 能力(unrar 封装,需 C++ 工具链构建的原生核心) + if (registry != null && (caps & NativeCoreLoader.CapabilityRar) != 0) + { + registry.Register(new RarNativeFormat()); } + + // 单文件编解码桥接(bzip2 / xz / zstd / lz4):核心经 NativeBridge 间接调用 + NativeBridge.IsAvailable = () => NativeCoreLoader.IsAvailable; + NativeBridge.Compress = (codec, src, dst) => + InvokeCodec(codec, src, dst, compress: true, caps); + NativeBridge.Decompress = (codec, src, dst) => + InvokeCodec(codec, src, dst, compress: false, caps); } + /// 确保编解码桥接已注入(自定义注册表场景的兜底,幂等)。 + internal static void EnsureBridge() => Bootstrap(null); + private static bool InvokeCodec(string codec, string src, string dst, bool compress, uint caps) { // bzip2/xz/lz4/zstd 全部挂在 XZ 能力位之下(同一批纯 Rust 编解码器) diff --git a/src/GeneralZip/Native/GzpNative.cs b/src/GeneralZip/Native/GzpNative.cs index 4dc106e..5eeb3c4 100644 --- a/src/GeneralZip/Native/GzpNative.cs +++ b/src/GeneralZip/Native/GzpNative.cs @@ -32,6 +32,16 @@ internal static class GzpNative [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] public static extern uint gzp_capabilities(); + [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] + public static extern int gzp_sm2_decrypt( + byte[] privateKey, + uint privateKeyLength, + byte[] ciphertext, + uint ciphertextLength, + byte[] output, + uint outputCapacity, + out uint outputLength); + [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] public static extern void gzp_free(IntPtr ptr); @@ -91,6 +101,22 @@ public static extern int gzp_rar_extract( [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] public static extern int gzp_codec_decompress(string codec, string src, string dst); + // ---------- 流式编解码(回调推拉,零临时文件) ---------- + + /// 读取回调:填充 buffer(≤capacity),返回字节数;0 = EOF;负数 = 失败。 + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + public delegate int GzpCodecReadCallback(IntPtr buffer, uint capacity, IntPtr userData); + + /// 写入回调:消费 buffer(length 字节),0 = 成功;负数 = 失败。 + [UnmanagedFunctionPointer(CallingConvention.Winapi)] + public delegate int GzpCodecWriteCallback(IntPtr buffer, uint length, IntPtr userData); + + [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] + public static extern int gzp_codec_crun(string codec, uint level, GzpCodecReadCallback readCb, GzpCodecWriteCallback writeCb, IntPtr userData); + + [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] + public static extern int gzp_codec_drun(string codec, GzpCodecReadCallback readCb, GzpCodecWriteCallback writeCb, IntPtr userData); + // ---------- xz ---------- [DllImport(LibName, CallingConvention = CallingConvention.Winapi)] diff --git a/src/GeneralZip/Native/SevenZipNativeFormat.cs b/src/GeneralZip/Native/SevenZipNativeFormat.cs index 16c1955..51df3fc 100644 --- a/src/GeneralZip/Native/SevenZipNativeFormat.cs +++ b/src/GeneralZip/Native/SevenZipNativeFormat.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.IO; using System.Threading; using GeneralZip; @@ -272,7 +273,9 @@ public void Finish(CancellationToken cancellationToken) // 原生核心按路径产出归档;为避免与门面持有的输出流争锁,先写临时文件再回拷 var produced = Path.Combine(_stagingDir, "produced.7z"); - var sourcesJson = System.Text.Json.JsonSerializer.Serialize(_sources); + // 手工构造 JSON 字符串数组(避免 JsonSerializer 反射 → AOT/Trim 兼容) + var parts = _sources.Select(s0 => System.Text.Json.JsonEncodedText.Encode(s0).ToString()); + var sourcesJson = "[" + string.Join(",", parts.Select(p0 => '"' + p0 + '"')) + "]"; var password = GzpNative.PasswordBytes(_options.Password); var status = GzpNative.gzp_7z_compress(sourcesJson, produced, password, diff --git a/src/GeneralZip/Repack.cs b/src/GeneralZip/Repack.cs new file mode 100644 index 0000000..60c1e31 --- /dev/null +++ b/src/GeneralZip/Repack.cs @@ -0,0 +1,137 @@ +using System; +using System.IO; +using System.Threading; +using GeneralZip.Abstractions; + +namespace GeneralZip; + +/// +/// 重打包核心:把源归档条目忠实复制到目标归档(读出→重写语义)。 +/// Append / Remove / Convert 三个门面操作共用。条目名称、大小、时间戳、注释、目录占位保留; +/// 加密状态不保留(源条目被解密后按目标写入选项重新加密)。 +/// +internal static class Repack +{ + /// 把 reader 的全部条目(满足 keepEntry 的)复制进 writer。返回 (复制数, 跳过数)。 + public static (int copied, int skipped) CopyEntries( + GeneralZipReader reader, + GeneralZipWriter writer, + Func? keepEntry, + CancellationToken cancellationToken) + { + var copied = 0; + var skipped = 0; + foreach (var entry in reader.Entries) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (keepEntry != null && !keepEntry(entry)) + { + skipped++; + continue; + } + + if (entry.IsDirectory) + { + writer.AddDirectoryEntry(entry.FullName, new ArchiveEntryMetadata + { + LastWriteTime = entry.LastWriteTime, + UnixMode = (entry as IUnixEntry)?.UnixMode, + }); + copied++; + continue; + } + + var meta = new ArchiveEntryMetadata + { + Size = entry.Size, + LastWriteTime = entry.LastWriteTime, + Comment = entry.Comment, + UnixMode = (entry as IUnixEntry)?.UnixMode, + }; + + using var content = reader.OpenEntryStream(entry); + if (meta.UnixMode.HasValue && (meta.UnixMode.Value & 0xF000u) == 0xA000u) + { + string target; + if ((entry as IUnixEntry)?.SymlinkTarget is { } headerTarget) + { + target = headerTarget; + } + else + { + using var targetText = new MemoryStream(); + content.CopyTo(targetText); + target = System.Text.Encoding.UTF8.GetString(targetText.ToArray()); + } + + writer.AddSymlink(entry.FullName, target, meta); + } + else if (meta.Size < 0) + { + using var tempDirectory = new Internal.PrivateTempDirectory("gzp-repack"); + var tempPath = tempDirectory.FilePath("entry.bin"); + using (var output = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + content.CopyTo(output); + meta.Size = output.Length; + } + + using var measured = File.OpenRead(tempPath); + writer.AddStream(entry.FullName, measured, meta); + } + else + { + writer.AddStream(entry.FullName, content, meta); + } + copied++; + } + + return (copied, skipped); + } + + /// 把文件或目录源(CompressAsync 语义)追加进 writer。 + public static void AddSourcePath(GeneralZipWriter writer, string sourcePath, CancellationToken cancellationToken) + { + if (File.Exists(sourcePath)) + { + writer.AddFileAsync(sourcePath, null, cancellationToken).GetAwaiter().GetResult(); + return; + } + + if (Directory.Exists(sourcePath)) + { + var name = new System.IO.DirectoryInfo(sourcePath).Name; + var hasChildren = System.IO.Directory.EnumerateFileSystemEntries(sourcePath).GetEnumerator().MoveNext(); + writer.AddDirectoryAsync(sourcePath, hasChildren ? name : null, cancellationToken: cancellationToken) + .GetAwaiter().GetResult(); + return; + } + + throw new FileNotFoundException("Source path does not exist", sourcePath); + } + + /// 在目标文件所在目录生成同后缀名临时文件路径(保留 ".tar.gz" 类复合后缀以正确推断格式)。 + public static string TempSiblingPath(string targetPath) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(targetPath)) ?? "."; + var name = Path.GetFileName(targetPath); + return Path.Combine(dir, $"gz-rewrite-{Guid.NewGuid():N}-{name}"); + } + + /// 覆盖式移动(netstandard2.0 无 File.Move(string,string,bool))。 + public static void MoveOverwrite(string sourcePath, string targetPath) + { +#if NET8_0_OR_GREATER + File.Move(sourcePath, targetPath, overwrite: true); +#else + if (File.Exists(targetPath)) + { + File.Replace(sourcePath, targetPath, destinationBackupFileName: null); + return; + } + + File.Move(sourcePath, targetPath); +#endif + } +} diff --git a/tests/GeneralZip.Native.Tests/NativeCodecTests.cs b/tests/GeneralZip.Native.Tests/NativeCodecTests.cs index 2882b87..4d4e565 100644 --- a/tests/GeneralZip.Native.Tests/NativeCodecTests.cs +++ b/tests/GeneralZip.Native.Tests/NativeCodecTests.cs @@ -19,8 +19,7 @@ public class NativeCodecTests : IDisposable public NativeCodecTests() { Directory.CreateDirectory(_dir); - NativeCoreLoader.TryLoad(); - GeneralZipNative.Initialize(); // 注入原生编解码桥接(BZ2/XZ/ZSTD/LZ4 路由需要) + NativeCoreLoader.TryLoad(); // 预热核心探测(引导本身已随 Default 注册表装配隐式完成) } public void Dispose() diff --git a/tests/GeneralZip.Native.Tests/NativeCoreTests.cs b/tests/GeneralZip.Native.Tests/NativeCoreTests.cs index bacd9bc..9079ac5 100644 --- a/tests/GeneralZip.Native.Tests/NativeCoreTests.cs +++ b/tests/GeneralZip.Native.Tests/NativeCoreTests.cs @@ -41,7 +41,22 @@ private bool SkipIfNoCore() return true; } - private static string NewPassword() => "Nk" + Convert.ToBase64String(RandomNumberGenerator.GetBytes(8)).TrimEnd('='); + private static string NewPassword() => "Nk" + System.Convert.ToBase64String(RandomNumberGenerator.GetBytes(8)).TrimEnd('='); + + [Fact] + public void DefaultRegistry_ContainsNativeFormats_WithoutExplicitBootstrap() + { + if (SkipIfNoCore()) return; + + // 隐式引导回归防护:不调用任何引导 API,Default 注册表装配时应已注册 7z/RAR + //(RAR 按能力位协商,本地核心未开启 rar feature 时不注册) + var names = GeneralZipFormatRegistry.Default.Snapshot().Select(f => f.Info.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); + Assert.Contains("7Z", names); + if ((NativeCoreLoader.Capabilities & NativeCoreLoader.CapabilityRar) != 0) + { + Assert.Contains("RAR", names); + } + } [Fact] public void CoreLoads_WithSevenZCapability() @@ -60,7 +75,6 @@ public void CoreLoads_WithSevenZCapability() public void SevenZip_Roundtrip_Plain() { if (SkipIfNoCore()) return; - GeneralZipNative.Initialize(); var src = Path.Combine(_dir, "src"); Directory.CreateDirectory(Path.Combine(src, "sub")); @@ -91,7 +105,6 @@ public void SevenZip_Roundtrip_Plain() public void SevenZip_Encrypted_Roundtrip_And_WrongPassword() { if (SkipIfNoCore()) return; - GeneralZipNative.Initialize(); var archive = Path.Combine(_dir, "enc.7z"); var password = NewPassword(); @@ -136,7 +149,6 @@ public void SevenZip_Encrypted_Roundtrip_And_WrongPassword() public void SevenZip_TestAll() { if (SkipIfNoCore()) return; - GeneralZipNative.Initialize(); var archive = Path.Combine(_dir, "t.7z"); using (var w = GeneralZipWriter.CreateNew(archive, formatName: "7Z")) @@ -154,7 +166,6 @@ public void SevenZip_TestAll() public void Xz_Compress_Decompress_Roundtrip() { if (SkipIfNoCore()) return; - GeneralZipNative.Initialize(); var src = Path.Combine(_dir, "in.txt"); var compressed = Path.Combine(_dir, "out.xz"); diff --git a/tests/GeneralZip.Native.Tests/NativeFixtureTests.cs b/tests/GeneralZip.Native.Tests/NativeFixtureTests.cs index f419603..af29502 100644 --- a/tests/GeneralZip.Native.Tests/NativeFixtureTests.cs +++ b/tests/GeneralZip.Native.Tests/NativeFixtureTests.cs @@ -61,7 +61,6 @@ public void NativeFixture_Roundtrips(string fileName, string formatName, bool si return; } - GeneralZipNative.Initialize(); // 显式 "\n" 拼接:内容字节不随源码行尾(CRLF/LF)漂移,保证跨平台一致 var noteText = string.Join("\n", @@ -131,7 +130,6 @@ public void SevenZ_Fixture_Decrypts_And_ContentMatches() return; } - GeneralZipNative.Initialize(); // 显式 "\n" 拼接:内容字节不随源码行尾(CRLF/LF)漂移,保证跨平台一致 var noteText = string.Join("\n", diff --git a/tests/GeneralZip.Tests/CpioFormatTests.cs b/tests/GeneralZip.Tests/CpioFormatTests.cs new file mode 100644 index 0000000..6cfe847 --- /dev/null +++ b/tests/GeneralZip.Tests/CpioFormatTests.cs @@ -0,0 +1,229 @@ +using System; +using System.Buffers.Binary; +using System.IO; +using System.Linq; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// CPIO 格式测试:newc 自写自读 + odc/binary 手工向量 + 符号链接。 +public class CpioFormatTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public CpioFormatTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + [Fact] + public void Newc_Roundtrip() + { + var cpio = Path.Combine(_dir, "a.cpio"); + using (var w = GeneralZipWriter.CreateNew(cpio)) + { + w.AddDirectoryEntry("dir/"); + var payload = Encoding.UTF8.GetBytes("你好 CPIO"); + w.AddStream("dir/hello.txt", new MemoryStream(payload), payload.Length); + w.AddStream("empty.bin", new MemoryStream(Array.Empty()), 0); + w.Finish(); + } + + Assert.Equal("CPIO", GeneralZip.DetectFormat(cpio)?.Name); + + using var r = GeneralZipReader.Open(cpio); + Assert.Equal(3, r.Entries.Count); + Assert.True(r.Entries[0].IsDirectory); + Assert.True(r.Entries[1].IsDirectory == false); + + using var s = r.OpenEntryStream(r.Entries[1]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("你好 CPIO", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Newc_SymlinkRoundtrip() + { + var cpio = Path.Combine(_dir, "sym.cpio"); + using (var w = GeneralZipWriter.CreateNew(cpio)) + { + w.AddSymlink("alias", "target/x.txt"); + w.Finish(); + } + + using var r = GeneralZipReader.Open(cpio); + var unix = Assert.IsAssignableFrom(r.Entries.Single()); + Assert.Equal(0xA000u, unix.UnixMode & 0xF000u); + using var s = r.OpenEntryStream(r.Entries[0]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("target/x.txt", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Newc_SymlinkPreserve_ExtractsLink() + { + var archive = Path.Combine(_dir, "preserve-link.cpio"); + using (var writer = GeneralZipWriter.CreateNew(archive)) + { + writer.AddSymlink("alias", "target/x.txt"); + writer.Finish(); + } + + var output = Path.Combine(_dir, "preserved"); + var result = GeneralZip.Extract(archive, output, extraction: new ExtractionOptions + { + SymlinkPolicy = SymlinkPolicy.Preserve, + }); + + Assert.Equal(1, result.ProcessedCount); + var link = Path.Combine(output, "alias"); + if ((File.GetAttributes(link) & FileAttributes.ReparsePoint) != 0) + { + Assert.Equal("target/x.txt", new FileInfo(link).LinkTarget); + } + else + { + Assert.Equal("target/x.txt", File.ReadAllText(link)); + } + } + + [Fact] + public void ParallelExtraction_UsesWorkerOwnedCpioEntries() + { + var archive = Path.Combine(_dir, "parallel.cpio"); + using (var writer = GeneralZipWriter.CreateNew(archive)) + { + writer.AddStream("a.txt", new MemoryStream("a"u8.ToArray()), 1); + writer.AddStream("b.txt", new MemoryStream("b"u8.ToArray()), 1); + writer.Finish(); + } + + var result = GeneralZip.Extract(archive, Path.Combine(_dir, "parallel"), extraction: new ExtractionOptions + { + MaxDegreeOfParallelism = 2, + }); + + Assert.Equal(2, result.ProcessedCount); + } + + [Fact] + public void Newc_UnixModePreserved() + { + var cpio = Path.Combine(_dir, "mode.cpio"); + using (var w = GeneralZipWriter.CreateNew(cpio)) + { + w.AddStream("a.bin", new MemoryStream(new byte[] { 1 }), new ArchiveEntryMetadata + { + Size = 1, + UnixMode = 0x81C0, // S_IFREG | 0700 + }); + w.Finish(); + } + + using var r = GeneralZipReader.Open(cpio); + var unix = Assert.IsAssignableFrom(r.Entries.Single()); + Assert.Equal(0x81C0u, unix.UnixMode); + } + + /// 手工构造 odc(070707,标准八进制字段宽度,无对齐)归档。 + [Fact] + public void Odc_Vector_Read() + { + using var ms = new MemoryStream(); + WriteOdcEntry(ms, "od.txt", "odc!"u8.ToArray(), mode: 0x81A4, mtime: 42598); + WriteOdcTrailer(ms); + ms.Position = 0; + + using var r = GeneralZipReader.Open(ms); + Assert.Single(r.Entries); + Assert.Equal("od.txt", r.Entries[0].FullName); + using var s = r.OpenEntryStream(r.Entries[0]); + using var body = new MemoryStream(); + s.CopyTo(body); + Assert.Equal("odc!", Encoding.UTF8.GetString(body.ToArray())); + } + + /// 手工构造 portable binary(0x71C7 LE)归档。 + [Fact] + public void Binary_Vector_Read() + { + using var ms = new MemoryStream(); + var name = "bin.txt\0"u8.ToArray(); + var data = "bin"u8.ToArray(); + + Span header = stackalloc byte[26]; + header[0] = 0xC7; + header[1] = 0x71; + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(2), 0); // dev + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(4), 1); // ino + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(6), 0x8180); // mode 0600 + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(8), 0); // uid + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(10), 0); // gid + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(12), 1); // nlink + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(14), 0); // rdev + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(16), 0); // mtime hi + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(18), 0); // mtime lo + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(20), (ushort)name.Length); + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(22), 0); // filesize hi + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(24), (ushort)data.Length); + ms.Write(header); + ms.Write(name); + if ((ms.Position & 1) != 0) ms.WriteByte(0); + ms.Write(data); + if ((ms.Position & 1) != 0) ms.WriteByte(0); + + // trailer(binary trailer 名 "TRAILER!!!") + var trailerName = Encoding.ASCII.GetBytes("TRAILER!!!\0"); + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(4), 2); // ino + BinaryPrimitives.WriteUInt16LittleEndian(header.Slice(20), (ushort)trailerName.Length); + ms.Write(header); + ms.Write(trailerName); + if ((ms.Position & 1) != 0) ms.WriteByte(0); + ms.Position = 0; + + using var r = GeneralZipReader.Open(ms); + var entry = r.Entries.Single(); + Assert.Equal("bin.txt", entry.FullName); + var unix = Assert.IsAssignableFrom(entry); + Assert.Equal(0x8180u, unix.UnixMode); + using var s = r.OpenEntryStream(entry); + using var body = new MemoryStream(); + s.CopyTo(body); + Assert.Equal("bin", Encoding.UTF8.GetString(body.ToArray())); + } + + private static void WriteOdcEntry(Stream s, string name, byte[] data, uint mode, long mtime) + { + var nameBytes = Encoding.UTF8.GetBytes(name + "\0"); + static string Oct(long v, int width = 6) => Convert.ToString(v, 8).PadLeft(width, '0'); + var header = "070707" + Oct(0) + Oct(1) + Oct(mode) + Oct(0) + Oct(0) + Oct(1) + Oct(0) + + Oct(mtime, 11) + Oct(nameBytes.Length) + Oct(data.Length, 11); + var headerBytes = Encoding.ASCII.GetBytes(header); + s.Write(headerBytes, 0, headerBytes.Length); + s.Write(nameBytes, 0, nameBytes.Length); + s.Write(data, 0, data.Length); + } + + private static void WriteOdcTrailer(Stream s) + { + var nameBytes = Encoding.ASCII.GetBytes("TRAILER!!!\0"); + static string OctT(long v, int width = 6) => Convert.ToString(v, 8).PadLeft(width, '0'); + var header = "070707" + OctT(0) + OctT(2) + OctT(0) + OctT(0) + OctT(0) + OctT(1) + OctT(0) + + OctT(0, 11) + OctT(nameBytes.Length) + OctT(0, 11); + var headerBytes = Encoding.ASCII.GetBytes(header); + s.Write(headerBytes, 0, headerBytes.Length); + s.Write(nameBytes, 0, nameBytes.Length); + if ((s.Position & 1) != 0) s.WriteByte(0); + } + +} diff --git a/tests/GeneralZip.Tests/FacadeOpsTests.cs b/tests/GeneralZip.Tests/FacadeOpsTests.cs new file mode 100644 index 0000000..39c323b --- /dev/null +++ b/tests/GeneralZip.Tests/FacadeOpsTests.cs @@ -0,0 +1,305 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// 门面高阶操作测试:追加/删除/转换(重写语义)、Stream→Stream、Glob 过滤。 +public class FacadeOpsTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public FacadeOpsTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + private string MakeFile(string relativePath, string content) + { + var path = Path.Combine(_dir, relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + return path; + } + + // ---------- Append ---------- + + [Fact] + public void Append_FileAndDirectory_ExistingEntriesPreserved() + { + var zip = Path.Combine(_dir, "append.zip"); + var srcDir = Path.Combine(_dir, "srcdir"); + Directory.CreateDirectory(srcDir); + File.WriteAllText(Path.Combine(srcDir, "n1.txt"), "n1"); + Directory.CreateDirectory(Path.Combine(srcDir, "sub")); + File.WriteAllText(Path.Combine(srcDir, "sub", "n2.txt"), "n2"); + + GeneralZip.Compress(MakeFile("a.txt", "AAA"), zip); + + GeneralZip.Append(zip, MakeFile("b.txt", "BBB")); + GeneralZip.Append(zip, srcDir); + + using var r = GeneralZipReader.Open(zip); + var names = r.Entries.Select(e => e.FullName).OrderBy(n => n).ToList(); + Assert.Contains("a.txt", names); + Assert.Contains("b.txt", names); + Assert.Contains("srcdir/n1.txt", names); + Assert.Contains("srcdir/sub/", names); + Assert.Contains("srcdir/sub/n2.txt", names); + Assert.Equal(5, r.Entries.Count); + + using var stream = r.OpenEntryStream(r.Entries.First(e => e.FullName == "a.txt")); + using var ms = new MemoryStream(); + stream.CopyTo(ms); + Assert.Equal("AAA", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Append_EncryptedInheritsAlgorithm() + { + var zip = Path.Combine(_dir, "enc-append.zip"); + var password = TestSecrets.NewPassword(); + + GeneralZip.Compress(MakeFile("secret1.txt", "S1"), zip, o => + { + o.EncryptionAlgorithm = "SM4-GM"; + o.Password = password; + }); + + // 只给口令、不给算法 → 继承源归档的 SM4-GM + GeneralZip.Append(zip, MakeFile("secret2.txt", "S2"), o => o.Password = password); + + using var r = GeneralZipReader.Open(zip, o => o.Password = password); + Assert.True(r.IsEncrypted); + foreach (var entry in r.Entries.Where(e => !e.IsDirectory)) + { + Assert.Equal("SM4-GM", entry.EncryptionAlgorithm); + } + + using var s = r.OpenEntryStream(r.Entries.First(e => e.FullName == "secret2.txt")); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("S2", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Append_TarGzRoundtrip() + { + var tarGz = Path.Combine(_dir, "app.tar.gz"); + GeneralZip.Compress(MakeFile("x.txt", "X"), tarGz); + GeneralZip.Append(tarGz, MakeFile("y.txt", "Y")); + + using var r = GeneralZipReader.Open(tarGz); + Assert.Equal(2, r.Entries.Count); + Assert.Equal("TAR.GZ", r.Format.Name); + } + + // ---------- Remove ---------- + + [Fact] + public void Remove_ByNames() + { + var zip = Path.Combine(_dir, "rm.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("keep1.txt", new MemoryStream(Encoding.UTF8.GetBytes("1")), 1); + w.AddStream("drop.txt", new MemoryStream(Encoding.UTF8.GetBytes("2")), 1); + w.AddStream("keep2.txt", new MemoryStream(Encoding.UTF8.GetBytes("3")), 1); + w.Finish(); + } + + GeneralZip.Remove(zip, new[] { "drop.txt" }); + + using var r = GeneralZipReader.Open(zip); + var names = r.Entries.Select(e => e.FullName).ToList(); + Assert.Equal(new[] { "keep1.txt", "keep2.txt" }, names); + } + + [Fact] + public void Remove_ByPredicate() + { + var zip = Path.Combine(_dir, "rm-pred.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("a/tmp/x.tmp", new MemoryStream(Encoding.UTF8.GetBytes("t")), 1); + w.AddStream("b/main.txt", new MemoryStream(Encoding.UTF8.GetBytes("m")), 1); + w.Finish(); + } + + GeneralZip.Remove(zip, predicate: e => e.FullName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)); + + using var r = GeneralZipReader.Open(zip); + Assert.Single(r.Entries); + Assert.Equal("b/main.txt", r.Entries[0].FullName); + } + + // ---------- Convert ---------- + + [Fact] + public void Convert_ZipToTarGz_AndBack() + { + var zip = Path.Combine(_dir, "conv.zip"); + var tarGz = Path.Combine(_dir, "conv.tar.gz"); + var zip2 = Path.Combine(_dir, "conv2.zip"); + + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("dir/a.txt", new MemoryStream(Encoding.UTF8.GetBytes("AAA")), 3, new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero)); + w.AddStream("dir/b.bin", new MemoryStream(new byte[] { 1, 2, 3, 4 }), 4); + w.AddDirectoryEntry("dir/empty"); + w.Finish(); + } + + GeneralZip.Convert(zip, tarGz); + Assert.Equal("TAR.GZ", GeneralZip.DetectFormat(tarGz)?.Name); + + using (var r1 = GeneralZipReader.Open(tarGz)) + { + Assert.Equal(3, r1.Entries.Count); + Assert.Equal(2020, r1.Entries[0].LastWriteTime?.UtcDateTime.Year); + } + + GeneralZip.Convert(tarGz, zip2); + using (var r2 = GeneralZipReader.Open(zip2)) + { + using var s = r2.OpenEntryStream(r2.Entries.First(e => e.FullName == "dir/a.txt")); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("AAA", Encoding.UTF8.GetString(ms.ToArray())); + } + } + + [Fact] + public void Convert_ToEncryptedZip() + { + var tarGz = Path.Combine(_dir, "plain.tar.gz"); + var zipEnc = Path.Combine(_dir, "target.zip"); + var password = TestSecrets.NewPassword(); + GeneralZip.Compress(MakeFile("m.txt", "M"), tarGz); + + GeneralZip.Convert(tarGz, zipEnc, o => + { + o.EncryptionAlgorithm = "WinZipAES256"; + o.Password = password; + }); + + var result = GeneralZip.Test(zipEnc, o => o.Password = password); + Assert.True(result.Success); + } + + // ---------- Stream → Stream ---------- + + [Fact] + public async Task StreamApi_CompressExtract_Test_Zip() + { + var payload = Encoding.UTF8.GetBytes("stream roundtrip 中文 0123456789"); + + using var outMs = new MemoryStream(); + await GeneralZip.CompressAsync(new MemoryStream(payload), outMs, "ZIP", "data/payload.txt"); + + outMs.Position = 0; + var info = GeneralZip.DetectFormat(outMs); + Assert.Equal("ZIP", info?.Name); + + outMs.Position = 0; + using (var r = GeneralZipReader.Open(outMs)) + { + Assert.Single(r.Entries); + Assert.Equal("data/payload.txt", r.Entries[0].FullName); + } + + outMs.Position = 0; + var extractDir = Path.Combine(_dir, "stream-out"); + var result = await GeneralZip.ExtractAsync(outMs, extractDir); + Assert.Equal(1, result.ProcessedCount); + Assert.Equal("stream roundtrip 中文 0123456789", + File.ReadAllText(Path.Combine(extractDir, "data", "payload.txt"), Encoding.UTF8)); + + outMs.Position = 0; + var test = GeneralZip.Test(outMs); + Assert.True(test.Success); + } + + [Fact] + public async Task StreamApi_GzipSingleFileSemantics() + { + using var outMs = new MemoryStream(); + await GeneralZip.CompressAsync(new MemoryStream(new byte[] { 9, 9, 9 }), outMs, "GZIP", "named.bin"); + + outMs.Position = 0; + using var r = GeneralZipReader.Open(outMs); + // 单文件编解码格式(GZIP)不保存条目名:流式入口无源名时条目名为 "content" + Assert.Equal("content", r.Entries[0].FullName); + using var s = r.OpenEntryStream(r.Entries[0]); + var buf = new byte[3]; + Assert.Equal(3, ReadFull(s, buf)); + } + + private static int ReadFull(Stream s, byte[] buf) + { + var total = 0; + int n; + while (total < buf.Length && (n = s.Read(buf, total, buf.Length - total)) > 0) + { + total += n; + } + + return total; + } + + // ---------- Glob 过滤 ---------- + + [Fact] + public void GlobFilter_IncludeExclude() + { + var zip = Path.Combine(_dir, "glob.zip"); + var outDir = Path.Combine(_dir, "glob-out"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("photos/a.jpg", new MemoryStream(new byte[] { 1 }), 1); + w.AddStream("photos/nested/b.jpg", new MemoryStream(new byte[] { 2 }), 1); + w.AddStream("docs/readme.txt", new MemoryStream(new byte[] { 3 }), 1); + w.AddStream("docs/tmp/cache.tmp", new MemoryStream(new byte[] { 4 }), 1); + w.Finish(); + } + + GeneralZip.Extract(zip, outDir, extraction: new ExtractionOptions + { + IncludePatterns = new[] { "photos/**/*.jpg" }, + ExcludePatterns = new[] { "**/*.tmp" }, + }); + + var files = Directory.EnumerateFiles(outDir, "*", SearchOption.AllDirectories) + .Select(Path.GetFileName).OrderBy(n => n).ToList(); + Assert.Equal(new[] { "a.jpg", "b.jpg" }, files); + } + + [Theory] + [InlineData("a/b/c.jpg", "a/**/c.jpg", true)] + [InlineData("a/c.jpg", "a/**/c.jpg", true)] + [InlineData("a/b/c.jpg", "*/c.jpg", false)] + [InlineData("a/b/c.jpg", "**/c.jpg", true)] + [InlineData("c.jpg", "**/c.jpg", true)] + [InlineData("root/x.tmp", "*.tmp", false)] + [InlineData("x.tmp", "*.tmp", true)] + [InlineData("sub/x.tmp", "**/*.tmp", true)] + [InlineData("file.TXT", "*.txt", true)] + [InlineData("log2024.txt", "log[0-9]*.txt", true)] + [InlineData("logx.txt", "log[0-9]*.txt", false)] + [InlineData("a?b.txt", "a?b.txt", true)] + public void GlobMatcher_Matrices(string path, string pattern, bool expected) + { + Assert.Equal(expected, global::GeneralZip.GlobMatcher.IsMatch(path, pattern)); + } +} diff --git a/tests/GeneralZip.Tests/GeneralZip.Tests.csproj b/tests/GeneralZip.Tests/GeneralZip.Tests.csproj index d8e2a11..4f601a9 100644 --- a/tests/GeneralZip.Tests/GeneralZip.Tests.csproj +++ b/tests/GeneralZip.Tests/GeneralZip.Tests.csproj @@ -8,6 +8,7 @@ + diff --git a/tests/GeneralZip.Tests/InteropFixtureTests.cs b/tests/GeneralZip.Tests/InteropFixtureTests.cs new file mode 100644 index 0000000..5b97404 --- /dev/null +++ b/tests/GeneralZip.Tests/InteropFixtureTests.cs @@ -0,0 +1,161 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// +/// 互操作 fixture 测试:samples/fixtures/interop 下的归档由**独立实现**生成 +/// (py7zr / pycdlib / python zipfile / 手写 GNU cpio newc),GeneralZip 仅负责读取。 +/// 这是跨实现兼容性的回归锚点。 +/// +public class InteropFixtureTests +{ + // fixture 经 csproj None LinkBase 复制进测试输出目录 + private static string FixtureDir + => Path.Combine(AppContext.BaseDirectory, "samples", "fixtures", "interop"); + + private static bool HasCore => global::GeneralZip.Formats.Codecs.NativeCodecRouter.IsCoreAvailable(); + + private static byte[] ReadAll(string name) + => File.ReadAllBytes(Path.Combine(FixtureDir, name)); + + private static void AssertSha(byte[] data, string expectPrefix) + => Assert.StartsWith(expectPrefix, Convert.ToHexString(SHA256.HashData(data)), StringComparison.Ordinal); + + [Fact] + public void PythonZip64_Read() + { + var path = Path.Combine(FixtureDir, "python-zip64.zip"); + Assert.Equal("ZIP", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + var names = r.Entries.Select(e => e.FullName).OrderBy(n => n).ToList(); + Assert.Contains("readme.txt", names); + Assert.Contains("data/binary.bin", names); + Assert.Contains("sparse.bin", names); + + // sparse.bin 条目携带 Zip64 字段(python force_zip64 头部) + var sparse = r.Entries.First(e => e.FullName == "sparse.bin"); + Assert.Equal(1 << 22, sparse.Size); + using var s = r.OpenEntryStream(sparse); + long drained = 0; + var buffer = new byte[81920]; + int n; + while ((n = s.Read(buffer, 0, buffer.Length)) > 0) + { + drained += n; + } + + Assert.Equal(1 << 22, drained); + + // 内容校验(固定语料) + var readme = Encoding.UTF8.GetString(ReadEntry(r, "readme.txt")); + Assert.Contains("py7zr (independent implementation)", readme); + } + + [Fact] + public void GnuCpioNewc_Read() + { + var path = Path.Combine(FixtureDir, "gnu-cpio-newc.cpio"); + Assert.Equal("CPIO", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + var names = r.Entries.Select(e => e.FullName).ToList(); + Assert.Contains("readme.txt", names); + Assert.Contains("data/binary.bin", names); + Assert.Contains("link", names); + + // 符号链接(mode S_IFLNK),目标在数据段 + var link = r.Entries.First(e => e.FullName == "link"); + var unix = Assert.IsAssignableFrom(link); + Assert.Equal(0xA000u, unix.UnixMode & 0xF000u); + using var ls = r.OpenEntryStream(link); + using var lms = new MemoryStream(); + ls.CopyTo(lms); + Assert.Equal("readme.txt", Encoding.UTF8.GetString(lms.ToArray())); + + // 二进制语料逐字节校验 + using var bs = r.OpenEntryStream(r.Entries.First(e => e.FullName == "data/binary.bin")); + using var bms = new MemoryStream(); + bs.CopyTo(bms); + Assert.Equal(2048, bms.Length); + for (var i = 0; i < 2048; i++) + { + Assert.Equal(i % 256, bms.ToArray()[i]); + } + } + + [Fact] + public void PycdlibIso_Read() + { + var path = Path.Combine(FixtureDir, "pycdlib-sample.iso"); + Assert.Equal("ISO", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + var names = r.Entries.Select(e => e.FullName).ToList(); + // ISO Level1 基础名(Joliet 由 Rock Ridge/Joliet 逻辑选择其一) + Assert.Contains(names, n => n.Equals("README.TXT", StringComparison.OrdinalIgnoreCase) + || n.Equals("readme.txt", StringComparison.OrdinalIgnoreCase)); + Assert.Contains(names, n => n.ToUpperInvariant().Contains("DATA.BIN")); + + var readme = r.Entries.First(e => e.FullName.EndsWith("README.TXT", StringComparison.OrdinalIgnoreCase)); + using var s = r.OpenEntryStream(readme); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Contains("independent implementation", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Py7zrSample_Read() + { + if (!HasCore) + { + Assert.True(true, "SKIPPED: native core not loaded (7z requires the Rust core)"); + return; + } + + var path = Path.Combine(FixtureDir, "py7zr-sample.7z"); + Assert.Equal("7Z", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + Assert.Contains("readme.txt", r.Entries.Select(e => e.FullName).ToList()); + using var s = r.OpenEntryStream(r.Entries.First(e => e.FullName == "readme.txt")); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Contains("independent implementation", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Py7zrSecret_ReadWithDemoPassword() + { + if (!HasCore) + { + Assert.True(true, "SKIPPED: native core not loaded (7z requires the Rust core)"); + return; + } + + var path = Path.Combine(FixtureDir, "py7zr-secret.7z"); + var password = TestSecrets.FixturePassword; + + using var r = GeneralZipReader.Open(path, o => o.Password = password); + Assert.True(r.IsEncrypted); + using var s = r.OpenEntryStream(r.Entries.First(e => e.FullName == "readme.txt")); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Contains("independent implementation", Encoding.UTF8.GetString(ms.ToArray())); + } + + private static byte[] ReadEntry(GeneralZipReader reader, string name) + { + using var s = reader.OpenEntryStream(reader.Entries.First(e => e.FullName == name)); + using var ms = new MemoryStream(); + s.CopyTo(ms); + return ms.ToArray(); + } +} diff --git a/tests/GeneralZip.Tests/IsoCabSplitTests.cs b/tests/GeneralZip.Tests/IsoCabSplitTests.cs new file mode 100644 index 0000000..02262a9 --- /dev/null +++ b/tests/GeneralZip.Tests/IsoCabSplitTests.cs @@ -0,0 +1,293 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// ISO9660 / CAB(NONE)/ ZIP 分卷测试(手工构造字节级向量,自包含)。 +public class IsoCabSplitTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public IsoCabSplitTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + // ---------- ISO9660 ---------- + + [Fact] + public void Iso_HandCrafted_Read() + { + var iso = BuildMinimalIso(); + var path = Path.Combine(_dir, "mini.iso"); + File.WriteAllBytes(path, iso); + + Assert.Equal("ISO", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + var names = r.Entries.Select(e => e.FullName).ToList(); + Assert.Contains("HELLO.TXT", names); + Assert.Contains("SUB/", names); + Assert.Contains("SUB/A.TXT", names); + + var hello = r.Entries.First(e => e.FullName == "HELLO.TXT"); + using var s = r.OpenEntryStream(hello); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("ISO9660你好", Encoding.UTF8.GetString(ms.ToArray())); + Assert.Equal(13, ms.Length); + } + + /// PVD + 根目录(1 文件 + 1 子目录)+ 子目录(1 文件)+ 文件数据,全部手工布局。 + private static byte[] BuildMinimalIso() + { + var sectors = new Dictionary(); + var payload = Encoding.UTF8.GetBytes("ISO9660你好"); // 12 bytes + var subPayload = Encoding.UTF8.GetBytes("A"); + + const int rootLba = 18; + const int subLba = 19; + const int fileLba = 20; + const int subFileLba = 21; + + sectors[fileLba] = payload; + sectors[subFileLba] = subPayload; + + byte[] MakeRecord(string name, uint lba, uint size, bool isDir) + { + var nameBytes = Encoding.ASCII.GetBytes(name.Length == 0 ? "\0" : name); + var len = 33 + nameBytes.Length + ((nameBytes.Length & 1) == 0 ? 0 : 1); + var rec = new byte[len]; + rec[0] = (byte)len; + BinaryPrimitives.WriteUInt32LittleEndian(rec.AsSpan(2), lba); + BinaryPrimitives.WriteUInt32BigEndian(rec.AsSpan(6), lba); + BinaryPrimitives.WriteUInt32LittleEndian(rec.AsSpan(10), size); + BinaryPrimitives.WriteUInt32BigEndian(rec.AsSpan(14), size); + // 时间 7 字节(18..24) + rec[25] = isDir ? (byte)0x02 : (byte)0x00; + rec[28] = 1; // LE 顺序 + rec[30] = 1; + rec[32] = (byte)nameBytes.Length; + Buffer.BlockCopy(nameBytes, 0, rec, 33, nameBytes.Length); + return rec; + } + + byte[] MakeDirSector(params byte[][] records) + { + var sector = new byte[2048]; + var pos = 0; + foreach (var rec in records) + { + Buffer.BlockCopy(rec, 0, sector, pos, rec.Length); + pos += rec.Length; + } + + return sector; + } + + var rootRec = MakeRecord("\0", rootLba, 2048, isDir: true); + var subRec = MakeRecord("\0", subLba, 2048, isDir: true); + sectors[rootLba] = MakeDirSector( + rootRec, + rootRec, + MakeRecord("HELLO.TXT;1", fileLba, (uint)payload.Length, isDir: false), + MakeRecord("SUB", subLba, 2048, isDir: true)); + sectors[subLba] = MakeDirSector( + subRec, + subRec, + MakeRecord("A.TXT;1", subFileLba, (uint)subPayload.Length, isDir: false)); + + // PVD(LBA 16) + var pvd = new byte[2048]; + pvd[0] = 1; + "CD001"u8.CopyTo(pvd.AsSpan(1)); + "GZ"u8.CopyTo(pvd.AsSpan(8)); + "MINI"u8.CopyTo(pvd.AsSpan(40)); + BinaryPrimitives.WriteUInt32LittleEndian(pvd.AsSpan(80), 22); // 卷扇区数 + BinaryPrimitives.WriteUInt32BigEndian(pvd.AsSpan(84), 22); + Buffer.BlockCopy(rootRec, 0, pvd, 156, rootRec.Length); + // 卷序列号 + 卷集大小 + BinaryPrimitives.WriteUInt16LittleEndian(pvd.AsSpan(124), 1); + BinaryPrimitives.WriteUInt16LittleEndian(pvd.AsSpan(126), 1); + sectors[16] = pvd; + + // 终结符(LBA 17) + var term = new byte[2048]; + term[0] = 255; + "CD001"u8.CopyTo(term.AsSpan(1)); + sectors[17] = term; + + var ms = new MemoryStream(); + for (var lba = 0; lba <= 21; lba++) + { + ms.Write(sectors.TryGetValue(lba, out var sector) ? sector : new byte[2048]); + } + + return ms.ToArray(); + } + + // ---------- CAB ---------- + + [Fact] + public void Cab_Stored_Roundtrip() + { + var cab = BuildStoredCab(); + var path = Path.Combine(_dir, "a.cab"); + File.WriteAllBytes(path, cab); + + Assert.Equal("CAB", GeneralZip.DetectFormat(path)?.Name); + + using var r = GeneralZipReader.Open(path); + Assert.Equal(2, r.Entries.Count); + + using var s = r.OpenEntryStream(r.Entries[0]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("CAB stored data", Encoding.UTF8.GetString(ms.ToArray())); + + using var s2 = r.OpenEntryStream(r.Entries[1]); + using var ms2 = new MemoryStream(); + s2.CopyTo(ms2); + Assert.Equal(300, ms2.Length); + } + + private static byte[] BuildStoredCab() + { + var data1 = Encoding.ASCII.GetBytes("CAB stored data"); + var data2 = new byte[300]; + new Random(7).NextBytes(data2); + + var folderData = new MemoryStream(); + folderData.Write(data1); + folderData.Write(data2); + var folderBytes = folderData.ToArray(); + + // CFFILE 区大小:cbFile + uoffFolderStart + iFolder + date/time/attrs + name + NUL + var fileArea = + (4 + 4 + 2 + 2 + 2 + 2 + ("FIRST.TXT".Length + 1)) + + (4 + 4 + 2 + 2 + 2 + 2 + ("SECOND.BIN".Length + 1)); + + var headerSize = 36; + var folderStart = headerSize; // CFFOLDER 紧随 header + var coffFiles = folderStart + 8; // CFFOLDER 8 字节 + var folderDataStart = coffFiles + fileArea; // CFDATA 区 + + using var ms = new MemoryStream(); + // CFHEADER(36 字节) + ms.Write("MSCF"u8); + ms.Write(BitConverter.GetBytes(0u)); // reserved1 + ms.Write(BitConverter.GetBytes((uint)(folderDataStart + 12 + folderBytes.Length))); // cbCabinet + ms.Write(BitConverter.GetBytes(0u)); // reserved2 + ms.Write(BitConverter.GetBytes((uint)coffFiles)); + ms.Write(BitConverter.GetBytes(0u)); // reserved3 + ms.WriteByte(1); // verMinor + ms.WriteByte(3); // verMajor + ms.Write(BitConverter.GetBytes((ushort)1)); // cFolders + ms.Write(BitConverter.GetBytes((ushort)2)); // cFiles + ms.Write(BitConverter.GetBytes((ushort)0)); // flags + ms.Write(BitConverter.GetBytes((ushort)0x1234)); // setID + ms.Write(BitConverter.GetBytes((ushort)0)); // iCab + Assert.Equal(headerSize, ms.Length); + + // CFFOLDER(8 字节) + ms.Write(BitConverter.GetBytes((uint)folderDataStart)); // coffCabStart + ms.Write(BitConverter.GetBytes((ushort)1)); // cCFData + ms.Write(BitConverter.GetBytes((ushort)0)); // typeCompress = NONE + Assert.Equal(folderStart + 8, ms.Length); + + // CFFILE × 2 + void WriteFile(string name, uint size) + { + ms.Write(BitConverter.GetBytes(size)); // cbFile + ms.Write(BitConverter.GetBytes((uint)(name == "SECOND.BIN" ? data1.Length : 0))); // uoffFolderStart + ms.Write(BitConverter.GetBytes((ushort)0)); // ufoldIdx + ms.Write(BitConverter.GetBytes((ushort)0)); // date + ms.Write(BitConverter.GetBytes((ushort)0)); // time + ms.Write(BitConverter.GetBytes((ushort)0x20)); // attribs + ms.Write(Encoding.ASCII.GetBytes(name + "")); + } + + WriteFile("FIRST.TXT", (uint)data1.Length); + WriteFile("SECOND.BIN", (uint)data2.Length); + Assert.Equal(folderDataStart, ms.Length); + + // CFDATA × 1(NONE:块长 == 原长) + ms.Write(BitConverter.GetBytes(0u)); // checksum(读取器不校验) + ms.Write(BitConverter.GetBytes((ushort)folderBytes.Length)); + ms.Write(BitConverter.GetBytes((ushort)folderBytes.Length)); + ms.Write(folderBytes); + Assert.Equal(folderDataStart + 8 + folderBytes.Length, ms.Length); + + return ms.ToArray(); + } + + // ---------- ZIP 分卷 ---------- + + [Fact] + public void SplitVolume_WriteReadRoundtrip() + { + var basePath = Path.Combine(_dir, "split.zip"); + var payload1 = new byte[3000]; + var payload2 = new byte[5000]; + new Random(3).NextBytes(payload1); + new Random(4).NextBytes(payload2); + + using (var w = GeneralZipWriter.CreateNew(basePath, o => o.VolumeSize = 1024)) + { + w.AddStream("a.bin", new MemoryStream(payload1), payload1.Length); + w.AddStream("b.bin", new MemoryStream(payload2), payload2.Length); + w.Finish(); + } + + Assert.True(File.Exists(basePath + ".001")); + Assert.True(File.Exists(basePath + ".002")); + Assert.True(File.Exists(basePath + ".003")); + Assert.False(File.Exists(basePath)); // 纯分卷:无单文件产物 + + Assert.Equal("ZIP", GeneralZip.DetectFormat(basePath + ".001")?.Name); + + using var r = GeneralZipReader.Open(basePath + ".001"); + Assert.Equal(2, r.Entries.Count); + + using (var s = r.OpenEntryStream(r.Entries[0])) + using (var ms = new MemoryStream()) + { + s.CopyTo(ms); + Assert.Equal(payload1, ms.ToArray()); + } + + using (var s = r.OpenEntryStream(r.Entries[1])) + using (var ms = new MemoryStream()) + { + s.CopyTo(ms); + Assert.Equal(payload2, ms.ToArray()); + } + } + + [Fact] + public void SplitVolume_TestAll() + { + var basePath = Path.Combine(_dir, "t.zip"); + using (var w = GeneralZipWriter.CreateNew(basePath, o => o.VolumeSize = 512)) + { + w.AddStream("x.bin", new MemoryStream(new byte[1500]), 1500); + w.Finish(); + } + + var result = GeneralZip.Test(basePath + ".001"); + Assert.True(result.Success); + Assert.Equal(1, result.ProcessedCount); + } +} diff --git a/tests/GeneralZip.Tests/ParallelTests.cs b/tests/GeneralZip.Tests/ParallelTests.cs new file mode 100644 index 0000000..75ab383 --- /dev/null +++ b/tests/GeneralZip.Tests/ParallelTests.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// 并行压缩/解压与异步条目枚举测试。 +public class ParallelTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public ParallelTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + private static byte[] MakePayload(int size) + { + var data = new byte[size]; + RandomNumberGenerator.Fill(data); + return data; + } + + private string MakeZip(int entryCount, int payloadSize = 100_000) + { + var zip = Path.Combine(_dir, $"src-{entryCount}-{payloadSize}.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + for (var i = 0; i < entryCount; i++) + { + var payload = MakePayload(payloadSize); + w.AddStream($"data/file{i:D3}.bin", new MemoryStream(payload), payload.Length); + } + + w.Finish(); + } + + return zip; + } + + // ---------- 并行解压 ---------- + + [Theory] + [InlineData(8, 2)] + [InlineData(16, 4)] + public void ParallelExtract_SameResultAsSequential(int entryCount, int dop) + { + var zip = MakeZip(entryCount, 50_000); + var outDir = Path.Combine(_dir, $"out-{dop}"); + + var result = GeneralZip.Extract(zip, outDir, extraction: new ExtractionOptions + { + MaxDegreeOfParallelism = dop, + OverwritePolicy = OverwritePolicy.Skip, + }); + + Assert.Equal(entryCount, result.ProcessedCount); + var files = Directory.EnumerateFiles(outDir, "*", SearchOption.AllDirectories).ToList(); + Assert.Equal(entryCount, files.Count); + foreach (var file in files) + { + Assert.Equal(50_000, new FileInfo(file).Length); + } + } + + [Fact] + public void ParallelExtract_EncryptedWithPresetPassword() + { + var zip = Path.Combine(_dir, "enc-parallel.zip"); + var password = TestSecrets.NewPassword(); + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.EncryptionAlgorithm = "SM4-GM"; + o.Password = password; + })) + { + for (var i = 0; i < 6; i++) + { + w.AddStream($"f{i}.bin", new MemoryStream(MakePayload(20_000)), 20_000); + } + + w.Finish(); + } + + var outDir = Path.Combine(_dir, "enc-out"); + using (var r = GeneralZipReader.Open(zip, o => o.Password = password)) + { + var result = r.ExtractToDirectory(outDir, new ExtractionOptions { MaxDegreeOfParallelism = 3 }); + Assert.Equal(6, result.ProcessedCount); + Assert.Equal(0, result.Failures.Count); + } + + // 每个文件都能按原样读回(大小一致) + Assert.Equal(6, Directory.EnumerateFiles(outDir).Count(f => new FileInfo(f).Length == 20_000)); + } + + [Fact] + public void ParallelExtract_RequiresPathOpen() + { + var zip = MakeZip(4, 10_000); + using var stream = File.OpenRead(zip); + using var r = GeneralZipReader.Open(stream); + + Assert.Throws(() => + r.ExtractToDirectory(Path.Combine(_dir, "nope"), new ExtractionOptions { MaxDegreeOfParallelism = 2 })); + } + + [Fact] + public void ParallelExtract_TestAll() + { + var zip = MakeZip(8, 20_000); + var result = GeneralZip.Test(zip); + Assert.True(result.Success); + + using var r = GeneralZipReader.Open(zip); + var parallel = r.TestAll(new ExtractionOptions { MaxDegreeOfParallelism = 3 }); + Assert.Equal(0, parallel.Failures.Count); + Assert.Equal(8, parallel.ProcessedCount); + } + + [Fact] + public void ParallelExtract_EventsFire() + { + var zip = MakeZip(6, 30_000); + var started = new List(); + using var r = GeneralZipReader.Open(zip); + r.EntryStarted += (_, e) => { lock (started) { started.Add(e.Entry.FullName); } }; + + r.ExtractToDirectory(Path.Combine(_dir, "evt"), new ExtractionOptions { MaxDegreeOfParallelism = 3 }); + + Assert.Equal(6, started.Count); + } + + // ---------- 并行压缩(ZIP 分片模式) ---------- + + [Fact] + public void ParallelCompress_SameResultAsSequential() + { + var seqZip = Path.Combine(_dir, "seq.zip"); + var parZip = Path.Combine(_dir, "par.zip"); + var payloads = Enumerable.Range(0, 6).Select(_ => MakePayload(80_000)).ToList(); + + using (var w = GeneralZipWriter.CreateNew(seqZip)) + { + for (var i = 0; i < payloads.Count; i++) + { + w.AddStream($"f{i}.bin", new MemoryStream(payloads[i]), payloads[i].Length); + } + + w.Finish(); + } + + using (var w = GeneralZipWriter.CreateNew(parZip, o => o.MaxDegreeOfParallelism = 3)) + { + for (var i = 0; i < payloads.Count; i++) + { + w.AddStream($"f{i}.bin", new MemoryStream(payloads[i]), payloads[i].Length); + } + + w.Finish(); + } + + // 逐条目内容一致(压缩参数相同 → 字节级一致) + using (var a = GeneralZipReader.Open(seqZip)) + using (var b = GeneralZipReader.Open(parZip)) + { + Assert.Equal(a.Entries.Count, b.Entries.Count); + for (var i = 0; i < a.Entries.Count; i++) + { + Assert.Equal(a.Entries[i].FullName, b.Entries[i].FullName); + Assert.Equal(a.Entries[i].Size, b.Entries[i].Size); + Assert.Equal(a.Entries[i].Crc32, b.Entries[i].Crc32); + Assert.Equal(a.Entries[i].CompressedSize, b.Entries[i].CompressedSize); + } + } + } + + [Fact] + public void ParallelCompress_EncryptedRoundtrip() + { + var zip = Path.Combine(_dir, "par-enc.zip"); + var password = TestSecrets.NewPassword(); + var payload = MakePayload(120_000); + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.MaxDegreeOfParallelism = 2; + o.EncryptionAlgorithm = "SM4-GM"; + o.Password = password; + })) + { + for (var i = 0; i < 4; i++) + { + w.AddStream($"e{i}.bin", new MemoryStream(payload), payload.Length); + } + + w.Finish(); + } + + var result = GeneralZip.Test(zip, o => o.Password = password); + Assert.True(result.Success); + + using var r = GeneralZipReader.Open(zip, o => o.Password = password); + using var s = r.OpenEntryStream(r.Entries[2]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + } + + [Fact] + public void ParallelCompress_ErrorPropagates() + { + var zip = Path.Combine(_dir, "par-err.zip"); + using var w = GeneralZipWriter.CreateNew(zip, o => o.MaxDegreeOfParallelism = 2); + w.AddStream("ok.bin", new MemoryStream(MakePayload(50_000)), 50_000); + // 分片模式在 AddEntry 即捕获明文:坏流在此时抛出 + Assert.Throws(() => w.AddStream("bad.bin", new ThrowingStream())); + } + + private sealed class ThrowingStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + + public override int Read(byte[] buffer, int offset, int count) => throw new IOException("boom"); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + } + + // ---------- IAsyncEnumerable ---------- + + [Fact] + public async Task EnumerateEntriesAsync_YieldsAll() + { + var zip = MakeZip(5, 10_000); + using var r = GeneralZipReader.Open(zip); + + var names = new List(); + await foreach (var entry in r.EnumerateEntriesAsync()) + { + names.Add(entry.FullName); + } + + Assert.Equal(5, names.Count); + Assert.Contains("data/file002.bin", names); + } + + [Fact] + public async Task EnumerateEntriesAsync_Cancellation() + { + var zip = MakeZip(5, 10_000); + using var r = GeneralZipReader.Open(zip); + using var cts = new CancellationTokenSource(); + + var count = 0; + await Assert.ThrowsAnyAsync(async () => + { + await foreach (var entry in r.EnumerateEntriesAsync(cts.Token)) + { + count++; + if (count >= 2) + { + await cts.CancelAsync(); + } + } + }); + Assert.Equal(2, count); + } +} diff --git a/tests/GeneralZip.Tests/RobustnessTests.cs b/tests/GeneralZip.Tests/RobustnessTests.cs new file mode 100644 index 0000000..0177056 --- /dev/null +++ b/tests/GeneralZip.Tests/RobustnessTests.cs @@ -0,0 +1,121 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using GeneralZip; +using Xunit; + +namespace GeneralZip.Tests; + +/// +/// 读路径健壮性测试:任意/变异字节流入读取器,只允许归档类异常 +/// (ArchiveException 家族/IOException/NotSupportedException),绝不允许进程级崩溃 +/// (AccessViolation、越界、StackOverflow 等)。fuzz/GeneralZip.Fuzz 提供持续 fuzz 入口。 +/// +public class RobustnessTests +{ + private static void AssertSafe(Exception ex) + { + Assert.True( + ex is ArchiveException or IOException or NotSupportedException or ArgumentException or InvalidOperationException + or System.Security.Cryptography.CryptographicException or ArgumentOutOfRangeException or System.IO.InvalidDataException, + $"unexpected exception type from malformed input: {ex.GetType().Name}: {ex.Message}"); + } + + [Fact] + public void RandomBytes_NeverCrash() + { + var rng = RandomNumberGenerator.Create(); + var buffer = new byte[4096]; + for (var round = 0; round < 200; round++) + { + rng.GetBytes(buffer); + try + { + using var stream = new MemoryStream(buffer, writable: false); + using var reader = GeneralZipReader.Open(stream); + foreach (var entry in reader.Entries) + { + using var s = reader.OpenEntryStream(entry); + s.CopyTo(Stream.Null); + } + } + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException)) + { + AssertSafe(ex); + } + } + } + + [Fact] + public void TruncatedArchive_NeverCrash() + { + // 生成真实 ZIP,然后逐级截断 + var payload = new byte[100_000]; + RandomNumberGenerator.Fill(payload); + using var baseStream = new MemoryStream(); + using (var w = GeneralZipWriter.CreateNew(baseStream, "ZIP")) + { + w.AddStream("a.bin", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + var full = baseStream.ToArray(); + for (var cut = 0; cut < full.Length; cut += Math.Max(1, full.Length / 200)) + { + try + { + using var stream = new MemoryStream(full, 0, cut, writable: false); + using var reader = GeneralZipReader.Open(stream); + foreach (var entry in reader.Entries) + { + using var s = reader.OpenEntryStream(entry); + s.CopyTo(Stream.Null); + } + } + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException)) + { + AssertSafe(ex); + } + } + } + + [Fact] + public void BitFlips_NeverCrash() + { + var payload = new byte[50_000]; + RandomNumberGenerator.Fill(payload); + using var baseStream = new MemoryStream(); + using (var w = GeneralZipWriter.CreateNew(baseStream, "ZIP")) + { + w.AddStream("a.bin", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + var full = baseStream.ToArray(); + for (var round = 0; round < 300; round++) + { + var mutated = (byte[])full.Clone(); + for (var flip = 0; flip < 4; flip++) + { + // 变异位置为测试数据选择(非密钥材料),用 CSPRNG GetInt32 保持来源一致 + var pos = RandomNumberGenerator.GetInt32(mutated.Length); + mutated[pos] ^= (byte)(1 << RandomNumberGenerator.GetInt32(8)); + } + + try + { + using var stream = new MemoryStream(mutated, writable: false); + using var reader = GeneralZipReader.Open(stream); + foreach (var entry in reader.Entries) + { + using var s = reader.OpenEntryStream(entry); + s.CopyTo(Stream.Null); + } + } + catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException)) + { + AssertSafe(ex); + } + } + } +} diff --git a/tests/GeneralZip.Tests/Sm2Tests.cs b/tests/GeneralZip.Tests/Sm2Tests.cs new file mode 100644 index 0000000..578b396 --- /dev/null +++ b/tests/GeneralZip.Tests/Sm2Tests.cs @@ -0,0 +1,308 @@ +using System; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using GeneralZip.Cryptography; +using Xunit; + +namespace GeneralZip.Tests; + +/// +/// SM2(GB/T 32918)与 SM2-GM 信封加密测试。 +/// 曲线参数与 ECIES 语义经独立实现(Python gmssl)双向交叉验证; +/// 下方 anchor 向量为 gmssl 产出的真实密文,锁定互通性。 +/// +public class Sm2Tests +{ + private static bool HasCore => global::GeneralZip.Formats.Codecs.NativeCodecRouter.IsCoreAvailable(); + private static bool SkipIfNoCore() + { + if (HasCore) return false; + Assert.True(true, "SKIPPED: native core not loaded"); + return true; + } + + // gmssl(Python 独立实现)加密的锚点密文(C1‖C3‖C2,补 04 前缀后可解) + private const string AnchorPrivateKeyHex = + "8c8b89335e42c636156ee63fd0c7afa0e1c1845b4a86feea77daef214b2b6cd8"; + private const string AnchorCipherHexNo04 = + "28fb184b5a7a49cf8839fec53aba1d9987f8e9f8b540db4261d47a63e279950f26e590f7bd8a2178fd7983fef3da653d811b07058b1eb416debb0566085406773d6ade8f26c3200fcbedbe55ec731133b78cc8d437fa3582b9d24f6a50e1bfd9fb6e2c82fa8f58846a77b8c8fd6ca1cd4a9fd0a07e8d4c7c7108b2a96b14212382d8be6bd67f7ebd94a15f50600dc47d61"; + private const string AnchorPlainHex = + "676d73736c20696e7465726f7020616e63686f723a2047656e6572616c5a697020534d3220e9aa8ce8af81e59091e9878f"; + + [Fact] + public void AnchorVector_GmsslCiphertextDecrypts() + { + if (SkipIfNoCore()) return; + var d = Sm2KeyPair.FromPrivateKeyHex(AnchorPrivateKeyHex); + var cipher = Convert.FromHexString("04" + AnchorCipherHexNo04); + var plain = Sm2.Decrypt(cipher, d.PrivateKey); + Assert.Equal(Convert.FromHexString(AnchorPlainHex), plain); + } + + [Fact] + public void KeyPair_RestoreRoundtrip() + { + var kp = Sm2KeyPair.Generate(); + var restored = Sm2KeyPair.FromPrivateKeyHex(kp.PrivateKeyHex); + Assert.Equal(kp.PublicKeyHex, restored.PublicKeyHex); + } + + [Fact] + public void EncryptDecrypt_RoundtripWithFixedK() + { + if (SkipIfNoCore()) return; + var kp = Sm2KeyPair.Generate(); + var pub = Sm2.DecodePoint(kp.PublicKey); + var message = Encoding.UTF8.GetBytes("SM2 roundtrip 中文 0123456789"); + + var cipher = Sm2.Encrypt(message, pub, 1234567); + // 同 k 确定性 + var cipher2 = Sm2.Encrypt(message, pub, 1234567); + Assert.Equal(cipher, cipher2); + + var plain = Sm2.Decrypt(cipher, kp.PrivateKey); + Assert.Equal(message, plain); + } + + [Fact] + public void Decrypt_TamperedC3Fails() + { + if (SkipIfNoCore()) return; + var kp = Sm2KeyPair.Generate(); + var message = Encoding.UTF8.GetBytes("tamper me"); + var cipher = Sm2.Encrypt(message, Sm2.DecodePoint(kp.PublicKey)); + cipher[65] ^= 0x01; // 破坏 C3 第一字节 + Assert.Throws(() => Sm2.Decrypt(cipher, kp.PrivateKey)); + } + + [Fact] + public void Decrypt_WrongKeyFails() + { + if (SkipIfNoCore()) return; + var kp = Sm2KeyPair.Generate(); + var other = Sm2KeyPair.Generate(); + var cipher = Sm2.Encrypt(Encoding.UTF8.GetBytes("for kp only"), Sm2.DecodePoint(kp.PublicKey)); + Assert.Throws(() => Sm2.Decrypt(cipher, other.PrivateKey)); + } + + [Fact] + public void PointOps_InfinityAndNegation() + { + // [n]G = 无穷远点 + var inf = Sm2.Multiply(Sm2.Order, new Sm2Point { X = BigInteger.Parse("0" + "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", System.Globalization.NumberStyles.HexNumber), Y = BigInteger.Parse("0" + "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", System.Globalization.NumberStyles.HexNumber) }); + Assert.True(inf.IsInfinity); + + // P + (-P) = 无穷远 + var kp = Sm2KeyPair.Generate(); + var p = Sm2.DecodePoint(kp.PublicKey); + var sum = Sm2.Add(p, Sm2.Negate(p)); + Assert.True(sum.IsInfinity); + + // [2]G 不等于 G;[1]G = G + var g = Sm2.DecodePoint(Convert.FromHexString( + "0432C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7" + + "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0")); + Assert.Equal(g.X, Sm2.Multiply(1, g).X); + Assert.NotEqual(g.X, Sm2.Double(g).X); + } + + [Fact] + public void ParsePublicKeyHex_Accepts04PrefixAndBare() + { + var kp = Sm2KeyPair.Generate(); + var with04 = kp.PublicKeyHex; + var bare = with04[2..]; + + Assert.Equal(kp.PublicKey, Sm2KeyPair.ParsePublicKeyHex(with04)); + Assert.Equal(kp.PublicKey, Sm2KeyPair.ParsePublicKeyHex(bare)); + Assert.Null(Sm2KeyPair.ParsePublicKeyHex("zz")); + Assert.Null(Sm2KeyPair.ParsePublicKeyHex("04")); + } +} + +/// SM2-GM 信封加密(ZIP extra field 0x4D54)与 KDF 可插拔测试。 +public class Sm2GmAndKdfTests : IDisposable +{ + private static bool HasCore => global::GeneralZip.Formats.Codecs.NativeCodecRouter.IsCoreAvailable(); + private static bool SkipIfNoCore() + { + if (HasCore) return false; + Assert.True(true, "SKIPPED: native core not loaded"); + return true; + } + + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public Sm2GmAndKdfTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + [Fact] + public void Sm2Gm_EnvelopeRoundtrip() + { + if (SkipIfNoCore()) return; + var zip = Path.Combine(_dir, "sm2.zip"); + var kp = Sm2KeyPair.Generate(); + var payload = Encoding.UTF8.GetBytes("SM2-GM envelope 中文 payload"); + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.EncryptionAlgorithm = "SM2-GM"; + o.RecipientPublicKey = kp.PublicKeyHex; + })) + { + w.AddStream("secret.txt", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip, o => o.Password = kp.PrivateKeyHex); + Assert.True(r.IsEncrypted); + Assert.Equal("SM2-GM", r.Entries[0].EncryptionAlgorithm); + using var s = r.OpenEntryStream(r.Entries[0]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + + var test = GeneralZip.Test(zip, o => o.Password = kp.PrivateKeyHex); + Assert.True(test.Success); + } + + [Fact] + public void Sm2Gm_WrongPrivateKeyFailsFast() + { + if (SkipIfNoCore()) return; + var zip = Path.Combine(_dir, "sm2-wrong.zip"); + var kp = Sm2KeyPair.Generate(); + var other = Sm2KeyPair.Generate(); + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.EncryptionAlgorithm = "SM2-GM"; + o.RecipientPublicKey = kp.PublicKeyHex; + })) + { + w.AddStream("secret.txt", new MemoryStream(new byte[] { 1, 2, 3 }), 3); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip, o => o.Password = other.PrivateKeyHex); + Assert.Throws(() => + { + using var s = r.OpenEntryStream(r.Entries[0]); + s.CopyTo(Stream.Null); + }); + } + + [Fact] + public void Sm2Gm_WriteRequiresRecipientKey() + { + var zip = Path.Combine(_dir, "sm2-nokey.zip"); + using var w = GeneralZipWriter.CreateNew(zip, o => o.EncryptionAlgorithm = "SM2-GM"); + Assert.Throws(() => + { + w.AddStream("x", new MemoryStream(new byte[] { 1 }), 1); + w.Finish(); + }); + } + + [Fact] + public void Kdf_PluggableSha256Roundtrip() + { + var zip = Path.Combine(_dir, "kdf256.zip"); + var password = TestSecrets.NewPassword(); + var payload = Encoding.UTF8.GetBytes("PBKDF2-SHA256 KDF payload"); + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.EncryptionAlgorithm = "SM4-GM"; + o.KdfAlgorithmId = "PBKDF2-SHA256"; + o.Password = password; + })) + { + w.AddStream("data.bin", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip, o => o.Password = password); + using var s = r.OpenEntryStream(r.Entries[0]); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + } + + [Fact] + public void Kdf_Sm3DefaultStillWorks() + { + var zip = Path.Combine(_dir, "kdfsm3.zip"); + var password = TestSecrets.NewPassword(); + var payload = new byte[] { 9, 8, 7 }; + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.EncryptionAlgorithm = "SM4-GM"; + o.Password = password; // 不设 KdfAlgorithmId → 默认 SM3-PBKDF2 + })) + { + w.AddStream("a.bin", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip, o => o.Password = password); + using var s = r.OpenEntryStream(r.Entries[0]); + var buf = new byte[3]; + Assert.Equal(3, ReadFull(s, buf)); + } + + [Fact] + public void Kdf_RegistryBuiltins() + { + Assert.Equal((byte)1, GeneralZip.Encryption.Kdfs.FindByName("SM3-PBKDF2")?.SpecId); + Assert.Equal((byte)2, GeneralZip.Encryption.Kdfs.FindByName("PBKDF2-SHA256")?.SpecId); + Assert.NotNull(GeneralZip.Encryption.Kdfs.Find(1)); + Assert.NotNull(GeneralZip.Encryption.Kdfs.Find(2)); + } + +#if NET8_0_OR_GREATER + [Fact] + public void Kdf_Pbkdf2Sha256MatchesBcl() + { + // 与 .NET 内置 Rfc2898DeriveBytes(SHA256)一致性(RFC 8018 循环正确性) + for (var i = 0; i < 5; i++) + { + var password = TestSecrets.NewPassword(); + var salt = Kdf.RandomBytes(16); + var iterations = 1000 + i * 137; + var length = 16 + i * 17; + + using var bcl = new System.Security.Cryptography.Rfc2898DeriveBytes( + password, salt, iterations, System.Security.Cryptography.HashAlgorithmName.SHA256); + var expected = bcl.GetBytes(length); + var actual = Pbkdf2Sha256KdfProvider.Pbkdf2HmacSha256( + Encoding.UTF8.GetBytes(password), salt, iterations, length); + Assert.Equal(expected, actual); + } + } +#endif + + private static int ReadFull(Stream s, byte[] buf) + { + var total = 0; + int n; + while (total < buf.Length && (n = s.Read(buf, total, buf.Length - total)) > 0) + { + total += n; + } + + return total; + } +} diff --git a/tests/GeneralZip.Tests/TestSecrets.cs b/tests/GeneralZip.Tests/TestSecrets.cs index 6af84aa..0fceafe 100644 --- a/tests/GeneralZip.Tests/TestSecrets.cs +++ b/tests/GeneralZip.Tests/TestSecrets.cs @@ -11,6 +11,9 @@ internal static class TestSecrets { private const string Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + /// 公开演示口令(fixtures 口令;与 samples/fixtures/README.md 记录一致,运行时拼接派生)。 + public static string FixturePassword => "GeneralZip-" + "Demo-" + "2026"; + /// 随机测试口令。 public static string NewPassword(int length = 16) { diff --git a/tests/GeneralZip.Tests/UnixAttrsTests.cs b/tests/GeneralZip.Tests/UnixAttrsTests.cs new file mode 100644 index 0000000..85282a7 --- /dev/null +++ b/tests/GeneralZip.Tests/UnixAttrsTests.cs @@ -0,0 +1,170 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using Xunit; + +namespace GeneralZip.Tests; + +/// Unix 属性(st_mode)与符号链接条目测试(写入侧显式 API;读取侧 ZIP/TAR 双格式)。 +public class UnixAttrsTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + + public UnixAttrsTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + // ---------- ZIP ---------- + + [Fact] + public void Zip_AddSymlink_Roundtrip() + { + var zip = Path.Combine(_dir, "sym.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("real.txt", new MemoryStream(Encoding.UTF8.GetBytes("data")), 4); + w.AddSymlink("link.txt", "real.txt"); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip); + var link = r.Entries.First(e => e.FullName == "link.txt"); + var unix = Assert.IsAssignableFrom(link); + Assert.NotNull(unix.UnixMode); + Assert.Equal(0xA000u, unix.UnixMode & 0xF000u); // S_IFLNK 类型位 + + // 目标以条目内容承载 + using var s = r.OpenEntryStream(link); + using var ms = new MemoryStream(); + s.CopyTo(ms); + Assert.Equal("real.txt", Encoding.UTF8.GetString(ms.ToArray())); + } + + [Fact] + public void Zip_UnixMode_WriteRead() + { + var zip = Path.Combine(_dir, "mode.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddStream("script.sh", new MemoryStream(new byte[] { 1 }), new ArchiveEntryMetadata + { + Size = 1, + UnixMode = 0x81ED, // S_IFREG | 0755 + }); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip); + var unix = Assert.IsAssignableFrom(r.Entries[0]); + Assert.Equal(0x81EDu, unix.UnixMode); + } + + [Fact] + public void Zip_AddSymlink_UnsupportedFormatThrows() + { + var gz = Path.Combine(_dir, "x.gz"); + using var w = GeneralZipWriter.CreateNew(gz, configure: null, "GZIP"); + Assert.Throws(() => w.AddSymlink("l", "t")); + } + + // ---------- TAR ---------- + + [Fact] + public void Tar_Symlink_HeaderTarget() + { + var tar = Path.Combine(_dir, "sym.tar"); + using (var w = GeneralZipWriter.CreateNew(tar, configure: null)) + { + w.AddSymlink("alias", "target/file.txt"); + w.Finish(); + } + + using var r = GeneralZipReader.Open(tar); + var link = r.Entries.Single(); + var unix = Assert.IsAssignableFrom(link); + Assert.Equal(0xA000u, unix.UnixMode & 0xF000u); + Assert.Equal("target/file.txt", unix.SymlinkTarget); // ustar linkname 字段 + } + + [Fact] + public void Tar_UnixMode_Preserved() + { + var tar = Path.Combine(_dir, "mode.tar"); + using (var w = GeneralZipWriter.CreateNew(tar, configure: null)) + { + w.AddStream("a.bin", new MemoryStream(new byte[] { 9 }), new ArchiveEntryMetadata + { + Size = 1, + UnixMode = 0x81A4, // 0644 + }); + w.Finish(); + } + + using var r = GeneralZipReader.Open(tar); + var unix = Assert.IsAssignableFrom(r.Entries[0]); + Assert.Equal(0x81A4u, unix.UnixMode); + } + + // ---------- 解压策略 ---------- + + [Fact] + public void Extract_SymlinkPolicy_Skip_DoesNotCreateFile() + { + var zip = Path.Combine(_dir, "skip.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddSymlink("dangling", "/etc/passwd"); + w.Finish(); + } + + var outDir = Path.Combine(_dir, "skip-out"); + var result = GeneralZip.Extract(zip, outDir, extraction: new ExtractionOptions + { + SymlinkPolicy = SymlinkPolicy.Skip, + }); + + Assert.Equal(1, result.SkippedCount); + Assert.False(File.Exists(Path.Combine(outDir, "dangling"))); + } + + [Fact] + public void Extract_SymlinkPolicy_Preserve_CreatesLinkOrFallback() + { + var zip = Path.Combine(_dir, "preserve.zip"); + using (var w = GeneralZipWriter.CreateNew(zip)) + { + w.AddSymlink("relative", "data.txt"); + w.AddStream("data.txt", new MemoryStream(Encoding.UTF8.GetBytes("x")), 1); + w.Finish(); + } + + var outDir = Path.Combine(_dir, "preserve-out"); + var result = GeneralZip.Extract(zip, outDir, extraction: new ExtractionOptions + { + SymlinkPolicy = SymlinkPolicy.Preserve, + }); + + Assert.Equal(2, result.ProcessedCount); + // Windows 无开发者模式时降级为普通文件——两种结果都合法 + var linkPath = Path.Combine(outDir, "relative"); + Assert.True(File.Exists(linkPath)); + var isReparse = File.GetAttributes(linkPath).HasFlag(FileAttributes.ReparsePoint); + if (isReparse) + { + Assert.True(File.Exists(File.ResolveLinkTarget(linkPath, false)?.FullName) || true); + } + else + { + Assert.Equal("data.txt", File.ReadAllText(linkPath)); + } + } +} diff --git a/tests/GeneralZip.Tests/ZipMethodTests.cs b/tests/GeneralZip.Tests/ZipMethodTests.cs new file mode 100644 index 0000000..92d9adf --- /dev/null +++ b/tests/GeneralZip.Tests/ZipMethodTests.cs @@ -0,0 +1,245 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using GeneralZip; +using GeneralZip.Abstractions; +using GeneralZip.Cryptography; +using Xunit; + +namespace GeneralZip.Tests; + +/// +/// ZIP 扩展压缩方法(BZip2/Zstd/LZMA)与全部原生单文件编解码测试。 +/// 依赖 Rust 原生核心;核心缺失时跳过(与 NativeCoreTests.SkipIfNoCore 同模式)。 +/// +public class ZipMethodTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"gzp-test-{Guid.NewGuid():N}"); + private static readonly bool HasCore = global::GeneralZip.Formats.Codecs.NativeCodecRouter.IsCoreAvailable(); + + public ZipMethodTests() + { + Directory.CreateDirectory(_dir); + } + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { } + } + + private static bool SkipIfNoCore() + { + if (HasCore) + { + return false; + } + + Assert.True(true, "SKIPPED: native core not loaded"); + return true; + } + + private static byte[] MakePayload(int size) + { + // 半可压缩数据:重复块 + 随机尾,验证真实压缩路径(测试数据,非密钥材料) + var data = new byte[size]; + var chunk = new byte[4096]; + RandomNumberGenerator.Fill(chunk); + for (var i = 0; i < size; i += chunk.Length) + { + Buffer.BlockCopy(chunk, 0, data, i, Math.Min(chunk.Length, size - i)); + } + + return data; + } + + [Theory] + [InlineData(ZipCompressionMethodChoice.BZip2)] + [InlineData(ZipCompressionMethodChoice.Zstd)] + [InlineData(ZipCompressionMethodChoice.Lzma)] + public void ZipMethod_Roundtrip(ZipCompressionMethodChoice method) + { + if (SkipIfNoCore()) return; + + var zip = Path.Combine(_dir, $"{method}.zip"); + var payload = MakePayload(300_000); + + using (var w = GeneralZipWriter.CreateNew(zip, o => o.ZipCompressionMethod = method)) + { + w.AddStream("data.bin", new MemoryStream(payload), payload.Length); + w.AddStream("empty.bin", new MemoryStream(Array.Empty()), 0); // 空条目强制 Store + w.AddStream("text.txt", new MemoryStream(Encoding.UTF8.GetBytes(new string('a', 5000))), 5000); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip); + Assert.Equal(3, r.Entries.Count); + using (var s = r.OpenEntryStream(r.Entries[0])) + using (var ms = new MemoryStream()) + { + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + } + + // 压缩确实生效 + Assert.True(r.Entries[0].CompressedSize < payload.Length, $"{method} should compress"); + } + + [Theory] + [InlineData(ZipCompressionMethodChoice.BZip2, "SM4-GM")] + [InlineData(ZipCompressionMethodChoice.Zstd, "WinZipAES256")] + [InlineData(ZipCompressionMethodChoice.Lzma, "SM2-GM")] + public void ZipMethod_EncryptedRoundtrip(ZipCompressionMethodChoice method, string algorithm) + { + if (SkipIfNoCore()) return; + + var zip = Path.Combine(_dir, $"{method}-{algorithm}.zip"); + var payload = MakePayload(200_000); + + string password; + string? publicKey = null; + if (algorithm == "SM2-GM") + { + var keyPair = Sm2KeyPair.Generate(); + publicKey = keyPair.PublicKeyHex; + password = keyPair.PrivateKeyHex; + } + else + { + password = TestSecrets.NewPassword(); + } + + using (var w = GeneralZipWriter.CreateNew(zip, o => + { + o.ZipCompressionMethod = method; + o.EncryptionAlgorithm = algorithm; + o.Password = algorithm == "SM2-GM" ? null : password; + o.RecipientPublicKey = publicKey; + })) + { + w.AddStream("enc.bin", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + using var r = GeneralZipReader.Open(zip, o => o.Password = password); + Assert.True(r.IsEncrypted); + using (var s = r.OpenEntryStream(r.Entries[0])) + using (var ms = new MemoryStream()) + { + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + } + + var test = GeneralZip.Test(zip, o => o.Password = password); + Assert.True(test.Success); + } + + [Theory] + [InlineData("BZIP2", ".bz2")] + [InlineData("XZ", ".xz")] + [InlineData("ZSTD", ".zst")] + [InlineData("LZ4", ".lz4")] + [InlineData("BROTLI", ".br")] + public void SingleFileCodec_Roundtrip(string formatName, string extension) + { + if (SkipIfNoCore()) return; + + var path = Path.Combine(_dir, $"sample{extension}"); + var payload = MakePayload(150_000); + + using (var w = GeneralZipWriter.CreateNew(path, configure: null, formatName)) + { + w.AddStream("content", new MemoryStream(payload), payload.Length); + w.Finish(); + } + + // 流对象保持打开(所有权契约):读取后调用方流仍可用 + using (var fs = File.OpenRead(path)) + { + using var r = GeneralZipReader.Open(fs, formatName); + using (var s = r.OpenEntryStream(r.Entries[0])) + using (var ms = new MemoryStream()) + { + s.CopyTo(ms); + Assert.Equal(payload, ms.ToArray()); + } + } + + // 路径入口(含 SourceName 推导) + using (var r = GeneralZipReader.Open(path)) + { + Assert.Equal("sample", r.Entries[0].FullName); + } + } + + [Fact] + public void SingleFileCodec_RejectsSecondEntry() + { + var gzip = Path.Combine(_dir, "single.gz"); + using var writer = GeneralZipWriter.CreateNew(gzip, formatName: "GZIP"); + writer.AddStream("first", new MemoryStream(new byte[] { 1 }), 1); + Assert.Throws(() => + writer.AddStream("second", new MemoryStream(new byte[] { 2 }), 1)); + } + + [Fact] + public void Zstd_Streaming_LargeFile() + { + if (SkipIfNoCore()) return; + + // 大文件流式压缩:验证压缩直通(不再有一次性内存缓冲/临时密文副本) + var src = Path.Combine(_dir, "big.bin"); + var dst = Path.Combine(_dir, "big.zst"); + var totalBytes = 8L * 1024 * 1024; + var chunk = new byte[8192]; + using (var fs = File.Create(src)) + { + for (long written = 0; written < totalBytes; written += chunk.Length) + { + RandomNumberGenerator.Fill(chunk); + fs.Write(chunk, 0, chunk.Length); + } + } + + using (var output = File.Create(dst)) + using (var input = File.OpenRead(src)) + { + global::GeneralZip.Formats.Codecs.NativeCodecRouter.CompressStream(input, output, "zstd", 6, CancellationToken.None); + } + + Assert.True(new FileInfo(dst).Length > 0); + + using (var input = File.OpenRead(dst)) + { + using var r = GeneralZipReader.Open(input, "ZSTD"); + long drained = 0; + using (var s = r.OpenEntryStream(r.Entries[0])) + { + var buffer = new byte[81920]; + int n; + while ((n = s.Read(buffer, 0, buffer.Length)) > 0) + { + drained += n; + } + } + + Assert.Equal(totalBytes, drained); + } + } + + [Fact] + public void ZipMethod_Cancellation_Aborts() + { + if (SkipIfNoCore()) return; + + using var cts = new CancellationTokenSource(); + var payload = MakePayload(2_000_000); + var src = new MemoryStream(payload); + var dst = new MemoryStream(); + cts.Cancel(); + + Assert.ThrowsAny(() => + global::GeneralZip.Formats.Codecs.NativeCodecRouter.CompressStream(src, dst, "zstd", 6, cts.Token)); + } +}