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

180 lines
6.8 KiB
C#
Raw Permalink 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.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
{
// 临时结果文件删不掉不影响业务
}
}
}