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
Retry LibreOffice with a repacked ZIP when it can't load an Office file
KnifeLemon4706ad76d28a
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 3ff7b465..efb5862c 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -784,6 +784,9 @@ bundled with the installer), never a 7-Zip installed on the PC. It runs as a sepfails when two conversions share a profile).- HWP/HWPX import comes from the H2Orestart extension, which is written in Java; Filee points LibreOffice at thedownloaded JRE (`-env:UNO_JAVA_JFW_JREHOME`).+- When LibreOffice can't load an Office Open XML or OpenDocument file ("source file could not be loaded"), Filee+ converts once more from a copy in the job folder with the same parts in a plainly written ZIP (`PackageRepacker`):+ LibreOffice 26.2 refuses some valid containers, e.g. uncompressed entries with data descriptors (Tencent Docs, #141).- It is the only reader of rarer formats, converted to PDF and to the editable formats of their kind: DOT, Works /WPS Writer, WordPerfect, Lotus Word Pro, AbiWord, Apple Pages, StarWriter, ClarisWorks / AppleWorks (`.cwk`),MacWrite (`.mcw`), T602 (`.602`) and Pocket Word (`.psw`) (→ DOCX, ODT, FODT, OTT, DOC, RTF, TXT, HTML); WPSdiff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 7d82f4b0..6601f925 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -31,7 +31,10 @@ public static class EngineRegistry/// AppSettings.EnginePriority: built-in engines first, the optional downloads last. Software installed on the/// system (Microsoft Office, a system-wide LibreOffice) is never used./// </summary>- /// <param name="loggers">The app's log; FFmpeg writes which hardware encoders work and when one failed.</param>+ /// <param name="loggers">+ /// The app's log; FFmpeg writes which hardware encoders work and when one failed, LibreOffice when a file needed+ /// its container repacked.+ /// </param>public static IReadOnlyList<IConverter> CreateAll(EngineEnvironment env, ILoggerFactory? loggers = null) =>[new MagickImageConverter(),@@ -60,7 +63,7 @@ public static class EngineRegistrynew PandocConverter(),new GhostscriptConverter(),new CalibreConverter(),- new LibreOfficeConverter(env),+ new LibreOfficeConverter(env, loggers?.CreateLogger<LibreOfficeConverter>()),];/// <summary>Finds the PDF merger among the converters.</summary>diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.csindex 5c036f0e..ae85f781 100644--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs@@ -14,10 +14,14 @@// * The first conversion with a new profile takes 2-3× longer (LibreOffice builds its caches), so WarmUpAsync// converts a tiny file once per worker profile in the background. --terminate_after_init alone doesn't help.// * soffice reports no progress: ProgressEstimate keeps the progress ring moving while it runs.+// * Its ZIP reader refuses some containers other readers open (Tencent Docs exports, issue #141), saying only "source+// file could not be loaded": an Office Open XML / OpenDocument file is tried once more as a repacked copy.using Filee.Core.Conversion;using Filee.Core.Formats;using Filee.Engines.Infrastructure;+using Microsoft.Extensions.Logging;+using Microsoft.Extensions.Logging.Abstractions;using PdfSharp.Pdf;using PdfSharp.Pdf.IO;@@ -60,6 +64,7 @@ public sealed class LibreOfficeConverter : IConverterprivate static readonly string[] DrawOnlyFor = ["svg", "pdf"];private readonly EngineEnvironment _env;+ private readonly ILogger _logger;// A worker profile must never be used by two soffice processes at once: conversions and the warm-up take a// profile number from _freeProfiles (guarded by itself) after _capacity lets them in.@@ -68,9 +73,11 @@ public sealed class LibreOfficeConverter : IConverterprivate string? _soffice;private bool _hasHwpFilter;- public LibreOfficeConverter(EngineEnvironment env)+ /// <param name="logger">The app's log; notes when a file only loaded after its container was repacked.</param>+ public LibreOfficeConverter(EngineEnvironment env, ILogger? logger = null){_env = env;+ _logger = logger ?? NullLogger.Instance;Locate();Edges = BuildEdges(_hasHwpFilter, EngineEnvironment.LibreOfficeForSlides, EngineEnvironment.LibreOfficeForHwp,EngineEnvironment.LibreOfficeForDocuments, EngineEnvironment.LibreOfficeForSheets);@@ -100,15 +107,17 @@ public sealed class LibreOfficeConverter : IConvertervar slot = await TakeProfileAsync(cancellationToken);try{- var outDir = Path.Combine(step.WorkDirectory, "lo-" + Guid.NewGuid().ToString("N")[..8]);- Directory.CreateDirectory(outDir);-progress?.Report(0.1);var input = step.From == "pdf" && step.To == "svg" ? FirstPage(step) : step.InputPath;- ProcessResult result;- using (ProgressEstimate.Start(progress, TypicalDuration))- result = await RunAsync(soffice, slot, FilterFor(step.From, step.To, step.Preset.Document.PdfA, FormatRegistry.ExtensionOf(step.InputPath)), outDir, input, cancellationToken);- var produced = Directory.EnumerateFiles(outDir).FirstOrDefault(f => new FileInfo(f).Length > 0);+ var filter = FilterFor(step.From, step.To, step.Preset.Document.PdfA, FormatRegistry.ExtensionOf(step.InputPath));+ var (produced, result) = await ConvertOnceAsync(soffice, slot, filter, step.WorkDirectory, input, progress, cancellationToken);+ if (produced is null && Repack(step.InputPath, step.WorkDirectory) is { } repacked)+ {+ _logger.LogInformation("{File}: LibreOffice could not load it, trying again with the ZIP container repacked", step.InputPath);+ (produced, _) = await ConvertOnceAsync(soffice, slot, filter, step.WorkDirectory, repacked, progress, cancellationToken);+ _logger.LogInformation("{File}: the repacked copy {Result}", step.InputPath, produced is null ? "failed too" : "converted");+ }+ // The first attempt's error, which is about the user's own file.if (produced is null)throw new InvalidOperationException($"LibreOffice produced no output (exit {result.ExitCode}). {result.StandardError.Trim()}");@@ -126,6 +135,41 @@ public sealed class LibreOfficeConverter : IConverter}}+ /// <summary>Runs LibreOffice into a fresh folder; returns the file it wrote (null if none) and how it ended.</summary>+ private async Task<(string? Produced, ProcessResult Result)> ConvertOnceAsync(string soffice, int slot, string filter, string workDirectory,+ string input, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var outDir = Path.Combine(workDirectory, "lo-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(outDir);+ ProcessResult result;+ using (ProgressEstimate.Start(progress, TypicalDuration))+ result = await RunAsync(soffice, slot, filter, outDir, input, cancellationToken);+ return (Directory.EnumerateFiles(outDir).FirstOrDefault(f => new FileInfo(f).Length > 0), result);+ }++ /// <summary>+ /// A copy of an Office Open XML or OpenDocument file with its ZIP container rewritten by <see cref="PackageRepacker"/>,+ /// under the same file name (LibreOffice also goes by the name). Null for other files and unreadable containers.+ /// </summary>+ private string? Repack(string input, string workDirectory)+ {+ if (!PackageRepacker.IsPackage(input))+ return null;+ try+ {+ var folder = Path.Combine(workDirectory, "lo-repack-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ var copy = Path.Combine(folder, Path.GetFileName(input));+ PackageRepacker.Repack(input, copy);+ return copy;+ }+ catch (Exception e) when (e is InvalidDataException or IOException or UnauthorizedAccessException)+ {+ _logger.LogInformation("{File}: could not repack the ZIP container: {Message}", input, e.Message);+ return null;+ }+ }+/// <summary>/// The first page of the preset's page range as a PDF of its own: Draw's SVG export writes every page of a PDF on/// top of each other, so it gets one page (like the other drawings, whose SVG holds the first page).diff --git a/src/Filee.Engines/Office/PackageRepacker.cs b/src/Filee.Engines/Office/PackageRepacker.csnew file mode 100644index 00000000..6179f14d--- /dev/null+++ b/src/Filee.Engines/Office/PackageRepacker.cs@@ -0,0 +1,60 @@+// Rewrites the ZIP container of an Office Open XML or OpenDocument file with plain structure, for LibreOffice.+// LibreOffice's package reader (26.2) refuses archives that other readers open, such as Tencent Docs exports (issue+// #141): it fails on entries stored uncompressed with a data descriptor, bytes between entries and a name that appears+// twice, saying only "source file could not be loaded". The parts are fine, so a copy with the same parts written by+// System.IO.Compression loads.++using System.IO.Compression;++namespace Filee.Engines.Office;++/// <summary>Copies an Office Open XML or OpenDocument package into a new, plainly structured ZIP.</summary>+internal static class PackageRepacker+{+ private const string ContentTypes = "[Content_Types].xml";+ private const string Mimetype = "mimetype";++ /// <summary>The file is a ZIP that holds <c>[Content_Types].xml</c> (Office Open XML) or <c>mimetype</c> (OpenDocument).</summary>+ public static bool IsPackage(string path)+ {+ try+ {+ using var zip = ZipFile.OpenRead(path);+ return zip.GetEntry(ContentTypes) is not null || zip.GetEntry(Mimetype) is not null;+ }+ catch (InvalidDataException) { return false; }+ catch (IOException) { return false; }+ catch (UnauthorizedAccessException) { return false; }+ }++ /// <summary>+ /// Writes every part of <paramref name="input"/> to <paramref name="output"/> with the same name and content:+ /// <c>[Content_Types].xml</c> first, an OpenDocument <c>mimetype</c> first and uncompressed (its signature),+ /// everything else deflated, without directory entries, data descriptors or extra fields. A name that appears+ /// twice keeps its first part.+ /// </summary>+ public static void Repack(string input, string output)+ {+ using var source = ZipFile.OpenRead(input);+ var parts = source.Entries.Where(e => !e.FullName.EndsWith('/') && !e.FullName.EndsWith('\\'))+ .OrderBy(e => e.FullName is ContentTypes or Mimetype ? 0 : 1)+ .ToList();++ // A seekable stream: the sizes go into the local headers instead of data descriptors.+ using var file = File.Create(output);+ using var zip = new ZipArchive(file, ZipArchiveMode.Create);+ var written = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ foreach (var part in parts)+ {+ if (!written.Add(part.FullName))+ continue;+ var level = part.FullName == Mimetype ? CompressionLevel.NoCompression : CompressionLevel.Optimal;+ var copy = zip.CreateEntry(part.FullName, level);+ if (part.LastWriteTime.Year is >= 1980 and <= 2107)+ copy.LastWriteTime = part.LastWriteTime;+ using var from = part.Open();+ using var to = copy.Open();+ from.CopyTo(to);+ }+ }+}diff --git a/tests/Filee.Engines.Tests/PackageRepackerTests.cs b/tests/Filee.Engines.Tests/PackageRepackerTests.csnew file mode 100644index 00000000..9e540515--- /dev/null+++ b/tests/Filee.Engines.Tests/PackageRepackerTests.cs@@ -0,0 +1,216 @@+// Issue #141: LibreOffice refuses some ZIP containers that other readers open (Tencent Docs exports), saying only+// "source file could not be loaded". It gets a second try with the same parts repacked by PackageRepacker; the+// built-in readers take such files as they are.++using System.IO.Compression;+using System.Security.Cryptography;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Hwp.Hwpx;+using Filee.Engines.Hwp.Hwpx.Docx;+using Filee.Engines.Hwp.Hwpx.Pptx;+using Filee.Engines.Office;+using Filee.Engines.Office.Sheets;+using static Filee.Engines.Tests.QuirkyZip.Quirks;++namespace Filee.Engines.Tests;++public class PackageRepackerTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ /// <summary>Every quirk at once, the parts in reverse order ([Content_Types].xml last).</summary>+ private const QuirkyZip.Quirks Everything = DirectoryEntries | DataDescriptors | Stored | Gaps | DuplicateName | Reversed;++ private string Docx(string folder, string text, string name = "report.docx")+ {+ var docx = new DocxBuilder();+ var picture = docx.Image(Png());+ docx.Paragraph(DocxBuilder.P(DocxBuilder.R(text))).Paragraph(DocxBuilder.P(DocxBuilder.InlinePicture(picture, 914400, 914400)));+ return docx.Save(Path.Combine(folder, name));+ }++ private static byte[] Png()+ {+ using var image = new ImageMagick.MagickImage(ImageMagick.MagickColors.Teal, 16, 16);+ return image.ToByteArray(ImageMagick.MagickFormat.Png);+ }++ private static string Odt(string path, string text)+ {+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);+ void Write(string name, string content, CompressionLevel level = CompressionLevel.Optimal)+ {+ using var stream = zip.CreateEntry(name, level).Open();+ stream.Write(Encoding.UTF8.GetBytes(content));+ }+ Write("mimetype", "application/vnd.oasis.opendocument.text", CompressionLevel.NoCompression);+ Write("META-INF/manifest.xml",+ "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">" ++ "<manifest:file-entry manifest:full-path=\"/\" manifest:version=\"1.2\" manifest:media-type=\"application/vnd.oasis.opendocument.text\"/>" ++ "<manifest:file-entry manifest:full-path=\"content.xml\" manifest:media-type=\"text/xml\"/></manifest:manifest>");+ Write("content.xml",+ "<office:document-content xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" office:version=\"1.2\">" ++ $"<office:body><office:text><text:p>{text}</text:p></office:text></office:body></office:document-content>");+ return path;+ }++ private static string Text(HDocument document) =>+ string.Concat(DocxAssert.Paragraphs(document.Sections.SelectMany(s => s.Blocks)).Select(DocxAssert.TextOf));++ [Fact]+ public void Repacking_keeps_every_part_in_a_plain_container()+ {+ var folder = fx.NewFolder();+ var plain = Docx(folder, "Tencent office");+ var quirky = QuirkyZip.Rewrite(plain, Path.Combine(folder, "quirky.docx"), Everything);+ var before = SHA256.HashData(File.ReadAllBytes(quirky));++ var repacked = Path.Combine(fx.NewFolder(), "quirky.docx");+ PackageRepacker.Repack(quirky, repacked);++ // The same parts with the same content (the second copy of a name dropped)...+ var expected = QuirkyZip.Parts(plain).ToDictionary(p => p.Name, p => p.Data);+ var parts = QuirkyZip.Parts(repacked);+ Assert.Equal(expected.Keys.Order(), parts.Select(p => p.Name).Order());+ Assert.All(parts, p => Assert.Equal(expected[p.Name], p.Data));+ // ... in a plain container: [Content_Types].xml first, no folders, deflated, sizes in the local headers, no+ // data descriptors, extra fields or gaps.+ var entries = QuirkyZip.LocalEntries(repacked);+ Assert.Equal("[Content_Types].xml", entries[0].Name);+ Assert.Equal(parts.Count, entries.Count);+ Assert.All(entries, e =>+ {+ Assert.False(e.Name.EndsWith('/'), e.Name);+ Assert.Equal(0, e.Flags & 0x0008);+ Assert.Equal(8, e.Method);+ Assert.Equal(0, e.ExtraLength);+ Assert.NotEqual(0u, e.Crc);+ });+ // The user's file is untouched.+ Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(quirky)));+ }++ [Fact]+ public void An_opendocument_file_gets_its_mimetype_first_and_uncompressed()+ {+ var folder = fx.NewFolder();+ var quirky = QuirkyZip.Rewrite(Odt(Path.Combine(folder, "plain.odt"), "Hello"), Path.Combine(folder, "letter.odt"), DataDescriptors | Reversed);+ Assert.NotEqual("mimetype", QuirkyZip.Parts(quirky)[0].Name);++ var repacked = Path.Combine(fx.NewFolder(), "letter.odt");+ PackageRepacker.Repack(quirky, repacked);++ var mimetype = QuirkyZip.LocalEntries(repacked)[0];+ Assert.Equal("mimetype", mimetype.Name);+ Assert.Equal(0, mimetype.Method);+ Assert.Equal(0, mimetype.ExtraLength);+ Assert.Equal("application/vnd.oasis.opendocument.text"u8.ToArray(), QuirkyZip.Parts(repacked)[0].Data);+ }++ [Fact]+ public void Only_office_packages_are_repacked()+ {+ var folder = fx.NewFolder();+ Assert.True(PackageRepacker.IsPackage(Docx(folder, "x")));+ Assert.True(PackageRepacker.IsPackage(Odt(Path.Combine(folder, "a.odt"), "x")));++ var zip = Path.Combine(folder, "notes.zip");+ using (var archive = ZipFile.Open(zip, ZipArchiveMode.Create))+ archive.CreateEntry("notes.txt");+ Assert.False(PackageRepacker.IsPackage(zip));+ var text = Path.Combine(folder, "fake.docx");+ File.WriteAllText(text, "not a zip");+ Assert.False(PackageRepacker.IsPackage(text));+ }++ [Fact]+ public void Built_in_readers_take_quirky_containers()+ {+ // DOCX / XLSX / PPTX / ODS → PDF, HWPX, CSV ... read the parts through System.IO.Compression, which goes by the+ // central directory: folders, data descriptors and gaps don't matter.+ const QuirkyZip.Quirks quirks = DirectoryEntries | DataDescriptors | Stored | Gaps | Reversed;+ var folder = fx.NewFolder();++ var docx = QuirkyZip.Rewrite(Docx(folder, "Hello Tencent"), Path.Combine(folder, "quirky.docx"), quirks);+ Assert.Contains("Hello Tencent", Text(DocxReader.Read(docx, Path.Combine(folder, "docx-media"))));+ var dotx = Path.Combine(folder, "quirky.dotx");+ OoxmlConverter.Rewrite(docx, dotx, "dotx");+ Assert.Contains("Hello Tencent", Text(DocxReader.Read(dotx, Path.Combine(folder, "dotx-media"))));++ var xlsx = new XlsxBuilder();+ xlsx.Sheet("Data", XlsxBuilder.Row(1, xlsx.Text("A1", "Tencent cell"), XlsxBuilder.Number("B1", 42)));+ var quirkyXlsx = QuirkyZip.Rewrite(xlsx.Save(Path.Combine(folder, "plain.xlsx")), Path.Combine(folder, "quirky.xlsx"), quirks);+ Assert.Equal("Tencent cell", XlsxReader.Read(quirkyXlsx).Sheets[0].Get(0, 0)?.Text);++ var pptx = new PptxBuilder();+ pptx.Slide(pptx.Title("Tencent slide"));+ var quirkyPptx = QuirkyZip.Rewrite(pptx.Save(Path.Combine(folder, "plain.pptx")), Path.Combine(folder, "quirky.pptx"), quirks);+ Assert.Contains("Tencent slide", Text(PptxReader.Read(quirkyPptx, Path.Combine(folder, "pptx-media"))));++ var book = new Workbook();+ book.Sheets.Add(new Worksheet("Data"));+ book.Sheets[0].Set(0, 0, new SheetCell("Tencent ods", CellStyle.Default));+ OdsWriter.Write(book, Path.Combine(folder, "plain.ods"));+ var ods = QuirkyZip.Rewrite(Path.Combine(folder, "plain.ods"), Path.Combine(folder, "quirky.ods"), quirks);+ Assert.Equal("Tencent ods", OdsReader.Read(ods).Sheets[0].Get(0, 0)?.Text);+ }++ [Theory]+ [InlineData(DirectoryEntries | DataDescriptors)]+ [InlineData(Stored | DataDescriptors)]+ [InlineData(Gaps)]+ [InlineData(DuplicateName)]+ public async Task LibreOffice_converts_a_container_it_refuses_from_a_repacked_copy(QuirkyZip.Quirks quirks)+ {+ // LibreOffice 26.2 fails to load each of these ("source file could not be loaded"), the repacked copy converts.+ var libreOffice = fx.Converters.Single(c => c.Id == "libreoffice");+ Assert.SkipUnless(fx.Catalog.StatusOf(libreOffice).IsAvailable, "LibreOffice not installed");+ var folder = fx.NewFolder();+ var docx = QuirkyZip.Rewrite(Docx(folder, "Hello Tencent", "plain.docx"), Path.Combine(folder, "腾讯文档.docx"), quirks);+ var before = SHA256.HashData(File.ReadAllBytes(docx));++ var (odt, repacked) = await ConvertAsync(libreOffice, docx, "docx", "odt");++ Assert.True(repacked, "LibreOffice loaded the file the first time");+ using (var zip = ZipFile.OpenRead(odt))+ Assert.Contains("Hello Tencent", new StreamReader(zip.GetEntry("content.xml")!.Open()).ReadToEnd());+ Assert.Equal(before, SHA256.HashData(File.ReadAllBytes(docx)));+ }++ [Fact]+ public async Task LibreOffice_converts_a_refused_opendocument_file_from_a_repacked_copy()+ {+ var libreOffice = fx.Converters.Single(c => c.Id == "libreoffice");+ Assert.SkipUnless(fx.Catalog.StatusOf(libreOffice).IsAvailable, "LibreOffice not installed");+ var folder = fx.NewFolder();+ var plain = Odt(Path.Combine(folder, "plain.odt"), "Hello OpenDocument");+ var odt = QuirkyZip.Rewrite(plain, Path.Combine(folder, "letter.odt"), Stored | DataDescriptors);++ var (docx, repacked) = await ConvertAsync(libreOffice, odt, "odt", "docx");++ Assert.True(repacked, "LibreOffice loaded the file the first time");+ Assert.Contains("Hello OpenDocument", Text(DocxAssert.ReadBack(docx)));+ // A file LibreOffice loads is converted as it is.+ Assert.False((await ConvertAsync(libreOffice, plain, "odt", "docx")).Repacked);+ }++ /// <returns>The output, and whether a repacked copy was needed (the work folder holds one).</returns>+ private static async Task<(string Output, bool Repacked)> ConvertAsync(IConverter libreOffice, string input, string from, string to)+ {+ var output = Path.Combine(Path.GetDirectoryName(input)!, "out", Path.GetFileNameWithoutExtension(input) + "." + to);+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);+ var work = Path.Combine(Path.GetDirectoryName(input)!, "work-" + Guid.NewGuid().ToString("N")[..6]);+ Directory.CreateDirectory(work);+ await HwpxAssert.LibreOfficeGate.WaitAsync(TestContext.Current.CancellationToken);+ try+ {+ var written = await libreOffice.ConvertAsync(new ConversionStep(input, from, to, new Preset(), new HwpxAssert.FixedPath(output), work),+ null, TestContext.Current.CancellationToken);+ return (written.Single(), Directory.EnumerateDirectories(work, "lo-repack-*").Any());+ }+ finally+ {+ HwpxAssert.LibreOfficeGate.Release();+ }+ }+}diff --git a/tests/Filee.Engines.Tests/QuirkyZip.cs b/tests/Filee.Engines.Tests/QuirkyZip.csnew file mode 100644index 00000000..165abd27--- /dev/null+++ b/tests/Filee.Engines.Tests/QuirkyZip.cs@@ -0,0 +1,184 @@+// Rewrites a ZIP written by System.IO.Compression the way other writers lay out Office files (issue #141): directory+// entries, data descriptors, uncompressed parts, bytes between entries, a name stored twice. System.IO.Compression+// reads them all; LibreOffice 26.2 refuses data descriptors after uncompressed entries (folders included), gaps and+// duplicate names. Also reads back the raw layout of a ZIP.++using System.Buffers.Binary;+using System.IO.Compression;+using System.Text;+using Filee.Engines.Archives;++namespace Filee.Engines.Tests;++public static class QuirkyZip+{+ [Flags]+ public enum Quirks+ {+ None = 0,++ /// <summary>A "folder/" entry for every folder, before the parts.</summary>+ DirectoryEntries = 1,++ /// <summary>Every entry flagged with bit 3: zero CRC and sizes in the local header, a data descriptor after the data.</summary>+ DataDescriptors = 2,++ /// <summary>Parts stored uncompressed instead of deflated.</summary>+ Stored = 4,++ /// <summary>16 zero bytes after every entry.</summary>+ Gaps = 8,++ /// <summary>The last part a second time under the same name.</summary>+ DuplicateName = 16,++ /// <summary>The parts in reverse order: [Content_Types].xml or mimetype last.</summary>+ Reversed = 32,+ }++ /// <summary>One local file header as written in the file.</summary>+ public readonly record struct LocalEntry(string Name, ushort Flags, ushort Method, uint Crc, uint CompressedSize, uint Size, int ExtraLength);++ /// <summary>The parts of a ZIP (directories left out), in order: name → content.</summary>+ public static List<(string Name, byte[] Data)> Parts(string path)+ {+ using var zip = ZipFile.OpenRead(path);+ return [.. zip.Entries.Where(e => !e.FullName.EndsWith('/')).Select(e => (e.FullName, Read(e)))];+ }++ /// <summary>Writes the parts of <paramref name="source"/> to <paramref name="target"/> with <paramref name="quirks"/>.</summary>+ public static string Rewrite(string source, string target, Quirks quirks)+ {+ var parts = Parts(source).Select(p => (p.Name, (byte[]?)p.Data)).ToList();+ if (quirks.HasFlag(Quirks.Reversed))+ parts.Reverse();+ if (quirks.HasFlag(Quirks.DirectoryEntries))+ {+ var folders = parts.SelectMany(p => Folders(p.Name)).Distinct().Order(StringComparer.Ordinal).ToList();+ parts.InsertRange(0, folders.Select(f => (f, (byte[]?)null)));+ }+ if (quirks.HasFlag(Quirks.DuplicateName))+ parts.Add(parts[^1]);++ using var output = new MemoryStream();+ using var central = new MemoryStream();+ var writer = new BinaryWriter(output);+ var directory = new BinaryWriter(central);+ foreach (var (name, data) in parts)+ {+ var content = data ?? [];+ var stored = data is null || quirks.HasFlag(Quirks.Stored);+ var packed = stored ? content : Deflate(content);+ var crc = Crc32.Compute(content);+ var descriptor = quirks.HasFlag(Quirks.DataDescriptors);+ var flags = (ushort)((descriptor ? 0x0008 : 0) | 0x0800);+ var method = (ushort)(stored ? 0 : 8);+ var nameBytes = Encoding.UTF8.GetBytes(name);+ var offset = (uint)output.Position;++ writer.Write(0x04034b50u);+ writer.Write((ushort)20);+ writer.Write(flags);+ writer.Write(method);+ writer.Write(0u); // DOS time and date+ writer.Write(descriptor ? 0u : crc);+ writer.Write(descriptor ? 0u : (uint)packed.Length);+ writer.Write(descriptor ? 0u : (uint)content.Length);+ writer.Write((ushort)nameBytes.Length);+ writer.Write((ushort)0);+ writer.Write(nameBytes);+ writer.Write(packed);+ if (descriptor)+ {+ writer.Write(0x08074b50u);+ writer.Write(crc);+ writer.Write((uint)packed.Length);+ writer.Write((uint)content.Length);+ }+ if (quirks.HasFlag(Quirks.Gaps))+ writer.Write(new byte[16]);++ directory.Write(0x02014b50u);+ directory.Write((ushort)0x031E);+ directory.Write((ushort)20);+ directory.Write(flags);+ directory.Write(method);+ directory.Write(0u);+ directory.Write(crc);+ directory.Write((uint)packed.Length);+ directory.Write((uint)content.Length);+ directory.Write((ushort)nameBytes.Length);+ directory.Write((ushort)0); // extra+ directory.Write((ushort)0); // comment+ directory.Write((ushort)0); // disk+ directory.Write((ushort)0); // internal attributes+ directory.Write(data is null ? 0x10u : 0u);+ directory.Write(offset);+ directory.Write(nameBytes);+ }+ var centralOffset = (uint)output.Position;+ writer.Write(central.ToArray());+ writer.Write(0x06054b50u);+ writer.Write((ushort)0);+ writer.Write((ushort)0);+ writer.Write((ushort)parts.Count);+ writer.Write((ushort)parts.Count);+ writer.Write((uint)central.Length);+ writer.Write(centralOffset);+ writer.Write((ushort)0);+ writer.Flush();+ File.WriteAllBytes(target, output.ToArray());+ return target;+ }++ /// <summary>+ /// The local headers from the start of the file, each followed directly by its data (no data descriptors, no+ /// gaps), up to the central directory; fails when the layout is anything else.+ /// </summary>+ public static List<LocalEntry> LocalEntries(string path)+ {+ var bytes = File.ReadAllBytes(path).AsSpan();+ var entries = new List<LocalEntry>();+ var position = 0;+ while (BinaryPrimitives.ReadUInt32LittleEndian(bytes[position..]) == 0x04034b50)+ {+ var header = bytes[position..];+ var nameLength = BinaryPrimitives.ReadUInt16LittleEndian(header[26..]);+ var extraLength = BinaryPrimitives.ReadUInt16LittleEndian(header[28..]);+ var entry = new LocalEntry(+ Encoding.UTF8.GetString(header.Slice(30, nameLength)),+ BinaryPrimitives.ReadUInt16LittleEndian(header[6..]),+ BinaryPrimitives.ReadUInt16LittleEndian(header[8..]),+ BinaryPrimitives.ReadUInt32LittleEndian(header[14..]),+ BinaryPrimitives.ReadUInt32LittleEndian(header[18..]),+ BinaryPrimitives.ReadUInt32LittleEndian(header[22..]),+ extraLength);+ entries.Add(entry);+ position += 30 + nameLength + extraLength + (int)entry.CompressedSize;+ }+ Assert.Equal(0x02014b50u, BinaryPrimitives.ReadUInt32LittleEndian(bytes[position..]));+ return entries;+ }++ private static IEnumerable<string> Folders(string name)+ {+ for (var slash = name.IndexOf('/'); slash >= 0; slash = name.IndexOf('/', slash + 1))+ yield return name[..(slash + 1)];+ }++ private static byte[] Read(ZipArchiveEntry entry)+ {+ using var stream = entry.Open();+ using var buffer = new MemoryStream();+ stream.CopyTo(buffer);+ return buffer.ToArray();+ }++ private static byte[] Deflate(byte[] data)+ {+ using var buffer = new MemoryStream();+ using (var deflate = new DeflateStream(buffer, CompressionLevel.Optimal, leaveOpen: true))+ deflate.Write(data);+ return buffer.ToArray();+ }+}