Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Add the archive engine: extract, convert and compress into one archive
KnifeLemon95222738197a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 32745737..710f9a1a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -28,10 +28,11 @@ jobs:- name: Buildrun: dotnet build Filee.slnx --no-restore -c Release- # rhwp + Pandoc are small; with them the HWP/HWPX engine tests run too (LibreOffice is skipped to save time).- - name: Fetch rhwp and Pandoc for engine tests+ # rhwp, Pandoc and 7-Zip are small; with them the HWP/HWPX and archive engine tests run too (LibreOffice is+ # skipped to save time).+ - name: Fetch rhwp, Pandoc and 7-Zip for engine testsshell: pwsh- run: ./build/fetch-engines.ps1 -Only rhwp,pandoc+ run: ./build/fetch-engines.ps1 -Only rhwp,pandoc,7zip- name: Testrun: dotnet test Filee.slnx --no-build -c Release --logger "trx" --results-directory TestResultsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex f3005cf2..0bcbba94 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -47,9 +47,9 @@ jobs:# Only the small rhwp is bundled. LibreOffice (+ H2Orestart, Java) and Pandoc are large and are downloaded by# the app when the user picks them (first-run setup or Settings > Engines), see engines.json.- - name: Bundle conversion engines (rhwp)+ - name: Bundle conversion engines (rhwp, 7-Zip)shell: pwsh- run: ./build/fetch-engines.ps1 -Only rhwp -Destination "${{ env.PUBLISH_DIR }}/engines"+ run: ./build/fetch-engines.ps1 -Only rhwp,7zip -Destination "${{ env.PUBLISH_DIR }}/engines"- name: Install Velopack CLIrun: dotnet tool install -g vpkdiff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 05fb3bc0..38f62174 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -30,6 +30,12 @@ Bundled with the installer:| Component | License | Project ||---|---|---|| rhwp | MIT | https://github.com/edwardkim/rhwp |+| 7-Zip (console: `7z.exe`, `7z.dll`) | GNU LGPL-2.1-or-later; parts of `7z.dll`: LGPL with the unRAR license restriction, BSD-3-Clause, BSD-2-Clause | https://www.7-zip.org |++7-Zip is Copyright (C) 1999-2026 Igor Pavlov; its `License.txt` is installed next to it (`engines/7zip`). The RAR+decompression code in `7z.dll` is under the unRAR license restriction: it may be used to unpack RAR archives, but not+to develop a RAR (WinRAR) compatible archiver or to re-create the RAR compression algorithm. Filee only reads RAR+files. Source code: https://github.com/ip7z/7zip.Downloaded from their official release pages when the user chooses to install them(pinned in `src/Filee.Engines/Infrastructure/engines.json`):diff --git a/build/fetch-engines.ps1 b/build/fetch-engines.ps1index 932fa812..c42af4a9 100644--- a/build/fetch-engines.ps1+++ b/build/fetch-engines.ps1@@ -1,7 +1,7 @@<#.SYNOPSIS- Downloads and prepares conversion engines for development and for the installer (which bundles rhwp only;- the app downloads the large engines on demand, see src/Filee.Engines/Infrastructure/EngineInstaller.cs).+ Downloads and prepares conversion engines for development and for the installer (which bundles rhwp and 7-Zip+ only; the app downloads the large engines on demand, see src/Filee.Engines/Infrastructure/EngineInstaller.cs)..DESCRIPTIONProduces this layout (next to Filee.exe in a published build, or in the repo root for development):@@ -12,6 +12,7 @@jre/ Eclipse Temurin JRE 21 (GPLv2 + Classpath Exception), used by H2Orestartrhwp/ rhwp command line (MIT), HWP/HWPX -> PDFpandoc/ Pandoc (GPL-2.0-or-later, separate program), Markdown/HTML and MD/HTML/ODT/RTF -> HWPX+ 7zip/ 7-Zip console (7z.exe + 7z.dll, LGPL-2.1 + unRAR restriction, separate program), archivesEvery download is pinned to a version and verified with SHA-256 (src/Filee.Engines/Infrastructure/engines.json,shared with the app). Downloads are cached in build/.cache.@@ -114,6 +115,25 @@ if ('pandoc' -in $selected) {if (-not (Test-Path (Join-Path $Destination 'pandoc\pandoc.exe'))) { throw 'pandoc.exe not found in the archive.' }}+if ('7zip' -in $selected) {+ # The official MSI unpacked with an administrative install (files only, no system changes). Only the console+ # program is kept: 7z.exe + 7z.dll (all formats, incl. RAR), the license and the readme; not the GUI or help.+ $msi = Get-Engine '7zip'+ $tmp = Join-Path $cache '7z-admin'+ Reset-Folder $tmp+ $proc = Start-Process msiexec.exe -ArgumentList @('/a', "`"$msi`"", '/qn', "TARGETDIR=`"$tmp`"") -Wait -PassThru+ if ($proc.ExitCode -ne 0) { throw "msiexec /a failed for 7-Zip with exit code $($proc.ExitCode)." }++ $exe = Get-ChildItem $tmp -Recurse -Filter '7z.exe' | Select-Object -First 1+ if (-not $exe) { throw '7z.exe not found after extracting the 7-Zip MSI.' }+ $target = Join-Path $Destination '7zip'+ Reset-Folder $target+ foreach ($name in @('7z.exe', '7z.dll', 'License.txt', 'readme.txt')) {+ Copy-Item (Join-Path $exe.DirectoryName $name) $target+ }+ Remove-Item $tmp -Recurse -Force+}+if ('jre' -in $selected) {$zip = Get-Engine 'jre'Expand-Flat $zip (Join-Path $Destination 'jre')diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d0f651b2..67b7679c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -40,6 +40,7 @@5. **Run** – `JobQueue` runs steps with per-engine concurrency limits. Intermediate files live in a temp folder;final outputs are named by `OutputPathResolver` (pattern, folder, conflict policy; the source is never overwritten)."Merge into one PDF" converts each file to PDF and merges with PDFsharp.+ "Compress into one archive" packs the dropped files, unconverted, with the archive engine (`IFileCombiner`).6. **Report** – progress and results appear in the toast window and in Home → Recent conversions.## Donut controldiff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 15adb4d1..d0409cdf 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -13,6 +13,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) || **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc || rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |+| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files || LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT || Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |@@ -97,6 +98,49 @@ Not converted: Word charts, SmartArt, equations (kept as text), free-form shapesrhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goesthrough the HWPX writer and then rhwp.+## Archives++The archive engine (`Archives/ArchiveConverter.cs`, id `archive`) uses Filee's own copy of the 7-Zip console program+(`7z.exe` + `7z.dll`, taken from the official x64 MSI with `msiexec /a` by `build/fetch-engines.ps1 -Only 7zip` and+bundled with the installer), never a 7-Zip installed on the PC. It runs as a separate process (LGPL).++| Format | Read | Write |+|---|---|---|+| ZIP, JAR | 7-Zip | ZIP in-process (System.IO.Compression): UTF-8 names with the language-encoding flag, times, empty folders |+| 7Z | 7-Zip | 7-Zip |+| TAR | 7-Zip | in-process (System.Formats.Tar, PAX: UTF-8 names, times) |+| TAR.GZ | 7-Zip, in two stages | in-process (PAX TAR + GZipStream) |+| TAR.BZ2, TAR.XZ | 7-Zip, in two stages | TAR in-process, compressed by 7-Zip |+| TAR.7Z, TAR.Z | 7-Zip, in two stages | — |+| LZ, TAR.LZ (lzip) | Filee: each member rewritten as a .lzma file for 7-Zip's LZMA decoder, CRC and size checked | — |+| GZ, BZ2, XZ | 7-Zip | 7-Zip; one file only (from another single-file format, or "Compress into one archive" with one file) |+| LZMA, Z | 7-Zip | — |+| RAR 4/5, CAB, CPIO, DEB, RPM, DMG, ISO, IMG, LHA/LZH, ARJ | 7-Zip (an RPM's payload is unpacked until the files appear) | — |+| ALZ (ALZip) | Filee: store, deflate and ALZip's bzip2 variant | — |+| EGG (ALZip) | Filee: store, deflate, bzip2, LZMA (decoded by 7-Zip); several blocks per file | — |++- **Extract** (target `folder`): the archive is unpacked into a hidden folder next to the result and moved into place+ when complete. When the archive holds exactly one top folder, its content becomes the result folder (`photos.zip`+ with `photos/…` gives `photos/…`, not `photos/photos/…`). Name conflicts follow the preset: `name (2)`, overwrite+ (files are merged into the existing folder) or skip.+- **Archive → archive** unpacks into the job's temp folder and packs everything into the target. `Preset.Archive.Level`+ maps to Store / Fastest / Optimal / SmallestSize in-process and to 7-Zip's `-mx0/1/5/9`.+- **Compress into one archive** (`Archive.CombineIntoOne`, the "One ZIP" preset): `JobQueue` hands all dropped files,+ of any type and unconverted, to `IFileCombiner` (implemented by this engine). The archive is named after the first+ file with the output pattern; files with the same name become `name (2).ext`. ZIP, TAR and TAR.GZ need no 7-Zip.+- **Safety**: every archive is listed first. Encrypted entries or archives stop with "password-protected"; entries+ (or hard links) with `..`, a drive or a leading slash stop the job ("points outside the target folder", nothing is+ written); symbolic links are never unpacked and any link left afterwards is deleted; archives with more than+ 1,000,000 entries or more data than the drive has free are refused; Filee's own readers also stop when data unpacks+ to more than the entry declares, and check CRCs.+- **Not supported**: encrypted archives, split (multi-volume) ALZ and EGG, solid EGG, EGG entries compressed with+ ESTsoft's own AZO method, LZO / TAR.LZO (lzop; 7-Zip has no reader either), and writing RAR, ALZ or EGG.+- The ALZ and EGG readers are Filee's own code, written from the format descriptions of unalz (zlib licence), the+ `unalz` Rust crate, EggDotNet and unegg (MIT). ALZip's bzip2 has no `BZh` header, starts every block with `DLZ\x01`+ instead of the block magic, CRC and randomised bit, and ends with `DLZ\x02` (`Archives/Bzip2Decoder.cs`).+- Tests (`ArchiveTests.cs`) build ALZ, EGG and lzip files in code (`ArchiveBuilders.cs`, with bzip2 and LZMA streams+ written by 7-Zip) and skip the 7-Zip parts when `engines/7zip` is missing.+## LibreOffice- Each parallel worker gets its own profile under `%APPDATA%\Filee\libreoffice-profiles` (LibreOffice silentlydiff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.csindex 1d7ae0e0..61a89be3 100644--- a/src/Filee.App/Services/AppHost.cs+++ b/src/Filee.App/Services/AppHost.cs@@ -46,7 +46,8 @@ public static class AppHostservices.AddSingleton(sp => new JobQueue(sp.GetRequiredService<ConverterCatalog>(),EngineRegistry.FindPdfMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>()),- sp.GetRequiredService<ILogger<JobQueue>>()));+ sp.GetRequiredService<ILogger<JobQueue>>(),+ EngineRegistry.FindFileCombiner(sp.GetRequiredService<IReadOnlyList<IConverter>>())));services.AddSingleton<EngineDownloadService>();services.AddSingleton<PresetAvailability>();diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.csindex c581336b..fb8c1689 100644--- a/src/Filee.App/Services/PresetAvailability.cs+++ b/src/Filee.App/Services/PresetAvailability.cs@@ -15,6 +15,14 @@ public sealed class PresetAvailability(ConverterCatalog catalog, ILocalizer loc,/// </summary>public string? Check(Preset preset, IReadOnlyList<FileFormat> formats){+ // "Compress into one archive" packs the files as they are, so any file works, even of an unknown type.+ if (preset.Archive.CombineIntoOne+ && FormatRegistry.FindById(preset.TargetFormat) is { Category: FormatCategory.Archive } archive+ && archive.Id != FormatRegistry.Folder)+ {+ return catalog.All.OfType<IFileCombiner>().Any(c => c.CanCombineInto(archive.Id)) ? null : loc["error.no_route"];+ }+if (formats.Count == 0)return loc["error.unsupported_source"];diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.csindex f596ae00..f85b8286 100644--- a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs@@ -28,15 +28,18 @@ public sealed partial class HistoryItemViewModel(HistoryEntry entry, ILocalizerpublic bool Succeeded { get; } = entry.State == JobState.Completed;public bool HasErrors { get; } = entry.Errors.Count > 0 || entry.State == JobState.Failed;public string? Errors { get; } = entry.Errors.Count == 0 ? null : string.Join(Environment.NewLine, entry.Errors);- public bool HasOutputs { get; } = entry.Outputs.Any(File.Exists);+ public bool HasOutputs { get; } = entry.Outputs.Any(Exists);[RelayCommand]private void OpenFolder(){- var output = entry.Outputs.FirstOrDefault(File.Exists);+ // An output may be a folder ("Extract"): revealing it opens the extracted files.+ var output = entry.Outputs.FirstOrDefault(Exists);if (output is not null)platform.RevealInFileManager(output);}++ private static bool Exists(string path) => File.Exists(path) || Directory.Exists(path);}public sealed partial class HomePageViewModel : ObservableObject, IDisposablediff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.csindex e5e32e1f..ca41886f 100644--- a/src/Filee.Core/Conversion/IConverter.cs+++ b/src/Filee.Core/Conversion/IConverter.cs@@ -89,3 +89,22 @@ public interface IPdfMerger{Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken);}++/// <summary>+/// Packs several files, unchanged, into one archive ("Compress into one archive"). Implemented by the archive engine;+/// <see cref="JobQueue"/> uses it when a preset sets <see cref="ArchiveOptions.CombineIntoOne"/>.+/// </summary>+public interface IFileCombiner+{+ /// <summary>True if files can be packed into <paramref name="format"/> now (e.g. the tool it needs is installed).</summary>+ bool CanCombineInto(string format);++ /// <summary>Writes every file of <paramref name="inputPaths"/> into one archive of <paramref name="format"/>.</summary>+ /// <param name="inputPaths">Files to pack, stored under their own names (renamed "name (2)" on clashes).</param>+ /// <param name="outputPath">Archive to create; written only when complete.</param>+ /// <param name="format">Archive format id, e.g. <c>"zip"</c>.</param>+ /// <param name="preset">Options, e.g. <see cref="ArchiveOptions.Level"/>.</param>+ /// <param name="workDirectory">Scratch directory for intermediate files; deleted after the job.</param>+ Task CombineAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Preset preset,+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken);+}diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex 4922f28d..e0474b95 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -15,16 +15,22 @@ public sealed class JobQueue : IAsyncDisposable{private readonly ConverterCatalog _catalog;private readonly IPdfMerger? _pdfMerger;+ private readonly IFileCombiner? _combiner;private readonly ILogger _log;private readonly Channel<ConversionJob> _channel = Channel.CreateUnbounded<ConversionJob>();private readonly ConcurrentDictionary<string, SemaphoreSlim> _engineGates = new();private readonly HashSet<string> _reservedOutputs = new(StringComparer.OrdinalIgnoreCase);private readonly Task _worker;- public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger<JobQueue>? log = null)+ /// <param name="catalog">Converters and their priority.</param>+ /// <param name="pdfMerger">Used by "Merge into one PDF" presets.</param>+ /// <param name="log">Optional logger.</param>+ /// <param name="combiner">Used by "Compress into one archive" presets (<see cref="ArchiveOptions.CombineIntoOne"/>).</param>+ public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger<JobQueue>? log = null, IFileCombiner? combiner = null){_catalog = catalog;_pdfMerger = pdfMerger;+ _combiner = combiner;_log = log ?? (ILogger)NullLogger.Instance;_worker = Task.Run(WorkLoopAsync);}@@ -59,9 +65,16 @@ public sealed class JobQueue : IAsyncDisposable&& job.Preset.TargetFormat == "pdf"&& job.Files.Count > 1&& _pdfMerger is not null;+ // Any files, one of them or many, archives or not: they go into the archive as they are.+ var combine = job.Preset.Archive.CombineIntoOne+ && _combiner is not null+ && FormatRegistry.FindById(job.Preset.TargetFormat) is { Category: FormatCategory.Archive } archive+ && archive.Id != FormatRegistry.Folder;if (merge)await RunMergedAsync(job, planner, workDir);+ else if (combine)+ await RunCombinedAsync(job, workDir);elseawait Parallel.ForEachAsync(job.Files.Select((f, i) => (File: f, Index: i + 1)),@@ -131,6 +144,84 @@ public sealed class JobQueue : IAsyncDisposableNotify(job);}+ /// <summary>Packs every source file, unchanged, into one archive named after the first file.</summary>+ private async Task RunCombinedAsync(ConversionJob job, string workDir)+ {+ var format = FormatRegistry.Get(job.Preset.TargetFormat);+ var inputs = new List<FileResult>();+ foreach (var file in job.Files)+ {+ // Folders (from the command line; drops deliver files) are packed with their content.+ if (File.Exists(file.SourcePath) || Directory.Exists(file.SourcePath))+ inputs.Add(file);+ else+ MarkFailed(file, "The file no longer exists.");+ }+ if (inputs.Count == 0)+ {+ Notify(job);+ return;+ }++ var output = CreateFinalAllocator(job, inputs[0].SourcePath, 1).Allocate(format.PrimaryExtension);+ if (output is null)+ {+ foreach (var f in inputs)+ {+ f.State = FileState.Skipped;+ f.Progress = 1;+ }+ Notify(job);+ return;+ }++ foreach (var f in inputs)+ f.State = FileState.Running;+ Notify(job);+ var progress = new Progress<double>(p =>+ {+ // Reports arrive on the thread pool, possibly out of order: progress only moves forward.+ var value = Math.Clamp(p, 0, 1);+ if (value <= inputs[0].Progress)+ return;+ foreach (var f in inputs)+ f.Progress = value;+ Notify(job);+ });++ try+ {+ await _combiner!.CombineAsync(inputs.Select(f => f.SourcePath).ToList(), output, format.Id, job.Preset,+ workDir, progress, job.CancellationToken);+ inputs[0].Outputs.Add(output);+ foreach (var f in inputs)+ {+ f.State = FileState.Done;+ f.Progress = 1;+ }+ }+ catch (OperationCanceledException)+ {+ foreach (var f in inputs)+ f.State = FileState.Cancelled;+ }+ catch (Exception ex)+ {+ _log.LogWarning(ex, "Packing {Count} file(s) into {Output} failed", inputs.Count, output);+ foreach (var f in inputs)+ MarkFailed(f, ex.Message);+ }+ Notify(job);++ static void MarkFailed(FileResult f, string detail)+ {+ f.State = FileState.Failed;+ f.ErrorKey = "error.conversion_failed";+ f.ErrorDetail = detail;+ f.Progress = 1;+ }+ }+/// <summary>/// Converts one source file along its planned route./// With <paramref name="finalOutput"/> false, results stay in the work directory (used for merging).diff --git a/src/Filee.Engines/Archives/AlzReader.cs b/src/Filee.Engines/Archives/AlzReader.csnew file mode 100644index 00000000..b5f4b5cc--- /dev/null+++ b/src/Filee.Engines/Archives/AlzReader.cs@@ -0,0 +1,216 @@+// Reads ALZ archives, the format of the Korean ALZip (ESTsoft), which 7-Zip does not support. Layout as documented by+// unalz (zlib licence) and the "unalz" Rust crate (MIT); Filee's reader is its own:+//+// "ALZ\x01" + 4 bytes archive header+// "BLZ\x01" + local file header + name + data one per entry+// "CLZ\x01" + 12 bytes central directory marker+// "CLZ\x02" (+ 12 bytes of end info) end of archive; "ELZ\x01" is a comment section+//+// Local file header (little endian): name length u16, attributes u8 (0x10 = folder), DOS time u32, descriptor u8+// (bit 0 = encrypted, bits 4-7 = width of the size fields: 0x10/0x20/0x40/0x80 = 1/2/4/8 bytes), unknown u8; then,+// when the width is not 0: method u8 (0 store, 1 ALZ bzip2, 2 deflate), unknown u8, CRC-32 u32, packed size,+// unpacked size. Names are CP949 (Korean Windows) unless they are valid UTF-8.++using System.IO.Compression;+using System.Text;++namespace Filee.Engines.Archives;++/// <summary>Unpacks ALZ archives (store, deflate and ALZip's bzip2 variant).</summary>+internal static class AlzReader+{+ private const uint ArchiveSignature = 0x015A4C41; // "ALZ\x01"+ private const uint EntrySignature = 0x015A4C42; // "BLZ\x01"+ private const uint DirectorySignature = 0x015A4C43; // "CLZ\x01"+ private const uint EndSignature = 0x025A4C43; // "CLZ\x02"+ private const uint SplitMarker = 0x035A4C43; // "CLZ\x03"+ private const uint CommentSignature = 0x015A4C45; // "ELZ\x01"+ private const uint SplitSignature = 0x015A4C53; // "SLZ\x01"++ /// <summary>One entry of the archive.</summary>+ private sealed record Entry(string Name, bool IsFolder, DateTime? Modified, int Method, uint Crc, long PackedSize, long Size, long DataOffset);++ /// <summary>Unpacks every entry of <paramref name="archive"/> into <paramref name="targetDirectory"/>.</summary>+ public static void Extract(string archive, string targetDirectory, CancellationToken cancellationToken)+ {+ var archiveName = Path.GetFileName(archive);+ using var stream = new FileStream(archive, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16);+ var entries = ReadEntries(stream, archiveName);+ ArchiveSafety.EnsureRoom(entries.Where(e => !e.IsFolder).Sum(e => e.Size), targetDirectory, archiveName);++ var folders = new List<(string Path, DateTime? Modified)>();+ foreach (var entry in entries)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var path = ArchiveSafety.ResolveEntryPath(targetDirectory, entry.Name, archiveName);+ if (entry.IsFolder)+ {+ Directory.CreateDirectory(path);+ folders.Add((path, entry.Modified));+ continue;+ }++ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ path = ArchiveFiles.UniquePath(path);+ stream.Position = entry.DataOffset;+ var crc = new Crc32();+ using (var output = new CrcStream(new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16), crc))+ {+ var packed = new BoundedStream(stream, entry.PackedSize);+ switch (entry.Method)+ {+ case 0:+ ArchiveFiles.CopyLimited(packed, output, entry.Size, cancellationToken);+ break;+ case 1:+ Bzip2Decoder.Decompress(packed, output, alzFraming: true, entry.Size, cancellationToken);+ break;+ case 2:+ using (var inflate = new DeflateStream(packed, CompressionMode.Decompress))+ ArchiveFiles.CopyLimited(inflate, output, entry.Size, cancellationToken);+ break;+ default:+ throw new InvalidDataException($"{archiveName} uses an unknown ALZ compression method ({entry.Method}).");+ }+ }++ if (new FileInfo(path).Length != entry.Size || crc.Value != entry.Crc)+ throw ArchiveSafety.Damaged(archiveName, $"checksum error in {entry.Name}");+ if (entry.Modified is { } modified)+ File.SetLastWriteTime(path, modified);+ }++ // Folder times last: writing files into a folder changes its time.+ foreach (var (path, modified) in folders)+ if (modified is { } time)+ Directory.SetLastWriteTime(path, time);+ }++ private static List<Entry> ReadEntries(FileStream stream, string archiveName)+ {+ var reader = new BinaryReader(stream, Encoding.Latin1, leaveOpen: true);+ var entries = new List<Entry>();+ try+ {+ if (stream.Length < 8 || reader.ReadUInt32() != ArchiveSignature)+ throw new InvalidDataException($"{archiveName} is not an ALZ archive.");+ reader.ReadUInt32(); // version / unknown++ while (stream.Position + 4 <= stream.Length)+ {+ switch (reader.ReadUInt32())+ {+ case EntrySignature:+ if (entries.Count >= ArchiveSafety.MaxEntries)+ throw new InvalidDataException($"{archiveName} has more than {ArchiveSafety.MaxEntries:N0} entries; Filee does not unpack it.");+ entries.Add(ReadEntry(reader, archiveName));+ break;+ case DirectorySignature:+ stream.Seek(12, SeekOrigin.Current);+ break;+ case SplitMarker:+ break;+ case CommentSignature:+ SkipComment(stream, reader);+ break;+ case EndSignature:+ return entries;+ case SplitSignature:+ throw new InvalidDataException($"{archiveName} is part of a split ALZ archive (.alz + .a00 …); Filee cannot unpack split archives.");+ default:+ throw ArchiveSafety.Damaged(archiveName, "unknown ALZ header");+ }+ }+ return entries; // no end record: keep what was found, the data checks catch damage+ }+ catch (EndOfStreamException)+ {+ throw ArchiveSafety.Damaged(archiveName, "the archive ends too early");+ }+ }++ private static Entry ReadEntry(BinaryReader reader, string archiveName)+ {+ var nameLength = reader.ReadUInt16();+ var attributes = reader.ReadByte();+ var dosTime = reader.ReadUInt32();+ var descriptor = reader.ReadByte();+ reader.ReadByte(); // unknown++ if ((descriptor & 0x01) != 0)+ throw ArchiveSafety.Encrypted(archiveName);++ var width = (descriptor & 0xF0) switch+ {+ 0x00 => 0,+ 0x10 => 1,+ 0x20 => 2,+ 0x40 => 4,+ 0x80 => 8,+ _ => throw ArchiveSafety.Damaged(archiveName, "invalid ALZ size field"),+ };+ int method = 0;+ uint crc = 0;+ long packedSize = 0, size = 0;+ if (width > 0)+ {+ method = reader.ReadByte();+ reader.ReadByte(); // unknown+ crc = reader.ReadUInt32();+ packedSize = ReadSize(reader, width);+ size = ReadSize(reader, width);+ }+ if (nameLength == 0 || packedSize < 0 || size < 0)+ throw ArchiveSafety.Damaged(archiveName, "invalid ALZ entry");++ var name = DecodeName(reader.ReadBytes(nameLength));+ var offset = reader.BaseStream.Position;+ if (offset + packedSize > reader.BaseStream.Length)+ throw ArchiveSafety.Damaged(archiveName, "the archive ends too early");+ reader.BaseStream.Seek(packedSize, SeekOrigin.Current);++ var isFolder = (attributes & 0x10) != 0;+ return new Entry(name, isFolder, FromDosTime(dosTime), method, crc, packedSize, size, offset);+ }++ private static long ReadSize(BinaryReader reader, int width)+ {+ Span<byte> bytes = stackalloc byte[8];+ bytes.Clear();+ reader.BaseStream.ReadExactly(bytes[..width]);+ return BitConverter.ToInt64(bytes);+ }++ /// <summary>Skips an "ELZ\x01" comment section; its size is in the 12 bytes after the end record.</summary>+ private static void SkipComment(FileStream stream, BinaryReader reader)+ {+ var position = stream.Position;+ stream.Position = stream.Length - 12;+ var size = reader.ReadUInt32(); // includes the 4-byte signature already read+ stream.Position = position + Math.Max(0, size - 4L);+ }++ /// <summary>CP949 names as written by Korean Windows, UTF-8 when the bytes are valid UTF-8.</summary>+ internal static string DecodeName(byte[] bytes)+ {+ try+ {+ return new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);+ }+ catch (DecoderFallbackException)+ {+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);+ return Encoding.GetEncoding(949).GetString(bytes);+ }+ }++ /// <summary>DOS date and time (local time, 2-second steps), or null when invalid.</summary>+ internal static DateTime? FromDosTime(uint value)+ {+ int second = (int)(value & 0x1F) * 2, minute = (int)(value >> 5) & 0x3F, hour = (int)(value >> 11) & 0x1F;+ int day = (int)(value >> 16) & 0x1F, month = (int)(value >> 21) & 0x0F, year = 1980 + (int)(value >> 25);+ if (month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) || hour > 23 || minute > 59 || second > 59)+ return null;+ return new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local);+ }+}diff --git a/src/Filee.Engines/Archives/ArchiveConverter.cs b/src/Filee.Engines/Archives/ArchiveConverter.csnew file mode 100644index 00000000..fa698444--- /dev/null+++ b/src/Filee.Engines/Archives/ArchiveConverter.cs@@ -0,0 +1,147 @@+// Archives: unpack (to a folder, the "Extract" preset), convert between archive formats (ZIP, 7Z, TAR, TAR.GZ,+// TAR.BZ2, TAR.XZ and single-file GZ / BZ2 / XZ), and "Compress into one archive" for any files (IFileCombiner).+// Reading uses the bundled 7-Zip (engines/7zip, LGPL, separate process) plus Filee's own ALZ, EGG and lzip readers;+// ZIP, TAR and TAR.GZ are written in-process, the other formats by 7-Zip. See docs/ENGINES.md.++using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;++namespace Filee.Engines.Archives;++/// <summary>The archive engine.</summary>+public sealed class ArchiveConverter : IConverter, IFileCombiner+{+ /// <summary>Archive formats Filee writes (plus <see cref="FormatRegistry.Folder"/>).</summary>+ private static readonly string[] ArchiveTargets = ["zip", "7z", "tar", "tgz", "tbz2", "txz"];++ /// <summary>Compressed single files (no names or folders inside); they convert among each other.</summary>+ private static readonly string[] SingleFileSources = ["gz", "bz2", "xz", "lzma", "z", "lz"];++ private SevenZip? _sevenZip;++ public string Id => "archive";+ public string DisplayName => "Archives (7-Zip)";++ /// <summary>7-Zip already uses several threads; two jobs at once keep the disk busy without thrashing it.</summary>+ public int MaxParallelism => 2;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ .. from source in ArchiveExtractor.ReadableFormats+ from target in ArchiveTargets.Append(FormatRegistry.Folder)+ select new ConversionEdge(source, target),+ .. from source in SingleFileSources+ from target in ArchivePacker.SingleFileFormats+ select new ConversionEdge(source, target),+ ];++ public EngineStatus GetStatus()+ {+ _sevenZip = SevenZip.Locate();+ return _sevenZip is null ? EngineStatus.Unavailable("engine.reason.not_installed") : EngineStatus.Available(_sevenZip.Executable);+ }++ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var sevenZip = _sevenZip ??= SevenZip.Locate();+ var extractor = new ArchiveExtractor(sevenZip);+ if (step.To == FormatRegistry.Folder)+ return await ExtractToFolderAsync(step, extractor, progress, cancellationToken);++ // Archive → archive: unpack into the job's work folder, then pack everything that came out.+ var scratch = Path.Combine(step.WorkDirectory, "archive-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(scratch);+ try+ {+ string unpacked;+ using (ProgressEstimate.Start(progress, TypicalDuration(step.InputPath), 0.02, 0.45))+ unpacked = await extractor.ExtractAsync(step.InputPath, step.From, scratch, cancellationToken);+ var items = Directory.EnumerateFileSystemEntries(unpacked)+ .Order(StringComparer.Ordinal)+ .Select(path => new PackItem(path, Path.GetFileName(path)))+ .ToList();++ var output = step.Output.Allocate(FormatRegistry.Get(step.To).PrimaryExtension);+ if (output is null)+ return [];+ await new ArchivePacker(sevenZip).PackAsync(items, output, step.To, step.Preset.Archive.Level, scratch,+ Scaled(progress, 0.5, 1), cancellationToken);+ progress?.Report(1);+ return [output];+ }+ finally+ {+ ArchiveFiles.TryDeleteFolder(scratch);+ }+ }++ /// <summary>+ /// Unpacks into the folder the output rule names. The archive is unpacked into a hidden folder next to it (same+ /// drive, so the final move is instant) and only moved into place when complete; one top folder is not nested twice.+ /// </summary>+ private static async Task<IReadOnlyList<string>> ExtractToFolderAsync(ConversionStep step, ArchiveExtractor extractor,+ IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var output = step.Output.Allocate("");+ if (output is null)+ return [];++ var staging = Path.Combine(Path.GetDirectoryName(output)!, $".{Path.GetFileName(output)}.filee-{Guid.NewGuid().ToString("N")[..8]}");+ Directory.CreateDirectory(staging).Attributes |= FileAttributes.Hidden;+ try+ {+ string unpacked;+ using (ProgressEstimate.Start(progress, TypicalDuration(step.InputPath), 0.02, 0.95))+ unpacked = await extractor.ExtractAsync(step.InputPath, step.From, staging, cancellationToken);+ ArchiveFiles.MoveFolder(ArchiveFiles.ContentRoot(unpacked), output);+ progress?.Report(1);+ return [output];+ }+ finally+ {+ ArchiveFiles.TryDeleteFolder(staging);+ }+ }++ public bool CanCombineInto(string format) =>+ ArchivePacker.BuiltInFormats.Contains(format)+ || (ArchiveTargets.Contains(format) || ArchivePacker.SingleFileFormats.Contains(format))+ && (_sevenZip ??= SevenZip.Locate()) is not null;++ public async Task CombineAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Preset preset,+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var sevenZip = ArchivePacker.BuiltInFormats.Contains(format) ? null : _sevenZip ??= SevenZip.Locate();+ await new ArchivePacker(sevenZip).PackAsync(UniqueEntries(inputPaths), outputPath, format, preset.Archive.Level,+ workDirectory, progress, cancellationToken);+ progress?.Report(1);+ }++ /// <summary>+ /// Each file (or folder) under its own name; later ones with a name already used become "name (2).ext".+ /// </summary>+ internal static List<PackItem> UniqueEntries(IReadOnlyList<string> paths)+ {+ var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ var items = new List<PackItem>();+ foreach (var path in paths)+ {+ var name = Path.GetFileName(Path.TrimEndingDirectorySeparator(path));+ var stem = Path.GetFileNameWithoutExtension(name);+ var ext = Path.GetExtension(name);+ for (var n = 2; !used.Add(name); n++)+ name = $"{stem} ({n}){ext}";+ items.Add(new PackItem(path, name));+ }+ return items;+ }++ /// <summary>Expected duration of unpacking for the progress estimate (~60 MB/s).</summary>+ private static TimeSpan TypicalDuration(string path) =>+ TimeSpan.FromSeconds(Math.Max(0.5, new FileInfo(path).Length / 60e6));++ private static IProgress<double>? Scaled(IProgress<double>? progress, double from, double to) =>+ progress is null ? null : new Progress<double>(p => progress.Report(from + (to - from) * p));+}diff --git a/src/Filee.Engines/Archives/ArchiveExtractor.cs b/src/Filee.Engines/Archives/ArchiveExtractor.csnew file mode 100644index 00000000..69add2d0--- /dev/null+++ b/src/Filee.Engines/Archives/ArchiveExtractor.cs@@ -0,0 +1,120 @@+// Unpacks every archive format Filee reads into a folder: the bundled 7-Zip for most of them, Filee's own readers for+// ALZ, EGG and lzip. Compressed TARs (.tar.gz, .tar.lz …) and RPM payloads are unpacked stage by stage until the+// files appear. Every stage is checked first (encryption, paths leaving the folder, disk space) and links are removed.++using Filee.Core.Formats;++namespace Filee.Engines.Archives;++/// <summary>Unpacks archives into scratch folders.</summary>+internal sealed class ArchiveExtractor(SevenZip? sevenZip)+{+ /// <summary>Formats read by 7-Zip.</summary>+ public static readonly IReadOnlyList<string> SevenZipFormats =+ [+ "zip", "jar", "7z", "rar", "tar", "tgz", "tbz2", "txz", "tar7z", "tz", "gz", "bz2", "xz", "lzma", "z",+ "cab", "cpio", "deb", "rpm", "dmg", "iso", "img", "lha", "arj",+ ];++ /// <summary>Formats read by Filee's own code (lzip still needs 7-Zip's LZMA decoder).</summary>+ public static readonly IReadOnlyList<string> BuiltInFormats = ["alz", "egg", "lz", "tlz"];++ /// <summary>Everything that can be unpacked.</summary>+ public static IEnumerable<string> ReadableFormats => SevenZipFormats.Concat(BuiltInFormats);++ /// <summary>A TAR inside a compressed stream (or a 7z): unpacking the outer layer yields one .tar file.</summary>+ private static readonly HashSet<string> TarWrapped = ["tgz", "tbz2", "txz", "tar7z", "tz", "tlz"];++ /// <summary>Formats an RPM payload comes in (7-Zip shows it as one compressed CPIO file).</summary>+ private static readonly HashSet<string> RpmPayload = ["cpio", "gz", "bz2", "xz", "lzma", "z", "zst"];++ private const int MaxStages = 3;++ /// <summary>+ /// Unpacks <paramref name="archive"/> (of format <paramref name="format"/>) into a new folder below+ /// <paramref name="scratchRoot"/> and returns that folder.+ /// </summary>+ public async Task<string> ExtractAsync(string archive, string format, string scratchRoot, CancellationToken cancellationToken)+ {+ var current = archive;+ var currentFormat = format;+ string? previous = null;+ for (var stage = 0; ; stage++)+ {+ var folder = Path.Combine(scratchRoot, "x" + stage);+ Directory.CreateDirectory(folder);+ await ExtractOnceAsync(current, currentFormat, folder, scratchRoot, cancellationToken);+ ArchiveSafety.RemoveLinks(folder);+ if (previous is not null)+ ArchiveFiles.TryDeleteFolder(previous);++ if (stage + 1 < MaxStages && InnerArchive(format, folder) is { } inner)+ {+ previous = folder;+ (current, currentFormat) = inner;+ continue;+ }+ return folder;+ }+ }++ private async Task ExtractOnceAsync(string archive, string format, string folder, string scratchRoot, CancellationToken cancellationToken)+ {+ var name = Path.GetFileName(archive);+ switch (format)+ {+ case "alz":+ await Task.Run(() => AlzReader.Extract(archive, folder, cancellationToken), cancellationToken);+ break;+ case "egg":+ await EggReader.ExtractAsync(archive, folder, sevenZip, scratchRoot, cancellationToken);+ break;+ case "lz":+ case "tlz":+ var output = FormatRegistry.NameWithoutExtension(archive) + (format == "tlz" ? ".tar" : "");+ await LzipReader.DecompressAsync(archive, Path.Combine(folder, output), Require(), scratchRoot, cancellationToken);+ break;+ default:+ var tool = Require();+ var entries = await tool.ListAsync(archive, cancellationToken);+ ArchiveSafety.CheckListing(entries, name, folder);+ var links = entries.Where(e => e.IsSymbolicLink).Select(e => e.Path).ToList();+ await tool.ExtractAsync(archive, folder, links, scratchRoot, cancellationToken);+ break;+ }+ }++ /// <summary>The single archive file a stage produced that must be unpacked as well, or null when done.</summary>+ private static (string Path, string Format)? InnerArchive(string originalFormat, string folder)+ {+ if (!TarWrapped.Contains(originalFormat) && originalFormat != "rpm")+ return null;+ var entries = Directory.GetFileSystemEntries(folder);+ if (entries.Length != 1 || !File.Exists(entries[0]))+ return null;++ var file = entries[0];+ if (IsTar(file))+ return (file, "tar");+ if (originalFormat == "rpm")+ {+ var detected = FormatRegistry.Detect(file)?.Id ?? Path.GetExtension(file).TrimStart('.').ToLowerInvariant();+ if (RpmPayload.Contains(detected))+ return (file, detected);+ }+ return null;+ }++ /// <summary>True for a .tar file or a file with the "ustar" signature at offset 257.</summary>+ internal static bool IsTar(string path)+ {+ if (path.EndsWith(".tar", StringComparison.OrdinalIgnoreCase))+ return true;+ Span<byte> header = stackalloc byte[262];+ using var stream = File.OpenRead(path);+ return stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false) == header.Length+ && header[257..262].SequenceEqual("ustar"u8);+ }++ private SevenZip Require() => sevenZip ?? throw new InvalidOperationException("7-Zip was not found (engines/7zip).");+}diff --git a/src/Filee.Engines/Archives/ArchiveFiles.cs b/src/Filee.Engines/Archives/ArchiveFiles.csnew file mode 100644index 00000000..c71748cf--- /dev/null+++ b/src/Filee.Engines/Archives/ArchiveFiles.cs@@ -0,0 +1,160 @@+// File system helpers for the archive engine: copying with a size cap, unique names, and moving an unpacked folder+// into place (with the "one top folder is not nested twice" rule of the Extract preset).++namespace Filee.Engines.Archives;++/// <summary>Copy, naming and folder-moving helpers.</summary>+internal static class ArchiveFiles+{+ /// <summary>Copies a stream, failing when it holds more than <paramref name="maxBytes"/> (a lying or damaged header).</summary>+ public static long CopyLimited(Stream from, Stream to, long maxBytes, CancellationToken cancellationToken, Action<long>? progress = null)+ {+ var buffer = new byte[1 << 16];+ long total = 0;+ int read;+ while ((read = from.Read(buffer, 0, buffer.Length)) > 0)+ {+ cancellationToken.ThrowIfCancellationRequested();+ total += read;+ if (total > maxBytes)+ throw new InvalidDataException("the data unpacks to more than the archive declares");+ to.Write(buffer, 0, read);+ progress?.Invoke(read);+ }+ return total;+ }++ /// <summary>+ /// <paramref name="path"/> if it is free, else "name_1.ext", "name_2.ext" … (as 7-Zip names clashing entries), so+ /// entries that differ only in case both survive on Windows.+ /// </summary>+ public static string UniquePath(string path)+ {+ if (!File.Exists(path) && !Directory.Exists(path))+ return path;+ var dir = Path.GetDirectoryName(path)!;+ var stem = Path.GetFileNameWithoutExtension(path);+ var ext = Path.GetExtension(path);+ for (var n = 1; ; n++)+ {+ var candidate = Path.Combine(dir, $"{stem}_{n}{ext}");+ if (!File.Exists(candidate) && !Directory.Exists(candidate))+ return candidate;+ }+ }++ /// <summary>+ /// The folder whose content forms the result of "Extract": the unpacked folder itself, or its only entry when that+ /// is a folder ("photos.zip" holding "photos/…" becomes "photos/…", not "photos/photos/…").+ /// </summary>+ public static string ContentRoot(string unpacked)+ {+ var entries = Directory.GetFileSystemEntries(unpacked);+ return entries.Length == 1 && Directory.Exists(entries[0]) ? entries[0] : unpacked;+ }++ /// <summary>+ /// Moves the folder <paramref name="source"/> to <paramref name="target"/>. An existing target (the preset+ /// overwrites) receives the files, replacing those with the same names.+ /// </summary>+ public static void MoveFolder(string source, string target)+ {+ if (File.Exists(target))+ throw new IOException($"A file named {Path.GetFileName(target)} is in the way of the extracted folder.");+ if (!Directory.Exists(target))+ {+ try+ {+ Directory.Move(source, target);+ return;+ }+ catch (IOException) when (!SameVolume(source, target))+ {+ // Different drives: fall through to copying file by file.+ }+ }+ MergeInto(source, target);+ }++ private static void MergeInto(string source, string target)+ {+ var info = new DirectoryInfo(target);+ if (info.Exists && info.Attributes.HasFlag(FileAttributes.ReparsePoint))+ throw new IOException($"{target} is a link; Filee does not extract into links.");+ Directory.CreateDirectory(target);+ foreach (var file in Directory.EnumerateFiles(source))+ File.Move(file, Path.Combine(target, Path.GetFileName(file)), overwrite: true);+ foreach (var dir in Directory.EnumerateDirectories(source))+ {+ var destination = Path.Combine(target, Path.GetFileName(dir));+ if (File.Exists(destination))+ File.Delete(destination);+ if (!Directory.Exists(destination) && SameVolume(dir, destination))+ Directory.Move(dir, destination);+ else+ MergeInto(dir, destination);+ }+ Directory.SetLastWriteTime(target, Directory.GetLastWriteTime(source));+ }++ private static bool SameVolume(string a, string b) =>+ string.Equals(Path.GetPathRoot(Path.GetFullPath(a)), Path.GetPathRoot(Path.GetFullPath(b)), StringComparison.OrdinalIgnoreCase);++ /// <summary>Deletes a folder tree, ignoring failures (a scanner may still hold a file; temp is cleaned later).</summary>+ public static void TryDeleteFolder(string path)+ {+ try+ {+ if (Directory.Exists(path))+ Directory.Delete(path, recursive: true);+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }++ /// <summary>Deletes a file, ignoring failures.</summary>+ public static void TryDeleteFile(string path)+ {+ try+ {+ File.Delete(path);+ }+ catch (IOException) { }+ catch (UnauthorizedAccessException) { }+ }+}++/// <summary>Write-only pass-through stream that computes the CRC-32 of what is written.</summary>+internal sealed class CrcStream(Stream inner, Crc32 crc) : Stream+{+ public override bool CanRead => false;+ public override bool CanSeek => false;+ public override bool CanWrite => true;+ public override long Length => inner.Length;++ public override long Position+ {+ get => inner.Position;+ set => throw new NotSupportedException();+ }++ public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));++ public override void Write(ReadOnlySpan<byte> buffer)+ {+ crc.Append(buffer);+ inner.Write(buffer);+ }++ public override void Flush() => inner.Flush();+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();+ public override void SetLength(long value) => throw new NotSupportedException();++ protected override void Dispose(bool disposing)+ {+ if (disposing)+ inner.Dispose();+ base.Dispose(disposing);+ }+}diff --git a/src/Filee.Engines/Archives/ArchivePacker.cs b/src/Filee.Engines/Archives/ArchivePacker.csnew file mode 100644index 00000000..e82077f3--- /dev/null+++ b/src/Filee.Engines/Archives/ArchivePacker.cs@@ -0,0 +1,334 @@+// Writes archives. ZIP, TAR and TAR.GZ are written in-process (System.IO.Compression / System.Formats.Tar), so file+// names are exactly what Filee chooses: UTF-8 in ZIP (with the language encoding flag), PAX headers in TAR. 7Z, the+// bzip2 / xz TAR variants and single-file GZ / BZ2 / XZ are written by the bundled 7-Zip.++using System.Formats.Tar;+using System.IO.Compression;+using System.Text;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;++namespace Filee.Engines.Archives;++/// <summary>A file or folder to store in an archive under <paramref name="EntryName"/>; folders go in with their content.</summary>+internal sealed record PackItem(string SourcePath, string EntryName);++/// <summary>Creates archives from files and folders.</summary>+internal sealed class ArchivePacker(SevenZip? sevenZip)+{+ /// <summary>Formats written without 7-Zip.</summary>+ public static readonly IReadOnlySet<string> BuiltInFormats = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "zip", "tar", "tgz" };++ /// <summary>Formats that hold exactly one file, without name or folders.</summary>+ public static readonly IReadOnlySet<string> SingleFileFormats = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "gz", "bz2", "xz" };++ /// <summary>+ /// Writes <paramref name="items"/> into a new archive of <paramref name="format"/> at <paramref name="outputPath"/>.+ /// The archive is built under a temporary name next to it and renamed when complete, so a failed or cancelled run+ /// never leaves a broken archive (or replaces an existing one).+ /// </summary>+ public async Task PackAsync(IReadOnlyList<PackItem> items, string outputPath, string format, ArchiveLevel level,+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var dir = Path.GetDirectoryName(Path.GetFullPath(outputPath))!;+ Directory.CreateDirectory(dir);+ var temp = Path.Combine(dir, $".{Path.GetFileName(outputPath)}.filee-{Guid.NewGuid().ToString("N")[..8]}.tmp");+ try+ {+ switch (format)+ {+ case "zip":+ await Task.Run(() => WriteZip(items, temp, level, progress, cancellationToken), cancellationToken);+ break;+ case "tar":+ case "tgz":+ await Task.Run(() => WriteTar(items, temp, format == "tgz" ? level : null, progress, cancellationToken), cancellationToken);+ break;+ case "tbz2":+ case "txz":+ {+ // 7-Zip compresses a single stream; the TAR is written first, in the work folder.+ var tar = Path.Combine(workDirectory, $"pack-{Guid.NewGuid():N}.tar");+ try+ {+ await Task.Run(() => WriteTar(items, tar, null, Scaled(progress, 0, 0.3), cancellationToken), cancellationToken);+ await RunSevenZipAsync(format == "tbz2" ? "bzip2" : "xz", [tar], temp, level, workDirectory, progress, 0.3, cancellationToken);+ }+ finally+ {+ ArchiveFiles.TryDeleteFile(tar);+ }+ break;+ }+ case "7z":+ await RunSevenZipAsync("7z", await NamedAsAsync(items, workDirectory, cancellationToken), temp, level, workDirectory, progress, 0, cancellationToken);+ break;+ case "gz":+ case "bz2":+ case "xz":+ if (items.Count != 1 || !File.Exists(items[0].SourcePath))+ throw new InvalidOperationException(+ $"A .{format} file holds a single file. Choose TAR.{format.ToUpperInvariant()} to compress several files or folders.");+ var type = format switch { "gz" => "gzip", "bz2" => "bzip2", _ => "xz" };+ await RunSevenZipAsync(type, await NamedAsAsync(items, workDirectory, cancellationToken), temp, level, workDirectory, progress, 0, cancellationToken);+ break;+ default:+ throw new NotSupportedException($"Filee cannot write {format} archives.");+ }+ File.Move(temp, outputPath, overwrite: true);+ }+ finally+ {+ ArchiveFiles.TryDeleteFile(temp);+ }+ }++ private async Task RunSevenZipAsync(string type, IReadOnlyList<string> paths, string archive, ArchiveLevel level,+ string workDirectory, IProgress<double>? progress, double from, CancellationToken cancellationToken)+ {+ if (sevenZip is null)+ throw new InvalidOperationException("7-Zip was not found (engines/7zip).");+ // 7-Zip reports nothing while it works: estimate from the amount of data (~40 MB/s at normal level).+ var bytes = paths.Sum(TotalSize);+ var typical = TimeSpan.FromSeconds(Math.Max(0.5, bytes / 40e6));+ using (ProgressEstimate.Start(progress, typical, Math.Max(from, 0.05), 0.95))+ await sevenZip.AddAsync(archive, type, level, paths, workDirectory, cancellationToken);+ }++ /// <summary>+ /// Paths 7-Zip can take as they are: it stores each under its own file name, so items whose entry name differs+ /// (a renamed duplicate) are copied under that name into the work folder first.+ /// </summary>+ private static async Task<IReadOnlyList<string>> NamedAsAsync(IReadOnlyList<PackItem> items, string workDirectory, CancellationToken cancellationToken)+ {+ var paths = new List<string>();+ foreach (var item in items)+ {+ if (string.Equals(Path.GetFileName(item.SourcePath), item.EntryName, StringComparison.Ordinal))+ {+ paths.Add(item.SourcePath);+ continue;+ }+ var folder = Path.Combine(workDirectory, "rename-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ var copy = Path.Combine(folder, item.EntryName);+ if (Directory.Exists(item.SourcePath))+ await CopyFolderAsync(new DirectoryInfo(item.SourcePath), copy, cancellationToken);+ else+ await CopyFileAsync(item.SourcePath, copy, cancellationToken);+ paths.Add(copy);+ }+ return paths;+ }++ private static async Task CopyFileAsync(string source, string target, CancellationToken cancellationToken)+ {+ await using (var from = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))+ await using (var to = new FileStream(target, FileMode.CreateNew, FileAccess.Write))+ await from.CopyToAsync(to, cancellationToken);+ File.SetLastWriteTimeUtc(target, File.GetLastWriteTimeUtc(source));+ }++ /// <summary>Copies a folder tree without following links.</summary>+ private static async Task CopyFolderAsync(DirectoryInfo source, string target, CancellationToken cancellationToken)+ {+ Directory.CreateDirectory(target);+ foreach (var info in source.EnumerateFileSystemInfos())+ {+ if (info.Attributes.HasFlag(FileAttributes.ReparsePoint))+ continue;+ var destination = Path.Combine(target, info.Name);+ if (info is DirectoryInfo dir)+ await CopyFolderAsync(dir, destination, cancellationToken);+ else+ await CopyFileAsync(info.FullName, destination, cancellationToken);+ }+ Directory.SetLastWriteTimeUtc(target, source.LastWriteTimeUtc);+ }++ private static void WriteZip(IReadOnlyList<PackItem> items, string path, ArchiveLevel level, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var files = Expand(items).ToList();+ var counter = new ByteCounter(files.Sum(f => f.Length), progress);+ var compression = level switch+ {+ ArchiveLevel.Store => CompressionLevel.NoCompression,+ ArchiveLevel.Fast => CompressionLevel.Fastest,+ ArchiveLevel.Maximum => CompressionLevel.SmallestSize,+ _ => CompressionLevel.Optimal,+ };++ using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 1 << 16);+ // UTF-8 names get the "language encoding" flag, so every unzip tool shows Korean or Chinese names correctly.+ using var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: false, new UTF8Encoding(false));+ foreach (var file in files)+ {+ cancellationToken.ThrowIfCancellationRequested();+ if (file.IsFolder)+ {+ zip.CreateEntry(file.EntryName + "/").LastWriteTime = ZipTime(file.Modified);+ continue;+ }+ var entry = zip.CreateEntry(file.EntryName, compression);+ entry.LastWriteTime = ZipTime(file.Modified);+ using var source = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16);+ using var target = entry.Open();+ ArchiveFiles.CopyLimited(source, target, long.MaxValue, cancellationToken, counter.Add);+ }+ }++ /// <summary>Writes a PAX TAR (UTF-8 names, times), gzip-compressed when <paramref name="gzipLevel"/> is set.</summary>+ private static void WriteTar(IReadOnlyList<PackItem> items, string path, ArchiveLevel? gzipLevel, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var files = Expand(items).ToList();+ var counter = new ByteCounter(files.Sum(f => f.Length), progress);++ using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16);+ using Stream stream = gzipLevel is { } level+ ? new GZipStream(file, level switch+ {+ ArchiveLevel.Store => CompressionLevel.NoCompression,+ ArchiveLevel.Fast => CompressionLevel.Fastest,+ ArchiveLevel.Maximum => CompressionLevel.SmallestSize,+ _ => CompressionLevel.Optimal,+ }, leaveOpen: true)+ : new NonClosingStream(file);+ using var writer = new TarWriter(stream, TarEntryFormat.Pax, leaveOpen: true);+ foreach (var item in files)+ {+ cancellationToken.ThrowIfCancellationRequested();+ if (item.IsFolder)+ {+ writer.WriteEntry(new PaxTarEntry(TarEntryType.Directory, item.EntryName + "/")+ {+ ModificationTime = item.Modified,+ Mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute+ | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute,+ });+ continue;+ }+ using var source = new FileStream(item.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16);+ var entry = new PaxTarEntry(TarEntryType.RegularFile, item.EntryName)+ {+ ModificationTime = item.Modified,+ Mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead,+ DataStream = new CountingStream(source, counter.Add, cancellationToken),+ };+ writer.WriteEntry(entry);+ }+ }++ /// <summary>A file or folder in the order it is written, with its name inside the archive.</summary>+ private sealed record PackFile(string Path, string EntryName, bool IsFolder, long Length, DateTimeOffset Modified);++ /// <summary>+ /// Every file and folder of the items, folders before their content. Links are skipped, never followed, so+ /// nothing outside the given folders ends up in the archive.+ /// </summary>+ private static IEnumerable<PackFile> Expand(IReadOnlyList<PackItem> items)+ {+ foreach (var item in items)+ {+ var name = item.EntryName.Replace('\\', '/').Trim('/');+ if (File.Exists(item.SourcePath))+ {+ var info = new FileInfo(item.SourcePath);+ yield return new PackFile(info.FullName, name, false, info.Length, info.LastWriteTimeUtc);+ }+ else if (Directory.Exists(item.SourcePath))+ {+ foreach (var file in ExpandFolder(new DirectoryInfo(item.SourcePath), name))+ yield return file;+ }+ else+ {+ throw new FileNotFoundException($"{item.SourcePath} was not found.", item.SourcePath);+ }+ }+ }++ private static IEnumerable<PackFile> ExpandFolder(DirectoryInfo folder, string name)+ {+ yield return new PackFile(folder.FullName, name, true, 0, folder.LastWriteTimeUtc);+ foreach (var info in folder.EnumerateFileSystemInfos().OrderBy(i => i.Name, StringComparer.Ordinal))+ {+ if (info.Attributes.HasFlag(FileAttributes.ReparsePoint))+ continue;+ var child = name + "/" + info.Name;+ if (info is DirectoryInfo dir)+ {+ foreach (var file in ExpandFolder(dir, child))+ yield return file;+ }+ else if (info is FileInfo file)+ {+ yield return new PackFile(file.FullName, child, false, file.Length, file.LastWriteTimeUtc);+ }+ }+ }++ private static long TotalSize(string path) =>+ File.Exists(path) ? new FileInfo(path).Length+ : Directory.Exists(path) ? new DirectoryInfo(path).EnumerateFiles("*", SearchOption.AllDirectories).Sum(f => f.Length)+ : 0;++ /// <summary>ZIP stores DOS times (local, 1980–2107).</summary>+ private static DateTimeOffset ZipTime(DateTimeOffset time)+ {+ var local = time.ToLocalTime();+ return local.Year < 1980 ? new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset)+ : local.Year > 2107 ? new DateTimeOffset(2107, 12, 31, 0, 0, 0, local.Offset)+ : local;+ }++ private static IProgress<double>? Scaled(IProgress<double>? progress, double from, double to) =>+ progress is null ? null : new Progress<double>(p => progress.Report(from + (to - from) * p));++ /// <summary>Turns bytes written into a 0..1 progress value.</summary>+ private sealed class ByteCounter(long total, IProgress<double>? progress)+ {+ private long _done;+ private double _reported;++ public void Add(long bytes)+ {+ _done += bytes;+ var value = total <= 0 ? 1 : Math.Min(1, _done / (double)total);+ if (value - _reported >= 0.01)+ {+ _reported = value;+ progress?.Report(value);+ }+ }+ }++ /// <summary>Read-only pass-through that reports bytes read and honours cancellation (TarWriter copies the data itself).</summary>+ private sealed class CountingStream(Stream inner, Action<long> onRead, CancellationToken cancellationToken) : Stream+ {+ public override bool CanRead => true;+ public override bool CanSeek => inner.CanSeek;+ public override bool CanWrite => false;+ public override long Length => inner.Length;++ public override long Position+ {+ get => inner.Position;+ set => inner.Position = value;+ }++ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));++ public override int Read(Span<byte> buffer)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var read = inner.Read(buffer);+ onRead(read);+ return read;+ }++ public override void Flush() { }+ public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);+ public override void SetLength(long value) => throw new NotSupportedException();+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();+ }+}diff --git a/src/Filee.Engines/Archives/ArchiveSafety.cs b/src/Filee.Engines/Archives/ArchiveSafety.csnew file mode 100644index 00000000..9604b8da--- /dev/null+++ b/src/Filee.Engines/Archives/ArchiveSafety.cs@@ -0,0 +1,155 @@+// Guards for unpacking archives from anywhere: entries that would land outside the target folder ("zip slip"),+// symbolic links, encrypted content and archives that would not fit on the disk. Also the error messages for them.++using System.Globalization;++namespace Filee.Engines.Archives;++/// <summary>Checks and path helpers shared by the 7-Zip and the built-in archive readers.</summary>+internal static class ArchiveSafety+{+ /// <summary>More entries than this are refused: real archives stay far below, "entry bombs" do not.</summary>+ public const int MaxEntries = 1_000_000;++ /// <summary>Space that must stay free on the drive after unpacking.</summary>+ private const long Reserve = 64L * 1024 * 1024;++ private static readonly HashSet<char> InvalidNameChars =+ [.. Path.GetInvalidFileNameChars(), '<', '>', ':', '"', '/', '\\', '|', '?', '*'];++ private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)+ {+ "CON", "PRN", "AUX", "NUL",+ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",+ "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",+ };++ /// <summary>True if an entry path is absolute, starts with a drive, or climbs out of the target with "..".</summary>+ public static bool IsUnsafePath(string entryPath)+ {+ if (entryPath.Length == 0)+ return false;+ if (entryPath[0] is '/' or '\\')+ return true;+ if (entryPath.Length >= 2 && entryPath[1] == ':' && char.IsAsciiLetter(entryPath[0]))+ return true;+ return entryPath.Split('/', '\\').Any(part => part == "..");+ }++ /// <summary>+ /// Refuses a 7-Zip listing with encrypted entries, entries or hard links pointing outside the target folder,+ /// too many entries, or more data than the drive of <paramref name="targetDirectory"/> can hold.+ /// </summary>+ public static void CheckListing(IReadOnlyList<SevenZipEntry> entries, string archiveName, string targetDirectory)+ {+ if (entries.Count > MaxEntries)+ throw new InvalidDataException($"{archiveName} has more than {MaxEntries:N0} entries; Filee does not unpack it.");+ foreach (var entry in entries)+ {+ if (entry.IsEncrypted)+ throw Encrypted(archiveName);+ if (IsUnsafePath(entry.Path) || entry.HardLink is { Length: > 0 } link && IsUnsafePath(link))+ throw Unsafe(archiveName, entry.Path);+ }+ EnsureRoom(entries.Where(e => !e.IsFolder).Sum(e => e.Size), targetDirectory, archiveName);+ }++ /// <summary>Throws when <paramref name="bytes"/> would not fit on the drive of <paramref name="directory"/>.</summary>+ public static void EnsureRoom(long bytes, string directory, string archiveName)+ {+ var root = Path.GetPathRoot(Path.GetFullPath(directory));+ if (string.IsNullOrEmpty(root) || bytes <= 0)+ return;+ long free;+ try+ {+ free = new DriveInfo(root).AvailableFreeSpace;+ }+ catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)+ {+ return; // network shares have no DriveInfo; the write itself fails if space runs out+ }+ if (bytes > free - Reserve)+ throw new IOException($"{archiveName} unpacks to {FormatSize(bytes)}, but only {FormatSize(free)} is free on {root}.");+ }++ /// <summary>+ /// Turns an entry name read by Filee's own readers into a path inside <paramref name="root"/>: separators are+ /// normalized, characters Windows does not allow are replaced, and anything escaping the root is refused.+ /// </summary>+ public static string ResolveEntryPath(string root, string entryName, string archiveName)+ {+ if (IsUnsafePath(entryName))+ throw Unsafe(archiveName, entryName);+ var parts = entryName.Split(['/', '\\'], StringSplitOptions.RemoveEmptyEntries)+ .Where(part => part != ".")+ .Select(SanitizeSegment)+ .ToList();+ if (parts.Count == 0)+ throw Damaged(archiveName, "an entry has no name");++ var fullRoot = Path.GetFullPath(root);+ var full = Path.GetFullPath(Path.Combine([fullRoot, .. parts]));+ if (!full.StartsWith(Path.TrimEndingDirectorySeparator(fullRoot) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))+ throw Unsafe(archiveName, entryName);+ return full;+ }++ /// <summary>+ /// Deletes symbolic links and junctions below <paramref name="root"/> without following them, so nothing packed or+ /// moved later can reach outside the unpacked folder.+ /// </summary>+ public static void RemoveLinks(string root)+ {+ foreach (var info in new DirectoryInfo(root).EnumerateFileSystemInfos())+ {+ if (info.Attributes.HasFlag(FileAttributes.ReparsePoint))+ {+ if (info is DirectoryInfo linkedDir)+ linkedDir.Delete(recursive: false); // removes the link, not its target+ else+ info.Delete();+ }+ else if (info is DirectoryInfo dir)+ {+ RemoveLinks(dir.FullName);+ }+ }+ }++ public static Exception Encrypted(string archiveName) =>+ new InvalidDataException($"{archiveName} is password-protected. Filee cannot unpack encrypted archives.");++ public static Exception Unsafe(string archiveName, string entry) =>+ new InvalidDataException($"{archiveName} was not unpacked: the entry \"{entry}\" points outside the target folder.");++ public static Exception Damaged(string archiveName, string detail) =>+ new InvalidDataException($"{archiveName} is damaged or incomplete ({detail}).");++ /// <summary>"1.4 GB" style size for messages.</summary>+ public static string FormatSize(long bytes)+ {+ string[] units = ["bytes", "KB", "MB", "GB", "TB"];+ double value = bytes;+ var unit = 0;+ while (value >= 1024 && unit < units.Length - 1)+ {+ value /= 1024;+ unit++;+ }+ return unit == 0+ ? $"{bytes} bytes"+ : value.ToString(value < 10 ? "0.0" : "0", CultureInfo.InvariantCulture) + " " + units[unit];+ }++ /// <summary>One path segment made valid on Windows: invalid characters become "_", device names get a prefix.</summary>+ private static string SanitizeSegment(string segment)+ {+ var chars = segment.Select(c => InvalidNameChars.Contains(c) || char.IsControl(c) ? '_' : c).ToArray();+ var name = new string(chars).TrimEnd('.', ' ');+ if (name.Length == 0)+ return "_";+ var stem = name.Split('.')[0];+ return ReservedNames.Contains(stem) ? "_" + name : name;+ }+}diff --git a/src/Filee.Engines/Archives/BoundedStream.cs b/src/Filee.Engines/Archives/BoundedStream.csnew file mode 100644index 00000000..4f4a2696--- /dev/null+++ b/src/Filee.Engines/Archives/BoundedStream.cs@@ -0,0 +1,42 @@+// A read-only window of a stream: the compressed data of one archive entry, so a decoder can never read into the+// next entry's headers.++namespace Filee.Engines.Archives;++/// <summary>Reads at most <c>length</c> bytes of an inner stream from its current position.</summary>+internal sealed class BoundedStream(Stream inner, long length) : Stream+{+ private readonly long _length = length;+ private long _remaining = length;++ public override bool CanRead => true;+ public override bool CanSeek => false;+ public override bool CanWrite => false;+ public override long Length => _length;++ public override long Position+ {+ get => _length - _remaining;+ set => throw new NotSupportedException();+ }++ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));++ public override int Read(Span<byte> buffer)+ {+ if (_remaining <= 0)+ return 0;+ if (buffer.Length > _remaining)+ buffer = buffer[..(int)_remaining];+ var read = inner.Read(buffer);+ if (read == 0)+ throw new EndOfStreamException("The archive ends in the middle of an entry.");+ _remaining -= read;+ return read;+ }++ 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();+}diff --git a/src/Filee.Engines/Archives/Bzip2Decoder.cs b/src/Filee.Engines/Archives/Bzip2Decoder.csnew file mode 100644index 00000000..c08cad76--- /dev/null+++ b/src/Filee.Engines/Archives/Bzip2Decoder.cs@@ -0,0 +1,420 @@+// bzip2 decompression in managed code, written for ALZip archives: ALZ stores bzip2 blocks without the "BZh" stream+// header, marks each block with "DLZ\x01" (instead of the 48-bit block magic, the block CRC and the "randomised" bit)+// and ends with "DLZ\x02". Standard bzip2 streams (used by EGG) are read too. The block format itself (Huffman+// coded MTF/RLE2 symbols, Burrows-Wheeler transform, RLE1) is plain bzip2.++namespace Filee.Engines.Archives;++/// <summary>Decodes standard or ALZ-framed bzip2 data.</summary>+internal sealed class Bzip2Decoder+{+ private const ulong BlockMagic = 0x314159265359;+ private const ulong StreamEndMagic = 0x177245385090;+ private const uint AlzBlockMarker = 0x444C5A01; // "DLZ\x01"+ private const uint AlzEndMarker = 0x444C5A02; // "DLZ\x02"+ private const int MaxCodeLength = 20;+ private const int GroupSize = 50;+ private const int MaxSelectors = 18002;++ private static readonly uint[] BlockCrcTable = CreateBlockCrcTable();++ private readonly Stream _input;+ private readonly Stream _output;+ private readonly long _maxOutput;+ private readonly byte[] _inBuffer = new byte[64 * 1024];+ private int _inPos;+ private int _inLength;+ private ulong _bits;+ private int _bitCount;+ private long _written;+ private int[] _tt = [];++ private Bzip2Decoder(Stream input, Stream output, long maxOutput)+ {+ _input = input;+ _output = output;+ _maxOutput = maxOutput;+ }++ /// <summary>Decompresses <paramref name="input"/> to <paramref name="output"/>.</summary>+ /// <param name="alzFraming">True for ALZ's variant of the stream framing (see the file comment).</param>+ /// <param name="maxOutput">Stops with an error when the data would unpack to more bytes than this.</param>+ /// <returns>Number of bytes written.</returns>+ public static long Decompress(Stream input, Stream output, bool alzFraming, long maxOutput, CancellationToken cancellationToken)+ {+ var decoder = new Bzip2Decoder(input, output, maxOutput);+ if (alzFraming)+ decoder.DecodeAlz(cancellationToken);+ else+ decoder.DecodeStandard(cancellationToken);+ return decoder._written;+ }++ private void DecodeAlz(CancellationToken cancellationToken)+ {+ // ALZip always writes 900k blocks and leaves out the stream header.+ while (TryReadBits(32, out var marker))+ {+ cancellationToken.ThrowIfCancellationRequested();+ if (marker == AlzEndMarker)+ return;+ if (marker != AlzBlockMarker)+ throw new InvalidDataException("bzip2 block marker missing");+ DecodeBlock(9, expectedCrc: null);+ }+ }++ private void DecodeStandard(CancellationToken cancellationToken)+ {+ // Several streams may follow each other (pbzip2, "cat a.bz2 b.bz2").+ var first = true;+ while (true)+ {+ if (!TryReadBits(8, out var b))+ {+ if (first)+ throw new InvalidDataException("empty bzip2 data");+ return;+ }+ // Some writers leave out the "BZ" signature and start with "h9".+ if (b == 'B')+ {+ if (ReadBits(8) != 'Z')+ throw new InvalidDataException("not bzip2 data");+ b = ReadBits(8);+ }+ if (b != 'h')+ throw new InvalidDataException("not bzip2 data");+ var level = (int)ReadBits(8) - '0';+ if (level is < 1 or > 9)+ throw new InvalidDataException("invalid bzip2 block size");+ first = false;++ uint combined = 0;+ while (true)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var magic = ((ulong)ReadBits(24) << 24) | ReadBits(24);+ var crc = ReadBits(32);+ if (magic == StreamEndMagic)+ {+ if (crc != combined)+ throw new InvalidDataException("bzip2 stream checksum mismatch");+ break;+ }+ if (magic != BlockMagic)+ throw new InvalidDataException("bzip2 block magic missing");+ if (ReadBits(1) != 0)+ throw new InvalidDataException("randomised bzip2 blocks (bzip2 0.9.0) are not supported");+ DecodeBlock(level, crc);+ combined = ((combined << 1) | (combined >> 31)) ^ crc;+ }+ // The next stream starts on a byte boundary.+ _bitCount -= _bitCount % 8;+ }+ }++ /// <summary>Decodes one block, starting at origPtr (after magic, CRC and randomised bit).</summary>+ private void DecodeBlock(int level, uint? expectedCrc)+ {+ var blockMax = level * 100_000;+ if (_tt.Length < blockMax)+ _tt = new int[blockMax];+ var tt = _tt;++ var origPtr = (int)ReadBits(24);++ // Symbols used in this block, as a 16x16 bitmap.+ var seqToUnseq = new byte[256];+ var inUseCount = 0;+ var inUse16 = ReadBits(16);+ for (var i = 0; i < 16; i++)+ {+ if ((inUse16 & (0x8000u >> i)) == 0)+ continue;+ var bits = ReadBits(16);+ for (var j = 0; j < 16; j++)+ if ((bits & (0x8000u >> j)) != 0)+ seqToUnseq[inUseCount++] = (byte)(i * 16 + j);+ }+ if (inUseCount == 0)+ throw new InvalidDataException("bzip2 block uses no symbols");+ var alphaSize = inUseCount + 2;++ var groupCount = (int)ReadBits(3);+ var selectorCount = (int)ReadBits(15);+ if (groupCount is < 2 or > 6 || selectorCount < 1)+ throw new InvalidDataException("invalid bzip2 block header");++ // Selectors (which Huffman table each group of 50 symbols uses), MTF and unary coded.+ var selectors = new byte[Math.Min(selectorCount, MaxSelectors)];+ Span<byte> mtfGroups = stackalloc byte[6];+ for (var i = 0; i < groupCount; i++)+ mtfGroups[i] = (byte)i;+ for (var i = 0; i < selectorCount; i++)+ {+ var j = 0;+ while (ReadBits(1) == 1)+ if (++j >= groupCount)+ throw new InvalidDataException("invalid bzip2 selector");+ var value = mtfGroups[j];+ for (; j > 0; j--)+ mtfGroups[j] = mtfGroups[j - 1];+ mtfGroups[0] = value;+ if (i < selectors.Length)+ selectors[i] = value; // bzip2 1.0.8 reads but ignores selectors beyond the limit+ }++ // Code lengths, delta coded, and the canonical Huffman decode tables built from them.+ var limit = new int[groupCount, MaxCodeLength + 2];+ var baseTable = new int[groupCount, MaxCodeLength + 2];+ var perm = new int[groupCount, 258];+ var minLengths = new int[groupCount];+ var lengths = new int[alphaSize];+ for (var t = 0; t < groupCount; t++)+ {+ var current = (int)ReadBits(5);+ for (var i = 0; i < alphaSize; i++)+ {+ while (true)+ {+ if (current is < 1 or > MaxCodeLength)+ throw new InvalidDataException("invalid bzip2 code length");+ if (ReadBits(1) == 0)+ break;+ current += ReadBits(1) == 0 ? 1 : -1;+ }+ lengths[i] = current;+ }+ minLengths[t] = BuildDecodeTable(lengths, alphaSize, t, limit, baseTable, perm);+ }++ // MTF / RLE2 symbols → block bytes.+ Span<byte> mtf = stackalloc byte[256];+ for (var i = 0; i < 256; i++)+ mtf[i] = (byte)i;+ Span<int> counts = stackalloc int[256];+ counts.Clear();+ var endOfBlock = inUseCount + 1;+ var length = 0;+ var groupIndex = -1;+ var groupLeft = 0;+ var table = 0;++ var symbol = NextSymbol();+ while (symbol != endOfBlock)+ {+ if (symbol <= 1)+ {+ // RUNA / RUNB: a bijective base-2 run length of the symbol at the MTF front.+ var run = 0;+ var weight = 1;+ do+ {+ if (weight > blockMax)+ throw new InvalidDataException("bzip2 run too long");+ run += (symbol + 1) * weight;+ weight <<= 1;+ symbol = NextSymbol();+ } while (symbol <= 1);++ var value = seqToUnseq[mtf[0]];+ if (length + run > blockMax)+ throw new InvalidDataException("bzip2 block too long");+ counts[value] += run;+ tt.AsSpan(length, run).Fill(value);+ length += run;+ continue;+ }++ if (length >= blockMax)+ throw new InvalidDataException("bzip2 block too long");+ var index = symbol - 1;+ if (index >= inUseCount)+ throw new InvalidDataException("invalid bzip2 symbol");+ var front = mtf[index];+ mtf[..index].CopyTo(mtf[1..]);+ mtf[0] = front;+ var b = seqToUnseq[front];+ counts[b]++;+ tt[length++] = b;+ symbol = NextSymbol();+ }+ if (origPtr < 0 || origPtr >= Math.Max(length, 1))+ throw new InvalidDataException("invalid bzip2 origin pointer");++ // Inverse Burrows-Wheeler transform: link every position to its successor.+ Span<int> starts = stackalloc int[256];+ var sum = 0;+ for (var i = 0; i < 256; i++)+ {+ starts[i] = sum;+ sum += counts[i];+ }+ for (var i = 0; i < length; i++)+ {+ var b = tt[i] & 0xFF;+ tt[starts[b]++] |= i << 8;+ }++ // Walk the chain and undo the initial run-length coding (4 equal bytes + a count byte).+ var crc = 0xFFFFFFFFu;+ var buffer = new byte[64 * 1024];+ var used = 0;+ var position = length == 0 ? 0 : tt[origPtr] >> 8;+ var previous = -1;+ var repeat = 0;+ for (var i = 0; i < length; i++)+ {+ var entry = tt[position];+ var b = entry & 0xFF;+ position = entry >> 8;+ if (repeat == 4)+ {+ for (var k = 0; k < b; k++)+ Emit((byte)previous);+ repeat = 0;+ previous = -1;+ continue;+ }+ repeat = b == previous ? repeat + 1 : 1;+ previous = b;+ Emit((byte)b);+ }+ Flush();++ if (expectedCrc is { } expected && ~crc != expected)+ throw new InvalidDataException("bzip2 block checksum mismatch");++ void Emit(byte value)+ {+ crc = (crc << 8) ^ BlockCrcTable[(crc >> 24) ^ value];+ buffer[used++] = value;+ if (used == buffer.Length)+ Flush();+ }++ void Flush()+ {+ if (used == 0)+ return;+ _written += used;+ if (_written > _maxOutput)+ throw new InvalidDataException("the data unpacks to more than the archive declares");+ _output.Write(buffer, 0, used);+ used = 0;+ }++ int NextSymbol()+ {+ if (groupLeft == 0)+ {+ if (++groupIndex >= selectors.Length)+ throw new InvalidDataException("bzip2 selectors exhausted");+ table = selectors[groupIndex];+ groupLeft = GroupSize;+ }+ groupLeft--;+ var bitsUsed = minLengths[table];+ var code = (int)ReadBits(bitsUsed);+ while (bitsUsed <= MaxCodeLength && code > limit[table, bitsUsed])+ {+ bitsUsed++;+ code = (code << 1) | (int)ReadBits(1);+ }+ if (bitsUsed > MaxCodeLength)+ throw new InvalidDataException("invalid bzip2 Huffman code");+ var slot = code - baseTable[table, bitsUsed];+ if (slot is < 0 or >= 258)+ throw new InvalidDataException("invalid bzip2 Huffman code");+ return perm[table, slot];+ }+ }++ /// <summary>Canonical Huffman decode tables as in the reference bzip2 (limit / base / perm per code length).</summary>+ /// <returns>The shortest code length.</returns>+ private static int BuildDecodeTable(int[] lengths, int alphaSize, int t, int[,] limit, int[,] baseTable, int[,] perm)+ {+ var minLength = MaxCodeLength;+ var maxLength = 0;+ for (var i = 0; i < alphaSize; i++)+ {+ minLength = Math.Min(minLength, lengths[i]);+ maxLength = Math.Max(maxLength, lengths[i]);+ }++ var p = 0;+ for (var len = minLength; len <= maxLength; len++)+ for (var symbol = 0; symbol < alphaSize; symbol++)+ if (lengths[symbol] == len)+ perm[t, p++] = symbol;++ Span<int> countAtLength = stackalloc int[MaxCodeLength + 2];+ countAtLength.Clear();+ for (var i = 0; i < alphaSize; i++)+ countAtLength[lengths[i] + 1]++;+ for (var i = 1; i < MaxCodeLength + 2; i++)+ countAtLength[i] += countAtLength[i - 1];++ for (var i = 0; i < MaxCodeLength + 2; i++)+ {+ limit[t, i] = -1; // lengths outside min..max never match, so decoding continues to longer codes+ baseTable[t, i] = countAtLength[i];+ }++ var code = 0;+ for (var len = minLength; len <= maxLength; len++)+ {+ code += countAtLength[len + 1] - countAtLength[len];+ limit[t, len] = code - 1;+ code <<= 1;+ }+ for (var len = minLength + 1; len <= maxLength; len++)+ baseTable[t, len] = ((limit[t, len - 1] + 1) << 1) - countAtLength[len];+ return minLength;+ }++ private uint ReadBits(int count)+ {+ if (!TryReadBits(count, out var value))+ throw new InvalidDataException("bzip2 data ends unexpectedly");+ return value;+ }++ /// <summary>Reads up to 32 bits, most significant first; false when the input is exhausted.</summary>+ private bool TryReadBits(int count, out uint value)+ {+ while (_bitCount < count)+ {+ if (_inPos == _inLength)+ {+ _inLength = _input.Read(_inBuffer, 0, _inBuffer.Length);+ _inPos = 0;+ if (_inLength == 0)+ {+ value = 0;+ return false;+ }+ }+ _bits = (_bits << 8) | _inBuffer[_inPos++];+ _bitCount += 8;+ }+ _bitCount -= count;+ value = (uint)((_bits >> _bitCount) & ((1UL << count) - 1));+ return true;+ }++ /// <summary>bzip2's block CRC: CRC-32 with the polynomial 0x04C11DB7, most significant bit first.</summary>+ private static uint[] CreateBlockCrcTable()+ {+ var table = new uint[256];+ for (uint i = 0; i < 256; i++)+ {+ var c = i << 24;+ for (var k = 0; k < 8; k++)+ c = (c & 0x80000000) != 0 ? (c << 1) ^ 0x04C11DB7 : c << 1;+ table[i] = c;+ }+ return table;+ }+}diff --git a/src/Filee.Engines/Archives/Crc32.cs b/src/Filee.Engines/Archives/Crc32.csnew file mode 100644index 00000000..5590a390--- /dev/null+++ b/src/Filee.Engines/Archives/Crc32.cs@@ -0,0 +1,42 @@+// CRC-32 (IEEE 802.3, as in ZIP, gzip, ALZ, EGG and lzip) for checking what Filee's own archive readers unpack.++namespace Filee.Engines.Archives;++/// <summary>Incremental CRC-32 with the reflected polynomial 0xEDB88320.</summary>+internal sealed class Crc32+{+ private static readonly uint[] Table = CreateTable();+ private uint _crc = 0xFFFFFFFF;++ /// <summary>The checksum of everything passed to <see cref="Append"/> so far.</summary>+ public uint Value => ~_crc;++ public void Append(ReadOnlySpan<byte> data)+ {+ var crc = _crc;+ foreach (var b in data)+ crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8);+ _crc = crc;+ }++ /// <summary>CRC-32 of <paramref name="data"/>.</summary>+ public static uint Compute(ReadOnlySpan<byte> data)+ {+ var crc = new Crc32();+ crc.Append(data);+ return crc.Value;+ }++ private static uint[] CreateTable()+ {+ var table = new uint[256];+ for (uint i = 0; i < 256; i++)+ {+ var c = i;+ for (var k = 0; k < 8; k++)+ c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;+ table[i] = c;+ }+ return table;+ }+}diff --git a/src/Filee.Engines/Archives/EggReader.cs b/src/Filee.Engines/Archives/EggReader.csnew file mode 100644index 00000000..e54c2acf--- /dev/null+++ b/src/Filee.Engines/Archives/EggReader.cs@@ -0,0 +1,322 @@+// Reads EGG archives, ALZip's newer format, which 7-Zip does not support. Layout as documented by EggDotNet (MIT)+// and unegg (MIT); Filee's reader is its own. All numbers are little endian.+//+// "EGGA" version u16, header id u32, reserved u32, extra fields…, END archive header+// FILE (0x0A8590E3) file id u32, size u64, extra fields…, END one per entry, followed by+// BLOCK (0x02B50C13) method u8, hint u8, size u32, packed u32, CRC-32 u32, END, data one or more blocks+// END (0x08E28222) end of archive+//+// An extra field is magic u32, flags u8, size u16 (u32 when flags bit 0 is set) and data. The file name field+// has a locale u16 before the name when flags & 0x08 (else the name is UTF-8) and a parent id u32 when flags & 0x10.+// Methods: 0 store, 1 deflate, 2 bzip2, 3 AZO (ESTsoft's own, not supported), 4 LZMA (ZIP-style: 4-byte version+// and size header, 5 property bytes, raw data; decoded by 7-Zip). Solid, split and encrypted archives are refused.++using System.IO.Compression;+using System.Text;++namespace Filee.Engines.Archives;++/// <summary>Unpacks EGG archives (store, deflate, bzip2 and LZMA blocks).</summary>+internal static class EggReader+{+ private const uint ArchiveMagic = 0x41474745; // "EGGA"+ private const uint EndMagic = 0x08E28222;+ private const uint FileMagic = 0x0A8590E3;+ private const uint BlockMagic = 0x02B50C13;+ private const uint FileNameMagic = 0x0A8591AC;+ private const uint WindowsInfoMagic = 0x2C86950B;+ private const uint PosixInfoMagic = 0x1EE922E5;+ private const uint EncryptMagic = 0x08D1470F;+ private const uint SplitMagic = 0x24F5A262;+ private const uint SolidMagic = 0x24E5A060;++ /// <summary>One compressed block of an entry's data.</summary>+ private sealed record Block(int Method, long Size, long PackedSize, uint Crc, long DataOffset);++ /// <summary>One entry of the archive.</summary>+ private sealed class Entry+ {+ public string Name { get; set; } = "";+ public long Size { get; set; }+ public bool IsFolder { get; set; }+ public DateTime? Modified { get; set; }+ public List<Block> Blocks { get; } = [];+ }++ /// <summary>Unpacks every entry of <paramref name="archive"/> into <paramref name="targetDirectory"/>.</summary>+ /// <param name="sevenZip">Decodes LZMA blocks; null when 7-Zip is missing (LZMA entries then fail).</param>+ public static async Task ExtractAsync(string archive, string targetDirectory, SevenZip? sevenZip, string workDirectory,+ CancellationToken cancellationToken)+ {+ var archiveName = Path.GetFileName(archive);+ await using var stream = new FileStream(archive, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16);+ var entries = ReadEntries(stream, archiveName);+ ArchiveSafety.EnsureRoom(entries.Where(e => !e.IsFolder).Sum(e => e.Size), targetDirectory, archiveName);++ var folders = new List<(string Path, DateTime? Modified)>();+ foreach (var entry in entries)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var path = ArchiveSafety.ResolveEntryPath(targetDirectory, entry.Name, archiveName);+ if (entry.IsFolder)+ {+ Directory.CreateDirectory(path);+ folders.Add((path, entry.Modified));+ continue;+ }++ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ path = ArchiveFiles.UniquePath(path);+ await using (var output = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16))+ {+ foreach (var block in entry.Blocks)+ {+ var crc = new Crc32();+ var start = output.Position;+ await using (var checkedOutput = new CrcStream(new NonClosingStream(output), crc))+ await DecodeBlockAsync(stream, block, checkedOutput, sevenZip, workDirectory, archiveName, cancellationToken);+ if (output.Position - start != block.Size || crc.Value != block.Crc)+ throw ArchiveSafety.Damaged(archiveName, $"checksum error in {entry.Name}");+ }+ }+ if (new FileInfo(path).Length != entry.Size)+ throw ArchiveSafety.Damaged(archiveName, $"wrong size of {entry.Name}");+ if (entry.Modified is { } modified)+ File.SetLastWriteTimeUtc(path, modified);+ }++ foreach (var (path, modified) in folders)+ if (modified is { } time)+ Directory.SetLastWriteTimeUtc(path, time);+ }++ private static async Task DecodeBlockAsync(FileStream stream, Block block, Stream output, SevenZip? sevenZip,+ string workDirectory, string archiveName, CancellationToken cancellationToken)+ {+ stream.Position = block.DataOffset;+ var packed = new BoundedStream(stream, block.PackedSize);+ switch (block.Method)+ {+ case 0:+ ArchiveFiles.CopyLimited(packed, output, block.Size, cancellationToken);+ break;+ case 1:+ await using (var inflate = new DeflateStream(packed, CompressionMode.Decompress))+ ArchiveFiles.CopyLimited(inflate, output, block.Size, cancellationToken);+ break;+ case 2:+ Bzip2Decoder.Decompress(packed, output, alzFraming: false, block.Size, cancellationToken);+ break;+ case 3:+ throw new NotSupportedException($"{archiveName} is compressed with ALZip's own AZO method, which Filee cannot unpack. Save it again in ALZip as ZIP or 7Z, or as EGG with another method.");+ case 4:+ await DecodeLzmaAsync(packed, block, output, sevenZip, workDirectory, archiveName, cancellationToken);+ break;+ default:+ throw new InvalidDataException($"{archiveName} uses an unknown EGG compression method ({block.Method}).");+ }+ }++ /// <summary>+ /// LZMA blocks carry ZIP's LZMA header (version u16, property size u16, 5 property bytes). Rewritten as a .lzma+ /// file (properties, unpacked size u64, data) they can be decoded by 7-Zip.+ /// </summary>+ private static async Task DecodeLzmaAsync(Stream packed, Block block, Stream output, SevenZip? sevenZip,+ string workDirectory, string archiveName, CancellationToken cancellationToken)+ {+ if (sevenZip is null)+ throw new InvalidOperationException("7-Zip was not found; it is needed for LZMA data.");+ var header = new byte[9];+ packed.ReadExactly(header);+ var folder = Path.Combine(workDirectory, "egg-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ try+ {+ var lzma = Path.Combine(folder, "block.lzma");+ await using (var file = new FileStream(lzma, FileMode.CreateNew, FileAccess.Write))+ {+ file.Write(header, 4, 5);+ file.Write(BitConverter.GetBytes(block.Size));+ ArchiveFiles.CopyLimited(packed, file, block.PackedSize, cancellationToken);+ }+ var unpacked = Path.Combine(folder, "out");+ await sevenZip.ExtractAsync(lzma, unpacked, [], folder, cancellationToken);+ await using var result = File.OpenRead(Path.Combine(unpacked, "block"));+ ArchiveFiles.CopyLimited(result, output, block.Size, cancellationToken);+ }+ catch (FileNotFoundException)+ {+ throw ArchiveSafety.Damaged(archiveName, "LZMA data could not be decoded");+ }+ finally+ {+ ArchiveFiles.TryDeleteFolder(folder);+ }+ }++ private static List<Entry> ReadEntries(FileStream stream, string archiveName)+ {+ var reader = new BinaryReader(stream, Encoding.Latin1, leaveOpen: true);+ var entries = new List<Entry>();+ try+ {+ if (stream.Length < 14 || reader.ReadUInt32() != ArchiveMagic)+ throw new InvalidDataException($"{archiveName} is not an EGG archive.");+ reader.ReadUInt16(); // version+ reader.ReadUInt32(); // header id+ reader.ReadUInt32(); // reserved+ ReadExtraFields(reader, archiveName, null);++ Entry? current = null;+ while (stream.Position + 4 <= stream.Length)+ {+ var magic = reader.ReadUInt32();+ switch (magic)+ {+ case FileMagic:+ if (entries.Count >= ArchiveSafety.MaxEntries)+ throw new InvalidDataException($"{archiveName} has more than {ArchiveSafety.MaxEntries:N0} entries; Filee does not unpack it.");+ current = new Entry();+ reader.ReadUInt32(); // file id+ current.Size = reader.ReadInt64();+ ReadExtraFields(reader, archiveName, current);+ entries.Add(current);+ break;+ case BlockMagic when current is not null:+ var method = reader.ReadByte();+ reader.ReadByte(); // hint+ var size = reader.ReadUInt32();+ var packedSize = reader.ReadUInt32();+ var crc = reader.ReadUInt32();+ if (reader.ReadUInt32() != EndMagic)+ throw ArchiveSafety.Damaged(archiveName, "invalid EGG block header");+ if (stream.Position + packedSize > stream.Length)+ throw ArchiveSafety.Damaged(archiveName, "the archive ends too early");+ current.Blocks.Add(new Block(method, size, packedSize, crc, stream.Position));+ stream.Seek(packedSize, SeekOrigin.Current);+ break;+ case EndMagic:+ return Validate(entries, archiveName);+ default:+ // Comments and other extra fields between entries.+ SkipExtraField(reader, archiveName);+ break;+ }+ }+ return Validate(entries, archiveName);+ }+ catch (EndOfStreamException)+ {+ throw ArchiveSafety.Damaged(archiveName, "the archive ends too early");+ }+ }++ private static List<Entry> Validate(List<Entry> entries, string archiveName)+ {+ foreach (var entry in entries)+ {+ if (entry.Name.Length == 0)+ throw ArchiveSafety.Damaged(archiveName, "an entry has no name");+ if (entry.Name.EndsWith('/') || entry.Name.EndsWith('\\'))+ entry.IsFolder = true;+ if (!entry.IsFolder && entry.Blocks.Sum(b => b.Size) != entry.Size)+ throw ArchiveSafety.Damaged(archiveName, $"the blocks of {entry.Name} do not add up");+ }+ return entries;+ }++ /// <summary>Reads extra fields up to the END marker, filling <paramref name="entry"/> (null: archive header).</summary>+ private static void ReadExtraFields(BinaryReader reader, string archiveName, Entry? entry)+ {+ while (true)+ {+ var magic = reader.ReadUInt32();+ if (magic == EndMagic)+ return;+ var flags = reader.ReadByte();+ switch (magic)+ {+ case SplitMagic:+ throw new InvalidDataException($"{archiveName} is part of a split EGG archive; Filee cannot unpack split archives.");+ case SolidMagic:+ throw new NotSupportedException($"{archiveName} is a solid EGG archive, which Filee cannot unpack.");+ case EncryptMagic:+ throw ArchiveSafety.Encrypted(archiveName);+ case FileNameMagic when entry is not null:+ var nameLength = (flags & 0x01) != 0 ? (int)reader.ReadUInt32() : reader.ReadUInt16();+ if ((flags & 0x04) != 0)+ throw ArchiveSafety.Encrypted(archiveName);+ Encoding encoding = new UTF8Encoding(false);+ if ((flags & 0x08) != 0)+ {+ var codePage = reader.ReadUInt16();+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);+ try+ {+ encoding = Encoding.GetEncoding(codePage);+ }+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException)+ {+ encoding = Encoding.GetEncoding(949);+ }+ }+ if ((flags & 0x10) != 0)+ reader.ReadUInt32(); // parent path id; names already hold the full path+ entry.Name = encoding.GetString(reader.ReadBytes(nameLength));+ break;+ case WindowsInfoMagic when entry is not null:+ var infoSize = ReadFieldSize(reader, flags);+ var fileTime = reader.ReadInt64();+ var attributes = reader.ReadByte();+ reader.BaseStream.Seek(infoSize - 9, SeekOrigin.Current);+ entry.Modified = fileTime > 0 && fileTime < DateTime.MaxValue.ToFileTimeUtc() ? DateTime.FromFileTimeUtc(fileTime) : null;+ entry.IsFolder |= (attributes & 0x10) != 0;+ break;+ case PosixInfoMagic when entry is not null:+ var posixSize = ReadFieldSize(reader, flags);+ var mode = reader.ReadUInt32();+ reader.BaseStream.Seek(posixSize - 4, SeekOrigin.Current);+ entry.IsFolder |= (mode & 0xF000) == 0x4000;+ break;+ default:+ reader.BaseStream.Seek(ReadFieldSize(reader, flags), SeekOrigin.Current);+ break;+ }+ }+ }++ /// <summary>Skips an extra field whose magic has been read.</summary>+ private static void SkipExtraField(BinaryReader reader, string archiveName)+ {+ var flags = reader.ReadByte();+ var size = ReadFieldSize(reader, flags);+ if (reader.BaseStream.Position + size > reader.BaseStream.Length)+ throw ArchiveSafety.Damaged(archiveName, "unknown EGG header");+ reader.BaseStream.Seek(size, SeekOrigin.Current);+ }++ private static long ReadFieldSize(BinaryReader reader, byte flags) =>+ (flags & 0x01) != 0 ? reader.ReadUInt32() : reader.ReadUInt16();+}++/// <summary>Forwards writes to a stream without closing it when disposed.</summary>+internal sealed class NonClosingStream(Stream inner) : Stream+{+ public override bool CanRead => false;+ public override bool CanSeek => false;+ public override bool CanWrite => true;+ public override long Length => inner.Length;++ public override long Position+ {+ get => inner.Position;+ set => throw new NotSupportedException();+ }++ public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);+ public override void Write(ReadOnlySpan<byte> buffer) => inner.Write(buffer);+ public override void Flush() => inner.Flush();+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();+ public override void SetLength(long value) => throw new NotSupportedException();+}diff --git a/src/Filee.Engines/Archives/LzipReader.cs b/src/Filee.Engines/Archives/LzipReader.csnew file mode 100644index 00000000..f135df22--- /dev/null+++ b/src/Filee.Engines/Archives/LzipReader.cs@@ -0,0 +1,122 @@+// Reads lzip files (.lz, .tar.lz), which 7-Zip does not open. An lzip member is a 6-byte header ("LZIP", version 1,+// coded dictionary size), a raw LZMA stream (lc=3, lp=0, pb=2, always ended by an end marker) and a 20-byte+// trailer (CRC-32 u32, data size u64, member size u64). Each member is rewritten as a classic .lzma file, which the+// bundled 7-Zip decodes; the result is checked against the trailer.++namespace Filee.Engines.Archives;++/// <summary>Decompresses lzip files with the help of 7-Zip's LZMA decoder.</summary>+internal static class LzipReader+{+ private const int HeaderSize = 6;+ private const int TrailerSize = 20;++ /// <summary>Decompresses <paramref name="lzipFile"/> into <paramref name="outputFile"/>.</summary>+ public static async Task DecompressAsync(string lzipFile, string outputFile, SevenZip sevenZip, string workDirectory,+ CancellationToken cancellationToken)+ {+ var name = Path.GetFileName(lzipFile);+ await using var input = new FileStream(lzipFile, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16);+ var members = FindMembers(input, name);+ ArchiveSafety.EnsureRoom(members.Sum(m => m.DataSize), Path.GetDirectoryName(Path.GetFullPath(outputFile))!, name);++ var folder = Path.Combine(workDirectory, "lzip-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ try+ {+ await using var output = new FileStream(outputFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16);+ foreach (var member in members)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var lzma = Path.Combine(folder, "member.lzma");+ await using (var file = new FileStream(lzma, FileMode.Create, FileAccess.Write))+ {+ input.Position = member.Start + 5;+ var dictionary = DictionarySize(input.ReadByte());+ // .lzma header: properties (lc=3, lp=0, pb=2), dictionary size, unknown size (-1: until the end marker).+ file.WriteByte(0x5D);+ file.Write(BitConverter.GetBytes(dictionary));+ file.Write(BitConverter.GetBytes(-1L));+ ArchiveFiles.CopyLimited(new BoundedStream(input, member.Size - HeaderSize - TrailerSize), file, long.MaxValue, cancellationToken);+ }++ var unpacked = Path.Combine(folder, "out");+ ArchiveFiles.TryDeleteFolder(unpacked);+ await sevenZip.ExtractAsync(lzma, unpacked, [], folder, cancellationToken);+ var result = Path.Combine(unpacked, "member");+ if (!File.Exists(result))+ throw ArchiveSafety.Damaged(name, "LZMA data could not be decoded");++ var crc = new Crc32();+ await using (var decoded = File.OpenRead(result))+ await using (var checkedOutput = new CrcStream(new NonClosingStream(output), crc))+ {+ if (ArchiveFiles.CopyLimited(decoded, checkedOutput, member.DataSize, cancellationToken) != member.DataSize)+ throw ArchiveSafety.Damaged(name, "wrong data size");+ }+ if (crc.Value != member.Crc)+ throw ArchiveSafety.Damaged(name, "checksum error");+ }+ }+ catch+ {+ ArchiveFiles.TryDeleteFile(outputFile);+ throw;+ }+ finally+ {+ ArchiveFiles.TryDeleteFolder(folder);+ }+ File.SetLastWriteTimeUtc(outputFile, File.GetLastWriteTimeUtc(lzipFile));+ }++ /// <summary>One lzip member.</summary>+ private sealed record Member(long Start, long Size, uint Crc, long DataSize);++ /// <summary>+ /// Finds the members from the end of the file backwards (every trailer ends with its member's size), as lzip does.+ /// </summary>+ private static List<Member> FindMembers(FileStream input, string name)+ {+ var members = new List<Member>();+ var trailer = new byte[TrailerSize];+ var header = new byte[5];+ var end = input.Length;+ while (end > 0)+ {+ if (end < HeaderSize + TrailerSize)+ throw InvalidLzip(name);+ input.Position = end - TrailerSize;+ input.ReadExactly(trailer);+ var crc = BitConverter.ToUInt32(trailer, 0);+ var dataSize = BitConverter.ToInt64(trailer, 4);+ var size = BitConverter.ToInt64(trailer, 12);+ if (size < HeaderSize + TrailerSize || size > end || dataSize < 0)+ throw InvalidLzip(name);++ var start = end - size;+ input.Position = start;+ input.ReadExactly(header);+ if (header[0] != 'L' || header[1] != 'Z' || header[2] != 'I' || header[3] != 'P' || header[4] != 1)+ throw InvalidLzip(name);+ members.Insert(0, new Member(start, size, crc, dataSize));+ end = start;+ }+ if (members.Count == 0)+ throw InvalidLzip(name);+ return members;+ }++ /// <summary>+ /// The coded dictionary size of the header: bits 0-4 are the base-2 logarithm, bits 5-7 subtract that many+ /// sixteenths.+ /// </summary>+ internal static uint DictionarySize(int coded)+ {+ var size = 1u << (coded & 0x1F);+ return size - (size / 16) * (uint)((coded >> 5) & 7);+ }++ private static InvalidDataException InvalidLzip(string name) =>+ new($"{name} is not a valid lzip file, or it is damaged.");+}diff --git a/src/Filee.Engines/Archives/SevenZip.cs b/src/Filee.Engines/Archives/SevenZip.csnew file mode 100644index 00000000..654c5ea1--- /dev/null+++ b/src/Filee.Engines/Archives/SevenZip.cs@@ -0,0 +1,218 @@+// Runs Filee's own copy of the 7-Zip console program (engines/7zip: 7z.exe + 7z.dll, GNU LGPL with the unRAR+// restriction, used as a separate process) to list, unpack and create archives, and turns its messages into clear+// errors. 7-Zip installed on the system is never used.++using System.Text;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;++namespace Filee.Engines.Archives;++/// <summary>One entry of a 7-Zip listing (<c>7z l -slt</c>).</summary>+/// <param name="Path">Path inside the archive as 7-Zip reports it (with backslashes on Windows).</param>+/// <param name="SymbolicLink">Target of a symbolic link entry (tar, cpio, zip from Unix), otherwise null.</param>+/// <param name="HardLink">Target of a hard link entry (tar), otherwise null.</param>+internal sealed record SevenZipEntry(string Path, bool IsFolder, long Size, bool IsEncrypted, string? SymbolicLink, string? HardLink)+{+ /// <summary>Unix mode or attribute string of the entry, used to spot links that carry no target field.</summary>+ public string? Mode { get; init; }++ /// <summary>True for symbolic links, which Filee never unpacks (they could point anywhere).</summary>+ public bool IsSymbolicLink => !string.IsNullOrEmpty(SymbolicLink)+ || Mode is { } mode && mode.Split(' ').Any(part => part.Length == 10 && part[0] == 'l');+}++/// <summary>The bundled 7-Zip console program.</summary>+internal sealed class SevenZip(string executable)+{+ /// <summary>Archives can be many gigabytes; the timeout only ends a process that hangs.</summary>+ private static readonly TimeSpan Timeout = TimeSpan.FromHours(6);++ /// <summary>+ /// Password passed when reading, so 7-Zip never waits for one on the console. Unencrypted archives ignore it; for+ /// encrypted ones 7-Zip reports "Wrong password", which becomes the "password-protected" message.+ /// </summary>+ private const string NoPassword = "-pfilee-no-password";++ public string Executable { get; } = executable;++ /// <summary>Filee's own copy (engines/7zip), never one installed on the system.</summary>+ public static SevenZip? Locate() =>+ EngineEnvironment.FindBundled("7zip") is { } folder+ && EngineEnvironment.FirstExisting(Path.Combine(folder, OperatingSystem.IsWindows() ? "7z.exe" : "7zz")) is { } exe+ ? new SevenZip(exe)+ : null;++ /// <summary>Lists the entries of an archive.</summary>+ public async Task<IReadOnlyList<SevenZipEntry>> ListAsync(string archive, CancellationToken cancellationToken)+ {+ var result = await RunAsync(["l", "-slt", "-sccUTF-8", "-bsp0", NoPassword, "--", Path.GetFullPath(archive)], cancellationToken);+ if (result.ExitCode is not (0 or 1))+ throw Failure(archive, result);+ return ParseListing(result.StandardOutput);+ }++ /// <summary>+ /// Unpacks every entry of <paramref name="archive"/> except <paramref name="exclude"/> into+ /// <paramref name="outputDirectory"/>. Clashing names ("A.txt" and "a.txt" on Windows) are renamed, not overwritten.+ /// </summary>+ public async Task ExtractAsync(string archive, string outputDirectory, IReadOnlyCollection<string> exclude,+ string workDirectory, CancellationToken cancellationToken)+ {+ List<string> args = ["x", "-y", "-aou", "-sccUTF-8", "-scsUTF-8", "-bsp0", "-bb0", NoPassword, "-o" + Path.GetFullPath(outputDirectory)];+ if (exclude.Count > 0)+ {+ // A list file keeps unusual names intact; -spd turns off wildcard matching so "*" in a name is literal.+ var list = Path.Combine(workDirectory, $"exclude-{Guid.NewGuid():N}.txt");+ await File.WriteAllLinesAsync(list, exclude, new UTF8Encoding(false), cancellationToken);+ args.AddRange(["-spd", "-x@" + list]);+ }+ args.AddRange(["--", Path.GetFullPath(archive)]);++ var result = await RunAsync(args, cancellationToken);+ if (result.ExitCode is 0 or 1 || result.ExitCode == 2 && OnlyLinkErrors(result))+ return;+ throw Failure(archive, result);+ }++ /// <summary>+ /// Creates <paramref name="archive"/> (which must not exist) from files and folders; each is stored under its own+ /// name, folders with their content.+ /// </summary>+ /// <param name="type">7-Zip archive type: 7z, zip, tar, gzip, bzip2 or xz.</param>+ public async Task AddAsync(string archive, string type, ArchiveLevel level, IReadOnlyList<string> items,+ string workDirectory, CancellationToken cancellationToken)+ {+ var list = Path.Combine(workDirectory, $"items-{Guid.NewGuid():N}.txt");+ await File.WriteAllLinesAsync(list, items.Select(Path.GetFullPath), new UTF8Encoding(false), cancellationToken);+ // -ssw packs files other programs have open; -sse stops instead of silently leaving out unreadable files.+ // No "--" here: it would also turn off the @list file.+ var result = await RunAsync(+ ["a", "-t" + type, LevelSwitch(level), "-ssw", "-sse", "-y", "-sccUTF-8", "-scsUTF-8", "-bsp0", "-bb0",+ Path.GetFullPath(archive), "@" + list],+ cancellationToken);+ if (result.ExitCode is not (0 or 1) || !File.Exists(archive))+ throw new InvalidOperationException($"7-Zip could not create the archive (exit {result.ExitCode}). {ErrorText(result)}".Trim());+ }++ /// <summary>7-Zip's -mx switch for a preset level.</summary>+ internal static string LevelSwitch(ArchiveLevel level) => level switch+ {+ ArchiveLevel.Store => "-mx0",+ ArchiveLevel.Fast => "-mx1",+ ArchiveLevel.Maximum => "-mx9",+ _ => "-mx5",+ };++ /// <summary>Parses the technical listing: blocks of "Key = Value" lines, one per entry, after a "----------" line.</summary>+ internal static List<SevenZipEntry> ParseListing(string output)+ {+ var entries = new List<SevenZipEntry>();+ Dictionary<string, string>? fields = null;+ var inEntries = false;++ foreach (var line in output.Split('\n').Select(l => l.TrimEnd('\r')))+ {+ if (!inEntries)+ {+ inEntries = line.StartsWith("----------", StringComparison.Ordinal);+ continue;+ }+ if (line.Length == 0)+ {+ Flush();+ continue;+ }+ var separator = line.IndexOf(" = ", StringComparison.Ordinal);+ if (separator > 0)+ (fields ??= new(StringComparer.Ordinal))[line[..separator]] = line[(separator + 3)..];+ else if (line.EndsWith(" =", StringComparison.Ordinal))+ (fields ??= new(StringComparer.Ordinal))[line[..^2]] = "";+ }+ Flush();+ return entries;++ void Flush()+ {+ if (fields is null || !fields.TryGetValue("Path", out var path))+ {+ fields = null;+ return;+ }+ string? Field(string key) => fields.TryGetValue(key, out var v) && v.Length > 0 ? v : null;+ var attributes = Field("Attributes") ?? "";+ entries.Add(new SevenZipEntry(+ path,+ Field("Folder") == "+" || attributes.StartsWith('D'),+ long.TryParse(Field("Size"), out var size) ? size : 0,+ Field("Encrypted") == "+",+ Field("Symbolic Link"),+ Field("Hard Link"))+ {+ Mode = Field("Mode") ?? Field("Attributes"),+ });+ fields = null;+ }+ }++ private Task<ProcessResult> RunAsync(IEnumerable<string> arguments, CancellationToken cancellationToken) =>+ ProcessRunner.RunAsync(Executable, arguments, Timeout, cancellationToken);++ /// <summary>True when every error 7-Zip reported is about a link it did not create (we never want links).</summary>+ private static bool OnlyLinkErrors(ProcessResult result)+ {+ var errors = ErrorLines(result).ToList();+ return errors.Count > 0 && errors.All(e =>+ e.Contains("symbolic link", StringComparison.OrdinalIgnoreCase)+ || e.Contains("Dangerous link", StringComparison.OrdinalIgnoreCase));+ }++ /// <summary>Turns a failed 7-Zip run on an archive into an exception with a message users understand.</summary>+ private static Exception Failure(string archive, ProcessResult result)+ {+ var name = Path.GetFileName(archive);+ var text = result.StandardError + "\n" + result.StandardOutput;+ bool Has(string s) => text.Contains(s, StringComparison.OrdinalIgnoreCase);++ if (Has("Wrong password") || Has("encrypted archive"))+ return ArchiveSafety.Encrypted(name);+ if (Has("Cannot open the file as") || Has("Is not archive") || Has("Can not open the file as"))+ return new InvalidDataException($"{name} is not a valid archive, or not the kind its extension says.");+ if (Has("Unexpected end") || Has("Data Error") || Has("CRC Failed") || Has("Headers Error") || Has("Missing volume"))+ return ArchiveSafety.Damaged(name, ErrorText(result));+ return new InvalidOperationException($"7-Zip could not read {name} (exit {result.ExitCode}). {ErrorText(result)}".Trim());+ }++ /// <summary>+ /// The lines of 7-Zip's output that describe errors ("ERROR: ...", and the lines under an "ERRORS:" heading),+ /// without its banner and statistics.+ /// </summary>+ private static IEnumerable<string> ErrorLines(ProcessResult result)+ {+ var underHeading = false;+ foreach (var line in (result.StandardError + "\n" + result.StandardOutput).Split('\n').Select(l => l.Trim()))+ {+ if (line is "ERRORS:" or "WARNINGS:")+ {+ underHeading = true;+ continue;+ }+ if (line.Length == 0)+ {+ underHeading = false;+ continue;+ }+ if (underHeading+ || line.StartsWith("ERROR", StringComparison.OrdinalIgnoreCase)+ || line.StartsWith("Open ERROR", StringComparison.OrdinalIgnoreCase)+ || line.StartsWith("WARNING", StringComparison.OrdinalIgnoreCase))+ yield return line;+ }+ }++ private static string ErrorText(ProcessResult result)+ {+ var lines = ErrorLines(result).Distinct().Take(3).ToList();+ return string.Join(" ", lines.Count > 0 ? lines : result.StandardError.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0).Take(3));+ }+}diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 31b45a74..c0ae9d37 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -1,6 +1,7 @@// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.using Filee.Core.Conversion;+using Filee.Engines.Archives;using Filee.Engines.Hwp;using Filee.Engines.Hwp.Hwpx;using Filee.Engines.Infrastructure;@@ -29,6 +30,7 @@ public static class EngineRegistrynew MarkdownConverter(),new SpreadsheetConverter(),new HwpxConverter(),+ new ArchiveConverter(),new PandocConverter(),new LibreOfficeConverter(env),];@@ -36,4 +38,8 @@ public static class EngineRegistry/// <summary>Finds the PDF merger among the converters.</summary>public static IPdfMerger? FindPdfMerger(IEnumerable<IConverter> converters) =>converters.OfType<IPdfMerger>().FirstOrDefault();++ /// <summary>Finds the engine that packs several files into one archive ("Compress into one archive").</summary>+ public static IFileCombiner? FindFileCombiner(IEnumerable<IConverter> converters) =>+ converters.OfType<IFileCombiner>().FirstOrDefault();}diff --git a/src/Filee.Engines/Infrastructure/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.csindex ace46435..2522c5a7 100644--- a/src/Filee.Engines/Infrastructure/EngineDownloads.cs+++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs@@ -22,7 +22,7 @@ public static class EngineDownloadspublic static IReadOnlyDictionary<string, EngineComponent> Components { get; } = Load();/// <summary>- /// Packages offered in Settings → Engines and on first run. rhwp is not listed: it is small and bundled.+ /// Packages offered in Settings → Engines and on first run. rhwp and 7-Zip are not listed: they are small and bundled./// </summary>public static IReadOnlyList<EnginePackage> Packages { get; } =[diff --git a/src/Filee.Engines/Infrastructure/engines.json b/src/Filee.Engines/Infrastructure/engines.jsonindex 02d25ed7..02f23d44 100644--- a/src/Filee.Engines/Infrastructure/engines.json+++ b/src/Filee.Engines/Infrastructure/engines.json@@ -8,6 +8,13 @@"size": 10270410,"kind": "zip"},+ "7zip": {+ "version": "26.03",+ "url": "https://github.com/ip7z/7zip/releases/download/26.03/7z2603-x64.msi",+ "sha256": "C0680064D698A62DD4A5A47F403DB356A6531A5473E4C4B1D090EA2590513926",+ "size": 2007040,+ "kind": "msi"+ },"pandoc": {"version": "3.12","url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-windows-x86_64.zip",diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.csindex abf3168c..badd5027 100644--- a/tests/Filee.Core.Tests/FakeConverter.cs+++ b/tests/Filee.Core.Tests/FakeConverter.cs@@ -49,6 +49,26 @@ internal sealed class FakeMerger : IPdfMerger}}+/// <summary>Test double for "Compress into one archive": writes the input names into the output file.</summary>+internal sealed class FakeCombiner : IFileCombiner+{+ public List<string> Inputs { get; } = [];++ public bool Throw { get; set; }++ public bool CanCombineInto(string format) => true;++ public Task CombineAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Filee.Core.Presets.Preset preset,+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ if (Throw)+ throw new InvalidOperationException("boom");+ Inputs.AddRange(inputPaths);+ File.WriteAllText(outputPath, string.Join("|", inputPaths.Select(Path.GetFileName)));+ return Task.CompletedTask;+ }+}+/// <summary>Creates and removes a unique temp directory.</summary>internal sealed class TempDir : IDisposable{diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.csindex fa784876..8a5fe370 100644--- a/tests/Filee.Core.Tests/JobQueueTests.cs+++ b/tests/Filee.Core.Tests/JobQueueTests.cs@@ -117,6 +117,58 @@ public class JobQueueTestsAssert.Equal(second, merger.Inputs[1]); // existing PDFs are merged as-is}+ [Fact]+ public async Task Combine_packs_every_file_as_is_even_one_or_of_unknown_type()+ {+ using var dir = new TempDir();+ var a = dir.File("report.docx");+ var b = dir.File("data.xyz");+ var combiner = new FakeCombiner();+ // No converter at all: combining must not need a route.+ await using var queue = new JobQueue(new ConverterCatalog([]), combiner: combiner);+ var preset = new Preset { TargetFormat = "zip", Archive = { CombineIntoOne = true }, Output = { FileNamePattern = "{name}_files" } };++ var job = await Run(queue, [a, b], preset);++ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal([a, b], combiner.Inputs);+ Assert.Equal(Path.Combine(dir.Path, "report_files.zip"), job.Outputs.Single());+ Assert.All(job.Files, f => Assert.Equal(FileState.Done, f.State));++ var single = await Run(queue, [b], preset);+ Assert.Equal(Path.Combine(dir.Path, "data_files.zip"), single.Outputs.Single());+ }++ [Fact]+ public async Task Combine_uses_the_two_part_extension_and_reports_failures_for_every_file()+ {+ using var dir = new TempDir();+ var a = dir.File("a.txt");+ await using var queue = new JobQueue(new ConverterCatalog([]), combiner: new FakeCombiner());++ var job = await Run(queue, [a], new Preset { TargetFormat = "tgz", Archive = { CombineIntoOne = true } });+ Assert.Equal(Path.Combine(dir.Path, "a.tar.gz"), job.Outputs.Single());++ await using var failing = new JobQueue(new ConverterCatalog([]), combiner: new FakeCombiner { Throw = true });+ var failed = await Run(failing, [a, dir.File("b.txt")], new Preset { TargetFormat = "zip", Archive = { CombineIntoOne = true } });+ Assert.Equal(JobState.Failed, failed.State);+ Assert.All(failed.Files, f => Assert.Equal("boom", f.ErrorDetail));+ }++ [Fact]+ public async Task Without_combine_archive_targets_convert_file_by_file()+ {+ using var dir = new TempDir();+ var combiner = new FakeCombiner();+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("archive", new ConversionEdge("rar", "zip"))]), combiner: combiner);++ var job = await Run(queue, [dir.File("a.rar"), dir.File("b.rar")], new Preset { TargetFormat = "zip" });++ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal(2, job.Outputs.Count());+ Assert.Empty(combiner.Inputs);+ }+[Fact]public async Task Parallel_files_with_the_same_name_do_not_collide(){diff --git a/tests/Filee.Engines.Tests/ArchiveBuilders.cs b/tests/Filee.Engines.Tests/ArchiveBuilders.csnew file mode 100644index 00000000..b32ff293--- /dev/null+++ b/tests/Filee.Engines.Tests/ArchiveBuilders.cs@@ -0,0 +1,302 @@+// Builds archive test inputs in code: folder trees with Korean names, ZIPs (System.IO.Compression), ALZ and EGG+// files written per their format documentation (see AlzReader / EggReader), lzip files, and raw bzip2 / LZMA streams+// taken from what the bundled 7-Zip writes.++using System.IO.Compression;+using System.Text;+using Filee.Engines.Archives;+using Filee.Engines.Infrastructure;++namespace Filee.Engines.Tests;++internal static class ArchiveBuilders+{+ /// <summary>A fixed modification time for checking that times survive.</summary>+ public static readonly DateTime KnownTime = new(2021, 5, 6, 7, 8, 10, DateTimeKind.Local);++ /// <summary>+ /// Creates <paramref name="name"/> below <paramref name="parent"/> with a Korean file name, a nested folder with+ /// a Korean name, an empty folder, and a file with <see cref="KnownTime"/>.+ /// </summary>+ public static string MakeTree(string parent, string name)+ {+ var root = Path.Combine(parent, name);+ Directory.CreateDirectory(Path.Combine(root, "docs", "보고서"));+ Directory.CreateDirectory(Path.Combine(root, "empty"));+ File.WriteAllText(Path.Combine(root, "readme.txt"), "Filee archive test\n");+ File.WriteAllText(Path.Combine(root, "한글 문서.txt"), "안녕하세요, archive 文件");+ File.WriteAllText(Path.Combine(root, "docs", "보고서", "data.csv"), "a,b\n1,2\n");+ File.WriteAllBytes(Path.Combine(root, "docs", "noise.bin"), Noise(200_000, 7));+ File.SetLastWriteTime(Path.Combine(root, "readme.txt"), KnownTime);+ return root;+ }++ /// <summary>Relative path → SHA-256 of every file below <paramref name="root"/>, and "dir/" for empty folders.</summary>+ public static SortedDictionary<string, string> Snapshot(string root)+ {+ var result = new SortedDictionary<string, string>(StringComparer.Ordinal);+ foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories))+ result[Relative(root, file)] = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(file)));+ foreach (var dir in Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories))+ if (!Directory.EnumerateFileSystemEntries(dir).Any())+ result[Relative(root, dir) + "/"] = "";+ return result;+ }++ private static string Relative(string root, string path) => Path.GetRelativePath(root, path).Replace('\\', '/');++ /// <summary>Pseudo-random bytes (compress badly, like photos).</summary>+ public static byte[] Noise(int length, int seed)+ {+ var bytes = new byte[length];+ new Random(seed).NextBytes(bytes);+ return bytes;+ }++ /// <summary>Text that compresses well but not trivially (for multi-block bzip2).</summary>+ public static byte[] Words(int length)+ {+ var sb = new StringBuilder();+ var random = new Random(42);+ string[] words = ["파일", "변환", "archive", "Filee", "압축", "folder", "데이터", "zip", "문서", "7-Zip", "\n"];+ while (sb.Length < length)+ sb.Append(words[random.Next(words.Length)]).Append(' ');+ return Encoding.UTF8.GetBytes(sb.ToString())[..length];+ }++ /// <summary>The bundled 7-Zip, or null when engines/7zip is missing.</summary>+ public static string? SevenZipExe => SevenZip.Locate()?.Executable;++ /// <summary>Runs 7-Zip with the given arguments and fails the test on an error.</summary>+ public static async Task Run7zAsync(params string[] args)+ {+ var result = await ProcessRunner.RunAsync(SevenZipExe!, args, TimeSpan.FromMinutes(2), CancellationToken.None);+ Assert.True(result.ExitCode == 0, $"7z {string.Join(' ', args)}: {result.StandardOutput} {result.StandardError}");+ }++ /// <summary>Standard bzip2 stream of <paramref name="data"/> written by 7-Zip at level 9 ("BZh9", 900k blocks).</summary>+ public static async Task<byte[]> Bzip2Async(byte[] data, string workDir)+ {+ var dir = Directory.CreateDirectory(Path.Combine(workDir, "bz-" + Guid.NewGuid().ToString("N")[..6])).FullName;+ var input = Path.Combine(dir, "data.bin");+ await File.WriteAllBytesAsync(input, data);+ var output = Path.Combine(dir, "data.bz2");+ await Run7zAsync("a", "-tbzip2", "-mx9", "-mmt=off", output, input);+ return await File.ReadAllBytesAsync(output);+ }++ /// <summary>+ /// A raw LZMA stream (lc=3, lp=0, pb=2, 1 MiB dictionary) of <paramref name="data"/>: 7-Zip writes it into a .7z+ /// without header compression, where the only packed stream starts at offset 32 and is as long as the "next+ /// header offset" of the signature header says.+ /// </summary>+ public static async Task<byte[]> RawLzmaAsync(byte[] data, bool endMarker, string workDir)+ {+ var dir = Directory.CreateDirectory(Path.Combine(workDir, "lzma-" + Guid.NewGuid().ToString("N")[..6])).FullName;+ var input = Path.Combine(dir, "data.bin");+ await File.WriteAllBytesAsync(input, data);+ var output = Path.Combine(dir, "data.7z");+ await Run7zAsync("a", "-t7z", "-m0=LZMA:d=1m:lc=3:lp=0:pb=2" + (endMarker ? ":eos" : ""), "-mhc=off", "-mf=off",+ "-ms=off", "-mmt=off", output, input);+ var archive = await File.ReadAllBytesAsync(output);+ var packedSize = (int)BitConverter.ToInt64(archive, 12);+ return archive[32..(32 + packedSize)];+ }++ /// <summary>An lzip member of <paramref name="data"/> (see LzipReader).</summary>+ public static async Task<byte[]> LzipAsync(byte[] data, string workDir)+ {+ var lzma = await RawLzmaAsync(data, endMarker: true, workDir);+ using var ms = new MemoryStream();+ ms.Write("LZIP"u8);+ ms.WriteByte(1);+ ms.WriteByte(20); // 2^20 = 1 MiB dictionary+ ms.Write(lzma);+ ms.Write(BitConverter.GetBytes(Crc32.Compute(data)));+ ms.Write(BitConverter.GetBytes((long)data.Length));+ ms.Write(BitConverter.GetBytes(6L + lzma.Length + 20));+ return ms.ToArray();+ }++ /// <summary>+ /// Rewrites a standard bzip2 stream into ALZip's framing: no "BZh9", "DLZ\x01" instead of each block's magic, CRC+ /// and randomised bit, "DLZ\x02" instead of the end magic and combined CRC. Blocks are found by their 48-bit magic.+ /// </summary>+ public static byte[] ToAlzBzip2(byte[] standard)+ {+ Assert.Equal("BZh9"u8.ToArray(), standard[..4]);+ var bits = new bool[standard.Length * 8];+ for (var i = 0; i < bits.Length; i++)+ bits[i] = (standard[i >> 3] & (0x80 >> (i & 7))) != 0;++ const ulong blockMagic = 0x314159265359, endMagic = 0x177245385090;+ ulong Read48(int at)+ {+ ulong v = 0;+ for (var i = 0; i < 48; i++)+ v = (v << 1) | (bits[at + i] ? 1UL : 0);+ return v;+ }++ var output = new List<bool>();+ void Write(uint value, int count)+ {+ for (var i = count - 1; i >= 0; i--)+ output.Add(((value >> i) & 1) != 0);+ }++ var pos = 32;+ while (true)+ {+ var magic = Read48(pos);+ if (magic == endMagic)+ {+ Write(0x444C5A02, 32);+ break;+ }+ Assert.Equal(blockMagic, magic);+ Write(0x444C5A01, 32);+ pos += 48 + 32 + 1;+ var next = pos;+ while (Read48(next) is not (blockMagic or endMagic))+ next++;+ output.AddRange(bits[pos..next]);+ pos = next;+ }++ var bytes = new byte[(output.Count + 7) / 8];+ for (var i = 0; i < output.Count; i++)+ if (output[i])+ bytes[i >> 3] |= (byte)(0x80 >> (i & 7));+ return bytes;+ }++ /// <summary>One entry of a test ALZ file.</summary>+ /// <param name="Method">0 store, 1 ALZ bzip2 (<paramref name="Packed"/> must be given), 2 deflate.</param>+ public sealed record AlzItem(string Name, byte[]? Data, int Method = 0, byte[]? Packed = null, bool Encrypted = false);++ /// <summary>Writes an ALZ archive; names are stored in CP949 like ALZip does.</summary>+ public static void WriteAlz(string path, IEnumerable<AlzItem> items)+ {+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);+ var cp949 = Encoding.GetEncoding(949);+ using var w = new BinaryWriter(File.Create(path));+ w.Write("ALZ\x01"u8);+ w.Write([0x0A, 0, 0, 0]);+ foreach (var item in items)+ {+ var name = cp949.GetBytes(item.Name);+ var packed = item.Data is null ? [] : item.Method switch+ {+ 0 => item.Data,+ 1 => item.Packed!,+ _ => Deflate(item.Data),+ };+ w.Write("BLZ\x01"u8);+ w.Write((ushort)name.Length);+ w.Write((byte)(item.Data is null ? 0x10 : 0x20));+ w.Write(DosTime(KnownTime));+ w.Write((byte)((item.Data is null ? 0x00 : 0x40) | (item.Encrypted ? 1 : 0)));+ w.Write((byte)0);+ if (item.Data is not null)+ {+ w.Write((byte)item.Method);+ w.Write((byte)0);+ w.Write(Crc32.Compute(item.Data));+ w.Write(packed.Length);+ w.Write(item.Data.Length);+ }+ w.Write(name);+ if (item.Encrypted)+ w.Write(new byte[12]);+ w.Write(packed);+ }+ w.Write("CLZ\x01"u8);+ w.Write(new byte[12]);+ w.Write("CLZ\x02"u8);+ w.Write(new byte[12]);+ }++ /// <summary>One block of a test EGG entry.</summary>+ /// <param name="Method">0 store, 1 deflate, 2 bzip2, 4 LZMA (<paramref name="Packed"/> given for 2 and 4).</param>+ public sealed record EggBlock(byte[] Data, int Method, byte[]? Packed = null);++ /// <summary>One entry of a test EGG file; no blocks for folders.</summary>+ public sealed record EggItem(string Name, bool Folder, params EggBlock[] Blocks);++ /// <summary>Writes an EGG archive (UTF-8 names, Windows file info with <see cref="KnownTime"/>).</summary>+ public static void WriteEgg(string path, IEnumerable<EggItem> items, bool solid = false)+ {+ const uint end = 0x08E28222;+ using var w = new BinaryWriter(File.Create(path));+ w.Write(0x41474745u);+ w.Write((ushort)0x0100);+ w.Write(0x12345678u);+ w.Write(0u);+ if (solid)+ {+ w.Write(0x24E5A060u);+ w.Write((byte)0);+ w.Write((ushort)0);+ }+ w.Write(end);++ var id = 0u;+ foreach (var item in items)+ {+ w.Write(0x0A8590E3u);+ w.Write(id++);+ w.Write((long)item.Blocks.Sum(b => b.Data.Length));++ var name = Encoding.UTF8.GetBytes(item.Name);+ w.Write(0x0A8591ACu);+ w.Write((byte)0);+ w.Write((ushort)name.Length);+ w.Write(name);++ w.Write(0x2C86950Bu);+ w.Write((byte)0);+ w.Write((ushort)9);+ w.Write(KnownTime.ToFileTimeUtc());+ w.Write((byte)(item.Folder ? 0x10 : 0x20));+ w.Write(end);++ foreach (var block in item.Blocks)+ {+ var packed = block.Method switch+ {+ 0 => block.Data,+ 1 => Deflate(block.Data),+ _ => block.Packed!,+ };+ w.Write(0x02B50C13u);+ w.Write((byte)block.Method);+ w.Write((byte)0);+ w.Write((uint)block.Data.Length);+ w.Write((uint)packed.Length);+ w.Write(Crc32.Compute(block.Data));+ w.Write(end);+ w.Write(packed);+ }+ }+ w.Write(end);+ }++ /// <summary>EGG's LZMA block layout: ZIP's 4-byte LZMA header, 5 property bytes, raw data.</summary>+ public static byte[] EggLzma(byte[] rawLzma)+ {+ byte[] header = [9, 20, 5, 0, 0x5D, 0x00, 0x00, 0x10, 0x00]; // version 9.20, 5 property bytes, 1 MiB dictionary+ return [.. header, .. rawLzma];+ }++ private static byte[] Deflate(byte[] data)+ {+ using var ms = new MemoryStream();+ using (var deflate = new DeflateStream(ms, CompressionLevel.Optimal, leaveOpen: true))+ deflate.Write(data);+ return ms.ToArray();+ }++ private static uint DosTime(DateTime t) =>+ (uint)((t.Year - 1980) << 25 | t.Month << 21 | t.Day << 16 | t.Hour << 11 | t.Minute << 5 | t.Second / 2);+}diff --git a/tests/Filee.Engines.Tests/ArchiveTests.cs b/tests/Filee.Engines.Tests/ArchiveTests.csnew file mode 100644index 00000000..76d30c2d--- /dev/null+++ b/tests/Filee.Engines.Tests/ArchiveTests.cs@@ -0,0 +1,605 @@+// Archive engine: conversions between archive formats (names incl. Korean, folders, contents and times survive),+// Extract to a folder, "Compress into one archive", Filee's own ALZ / EGG / lzip / bzip2 readers, and the safety+// checks (zip slip, links, passwords). Tests that need the bundled 7-Zip skip when engines/7zip is missing+// (pwsh build/fetch-engines.ps1 -Only 7zip).++using System.Formats.Tar;+using System.IO.Compression;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Archives;+using static Filee.Engines.Tests.ArchiveBuilders;++namespace Filee.Engines.Tests;++public class ArchiveTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static CancellationToken Ct => TestContext.Current.CancellationToken;++ private void SkipWithout7Zip()+ {+ var engine = fx.Converters.Single(c => c.Id == "archive");+ Assert.SkipUnless(fx.Catalog.StatusOf(engine).IsAvailable, "7-Zip not found (pwsh build/fetch-engines.ps1 -Only 7zip)");+ }++ private async Task<ConversionJob> ConvertOkAsync(string source, Preset preset)+ {+ var job = await fx.ConvertAsync([source], preset);+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ return job;+ }++ private static Preset Extract => BuiltInData.CreatePresets().Single(p => p.Id == "extract");++ // ───────── Routes ─────────++ [Theory]+ [InlineData("zip")]+ [InlineData("jar")]+ [InlineData("7z")]+ [InlineData("rar")]+ [InlineData("tgz")]+ [InlineData("tbz2")]+ [InlineData("txz")]+ [InlineData("tar7z")]+ [InlineData("tz")]+ [InlineData("iso")]+ [InlineData("dmg")]+ [InlineData("cab")]+ [InlineData("rpm")]+ [InlineData("deb")]+ [InlineData("lha")]+ [InlineData("arj")]+ [InlineData("alz")]+ [InlineData("egg")]+ [InlineData("lz")]+ [InlineData("tlz")]+ public void Every_readable_archive_converts_in_one_step(string from)+ {+ var planner = fx.Catalog.CreatePlanner(["archive"]);+ foreach (var to in new[] { "zip", "7z", "tar", "tgz", "tbz2", "txz", FormatRegistry.Folder })+ {+ var route = planner.Plan(from, to);+ Assert.NotNull(route);+ Assert.Equal("archive", Assert.Single(route.Steps).Converter.Id);+ }+ }++ [Fact]+ public void Single_file_compressors_convert_among_each_other_but_archives_do_not_shrink_to_them()+ {+ var planner = fx.Catalog.CreatePlanner(["archive"]);+ Assert.Single(planner.Plan("gz", "xz")!.Steps);+ Assert.Single(planner.Plan("lzma", "bz2")!.Steps);+ Assert.Single(planner.Plan("lz", "gz")!.Steps);+ Assert.Null(planner.Plan("zip", "gz")); // several files do not fit into one .gz+ Assert.Null(planner.Plan("zip", "rar")); // RAR cannot be written+ Assert.Null(planner.Plan("lzo", "zip")); // no LZO reader+ // Every format the edges name exists in the registry.+ foreach (var edge in fx.Converters.Single(c => c.Id == "archive").Edges)+ {+ Assert.NotNull(FormatRegistry.FindById(edge.From));+ Assert.NotNull(FormatRegistry.FindById(edge.To));+ }+ }++ // ───────── Archive → archive ─────────++ [Fact]+ public async Task Zip_7z_tgz_tar_zip_round_trip_keeps_names_folders_contents_and_times()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var tree = MakeTree(dir, "프로젝트");+ var expected = Snapshot(tree);+ var zip = Path.Combine(dir, "프로젝트.zip");+ ZipFile.CreateFromDirectory(tree, zip, CompressionLevel.Optimal, includeBaseDirectory: true, Encoding.UTF8);++ var current = zip;+ foreach (var target in new[] { "7z", "tgz", "tar", "tbz2", "txz", "zip" })+ {+ var job = await ConvertOkAsync(current, new Preset { TargetFormat = target });+ current = job.Outputs.Single();+ Assert.EndsWith("." + FormatRegistry.Get(target).PrimaryExtension, current);+ }++ // The last ZIP read by .NET's own reader: same tree below the "프로젝트" folder, UTF-8 names flagged.+ var check = Path.Combine(dir, "check");+ ZipFile.ExtractToDirectory(current, check);+ Assert.Equal(expected, Snapshot(Path.Combine(check, "프로젝트")));+ var time = File.GetLastWriteTime(Path.Combine(check, "프로젝트", "readme.txt"));+ Assert.True(Math.Abs((time - KnownTime).TotalSeconds) <= 2, $"time {time} instead of {KnownTime}");+ }++ [Fact]+ public async Task Store_and_maximum_levels_are_applied()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var text = Path.Combine(dir, "big.txt");+ await File.WriteAllBytesAsync(text, Words(300_000), Ct);+ var source = Path.Combine(dir, "source.zip");+ using (var zip = ZipFile.Open(source, ZipArchiveMode.Create))+ zip.CreateEntryFromFile(text, "big.txt");++ var stored = await ConvertOkAsync(source, new Preset { TargetFormat = "7z", Archive = { Level = ArchiveLevel.Store }, Output = { FileNamePattern = "{name}_store" } });+ var max = await ConvertOkAsync(source, new Preset { TargetFormat = "7z", Archive = { Level = ArchiveLevel.Maximum }, Output = { FileNamePattern = "{name}_max" } });+ Assert.True(new FileInfo(stored.Outputs.Single()).Length > 300_000);+ Assert.True(new FileInfo(max.Outputs.Single()).Length < 100_000);+ }++ [Fact]+ public async Task Single_file_streams_convert_gz_xz_bz2()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var data = Words(50_000);+ var csv = Path.Combine(dir, "data.csv");+ await File.WriteAllBytesAsync(csv, data, Ct);+ var gz = Path.Combine(dir, "data.csv.gz");+ await Run7zAsync("a", "-tgzip", gz, csv);+ File.Delete(csv);++ var xz = (await ConvertOkAsync(gz, new Preset { TargetFormat = "xz" })).Outputs.Single();+ var bz2 = (await ConvertOkAsync(xz, new Preset { TargetFormat = "bz2" })).Outputs.Single();+ Assert.EndsWith("data.csv.bz2", bz2);++ var folder = (await ConvertOkAsync(bz2, Extract)).Outputs.Single();+ Assert.Equal(data, await File.ReadAllBytesAsync(Path.Combine(folder, "data.csv"), Ct));+ }++ // ───────── Extract ─────────++ [Fact]+ public async Task Extract_does_not_nest_a_single_top_folder_and_renames_on_conflict()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var tree = MakeTree(dir, "photos");+ var expected = Snapshot(tree);+ var zip = Path.Combine(dir, "사진.zip");+ ZipFile.CreateFromDirectory(tree, zip, CompressionLevel.Fastest, includeBaseDirectory: true, Encoding.UTF8);+ Directory.Delete(tree, true);++ var first = await ConvertOkAsync(zip, Extract);+ var folder = first.Outputs.Single();+ Assert.Equal(Path.Combine(dir, "사진"), folder);+ Assert.Equal(expected, Snapshot(folder)); // photos/… became 사진/…, not 사진/photos/…++ var second = await ConvertOkAsync(zip, Extract);+ Assert.Equal(Path.Combine(dir, "사진 (2)"), second.Outputs.Single());+ Assert.Equal(expected, Snapshot(second.Outputs.Single()));++ // Nothing else was left next to the archive (no staging folders).+ Assert.Equal(["사진", "사진 (2)", "사진.zip"], Directory.GetFileSystemEntries(dir).Select(Path.GetFileName).Order(StringComparer.Ordinal));+ }++ [Fact]+ public async Task Extract_keeps_several_top_entries_in_a_folder_named_after_the_archive_and_unpacks_tar_gz_fully()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var tree = MakeTree(dir, "tree");+ var tgz = Path.Combine(dir, "backup.tar.gz");+ await using (var file = File.Create(tgz))+ await using (var gzip = new GZipStream(file, CompressionLevel.Fastest))+ await TarFile.CreateFromDirectoryAsync(tree, gzip, includeBaseDirectory: false, Ct);++ var folder = (await ConvertOkAsync(tgz, Extract)).Outputs.Single();+ Assert.Equal(Path.Combine(dir, "backup"), folder);+ Assert.Equal(Snapshot(tree), Snapshot(folder)); // files, not a lone backup.tar+ }++ [Fact]+ public async Task Extract_with_overwrite_merges_into_the_existing_folder_and_skip_leaves_it_alone()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var tree = MakeTree(dir, "data");+ var zip = Path.Combine(dir, "data.zip");+ ZipFile.CreateFromDirectory(tree, zip, CompressionLevel.Fastest, includeBaseDirectory: false, Encoding.UTF8);+ Directory.Delete(tree, true);+ var target = Directory.CreateDirectory(Path.Combine(dir, "data")).FullName;+ await File.WriteAllTextAsync(Path.Combine(target, "readme.txt"), "old", Ct);+ await File.WriteAllTextAsync(Path.Combine(target, "mine.txt"), "keep", Ct);++ var overwrite = Extract;+ overwrite.Output.Conflict = ConflictPolicy.Overwrite;+ Assert.Equal(target, (await ConvertOkAsync(zip, overwrite)).Outputs.Single());+ Assert.Equal("Filee archive test\n", await File.ReadAllTextAsync(Path.Combine(target, "readme.txt"), Ct));+ Assert.Equal("keep", await File.ReadAllTextAsync(Path.Combine(target, "mine.txt"), Ct));+ Assert.True(File.Exists(Path.Combine(target, "docs", "보고서", "data.csv")));++ var skip = Extract;+ skip.Output.Conflict = ConflictPolicy.Skip;+ var skipped = await fx.ConvertAsync([zip], skip);+ Assert.Equal(FileState.Skipped, skipped.Files[0].State);+ Assert.Empty(skipped.Outputs);+ }++ [Fact]+ public async Task Tar_symbolic_links_are_not_unpacked()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var tar = Path.Combine(dir, "links.tar");+ await using (var stream = File.Create(tar))+ await using (var writer = new TarWriter(stream, TarEntryFormat.Pax))+ {+ await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.RegularFile, "real.txt") { DataStream = new MemoryStream("real"u8.ToArray()) }, Ct);+ await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.SymbolicLink, "escape") { LinkName = "../../../../Windows/win.ini" }, Ct);+ await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.SymbolicLink, "inside") { LinkName = "real.txt" }, Ct);+ }++ var folder = (await ConvertOkAsync(tar, Extract)).Outputs.Single();+ Assert.Equal(["real.txt"], Directory.GetFileSystemEntries(folder).Select(Path.GetFileName));+ }++ [Fact]+ public async Task Zip_slip_entries_are_rejected()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var inner = Directory.CreateDirectory(Path.Combine(dir, "inner")).FullName;+ var zip = Path.Combine(inner, "evil.zip");+ using (var archive = ZipFile.Open(zip, ZipArchiveMode.Create))+ {+ using (var w = new StreamWriter(archive.CreateEntry("good.txt").Open()))+ w.Write("good");+ using (var w = new StreamWriter(archive.CreateEntry("../../evil.txt").Open()))+ w.Write("evil");+ }++ var job = await fx.ConvertAsync([zip], Extract);++ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("outside the target folder", job.Files[0].ErrorDetail);+ Assert.False(File.Exists(Path.Combine(dir, "evil.txt")));+ Assert.Equal(["evil.zip"], Directory.GetFileSystemEntries(inner).Select(Path.GetFileName)); // no half-extracted folder+ }++ [Fact]+ public async Task Password_protected_archives_fail_with_a_clear_message()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var secret = Path.Combine(dir, "secret.txt");+ await File.WriteAllTextAsync(secret, "secret", Ct);+ var zip = Path.Combine(dir, "locked.zip");+ var sevenZip = Path.Combine(dir, "locked.7z");+ await Run7zAsync("a", "-tzip", "-ppassword", zip, secret);+ await Run7zAsync("a", "-t7z", "-ppassword", "-mhe=on", sevenZip, secret);++ foreach (var archive in new[] { zip, sevenZip })+ {+ var job = await fx.ConvertAsync([archive], new Preset { TargetFormat = "tgz" });+ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("password-protected", job.Files[0].ErrorDetail);+ }+ }++ [Fact]+ public async Task Damaged_and_fake_archives_fail_cleanly()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var fake = Path.Combine(dir, "fake.zip");+ await File.WriteAllTextAsync(fake, "this is not a zip", Ct);++ var job = await fx.ConvertAsync([fake], Extract);++ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("not a valid archive", job.Files[0].ErrorDetail);+ Assert.Equal(["fake.zip"], Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));+ }++ // ───────── Compress into one archive ─────────++ [Fact]+ public async Task Zip_all_packs_any_files_as_they_are()+ {+ var dir = fx.NewFolder();+ var a = Directory.CreateDirectory(Path.Combine(dir, "a")).FullName;+ var b = Directory.CreateDirectory(Path.Combine(dir, "b")).FullName;+ var report = Path.Combine(a, "보고서.txt");+ await File.WriteAllTextAsync(report, "보고서", Ct);+ var unknown = Path.Combine(a, "data.xyz");+ await File.WriteAllBytesAsync(unknown, Noise(1000, 1), Ct);+ var image = EngineFixture.MakeImage(a, "photo.png", ImageMagick.MagickFormat.Png);+ var sameName = Path.Combine(b, "보고서.txt");+ await File.WriteAllTextAsync(sameName, "다른 보고서", Ct);++ var zipAll = BuiltInData.CreatePresets().Single(p => p.Id == "zip-all");+ var job = await fx.ConvertAsync([report, unknown, image, sameName], zipAll);++ Assert.Equal(JobState.Completed, job.State);+ var output = job.Outputs.Single();+ Assert.Equal(Path.Combine(a, "보고서_files.zip"), output);+ using var zip = ZipFile.OpenRead(output);+ Assert.Equal(["data.xyz", "photo.png", "보고서 (2).txt", "보고서.txt"], zip.Entries.Select(e => e.FullName).Order(StringComparer.Ordinal));+ using (var reader = new StreamReader(zip.GetEntry("보고서 (2).txt")!.Open()))+ Assert.Equal("다른 보고서", await reader.ReadToEndAsync(Ct));+ Assert.Equal(await File.ReadAllBytesAsync(image, Ct), ReadAll(zip.GetEntry("photo.png")!));+ Assert.True(File.Exists(report)); // sources untouched+ }++ [Fact]+ public async Task Zip_all_works_for_a_single_file_and_honours_the_level()+ {+ var dir = fx.NewFolder();+ var text = Path.Combine(dir, "notes.md");+ await File.WriteAllBytesAsync(text, Words(100_000), Ct);+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "zip-all");+ preset.Archive.Level = ArchiveLevel.Store;++ var job = await fx.ConvertAsync([text], preset);++ Assert.Equal(JobState.Completed, job.State);+ using var zip = ZipFile.OpenRead(job.Outputs.Single());+ var entry = Assert.Single(zip.Entries);+ Assert.Equal("notes.md", entry.Name);+ Assert.Equal(entry.Length, entry.CompressedLength);+ }++ [Fact]+ public async Task Zip_all_packs_a_folder_from_the_command_line_with_its_content()+ {+ var dir = fx.NewFolder();+ var tree = MakeTree(dir, "tree");++ var job = await fx.ConvertAsync([tree], BuiltInData.CreatePresets().Single(p => p.Id == "zip-all"));++ Assert.Equal(JobState.Completed, job.State);+ Assert.Equal(Path.Combine(dir, "tree_files.zip"), job.Outputs.Single());+ var check = Path.Combine(dir, "check");+ ZipFile.ExtractToDirectory(job.Outputs.Single(), check);+ Assert.Equal(Snapshot(tree), Snapshot(Path.Combine(check, "tree")));+ }++ [Theory]+ [InlineData("7z")]+ [InlineData("tgz")]+ [InlineData("txz")]+ public async Task Combine_into_other_archive_formats(string format)+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var one = Path.Combine(dir, "하나.txt");+ var two = Path.Combine(Directory.CreateDirectory(Path.Combine(dir, "sub")).FullName, "하나.txt");+ await File.WriteAllTextAsync(one, "1", Ct);+ await File.WriteAllTextAsync(two, "2", Ct);++ var job = await fx.ConvertAsync([one, two], new Preset { TargetFormat = format, Archive = { CombineIntoOne = true } });+ Assert.Equal(JobState.Completed, job.State);++ var folder = (await ConvertOkAsync(job.Outputs.Single(), Extract)).Outputs.Single();+ Assert.Equal("1", await File.ReadAllTextAsync(Path.Combine(folder, "하나.txt"), Ct));+ Assert.Equal("2", await File.ReadAllTextAsync(Path.Combine(folder, "하나 (2).txt"), Ct));+ }++ // ───────── Filee's own readers ─────────++ [Fact]+ public async Task Alz_with_stored_deflated_and_bzip2_entries_and_korean_names()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var big = Words(2_000_000); // three 900k bzip2 blocks+ var small = Encoding.UTF8.GetBytes("알집 테스트 ALZ");+ var alz = Path.Combine(dir, "알집.alz");+ WriteAlz(alz,+ [+ new("폴더\\", null),+ new("폴더\\저장.txt", small, Method: 0),+ new("압축.txt", Words(10_000), Method: 2),+ new("큰 파일.txt", big, Method: 1, Packed: ToAlzBzip2(await Bzip2Async(big, dir))),+ ]);++ var folder = (await ConvertOkAsync(alz, Extract)).Outputs.Single();++ Assert.Equal(small, await File.ReadAllBytesAsync(Path.Combine(folder, "폴더", "저장.txt"), Ct));+ Assert.Equal(Words(10_000), await File.ReadAllBytesAsync(Path.Combine(folder, "압축.txt"), Ct));+ Assert.Equal(big, await File.ReadAllBytesAsync(Path.Combine(folder, "큰 파일.txt"), Ct));+ Assert.Equal(KnownTime, File.GetLastWriteTime(Path.Combine(folder, "압축.txt")));++ var zip = (await ConvertOkAsync(alz, new Preset { TargetFormat = "zip" })).Outputs.Single();+ using var archive = ZipFile.OpenRead(zip);+ Assert.Contains(archive.Entries, e => e.FullName == "폴더/저장.txt");+ }++ [Fact]+ public void Alz_reader_refuses_escaping_and_encrypted_entries_without_writing_outside()+ {+ var dir = fx.NewFolder();+ var target = Directory.CreateDirectory(Path.Combine(dir, "out")).FullName;+ var slip = Path.Combine(dir, "slip.alz");+ WriteAlz(slip, [new("ok.txt", [1]), new("..\\..\\evil.txt", [2])]);+ var locked = Path.Combine(dir, "locked.alz");+ WriteAlz(locked, [new("secret.txt", [3], Encrypted: true)]);++ var error = Assert.Throws<InvalidDataException>(() => AlzReader.Extract(slip, target, Ct));+ Assert.Contains("outside the target folder", error.Message);+ Assert.False(File.Exists(Path.Combine(dir, "evil.txt")));+ Assert.Contains("password-protected", Assert.Throws<InvalidDataException>(() => AlzReader.Extract(locked, target, Ct)).Message);+ }++ [Fact]+ public async Task Egg_with_store_deflate_bzip2_lzma_and_multi_block_entries()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var text = Words(30_000);+ var part1 = Words(5_000);+ var part2 = Noise(7_000, 3);+ var egg = Path.Combine(dir, "에그.egg");+ WriteEgg(egg,+ [+ new("문서/", true),+ new("문서/stored.txt", false, new EggBlock(text, 0)),+ new("deflate.txt", false, new EggBlock(text, 1)),+ new("bzip2.txt", false, new EggBlock(text, 2, await Bzip2Async(text, dir))),+ new("lzma.txt", false, new EggBlock(text, 4, EggLzma(await RawLzmaAsync(text, endMarker: false, dir)))),+ new("두 블록.bin", false, new EggBlock(part1, 1), new EggBlock(part2, 0)),+ ]);++ var folder = (await ConvertOkAsync(egg, Extract)).Outputs.Single();++ foreach (var name in new[] { "문서/stored.txt", "deflate.txt", "bzip2.txt", "lzma.txt" })+ Assert.Equal(text, await File.ReadAllBytesAsync(Path.Combine(folder, name), Ct));+ byte[] joined = [.. part1, .. part2];+ Assert.Equal(joined, await File.ReadAllBytesAsync(Path.Combine(folder, "두 블록.bin"), Ct));+ Assert.Equal(KnownTime, File.GetLastWriteTime(Path.Combine(folder, "deflate.txt")));+ }++ [Fact]+ public async Task Solid_egg_archives_fail_with_a_clear_message()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var egg = Path.Combine(dir, "solid.egg");+ WriteEgg(egg, [new("a.txt", false, new EggBlock([1, 2, 3], 0))], solid: true);++ var job = await fx.ConvertAsync([egg], Extract);++ Assert.Equal(JobState.Failed, job.State);+ Assert.Contains("solid", job.Files[0].ErrorDetail);+ }++ [Fact]+ public async Task Lzip_files_and_tar_lz_are_unpacked()+ {+ SkipWithout7Zip();+ var dir = fx.NewFolder();+ var first = Words(40_000);+ var second = Noise(3_000, 9);+ var lz = Path.Combine(dir, "log.txt.lz");+ // Two members, as written by plzip or "cat a.lz b.lz".+ byte[] members = [.. await LzipAsync(first, dir), .. await LzipAsync(second, dir)];+ await File.WriteAllBytesAsync(lz, members, Ct);++ var folder = (await ConvertOkAsync(lz, Extract)).Outputs.Single();+ byte[] both = [.. first, .. second];+ Assert.Equal(both, await File.ReadAllBytesAsync(Path.Combine(folder, "log.txt"), Ct));++ var tree = MakeTree(dir, "tree");+ using var tar = new MemoryStream();+ await TarFile.CreateFromDirectoryAsync(tree, tar, includeBaseDirectory: false, Ct);+ var tarLz = Path.Combine(dir, "backup.tar.lz");+ await File.WriteAllBytesAsync(tarLz, await LzipAsync(tar.ToArray(), dir), Ct);++ var unpacked = (await ConvertOkAsync(tarLz, Extract)).Outputs.Single();+ Assert.Equal(Snapshot(tree), Snapshot(unpacked));+ var zip = (await ConvertOkAsync(tarLz, new Preset { TargetFormat = "zip" })).Outputs.Single();+ Assert.EndsWith("backup.zip", zip);+ }++ [Fact]+ public async Task Bzip2_decoder_reads_standard_multi_block_streams()+ {+ Assert.SkipUnless(SevenZipExe is not null, "7-Zip not found");+ var dir = fx.NewFolder();+ var data = Words(2_500_000);+ var bz2 = await Bzip2Async(data, dir);++ using var output = new MemoryStream();+ Bzip2Decoder.Decompress(new MemoryStream(bz2), output, alzFraming: false, long.MaxValue, Ct);+ Assert.Equal(data, output.ToArray());++ // A flipped bit is caught by the block checksum instead of producing wrong data.+ bz2[bz2.Length / 2] ^= 0x10;+ Assert.ThrowsAny<InvalidDataException>(() =>+ {+ Bzip2Decoder.Decompress(new MemoryStream(bz2), new MemoryStream(), alzFraming: false, long.MaxValue, Ct);+ });+ }++ // ───────── Helpers ─────────++ [Theory]+ [InlineData("../evil.txt", true)]+ [InlineData("a/../../evil.txt", true)]+ [InlineData("..\\evil.txt", true)]+ [InlineData("/etc/passwd", true)]+ [InlineData("\\abs.txt", true)]+ [InlineData("C:\\drive.txt", true)]+ [InlineData("a/b/c.txt", false)]+ [InlineData("한글/파일..txt", false)]+ public void Unsafe_entry_paths_are_recognised(string path, bool unsafePath) =>+ Assert.Equal(unsafePath, ArchiveSafety.IsUnsafePath(path));++ [Fact]+ public void Entry_names_are_made_valid_windows_names_inside_the_root()+ {+ var root = fx.NewFolder();+ Assert.Equal(Path.Combine(root, "폴더", "파일.txt"), ArchiveSafety.ResolveEntryPath(root, @"폴더\파일.txt", "x.alz"));+ Assert.Equal(Path.Combine(root, "a_b", "_CON.txt"), ArchiveSafety.ResolveEntryPath(root, "a|b/CON.txt", "x.alz"));+ Assert.Equal(Path.Combine(root, "file.txt_stream"), ArchiveSafety.ResolveEntryPath(root, "file.txt:stream", "x.alz")); // no NTFS streams+ Assert.Equal(Path.Combine(root, "dir", "file_"), ArchiveSafety.ResolveEntryPath(root, "./dir//file?", "x.alz"));+ }++ [Fact]+ public void Listing_parser_reads_7zip_technical_output()+ {+ const string output = """+ 7-Zip 26.03 (x64)++ Listing archive: x.tar++ --+ Path = x.tar+ Type = tar++ ----------+ Path = dir\file.txt+ Folder = -+ Size = 7+ Mode = -rw-r--r--+ Symbolic Link =+ Hard Link =++ Path = dir\link+ Folder = -+ Size = 27+ Mode = lrw-r--r--+ Symbolic Link = ../../x+ Hard Link =++ Path = dir+ Folder = ++ Size = 0+ Encrypted = +++ """;+ var entries = SevenZip.ParseListing(output);+ Assert.Equal(["dir\\file.txt", "dir\\link", "dir"], entries.Select(e => e.Path));+ Assert.False(entries[0].IsSymbolicLink);+ Assert.True(entries[1].IsSymbolicLink);+ Assert.True(entries[2].IsFolder);+ Assert.True(entries[2].IsEncrypted);+ Assert.Equal(7, entries[0].Size);+ }++ [Fact]+ public void Clashing_names_in_one_archive_are_numbered()+ {+ var items = ArchiveConverter.UniqueEntries([@"C:\a\x.txt", @"C:\b\X.txt", @"C:\c\x.txt", @"C:\d\y"]);+ Assert.Equal(["x.txt", "X (2).txt", "x (3).txt", "y"], items.Select(i => i.EntryName));+ }++ [Theory]+ [InlineData(0x14, 1u << 20)]+ [InlineData(0xD3, (1u << 19) - 6 * (1u << 15))] // 2^19 minus 6/16+ [InlineData(0x0C, 4096u)]+ public void Lzip_dictionary_sizes(int coded, uint expected) =>+ Assert.Equal(expected, LzipReader.DictionarySize(coded));++ private static byte[] ReadAll(ZipArchiveEntry entry)+ {+ using var stream = entry.Open();+ using var ms = new MemoryStream();+ stream.CopyTo(ms);+ return ms.ToArray();+ }+}diff --git a/tests/Filee.Engines.Tests/EngineFixture.cs b/tests/Filee.Engines.Tests/EngineFixture.csindex 9d1242f3..466ea298 100644--- a/tests/Filee.Engines.Tests/EngineFixture.cs+++ b/tests/Filee.Engines.Tests/EngineFixture.cs@@ -66,7 +66,8 @@ public sealed class EngineFixture : IDisposablepublic async Task<ConversionJob> ConvertAsync(IReadOnlyList<string> sources, Preset preset){- await using var queue = new JobQueue(Catalog, EngineRegistry.FindPdfMerger(Converters));+ await using var queue = new JobQueue(Catalog, EngineRegistry.FindPdfMerger(Converters),+ combiner: EngineRegistry.FindFileCombiner(Converters));var job = new ConversionJob(sources, preset, preset.Name);await queue.RunAsync(job);return job;