packServer/desktop/Services/Agent/ServiceInstaller.cs
liufumingren 11ebb33966 feat(extension): 插件配置集中管理 + 桌面端策略安装 + 跨网下载修复
- 后端:sys_config 存插件配置(识别前缀/生效站点/模板),平台管理员 GET/PUT /api/web/admin/extension;
  插件读取 GET /api/web/extension/config(Redis 缓存 1 小时,保存即失效)
- 前端:平台管理 → 插件配置页(只维护前缀,单号正则由服务端生成)
- 插件:改为只拉取执行(每 5 分钟 + 手动同步),移除规则编辑/试跑/导入导出;安装包地址自动取最新发布
- 桌面端:工具 → 安装/卸载谷歌插件(生成 .reg + reg import 写 HKLM 策略,读注册表验证);
  跨网下载改走云端中转;局域网探测补排障日志;自动更新按包类型取 md5Exe/sizeExe
- 发布:npm run extension:publish(crx + updates.xml)、extension:zip(商店上传包),
  nginx 对 /download/extension/updates.xml 关缓存

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-01 03:16:26 +08:00

664 lines
25 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.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace YuncangTrace.LocalService.Services;
/// <summary>Windows 服务当前状态(SCM 的 dwCurrentState)</summary>
public enum AgentServiceState
{
Unknown = 0,
NotInstalled,
Stopped,
StartPending,
StopPending,
Running,
}
/// <summary>
/// 「扫码后台服务」的安装/卸载/启停(服务名 <c>YuncangTraceAgent</c>)。
///
/// 设计要点:
/// - **服务跑自己的 exe 副本**(<c>%ProgramData%\YuncangTrace\agent\YuncangTraceAgent.exe</c>),
/// MSI 升级替换安装目录的 exe 时不会撞「文件被占用」;
/// - 安装/卸载/启停都需要管理员权限 → 用 <c>runas</c> 起一个临时进程执行(**只在这些操作时弹 UAC**);
/// - 服务以 <c>LocalSystem</c> 自动启动,用户注销/退出桌面端不影响扫码上报。
/// </summary>
public static class ServiceInstaller
{
public const string ServiceName = "YuncangTraceAgent";
public const string DisplayName = "云仓视频溯源-扫码服务";
/// <summary>提权 helper 的命令行标记</summary>
private const string ControlArg = "--agent-control";
private const int ErrorCancelled = 1223;
private sealed class HelperResult
{
public bool Ok { get; set; }
public string Message { get; set; } = "";
}
/// <summary>这次启动是不是「服务管理 helper」</summary>
public static bool IsHelperCall(string[] args)
=> args.Length > 0 && args[0].Equals(ControlArg, StringComparison.OrdinalIgnoreCase);
/// <summary>服务是否已注册(读注册表,普通权限即可)</summary>
public static bool IsInstalled
{
get
{
try
{
using var key = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{ServiceName}");
return key is not null;
}
catch
{
return false;
}
}
}
/// <summary>服务是否正在运行</summary>
public static bool IsRunning => QueryState() == AgentServiceState.Running;
/// <summary>服务副本是否和当前程序版本不一致(升级后需要更新)</summary>
public static bool NeedsBinaryUpdate
{
get
{
try
{
var source = Environment.ProcessPath;
if (string.IsNullOrEmpty(source) || !File.Exists(source)) return false;
if (!File.Exists(AgentPaths.AgentExe)) return true;
var running = FileVersionInfo.GetVersionInfo(AgentPaths.AgentExe).FileVersion ?? "";
var current = FileVersionInfo.GetVersionInfo(source).FileVersion ?? "";
if (!string.Equals(running, current, StringComparison.OrdinalIgnoreCase)) return true;
return new FileInfo(source).Length != new FileInfo(AgentPaths.AgentExe).Length;
}
catch
{
return true;
}
}
}
// ==================== 桌面端调用(会弹 UAC) ====================
public static Task<(bool Ok, string Message)> InstallOrUpdateAsync(CancellationToken ct = default)
=> RunElevatedAsync("install", ct);
public static Task<(bool Ok, string Message)> UninstallAsync(CancellationToken ct = default)
=> RunElevatedAsync("uninstall", ct);
public static Task<(bool Ok, string Message)> StartAsync(CancellationToken ct = default)
=> RunElevatedAsync("start", ct);
public static Task<(bool Ok, string Message)> StopAsync(CancellationToken ct = default)
=> RunElevatedAsync("stop", ct);
private static async Task<(bool Ok, string Message)> RunElevatedAsync(string action, CancellationToken ct)
{
var exe = Environment.ProcessPath;
if (string.IsNullOrEmpty(exe)) return (false, "找不到当前程序路径,无法请求管理员权限");
var resultFile = Path.Combine(Path.GetTempPath(), $"yuncang_agent_{Guid.NewGuid():N}.json");
try
{
var psi = new ProcessStartInfo(exe, $"{ControlArg} {action} \"{resultFile}\"")
{
UseShellExecute = true, // runas 只能走 ShellExecute
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden,
};
using var process = await Task.Run(() => Process.Start(psi), ct).ConfigureAwait(false);
if (process is null) return (false, "提权进程启动失败");
await process.WaitForExitAsync(ct).ConfigureAwait(false);
var result = ReadResult(resultFile);
return result is null
? (false, $"操作没有返回结果(退出码 {process.ExitCode})")
: (result.Ok, result.Message);
}
catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
{
return (false, "已取消管理员授权(安装/管理后台服务需要管理员权限)");
}
catch (Exception ex)
{
return (false, ex.Message);
}
finally
{
TryDelete(resultFile);
}
}
// ==================== 提权 helper 入口 ====================
/// <summary>
/// 提权后的实际执行体:<c>--agent-control install|uninstall|start|stop "&lt;结果文件&gt;"</c>
/// </summary>
public static void RunHelper(string[] args)
{
var action = args.Length > 1 ? args[1].ToLowerInvariant() : "";
var resultFile = args.Length > 2 ? args[2] : "";
HelperResult result;
try
{
result = action switch
{
"install" => InstallCore(),
"uninstall" => UninstallCore(),
"start" => StartCore(),
"stop" => StopCore(),
_ => new HelperResult { Ok = false, Message = $"未知操作:{action}" },
};
}
catch (Exception ex)
{
result = new HelperResult { Ok = false, Message = ex.Message };
}
if (resultFile.Length > 0)
{
try
{
File.WriteAllText(resultFile, JsonSerializer.Serialize(result));
}
catch (Exception ex)
{
AppLog.Write($"[agent] 写服务管理结果失败:{ex.Message}");
}
}
AppLog.Write($"[agent] 服务管理({action}):{(result.Ok ? "成功" : "失败")} {result.Message}");
}
private static HelperResult InstallCore()
{
if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限");
var source = Environment.ProcessPath;
if (string.IsNullOrEmpty(source) || !File.Exists(source)) return Fail("找不到当前程序 exe");
Directory.CreateDirectory(AgentPaths.MachineRoot);
Directory.CreateDirectory(AgentPaths.AgentDir);
// 桌面端(普通用户)要能写 agent.json / channels.json / 命令文件,并读状态
RunTool("icacls.exe", AgentPaths.MachineRoot, "/grant", "*S-1-5-32-545:(OI)(CI)M", "/T", "/C", "/Q");
// 先停旧服务,才能替换副本 exe
StopCore();
WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15));
// 服务进程退出后文件句柄还要几十毫秒才释放 → 重试几次
Exception? copyError = null;
for (var attempt = 0; attempt < 20; attempt++)
{
try
{
CopyAgentFiles(source);
copyError = null;
break;
}
catch (Exception ex)
{
copyError = ex;
Thread.Sleep(500);
}
}
if (copyError is not null) return Fail($"复制后台服务程序失败:{copyError.Message}");
// 局域网发现端口:不放开的话同 LAN 的桌面端根本探测不到本机,
// 「共用一套 NVR 会话池」就永远走不到内网这条路。
EnsureFirewallRules();
var binPath = $"\"{AgentPaths.AgentExe}\" --service";
if (!IsInstalled)
{
var create = RunSc("create", ServiceName,
"binPath=", binPath,
"start=", "auto",
"DisplayName=", DisplayName);
// 1072 = 服务标记为删除(上一次卸载还没完全生效)→ 等一会重试
for (var i = 0; i < 20 && create.Code == 1072; i++)
{
Thread.Sleep(500);
create = RunSc("create", ServiceName,
"binPath=", binPath,
"start=", "auto",
"DisplayName=", DisplayName);
}
if (create.Code != 0) return Fail($"创建服务失败({create.Code}):{create.Output}");
}
else
{
var config = RunSc("config", ServiceName, "binPath=", binPath, "start=", "auto");
if (config.Code != 0) return Fail($"更新服务配置失败({config.Code}):{config.Output}");
}
RunSc("description", ServiceName, "云仓视频溯源扫码服务(后台收码/上报,退出桌面端后仍运行)");
// 崩溃自动重启:5s → 10s → 30s
RunSc("failure", ServiceName, "reset=", "86400",
"actions=", "restart/5000/restart/10000/restart/30000");
// ⚠️ 开发版(框架依赖)必须告诉服务 .NET 装在哪:
// 服务以 LocalSystem 跑,看不到当前用户 PATH / DOTNET_ROOT,
// apphost 会直接报「You must install .NET」→ 服务永远进不了 Running → 桌面提示“后台服务启动超时”。
EnsureServiceDotnetEnvironment();
var start = StartCore();
if (!start.Ok) return start;
return new HelperResult
{
Ok = true,
Message = $"后台服务已安装并启动:{AgentPaths.AgentExe}",
};
}
/// <summary>
/// 开发版(框架依赖)装服务时,把 .NET 运行时目录写进服务的环境变量。
///
/// 服务以 <c>LocalSystem</c> 身份运行:看不到当前用户目录里的 .NET(本机 8.0 装在
/// <c>%LOCALAPPDATA%\Microsoft\dotnet</c>),apphost 直接报 “You must install .NET” 并退出 →
/// SCM 状态一直进不了 Running → 桌面端只会看到「后台服务启动超时」。
///
/// 自包含单文件发布不需要(运行时就在 exe 里)。
/// </summary>
private static void EnsureServiceDotnetEnvironment()
{
try
{
var sourceDir = Path.GetDirectoryName(Environment.ProcessPath ?? string.Empty) ?? string.Empty;
var frameworkDependent = File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll"));
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
$@"SYSTEM\CurrentControlSet\Services\{ServiceName}", writable: true);
if (key is null) return;
if (!frameworkDependent)
{
// 换回自包含版时把上次写的值清掉,避免指到一个不存在的目录
if (key.GetValue("Environment") is not null) key.DeleteValue("Environment", throwOnMissingValue: false);
return;
}
// ⚠️ 不要用 typeof(object).Assembly.Location:单文件发布里它恒为空(IL3000),
// RuntimeEnvironment.GetRuntimeDirectory() 在框架依赖时才是真实的 <root>\shared\Microsoft.NETCore.App\8.0.x\
var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
if (string.IsNullOrWhiteSpace(runtimeDir)) return;
var dotnetRoot = Path.GetFullPath(Path.Combine(runtimeDir, "..", ".."));
if (!File.Exists(Path.Combine(dotnetRoot, "dotnet.exe"))) return;
key.SetValue("Environment",
new[] { $"DOTNET_ROOT={dotnetRoot}", $"PATH={dotnetRoot};%PATH%" },
Microsoft.Win32.RegistryValueKind.MultiString);
AppLog.Write($"[agent] 开发版服务已写入 DOTNET_ROOT={dotnetRoot}");
}
catch (Exception ex)
{
AppLog.Write($"[agent] 写服务 DOTNET_ROOT 失败:{ex.Message}");
}
}
private static HelperResult UninstallCore()
{
if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限");
StopCore();
WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15));
if (IsInstalled)
{
var delete = RunSc("delete", ServiceName);
if (delete.Code != 0 && delete.Code != 1060)
{
return Fail($"删除服务失败({delete.Code}):{delete.Output}");
}
// sc delete 是异步的:等注册表项真的消失,避免下次安装报 1072(标记为删除)
for (var i = 0; i < 40 && IsInstalled; i++) Thread.Sleep(250);
}
// 只删「服务程序 + 服务专用文件」,通道/扫码记录保留给桌面端回写
foreach (var file in new[]
{
AgentPaths.ConfigFile, AgentPaths.TokenFile, AgentPaths.StatusFile,
AgentPaths.CommandFile, AgentPaths.DiscoveredFile,
})
{
TryDelete(file);
}
TryDeleteDirectory(AgentPaths.AgentDir);
RemoveFirewallRules();
return new HelperResult { Ok = true, Message = "后台服务已卸载" };
}
/// <summary>
/// 放行局域网发现端口(TCP 取流健康端点 + UDP 询问应答)。
///
/// ⚠️ 必须是 <c>profile=any</c>:仓库/公司的网卡经常被 Windows 判成「**公用网络**」
/// (插网线、连 WiFi、没加域都是 Public),而 `domain,private` 的规则在公用网络下
/// **完全不生效** —— 2026-10-31 现场复现:同一局域网,别的查询机永远探测不到这台,
/// 只有本机自测能通(loopback 不受防火墙过滤)。
/// 端口本身有身份校验(主体令牌,且只回同主体/同后端的询问),不靠防火墙档位兜底。
/// </summary>
private static void EnsureFirewallRules()
{
AddFirewallRule("YuncangTrace Edge (TCP 17311)", "TCP", "17311");
AddFirewallRule("YuncangTrace Edge (UDP 17310)", "UDP", "17310");
}
private static void AddFirewallRule(string name, string protocol, string port)
{
// 已存在就静默覆盖(delete + add 比判断是否存在简单可靠)
RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}");
var result = RunTool("netsh.exe", "advfirewall", "firewall", "add", "rule",
$"name={name}", "dir=in", "action=allow", $"protocol={protocol}", $"localport={port}",
"profile=any");
if (result.Code != 0)
{
AppLog.Write($"[agent] 添加防火墙规则失败({name}):{result.Output}");
}
else
{
AppLog.Write($"[agent] 防火墙规则已更新:{name}({protocol} {port},profile=any)");
}
}
private static void RemoveFirewallRules()
{
foreach (var name in new[] { "YuncangTrace Edge (TCP 17311)", "YuncangTrace Edge (UDP 17310)" })
{
RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}");
}
}
private static HelperResult StartCore()
{
if (!IsInstalled) return Fail("服务未安装");
// ⚠️ 每次启动前都补齐 .NET 环境变量:服务副本可能是开发版(框架依赖),
// 而 `.NET Runtime` 事件里只会看到 “You must install .NET”,界面上则表现为「启动超时」。
EnsureServiceDotnetEnvironment();
var (code, output) = RunSc("start", ServiceName);
// 1056 = 已在运行;1053 = 已受理但还没进入 Running(下面轮询确认)
if (code is not (0 or 1056 or 1053)) return Fail($"启动服务失败({code}):{output}");
return WaitForState(state => state == AgentServiceState.Running, TimeSpan.FromSeconds(20))
? new HelperResult { Ok = true, Message = "后台服务已启动" }
: Fail("后台服务启动超时(查看 事件查看器/服务日志)");
}
private static HelperResult StopCore()
{
if (!IsInstalled) return new HelperResult { Ok = true, Message = "服务未安装,无需停止" };
var (code, output) = RunSc("stop", ServiceName);
// 1062 = 服务未启动;1073 = 已停止
if (code is not (0 or 1062 or 1073)) return Fail($"停止服务失败({code}):{output}");
return WaitForState(state => state is AgentServiceState.Stopped or AgentServiceState.NotInstalled,
TimeSpan.FromSeconds(15))
? new HelperResult { Ok = true, Message = "后台服务已停止" }
: Fail("后台服务停止超时");
}
private static HelperResult Fail(string message) => new() { Ok = false, Message = message };
/// <summary>
/// 把当前程序复制到 ProgramData 作为服务副本。
///
/// 单文件发布只复制 exe;开发环境(framework-dependent)连 dll/json 一起复制。
/// **native 运行库(HCNetSDK / ffmpeg)两种模式都要复制** ——
/// 取流由 <c>--hik-worker</c> 子进程执行,缺它就直接不可用。
/// </summary>
private static void CopyAgentFiles(string source)
{
var sourceDir = Path.GetDirectoryName(source)
?? throw new InvalidOperationException("取不到程序目录");
var singleFile = !File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll"));
foreach (var file in Directory.EnumerateFiles(AgentPaths.AgentDir))
{
try
{
File.Delete(file);
}
catch
{
// 旧文件删不掉就覆盖写
}
}
if (singleFile)
{
File.Copy(source, AgentPaths.AgentExe, overwrite: true);
}
else
{
foreach (var file in Directory.EnumerateFiles(sourceDir))
{
var extension = Path.GetExtension(file).ToLowerInvariant();
if (extension is not (".exe" or ".dll" or ".json")) continue;
if (Path.GetFileName(file).Contains("ffmpeg", StringComparison.OrdinalIgnoreCase)) continue;
File.Copy(file, Path.Combine(AgentPaths.AgentDir, Path.GetFileName(file)), overwrite: true);
}
if (!File.Exists(AgentPaths.AgentExe)) File.Copy(source, AgentPaths.AgentExe, overwrite: true);
}
CopyNativeDirectory(sourceDir);
}
/// <summary>
/// 复制 <c>native</c>(HCNetSDK + ffmpeg)到服务副本目录。
///
/// ⚠️ 每次**先删后拷**:SDK 的组件文件集合会随版本变化,
/// 残留旧 DLL 会让 HCCore 加载错版本(现象是登录莫名失败)。
/// </summary>
private static void CopyNativeDirectory(string sourceDir)
{
var from = Path.Combine(sourceDir, "native");
if (!Directory.Exists(from))
{
AppLog.Write("[agent] 程序目录没有 native(缺 HCNetSDK/ffmpeg):服务取流不可用,扫码不受影响");
return;
}
var to = Path.Combine(AgentPaths.AgentDir, "native");
try
{
if (Directory.Exists(to)) Directory.Delete(to, recursive: true);
}
catch (Exception ex)
{
AppLog.Write($"[agent] 清空旧 native 失败(继续覆盖写):{ex.Message}");
}
var count = 0;
foreach (var file in Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(to, Path.GetRelativePath(from, file));
var dir = Path.GetDirectoryName(target);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.Copy(file, target, overwrite: true);
count++;
}
AppLog.Write($"[agent] 已复制 native 运行库 {count} 个文件到 {to}");
}
// ==================== 状态查询(SCM,无需管理员) ====================
public static AgentServiceState QueryState()
{
IntPtr manager = IntPtr.Zero;
IntPtr service = IntPtr.Zero;
try
{
manager = OpenSCManager(null, null, ScManagerConnect);
if (manager == IntPtr.Zero) return AgentServiceState.Unknown;
service = OpenService(manager, ServiceName, ServiceQueryStatus);
if (service == IntPtr.Zero) return AgentServiceState.NotInstalled;
if (!QueryServiceStatus(service, out var status)) return AgentServiceState.Unknown;
return status.dwCurrentState switch
{
1 => AgentServiceState.Stopped,
2 => AgentServiceState.StartPending,
3 => AgentServiceState.StopPending,
4 => AgentServiceState.Running,
_ => AgentServiceState.Unknown,
};
}
catch
{
return AgentServiceState.Unknown;
}
finally
{
if (service != IntPtr.Zero) CloseServiceHandle(service);
if (manager != IntPtr.Zero) CloseServiceHandle(manager);
}
}
private static bool WaitForState(Func<AgentServiceState, bool> predicate, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (predicate(QueryState())) return true;
Thread.Sleep(250);
}
return predicate(QueryState());
}
// ==================== 工具 ====================
private static (int Code, string Output) RunSc(params string[] args) => RunTool("sc.exe", args);
private static (int Code, string Output) RunTool(string file, params string[] args)
{
try
{
var psi = new ProcessStartInfo(file)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
foreach (var arg in args) psi.ArgumentList.Add(arg);
using var process = Process.Start(psi);
if (process is null) return (-1, $"{file} 启动失败");
var output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd();
process.WaitForExit();
return (process.ExitCode, output.Trim());
}
catch (Exception ex)
{
return (-1, 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
{
// 忽略
}
}
private static void TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path)) Directory.Delete(path, recursive: true);
}
catch
{
// 文件还被占用时下次安装会覆盖,不必强求
}
}
// ==================== Win32 ====================
private const uint ScManagerConnect = 0x0001;
private const uint ServiceQueryStatus = 0x0004;
[StructLayout(LayoutKind.Sequential)]
private struct ServiceStatus
{
public uint dwServiceType;
public uint dwCurrentState;
public uint dwControlsAccepted;
public uint dwWin32ExitCode;
public uint dwServiceSpecificExitCode;
public uint dwCheckPoint;
public uint dwWaitHint;
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenSCManager(string? machineName, string? databaseName, uint desiredAccess);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr OpenService(IntPtr manager, string serviceName, uint desiredAccess);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool QueryServiceStatus(IntPtr service, out ServiceStatus status);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CloseServiceHandle(IntPtr handle);
}