using System.IO; using Chronos.Core.Diagnostics; using Chronos.Core.Packaging; using Chronos.Setup.Cli; namespace Chronos.Setup.Engine; /// /// /S: install or uninstall without a window, reporting only through the exit code and the setup log. /// Running programs are asked to close; if they do not, setup stops with /// before touching anything. Then the services of the installed programs are stopped (and started again after the /// upgrade, or when it fails) or deleted with the uninstall, which asks for administrator approval when setup runs /// without it. Silent uninstall never removes user data. /// internal static class SilentSetup { public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20); public static async Task RunAsync(SetupArguments arguments) { try { return arguments.Uninstall ? await UninstallAsync(arguments).ConfigureAwait(false) : await InstallAsync(arguments).ConfigureAwait(false); } catch (Exception ex) { Log.Error("setup", "Silent setup failed", ex); return CodeFor(ex); } } /// Exit code for a failure. public static SetupExitCode CodeFor(Exception ex) => ex switch { SetupException s => s.Code, PayloadException => SetupExitCode.PayloadInvalid, // ERROR_DISK_FULL / ERROR_HANDLE_DISK_FULL IOException { HResult: unchecked((int)0x80070070) or unchecked((int)0x80070027) } => SetupExitCode.DiskFull, _ => SetupExitCode.Failed, }; private static async Task InstallAsync(SetupArguments arguments) { using var payload = PayloadReader.OpenCurrentProcess(); var engine = new InstallEngine(payload); var plan = InstallPlan.Resolve(engine.Manifest, arguments); if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory)) Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'"); if (!InstallPlan.IsValidDirectory(engine.Manifest, plan.Scope, plan.Directory, plan.Components)) { Log.Error("setup", $"'{plan.Directory}' cannot take {string.Join(", ", plan.Components)} for {plan.Scope}"); return SetupExitCode.InvalidArguments; } if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments; var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null; if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); // Read before the upgrade rewrites the log, so a program it drops still names its service. var programs = InstallPlan.Programs(engine.Manifest, plan.Directory).ToList(); var owned = CommandProgram.FullPaths(plan.Directory, programs); var closed = await CloseProgramsAsync(plan.Directory, programs, owned).ConfigureAwait(false); if (closed.Code != SetupExitCode.Success) return closed.Code; var stopped = closed.Services; try { var code = await InstalledServices.ApplyAsync(plan.Directory, stopped, ServiceActions.Stop, IntPtr.Zero).ConfigureAwait(false); if (code != SetupExitCode.Success) { await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false); return code; } var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu); engine.Install(request, null, CancellationToken.None); } catch { await StartAgainAsync(plan.Directory, stopped).ConfigureAwait(false); throw; } // Services whose program the upgrade removed go; the ones stopped for it run again. var after = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); var services = await InstalledServices.ApplyAsync(plan.Directory, after, ServiceActions.Prune | ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false); if (services != SetupExitCode.Success) return services; if (launch is null) return SetupExitCode.Success; if (arguments.Elevated) return SetupExitCode.LaunchRequested; Launcher.Start(launch); return SetupExitCode.Success; } private static async Task UninstallAsync(SetupArguments arguments) { var product = UninstallEngine.Locate(arguments.Directory, PayloadProduct()); if (product is null) return SetupExitCode.NotInstalled; if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false); var owned = CommandProgram.FullPaths(product.Directory, product.Log.Files); var closed = await CloseProgramsAsync(product.Directory, product.Log.Files, owned).ConfigureAwait(false); if (closed.Code != SetupExitCode.Success) return closed.Code; // Only now that the programs are closed. Services that were not running are still registered: no service may // outlive its program. If one cannot be deleted, the ones stopped here run again. var services = await InstalledServices.ApplyAsync(product.Directory, InstalledServices.Find(owned), ServiceActions.Remove, IntPtr.Zero).ConfigureAwait(false); if (services != SetupExitCode.Success) { await StartAgainAsync(product.Directory, closed.Services).ConfigureAwait(false); return services; } UninstallEngine.Uninstall(product, userData: null, null); return SetupExitCode.Success; } /// The product named by this program's payload, when it has one (a full installer run with /uninstall). public static string? PayloadProduct() { try { using var payload = PayloadReader.OpenCurrentProcess(); return payload.Manifest.Product; } catch (PayloadException) { return null; } } /// /// Asks the running programs of to close and returns the running services of /// , which the caller stops or deletes: a program that does not close stops setup before /// any service is touched. /// private static async Task<(SetupExitCode Code, IReadOnlyList Services)> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned) { var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList(); var running = RunningPrograms.Find(directory, programs, services); try { if (running.Count == 0) return (SetupExitCode.Success, services); Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close"); var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false); return (still.Count == 0 ? SetupExitCode.Success : SetupExitCode.ProgramRunning, services); } finally { foreach (var p in running) p.Dispose(); } } /// After a failure, starts again the services setup stopped, so a failed upgrade does not leave the server down. private static async Task StartAgainAsync(string directory, IReadOnlyList stopped) { if (stopped.Count == 0) return; try { var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, IntPtr.Zero).ConfigureAwait(false); if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}"); } catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) { Log.Warning("setup", "Stopped services not started again", ex); } } }