Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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}");
}
1 change: 1 addition & 0 deletions src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
49 changes: 46 additions & 3 deletions src/FourFoldAccountManager.Desktop/Updates/UpdateInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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);
Expand Down Expand Up @@ -80,6 +81,46 @@ public static bool TryRunReplacementMode(IReadOnlyList<string> 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) ||
Expand Down Expand Up @@ -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)
{
Expand Down
Loading