715 lines
35 KiB
C#
715 lines
35 KiB
C#
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRuntime
|
|
{
|
|
private Process? _process;
|
|
private int _routingApiPort;
|
|
private int _learningProbePort;
|
|
private int _directProbePort;
|
|
private CancellationTokenSource _learningEpoch = new();
|
|
private LearningProbeBudget _learningBudget = new();
|
|
private readonly NetworkLearningLeases _networkLearned = new();
|
|
private string? _directFirstConfig;
|
|
internal string CachedLearningRevision { get; private set; } = "";
|
|
private IReadOnlyList<RoutingTarget> _learningCandidates = [];
|
|
private bool _needsRecovery;
|
|
private bool _disposed;
|
|
private NetworkOwnerLease? _ownerLease;
|
|
private bool _recoveryComplete;
|
|
private readonly SemaphoreSlim _lifecycle = new(1, 1);
|
|
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
|
private string? _baseConfigJson;
|
|
private string? _tailnetFallbackConfigJson;
|
|
// Retain the authenticated alternative for compatibility/identity checks.
|
|
// A public fallback is sticky: automatic physical-network recovery must
|
|
// never promote it to this cached internal alternative.
|
|
private string? _preferredTailnetConfigJson;
|
|
private string? _tailnetInterfaceName;
|
|
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
|
|
internal (string Address, int Port)? PreferredTailnetEndpoint
|
|
{
|
|
get
|
|
{
|
|
var current = _baseConfigJson;
|
|
var preferred = _preferredTailnetConfigJson;
|
|
if (!IsRunning || current is null || preferred is null
|
|
|| !TailnetTransport.SameAuthorizedFallback(preferred, current)) return null;
|
|
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
|
|
}
|
|
}
|
|
private string _routeMode = "smart";
|
|
private string _nodeSlug = "";
|
|
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
|
|
internal bool IsRunning => _process is { HasExited: false };
|
|
internal bool IsTransitioning => _lifecycle.CurrentCount == 0;
|
|
internal int? CoreId => IsRunning ? _process!.Id : null;
|
|
private TunRouting.PhysicalNetwork? _boundNetwork;
|
|
internal TunRouting.PhysicalNetwork? BoundNetwork => _boundNetwork;
|
|
public string? BoundNetworkFingerprint => PhysicalUplink.Fingerprint(_boundNetwork);
|
|
public bool CanRebindNetwork => !string.IsNullOrWhiteSpace(_baseConfigJson) && _boundNetwork is not null;
|
|
bool IHandoverRuntime.IsRunning => IsRunning;
|
|
|
|
public async Task SuspendForNetworkChangeAsync(CancellationToken token)
|
|
{
|
|
await _lifecycle.WaitAsync(token);
|
|
try { await StopCoreAsync(); }
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
public async Task RebindNetworkAsync(CancellationToken token)
|
|
{
|
|
await _lifecycle.WaitAsync(token);
|
|
try
|
|
{
|
|
if (!CanRebindNetwork) throw new InvalidOperationException("没有可恢复的已授权线路。");
|
|
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
|
|
token.ThrowIfCancellationRequested();
|
|
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
|
|
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
|
|
StopCoreAsync, CheckProxyHealthAsync, token,
|
|
preferredTailnetConfig: _preferredTailnetConfigJson,
|
|
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
|
|
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
|
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
|
|
}
|
|
catch { await StopCoreAsync(); throw; }
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
internal async Task<(long Up, long Down)?> ReadTrafficAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (!IsRunning || _routingApiPort == 0) return null;
|
|
return await ReadTrafficCountersAsync(XrayPath, _routingApiPort, cancellationToken);
|
|
}
|
|
|
|
internal static async Task<(long Up, long Down)?> ReadTrafficCountersAsync(string xrayPath, int apiPort, CancellationToken cancellationToken)
|
|
{
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(4));
|
|
using var process = new Process { StartInfo = new ProcessStartInfo {
|
|
FileName = xrayPath, UseShellExecute = false, CreateNoWindow = true,
|
|
RedirectStandardOutput = true, RedirectStandardError = true,
|
|
}};
|
|
foreach (var arg in new[] {"api", "statsquery", $"--server=127.0.0.1:{apiPort}", "--timeout=2", "-pattern", "outbound>>>proxy>>>traffic>>>"})
|
|
process.StartInfo.ArgumentList.Add(arg);
|
|
try
|
|
{
|
|
process.Start();
|
|
var output = process.StandardOutput.ReadToEndAsync(timeout.Token);
|
|
var errors = process.StandardError.ReadToEndAsync(timeout.Token);
|
|
await process.WaitForExitAsync(timeout.Token);
|
|
await errors;
|
|
if (process.ExitCode != 0) return null;
|
|
using var doc = System.Text.Json.JsonDocument.Parse(await output);
|
|
long up = 0, down = 0;
|
|
if (doc.RootElement.TryGetProperty("stat", out var stats))
|
|
foreach (var stat in stats.EnumerateArray())
|
|
{
|
|
var name = stat.GetProperty("name").GetString();
|
|
var value = stat.TryGetProperty("value", out var v) ? (v.ValueKind == System.Text.Json.JsonValueKind.String ? long.Parse(v.GetString()!) : v.GetInt64()) : 0;
|
|
if (name == "outbound>>>proxy>>>traffic>>>uplink") up = value;
|
|
if (name == "outbound>>>proxy>>>traffic>>>downlink") down = value;
|
|
}
|
|
return (up, down);
|
|
}
|
|
catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested) { return null; }
|
|
finally { try { if (!process.HasExited) process.Kill(); } catch { } }
|
|
}
|
|
|
|
internal Task<bool> CheckHealthAsync(CancellationToken token)
|
|
// Health must traverse ordinary smart routing too. The forced-proxy
|
|
// listener is only comparison evidence, not proof that business routes work.
|
|
=> !IsRunning ? Task.FromResult(false) : NodeHealthProbe.CheckAsync(token);
|
|
|
|
internal Task<bool> CheckProxyHealthAsync(CancellationToken token)
|
|
=> !IsRunning || _learningProbePort == 0 ? Task.FromResult(false)
|
|
: NodeHealthProbe.CheckAsync(token, _learningProbePort);
|
|
|
|
internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted);
|
|
internal async Task<HealthResult> CheckHealthWithRepairAsync(CancellationToken token)
|
|
{
|
|
var expectedCore = CoreId;
|
|
if (await CheckHealthAsync(token)) return new(true, false, false);
|
|
if (_routeMode != "smart" || expectedCore is null || CoreId != expectedCore || _learningProbePort == 0)
|
|
return new(false, false, false);
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token, _learningEpoch.Token);
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(45));
|
|
var proxyHealthy = false;
|
|
try
|
|
{
|
|
// A failing ordinary route is not proof that the proxy node is down.
|
|
if (!await NodeHealthProbe.CheckAsync(deadline.Token, _learningProbePort)) return new(false, false, false);
|
|
proxyHealthy = true;
|
|
if (CoreId != expectedCore) return new(false, true, false);
|
|
AppPaths.WriteLog("普通智能路径异常,代理比较路径正常;先重新验证并热修复规则,不重启内核。");
|
|
await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
|
ScheduleLearningAsync(new LearningObservation { Target = target, Port = 443, AccessKind = "http",
|
|
Node = _nodeSlug, Scope = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, deadline.Token)));
|
|
return new(await CheckHealthAsync(deadline.Token), true, true);
|
|
}
|
|
catch (OperationCanceledException) when (!token.IsCancellationRequested)
|
|
{ return new(false, proxyHealthy, proxyHealthy); }
|
|
}
|
|
|
|
internal Func<LearningObservation, Task>? ObservationDetectedAsync { get; set; }
|
|
internal Action<string>? StatusMessage { get; set; }
|
|
|
|
internal XrayManager(bool recoverStale = true)
|
|
{
|
|
AppPaths.EnsureDirectory();
|
|
// Constructing controls installs a WinForms synchronization context before
|
|
// Application.Run. Blocking on async adapter cleanup here deadlocks the
|
|
// UI before the login window has ever been displayed.
|
|
_needsRecovery = recoverStale;
|
|
}
|
|
|
|
internal async Task InitializeAsync(CancellationToken cancellationToken)
|
|
{
|
|
await _lifecycle.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
try
|
|
{
|
|
_ownerLease ??= NetworkOwnerLease.Acquire();
|
|
if (!_needsRecovery) { _recoveryComplete = true; return; }
|
|
await Task.Run(() => RecoverStaleStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
|
_needsRecovery = false;
|
|
_recoveryComplete = true;
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
|
|
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
|
|
{
|
|
if (TailnetTransport.Address(configJson) is not null
|
|
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
|
|
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。");
|
|
var preferred = preferredTailnetConfigJson
|
|
?? (TailnetTransport.Address(configJson) is not null ? configJson : null);
|
|
var original = tailnetFallbackConfigJson
|
|
?? (TailnetTransport.Address(configJson) is null ? configJson : null);
|
|
if (preferred is not null && !TailnetTransport.SameAuthorizedFallback(preferred, original))
|
|
throw new InvalidOperationException("Tailscale 恢复入口与已授权线路不匹配。");
|
|
await InitializeAsync(cancellationToken);
|
|
await _lifecycle.WaitAsync(cancellationToken);
|
|
try
|
|
{
|
|
await StopCoreAsync();
|
|
_baseConfigJson = configJson;
|
|
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
|
|
_preferredTailnetConfigJson = preferred;
|
|
_routeMode = routeMode;
|
|
_nodeSlug = nodeSlug;
|
|
await StartCoreAsync(cancellationToken);
|
|
}
|
|
catch
|
|
{
|
|
await StopCoreAsync().ConfigureAwait(false);
|
|
throw;
|
|
}
|
|
finally
|
|
{
|
|
_lifecycle.Release();
|
|
}
|
|
if (_routeMode == "smart")
|
|
{
|
|
// The same three fixed health destinations, but first validate their real
|
|
// physical direct path. Never mark all server candidate domains as proxy.
|
|
StatusMessage?.Invoke("正在验证本地直连与代理路径…");
|
|
using var warmup = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _learningEpoch.Token);
|
|
warmup.CancelAfter(TimeSpan.FromSeconds(15));
|
|
await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
|
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
|
|
Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmup.Token)));
|
|
}
|
|
}
|
|
|
|
internal async Task StopAsync()
|
|
{
|
|
await _lifecycle.WaitAsync().ConfigureAwait(false);
|
|
try
|
|
{
|
|
await StopCoreAsync().ConfigureAwait(false);
|
|
_baseConfigJson = null;
|
|
_tailnetFallbackConfigJson = null;
|
|
_preferredTailnetConfigJson = null;
|
|
_tailnetInterfaceName = null;
|
|
_nodeSlug = "";
|
|
_boundNetwork = null;
|
|
}
|
|
finally
|
|
{
|
|
_lifecycle.Release();
|
|
}
|
|
}
|
|
|
|
internal async Task<bool> RenewPrivateAuthorizationAsync(string configJson, int expectedCore, CancellationToken token)
|
|
{
|
|
PrivateAuxiliaryRuntime.ValidateLifetime(configJson);
|
|
await _lifecycle.WaitAsync(token);
|
|
try
|
|
{
|
|
if (CoreId != expectedCore || _baseConfigJson is null
|
|
|| !PrivateAuxiliaryRuntime.SameConnection(_baseConfigJson, configJson)) return false;
|
|
_baseConfigJson = configJson; // Expiry metadata only; do not restart a healthy core/stream.
|
|
return true;
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
private async Task StartCoreAsync(CancellationToken cancellationToken)
|
|
{
|
|
EnsureRuntime();
|
|
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
|
|
PrivateAuxiliaryRuntime.ValidateLifetime(_baseConfigJson);
|
|
var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson);
|
|
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
|
|
if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson));
|
|
var tailnetAddress = TailnetTransport.Address(_baseConfigJson);
|
|
var tailnetInterface = tailnetAddress is null ? null : TailnetTransport.RequireExistingRoute(tailnetAddress);
|
|
_tailnetInterfaceName = tailnetInterface;
|
|
var proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken);
|
|
var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses);
|
|
_learningEpoch = new CancellationTokenSource();
|
|
_learningBudget = new LearningProbeBudget();
|
|
_networkLearned.Clear();
|
|
CachedLearningRevision = "";
|
|
_learningCandidates = [];
|
|
_directFirstConfig = _routeMode == "smart" ? LearningPolicy.DirectFirst(_baseConfigJson) : _baseConfigJson;
|
|
AppPaths.WriteLog(
|
|
$"出口网卡已选择:{physicalNetwork.InterfaceName} ({physicalNetwork.Ipv4Address}, IF {physicalNetwork.InterfaceIndex})");
|
|
await TunRouting.CleanupOwnedAdapterAsync(cancellationToken);
|
|
|
|
// Validate routing and outbound settings without a TUN inbound. Xray's
|
|
// `run -test` starts inbounds, which can create and leave a Windows
|
|
// Wintun device even though no real connection was requested.
|
|
var validationConfig = TunConfigBuilder.Build(
|
|
_directFirstConfig,
|
|
physicalNetwork.InterfaceName,
|
|
includeLocalLearning: _routeMode == "smart",
|
|
includeTun: false, tailnetInterfaceName: tailnetInterface);
|
|
File.WriteAllText(AppPaths.ConfigFile, validationConfig, new UTF8Encoding(false));
|
|
|
|
var validation = await RunValidationAsync(cancellationToken);
|
|
if (validation.ExitCode != 0)
|
|
{
|
|
SafeDeleteConfig();
|
|
throw new InvalidOperationException($"线路配置校验失败:{validation.Output.Trim()}");
|
|
}
|
|
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
_routingApiPort = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
listener.Stop();
|
|
var probeListener = new TcpListener(IPAddress.Loopback, 0);
|
|
probeListener.Start();
|
|
_learningProbePort = ((IPEndPoint)probeListener.LocalEndpoint).Port;
|
|
probeListener.Stop();
|
|
using var directListener = new TcpListener(IPAddress.Loopback, 0);
|
|
directListener.Start();
|
|
_directProbePort = ((IPEndPoint)directListener.LocalEndpoint).Port;
|
|
directListener.Stop();
|
|
var runtimeConfig = TunConfigBuilder.Build(
|
|
_directFirstConfig,
|
|
physicalNetwork.InterfaceName,
|
|
includeLocalLearning: _routeMode == "smart",
|
|
routingApiPort: _routingApiPort, learningProbePort: _learningProbePort, directProbePort: _directProbePort,
|
|
tailnetInterfaceName: tailnetInterface);
|
|
File.WriteAllText(AppPaths.ConfigFile, runtimeConfig, new UTF8Encoding(false));
|
|
|
|
_process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = XrayPath,
|
|
Arguments = $"run -c \"{AppPaths.ConfigFile}\"",
|
|
WorkingDirectory = _xrayDirectory,
|
|
UseShellExecute = false,
|
|
CreateNoWindow = true,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
StandardOutputEncoding = Encoding.UTF8,
|
|
StandardErrorEncoding = Encoding.UTF8,
|
|
},
|
|
EnableRaisingEvents = true,
|
|
};
|
|
_process.OutputDataReceived += (_, eventArgs) => AppendXrayLog(eventArgs.Data);
|
|
_process.ErrorDataReceived += (_, eventArgs) => AppendXrayLog(eventArgs.Data);
|
|
var startedProcess = _process;
|
|
_process.Exited += (_, _) => _ = HandleCoreExitAsync(startedProcess);
|
|
if (!_process.Start()) throw new InvalidOperationException("Xray 内核无法启动。");
|
|
_process.BeginOutputReadLine();
|
|
_process.BeginErrorReadLine();
|
|
File.WriteAllText(AppPaths.PidFile, _process.Id.ToString());
|
|
|
|
await Task.Delay(900, cancellationToken);
|
|
if (_process.HasExited)
|
|
{
|
|
var details = ReadRecentXrayLog();
|
|
await TunRouting.CleanupOwnedAdapterAsync(CancellationToken.None);
|
|
if (details.Contains("0x800700B7", StringComparison.OrdinalIgnoreCase)
|
|
|| details.Contains("Creating adapter", StringComparison.OrdinalIgnoreCase)
|
|
|| details.Contains("device creation", StringComparison.OrdinalIgnoreCase))
|
|
throw new LocalNetworkException("本机虚拟网卡未能创建,可能仍被旧内核占用;这不是节点故障。已恢复本次连接的网络设置,请退出旧版纵横家后重试。");
|
|
throw new InvalidOperationException($"Xray 内核启动后异常退出。{details}");
|
|
}
|
|
|
|
try
|
|
{
|
|
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken, preservePrivateRoute, tailnetAddress);
|
|
// Apply 0.2.5 routing first, then wait until Windows has completed
|
|
// DAD before applications can use the tunnel's DNS/IPv4 path.
|
|
await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true);
|
|
await ProxyDnsPolicy.EnableAsync(_baseConfigJson, cancellationToken);
|
|
StatusMessage?.Invoke("正在等待 Windows 网络与 DNS 就绪…");
|
|
await WaitForDnsReadyAsync(cancellationToken);
|
|
await Task.Delay(250, cancellationToken);
|
|
_boundNetwork = physicalNetwork;
|
|
SafeDeleteConfig();
|
|
}
|
|
catch
|
|
{
|
|
await StopCoreAsync();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private static async Task WaitForDnsReadyAsync(CancellationToken cancellationToken)
|
|
{
|
|
var started = Stopwatch.StartNew();
|
|
Exception? lastError = null;
|
|
for (var attempt = 0; attempt < 40; attempt++)
|
|
{
|
|
try
|
|
{
|
|
var addresses = await Dns.GetHostAddressesAsync("vpn.example.invalid", cancellationToken);
|
|
if (addresses.Any(address => address.AddressFamily == AddressFamily.InterNetwork))
|
|
{
|
|
AppPaths.WriteLog($"Windows DNS 已就绪({started.ElapsedMilliseconds} ms)。");
|
|
return;
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception exception) when (exception is SocketException or IOException)
|
|
{
|
|
lastError = exception;
|
|
}
|
|
await Task.Delay(500, cancellationToken);
|
|
}
|
|
throw new InvalidOperationException(
|
|
$"Windows DNS 在 20 秒内未就绪,已恢复原网络。{lastError?.GetBaseException().Message}");
|
|
}
|
|
|
|
private async Task StopCoreAsync()
|
|
{
|
|
// A rejected second instance must not delete the active owner's DNS,
|
|
// routes, PID journal or virtual adapter through its error/Dispose path.
|
|
if (_ownerLease is null || !_recoveryComplete) return;
|
|
_learningEpoch.Cancel();
|
|
var proxyRestored = SystemProxy.Restore();
|
|
Exception? restoreError = null;
|
|
using var recovery = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
|
Exception? dnsRestoreError = null;
|
|
try { await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
|
catch (Exception error) { dnsRestoreError = error; AppPaths.WriteError(error); }
|
|
try { await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); }
|
|
catch (Exception error) { restoreError = error; AppPaths.WriteError(error); }
|
|
try
|
|
{
|
|
if (_process is { HasExited: false })
|
|
{
|
|
_process.Kill(entireProcessTree: true);
|
|
_process.WaitForExit(5_000);
|
|
}
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
AppPaths.WriteError(exception);
|
|
}
|
|
finally
|
|
{
|
|
_process?.Dispose();
|
|
_process = null;
|
|
SafeDelete(AppPaths.PidFile);
|
|
SafeDeleteConfig();
|
|
}
|
|
await TunRouting.CleanupOwnedAdapterAsync(CancellationToken.None).ConfigureAwait(false);
|
|
if (restoreError is not null)
|
|
{
|
|
// Removal of a failed TUN device may have removed its routes too.
|
|
// Retry the retained journal; never erase it merely because exit was requested.
|
|
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
|
await TunRouting.RestoreAsync(retry.Token).ConfigureAwait(false);
|
|
}
|
|
if (!proxyRestored && !SystemProxy.Restore())
|
|
throw new IOException("系统代理恢复未完成,恢复记录已保留。请勿继续升级安装。");
|
|
if (dnsRestoreError is not null)
|
|
{
|
|
using var retry = new CancellationTokenSource(TimeSpan.FromSeconds(25));
|
|
await ProxyDnsPolicy.RestoreAsync(retry.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
private async Task HandleCoreExitAsync(Process exited)
|
|
{
|
|
try
|
|
{
|
|
await _lifecycle.WaitAsync().ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (_disposed || !ReferenceEquals(_process, exited)) return;
|
|
await StopCoreAsync().ConfigureAwait(false);
|
|
StatusMessage?.Invoke("网络内核异常停止,已恢复本地网络;等待自动重连");
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
catch (Exception error) { AppPaths.WriteError(error); }
|
|
}
|
|
|
|
internal async Task CacheLearningCandidatesAsync(RoutingManifest manifest, int expectedCore, CancellationToken token)
|
|
{
|
|
if (manifest.Mode != "direct_first_candidates") throw new InvalidDataException("拒绝非直连优先的学习策略。");
|
|
await _lifecycle.WaitAsync(token);
|
|
try
|
|
{
|
|
if (CoreId != expectedCore || _directFirstConfig is null) throw new IOException("学习同步期间连接已改变。");
|
|
_ = LearningPolicy.Merge(_directFirstConfig, manifest); // Validate all candidates; never force them on this network.
|
|
CachedLearningRevision = manifest.Revision;
|
|
_learningCandidates = manifest.Rules.ToArray();
|
|
// Candidate delivery never evicts a locally proved rule. Local maintenance
|
|
// owns rechecks and hard deadlines independently of backend availability.
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
|
|
internal async Task ExpireLearningAsync(CancellationToken token)
|
|
{
|
|
var rechecks = new List<(NetworkLearningLeases.Entry Entry, int? Core, int Direct, int Proxy,
|
|
LearningProbeBudget Budget, CancellationToken Epoch, string Node, string Scope)>();
|
|
await _lifecycle.WaitAsync(token);
|
|
try
|
|
{
|
|
if (!IsRunning || _routeMode != "smart") return;
|
|
var now = Environment.TickCount64;
|
|
_networkLearned.Expire(now);
|
|
if (_networkLearned.Dirty) await ApplyNetworkLearningAsync(token);
|
|
foreach (var entry in _networkLearned.Due(now))
|
|
{
|
|
if (!_learningBudget.TryEnter(entry.Target.Target, now)) continue;
|
|
_networkLearned.Scheduled(entry, now);
|
|
rechecks.Add((entry, CoreId, _directProbePort, _learningProbePort, _learningBudget,
|
|
_learningEpoch.Token, _nodeSlug, PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public"));
|
|
}
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
foreach (var check in rechecks)
|
|
_ = HandleObservationAsync(new LearningObservation { TargetType = check.Entry.Target.TargetType,
|
|
Target = check.Entry.Target.Target, Port = 443, AccessKind = "http", Node = check.Node, Scope = check.Scope },
|
|
check.Core, check.Direct, check.Proxy, check.Budget, check.Epoch, check.Entry);
|
|
}
|
|
|
|
private async Task ApplyNetworkLearningAsync(CancellationToken token)
|
|
{
|
|
if (_directFirstConfig is null || _boundNetwork is null) return;
|
|
var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1,
|
|
Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() });
|
|
var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName,
|
|
_learningProbePort, _directProbePort, _tailnetInterfaceName);
|
|
await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token);
|
|
_networkLearned.Applied();
|
|
}
|
|
|
|
private async Task<(int ExitCode, string Output)> RunValidationAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = XrayPath,
|
|
Arguments = $"run -test -c \"{AppPaths.ConfigFile}\"",
|
|
WorkingDirectory = _xrayDirectory,
|
|
UseShellExecute = false,
|
|
CreateNoWindow = true,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
StandardOutputEncoding = Encoding.UTF8,
|
|
StandardErrorEncoding = Encoding.UTF8,
|
|
}
|
|
};
|
|
process.Start();
|
|
var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken);
|
|
var stderr = process.StandardError.ReadToEndAsync(cancellationToken);
|
|
await process.WaitForExitAsync(cancellationToken);
|
|
return (process.ExitCode, string.Join(" ", await stdout, await stderr));
|
|
}
|
|
|
|
private static async Task<IReadOnlyCollection<IPAddress>> ResolveProxyServerAddressesAsync(
|
|
string baseConfigJson,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var addresses = new HashSet<IPAddress>();
|
|
var hosts = TunConfigBuilder.GetProxyServerHosts(baseConfigJson);
|
|
if (hosts.Count == 0)
|
|
{
|
|
throw new InvalidOperationException("线路配置缺少代理节点地址。");
|
|
}
|
|
foreach (var host in hosts)
|
|
{
|
|
if (IPAddress.TryParse(host, out var address))
|
|
{
|
|
addresses.Add(address);
|
|
continue;
|
|
}
|
|
foreach (var resolved in await Dns.GetHostAddressesAsync(host, cancellationToken))
|
|
{
|
|
if (resolved.AddressFamily == AddressFamily.InterNetwork) addresses.Add(resolved);
|
|
}
|
|
}
|
|
if (addresses.Count == 0)
|
|
{
|
|
throw new InvalidOperationException("无法解析代理节点地址,未修改系统路由。");
|
|
}
|
|
return addresses;
|
|
}
|
|
|
|
private void EnsureRuntime()
|
|
{
|
|
foreach (var file in new[]
|
|
{
|
|
XrayPath,
|
|
Path.Combine(_xrayDirectory, "geoip.dat"),
|
|
Path.Combine(_xrayDirectory, "geosite.dat"),
|
|
Path.Combine(_xrayDirectory, "wintun.dll"),
|
|
})
|
|
{
|
|
if (!File.Exists(file)) throw new FileNotFoundException($"客户端组件缺失:{Path.GetFileName(file)}");
|
|
}
|
|
}
|
|
|
|
private async Task RecoverStaleStateAsync(CancellationToken cancellationToken)
|
|
{
|
|
var hadTunnelState = File.Exists(AppPaths.TunStateFile);
|
|
await NetworkOwnerLease.RecoverOrphanAsync(XrayPath, cancellationToken).ConfigureAwait(false);
|
|
if (!SystemProxy.Restore()) throw new IOException("上次系统代理恢复未完成,请先检查权限后重试。");
|
|
await ProxyDnsPolicy.RestoreAsync(cancellationToken).ConfigureAwait(false);
|
|
await TunRouting.RestoreAsync(cancellationToken).ConfigureAwait(false);
|
|
SafeDelete(AppPaths.PidFile);
|
|
SafeDeleteConfig();
|
|
if (hadTunnelState)
|
|
await TunRouting.CleanupOwnedAdapterAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
private void AppendXrayLog(string? value)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value)) return;
|
|
DetectDirectFailure(value);
|
|
// Info is consumed in memory for learning, never persisted as browsing history.
|
|
if (!value.Contains("[Warning]", StringComparison.OrdinalIgnoreCase)
|
|
&& !value.Contains("[Error]", StringComparison.OrdinalIgnoreCase)
|
|
&& !value.Contains("Creating adapter", StringComparison.OrdinalIgnoreCase)
|
|
&& !value.Contains("Failed to start", StringComparison.OrdinalIgnoreCase)) return;
|
|
try
|
|
{
|
|
File.AppendAllText(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}");
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
private void DetectDirectFailure(string value)
|
|
{
|
|
if (_routeMode != "smart" || !IsRunning || IsTransitioning || _learningEpoch.IsCancellationRequested) return;
|
|
var scope = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public";
|
|
var observation = LearningPolicy.ParseAttempt(value, _nodeSlug, scope);
|
|
if (observation is null) return;
|
|
_ = ScheduleLearningAsync(observation, _learningEpoch.Token);
|
|
}
|
|
|
|
private Task ScheduleLearningAsync(LearningObservation observation, CancellationToken token)
|
|
{
|
|
var budget = _learningBudget;
|
|
if (!budget.TryEnter(observation.Target, Environment.TickCount64)) return Task.CompletedTask;
|
|
return HandleObservationAsync(observation, CoreId, _directProbePort, _learningProbePort, budget, token);
|
|
}
|
|
|
|
private async Task HandleObservationAsync(LearningObservation observation, int? expectedCore, int directPort,
|
|
int proxyPort, LearningProbeBudget budget, CancellationToken token, NetworkLearningLeases.Entry? recheck = null)
|
|
{
|
|
try
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
var comparison = await ProxyProbe.CompareTlsAsync(observation, directPort, proxyPort, token);
|
|
if (token.IsCancellationRequested || CoreId != expectedCore) return;
|
|
// Persist counters/outcomes only, not user targets or URLs. An attempt is not a failure.
|
|
AppPaths.WriteLog($"学习路径验证:direct_tls={comparison.DirectTls?.ToString() ?? "unknown"}; proxy_tls={comparison.ProxyTls?.ToString() ?? "not_tested"}; promote={comparison.ShouldProxy}");
|
|
if (comparison.DirectTls == false && comparison.ProxyTls.HasValue && ObservationDetectedAsync is not null)
|
|
{
|
|
await ObservationDetectedAsync(observation);
|
|
await ObservationDetectedAsync(new LearningObservation {
|
|
TargetType = observation.TargetType, Target = observation.Target, Port = observation.Port,
|
|
AccessKind = observation.AccessKind, Network = observation.Network, Node = observation.Node, Scope = observation.Scope,
|
|
Outcome = comparison.ShouldProxy ? "proxy_succeeded" : "proxy_failed",
|
|
EvidenceKind = comparison.ShouldProxy && observation.Scope == "public" ? "tls" : "", RelatedReportId = observation.ReportId });
|
|
}
|
|
await _lifecycle.WaitAsync(token);
|
|
try
|
|
{
|
|
if (CoreId != expectedCore || _routeMode != "smart" || token.IsCancellationRequested) return;
|
|
if (recheck is not null && !_networkLearned.Current(recheck)) return;
|
|
_networkLearned.Observe(new RoutingTarget { TargetType = observation.TargetType, Target = observation.Target, MatchMode = "exact" },
|
|
comparison, Environment.TickCount64, recheck);
|
|
if (_networkLearned.Dirty) await ApplyNetworkLearningAsync(token);
|
|
if (comparison.ShouldProxy)
|
|
StatusMessage?.Invoke("本地直连失败的目标已通过代理验证;到期前复查,连接保持不中断");
|
|
}
|
|
finally { _lifecycle.Release(); }
|
|
}
|
|
catch (OperationCanceledException) { }
|
|
catch (Exception exception) { AppPaths.WriteLog("学习验证/热更新失败,原连接保持:" + exception.GetType().Name); }
|
|
finally { budget.Exit(); }
|
|
}
|
|
|
|
private static string ReadRecentXrayLog()
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(AppPaths.XrayLogFile)) return "";
|
|
var lines = File.ReadLines(AppPaths.XrayLogFile).TakeLast(3);
|
|
return $" {string.Join(" ", lines)}";
|
|
}
|
|
catch { return ""; }
|
|
}
|
|
|
|
private static void SafeDeleteConfig() => SafeDelete(AppPaths.ConfigFile);
|
|
|
|
private static void SafeDelete(string path)
|
|
{
|
|
try { if (File.Exists(path)) File.Delete(path); } catch { }
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
try { StopAsync().ConfigureAwait(false).GetAwaiter().GetResult(); }
|
|
// Exited callbacks can already be waiting on this purely managed semaphore.
|
|
// Let it be collected after those callbacks, rather than disposing under Release.
|
|
finally { _ownerLease?.Dispose(); _ownerLease = null; }
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
try { await StopAsync().ConfigureAwait(false); }
|
|
finally { _ownerLease?.Dispose(); _ownerLease = null; }
|
|
}
|
|
}
|