fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
22 changed files with 834 additions and 282 deletions
Showing only changes of commit 067e8ca062 - Show all commits

No files matched your search

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