using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Setup.Cli;
using static Titano.Setup.Interop.ServiceNative;
namespace Titano.Setup.Engine;
/// A Windows service whose program lies inside an installation folder (Titano.Server.exe --install-service).
/// Service key name (TitanoServer).
/// Full path of the program the service starts.
/// Starts with Windows (start type automatic).
internal sealed record InstalledService(string Name, string DisplayName, string Program, bool AutoStart);
/// What setup does with the services of an installation; several may be combined.
[Flags]
internal enum ServiceActions
{
None = 0,
/// Stops the running ones, before their files are replaced.
Stop = 1,
/// Deletes the ones whose program no longer exists (an upgrade dropped the component).
Prune = 2,
/// Starts the automatic ones that are stopped (after an upgrade that stopped them).
Start = 4,
/// Stops and deletes them all (uninstall), so no service is left pointing at a deleted program.
Remove = 8,
}
///
/// Services registered from an installation folder. Setup ignored them before: an upgrade failed while the service
/// kept its files open, and an uninstall left an automatic LocalSystem service pointing at a deleted path. They are
/// found in the registry (no administrator rights needed) and stopped, started or deleted through the Service
/// Control Manager, which needs administrator rights: an unelevated setup runs that step in an elevated copy of
/// itself (/SERVICES=…).
///
internal static class InstalledServices
{
private const string ServicesKey = @"SYSTEM\CurrentControlSet\Services";
/// SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS: programs, not drivers.
private const int Win32Service = 0x30;
private const int AutoStartType = 2;
/// How long a service may take to stop and its process to exit (as programs asked to close).
public static readonly TimeSpan StopTimeout = TimeSpan.FromSeconds(30);
/// Services whose program lies inside ; services already marked for deletion are skipped.
public static IReadOnlyList Find(string directory)
{
var found = new List();
using var services = Registry.LocalMachine.OpenSubKey(ServicesKey);
if (services is null) return found;
foreach (var name in services.GetSubKeyNames())
{
try
{
using var key = services.OpenSubKey(name);
if (key is null || key.GetValue("Type") is not int type || (type & Win32Service) == 0) continue;
if (key.GetValue("DeleteFlag") is int deleting && deleting != 0) continue;
if (key.GetValue("ImagePath") is not string image || CommandProgram.Of(image) is not { } program || !CommandProgram.IsPathInside(program, directory)) continue;
var display = key.GetValue("DisplayName") as string;
found.Add(new InstalledService(name, display is { Length: > 0 } && display[0] != '@' ? display : name, program, key.GetValue("Start") is AutoStartType));
}
catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException)
{
// A key this account may not read is not one setup registered.
Log.Debug("setup", $"Service key {name} not read: {ex.Message}");
}
}
return found;
}
/// True when the service is not stopped (running, starting, stopping or paused), or its state cannot be read.
public static unsafe bool IsRunning(InstalledService service)
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) return true;
try
{
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus);
if (handle == 0) return Marshal.GetLastPInvokeError() != ErrorServiceDoesNotExist;
try
{
return !TryQuery(handle, out var status) || status.CurrentState != StateStopped;
}
finally
{
CloseServiceHandle(handle);
}
}
finally
{
CloseServiceHandle(manager);
}
}
/// True when would change something about .
public static bool NeedsWork(IReadOnlyList services, ServiceActions actions) => services.Any(s =>
actions.HasFlag(ServiceActions.Remove)
|| (actions.HasFlag(ServiceActions.Prune) && !File.Exists(s.Program))
|| (actions.HasFlag(ServiceActions.Stop) && IsRunning(s))
|| (actions.HasFlag(ServiceActions.Start) && s.AutoStart && File.Exists(s.Program) && !IsRunning(s)));
///
/// Applies to the services of : in this process when it has
/// administrator rights, otherwise in an elevated copy (UAC prompt owned by ). Success
/// when there is nothing to do.
///
public static async Task ApplyAsync(string directory, ServiceActions actions, IntPtr owner)
{
if (!NeedsWork(Find(directory), actions)) return SetupExitCode.Success;
if (Elevation.IsElevated) return await Task.Run(() => Apply(directory, actions)).ConfigureAwait(false);
Log.Info("setup", $"Asking for administrator rights to {actions} the services of '{directory}'");
var arguments = new SetupArguments { Services = actions, Directory = directory, Language = Loc.Culture.Name };
return Elevation.Start(arguments, owner) is { } child ? await Elevation.WaitAsync(child, null).ConfigureAwait(false) : SetupExitCode.ElevationDeclined;
}
///
/// The elevated step (/SERVICES=… /DIR=…): applies the actions in this process. Refuses a folder setup would not
/// install to, and needs administrator rights.
///
public static SetupExitCode RunStep(SetupArguments arguments)
{
if (arguments.Directory is not { } directory || !SetupPaths.IsUsableInstallDirectory(directory)) return SetupExitCode.InvalidArguments;
return Elevation.IsElevated ? Apply(directory, arguments.Services) : SetupExitCode.ElevationDeclined;
}
///
/// Applies in this process (administrator rights). Returns
/// when a service did not stop in time,
/// when the Service Control Manager refused a step (logged).
///
public static unsafe SetupExitCode Apply(string directory, ServiceActions actions)
{
var services = Find(directory);
if (services.Count == 0) return SetupExitCode.Success;
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) return Failure("Service Control Manager not opened", null);
try
{
foreach (var service in services)
{
var handle = OpenServiceW(manager, service.Name, ServiceQueryStatus | ServiceStop | ServiceStart | Delete);
if (handle == 0)
{
if (Marshal.GetLastPInvokeError() == ErrorServiceDoesNotExist) continue;
return Failure("Service not opened", service);
}
try
{
var remove = actions.HasFlag(ServiceActions.Remove) || (actions.HasFlag(ServiceActions.Prune) && !File.Exists(service.Program));
if ((remove || actions.HasFlag(ServiceActions.Stop)) && !Stop(handle, service)) return SetupExitCode.ProgramRunning;
if (remove)
{
if (!DeleteService(handle) && Marshal.GetLastPInvokeError() != ErrorServiceMarkedForDelete) return Failure("Service not deleted", service);
Log.Info("setup", $"Service {service.Name} deleted");
}
else if (actions.HasFlag(ServiceActions.Start) && service.AutoStart && File.Exists(service.Program))
{
if (!StartServiceW(handle, 0, 0) && Marshal.GetLastPInvokeError() != ErrorServiceAlreadyRunning) return Failure("Service not started", service);
Log.Info("setup", $"Service {service.Name} started");
}
}
finally
{
CloseServiceHandle(handle);
}
}
return SetupExitCode.Success;
}
finally
{
CloseServiceHandle(manager);
}
}
/// Stops the service and waits for its process to exit, so its files can be replaced; false on timeout.
private static unsafe bool Stop(nint handle, InstalledService service)
{
if (!TryQuery(handle, out var status)) return false;
if (status.CurrentState == StateStopped) return true;
var processId = (int)status.ProcessId;
ServiceStatus stopped;
if (!ControlService(handle, ControlStop, &stopped) && Marshal.GetLastPInvokeError() is var error && error != ErrorServiceNotActive)
Log.Warning("setup", $"Service {service.Name} refused to stop (error {error}); waiting for it");
var deadline = Stopwatch.StartNew();
while (TryQuery(handle, out status) && status.CurrentState != StateStopped)
{
if (deadline.Elapsed > StopTimeout)
{
Log.Warning("setup", $"Service {service.Name} did not stop within {StopTimeout.TotalSeconds:0} s");
return false;
}
Thread.Sleep(250);
}
if (processId != 0) WaitForExit(processId, StopTimeout - deadline.Elapsed);
Log.Info("setup", $"Service {service.Name} stopped");
return true;
}
private static void WaitForExit(int processId, TimeSpan timeout)
{
try
{
using var process = Process.GetProcessById(processId);
process.WaitForExit(timeout > TimeSpan.Zero ? timeout : TimeSpan.Zero);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)
{
// Already gone, or not ours to wait for: the stopped state is what counts.
}
}
private static unsafe bool TryQuery(nint handle, out ServiceStatusProcess status)
{
ServiceStatusProcess value;
var ok = QueryServiceStatusEx(handle, StatusProcessInfo, &value, sizeof(ServiceStatusProcess), out _);
status = value;
return ok;
}
private static SetupExitCode Failure(string what, InstalledService? service)
{
var error = Marshal.GetLastPInvokeError();
Log.Error("setup", $"{what}{(service is null ? string.Empty : " (" + service.Name + ")")}: error {error}");
return SetupExitCode.Failed;
}
}