diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index 83f3f7a6..b786e32f 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -42,7 +42,7 @@ for community review. Development happens elsewhere; please use the issues here in `SHA256SUMS` of the same release. 3. Run the setup. It installs for the current user into `%LOCALAPPDATA%\Programs\Titano` without administrator rights; choose *All users* to install into `Program Files` (Windows asks for permission). The *Server* component - runs as a Windows service, so choosing it installs for all users. + runs as a Windows service, so choosing it installs for all users, in a folder inside `Program Files`. - **Upgrade:** Titano checks this repository at start (you can turn this off in Settings › Updates) and shows a notice when a new version exists. *Download* fetches the setup, verifies it against `SHA256SUMS` and shows it in Explorer; diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7c28df55..75f740b4 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -577,6 +577,7 @@ Add shortcuts to the desktop Where the programs are installed · your data stays in its own folder Enter a full folder path that is not a drive root or a system folder + {0} runs as a Windows service, so choose a folder inside Program Files Copy the selected programs and register them with Windows Folder of the installed programs Install in your user folder · no administrator rights needed @@ -586,6 +587,7 @@ Open the installed program Already installed here · uninstall it first to change folder or scope Runs as a Windows service, so it installs for all users only · this copy is installed for you alone; uninstall it first to add it + Runs as a Windows service, so it installs inside Program Files only · this copy is installed elsewhere; uninstall it first to add it Select at least one program to install Also delete %LOCALAPPDATA%\Titano: database, backups, cache, settings, logs, the uploader queue and sign-in · photos in archives are kept Also delete Titano’s database, backups, cache, settings and logs in %LOCALAPPDATA%\Titano · the Uploader’s files and photos in archives are kept diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index bfa8bc87..6dedbcb0 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -577,6 +577,7 @@ Aggiungi collegamenti al desktop Dove vengono installati i programmi · i tuoi dati restano nella loro cartella Inserisci il percorso completo di una cartella che non sia la radice di un'unità o una cartella di sistema + {0} è un servizio di Windows, quindi scegli una cartella dentro Programmi Copia i programmi selezionati e registrali in Windows Cartella dei programmi installati Installa nella tua cartella utente · non servono diritti di amministratore @@ -586,6 +587,7 @@ Apri il programma installato Già installato qui · disinstallalo prima per cambiare cartella o ambito È un servizio di Windows, quindi si installa solo per tutti gli utenti · questa copia è installata solo per te; disinstallala prima per aggiungerlo + È un servizio di Windows, quindi si installa solo dentro Programmi · questa copia è installata altrove; disinstallala prima per aggiungerlo Seleziona almeno un programma da installare Elimina anche %LOCALAPPDATA%\Titano: database, backup, cache, impostazioni, log, coda e accesso dell'uploader · le foto negli archivi restano Elimina anche database, backup, cache, impostazioni e log di Titano in %LOCALAPPDATA%\Titano · i file dell'uploader e le foto negli archivi restano diff --git a/src/Titano.Core/IO/StartupCommand.cs b/src/Titano.Core/IO/StartupCommand.cs new file mode 100644 index 00000000..6e023874 --- /dev/null +++ b/src/Titano.Core/IO/StartupCommand.cs @@ -0,0 +1,61 @@ +namespace Titano.Core.IO; + +/// +/// The sign-in entries of Titano's programs: HKCU\Software\Microsoft\Windows\CurrentVersion\Run values whose +/// command starts one executable with one option ("C:\…\Titano.exe" --minimized). Shared by the programs that +/// write them and the uninstaller that removes them; the paths are Windows paths, compared ignoring case. +/// +public static class StartupCommand +{ + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + + /// The client's value (Settings › General › Startup). + public const string ClientValue = "Titano"; + + /// The Uploader's value (its "Start with Windows"). + public const string UploaderValue = "Titano Uploader"; + + /// The command that starts with . + public static string Format(string executable, string option) => $"\"{executable}\" {option}"; + + /// + /// The program starts: its quoted first part, or the text up to the first space when it + /// is not quoted; null for an empty or malformed command. + /// + public static string? Executable(string? command) + { + var text = command?.Trim(); + if (string.IsNullOrEmpty(text)) return null; + if (text[0] == '"') + { + var end = text.IndexOf('"', 1); + return end > 1 ? text[1..end] : null; + } + var space = text.IndexOf(' ', StringComparison.Ordinal); + return space < 0 ? text : text[..space]; + } + + /// starts , not another copy of the program. + public static bool Starts(string? command, string? executable) => + executable is { Length: > 0 } && string.Equals(Executable(command), executable, StringComparison.OrdinalIgnoreCase); + + /// The program starts lies in or one of its folders. + public static bool StartsFrom(string? command, string directory) + { + ArgumentNullException.ThrowIfNull(directory); + var folder = directory.TrimEnd('\\', '/'); + return Executable(command) is { } exe && folder.Length > 0 && exe.Length > folder.Length + 1 + && exe.StartsWith(folder, StringComparison.OrdinalIgnoreCase) && exe[folder.Length] is '\\' or '/'; + } + + /// The folder of the program starts; null when it names none. + public static string? Folder(string? command) => Executable(command) is { } exe ? FolderOf(exe) : null; + + /// The folder part of a Windows path (on any platform); null when it has none. + public static string? FolderOf(string path) + { + ArgumentNullException.ThrowIfNull(path); + var slash = path.LastIndexOfAny(['\\', '/']); + return slash > 0 ? path[..slash] : null; + } +} diff --git a/src/Titano.Setup/Cli/SetupArguments.cs b/src/Titano.Setup/Cli/SetupArguments.cs index 52f52c29..4695f2ea 100644 --- a/src/Titano.Setup/Cli/SetupArguments.cs +++ b/src/Titano.Setup/Cli/SetupArguments.cs @@ -8,8 +8,8 @@ namespace Titano.Setup.Cli; /// /S silent · /DIR=path · /COMPONENTS=Titano,Uploader · /ALLUSERS · /NODESKTOP · /// /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall. /// Internal: /ELEVATED (relaunched for administrator rights), /CLEANUP=path /WAITPID=n (removes the -/// uninstaller after the uninstall process exits), /SERVICES=stop,prune,start,remove /DIR=path (the elevated -/// step that stops, starts or deletes the Windows services of an installation). +/// uninstaller after the uninstall process exits), /SERVICES=stop,prune,start,remove /NAMES=a,b /DIR=path (the +/// elevated step that stops, starts or deletes the named Windows services of an installation). /// internal sealed record SetupArguments { @@ -27,6 +27,9 @@ internal sealed record SetupArguments public int WaitProcessId { get; init; } public ServiceActions Services { get; init; } + /// The services applies to (key names, as the unelevated setup found them). + public IReadOnlyList? ServiceNames { get; init; } + /// Parses ; throws for unknown or malformed switches. public static SetupArguments Parse(IEnumerable args) { @@ -52,11 +55,13 @@ internal sealed record SetupArguments ("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') }, ("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid }, ("SERVICES", { Length: > 0 }) => result with { Services = ParseServices(value) }, + ("NAMES", { Length: > 0 }) => result with { ServiceNames = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }, _ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."), }; } if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID."); - if (result.Services != ServiceActions.None && result.Directory is null) throw new ArgumentException("/SERVICES needs /DIR."); + if (result.Services != ServiceActions.None && (result.Directory is null || result.ServiceNames is not { Count: > 0 })) + throw new ArgumentException("/SERVICES needs /DIR and /NAMES."); return result; } @@ -73,6 +78,7 @@ internal sealed record SetupArguments if (Launch) yield return "/LAUNCH"; if (Language is not null) yield return "/LANG=" + Language; if (Services != ServiceActions.None) yield return "/SERVICES=" + Services.ToString().Replace(" ", string.Empty, StringComparison.Ordinal).ToLowerInvariant(); + if (ServiceNames is not null) yield return "/NAMES=" + string.Join(',', ServiceNames); if (Elevated) yield return "/ELEVATED"; } diff --git a/src/Titano.Setup/Engine/CommandProgram.cs b/src/Titano.Setup/Engine/CommandProgram.cs index a734fbce..31d98946 100644 --- a/src/Titano.Setup/Engine/CommandProgram.cs +++ b/src/Titano.Setup/Engine/CommandProgram.cs @@ -1,8 +1,13 @@ using System.IO; +using Titano.Core.Packaging; namespace Titano.Setup.Engine; -/// The program a command line registered with Windows starts: a service's image path, a Run value. +/// +/// The program a command line registered with Windows starts (a service's image path, a Run value), and whether it is +/// one setup installed: setup changes only what starts a program its log or payload lists, never another program +/// that happens to live in the same folder. +/// internal static class CommandProgram { /// @@ -18,8 +23,30 @@ internal static class CommandProgram return first is not null && Path.IsPathFullyQualified(first) ? first : null; } - /// True when starts a program inside . - public static bool IsInside(string commandLine, string directory) => Of(commandLine) is { } program && IsPathInside(program, directory); + /// + /// Full paths of (an install log's or a manifest's files) under + /// , compared ignoring case: the programs setup installs or installed there. + /// + public static IReadOnlySet FullPaths(string directory, IEnumerable payloadPaths) + { + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var path in payloadPaths.Where(PayloadPath.IsValid)) paths.Add(PayloadPath.Resolve(directory, path)); + return paths; + } + + /// True when (a full path, in any form Windows accepts) is one of . + public static bool IsAmong(string? program, IReadOnlySet programs) + { + if (string.IsNullOrEmpty(program) || !Path.IsPathFullyQualified(program)) return false; + try + { + return programs.Contains(Path.GetFullPath(program)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } /// that answers false for a path Windows cannot normalise. public static bool IsPathInside(string path, string directory) diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs index 88cf5597..ca050ccc 100644 --- a/src/Titano.Setup/Engine/InstallEngine.cs +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -74,7 +74,7 @@ internal sealed class InstallEngine(PayloadReader payload) // Saved before registration so that an uninstall can always undo whatever follows. log.Save(directory); - foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name); + foreach (var (link, target, name, _) in shortcuts.Where(s => s.Create)) ShellLink.Create(link, target, name); foreach (var a in fileTypes) SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, FileTypeName(a), PayloadPath.Resolve(directory, a.Target)); if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged(); @@ -105,14 +105,15 @@ internal sealed class InstallEngine(PayloadReader payload) : null; /// - /// The shortcuts to create. A shortcut of the same name that starts an existing program elsewhere (the same - /// program installed by another Titano product, or the user's own) is left as it is and not logged, so neither - /// install retargets or removes the other's. + /// The shortcuts to log, and among them those to create. A shortcut of the same name that starts an existing program + /// elsewhere (the same program installed by another Titano product, or the user's own) is left as it is but logged: + /// neither install retargets or removes the other's, and when the other product is uninstalled it hands the + /// shortcut over to this copy (). /// - private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory) + private List<(string Link, string Target, string Name, bool Create)> PlanShortcuts(InstallRequest request, string directory) { var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); - var result = new List<(string, string, string)>(); + var result = new List<(string, string, string, bool)>(); foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component))) { var target = PayloadPath.Resolve(directory, s.Target); @@ -123,12 +124,13 @@ internal sealed class InstallEngine(PayloadReader payload) void Add(string link, string target, string name) { + var create = true; if (ShellLink.TargetOf(link) is { } current && !CommandProgram.IsPathInside(current, directory) && File.Exists(current)) { Log.Info("setup", $"Shortcut '{link}' starts '{current}'; left as it is"); - return; + create = false; } - result.Add((link, target, name)); + result.Add((link, target, name, create)); } } @@ -138,13 +140,32 @@ internal sealed class InstallEngine(PayloadReader payload) return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList(); } - /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). + /// + /// Removes what the previous version installed and this one no longer does (files, the sign-in entries of those + /// programs, shortcuts, file types). + /// private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) { var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); - if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete); - foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase)) - UninstallEngine.DeleteShortcut(link, previous.Scope, directory); + if (obsolete.Count > 0) + { + InstalledFiles.Remove(directory, obsolete); + try + { + // A dropped Uploader no longer starts at sign-in. + SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, obsolete)); + } + catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) + { + Log.Warning("setup", "Sign-in entries not removed", ex); + } + } + var links = previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase).ToList(); + if (links.Count > 0) + { + var others = SetupRegistry.OtherInstalls(directory, Publisher); + foreach (var link in links) UninstallEngine.DeleteShortcut(link, previous.Scope, directory, others); + } foreach (var a in previous.Associations.Except(current.Associations)) { if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId); diff --git a/src/Titano.Setup/Engine/InstallLog.cs b/src/Titano.Setup/Engine/InstallLog.cs index 4cdc6f5c..c395a965 100644 --- a/src/Titano.Setup/Engine/InstallLog.cs +++ b/src/Titano.Setup/Engine/InstallLog.cs @@ -23,7 +23,10 @@ internal sealed class InstallLog /// Installed payload paths, relative to the install folder (the uninstaller and this log excluded). public List Files { get; set; } = []; - /// Full paths of the shortcuts setup created. + /// + /// Full paths of the shortcuts setup created, or would have created but found starting an existing program elsewhere + /// (another Titano product's copy, which hands them over to this one when it is uninstalled). + /// public List Shortcuts { get; set; } = []; public List Associations { get; set; } = []; diff --git a/src/Titano.Setup/Engine/InstallPlan.cs b/src/Titano.Setup/Engine/InstallPlan.cs index d89084d7..a3c28e58 100644 --- a/src/Titano.Setup/Engine/InstallPlan.cs +++ b/src/Titano.Setup/Engine/InstallPlan.cs @@ -8,7 +8,8 @@ namespace Titano.Setup.Engine; /// Where and what to install before the user changes anything: an existing installation fixes folder and scope /// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. A /// component that installs for all users only (, the Server) makes a new -/// installation an all-users one; a per-user installation upgraded in place cannot take it. +/// installation an all-users one, in a folder inside Program Files; an installation upgraded in place elsewhere (for +/// the current user, or in another folder) cannot take it. /// internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing) { @@ -32,30 +33,39 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn } var allUsersOnly = components.Where(id => manifest.FindComponent(id)!.AllUsersOnly).ToList(); - if (allUsersOnly.Count > 0 && scope == InstallScope.CurrentUser) + if (allUsersOnly.Count > 0 && existing is null) scope = InstallScope.AllUsers; + var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product); + if (allUsersOnly.Count > 0 && existing is not null && !IsServiceSafe(existing.Scope, existing.Directory)) { - if (existing is null) - { - scope = InstallScope.AllUsers; - } - else if (arguments.Components is not null) + if (arguments.Components is not null) { throw new SetupException(SetupExitCode.InvalidArguments, - $"{string.Join(", ", allUsersOnly)} installs for all users only; {manifest.Product} is installed for the current user."); - } - else - { - // An earlier per-user install carried it: the upgrade drops it, and its service with it (Prune). - Log.Warning("setup", $"{string.Join(", ", allUsersOnly)} not kept: it installs for all users only"); - components = [.. components.Except(allUsersOnly, StringComparer.OrdinalIgnoreCase)]; + $"{string.Join(", ", allUsersOnly)} installs for all users inside Program Files only; {manifest.Product} is installed in '{existing.Directory}' for {existing.Scope}."); } + // An earlier installation elsewhere carried it: the upgrade drops it, and its service with it (Prune). + Log.Warning("setup", $"{string.Join(", ", allUsersOnly)} not kept: it installs for all users inside Program Files only"); + components = [.. components.Except(allUsersOnly, StringComparer.OrdinalIgnoreCase)]; } - var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product); return new InstallPlan(scope, directory, components, existing); } - /// False for a component that installs for all users only when a per-user installation is upgraded. - public bool CanInstall(PayloadComponent component) => !(component.AllUsersOnly && Existing is { Scope: InstallScope.CurrentUser }); + /// + /// False for a component that installs for all users only when an installation that is not an all-users one inside + /// Program Files is upgraded. + /// + public bool CanInstall(PayloadComponent component) => !component.AllUsersOnly || Existing is null || IsServiceSafe(Existing.Scope, Existing.Directory); + + /// + /// True when may be installed in for + /// : a folder setup can use and, when one of them runs as a LocalSystem service, an + /// all-users folder inside Program Files, which standard users cannot change. + /// + public static bool IsValidDirectory(PayloadManifest manifest, InstallScope scope, string directory, IEnumerable components) => + SetupPaths.IsUsableInstallDirectory(directory) + && (!components.Any(id => manifest.FindComponent(id)?.AllUsersOnly == true) || IsServiceSafe(scope, directory)); + + /// True for an all-users installation inside Program Files: where a program a LocalSystem service starts may live. + public static bool IsServiceSafe(InstallScope scope, string directory) => scope == InstallScope.AllUsers && SetupPaths.IsInsideProgramFiles(directory); /// Executables to look for among running processes: the new payload's and the previous install's. public static IEnumerable Programs(PayloadManifest manifest, string directory) => diff --git a/src/Titano.Setup/Engine/InstalledServices.cs b/src/Titano.Setup/Engine/InstalledServices.cs index d01dd4e3..17d76712 100644 --- a/src/Titano.Setup/Engine/InstalledServices.cs +++ b/src/Titano.Setup/Engine/InstalledServices.cs @@ -5,18 +5,18 @@ using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; using Titano.Core.Localization; +using Titano.Core.Packaging; using Titano.Setup.Cli; using static Titano.Setup.Interop.ServiceNative; namespace Titano.Setup.Engine; -/// A Windows service whose program lies inside an installation folder (Titano.Server.exe --install-service). +/// A Windows service that starts a program setup installed (Titano.Server.exe --install-service). /// Service key name (TitanoServer). /// Full path of the program the service starts. -/// Starts with Windows (start type automatic). -internal sealed record InstalledService(string Name, string DisplayName, string Program, bool AutoStart); +internal sealed record InstalledService(string Name, string DisplayName, string Program); -/// What setup does with the services of an installation; several may be combined. +/// What setup does with the services it is given; several may be combined. [Flags] internal enum ServiceActions { @@ -28,7 +28,7 @@ internal enum ServiceActions /// Deletes the ones whose program no longer exists (an upgrade dropped the component). Prune = 2, - /// Starts the automatic ones that are stopped (after an upgrade that stopped them). + /// Starts the stopped ones whose program exists (the ones setup stopped for an upgrade). Start = 4, /// Stops and deletes them all (uninstall), so no service is left pointing at a deleted program. @@ -36,11 +36,12 @@ internal enum ServiceActions } /// -/// Services registered from an installation folder. Setup ignored them before: an upgrade failed while the service -/// kept its files open, and an uninstall left an automatic LocalSystem service pointing at a deleted path. They are -/// found in the registry (no administrator rights needed) and stopped, started or deleted through the Service -/// Control Manager, which needs administrator rights: an unelevated setup runs that step in an elevated copy of -/// itself (/SERVICES=…). +/// Services that start a program setup installed. Setup ignored them before: an upgrade failed while the service kept +/// its files open, and an uninstall left an automatic LocalSystem service pointing at a deleted path. Only a service +/// whose program is one of the files an install log or the payload lists counts, never any other service that lives +/// in the same folder. They are found in the registry (no administrator rights needed) and stopped, started or +/// deleted through the Service Control Manager, which needs administrator rights: an unelevated setup runs that step +/// in an elevated copy of itself (/SERVICES=… /NAMES=…), which checks each named service again. /// internal static class InstalledServices { @@ -49,100 +50,100 @@ internal static class InstalledServices /// SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS: programs, not drivers. private const int Win32Service = 0x30; - private const int AutoStartType = 2; + /// A state that could not be read: treated as running, so setup never replaces files a service may hold. + private const uint StateUnknown = uint.MaxValue; /// How long a service may take to stop and its process to exit (as programs asked to close). public static readonly TimeSpan StopTimeout = TimeSpan.FromSeconds(30); - /// Services whose program lies inside ; services already marked for deletion are skipped. - public static IReadOnlyList Find(string directory) + /// + /// Services whose program is one of (); services + /// already marked for deletion are skipped. + /// + public static IReadOnlyList Find(IReadOnlySet programs) + { + if (programs.Count == 0) return []; + using var services = Registry.LocalMachine.OpenSubKey(ServicesKey); + return services is null ? [] : Find(services, programs); + } + + /// over the service keys under . + public static IReadOnlyList Find(RegistryKey services, IReadOnlySet programs) { var found = new List(); - using var services = Registry.LocalMachine.OpenSubKey(ServicesKey); - if (services is null) return found; foreach (var name in services.GetSubKeyNames()) { - try - { - using var key = services.OpenSubKey(name); - if (key is null || key.GetValue("Type") is not int type || (type & Win32Service) == 0) continue; - if (key.GetValue("DeleteFlag") is int deleting && deleting != 0) continue; - if (key.GetValue("ImagePath") is not string image || CommandProgram.Of(image) is not { } program || !CommandProgram.IsPathInside(program, directory)) continue; - var display = key.GetValue("DisplayName") as string; - found.Add(new InstalledService(name, display is { Length: > 0 } && display[0] != '@' ? display : name, program, key.GetValue("Start") is AutoStartType)); - } - catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException) - { - // A key this account may not read is not one setup registered. - Log.Debug("setup", $"Service key {name} not read: {ex.Message}"); - } + if (Read(services, name) is { } service && CommandProgram.IsAmong(service.Program, programs)) found.Add(service); } return found; } /// True when the service is not stopped (running, starting, stopping or paused), or its state cannot be read. - public static unsafe bool IsRunning(InstalledService service) - { - var manager = OpenSCManagerW(null, null, ScManagerConnect); - if (manager == 0) return true; - try - { - var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus); - if (handle == 0) return Marshal.GetLastPInvokeError() != ErrorServiceDoesNotExist; - try - { - return !TryQuery(handle, out var status) || status.CurrentState != StateStopped; - } - finally - { - CloseServiceHandle(handle); - } - } - finally - { - CloseServiceHandle(manager); - } - } + public static bool IsRunning(InstalledService service) => State(service) is { } state && state != StateStopped; /// True when would change something about . - public static bool NeedsWork(IReadOnlyList services, ServiceActions actions) => services.Any(s => - actions.HasFlag(ServiceActions.Remove) - || (actions.HasFlag(ServiceActions.Prune) && !File.Exists(s.Program)) - || (actions.HasFlag(ServiceActions.Stop) && IsRunning(s)) - || (actions.HasFlag(ServiceActions.Start) && s.AutoStart && File.Exists(s.Program) && !IsRunning(s))); + public static bool NeedsWork(IReadOnlyList services, ServiceActions actions) => services.Any(s => NeedsWork(s, actions)); /// - /// Applies to the services of : in this process when it has - /// administrator rights, otherwise in an elevated copy (UAC prompt owned by ). Success - /// when there is nothing to do. + /// Applies to (found by + /// for ): in this process when it has administrator rights, otherwise in an elevated + /// copy (UAC prompt owned by ). Success when there is nothing to do. /// - public static async Task ApplyAsync(string directory, ServiceActions actions, IntPtr owner) + public static async Task ApplyAsync(string directory, IReadOnlyList services, ServiceActions actions, IntPtr owner) { - if (!NeedsWork(Find(directory), actions)) return SetupExitCode.Success; - if (Elevation.IsElevated) return await Task.Run(() => Apply(directory, actions)).ConfigureAwait(false); - Log.Info("setup", $"Asking for administrator rights to {actions} the services of '{directory}'"); - var arguments = new SetupArguments { Services = actions, Directory = directory, Language = Loc.Culture.Name }; + var pending = services.Where(s => NeedsWork(s, actions)).ToList(); + if (pending.Count == 0) return SetupExitCode.Success; + if (Elevation.IsElevated) return await Task.Run(() => Apply(pending, actions)).ConfigureAwait(false); + if (pending.FirstOrDefault(s => s.Name.Contains(',', StringComparison.Ordinal)) is { } unnamed) + { + // The elevated step takes a comma-separated list; Titano's own service is named TitanoServer. + Log.Error("setup", $"Service '{unnamed.Name}' cannot be passed to the elevated step"); + return SetupExitCode.Failed; + } + Log.Info("setup", $"Asking for administrator rights to {actions} {string.Join(", ", pending.Select(s => s.Name))}"); + var arguments = new SetupArguments { Services = actions, ServiceNames = [.. pending.Select(s => s.Name)], Directory = directory, Language = Loc.Culture.Name }; return Elevation.Start(arguments, owner) is { } child ? await Elevation.WaitAsync(child, null).ConfigureAwait(false) : SetupExitCode.ElevationDeclined; } /// - /// The elevated step (/SERVICES=… /DIR=…): applies the actions in this process. Refuses a folder setup would not - /// install to, and needs administrator rights. + /// The elevated step (/SERVICES=… /NAMES=… /DIR=…): reads each named service again and applies the actions + /// in this process. A name must still start a program of the folder's install log or of this setup's payload (or, + /// for , a program of the folder that no longer exists); otherwise nothing is done. + /// Refuses a folder setup would not install to, and needs administrator rights. /// public static SetupExitCode RunStep(SetupArguments arguments) { - if (arguments.Directory is not { } directory || !SetupPaths.IsUsableInstallDirectory(directory)) return SetupExitCode.InvalidArguments; - return Elevation.IsElevated ? Apply(directory, arguments.Services) : SetupExitCode.ElevationDeclined; + if (arguments.Directory is not { } directory || !SetupPaths.IsUsableInstallDirectory(directory) || arguments.ServiceNames is not { Count: > 0 } names) + return SetupExitCode.InvalidArguments; + if (!Elevation.IsElevated) return SetupExitCode.ElevationDeclined; + var owned = CommandProgram.FullPaths(directory, (InstallLog.TryLoad(directory)?.Files ?? []).Concat(PayloadFiles())); + using var root = Registry.LocalMachine.OpenSubKey(ServicesKey); + var services = new List(); + foreach (var name in names) + { + if ((root is null ? null : Read(root, name)) is not { } service) + { + Log.Info("setup", $"Service {name} no longer exists"); + continue; + } + var gone = arguments.Services.HasFlag(ServiceActions.Prune) && CommandProgram.IsPathInside(service.Program, directory) && !File.Exists(service.Program); + if (!CommandProgram.IsAmong(service.Program, owned) && !gone) + { + Log.Error("setup", $"Service {name} starts '{service.Program}', which setup did not install in '{directory}'"); + return SetupExitCode.InvalidArguments; + } + services.Add(service); + } + return Apply(services, arguments.Services); } /// - /// Applies in this process (administrator rights). Returns + /// Applies to in this process (administrator rights). Returns /// when a service did not stop in time, - /// when the Service Control Manager refused a step (logged). + /// when the Service Control Manager refused a step (logged). A service that no longer exists is skipped. /// - public static unsafe SetupExitCode Apply(string directory, ServiceActions actions) + public static unsafe SetupExitCode Apply(IReadOnlyList services, ServiceActions actions) { - var services = Find(directory); if (services.Count == 0) return SetupExitCode.Success; var manager = OpenSCManagerW(null, null, ScManagerConnect); if (manager == 0) return Failure("Service Control Manager not opened", null); @@ -165,7 +166,7 @@ internal static class InstalledServices if (!DeleteService(handle) && Marshal.GetLastPInvokeError() != ErrorServiceMarkedForDelete) return Failure("Service not deleted", service); Log.Info("setup", $"Service {service.Name} deleted"); } - else if (actions.HasFlag(ServiceActions.Start) && service.AutoStart && File.Exists(service.Program)) + else if (actions.HasFlag(ServiceActions.Start) && File.Exists(service.Program)) { if (!StartServiceW(handle, 0, 0) && Marshal.GetLastPInvokeError() != ErrorServiceAlreadyRunning) return Failure("Service not started", service); Log.Info("setup", $"Service {service.Name} started"); @@ -184,6 +185,76 @@ internal static class InstalledServices } } + private static bool NeedsWork(InstalledService service, ServiceActions actions) + { + if (actions.HasFlag(ServiceActions.Remove)) return State(service) is not null; + if (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program)) return State(service) is not null; + var state = State(service); + return (actions.HasFlag(ServiceActions.Stop) && state is { } running && running != StateStopped) + || (actions.HasFlag(ServiceActions.Start) && state == StateStopped && File.Exists(service.Program)); + } + + /// + /// The service named under when it is a Win32 service not marked + /// for deletion whose command names a full path; null otherwise, or when this account may not read its key. + /// + private static InstalledService? Read(RegistryKey services, string name) + { + try + { + using var key = services.OpenSubKey(name); + if (key is null || key.GetValue("Type") is not int type || (type & Win32Service) == 0) return null; + if (key.GetValue("DeleteFlag") is int deleting && deleting != 0) return null; + if (key.GetValue("ImagePath") is not string image || CommandProgram.Of(image) is not { } program) return null; + var display = key.GetValue("DisplayName") as string; + return new InstalledService(name, display is { Length: > 0 } && display[0] != '@' ? display : name, program); + } + catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException) + { + // A key this account may not read is not one setup registered. + Log.Debug("setup", $"Service key {name} not read: {ex.Message}"); + return null; + } + } + + /// The service's current state; null when it no longer exists, when it cannot be read. + private static unsafe uint? State(InstalledService service) + { + var manager = OpenSCManagerW(null, null, ScManagerConnect); + if (manager == 0) return StateUnknown; + try + { + var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus); + if (handle == 0) return Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist ? null : StateUnknown; + try + { + return TryQuery(handle, out var status) ? status.CurrentState : StateUnknown; + } + finally + { + CloseServiceHandle(handle); + } + } + finally + { + CloseServiceHandle(manager); + } + } + + /// The files of the payload this setup carries; none for an uninstaller. + private static IReadOnlyList PayloadFiles() + { + try + { + using var payload = PayloadReader.OpenCurrentProcess(); + return [.. payload.Manifest.Files.Select(f => f.Path)]; + } + catch (PayloadException) + { + return []; + } + } + /// Stops the service and waits for its process to exit, so its files can be replaced; false on timeout. private static unsafe bool Stop(nint handle, InstalledService service) { diff --git a/src/Titano.Setup/Engine/SetupPaths.cs b/src/Titano.Setup/Engine/SetupPaths.cs index 4a1ac77d..17e32a9f 100644 --- a/src/Titano.Setup/Engine/SetupPaths.cs +++ b/src/Titano.Setup/Engine/SetupPaths.cs @@ -67,6 +67,21 @@ internal static class SetupPaths && !IsSameOrInside(UserData, full); } + /// + /// True for a folder inside Program Files (not Program Files itself), where only administrators may change the + /// programs: the only place a program run by a LocalSystem service may live. + /// + public static bool IsInsideProgramFiles(string? path) + { + if (!IsUsableInstallDirectory(path)) return false; + foreach (var special in (ReadOnlySpan)[Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86]) + { + var programFiles = Environment.GetFolderPath(special); + if (programFiles.Length > 0 && IsSameOrInside(path!, programFiles) && !IsSameOrInside(programFiles, path!)) return true; + } + return false; + } + /// True when is or lies inside it (case-insensitive). public static bool IsSameOrInside(string path, string folder) { diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs index ab75aa1d..9d1f161d 100644 --- a/src/Titano.Setup/Engine/SetupRegistry.cs +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -2,12 +2,19 @@ using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Microsoft.Win32; +using Titano.Core.IO; namespace Titano.Setup.Engine; /// An installation found in Add/Remove Programs. internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version); +/// +/// Another Titano installation registered in Add/Remove Programs: its folder, and its log when that can be read now +/// (null for a drive that is offline, a folder that is gone or a log that cannot be read). +/// +internal sealed record OtherInstall(string? Directory, InstallLog? Log); + /// Values written to the Add/Remove Programs entry. internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl); @@ -36,12 +43,13 @@ internal static partial class SetupRegistry } /// - /// The logs of the other installations by (any product, either scope) except the one in - /// : what an uninstall must leave working (the user data they share). + /// The other installations by (any product, either scope) except the one in + /// : what an uninstall must leave working (the user data and shortcuts they share). + /// Every registered entry counts, also one whose folder or log cannot be read right now. /// - public static IReadOnlyList OtherInstalls(string directory, string publisher) + public static IReadOnlyList OtherInstalls(string directory, string publisher) { - var found = new List(); + var found = new List(); foreach (var scope in (ReadOnlySpan)[InstallScope.CurrentUser, InstallScope.AllUsers]) { using var root = Hive(scope).OpenSubKey(UninstallRoot.TrimEnd('\\')); @@ -52,9 +60,11 @@ internal static partial class SetupRegistry { using var key = root.OpenSubKey(name); if (key?.GetValue("Publisher") is not string p || !p.Equals(publisher, StringComparison.Ordinal)) continue; - if (key.GetValue("InstallLocation") is not string location || !Directory.Exists(location)) continue; - if (CommandProgram.IsPathInside(location, directory) && CommandProgram.IsPathInside(directory, location)) continue; - if (InstallLog.TryLoad(location) is { } log) found.Add(log); + var location = key.GetValue("InstallLocation") as string; + if (location is { Length: > 0 } && CommandProgram.IsPathInside(location, directory) && CommandProgram.IsPathInside(directory, location)) continue; + var log = location is { Length: > 0 } && Directory.Exists(location) ? InstallLog.TryLoad(location) : null; + if (log is null) Titano.Core.Diagnostics.Log.Info("setup", $"Installation '{name}' in '{location}' cannot be read now; it counts as using every program"); + found.Add(new OtherInstall(location, log)); } catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) { @@ -86,6 +96,31 @@ internal static partial class SetupRegistry public static void DeleteUninstallEntry(InstallScope scope, string productKey) => Hive(scope).DeleteSubKeyTree(UninstallRoot + productKey, throwOnMissingSubKey: false); + /// + /// Removes the sign-in entries of the client and the Uploader (HKCU\…\Run, written by the programs + /// themselves) that start one of ( of the files an + /// installation lists); another copy's entries, and other programs' values, stay. + /// + public static void DeleteStartupEntries(IReadOnlySet programs) + { + using var run = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey, writable: true); + if (run is not null) DeleteStartupEntries(run, programs); + } + + /// in ; returns the names removed. + public static IReadOnlyList DeleteStartupEntries(RegistryKey run, IReadOnlySet programs) + { + var removed = new List(); + foreach (var name in (ReadOnlySpan)[StartupCommand.ClientValue, StartupCommand.UploaderValue]) + { + if (!CommandProgram.IsAmong(StartupCommand.Executable(run.GetValue(name) as string), programs)) continue; + run.DeleteValue(name, throwOnMissingValue: false); + removed.Add(name); + Titano.Core.Diagnostics.Log.Info("setup", $"Sign-in entry '{name}' removed"); + } + return removed; + } + /// Registers to open with "program" "%1" under . public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program) { diff --git a/src/Titano.Setup/Engine/SilentSetup.cs b/src/Titano.Setup/Engine/SilentSetup.cs index 9d1e20da..a5db2409 100644 --- a/src/Titano.Setup/Engine/SilentSetup.cs +++ b/src/Titano.Setup/Engine/SilentSetup.cs @@ -7,9 +7,10 @@ namespace Titano.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 . -/// Services of the installation are stopped (and started again after an upgrade, or deleted with the uninstall), -/// which asks for administrator approval when setup runs without it. Silent uninstall never removes user data. +/// 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 { @@ -45,20 +46,42 @@ internal static class SilentSetup 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 (!SetupPaths.IsUsableInstallDirectory(plan.Directory)) return SetupExitCode.InvalidArguments; + 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); - var closed = await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory), ServiceActions.Stop).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 request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu); - engine.Install(request, null, CancellationToken.None); + 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 services = await InstalledServices.ApplyAsync(plan.Directory, ServiceActions.Prune | (closed.StoppedServices ? ServiceActions.Start : ServiceActions.None), IntPtr.Zero) - .ConfigureAwait(false); + 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; @@ -73,11 +96,17 @@ internal static class SilentSetup 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 closed = await CloseProgramsAsync(product.Directory, product.Log.Files, ServiceActions.Remove).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; - // Services that were not running are still registered: no service may outlive its program. - var services = await InstalledServices.ApplyAsync(product.Directory, ServiceActions.Remove, IntPtr.Zero).ConfigureAwait(false); - if (services != SetupExitCode.Success) return services; + // 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; } @@ -97,29 +126,39 @@ internal static class SilentSetup } /// - /// Applies to the running services of (an elevated step - /// when needed), then asks the running programs to close. + /// 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, bool StoppedServices)> CloseProgramsAsync(string directory, IEnumerable programs, ServiceActions toServices) + private static async Task<(SetupExitCode Code, IReadOnlyList Services)> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned) { - var services = InstalledServices.Find(directory).Where(InstalledServices.IsRunning).ToList(); + var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList(); var running = RunningPrograms.Find(directory, programs, services); try { - if (services.Count > 0) - { - Log.Info("setup", $"Stopping {RunningPrograms.Describe([], services)}"); - var code = await InstalledServices.ApplyAsync(directory, toServices, IntPtr.Zero).ConfigureAwait(false); - if (code != SetupExitCode.Success) return (code, false); - } - if (running.Count == 0) return (SetupExitCode.Success, services.Count > 0); + 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.Count > 0); + 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); + } + } } diff --git a/src/Titano.Setup/Engine/StartupEntries.cs b/src/Titano.Setup/Engine/StartupEntries.cs deleted file mode 100644 index 73489a24..00000000 --- a/src/Titano.Setup/Engine/StartupEntries.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.IO; -using System.Security; -using Microsoft.Win32; -using Titano.Core.Diagnostics; - -namespace Titano.Setup.Engine; - -/// -/// "Start with Windows" values under HKCU\Software\Microsoft\Windows\CurrentVersion\Run (the Uploader writes -/// "Titano Uploader"). An uninstall removes every value that starts a program inside the folder it removes: Windows -/// would otherwise try to start a deleted program at each sign-in. Values of other programs are left alone. -/// -internal static class StartupEntries -{ - public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; - - /// Removes the current user's Run values that start a program inside ; returns their names. - public static IReadOnlyList RemoveInside(string directory) - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(RunKey, writable: true); - return key is null ? [] : RemoveInside(key, directory); - } - catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) - { - // A leftover entry is harmless (Windows skips a missing program); it must not fail the uninstall. - Log.Warning("setup", "Startup entries not checked", ex); - return []; - } - } - - /// Removes the values of that start a program inside . - public static IReadOnlyList RemoveInside(RegistryKey runKey, string directory) - { - var removed = new List(); - foreach (var name in runKey.GetValueNames()) - { - if (runKey.GetValue(name) is not string command || !CommandProgram.IsInside(command, directory)) continue; - runKey.DeleteValue(name, throwOnMissingValue: false); - removed.Add(name); - Log.Info("setup", $"Startup entry '{name}' removed"); - } - return removed; - } -} diff --git a/src/Titano.Setup/Engine/UninstallEngine.cs b/src/Titano.Setup/Engine/UninstallEngine.cs index dae792ca..7eb8f8df 100644 --- a/src/Titano.Setup/Engine/UninstallEngine.cs +++ b/src/Titano.Setup/Engine/UninstallEngine.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Runtime.InteropServices; using Titano.Core.Diagnostics; using Titano.Core.Packaging; using Titano.Setup.Cli; @@ -10,10 +11,11 @@ namespace Titano.Setup.Engine; internal sealed record InstalledProduct(string Directory, InstallLog Log); /// -/// Removes an installation using only its log: shortcuts that still start its programs, "Start with Windows" entries -/// pointing into its folder, file types, logged files, the log and the Add/Remove Programs entry, then the -/// uninstaller itself. Files the log does not list are left alone; user data is deleted only through a plan the user -/// saw and chose in the window. Windows services of the folder are stopped and deleted by the caller first +/// Removes an installation using only its log: shortcuts that still start its programs (handed to another Titano +/// product that installed the same program and shares them), file types, logged files, the log, the Add/Remove +/// Programs entry and the sign-in entries of its programs, then the uninstaller itself. Files the log does not list, +/// and anything that starts a program it does not list, are left alone; user data is deleted only through a plan the +/// user saw and chose in the window. The Windows services of its programs are stopped and deleted by the caller first /// (), as that may need an elevated step. /// internal static class UninstallEngine @@ -42,8 +44,11 @@ internal static class UninstallEngine Log.Info("setup", $"Removing {userData.Entries.Count} entries of '{userData.Folder}' at the user's request"); userData.Remove(); } - foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory); - StartupEntries.RemoveInside(directory); + if (log.Shortcuts.Count > 0) + { + var others = SetupRegistry.OtherInstalls(directory, InstallEngine.Publisher); + foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory, others); + } progress?.Report(new SetupProgress(0.1, string.Empty)); var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList(); @@ -64,6 +69,15 @@ internal static class UninstallEngine } SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey); + try + { + SetupRegistry.DeleteStartupEntries(CommandProgram.FullPaths(directory, log.Files)); + } + catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) + { + // Windows skips a sign-in entry whose program is gone; not worth failing the removal. + Log.Warning("setup", "Sign-in entries not removed", ex); + } File.Delete(Path.Combine(directory, InstallLog.FileName)); var uninstaller = Path.Combine(directory, log.UninstallerName); try @@ -89,9 +103,11 @@ internal static class UninstallEngine /// /// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder that /// still starts a program inside : another product installing a program of the same - /// name may have pointed it at its own copy since. + /// name may have pointed it at its own copy since. When another installation () shares + /// the shortcut and has the same program, the shortcut is pointed at that copy instead, so the program that stays + /// installed keeps its shortcut. /// - public static void DeleteShortcut(string link, InstallScope scope, string directory) + public static void DeleteShortcut(string link, InstallScope scope, string directory, IReadOnlyList others) { var folder = Path.GetDirectoryName(link); var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) @@ -110,11 +126,44 @@ internal static class UninstallEngine Log.Info("setup", $"Shortcut '{link}' now starts '{target}'; kept"); return; } + if (SharedCopy(link, scope, directory, target, others) is { } copy) + { + ShellLink.Create(link, copy, Path.GetFileNameWithoutExtension(link)); + Log.Info("setup", $"Shortcut '{link}' now starts '{copy}', which stays installed"); + return; + } File.Delete(link); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or COMException) { Log.Warning("setup", $"Shortcut '{link}' not removed", ex); } } + + /// + /// The same program as (the same path inside its folder) installed by another product of + /// the same scope whose log lists too; null when there is none. + /// + private static string? SharedCopy(string link, InstallScope scope, string directory, string target, IReadOnlyList others) + { + string relative; + try + { + relative = PayloadPath.FromRelative(Path.GetRelativePath(directory, target)); + } + catch (Exception ex) when (ex is PayloadException or ArgumentException) + { + return null; + } + foreach (var other in others) + { + if (other is not { Directory: { } otherDirectory, Log: { } log } || log.Scope != scope) continue; + if (!log.Shortcuts.Contains(link, StringComparer.OrdinalIgnoreCase) || !log.Files.Contains(relative, PayloadPath.Comparer)) continue; + // The folder comes from another product's registry entry: one Windows cannot use is skipped. + if (!SetupPaths.IsUsableInstallDirectory(otherDirectory)) continue; + var copy = PayloadPath.Resolve(otherDirectory, relative); + if (File.Exists(copy)) return copy; + } + return null; + } } diff --git a/src/Titano.Setup/Engine/UserDataPlan.cs b/src/Titano.Setup/Engine/UserDataPlan.cs index 07642f84..c7461c70 100644 --- a/src/Titano.Setup/Engine/UserDataPlan.cs +++ b/src/Titano.Setup/Engine/UserDataPlan.cs @@ -115,4 +115,12 @@ internal static class UserDataOwners foreach (var other in others) owners.ExceptWith(other); return owners; } + + /// + /// for the installations registered + /// on this PC: one whose log cannot be read now (a drive that is offline, a damaged log) counts as using every + /// program's data, so its data is never offered for removal. + /// + public static IReadOnlySet RemovableBeside(IEnumerable components, IEnumerable others) => + Removable(components, others.Select(o => o.Log?.Components ?? (IEnumerable)All)); } diff --git a/src/Titano.Setup/Views/ComponentOption.cs b/src/Titano.Setup/Views/ComponentOption.cs index bf2bc283..a36a3f40 100644 --- a/src/Titano.Setup/Views/ComponentOption.cs +++ b/src/Titano.Setup/Views/ComponentOption.cs @@ -6,9 +6,11 @@ namespace Titano.Setup.Views; /// /// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. A component -/// that installs for all users only says so in its tooltip, and is unavailable when a per-user installation is upgraded. +/// that installs for all users only says so in its tooltip, and is unavailable when an installation that is not an +/// all-users one inside Program Files is upgraded. /// -internal sealed class ComponentOption(PayloadComponent component, bool selected, bool available, Action changed) : LocalizedViewModel +/// The tooltip key saying why it cannot be added here; null when it can. +internal sealed class ComponentOption(PayloadComponent component, bool selected, string? unavailableToolTip, Action changed) : LocalizedViewModel { private bool _selected = selected; @@ -19,10 +21,10 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected, /// Installs for all users only (the Server runs as a LocalSystem service from Program Files). public bool AllUsersOnly => component.AllUsersOnly; - /// False when it cannot be installed here: it needs all users and this installation is for the current user. - public bool IsAvailable { get; } = available; + /// False when it cannot be installed here: it needs all users in Program Files and this installation is not. + public bool IsAvailable => unavailableToolTip is null; - public string ToolTip => !IsAvailable ? Loc.L("Tooltips.Setup.NeedsAllUsers") + public string ToolTip => unavailableToolTip is { } reason ? Loc.L(reason) : AllUsersOnly ? Loc.L("Tooltips.Setup.AllUsersOnly", Description) : Description; diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs index 72c2ccfc..4989ae10 100644 --- a/src/Titano.Setup/Views/SetupViewModel.cs +++ b/src/Titano.Setup/Views/SetupViewModel.cs @@ -61,7 +61,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private bool _accessDenied; private string? _launchProgram; private Func? _operation; - private bool _stoppedServices; + + /// The services setup stopped for the current step, started again after the upgrade or when the step fails. + private IReadOnlyList _stopped = []; private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed, IReadOnlySet? dataOwners = null) @@ -73,8 +75,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo _installed = installed; // "Remove my data" covers the programs this product installed that no other installed Titano product still has. _dataOwners = installed is null ? new HashSet() - : dataOwners ?? UserDataOwners.Removable(installed.Log.Components, - SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher).Select(l => (IEnumerable)l.Components)); + : dataOwners ?? UserDataOwners.RemovableBeside(installed.Log.Components, SetupRegistry.OtherInstalls(installed.Directory, InstallEngine.Publisher)); if (payload is not null) { _engine = new InstallEngine(payload); @@ -87,7 +88,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo _launchAfter = arguments.Launch; Components = _engine is null ? [] - : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), _plan.CanInstall(c), + : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), UnavailableReason(c), OnComponentsChanged))]; Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; @@ -198,6 +199,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo OnPropertyChanged(nameof(IsJustMe)); // Follow the scope while the folder is still the suggested one. if (string.Equals(Path.TrimEndingDirectorySeparator(_directory), before, StringComparison.OrdinalIgnoreCase)) Directory = DefaultDirectory(); + else OnDirectoryRuleChanged(); } } @@ -212,18 +214,25 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo get => _directory; set { - if (!Set(ref _directory, value ?? string.Empty)) return; - ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory))); - OnPropertyChanged(nameof(DirectoryToolTip)); - OnPropertyChanged(nameof(InstallToolTip)); + if (Set(ref _directory, value ?? string.Empty)) OnDirectoryRuleChanged(); } } - private bool IsDirectoryValid => SetupPaths.IsUsableInstallDirectory(_directory); + /// + /// A folder setup can use; inside Program Files when a selected component runs as a LocalSystem service (a folder + /// such as C:\Titano would let standard users replace the program the service starts). + /// + private bool IsDirectoryValid => _engine is not null + && InstallPlan.IsValidDirectory(_engine.Manifest, _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _directory, SelectedComponents); + + /// Why the folder cannot be used: not a usable folder, or outside Program Files for a service. + private string FolderErrorText => SetupPaths.IsUsableInstallDirectory(_directory) && AllUsersComponent is { } component + ? Loc.L("Tooltips.Setup.FolderProgramFiles", component.Name) + : Loc.L("Tooltips.Setup.FolderInvalid"); public string DirectoryToolTip => !CanChangeLocation ? Loc.L("Tooltips.Setup.Locked") - : IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid"); + : IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : FolderErrorText; /// Browse is disabled when upgrading; its tooltip then says why (DESIGN §4). public string BrowseToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Browse") : Loc.L("Tooltips.Setup.Locked"); @@ -265,13 +274,13 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo /// What Install does, or why it is disabled: no program selected, or a folder it cannot use. public string InstallToolTip => !Components.Any(c => c.IsSelected) ? Loc.L("Tooltips.Setup.NoComponent") - : !IsDirectoryValid ? Loc.L("Tooltips.Setup.FolderInvalid") + : !IsDirectoryValid ? FolderErrorText : CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update"); /// Removing user data waits for its plan, so the user has seen what goes before choosing Uninstall. private bool CanStart => IsOptions && (IsUninstall ? !_removeUserData || _dataPlan is not null - : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected) && (_allUsers || AllUsersComponent is null)); + : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected)); // ---- Uninstall options ---- @@ -384,7 +393,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public bool HasErrors => IsInstall && !IsDirectoryValid; public IEnumerable GetErrors(string? propertyName) => - propertyName == nameof(Directory) && HasErrors ? new[] { Loc.L("Tooltips.Setup.FolderInvalid") } : Array.Empty(); + propertyName == nameof(Directory) && HasErrors ? new[] { FolderErrorText } : Array.Empty(); /// Called once the window is visible: an elevated copy continues the install the user already started. public void OnShown() @@ -425,6 +434,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private async Task InstallAsync() { var engine = _engine!; + string? directory = null; try { var request = new InstallRequest( @@ -442,22 +452,31 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo await InstallElevatedAsync(request, program); return; } - if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory), ServiceActions.Stop)) return; + directory = request.Directory; + // Read before the upgrade rewrites the log, so a program it drops still names its service. + var programs = InstallPlan.Programs(engine.Manifest, request.Directory).ToList(); + var owned = CommandProgram.FullPaths(request.Directory, programs); + if (await CloseProgramsAsync(request.Directory, programs, owned) is not { } running) return; BeginWork(indeterminate: false); + if (running.Count > 0) + { + _stopped = running; + await ApplyToServicesAsync(request.Directory, running, ServiceActions.Stop); + } var progress = new Progress(ReportProgress); await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); // Services whose program the upgrade removed go; the ones stopped for it run again. - var after = ServiceActions.Prune | (_stoppedServices ? ServiceActions.Start : ServiceActions.None); - var services = await InstalledServices.ApplyAsync(request.Directory, after, WindowHandle); - if (services != SetupExitCode.Success) throw new SetupException(services, $"Services not updated: {services}"); - _stoppedServices = false; + var after = InstalledServices.Find(owned).Where(s => !File.Exists(s.Program)).UnionBy(_stopped, s => s.Name, StringComparer.OrdinalIgnoreCase).ToList(); + _stopped = []; + await ApplyToServicesAsync(request.Directory, after, ServiceActions.Prune | ServiceActions.Start); _launchProgram = program; Complete(); if (launch is not null) Launch(); } catch (Exception ex) { + await StartStoppedAsync(directory); Fail(ex); } } @@ -489,11 +508,14 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo var installed = _installed!; try { - if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files, ServiceActions.Remove)) return; + var owned = CommandProgram.FullPaths(installed.Directory, installed.Log.Files); + if (await CloseProgramsAsync(installed.Directory, installed.Log.Files, owned) is not { } running) return; BeginWork(indeterminate: false); - // A service that was not running is still registered: none may outlive its program. - var services = await InstalledServices.ApplyAsync(installed.Directory, ServiceActions.Remove, WindowHandle); - if (services != SetupExitCode.Success) throw new SetupException(services, $"Services not removed: {services}"); + // Only now that the programs are closed. A service that was not running is still registered: none may + // outlive its program. If one cannot be deleted, the ones stopped here run again. + _stopped = running; + await ApplyToServicesAsync(installed.Directory, InstalledServices.Find(owned), ServiceActions.Remove); + _stopped = []; var progress = new Progress(ReportProgress); var userData = _removeUserData ? _dataPlan : null; await Task.Run(() => UninstallEngine.Uninstall(installed, userData, progress)); @@ -501,44 +523,36 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo } catch (Exception ex) { + await StartStoppedAsync(installed.Directory); Fail(ex); } } /// - /// True when no installed program or service runs from . Otherwise the first call asks - /// the user (Confirm stage); after "Close programs" the services get (stopped, or - /// stopped and deleted; an elevated step when needed), the programs are asked to close and the operation continues. + /// Null when the user must first confirm (Confirm stage) that the programs and services running from + /// may close. Otherwise the running programs have closed, and the result lists the + /// running services of , which the caller stops or deletes: a program that does not close + /// stops setup before any service is touched. /// - private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs, ServiceActions toServices) + private async Task?> CloseProgramsAsync(string directory, IEnumerable programs, IReadOnlySet owned) { // A confirmation answers one prompt only; a later attempt asks again. var confirmed = _closeConfirmed; _closeConfirmed = false; - var services = InstalledServices.Find(directory).Where(InstalledServices.IsRunning).ToList(); + var services = InstalledServices.Find(owned).Where(InstalledServices.IsRunning).ToList(); var running = RunningPrograms.Find(directory, programs, services); try { - if (running.Count == 0 && services.Count == 0) return true; + if (running.Count == 0 && services.Count == 0) return services; _runningPrograms = RunningPrograms.Describe(running, services); if (!confirmed) { Stage = SetupStage.Confirm; - return false; + return null; } BeginWork(indeterminate: true); - if (services.Count > 0) - { - var code = await InstalledServices.ApplyAsync(directory, toServices, WindowHandle); - if (code != SetupExitCode.Success) - { - _runningPrograms = RunningPrograms.Describe([], services); - throw new SetupException(code, $"Services not stopped: {_runningPrograms}"); - } - _stoppedServices = true; - } var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout); - if (still.Count == 0) return true; + if (still.Count == 0) return services; _runningPrograms = RunningPrograms.Describe(still); throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}"); } @@ -548,6 +562,32 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo } } + /// Applies to (an elevated step when needed); throws when that fails. + private async Task ApplyToServicesAsync(string directory, IReadOnlyList services, ServiceActions actions) + { + var code = await InstalledServices.ApplyAsync(directory, services, actions, WindowHandle); + if (code == SetupExitCode.Success) return; + _runningPrograms = RunningPrograms.Describe([], services); + throw new SetupException(code, $"Services not updated ({actions}): {_runningPrograms}"); + } + + /// After a failure, starts again the services setup stopped for the step, so a failed upgrade does not leave the server down. + private async Task StartStoppedAsync(string? directory) + { + var stopped = _stopped; + _stopped = []; + if (directory is null || stopped.Count == 0) return; + try + { + var code = await InstalledServices.ApplyAsync(directory, stopped, ServiceActions.Start, WindowHandle); + if (code != SetupExitCode.Success) Log.Warning("setup", $"Stopped services not started again: {code}"); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException) + { + Log.Warning("setup", "Stopped services not started again", ex); + } + } + private void Browse() { if (PickFolder?.Invoke(_directory) is not { } folder) return; @@ -645,13 +685,27 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo OnPropertyChanged(nameof(CanChooseJustMe)); OnPropertyChanged(nameof(JustMeToolTip)); OnPropertyChanged(nameof(RequiredSpaceText)); - OnPropertyChanged(nameof(InstallToolTip)); OnPropertyChanged(nameof(HasDesktopOption)); OnPropertyChanged(nameof(HasStartMenuOption)); OnPropertyChanged(nameof(HasLaunchOption)); + OnDirectoryRuleChanged(); + } + + /// The folder, the scope or the components changed: whether the folder is valid, and why not, may have too. + private void OnDirectoryRuleChanged() + { + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory))); + OnPropertyChanged(nameof(DirectoryToolTip)); + OnPropertyChanged(nameof(InstallToolTip)); CommandManager.InvalidateRequerySuggested(); } + /// The tooltip key saying why cannot be added to the installation upgraded here; null when it can. + private string? UnavailableReason(PayloadComponent component) => + _plan!.CanInstall(component) ? null + : _plan.Existing is { Scope: InstallScope.CurrentUser } ? "Tooltips.Setup.NeedsAllUsers" + : "Tooltips.Setup.NeedsProgramFiles"; + private IEnumerable SelectedShortcuts() { if (_engine is null) return []; diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs index ff51ae65..4badfff3 100644 --- a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -1,6 +1,7 @@ using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; +using Titano.Core.IO; namespace Titano.Uploader.Infrastructure; @@ -14,13 +15,13 @@ public interface IStartupRegistration /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. -/// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value, as -/// setup deletes every Run value that starts a program in the folder it removes. +/// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value when +/// it starts the Uploader the uninstaller removes ( names it for both). /// public sealed class RunKeyStartupRegistration : IStartupRegistration { - private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; - private const string ValueName = "Titano Uploader"; + private const string RunKey = StartupCommand.RunKey; + private const string ValueName = StartupCommand.UploaderValue; public bool IsEnabled { diff --git a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs index 11ff998d..5f0d7cf5 100644 --- a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs +++ b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs @@ -10,12 +10,14 @@ using Titano.Testing; namespace Titano.App.Tests.Setup; /// -/// What setup leaves behind and what it registers: services and startup entries of the install folder (SETUP-1, -/// SETUP-2), shortcuts another product owns (SRS-09), the Server's all-users scope (SRS-06) and the file type name -/// in setup's language (SRS-04). +/// What setup leaves behind and what it registers: services and startup entries of the programs it installed, never +/// of other programs in the same folder (SETUP-1, SETUP-2), shortcuts another product owns or takes over (SRS-09), the +/// Server's all-users scope inside Program Files (SRS-06) and the file type name in setup's language (SRS-04). /// public sealed class SetupEngineTests(TestContext context) { + private const string TestsKey = @"Software\Titano.Tests"; + [Theory] [Case(@"""C:\Program Files\Titano\Titano.Server.exe"" --service", @"C:\Program Files\Titano\Titano.Server.exe")] [Case(@"C:\Program Files\Titano\Titano.Server.exe --service", @"C:\Program Files\Titano\Titano.Server.exe")] @@ -27,63 +29,115 @@ public sealed class SetupEngineTests(TestContext context) Assert.Equal(program, CommandProgram.Of(commandLine)); [Test] - public void ServiceStepsTravelToTheElevatedCopy() + public void ServiceStepsTravelToTheElevatedCopyWithTheirServices() { - var arguments = new SetupArguments { Services = ServiceActions.Prune | ServiceActions.Start, Directory = @"C:\Program Files\Titano", Elevated = true }; + var arguments = new SetupArguments + { + Services = ServiceActions.Prune | ServiceActions.Start, + ServiceNames = ["TitanoServer"], + Directory = @"C:\Program Files\Titano", + Elevated = true, + }; var switches = arguments.ToSwitches().ToList(); Assert.Contains("/SERVICES=prune,start", switches); - Assert.Equal(arguments, SetupArguments.Parse(switches)); + Assert.Contains("/NAMES=TitanoServer", switches); + var parsed = SetupArguments.Parse(switches); + Assert.Equal(arguments.Services, parsed.Services); + Assert.Equal(arguments.Directory, parsed.Directory); + Assert.SequenceEqual(["TitanoServer"], parsed.ServiceNames!); + Assert.True(parsed.Elevated); - Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/DIR=C:\\Apps\\Titano"]).Services); - Assert.Throws(() => SetupArguments.Parse(["/SERVICES=stop"])); - Assert.Throws(() => SetupArguments.Parse(["/SERVICES=kill", "/DIR=C:\\Apps\\Titano"])); - Assert.Throws(() => SetupArguments.Parse(["/SERVICES=none", "/DIR=C:\\Apps\\Titano"])); + Assert.Equal(ServiceActions.Remove, SetupArguments.Parse(["/SERVICES=Remove", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"]).Services); + // The step acts only on services the unelevated setup named. + Assert.Throws(() => SetupArguments.Parse(["/SERVICES=stop", "/NAMES=TitanoServer"])); + Assert.Throws(() => SetupArguments.Parse(["/SERVICES=stop", "/DIR=C:\\Apps\\Titano"])); + Assert.Throws(() => SetupArguments.Parse(["/SERVICES=kill", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"])); + Assert.Throws(() => SetupArguments.Parse(["/SERVICES=none", "/NAMES=TitanoServer", "/DIR=C:\\Apps\\Titano"])); } [Test] [WindowsOnly] - public void AServiceWhoseProgramIsGoneIsPrunedAndNothingStartsIt() + public void OnlyTheServicesOfProgramsSetupInstalledAreFound() + { + var folder = Path.Combine(context.CreateTempDirectory("services"), "Apps"); + var owned = CommandProgram.FullPaths(folder, ["Titano.Server.exe", "Titano.exe", "lib/Titano.Core.dll"]); + var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); + try + { + using var services = Registry.CurrentUser.CreateSubKey(keyPath, writable: true); + Service(services, "TitanoServer", 0x10, $"\"{Path.Combine(folder, "Titano.Server.exe")}\" --service"); + Service(services, "TitanoServerUnquoted", 0x10, Path.Combine(folder, "TITANO.SERVER.EXE") + " --service"); + // Another vendor's service, and a driver, that live in the same folder (a shared D:\Apps): never Titano's. + Service(services, "OtherVendor", 0x10, $"\"{Path.Combine(folder, "Other", "Other.exe")}\""); + Service(services, "OtherBeside", 0x10, $"\"{Path.Combine(folder, "Helper.exe")}\" /run"); + Service(services, "Driver", 0x1, Path.Combine(folder, "Titano.Server.exe")); + using (var deleting = services.CreateSubKey("Deleting", writable: true)) + { + deleting.SetValue("Type", 0x10, RegistryValueKind.DWord); + deleting.SetValue("DeleteFlag", 1, RegistryValueKind.DWord); + deleting.SetValue("ImagePath", Path.Combine(folder, "Titano.Server.exe"), RegistryValueKind.ExpandString); + } + + var found = InstalledServices.Find(services, owned); + Assert.SequenceEqual(["TitanoServer", "TitanoServerUnquoted"], found.Select(s => s.Name).Order(StringComparer.Ordinal)); + Assert.True(found.All(s => s.Program.Equals(Path.Combine(folder, "Titano.Server.exe"), StringComparison.OrdinalIgnoreCase))); + Assert.Empty(InstalledServices.Find(services, CommandProgram.FullPaths(folder, ["Titano.exe"]))); + } + finally + { + DeleteTestKey(keyPath); + } + + static void Service(RegistryKey services, string name, int type, string imagePath) + { + using var key = services.CreateSubKey(name, writable: true); + key.SetValue("Type", type, RegistryValueKind.DWord); + key.SetValue("ImagePath", imagePath, RegistryValueKind.ExpandString); + } + } + + [Test] + [WindowsOnly] + public void AServiceThatIsNotRegisteredNeedsNothing() { var folder = context.CreateTempDirectory("services"); - // No service is registered from a fresh folder, and nothing is asked of the Service Control Manager. - Assert.Empty(InstalledServices.Find(folder)); - Assert.Equal(SetupExitCode.Success, InstalledServices.Apply(folder, ServiceActions.Remove)); + // No service starts a program of a fresh folder, and nothing is asked of the Service Control Manager. + Assert.Empty(InstalledServices.Find(CommandProgram.FullPaths(folder, ["Titano.Server.exe"]))); + Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([], ServiceActions.Remove)); - var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.Server.exe"), AutoStart: true); + var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.Server.exe")); Assert.False(InstalledServices.IsRunning(gone)); - Assert.True(InstalledServices.NeedsWork([gone], ServiceActions.Prune)); - Assert.True(InstalledServices.NeedsWork([gone], ServiceActions.Remove)); - Assert.False(InstalledServices.NeedsWork([gone], ServiceActions.Stop)); - Assert.False(InstalledServices.NeedsWork([gone], ServiceActions.Start)); - Assert.False(InstalledServices.NeedsWork([], ServiceActions.Remove)); + foreach (var action in (ServiceActions[])[ServiceActions.Stop, ServiceActions.Prune, ServiceActions.Start, ServiceActions.Remove]) + Assert.False(InstalledServices.NeedsWork([gone], action), $"{action} of a service that does not exist"); + // Applying to it skips it: a service deleted meanwhile is not a failure. + Assert.Equal(SetupExitCode.Success, InstalledServices.Apply([gone], ServiceActions.Remove | ServiceActions.Start)); } [Test] [WindowsOnly] - public void UninstallRemovesOnlyTheStartupEntriesOfItsFolder() + public void UninstallRemovesOnlyTheSignInEntriesOfTheProgramsItRemoves() { - var folder = Path.Combine(context.CreateTempDirectory("startup"), "Titano Uploader"); - const string testsKey = @"Software\Titano.Tests"; - var keyPath = testsKey + @"\" + Guid.NewGuid().ToString("N"); + var folder = Path.Combine(context.CreateTempDirectory("startup"), "Apps"); + var keyPath = TestsKey + @"\" + Guid.NewGuid().ToString("N"); try { using (var run = Registry.CurrentUser.CreateSubKey(keyPath, writable: true)) { - run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Titano.Uploader.exe")}\" --tray"); - run.SetValue("Unquoted", Path.Combine(folder, "tools", "Helper.exe") + " /quiet"); - run.SetValue("Other", @"""C:\Program Files\Other\Other.exe"" --background"); + run.SetValue("Titano Uploader", $"\"{Path.Combine(folder, "Uploader", "Titano.Uploader.exe")}\" --tray"); + // A portable Titano unpacked in a subfolder of the same folder: not a program this installation lists. + run.SetValue("Titano", $"\"{Path.Combine(folder, "Portable", "Titano.exe")}\" --minimized"); + // Another program in the same folder, and a copy in a sibling folder. + run.SetValue("Other", $"\"{Path.Combine(folder, "Other.exe")}\" --background"); run.SetValue("Sibling", $"\"{folder} 2\\Titano.Uploader.exe\""); - Assert.SequenceEqual(["Titano Uploader", "Unquoted"], StartupEntries.RemoveInside(run, folder).Order(StringComparer.Ordinal)); - Assert.SequenceEqual(["Other", "Sibling"], run.GetValueNames().Order(StringComparer.Ordinal)); + var programs = CommandProgram.FullPaths(folder, ["Titano.exe", "Uploader/Titano.Uploader.exe", "Other.exe"]); + Assert.SequenceEqual(["Titano Uploader"], SetupRegistry.DeleteStartupEntries(run, programs)); + Assert.SequenceEqual(["Other", "Sibling", "Titano"], run.GetValueNames().Order(StringComparer.Ordinal)); } } finally { - Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false); - bool empty; - using (var tests = Registry.CurrentUser.OpenSubKey(testsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 }; - if (empty) Registry.CurrentUser.DeleteSubKey(testsKey, throwOnMissingSubKey: false); + DeleteTestKey(keyPath); } } @@ -114,21 +168,80 @@ public sealed class SetupEngineTests(TestContext context) [Test] [WindowsOnly] - public void TheServerMakesANewInstallationAnAllUsersOne() + public void AnUninstalledProductHandsItsShortcutToTheProductThatKeepsTheProgram() + { + var root = context.CreateTempDirectory("handover"); + foreach (var product in (string[])["Product A", "Product B"]) + { + Directory.CreateDirectory(Path.Combine(root, product)); + File.WriteAllBytes(Path.Combine(root, product, "Titano.Uploader.exe"), [0x4D, 0x5A]); + } + // A uniquely named shortcut in the user's own Start menu, the only folder setup deletes shortcuts from. + var link = Path.Combine(SetupPaths.StartMenu(InstallScope.CurrentUser), "Titano Test " + Guid.NewGuid().ToString("N") + ".lnk"); + try + { + ShellLink.Create(link, Path.Combine(root, "Product A", "Titano.Uploader.exe"), "Titano Test"); + // The folders as the shell stores them (the long form of a short temporary path). + var productA = Path.GetDirectoryName(Assert.NotNull(ShellLink.TargetOf(link)))!; + var productB = Path.Combine(Path.GetDirectoryName(productA)!, "Product B"); + var logB = new InstallLog { Product = "Titano Uploader", Version = "1.0.0", Scope = InstallScope.CurrentUser, Files = ["Titano.Uploader.exe"], Shortcuts = [link] }; + + // Product B also has the program and lists the shortcut: uninstalling A points it at B's copy. + UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, logB)]); + var handed = Assert.NotNull(ShellLink.TargetOf(link)); + Assert.Equal("Product B", Path.GetFileName(Path.GetDirectoryName(handed))); + + // Uninstalling A again leaves B's shortcut alone; uninstalling B with nobody left deletes it. + UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, []); + Assert.FileExists(link); + UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productB, [new OtherInstall(productA, null)]); + Assert.FileMissing(link); + + // A product that does not list the shortcut, or whose folder cannot be read now, takes nothing over. + ShellLink.Create(link, Path.Combine(productA, "Titano.Uploader.exe"), "Titano Test"); + UninstallEngine.DeleteShortcut(link, InstallScope.CurrentUser, productA, [new OtherInstall(productB, new InstallLog { Product = "Titano", Version = "1.0.0", Files = ["Titano.Uploader.exe"] })]); + Assert.FileMissing(link); + } + finally + { + if (File.Exists(link)) File.Delete(link); + } + } + + [Test] + [WindowsOnly] + public void TheServerMakesANewInstallationAnAllUsersOneInsideProgramFiles() { var manifest = Manifest(); var plan = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano", "Server"] }); Assert.Equal(InstallScope.AllUsers, plan.Scope); Assert.Equal(SetupPaths.DefaultDirectory(InstallScope.AllUsers, manifest.Product), plan.Directory); + Assert.True(InstallPlan.IsValidDirectory(manifest, plan.Scope, plan.Directory, plan.Components)); + + // A folder standard users can change (C:\Titano, D:\Apps\Titano) would let them replace what the service starts. + var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + var custom = Path.Combine(Path.GetPathRoot(programFiles)!, "Titano"); + Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano", "Server"])); + Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, custom, ["Titano"])); + Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, custom, ["Titano"])); + Assert.False(InstallPlan.IsValidDirectory(manifest, InstallScope.CurrentUser, Path.Combine(programFiles, "Titano"), ["Server"])); + Assert.True(InstallPlan.IsValidDirectory(manifest, InstallScope.AllUsers, Path.Combine(programFiles, "Vendor", "Titano"), ["Server"])); + Assert.False(SetupPaths.IsInsideProgramFiles(programFiles), "Program Files itself is shared by every program"); + Assert.False(SetupPaths.IsInsideProgramFiles(programFiles + " Extra" + Path.DirectorySeparatorChar + "Titano")); var desktop = InstallPlan.Resolve(manifest, new SetupArguments { Components = ["Titano"] }); Assert.Equal(InstallScope.CurrentUser, desktop.Scope); Assert.True(desktop.CanInstall(manifest.FindComponent("Server")!)); - // A per-user installation upgraded in place keeps its scope, so it cannot take the Server. + // A per-user installation upgraded in place keeps its scope, so it cannot take the Server; nor can an + // all-users one in a folder outside Program Files. var perUser = desktop with { Existing = new ExistingInstall(InstallScope.CurrentUser, desktop.Directory, "0.9.0") }; Assert.False(perUser.CanInstall(manifest.FindComponent("Server")!)); Assert.True(perUser.CanInstall(manifest.FindComponent("Titano")!)); + var elsewhere = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, custom, "0.9.0") }; + Assert.False(elsewhere.CanInstall(manifest.FindComponent("Server")!)); + var protectedFolder = desktop with { Existing = new ExistingInstall(InstallScope.AllUsers, Path.Combine(programFiles, "Titano"), "0.9.0") }; + Assert.True(protectedFolder.CanInstall(manifest.FindComponent("Server")!)); } [Test] @@ -142,6 +255,15 @@ public sealed class SetupEngineTests(TestContext context) Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it"))); } + /// Deletes a scratch key under , and that key too once it is empty. + private static void DeleteTestKey(string keyPath) + { + Registry.CurrentUser.DeleteSubKeyTree(keyPath, throwOnMissingSubKey: false); + bool empty; + using (var tests = Registry.CurrentUser.OpenSubKey(TestsKey)) empty = tests is { SubKeyCount: 0, ValueCount: 0 }; + if (empty) Registry.CurrentUser.DeleteSubKey(TestsKey, throwOnMissingSubKey: false); + } + /// A manifest under a product name no machine has installed, so the registry holds no installation of it. private static PayloadManifest Manifest() => new() { diff --git a/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs b/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs index ca636e13..8646284e 100644 --- a/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs +++ b/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs @@ -77,6 +77,18 @@ public sealed class UserDataPlanTests(TestContext context) Assert.Empty(UserDataOwners.Removable(["Server"], [])); } + [Test] + public void AnInstallationThatCannotBeReadNowKeepsEveryProgramsData() + { + string[] titano = ["Titano", "Uploader", "Server"]; + var uploader = new InstallLog { Product = "Titano Uploader", Version = "1.0.0", Components = ["Uploader"] }; + + Assert.SequenceEqual(["Titano"], UserDataOwners.RemovableBeside(titano, [new OtherInstall(@"D:\Titano Uploader", uploader)]).Order(StringComparer.Ordinal)); + // Its drive is offline, its folder is gone or its log is damaged: it may still use the desktop app's index. + Assert.Empty(UserDataOwners.RemovableBeside(titano, [new OtherInstall(@"E:\Titano Uploader", null)])); + Assert.Empty(UserDataOwners.RemovableBeside(titano, [new OtherInstall(null, null)])); + } + private static HashSet Owners(params string[] owners) => new(owners, StringComparer.OrdinalIgnoreCase); private string SampleFolder() diff --git a/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs new file mode 100644 index 00000000..6a24ece3 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/StartupCommandTests.cs @@ -0,0 +1,58 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +/// The sign-in entries of the client and the Uploader: which copy they start, and which folder the uninstaller may clean. +public sealed class StartupCommandTests +{ + private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe"; + + [Test] + public void TheCommandNamesItsProgram() + { + var command = StartupCommand.Format(Installed, "--minimized"); + Assert.Equal("\"" + Installed + "\" --minimized", command); + Assert.Equal(Installed, StartupCommand.Executable(command)); + Assert.Equal(@"C:\Users\ada\AppData\Local\Programs\Titano", StartupCommand.Folder(command)); + // Written by hand or by an older tool: unquoted, or with spaces around. + Assert.Equal(@"D:\Titano\Titano.exe", StartupCommand.Executable(@" D:\Titano\Titano.exe --minimized ")); + Assert.Equal(@"D:\Titano\Titano.exe", StartupCommand.Executable(@"D:\Titano\Titano.exe")); + Assert.Null(StartupCommand.Executable(null)); + Assert.Null(StartupCommand.Executable(" ")); + Assert.Null(StartupCommand.Executable("\"unterminated --minimized")); + Assert.Null(StartupCommand.Executable("\"\" --minimized")); + Assert.Null(StartupCommand.Folder("Titano.exe")); + Assert.Equal(@"D:\Titano", StartupCommand.FolderOf(@"D:\Titano\Titano.exe")); + } + + [Test] + public void AnEntryBelongsToTheCopyItStarts() + { + var command = StartupCommand.Format(Installed, "--minimized"); + Assert.True(StartupCommand.Starts(command, Installed)); + Assert.True(StartupCommand.Starts(command, Installed.ToUpperInvariant()), "Windows paths ignore case"); + // A portable copy on a USB stick, a second install or a development build is another program. + Assert.False(StartupCommand.Starts(command, @"E:\Titano\Titano.exe")); + Assert.False(StartupCommand.Starts(command, @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe.old")); + Assert.False(StartupCommand.Starts(command, null)); + Assert.False(StartupCommand.Starts(null, Installed)); + } + + [Test] + public void TheUninstallerRemovesOnlyTheEntriesOfItsFolder() + { + var client = StartupCommand.Format(Installed, "--minimized"); + var uploader = StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe", "--tray"); + const string folder = @"C:\Users\ada\AppData\Local\Programs\Titano"; + Assert.True(StartupCommand.StartsFrom(client, folder)); + Assert.True(StartupCommand.StartsFrom(client, folder + @"\")); + Assert.True(StartupCommand.StartsFrom(uploader, folder.ToLowerInvariant())); + // A sibling folder that shares the name's start, another drive, or nothing at all stay. + Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano2\Titano.exe", "--minimized"), folder)); + Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(@"E:\Titano\Titano.exe", "--minimized"), folder)); + Assert.False(StartupCommand.StartsFrom(StartupCommand.Format(folder, "--minimized"), folder)); + Assert.False(StartupCommand.StartsFrom(null, folder)); + Assert.False(StartupCommand.StartsFrom(client, @"\")); + } +}