feat(desktop): NTP 校时与提权校时助手

This commit is contained in:
liufumingren 2026-10-19 22:04:19 +08:00
parent cb504608a1
commit 0b0296cece
5 changed files with 942 additions and 0 deletions

93
desktop/NtpWindow.xaml Normal file
View File

@ -0,0 +1,93 @@
<Window x:Class="YuncangTrace.LocalService.NtpWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="NTP 校时"
Width="520" SizeToContent="Height"
ResizeMode="NoResize"
WindowStartupLocation="CenterOwner"
Background="{StaticResource BgBrush}"
FontFamily="Microsoft YaHei UI, Segoe UI"
FontSize="13">
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
CornerRadius="10" Margin="18" Padding="18">
<StackPanel>
<TextBlock Text="NTP 校时" FontSize="15" FontWeight="SemiBold" />
<TextBlock Text="扫码时间用本机时钟,回放按录像机时间定位;本机时间不准会让录像整体错位。"
FontSize="12" Foreground="{StaticResource MutedBrush}" Margin="0,4,0,14" />
<TextBlock Text="NTP 服务器" FontSize="12" Foreground="{StaticResource MutedBrush}" />
<TextBox x:Name="ServerBox" Padding="6,4" Margin="0,4,0,10"
ToolTip="域名或 IP,例如 ntp.aliyun.com / 112.124.21.102" />
<CheckBox x:Name="EnabledBox" Content="启用 NTP 校时(关闭后不再自动校时)" Margin="0,0,0,6" />
<CheckBox x:Name="StartupBox" Content="启动软件时自动校时" Margin="0,0,0,10" />
<TextBlock x:Name="ServiceModeTip" Text="服务模式:NTP 校时为强制开启,不能停用自动校时。"
FontSize="11" Foreground="#B45309" Margin="0,-4,0,10" Visibility="Collapsed" />
<DockPanel Margin="0,0,0,12" LastChildFill="False">
<TextBlock DockPanel.Dock="Left" Text="自动校时间隔(分钟,0 = 仅启动时)"
FontSize="12" Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" />
<TextBox x:Name="IntervalBox" DockPanel.Dock="Right" Width="70" Padding="6,4" />
</DockPanel>
<Border Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
CornerRadius="6" Padding="10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="本机时间:" Foreground="{StaticResource MutedBrush}" Margin="0,0,10,4" />
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="LocalTimeText" Margin="0,0,0,4" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="NTP 时间:" Foreground="{StaticResource MutedBrush}" Margin="0,0,10,4" />
<TextBlock Grid.Row="1" Grid.Column="1" x:Name="ServerTimeText" Text="—" Margin="0,0,0,4" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="偏差:" Foreground="{StaticResource MutedBrush}" Margin="0,0,10,4" />
<TextBlock Grid.Row="2" Grid.Column="1" x:Name="OffsetText" Text="—" Margin="0,0,0,4" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="往返:" Foreground="{StaticResource MutedBrush}" Margin="0,0,10,0" />
<TextBlock Grid.Row="3" Grid.Column="1" x:Name="RttText" Text="—" />
</Grid>
</Border>
<TextBlock x:Name="StatusText" Text="尚未校时" FontSize="12" Margin="0,10,0,0"
Foreground="{StaticResource MutedBrush}" TextWrapping="Wrap" />
<TextBlock Text="提示:修改「自动校时间隔」后需重启软件生效。"
FontSize="11" Foreground="{StaticResource MutedBrush}" Margin="0,4,0,0" />
<!-- 录像机 NTP:拉取当前主体全部 NVR,静默写入与上面一致的 NTP 服务器,并立即生效 -->
<Border Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}" BorderThickness="1"
CornerRadius="6" Padding="10" Margin="0,14,0,0">
<StackPanel>
<DockPanel LastChildFill="False" Margin="0,0,0,8">
<Button x:Name="SyncNvrButton" DockPanel.Dock="Right" Content="同步 NVR 时间"
Padding="14,5" Background="{StaticResource BrandBrush}" Foreground="White"
BorderThickness="0" Cursor="Hand" Click="SyncNvr_Click" />
<TextBlock Text="录像机 NTP(与上方服务器一致,立即生效)" FontSize="12"
Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" />
</DockPanel>
<TextBox x:Name="NvrResultBox" Height="120" IsReadOnly="True" AcceptsReturn="True"
TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12" Padding="8"
Background="White" BorderBrush="{StaticResource LineBrush}" />
</StackPanel>
</Border>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,14,0,0">
<Button Content="关闭" Padding="14,5" IsCancel="True" Click="Cancel_Click" />
<Button Content="保存" Padding="14,5" Margin="8,0,0,0" Click="Save_Click" />
<Button x:Name="SyncButton" Content="立即校时" Padding="14,5" Margin="8,0,0,0"
Background="{StaticResource BrandBrush}" Foreground="White" BorderThickness="0"
Cursor="Hand" Click="Sync_Click" />
</StackPanel>
</StackPanel>
</Border>
</Window>

412
desktop/NtpWindow.xaml.cs Normal file
View File

@ -0,0 +1,412 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using YuncangTrace.LocalService.Services;
using YuncangTrace.LocalService.Services.Hik;
namespace YuncangTrace.LocalService;
/// <summary>
/// NTP 校时设置窗:改 NTP 服务器 / 开关 / 间隔,并可立即校时。
///
/// ⚠️ 校时会修改**本机系统时间**,但软件默认以普通权限运行(manifest = asInvoker);
/// 非管理员时点「立即校时 / 同步 NVR 时间」才会用 runas 弹一次 UAC(见 <see cref="ElevatedNtp"/>)。
/// </summary>
public partial class NtpWindow : Window
{
private readonly AppSettings _settings;
private readonly ApiClient _api;
private readonly Session _session;
private readonly int _subjectId;
private readonly DispatcherTimer _clock;
/// <summary>服务模式(设备服务开启):NTP 为强制项,不能停用自动校时</summary>
private readonly bool _serviceMode;
private bool _busy;
public NtpWindow(AppSettings settings, ApiClient api, Session session, int subjectId)
{
InitializeComponent();
_settings = settings;
_api = api;
_session = session;
_subjectId = subjectId;
_serviceMode = settings.DeviceServiceEnabled;
ServerBox.Text = settings.NtpServer;
EnabledBox.IsChecked = settings.NtpEnabled;
StartupBox.IsChecked = settings.NtpSyncOnStartup;
IntervalBox.Text = settings.NtpSyncIntervalMinutes.ToString();
if (_serviceMode)
{
// 服务模式:必须启用 NTP + 启动校时 + 定时校时(间隔 > 0)
EnabledBox.IsChecked = true;
StartupBox.IsChecked = true;
EnabledBox.IsEnabled = false;
StartupBox.IsEnabled = false;
ServiceModeTip.Visibility = Visibility.Visible;
if (settings.NtpSyncIntervalMinutes <= 0) IntervalBox.Text = "30";
}
LocalTimeText.Text = Now();
StatusText.Text = string.IsNullOrWhiteSpace(settings.NtpLastSyncAt)
? "尚未校时"
: $"上次校时:{settings.NtpLastSyncAt}(偏差 {settings.NtpLastOffsetSeconds:+0.00;-0.00} 秒)";
// 服务模式:上次校时是后台服务做的,以它的状态为准
if (AgentPaths.MachineMode)
{
var agent = AgentFiles.LoadStatus();
if (!string.IsNullOrWhiteSpace(agent?.NtpLastSyncAt))
{
StatusText.Text = $"上次校时(后台服务):{agent!.NtpLastSyncAt}"
+ $"(偏差 {agent.NtpLastOffsetSeconds:+0.00;-0.00} 秒)";
}
}
if (!ClockSyncService.IsElevated)
{
StatusText.Text = "提示:修改系统时间需要管理员权限,点「立即校时」时会弹 UAC 确认。";
}
// 每秒刷新一次本机时间(改完系统时间后能直观看到变化)
_clock = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
_clock.Tick += (_, _) => LocalTimeText.Text = Now();
_clock.Start();
Closed += (_, _) => _clock.Stop();
// 打开时自动查询一次(只查询、不修改时间)
Loaded += async (_, _) => await ProbeAsync();
}
private static string Now() => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
/// <summary>查询 NTP 并展示偏差(不修改系统时间)</summary>
private async Task ProbeAsync()
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
try
{
ServerTimeText.Text = "查询中…";
OffsetText.Text = "—";
RttText.Text = "—";
var result = await NtpClient.QueryAsync(ServerBox.Text);
ShowResult(result);
StatusText.Text = Math.Abs(result.Offset.TotalSeconds) < ClockSyncService.MinimumAdjust.TotalSeconds
? "本机时间与 NTP 一致(偏差小于 0.2 秒)"
: "查询成功,可点「立即校时」写入系统时间";
}
catch (Exception ex)
{
ServerTimeText.Text = "—";
OffsetText.Text = "—";
RttText.Text = "—";
StatusText.Text = $"查询失败:{ex.Message}";
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
}
}
/// <summary>
/// 查询并校准本机时钟:
/// - 服务模式(后台服务在跑)→ 写命令文件,由 LocalSystem 服务校时(**不弹 UAC**);
/// - 已经是管理员 → 直接改;
/// - 否则用 runas 起一个只做校时的临时进程(弹一次 UAC)。
/// </summary>
private static Task<NtpResult> SyncLocalClockAsync(string server)
{
if (ServiceInstaller.IsRunning) return SyncViaServiceAsync(server);
return ClockSyncService.IsElevated
? ClockSyncService.SyncAsync(server)
: ElevatedNtp.SyncAsync(server);
}
/// <summary>让后台服务校时:写命令 → 轮询 agent-status.json 等结果</summary>
private static async Task<NtpResult> SyncViaServiceAsync(string server)
{
var before = AgentFiles.LoadStatus()?.NtpLastSyncAt ?? string.Empty;
AgentFiles.QueueCommand(command =>
{
command.NtpSyncAt = DateTime.UtcNow;
command.NtpServer = server;
});
for (var i = 0; i < 20; i++)
{
await Task.Delay(500);
var status = AgentFiles.LoadStatus();
if (status is null) continue;
if (string.IsNullOrWhiteSpace(status.NtpLastSyncAt)) continue;
if (status.NtpLastSyncAt == before) continue;
var serverTime = status.NtpServerTime is { } time
? new DateTimeOffset(time)
: DateTimeOffset.Now;
return new NtpResult(server, serverTime,
TimeSpan.FromSeconds(status.NtpLastOffsetSeconds),
TimeSpan.FromMilliseconds(status.NtpRoundTripMs));
}
throw new InvalidOperationException("后台服务没有响应校时请求(请确认「YuncangTraceAgent」服务在运行)");
}
/// <summary>服务模式:把 NTP 设置同步给后台服务(定时校时由它执行)</summary>
private void PushNtpSettingsToAgent()
{
if (!AgentPaths.MachineMode && !ServiceInstaller.IsInstalled) return;
var config = AgentFiles.LoadConfig() ?? new AgentConfig
{
ServerBaseUrl = _settings.ServerBaseUrl,
DeviceToken = _settings.DeviceToken,
DeviceSn = _settings.DeviceSn,
DeviceId = _settings.DeviceId,
SubjectId = _settings.SubjectId,
};
config.NtpEnabled = _settings.NtpEnabled;
config.NtpServer = _settings.NtpServer;
config.NtpIntervalMinutes = _settings.NtpSyncIntervalMinutes;
AgentFiles.SaveConfig(config);
}
/// <summary>查询 + 写入系统时间</summary>
private async void Sync_Click(object sender, RoutedEventArgs e)
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
try
{
var result = await SyncLocalClockAsync(ServerBox.Text);
LocalTimeText.Text = Now();
ShowResult(result);
_settings.NtpLastSyncAt = Now();
_settings.NtpLastOffsetSeconds = Math.Round(result.Offset.TotalSeconds, 2);
_settings.Save();
StatusText.Text = Math.Abs(result.Offset.TotalSeconds) < ClockSyncService.MinimumAdjust.TotalSeconds
? "本机时间已准确(偏差小于 0.2 秒,未调整)"
: "已校时:系统时间已按 NTP 调整";
AppLog.Write($"[ntp] 手动校时:{result.Server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒,往返 {result.RoundTrip.TotalMilliseconds:0} ms");
}
catch (OperationCanceledException)
{
StatusText.Text = "已取消:需要管理员权限才能修改系统时间";
AppLog.Write("[ntp] 手动校时:用户取消了管理员授权");
}
catch (Exception ex)
{
StatusText.Text = $"校时失败:{ex.Message}";
AppLog.Write($"[ntp] 手动校时失败:{ex.Message}");
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
}
}
private void ShowResult(NtpResult result)
{
ServerTimeText.Text = result.ServerTime.ToString("yyyy-MM-dd HH:mm:ss");
OffsetText.Text = $"{result.Offset.TotalSeconds:+0.00;-0.00} 秒(正数 = 本机慢了)";
RttText.Text = $"{result.RoundTrip.TotalMilliseconds:0} ms";
}
/// <summary>
/// 同步 NVR 时间:拉取当前主体全部录像机,静默把 NTP 写进去(与桌面端同一个服务器),
/// 并把设备时间直接校准到 NTP 时间(立即生效),逐台返回结果。
/// </summary>
private async void SyncNvr_Click(object sender, RoutedEventArgs e)
{
if (_busy) return;
_busy = true;
SyncButton.IsEnabled = false;
SyncNvrButton.IsEnabled = false;
var lines = new List<string>();
try
{
var server = (ServerBox.Text ?? string.Empty).Trim();
if (server.Length == 0) throw new InvalidOperationException("请先填写 NTP 服务器");
var formInterval = int.TryParse((IntervalBox.Text ?? string.Empty).Trim(), out var typed) && typed >= 0
? typed
: _settings.NtpSyncIntervalMinutes;
var interval = Math.Clamp(formInterval > 0 ? formInterval : 60, 1, 1440);
// 先落盘:录像机与桌面端必须用同一个 NTP 地址
_settings.NtpServer = server;
_settings.NtpSyncIntervalMinutes = formInterval;
if (_serviceMode)
{
_settings.NtpEnabled = true;
_settings.NtpSyncOnStartup = true;
}
_settings.Save();
PushNtpSettingsToAgent();
lines.Add($"NTP 服务器:{server}(正在校准本机时间…)");
ShowNvrResult(lines);
// 先校准本机(同时确认 NTP 服务器可用),再把同一个服务器写进录像机
var clock = await SyncLocalClockAsync(server);
var offset = clock.Offset;
_settings.NtpLastSyncAt = Now();
_settings.NtpLastOffsetSeconds = Math.Round(offset.TotalSeconds, 2);
_settings.Save();
LocalTimeText.Text = Now();
lines[0] = $"NTP 服务器:{server}(本机偏差 {offset.TotalSeconds:+0.00;-0.00} 秒,已校准本机)";
lines.Add("正在拉取录像机列表…");
ShowNvrResult(lines);
var nvrs = await _api.NvrsAsync(_session.Token, _subjectId);
lines[lines.Count - 1] = $"当前主体共 {nvrs.Count} 台录像机";
ShowNvrResult(lines);
if (nvrs.Count == 0) return;
var ok = 0;
// 独立的海康会话:不与回放/预览/下载抢同一个 UserID(否则会卡在会话锁上)
using var ntpDevice = new HikDeviceService();
foreach (var nvr in nvrs)
{
var label = string.IsNullOrWhiteSpace(nvr.Name)
? $"{nvr.Host}:{nvr.Port}"
: $"{nvr.Name}({nvr.Host}:{nvr.Port})";
var lineIndex = lines.Count;
lines.Add($"… {label} 正在同步…");
ShowNvrResult(lines);
try
{
var credential = await _api.NvrCredentialAsync(_session.Token, _subjectId, nvr.Id);
// SDK 调用是同步阻塞的,放到线程池,避免界面卡住
var (config, before, after) = await Task.Run(() =>
{
// 设置前的设备时间(给界面看「改前 → 改后」)
var old = ntpDevice.GetDeviceTime(credential.Host, credential.Port,
credential.Username, credential.Password);
// ① 写 NTP(内部 GET→改→SET,保留固件字段)
ntpDevice.SetNtpConfig(credential.Host, credential.Port, credential.Username,
credential.Password, server, interval, true);
// ② 立即生效:把设备时间设为 NTP 时间,并补偿写调用耗时 / 轮询确认
var target = DateTime.Now.Add(offset);
var now = ntpDevice.SetDeviceTimeAndConfirm(credential.Host, credential.Port,
credential.Username, credential.Password, target);
// ③ 回读 NTP 配置
var cfg = ntpDevice.GetNtpConfig(credential.Host, credential.Port,
credential.Username, credential.Password);
return (cfg, old, now);
});
var diff = (after - DateTime.Now.Add(offset)).TotalSeconds;
ok++;
lines[lineIndex] = $"✔ {label}:NTP {config.Server} / {config.IntervalMinutes} 分钟 / "
+ $"{(config.Enabled ? "已启用" : "未启用")};设备时间 {before:HH:mm:ss} → {after:HH:mm:ss}"
+ $"(与 NTP 差 {diff:+0.0;-0.0} 秒)";
}
catch (Exception ex)
{
lines[lineIndex] = $"✘ {label}:{ex.Message}";
}
ShowNvrResult(lines);
}
lines.Add($"完成:{ok}/{nvrs.Count} 台设置成功");
ShowNvrResult(lines);
AppLog.Write($"[ntp] 同步 NVR 完成:{ok}/{nvrs.Count} 台({server},间隔 {interval} 分钟)");
}
catch (OperationCanceledException)
{
lines.Add("已取消:需要管理员权限才能修改本机时间,未写入录像机");
ShowNvrResult(lines);
AppLog.Write("[ntp] 同步 NVR:用户取消了管理员授权");
}
catch (Exception ex)
{
lines.Add($"失败:{ex.Message}");
ShowNvrResult(lines);
AppLog.Write($"[ntp] 同步 NVR 失败:{ex.Message}");
}
finally
{
_busy = false;
SyncButton.IsEnabled = true;
SyncNvrButton.IsEnabled = true;
}
}
private void ShowNvrResult(List<string> lines)
=> NvrResultBox.Text = string.Join(Environment.NewLine, lines);
private void Save_Click(object sender, RoutedEventArgs e)
{
var server = (ServerBox.Text ?? string.Empty).Trim();
if (EnabledBox.IsChecked == true && server.Length == 0)
{
MessageBox.Show(this, "启用 NTP 校时时必须填写服务器地址", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (!int.TryParse((IntervalBox.Text ?? string.Empty).Trim(), out var minutes) || minutes < 0)
{
MessageBox.Show(this, "自动校时间隔必须是不小于 0 的整数(分钟,0 = 仅启动时)", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (_serviceMode && minutes < 5)
{
MessageBox.Show(this, "服务模式下必须保留定时自动校时(间隔至少 5 分钟)", "NTP 校时",
MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
_settings.NtpServer = server.Length == 0 ? "ntp.aliyun.com" : server;
_settings.NtpEnabled = _serviceMode || EnabledBox.IsChecked == true;
_settings.NtpSyncOnStartup = _serviceMode || StartupBox.IsChecked == true;
_settings.NtpSyncIntervalMinutes = minutes;
_settings.Save();
PushNtpSettingsToAgent();
AppLog.Write($"[ntp] 设置已保存:{(_settings.NtpEnabled ? "启用" : "关闭")},服务器 {_settings.NtpServer},"
+ $"启动时{(_settings.NtpSyncOnStartup ? "校时" : "不校时")},间隔 {_settings.NtpSyncIntervalMinutes} 分钟");
DialogResult = true;
}
private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false;
}

View File

@ -0,0 +1,172 @@
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,
};
}
}

View File

@ -0,0 +1,179 @@
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 「按需提权」的 NTP 校时。
///
/// 软件本身以**普通权限**启动(<c>app.manifest</c> 用 asInvoker):
/// 双击、开始菜单、网页 <c>yuncang://</c> 唤起都不会弹 UAC。
/// 只有真正要改系统时间时(NTP 窗口的「立即校时 / 同步 NVR 时间」)才用 <c>runas</c>
/// 把**同一个 exe** 再起一个带 <see cref="HelperArg"/> 参数的进程:
/// 那个进程只做「查询 NTP + 写系统时间 + 把结果写进临时文件」然后立刻退出,
/// 主进程读回结果继续刷新界面。
///
/// ⚠️ helper 进程的入口必须在 App.OnStartup **最先**判断 —— 要早于单实例互斥体,
/// 否则第二个实例会把参数转发给正在运行的主实例然后直接退出,校时就不会发生。
/// </summary>
public static class ElevatedNtp
{
/// <summary>helper 进程的命令行标记</summary>
public const string HelperArg = "--ntp-sync-elevated";
/// <summary>用户点了 UAC 的「否」(ERROR_CANCELLED)</summary>
private const int ErrorCancelled = 1223;
/// <summary>helper 写回、主进程读回的结果</summary>
public sealed class HelperResult
{
public bool Ok { get; set; }
public string? Error { get; set; }
public string Server { get; set; } = "";
public DateTimeOffset ServerTime { get; set; }
public double OffsetSeconds { get; set; }
public double RoundTripMs { get; set; }
}
/// <summary>这次启动是不是「提权校时 helper」</summary>
public static bool IsHelperCall(string[] args) => Array.IndexOf(args, HelperArg) >= 0;
/// <summary>
/// 以管理员身份校时一次(**会弹 UAC**)。
/// </summary>
/// <exception cref="OperationCanceledException">用户取消了 UAC 授权</exception>
/// <exception cref="InvalidOperationException">提权进程启动失败 / 校时失败</exception>
public static async Task<NtpResult> SyncAsync(string server, CancellationToken ct = default)
{
var exe = Environment.ProcessPath
?? throw new InvalidOperationException("找不到当前程序路径,无法请求管理员权限");
var resultFile = Path.Combine(Path.GetTempPath(), $"yuncang_ntp_{Guid.NewGuid():N}.json");
var psi = new ProcessStartInfo(exe, $"{HelperArg} \"{server}\" \"{resultFile}\"")
{
UseShellExecute = true, // runas 只能走 ShellExecute
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden,
};
try
{
// runas 下 Process.Start 会**等用户点完 UAC** 才返回 → 放到线程池,别冻住界面
using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false)
?? throw new InvalidOperationException("提权进程启动失败");
await process.WaitForExitAsync(ct).ConfigureAwait(false);
var payload = ReadResult(resultFile);
if (payload is null)
{
throw new InvalidOperationException($"提权校时没有返回结果(退出码 {process.ExitCode})");
}
if (!payload.Ok)
{
throw new InvalidOperationException(payload.Error ?? "提权校时失败");
}
return new NtpResult(
payload.Server,
payload.ServerTime,
TimeSpan.FromSeconds(payload.OffsetSeconds),
TimeSpan.FromMilliseconds(payload.RoundTripMs));
}
catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
{
throw new OperationCanceledException("已取消管理员授权,系统时间没有修改");
}
finally
{
TryDelete(resultFile);
}
}
/// <summary>
/// helper 进程入口:<c>--ntp-sync-elevated "&lt;服务器&gt;" "&lt;结果文件&gt;"</c>
///
/// 必须同步做完(调用方紧接着 Shutdown),所以走线程池 + GetResult;
/// 不能在这个类里 <c>await</c> —— WPF 的 OnStartup 是同步的,且进程不能提前退出。
/// </summary>
public static void RunHelper(string[] args)
{
var index = Array.IndexOf(args, HelperArg);
var server = index >= 0 && args.Length > index + 1 ? args[index + 1] : "";
var resultFile = index >= 0 && args.Length > index + 2 ? args[index + 2] : "";
var payload = new HelperResult { Server = server };
try
{
if (!ClockSyncService.IsElevated)
{
throw new InvalidOperationException("提权失败:当前进程仍不是管理员权限");
}
// Task.Run:避免捕获 WPF 的 SynchronizationContext 造成死锁
var result = Task.Run(() => ClockSyncService.SyncAsync(server)).GetAwaiter().GetResult();
payload.Ok = true;
payload.ServerTime = result.ServerTime;
payload.OffsetSeconds = result.Offset.TotalSeconds;
payload.RoundTripMs = result.RoundTrip.TotalMilliseconds;
AppLog.Write(result.Offset.Duration() < ClockSyncService.MinimumAdjust
? $"[ntp] 提权校时:{server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒(在误差范围内,未调整)"
: $"[ntp] 提权校时完成:{server} 偏差 {result.Offset.TotalSeconds:+0.00;-0.00} 秒,"
+ $"往返 {result.RoundTrip.TotalMilliseconds:0} ms");
}
catch (Exception ex)
{
payload.Ok = false;
payload.Error = ex.Message;
AppLog.Write($"[ntp] 提权校时失败({server}):{ex.Message}");
}
if (resultFile.Length == 0) return;
try
{
File.WriteAllText(resultFile, JsonSerializer.Serialize(payload));
}
catch (Exception ex)
{
AppLog.Write($"[ntp] 提权校时写结果失败({resultFile}):{ex.Message}");
}
}
private static HelperResult? ReadResult(string path)
{
try
{
if (!File.Exists(path)) return null;
var text = File.ReadAllText(path);
return string.IsNullOrWhiteSpace(text)
? null
: JsonSerializer.Deserialize<HelperResult>(text);
}
catch
{
return null;
}
}
private static void TryDelete(string path)
{
try
{
if (File.Exists(path)) File.Delete(path);
}
catch
{
// 临时结果文件删不掉不影响业务
}
}
}

View File

@ -0,0 +1,86 @@
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services;
/// <summary>一次 SNTP 查询的结果</summary>
/// <param name="Server">使用的 NTP 服务器(用户填的地址)</param>
/// <param name="ServerTime">服务器给出的当前时间(本地时区表示)</param>
/// <param name="Offset">服务器时间 - 本机时间(正数表示本机慢了)</param>
/// <param name="RoundTrip">一次 UDP 往返耗时</param>
public sealed record NtpResult(string Server, DateTimeOffset ServerTime, TimeSpan Offset, TimeSpan RoundTrip);
/// <summary>
/// 极简 SNTP 客户端(UDP 123,RFC 2030 / 4330),不依赖 Windows 时间服务。
///
/// 为什么自己实现:现场很多电脑的 Windows Time 服务根本没启动(`w32tm` 报 0x80070426),
/// 时间慢慢漂到差十秒;而回放是按录像机时间定位的,差几秒就会把面单截掉。
/// 这里直接向 NTP 服务器取时间,由本软件写回系统时钟;写时钟需要管理员权限,
/// 非管理员时由 <see cref="ElevatedNtp"/> 拉起提权 helper 完成。
/// </summary>
public static class NtpClient
{
/// <summary>NTP 的 1900-01-01 到 1970-01-01 之间的秒数</summary>
private const uint NtpEpochOffset = 2208988800u;
/// <summary>默认端口</summary>
public const int NtpPort = 123;
/// <summary>
/// 查询 NTP 服务器时间。
/// </summary>
/// <param name="server">域名或 IP(如 ntp.aliyun.com / 112.124.21.102)</param>
/// <param name="timeoutMs">超时(毫秒)</param>
public static async Task<NtpResult> QueryAsync(string server, int timeoutMs = 3000, CancellationToken ct = default)
{
var host = (server ?? string.Empty).Trim();
if (host.Length == 0) throw new ArgumentException("请填写 NTP 服务器地址");
var addresses = await Dns.GetHostAddressesAsync(host, ct).ConfigureAwait(false);
var address = addresses.FirstOrDefault(item => item.AddressFamily == AddressFamily.InterNetwork)
?? addresses.FirstOrDefault()
?? throw new InvalidOperationException($"解析不到 NTP 服务器:{host}");
using var udp = new UdpClient(address.AddressFamily);
udp.Connect(address, NtpPort);
// LI = 0(无闰秒警告),VN = 3,Mode = 3(客户端)
var request = new byte[48];
request[0] = 0x1B;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(timeoutMs);
try
{
var t1 = DateTime.UtcNow;
await udp.SendAsync(request.AsMemory(), timeout.Token).ConfigureAwait(false);
var response = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false);
var t4 = DateTime.UtcNow;
var data = response.Buffer;
if (data.Length < 48) throw new InvalidOperationException("NTP 响应格式不正确(长度不足 48 字节)");
// 服务器发包时间(Transmit Timestamp,bytes 40~47)
var seconds = ((uint)data[40] << 24 | (uint)data[41] << 16 | (uint)data[42] << 8 | data[43]) - NtpEpochOffset;
var fraction = ((uint)data[44] << 24 | (uint)data[45] << 16 | (uint)data[46] << 8 | data[47]) / 4294967296.0;
var serverUtc = DateTime.UnixEpoch.AddSeconds(seconds + fraction);
// 用「本机发送/接收的中点」估算单程延迟,得到偏差
var midpoint = t1.AddTicks((t4 - t1).Ticks / 2);
var offset = serverUtc - midpoint;
var result = new NtpResult(host, new DateTimeOffset(serverUtc, TimeSpan.Zero).ToLocalTime(),
offset, t4 - t1);
return result;
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException($"连接 NTP 服务器超时({host}:{NtpPort},{timeoutMs} ms)");
}
}
}