packServer/desktop/Services/ClockSyncService.cs
2026-10-19 22:04:19 +08:00

173 lines
6.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 把本机系统时钟校准到 NTP 时间。
///
/// ⚠️ 修改系统时间需要管理员权限(本软件默认以普通权限运行,非管理员时会由
/// <see cref="ElevatedNtp"/> 拉起提权 helper 执行本类的 <see cref="SyncAsync"/>),
/// 并且要先把当前进程令牌里的 <c>SeSystemtimePrivilege</c> 打开,
/// 否则 <c>SetSystemTime</c> 会失败(错误 1314)。
///
/// 现场根因:Windows Time 服务没启动时本机会慢慢变慢(实测差了近 10 秒),
/// 扫码时间是本机时钟打的、回放按录像机时间定位,差几秒面单就被截到回放窗口外。
/// </summary>
public static class ClockSyncService
{
/// <summary>小于这个偏差就不动系统时间(避免频繁触发系统时间变更事件)</summary>
public static readonly TimeSpan MinimumAdjust = TimeSpan.FromMilliseconds(200);
/// <summary>查询 + 校准,返回本次查询结果(即使偏差很小也会返回)。</summary>
public static async Task<NtpResult> SyncAsync(string server, int timeoutMs = 3000, CancellationToken ct = default)
{
var result = await NtpClient.QueryAsync(server, timeoutMs, ct).ConfigureAwait(false);
Apply(result.Offset);
return result;
}
/// <summary>
/// 按偏差调整系统时间(UTC 写入)。
/// </summary>
/// <exception cref="InvalidOperationException">没有权限 / SetSystemTime 失败</exception>
public static void Apply(TimeSpan offset)
{
if (offset.Duration() < MinimumAdjust) return;
if (!EnableSystemTimePrivilege())
{
throw new InvalidOperationException("没有修改系统时间的权限,请以管理员身份运行本软件");
}
var time = ToSystemTime(DateTime.UtcNow.Add(offset));
if (!SetSystemTime(ref time))
{
var error = Marshal.GetLastWin32Error();
throw new InvalidOperationException($"设置系统时间失败(错误 {error}),请以管理员身份运行本软件");
}
}
/// <summary>当前进程是否以管理员身份运行(给界面提示用)</summary>
public static bool IsElevated
{
get
{
try
{
using var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
}
// ==================== Win32 ====================
private const uint TokenAdjustPrivileges = 0x0020;
private const uint TokenQuery = 0x0008;
private const uint SePrivilegeEnabled = 0x00000002;
[StructLayout(LayoutKind.Sequential)]
private struct Luid
{
public uint LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
private struct LuidAndAttributes
{
public Luid Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
private struct TokenPrivileges
{
public uint PrivilegeCount;
public LuidAndAttributes Privilege;
}
[StructLayout(LayoutKind.Sequential)]
private struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Milliseconds;
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LookupPrivilegeValue(string? systemName, string name, out Luid luid);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges,
ref TokenPrivileges newState, uint bufferLength, IntPtr previousState, IntPtr returnLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetSystemTime(ref SystemTime systemTime);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
private static bool EnableSystemTimePrivilege()
{
if (!OpenProcessToken(GetCurrentProcess(), TokenAdjustPrivileges | TokenQuery, out var token))
{
return false;
}
try
{
if (!LookupPrivilegeValue(null, "SeSystemtimePrivilege", out var luid)) return false;
var privileges = new TokenPrivileges
{
PrivilegeCount = 1,
Privilege = new LuidAndAttributes { Luid = luid, Attributes = SePrivilegeEnabled },
};
if (!AdjustTokenPrivileges(token, false, ref privileges, 0, IntPtr.Zero, IntPtr.Zero)) return false;
// AdjustTokenPrivileges 在「部分成功」时也返回 true,必须再查一次错误码
return Marshal.GetLastWin32Error() == 0;
}
finally
{
CloseHandle(token);
}
}
private static SystemTime ToSystemTime(DateTime utc)
{
return new SystemTime
{
Year = (ushort)utc.Year,
Month = (ushort)utc.Month,
DayOfWeek = (ushort)utc.DayOfWeek,
Day = (ushort)utc.Day,
Hour = (ushort)utc.Hour,
Minute = (ushort)utc.Minute,
Second = (ushort)utc.Second,
Milliseconds = (ushort)utc.Millisecond,
};
}
}