Files
Chronos/src/Chronos.Server/Hosting/Windows/ServiceInstaller.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

161 lines
8.0 KiB
C#

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;
/// <summary>
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
/// (automatic start, LocalSystem, command line <c>"…\Chronos.Server.exe" --service</c>) or stops and removes it.
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. 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 <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
/// </summary>
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
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);
}
}
/// <summary>
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
/// </summary>
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;
}
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> 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<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
{
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;
}
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
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";
}
}