Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

Give msiexec real paths, without user junctions (#527)

cre8ive-marketingdf3b306776fa
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 42fdc3a0..5e7f8791 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -96,7 +96,8 @@ they can be installed or removed later in Settings → *Engines*. A conversion t
install root, so uninstalling removes them.
- LibreOffice and calibre come as MSIs and are unpacked with an administrative install (`msiexec /a`): files only,
no registry entries, no admin rights. LibreOffice's help, gallery and most dictionaries are removed afterwards
- (~500 MB).
+ (~500 MB). msiexec gets the real paths of the package, the target and its log: the Windows Installer service won't
+ follow a junction a user made (error 1620 or 1622, #527), as when `AppData\Local` was moved to another drive.
- Ghostscript comes from conda-forge (Artifex publishes only an NSIS installer): a `.conda` package is a zip with a
zstd tarball, of which only `Library/bin` is unpacked (SharpCompress; `fetch-engines.ps1` uses Windows' `tar.exe`).
Its fonts and resources are compiled into `gsdll64.dll`. The Microsoft C++ runtime it was built against
diff --git a/src/Filee.Engines/Infrastructure/EngineInstaller.cs b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
index 7b7b50f2..f2abe87d 100644
--- a/src/Filee.Engines/Infrastructure/EngineInstaller.cs
+++ b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
@@ -338,11 +338,17 @@ public sealed class EngineInstaller
return libreOffice;
}
- private static async Task UnpackMsiAsync(string id, string msi, string target, string log, CancellationToken cancellationToken)
+ private async Task UnpackMsiAsync(string id, string msi, string target, string log, CancellationToken cancellationToken)
{
if (!OperatingSystem.IsWindows())
throw new PlatformNotSupportedException($"The {id} package is a Windows installer.");
Directory.CreateDirectory(target);
+ // The Installer service won't follow a junction a user made (#527); Filee keeps using its own paths.
+ // The log too: through a link it can't be written (1622), as when %TEMP% has moved with AppData\Local.
+ msi = RealPath.Of(msi);
+ target = RealPath.Of(target);
+ log = Path.Combine(RealPath.Of(Path.GetDirectoryName(log)!), Path.GetFileName(log));
+ _logger.LogInformation("Unpacking {Component} with msiexec: {Msi} to {Target}, log {Log}", id, msi, target, log);
// msiexec parses its own command line: the property value must be quoted as TARGETDIR="...", so the
// argument list escaping of ProcessRunner cannot be used here.
using var process = Process.Start(new ProcessStartInfo("msiexec.exe", $"/a \"{msi}\" /qn /l*v \"{log}\" TARGETDIR=\"{target}\"")
@@ -362,15 +368,16 @@ public sealed class EngineInstaller
throw;
}
if (process.ExitCode != 0)
- {
- throw new InvalidOperationException(process.ExitCode switch
- {
- 1618 => "Another installation is running. Try again when it has finished.",
- _ => $"Unpacking {id} failed (msiexec exit code {process.ExitCode}, log: {log}).",
- });
- }
+ throw new InvalidOperationException(MsiFailure(id, process.ExitCode, log));
}
+ internal static string MsiFailure(string id, int exitCode, string log) => exitCode switch
+ {
+ 1618 => "Another installation is running. Try again when it has finished.",
+ 1620 => $"Windows Installer couldn't open the {id} package (error 1620): a folder on its way may be a link to another drive (log: {log}).",
+ _ => $"Unpacking {id} failed (msiexec exit code {exitCode}, log: {log}).",
+ };
+
/// <summary>
/// Removes what headless conversion never uses (~500 MB): help, readmes, the MSI copy, the gallery and spelling
/// dictionaries except English and Korean (their hyphenation patterns affect page layout in PDF export).
diff --git a/src/Filee.Engines/Infrastructure/RealPath.cs b/src/Filee.Engines/Infrastructure/RealPath.cs
new file mode 100644
index 00000000..2abb8750
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/RealPath.cs
@@ -0,0 +1,54 @@
+// The path a file or folder really has on Windows, with every junction, symbolic link and mount point on the way
+// followed (#527). The Windows Installer service runs as SYSTEM and refuses a path through a link a normal user
+// made ("untrusted mount point", error 448), so msiexec gets the real path instead.
+
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using Microsoft.Win32.SafeHandles;
+
+namespace Filee.Engines.Infrastructure;
+
+internal static class RealPath
+{
+ private const uint FileShareAll = 0x1 | 0x2 | 0x4; // read, write, delete
+ private const uint OpenExisting = 3;
+ private const uint BackupSemantics = 0x02000000; // also opens folders
+
+ /// <summary>
+ /// The final path of an existing file or folder (<c>GetFinalPathNameByHandle</c>), as a plain drive or UNC
+ /// path; <paramref name="path"/> itself when it can't be resolved.
+ /// </summary>
+ [SupportedOSPlatform("windows")]
+ public static string Of(string path)
+ {
+ using var handle = CreateFileW(path, 0, FileShareAll, 0, OpenExisting, BackupSemantics, 0);
+ if (handle.IsInvalid)
+ return path;
+ var buffer = new char[1024];
+ while (true)
+ {
+ var length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0);
+ if (length == 0)
+ return path;
+ if (length < buffer.Length)
+ return WithoutPrefix(new string(buffer, 0, (int)length));
+ buffer = new char[length]; // too small: length is the size needed, terminator included
+ }
+ }
+
+ /// <summary><c>\\?\C:\x</c> → <c>C:\x</c>, <c>\\?\UNC\server\share</c> → <c>\\server\share</c>.</summary>
+ internal static string WithoutPrefix(string path)
+ {
+ if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
+ return @"\\" + path[8..];
+ if (path.StartsWith(@"\\?\", StringComparison.Ordinal))
+ return path[4..];
+ return path;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, nint security, uint creation, uint flags, nint template);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, [Out] char[] buffer, uint size, uint flags);
+}
diff --git a/tests/Filee.Engines.Tests/RealPathTests.cs b/tests/Filee.Engines.Tests/RealPathTests.cs
new file mode 100644
index 00000000..8b5b0cb3
--- /dev/null
+++ b/tests/Filee.Engines.Tests/RealPathTests.cs
@@ -0,0 +1,88 @@
+// msiexec gets real paths, without the junctions a user made on the way (#527): the Windows Installer service
+// refuses those ("untrusted mount point") and fails with error 1620.
+
+using System.Diagnostics;
+using System.Runtime.Versioning;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Tests;
+
+public sealed class RealPathTests : IDisposable
+{
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "filee-realpath-" + Guid.NewGuid().ToString("N")[..8]);
+
+ private string Link => Path.Combine(_root, "link");
+
+ public RealPathTests() => Directory.CreateDirectory(_root);
+
+ public void Dispose()
+ {
+ // A junction goes first, on its own: a recursive delete with one inside fails with access denied.
+ try
+ {
+ if (Directory.Exists(Link))
+ Directory.Delete(Link);
+ Directory.Delete(_root, true);
+ }
+ catch (IOException) { }
+ }
+
+ [Fact]
+ [SupportedOSPlatform("windows")]
+ public void A_junction_on_the_way_is_followed_for_a_folder_and_a_file()
+ {
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows junctions.");
+ var real = Directory.CreateDirectory(Path.Combine(_root, "real", "staging")).Parent!.FullName;
+ File.WriteAllText(Path.Combine(real, "package.msi"), "");
+ var link = Link;
+ Junction(link, real); // like AppData\Local moved to another drive
+
+ // The temp folder may itself have short (8.3) names, which the final path spells out.
+ var expected = RealPath.Of(real);
+ Assert.DoesNotContain("link", expected, StringComparison.OrdinalIgnoreCase);
+ Assert.Equal(Path.Combine(expected, "staging"), RealPath.Of(Path.Combine(link, "staging")), ignoreCase: true);
+ Assert.Equal(Path.Combine(expected, "package.msi"), RealPath.Of(Path.Combine(link, "package.msi")), ignoreCase: true);
+ }
+
+ [Fact]
+ [SupportedOSPlatform("windows")]
+ public void A_path_without_links_stays_and_one_that_cannot_be_opened_is_kept()
+ {
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows final paths.");
+ var plain = Path.Combine(RealPath.Of(_root), "plain");
+ Directory.CreateDirectory(plain);
+ Assert.Equal(plain, RealPath.Of(plain));
+
+ var missing = Path.Combine(_root, "missing", "package.msi");
+ Assert.Equal(missing, RealPath.Of(missing));
+ }
+
+ [Fact]
+ public void The_long_path_prefix_is_dropped()
+ {
+ Assert.Equal(@"C:\Users\x", RealPath.WithoutPrefix(@"\\?\C:\Users\x"));
+ Assert.Equal(@"\\server\share\x", RealPath.WithoutPrefix(@"\\?\UNC\server\share\x"));
+ Assert.Equal(@"D:\x", RealPath.WithoutPrefix(@"D:\x"));
+ }
+
+ [Fact]
+ public void An_installer_that_cannot_open_its_package_says_so()
+ {
+ var message = EngineInstaller.MsiFailure("libreoffice", 1620, @"C:\Temp\filee-msiexec.log");
+ Assert.Contains("Windows Installer couldn't open the libreoffice package (error 1620)", message);
+ Assert.Contains(@"C:\Temp\filee-msiexec.log", message);
+ Assert.Contains("exit code 1603", EngineInstaller.MsiFailure("calibre", 1603, "log"));
+ }
+
+ private static void Junction(string link, string target)
+ {
+ using var mklink = Process.Start(new ProcessStartInfo("cmd.exe", ["/c", "mklink", "/J", link, target])
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ })!;
+ mklink.WaitForExit();
+ Assert.Equal(0, mklink.ExitCode);
+ }
+}