merge: Campaign LA LA10 - updater review-closed
This commit is contained in:
commit
da4fb3de19
40 changed files with 9778 additions and 68 deletions
|
|
@ -44,6 +44,7 @@ public sealed class LauncherProcessSupervisorFactory(
|
|||
/// </summary>
|
||||
public sealed class LauncherProcessSupervisor : ILauncherProcessSupervisor
|
||||
{
|
||||
private static readonly TimeSpan DisposeStopTimeout = TimeSpan.FromSeconds(5);
|
||||
private readonly ILauncherChildProcessFactory _factory;
|
||||
private readonly object _gate = new();
|
||||
private readonly Queue<LauncherSessionState> _pendingStateChanges = [];
|
||||
|
|
@ -51,6 +52,7 @@ public sealed class LauncherProcessSupervisor : ILauncherProcessSupervisor
|
|||
private LauncherSessionState _state = LauncherSessionState.Starting;
|
||||
private int? _exitCode;
|
||||
private bool _publishingStateChanges;
|
||||
private bool _disposed;
|
||||
|
||||
public LauncherProcessSupervisor(ILauncherChildProcessFactory? factory = null)
|
||||
{
|
||||
|
|
@ -100,6 +102,7 @@ public sealed class LauncherProcessSupervisor : ILauncherProcessSupervisor
|
|||
ILauncherChildProcess process;
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_process is not null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
|
|
@ -201,6 +204,11 @@ public sealed class LauncherProcessSupervisor : ILauncherProcessSupervisor
|
|||
if (!process.WaitForExit(timeout) && !process.HasExited)
|
||||
{
|
||||
process.Kill();
|
||||
if (!process.WaitForExit(Timeout.InfiniteTimeSpan) && !process.HasExited)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"The launcher child could not be observed terminal after it was killed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -307,6 +315,23 @@ public sealed class LauncherProcessSupervisor : ILauncherProcessSupervisor
|
|||
|
||||
public void Dispose()
|
||||
{
|
||||
ILauncherChildProcess? process;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
process = _process;
|
||||
}
|
||||
|
||||
if (process is { HasExited: false })
|
||||
{
|
||||
Stop(DisposeStopTimeout);
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (_process is not null)
|
||||
|
|
|
|||
|
|
@ -1,18 +1,19 @@
|
|||
using AcDream.Launcher.Core.Launching;
|
||||
using AcDream.Launcher.Core.Profiles;
|
||||
using AcDream.Launcher.Core.Updates;
|
||||
|
||||
namespace AcDream.Launcher.Core.Orchestration;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves and validates the co-deployed graphical/headless hosts. LA10 will
|
||||
/// replace the directory lookup with its versioned-current resolver; until
|
||||
/// then a missing host disables the corresponding action instead of deferring
|
||||
/// failure until process creation.
|
||||
/// Resolves and validates the graphical/headless hosts. Production uses the
|
||||
/// verified <c>DataDirectory/app/current.json</c> resolver; the explicit-path
|
||||
/// constructor remains the injectable test seam.
|
||||
/// </summary>
|
||||
public sealed class LauncherExecutableSet
|
||||
{
|
||||
private readonly Func<string, bool> _fileExists;
|
||||
private readonly Func<string, bool> _hasUnixExecutePermission;
|
||||
private readonly Func<ExecutablePaths> _resolve;
|
||||
|
||||
public LauncherExecutableSet(
|
||||
string graphicalHostPath,
|
||||
|
|
@ -23,25 +24,50 @@ public sealed class LauncherExecutableSet
|
|||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(graphicalHostPath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(headlessHostPath);
|
||||
GraphicalHostPath = graphicalHostPath;
|
||||
HeadlessHostPath = headlessHostPath;
|
||||
WorkingDirectory = workingDirectory;
|
||||
string graphical = graphicalHostPath;
|
||||
string headless = headlessHostPath;
|
||||
_resolve = () => new ExecutablePaths(graphical, headless, workingDirectory);
|
||||
_fileExists = fileExists ?? File.Exists;
|
||||
_hasUnixExecutePermission =
|
||||
hasUnixExecutePermission ?? HasUnixExecutePermission;
|
||||
}
|
||||
|
||||
public string GraphicalHostPath { get; }
|
||||
private LauncherExecutableSet(
|
||||
Func<ExecutablePaths> resolve,
|
||||
Func<string, bool>? fileExists = null,
|
||||
Func<string, bool>? hasUnixExecutePermission = null)
|
||||
{
|
||||
_resolve = resolve ?? throw new ArgumentNullException(nameof(resolve));
|
||||
_fileExists = fileExists ?? File.Exists;
|
||||
_hasUnixExecutePermission =
|
||||
hasUnixExecutePermission ?? HasUnixExecutePermission;
|
||||
}
|
||||
|
||||
public string HeadlessHostPath { get; }
|
||||
public string GraphicalHostPath => _resolve().GraphicalHostPath;
|
||||
|
||||
public string? WorkingDirectory { get; }
|
||||
public string HeadlessHostPath => _resolve().HeadlessHostPath;
|
||||
|
||||
public string? WorkingDirectory => _resolve().WorkingDirectory;
|
||||
|
||||
public LauncherCapability GetAvailability(LaunchMode mode)
|
||||
{
|
||||
ExecutablePaths paths;
|
||||
try
|
||||
{
|
||||
paths = _resolve();
|
||||
}
|
||||
catch (Exception ex) when (ex is LauncherUpdateException
|
||||
or InvalidOperationException
|
||||
or IOException
|
||||
or UnauthorizedAccessException)
|
||||
{
|
||||
return LauncherCapability.Unavailable(
|
||||
$"The active versioned client is unavailable: {ex.Message}");
|
||||
}
|
||||
|
||||
string path = mode == LaunchMode.Headless
|
||||
? HeadlessHostPath
|
||||
: GraphicalHostPath;
|
||||
? paths.HeadlessHostPath
|
||||
: paths.GraphicalHostPath;
|
||||
string host = mode == LaunchMode.Headless
|
||||
? "headless host"
|
||||
: "graphical client";
|
||||
|
|
@ -68,27 +94,27 @@ public sealed class LauncherExecutableSet
|
|||
string configFilePath)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(configFilePath);
|
||||
RequireAvailable(mode);
|
||||
ExecutablePaths paths = RequireAvailable(mode);
|
||||
|
||||
return mode == LaunchMode.Headless
|
||||
? new LauncherProcessSpec(
|
||||
HeadlessHostPath,
|
||||
paths.HeadlessHostPath,
|
||||
["--config", configFilePath],
|
||||
WorkingDirectory)
|
||||
paths.WorkingDirectory)
|
||||
: new LauncherProcessSpec(
|
||||
GraphicalHostPath,
|
||||
paths.GraphicalHostPath,
|
||||
["--session-config", configFilePath],
|
||||
WorkingDirectory);
|
||||
paths.WorkingDirectory);
|
||||
}
|
||||
|
||||
public LauncherProcessSpec CreateProbeSpec(string configFilePath)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(configFilePath);
|
||||
RequireAvailable(LaunchMode.Headless);
|
||||
ExecutablePaths paths = RequireAvailable(LaunchMode.Headless);
|
||||
return new LauncherProcessSpec(
|
||||
HeadlessHostPath,
|
||||
paths.HeadlessHostPath,
|
||||
["--config", configFilePath],
|
||||
WorkingDirectory);
|
||||
paths.WorkingDirectory);
|
||||
}
|
||||
|
||||
public static LauncherExecutableSet FromDirectory(string directory)
|
||||
|
|
@ -102,7 +128,35 @@ public sealed class LauncherExecutableSet
|
|||
fullDirectory);
|
||||
}
|
||||
|
||||
private void RequireAvailable(LaunchMode mode)
|
||||
/// <summary>
|
||||
/// Dynamic production resolver. The store cache is admitted only after a
|
||||
/// strict startup/update verification, and a pointer swap changes the
|
||||
/// binaries selected for the next session without replacing LA9 content.
|
||||
/// </summary>
|
||||
public static LauncherExecutableSet FromCurrentVersionStore(
|
||||
ClientVersionStore store)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
return new LauncherExecutableSet(() =>
|
||||
{
|
||||
ClientVersionResolution resolution = store.CachedResolution;
|
||||
if (!resolution.IsVerified || resolution.Directory is null)
|
||||
{
|
||||
throw new LauncherUpdateException(resolution.Status);
|
||||
}
|
||||
|
||||
return FromDirectoryPaths(resolution.Directory);
|
||||
});
|
||||
}
|
||||
|
||||
public static LauncherExecutableSet Unavailable(string reason)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(reason);
|
||||
return new LauncherExecutableSet(
|
||||
() => throw new LauncherUpdateException(reason));
|
||||
}
|
||||
|
||||
private ExecutablePaths RequireAvailable(LaunchMode mode)
|
||||
{
|
||||
LauncherCapability capability = GetAvailability(mode);
|
||||
if (!capability.IsAvailable)
|
||||
|
|
@ -110,6 +164,18 @@ public sealed class LauncherExecutableSet
|
|||
throw new LauncherOperationException(
|
||||
capability.Reason ?? "The selected launcher host is unavailable.");
|
||||
}
|
||||
|
||||
return _resolve();
|
||||
}
|
||||
|
||||
private static ExecutablePaths FromDirectoryPaths(string directory)
|
||||
{
|
||||
string fullDirectory = Path.GetFullPath(directory);
|
||||
string executableSuffix = OperatingSystem.IsWindows() ? ".exe" : string.Empty;
|
||||
return new ExecutablePaths(
|
||||
Path.Combine(fullDirectory, "AcDream.App" + executableSuffix),
|
||||
Path.Combine(fullDirectory, "acdream-headless" + executableSuffix),
|
||||
fullDirectory);
|
||||
}
|
||||
|
||||
private static bool HasUnixExecutePermission(string path)
|
||||
|
|
@ -134,4 +200,9 @@ public sealed class LauncherExecutableSet
|
|||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record ExecutablePaths(
|
||||
string GraphicalHostPath,
|
||||
string HeadlessHostPath,
|
||||
string? WorkingDirectory);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using AcDream.Launcher.Core.Launching;
|
||||
using AcDream.Launcher.Core.Profiles;
|
||||
using AcDream.Launcher.Core.Status;
|
||||
using AcDream.Launcher.Core.Updates;
|
||||
using AcDream.Platform;
|
||||
|
||||
namespace AcDream.Launcher.Core.Orchestration;
|
||||
|
|
@ -26,6 +27,7 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
private readonly ILauncherProcessSupervisorFactory _supervisorFactory;
|
||||
private readonly IStatusEventSourceFactory _statusSourceFactory;
|
||||
private readonly Func<string> _sessionIdFactory;
|
||||
private readonly UpdateSessionBarrier _updateSessionBarrier;
|
||||
private readonly List<ManagedActivity> _activities = [];
|
||||
|
||||
private LauncherInstallRecord? _installRecord;
|
||||
|
|
@ -42,7 +44,8 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
ILauncherProcessSupervisorFactory? supervisorFactory = null,
|
||||
IStatusEventSourceFactory? statusSourceFactory = null,
|
||||
Func<string>? sessionIdFactory = null,
|
||||
string? installationStatus = null)
|
||||
string? installationStatus = null,
|
||||
UpdateSessionBarrier? updateSessionBarrier = null)
|
||||
{
|
||||
_profileStore = profileStore ?? throw new ArgumentNullException(nameof(profileStore));
|
||||
_paths = paths ?? throw new ArgumentNullException(nameof(paths));
|
||||
|
|
@ -53,6 +56,8 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
_supervisorFactory = supervisorFactory ?? new LauncherProcessSupervisorFactory();
|
||||
_statusSourceFactory = statusSourceFactory ?? new StatusFileTailerFactory();
|
||||
_sessionIdFactory = sessionIdFactory ?? CreateSessionId;
|
||||
_updateSessionBarrier = updateSessionBarrier
|
||||
?? new UpdateSessionBarrier(paths.DataDirectory);
|
||||
_installationStatus = installationStatus
|
||||
?? (installRecord is null
|
||||
? FirstRunRequired
|
||||
|
|
@ -622,6 +627,7 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
}
|
||||
|
||||
request.Cancellation.Dispose();
|
||||
request.Activity.StartCompleted.Set();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -629,10 +635,18 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
{
|
||||
ILauncherProcessSupervisor? supervisor = null;
|
||||
string? password = request.Password;
|
||||
bool hostStarted = false;
|
||||
try
|
||||
{
|
||||
request.Cancellation.Token.ThrowIfCancellationRequested();
|
||||
|
||||
UpdateSessionBarrier.SessionLease sessionLease =
|
||||
_updateSessionBarrier.AcquireSession();
|
||||
lock (_gate)
|
||||
{
|
||||
request.Activity.UpdateSessionLease = sessionLease;
|
||||
}
|
||||
|
||||
ComposedSessionConfig composed = request.IsProbe
|
||||
? _configService.ComposeProbeAndWrite(
|
||||
request.Server,
|
||||
|
|
@ -674,6 +688,7 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
request.Activity.LaunchMode!.Value,
|
||||
composed.ConfigFilePath);
|
||||
supervisor.Start(processSpec, password);
|
||||
hostStarted = true;
|
||||
|
||||
request.Password = null;
|
||||
password = null;
|
||||
|
|
@ -728,6 +743,10 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
finally
|
||||
{
|
||||
request.Password = null;
|
||||
if (!hostStarted)
|
||||
{
|
||||
ReleaseUpdateSessionLease(request.Activity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -735,6 +754,7 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
ManagedActivity activity,
|
||||
LauncherSessionState processState)
|
||||
{
|
||||
UpdateSessionBarrier.SessionLease? sessionLease = null;
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
|
|
@ -774,10 +794,13 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
{
|
||||
activity.Status = activity.HostTerminalStatus;
|
||||
}
|
||||
sessionLease = activity.UpdateSessionLease;
|
||||
activity.UpdateSessionLease = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sessionLease?.Dispose();
|
||||
RaiseStateChanged();
|
||||
}
|
||||
catch
|
||||
|
|
@ -1179,11 +1202,16 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
private static void DisposeActivity(ManagedActivity activity)
|
||||
{
|
||||
activity.StartCancellation?.Cancel();
|
||||
activity.StartCompleted.Wait();
|
||||
activity.StartCancellation?.Dispose();
|
||||
activity.StartCancellation = null;
|
||||
|
||||
if (activity.Supervisor is not null)
|
||||
{
|
||||
// Disposal is a process-lifetime transaction: the shared update
|
||||
// lease remains held until Stop has observed the real child
|
||||
// terminal (including the post-kill wait).
|
||||
activity.Supervisor.Stop(TimeSpan.FromSeconds(5));
|
||||
if (activity.SupervisorStateHandler is not null)
|
||||
{
|
||||
activity.Supervisor.StateChanged -= activity.SupervisorStateHandler;
|
||||
|
|
@ -1192,6 +1220,16 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
activity.Supervisor.Dispose();
|
||||
activity.Supervisor = null;
|
||||
}
|
||||
|
||||
ReleaseUpdateSessionLease(activity);
|
||||
activity.StartCompleted.Dispose();
|
||||
}
|
||||
|
||||
private static void ReleaseUpdateSessionLease(ManagedActivity activity)
|
||||
{
|
||||
UpdateSessionBarrier.SessionLease? lease =
|
||||
Interlocked.Exchange(ref activity.UpdateSessionLease, null);
|
||||
lease?.Dispose();
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
|
|
@ -1252,6 +1290,10 @@ public sealed class LauncherOrchestrator : ILauncherOrchestrator
|
|||
|
||||
public CancellationTokenSource? StartCancellation { get; set; }
|
||||
|
||||
public UpdateSessionBarrier.SessionLease? UpdateSessionLease;
|
||||
|
||||
public ManualResetEventSlim StartCompleted { get; } = new(false);
|
||||
|
||||
public object StatusReadGate { get; } = new();
|
||||
|
||||
public bool IsActive => State is not (
|
||||
|
|
|
|||
84
src/AcDream.Launcher.Core/Updates/AtomicJsonFile.cs
Normal file
84
src/AcDream.Launcher.Core/Updates/AtomicJsonFile.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System.Text.Json;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
internal static class AtomicJsonFile
|
||||
{
|
||||
internal static async Task WriteAsync<T>(
|
||||
string path,
|
||||
T value,
|
||||
JsonSerializerOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
string fullPath = Path.GetFullPath(path);
|
||||
string directory = Path.GetDirectoryName(fullPath)
|
||||
?? throw new InvalidOperationException("The JSON path has no parent directory.");
|
||||
Directory.CreateDirectory(directory);
|
||||
string temporaryPath = Path.Combine(
|
||||
directory,
|
||||
$".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
|
||||
try
|
||||
{
|
||||
await using (var stream = new FileStream(
|
||||
temporaryPath,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
16 * 1024,
|
||||
FileOptions.Asynchronous | FileOptions.WriteThrough))
|
||||
{
|
||||
await JsonSerializer.SerializeAsync(
|
||||
stream,
|
||||
value,
|
||||
options,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(temporaryPath, fullPath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
VerifiedArtifactDownloader.TryDelete(temporaryPath);
|
||||
}
|
||||
}
|
||||
|
||||
internal static async Task WriteBytesAsync(
|
||||
string path,
|
||||
ReadOnlyMemory<byte> bytes,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
string fullPath = Path.GetFullPath(path);
|
||||
string directory = Path.GetDirectoryName(fullPath)
|
||||
?? throw new InvalidOperationException("The file path has no parent directory.");
|
||||
Directory.CreateDirectory(directory);
|
||||
string temporaryPath = Path.Combine(
|
||||
directory,
|
||||
$".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
|
||||
try
|
||||
{
|
||||
await using (var stream = new FileStream(
|
||||
temporaryPath,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
16 * 1024,
|
||||
FileOptions.Asynchronous | FileOptions.WriteThrough))
|
||||
{
|
||||
await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
|
||||
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(temporaryPath, fullPath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
VerifiedArtifactDownloader.TryDelete(temporaryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
1015
src/AcDream.Launcher.Core/Updates/ClientVersionStore.cs
Normal file
1015
src/AcDream.Launcher.Core/Updates/ClientVersionStore.cs
Normal file
File diff suppressed because it is too large
Load diff
33
src/AcDream.Launcher.Core/Updates/LauncherRuntimeIdentity.cs
Normal file
33
src/AcDream.Launcher.Core/Updates/LauncherRuntimeIdentity.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public static class LauncherRuntimeIdentity
|
||||
{
|
||||
public static string DetectRid()
|
||||
{
|
||||
string os = OperatingSystem.IsWindows()
|
||||
? "win"
|
||||
: OperatingSystem.IsLinux()
|
||||
? "linux"
|
||||
: throw new PlatformNotSupportedException(
|
||||
"The launcher updater supports Windows and Linux only.");
|
||||
string architecture = RuntimeInformation.ProcessArchitecture switch
|
||||
{
|
||||
Architecture.X64 => "x64",
|
||||
Architecture.Arm64 => "arm64",
|
||||
_ => throw new PlatformNotSupportedException(
|
||||
$"The launcher updater does not support {RuntimeInformation.ProcessArchitecture}."),
|
||||
};
|
||||
return $"{os}-{architecture}";
|
||||
}
|
||||
|
||||
internal static bool IsValidRid(string? rid) =>
|
||||
!string.IsNullOrEmpty(rid)
|
||||
&& rid.Length <= 64
|
||||
&& rid[0] is >= 'a' and <= 'z'
|
||||
&& rid.All(character =>
|
||||
character is >= 'a' and <= 'z'
|
||||
or >= '0' and <= '9'
|
||||
or '-');
|
||||
}
|
||||
418
src/AcDream.Launcher.Core/Updates/LauncherSelfUpdateBootstrap.cs
Normal file
418
src/AcDream.Launcher.Core/Updates/LauncherSelfUpdateBootstrap.cs
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public sealed record SelfUpdateStartupResult(
|
||||
bool ShouldExit,
|
||||
int ExitCode,
|
||||
string[] RemainingArguments);
|
||||
|
||||
/// <summary>
|
||||
/// Process-level self-update bootstrap. Every child argument is passed through
|
||||
/// <see cref="ProcessStartInfo.ArgumentList"/> with shell execution disabled.
|
||||
/// </summary>
|
||||
public static class LauncherSelfUpdateBootstrap
|
||||
{
|
||||
public const string HelperArgument = "--acdream-self-update-helper-v1";
|
||||
public const string ConfirmArgument = "--acdream-self-update-confirm-v1";
|
||||
internal const string DeferredArgument = "--acdream-self-update-deferred-v1";
|
||||
internal const int DeferredLeaseExitCode = 73;
|
||||
private static readonly TimeSpan ConfirmationTimeout = TimeSpan.FromSeconds(30);
|
||||
private static readonly TimeSpan CleanupTimeout = TimeSpan.FromSeconds(5);
|
||||
|
||||
public static async Task<SelfUpdateStartupResult> HandleAsync(
|
||||
string[] args,
|
||||
LauncherSelfUpdateManager manager,
|
||||
string launcherBaseDirectory,
|
||||
string currentExecutablePath,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(args);
|
||||
ArgumentNullException.ThrowIfNull(manager);
|
||||
string baseDirectory = Path.TrimEndingDirectorySeparator(
|
||||
Path.GetFullPath(launcherBaseDirectory));
|
||||
string executable = Path.GetFullPath(currentExecutablePath);
|
||||
|
||||
if (args.Length > 0
|
||||
&& string.Equals(args[0], DeferredArgument, StringComparison.Ordinal))
|
||||
{
|
||||
return new SelfUpdateStartupResult(false, 0, args[1..]);
|
||||
}
|
||||
|
||||
if (args.Length > 0
|
||||
&& string.Equals(args[0], HelperArgument, StringComparison.Ordinal))
|
||||
{
|
||||
if (args.Length < 4
|
||||
|| !int.TryParse(
|
||||
args[1],
|
||||
System.Globalization.NumberStyles.None,
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
out int parentPid)
|
||||
|| parentPid <= 0)
|
||||
{
|
||||
return new SelfUpdateStartupResult(true, 64, []);
|
||||
}
|
||||
|
||||
int exitCode = await RunHelperAsync(
|
||||
manager,
|
||||
parentPid,
|
||||
args[2],
|
||||
args[3],
|
||||
args[4..],
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new SelfUpdateStartupResult(true, exitCode, []);
|
||||
}
|
||||
|
||||
if (args.Length > 0
|
||||
&& string.Equals(args[0], ConfirmArgument, StringComparison.Ordinal))
|
||||
{
|
||||
if (args.Length < 2)
|
||||
{
|
||||
return new SelfUpdateStartupResult(true, 64, []);
|
||||
}
|
||||
|
||||
await manager.ConfirmAsync(
|
||||
args[1],
|
||||
baseDirectory,
|
||||
executable,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await FinishConfirmedCleanupAsync(
|
||||
manager,
|
||||
baseDirectory,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return new SelfUpdateStartupResult(false, 0, args[2..]);
|
||||
}
|
||||
|
||||
if (!manager.Barrier.TryAcquireExclusive(
|
||||
out UpdateSessionBarrier.ExclusiveLease? startupLease))
|
||||
{
|
||||
// A running session or another launcher is staging. Reading the
|
||||
// plan is safe, but cleanup or starting a competing helper is not.
|
||||
return new SelfUpdateStartupResult(false, 0, args);
|
||||
}
|
||||
|
||||
using (UpdateSessionBarrier.ExclusiveLease lease = startupLease
|
||||
?? throw new InvalidOperationException("Exclusive startup lease is missing."))
|
||||
{
|
||||
SelfUpdatePlan? plan = await manager.LoadPendingAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
_ = manager.CleanupOwnedResidueUnderLease(
|
||||
plan,
|
||||
baseDirectory,
|
||||
lease);
|
||||
if (plan is null)
|
||||
{
|
||||
return new SelfUpdateStartupResult(false, 0, args);
|
||||
}
|
||||
|
||||
if (!PathsEqual(plan.TargetDirectory, baseDirectory))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The pending self-update targets a different launcher directory.");
|
||||
}
|
||||
|
||||
if (plan.State == SelfUpdatePlanState.AwaitingConfirmation)
|
||||
{
|
||||
if (!manager.IsConfirmed(plan.TransactionId))
|
||||
{
|
||||
await manager.ConfirmAsync(
|
||||
plan.TransactionId,
|
||||
baseDirectory,
|
||||
executable,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await manager.CompleteConfirmedAsync(
|
||||
plan.TransactionId,
|
||||
baseDirectory,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
_ = manager.CleanupOwnedResidueUnderLease(
|
||||
pending: null,
|
||||
baseDirectory,
|
||||
lease);
|
||||
return new SelfUpdateStartupResult(false, 0, args);
|
||||
}
|
||||
|
||||
string expectedExecutable = ClientVersionStore.ResolveContained(
|
||||
baseDirectory,
|
||||
GetLauncherFileName(plan.Rid));
|
||||
if (!PathsEqual(executable, expectedExecutable))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"Self-update can start only from the published acdream-launcher executable.");
|
||||
}
|
||||
|
||||
string helperPath = manager.GetStagedLauncherPath(plan);
|
||||
var startInfo = new ProcessStartInfo(helperPath)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = manager.GetPayloadDirectory(plan.TransactionId),
|
||||
};
|
||||
startInfo.ArgumentList.Add(HelperArgument);
|
||||
startInfo.ArgumentList.Add(
|
||||
Environment.ProcessId.ToString(
|
||||
System.Globalization.CultureInfo.InvariantCulture));
|
||||
startInfo.ArgumentList.Add(baseDirectory);
|
||||
startInfo.ArgumentList.Add(plan.TransactionId);
|
||||
foreach (string argument in args)
|
||||
{
|
||||
startInfo.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
_ = Process.Start(startInfo)
|
||||
?? throw new LauncherUpdateException(
|
||||
"The launcher self-update helper could not be started.");
|
||||
return new SelfUpdateStartupResult(true, 0, []);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> RunHelperAsync(
|
||||
LauncherSelfUpdateManager manager,
|
||||
int parentPid,
|
||||
string targetDirectory,
|
||||
string transactionId,
|
||||
IReadOnlyList<string> publicArguments,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
SelfUpdatePlan plan = await manager.LoadPendingAsync(cancellationToken)
|
||||
.ConfigureAwait(false)
|
||||
?? throw new LauncherUpdateException("The helper found no pending self-update.");
|
||||
if (!string.Equals(plan.TransactionId, transactionId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The helper transaction does not match the pending self-update.");
|
||||
}
|
||||
|
||||
if (!PathsEqual(plan.TargetDirectory, targetDirectory))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The helper target does not match the pending self-update.");
|
||||
}
|
||||
|
||||
string launcherPath = ClientVersionStore.ResolveContained(
|
||||
targetDirectory,
|
||||
GetLauncherFileName(plan.Rid));
|
||||
var startInfo = new ProcessStartInfo(launcherPath)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = Path.GetFullPath(targetDirectory),
|
||||
};
|
||||
startInfo.ArgumentList.Add(ConfirmArgument);
|
||||
startInfo.ArgumentList.Add(transactionId);
|
||||
foreach (string argument in publicArguments)
|
||||
{
|
||||
startInfo.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
await WaitForParentExitAsync(parentPid, cancellationToken).ConfigureAwait(false);
|
||||
if (!manager.Barrier.TryAcquireExclusive(
|
||||
out UpdateSessionBarrier.ExclusiveLease? updateLease))
|
||||
{
|
||||
// Do not restart the canonical launcher: it would immediately see
|
||||
// the same staged plan and create an unbounded helper loop.
|
||||
return DeferredLeaseExitCode;
|
||||
}
|
||||
|
||||
using (UpdateSessionBarrier.ExclusiveLease lease = updateLease
|
||||
?? throw new InvalidOperationException("Exclusive update lease is missing."))
|
||||
{
|
||||
plan = await manager.LoadPendingAsync(cancellationToken)
|
||||
.ConfigureAwait(false)
|
||||
?? throw new LauncherUpdateException(
|
||||
"The helper found no pending self-update after acquiring the lease.");
|
||||
if (!string.Equals(
|
||||
plan.TransactionId,
|
||||
transactionId,
|
||||
StringComparison.Ordinal)
|
||||
|| !PathsEqual(plan.TargetDirectory, targetDirectory))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The pending self-update changed before the helper acquired its lease.");
|
||||
}
|
||||
|
||||
_ = manager.CleanupOwnedResidueUnderLease(
|
||||
plan,
|
||||
targetDirectory,
|
||||
lease);
|
||||
Process? replacement = null;
|
||||
try
|
||||
{
|
||||
plan = await manager.ApplyPendingAsync(targetDirectory, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
replacement = Process.Start(startInfo)
|
||||
?? throw new LauncherUpdateException(
|
||||
"The updated launcher could not be started.");
|
||||
DateTimeOffset deadline = DateTimeOffset.UtcNow + ConfirmationTimeout;
|
||||
while (!manager.IsConfirmed(transactionId))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (replacement.HasExited || DateTimeOffset.UtcNow >= deadline)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
replacement.HasExited
|
||||
? $"The updated launcher exited with code {replacement.ExitCode} "
|
||||
+ "before confirming startup."
|
||||
: "The updated launcher did not confirm startup in time.");
|
||||
}
|
||||
|
||||
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await manager.CompleteConfirmedAsync(
|
||||
transactionId,
|
||||
targetDirectory,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (replacement is { HasExited: false })
|
||||
{
|
||||
replacement.Kill(entireProcessTree: true);
|
||||
await replacement.WaitForExitAsync(CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
SelfUpdatePlan? pending = await manager.LoadPendingAsync(
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
SelfUpdatePlan? rollbackReceipt = pending?.State switch
|
||||
{
|
||||
SelfUpdatePlanState.Applying =>
|
||||
await manager.RecoverApplyingAsync(
|
||||
targetDirectory,
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false),
|
||||
SelfUpdatePlanState.AwaitingConfirmation =>
|
||||
await manager.RollbackAwaitingConfirmationAsync(
|
||||
targetDirectory,
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false),
|
||||
SelfUpdatePlanState.RolledBack => pending,
|
||||
_ => null,
|
||||
};
|
||||
if (rollbackReceipt?.State != SelfUpdatePlanState.RolledBack)
|
||||
{
|
||||
return 75;
|
||||
}
|
||||
|
||||
await manager.VerifyRestoredPriorAsync(
|
||||
targetDirectory,
|
||||
CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// An ambiguous state must not start either executable.
|
||||
return 75;
|
||||
}
|
||||
|
||||
var restored = new ProcessStartInfo(launcherPath)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = Path.GetFullPath(targetDirectory),
|
||||
};
|
||||
restored.ArgumentList.Add(DeferredArgument);
|
||||
foreach (string argument in publicArguments)
|
||||
{
|
||||
restored.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
_ = Process.Start(restored);
|
||||
return 74;
|
||||
}
|
||||
finally
|
||||
{
|
||||
replacement?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task FinishConfirmedCleanupAsync(
|
||||
LauncherSelfUpdateManager manager,
|
||||
string targetDirectory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
DateTimeOffset deadline = DateTimeOffset.UtcNow + CleanupTimeout;
|
||||
do
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (manager.Barrier.TryAcquireExclusive(
|
||||
out UpdateSessionBarrier.ExclusiveLease? lease))
|
||||
{
|
||||
using (UpdateSessionBarrier.ExclusiveLease acquiredLease = lease
|
||||
?? throw new InvalidOperationException(
|
||||
"Exclusive cleanup lease is missing."))
|
||||
{
|
||||
SelfUpdatePlan? pending = await manager.LoadPendingAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (pending is
|
||||
{
|
||||
State: SelfUpdatePlanState.AwaitingConfirmation,
|
||||
}
|
||||
&& manager.IsConfirmed(pending.TransactionId))
|
||||
{
|
||||
await manager.CompleteConfirmedAsync(
|
||||
pending.TransactionId,
|
||||
targetDirectory,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
pending = null;
|
||||
}
|
||||
|
||||
if (manager.CleanupOwnedResidueUnderLease(
|
||||
pending,
|
||||
targetDirectory,
|
||||
acquiredLease))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
while (DateTimeOffset.UtcNow < deadline);
|
||||
}
|
||||
|
||||
private static string GetLauncherFileName(string rid) =>
|
||||
"acdream-launcher"
|
||||
+ (rid.StartsWith("win-", StringComparison.Ordinal) ? ".exe" : string.Empty);
|
||||
|
||||
private static async Task WaitForParentExitAsync(
|
||||
int parentPid,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process parent = Process.GetProcessById(parentPid);
|
||||
if (parent.Id == Environment.ProcessId)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The self-update helper cannot wait on itself.");
|
||||
}
|
||||
|
||||
await parent.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// The parent exited before the helper opened it.
|
||||
}
|
||||
}
|
||||
|
||||
private static bool PathsEqual(string left, string right) =>
|
||||
string.Equals(
|
||||
Path.TrimEndingDirectorySeparator(Path.GetFullPath(left)),
|
||||
Path.TrimEndingDirectorySeparator(Path.GetFullPath(right)),
|
||||
OperatingSystem.IsWindows()
|
||||
? StringComparison.OrdinalIgnoreCase
|
||||
: StringComparison.Ordinal);
|
||||
}
|
||||
1803
src/AcDream.Launcher.Core/Updates/LauncherSelfUpdateManager.cs
Normal file
1803
src/AcDream.Launcher.Core/Updates/LauncherSelfUpdateManager.cs
Normal file
File diff suppressed because it is too large
Load diff
454
src/AcDream.Launcher.Core/Updates/LauncherUpdater.cs
Normal file
454
src/AcDream.Launcher.Core/Updates/LauncherUpdater.cs
Normal file
|
|
@ -0,0 +1,454 @@
|
|||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public enum LauncherUpdatePhase
|
||||
{
|
||||
Idle,
|
||||
Checking,
|
||||
DownloadingClient,
|
||||
ExtractingClient,
|
||||
ActivatingClient,
|
||||
DownloadingLauncher,
|
||||
StagingLauncher,
|
||||
RollingBack,
|
||||
Completed,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
public sealed record LauncherUpdateProgress(
|
||||
LauncherUpdatePhase Phase,
|
||||
string Status,
|
||||
long Completed = 0,
|
||||
long Total = 0)
|
||||
{
|
||||
public double Percent => Total <= 0
|
||||
? 0
|
||||
: Math.Clamp(Completed * 100d / Total, 0, 100);
|
||||
}
|
||||
|
||||
public sealed record LauncherUpdateCheckResult(
|
||||
ReleaseManifest Manifest,
|
||||
string Rid,
|
||||
LauncherVersion LauncherVersion,
|
||||
LauncherVersion? InstalledClientVersion,
|
||||
bool IsClientUpdateAvailable,
|
||||
bool IsLauncherUpdateAvailable,
|
||||
bool IsLauncherMinimumSatisfied,
|
||||
string Status);
|
||||
|
||||
public interface ILauncherUpdater
|
||||
{
|
||||
ClientVersionResolution CurrentClient { get; }
|
||||
|
||||
Task<ClientVersionResolution> InitializeAsync(
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<LauncherUpdateCheckResult> CheckAsync(
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<ClientVersionResolution> InstallClientAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<SelfUpdateStageResult> StageLauncherAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<ClientVersionResolution> RollbackClientAsync(
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Canonical LA10 update transaction. It holds the cross-process exclusive
|
||||
/// barrier for recovery/download/extraction/promotion/pointer publication and
|
||||
/// leaves LA9's verified DAT/pak record untouched.
|
||||
/// </summary>
|
||||
public sealed class LauncherUpdater : ILauncherUpdater
|
||||
{
|
||||
private readonly IReleaseManifestClient _manifestClient;
|
||||
private readonly ClientVersionStore _versions;
|
||||
private readonly LauncherSelfUpdateManager _selfUpdates;
|
||||
private readonly VerifiedArtifactDownloader _downloader;
|
||||
private readonly SafeZipExtractor _extractor;
|
||||
private readonly LauncherVersion _launcherVersion;
|
||||
private readonly string _rid;
|
||||
private readonly string _launcherTargetDirectory;
|
||||
private readonly Func<bool> _hasRunningSessions;
|
||||
private readonly SemaphoreSlim _operationGate = new(1, 1);
|
||||
|
||||
public LauncherUpdater(
|
||||
IReleaseManifestClient manifestClient,
|
||||
HttpClient httpClient,
|
||||
ClientVersionStore versions,
|
||||
LauncherSelfUpdateManager selfUpdates,
|
||||
LauncherVersion launcherVersion,
|
||||
string rid,
|
||||
string launcherTargetDirectory,
|
||||
Func<bool>? hasRunningSessions = null,
|
||||
SafeZipExtractor? extractor = null)
|
||||
{
|
||||
_manifestClient = manifestClient
|
||||
?? throw new ArgumentNullException(nameof(manifestClient));
|
||||
_versions = versions ?? throw new ArgumentNullException(nameof(versions));
|
||||
_selfUpdates = selfUpdates ?? throw new ArgumentNullException(nameof(selfUpdates));
|
||||
_launcherVersion = launcherVersion
|
||||
?? throw new ArgumentNullException(nameof(launcherVersion));
|
||||
if (!LauncherRuntimeIdentity.IsValidRid(rid))
|
||||
{
|
||||
throw new ArgumentException("RID is invalid.", nameof(rid));
|
||||
}
|
||||
|
||||
_rid = rid;
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(launcherTargetDirectory);
|
||||
_launcherTargetDirectory = Path.GetFullPath(launcherTargetDirectory);
|
||||
_hasRunningSessions = hasRunningSessions ?? (() => false);
|
||||
_downloader = new VerifiedArtifactDownloader(
|
||||
httpClient ?? throw new ArgumentNullException(nameof(httpClient)));
|
||||
_extractor = extractor ?? new SafeZipExtractor();
|
||||
}
|
||||
|
||||
public ClientVersionResolution CurrentClient => _versions.CachedResolution;
|
||||
|
||||
public Task<ClientVersionResolution> InitializeAsync(
|
||||
CancellationToken cancellationToken = default) =>
|
||||
_versions.LoadAndRecoverAsync(_rid, cancellationToken);
|
||||
|
||||
public async Task<LauncherUpdateCheckResult> CheckAsync(
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _operationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ReleaseManifest manifest = await _manifestClient.FetchAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
_ = manifest.RequireClient(_rid);
|
||||
_ = manifest.RequireLauncher(_rid);
|
||||
ClientVersionResolution installed = _versions.CachedResolution;
|
||||
LauncherVersion? installedVersion = installed.IsVerified
|
||||
? installed.Version
|
||||
: null;
|
||||
bool clientAvailable = installedVersion is null
|
||||
|| manifest.Version > installedVersion;
|
||||
bool launcherAvailable = manifest.Version > _launcherVersion;
|
||||
bool minimumSatisfied = _launcherVersion >= manifest.MinimumLauncherVersion;
|
||||
string status = BuildCheckStatus(
|
||||
manifest,
|
||||
installedVersion,
|
||||
clientAvailable,
|
||||
launcherAvailable,
|
||||
minimumSatisfied);
|
||||
return new LauncherUpdateCheckResult(
|
||||
manifest,
|
||||
_rid,
|
||||
_launcherVersion,
|
||||
installedVersion,
|
||||
clientAvailable,
|
||||
launcherAvailable,
|
||||
minimumSatisfied,
|
||||
status);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ClientVersionResolution> InstallClientAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(check);
|
||||
ValidateCheck(check);
|
||||
await _operationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
RefuseRunningSessions();
|
||||
using UpdateSessionBarrier.ExclusiveLease lease =
|
||||
_versions.Barrier.AcquireExclusive();
|
||||
RefuseRunningSessions();
|
||||
ClientVersionResolution current = await _versions
|
||||
.LoadAndRecoverUnderLeaseAsync(_rid, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (!check.IsLauncherMinimumSatisfied)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Client {check.Manifest.Version} requires launcher "
|
||||
+ $"{check.Manifest.MinimumLauncherVersion} or newer. "
|
||||
+ "Stage the launcher update first.");
|
||||
}
|
||||
|
||||
if (current.IsVerified
|
||||
&& current.Version is not null
|
||||
&& current.Version >= check.Manifest.Version)
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Completed,
|
||||
$"Client {current.Version} is already current.",
|
||||
1,
|
||||
1);
|
||||
return current;
|
||||
}
|
||||
|
||||
ReleaseArtifact artifact = check.Manifest.RequireClient(_rid);
|
||||
Guid transactionId = Guid.NewGuid();
|
||||
string staging = _versions.CreateClientStagingDirectory(transactionId);
|
||||
string archive = Path.Combine(
|
||||
_versions.AppDirectory,
|
||||
$".client-download-{transactionId:N}.zip");
|
||||
try
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.DownloadingClient,
|
||||
$"Downloading client {check.Manifest.Version}...",
|
||||
0,
|
||||
artifact.Size);
|
||||
var downloadProgress = new ForwardProgress<ArtifactDownloadProgress>(value =>
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.DownloadingClient,
|
||||
$"Downloading client {check.Manifest.Version}: "
|
||||
+ $"{value.BytesReceived:N0}/{value.TotalBytes:N0} bytes",
|
||||
value.BytesReceived,
|
||||
value.TotalBytes));
|
||||
_ = await _downloader.DownloadAsync(
|
||||
artifact,
|
||||
archive,
|
||||
downloadProgress,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.ExtractingClient,
|
||||
"Verifying paths and extracting the client archive...");
|
||||
IReadOnlyList<ExtractedFileRecord> files = await _extractor.ExtractAsync(
|
||||
archive,
|
||||
staging,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.ActivatingClient,
|
||||
$"Atomically activating client {check.Manifest.Version}...");
|
||||
ClientVersionResolution result = await _versions
|
||||
.PromoteAndActivateUnderLeaseAsync(
|
||||
staging,
|
||||
check.Manifest.Version,
|
||||
_rid,
|
||||
artifact,
|
||||
files,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Completed,
|
||||
$"Client {check.Manifest.Version} installed and activated.",
|
||||
1,
|
||||
1);
|
||||
return result;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Cancelled,
|
||||
"Client update cancelled; the active version was not changed.");
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Failed,
|
||||
$"Client update failed: {ex.Message}");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
VerifiedArtifactDownloader.TryDelete(archive);
|
||||
SafeZipExtractor.TryDeleteDirectory(staging);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<SelfUpdateStageResult> StageLauncherAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(check);
|
||||
ValidateCheck(check);
|
||||
await _operationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
RefuseRunningSessions();
|
||||
if (check.Manifest.Version <= _launcherVersion)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Launcher {_launcherVersion} is already current.");
|
||||
}
|
||||
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.DownloadingLauncher,
|
||||
$"Downloading launcher {check.Manifest.Version}...");
|
||||
var downloadProgress = new ForwardProgress<ArtifactDownloadProgress>(value =>
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.DownloadingLauncher,
|
||||
$"Downloading launcher {check.Manifest.Version}: "
|
||||
+ $"{value.BytesReceived:N0}/{value.TotalBytes:N0} bytes",
|
||||
value.BytesReceived,
|
||||
value.TotalBytes));
|
||||
try
|
||||
{
|
||||
SelfUpdateStageResult result = await _selfUpdates.StageAsync(
|
||||
check.Manifest,
|
||||
_rid,
|
||||
_launcherTargetDirectory,
|
||||
downloadProgress,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.StagingLauncher,
|
||||
result.Status,
|
||||
1,
|
||||
1);
|
||||
return result;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Cancelled,
|
||||
"Launcher update staging cancelled.");
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Failed,
|
||||
$"Launcher update staging failed: {ex.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ClientVersionResolution> RollbackClientAsync(
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _operationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
RefuseRunningSessions();
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.RollingBack,
|
||||
"Verifying and activating the previous client version...");
|
||||
ClientVersionResolution result = await _versions.RollbackAsync(
|
||||
_rid,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
Report(
|
||||
progress,
|
||||
LauncherUpdatePhase.Completed,
|
||||
$"Rolled back to client {result.Version}.",
|
||||
1,
|
||||
1);
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateCheck(LauncherUpdateCheckResult check)
|
||||
{
|
||||
if (!string.Equals(check.Rid, _rid, StringComparison.Ordinal)
|
||||
|| !check.LauncherVersion.Equals(_launcherVersion))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The update check belongs to a different launcher runtime.");
|
||||
}
|
||||
|
||||
_ = check.Manifest.RequireClient(_rid);
|
||||
_ = check.Manifest.RequireLauncher(_rid);
|
||||
}
|
||||
|
||||
private void RefuseRunningSessions()
|
||||
{
|
||||
if (_hasRunningSessions())
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"Stop every launcher session before installing or rolling back an update.");
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCheckStatus(
|
||||
ReleaseManifest manifest,
|
||||
LauncherVersion? installed,
|
||||
bool clientAvailable,
|
||||
bool launcherAvailable,
|
||||
bool minimumSatisfied)
|
||||
{
|
||||
if (!minimumSatisfied)
|
||||
{
|
||||
return $"Release {manifest.Version} requires launcher "
|
||||
+ $"{manifest.MinimumLauncherVersion} or newer.";
|
||||
}
|
||||
|
||||
if (clientAvailable && launcherAvailable)
|
||||
{
|
||||
return $"Client and launcher {manifest.Version} are available.";
|
||||
}
|
||||
|
||||
if (clientAvailable)
|
||||
{
|
||||
return installed is null
|
||||
? $"Client {manifest.Version} is available for installation."
|
||||
: $"Client update {installed} -> {manifest.Version} is available.";
|
||||
}
|
||||
|
||||
if (launcherAvailable)
|
||||
{
|
||||
return $"Launcher {manifest.Version} is available.";
|
||||
}
|
||||
|
||||
return "Client and launcher are up to date.";
|
||||
}
|
||||
|
||||
private static void Report(
|
||||
IProgress<LauncherUpdateProgress>? progress,
|
||||
LauncherUpdatePhase phase,
|
||||
string status,
|
||||
long completed = 0,
|
||||
long total = 0) =>
|
||||
progress?.Report(new LauncherUpdateProgress(
|
||||
phase,
|
||||
status,
|
||||
completed,
|
||||
total));
|
||||
|
||||
private sealed class ForwardProgress<T>(Action<T> callback) : IProgress<T>
|
||||
{
|
||||
public void Report(T value) => callback(value);
|
||||
}
|
||||
}
|
||||
199
src/AcDream.Launcher.Core/Updates/LauncherVersion.cs
Normal file
199
src/AcDream.Launcher.Core/Updates/LauncherVersion.cs
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
/// <summary>
|
||||
/// Strict SemVer 2.0 value used by the release feed, client pointer, and
|
||||
/// self-update plan. Numeric identifiers are compared as digit strings so a
|
||||
/// maliciously large identifier cannot overflow a fixed-width integer.
|
||||
/// </summary>
|
||||
public sealed class LauncherVersion : IComparable<LauncherVersion>, IEquatable<LauncherVersion>
|
||||
{
|
||||
private readonly string[] _core;
|
||||
private readonly string[] _preRelease;
|
||||
|
||||
private LauncherVersion(
|
||||
string value,
|
||||
string[] core,
|
||||
string[] preRelease)
|
||||
{
|
||||
Value = value;
|
||||
_core = core;
|
||||
_preRelease = preRelease;
|
||||
}
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
public bool IsPreRelease => _preRelease.Length != 0;
|
||||
|
||||
public static LauncherVersion Parse(string value)
|
||||
{
|
||||
if (!TryParse(value, out LauncherVersion? version))
|
||||
{
|
||||
throw new FormatException($"'{value}' is not a strict SemVer 2.0 version.");
|
||||
}
|
||||
|
||||
return version;
|
||||
}
|
||||
|
||||
public static bool TryParse(
|
||||
string? value,
|
||||
[NotNullWhen(true)] out LauncherVersion? version)
|
||||
{
|
||||
version = null;
|
||||
if (string.IsNullOrEmpty(value)
|
||||
|| value.Length > 128
|
||||
|| !string.Equals(value, value.Trim(), StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string precedence = value;
|
||||
int plus = value.IndexOf('+', StringComparison.Ordinal);
|
||||
if (plus >= 0)
|
||||
{
|
||||
if (plus == value.Length - 1
|
||||
|| value.IndexOf('+', plus + 1) >= 0
|
||||
|| !ValidIdentifiers(value[(plus + 1)..], numericLeadingZeroRule: false))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
precedence = value[..plus];
|
||||
}
|
||||
|
||||
string coreText = precedence;
|
||||
string[] preRelease = [];
|
||||
int dash = precedence.IndexOf('-', StringComparison.Ordinal);
|
||||
if (dash >= 0)
|
||||
{
|
||||
if (dash == precedence.Length - 1
|
||||
|| !ValidIdentifiers(precedence[(dash + 1)..], numericLeadingZeroRule: true))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
coreText = precedence[..dash];
|
||||
preRelease = precedence[(dash + 1)..].Split('.');
|
||||
}
|
||||
|
||||
string[] core = coreText.Split('.');
|
||||
if (core.Length != 3 || core.Any(part => !ValidCoreNumber(part)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
version = new LauncherVersion(value, core, preRelease);
|
||||
return true;
|
||||
}
|
||||
|
||||
public int CompareTo(LauncherVersion? other)
|
||||
{
|
||||
if (other is null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
for (int index = 0; index < _core.Length; index++)
|
||||
{
|
||||
int comparison = CompareNumeric(_core[index], other._core[index]);
|
||||
if (comparison != 0)
|
||||
{
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
if (_preRelease.Length == 0 || other._preRelease.Length == 0)
|
||||
{
|
||||
return _preRelease.Length == other._preRelease.Length
|
||||
? 0
|
||||
: _preRelease.Length == 0 ? 1 : -1;
|
||||
}
|
||||
|
||||
int shared = Math.Min(_preRelease.Length, other._preRelease.Length);
|
||||
for (int index = 0; index < shared; index++)
|
||||
{
|
||||
string left = _preRelease[index];
|
||||
string right = other._preRelease[index];
|
||||
bool leftNumeric = IsDigits(left);
|
||||
bool rightNumeric = IsDigits(right);
|
||||
int comparison = leftNumeric && rightNumeric
|
||||
? CompareNumeric(left, right)
|
||||
: leftNumeric != rightNumeric
|
||||
? leftNumeric ? -1 : 1
|
||||
: string.Compare(left, right, StringComparison.Ordinal);
|
||||
if (comparison != 0)
|
||||
{
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
|
||||
return _preRelease.Length.CompareTo(other._preRelease.Length);
|
||||
}
|
||||
|
||||
public bool Equals(LauncherVersion? other) =>
|
||||
other is not null && CompareTo(other) == 0;
|
||||
|
||||
public override bool Equals(object? obj) => Equals(obj as LauncherVersion);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = new HashCode();
|
||||
foreach (string part in _core)
|
||||
{
|
||||
hash.Add(part, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
hash.Add(_preRelease.Length);
|
||||
foreach (string part in _preRelease)
|
||||
{
|
||||
hash.Add(part, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
|
||||
public override string ToString() => Value;
|
||||
|
||||
public static bool operator >(LauncherVersion left, LauncherVersion right) =>
|
||||
left.CompareTo(right) > 0;
|
||||
|
||||
public static bool operator <(LauncherVersion left, LauncherVersion right) =>
|
||||
left.CompareTo(right) < 0;
|
||||
|
||||
public static bool operator >=(LauncherVersion left, LauncherVersion right) =>
|
||||
left.CompareTo(right) >= 0;
|
||||
|
||||
public static bool operator <=(LauncherVersion left, LauncherVersion right) =>
|
||||
left.CompareTo(right) <= 0;
|
||||
|
||||
private static bool ValidCoreNumber(string value) =>
|
||||
IsDigits(value) && (value.Length == 1 || value[0] != '0');
|
||||
|
||||
private static bool ValidIdentifiers(string value, bool numericLeadingZeroRule)
|
||||
{
|
||||
string[] identifiers = value.Split('.');
|
||||
return identifiers.All(identifier =>
|
||||
identifier.Length > 0
|
||||
&& identifier.All(character =>
|
||||
character is >= '0' and <= '9'
|
||||
or >= 'A' and <= 'Z'
|
||||
or >= 'a' and <= 'z'
|
||||
or '-')
|
||||
&& (!numericLeadingZeroRule
|
||||
|| !IsDigits(identifier)
|
||||
|| identifier.Length == 1
|
||||
|| identifier[0] != '0'));
|
||||
}
|
||||
|
||||
private static bool IsDigits(string value) =>
|
||||
value.Length > 0 && value.All(character => character is >= '0' and <= '9');
|
||||
|
||||
private static int CompareNumeric(string left, string right)
|
||||
{
|
||||
int length = left.Length.CompareTo(right.Length);
|
||||
return length != 0
|
||||
? length
|
||||
: string.Compare(left, right, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
38
src/AcDream.Launcher.Core/Updates/PortablePathRules.cs
Normal file
38
src/AcDream.Launcher.Core/Updates/PortablePathRules.cs
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
/// <summary>
|
||||
/// Host-independent path rules for payloads that must remain safe when moved
|
||||
/// between Linux and Windows. Windows device aliases are rejected on every
|
||||
/// host so a release cannot verify on one platform and become ambiguous on
|
||||
/// another.
|
||||
/// </summary>
|
||||
internal static class PortablePathRules
|
||||
{
|
||||
public static bool IsWindowsDeviceName(string segment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(segment);
|
||||
string stem = segment.Split('.')[0];
|
||||
if (stem.Equals("CON", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("PRN", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("AUX", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("NUL", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("CLOCK$", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("CONIN$", StringComparison.OrdinalIgnoreCase)
|
||||
|| stem.Equals("CONOUT$", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (stem.Length != 4
|
||||
|| (!stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase)
|
||||
&& !stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return stem[3] is >= '1' and <= '9'
|
||||
or '\u00b9'
|
||||
or '\u00b2'
|
||||
or '\u00b3';
|
||||
}
|
||||
}
|
||||
37
src/AcDream.Launcher.Core/Updates/ReleaseManifest.cs
Normal file
37
src/AcDream.Launcher.Core/Updates/ReleaseManifest.cs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public sealed record ReleaseArtifact(Uri Url, string Sha256, long Size);
|
||||
|
||||
public sealed record ReleaseManifest(
|
||||
LauncherVersion Version,
|
||||
LauncherVersion MinimumLauncherVersion,
|
||||
IReadOnlyDictionary<string, ReleaseArtifact> Clients,
|
||||
IReadOnlyDictionary<string, ReleaseArtifact> Launchers)
|
||||
{
|
||||
public const int CurrentSchemaVersion = 1;
|
||||
|
||||
public ReleaseArtifact RequireClient(string rid) =>
|
||||
Clients.TryGetValue(rid, out ReleaseArtifact? artifact)
|
||||
? artifact
|
||||
: throw new LauncherUpdateException(
|
||||
$"Release {Version} has no client payload for RID '{rid}'.");
|
||||
|
||||
public ReleaseArtifact RequireLauncher(string rid) =>
|
||||
Launchers.TryGetValue(rid, out ReleaseArtifact? artifact)
|
||||
? artifact
|
||||
: throw new LauncherUpdateException(
|
||||
$"Release {Version} has no launcher payload for RID '{rid}'.");
|
||||
}
|
||||
|
||||
public sealed class LauncherUpdateException : Exception
|
||||
{
|
||||
public LauncherUpdateException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public LauncherUpdateException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
407
src/AcDream.Launcher.Core/Updates/ReleaseManifestClient.cs
Normal file
407
src/AcDream.Launcher.Core/Updates/ReleaseManifestClient.cs
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public interface IReleaseManifestClient
|
||||
{
|
||||
Task<ReleaseManifest> FetchAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strict, bounded reader for the pinned GitHub Releases manifest. Production
|
||||
/// construction is HTTPS-only. The loopback HTTP allowance is available only
|
||||
/// through an internal fixture factory and is never inferred from a URI.
|
||||
/// Redirects are followed manually so every hop is checked before any bytes
|
||||
/// cross that hop.
|
||||
/// </summary>
|
||||
public sealed class ReleaseManifestClient : IReleaseManifestClient, IDisposable
|
||||
{
|
||||
public const string GitHubOwner = "eriknihlen";
|
||||
public const string GitHubRepository = "acdream";
|
||||
public const int MaximumManifestBytes = 1024 * 1024;
|
||||
public const long MaximumArtifactBytes = 4L * 1024 * 1024 * 1024;
|
||||
public const int MaximumRedirects = 5;
|
||||
|
||||
public static Uri ProductionManifestUri { get; } = new(
|
||||
$"https://github.com/{GitHubOwner}/{GitHubRepository}/releases/latest/download/manifest.json");
|
||||
|
||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = false,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
|
||||
MaxDepth = 16,
|
||||
};
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly Uri _manifestUri;
|
||||
private readonly bool _allowLoopbackHttp;
|
||||
|
||||
public ReleaseManifestClient(TimeSpan? timeout = null)
|
||||
: this(
|
||||
ProductionManifestUri,
|
||||
allowLoopbackHttp: false,
|
||||
CreateRedirectDisabledHandler(),
|
||||
timeout)
|
||||
{
|
||||
}
|
||||
|
||||
private ReleaseManifestClient(
|
||||
Uri manifestUri,
|
||||
bool allowLoopbackHttp,
|
||||
HttpMessageHandler handler,
|
||||
TimeSpan? timeout)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifestUri);
|
||||
ArgumentNullException.ThrowIfNull(handler);
|
||||
_manifestUri = manifestUri;
|
||||
_allowLoopbackHttp = allowLoopbackHttp;
|
||||
RequireTransport(_manifestUri, "manifest", _allowLoopbackHttp);
|
||||
_httpClient = new HttpClient(handler, disposeHandler: true)
|
||||
{
|
||||
Timeout = timeout ?? TimeSpan.FromSeconds(15),
|
||||
};
|
||||
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("acdream-launcher/1");
|
||||
}
|
||||
|
||||
internal static ReleaseManifestClient CreateLoopbackFixture(
|
||||
Uri manifestUri,
|
||||
TimeSpan? timeout = null) => new(
|
||||
manifestUri,
|
||||
allowLoopbackHttp: true,
|
||||
CreateRedirectDisabledHandler(),
|
||||
timeout);
|
||||
|
||||
internal static ReleaseManifestClient CreateForTransportTest(
|
||||
Uri manifestUri,
|
||||
bool allowLoopbackHttp,
|
||||
HttpMessageHandler handler) => new(
|
||||
manifestUri,
|
||||
allowLoopbackHttp,
|
||||
handler,
|
||||
TimeSpan.FromSeconds(15));
|
||||
|
||||
public async Task<ReleaseManifest> FetchAsync(
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
Uri current = _manifestUri;
|
||||
var visited = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (int redirectCount = 0;;)
|
||||
{
|
||||
RequireTransport(current, "manifest redirect", _allowLoopbackHttp);
|
||||
if (!visited.Add(current.AbsoluteUri))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The release manifest redirect chain contains a loop.");
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, current);
|
||||
using HttpResponseMessage response = await _httpClient.SendAsync(
|
||||
request,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (IsRedirect(response.StatusCode))
|
||||
{
|
||||
if (redirectCount >= MaximumRedirects)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release manifest exceeded {MaximumRedirects} redirects.");
|
||||
}
|
||||
|
||||
Uri? location = response.Headers.Location;
|
||||
if (location is null)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The release manifest redirect has no Location header.");
|
||||
}
|
||||
|
||||
Uri next = location.IsAbsoluteUri
|
||||
? location
|
||||
: new Uri(current, location);
|
||||
RequireTransport(next, "manifest redirect", _allowLoopbackHttp);
|
||||
current = next;
|
||||
redirectCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await ReadAndParseAsync(response, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (LauncherUpdateException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException
|
||||
or IOException
|
||||
or JsonException
|
||||
or NotSupportedException)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release manifest could not be loaded: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
internal static ReleaseManifest Parse(
|
||||
ReadOnlySpan<byte> utf8,
|
||||
bool allowLoopbackHttpArtifacts = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument document = JsonDocument.Parse(
|
||||
utf8.ToArray(),
|
||||
new JsonDocumentOptions
|
||||
{
|
||||
AllowTrailingCommas = false,
|
||||
CommentHandling = JsonCommentHandling.Disallow,
|
||||
MaxDepth = 16,
|
||||
});
|
||||
RejectDuplicateProperties(document.RootElement, "$" );
|
||||
ManifestDocument? value = document.RootElement.Deserialize<ManifestDocument>(
|
||||
SerializerOptions);
|
||||
return Validate(value, allowLoopbackHttpArtifacts);
|
||||
}
|
||||
catch (LauncherUpdateException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException
|
||||
or FormatException
|
||||
or InvalidOperationException)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release manifest is invalid: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _httpClient.Dispose();
|
||||
|
||||
internal static void RequireTransport(
|
||||
Uri uri,
|
||||
string description,
|
||||
bool allowLoopbackHttp)
|
||||
{
|
||||
if (!uri.IsAbsoluteUri
|
||||
|| (uri.Scheme != Uri.UriSchemeHttps
|
||||
&& !(allowLoopbackHttp
|
||||
&& uri.Scheme == Uri.UriSchemeHttp
|
||||
&& uri.IsLoopback)))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The {description} URI must use HTTPS"
|
||||
+ (allowLoopbackHttp ? " (or fixture-only loopback HTTP)." : "."));
|
||||
}
|
||||
}
|
||||
|
||||
internal static void RequireSecureOrLoopback(Uri uri, string description) =>
|
||||
RequireTransport(uri, description, allowLoopbackHttp: true);
|
||||
|
||||
private async Task<ReleaseManifest> ReadAndParseAsync(
|
||||
HttpResponseMessage response,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (response.Content.Headers.ContentLength is long contentLength
|
||||
&& contentLength > MaximumManifestBytes)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release manifest is larger than {MaximumManifestBytes} bytes.");
|
||||
}
|
||||
|
||||
await using Stream input = await response.Content
|
||||
.ReadAsStreamAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
using var output = new MemoryStream();
|
||||
byte[] buffer = new byte[16 * 1024];
|
||||
while (true)
|
||||
{
|
||||
int read = await input.ReadAsync(buffer, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (output.Length + read > MaximumManifestBytes)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release manifest is larger than {MaximumManifestBytes} bytes.");
|
||||
}
|
||||
|
||||
output.Write(buffer, 0, read);
|
||||
}
|
||||
|
||||
return Parse(output.ToArray(), _allowLoopbackHttp);
|
||||
}
|
||||
|
||||
private static ReleaseManifest Validate(
|
||||
ManifestDocument? document,
|
||||
bool allowLoopbackHttpArtifacts)
|
||||
{
|
||||
if (document is null)
|
||||
{
|
||||
throw new LauncherUpdateException("The release manifest is empty.");
|
||||
}
|
||||
|
||||
if (document.SchemaVersion != ReleaseManifest.CurrentSchemaVersion)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Release manifest schema version {document.SchemaVersion} is not supported.");
|
||||
}
|
||||
|
||||
LauncherVersion version = LauncherVersion.Parse(
|
||||
document.Version
|
||||
?? throw new LauncherUpdateException("The release version is missing."));
|
||||
LauncherVersion minimum = LauncherVersion.Parse(
|
||||
document.MinimumLauncherVersion
|
||||
?? throw new LauncherUpdateException(
|
||||
"The minimum launcher version is missing."));
|
||||
if (minimum > version)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The minimum launcher version cannot exceed the release version.");
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, ReleaseArtifact> clients = ValidateArtifacts(
|
||||
document.Clients,
|
||||
"clients",
|
||||
allowLoopbackHttpArtifacts);
|
||||
IReadOnlyDictionary<string, ReleaseArtifact> launchers = ValidateArtifacts(
|
||||
document.Launchers,
|
||||
"launchers",
|
||||
allowLoopbackHttpArtifacts);
|
||||
return new ReleaseManifest(version, minimum, clients, launchers);
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, ReleaseArtifact> ValidateArtifacts(
|
||||
Dictionary<string, ArtifactDocument>? artifacts,
|
||||
string field,
|
||||
bool allowLoopbackHttpArtifacts)
|
||||
{
|
||||
if (artifacts is null || artifacts.Count == 0)
|
||||
{
|
||||
throw new LauncherUpdateException($"Manifest field '{field}' must not be empty.");
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, ReleaseArtifact>(StringComparer.Ordinal);
|
||||
foreach ((string rid, ArtifactDocument value) in artifacts)
|
||||
{
|
||||
if (!LauncherRuntimeIdentity.IsValidRid(rid))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Manifest field '{field}' contains invalid RID '{rid}'.");
|
||||
}
|
||||
|
||||
if (value is null)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Manifest payload '{field}.{rid}' is null.");
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(value.Url, UriKind.Absolute, out Uri? uri))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Manifest payload '{field}.{rid}' has an invalid URL.");
|
||||
}
|
||||
|
||||
RequireTransport(
|
||||
uri,
|
||||
$"{field}.{rid} artifact",
|
||||
allowLoopbackHttpArtifacts);
|
||||
if (!IsSha256(value.Sha256))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Manifest payload '{field}.{rid}' has an invalid SHA-256 digest.");
|
||||
}
|
||||
|
||||
if (value.Size <= 0 || value.Size > MaximumArtifactBytes)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Manifest payload '{field}.{rid}' has an invalid size.");
|
||||
}
|
||||
|
||||
result.Add(
|
||||
rid,
|
||||
new ReleaseArtifact(uri, value.Sha256!.ToLowerInvariant(), value.Size));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static bool IsSha256(string? value) =>
|
||||
value is { Length: 64 } && value.All(Uri.IsHexDigit);
|
||||
|
||||
private static bool IsRedirect(HttpStatusCode statusCode) => statusCode is
|
||||
HttpStatusCode.MovedPermanently
|
||||
or HttpStatusCode.Found
|
||||
or HttpStatusCode.SeeOther
|
||||
or HttpStatusCode.TemporaryRedirect
|
||||
or HttpStatusCode.PermanentRedirect;
|
||||
|
||||
private static HttpMessageHandler CreateRedirectDisabledHandler() =>
|
||||
new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
UseCookies = false,
|
||||
AutomaticDecompression = DecompressionMethods.None,
|
||||
};
|
||||
|
||||
private static void RejectDuplicateProperties(JsonElement element, string path)
|
||||
{
|
||||
if (element.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (JsonProperty property in element.EnumerateObject())
|
||||
{
|
||||
if (!names.Add(property.Name))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Duplicate JSON property '{path}.{property.Name}' is not allowed.");
|
||||
}
|
||||
|
||||
RejectDuplicateProperties(property.Value, $"{path}.{property.Name}");
|
||||
}
|
||||
}
|
||||
else if (element.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
int index = 0;
|
||||
foreach (JsonElement item in element.EnumerateArray())
|
||||
{
|
||||
RejectDuplicateProperties(item, $"{path}[{index++}]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ManifestDocument
|
||||
{
|
||||
public int SchemaVersion { get; init; }
|
||||
|
||||
public string? Version { get; init; }
|
||||
|
||||
public string? MinimumLauncherVersion { get; init; }
|
||||
|
||||
public Dictionary<string, ArtifactDocument>? Clients { get; init; }
|
||||
|
||||
public Dictionary<string, ArtifactDocument>? Launchers { get; init; }
|
||||
}
|
||||
|
||||
private sealed class ArtifactDocument
|
||||
{
|
||||
public string? Url { get; init; }
|
||||
|
||||
public string? Sha256 { get; init; }
|
||||
|
||||
public long Size { get; init; }
|
||||
}
|
||||
}
|
||||
469
src/AcDream.Launcher.Core/Updates/SafeZipExtractor.cs
Normal file
469
src/AcDream.Launcher.Core/Updates/SafeZipExtractor.cs
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
using System.Buffers;
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public sealed record SafeZipExtractionLimits(
|
||||
int MaximumEntries = 20_000,
|
||||
long MaximumEntryBytes = 2L * 1024 * 1024 * 1024,
|
||||
long MaximumTotalBytes = 8L * 1024 * 1024 * 1024,
|
||||
double MaximumCompressionRatio = 200,
|
||||
int MaximumRelativePathLength = 512);
|
||||
|
||||
public sealed record ExtractedFileRecord(
|
||||
string Path,
|
||||
string Sha256,
|
||||
long Size,
|
||||
int UnixMode);
|
||||
|
||||
/// <summary>
|
||||
/// Portable ZIP extractor for release assets. The complete central-directory
|
||||
/// shape is validated before the first output path is created.
|
||||
/// </summary>
|
||||
public sealed class SafeZipExtractor
|
||||
{
|
||||
private const int BufferSize = 128 * 1024;
|
||||
private const int UnixTypeMask = 0xF000;
|
||||
private const int UnixRegularFile = 0x8000;
|
||||
private const int UnixDirectory = 0x4000;
|
||||
private const int UnixPermissionMask = 0x1FF;
|
||||
private readonly SafeZipExtractionLimits _limits;
|
||||
|
||||
public SafeZipExtractor(SafeZipExtractionLimits? limits = null)
|
||||
{
|
||||
_limits = limits ?? new SafeZipExtractionLimits();
|
||||
if (_limits.MaximumEntries <= 0
|
||||
|| _limits.MaximumEntryBytes <= 0
|
||||
|| _limits.MaximumTotalBytes <= 0
|
||||
|| _limits.MaximumCompressionRatio <= 0
|
||||
|| _limits.MaximumRelativePathLength <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(limits),
|
||||
"ZIP extraction limits must all be positive.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<ExtractedFileRecord>> ExtractAsync(
|
||||
string archivePath,
|
||||
string destinationDirectory,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(archivePath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(destinationDirectory);
|
||||
string archive = Path.GetFullPath(archivePath);
|
||||
string destination = Path.GetFullPath(destinationDirectory);
|
||||
|
||||
if (Directory.Exists(destination)
|
||||
&& Directory.EnumerateFileSystemEntries(destination).Any())
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The ZIP extraction destination must be empty.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using var stream = new FileStream(
|
||||
archive,
|
||||
FileMode.Open,
|
||||
FileAccess.Read,
|
||||
FileShare.Read,
|
||||
BufferSize,
|
||||
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: false);
|
||||
IReadOnlyList<ValidatedEntry> entries = ValidateArchive(zip);
|
||||
|
||||
Directory.CreateDirectory(destination);
|
||||
RejectReparsePoint(destination, "extraction root");
|
||||
foreach (string directory in entries
|
||||
.SelectMany(entry => ParentPaths(entry.RelativePath))
|
||||
.Concat(entries.Where(entry => entry.IsDirectory)
|
||||
.Select(entry => entry.RelativePath))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.OrderBy(path => path.Count(character => character == '/'))
|
||||
.ThenBy(path => path, StringComparer.Ordinal))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
string directoryPath = ResolveContained(destination, directory);
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
RejectReparsePoint(directoryPath, $"directory '{directory}'");
|
||||
}
|
||||
|
||||
var files = new List<ExtractedFileRecord>();
|
||||
long actualTotal = 0;
|
||||
foreach (ValidatedEntry entry in entries.Where(entry => !entry.IsDirectory))
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
string outputPath = ResolveContained(destination, entry.RelativePath);
|
||||
EnsureParentsAreDirectories(destination, entry.RelativePath);
|
||||
await using Stream input = entry.Entry.Open();
|
||||
await using var output = new FileStream(
|
||||
outputPath,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
BufferSize,
|
||||
FileOptions.Asynchronous
|
||||
| FileOptions.SequentialScan
|
||||
| FileOptions.WriteThrough);
|
||||
using IncrementalHash hash = IncrementalHash.CreateHash(
|
||||
HashAlgorithmName.SHA256);
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
|
||||
long actualEntry = 0;
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int read = await input.ReadAsync(
|
||||
buffer.AsMemory(0, BufferSize),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
actualEntry = checked(actualEntry + read);
|
||||
actualTotal = checked(actualTotal + read);
|
||||
if (actualEntry > entry.Entry.Length
|
||||
|| actualEntry > _limits.MaximumEntryBytes
|
||||
|| actualTotal > _limits.MaximumTotalBytes)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry '{entry.RelativePath}' exceeded its declared limits.");
|
||||
}
|
||||
|
||||
hash.AppendData(buffer, 0, read);
|
||||
await output.WriteAsync(
|
||||
buffer.AsMemory(0, read),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
output.Flush(flushToDisk: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
|
||||
}
|
||||
|
||||
if (actualEntry != entry.Entry.Length)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry '{entry.RelativePath}' length changed while extracting.");
|
||||
}
|
||||
|
||||
int unixMode = entry.UnixMode & UnixPermissionMask;
|
||||
if (OperatingSystem.IsLinux() && unixMode != 0)
|
||||
{
|
||||
File.SetUnixFileMode(outputPath, (UnixFileMode)unixMode);
|
||||
}
|
||||
|
||||
files.Add(new ExtractedFileRecord(
|
||||
entry.RelativePath,
|
||||
Convert.ToHexStringLower(hash.GetHashAndReset()),
|
||||
actualEntry,
|
||||
unixMode));
|
||||
}
|
||||
|
||||
files.Sort((left, right) => string.Compare(
|
||||
left.Path,
|
||||
right.Path,
|
||||
StringComparison.Ordinal));
|
||||
return files;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
TryDeleteDirectory(destination);
|
||||
throw;
|
||||
}
|
||||
catch (LauncherUpdateException)
|
||||
{
|
||||
TryDeleteDirectory(destination);
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException
|
||||
or UnauthorizedAccessException
|
||||
or InvalidDataException
|
||||
or NotSupportedException
|
||||
or CryptographicException)
|
||||
{
|
||||
TryDeleteDirectory(destination);
|
||||
throw new LauncherUpdateException(
|
||||
$"The release ZIP could not be extracted safely: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<ValidatedEntry> ValidateArchive(ZipArchive zip)
|
||||
{
|
||||
if (zip.Entries.Count == 0 || zip.Entries.Count > _limits.MaximumEntries)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry count {zip.Entries.Count} is outside the allowed range.");
|
||||
}
|
||||
|
||||
var result = new List<ValidatedEntry>(zip.Entries.Count);
|
||||
var explicitEntries = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var nodes = new Dictionary<string, PathNode>(StringComparer.OrdinalIgnoreCase);
|
||||
long totalLength = 0;
|
||||
long totalCompressed = 0;
|
||||
foreach (ZipArchiveEntry entry in zip.Entries)
|
||||
{
|
||||
string relative = NormalizeEntryPath(entry.FullName);
|
||||
if (!explicitEntries.Add(relative))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP contains a duplicate/case-colliding entry '{relative}'.");
|
||||
}
|
||||
|
||||
int unixAttributes = entry.ExternalAttributes >> 16;
|
||||
int unixType = unixAttributes & UnixTypeMask;
|
||||
bool trailingDirectory = entry.FullName.EndsWith("/", StringComparison.Ordinal)
|
||||
|| entry.FullName.EndsWith("\\", StringComparison.Ordinal);
|
||||
bool isDirectory = trailingDirectory || unixType == UnixDirectory;
|
||||
if ((entry.ExternalAttributes & (int)FileAttributes.ReparsePoint) != 0
|
||||
|| unixType is not (0 or UnixRegularFile or UnixDirectory)
|
||||
|| (unixType == UnixDirectory && !trailingDirectory)
|
||||
|| (isDirectory && (entry.Length != 0 || entry.CompressedLength != 0)))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry '{relative}' is a symlink, reparse point, or unsupported type.");
|
||||
}
|
||||
|
||||
AddPathNodes(nodes, relative, isDirectory);
|
||||
if (!isDirectory)
|
||||
{
|
||||
if (entry.Length < 0
|
||||
|| entry.CompressedLength < 0
|
||||
|| entry.Length > _limits.MaximumEntryBytes)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry '{relative}' exceeds the per-file limit.");
|
||||
}
|
||||
|
||||
totalLength = checked(totalLength + entry.Length);
|
||||
totalCompressed = checked(totalCompressed + entry.CompressedLength);
|
||||
if (totalLength > _limits.MaximumTotalBytes
|
||||
|| IsRatioExceeded(entry.Length, entry.CompressedLength))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP entry '{relative}' exceeds extraction size/ratio limits.");
|
||||
}
|
||||
}
|
||||
|
||||
result.Add(new ValidatedEntry(entry, relative, isDirectory, unixAttributes));
|
||||
}
|
||||
|
||||
if (totalLength > 0
|
||||
&& (totalCompressed == 0 || IsRatioExceeded(totalLength, totalCompressed)))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"ZIP aggregate compression ratio exceeds the allowed limit.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private string NormalizeEntryPath(string name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)
|
||||
|| name.IndexOf('\0') >= 0
|
||||
|| name.Contains(':', StringComparison.Ordinal))
|
||||
{
|
||||
throw new LauncherUpdateException("ZIP contains an empty, NUL, or ADS path.");
|
||||
}
|
||||
|
||||
string normalized = name.Replace('\\', '/');
|
||||
bool directory = normalized.EndsWith("/", StringComparison.Ordinal);
|
||||
normalized = normalized.TrimEnd('/');
|
||||
if (normalized.Length == 0
|
||||
|| normalized.Length > _limits.MaximumRelativePathLength
|
||||
|| normalized.StartsWith("/", StringComparison.Ordinal)
|
||||
|| Path.IsPathRooted(normalized))
|
||||
{
|
||||
throw new LauncherUpdateException($"ZIP path '{name}' is rooted or too long.");
|
||||
}
|
||||
|
||||
string[] segments = normalized.Split('/');
|
||||
foreach (string segment in segments)
|
||||
{
|
||||
if (segment.Length == 0
|
||||
|| segment is "." or ".."
|
||||
|| segment.EndsWith(' ')
|
||||
|| segment.EndsWith('.')
|
||||
|| segment.Any(character =>
|
||||
char.IsControl(character)
|
||||
|| character is '<' or '>' or '"' or '|' or '?' or '*')
|
||||
|| PortablePathRules.IsWindowsDeviceName(segment))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP path '{name}' contains an unsafe segment.");
|
||||
}
|
||||
}
|
||||
|
||||
return string.Join('/', segments) + (directory ? "/" : string.Empty);
|
||||
}
|
||||
|
||||
private static void AddPathNodes(
|
||||
Dictionary<string, PathNode> nodes,
|
||||
string relative,
|
||||
bool isDirectory)
|
||||
{
|
||||
string path = relative.TrimEnd('/');
|
||||
string[] segments = path.Split('/');
|
||||
string current = string.Empty;
|
||||
for (int index = 0; index < segments.Length; index++)
|
||||
{
|
||||
current = current.Length == 0
|
||||
? segments[index]
|
||||
: current + "/" + segments[index];
|
||||
bool nodeIsDirectory = index < segments.Length - 1 || isDirectory;
|
||||
if (nodes.TryGetValue(current, out PathNode? existing))
|
||||
{
|
||||
if (!string.Equals(existing.Spelling, current, StringComparison.Ordinal)
|
||||
|| (!existing.IsDirectory || !nodeIsDirectory))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP path '{relative}' collides with '{existing.Spelling}'.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
nodes.Add(current, new PathNode(current, nodeIsDirectory));
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsRatioExceeded(long expanded, long compressed) =>
|
||||
expanded > 0
|
||||
&& (compressed <= 0 || expanded / (double)compressed > _limits.MaximumCompressionRatio);
|
||||
|
||||
private static IEnumerable<string> ParentPaths(string relative)
|
||||
{
|
||||
string path = relative.TrimEnd('/');
|
||||
int slash = path.IndexOf('/');
|
||||
while (slash >= 0)
|
||||
{
|
||||
yield return path[..slash];
|
||||
slash = path.IndexOf('/', slash + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveContained(string root, string relative)
|
||||
{
|
||||
string path = Path.GetFullPath(
|
||||
Path.Combine(root, relative.TrimEnd('/').Replace('/', Path.DirectorySeparatorChar)));
|
||||
string prefix = Path.EndsInDirectorySeparator(root)
|
||||
? root
|
||||
: root + Path.DirectorySeparatorChar;
|
||||
if (!path.StartsWith(
|
||||
prefix,
|
||||
OperatingSystem.IsWindows()
|
||||
? StringComparison.OrdinalIgnoreCase
|
||||
: StringComparison.Ordinal))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP path '{relative}' escaped the extraction directory.");
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void EnsureParentsAreDirectories(string root, string relative)
|
||||
{
|
||||
foreach (string parent in ParentPaths(relative))
|
||||
{
|
||||
string path = ResolveContained(root, parent);
|
||||
if (!Directory.Exists(path))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"ZIP parent '{parent}' is not a directory.");
|
||||
}
|
||||
|
||||
RejectReparsePoint(path, $"directory '{parent}'");
|
||||
}
|
||||
}
|
||||
|
||||
private static void RejectReparsePoint(string path, string description)
|
||||
{
|
||||
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The {description} is a reparse point.");
|
||||
}
|
||||
}
|
||||
|
||||
internal static void TryDeleteDirectory(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
{
|
||||
DeleteDirectoryWithoutFollowingReparsePoints(path);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The exact random staging name is reclaimed under the update lease.
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteDirectoryWithoutFollowingReparsePoints(string directory)
|
||||
{
|
||||
FileAttributes rootAttributes = File.GetAttributes(directory);
|
||||
if ((rootAttributes & FileAttributes.ReparsePoint) != 0)
|
||||
{
|
||||
DeleteReparsePoint(directory);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (string entry in Directory.EnumerateFileSystemEntries(
|
||||
directory,
|
||||
"*",
|
||||
SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
FileAttributes attributes = File.GetAttributes(entry);
|
||||
if ((attributes & FileAttributes.ReparsePoint) != 0)
|
||||
{
|
||||
DeleteReparsePoint(entry);
|
||||
}
|
||||
else if ((attributes & FileAttributes.Directory) != 0)
|
||||
{
|
||||
DeleteDirectoryWithoutFollowingReparsePoints(entry);
|
||||
}
|
||||
else
|
||||
{
|
||||
File.Delete(entry);
|
||||
}
|
||||
}
|
||||
|
||||
Directory.Delete(directory, recursive: false);
|
||||
}
|
||||
|
||||
private static void DeleteReparsePoint(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
Directory.Delete(path, recursive: false);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
Directory.Delete(path, recursive: false);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record PathNode(string Spelling, bool IsDirectory);
|
||||
|
||||
private sealed record ValidatedEntry(
|
||||
ZipArchiveEntry Entry,
|
||||
string RelativePath,
|
||||
bool IsDirectory,
|
||||
int UnixMode);
|
||||
}
|
||||
140
src/AcDream.Launcher.Core/Updates/UpdateSessionBarrier.cs
Normal file
140
src/AcDream.Launcher.Core/Updates/UpdateSessionBarrier.cs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
/// <summary>
|
||||
/// One portable OS-handle barrier shared by supervised sessions and held
|
||||
/// exclusively by update/rollback/recovery transactions. File contents are
|
||||
/// never authoritative.
|
||||
/// </summary>
|
||||
public sealed class UpdateSessionBarrier
|
||||
{
|
||||
public const string LockFileName = ".update-session.lock";
|
||||
|
||||
private readonly string _lockPath;
|
||||
|
||||
public UpdateSessionBarrier(string dataDirectory)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
|
||||
_lockPath = Path.Combine(
|
||||
Path.GetFullPath(dataDirectory),
|
||||
"app",
|
||||
LockFileName);
|
||||
}
|
||||
|
||||
public string LockPath => _lockPath;
|
||||
|
||||
public SessionLease AcquireSession()
|
||||
{
|
||||
FileStream stream = Open(FileShare.ReadWrite, "A client update is in progress.");
|
||||
return new SessionLease(stream);
|
||||
}
|
||||
|
||||
public ExclusiveLease AcquireExclusive()
|
||||
{
|
||||
FileStream stream = Open(
|
||||
FileShare.None,
|
||||
"A launcher session or another update transaction is running. "
|
||||
+ "Stop every launcher session before updating.");
|
||||
return new ExclusiveLease(this, stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Non-blocking startup probe. Contention is an expected "not now"
|
||||
/// result; permission and path failures remain hard errors.
|
||||
/// </summary>
|
||||
public bool TryAcquireExclusive(out ExclusiveLease? lease)
|
||||
{
|
||||
Directory.CreateDirectory(
|
||||
Path.GetDirectoryName(_lockPath)
|
||||
?? throw new InvalidOperationException(
|
||||
"The update/session lock path has no parent directory."));
|
||||
try
|
||||
{
|
||||
lease = new ExclusiveLease(
|
||||
this,
|
||||
new FileStream(
|
||||
_lockPath,
|
||||
FileMode.OpenOrCreate,
|
||||
FileAccess.ReadWrite,
|
||||
FileShare.None,
|
||||
bufferSize: 1,
|
||||
FileOptions.None));
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
lease = null;
|
||||
return false;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The update/session lease could not be opened: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
internal void RequireOwned(ExclusiveLease lease)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(lease);
|
||||
if (!lease.IsHeldBy(this))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The cleanup operation does not hold this update barrier's exclusive lease.");
|
||||
}
|
||||
}
|
||||
|
||||
private FileStream Open(FileShare share, string refusal)
|
||||
{
|
||||
Directory.CreateDirectory(
|
||||
Path.GetDirectoryName(_lockPath)
|
||||
?? throw new InvalidOperationException(
|
||||
"The update/session lock path has no parent directory."));
|
||||
try
|
||||
{
|
||||
return new FileStream(
|
||||
_lockPath,
|
||||
FileMode.OpenOrCreate,
|
||||
FileAccess.ReadWrite,
|
||||
share,
|
||||
bufferSize: 1,
|
||||
FileOptions.None);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new LauncherUpdateException(refusal, ex);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The update/session lease could not be opened: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SessionLease : IDisposable
|
||||
{
|
||||
private FileStream? _stream;
|
||||
|
||||
internal SessionLease(FileStream stream) => _stream = stream;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _stream, null)?.Dispose();
|
||||
}
|
||||
|
||||
public sealed class ExclusiveLease : IDisposable
|
||||
{
|
||||
private readonly UpdateSessionBarrier _owner;
|
||||
private FileStream? _stream;
|
||||
|
||||
internal ExclusiveLease(UpdateSessionBarrier owner, FileStream stream)
|
||||
{
|
||||
_owner = owner;
|
||||
_stream = stream;
|
||||
}
|
||||
|
||||
internal bool IsHeldBy(UpdateSessionBarrier owner) =>
|
||||
ReferenceEquals(_owner, owner)
|
||||
&& Volatile.Read(ref _stream) is not null;
|
||||
|
||||
public void Dispose() => Interlocked.Exchange(ref _stream, null)?.Dispose();
|
||||
}
|
||||
}
|
||||
277
src/AcDream.Launcher.Core/Updates/VerifiedArtifactDownloader.cs
Normal file
277
src/AcDream.Launcher.Core/Updates/VerifiedArtifactDownloader.cs
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace AcDream.Launcher.Core.Updates;
|
||||
|
||||
public sealed record ArtifactDownloadProgress(long BytesReceived, long TotalBytes)
|
||||
{
|
||||
public double Percent => TotalBytes <= 0
|
||||
? 0
|
||||
: Math.Clamp(BytesReceived * 100d / TotalBytes, 0, 100);
|
||||
}
|
||||
|
||||
public sealed record VerifiedArtifactDownload(
|
||||
string FilePath,
|
||||
long Size,
|
||||
string Sha256);
|
||||
|
||||
/// <summary>
|
||||
/// Streams a bounded release asset directly to a caller-owned staging path,
|
||||
/// computing SHA-256 during the write. A partial/cancelled/wrong artifact is
|
||||
/// deleted before the call returns.
|
||||
/// </summary>
|
||||
public sealed class VerifiedArtifactDownloader
|
||||
{
|
||||
private const int BufferSize = 128 * 1024;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
public VerifiedArtifactDownloader(HttpClient httpClient)
|
||||
{
|
||||
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
public async Task<VerifiedArtifactDownload> DownloadAsync(
|
||||
ReleaseArtifact artifact,
|
||||
string destinationPath,
|
||||
IProgress<ArtifactDownloadProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(artifact);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(destinationPath);
|
||||
ReleaseManifestClient.RequireSecureOrLoopback(artifact.Url, "artifact");
|
||||
if (artifact.Size <= 0
|
||||
|| artifact.Size > ReleaseManifestClient.MaximumArtifactBytes
|
||||
|| !ReleaseManifestClient.IsSha256(artifact.Sha256))
|
||||
{
|
||||
throw new LauncherUpdateException("The requested artifact metadata is invalid.");
|
||||
}
|
||||
|
||||
string fullPath = Path.GetFullPath(destinationPath);
|
||||
Directory.CreateDirectory(
|
||||
Path.GetDirectoryName(fullPath)
|
||||
?? throw new InvalidOperationException(
|
||||
"The artifact staging path has no parent directory."));
|
||||
|
||||
bool ownsDestination = false;
|
||||
try
|
||||
{
|
||||
using HttpResponseMessage response = await SendWithValidatedRedirectsAsync(
|
||||
artifact.Url,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.Content.Headers.ContentLength is long contentLength
|
||||
&& contentLength != artifact.Size)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Artifact size header mismatch: expected {artifact.Size}, "
|
||||
+ $"received {contentLength}.");
|
||||
}
|
||||
|
||||
if (response.Content.Headers.ContentEncoding.Count != 0)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"Release artifact content encoding is not allowed.");
|
||||
}
|
||||
|
||||
await using Stream input = await response.Content
|
||||
.ReadAsStreamAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await using var output = new FileStream(
|
||||
fullPath,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
BufferSize,
|
||||
FileOptions.Asynchronous
|
||||
| FileOptions.SequentialScan
|
||||
| FileOptions.WriteThrough);
|
||||
ownsDestination = true;
|
||||
using IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
|
||||
long received = 0;
|
||||
try
|
||||
{
|
||||
progress?.Report(new ArtifactDownloadProgress(0, artifact.Size));
|
||||
while (true)
|
||||
{
|
||||
int read = await input.ReadAsync(
|
||||
buffer.AsMemory(0, BufferSize),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
received = checked(received + read);
|
||||
if (received > artifact.Size)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Artifact exceeded its declared size of {artifact.Size} bytes.");
|
||||
}
|
||||
|
||||
hash.AppendData(buffer, 0, read);
|
||||
await output.WriteAsync(
|
||||
buffer.AsMemory(0, read),
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
progress?.Report(new ArtifactDownloadProgress(received, artifact.Size));
|
||||
}
|
||||
|
||||
await output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
output.Flush(flushToDisk: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
|
||||
}
|
||||
|
||||
if (received != artifact.Size)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"Artifact ended at {received} bytes; expected {artifact.Size}.");
|
||||
}
|
||||
|
||||
string actualSha256 = Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
if (!string.Equals(
|
||||
actualSha256,
|
||||
artifact.Sha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"Artifact SHA-256 does not match the release manifest.");
|
||||
}
|
||||
|
||||
return new VerifiedArtifactDownload(fullPath, received, actualSha256);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (ownsDestination)
|
||||
{
|
||||
TryDelete(fullPath);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (LauncherUpdateException)
|
||||
{
|
||||
if (ownsDestination)
|
||||
{
|
||||
TryDelete(fullPath);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException
|
||||
or IOException
|
||||
or UnauthorizedAccessException
|
||||
or CryptographicException)
|
||||
{
|
||||
if (ownsDestination)
|
||||
{
|
||||
TryDelete(fullPath);
|
||||
}
|
||||
|
||||
throw new LauncherUpdateException(
|
||||
$"The release artifact could not be downloaded: {ex.Message}",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> SendWithValidatedRedirectsAsync(
|
||||
Uri initialUri,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
bool allowLoopbackHttp = initialUri.Scheme == Uri.UriSchemeHttp
|
||||
&& initialUri.IsLoopback;
|
||||
Uri current = initialUri;
|
||||
var visited = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (int redirectCount = 0;;)
|
||||
{
|
||||
ReleaseManifestClient.RequireTransport(
|
||||
current,
|
||||
"artifact redirect",
|
||||
allowLoopbackHttp);
|
||||
if (!visited.Add(current.AbsoluteUri))
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The release artifact redirect chain contains a loop.");
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, current);
|
||||
HttpResponseMessage response = await _httpClient.SendAsync(
|
||||
request,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
Uri effectiveUri = response.RequestMessage?.RequestUri ?? current;
|
||||
if (!Uri.Equals(effectiveUri, current))
|
||||
{
|
||||
response.Dispose();
|
||||
throw new LauncherUpdateException(
|
||||
"The artifact HTTP transport followed an automatic redirect; "
|
||||
+ "every redirect must be validated before it is requested.");
|
||||
}
|
||||
|
||||
if (!IsRedirect(response.StatusCode))
|
||||
{
|
||||
return response;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (redirectCount >= ReleaseManifestClient.MaximumRedirects)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
$"The release artifact exceeded "
|
||||
+ $"{ReleaseManifestClient.MaximumRedirects} redirects.");
|
||||
}
|
||||
|
||||
Uri? location = response.Headers.Location;
|
||||
if (location is null)
|
||||
{
|
||||
throw new LauncherUpdateException(
|
||||
"The release artifact redirect has no Location header.");
|
||||
}
|
||||
|
||||
Uri next = location.IsAbsoluteUri
|
||||
? location
|
||||
: new Uri(current, location);
|
||||
ReleaseManifestClient.RequireTransport(
|
||||
next,
|
||||
"artifact redirect",
|
||||
allowLoopbackHttp);
|
||||
current = next;
|
||||
redirectCount++;
|
||||
}
|
||||
finally
|
||||
{
|
||||
response.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsRedirect(HttpStatusCode statusCode) => statusCode is
|
||||
HttpStatusCode.MovedPermanently
|
||||
or HttpStatusCode.Found
|
||||
or HttpStatusCode.SeeOther
|
||||
or HttpStatusCode.TemporaryRedirect
|
||||
or HttpStatusCode.PermanentRedirect;
|
||||
|
||||
internal static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// The exact random staging name is reclaimed by startup recovery.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,10 @@
|
|||
<PublishBakeTool Condition="'$(PublishBakeTool)' == ''">true</PublishBakeTool>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="AcDream.Launcher.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="12.1.1" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="12.1.1" />
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
using System.Reflection;
|
||||
using AcDream.Launcher.Core.Installation;
|
||||
using AcDream.Launcher.Core.Launching;
|
||||
using AcDream.Launcher.Core.Orchestration;
|
||||
using AcDream.Launcher.Core.Profiles;
|
||||
using AcDream.Launcher.Core.Updates;
|
||||
using AcDream.Launcher.ViewModels;
|
||||
using AcDream.Platform;
|
||||
using Avalonia;
|
||||
|
|
@ -14,6 +16,7 @@ public sealed partial class App : Application
|
|||
{
|
||||
private LauncherOrchestrator? _orchestrator;
|
||||
private LauncherWindowViewModel? _viewModel;
|
||||
private LauncherUpdateComposition? _updateComposition;
|
||||
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
|
|
@ -23,6 +26,7 @@ public sealed partial class App : Application
|
|||
{
|
||||
ApplicationPathSet paths = ApplicationPathSet.Resolve();
|
||||
LauncherProfileStore profiles = LauncherProfileStore.ForApplicationPaths(paths);
|
||||
string rid = LauncherRuntimeIdentity.DetectRid();
|
||||
string executableSuffix = OperatingSystem.IsWindows() ? ".exe" : string.Empty;
|
||||
var installer = new LauncherInstaller(
|
||||
paths,
|
||||
|
|
@ -47,16 +51,27 @@ public sealed partial class App : Application
|
|||
$"Client content verification failed: {ex.Message}");
|
||||
}
|
||||
|
||||
LauncherUpdateComposition updates = LauncherUpdateComposition.Create(
|
||||
paths,
|
||||
rid,
|
||||
GetLauncherVersion(),
|
||||
AppContext.BaseDirectory,
|
||||
() => _orchestrator?.GetSnapshot().Sessions.Any(session => session.IsActive)
|
||||
== true);
|
||||
_updateComposition = updates;
|
||||
|
||||
_orchestrator = new LauncherOrchestrator(
|
||||
profiles,
|
||||
paths,
|
||||
LauncherExecutableSet.FromDirectory(AppContext.BaseDirectory),
|
||||
updates.Executables,
|
||||
verification.Record,
|
||||
installationStatus: verification.Status);
|
||||
installationStatus: verification.Status,
|
||||
updateSessionBarrier: updates.Versions.Barrier);
|
||||
_viewModel = new LauncherWindowViewModel(
|
||||
_orchestrator,
|
||||
new AvaloniaUiDispatcher(),
|
||||
installer);
|
||||
installer,
|
||||
updates.Updater);
|
||||
_viewModel.Initialize();
|
||||
|
||||
desktop.MainWindow = new MainWindow
|
||||
|
|
@ -73,7 +88,23 @@ public sealed partial class App : Application
|
|||
{
|
||||
_viewModel?.Dispose();
|
||||
_orchestrator?.Dispose();
|
||||
_updateComposition?.Dispose();
|
||||
_viewModel = null;
|
||||
_orchestrator = null;
|
||||
_updateComposition = null;
|
||||
}
|
||||
|
||||
private static LauncherVersion GetLauncherVersion()
|
||||
{
|
||||
string? informationalVersion = typeof(App).Assembly
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
|
||||
.InformationalVersion;
|
||||
if (!LauncherVersion.TryParse(informationalVersion, out LauncherVersion? version))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Launcher informational version '{informationalVersion}' is not SemVer 2.0.");
|
||||
}
|
||||
|
||||
return version;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
128
src/AcDream.Launcher/LauncherUpdateComposition.cs
Normal file
128
src/AcDream.Launcher/LauncherUpdateComposition.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System.Net;
|
||||
using System.Security;
|
||||
using System.Text.Json;
|
||||
using AcDream.Launcher.Core.Orchestration;
|
||||
using AcDream.Launcher.Core.Updates;
|
||||
using AcDream.Launcher.ViewModels;
|
||||
using AcDream.Platform;
|
||||
|
||||
namespace AcDream.Launcher;
|
||||
|
||||
/// <summary>
|
||||
/// Testable startup transaction for versioned-client/update services. Storage
|
||||
/// failures produce a fail-closed executable resolver and an unavailable UI
|
||||
/// projection; they do not abort profile/installer window construction.
|
||||
/// </summary>
|
||||
internal sealed class LauncherUpdateComposition : IDisposable
|
||||
{
|
||||
private readonly HttpClient? _artifactClient;
|
||||
private readonly ReleaseManifestClient? _manifestClient;
|
||||
|
||||
private LauncherUpdateComposition(
|
||||
ClientVersionStore versions,
|
||||
LauncherExecutableSet executables,
|
||||
ILauncherUpdater updater,
|
||||
HttpClient? artifactClient,
|
||||
ReleaseManifestClient? manifestClient)
|
||||
{
|
||||
Versions = versions;
|
||||
Executables = executables;
|
||||
Updater = updater;
|
||||
_artifactClient = artifactClient;
|
||||
_manifestClient = manifestClient;
|
||||
}
|
||||
|
||||
public ClientVersionStore Versions { get; }
|
||||
|
||||
public LauncherExecutableSet Executables { get; }
|
||||
|
||||
public ILauncherUpdater Updater { get; }
|
||||
|
||||
public static LauncherUpdateComposition Create(
|
||||
ApplicationPathSet paths,
|
||||
string rid,
|
||||
LauncherVersion launcherVersion,
|
||||
string launcherTargetDirectory,
|
||||
Func<bool> hasRunningSessions,
|
||||
Func<ClientVersionStore, string, ClientVersionResolution>? initialize = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(paths);
|
||||
ArgumentNullException.ThrowIfNull(launcherVersion);
|
||||
ArgumentNullException.ThrowIfNull(hasRunningSessions);
|
||||
var versions = new ClientVersionStore(paths);
|
||||
HttpClient? artifactClient = null;
|
||||
ReleaseManifestClient? manifestClient = null;
|
||||
try
|
||||
{
|
||||
_ = initialize is null
|
||||
? versions.LoadAndRecoverAsync(rid).GetAwaiter().GetResult()
|
||||
: initialize(versions, rid);
|
||||
artifactClient = new HttpClient(
|
||||
new HttpClientHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
UseCookies = false,
|
||||
AutomaticDecompression = DecompressionMethods.None,
|
||||
},
|
||||
disposeHandler: true)
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(15),
|
||||
};
|
||||
artifactClient.DefaultRequestHeaders.UserAgent.ParseAdd("acdream-launcher/1");
|
||||
manifestClient = new ReleaseManifestClient(TimeSpan.FromSeconds(15));
|
||||
var selfUpdates = new LauncherSelfUpdateManager(paths, artifactClient);
|
||||
var updater = new LauncherUpdater(
|
||||
manifestClient,
|
||||
artifactClient,
|
||||
versions,
|
||||
selfUpdates,
|
||||
launcherVersion,
|
||||
rid,
|
||||
launcherTargetDirectory,
|
||||
hasRunningSessions);
|
||||
return new LauncherUpdateComposition(
|
||||
versions,
|
||||
LauncherExecutableSet.FromCurrentVersionStore(versions),
|
||||
updater,
|
||||
artifactClient,
|
||||
manifestClient);
|
||||
}
|
||||
catch (Exception ex) when (IsStorageFailure(ex))
|
||||
{
|
||||
manifestClient?.Dispose();
|
||||
artifactClient?.Dispose();
|
||||
string status = "Versioned client update storage is unavailable: "
|
||||
+ (string.IsNullOrWhiteSpace(ex.Message)
|
||||
? "the storage operation failed."
|
||||
: ex.Message);
|
||||
var resolution = new ClientVersionResolution(
|
||||
ClientVersionState.Invalid,
|
||||
status,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
return new LauncherUpdateComposition(
|
||||
versions,
|
||||
LauncherExecutableSet.Unavailable(status),
|
||||
new UnavailableLauncherUpdater(status, resolution),
|
||||
artifactClient: null,
|
||||
manifestClient: null);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_manifestClient?.Dispose();
|
||||
_artifactClient?.Dispose();
|
||||
}
|
||||
|
||||
private static bool IsStorageFailure(Exception exception) => exception is
|
||||
IOException
|
||||
or UnauthorizedAccessException
|
||||
or SecurityException
|
||||
or JsonException
|
||||
or FormatException
|
||||
or NotSupportedException
|
||||
or LauncherUpdateException;
|
||||
}
|
||||
|
|
@ -45,7 +45,7 @@
|
|||
<Button Content="First-run setup"
|
||||
Command="{Binding FirstRunWizardShell.OpenCommand}" />
|
||||
<Button Content="Check for updates"
|
||||
Command="{Binding UpdatePromptShell.OpenCommand}" />
|
||||
Command="{Binding UpdatePrompt.OpenCommand}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
|
@ -434,21 +434,72 @@
|
|||
KeyboardNavigation.TabNavigation="Cycle"
|
||||
KeyDown="OnModalKeyDown"
|
||||
AutomationProperties.Name="Update prompt modal dialog"
|
||||
IsVisible="{Binding UpdatePromptShell.IsOpen}">
|
||||
<Border Classes="card" Width="560" HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
IsVisible="{Binding UpdatePrompt.IsOpen}">
|
||||
<Border Classes="card" Width="640" HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Text="{Binding UpdatePromptShell.Title}" FontSize="24" FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding UpdatePromptShell.Body}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="{Binding UpdatePrompt.Title}" FontSize="24" FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding UpdatePrompt.Body}" TextWrapping="Wrap" />
|
||||
<Grid ColumnDefinitions="*,*" ColumnSpacing="16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Installed client" Classes="muted" />
|
||||
<TextBlock Text="{Binding UpdatePrompt.CurrentClientVersion}" FontWeight="SemiBold" />
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1">
|
||||
<TextBlock Text="Available release" Classes="muted" />
|
||||
<TextBlock Text="{Binding UpdatePrompt.AvailableVersion}" FontWeight="SemiBold" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding UpdatePrompt.MinimumLauncherStatus}"
|
||||
TextWrapping="Wrap"
|
||||
Classes="muted" />
|
||||
<Border Background="#24344B" Padding="10" CornerRadius="5">
|
||||
<TextBlock Text="{Binding UpdatePromptShell.Status}" TextWrapping="Wrap" />
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="{Binding UpdatePrompt.Status}" TextWrapping="Wrap" />
|
||||
<ProgressBar Minimum="0"
|
||||
Maximum="100"
|
||||
Value="{Binding UpdatePrompt.ProgressPercent}"
|
||||
IsIndeterminate="{Binding UpdatePrompt.IsProgressIndeterminate}"
|
||||
IsVisible="{Binding UpdatePrompt.IsBusy}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<Button x:Name="UpdateCloseButton"
|
||||
Content="Close"
|
||||
HorizontalAlignment="Right"
|
||||
IsCancel="True"
|
||||
IsDefault="True"
|
||||
AutomationProperties.Name="Close update prompt"
|
||||
Command="{Binding UpdatePromptShell.CloseCommand}" />
|
||||
<Border Background="#5B2630"
|
||||
Padding="10"
|
||||
CornerRadius="5"
|
||||
IsVisible="{Binding UpdatePrompt.HasError}">
|
||||
<TextBlock Text="{Binding UpdatePrompt.Error}" TextWrapping="Wrap" />
|
||||
</Border>
|
||||
<Border Background="#365B32"
|
||||
Padding="10"
|
||||
CornerRadius="5"
|
||||
IsVisible="{Binding UpdatePrompt.IsLauncherRestartRequired}">
|
||||
<TextBlock Text="{Binding UpdatePrompt.LauncherRestartStatus}"
|
||||
TextWrapping="Wrap"
|
||||
FontWeight="SemiBold" />
|
||||
</Border>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
|
||||
<Button Content="Check again"
|
||||
AutomationProperties.Name="Check for updates now"
|
||||
Command="{Binding UpdatePrompt.CheckCommand}" />
|
||||
<Button Content="Rollback client"
|
||||
AutomationProperties.Name="Rollback client version"
|
||||
Command="{Binding UpdatePrompt.RollbackCommand}" />
|
||||
<Button Content="Stage launcher"
|
||||
AutomationProperties.Name="Stage launcher self-update"
|
||||
Command="{Binding UpdatePrompt.StageLauncherCommand}" />
|
||||
<Button Content="Install client"
|
||||
Classes="primary"
|
||||
IsDefault="True"
|
||||
AutomationProperties.Name="Install client update"
|
||||
Command="{Binding UpdatePrompt.InstallClientCommand}" />
|
||||
<Button Content="Cancel"
|
||||
AutomationProperties.Name="Cancel update operation"
|
||||
Command="{Binding UpdatePrompt.CancelCommand}" />
|
||||
<Button x:Name="UpdateCloseButton"
|
||||
Content="Close"
|
||||
IsCancel="True"
|
||||
AutomationProperties.Name="Close update prompt"
|
||||
Command="{Binding UpdatePrompt.CloseCommand}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Border>
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ public sealed partial class MainWindow : Window
|
|||
{
|
||||
FirstRunDatDirectoryTextBox.Focus();
|
||||
}
|
||||
else if (viewModel.UpdatePromptShell.IsOpen)
|
||||
else if (viewModel.UpdatePrompt.IsOpen)
|
||||
{
|
||||
UpdateCloseButton.Focus();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
using AcDream.Launcher.Core.Updates;
|
||||
using AcDream.Platform;
|
||||
using Avalonia;
|
||||
|
||||
namespace AcDream.Launcher;
|
||||
|
|
@ -15,7 +17,34 @@ internal static class Program
|
|||
return 0;
|
||||
}
|
||||
|
||||
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
try
|
||||
{
|
||||
ApplicationPathSet paths = ApplicationPathSet.Resolve();
|
||||
using var httpClient = new HttpClient();
|
||||
var selfUpdates = new LauncherSelfUpdateManager(paths, httpClient);
|
||||
string executable = Environment.ProcessPath
|
||||
?? throw new InvalidOperationException(
|
||||
"The launcher executable path is unavailable.");
|
||||
SelfUpdateStartupResult startup = LauncherSelfUpdateBootstrap.HandleAsync(
|
||||
args,
|
||||
selfUpdates,
|
||||
AppContext.BaseDirectory,
|
||||
executable)
|
||||
.GetAwaiter()
|
||||
.GetResult();
|
||||
if (startup.ShouldExit)
|
||||
{
|
||||
return startup.ExitCode;
|
||||
}
|
||||
|
||||
return BuildAvaloniaApp().StartWithClassicDesktopLifetime(
|
||||
startup.RemainingArguments);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"Launcher startup failed safely: {ex.Message}");
|
||||
return 74;
|
||||
}
|
||||
}
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp() =>
|
||||
|
|
|
|||
530
src/AcDream.Launcher/ViewModels/LauncherUpdateViewModel.cs
Normal file
530
src/AcDream.Launcher/ViewModels/LauncherUpdateViewModel.cs
Normal file
|
|
@ -0,0 +1,530 @@
|
|||
using AcDream.Launcher.Core.Updates;
|
||||
|
||||
namespace AcDream.Launcher.ViewModels;
|
||||
|
||||
public sealed class LauncherUpdateViewModel : ObservableObject, IDisposable
|
||||
{
|
||||
private readonly ILauncherUpdater _updater;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly Action _onClientChanged;
|
||||
private readonly Func<bool> _canOpen;
|
||||
private readonly Func<bool> _canMutate;
|
||||
private CancellationTokenSource? _cancellation;
|
||||
private LauncherUpdateCheckResult? _check;
|
||||
private bool _isOpen;
|
||||
private bool _isBusy;
|
||||
private bool _disposed;
|
||||
private string _status = "No update check has run yet.";
|
||||
private string? _error;
|
||||
private LauncherUpdatePhase _phase = LauncherUpdatePhase.Idle;
|
||||
private double _progressPercent;
|
||||
private bool _isProgressIndeterminate;
|
||||
private string? _launcherRestartStatus;
|
||||
|
||||
public LauncherUpdateViewModel(
|
||||
ILauncherUpdater updater,
|
||||
IUiDispatcher dispatcher,
|
||||
Action onClientChanged,
|
||||
Func<bool>? canOpen = null,
|
||||
Func<bool>? canMutate = null)
|
||||
{
|
||||
_updater = updater ?? throw new ArgumentNullException(nameof(updater));
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
_onClientChanged = onClientChanged
|
||||
?? throw new ArgumentNullException(nameof(onClientChanged));
|
||||
_canOpen = canOpen ?? (() => true);
|
||||
_canMutate = canMutate ?? (() => true);
|
||||
|
||||
OpenCommand = new AsyncRelayCommand(OpenAndCheckAsync, () => _canOpen() && !IsBusy);
|
||||
CloseCommand = new RelayCommand(Close, () => !IsBusy);
|
||||
CheckCommand = new AsyncRelayCommand(
|
||||
() => CheckAsync(startup: false),
|
||||
() => IsOpen && !IsBusy);
|
||||
InstallClientCommand = new AsyncRelayCommand(
|
||||
InstallClientAsync,
|
||||
() => IsOpen
|
||||
&& !IsBusy
|
||||
&& _canMutate()
|
||||
&& _check is
|
||||
{
|
||||
IsClientUpdateAvailable: true,
|
||||
IsLauncherMinimumSatisfied: true,
|
||||
});
|
||||
StageLauncherCommand = new AsyncRelayCommand(
|
||||
StageLauncherAsync,
|
||||
() => IsOpen
|
||||
&& !IsBusy
|
||||
&& _canMutate()
|
||||
&& !IsLauncherRestartRequired
|
||||
&& _check is { IsLauncherUpdateAvailable: true });
|
||||
RollbackCommand = new AsyncRelayCommand(
|
||||
RollbackAsync,
|
||||
() => IsOpen
|
||||
&& !IsBusy
|
||||
&& _canMutate()
|
||||
&& !string.IsNullOrEmpty(_updater.CurrentClient.PreviousVersion));
|
||||
CancelCommand = new RelayCommand(
|
||||
() => _cancellation?.Cancel(),
|
||||
() => IsBusy && _cancellation is not null);
|
||||
}
|
||||
|
||||
public string Title => "Client and launcher updates";
|
||||
|
||||
public string Body =>
|
||||
"Releases are downloaded from the pinned eriknihlen/acdream GitHub feed. "
|
||||
+ "Every archive is size/SHA-256 verified and safely extracted before "
|
||||
+ "the active client pointer can change.";
|
||||
|
||||
public bool IsOpen
|
||||
{
|
||||
get => _isOpen;
|
||||
private set
|
||||
{
|
||||
if (SetProperty(ref _isOpen, value))
|
||||
{
|
||||
NotifyCommandStates();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _isBusy;
|
||||
private set
|
||||
{
|
||||
if (SetProperty(ref _isBusy, value))
|
||||
{
|
||||
OnPropertyChanged(nameof(CanClose));
|
||||
NotifyCommandStates();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanClose => !IsBusy;
|
||||
|
||||
public string Status
|
||||
{
|
||||
get => _status;
|
||||
private set => SetProperty(ref _status, value);
|
||||
}
|
||||
|
||||
public string? Error
|
||||
{
|
||||
get => _error;
|
||||
private set
|
||||
{
|
||||
if (SetProperty(ref _error, value))
|
||||
{
|
||||
OnPropertyChanged(nameof(HasError));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasError => !string.IsNullOrWhiteSpace(Error);
|
||||
|
||||
public LauncherUpdatePhase Phase
|
||||
{
|
||||
get => _phase;
|
||||
private set => SetProperty(ref _phase, value);
|
||||
}
|
||||
|
||||
public double ProgressPercent
|
||||
{
|
||||
get => _progressPercent;
|
||||
private set => SetProperty(ref _progressPercent, value);
|
||||
}
|
||||
|
||||
public bool IsProgressIndeterminate
|
||||
{
|
||||
get => _isProgressIndeterminate;
|
||||
private set => SetProperty(ref _isProgressIndeterminate, value);
|
||||
}
|
||||
|
||||
public string CurrentClientVersion =>
|
||||
_updater.CurrentClient.Version?.Value ?? "not installed";
|
||||
|
||||
public string AvailableVersion => _check?.Manifest.Version.Value ?? "not checked";
|
||||
|
||||
public string CurrentLauncherVersion =>
|
||||
_check?.LauncherVersion.Value ?? "loading";
|
||||
|
||||
public bool IsClientUpdateAvailable => _check?.IsClientUpdateAvailable == true;
|
||||
|
||||
public bool IsLauncherUpdateAvailable => _check?.IsLauncherUpdateAvailable == true;
|
||||
|
||||
public bool IsLauncherRestartRequired =>
|
||||
!string.IsNullOrWhiteSpace(_launcherRestartStatus);
|
||||
|
||||
public string LauncherRestartStatus => _launcherRestartStatus ?? string.Empty;
|
||||
|
||||
public bool IsLauncherMinimumBlocked => _check is
|
||||
{
|
||||
IsClientUpdateAvailable: true,
|
||||
IsLauncherMinimumSatisfied: false,
|
||||
};
|
||||
|
||||
public string MinimumLauncherStatus => _check is null
|
||||
? string.Empty
|
||||
: _check.IsLauncherMinimumSatisfied
|
||||
? $"Launcher meets minimum {_check.Manifest.MinimumLauncherVersion}."
|
||||
: $"Install launcher {_check.Manifest.MinimumLauncherVersion} or newer before the client update.";
|
||||
|
||||
public AsyncRelayCommand OpenCommand { get; }
|
||||
|
||||
public RelayCommand CloseCommand { get; }
|
||||
|
||||
public AsyncRelayCommand CheckCommand { get; }
|
||||
|
||||
public AsyncRelayCommand InstallClientCommand { get; }
|
||||
|
||||
public AsyncRelayCommand StageLauncherCommand { get; }
|
||||
|
||||
public AsyncRelayCommand RollbackCommand { get; }
|
||||
|
||||
public RelayCommand CancelCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Launch-time polling is deliberately nonfatal: an offline or malformed
|
||||
/// feed changes only this status and never prevents profile/session use.
|
||||
/// </summary>
|
||||
public async Task StartupCheckAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await CheckAsync(startup: true).ConfigureAwait(true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// CheckAsync owns visible state and never lets startup polling
|
||||
// escape into the Avalonia initialization transaction.
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (!IsBusy)
|
||||
{
|
||||
IsOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyCommandStates()
|
||||
{
|
||||
OpenCommand.NotifyCanExecuteChanged();
|
||||
CloseCommand.NotifyCanExecuteChanged();
|
||||
CheckCommand.NotifyCanExecuteChanged();
|
||||
InstallClientCommand.NotifyCanExecuteChanged();
|
||||
StageLauncherCommand.NotifyCanExecuteChanged();
|
||||
RollbackCommand.NotifyCanExecuteChanged();
|
||||
CancelCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_cancellation?.Cancel();
|
||||
_cancellation?.Dispose();
|
||||
_cancellation = null;
|
||||
}
|
||||
|
||||
private async Task OpenAndCheckAsync()
|
||||
{
|
||||
IsOpen = true;
|
||||
await CheckAsync(startup: false).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
private async Task CheckAsync(bool startup)
|
||||
{
|
||||
if (IsBusy || _disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
_cancellation = cancellation;
|
||||
IsBusy = true;
|
||||
Error = null;
|
||||
Phase = LauncherUpdatePhase.Checking;
|
||||
Status = "Checking the pinned GitHub release manifest...";
|
||||
IsProgressIndeterminate = true;
|
||||
ProgressPercent = 0;
|
||||
try
|
||||
{
|
||||
_check = await _updater.CheckAsync(cancellation.Token)
|
||||
.ConfigureAwait(true);
|
||||
Status = _check.Status;
|
||||
Phase = LauncherUpdatePhase.Completed;
|
||||
RefreshVersionProperties();
|
||||
if (startup
|
||||
&& (_check.IsClientUpdateAvailable
|
||||
|| _check.IsLauncherUpdateAvailable))
|
||||
{
|
||||
IsOpen = true;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = "Update check cancelled.";
|
||||
Phase = LauncherUpdatePhase.Cancelled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string detail = SafeDisplayError(ex);
|
||||
Status = startup
|
||||
? $"Automatic update check unavailable; continuing offline. {detail}"
|
||||
: "Update check failed.";
|
||||
Error = startup ? null : detail;
|
||||
Phase = LauncherUpdatePhase.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsProgressIndeterminate = false;
|
||||
if (ReferenceEquals(_cancellation, cancellation))
|
||||
{
|
||||
_cancellation = null;
|
||||
}
|
||||
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private Task InstallClientAsync() => RunMutationAsync(
|
||||
(check, progress, token) => _updater.InstallClientAsync(check, progress, token),
|
||||
"Installing the client update...",
|
||||
"Client update installed and activated.",
|
||||
clientChanged: true);
|
||||
|
||||
private Task StageLauncherAsync() => RunMutationAsync(
|
||||
async (check, progress, token) =>
|
||||
{
|
||||
SelfUpdateStageResult staged = await _updater
|
||||
.StageLauncherAsync(check, progress, token)
|
||||
.ConfigureAwait(true);
|
||||
_launcherRestartStatus = staged.Status;
|
||||
OnPropertyChanged(nameof(IsLauncherRestartRequired));
|
||||
OnPropertyChanged(nameof(LauncherRestartStatus));
|
||||
return _updater.CurrentClient;
|
||||
},
|
||||
"Staging the launcher update...",
|
||||
"Launcher update staged; restart the launcher to apply it.",
|
||||
clientChanged: false);
|
||||
|
||||
private async Task RollbackAsync()
|
||||
{
|
||||
if (IsBusy || _disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
_cancellation = cancellation;
|
||||
IsBusy = true;
|
||||
Error = null;
|
||||
Status = "Rolling back the client...";
|
||||
IsProgressIndeterminate = true;
|
||||
try
|
||||
{
|
||||
var progress = new UiProgress<LauncherUpdateProgress>(
|
||||
_dispatcher,
|
||||
ApplyProgress);
|
||||
_ = await _updater.RollbackClientAsync(progress, cancellation.Token)
|
||||
.ConfigureAwait(true);
|
||||
_onClientChanged();
|
||||
RefreshVersionProperties();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = "Rollback cancelled; the active version was not changed.";
|
||||
Phase = LauncherUpdatePhase.Cancelled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Error = SafeDisplayError(ex);
|
||||
Status = "Rollback failed.";
|
||||
Phase = LauncherUpdatePhase.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsProgressIndeterminate = false;
|
||||
if (ReferenceEquals(_cancellation, cancellation))
|
||||
{
|
||||
_cancellation = null;
|
||||
}
|
||||
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunMutationAsync(
|
||||
Func<
|
||||
LauncherUpdateCheckResult,
|
||||
IProgress<LauncherUpdateProgress>,
|
||||
CancellationToken,
|
||||
Task<ClientVersionResolution>> operation,
|
||||
string initialStatus,
|
||||
string completedStatus,
|
||||
bool clientChanged)
|
||||
{
|
||||
if (IsBusy || _disposed || _check is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
_cancellation = cancellation;
|
||||
IsBusy = true;
|
||||
Error = null;
|
||||
Status = initialStatus;
|
||||
IsProgressIndeterminate = true;
|
||||
ProgressPercent = 0;
|
||||
try
|
||||
{
|
||||
var progress = new UiProgress<LauncherUpdateProgress>(
|
||||
_dispatcher,
|
||||
ApplyProgress);
|
||||
_ = await operation(_check, progress, cancellation.Token)
|
||||
.ConfigureAwait(true);
|
||||
if (clientChanged)
|
||||
{
|
||||
_onClientChanged();
|
||||
}
|
||||
|
||||
RefreshVersionProperties();
|
||||
Phase = LauncherUpdatePhase.Completed;
|
||||
Status = IsLauncherRestartRequired
|
||||
? LauncherRestartStatus
|
||||
: completedStatus;
|
||||
try
|
||||
{
|
||||
_check = await _updater.CheckAsync(CancellationToken.None)
|
||||
.ConfigureAwait(true);
|
||||
if (!IsLauncherRestartRequired)
|
||||
{
|
||||
Status = _check.Status;
|
||||
}
|
||||
|
||||
RefreshVersionProperties();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Status += " Release status refresh is unavailable: "
|
||||
+ SafeDisplayError(ex);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = "Update operation cancelled; published state was not changed.";
|
||||
Phase = LauncherUpdatePhase.Cancelled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Error = SafeDisplayError(ex);
|
||||
Status = "Update operation failed.";
|
||||
Phase = LauncherUpdatePhase.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsProgressIndeterminate = false;
|
||||
if (ReferenceEquals(_cancellation, cancellation))
|
||||
{
|
||||
_cancellation = null;
|
||||
}
|
||||
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyProgress(LauncherUpdateProgress value)
|
||||
{
|
||||
Phase = value.Phase;
|
||||
Status = value.Status;
|
||||
ProgressPercent = value.Percent;
|
||||
IsProgressIndeterminate = value.Total <= 0
|
||||
&& value.Phase is not (
|
||||
LauncherUpdatePhase.Completed
|
||||
or LauncherUpdatePhase.Cancelled
|
||||
or LauncherUpdatePhase.Failed);
|
||||
}
|
||||
|
||||
private void RefreshVersionProperties()
|
||||
{
|
||||
OnPropertyChanged(nameof(CurrentClientVersion));
|
||||
OnPropertyChanged(nameof(AvailableVersion));
|
||||
OnPropertyChanged(nameof(CurrentLauncherVersion));
|
||||
OnPropertyChanged(nameof(IsClientUpdateAvailable));
|
||||
OnPropertyChanged(nameof(IsLauncherUpdateAvailable));
|
||||
OnPropertyChanged(nameof(IsLauncherRestartRequired));
|
||||
OnPropertyChanged(nameof(LauncherRestartStatus));
|
||||
OnPropertyChanged(nameof(IsLauncherMinimumBlocked));
|
||||
OnPropertyChanged(nameof(MinimumLauncherStatus));
|
||||
NotifyCommandStates();
|
||||
}
|
||||
|
||||
private static string SafeDisplayError(Exception exception) =>
|
||||
string.IsNullOrWhiteSpace(exception.Message)
|
||||
? "The update operation failed."
|
||||
: exception.Message;
|
||||
|
||||
private sealed class UiProgress<T>(IUiDispatcher dispatcher, Action<T> callback)
|
||||
: IProgress<T>
|
||||
{
|
||||
public void Report(T value) => dispatcher.Post(() => callback(value));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class UnavailableLauncherUpdater : ILauncherUpdater
|
||||
{
|
||||
private readonly ClientVersionResolution _resolution;
|
||||
private readonly string _status;
|
||||
|
||||
public UnavailableLauncherUpdater(
|
||||
string status = "Versioned client updater is unavailable.",
|
||||
ClientVersionResolution? resolution = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(status);
|
||||
_status = status;
|
||||
_resolution = resolution ?? new ClientVersionResolution(
|
||||
ClientVersionState.Invalid,
|
||||
status,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
public ClientVersionResolution CurrentClient => _resolution;
|
||||
|
||||
public Task<ClientVersionResolution> InitializeAsync(
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(_resolution);
|
||||
|
||||
public Task<LauncherUpdateCheckResult> CheckAsync(
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Task.FromException<LauncherUpdateCheckResult>(
|
||||
new LauncherUpdateException(_status));
|
||||
|
||||
public Task<ClientVersionResolution> InstallClientAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Task.FromException<ClientVersionResolution>(
|
||||
new LauncherUpdateException(_status));
|
||||
|
||||
public Task<SelfUpdateStageResult> StageLauncherAsync(
|
||||
LauncherUpdateCheckResult check,
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Task.FromException<SelfUpdateStageResult>(
|
||||
new LauncherUpdateException(_status));
|
||||
|
||||
public Task<ClientVersionResolution> RollbackClientAsync(
|
||||
IProgress<LauncherUpdateProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Task.FromException<ClientVersionResolution>(
|
||||
new LauncherUpdateException(_status));
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ using AcDream.Launcher.Core.Installation;
|
|||
using AcDream.Launcher.Core.Launching;
|
||||
using AcDream.Launcher.Core.Orchestration;
|
||||
using AcDream.Launcher.Core.Profiles;
|
||||
using AcDream.Launcher.Core.Updates;
|
||||
|
||||
namespace AcDream.Launcher.ViewModels;
|
||||
|
||||
|
|
@ -25,7 +26,8 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
public LauncherWindowViewModel(
|
||||
ILauncherOrchestrator orchestrator,
|
||||
IUiDispatcher dispatcher,
|
||||
ILauncherInstaller? installer = null)
|
||||
ILauncherInstaller? installer = null,
|
||||
ILauncherUpdater? updater = null)
|
||||
{
|
||||
_orchestrator = orchestrator ?? throw new ArgumentNullException(nameof(orchestrator));
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
|
|
@ -38,17 +40,16 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
OnInstallCompleted,
|
||||
() => CanInteract,
|
||||
() => !IsBusy && Sessions.All(session => !session.IsActive));
|
||||
UpdatePromptShell = new LauncherShellViewModel(
|
||||
"Client update",
|
||||
"Review a signed release manifest, verify the downloaded archive, "
|
||||
+ "and atomically switch the installed client version. The updater "
|
||||
+ "transaction lands in Campaign LA slice LA10.",
|
||||
"Updater shell ready — implementation arrives in LA10.",
|
||||
() => CanInteract);
|
||||
UpdatePrompt = new LauncherUpdateViewModel(
|
||||
updater ?? new UnavailableLauncherUpdater(),
|
||||
dispatcher,
|
||||
OnClientVersionChanged,
|
||||
() => CanInteract,
|
||||
() => !IsBusy && Sessions.All(session => !session.IsActive));
|
||||
|
||||
EditorDialog.PropertyChanged += OnModalPropertyChanged;
|
||||
FirstRunWizardShell.PropertyChanged += OnModalPropertyChanged;
|
||||
UpdatePromptShell.PropertyChanged += OnModalPropertyChanged;
|
||||
UpdatePrompt.PropertyChanged += OnModalPropertyChanged;
|
||||
|
||||
AddServerCommand = new RelayCommand(OpenAddServerDialog, () => CanInteract);
|
||||
AddAccountCommand = new RelayCommand(OpenAddAccountDialog, CanAddAccount);
|
||||
|
|
@ -92,7 +93,7 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
|
||||
public FirstRunInstallerViewModel FirstRunWizardShell { get; }
|
||||
|
||||
public LauncherShellViewModel UpdatePromptShell { get; }
|
||||
public LauncherUpdateViewModel UpdatePrompt { get; }
|
||||
|
||||
public LauncherTreeNodeViewModel? SelectedNode
|
||||
{
|
||||
|
|
@ -136,7 +137,7 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
public bool IsModalOpen =>
|
||||
EditorDialog.IsOpen
|
||||
|| FirstRunWizardShell.IsOpen
|
||||
|| UpdatePromptShell.IsOpen;
|
||||
|| UpdatePrompt.IsOpen;
|
||||
|
||||
private bool CanInteract => !IsBusy && !IsModalOpen;
|
||||
|
||||
|
|
@ -300,6 +301,7 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
}
|
||||
|
||||
RefreshFromCore();
|
||||
_ = UpdatePrompt.StartupCheckAsync();
|
||||
}
|
||||
|
||||
public void PollStatus()
|
||||
|
|
@ -333,8 +335,9 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
_orchestrator.StateChanged -= OnOrchestratorStateChanged;
|
||||
EditorDialog.PropertyChanged -= OnModalPropertyChanged;
|
||||
FirstRunWizardShell.PropertyChanged -= OnModalPropertyChanged;
|
||||
UpdatePromptShell.PropertyChanged -= OnModalPropertyChanged;
|
||||
UpdatePrompt.PropertyChanged -= OnModalPropertyChanged;
|
||||
FirstRunWizardShell.Dispose();
|
||||
UpdatePrompt.Dispose();
|
||||
}
|
||||
|
||||
private void OnOrchestratorStateChanged(object? sender, EventArgs e) =>
|
||||
|
|
@ -350,7 +353,8 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
{
|
||||
if (e.PropertyName != nameof(ProfileEditorDialogViewModel.IsOpen)
|
||||
&& e.PropertyName != nameof(LauncherShellViewModel.IsOpen)
|
||||
&& e.PropertyName != nameof(FirstRunInstallerViewModel.IsOpen))
|
||||
&& e.PropertyName != nameof(FirstRunInstallerViewModel.IsOpen)
|
||||
&& e.PropertyName != nameof(LauncherUpdateViewModel.IsOpen))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
@ -376,9 +380,9 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
{
|
||||
FirstRunWizardShell.Close();
|
||||
}
|
||||
else if (UpdatePromptShell.IsOpen)
|
||||
else if (UpdatePrompt.IsOpen)
|
||||
{
|
||||
UpdatePromptShell.IsOpen = false;
|
||||
UpdatePrompt.Close();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -976,6 +980,13 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
RefreshFromCore();
|
||||
}
|
||||
|
||||
private void OnClientVersionChanged()
|
||||
{
|
||||
OperationStatus = "Versioned client activation changed.";
|
||||
LastError = null;
|
||||
RefreshFromCore();
|
||||
}
|
||||
|
||||
private void NotifyCommandStates()
|
||||
{
|
||||
AddServerCommand.NotifyCanExecuteChanged();
|
||||
|
|
@ -996,7 +1007,7 @@ public sealed class LauncherWindowViewModel : ObservableObject, IDisposable
|
|||
session.NotifyCommandState();
|
||||
}
|
||||
FirstRunWizardShell.NotifyCommandStates();
|
||||
UpdatePromptShell.NotifyCommandStates();
|
||||
UpdatePrompt.NotifyCommandStates();
|
||||
}
|
||||
|
||||
private readonly record struct SelectionKey(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue