XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32.SafeHandles;

namespace XFEToolBox.Indexing.Service.Installation;

/// <summary>Small, opt-in elevated entry point. It accepts no caller-supplied paths or SCM commands.</summary>
public static class IndexingServiceInstaller
{
    public const string ServiceName = "XFEToolBoxIndexing";
    public const string ExecutableName = "XFEToolBox.Indexing.Service.exe";
    public static string InstallationDirectory => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "XFEToolBox", "Services", "IndexingService");
    public static string CacheDirectory => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "XFEToolBox", "IndexingService");

    public static int Run(string operation)
    {
        try
        {
            if (operation is not ("--install" or "--uninstall"))
                throw new ArgumentException("Only --install or --uninstall is accepted.");
            if (!OperatingSystem.IsWindows() ||
                !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
                throw new UnauthorizedAccessException("请以管理员权限运行独立索引服务安装程序。");
            using var mutex = new Mutex(false, "Global\\XFEToolBox.Indexing.Installation");
            var ownsMutex = false;
            try
            {
                try { ownsMutex = mutex.WaitOne(TimeSpan.FromMinutes(2)); }
                catch (AbandonedMutexException) { ownsMutex = true; }
                if (!ownsMutex) throw new TimeoutException("另一个索引服务安装程序仍在运行。");
                if (operation == "--install") Install();
                else Uninstall();
                return 0;
            }
            finally { if (ownsMutex) mutex.ReleaseMutex(); }
        }
        catch (Exception exception)
        {
            Console.Error.WriteLine(exception.Message);
            TryWriteLog(exception);
            return exception is UnauthorizedAccessException ? 5 : 1;
        }
    }

    private static void Install()
    {
        var source = Path.GetDirectoryName(Environment.ProcessPath ?? throw new InvalidOperationException("无法确定安装文件路径。"))!;
        if (!File.Exists(Path.Combine(source, ExecutableName)))
            throw new InvalidDataException("服务安装文件不完整。");
        RejectReparsePath(source);
        var destination = InstallationDirectory;
        var parent = Path.GetDirectoryName(destination)!;
        SecureDirectory(Path.GetDirectoryName(parent)!, allowUsersRead: true);
        SecureDirectory(parent, allowUsersRead: true);
        SecureDirectory(Path.GetDirectoryName(CacheDirectory)!, allowUsersRead: true);
        SecureDirectory(CacheDirectory, allowUsersRead: false);
        RejectReparsePath(destination);

        using var manager = OpenSCManager(null, null, 0x0001 | 0x0002);
        EnsureValid(manager, "无法打开 Windows 服务管理器。");
        using var existing = OpenService(manager, ServiceName, 0x0002 | 0x0004 | 0x0010 | 0x0020 | 0x0001 | 0x00040000);
        var existingError = existing.IsInvalid ? Marshal.GetLastWin32Error() : 0;
        if (existing.IsInvalid && existingError != 1060)
            throw new Win32Exception(existingError, "无法打开已有索引服务。");
        if (!existing.IsInvalid) VerifyInstalledServicePath(existing, destination);

        // Stage in a protected sibling before stopping the existing service. Roll back the complete
        // directory on any copy/configuration/start failure; never run from a user-writable folder.
        var sameSource = Path.TrimEndingDirectorySeparator(source).Equals(
            Path.TrimEndingDirectorySeparator(destination), StringComparison.OrdinalIgnoreCase);
        var staging = Path.Combine(parent, "IndexingService.setup-" + Guid.NewGuid().ToString("N"));
        var backup = Path.Combine(parent, "IndexingService.previous-" + Guid.NewGuid().ToString("N"));
        var movedOld = false;
        var movedNew = false;
        var succeeded = false;
        ServiceControlHandle? created = null;
        try
        {
            if (!sameSource)
            {
                SecureDirectory(staging, allowUsersRead: true);
                CopyBundle(source, staging);
            }
            if (!existing.IsInvalid) StopAndWait(existing);
            // A running instance may atomically replace its checkpoint files; wait for it to
            // finish before checking and hardening pre-existing cache children.
            HardenTree(CacheDirectory, allowUsersRead: false);
            if (!sameSource)
            {
                if (Directory.Exists(destination))
                {
                    RejectReparsePath(destination);
                    Directory.Move(destination, backup);
                    movedOld = true;
                }
                Directory.Move(staging, destination);
                movedNew = true;
            }
            else
            {
                SecureDirectory(destination, allowUsersRead: true);
                HardenTree(destination, allowUsersRead: true);
            }

            var binary = '"' + Path.Combine(destination, ExecutableName) + '"';
            var service = existing;
            if (existing.IsInvalid)
            {
                created = CreateService(manager, ServiceName, "XFEToolBox 高速文件索引", 0x000F01FF,
                    0x10, 2, 1, binary, null, IntPtr.Zero, null, "LocalSystem", null);
                EnsureValid(created, "无法创建索引服务。");
                service = created;
            }
            else if (!ChangeServiceConfig(service, 0x10, 2, 1, binary, null, IntPtr.Zero, null, "LocalSystem", null,
                         "XFEToolBox 高速文件索引"))
                ThrowLastError("无法更新索引服务配置。");
            var delayed = new DelayedAutoStart { Enabled = true };
            if (!ChangeServiceConfig2(service, 3, ref delayed)) ThrowLastError("无法配置延迟自动启动。");
            SetServicePermissions(service);
            if (!StartService(service, 0, IntPtr.Zero) && Marshal.GetLastWin32Error() != 1056)
                ThrowLastError("无法启动索引服务。");
            WaitForState(service, 4, TimeSpan.FromSeconds(45));
            succeeded = true;
        }
        catch
        {
            if (created is not null && !created.IsInvalid)
            {
                try { StopAndWait(created); DeleteService(created); } catch { }
            }
            else if (!existing.IsInvalid)
            {
                try { StopAndWait(existing); } catch { }
            }
            if (movedNew)
            {
                // Keep the failed new payload out of the live path, without deleting unrelated data.
                Directory.Move(destination, staging);
                movedNew = false;
            }
            if (movedOld)
            {
                Directory.Move(backup, destination);
                movedOld = false;
            }
            if (!existing.IsInvalid) StartService(existing, 0, IntPtr.Zero);
            throw;
        }
        finally
        {
            created?.Dispose();
            TryRemoveSetupTree(staging, parent);
            if (succeeded && movedOld) TryRemoveSetupTree(backup, parent);
        }
    }

    private static void Uninstall()
    {
        using var manager = OpenSCManager(null, null, 0x0001);
        EnsureValid(manager, "无法打开 Windows 服务管理器。");
        using var service = OpenService(manager, ServiceName, 0x0001 | 0x0004 | 0x0020 | 0x00010000);
        if (service.IsInvalid)
        {
            if (Marshal.GetLastWin32Error() == 1060) return;
            ThrowLastError("无法打开索引服务。");
        }
        VerifyInstalledServicePath(service, InstallationDirectory);
        StopAndWait(service);
        if (!DeleteService(service) && Marshal.GetLastWin32Error() != 1072)
            ThrowLastError("无法卸载索引服务。");
        // Intentionally retain the protected payload and ProgramData index: uninstall can be
        // invoked from that executable, and a reinstall can resume the existing USN checkpoint.
    }

    private static void CopyBundle(string source, string destination)
    {
        var pending = new Stack<(string Source, string Destination)>();
        pending.Push((source, destination));
        var count = 0;
        long bytes = 0;
        var pinnedDirectories = new Dictionary<string, SafeFileHandle>(StringComparer.OrdinalIgnoreCase);
        try
        {
            // Keep the source root's ancestor chain and every visited directory open without
            // FILE_SHARE_DELETE. A user cannot swap an ancestor junction while an elevated
            // path-based directory enumeration is taking place.
            var ancestors = new Stack<string>();
            for (var current = Path.GetFullPath(source); current is not null; current = Path.GetDirectoryName(current))
                ancestors.Push(current);
            while (ancestors.TryPop(out var ancestor)) PinSourceDirectory(ancestor, pinnedDirectories);
            while (pending.TryPop(out var pair))
            {
                PinSourceDirectory(pair.Source, pinnedDirectories);
                foreach (var entry in Directory.EnumerateFileSystemEntries(pair.Source))
                {
                    if ((File.GetAttributes(entry) & FileAttributes.ReparsePoint) != 0)
                        throw new InvalidDataException("服务安装目录不能包含符号链接或重解析点。");
                    if (++count > 20000) throw new InvalidDataException("服务安装文件数量异常。");
                    var target = Path.Combine(pair.Destination, Path.GetFileName(entry));
                    if (Directory.Exists(entry))
                    {
                        SecureDirectory(target, true);
                        pending.Push((entry, target));
                    }
                    else
                    {
                        bytes += CopyBundleFile(entry, target, 2L * 1024 * 1024 * 1024 - bytes);
                        SecureFile(target, true);
                    }
                }
            }
        }
        finally { foreach (var handle in pinnedDirectories.Values) handle.Dispose(); }
    }

    private static void PinSourceDirectory(string path, IDictionary<string, SafeFileHandle> pinned)
    {
        if (pinned.ContainsKey(path)) return;
        // LIST_DIRECTORY is intentional: an attribute-only handle does not necessarily
        // participate in NTFS share-access checks and is insufficient to pin a name.
        var handle = CreateFileW(path, 0x81, 3, IntPtr.Zero, 3, 0x00200000 | 0x02000000, IntPtr.Zero);
        try
        {
            if (handle.IsInvalid) ThrowLastError("无法安全访问服务发行目录。");
            if (!GetFileInformationByHandle(handle, out var information)) ThrowLastError("无法验证服务发行目录。");
            if ((information.Attributes & 0x400u) != 0 || (information.Attributes & 0x10u) == 0)
                throw new InvalidDataException("服务发行目录不能包含重解析点:" + path);
            ValidateSourceHandlePath(handle, path);
            pinned.Add(path, handle);
        }
        catch { handle.Dispose(); throw; }
    }

    private static long CopyBundleFile(string source, string destination, long remainingBytes)
    {
        // The bundle is deliberately allowed to live in a user-owned portable folder. Never
        // reopen a path after validation: an elevated path-based File.Copy could follow a
        // replaced reparse point, or export the contents of a hard-linked privileged file.
        using var handle = CreateFileW(source, 0x80000000, 1, IntPtr.Zero, 3, 0x00200000 | 0x08000000, IntPtr.Zero);
        if (handle.IsInvalid) ThrowLastError("无法安全读取索引服务发行文件。");
        if (!GetFileInformationByHandle(handle, out var information)) ThrowLastError("无法验证索引服务发行文件。");
        if ((information.Attributes & (0x400u | 0x10u)) != 0 || information.NumberOfLinks != 1)
            throw new InvalidDataException("服务发行文件不能是重解析点、目录或 NTFS 硬链接:" + source);

        // OPEN_REPARSE_POINT protects the final component. A normalized final-path check
        // additionally detects an ancestor junction swapped between enumeration and open.
        ValidateSourceHandlePath(handle, source);

        var length = ((long)information.SizeHigh << 32) | information.SizeLow;
        if (length < 0 || length > remainingBytes) throw new InvalidDataException("服务安装文件体积异常。");
        using var input = new FileStream(handle, FileAccess.Read, 64 * 1024, isAsync: false);
        using var output = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024);
        input.CopyTo(output, 64 * 1024);
        return length;
    }

    private static void ValidateSourceHandlePath(SafeFileHandle handle, string source)
    {
        var actualPath = ReadNativePath((buffer, capacity) => GetFinalPathNameByHandleW(handle, buffer, capacity, 0));
        if (actualPath.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase)) actualPath = @"\\" + actualPath[8..];
        else if (actualPath.StartsWith(@"\\?\", StringComparison.Ordinal)) actualPath = actualPath[4..];
        var expectedPath = ReadNativePath((buffer, capacity) => GetLongPathNameW(Path.GetFullPath(source), buffer, capacity));
        if (!actualPath.Equals(expectedPath, StringComparison.OrdinalIgnoreCase))
            throw new InvalidDataException("服务发行文件路径在读取前发生变化或经过目录重解析点:" + source);
    }

    private static string ReadNativePath(Func<StringBuilder, uint, uint> read)
    {
        var buffer = new StringBuilder(512);
        var length = read(buffer, (uint)buffer.Capacity);
        if (length == 0) ThrowLastError("无法验证服务发行文件的实际路径。");
        if (length >= buffer.Capacity)
        {
            if (length > 32768) throw new InvalidDataException("服务发行文件路径过长。");
            buffer.EnsureCapacity(checked((int)length + 1));
            length = read(buffer, (uint)buffer.Capacity);
            if (length == 0 || length >= buffer.Capacity) ThrowLastError("无法验证服务发行文件的实际路径。");
        }
        return buffer.ToString();
    }

    private static void HardenTree(string directory, bool allowUsersRead)
    {
        foreach (var entry in Directory.EnumerateFileSystemEntries(directory))
        {
            RejectReparsePath(entry);
            if (Directory.Exists(entry))
            {
                SecureDirectory(entry, allowUsersRead);
                HardenTree(entry, allowUsersRead);
            }
            else SecureFile(entry, allowUsersRead);
        }
    }

    private static void SecureDirectory(string directory, bool allowUsersRead)
    {
        RejectReparsePath(directory);
        var security = new DirectorySecurity();
        security.SetAccessRuleProtection(true, false);
        security.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null));
        var inheritance = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
        foreach (var sid in new[] { WellKnownSidType.LocalSystemSid, WellKnownSidType.BuiltinAdministratorsSid })
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(sid, null), FileSystemRights.FullControl,
                inheritance, PropagationFlags.None, AccessControlType.Allow));
        if (allowUsersRead)
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
                FileSystemRights.ReadAndExecute, inheritance, PropagationFlags.None, AccessControlType.Allow));
        var info = new DirectoryInfo(directory);
        if (!info.Exists) info.Create(security);
        else
        {
            RequireTrustedSecurity(info.GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access));
            info.SetAccessControl(security);
        }
        RejectReparsePath(directory);
    }

    private static void SecureFile(string path, bool allowUsersRead)
    {
        RejectReparsePath(path);
        var info = new FileInfo(path);
        RequireTrustedSecurity(info.GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access));
        var security = new FileSecurity();
        security.SetAccessRuleProtection(true, false);
        security.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null));
        foreach (var sid in new[] { WellKnownSidType.LocalSystemSid, WellKnownSidType.BuiltinAdministratorsSid })
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(sid, null), FileSystemRights.FullControl, AccessControlType.Allow));
        if (allowUsersRead)
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
                FileSystemRights.ReadAndExecute, AccessControlType.Allow));
        info.SetAccessControl(security);
    }

    private static void RequireTrustedSecurity(FileSystemSecurity security)
    {
        var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
        var administrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
        var owner = security.GetOwner(typeof(SecurityIdentifier));
        if (!system.Equals(owner) && !administrators.Equals(owner))
            throw new UnauthorizedAccessException("现有索引服务目录/文件不是由 SYSTEM 或管理员拥有,请由管理员检查并移走后重试。");
        const FileSystemRights write = FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles |
            FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership;
        foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
        {
            if (rule.AccessControlType != AccessControlType.Allow || (rule.PropagationFlags & PropagationFlags.InheritOnly) != 0 ||
                (rule.FileSystemRights & write) == 0) continue;
            if (!system.Equals(rule.IdentityReference) && !administrators.Equals(rule.IdentityReference))
                throw new UnauthorizedAccessException("现有索引服务目录/文件允许普通账户写入,已拒绝将其用作特权服务路径。");
        }
    }

    internal static void RejectReparsePath(string path)
    {
        for (var current = Path.GetFullPath(path); current is not null; current = Path.GetDirectoryName(current))
        {
            // GetAttributes also recognizes dangling junctions, unlike Directory.Exists.
            try
            {
                if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
                    throw new InvalidDataException("索引服务路径不能经过符号链接或目录重解析点:" + current);
            }
            catch (FileNotFoundException) { }
            catch (DirectoryNotFoundException) { }
        }
    }

    private static void TryRemoveSetupTree(string directory, string allowedParent)
    {
        try
        {
            var full = Path.GetFullPath(directory);
            if (!Path.GetDirectoryName(full)!.Equals(Path.GetFullPath(allowedParent), StringComparison.OrdinalIgnoreCase) ||
                !(Path.GetFileName(full).StartsWith("IndexingService.setup-", StringComparison.Ordinal) ||
                  Path.GetFileName(full).StartsWith("IndexingService.previous-", StringComparison.Ordinal))) return;
            if (!Directory.Exists(full)) return;
            RemoveTree(full);
        }
        catch (Exception exception) { Trace.WriteLine("Service setup cleanup: " + exception.Message); }

        static void RemoveTree(string path)
        {
            RejectReparsePath(path);
            foreach (var entry in Directory.EnumerateFileSystemEntries(path))
            {
                RejectReparsePath(entry);
                if (Directory.Exists(entry)) RemoveTree(entry);
                else File.Delete(entry);
            }
            Directory.Delete(path);
        }
    }

    private static void VerifyInstalledServicePath(ServiceControlHandle service, string directory)
    {
        QueryServiceConfig(service, IntPtr.Zero, 0, out var needed);
        if (needed is <= 0 or > 65536) ThrowLastError("无法验证现有服务路径。");
        var buffer = Marshal.AllocHGlobal(needed);
        try
        {
            if (!QueryServiceConfig(service, buffer, needed, out _)) ThrowLastError("无法读取现有服务配置。");
            var config = Marshal.PtrToStructure<ServiceConfig>(buffer);
            var binary = Marshal.PtrToStringUni(config.BinaryPath)?.Trim().Trim('"');
            var expected = Path.Combine(directory, ExecutableName);
            if (binary is null || !Path.GetFullPath(binary).Equals(expected, StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("同名服务不是位于受保护目录中的 XFEToolBox 索引服务,已拒绝修改。");
        }
        finally { Marshal.FreeHGlobal(buffer); }
    }

    private static void SetServicePermissions(ServiceControlHandle service)
    {
        const string descriptor = "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;CCLCSWLORC;;;BU)";
        if (!ConvertStringSecurityDescriptorToSecurityDescriptor(descriptor, 1, out var security, out _))
            ThrowLastError("无法创建服务访问策略。");
        try
        {
            if (!SetServiceObjectSecurity(service, 4, security)) ThrowLastError("无法限制服务管理权限。");
        }
        finally { LocalFree(security); }
    }

    private static void StopAndWait(ServiceControlHandle service)
    {
        if (!QueryServiceStatus(service, out var status)) ThrowLastError("无法读取服务状态。");
        if (status.CurrentState == 1) return;
        if (!ControlService(service, 1, out _) && Marshal.GetLastWin32Error() != 1062)
            ThrowLastError("无法停止正在运行的索引服务。");
        WaitForState(service, 1, TimeSpan.FromSeconds(45));
    }

    private static void WaitForState(ServiceControlHandle service, uint expected, TimeSpan timeout)
    {
        var elapsed = Stopwatch.StartNew();
        while (elapsed.Elapsed < timeout)
        {
            if (!QueryServiceStatus(service, out var status)) ThrowLastError("无法读取服务状态。");
            if (status.CurrentState == expected) return;
            if (expected == 4 && status.CurrentState == 1)
                throw new InvalidOperationException($"索引服务启动后立即退出({status.Win32ExitCode})。");
            Thread.Sleep(100);
        }
        throw new TimeoutException("等待索引服务状态改变超时。");
    }

    private static void TryWriteLog(Exception exception)
    {
        try
        {
            RejectReparsePath(CacheDirectory);
            if (Directory.Exists(CacheDirectory))
            {
                RequireTrustedSecurity(new DirectoryInfo(CacheDirectory).GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access));
                var log = Path.Combine(CacheDirectory, "installation.log");
                RejectReparsePath(log);
                if (File.Exists(log)) RequireTrustedSecurity(new FileInfo(log).GetAccessControl(AccessControlSections.Owner | AccessControlSections.Access));
                File.AppendAllText(log, DateTimeOffset.UtcNow.ToString("O") + " " + exception + Environment.NewLine);
            }
        }
        catch { /* Diagnostic failure must not conceal the original exit code. */ }
    }

    private static void EnsureValid(ServiceControlHandle handle, string message)
    {
        if (handle.IsInvalid) ThrowLastError(message);
    }
    private static void ThrowLastError(string message) => throw new Win32Exception(Marshal.GetLastWin32Error(), message);

    private sealed class ServiceControlHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        public ServiceControlHandle() : base(true) { }
        protected override bool ReleaseHandle() => CloseServiceHandle(handle);
    }
    [StructLayout(LayoutKind.Sequential)] private struct ServiceStatus
    {
        public uint ServiceType, CurrentState, ControlsAccepted, Win32ExitCode, ServiceSpecificExitCode, CheckPoint, WaitHint;
    }
    [StructLayout(LayoutKind.Sequential)] private struct ServiceConfig
    {
        public uint ServiceType, StartType, ErrorControl;
        public IntPtr BinaryPath, LoadOrderGroup;
        public uint TagId;
        public IntPtr Dependencies, StartName, DisplayName;
    }
    [StructLayout(LayoutKind.Sequential)] private struct DelayedAutoStart { [MarshalAs(UnmanagedType.Bool)] public bool Enabled; }
    [StructLayout(LayoutKind.Sequential)] private struct FileInformation
    {
        public uint Attributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write;
        public uint Volume, SizeHigh, SizeLow, NumberOfLinks, IndexHigh, IndexLow;
    }

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern ServiceControlHandle OpenSCManager(string? machine, string? database, uint access);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern ServiceControlHandle OpenService(ServiceControlHandle manager, string name, uint access);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern ServiceControlHandle CreateService(ServiceControlHandle manager, string name, string displayName, uint access,
        uint type, uint start, uint error, string path, string? group, IntPtr tag, string? dependencies, string? account, string? password);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool ChangeServiceConfig(ServiceControlHandle service, uint type, uint start, uint error, string path,
        string? group, IntPtr tag, string? dependencies, string? account, string? password, string? displayName);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool ChangeServiceConfig2(ServiceControlHandle service, uint level, ref DelayedAutoStart value);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool QueryServiceConfig(ServiceControlHandle service, IntPtr config, int size, out int needed);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool StartService(ServiceControlHandle service, uint count, IntPtr arguments);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool QueryServiceStatus(ServiceControlHandle service, out ServiceStatus status);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool ControlService(ServiceControlHandle service, uint control, out ServiceStatus status);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool DeleteService(ServiceControlHandle service);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseServiceHandle(IntPtr handle);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string text, uint revision, out IntPtr descriptor, out uint size);
    [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetServiceObjectSecurity(ServiceControlHandle service, uint information, IntPtr descriptor);
    [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory);
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint mode, uint flags, IntPtr template);
    [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetFileInformationByHandle(SafeFileHandle file, out FileInformation information);
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern uint GetFinalPathNameByHandleW(SafeFileHandle file, StringBuilder path, uint length, uint flags);
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern uint GetLongPathNameW(string path, StringBuilder output, uint length);
}