using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using Chronos.Core.Localization;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
///
/// --install-service / --uninstall-service: registers the server with the Service Control Manager
/// (automatic start, LocalSystem, command line "…\Chronos.Server.exe" --service) or stops and removes it.
/// Both need an elevated prompt; failures surface as . A LocalSystem service runs whatever
/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM,
/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to
/// any program of that user. Otherwise refuses with .
///
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// TrustedInstaller, the owner of Windows' own files under Program Files.
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// This copy is not in a folder that only administrators can change.
public static void Install()
{
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart,
ServiceErrorNormal, CommandLine(), null, 0, null, null, null);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
fixed (char* text = Loc.L("Server.Service.Description"))
{
var description = new ServiceDescription { Description = text };
ChangeServiceConfig2W(service, ServiceConfigDescription, &description);
}
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
public static void Uninstall()
{
var manager = OpenSCManagerW(null, null, ScManagerConnect);
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus);
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
try
{
ServiceStatus status;
if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive)
throw new Win32Exception(stopError);
if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete)
throw new Win32Exception(deleteError);
}
finally
{
CloseServiceHandle(service);
}
}
finally
{
CloseServiceHandle(manager);
}
}
///
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by dotnet, the host's folder) must be inside Program Files and changeable only by administrators.
///
internal static string? UnsafeLocation()
{
var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program);
if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open);
// Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it.
if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host
&& !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase))
{
if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host);
if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen);
}
return null;
}
/// True for a path inside %ProgramFiles% or %ProgramFiles(x86)% (not the folder itself).
internal static bool IsUnderProgramFiles(string path)
{
var full = Path.GetFullPath(path);
foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 })
{
var root = Environment.GetFolderPath(folder);
if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
///
/// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than
/// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none.
///
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet trusted)
{
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
foreach (var file in folder.EnumerateFiles())
{
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
}
if (!recursive) return null;
foreach (var child in folder.EnumerateDirectories())
{
if (FindChangeable(child, recursive: true, trusted) is { } path) return path;
}
return null;
}
private static HashSet TrustedAccounts()
{
var trusted = new HashSet
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
TrustedInstaller,
};
// Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it.
using var identity = WindowsIdentity.GetCurrent();
if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user);
return trusted;
}
/// The service's command line: this executable (or dotnet plus this assembly) with --service.
private static string CommandLine()
{
var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown.");
// Assembly.Location is empty in a single-file app; under dotnet the entry assembly sits in the base directory.
var assembly = Path.Combine(AppContext.BaseDirectory, typeof(ServiceInstaller).Assembly.GetName().Name + ".dll");
return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
? $"\"{process}\" \"{assembly}\" --service"
: $"\"{process}\" --service";
}
}