From 4f6bbfba5d2d72cc7ca68ae8310922917ad46e41 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 10:29:16 +0000 Subject: [PATCH] fix(setup): handle install-folder services, startup entries, shared shortcuts and data - Windows services whose program lies in the install folder (Titano.Server --install-service) are found in the registry and, through the Service Control Manager, stopped before files are replaced (they join the "programs running" prompt), started again after an upgrade that stopped them, deleted when an upgrade drops their program and on uninstall. An unelevated setup runs that step in an elevated copy (/SERVICES=...). - The Server component installs for all users only (manifest allUsersOnly): choosing it moves a new install to Program Files and disables "Just me" with the reason; a per-user install cannot take it. - Uninstall removes every HKCU Run value that starts a program in the folder (the Uploader's "Start with Windows"). - A shortcut that already starts an existing program elsewhere is neither retargeted nor logged, and a logged shortcut is deleted only while it still starts a program of this folder, so the two products no longer remove each other's "Titano Uploader" shortcuts. - "Remove my data" lists and deletes only the data of this product's programs that no other installed Titano product uses (the desktop app and the Uploader share %LOCALAPPDATA%\Titano and its logs folder). - The .titano file type is named in setup's language (Setup.FileType.*). Setup tests run in Titano.App.Tests on Windows CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- deploy/releases-repo/README.md | 6 +- i18n/en/Setup.resx | 1 + i18n/en/Tooltips.resx | 5 + i18n/it/Setup.it.resx | 1 + i18n/it/Tooltips.it.resx | 5 + src/Titano.Core/Packaging/PayloadManifest.cs | 6 + src/Titano.Core/Packaging/PayloadWriter.cs | 5 +- src/Titano.Setup/Cli/SetupArguments.cs | 21 +- src/Titano.Setup/Engine/CommandProgram.cs | 60 +++++ src/Titano.Setup/Engine/InstallEngine.cs | 36 ++- src/Titano.Setup/Engine/InstallPlan.cs | 30 ++- src/Titano.Setup/Engine/InstalledServices.cs | 238 ++++++++++++++++++ src/Titano.Setup/Engine/RunningPrograms.cs | 19 +- src/Titano.Setup/Engine/SetupRegistry.cs | 30 +++ src/Titano.Setup/Engine/SilentSetup.cs | 50 +++- src/Titano.Setup/Engine/StartupEntries.cs | 46 ++++ src/Titano.Setup/Engine/UninstallEngine.cs | 36 ++- src/Titano.Setup/Engine/UserDataPlan.cs | 96 ++++++- src/Titano.Setup/Interop/ServiceNative.cs | 74 ++++++ src/Titano.Setup/Interop/ShellLink.cs | 47 +++- src/Titano.Setup/Program.cs | 5 +- src/Titano.Setup/Titano.Setup.csproj | 3 + src/Titano.Setup/Views/ComponentOption.cs | 19 +- src/Titano.Setup/Views/SetupCapture.cs | 8 +- src/Titano.Setup/Views/SetupViewModel.cs | 91 +++++-- src/Titano.Setup/Views/SetupWindow.xaml | 9 +- .../Commands/PackInstallerCommand.cs | 10 +- .../Infrastructure/StartupRegistration.cs | 3 +- .../Setup/SetupEngineTests.cs | 156 ++++++++++++ .../Setup/UserDataPlanTests.cs | 102 ++++++++ .../Titano.App.Tests/Titano.App.Tests.csproj | 1 + .../PackInstallerCommandTests.cs | 44 ++++ 32 files changed, 1175 insertions(+), 88 deletions(-) create mode 100644 src/Titano.Setup/Engine/CommandProgram.cs create mode 100644 src/Titano.Setup/Engine/InstalledServices.cs create mode 100644 src/Titano.Setup/Engine/StartupEntries.cs create mode 100644 src/Titano.Setup/Interop/ServiceNative.cs create mode 100644 tests/Titano.App.Tests/Setup/SetupEngineTests.cs create mode 100644 tests/Titano.App.Tests/Setup/UserDataPlanTests.cs create mode 100644 tests/Titano.Tools.Tests/PackInstallerCommandTests.cs diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index 19fcefa7..83f3f7a6 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -41,13 +41,15 @@ for community review. Development happens elsewhere; please use the issues here `Get-FileHash .\Titano-Setup-.exe -Algorithm SHA256` and compare the value with the line for that file 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). + 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. - **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; run it to upgrade in place. Your archive, settings and index are kept. - **Uninstall:** Windows Settings › Apps › Installed apps › Titano › Uninstall. Your photos and archive are never - touched; the program data folder (`%LOCALAPPDATA%\Titano`) is removed only if you tick the option to do so. + touched; the program data in `%LOCALAPPDATA%\Titano` is removed only if you tick the option to do so, and only the + part no other installed Titano program still uses. A Titano Server service of that folder is stopped and removed. - **Silent install** (IT deployment): `Titano-Setup-.exe /S [/DIR="D:\Apps\Titano"] [/ALLUSERS] [/COMPONENTS=Titano,Uploader,Server] [/NODESKTOP] [/NOSTARTMENU] [/LANG=it]`. Silent uninstall: `"%LOCALAPPDATA%\Programs\Titano\Uninstall Titano.exe" /uninstall /S`. diff --git a/i18n/en/Setup.resx b/i18n/en/Setup.resx index 651318ff..9a624382 100644 --- a/i18n/en/Setup.resx +++ b/i18n/en/Setup.resx @@ -31,6 +31,7 @@ Language Options Install for + Titano project Browse Version {0} · installed {1} Version {0} diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 915ab73b..71b9d485 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -560,6 +560,7 @@ Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies Send a daily anonymous count of versions and languages in use; nothing else, off by default Install in Program Files for every account · asks for administrator approval + {0} · it runs as a Windows service, so it installs for all users in Program Files Return to the options without changing anything Choose the installation folder Close setup without changing anything @@ -575,12 +576,16 @@ Copy the selected programs and register them with Windows Folder of the installed programs Install in your user folder · no administrator rights needed + {0} runs as a Windows service, so it installs for all users only Language of this setup Open the program when setup finishes 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 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 + Also delete the Uploader’s queue, settings, sign-in and logs in %LOCALAPPDATA%\Titano · Titano’s files and photos in archives are kept Run the same step again Add the programs to the Start menu Remove programs, shortcuts and file types · your data is kept unless selected diff --git a/i18n/it/Setup.it.resx b/i18n/it/Setup.it.resx index 57e525ae..2156a9e5 100644 --- a/i18n/it/Setup.it.resx +++ b/i18n/it/Setup.it.resx @@ -31,6 +31,7 @@ Lingua Opzioni Installa per + Progetto Titano Sfoglia Versione {0} · installata {1} Versione {0} diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 634fa3ca..acfb90d1 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -560,6 +560,7 @@ Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore + {0} · è un servizio di Windows, quindi si installa per tutti gli utenti in Programmi Torna alle opzioni senza modificare nulla Scegli la cartella di installazione Chiudi l'installazione senza modificare nulla @@ -575,12 +576,16 @@ Copia i programmi selezionati e registrali in Windows Cartella dei programmi installati Installa nella tua cartella utente · non servono diritti di amministratore + {0} è un servizio di Windows, quindi si installa solo per tutti gli utenti Lingua di questa installazione Apri il programma al termine dell'installazione 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 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 + Elimina anche coda, impostazioni, accesso e log dell'uploader in %LOCALAPPDATA%\Titano · i file di Titano e le foto negli archivi restano Esegui di nuovo lo stesso passaggio Aggiungi i programmi al menu Start Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta diff --git a/src/Titano.Core/Packaging/PayloadManifest.cs b/src/Titano.Core/Packaging/PayloadManifest.cs index e4b304cc..0f1cf32e 100644 --- a/src/Titano.Core/Packaging/PayloadManifest.cs +++ b/src/Titano.Core/Packaging/PayloadManifest.cs @@ -155,6 +155,12 @@ public sealed class PayloadComponent /// Installed size in bytes (sum of the component's files). public long EstimatedSize { get; init; } + + /// + /// Installs only for all users (Program Files): the component runs as a Windows service under LocalSystem, which + /// must not start a program from a folder its user can write to. + /// + public bool AllUsersOnly { get; init; } } /// One installed file and where its bytes live in the data region. diff --git a/src/Titano.Core/Packaging/PayloadWriter.cs b/src/Titano.Core/Packaging/PayloadWriter.cs index 09b3d5ac..ffcf06f5 100644 --- a/src/Titano.Core/Packaging/PayloadWriter.cs +++ b/src/Titano.Core/Packaging/PayloadWriter.cs @@ -5,8 +5,8 @@ using Titano.Core.IO; namespace Titano.Core.Packaging; -/// A component to pack: its manifest identity and the folder whose whole tree it installs. -public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder); +/// A component to pack: its manifest identity, the folder whose whole tree it installs and whether it needs an all-users install. +public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder, bool AllUsersOnly = false); /// Everything the packer needs besides the setup program. public sealed class PayloadSource @@ -48,6 +48,7 @@ public static class PayloadWriter Id = c.Id, DisplayName = c.DisplayName, DefaultSelected = c.DefaultSelected, + AllUsersOnly = c.AllUsersOnly, EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size), }).ToList(); var manifest = new PayloadManifest diff --git a/src/Titano.Setup/Cli/SetupArguments.cs b/src/Titano.Setup/Cli/SetupArguments.cs index e5f54e19..52f52c29 100644 --- a/src/Titano.Setup/Cli/SetupArguments.cs +++ b/src/Titano.Setup/Cli/SetupArguments.cs @@ -1,4 +1,5 @@ using System.Text; +using Titano.Setup.Engine; namespace Titano.Setup.Cli; @@ -7,7 +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). +/// 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). /// internal sealed record SetupArguments { @@ -23,6 +25,7 @@ internal sealed record SetupArguments public bool Elevated { get; init; } public string? CleanupTarget { get; init; } public int WaitProcessId { get; init; } + public ServiceActions Services { get; init; } /// Parses ; throws for unknown or malformed switches. public static SetupArguments Parse(IEnumerable args) @@ -48,10 +51,12 @@ internal sealed record SetupArguments ("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }, ("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) }, _ => 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."); return result; } @@ -67,9 +72,23 @@ internal sealed record SetupArguments if (NoStartMenu) yield return "/NOSTARTMENU"; 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 (Elevated) yield return "/ELEVATED"; } + /// A comma-separated list of names, in any case. + private static ServiceActions ParseServices(string value) + { + var actions = ServiceActions.None; + foreach (var name in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (!Enum.TryParse(name, ignoreCase: true, out var action) || action == ServiceActions.None || !Enum.IsDefined(action)) + throw new ArgumentException($"Unknown service action '{name}'."); + actions |= action; + } + return actions; + } + /// /// Joins arguments into one command line that CommandLineToArgvW splits back into the same strings /// (quotes around spaces, backslashes doubled before a quote). diff --git a/src/Titano.Setup/Engine/CommandProgram.cs b/src/Titano.Setup/Engine/CommandProgram.cs new file mode 100644 index 00000000..a734fbce --- /dev/null +++ b/src/Titano.Setup/Engine/CommandProgram.cs @@ -0,0 +1,60 @@ +using System.IO; + +namespace Titano.Setup.Engine; + +/// The program a command line registered with Windows starts: a service's image path, a Run value. +internal static class CommandProgram +{ + /// + /// The first token, quoted or up to .exe, with environment variables expanded; for the dotnet host, + /// the assembly it runs. Null when the line names no full path. + /// + public static string? Of(string commandLine) + { + var line = Environment.ExpandEnvironmentVariables(commandLine).Trim(); + var first = NextToken(ref line); + if (first is null) return null; + if (Path.GetFileNameWithoutExtension(first).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) first = NextToken(ref line); + 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); + + /// that answers false for a path Windows cannot normalise. + public static bool IsPathInside(string path, string directory) + { + try + { + return SetupPaths.IsSameOrInside(path, directory); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + /// Takes the next token of a command line: quoted, or up to .exe followed by a space, or up to the next space. + private static string? NextToken(ref string line) + { + line = line.TrimStart(); + if (line.Length == 0) return null; + string token; + if (line[0] == '"') + { + var close = line.IndexOf('"', 1); + token = close < 0 ? line[1..] : line[1..close]; + line = close < 0 ? string.Empty : line[(close + 1)..]; + } + else + { + // An unquoted path with spaces ("C:\Program Files\Titano\Titano.Server.exe --service") ends at its extension. + var exe = line.IndexOf(".exe", StringComparison.OrdinalIgnoreCase); + var space = line.IndexOf(' '); + var end = exe >= 0 && (exe + 4 == line.Length || line[exe + 4] == ' ') ? exe + 4 : space >= 0 ? space : line.Length; + token = line[..end]; + line = line[end..]; + } + return token.Length == 0 ? null : token; + } +} diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs index dc216279..88cf5597 100644 --- a/src/Titano.Setup/Engine/InstallEngine.cs +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -1,6 +1,8 @@ +using System.Globalization; using System.IO; using System.Reflection; using Titano.Core.Diagnostics; +using Titano.Core.Localization; using Titano.Core.Packaging; using Titano.Setup.Cli; using Titano.Setup.Interop; @@ -74,7 +76,7 @@ internal sealed class InstallEngine(PayloadReader payload) foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name); foreach (var a in fileTypes) - SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target)); + 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(); var uninstallerPath = Path.Combine(directory, uninstaller); @@ -86,13 +88,27 @@ internal sealed class InstallEngine(PayloadReader payload) return log; } - private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano"; + /// The Add/Remove Programs publisher of every Titano product (they share the user data folder). + public static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano"; + + /// + /// The file type name Explorer shows, in setup's language (or ): + /// Setup.FileType.<last part of the ProgID> ("Titano.Project" → Setup.FileType.Project), else the + /// manifest's English description. + /// + public static string FileTypeName(PayloadAssociation association, CultureInfo? culture = null) => + Loc.Get("Setup.FileType." + association.ProgId[(association.ProgId.LastIndexOf('.') + 1)..], culture ?? Loc.Culture) ?? association.Description; private static string? AboutUrl => typeof(InstallEngine).Assembly.GetCustomAttributes().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo ? "https://github.com/" + repo : 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. + /// private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory) { var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); @@ -100,10 +116,20 @@ internal sealed class InstallEngine(PayloadReader payload) foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component))) { var target = PayloadPath.Resolve(directory, s.Target); - if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name)); - if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name)); + if (s.StartMenu && request.StartMenuShortcuts) Add(Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name); + if (s.Desktop && request.DesktopShortcuts) Add(Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name); } return result; + + void Add(string link, string target, string name) + { + 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; + } + result.Add((link, target, name)); + } } private List PlanFileTypes(InstallRequest request) @@ -118,7 +144,7 @@ internal sealed class InstallEngine(PayloadReader payload) 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); + UninstallEngine.DeleteShortcut(link, previous.Scope, directory); 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/InstallPlan.cs b/src/Titano.Setup/Engine/InstallPlan.cs index 6b9f3cdc..d89084d7 100644 --- a/src/Titano.Setup/Engine/InstallPlan.cs +++ b/src/Titano.Setup/Engine/InstallPlan.cs @@ -1,3 +1,4 @@ +using Titano.Core.Diagnostics; using Titano.Core.Packaging; using Titano.Setup.Cli; @@ -5,7 +6,9 @@ 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. +/// (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. /// internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing) { @@ -13,7 +16,6 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn { var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product)); var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); - var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product); IReadOnlyList components; if (arguments.Components is { } requested) @@ -28,9 +30,33 @@ internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOn var kept = previous?.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList(); components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; } + + var allUsersOnly = components.Where(id => manifest.FindComponent(id)!.AllUsersOnly).ToList(); + if (allUsersOnly.Count > 0 && scope == InstallScope.CurrentUser) + { + if (existing is null) + { + scope = InstallScope.AllUsers; + } + else 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)]; + } + } + 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 }); + /// Executables to look for among running processes: the new payload's and the previous install's. public static IEnumerable Programs(PayloadManifest manifest, string directory) => manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []); diff --git a/src/Titano.Setup/Engine/InstalledServices.cs b/src/Titano.Setup/Engine/InstalledServices.cs new file mode 100644 index 00000000..d01dd4e3 --- /dev/null +++ b/src/Titano.Setup/Engine/InstalledServices.cs @@ -0,0 +1,238 @@ +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using Microsoft.Win32; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +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). +/// 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); + +/// What setup does with the services of an installation; several may be combined. +[Flags] +internal enum ServiceActions +{ + None = 0, + + /// Stops the running ones, before their files are replaced. + Stop = 1, + + /// 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). + Start = 4, + + /// Stops and deletes them all (uninstall), so no service is left pointing at a deleted program. + Remove = 8, +} + +/// +/// 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=…). +/// +internal static class InstalledServices +{ + private const string ServicesKey = @"SYSTEM\CurrentControlSet\Services"; + + /// SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS: programs, not drivers. + private const int Win32Service = 0x30; + + private const int AutoStartType = 2; + + /// 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) + { + 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}"); + } + } + 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); + } + } + + /// 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))); + + /// + /// 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. + /// + public static async Task ApplyAsync(string directory, 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 }; + 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. + /// + 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; + } + + /// + /// Applies in this process (administrator rights). Returns + /// when a service did not stop in time, + /// when the Service Control Manager refused a step (logged). + /// + public static unsafe SetupExitCode Apply(string directory, 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); + try + { + foreach (var service in services) + { + var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus | ServiceStop | ServiceStart | Delete); + if (handle == 0) + { + if (Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist) continue; + return Failure("Service not opened", service); + } + try + { + var remove = actions.HasFlag(ServiceActions.Remove) || (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program)); + if ((remove || actions.HasFlag(ServiceActions.Stop)) && !Stop(handle, service)) return SetupExitCode.ProgramRunning; + if (remove) + { + 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)) + { + if (!StartServiceW(handle, 0, 0) && Marshal.GetLastPInvokeError() != ErrorServiceAlreadyRunning) return Failure("Service not started", service); + Log.Info("setup", $"Service {service.Name} started"); + } + } + finally + { + CloseServiceHandle(handle); + } + } + return SetupExitCode.Success; + } + finally + { + CloseServiceHandle(manager); + } + } + + /// 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) + { + if (!TryQuery(handle, out var status)) return false; + if (status.CurrentState == StateStopped) return true; + var processId = (int)status.ProcessId; + ServiceStatus stopped; + if (!ControlService(handle, ControlStop, &stopped) && Marshal.GetLastPInvokeError() is var error && error != ErrorServiceNotActive) + Log.Warning("setup", $"Service {service.Name} refused to stop (error {error}); waiting for it"); + var deadline = Stopwatch.StartNew(); + while (TryQuery(handle, out status) && status.CurrentState != StateStopped) + { + if (deadline.Elapsed > StopTimeout) + { + Log.Warning("setup", $"Service {service.Name} did not stop within {StopTimeout.TotalSeconds:0} s"); + return false; + } + Thread.Sleep(250); + } + if (processId != 0) WaitForExit(processId, StopTimeout - deadline.Elapsed); + Log.Info("setup", $"Service {service.Name} stopped"); + return true; + } + + private static void WaitForExit(int processId, TimeSpan timeout) + { + try + { + using var process = Process.GetProcessById(processId); + process.WaitForExit(timeout > TimeSpan.Zero ? timeout : TimeSpan.Zero); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception) + { + // Already gone, or not ours to wait for: the stopped state is what counts. + } + } + + private static unsafe bool TryQuery(nint handle, out ServiceStatusProcess status) + { + ServiceStatusProcess value; + var ok = QueryServiceStatusEx(handle, StatusProcessInfo, &value, sizeof(ServiceStatusProcess), out _); + status = value; + return ok; + } + + private static SetupExitCode Failure(string what, InstalledService? service) + { + var error = Marshal.GetLastPInvokeError(); + Log.Error("setup", $"{what}{(service is null ? string.Empty : " (" + service.Name + ")")}: error {error}"); + return SetupExitCode.Failed; + } +} diff --git a/src/Titano.Setup/Engine/RunningPrograms.cs b/src/Titano.Setup/Engine/RunningPrograms.cs index b060a50b..a7942ae9 100644 --- a/src/Titano.Setup/Engine/RunningPrograms.cs +++ b/src/Titano.Setup/Engine/RunningPrograms.cs @@ -6,13 +6,18 @@ namespace Titano.Setup.Engine; /// /// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when -/// the user clicks ✕); it never terminates a process. +/// the user clicks ✕); it never terminates a process. A program running as a Windows service is stopped through +/// the Service Control Manager instead (). /// internal static class RunningPrograms { - /// Processes of (payload paths) started from inside . - public static IReadOnlyList Find(string directory, IEnumerable executables) + /// + /// Processes of (payload paths) started from inside , + /// except the programs of , which ignore WM_CLOSE. + /// + public static IReadOnlyList Find(string directory, IEnumerable executables, IReadOnlyCollection? services = null) { + var servicePrograms = new HashSet((services ?? []).Select(s => s.Program), StringComparer.OrdinalIgnoreCase); var names = executables .Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal)) .Select(Path.GetFileNameWithoutExtension) @@ -23,16 +28,16 @@ internal static class RunningPrograms foreach (var process in Process.GetProcessesByName(name)) { var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id); - if (image is not null && SetupPaths.IsSameOrInside(image, directory)) found.Add(process); + if (image is not null && SetupPaths.IsSameOrInside(image, directory) && !servicePrograms.Contains(image)) found.Add(process); else process.Dispose(); } } return found; } - /// Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt. - public static string Describe(IReadOnlyList processes) => - string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase)); + /// Display names ("Titano", "Titano.Uploader", a service's "Titano Server") of what must close, for the prompt. + public static string Describe(IReadOnlyList processes, IReadOnlyCollection? services = null) => + string.Join(", ", processes.Select(p => p.ProcessName).Concat((services ?? []).Select(s => s.DisplayName)).Distinct(StringComparer.OrdinalIgnoreCase)); /// Asks each process to close and waits up to ; returns those still running. public static async Task> CloseAsync(IReadOnlyList processes, TimeSpan timeout) diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs index 006c7703..ab75aa1d 100644 --- a/src/Titano.Setup/Engine/SetupRegistry.cs +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -35,6 +35,36 @@ internal static partial class SetupRegistry return null; } + /// + /// 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). + /// + public static IReadOnlyList OtherInstalls(string directory, string publisher) + { + var found = new List(); + foreach (var scope in (ReadOnlySpan)[InstallScope.CurrentUser, InstallScope.AllUsers]) + { + using var root = Hive(scope).OpenSubKey(UninstallRoot.TrimEnd('\\')); + if (root is null) continue; + foreach (var name in root.GetSubKeyNames()) + { + try + { + 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); + } + catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException) + { + // Another program's entry this account may not read. + } + } + } + return found; + } + public static void WriteUninstallEntry(InstallScope scope, string productKey, UninstallEntry entry) { using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true); diff --git a/src/Titano.Setup/Engine/SilentSetup.cs b/src/Titano.Setup/Engine/SilentSetup.cs index a0c7a398..9d1e20da 100644 --- a/src/Titano.Setup/Engine/SilentSetup.cs +++ b/src/Titano.Setup/Engine/SilentSetup.cs @@ -8,7 +8,8 @@ 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 . -/// Silent uninstall never removes user data. +/// 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. /// internal static class SilentSetup { @@ -51,10 +52,14 @@ internal static class SilentSetup if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); - if (!await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory)).ConfigureAwait(false)) - return SetupExitCode.ProgramRunning; + var closed = await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory), ServiceActions.Stop).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); + // 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); + if (services != SetupExitCode.Success) return services; if (launch is null) return SetupExitCode.Success; if (arguments.Elevated) return SetupExitCode.LaunchRequested; @@ -68,8 +73,12 @@ 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); - if (!await CloseProgramsAsync(product.Directory, product.Log.Files).ConfigureAwait(false)) return SetupExitCode.ProgramRunning; - UninstallEngine.Uninstall(product, removeUserData: false, null); + var closed = await CloseProgramsAsync(product.Directory, product.Log.Files, ServiceActions.Remove).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; + UninstallEngine.Uninstall(product, userData: null, null); return SetupExitCode.Success; } @@ -87,13 +96,30 @@ internal static class SilentSetup } } - private static async Task CloseProgramsAsync(string directory, IEnumerable programs) + /// + /// Applies to the running services of (an elevated step + /// when needed), then asks the running programs to close. + /// + private static async Task<(SetupExitCode Code, bool StoppedServices)> CloseProgramsAsync(string directory, IEnumerable programs, ServiceActions toServices) { - var running = RunningPrograms.Find(directory, programs); - if (running.Count == 0) return true; - Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close"); - var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false); - foreach (var p in running) p.Dispose(); - return still.Count == 0; + var services = InstalledServices.Find(directory).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); + 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); + } + finally + { + foreach (var p in running) p.Dispose(); + } } } diff --git a/src/Titano.Setup/Engine/StartupEntries.cs b/src/Titano.Setup/Engine/StartupEntries.cs new file mode 100644 index 00000000..73489a24 --- /dev/null +++ b/src/Titano.Setup/Engine/StartupEntries.cs @@ -0,0 +1,46 @@ +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 d793b225..dae792ca 100644 --- a/src/Titano.Setup/Engine/UninstallEngine.cs +++ b/src/Titano.Setup/Engine/UninstallEngine.cs @@ -10,9 +10,11 @@ namespace Titano.Setup.Engine; internal sealed record InstalledProduct(string Directory, InstallLog Log); /// -/// Removes an installation using only its log: shortcuts, 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; the user data folder -/// is deleted only when removeUserData is set by an explicit choice in the window. +/// 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 +/// (), as that may need an elevated step. /// internal static class UninstallEngine { @@ -29,17 +31,19 @@ internal static class UninstallEngine return null; } - public static void Uninstall(InstalledProduct product, bool removeUserData, IProgress? progress) + /// The "Remove my data" plan the user confirmed; null keeps the user data. + public static void Uninstall(InstalledProduct product, UserDataPlan? userData, IProgress? progress) { var (directory, log) = product; - Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {removeUserData})"); + Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {userData is not null})"); // First, so that a failure here leaves the program installed and the uninstaller able to retry. - if (removeUserData && Directory.Exists(SetupPaths.UserData)) + if (userData is { Entries.Count: > 0 }) { - Log.Info("setup", $"Removing user data '{SetupPaths.UserData}' at the user's request"); - Directory.Delete(SetupPaths.UserData, recursive: true); + 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); + foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope, directory); + StartupEntries.RemoveInside(directory); progress?.Report(new SetupProgress(0.1, string.Empty)); var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList(); @@ -82,8 +86,12 @@ internal static class UninstallEngine progress?.Report(new SetupProgress(1, string.Empty)); } - /// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder. - public static void DeleteShortcut(string link, InstallScope scope) + /// + /// 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. + /// + public static void DeleteShortcut(string link, InstallScope scope, string directory) { var folder = Path.GetDirectoryName(link); var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) @@ -96,6 +104,12 @@ internal static class UninstallEngine } try { + if (ShellLink.TargetOf(link) is not { } target) return; + if (!CommandProgram.IsPathInside(target, directory)) + { + Log.Info("setup", $"Shortcut '{link}' now starts '{target}'; kept"); + return; + } File.Delete(link); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/src/Titano.Setup/Engine/UserDataPlan.cs b/src/Titano.Setup/Engine/UserDataPlan.cs index 1e773ba1..07642f84 100644 --- a/src/Titano.Setup/Engine/UserDataPlan.cs +++ b/src/Titano.Setup/Engine/UserDataPlan.cs @@ -2,15 +2,17 @@ using System.IO; namespace Titano.Setup.Engine; -/// One top-level file or folder of the user data folder and the bytes it holds. +/// One file or folder of the user data folder (its path relative to that folder) and the bytes it holds. internal sealed record UserDataEntry(string Name, long Bytes); /// -/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): every top-level -/// entry of the user data folder with its size, largest first. Links are not followed, as the deletion does not -/// follow them either. +/// Dry run of "Remove my data" (BRIEF §0.2 rule 8: a destructive operation shows its plan first): the entries of the +/// user data folder that belong to the programs being removed, with their sizes, largest first. The desktop app and +/// the Uploader share the folder (and its logs), so uninstalling one product never lists what another +/// installed product still uses (). deletes exactly these entries. +/// Links are not followed, as the deletion does not follow them either. /// -internal sealed record UserDataPlan(IReadOnlyList Entries) +internal sealed record UserDataPlan(string Folder, IReadOnlyList Entries) { private static readonly EnumerationOptions TopLevel = new() { IgnoreInaccessible = true, AttributesToSkip = 0 }; @@ -23,13 +25,52 @@ internal sealed record UserDataPlan(IReadOnlyList Entries) public long TotalBytes => Entries.Sum(e => e.Bytes); - /// Measures ; empty when it does not exist. Reads sizes only, changes nothing. - public static UserDataPlan Measure(string folder) + /// + /// Measures what of belongs to (component ids); empty when the + /// folder does not exist or no owner is given. Reads sizes only, changes nothing. + /// + public static UserDataPlan Measure(string folder, IReadOnlySet owners) { var root = new DirectoryInfo(folder); - if (!root.Exists) return new UserDataPlan([]); - var entries = root.EnumerateFileSystemInfos("*", TopLevel).Select(e => new UserDataEntry(e.Name, SizeOf(e))); - return new UserDataPlan([.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]); + if (!root.Exists || owners.Count == 0) return new UserDataPlan(folder, []); + var whole = UserDataOwners.All.All(owners.Contains); + var entries = new List(); + foreach (var entry in root.EnumerateFileSystemInfos("*", TopLevel)) + { + if (!whole && entry is DirectoryInfo shared && UserDataOwners.IsShared(shared)) + { + // A folder both programs write to: only this product's files in it. + entries.AddRange(shared.EnumerateFileSystemInfos("*", TopLevel) + .Where(e => owners.Contains(UserDataOwners.OwnerOf(e.Name))) + .Select(e => new UserDataEntry(Path.Combine(shared.Name, e.Name), SizeOf(e)))); + } + else if (owners.Contains(UserDataOwners.OwnerOf(entry.Name))) + { + entries.Add(new UserDataEntry(entry.Name, SizeOf(entry))); + } + } + return new UserDataPlan(folder, [.. entries.OrderByDescending(e => e.Bytes).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)]); + } + + /// + /// Deletes the listed entries (a link, not what it points to), then the folders they leave empty. Throws on the + /// first entry that cannot be deleted, before anything else of the uninstall changes. + /// + public void Remove() + { + foreach (var entry in Entries) + { + var path = Path.GetFullPath(Path.Combine(Folder, entry.Name)); + // The plan comes from this folder's listing; anything else is never deleted. + if (!SetupPaths.IsSameOrInside(path, Folder) || SetupPaths.IsSameOrInside(Folder, path)) continue; + var info = new FileInfo(path); + if (!info.Exists && !Directory.Exists(path)) continue; + if (!info.Attributes.HasFlag(FileAttributes.Directory)) File.Delete(path); + else Directory.Delete(path, recursive: !info.Attributes.HasFlag(FileAttributes.ReparsePoint)); + var parent = Path.GetDirectoryName(path)!; + if (!SetupPaths.IsSameOrInside(Folder, parent) && !Directory.EnumerateFileSystemEntries(parent).Any()) Directory.Delete(parent); + } + if (Directory.Exists(Folder) && !Directory.EnumerateFileSystemEntries(Folder).Any()) Directory.Delete(Folder); } private static long SizeOf(FileSystemInfo entry) => entry switch @@ -40,3 +81,38 @@ internal sealed record UserDataPlan(IReadOnlyList Entries) _ => 0, }; } + +/// +/// Which program each entry of the user data folder (%LOCALAPPDATA%\Titano) belongs to: the Uploader's files +/// start with uploader (settings and sign-in, queue, watch memory, its logs); everything else is the desktop +/// app's (index, settings, backups, cache, its logs). Titano Server keeps its data elsewhere. +/// +internal static class UserDataOwners +{ + public const string Titano = "Titano"; + public const string Uploader = "Uploader"; + + /// The folder both programs write their logs to. + private const string SharedFolder = "logs"; + + /// The components that keep data in the folder. + public static readonly IReadOnlySet All = new HashSet([Titano, Uploader], StringComparer.OrdinalIgnoreCase); + + /// The component that owns the top-level entry, or the file inside the shared logs folder, called . + public static string OwnerOf(string name) => name.StartsWith("uploader", StringComparison.OrdinalIgnoreCase) ? Uploader : Titano; + + /// True for the logs folder both programs write to (a real folder, not a link to one). + public static bool IsShared(DirectoryInfo folder) => + folder.Name.Equals(SharedFolder, StringComparison.OrdinalIgnoreCase) && !folder.Attributes.HasFlag(FileAttributes.ReparsePoint); + + /// + /// The owners whose data uninstalling a product with may remove: its components that + /// keep data, minus those another installed product still has (' components). + /// + public static IReadOnlySet Removable(IEnumerable components, IEnumerable> others) + { + var owners = new HashSet(components.Where(All.Contains), StringComparer.OrdinalIgnoreCase); + foreach (var other in others) owners.ExceptWith(other); + return owners; + } +} diff --git a/src/Titano.Setup/Interop/ServiceNative.cs b/src/Titano.Setup/Interop/ServiceNative.cs new file mode 100644 index 00000000..70f814a7 --- /dev/null +++ b/src/Titano.Setup/Interop/ServiceNative.cs @@ -0,0 +1,74 @@ +using System.Runtime.InteropServices; + +namespace Titano.Setup.Interop; + +/// Service Control Manager functions of advapi32: query, stop, start and delete one service by name. +internal static unsafe partial class ServiceNative +{ + public const uint ScManagerConnect = 0x1; + public const uint ServiceQueryStatus = 0x4; + public const uint ServiceStart = 0x10; + public const uint ServiceStop = 0x20; + public const uint Delete = 0x10000; + + public const uint ControlStop = 1; + public const uint StateStopped = 1; + public const int StatusProcessInfo = 0; + + public const int ErrorServiceDoesNotExist = 1060; + public const int ErrorServiceNotActive = 1062; + public const int ErrorServiceAlreadyRunning = 1056; + public const int ErrorServiceMarkedForDelete = 1072; + + [StructLayout(LayoutKind.Sequential)] + public struct ServiceStatus + { + public uint ServiceType; + public uint CurrentState; + public uint ControlsAccepted; + public uint Win32ExitCode; + public uint ServiceSpecificExitCode; + public uint CheckPoint; + public uint WaitHint; + } + + [StructLayout(LayoutKind.Sequential)] + public struct ServiceStatusProcess + { + public uint ServiceType; + public uint CurrentState; + public uint ControlsAccepted; + public uint Win32ExitCode; + public uint ServiceSpecificExitCode; + public uint CheckPoint; + public uint WaitHint; + public uint ProcessId; + public uint ServiceFlags; + } + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess); + + [LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool QueryServiceStatusEx(nint service, int infoLevel, ServiceStatusProcess* buffer, int bufferSize, out int bytesNeeded); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool ControlService(nint service, uint control, ServiceStatus* status); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool StartServiceW(nint service, uint argumentCount, nint arguments); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DeleteService(nint service); + + [LibraryImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool CloseServiceHandle(nint handle); +} diff --git a/src/Titano.Setup/Interop/ShellLink.cs b/src/Titano.Setup/Interop/ShellLink.cs index 6f033480..59af4ca4 100644 --- a/src/Titano.Setup/Interop/ShellLink.cs +++ b/src/Titano.Setup/Interop/ShellLink.cs @@ -4,9 +4,15 @@ using System.Runtime.InteropServices.ComTypes; namespace Titano.Setup.Interop; -/// Creates .lnk shortcuts through the shell's IShellLinkW and IPersistFile COM interfaces. +/// Creates and reads .lnk shortcuts through the shell's IShellLinkW and IPersistFile COM interfaces. internal static class ShellLink { + private const int StgmRead = 0; + private const uint SlgpRawPath = 0x4; + + /// Characters of the target buffer: the longest path Windows accepts. + private const int MaxTarget = 32768; + /// Writes a shortcut at that starts in its own folder. public static void Create(string linkPath, string target, string description) { @@ -29,11 +35,48 @@ internal static class ShellLink }); } + /// + /// The program a shortcut starts, as stored in the file (the target need not exist); null when the file is + /// missing or is not a shortcut to a file. + /// + public static string? TargetOf(string linkPath) + { + if (!File.Exists(linkPath)) return null; + string? target = null; + StaThread.Run(() => + { + var link = (IShellLinkW)new ShellLinkObject(); + try + { + ((IPersistFile)link).Load(linkPath, StgmRead); + var buffer = Marshal.AllocHGlobal(MaxTarget * sizeof(char)); + try + { + link.GetPath(buffer, MaxTarget, IntPtr.Zero, SlgpRawPath); + target = Marshal.PtrToStringUni(buffer); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + catch (COMException) + { + // Not a shortcut, or a shortcut to a shell item that is not a file. + } + finally + { + Marshal.FinalReleaseComObject(link); + } + }); + return string.IsNullOrEmpty(target) ? null : Environment.ExpandEnvironmentVariables(target); + } + [ComImport] [Guid("00021401-0000-0000-C000-000000000046")] private class ShellLinkObject; - /// Vtable-ordered declaration; only the setters are called, so getters take raw pointers. + /// Vtable-ordered declaration; setters take strings, getters raw buffers. [ComImport] [Guid("000214F9-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] diff --git a/src/Titano.Setup/Program.cs b/src/Titano.Setup/Program.cs index abb738c3..cb56360c 100644 --- a/src/Titano.Setup/Program.cs +++ b/src/Titano.Setup/Program.cs @@ -7,8 +7,8 @@ using Titano.Setup.Engine; namespace Titano.Setup; /// -/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the -/// . The return value is the process exit code (). +/// Entry point. Silent mode, the uninstaller cleanup helper and the elevated service step run without WPF; the +/// interactive window is the . The return value is the process exit code (). /// internal static class Program { @@ -34,6 +34,7 @@ internal static class Program ApplyLanguage(arguments.Language); if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId); + if (arguments.Services != ServiceActions.None) return (int)InstalledServices.RunStep(arguments); if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult(); return new App(arguments).Run(); diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj index f70eaf7c..6049a9ee 100644 --- a/src/Titano.Setup/Titano.Setup.csproj +++ b/src/Titano.Setup/Titano.Setup.csproj @@ -14,6 +14,9 @@ true + + + diff --git a/src/Titano.Setup/Views/ComponentOption.cs b/src/Titano.Setup/Views/ComponentOption.cs index 45b8336f..bf2bc283 100644 --- a/src/Titano.Setup/Views/ComponentOption.cs +++ b/src/Titano.Setup/Views/ComponentOption.cs @@ -4,8 +4,11 @@ using Titano.Ui.Mvvm; namespace Titano.Setup.Views; -/// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. -internal sealed class ComponentOption(PayloadComponent component, bool selected, Action changed) : LocalizedViewModel +/// +/// 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. +/// +internal sealed class ComponentOption(PayloadComponent component, bool selected, bool available, Action changed) : LocalizedViewModel { private bool _selected = selected; @@ -13,7 +16,17 @@ internal sealed class ComponentOption(PayloadComponent component, bool selected, public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName; - public string ToolTip => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); + /// 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; + + public string ToolTip => !IsAvailable ? Loc.L("Tooltips.Setup.NeedsAllUsers") + : AllUsersOnly ? Loc.L("Tooltips.Setup.AllUsersOnly", Description) + : Description; + + private string Description => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); public string SizeText => ByteSize.Format(component.EstimatedSize); diff --git a/src/Titano.Setup/Views/SetupCapture.cs b/src/Titano.Setup/Views/SetupCapture.cs index f25307c1..3adfff02 100644 --- a/src/Titano.Setup/Views/SetupCapture.cs +++ b/src/Titano.Setup/Views/SetupCapture.cs @@ -31,7 +31,7 @@ internal static class SetupCapture ]; /// What a user data folder typically holds; eight entries, so the plan also shows its "more" line. - private static readonly UserDataPlan SamplePlan = new( + private static readonly UserDataPlan SamplePlan = new(SetupPaths.UserData, [ new UserDataEntry("cache", 2_140_000_000), new UserDataEntry("backups", 1_210_000_000), @@ -95,8 +95,10 @@ internal static class SetupCapture Program.ApplyLanguage(language); using var payload = PayloadReader.Open(installer); using var install = SetupViewModel.ForInstall(new SetupArguments(), payload); + // Both programs' data, whatever this machine has installed, so every capture shows the same screen. using var uninstall = SetupViewModel.ForUninstall(new SetupArguments(), new InstalledProduct( - SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0" })); + SetupPaths.DefaultDirectory(InstallScope.CurrentUser, Product), new InstallLog { Product = Product, Version = "1.0.0", Components = ["Titano", "Uploader"] }), + UserDataOwners.All); foreach (var theme in themes) { ThemeManager.Apply(theme); @@ -154,7 +156,7 @@ internal static class SetupCapture { Product = Product, Version = "1.0.0", - Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id)))], + Components = [.. components.Select(c => new PayloadComponentSource(c.Id, c.DisplayName, c.Selected, Path.Combine(work, c.Id), AllUsersOnly: c.Id == "Server"))], Shortcuts = [.. components.Select(c => new PayloadShortcut { Component = c.Id, Name = c.DisplayName, Target = c.Program, StartMenu = true, Desktop = c.Id != "Server" })], }, installer); return installer; diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs index 8cc1b642..72c2ccfc 100644 --- a/src/Titano.Setup/Views/SetupViewModel.cs +++ b/src/Titano.Setup/Views/SetupViewModel.cs @@ -42,6 +42,7 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private readonly InstalledProduct? _installed; private readonly string _product; private readonly string? _version; + private readonly IReadOnlySet _dataOwners; private SetupStage _stage; private string _directory = string.Empty; private bool _allUsers; @@ -60,14 +61,20 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private bool _accessDenied; private string? _launchProgram; private Func? _operation; + private bool _stoppedServices; - private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed) + private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed, + IReadOnlySet? dataOwners = null) { _arguments = arguments; _product = product; _version = version; _payload = payload; _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)); if (payload is not null) { _engine = new InstallEngine(payload); @@ -80,7 +87,8 @@ 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), OnComponentsChanged))]; + : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), _plan.CanInstall(c), + OnComponentsChanged))]; Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart); @@ -99,8 +107,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) => new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null); - public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) => - new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory }; + /// Whose user data "Remove my data" covers; null works it out from the installed products. + public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed, IReadOnlySet? dataOwners = null) => + new(arguments, installed.Log.Product, installed.Log.Version, null, installed, dataOwners) { Directory = installed.Directory }; /// A screen that can only report why setup cannot run (no payload, nothing installed…). public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code) @@ -219,7 +228,15 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo /// 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"); - public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked"); + /// A selected component installs for all users only (the Server runs as a LocalSystem service from Program Files). + private ComponentOption? AllUsersComponent => Components.FirstOrDefault(c => c.IsSelected && c.AllUsersOnly); + + /// "Just me" is offered unless the location is fixed (upgrade) or a selected component needs all users. + public bool CanChooseJustMe => CanChangeLocation && AllUsersComponent is null; + + public string JustMeToolTip => !CanChangeLocation ? Loc.L("Tooltips.Setup.Locked") + : AllUsersComponent is { } component ? Loc.L("Tooltips.Setup.JustMeLocked", component.Name) + : Loc.L("Tooltips.Setup.JustMe"); public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked"); public bool DesktopShortcut @@ -252,7 +269,9 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo : 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)); + private bool CanStart => IsOptions && (IsUninstall + ? !_removeUserData || _dataPlan is not null + : IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected) && (_allUsers || AllUsersComponent is null)); // ---- Uninstall options ---- @@ -269,6 +288,17 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo } } + /// + /// "Remove my data" is offered when this product's programs keep data no other installed Titano product still uses + /// (the desktop app and the Uploader share the folder). + /// + public bool HasRemoveDataOption => _dataOwners.Count > 0; + + /// What "Remove my data" deletes: both programs' data, or only the desktop app's or the Uploader's. + public string RemoveDataToolTip => Loc.L(UserDataOwners.All.All(_dataOwners.Contains) ? "Tooltips.Setup.RemoveData" + : _dataOwners.Contains(UserDataOwners.Uploader) ? "Tooltips.Setup.RemoveDataUploader" + : "Tooltips.Setup.RemoveDataTitano"); + public bool IsDataPlanVisible => _removeUserData && _dataPlan is not null; /// "Deletes 3.4 GB" over the plan's lines. @@ -412,11 +442,16 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo await InstallElevatedAsync(request, program); return; } - if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return; + if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory), ServiceActions.Stop)) return; BeginWork(indeterminate: false); 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; _launchProgram = program; Complete(); if (launch is not null) Launch(); @@ -454,11 +489,14 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo var installed = _installed!; try { - if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return; + if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files, ServiceActions.Remove)) 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}"); var progress = new Progress(ReportProgress); - var removeData = _removeUserData; - await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress)); + var userData = _removeUserData ? _dataPlan : null; + await Task.Run(() => UninstallEngine.Uninstall(installed, userData, progress)); Complete(); } catch (Exception ex) @@ -468,25 +506,37 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo } /// - /// True when no installed program runs from . Otherwise the first call asks the user - /// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues. + /// 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. /// - private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs) + private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs, ServiceActions toServices) { // A confirmation answers one prompt only; a later attempt asks again. var confirmed = _closeConfirmed; _closeConfirmed = false; - var running = RunningPrograms.Find(directory, programs); + var services = InstalledServices.Find(directory).Where(InstalledServices.IsRunning).ToList(); + var running = RunningPrograms.Find(directory, programs, services); try { - if (running.Count == 0) return true; - _runningPrograms = RunningPrograms.Describe(running); + if (running.Count == 0 && services.Count == 0) return true; + _runningPrograms = RunningPrograms.Describe(running, services); if (!confirmed) { Stage = SetupStage.Confirm; return false; } 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; _runningPrograms = RunningPrograms.Describe(still); @@ -570,12 +620,12 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo _measuring = true; try { - _dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData)); + _dataPlan = await Task.Run(() => UserDataPlan.Measure(SetupPaths.UserData, _dataOwners)); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("setup", $"User data '{SetupPaths.UserData}' not measured", ex); - _dataPlan = new UserDataPlan([]); + _dataPlan = new UserDataPlan(SetupPaths.UserData, []); } finally { @@ -589,6 +639,11 @@ internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo private void OnComponentsChanged() { + // The Server runs as a LocalSystem service, which must not start a program its user can replace: selecting it + // moves a new installation to all users (Program Files). + if (AllUsersComponent is not null && !_allUsers && CanChangeLocation) IsAllUsers = true; + OnPropertyChanged(nameof(CanChooseJustMe)); + OnPropertyChanged(nameof(JustMeToolTip)); OnPropertyChanged(nameof(RequiredSpaceText)); OnPropertyChanged(nameof(InstallToolTip)); OnPropertyChanged(nameof(HasDesktopOption)); diff --git a/src/Titano.Setup/Views/SetupWindow.xaml b/src/Titano.Setup/Views/SetupWindow.xaml index fe8ffd5e..9a8dfbd8 100644 --- a/src/Titano.Setup/Views/SetupWindow.xaml +++ b/src/Titano.Setup/Views/SetupWindow.xaml @@ -44,7 +44,8 @@ - + @@ -52,7 +53,7 @@ - @@ -96,8 +97,10 @@ + + Foreground="{DynamicResource Brush.Warning}" ToolTip="{Binding RemoveDataToolTip}" + Visibility="{Binding HasRemoveDataOption, Converter={StaticResource BoolToVisibility}}" /> diff --git a/src/Titano.Tools/Commands/PackInstallerCommand.cs b/src/Titano.Tools/Commands/PackInstallerCommand.cs index 24720315..8a835dcf 100644 --- a/src/Titano.Tools/Commands/PackInstallerCommand.cs +++ b/src/Titano.Tools/Commands/PackInstallerCommand.cs @@ -6,18 +6,20 @@ namespace Titano.Tools.Commands; /// /// pack-installer --setup Titano.Setup.exe --product Titano --version 1.2.3 --component Id=folder … --out file: /// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default -/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. +/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. The Server +/// installs only for all users: it is registered as a LocalSystem service, which must run from Program Files. /// internal sealed class PackInstallerCommand : ICommand { - private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association); + private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association, bool AllUsersOnly = false); + /// The file type's description is the English fallback; setup writes it in its own language (Setup.FileType.*). private static readonly Dictionary Known = new(StringComparer.OrdinalIgnoreCase) { ["Titano"] = new("Titano", true, "Titano.exe", Desktop: true, new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }), ["Uploader"] = new("Titano Uploader", true, "Titano.Uploader.exe", Desktop: true, null), - ["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null), + ["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null, AllUsersOnly: true), }; public string Name => "pack-installer"; @@ -49,7 +51,7 @@ internal sealed class PackInstallerCommand : ICommand components.Add(new PayloadComponentSource(id, id, true, folder)); continue; } - components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder)); + components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder, known.AllUsersOnly)); if (!File.Exists(Path.Combine(folder, known.Program))) { Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered."); diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs index 0953ab73..ff51ae65 100644 --- a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -14,7 +14,8 @@ 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. +/// 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. /// public sealed class RunKeyStartupRegistration : IStartupRegistration { diff --git a/tests/Titano.App.Tests/Setup/SetupEngineTests.cs b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs new file mode 100644 index 00000000..11ff998d --- /dev/null +++ b/tests/Titano.App.Tests/Setup/SetupEngineTests.cs @@ -0,0 +1,156 @@ +using System.Globalization; +using System.IO; +using Microsoft.Win32; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Engine; +using Titano.Setup.Interop; +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). +/// +public sealed class SetupEngineTests(TestContext context) +{ + [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")] + [Case(@"""C:\Program Files\dotnet\dotnet.exe"" ""C:\Apps\Titano\Titano.Server.dll"" --service", @"C:\Apps\Titano\Titano.Server.dll")] + [Case(@"C:\Windows\system32\svchost.exe -k netsvcs", @"C:\Windows\system32\svchost.exe")] + [Case(@"Titano.Uploader.exe --tray", null)] + [Case("", null)] + public void TheProgramOfACommandLineIsItsFirstFullPath(string commandLine, string? program) => + Assert.Equal(program, CommandProgram.Of(commandLine)); + + [Test] + public void ServiceStepsTravelToTheElevatedCopy() + { + var arguments = new SetupArguments { Services = ServiceActions.Prune | ServiceActions.Start, 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.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"])); + } + + [Test] + [WindowsOnly] + public void AServiceWhoseProgramIsGoneIsPrunedAndNothingStartsIt() + { + 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)); + + var gone = new InstalledService("TitanoTest" + Guid.NewGuid().ToString("N"), "Titano Server", Path.Combine(folder, "Titano.Server.exe"), AutoStart: true); + 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)); + } + + [Test] + [WindowsOnly] + public void UninstallRemovesOnlyTheStartupEntriesOfItsFolder() + { + var folder = Path.Combine(context.CreateTempDirectory("startup"), "Titano Uploader"); + const string testsKey = @"Software\Titano.Tests"; + 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("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)); + } + } + 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); + } + } + + [Test] + [WindowsOnly] + public void AShortcutTellsWhichProgramItStarts() + { + var folder = context.CreateTempDirectory("links"); + var target = Path.Combine(folder, "Product A", "Titano.Uploader.exe"); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.WriteAllBytes(target, [0x4D, 0x5A]); + var link = Path.Combine(folder, "Titano Uploader.lnk"); + ShellLink.Create(link, target, "Titano Uploader"); + + // The shell may store the long form of a short (8.3) temporary path: the same file either way. + var stored = Assert.NotNull(ShellLink.TargetOf(link)); + Assert.Equal(Path.GetFileName(target), Path.GetFileName(stored)); + Assert.FileExists(stored); + var productA = Path.GetDirectoryName(stored)!; + Assert.True(CommandProgram.IsPathInside(stored, productA)); + Assert.False(CommandProgram.IsPathInside(stored, Path.Combine(Path.GetDirectoryName(productA)!, "Product B"))); + Assert.False(CommandProgram.IsPathInside(stored, productA + " 2")); + Assert.Null(ShellLink.TargetOf(Path.Combine(folder, "missing.lnk"))); + var notALink = Path.Combine(folder, "not a link.lnk"); + File.WriteAllText(notALink, "plain text"); + Assert.Null(ShellLink.TargetOf(notALink)); + } + + [Test] + [WindowsOnly] + public void TheServerMakesANewInstallationAnAllUsersOne() + { + 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); + + 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. + 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")!)); + } + + [Test] + public void TheProjectFileTypeIsNamedInSetupsLanguage() + { + var association = new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }; + Assert.Equal("Titano project", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("en"))); + Assert.Equal("Progetto Titano", InstallEngine.FileTypeName(association, CultureInfo.GetCultureInfo("it"))); + + var unknown = new PayloadAssociation { Component = "Titano", Extension = ".tlx", ProgId = "Titano.Unknown", Description = "Something else", Target = "Titano.exe" }; + Assert.Equal("Something else", InstallEngine.FileTypeName(unknown, CultureInfo.GetCultureInfo("it"))); + } + + /// A manifest under a product name no machine has installed, so the registry holds no installation of it. + private static PayloadManifest Manifest() => new() + { + Product = "TitanoTest" + Guid.NewGuid().ToString("N")[..12], + Version = "1.0.0", + Components = + [ + new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true }, + new PayloadComponent { Id = "Server", DisplayName = "Titano Server", AllUsersOnly = true }, + ], + }; +} diff --git a/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs b/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs new file mode 100644 index 00000000..ca636e13 --- /dev/null +++ b/tests/Titano.App.Tests/Setup/UserDataPlanTests.cs @@ -0,0 +1,102 @@ +using System.IO; +using Titano.Setup.Engine; +using Titano.Testing; + +namespace Titano.App.Tests.Setup; + +/// +/// "Remove my data" covers only the programs being removed (SRS-05): the desktop app and the Uploader share +/// %LOCALAPPDATA%\Titano and its logs folder, and uninstalling one product never deletes what another still uses. +/// +public sealed class UserDataPlanTests(TestContext context) +{ + [Test] + public void TheDesktopAppsPlanLeavesTheUploadersFiles() + { + var folder = SampleFolder(); + var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano)); + + Assert.SequenceEqual( + ["backups", "cache", "logs" + Path.DirectorySeparatorChar + "titano-20261012.log", "settings.json", "titano.db"], + plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal)); + Assert.Equal(4000L + 3000 + 300 + 20 + 100, plan.TotalBytes); + + plan.Remove(); + Assert.SequenceEqual( + ["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"], + Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(folder, f)).Order(StringComparer.Ordinal)); + Assert.False(Directory.Exists(Path.Combine(folder, "cache"))); + } + + [Test] + public void TheUploadersPlanLeavesTheDesktopAppsFilesAndEmptiedFoldersGo() + { + var folder = SampleFolder(); + var plan = UserDataPlan.Measure(folder, Owners(UserDataOwners.Uploader)); + + Assert.SequenceEqual( + ["logs" + Path.DirectorySeparatorChar + "uploader-20261012.log", "uploader-queue.json", "uploader.json"], + plan.Entries.Select(e => e.Name).Order(StringComparer.Ordinal)); + + plan.Remove(); + Assert.True(File.Exists(Path.Combine(folder, "titano.db"))); + Assert.True(File.Exists(Path.Combine(folder, "logs", "titano-20261012.log"))); + Assert.FileMissing(Path.Combine(folder, "uploader.json")); + Assert.FileMissing(Path.Combine(folder, "logs", "uploader-20261012.log")); + + // Once the desktop app's data goes too, nothing is left of the folder. + UserDataPlan.Measure(folder, Owners(UserDataOwners.Titano)).Remove(); + Assert.False(Directory.Exists(folder)); + } + + [Test] + public void BothProgramsDataIsTheWholeFolderAndNoOwnerIsAnEmptyPlan() + { + var folder = SampleFolder(); + var whole = UserDataPlan.Measure(folder, UserDataOwners.All); + Assert.SequenceEqual( + ["backups", "cache", "logs", "settings.json", "titano.db", "uploader-queue.json", "uploader.json"], + whole.Entries.Select(e => e.Name).Order(StringComparer.Ordinal)); + Assert.Empty(UserDataPlan.Measure(folder, Owners()).Entries); + + whole.Remove(); + Assert.False(Directory.Exists(folder)); + } + + [Test] + public void AProductRemovesTheDataOfItsProgramsThatNoOtherInstalledProductHas() + { + string[] titano = ["Titano", "Uploader", "Server"]; + string[] uploader = ["Uploader"]; + + Assert.SequenceEqual(["Titano", "Uploader"], UserDataOwners.Removable(titano, []).Order(StringComparer.Ordinal)); + Assert.SequenceEqual(["Titano"], UserDataOwners.Removable(titano, [uploader]).Order(StringComparer.Ordinal)); + Assert.Empty(UserDataOwners.Removable(uploader, [titano])); + Assert.SequenceEqual(["Uploader"], UserDataOwners.Removable(uploader, [["titano"]])); + // Titano Server keeps its data elsewhere: a Server-only product removes nothing here. + Assert.Empty(UserDataOwners.Removable(["Server"], [])); + } + + private static HashSet Owners(params string[] owners) => new(owners, StringComparer.OrdinalIgnoreCase); + + private string SampleFolder() + { + var folder = Path.Combine(context.CreateTempDirectory("userdata"), "Titano"); + Write(folder, "titano.db", 4000); + Write(folder, "settings.json", 20); + Write(folder, Path.Combine("cache", "proxies", "a.jpg"), 3000); + Write(folder, Path.Combine("backups", "titano-1.db"), 100); + Write(folder, Path.Combine("logs", "titano-20261012.log"), 300); + Write(folder, Path.Combine("logs", "uploader-20261012.log"), 200); + Write(folder, "uploader.json", 10); + Write(folder, "uploader-queue.json", 50); + return folder; + } + + private static void Write(string folder, string relative, int bytes) + { + var path = Path.Combine(folder, relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, new byte[bytes]); + } +} diff --git a/tests/Titano.App.Tests/Titano.App.Tests.csproj b/tests/Titano.App.Tests/Titano.App.Tests.csproj index 43859d50..6f904c99 100644 --- a/tests/Titano.App.Tests/Titano.App.Tests.csproj +++ b/tests/Titano.App.Tests/Titano.App.Tests.csproj @@ -9,5 +9,6 @@ + diff --git a/tests/Titano.Tools.Tests/PackInstallerCommandTests.cs b/tests/Titano.Tools.Tests/PackInstallerCommandTests.cs new file mode 100644 index 00000000..02e84e1a --- /dev/null +++ b/tests/Titano.Tools.Tests/PackInstallerCommandTests.cs @@ -0,0 +1,44 @@ +using Titano.Core.Packaging; +using Titano.Testing; +using Titano.Tools.Commands; + +namespace Titano.Tools.Tests; + +/// pack-installer writes the components, shortcuts and file types setup installs (BRIEF §18). +public sealed class PackInstallerCommandTests(TestContext context) +{ + [Test] + public async Task TheServerInstallsOnlyForAllUsersAndTitanoOwnsTheProjectFileType() + { + var root = context.CreateTempDirectory("pack"); + var stub = Path.Combine(root, "Titano.Setup.exe"); + var bytes = new byte[4096]; + new Random(5).NextBytes(bytes); + "MZ"u8.CopyTo(bytes); + await File.WriteAllBytesAsync(stub, bytes); + var app = Program(root, "app", "Titano.exe"); + var server = Program(root, "server", "Titano.Server.exe"); + var output = Path.Combine(root, "out", "Titano-Setup.exe"); + + Assert.Equal(0, await new PackInstallerCommand().RunAsync( + ["--setup", stub, "--product", "Titano", "--version", "1.2.3", "--component", "Titano=" + app, "--component", "Server=" + server, "--out", output])); + + using var reader = PayloadReader.Open(output); + var manifest = reader.Manifest; + Assert.False(manifest.FindComponent("Titano")!.AllUsersOnly); + var serverComponent = manifest.FindComponent("Server")!; + Assert.True(serverComponent.AllUsersOnly); + Assert.False(serverComponent.DefaultSelected); + var association = Assert.Contains(manifest.Associations, a => a.Extension == ".titano"); + Assert.Equal("Titano.Project", association.ProgId); + Assert.Equal("Titano.exe", association.Target); + Assert.Equal("Titano", association.Component); + } + + private static string Program(string root, string folder, string name) + { + var dir = Directory.CreateDirectory(Path.Combine(root, folder)).FullName; + File.WriteAllText(Path.Combine(dir, name), "MZ " + name); + return dir; + } +}