using System.Diagnostics; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Security.Principal; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace UCVL.VPNPlus; internal static class TunRouting { internal const string AdapterName = "UCVL VPNPlus"; private static readonly string OwnedAdapterInstanceId = BuildOwnedAdapterInstanceId(); internal sealed record PhysicalNetwork( string InterfaceName, int InterfaceIndex, IPAddress Ipv4Address, int Ipv4PrefixLength, IPAddress Ipv4Gateway, IReadOnlyList Ipv4DnsServers); private sealed class TunState { public int InterfaceIndex { get; init; } public int PhysicalInterfaceIndex { get; init; } public List BypassIpv4Addresses { get; init; } = []; public bool Ipv4RoutesAdded { get; init; } public bool Ipv6RoutesAdded { get; init; } } internal static bool IsElevated() { using var identity = WindowsIdentity.GetCurrent(); return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator); } internal static PhysicalNetwork GetPhysicalNetwork(IReadOnlyCollection routeProbeAddresses) { var uplink = PhysicalUplink.Read(); if (uplink.Success && uplink.Network is not null) return uplink.Network; // Preserve the legacy fallback for special exit-node/PPP routing. var candidates = NetworkInterface.GetAllNetworkInterfaces() .Where(item => item.OperationalStatus == OperationalStatus.Up) .Where(item => item.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(item => !item.Name.StartsWith(AdapterName, StringComparison.OrdinalIgnoreCase)) .Select(item => new { Interface = item, Properties = item.GetIPProperties(), }) .Select(item => new { item.Interface, item.Properties, Ipv4 = item.Properties.GetIPv4Properties(), Unicast = item.Properties.UnicastAddresses .Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork) .Where(address => !IPAddress.IsLoopback(address.Address)) .ToList(), Gateway = item.Properties.GatewayAddresses .Select(gateway => gateway.Address) .FirstOrDefault(address => address.AddressFamily == AddressFamily.InterNetwork && !address.Equals(IPAddress.Any)), }) .Where(item => item.Ipv4 is not null && item.Unicast.Count > 0) .ToList(); IPAddress? routedLocalAddress = null; foreach (var probeAddress in routeProbeAddresses.Where(address => address.AddressFamily == AddressFamily.InterNetwork)) { try { using var probe = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); probe.Connect(new IPEndPoint(probeAddress, 443)); routedLocalAddress = (probe.LocalEndPoint as IPEndPoint)?.Address; if (routedLocalAddress is not null) break; } catch (SocketException) { // Continue with another node address. UDP Connect only asks // Windows which local route it would use; no payload is sent. } } var selected = routedLocalAddress is null ? null : candidates.FirstOrDefault(candidate => candidate.Unicast.Any(address => address.Address.Equals(routedLocalAddress))); selected ??= candidates.FirstOrDefault(candidate => candidate.Gateway is not null) ?? throw new InvalidOperationException("未找到可用的上网接口。请先连接有线网络、Wi-Fi、手机热点或 Tailscale Exit Node。"); var selectedAddress = selected.Unicast.FirstOrDefault(address => address.Address.Equals(routedLocalAddress)) ?? selected.Unicast[0]; var dnsServers = selected.Properties.DnsAddresses .Where(address => address.AddressFamily == AddressFamily.InterNetwork) .Where(address => !IPAddress.IsLoopback(address) && !address.Equals(IPAddress.Any)) .Distinct() .ToList(); return new PhysicalNetwork( selected.Interface.Name, selected.Ipv4!.Index, selectedAddress.Address, selectedAddress.PrefixLength, selected.Gateway ?? IPAddress.Any, dnsServers); } internal static async Task EnableAsync( PhysicalNetwork physicalNetwork, IReadOnlyCollection proxyServerAddresses, CancellationToken cancellationToken, bool preservePrivateNodeRoute = false, string? preserveTailnetAddress = null) { if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。"); var proxyIpv4Addresses = proxyServerAddresses .Where(address => address.AddressFamily == AddressFamily.InterNetwork) .Distinct() .ToList(); if (proxyIpv4Addresses.Count == 0) { throw new InvalidOperationException("代理节点没有可用的 IPv4 地址,无法建立物理网卡旁路。"); } if (preservePrivateNodeRoute) { if (proxyIpv4Addresses.Count != 1 || !PrivateAuxiliaryRouting.IsRegisteredEndpoint(proxyIpv4Addresses[0].ToString())) throw new InvalidOperationException("私有节点旁路目标不匹配。"); PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString()); } if (preserveTailnetAddress is not null) { if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1 || proxyIpv4Addresses[0].ToString() != preserveTailnetAddress) throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。"); TailnetTransport.RequireExistingRoute(preserveTailnetAddress); } var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault(); if (tunDnsServer is null) { throw new InvalidOperationException( $"出口网卡 {physicalNetwork.InterfaceName} 没有可用的 IPv4 DNS,请先检查当前网络的 DNS 设置。"); } var adapter = await WaitForAdapterAsync(cancellationToken); var index = adapter.GetIPProperties().GetIPv4Properties()?.Index ?? throw new InvalidOperationException("无法取得优创⁺纵横家虚拟网卡编号。"); await RunAsync( "netsh.exe", $"interface ipv4 set dnsservers name=\"{AdapterName}\" source=static address={tunDnsServer} validate=no", cancellationToken); AppPaths.WriteLog($"虚拟网卡 DNS 已跟随当前出口:{tunDnsServer}。"); if (preservePrivateNodeRoute || preserveTailnetAddress is not null) { if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString()); if (preserveTailnetAddress is not null) TailnetTransport.RequireExistingRoute(preserveTailnetAddress); } var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index, preservePrivateNodeRoute || preserveTailnetAddress is not null); // The journal records additions before applying them and skips exact // pre-existing routes. The user's LAN and Tailnet routes stay in place. await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()).ApplyAsync(routes, cancellationToken); AppPaths.WriteLog($"青岛管理旁路已建立:{PlatformBootstrapTransport.ManagementAddress} -> {physicalNetwork.InterfaceName}"); await RunAsync("ipconfig.exe", "/flushdns", cancellationToken); AppPaths.WriteLog("Windows DNS 缓存已刷新,新的网卡与 DNS 路由已生效。"); } internal static IReadOnlyList CreateOwnedRoutes(PhysicalNetwork physicalNetwork, IReadOnlyCollection proxyIpv4Addresses, int tunIndex, bool preserveProxyRoute) { var bypassAddresses = physicalNetwork.Ipv4DnsServers.Append(PlatformBootstrapTransport.ManagementAddress); if (!preserveProxyRoute) bypassAddresses = proxyIpv4Addresses.Concat(bypassAddresses); var routes = bypassAddresses.Distinct().Select(address => { var nextHop = IsOnLink(address, physicalNetwork.Ipv4Address, physicalNetwork.Ipv4PrefixLength) ? IPAddress.Any : physicalNetwork.Ipv4Gateway; return new Ipv4Route(address.ToString(), "255.255.255.255", nextHop.ToString(), physicalNetwork.InterfaceIndex); }).ToList(); routes.Add(new("0.0.0.0", "128.0.0.0", "0.0.0.0", tunIndex, 5)); routes.Add(new("128.0.0.0", "128.0.0.0", "0.0.0.0", tunIndex, 5)); return routes; } private static bool IsOnLink(IPAddress address, IPAddress localAddress, int prefixLength) { if (address.AddressFamily != AddressFamily.InterNetwork || localAddress.AddressFamily != AddressFamily.InterNetwork) { return false; } var addressBytes = address.GetAddressBytes(); var localBytes = localAddress.GetAddressBytes(); var remainingBits = Math.Clamp(prefixLength, 0, 32); for (var index = 0; index < addressBytes.Length && remainingBits > 0; index++) { var bits = Math.Min(remainingBits, 8); var mask = (byte)(0xFF << (8 - bits)); if ((addressBytes[index] & mask) != (localBytes[index] & mask)) return false; remainingBits -= bits; } return true; } internal static async Task CleanupOwnedAdapterAsync(CancellationToken cancellationToken) { if (!IsElevated()) return; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(TimeSpan.FromSeconds(10)); Process? process = null; try { process = new Process { StartInfo = new ProcessStartInfo { FileName = "pnputil.exe", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, } }; process.StartInfo.ArgumentList.Add("/remove-device"); process.StartInfo.ArgumentList.Add(OwnedAdapterInstanceId); process.Start(); var stdout = process.StandardOutput.ReadToEndAsync(timeout.Token); var stderr = process.StandardError.ReadToEndAsync(timeout.Token); await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); var output = string.Join(" ", await stdout.ConfigureAwait(false), await stderr.ConfigureAwait(false)).Trim(); if (process.ExitCode == 0) { AppPaths.WriteLog($"已清理优创⁺纵横家专属 Wintun 设备:{OwnedAdapterInstanceId}"); await Task.Delay(350, timeout.Token).ConfigureAwait(false); } else if (!string.IsNullOrWhiteSpace(output)) { AppPaths.WriteLog($"专属 Wintun 设备无需清理或已不存在(exit={process.ExitCode})。"); } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception exception) { // Adapter cleanup is best effort. A following Xray start will still // report a precise error if Windows keeps the owned device locked. AppPaths.WriteError(exception); } finally { if (process is not null) { try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } process.Dispose(); } } } internal static async Task RestoreAsync(CancellationToken cancellationToken) { if (!File.Exists(AppPaths.TunStateFile)) return; using var document = JsonDocument.Parse(File.ReadAllText(AppPaths.TunStateFile)); if (document.RootElement.TryGetProperty("SchemaVersion", out var schema) && schema.GetInt32() == 2) { await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()) .RestoreAsync(cancellationToken).ConfigureAwait(false); return; } // Upgrade recovery for 0.2.5's journal. Its flag was written only after // both split routes, so inspect both even if that flag is still false. var state = document.RootElement.Deserialize() ?? throw new InvalidDataException("旧版路由恢复记录无法读取。"); var table = new WindowsRouteTable(); var routes = table.Snapshot().Where(route => (route.InterfaceIndex == state.InterfaceIndex && route.Mask == "128.0.0.0" && route.NextHop == "0.0.0.0" && route.Destination is "0.0.0.0" or "128.0.0.0") || (route.InterfaceIndex == state.PhysicalInterfaceIndex && route.Mask == "255.255.255.255" && state.BypassIpv4Addresses.Contains(route.Destination))).ToList(); foreach (var route in routes) { await table.DeleteAsync(route, cancellationToken).ConfigureAwait(false); if (table.Snapshot().Any(route.SamePath)) throw new IOException("旧版路由恢复未完成。"); } if (state.Ipv6RoutesAdded) { // No released 0.2.5+ client creates IPv6 split routes. Preserve an // unfamiliar legacy journal instead of silently claiming recovery. throw new IOException("发现旧版 IPv6 路由恢复记录,需要检查后再连接。"); } File.Delete(AppPaths.TunStateFile); } internal static async Task WaitForAdapterAsync(CancellationToken cancellationToken, string adapterName = AdapterName, bool requireIpv4Ready = false) { for (var attempt = 0; attempt < (requireIpv4Ready ? 100 : 30); attempt++) { var adapter = NetworkInterface.GetAllNetworkInterfaces() .FirstOrDefault(item => string.Equals(item.Name, adapterName, StringComparison.OrdinalIgnoreCase)); // Production preserves 0.2.5 order: discover -> set DNS -> routes. // The caller also waits for DAD after baseline routes, before NRPT. if (adapter is not null && (!requireIpv4Ready || (adapter.OperationalStatus == OperationalStatus.Up && adapter.GetIPProperties().UnicastAddresses.Any(address => address.Address.AddressFamily == AddressFamily.InterNetwork && address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)))) return adapter; await Task.Delay(200, cancellationToken); } throw new InvalidOperationException("优创⁺纵横家虚拟网卡创建超时。"); } private static string BuildOwnedAdapterInstanceId() { var digest = MD5.HashData(Encoding.UTF8.GetBytes(AdapterName)); return $@"SWD\Wintun\{{{new Guid(digest).ToString().ToUpperInvariant()}}}"; } private static Task RunAsync(string fileName, string arguments, CancellationToken token) => NetworkCommand.RunAsync(fileName, arguments, token); }