diff --git a/src/FourFoldAccountManager.Desktop.Tests/Updates/UpdateInstallerTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Updates/UpdateInstallerTests.cs new file mode 100644 index 0000000..e453743 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop.Tests/Updates/UpdateInstallerTests.cs @@ -0,0 +1,87 @@ +using System.Diagnostics; +using System.IO; +using FourFoldAccountManager.Desktop.Updates; +using Xunit; + +namespace FourFoldAccountManager.Desktop.Tests.Updates; + +public sealed class UpdateInstallerTests +{ + // An exe first downloaded with a browser carries a Zone.Identifier stream, and File.Replace keeps it on + // every update. Relaunching that exe through the shell raises "Open File - Security Warning" inside the + // hidden helper, where nobody can answer it, so the helper never exits and the app never reopens. + [Fact] + public void HelperExitsAfterReplacingAnExeThatCarriesTheMarkOfTheWeb() + { + var directory = Directory.CreateTempSubdirectory("FourFoldUpdateInstallerTests-").FullName; + var quietExe = Path.Combine(Environment.SystemDirectory, "rundll32.exe"); + var update = Path.Combine(directory, "update.download"); + var target = Path.Combine(directory, "Fourfold.exe"); + File.Copy(quietExe, update); + File.Copy(quietExe, target); + File.WriteAllText(target + ":Zone.Identifier", "[ZoneTransfer]\r\nZoneId=3\r\n"); + + var startInfo = new ProcessStartInfo + { + FileName = Path.Combine(AppContext.BaseDirectory, "FourFoldAccountManager.Desktop.exe"), + UseShellExecute = false, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + }; + startInfo.ArgumentList.Add("--apply-update"); + startInfo.ArgumentList.Add(int.MaxValue.ToString()); + startInfo.ArgumentList.Add(update); + startInfo.ArgumentList.Add(target); + + using var helper = Process.Start(startInfo)!; + var exited = helper.WaitForExit(TimeSpan.FromSeconds(30)); + if (!exited) + { + helper.Kill(); + helper.WaitForExit(); + } + + Assert.True(exited, "The update helper was still running 30 seconds after replacing the exe."); + Assert.False(File.Exists(update)); + Directory.Delete(directory, recursive: true); + } + + // The cleanup deletes from the user's temp folder, so it must take only finished helpers: one that is + // still running keeps its exe locked and must keep the native libraries it extracted as well. + [Fact] + public void DeleteStaleHelpersRemovesFinishedHelpersAndLeavesRunningOnesAndOtherFiles() + { + var directory = Directory.CreateTempSubdirectory("FourFoldUpdateInstallerTests-").FullName; + var staleExe = CreateHelper(directory, "stale"); + var runningExe = CreateHelper(directory, "running"); + var orphanFolder = Directory.CreateDirectory(Path.Combine(directory, ".net", "FourFoldAccountManager-updater-orphan")).FullName; + var otherFile = Path.Combine(directory, "FourFoldAccountManager-notes.exe"); + var otherFolder = Directory.CreateDirectory(Path.Combine(directory, ".net", "SomeOtherApp")).FullName; + File.WriteAllText(otherFile, "keep"); + + using (File.Open(runningExe, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + UpdateInstaller.DeleteStaleHelpers(directory); + } + + Assert.False(File.Exists(staleExe)); + Assert.False(Directory.Exists(ExtractionFolder(directory, "stale"))); + Assert.False(Directory.Exists(orphanFolder)); + Assert.True(File.Exists(runningExe)); + Assert.True(File.Exists(Path.Combine(ExtractionFolder(directory, "running"), "native.dll"))); + Assert.True(File.Exists(otherFile)); + Assert.True(Directory.Exists(otherFolder)); + Directory.Delete(directory, recursive: true); + } + + private static string CreateHelper(string directory, string id) + { + var helperPath = Path.Combine(directory, $"FourFoldAccountManager-updater-{id}.exe"); + File.WriteAllText(helperPath, "helper"); + File.WriteAllText(Path.Combine(Directory.CreateDirectory(ExtractionFolder(directory, id)).FullName, "native.dll"), "native"); + return helperPath; + } + + private static string ExtractionFolder(string directory, string id) => + Path.Combine(directory, ".net", $"FourFoldAccountManager-updater-{id}"); +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 308e33f..6381687 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -377,6 +377,7 @@ private async Task CheckForUpdatesAsync() { try { + _ = Task.Run(() => UpdateInstaller.DeleteStaleHelpers()); var currentVersion = typeof(App).Assembly.GetName().Version ?? new Version(1, 1, 0); var currentExecutablePath = Environment.ProcessPath; if (string.IsNullOrWhiteSpace(currentExecutablePath)) diff --git a/src/FourFoldAccountManager.Desktop/Updates/UpdateInstaller.cs b/src/FourFoldAccountManager.Desktop/Updates/UpdateInstaller.cs index be8eec5..5249587 100644 --- a/src/FourFoldAccountManager.Desktop/Updates/UpdateInstaller.cs +++ b/src/FourFoldAccountManager.Desktop/Updates/UpdateInstaller.cs @@ -7,6 +7,7 @@ namespace FourFoldAccountManager.Desktop.Updates; public sealed class UpdateInstaller { private const string ApplyUpdateArgument = "--apply-update"; + private const string HelperNamePrefix = "FourFoldAccountManager-updater-"; public UpdateInstallResult TryStart(string verifiedUpdatePath, string currentExecutablePath, int parentProcessId) { @@ -26,7 +27,7 @@ public UpdateInstallResult TryStart(string verifiedUpdatePath, string currentExe return UpdateInstallResult.Failed; } - var helperPath = Path.Combine(Path.GetTempPath(), $"FourFoldAccountManager-updater-{Guid.NewGuid():N}.exe"); + var helperPath = Path.Combine(Path.GetTempPath(), $"{HelperNamePrefix}{Guid.NewGuid():N}.exe"); try { File.Copy(currentExecutablePath, helperPath, overwrite: false); @@ -80,6 +81,46 @@ public static bool TryRunReplacementMode(IReadOnlyList args) return true; } + // A helper cannot delete its own running exe, so the next normal start clears what earlier updates left. + // A helper that is still running keeps its exe locked, and that keeps its extracted native libraries too. + public static void DeleteStaleHelpers(string? temporaryDirectory = null) + { + var directory = temporaryDirectory ?? Path.GetTempPath(); + try + { + foreach (var helperPath in Directory.EnumerateFiles(directory, HelperNamePrefix + "*.exe")) + { + UpdateFiles.TryDelete(helperPath); + } + + // The single-file build extracts its native libraries into one folder per exe name. + var extractionRoot = Path.Combine(directory, ".net"); + if (!Directory.Exists(extractionRoot)) + { + return; + } + + foreach (var folder in Directory.EnumerateDirectories(extractionRoot, HelperNamePrefix + "*")) + { + if (File.Exists(Path.Combine(directory, Path.GetFileName(folder) + ".exe"))) + { + continue; + } + + try + { + Directory.Delete(folder, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + } + } + public static bool ReplaceTargetFile(string verifiedUpdatePath, string targetExecutablePath) { if (!Path.IsPathFullyQualified(verifiedUpdatePath) || @@ -174,11 +215,13 @@ private static void TryLaunch(string targetPath) { try { + // Not through the shell: an exe that still carries its browser download mark makes the shell ask + // "Open File - Security Warning" in this hidden helper, which then waits forever. Process.Start(new ProcessStartInfo { FileName = targetPath, - UseShellExecute = true - }); + UseShellExecute = false + })?.Dispose(); } catch (Exception exception) when (exception is InvalidOperationException or System.ComponentModel.Win32Exception) {