using System.Diagnostics; using System.Security.Cryptography; using System.Text.Json; namespace UCVL.VPNPlus; internal sealed class LocalNetworkException(string message, Exception? inner = null) : IOException(message, inner); // A file handle, not a thread-affine mutex: asynchronous start/stop can resume // on different threads. Windows releases this lease even after a process crash. internal sealed class NetworkOwnerLease : IDisposable { private readonly FileStream _handle; private NetworkOwnerLease(FileStream handle) => _handle = handle; internal static NetworkOwnerLease Acquire(string? testPath = null) { var path = testPath ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "UCVL", "VPNPlus", "network-owner.lock"); Directory.CreateDirectory(Path.GetDirectoryName(path)!); try { return new NetworkOwnerLease(new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); } catch (IOException error) { throw new LocalNetworkException("另一份纵横家正在使用本机网络。请先在该程序中选择“断开并退出”再连接;当前连接未被修改。", error); } } public void Dispose() => _handle.Dispose(); internal static async Task RecoverOrphanAsync(string expectedXray, CancellationToken token) { if (!File.Exists(AppPaths.PidFile) || !int.TryParse(File.ReadAllText(AppPaths.PidFile), out var pid)) return; Process stale; try { stale = Process.GetProcessById(pid); } catch (ArgumentException) { return; } using (stale) { if (!string.Equals(stale.ProcessName, "xray", StringComparison.OrdinalIgnoreCase)) return; var path = stale.MainModule?.FileName; if (path is null || !File.Exists(expectedXray) || !File.Exists(path)) throw new LocalNetworkException("无法确认旧网络内核的归属,未修改现有网络。请先退出旧版纵横家。"); // An upgrade/lab copy can live in a different directory. A PID or // process name alone is not enough to identify one of our cores. if (!string.Equals(path, expectedXray, StringComparison.OrdinalIgnoreCase) && !SHA256.HashData(File.ReadAllBytes(path)).SequenceEqual(SHA256.HashData(File.ReadAllBytes(expectedXray)))) throw new LocalNetworkException("检测到不同版本的网络内核仍在运行,请先退出旧版纵横家。"); var script = $"$p=Get-CimInstance Win32_Process -Filter 'ProcessId={pid}'; if ($p) {{ $p | Select-Object CommandLine,ParentProcessId,CreationDate | ConvertTo-Json -Compress }}"; using var query = Process.Start(SystemPowerShell.CreateStartInfo(script)) ?? throw new IOException("无法检查旧内核进程。"); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(10)); try { var output = query.StandardOutput.ReadToEndAsync(timeout.Token); var error = query.StandardError.ReadToEndAsync(timeout.Token); await query.WaitForExitAsync(timeout.Token).ConfigureAwait(false); await error; var json = await output; if (query.ExitCode != 0) throw new LocalNetworkException("旧网络内核检查失败,未修改现有连接。"); if (string.IsNullOrWhiteSpace(json)) return; using var doc = JsonDocument.Parse(json); var cmd = doc.RootElement.GetProperty("CommandLine").GetString() ?? ""; if (!cmd.Contains("-c \"" + AppPaths.ConfigFile + "\"", StringComparison.OrdinalIgnoreCase)) throw new LocalNetworkException("旧进程不属于此用户的纵横家配置,未停止该进程。"); var parentId = doc.RootElement.GetProperty("ParentProcessId").GetInt32(); try { using var parent = Process.GetProcessById(parentId); if (parent.StartTime <= stale.StartTime && !parent.HasExited) throw new LocalNetworkException("旧版纵横家或测试恢复程序仍在运行。请先退出旧程序;新程序不会争用它的虚拟网卡。"); } catch (ArgumentException) { } if (!stale.HasExited) { stale.Kill(); await stale.WaitForExitAsync(timeout.Token).ConfigureAwait(false); AppPaths.WriteLog("已停止经过归属校验的孤立内核,随后恢复原网络。"); } } finally { try { if (!query.HasExited) query.Kill(); } catch { } } } } }