- Windows services whose program lies in the install folder (Titano.Server --install-service) are found in the registry and, through the Service Control Manager, stopped before files are replaced (they join the "programs running" prompt), started again after an upgrade that stopped them, deleted when an upgrade drops their program and on uninstall. An unelevated setup runs that step in an elevated copy (/SERVICES=...). - The Server component installs for all users only (manifest allUsersOnly): choosing it moves a new install to Program Files and disables "Just me" with the reason; a per-user install cannot take it. - Uninstall removes every HKCU Run value that starts a program in the folder (the Uploader's "Start with Windows"). - A shortcut that already starts an existing program elsewhere is neither retargeted nor logged, and a logged shortcut is deleted only while it still starts a program of this folder, so the two products no longer remove each other's "Titano Uploader" shortcuts. - "Remove my data" lists and deletes only the data of this product's programs that no other installed Titano product uses (the desktop app and the Uploader share %LOCALAPPDATA%\Titano and its logs folder). - The .titano file type is named in setup's language (Setup.FileType.*). Setup tests run in Titano.App.Tests on Windows CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
239 lines
11 KiB
C#
239 lines
11 KiB
C#
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
using System.Security;
|
|
using Microsoft.Win32;
|
|
using Titano.Core.Diagnostics;
|
|
using Titano.Core.Localization;
|
|
using Titano.Setup.Cli;
|
|
using static Titano.Setup.Interop.ServiceNative;
|
|
|
|
namespace Titano.Setup.Engine;
|
|
|
|
/// <summary>A Windows service whose program lies inside an installation folder (<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);
|
|
|
|
/// <summary>What setup does with the services of an installation; several may be combined.</summary>
|
|
[Flags]
|
|
internal enum ServiceActions
|
|
{
|
|
None = 0,
|
|
|
|
/// <summary>Stops the running ones, before their files are replaced.</summary>
|
|
Stop = 1,
|
|
|
|
/// <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>
|
|
Start = 4,
|
|
|
|
/// <summary>Stops and deletes them all (uninstall), so no service is left pointing at a deleted program.</summary>
|
|
Remove = 8,
|
|
}
|
|
|
|
/// <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>).
|
|
/// </summary>
|
|
internal static class InstalledServices
|
|
{
|
|
private const string ServicesKey = @"SYSTEM\CurrentControlSet\Services";
|
|
|
|
/// <summary>SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS: programs, not drivers.</summary>
|
|
private const int Win32Service = 0x30;
|
|
|
|
private const int AutoStartType = 2;
|
|
|
|
/// <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)
|
|
{
|
|
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}");
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
|
|
/// <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)));
|
|
|
|
/// <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.
|
|
/// </summary>
|
|
public static async Task<SetupExitCode> ApplyAsync(string directory, ServiceActions actions, IntPtr owner)
|
|
{
|
|
if (!NeedsWork(Find(directory), actions)) return SetupExitCode.Success;
|
|
if (Elevation.IsElevated) return await Task.Run(() => Apply(directory, actions)).ConfigureAwait(false);
|
|
Log.Info("setup", $"Asking for administrator rights to {actions} the services of '{directory}'");
|
|
var arguments = new SetupArguments { Services = actions, Directory = directory, Language = Loc.Culture.Name };
|
|
return Elevation.Start(arguments, owner) is { } child ? await Elevation.WaitAsync(child, null).ConfigureAwait(false) : SetupExitCode.ElevationDeclined;
|
|
}
|
|
|
|
/// <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.
|
|
/// </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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Applies <paramref name="actions"/> 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).
|
|
/// </summary>
|
|
public static unsafe SetupExitCode Apply(string directory, ServiceActions actions)
|
|
{
|
|
var services = Find(directory);
|
|
if (services.Count == 0) return SetupExitCode.Success;
|
|
var manager = OpenSCManagerW(null, null, ScManagerConnect);
|
|
if (manager == 0) return Failure("Service Control Manager not opened", null);
|
|
try
|
|
{
|
|
foreach (var service in services)
|
|
{
|
|
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus | ServiceStop | ServiceStart | Delete);
|
|
if (handle == 0)
|
|
{
|
|
if (Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist) continue;
|
|
return Failure("Service not opened", service);
|
|
}
|
|
try
|
|
{
|
|
var remove = actions.HasFlag(ServiceActions.Remove) || (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program));
|
|
if ((remove || actions.HasFlag(ServiceActions.Stop)) && !Stop(handle, service)) return SetupExitCode.ProgramRunning;
|
|
if (remove)
|
|
{
|
|
if (!DeleteService(handle) && Marshal.GetLastPInvokeError() != ErrorServiceMarkedForDelete) return Failure("Service not deleted", service);
|
|
Log.Info("setup", $"Service {service.Name} deleted");
|
|
}
|
|
else if (actions.HasFlag(ServiceActions.Start) && service.AutoStart && File.Exists(service.Program))
|
|
{
|
|
if (!StartServiceW(handle, 0, 0) && Marshal.GetLastPInvokeError() != ErrorServiceAlreadyRunning) return Failure("Service not started", service);
|
|
Log.Info("setup", $"Service {service.Name} started");
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
CloseServiceHandle(handle);
|
|
}
|
|
}
|
|
return SetupExitCode.Success;
|
|
}
|
|
finally
|
|
{
|
|
CloseServiceHandle(manager);
|
|
}
|
|
}
|
|
|
|
/// <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)
|
|
{
|
|
if (!TryQuery(handle, out var status)) return false;
|
|
if (status.CurrentState == StateStopped) return true;
|
|
var processId = (int)status.ProcessId;
|
|
ServiceStatus stopped;
|
|
if (!ControlService(handle, ControlStop, &stopped) && Marshal.GetLastPInvokeError() is var error && error != ErrorServiceNotActive)
|
|
Log.Warning("setup", $"Service {service.Name} refused to stop (error {error}); waiting for it");
|
|
var deadline = Stopwatch.StartNew();
|
|
while (TryQuery(handle, out status) && status.CurrentState != StateStopped)
|
|
{
|
|
if (deadline.Elapsed > StopTimeout)
|
|
{
|
|
Log.Warning("setup", $"Service {service.Name} did not stop within {StopTimeout.TotalSeconds:0} s");
|
|
return false;
|
|
}
|
|
Thread.Sleep(250);
|
|
}
|
|
if (processId != 0) WaitForExit(processId, StopTimeout - deadline.Elapsed);
|
|
Log.Info("setup", $"Service {service.Name} stopped");
|
|
return true;
|
|
}
|
|
|
|
private static void WaitForExit(int processId, TimeSpan timeout)
|
|
{
|
|
try
|
|
{
|
|
using var process = Process.GetProcessById(processId);
|
|
process.WaitForExit(timeout > TimeSpan.Zero ? timeout : TimeSpan.Zero);
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)
|
|
{
|
|
// Already gone, or not ours to wait for: the stopped state is what counts.
|
|
}
|
|
}
|
|
|
|
private static unsafe bool TryQuery(nint handle, out ServiceStatusProcess status)
|
|
{
|
|
ServiceStatusProcess value;
|
|
var ok = QueryServiceStatusEx(handle, StatusProcessInfo, &value, sizeof(ServiceStatusProcess), out _);
|
|
status = value;
|
|
return ok;
|
|
}
|
|
|
|
private static SetupExitCode Failure(string what, InstalledService? service)
|
|
{
|
|
var error = Marshal.GetLastPInvokeError();
|
|
Log.Error("setup", $"{what}{(service is null ? string.Empty : " (" + service.Name + ")")}: error {error}");
|
|
return SetupExitCode.Failed;
|
|
}
|
|
}
|