diff --git a/windows/ConnectionHealthPolicy.cs b/windows/ConnectionHealthPolicy.cs index ab9b660..50aeace 100644 --- a/windows/ConnectionHealthPolicy.cs +++ b/windows/ConnectionHealthPolicy.cs @@ -1,60 +1,69 @@ -namespace UCVL.VPNPlus; - -// Advisory after connection only; never an Internet-site gate in StartAsync. -// A delayed probe must not undo a user's disconnect or judge a different core. -internal sealed class ConnectionHealthPolicy -{ - internal enum Decision { Ignore, Keep, Repair, PendingAdvisory, WebsiteUnavailable, TailnetEgressUnverified, Switch } - internal long Revision { get; private set; } - internal int Failures { get; private set; } - internal bool HasBeenHealthy { get; private set; } - private long _nextProbe; - private Decision? _advisoryCandidate; - internal void Invalidate() - { - Revision++; - _advisoryCandidate = null; - } - internal void BeginCore(long now) - { - Invalidate(); Failures = 0; HasBeenHealthy = false; - _nextProbe = now + 5_000; - } - internal void ResetFailures() => Failures = 0; - internal bool IsDue(long now, bool running) => !running || now >= _nextProbe; - internal Decision Observe(long revision, int? testedCore, int? currentCore, - bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false, - bool activeTailnet = false, bool businessUnavailable = false) - { - if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting) - return Decision.Ignore; - if (healthy && currentCore is not null) { - _advisoryCandidate = null; - HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000; - return Decision.Keep; - } - if (currentCore is not null && (businessUnavailable && proxyHealthy || activeTailnet && !proxyHealthy)) { - // Third-party HTTP diagnostics cannot identify an active Tailnet - // transport failure. The bounded periodic ICMP policy owns fallback. - Failures = 0; _nextProbe = now + 20_000; - var advisory = proxyHealthy ? Decision.WebsiteUnavailable : Decision.TailnetEgressUnverified; - var confirmed = _advisoryCandidate == advisory; - _advisoryCandidate = advisory; - return confirmed ? advisory : Decision.PendingAdvisory; - } - _advisoryCandidate = null; - if (proxyHealthy && currentCore is not null) { - // Do not punish/restart a working node for a local smart-rule fault. - // The UI must show degraded routing, not declare the business path healthy. - Failures = 0; _nextProbe = now + 20_000; - return Decision.Repair; - } - Failures++; - _nextProbe = now + (HasBeenHealthy ? 20_000 : 5_000); - // Established connections retain tolerance for two transient rounds. - // An unverified newly selected node gets one retry, not a minute of - // false connected state; a dead core does not wait for HTTP timeouts. - return currentCore is null || Failures >= (HasBeenHealthy ? 3 : 2) - ? Decision.Switch : Decision.Keep; - } -} +namespace UCVL.VPNPlus; + +// Advisory after connection only; never an Internet-site gate in StartAsync. +// A delayed probe must not undo a user's disconnect or judge a different core. +internal sealed class ConnectionHealthPolicy +{ + internal enum Decision { Ignore, Keep, Repair, PendingAdvisory, WebsiteUnavailable, TailnetEgressUnverified, Switch } + internal long Revision { get; private set; } + internal int Failures { get; private set; } + internal bool HasBeenHealthy { get; private set; } + private long _nextProbe; + private Decision? _advisoryCandidate; + internal void Invalidate() + { + Revision++; + _advisoryCandidate = null; + } + internal void BeginCore(long now) + { + Invalidate(); Failures = 0; HasBeenHealthy = false; + _nextProbe = now + 5_000; + } + internal void ResetFailures() => Failures = 0; + internal bool IsDue(long now, bool running) => !running || now >= _nextProbe; + internal Decision Observe(long revision, int? testedCore, int? currentCore, + bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false, + bool activeTailnet = false, bool businessUnavailable = false) + { + if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting) + return Decision.Ignore; + if (healthy && currentCore is not null) { + _advisoryCandidate = null; + HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000; + return Decision.Keep; + } + if (currentCore is not null && businessUnavailable && proxyHealthy) { + Failures = 0; _nextProbe = now + 20_000; + const Decision advisory = Decision.WebsiteUnavailable; + var confirmed = _advisoryCandidate == advisory; + _advisoryCandidate = advisory; + return confirmed ? advisory : Decision.PendingAdvisory; + } + _advisoryCandidate = null; + if (proxyHealthy && currentCore is not null) { + // Do not punish/restart a working node for a local smart-rule fault. + // The UI must show degraded routing, not declare the business path healthy. + Failures = 0; _nextProbe = now + 20_000; + return Decision.Repair; + } + if (currentCore is not null && activeTailnet) { + // A verified proxy can survive one failed round without moving. + // Three rounds with no forced HTTPS response request same-node fallback. + _advisoryCandidate = null; + _nextProbe = now + 20_000; + return ++Failures switch { + 1 => Decision.PendingAdvisory, + 2 => Decision.TailnetEgressUnverified, + _ => Decision.Switch, + }; + } + Failures++; + _nextProbe = now + (HasBeenHealthy ? 20_000 : 5_000); + // Established connections retain tolerance for two transient rounds. + // An unverified newly selected node gets one retry, not a minute of + // false connected state; a dead core does not wait for HTTP timeouts. + return currentCore is null || Failures >= (HasBeenHealthy ? 3 : 2) + ? Decision.Switch : Decision.Keep; + } +} diff --git a/windows/ConnectionHealthSelfTest.cs b/windows/ConnectionHealthSelfTest.cs index 39395f8..66a2400 100644 --- a/windows/ConnectionHealthSelfTest.cs +++ b/windows/ConnectionHealthSelfTest.cs @@ -1,90 +1,93 @@ -using System.Text.Json; - -namespace UCVL.VPNPlus; - -internal static class ConnectionHealthSelfTest -{ - internal static int Run() - { - var checks = new Dictionary(); - var policy = new ConnectionHealthPolicy(); - policy.BeginCore(1_000); - checks["new_core_has_short_background_grace"] = !policy.IsDue(5_999, true) && policy.IsDue(6_000, true); - checks["dead_core_does_not_wait_for_probe_due"] = policy.IsDue(1_001, false); - var revision = policy.Revision; - ConnectionHealthPolicy.Decision Observe(bool healthy, long now, int? core = 10) - => policy.Observe(policy.Revision, core, core, true, false, false, false, healthy, now); - checks["first_unverified_failure_is_tolerated"] = Observe(false,6_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 1; - checks["unverified_retry_is_bounded"] = !policy.IsDue(10_999,true) && policy.IsDue(11_000,true); - checks["second_unverified_failure_requests_switch"] = Observe(false,11_000) == ConnectionHealthPolicy.Decision.Switch; - policy.BeginCore(20_000); - checks["new_core_clears_previous_failure_history"] = !policy.HasBeenHealthy && policy.Failures == 0; - checks["healthy_transport_resets_failures"] = Observe(true,25_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; - checks["established_probe_cadence_remains_twenty_seconds"] = !policy.IsDue(44_999,true) && policy.IsDue(45_000,true); - checks["established_first_failure_tolerated"] = Observe(false,45_000) == ConnectionHealthPolicy.Decision.Keep; - checks["established_second_failure_tolerated"] = Observe(false,65_000) == ConnectionHealthPolicy.Decision.Keep; - checks["established_third_failure_switches"] = Observe(false,85_000) == ConnectionHealthPolicy.Decision.Switch; - checks["success_clears_consecutive_failures"] = Observe(true,90_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 0; - checks["old_revision_cannot_apply"] = policy.Observe(revision,10,10,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["different_core_result_cannot_apply"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["core_exited_during_probe_result_is_ignored"] = policy.Observe(policy.Revision,10,null,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["user_disconnect_cannot_be_undone_by_late_failure"] = policy.Observe(policy.Revision,10,10,false,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["busy_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,true,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["learning_transition_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,true,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["exit_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,false,true,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; - checks["ignored_results_do_not_modify_failures"] = policy.Failures == 0; - checks["dead_core_requests_switch"] = Observe(false,91_000,null) == ConnectionHealthPolicy.Decision.Switch; - policy.ResetFailures(); - checks["control_plane_deferral_retains_established_status"] = policy.HasBeenHealthy && policy.Failures == 0; - revision = policy.Revision; - policy.Invalidate(); - checks["new_attempt_invalidates_inflight_probe"] = policy.Observe(revision,10,10,true,false,false,false,true,92_000) == ConnectionHealthPolicy.Decision.Ignore; - policy.BeginCore(100_000); - checks["healthy_proxy_is_not_false_business_success"] = policy.Observe(policy.Revision,10,10,true,false,false,false,false,105_000,true) - == ConnectionHealthPolicy.Decision.Repair && !policy.HasBeenHealthy; - checks["local_fault_never_accumulates_node_penalty"] = Enumerable.Range(0,12).All(i => - policy.Observe(policy.Revision,10,10,true,false,false,false,false,125_000 + i*20_000,true) == ConnectionHealthPolicy.Decision.Repair) - && policy.Failures == 0; - checks["repaired_business_path_restores_health"] = Observe(true,400_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; - checks["proxy_failure_still_switches_after_threshold"] = Observe(false,420_000) == ConnectionHealthPolicy.Decision.Keep - && Observe(false,440_000) == ConnectionHealthPolicy.Decision.Keep && Observe(false,460_000) == ConnectionHealthPolicy.Decision.Switch; - checks["late_proxy_success_does_not_revive_dead_core"] = policy.Observe(policy.Revision,null,null,true,false,false,false,false,480_000,true) - == ConnectionHealthPolicy.Decision.Switch; - checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true) - == ConnectionHealthPolicy.Decision.Ignore; - ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10, - true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true); - ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10, - true, false, false, false, false, now, activeTailnet: true); - - policy.BeginCore(600_000); - checks["one_tailnet_egress_failure_waits_for_confirmation"] = TailnetEgress(605_000) == ConnectionHealthPolicy.Decision.PendingAdvisory - && !policy.IsDue(624_999, true) && policy.IsDue(625_000, true); - checks["repeated_egress_failures_do_not_rebuild_live_tailnet_core"] = Enumerable.Range(0, 12).All(i => - TailnetEgress(625_000 + i * 20_000) == ConnectionHealthPolicy.Decision.TailnetEgressUnverified) && policy.Failures == 0; - checks["site_failure_is_distinct_and_requires_its_own_confirmation"] = Website(900_000) == ConnectionHealthPolicy.Decision.PendingAdvisory - && Website(920_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable && policy.Failures == 0; - checks["success_resets_advisory_confirmation"] = Observe(true, 940_000) == ConnectionHealthPolicy.Decision.Keep - && Website(960_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; - checks["alternating_advisory_categories_do_not_confirm_each_other"] = TailnetEgress(980_000) == ConnectionHealthPolicy.Decision.PendingAdvisory - && Website(1_000_000) == ConnectionHealthPolicy.Decision.PendingAdvisory - && TailnetEgress(1_020_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; - checks["routing_repair_interrupts_advisory_confirmation"] = policy.Observe(policy.Revision, 10, 10, - true, false, false, false, false, 1_040_000, proxyHealthy: true) == ConnectionHealthPolicy.Decision.Repair - && TailnetEgress(1_060_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; - policy.BeginCore(1_080_000); - checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; - checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null, - true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch; - revision = policy.Revision; - policy.Invalidate(); - checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10, - true, false, false, false, true, 1_125_000, proxyHealthy: true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore; - foreach (var check in ConnectionAuthorizationSelfTest.Check()) checks.Add(check.Key, check.Value); - var passed = checks.Values.All(v => v); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"), - JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false, - authenticated_codex_tested=false, checks, passed },new JsonSerializerOptions{WriteIndented=true})); - return passed ? 0 : 17; - } -} +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class ConnectionHealthSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + var policy = new ConnectionHealthPolicy(); + policy.BeginCore(1_000); + checks["new_core_has_short_background_grace"] = !policy.IsDue(5_999, true) && policy.IsDue(6_000, true); + checks["dead_core_does_not_wait_for_probe_due"] = policy.IsDue(1_001, false); + var revision = policy.Revision; + ConnectionHealthPolicy.Decision Observe(bool healthy, long now, int? core = 10) + => policy.Observe(policy.Revision, core, core, true, false, false, false, healthy, now); + checks["first_unverified_failure_is_tolerated"] = Observe(false,6_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 1; + checks["unverified_retry_is_bounded"] = !policy.IsDue(10_999,true) && policy.IsDue(11_000,true); + checks["second_unverified_failure_requests_switch"] = Observe(false,11_000) == ConnectionHealthPolicy.Decision.Switch; + policy.BeginCore(20_000); + checks["new_core_clears_previous_failure_history"] = !policy.HasBeenHealthy && policy.Failures == 0; + checks["healthy_transport_resets_failures"] = Observe(true,25_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; + checks["established_probe_cadence_remains_twenty_seconds"] = !policy.IsDue(44_999,true) && policy.IsDue(45_000,true); + checks["established_first_failure_tolerated"] = Observe(false,45_000) == ConnectionHealthPolicy.Decision.Keep; + checks["established_second_failure_tolerated"] = Observe(false,65_000) == ConnectionHealthPolicy.Decision.Keep; + checks["established_third_failure_switches"] = Observe(false,85_000) == ConnectionHealthPolicy.Decision.Switch; + checks["success_clears_consecutive_failures"] = Observe(true,90_000) == ConnectionHealthPolicy.Decision.Keep && policy.Failures == 0; + checks["old_revision_cannot_apply"] = policy.Observe(revision,10,10,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["different_core_result_cannot_apply"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["core_exited_during_probe_result_is_ignored"] = policy.Observe(policy.Revision,10,null,true,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["user_disconnect_cannot_be_undone_by_late_failure"] = policy.Observe(policy.Revision,10,10,false,false,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["busy_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,true,false,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["learning_transition_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,true,false,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["exit_result_is_ignored"] = policy.Observe(policy.Revision,10,10,true,false,false,true,false,91_000) == ConnectionHealthPolicy.Decision.Ignore; + checks["ignored_results_do_not_modify_failures"] = policy.Failures == 0; + checks["dead_core_requests_switch"] = Observe(false,91_000,null) == ConnectionHealthPolicy.Decision.Switch; + policy.ResetFailures(); + checks["control_plane_deferral_retains_established_status"] = policy.HasBeenHealthy && policy.Failures == 0; + revision = policy.Revision; + policy.Invalidate(); + checks["new_attempt_invalidates_inflight_probe"] = policy.Observe(revision,10,10,true,false,false,false,true,92_000) == ConnectionHealthPolicy.Decision.Ignore; + policy.BeginCore(100_000); + checks["healthy_proxy_is_not_false_business_success"] = policy.Observe(policy.Revision,10,10,true,false,false,false,false,105_000,true) + == ConnectionHealthPolicy.Decision.Repair && !policy.HasBeenHealthy; + checks["local_fault_never_accumulates_node_penalty"] = Enumerable.Range(0,12).All(i => + policy.Observe(policy.Revision,10,10,true,false,false,false,false,125_000 + i*20_000,true) == ConnectionHealthPolicy.Decision.Repair) + && policy.Failures == 0; + checks["repaired_business_path_restores_health"] = Observe(true,400_000) == ConnectionHealthPolicy.Decision.Keep && policy.HasBeenHealthy; + checks["proxy_failure_still_switches_after_threshold"] = Observe(false,420_000) == ConnectionHealthPolicy.Decision.Keep + && Observe(false,440_000) == ConnectionHealthPolicy.Decision.Keep && Observe(false,460_000) == ConnectionHealthPolicy.Decision.Switch; + checks["late_proxy_success_does_not_revive_dead_core"] = policy.Observe(policy.Revision,null,null,true,false,false,false,false,480_000,true) + == ConnectionHealthPolicy.Decision.Switch; + checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true) + == ConnectionHealthPolicy.Decision.Ignore; + ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true); + ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, now, activeTailnet: true); + + policy.BeginCore(600_000); + checks["one_tailnet_egress_failure_waits_for_confirmation"] = TailnetEgress(605_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && !policy.IsDue(624_999, true) && policy.IsDue(625_000, true) && policy.Failures == 1; + checks["confirmed_tailnet_egress_outage_requests_same_node_fallback"] = + TailnetEgress(625_000) == ConnectionHealthPolicy.Decision.TailnetEgressUnverified + && TailnetEgress(645_000) == ConnectionHealthPolicy.Decision.Switch; + checks["tailnet_success_breaks_consecutive_egress_outage"] = Observe(true, 665_000) == ConnectionHealthPolicy.Decision.Keep + && policy.Failures == 0 && TailnetEgress(685_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["site_failure_is_distinct_and_requires_its_own_confirmation"] = Website(900_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && Website(920_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable && policy.Failures == 0; + checks["success_resets_advisory_confirmation"] = Observe(true, 940_000) == ConnectionHealthPolicy.Decision.Keep + && Website(960_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["alternating_advisory_categories_do_not_confirm_each_other"] = TailnetEgress(980_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && Website(1_000_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && TailnetEgress(1_020_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["routing_repair_interrupts_advisory_confirmation"] = policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, 1_040_000, proxyHealthy: true) == ConnectionHealthPolicy.Decision.Repair + && TailnetEgress(1_060_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + policy.BeginCore(1_080_000); + checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null, + true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch; + revision = policy.Revision; + policy.Invalidate(); + checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10, + true, false, false, false, true, 1_125_000, proxyHealthy: true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore; + foreach (var check in ConnectionAuthorizationSelfTest.Check()) checks.Add(check.Key, check.Value); + var passed = checks.Values.All(v => v); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"), + JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false, + authenticated_codex_tested=false, checks, passed },new JsonSerializerOptions{WriteIndented=true})); + return passed ? 0 : 17; + } +} diff --git a/windows/DashboardInteractionSelfTest.cs b/windows/DashboardInteractionSelfTest.cs index 7bbd77c..9428667 100644 --- a/windows/DashboardInteractionSelfTest.cs +++ b/windows/DashboardInteractionSelfTest.cs @@ -122,6 +122,30 @@ internal sealed partial class MainForm SetNodeTrafficPermission(false); SetTailnetTrafficVisibility(false); checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; + + var emptyProfile = new Profile { RouteModes = profile.RouteModes }; + _wantConnected = true; + SetConnectionState(true, "已连接", "隔离刷新"); + UpdateProfile(emptyProfile, preserveSelections: true); + checks["empty_node_refresh_preserves_disconnect_action"] = _connectButton.Enabled && _selectionUiConnected; + + _wantConnected = false; + SetConnectionState(false, "未连接", "隔离刷新"); + UpdateProfile(emptyProfile, preserveSelections: true); + checks["empty_node_refresh_disables_new_connection"] = !_connectButton.Enabled; + + using (var attempt = new CancellationTokenSource()) + { + _connectionAttemptCancellation = attempt; + SetBusy(true); + UpdateProfile(profile, preserveSelections: true); + checks["profile_refresh_preserves_cancel_action_during_connect"] = _connectButton.Enabled; + attempt.Cancel(); + UpdateProfile(profile, preserveSelections: true); + checks["profile_refresh_disables_action_while_cancel_finishes"] = !_connectButton.Enabled; + _connectionAttemptCancellation = null; + } + SetBusy(false); ShowLogin(); checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120); RequestExit(); diff --git a/windows/LearningPolicy.cs b/windows/LearningPolicy.cs index 590f14c..ae0fc3e 100644 --- a/windows/LearningPolicy.cs +++ b/windows/LearningPolicy.cs @@ -1,112 +1,116 @@ -using System.Net; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.RegularExpressions; - -namespace UCVL.VPNPlus; - -// Minimal transport observations, not URL/history collection or an HTTP status classifier. -internal static class LearningPolicy -{ - private static readonly Regex Failure = new(@"proxy/freedom: failed to open connection to (?tcp|udp):(?\[[0-9a-fA-F:]+\]|[A-Za-z0-9._-]+):(?\d{1,5})", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private static readonly Regex DirectAttempt = new(@"app/dispatcher: (?:Hit route rule: \[[^\[\]\r\n]{1,200}\] so )?taking detour \[direct\] for \[tcp:(?[A-Za-z0-9._-]+):443\]", RegexOptions.Compiled); - - // An attempt is only a hint for a separate direct TLS check, never failure evidence. - // Probe outbounds have a different tag, preventing recursive self-observation. - internal static LearningObservation? ParseAttempt(string line, string node, string scope) - { - if (line.Length > 8192) return null; - var match = DirectAttempt.Match(line); - var target = match.Groups["target"].Value.TrimEnd('.').ToLowerInvariant(); - if (!match.Success || !Allowed("domain", target)) return null; - return new() { Target=target, TargetType="domain", Port=443, Network="tcp", AccessKind="http", Node=node, Scope=scope }; - } - internal static bool PublicIp(IPAddress ip) - { - if (ip.IsIPv4MappedToIPv6) return PublicIp(ip.MapToIPv4()); - var b = ip.GetAddressBytes(); - if (b.Length != 4) return false; // Do not automatically promote IPv6 without equivalent validation. - return b[0] is > 0 and < 224 && b[0] != 10 && b[0] != 127 - && !(b[0] == 100 && b[1] is >= 64 and <= 127) - && !(b[0] == 169 && b[1] == 254) && !(b[0] == 172 && b[1] is >= 16 and <= 31) - && !(b[0] == 192 && (b[1] == 168 || b[1] == 0 || b[1] == 2)) - && !(b[0] == 198 && (b[1] is 18 or 19 || b[1] == 51 && b[2] == 100)) - && !(b[0] == 203 && b[1] == 0 && b[2] == 113); - } - internal static bool Allowed(string kind, string target) - { - if (kind == "ip") return IPAddress.TryParse(target, out var ip) && PublicIp(ip); - if (kind != "domain" || IPAddress.TryParse(target, out _) || target.Length > 253 || !target.Contains('.')) return false; - if (target.Split('.').Any(label => !Regex.IsMatch(label, "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$"))) return false; - return !new[] { "toplc.cn", "ucvl.cn", "ucvl.net", "local", "localhost", "lan", "internal", "home", "invalid", "test", "example", "arpa", "onion" } - .Any(suffix => target == suffix || target.EndsWith("." + suffix, StringComparison.Ordinal)); - } - internal static LearningObservation? Parse(string line, string node, string scope) - { - if (line.Length > 8192) return null; - var match = Failure.Match(line); - if (!match.Success || !int.TryParse(match.Groups["port"].Value, out var port) || port is < 1 or > 65535) return null; - var target = match.Groups["target"].Value.Trim('[', ']').TrimEnd('.').ToLowerInvariant(); - var type = IPAddress.TryParse(target, out _) ? "ip" : "domain"; - if (!Allowed(type, target)) return null; - var failure = line.Contains("timeout", StringComparison.OrdinalIgnoreCase) || line.Contains("timed out", StringComparison.OrdinalIgnoreCase) ? "timeout" - : line.Contains("reset", StringComparison.OrdinalIgnoreCase) ? "reset" - : line.Contains("lookup", StringComparison.OrdinalIgnoreCase) || line.Contains("dns", StringComparison.OrdinalIgnoreCase) ? "dns" - : line.Contains("unreachable", StringComparison.OrdinalIgnoreCase) ? "unreachable" : "other"; - return new LearningObservation { Target = target, TargetType = type, Port = port, - Network = match.Groups["network"].Value.ToLowerInvariant(), AccessKind = port is 80 or 443 ? "http" : "socket", - FailureKind = failure, Node = node, Scope = scope }; - } - internal static string Merge(string baseConfig, RoutingManifest manifest) - { - if (manifest.Contract != 1 || !Regex.IsMatch(manifest.Revision, "^[0-9a-f]{64}$") || manifest.Rules.Count > 2048) - throw new InvalidDataException("智能规则版本或容量无效。"); - var root = JsonNode.Parse(baseConfig)!.AsObject(); - var rules = root["routing"]?["rules"]?.AsArray() ?? throw new InvalidDataException("缺少原路由。"); - // Server tags only the replaceable learned bank; preserve LAN/company/DNS/default rules. - for (var i = rules.Count - 1; i >= 0; i--) - if (rules[i]?["ruleTag"]?.GetValue() == "ucvl-learned") rules.RemoveAt(i); - var domains = new JsonArray(); var ips = new JsonArray(); - foreach (var entry in manifest.Rules) - { - if (!Allowed(entry.TargetType, entry.Target) || entry.MatchMode is not ("exact" or "suffix") - || entry.TargetType == "ip" && entry.MatchMode != "exact") throw new InvalidDataException("不安全的智能目标。"); - if (entry.TargetType == "domain") domains.Add((entry.MatchMode == "suffix" ? "domain:" : "full:") + entry.Target); - else ips.Add(entry.Target + "/32"); - } - // After private-address DIRECT. Never insert ahead of this safety boundary. - var insertion = rules.Count > 0 ? 1 : 0; - if (ips.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["ip"] = ips, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); - if (domains.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["domain"] = domains, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); - return root.ToJsonString(); - } - - internal static string DirectFirst(string baseConfig) - { - var root = JsonNode.Parse(baseConfig)!.AsObject(); - if (root["routing"]?["rules"] is JsonArray rules) - for (var i = rules.Count - 1; i >= 0; i--) - { - var rule = rules[i]!.AsObject(); - if (rule["ruleTag"]?.GetValue() == "ucvl-learned" || rule["outboundTag"]?.GetValue() == "proxy" - && (rule["domain"] is not null || rule["ip"] is not null) - && rule.All(pair => pair.Key is "type" or "domain" or "ip" or "outboundTag" or "ruleTag")) - rules.RemoveAt(i); // Shared/manual destination lists are hints in direct-first smart mode. - } - return root.ToJsonString(); - } -} - -internal sealed class RoutingManifest -{ - [System.Text.Json.Serialization.JsonPropertyName("contract")] public int Contract { get; init; } - [System.Text.Json.Serialization.JsonPropertyName("mode")] public string Mode { get; init; } = ""; - [System.Text.Json.Serialization.JsonPropertyName("revision")] public string Revision { get; init; } = ""; - [System.Text.Json.Serialization.JsonPropertyName("rules")] public List Rules { get; init; } = []; -} -internal sealed class RoutingTarget -{ - [System.Text.Json.Serialization.JsonPropertyName("target_type")] public string TargetType { get; init; } = ""; - [System.Text.Json.Serialization.JsonPropertyName("target")] public string Target { get; init; } = ""; - [System.Text.Json.Serialization.JsonPropertyName("match_mode")] public string MatchMode { get; init; } = ""; -} +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace UCVL.VPNPlus; + +// Minimal transport observations, not URL/history collection or an HTTP status classifier. +internal static class LearningPolicy +{ + private static readonly Regex Failure = new(@"proxy/freedom: failed to open connection to (?tcp|udp):(?\[[0-9a-fA-F:]+\]|[A-Za-z0-9._-]+):(?\d{1,5})", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static readonly Regex DirectAttempt = new(@"app/dispatcher: (?:Hit route rule: \[[^\[\]\r\n]{1,200}\] so )?taking detour \[direct\] for \[tcp:(?[A-Za-z0-9._-]+):443\]", RegexOptions.Compiled); + + // An attempt is only a hint for a separate direct TLS check, never failure evidence. + // Probe outbounds have a different tag, preventing recursive self-observation. + internal static LearningObservation? ParseAttempt(string line, string node, string scope) + { + if (line.Length > 8192) return null; + var match = DirectAttempt.Match(line); + var target = match.Groups["target"].Value.TrimEnd('.').ToLowerInvariant(); + if (!match.Success || !Allowed("domain", target)) return null; + return new() { Target=target, TargetType="domain", Port=443, Network="tcp", AccessKind="http", Node=node, Scope=scope }; + } + internal static bool PublicIp(IPAddress ip) + { + if (ip.IsIPv4MappedToIPv6) return PublicIp(ip.MapToIPv4()); + var b = ip.GetAddressBytes(); + if (b.Length != 4) return false; // Do not automatically promote IPv6 without equivalent validation. + return b[0] is > 0 and < 224 && b[0] != 10 && b[0] != 127 + && !(b[0] == 100 && b[1] is >= 64 and <= 127) + && !(b[0] == 169 && b[1] == 254) && !(b[0] == 172 && b[1] is >= 16 and <= 31) + && !(b[0] == 192 && (b[1] == 168 || b[1] == 0 || b[1] == 2)) + && !(b[0] == 198 && (b[1] is 18 or 19 || b[1] == 51 && b[2] == 100)) + && !(b[0] == 203 && b[1] == 0 && b[2] == 113); + } + internal static bool Allowed(string kind, string target) => IsValidTarget(kind, target) + && !(kind == "domain" && TailnetDnsPolicy.IsProtectedDomain(target)); + + private static bool IsValidTarget(string kind, string target) + { + if (kind == "ip") return IPAddress.TryParse(target, out var ip) && PublicIp(ip); + if (kind != "domain" || IPAddress.TryParse(target, out _) || target.Length > 253 || !target.Contains('.')) return false; + if (target.Split('.').Any(label => !Regex.IsMatch(label, "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$"))) return false; + return !new[] { "toplc.cn", "ucvl.cn", "ucvl.net", "local", "localhost", "lan", "internal", "home", "invalid", "test", "example", "arpa", "onion" } + .Any(suffix => target == suffix || target.EndsWith("." + suffix, StringComparison.Ordinal)); + } + internal static LearningObservation? Parse(string line, string node, string scope) + { + if (line.Length > 8192) return null; + var match = Failure.Match(line); + if (!match.Success || !int.TryParse(match.Groups["port"].Value, out var port) || port is < 1 or > 65535) return null; + var target = match.Groups["target"].Value.Trim('[', ']').TrimEnd('.').ToLowerInvariant(); + var type = IPAddress.TryParse(target, out _) ? "ip" : "domain"; + if (!Allowed(type, target)) return null; + var failure = line.Contains("timeout", StringComparison.OrdinalIgnoreCase) || line.Contains("timed out", StringComparison.OrdinalIgnoreCase) ? "timeout" + : line.Contains("reset", StringComparison.OrdinalIgnoreCase) ? "reset" + : line.Contains("lookup", StringComparison.OrdinalIgnoreCase) || line.Contains("dns", StringComparison.OrdinalIgnoreCase) ? "dns" + : line.Contains("unreachable", StringComparison.OrdinalIgnoreCase) ? "unreachable" : "other"; + return new LearningObservation { Target = target, TargetType = type, Port = port, + Network = match.Groups["network"].Value.ToLowerInvariant(), AccessKind = port is 80 or 443 ? "http" : "socket", + FailureKind = failure, Node = node, Scope = scope }; + } + internal static string Merge(string baseConfig, RoutingManifest manifest) + { + if (manifest.Contract != 1 || !Regex.IsMatch(manifest.Revision, "^[0-9a-f]{64}$") || manifest.Rules.Count > 2048) + throw new InvalidDataException("智能规则版本或容量无效。"); + var root = JsonNode.Parse(baseConfig)!.AsObject(); + var rules = root["routing"]?["rules"]?.AsArray() ?? throw new InvalidDataException("缺少原路由。"); + // Server tags only the replaceable learned bank; preserve LAN/company/DNS/default rules. + for (var i = rules.Count - 1; i >= 0; i--) + if (rules[i]?["ruleTag"]?.GetValue() == "ucvl-learned") rules.RemoveAt(i); + var domains = new JsonArray(); var ips = new JsonArray(); + foreach (var entry in manifest.Rules) + { + if (!IsValidTarget(entry.TargetType, entry.Target) || entry.MatchMode is not ("exact" or "suffix") + || entry.TargetType == "ip" && entry.MatchMode != "exact") throw new InvalidDataException("不安全的智能目标。"); + if (entry.TargetType == "domain" && TailnetDnsPolicy.IsProtectedDomain(entry.Target)) continue; + if (entry.TargetType == "domain") domains.Add((entry.MatchMode == "suffix" ? "domain:" : "full:") + entry.Target); + else ips.Add(entry.Target + "/32"); + } + // After private-address DIRECT. Never insert ahead of this safety boundary. + var insertion = rules.Count > 0 ? 1 : 0; + if (ips.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["ip"] = ips, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); + if (domains.Count > 0) rules.Insert(insertion, new JsonObject { ["type"] = "field", ["domain"] = domains, ["network"] = "tcp", ["port"] = "443", ["outboundTag"] = "proxy", ["ruleTag"] = "ucvl-learned" }); + return root.ToJsonString(); + } + + internal static string DirectFirst(string baseConfig) + { + var root = JsonNode.Parse(baseConfig)!.AsObject(); + if (root["routing"]?["rules"] is JsonArray rules) + for (var i = rules.Count - 1; i >= 0; i--) + { + var rule = rules[i]!.AsObject(); + if (rule["ruleTag"]?.GetValue() == "ucvl-learned" || rule["outboundTag"]?.GetValue() == "proxy" + && (rule["domain"] is not null || rule["ip"] is not null) + && rule.All(pair => pair.Key is "type" or "domain" or "ip" or "outboundTag" or "ruleTag")) + rules.RemoveAt(i); // Shared/manual destination lists are hints in direct-first smart mode. + } + return root.ToJsonString(); + } +} + +internal sealed class RoutingManifest +{ + [System.Text.Json.Serialization.JsonPropertyName("contract")] public int Contract { get; init; } + [System.Text.Json.Serialization.JsonPropertyName("mode")] public string Mode { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("revision")] public string Revision { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("rules")] public List Rules { get; init; } = []; +} +internal sealed class RoutingTarget +{ + [System.Text.Json.Serialization.JsonPropertyName("target_type")] public string TargetType { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("target")] public string Target { get; init; } = ""; + [System.Text.Json.Serialization.JsonPropertyName("match_mode")] public string MatchMode { get; init; } = ""; +} diff --git a/windows/LearningSelfTest.cs b/windows/LearningSelfTest.cs index 6651d50..d9f4b6a 100644 --- a/windows/LearningSelfTest.cs +++ b/windows/LearningSelfTest.cs @@ -1,93 +1,152 @@ -using System.Text.Json; -using System.Text.Json.Nodes; - -namespace UCVL.VPNPlus; - -internal static class LearningSelfTest -{ - internal static int Run() - { - var checks = new Dictionary(); - const string baseConfig = """{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"socks","settings":{"servers":[{"address":"8.8.8.8","port":443}]}},{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"},{"type":"field","domain":["domain:openai.com"],"outboundTag":"proxy","ruleTag":"ucvl-learned"},{"type":"field","domain":["geosite:category-ads-all"],"outboundTag":"block"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]}}"""; - bool Throws(Action action) { try { action(); return false; } catch (InvalidDataException) { return true; } } - LearningObservation? Parse(string text) => LearningPolicy.Parse(text, "fixture", "public"); - var line = "[Info] [123] app/proxyman/outbound: failed to process outbound traffic > proxy/freedom: failed to open connection to tcp:learn.example.com:443 > i/o timeout"; - var parsed = Parse(line); - checks["freedom_without_direct_detected"] = parsed is { Target: "learn.example.com", FailureKind: "timeout", Port: 443 }; - checks["acceptance_is_not_success"] = Parse("from tcp:127.0.0.1:777 accepted tcp:learn.example.com:443 [socks-in -> direct]") is null; - checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null; - checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null; - checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "172.16.0.111")) is null; - checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null; - checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com"; - checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null; - const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]"; - checks["tls_attempt_detected_before_failure_log"] = LearningPolicy.ParseAttempt(attempt,"fixture","public")?.Target == "tls-gap.example.com"; - var tagged = attempt.Replace("app/dispatcher: ", "app/dispatcher: Hit route rule: [ucvl-fixture-0] so "); - checks["real_tagged_attempt_detected"] = LearningPolicy.ParseAttempt(tagged,"fixture","public")?.Target == "tls-gap.example.com"; - checks["tagged_proxy_not_collected"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[proxy]"),"fixture","public") is null; - checks["tagged_probe_not_recursive"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[ucvl-learning-direct]"),"fixture","public") is null; - checks["oversized_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", new string('x',201)),"fixture","public") is null; - checks["multiline_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", "ucvl-\n0"),"fixture","public") is null; - checks["attempt_is_not_failure_evidence"] = Parse(attempt) is null; - checks["probe_not_recursively_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[ucvl-learning-direct]"),"fixture","public") is null; - checks["proxy_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[proxy]"),"fixture","public") is null; - checks["private_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","172.16.0.111"),"fixture","public") is null; - checks["non_tls_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace(":443]",":80]"),"fixture","public") is null; - checks["no_url_collection"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","example.com/path?token=x"),"fixture","public") is null; - foreach (bool? directTls in new bool?[] { true, false, null }) - foreach (bool? proxyTls in new bool?[] { true, false, null }) - checks[$"pair_{directTls}_{proxyTls}"] = new ProxyProbe.PathComparison(directTls,proxyTls).ShouldProxy == (directTls == false && proxyTls == true); - var budget = new LearningProbeBudget(); - checks["four_concurrent_probes"] = Enumerable.Range(0,4).All(i=>budget.TryEnter("target"+i,100_000)); - checks["fifth_probe_bounded"] = !budget.TryEnter("fifth",100_000); - budget.Exit(); - checks["duplicate_suppressed"] = !budget.TryEnter("target0",100_001); - checks["free_slot_available"] = budget.TryEnter("fifth",100_001); - for(var i=0;i<4;i++) budget.Exit(); - checks["target_rechecked_after_cooldown"] = budget.TryEnter("target0",130_001); - budget.Exit(); - NetworkLearningLeaseSelfTest.AddChecks(checks); - var rate = new LearningProbeBudget(); - checks["sixty_per_minute"] = Enumerable.Range(0,60).All(i=>{ var allowed=rate.TryEnter("r"+i,100_000); if(allowed) rate.Exit(); return allowed; }); - checks["rate_limit_enforced"] = !rate.TryEnter("overflow",100_001); - checks["rate_window_recovers"] = rate.TryEnter("new",160_001); - foreach (var host in new[] { "127.0.0.1", "100.100.1.1", "192.168.1.1", "169.254.169.254", "::1", "::ffff:127.0.0.1", "203.0.113.1" }) - checks["nonpublic_ip_" + host] = !LearningPolicy.Allowed("ip", host); - foreach (var host in new[] { "172.16.0.111", "a.local", "a.invalid", "x.toplc.cn", "a.com/path", "a.com?secret=1", "bad_.com", "-bad.com" }) - checks["unsafe_domain_" + host] = !LearningPolicy.Allowed("domain", host); - checks["public_ip_allowed"] = LearningPolicy.Allowed("ip", "8.8.8.8"); - var direct = LearningPolicy.DirectFirst(baseConfig); - checks["new_network_removes_shared_forcing"] = !direct.Contains("openai.com") && direct.Contains("category-ads-all"); - var root = JsonNode.Parse(direct)!; - checks["private_and_default_stay_direct"] = root["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "direct" - && root["routing"]!["rules"]!.AsArray().Last()!["outboundTag"]!.GetValue() == "direct"; - RoutingManifest Rules(string target) => new() { Contract = 1, Mode = "direct_first_candidates", Revision = new string('a',64), - Rules = [new RoutingTarget { TargetType = "domain", Target = target, MatchMode = "exact" }] }; - var verified = LearningPolicy.Merge(direct, Rules("learn.example.com")); - checks["confirmed_exact_only"] = verified.Contains("full:learn.example.com") && !verified.Contains("domain:learn.example.com"); - checks["only_verified_tcp443_is_proxied"] = JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["port"]!.GetValue() == "443" - && JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["network"]!.GetValue() == "tcp"; - checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue() == "geoip:private"; - checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com"); - checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com"); - checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn"))); - checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) })); - var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!; - checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue() == "info" && runtime["log"]!["access"]!.GetValue() == "none"; - checks["probe_loopback_only"] = runtime["inbounds"]![0]!["listen"]!.GetValue() == "127.0.0.1"; - checks["probe_forced_proxy_after_private_guard"] = runtime["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" - && runtime["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "proxy"; - checks["no_tun_in_test"] = runtime["inbounds"]!.AsArray().All(x => x!["protocol"]!.GetValue() != "tun"); - var both = JsonNode.Parse(TunConfigBuilder.Build(direct,"Ethernet",true,includeTun:false,learningProbePort:18091,directProbePort:18092))!; - var directInbound = both["inbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-direct-probe")!; - checks["direct_probe_loopback_only"] = directInbound["listen"]!.GetValue() == "127.0.0.1"; - checks["direct_probe_no_sniff"] = directInbound["sniffing"] is null; - var directOutbound = both["outbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-learning-direct")!; - checks["direct_probe_binds_physical"] = directOutbound["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "Ethernet"; - checks["direct_probe_not_learned_route"] = both["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" && both["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "ucvl-learning-direct"; - var report = new { scope="isolated policy tests; no current core or OS networking changed", passed=checks.Values.All(x=>x), checks }; - File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"learning-self-test.json"), JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true})); - return report.passed ? 0 : 31; - } -} +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace UCVL.VPNPlus; + +internal static class LearningSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + const string baseConfig = """{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"socks","settings":{"servers":[{"address":"8.8.8.8","port":443}]}},{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[{"type":"field","ip":["geoip:private"],"outboundTag":"direct"},{"type":"field","domain":["domain:openai.com"],"outboundTag":"proxy","ruleTag":"ucvl-learned"},{"type":"field","domain":["geosite:category-ads-all"],"outboundTag":"block"},{"type":"field","network":"tcp,udp","outboundTag":"direct"}]}}"""; + bool Throws(Action action) { try { action(); return false; } catch (InvalidDataException) { return true; } } + LearningObservation? Parse(string text) => LearningPolicy.Parse(text, "fixture", "public"); + var line = "[Info] [123] app/proxyman/outbound: failed to process outbound traffic > proxy/freedom: failed to open connection to tcp:learn.example.com:443 > i/o timeout"; + var parsed = Parse(line); + checks["freedom_without_direct_detected"] = parsed is { Target: "learn.example.com", FailureKind: "timeout", Port: 443 }; + checks["acceptance_is_not_success"] = Parse("from tcp:127.0.0.1:777 accepted tcp:learn.example.com:443 [socks-in -> direct]") is null; + checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null; + checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null; + checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "172.16.0.111")) is null; + checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null; + checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com"; + checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null; + const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]"; + checks["tls_attempt_detected_before_failure_log"] = LearningPolicy.ParseAttempt(attempt,"fixture","public")?.Target == "tls-gap.example.com"; + var tagged = attempt.Replace("app/dispatcher: ", "app/dispatcher: Hit route rule: [ucvl-fixture-0] so "); + checks["real_tagged_attempt_detected"] = LearningPolicy.ParseAttempt(tagged,"fixture","public")?.Target == "tls-gap.example.com"; + checks["tagged_proxy_not_collected"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[proxy]"),"fixture","public") is null; + checks["tagged_probe_not_recursive"] = LearningPolicy.ParseAttempt(tagged.Replace("[direct]", "[ucvl-learning-direct]"),"fixture","public") is null; + checks["oversized_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", new string('x',201)),"fixture","public") is null; + checks["multiline_tag_rejected"] = LearningPolicy.ParseAttempt(tagged.Replace("ucvl-fixture-0", "ucvl-\n0"),"fixture","public") is null; + checks["attempt_is_not_failure_evidence"] = Parse(attempt) is null; + checks["probe_not_recursively_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[ucvl-learning-direct]"),"fixture","public") is null; + checks["proxy_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[proxy]"),"fixture","public") is null; + checks["private_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","172.16.0.111"),"fixture","public") is null; + checks["non_tls_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace(":443]",":80]"),"fixture","public") is null; + checks["no_url_collection"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","example.com/path?token=x"),"fixture","public") is null; + foreach (bool? directTls in new bool?[] { true, false, null }) + foreach (bool? proxyTls in new bool?[] { true, false, null }) + checks[$"pair_{directTls}_{proxyTls}"] = new ProxyProbe.PathComparison(directTls,proxyTls).ShouldProxy == (directTls == false && proxyTls == true); + var budget = new LearningProbeBudget(); + checks["four_concurrent_probes"] = Enumerable.Range(0,4).All(i=>budget.TryEnter("target"+i,100_000)); + checks["fifth_probe_bounded"] = !budget.TryEnter("fifth",100_000); + budget.Exit(); + checks["duplicate_suppressed"] = !budget.TryEnter("target0",100_001); + checks["free_slot_available"] = budget.TryEnter("fifth",100_001); + for(var i=0;i<4;i++) budget.Exit(); + checks["target_rechecked_after_cooldown"] = budget.TryEnter("target0",130_001); + budget.Exit(); + NetworkLearningLeaseSelfTest.AddChecks(checks); + var rate = new LearningProbeBudget(); + checks["sixty_per_minute"] = Enumerable.Range(0,60).All(i=>{ var allowed=rate.TryEnter("r"+i,100_000); if(allowed) rate.Exit(); return allowed; }); + checks["rate_limit_enforced"] = !rate.TryEnter("overflow",100_001); + checks["rate_window_recovers"] = rate.TryEnter("new",160_001); + foreach (var host in new[] { "127.0.0.1", "100.100.1.1", "192.168.1.1", "169.254.169.254", "::1", "::ffff:127.0.0.1", "203.0.113.1" }) + checks["nonpublic_ip_" + host] = !LearningPolicy.Allowed("ip", host); + foreach (var host in new[] { "172.16.0.111", "a.local", "a.invalid", "x.toplc.cn", "a.com/path", "a.com?secret=1", "bad_.com", "-bad.com" }) + checks["unsafe_domain_" + host] = !LearningPolicy.Allowed("domain", host); + checks["public_ip_allowed"] = LearningPolicy.Allowed("ip", "8.8.8.8"); + var direct = LearningPolicy.DirectFirst(baseConfig); + checks["new_network_removes_shared_forcing"] = !direct.Contains("openai.com") && direct.Contains("category-ads-all"); + var root = JsonNode.Parse(direct)!; + checks["private_and_default_stay_direct"] = root["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "direct" + && root["routing"]!["rules"]!.AsArray().Last()!["outboundTag"]!.GetValue() == "direct"; + RoutingManifest Rules(string target) => new() { Contract = 1, Mode = "direct_first_candidates", Revision = new string('a',64), + Rules = [new RoutingTarget { TargetType = "domain", Target = target, MatchMode = "exact" }] }; + var verified = LearningPolicy.Merge(direct, Rules("learn.example.com")); + checks["confirmed_exact_only"] = verified.Contains("full:learn.example.com") && !verified.Contains("domain:learn.example.com"); + checks["only_verified_tcp443_is_proxied"] = JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["port"]!.GetValue() == "443" + && JsonNode.Parse(verified)!["routing"]!["rules"]![1]!["network"]!.GetValue() == "tcp"; + checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue() == "geoip:private"; + checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com"); + checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com"); + checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn"))); + checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) })); + var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!; + checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue() == "info" && runtime["log"]!["access"]!.GetValue() == "none"; + checks["probe_loopback_only"] = runtime["inbounds"]![0]!["listen"]!.GetValue() == "127.0.0.1"; + checks["probe_forced_proxy_after_private_guard"] = runtime["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" + && runtime["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "proxy"; + checks["no_tun_in_test"] = runtime["inbounds"]!.AsArray().All(x => x!["protocol"]!.GetValue() != "tun"); + var both = JsonNode.Parse(TunConfigBuilder.Build(direct,"Ethernet",true,includeTun:false,learningProbePort:18091,directProbePort:18092))!; + var directInbound = both["inbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-direct-probe")!; + checks["direct_probe_loopback_only"] = directInbound["listen"]!.GetValue() == "127.0.0.1"; + checks["direct_probe_no_sniff"] = directInbound["sniffing"] is null; + var directOutbound = both["outbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue()=="ucvl-learning-direct")!; + checks["direct_probe_binds_physical"] = directOutbound["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "Ethernet"; + checks["direct_probe_not_learned_route"] = both["routing"]!["rules"]![0]!["outboundTag"]!.GetValue() == "block" && both["routing"]!["rules"]![1]!["outboundTag"]!.GetValue() == "ucvl-learning-direct"; + AddTailnetDnsChecks(checks); + var report = new { scope="isolated policy tests; no current core or OS networking changed", passed=checks.Values.All(x=>x), checks }; + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"learning-self-test.json"), JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true})); + return report.passed ? 0 : 31; + } + + private static void AddTailnetDnsChecks(Dictionary checks) + { + const string source = """ + {"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"freedom"},{"tag":"direct","protocol":"freedom"}], + "routing":{"rules":[{"type":"field","outboundTag":"proxy","domain":[ + "domain:tailscale.com","domain:TS.NET.","full:DeRp1.Tailscale.Com","full:device.tail.ts.net.", + "domain:com.","domain:net.","domain:docs.example.com","full:mytailscale.com","full:api.nots.net", + "regexp:.*"]},{"type":"field","network":"tcp,udp","outboundTag":"proxy"}]}} + """; + var namespaces = ProxyDnsPolicy.Namespaces(source, + [("domain", "legacy.tailscale.com"), ("domain", "legacy.Ts.NeT."), ("domain", "legacy.example.com")]); + checks["tailnet_namespaces_excluded_from_windows_proxy_dns"] = !new[] + { + "tailscale.com", ".tailscale.com", "TS.NET.", ".TS.NET.", "DeRp1.Tailscale.Com", "device.tail.ts.net.", + "legacy.tailscale.com", "legacy.Ts.NeT.", "com.", ".com.", "net.", ".net." + }.Any(host => namespaces.Contains(host, StringComparer.OrdinalIgnoreCase)); + checks["unrelated_windows_proxy_dns_namespaces_retained"] = new[] + { + "openai.com", ".openai.com", "docs.example.com", ".docs.example.com", "mytailscale.com", + "api.nots.net", "legacy.example.com" + }.All(namespaces.Contains); + checks["tailnet_domains_cannot_be_learned"] = new[] + { + "tailscale.com", "controlplane.tailscale.com", "ts.net", "peer.tail.ts.net" + }.All(host => !LearningPolicy.Allowed("domain", host)) && LearningPolicy.Allowed("domain", "mytailscale.com"); + var mixed = LearningPolicy.Merge(source, new RoutingManifest + { + Contract = 1, Revision = new string('0', 64), Rules = + [ + new RoutingTarget { TargetType = "domain", Target = "derp2.tailscale.com", MatchMode = "exact" }, + new RoutingTarget { TargetType = "domain", Target = "verified.example.com", MatchMode = "exact" } + ] + }); + checks["older_manifest_keeps_unrelated_candidates"] = mixed.Contains("full:verified.example.com") + && !mixed.Contains("full:derp2.tailscale.com"); + + var initial = TunConfigBuilder.Build(source, "Ethernet", false, includeTun: false); + var updated = TunConfigBuilder.BuildLearningRouting(source, "Ethernet", 18091, 18092, null); + foreach (var (phase, json) in new[] { ("initial", initial), ("learning_update", updated) }) + { + var rules = JsonNode.Parse(json)!["routing"]!["rules"]!.AsArray(); + var domainRules = rules.Where(rule => rule?["domain"] is JsonArray).ToArray(); + var direct = domainRules[0]!; + var matchers = direct["domain"]!.AsArray().Select(n => n!.GetValue()).ToArray(); + bool Matches(string host) => matchers.Any(m => + m.StartsWith("regexp:") && Regex.IsMatch(host, m[7..])); + checks[$"tailnet_domains_route_direct_before_{phase}_proxy_rules"] = + direct["outboundTag"]!.GetValue() == "direct" + && Matches("tailscale.com") && Matches("controlplane.Tailscale.Com.") + && Matches("derp1.tailscale.com") && Matches("ts.net") && Matches("peer.tail.ts.net.") + && !Matches("mytailscale.com") && !Matches("tailscale.com.example.com") && !Matches("api.nots.net"); + checks[$"unrelated_{phase}_proxy_patterns_retained"] = domainRules.Any(rule => + rule!["outboundTag"]!.GetValue() == "proxy" + && rule["domain"]!.AsArray().Any(n => n!.GetValue() == "regexp:.*")); + } + } +} diff --git a/windows/MainForm.NextGeneration.cs b/windows/MainForm.NextGeneration.cs index 21ac9a9..717cd48 100644 --- a/windows/MainForm.NextGeneration.cs +++ b/windows/MainForm.NextGeneration.cs @@ -1,106 +1,108 @@ -namespace UCVL.VPNPlus; - -internal sealed partial class MainForm -{ - private readonly LearningSyncCoordinator _learningSync = new(); - private int? _learningSyncCore; - private readonly TailnetReadinessPolicy _tailnetReadiness = new(); - private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false }; - - private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null) - { - _connectionAttemptCancellation?.Cancel(); - _accessToken = token; - if (token is null) - { - _runtimeRepairRequired = false; - _statusDetail.AccessibleDescription = null; - _runtimeRepairTip.SetToolTip(_statusDetail, null); - } - _connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64); - _connectionHealth.Invalidate(); - _sessionRevision++; - _nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true); - _nextNodeTrafficAttempt = DateTimeOffset.MinValue; - _learningSync.Reset(); - _learningSyncCore = null; - _tailnetReadiness.Reset(); - _tailnetReconnectItem.Enabled = false; - while (_observationQueue.TryDequeue(out _)) { } - } - - private bool TryCancelPendingConnection() - { - if (_connectionAttemptCancellation is not { } pending) return false; - _wantConnected = false; - pending.Cancel(); - _connectButton.Enabled = false; - _statusDetail.Text = "正在取消连接并恢复本机网络…"; - return true; - } - - private TailnetReadinessPolicy.Context ReadTailnetReadinessContext() => new( - _sessionRevision, _xray.CoreId, _wantConnected, - _busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting, - _xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null); - - private bool CanRetainAuthorizedCore() => _connectionAuthorization.CanRetain(DateTimeOffset.UtcNow, - Environment.TickCount64, _currentNodeIsPrivateAuxiliary, _privateLeaseDeadlineTicks); - - // The initial connection already tested this address. At ten-minute - // intervals repeat only the authorized IP ping; failure on the active path - // retries the same node's domain through the normal fresh-grant connector. - private async Task CheckTailnetReadinessAsync() - { - if (_runtimeRepairRequired || !_wantConnected || _uiOnly || _preview) return; - if (!PreflightClientRuntime(suppressDialogs: true)) return; - if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket)) - { - _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting; - return; - } - var reachable = false; - try - { - if (_xray.TailnetProbeEndpoint is { } endpoint) - reachable = await TailnetPingConfirmation.ProbeAsync( - pingToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, pingToken), _lifetime.Token); - } - catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } - catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } - var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable); - if (_exiting || IsDisposed || Disposing) return; - if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return; - _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy; - if (result == TailnetReadinessPolicy.Result.Fallback && _currentNodeSlug is { } slug) - { - _tailnetPreference.Failed(slug, Environment.TickCount64); - _tailnetPreference.CommitDomainFallback(); - _transportRetryNodeSlug = slug; - _connectionHealth.Invalidate(); - AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "ping_failed_same_node_domain_fallback", slug).SafeMessage); - await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); - return; - } - if (result == TailnetReadinessPolicy.Result.BecameReady) - { - AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage); - _notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复", - "现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info); - } - } - - private async Task ReconnectThroughPreferredTailnetAsync() - { - if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning - || _xray.UsesTailnet || !_tailnetReadiness.IsReady) return; - if (!PreflightClientRuntime(suppressDialogs: false, clearRepair: true)) return; - _tailnetReadiness.Reset(); - _tailnetReconnectItem.Enabled = false; - _tailnetPreference.ResetForUserConnect(); - _transportRetryNodeSlug = _currentNodeSlug; - // Explicit operator action, with fresh management authorization and the - // normal same-node/manual constraints. No silent migration of streams. - await ToggleConnectionAsync(reconnect: true); - } -} +namespace UCVL.VPNPlus; + +internal sealed partial class MainForm +{ + private readonly LearningSyncCoordinator _learningSync = new(); + private int? _learningSyncCore; + private readonly TailnetReadinessPolicy _tailnetReadiness = new(); + private bool _checkingTailnetReadiness; + private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false }; + + private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null) + { + _connectionAttemptCancellation?.Cancel(); + _accessToken = token; + if (token is null) + { + _runtimeRepairRequired = false; + _statusDetail.AccessibleDescription = null; + _runtimeRepairTip.SetToolTip(_statusDetail, null); + } + _connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64); + _connectionHealth.Invalidate(); + _sessionRevision++; + _nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true); + _nextNodeTrafficAttempt = DateTimeOffset.MinValue; + _learningSync.Reset(); + _learningSyncCore = null; + _tailnetReadiness.Reset(); + _tailnetReconnectItem.Enabled = false; + while (_observationQueue.TryDequeue(out _)) { } + } + + private bool TryCancelPendingConnection() + { + if (_connectionAttemptCancellation is not { } pending) return false; + _wantConnected = false; + pending.Cancel(); + _connectButton.Enabled = false; + _statusDetail.Text = "正在取消连接并恢复本机网络…"; + return true; + } + + private TailnetReadinessPolicy.Context ReadTailnetReadinessContext() => new( + _sessionRevision, _xray.CoreId, _wantConnected, + _busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting, + _xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null); + + private bool CanRetainAuthorizedCore() => _connectionAuthorization.CanRetain(DateTimeOffset.UtcNow, + Environment.TickCount64, _currentNodeIsPrivateAuxiliary, _privateLeaseDeadlineTicks); + + // Recheck the authorized proxy port every ten minutes. Confirmed failure + // on the active path retries the same node's public entry with a fresh grant. + private async Task CheckTailnetReadinessAsync() + { + if (_runtimeRepairRequired || !_wantConnected || _uiOnly || _preview) return; + if (!PreflightClientRuntime(suppressDialogs: true)) return; + if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket)) + { + _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting; + return; + } + var reachable = false; + _checkingTailnetReadiness = true; + try + { + if (_xray.TailnetProbeEndpoint is { } endpoint) + reachable = await TailnetEndpointConfirmation.ProbeAsync( + probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token); + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } + catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } + finally { _checkingTailnetReadiness = false; } + var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable); + if (_exiting || IsDisposed || Disposing) return; + if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return; + _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy; + if (result == TailnetReadinessPolicy.Result.Fallback && _currentNodeSlug is { } slug) + { + _tailnetPreference.Failed(slug, Environment.TickCount64); + _tailnetPreference.CommitDomainFallback(); + _transportRetryNodeSlug = slug; + _connectionHealth.Invalidate(); + AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "tcp_endpoint_failed_same_node_domain_fallback", slug).SafeMessage); + await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); + return; + } + if (result == TailnetReadinessPolicy.Result.BecameReady) + { + AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage); + _notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复", + "现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info); + } + } + + private async Task ReconnectThroughPreferredTailnetAsync() + { + if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning + || _xray.UsesTailnet || !_tailnetReadiness.IsReady) return; + if (!PreflightClientRuntime(suppressDialogs: false, clearRepair: true)) return; + _tailnetReadiness.Reset(); + _tailnetReconnectItem.Enabled = false; + _tailnetPreference.ResetForUserConnect(); + _transportRetryNodeSlug = _currentNodeSlug; + // Explicit operator action, with fresh management authorization and the + // normal same-node/manual constraints. No silent migration of streams. + await ToggleConnectionAsync(reconnect: true); + } +} diff --git a/windows/MainForm.Selection.cs b/windows/MainForm.Selection.cs index b14aa5b..74b6028 100644 --- a/windows/MainForm.Selection.cs +++ b/windows/MainForm.Selection.cs @@ -71,7 +71,7 @@ internal sealed partial class MainForm if (_availableNodeCount > 0 && _statusTitle.Text == "未连接") _statusDetail.Text = ManualSelection ? "手动选择节点后连接;不可用时不会自动换节点" - : _privateAuxiliaryNodes.Count > 0 ? "先检测济南办私有节点;不可用时自动选择公共节点" : "点击连接,AI 自动选择工作节点"; + : _publicNodeCount == 0 ? "点击连接,检测已授权的私有内网节点" : "点击连接,优先尝试后台分配节点的内网入口"; } if (_selectionUiConnected && !string.IsNullOrWhiteSpace(_currentNodeName)) _currentNodeLabel.Text = _currentNodeName; diff --git a/windows/MainForm.cs b/windows/MainForm.cs index f249ad8..b573cf4 100644 --- a/windows/MainForm.cs +++ b/windows/MainForm.cs @@ -176,7 +176,12 @@ internal sealed partial class MainForm : Form _updateTimer.Tick += async (_, _) => await CheckForClientUpdateAsync(); _updateTimer.Start(); _trafficTimer.Tick += async (_, _) => await RefreshTrafficAsync(); - _healthTimer.Tick += async (_, _) => { await CheckTailnetReadinessAsync(); await MaintainConnectionAsync(); }; + _healthTimer.Tick += async (_, _) => + { + if (_checkingTailnetReadiness) return; + await CheckTailnetReadinessAsync(); + await MaintainConnectionAsync(); + }; _trafficTimer.Start(); _healthTimer.Start(); InitializeHandover(); @@ -830,7 +835,8 @@ internal sealed partial class MainForm : Form if (_runtimeRepairRequired) return; await CheckUplinkAsync(); if (_uplinkChecking || _handover.Pending || _handover.Settling) return; - if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return; + if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _checkingTailnetReadiness + || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return; _healthChecking = true; try { @@ -869,6 +875,8 @@ internal sealed partial class MainForm : Form _tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64); _tailnetPreference.CommitDomainFallback(); _transportRetryNodeSlug = _currentNodeSlug; + AppPaths.WriteLog(new TransportDiagnostic("health_recovery", + "tailnet_egress_failed_same_node_domain_fallback", _currentNodeSlug).SafeMessage); } else { @@ -876,9 +884,10 @@ internal sealed partial class MainForm : Form if (!ManualSelection) _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure(); } } - SetConnectionState(false, "链路异常,正在恢复", ManualSelection - ? "正在重试手动指定节点,不会切换其他节点" - : "连续检查失败,向 vpn-ai 申请备用工作节点"); + var recoveryDetail = _transportRetryNodeSlug is not null + ? "内网代理出口持续异常,正在验证同一节点的公网入口" + : ManualSelection ? "正在重试手动指定节点" : "连续检查失败,正在申请备用工作节点"; + SetConnectionState(false, "链路异常,正在恢复", recoveryDetail); await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); } catch (OperationCanceledException) { } @@ -1161,7 +1170,7 @@ internal sealed partial class MainForm : Form _routeCombo.SelectedItem = profile.RouteModes.FirstOrDefault(route => route.Id == selectedRoute) ?? profile.RouteModes.FirstOrDefault(); _routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效"; - _connectButton.Enabled = _availableNodeCount > 0 && !_busy; + RefreshConnectButtonAvailability(); if (_availableNodeCount == 0 && !_wantConnected) { SetConnectionState(false, "暂无线上的线路", "请联系管理员检查节点状态"); @@ -1197,8 +1206,7 @@ internal sealed partial class MainForm : Form _passwordText.ReadOnly = busy; _loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录"; _logoutButton.Enabled = !busy; - _connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false } - || !busy && (_availableNodeCount > 0 || _wantConnected); + RefreshConnectButtonAvailability(); if (_connectionAttemptCancellation is { IsCancellationRequested: false }) _connectButton.Text = "取消连接"; else if (!busy) _connectButton.Text = _selectionUiConnected ? "断开连接" : "连接"; RefreshSelectionControls(); @@ -1208,6 +1216,12 @@ internal sealed partial class MainForm : Form } } + private void RefreshConnectButtonAvailability() + { + _connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false } + || !_busy && (_availableNodeCount > 0 || _wantConnected); + } + private void CenterCards() { ApplyCompactTypography(); diff --git a/windows/NodeHealthProbe.cs b/windows/NodeHealthProbe.cs index 2f672cb..5f582ef 100644 --- a/windows/NodeHealthProbe.cs +++ b/windows/NodeHealthProbe.cs @@ -1,154 +1,161 @@ -using System.Net; - -namespace UCVL.VPNPlus; - -// An advisory probe for the explicitly retained automatic failover feature. -// It is NOT part of 0.2.5's connection transaction and never changes routes. -internal static class NodeHealthProbe -{ - internal readonly record struct Observation(bool BusinessHealthy, bool TransportReachable, string? Diagnostic = null); - internal readonly record struct Report(bool BusinessHealthy, bool TransportReachable); - internal static bool Accepts(int target, int status) => target == 0 - ? status is 200 or 204 - : status is >= 200 and < 500; - - internal static bool OverallHealthy(IReadOnlyList results) => - results.Count >= 3 && results[2] && (results[0] || results[1]); - - internal static bool AcceptsTransportStatus(int status) => status is >= 100 and <= 599; - - private static async Task Observed(Task probe) - { - try { return await probe.ConfigureAwait(false); } - catch { return default; } - } - - internal static async Task AggregateTransportAsync(IReadOnlyList> probes, - CancellationToken token, Action cancelRemaining) - { - var pending = probes.Select(Observed).ToList(); - try - { - token.ThrowIfCancellationRequested(); - while (pending.Count > 0) - { - var finished = await Task.WhenAny(pending).WaitAsync(token).ConfigureAwait(false); - pending.Remove(finished); - var observation = await finished.ConfigureAwait(false); - token.ThrowIfCancellationRequested(); - if (observation.TransportReachable) return true; - } - return false; - } - finally { cancelRemaining(); } - } - - internal static async Task AggregateReportAsync(IReadOnlyList> probes, - CancellationToken token, Action cancelRemaining) - { - var observations = probes.Select(Observed).ToArray(); - async Task BusinessAsync(Task probe) => (await probe.ConfigureAwait(false)).BusinessHealthy; - try - { - token.ThrowIfCancellationRequested(); - var business = AggregateAsync(observations.Select(BusinessAsync).ToArray(), token, () => { }); - var transport = AggregateTransportAsync(observations, token, () => { }); - await Task.WhenAll(business, transport).ConfigureAwait(false); - token.ThrowIfCancellationRequested(); - return new(await business.ConfigureAwait(false), await transport.ConfigureAwait(false)); - } - finally { cancelRemaining(); } - } - - internal static async Task AggregateAsync(IReadOnlyList> probes, - CancellationToken token, Action cancelRemaining) - { - async Task ResultAsync(Task probe) - { - try { return await probe.ConfigureAwait(false); } - catch { return false; } - } - // Observe every probe even after an early verdict. Cancellation or a - // late HTTP exception from a losing probe must not escape unobserved. - var observations = probes.Select(ResultAsync).ToArray(); - try - { - token.ThrowIfCancellationRequested(); - if (observations.Length < 3) return false; - var results = new bool?[3]; - var pending = Enumerable.Range(0, 3).ToList(); - while (pending.Count > 0) - { - var completed = await Task.WhenAny(pending.Select(index => observations[index])) - .WaitAsync(token).ConfigureAwait(false); - var index = pending.First(index => observations[index] == completed); - results[index] = await completed.ConfigureAwait(false); - pending.Remove(index); - token.ThrowIfCancellationRequested(); - // Codex is mandatory; either independent target is sufficient. - // Stop only once that same predicate is proved or impossible. - if (results[2] == false || results[0] == false && results[1] == false) return false; - if (results[2] == true && (results[0] == true || results[1] == true)) return true; - } - return false; - } - finally - { - cancelRemaining(); - } - } - - internal static async Task CheckAsync(CancellationToken token, int proxyPort = 0) - => (await CheckReportAsync(token, proxyPort).ConfigureAwait(false)).BusinessHealthy; - - internal static async Task CheckTransportAsync(CancellationToken token, int proxyPort) - => (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable; - - internal static async Task CheckReportAsync(CancellationToken token, int proxyPort = 0, bool transportOnly = false) - { - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); - timeout.CancelAfter(TimeSpan.FromSeconds(15)); - using var client = new HttpClient(new SocketsHttpHandler { - UseProxy = true, Proxy = new WebProxy(proxyPort > 0 ? $"socks5://127.0.0.1:{proxyPort}" : "http://127.0.0.1:10809"), - ConnectTimeout = TimeSpan.FromSeconds(8), AllowAutoRedirect = false, - }) { Timeout = Timeout.InfiniteTimeSpan }; - var targets = new[] { - (Name: "google", Url: "https://www.google.com/generate_204"), - (Name: "openai", Url: "https://api.openai.com/v1/models"), - (Name: "codex", Url: "https://chatgpt.com/backend-api/codex/models"), - }; - var probes = targets.Select(async (target, index) => { - try { - using var response = await client.GetAsync(target.Url, HttpCompletionOption.ResponseHeadersRead, timeout.Token); - var status = (int)response.StatusCode; - return new Observation(Accepts(index, status), AcceptsTransportStatus(status), $"http_{status}"); - } - catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } - catch (OperationCanceledException) { return new Observation(false, false, "timeout"); } - catch (HttpRequestException ex) { return new Observation(false, false, ex.HttpRequestError.ToString()); } - catch { return new Observation(false, false, "request_failed"); } - }).ToArray(); - // Retain the stricter business-site diagnostic separately. A valid - // TLS/HTTP response through the forced proxy, including 5xx, proves - // transport reachability without claiming the target service is healthy. - if (transportOnly) - return new(false, await AggregateTransportAsync(probes, token, timeout.Cancel).ConfigureAwait(false)); - try - { - var report = await AggregateReportAsync(probes, token, () => { }).ConfigureAwait(false); - if (!report.BusinessHealthy) - { - var path = proxyPort > 0 ? "forced_proxy" : "ordinary"; - var outcomes = targets.Select((target, index) => - { - var probe = probes[index]; - var result = probe.IsCompletedSuccessfully ? probe.Result.Diagnostic : "pending"; - return $"{target.Name}={result}"; - }); - AppPaths.WriteLog($"site_probe path={path} transport={report.TransportReachable} {string.Join(" ", outcomes)}"); - } - return report; - } - finally { timeout.Cancel(); } - } -} +using System.Net; + +namespace UCVL.VPNPlus; + +// An advisory probe for the explicitly retained automatic failover feature. +// It is NOT part of 0.2.5's connection transaction and never changes routes. +internal static class NodeHealthProbe +{ + internal readonly record struct Observation(bool BusinessHealthy, bool TransportReachable, string? Diagnostic = null); + internal readonly record struct Report(bool BusinessHealthy, bool TransportReachable); + internal static bool Accepts(int target, int status) => target == 0 + ? status is 200 or 204 + : status is >= 200 and < 500; + + internal static bool OverallHealthy(IReadOnlyList results) => + results.Count >= 3 && results[2] && (results[0] || results[1]); + + internal static bool AcceptsTransportStatus(int status) => status is >= 100 and <= 599; + + private static async Task Observed(Task probe) + { + try { return await probe.ConfigureAwait(false); } + catch { return default; } + } + + internal static async Task AggregateTransportAsync(IReadOnlyList> probes, + CancellationToken token, Action cancelRemaining) + { + var pending = probes.Select(Observed).ToList(); + try + { + token.ThrowIfCancellationRequested(); + while (pending.Count > 0) + { + var finished = await Task.WhenAny(pending).WaitAsync(token).ConfigureAwait(false); + pending.Remove(finished); + var observation = await finished.ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + if (observation.TransportReachable) return true; + } + return false; + } + finally { cancelRemaining(); } + } + + internal static async Task AggregateReportAsync(IReadOnlyList> probes, + CancellationToken token, Action cancelRemaining) + { + var observations = probes.Select(Observed).ToArray(); + async Task BusinessAsync(Task probe) => (await probe.ConfigureAwait(false)).BusinessHealthy; + try + { + token.ThrowIfCancellationRequested(); + var business = AggregateAsync(observations.Select(BusinessAsync).ToArray(), token, () => { }); + var transport = AggregateTransportAsync(observations, token, () => { }); + await Task.WhenAll(business, transport).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + return new(await business.ConfigureAwait(false), await transport.ConfigureAwait(false)); + } + finally { cancelRemaining(); } + } + + internal static async Task AggregateAsync(IReadOnlyList> probes, + CancellationToken token, Action cancelRemaining) + { + async Task ResultAsync(Task probe) + { + try { return await probe.ConfigureAwait(false); } + catch { return false; } + } + // Observe every probe even after an early verdict. Cancellation or a + // late HTTP exception from a losing probe must not escape unobserved. + var observations = probes.Select(ResultAsync).ToArray(); + try + { + token.ThrowIfCancellationRequested(); + if (observations.Length < 3) return false; + var results = new bool?[3]; + var pending = Enumerable.Range(0, 3).ToList(); + while (pending.Count > 0) + { + var completed = await Task.WhenAny(pending.Select(index => observations[index])) + .WaitAsync(token).ConfigureAwait(false); + var index = pending.First(index => observations[index] == completed); + results[index] = await completed.ConfigureAwait(false); + pending.Remove(index); + token.ThrowIfCancellationRequested(); + // Codex is mandatory; either independent target is sufficient. + // Stop only once that same predicate is proved or impossible. + if (results[2] == false || results[0] == false && results[1] == false) return false; + if (results[2] == true && (results[0] == true || results[1] == true)) return true; + } + return false; + } + finally + { + cancelRemaining(); + } + } + + internal static async Task CheckAsync(CancellationToken token, int proxyPort = 0) + => (await CheckReportAsync(token, proxyPort).ConfigureAwait(false)).BusinessHealthy; + + internal static async Task CheckTransportAsync(CancellationToken token, int proxyPort) + => (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable; + + internal static async Task CheckReportAsync(CancellationToken token, int proxyPort = 0, + bool transportOnly = false, HttpMessageHandler? transport = null) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); + timeout.CancelAfter(TimeSpan.FromSeconds(15)); + using var client = new HttpClient(transport ?? new SocketsHttpHandler { + UseProxy = true, Proxy = new WebProxy(proxyPort > 0 ? $"socks5://127.0.0.1:{proxyPort}" : "http://127.0.0.1:10809"), + ConnectTimeout = TimeSpan.FromSeconds(8), AllowAutoRedirect = false, + }) { Timeout = Timeout.InfiniteTimeSpan }; + var businessTargets = new[] { + (Name: "google", Url: "https://www.google.com/generate_204"), + (Name: "openai", Url: "https://api.openai.com/v1/models"), + (Name: "codex", Url: "https://chatgpt.com/backend-api/codex/models"), + }; + // The forced proxy has an independent HTTPS target for transport proof. + // The three business probes still own the Google/OpenAI/Codex verdict. + var targets = proxyPort > 0 + ? businessTargets.Append((Name: "cloudflare", Url: "https://www.cloudflare.com/cdn-cgi/trace")).ToArray() + : businessTargets; + var probes = targets.Select(async (target, index) => { + try { + using var response = await client.GetAsync(target.Url, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + var status = (int)response.StatusCode; + return new Observation(index < businessTargets.Length && Accepts(index, status), + AcceptsTransportStatus(status), $"http_{status}"); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } + catch (OperationCanceledException) { return new Observation(false, false, "timeout"); } + catch (HttpRequestException ex) { return new Observation(false, false, ex.HttpRequestError.ToString()); } + catch { return new Observation(false, false, "request_failed"); } + }).ToArray(); + // Retain the stricter business-site diagnostic separately. A valid + // TLS/HTTP response through the forced proxy, including 5xx, proves + // transport reachability without claiming the target service is healthy. + if (transportOnly) + return new(false, await AggregateTransportAsync(probes, token, timeout.Cancel).ConfigureAwait(false)); + try + { + var report = await AggregateReportAsync(probes, token, () => { }).ConfigureAwait(false); + if (!report.BusinessHealthy && transport is null) + { + var path = proxyPort > 0 ? "forced_proxy" : "ordinary"; + var outcomes = targets.Select((target, index) => + { + var probe = probes[index]; + var result = probe.IsCompletedSuccessfully ? probe.Result.Diagnostic : "pending"; + return $"{target.Name}={result}"; + }); + AppPaths.WriteLog($"site_probe path={path} transport={report.TransportReachable} {string.Join(" ", outcomes)}"); + } + return report; + } + finally { timeout.Cancel(); } + } +} diff --git a/windows/NodeHealthProbeSelfTest.cs b/windows/NodeHealthProbeSelfTest.cs index d3d1c46..3e09cec 100644 --- a/windows/NodeHealthProbeSelfTest.cs +++ b/windows/NodeHealthProbeSelfTest.cs @@ -1,222 +1,260 @@ -using System.Text.Json; - -namespace UCVL.VPNPlus; - -// Exercises the production aggregator without HTTP, proxies or network changes. -internal static class NodeHealthProbeSelfTest -{ - internal static async Task RunAsync() - { - var checks = new Dictionary(); - var errors = new Dictionary(); - async Task Check(string name, Func test) - { - try { await test(); checks[name] = true; } - catch (Exception error) { checks[name] = false; errors[name] = error.Message; } - } - - await Check("http_status_and_codex_requirement_preserved", () => { - Require(NodeHealthProbe.Accepts(0, 200) && NodeHealthProbe.Accepts(0, 204) - && !NodeHealthProbe.Accepts(0, 201) && !NodeHealthProbe.Accepts(0, 401) - && NodeHealthProbe.Accepts(1, 401) && !NodeHealthProbe.Accepts(1, 500) - && NodeHealthProbe.Accepts(2, 499) && !NodeHealthProbe.Accepts(2, 500), "HTTP status policy changed"); - Require(NodeHealthProbe.OverallHealthy(new[] { true, false, true }) - && NodeHealthProbe.OverallHealthy(new[] { false, true, true }) - && !NodeHealthProbe.OverallHealthy(new[] { true, true, false }) - && !NodeHealthProbe.OverallHealthy(new[] { false, false, true }), "Codex health predicate changed"); - return Task.CompletedTask; - }); - await Check("google_and_codex_do_not_wait_for_api", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "Required successes did not prove health"); - Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled"); - }); - await Check("api_and_codex_do_not_wait_for_google", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Api.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "Required successes did not prove health"); - Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled"); - }); - await Check("codex_failure_finishes_with_other_probes_pending", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); fixture.Codex.SetResult(false); - Require(!await Finished(result), "Codex failure must prove unhealthy"); - Require(fixture.Cancellation.IsCancellationRequested, "Unneeded HTTP probes were not cancelled"); - }); - await Check("both_independent_failures_do_not_wait_for_codex", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetResult(false); fixture.Api.SetResult(false); - Require(!await Finished(result), "No independent target can prove health"); - }); - await Check("google_and_api_success_still_waits_for_codex", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetResult(true); fixture.Api.SetResult(true); - await StillPending(result); - Require(!fixture.Cancellation.IsCancellationRequested, "Codex was cancelled before its verdict"); - fixture.Codex.SetResult(false); - Require(!await Finished(result), "Independent successes cannot mask Codex failure"); - }); - await Check("codex_success_still_waits_for_independent_proof", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); fixture.Codex.SetResult(true); - await StillPending(result); - fixture.Google.SetResult(false); await StillPending(result); - fixture.Api.SetResult(true); - Require(await Finished(result), "An eventual independent success must prove health"); - }); - await Check("critical_probe_exception_counts_as_failure", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); fixture.Codex.SetException(new HttpRequestException("test failure")); - Require(!await Finished(result), "Failed Codex probe must prove unhealthy"); - }); - await Check("independent_exception_allows_other_independent_success", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetException(new HttpRequestException("test failure")); - fixture.Api.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "One failed independent probe must not hide valid health"); - }); - await Check("two_independent_exceptions_prove_failure", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetException(new IOException("test failure")); - fixture.Api.SetException(new HttpRequestException("test failure")); - Require(!await Finished(result), "Two failed independent probes must prove unhealthy"); - }); - await Check("caller_precancellation_is_preserved", async () => { - using var caller = new CancellationTokenSource(); caller.Cancel(); - using var fixture = new Probes(); - await Cancelled(fixture.Start(caller.Token), caller.Token); - Require(fixture.Cancellation.IsCancellationRequested, "Probe cleanup did not run after cancellation"); - }); - await Check("caller_cancellation_interrupts_pending_probes", async () => { - using var caller = new CancellationTokenSource(); - using var fixture = new Probes(); - var result = fixture.Start(caller.Token); caller.Cancel(); - await Cancelled(result, caller.Token); - Require(fixture.Cancellation.IsCancellationRequested, "Pending HTTP probes were not cancelled"); - }); - await Check("late_failure_cannot_change_success", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Google.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "Health was not established"); - fixture.Api.SetException(new HttpRequestException("late unused failure")); - Require(await result, "Late unused failure changed a completed health verdict"); - }); - await Check("late_success_cannot_change_failure", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); fixture.Codex.SetResult(false); - Require(!await Finished(result), "Failure was not established"); - fixture.Google.SetResult(true); fixture.Api.SetResult(true); - Require(!await result, "Late successes changed a completed health verdict"); - }); - await Check("late_caller_cancellation_cannot_change_success", async () => { - using var caller = new CancellationTokenSource(); - using var fixture = new Probes(); - var result = fixture.Start(caller.Token); - fixture.Google.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "Health was not established"); caller.Cancel(); - Require(await result, "Later cancellation changed a completed health verdict"); - }); - await Check("cancelled_unused_probe_cannot_change_success", async () => { - using var fixture = new Probes(); - var result = fixture.Start(); - fixture.Api.SetResult(true); fixture.Codex.SetResult(true); - Require(await Finished(result), "Health was not established"); - fixture.Google.SetCanceled(fixture.Cancellation.Token); - Require(await result, "Unused-probe cancellation changed the health verdict"); - }); - - await Check("http_5xx_response_proves_transport_but_not_business_health", () => { - Require(NodeHealthProbe.AcceptsTransportStatus(503) && !NodeHealthProbe.Accepts(2, 503), "HTTP outage confused with proxy transport"); - return Task.CompletedTask; - }); - await Check("single_codex_outage_keeps_independent_transport_proof", async () => { - var report = await NodeHealthProbe.AggregateReportAsync(new[] { - Task.FromResult(new NodeHealthProbe.Observation(true, true)), - Task.FromResult(new NodeHealthProbe.Observation(true, true)), - Task.FromResult(new NodeHealthProbe.Observation(false, false)) }, CancellationToken.None, () => { }); - Require(!report.BusinessHealthy && report.TransportReachable, "Site failure must remain distinct from transport failure"); - }); - await Check("all_sites_return_5xx_still_is_not_transport_death", async () => { - var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3) - .Select(_ => Task.FromResult(new NodeHealthProbe.Observation(false, true))).ToArray(), CancellationToken.None, () => { }); - Require(!report.BusinessHealthy && report.TransportReachable, "HTTP responses lost transport proof"); - }); - await Check("transport_proof_does_not_wait_for_failed_codex", async () => { - var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var cancelled = false; - var reached = await NodeHealthProbe.AggregateTransportAsync(new[] { - Task.FromResult(new NodeHealthProbe.Observation(true, true)), pending.Task, pending.Task }, CancellationToken.None, () => cancelled = true) - .WaitAsync(TimeSpan.FromSeconds(1)); - Require(reached && cancelled, "Transport startup unnecessarily waited for a site diagnostic"); - pending.SetException(new IOException("late site fixture")); - }); - await Check("all_transport_failures_remain_unavailable", async () => { - var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3) - .Select(_ => Task.FromResult(default(NodeHealthProbe.Observation))).ToArray(), CancellationToken.None, () => { }); - Require(!report.BusinessHealthy && !report.TransportReachable, "Failed transport became false healthy"); - }); - await Check("transport_caller_cancellation_propagates", async () => { - using var caller = new CancellationTokenSource(); caller.Cancel(); - var cancelled = false; - try { await NodeHealthProbe.AggregateTransportAsync([], caller.Token, () => { }); } - catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; } - Require(cancelled, "Transport cancellation was converted to false health"); - }); - var passed = checks.Values.All(value => value); - var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false, - checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true }); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-health-probe-self-test.json"), report); - Console.WriteLine(report); - return passed ? 0 : 1; - } - - private static void Require(bool condition, string message) - { - if (!condition) throw new InvalidOperationException(message); - } - - private static async Task Finished(Task result) - { - try { return await result.WaitAsync(TimeSpan.FromSeconds(1)); } - catch (TimeoutException) { throw new InvalidOperationException("Health verdict waited for an unnecessary pending probe"); } - } - - private static async Task StillPending(Task result) - { - var winner = await Task.WhenAny(result, Task.Delay(40)); - Require(winner != result, "Health completed without required evidence"); - } - - private static async Task Cancelled(Task result, CancellationToken caller) - { - try { await result.WaitAsync(TimeSpan.FromSeconds(1)); } - catch (OperationCanceledException error) when (caller.IsCancellationRequested && error.CancellationToken == caller) { return; } - throw new InvalidOperationException("Caller cancellation did not propagate with its token"); - } - - private sealed class Probes : IDisposable - { - private Task? _running; - internal TaskCompletionSource Google { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal TaskCompletionSource Api { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal TaskCompletionSource Codex { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal CancellationTokenSource Cancellation { get; } = new(); - internal Task Start(CancellationToken caller = default) => _running = NodeHealthProbe.AggregateAsync( - new[] { Google.Task, Api.Task, Codex.Task }, caller, Cancellation.Cancel); - public void Dispose() - { - Google.TrySetResult(false); Api.TrySetResult(false); Codex.TrySetResult(false); - if (_running is null) Cancellation.Dispose(); - else _ = _running.ContinueWith(task => { _ = task.Exception; Cancellation.Dispose(); }, - CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - } - } -} +using System.Net; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Exercises the production aggregator without HTTP, proxies or network changes. +internal static class NodeHealthProbeSelfTest +{ + internal static async Task RunAsync() + { + var checks = new Dictionary(); + var errors = new Dictionary(); + async Task Check(string name, Func test) + { + try { await test(); checks[name] = true; } + catch (Exception error) { checks[name] = false; errors[name] = error.Message; } + } + + await Check("http_status_and_codex_requirement_preserved", () => { + Require(NodeHealthProbe.Accepts(0, 200) && NodeHealthProbe.Accepts(0, 204) + && !NodeHealthProbe.Accepts(0, 201) && !NodeHealthProbe.Accepts(0, 401) + && NodeHealthProbe.Accepts(1, 401) && !NodeHealthProbe.Accepts(1, 500) + && NodeHealthProbe.Accepts(2, 499) && !NodeHealthProbe.Accepts(2, 500), "HTTP status policy changed"); + Require(NodeHealthProbe.OverallHealthy(new[] { true, false, true }) + && NodeHealthProbe.OverallHealthy(new[] { false, true, true }) + && !NodeHealthProbe.OverallHealthy(new[] { true, true, false }) + && !NodeHealthProbe.OverallHealthy(new[] { false, false, true }), "Codex health predicate changed"); + return Task.CompletedTask; + }); + await Check("google_and_codex_do_not_wait_for_api", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "Required successes did not prove health"); + Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled"); + }); + await Check("api_and_codex_do_not_wait_for_google", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Api.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "Required successes did not prove health"); + Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled"); + }); + await Check("codex_failure_finishes_with_other_probes_pending", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); fixture.Codex.SetResult(false); + Require(!await Finished(result), "Codex failure must prove unhealthy"); + Require(fixture.Cancellation.IsCancellationRequested, "Unneeded HTTP probes were not cancelled"); + }); + await Check("both_independent_failures_do_not_wait_for_codex", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetResult(false); fixture.Api.SetResult(false); + Require(!await Finished(result), "No independent target can prove health"); + }); + await Check("google_and_api_success_still_waits_for_codex", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetResult(true); fixture.Api.SetResult(true); + await StillPending(result); + Require(!fixture.Cancellation.IsCancellationRequested, "Codex was cancelled before its verdict"); + fixture.Codex.SetResult(false); + Require(!await Finished(result), "Independent successes cannot mask Codex failure"); + }); + await Check("codex_success_still_waits_for_independent_proof", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); fixture.Codex.SetResult(true); + await StillPending(result); + fixture.Google.SetResult(false); await StillPending(result); + fixture.Api.SetResult(true); + Require(await Finished(result), "An eventual independent success must prove health"); + }); + await Check("critical_probe_exception_counts_as_failure", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); fixture.Codex.SetException(new HttpRequestException("test failure")); + Require(!await Finished(result), "Failed Codex probe must prove unhealthy"); + }); + await Check("independent_exception_allows_other_independent_success", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetException(new HttpRequestException("test failure")); + fixture.Api.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "One failed independent probe must not hide valid health"); + }); + await Check("two_independent_exceptions_prove_failure", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetException(new IOException("test failure")); + fixture.Api.SetException(new HttpRequestException("test failure")); + Require(!await Finished(result), "Two failed independent probes must prove unhealthy"); + }); + await Check("caller_precancellation_is_preserved", async () => { + using var caller = new CancellationTokenSource(); caller.Cancel(); + using var fixture = new Probes(); + await Cancelled(fixture.Start(caller.Token), caller.Token); + Require(fixture.Cancellation.IsCancellationRequested, "Probe cleanup did not run after cancellation"); + }); + await Check("caller_cancellation_interrupts_pending_probes", async () => { + using var caller = new CancellationTokenSource(); + using var fixture = new Probes(); + var result = fixture.Start(caller.Token); caller.Cancel(); + await Cancelled(result, caller.Token); + Require(fixture.Cancellation.IsCancellationRequested, "Pending HTTP probes were not cancelled"); + }); + await Check("late_failure_cannot_change_success", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Google.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "Health was not established"); + fixture.Api.SetException(new HttpRequestException("late unused failure")); + Require(await result, "Late unused failure changed a completed health verdict"); + }); + await Check("late_success_cannot_change_failure", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); fixture.Codex.SetResult(false); + Require(!await Finished(result), "Failure was not established"); + fixture.Google.SetResult(true); fixture.Api.SetResult(true); + Require(!await result, "Late successes changed a completed health verdict"); + }); + await Check("late_caller_cancellation_cannot_change_success", async () => { + using var caller = new CancellationTokenSource(); + using var fixture = new Probes(); + var result = fixture.Start(caller.Token); + fixture.Google.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "Health was not established"); caller.Cancel(); + Require(await result, "Later cancellation changed a completed health verdict"); + }); + await Check("cancelled_unused_probe_cannot_change_success", async () => { + using var fixture = new Probes(); + var result = fixture.Start(); + fixture.Api.SetResult(true); fixture.Codex.SetResult(true); + Require(await Finished(result), "Health was not established"); + fixture.Google.SetCanceled(fixture.Cancellation.Token); + Require(await result, "Unused-probe cancellation changed the health verdict"); + }); + + await Check("http_5xx_response_proves_transport_but_not_business_health", () => { + Require(NodeHealthProbe.AcceptsTransportStatus(503) && !NodeHealthProbe.Accepts(2, 503), "HTTP outage confused with proxy transport"); + return Task.CompletedTask; + }); + await Check("single_codex_outage_keeps_independent_transport_proof", async () => { + var report = await NodeHealthProbe.AggregateReportAsync(new[] { + Task.FromResult(new NodeHealthProbe.Observation(true, true)), + Task.FromResult(new NodeHealthProbe.Observation(true, true)), + Task.FromResult(new NodeHealthProbe.Observation(false, false)) }, CancellationToken.None, () => { }); + Require(!report.BusinessHealthy && report.TransportReachable, "Site failure must remain distinct from transport failure"); + }); + await Check("all_sites_return_5xx_still_is_not_transport_death", async () => { + var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3) + .Select(_ => Task.FromResult(new NodeHealthProbe.Observation(false, true))).ToArray(), CancellationToken.None, () => { }); + Require(!report.BusinessHealthy && report.TransportReachable, "HTTP responses lost transport proof"); + }); + await Check("transport_proof_does_not_wait_for_failed_codex", async () => { + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cancelled = false; + var reached = await NodeHealthProbe.AggregateTransportAsync(new[] { + Task.FromResult(new NodeHealthProbe.Observation(true, true)), pending.Task, pending.Task }, CancellationToken.None, () => cancelled = true) + .WaitAsync(TimeSpan.FromSeconds(1)); + Require(reached && cancelled, "Transport startup unnecessarily waited for a site diagnostic"); + pending.SetException(new IOException("late site fixture")); + }); + await Check("all_transport_failures_remain_unavailable", async () => { + var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3) + .Select(_ => Task.FromResult(default(NodeHealthProbe.Observation))).ToArray(), CancellationToken.None, () => { }); + Require(!report.BusinessHealthy && !report.TransportReachable, "Failed transport became false healthy"); + }); + await Check("forced_proxy_independent_https_keeps_business_verdict_separate", async () => { + using var transport = new IndependentHttpsFixture(); + var report = await NodeHealthProbe.CheckReportAsync(CancellationToken.None, proxyPort: 18091, transport: transport); + Require(transport.Seen.Count == 4 && transport.Seen.Contains(IndependentHttpsFixture.Anchor), + "The forced proxy did not try the independent HTTPS target"); + Require(report.TransportReachable && !report.BusinessHealthy, + "Independent HTTPS should prove transport without replacing business probes"); + }); + await Check("startup_transport_accepts_independent_https_alone", async () => { + using var transport = new IndependentHttpsFixture(); + var report = await NodeHealthProbe.CheckReportAsync(CancellationToken.None, proxyPort: 18091, + transportOnly: true, transport: transport); + Require(report.TransportReachable && !report.BusinessHealthy, "Independent HTTPS did not establish startup transport"); + }); + await Check("ordinary_probe_retains_the_three_business_targets", async () => { + using var transport = new IndependentHttpsFixture(); + var report = await NodeHealthProbe.CheckReportAsync(CancellationToken.None, transport: transport); + Require(transport.Seen.Count == 3 && !transport.Seen.Contains(IndependentHttpsFixture.Anchor) + && !report.TransportReachable && !report.BusinessHealthy, + "Ordinary health must keep its original business targets"); + }); + await Check("transport_caller_cancellation_propagates", async () => { + using var caller = new CancellationTokenSource(); caller.Cancel(); + var cancelled = false; + try { await NodeHealthProbe.AggregateTransportAsync([], caller.Token, () => { }); } + catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; } + Require(cancelled, "Transport cancellation was converted to false health"); + }); + var passed = checks.Values.All(value => value); + var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false, + checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-health-probe-self-test.json"), report); + Console.WriteLine(report); + return passed ? 0 : 1; + } + + private static void Require(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + } + + private sealed class IndependentHttpsFixture : HttpMessageHandler + { + internal const string Anchor = "https://www.cloudflare.com/cdn-cgi/trace"; + internal List Seen { get; } = new(); + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + var url = request.RequestUri!.AbsoluteUri; + Seen.Add(url); + return url == Anchor + ? Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)) + : Task.FromException(new HttpRequestException("business service unavailable")); + } + } + + private static async Task Finished(Task result) + { + try { return await result.WaitAsync(TimeSpan.FromSeconds(1)); } + catch (TimeoutException) { throw new InvalidOperationException("Health verdict waited for an unnecessary pending probe"); } + } + + private static async Task StillPending(Task result) + { + var winner = await Task.WhenAny(result, Task.Delay(40)); + Require(winner != result, "Health completed without required evidence"); + } + + private static async Task Cancelled(Task result, CancellationToken caller) + { + try { await result.WaitAsync(TimeSpan.FromSeconds(1)); } + catch (OperationCanceledException error) when (caller.IsCancellationRequested && error.CancellationToken == caller) { return; } + throw new InvalidOperationException("Caller cancellation did not propagate with its token"); + } + + private sealed class Probes : IDisposable + { + private Task? _running; + internal TaskCompletionSource Google { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal TaskCompletionSource Api { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal TaskCompletionSource Codex { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal CancellationTokenSource Cancellation { get; } = new(); + internal Task Start(CancellationToken caller = default) => _running = NodeHealthProbe.AggregateAsync( + new[] { Google.Task, Api.Task, Codex.Task }, caller, Cancellation.Cancel); + public void Dispose() + { + Google.TrySetResult(false); Api.TrySetResult(false); Codex.TrySetResult(false); + if (_running is null) Cancellation.Dispose(); + else _ = _running.ContinueWith(task => { _ = task.Exception; Cancellation.Dispose(); }, + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } +} diff --git a/windows/NodeTransportConnector.cs b/windows/NodeTransportConnector.cs index 9ec526a..5375fcc 100644 --- a/windows/NodeTransportConnector.cs +++ b/windows/NodeTransportConnector.cs @@ -1,152 +1,181 @@ -namespace UCVL.VPNPlus; - -// Contains only bounded identifiers and fixed reason codes, never config JSON, -// credentials, exception messages, URLs, or a management access token. -internal sealed record TransportDiagnostic(string Event, string Reason, string Node) -{ - private static string Identifier(string value) => new(value.Take(100) - .Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' ? c : '_').ToArray()); - internal string SafeMessage => $"transport event={Identifier(Event)} reason={Identifier(Reason)} node={Identifier(Node)}"; -} - -internal static class NodeTransportConnector -{ - internal static async Task RebindAsync(string current, string? original, - Func start, Func stop, - Func> proxyHealth, CancellationToken token, - string? preferredTailnetConfig = null, Action? requireRoute = null, - Func>? endpointProbe = null, - Action? diagnostic = null) - { - token.ThrowIfCancellationRequested(); - var tailnet = TailnetTransport.Address(current) is not null; - if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original)) - throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。"); - var selected = current; - var fallback = original; - // Once domain fallback has been selected, physical-network recovery - // retains it. Do not probe/promote a cached internal alternative. - // Only an explicit new user connection may select the internal IP again. - token.ThrowIfCancellationRequested(); - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); - if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45)); - try - { - if (tailnet && endpointProbe is not null) - { - var available = await endpointProbe(TailnetTransport.Address(selected)!, TailnetTransport.Port(selected), deadline.Token); - token.ThrowIfCancellationRequested(); - if (!available) - { - selected = fallback!; - tailnet = false; - diagnostic?.Invoke(new("rebind_fallback", "endpoint_unreachable", "")); - } - } - await start(selected, deadline.Token); - if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。"); - deadline.Token.ThrowIfCancellationRequested(); - diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", "")); - return selected; - } - catch (Exception e) when (tailnet && e is not LocalNetworkException && e is not ClientRuntimeException && !token.IsCancellationRequested) - { - await stop(); // Full cleanup before same-node fallback; failure aborts. - token.ThrowIfCancellationRequested(); - diagnostic?.Invoke(new("rebind_fallback", "proxy_health_or_start_failed", "")); - await start(fallback!, token); - token.ThrowIfCancellationRequested(); - return fallback!; - } - } - - // Called only as part of an explicit connect or confirmed-failure recovery. - // No background race or periodic optimization may replace a healthy session. - internal static async Task ConnectAsync(ConfigResponse response, TailnetPreference preference, - Func start, Func stop, Func> proxyHealth, - Action requireRoute, Action status, Func ticks, - CancellationToken token, bool allowKnownEndpoints = false, - Func>? endpointProbe = null, - Action? diagnostic = null) - { - token.ThrowIfCancellationRequested(); - var reason = "cooldown_active"; - var tailnet = preference.MayTry(response.Node.Slug, ticks()) - ? TailnetTransport.TryPrepare(response, out reason, allowKnownEndpoints) : null; - void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug)); - if (tailnet is null) Report("tailnet_skipped", reason); - else Report("tailnet_candidate", reason); - if (tailnet is not null) - { - try - { - requireRoute(TailnetTransport.Address(tailnet)!); - token.ThrowIfCancellationRequested(); - } - catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException) - { - preference.Failed(response.Node.Slug, ticks()); - tailnet = null; - reason = "route_unavailable"; - Report("tailnet_skipped", reason); - status("Tailscale 无独立内网路由,使用同一节点公网入口"); - } - } - if (tailnet is not null && endpointProbe is not null) - { - try - { - status("正在检测 Tailscale 代理端口(最多 5 秒)"); - if (!await endpointProbe(TailnetTransport.Address(tailnet)!, TailnetTransport.Port(tailnet), token)) - throw new IOException("Tailscale 代理端口不可达。"); - token.ThrowIfCancellationRequested(); - } - catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException) - { - preference.Failed(response.Node.Slug, ticks()); - tailnet = null; - reason = "endpoint_unreachable"; - Report("tailnet_skipped", reason); - status("Tailscale 代理端口不可达,使用同一节点公网入口"); - } - } - if (tailnet is not null) - { - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); - deadline.CancelAfter(TimeSpan.FromSeconds(45)); - try - { - token.ThrowIfCancellationRequested(); - status("正在验证 Tailscale 节点入口"); - await start(tailnet, deadline.Token); - deadline.Token.ThrowIfCancellationRequested(); - // Plain TCP/ping, or a successful DIRECT smart request, is not proof. - if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。"); - deadline.Token.ThrowIfCancellationRequested(); - Report("selected", "tailnet_verified"); - return true; - } - catch (LocalNetworkException) { throw; } - catch (ClientRuntimeException) { throw; } - catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } - catch (Exception) - { - preference.Failed(response.Node.Slug, ticks()); - // A failed restore must propagate: never stack a second connection. - await stop(); - reason = "proxy_health_or_start_failed"; - Report("tailnet_failed", reason); - status("Tailscale 协议或代理出口验证失败,回退同一节点公网入口"); - } - } - token.ThrowIfCancellationRequested(); - var commitDomain = response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global"; - try { await start(response.GetRuntimeConfigJson(), token); } - catch (ClientRuntimeException) { throw; } - catch { if (commitDomain) preference.CommitDomainFallback(); throw; } - if (commitDomain) preference.CommitDomainFallback(); - token.ThrowIfCancellationRequested(); - Report("selected", "public_ingress"); - return false; - } -} +namespace UCVL.VPNPlus; + +// Contains only bounded identifiers and fixed reason codes, never config JSON, +// credentials, exception messages, URLs, or a management access token. +internal sealed record TransportDiagnostic(string Event, string Reason, string Node) +{ + private static string Identifier(string value) => new(value.Take(100) + .Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' ? c : '_').ToArray()); + internal string SafeMessage => $"transport event={Identifier(Event)} reason={Identifier(Reason)} node={Identifier(Node)}"; +} + +internal static class NodeTransportConnector +{ + internal static async Task RebindAsync(string current, string? original, + Func start, Func stop, + Func> proxyHealth, CancellationToken token, + string? preferredTailnetConfig = null, Action? requireRoute = null, + Func>? endpointProbe = null, + Action? diagnostic = null, bool verifyPublicEgress = true) + { + token.ThrowIfCancellationRequested(); + var tailnet = TailnetTransport.Address(current) is not null; + if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original)) + throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。"); + var selected = current; + var fallback = original; + // Once domain fallback has been selected, physical-network recovery + // retains it. Do not probe/promote a cached internal alternative. + // Only an explicit new user connection may select the internal IP again. + token.ThrowIfCancellationRequested(); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45)); + try + { + if (tailnet && endpointProbe is not null) + { + var available = await endpointProbe(TailnetTransport.Address(selected)!, TailnetTransport.Port(selected), deadline.Token); + token.ThrowIfCancellationRequested(); + if (!available) + { + selected = fallback!; + tailnet = false; + diagnostic?.Invoke(new("rebind_fallback", "endpoint_unreachable", "")); + } + } + if (tailnet) + { + await start(selected, deadline.Token); + if (!await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。"); + deadline.Token.ThrowIfCancellationRequested(); + } + else + await StartAndVerifyPublicAsync(selected, start, proxyHealth, verifyPublicEgress, token, + () => diagnostic?.Invoke(new("rebind_failed", "public_proxy_health_failed", ""))); + diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", "")); + return selected; + } + catch (Exception e) when (tailnet && e is not LocalNetworkException && e is not ClientRuntimeException && !token.IsCancellationRequested) + { + await stop(); // Full cleanup before same-node fallback; failure aborts. + token.ThrowIfCancellationRequested(); + diagnostic?.Invoke(new("rebind_fallback", "proxy_health_or_start_failed", "")); + await StartAndVerifyPublicAsync(fallback!, start, proxyHealth, verifyPublicEgress, token, + () => diagnostic?.Invoke(new("rebind_failed", "public_proxy_health_failed", ""))); + diagnostic?.Invoke(new("rebind_selected", "public_ingress", "")); + return fallback!; + } + } + + // Called only as part of an explicit connect or confirmed-failure recovery. + // No background race or periodic optimization may replace a healthy session. + internal static async Task ConnectAsync(ConfigResponse response, TailnetPreference preference, + Func start, Func stop, Func> proxyHealth, + Action requireRoute, Action status, Func ticks, + CancellationToken token, bool allowKnownEndpoints = false, + Func>? endpointProbe = null, + Action? diagnostic = null) + { + token.ThrowIfCancellationRequested(); + var reason = "cooldown_active"; + var tailnet = preference.MayTry(response.Node.Slug, ticks()) + ? TailnetTransport.TryPrepare(response, out reason, allowKnownEndpoints) : null; + void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug)); + if (tailnet is null) Report("tailnet_skipped", reason); + else Report("tailnet_candidate", reason); + if (tailnet is not null) + { + try + { + requireRoute(TailnetTransport.Address(tailnet)!); + token.ThrowIfCancellationRequested(); + } + catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException) + { + preference.Failed(response.Node.Slug, ticks()); + tailnet = null; + reason = "route_unavailable"; + Report("tailnet_skipped", reason); + status("Tailscale 无独立内网路由,使用同一节点公网入口"); + } + } + if (tailnet is not null && endpointProbe is not null) + { + try + { + status("正在检测 Tailscale 代理端口(最多 5 秒)"); + if (!await endpointProbe(TailnetTransport.Address(tailnet)!, TailnetTransport.Port(tailnet), token)) + throw new IOException("Tailscale 代理端口不可达。"); + token.ThrowIfCancellationRequested(); + } + catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException) + { + preference.Failed(response.Node.Slug, ticks()); + tailnet = null; + reason = "endpoint_unreachable"; + Report("tailnet_skipped", reason); + status("Tailscale 代理端口不可达,使用同一节点公网入口"); + } + } + if (tailnet is not null) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(TimeSpan.FromSeconds(45)); + try + { + token.ThrowIfCancellationRequested(); + status("正在验证 Tailscale 节点入口"); + await start(tailnet, deadline.Token); + deadline.Token.ThrowIfCancellationRequested(); + // Plain TCP/ping, or a successful DIRECT smart request, is not proof. + if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。"); + deadline.Token.ThrowIfCancellationRequested(); + Report("selected", "tailnet_verified"); + return true; + } + catch (LocalNetworkException) { throw; } + catch (ClientRuntimeException) { throw; } + catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } + catch (Exception) + { + preference.Failed(response.Node.Slug, ticks()); + // A failed restore must propagate: never stack a second connection. + await stop(); + reason = "proxy_health_or_start_failed"; + Report("tailnet_failed", reason); + status("Tailscale 协议或代理出口验证失败,回退同一节点公网入口"); + } + } + token.ThrowIfCancellationRequested(); + var verifyPublicEgress = response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global"; + try + { + await StartAndVerifyPublicAsync(response.GetRuntimeConfigJson(), start, proxyHealth, verifyPublicEgress, token, + () => Report("public_failed", "public_proxy_health_failed")); + } + catch (Exception e) when (verifyPublicEgress && e is not ClientRuntimeException && e is not LocalNetworkException + && !token.IsCancellationRequested) + { + preference.CommitDomainFallback(); + throw; + } + token.ThrowIfCancellationRequested(); + if (verifyPublicEgress) preference.CommitDomainFallback(); + Report("selected", "public_ingress"); + return false; + } + + private static async Task StartAndVerifyPublicAsync(string config, + Func start, Func> proxyHealth, + bool verifyPublicEgress, CancellationToken token, Action reportFailure) + { + await start(config, token); + token.ThrowIfCancellationRequested(); + if (!verifyPublicEgress) return; + var reachable = await proxyHealth(token); + token.ThrowIfCancellationRequested(); + if (reachable) return; + reportFailure(); + throw new IOException("公网入口代理出口验证失败。"); + } +} diff --git a/windows/ProxyDnsPolicy.cs b/windows/ProxyDnsPolicy.cs index 2dce0e7..2368b7f 100644 --- a/windows/ProxyDnsPolicy.cs +++ b/windows/ProxyDnsPolicy.cs @@ -1,74 +1,77 @@ -using System.Diagnostics; -using System.Text.Json.Nodes; - -namespace UCVL.VPNPlus; - -// Only proxy-domain DNS is sent through the tunnel. Existing LAN/Tailscale -// namespaces and physical adapter DNS settings are not replaced. -internal static class ProxyDnsPolicy -{ - internal const string Owner = "UCVL.VPNPlus.ProxyDNS.v1"; - private static string Journal => Path.Combine(AppPaths.DataDirectory, "proxy-dns-owned.json"); - private static readonly string[] SeedDomains = ["chatgpt.com", "openai.com", "oaistatic.com", "oaiusercontent.com", "google.com", "googleapis.com", "googleusercontent.com", "gstatic.com", "googlevideo.com", "youtube.com", "youtu.be", "ytimg.com", "ggpht.com"]; - - internal static string[] Namespaces(string config) - { - var domains = new HashSet(SeedDomains, StringComparer.OrdinalIgnoreCase); - var exact = new HashSet(StringComparer.OrdinalIgnoreCase); - var root = JsonNode.Parse(config)!; - if (root["routing"]?["rules"] is JsonArray rules) - foreach (var rule in rules) - if (rule?["outboundTag"]?.GetValue() == "proxy" && rule["domain"] is JsonArray names) - foreach (var name in names) - { - var text = name?.GetValue() ?? ""; - if (text.StartsWith("domain:")) domains.Add(text[7..]); - if (text.StartsWith("full:")) exact.Add(text[5..]); - } - foreach (var item in LearningStore.GetActiveTargets().Where(t => t.TargetType == "domain")) exact.Add(item.Target); - static bool Safe(string value) => value.Length <= 253 && value.Contains('.') - && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-') - && Uri.CheckHostName(value) == UriHostNameType.Dns; - return domains.Where(Safe).SelectMany(d => new[] { d, "." + d }) - .Concat(exact.Where(Safe)).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToArray(); - } - - internal static async Task EnableAsync(string config, CancellationToken token) - { - var names = Namespaces(config); - if (names.Length == 0) return; - AppPaths.EnsureDirectory(); - // Intent first; a crash between policy creation and journal completion - // is still recovered by the unique ownership marker on next startup. - File.WriteAllText(Journal, System.Text.Json.JsonSerializer.Serialize(new { owner = Owner, names })); - var values = string.Join(",", names.Select(n => "'" + n + "'")); - await RunAsync($"$names=@({values}); $others=@(Get-DnsClientNrptRule | Where-Object {{$_.Comment -ne '{Owner}'}}); " + - "foreach ($r in $others) { foreach ($n in $r.Namespace) { if ($names -contains $n) { throw 'A managed DNS namespace already exists; it was not changed.' } } }; " + - $"Add-DnsClientNrptRule -Namespace $names -NameServers '8.8.8.8','1.1.1.1' -Comment '{Owner}' -DisplayName 'UCVL proxy domain DNS' | Out-Null; Clear-DnsClientCache", token); - AppPaths.WriteLog($"已为 {names.Length} 个代理域名范围启用隧道 DNS;保留现有内网/Tailscale DNS。"); - } - - internal static async Task RestoreAsync(CancellationToken token) - { - // No journal means this client has never installed a policy. On a - // process crash the intent journal is retained until cleanup succeeds. - if (!File.Exists(Journal)) return; - await RunAsync($"Get-DnsClientNrptRule | Where-Object {{$_.Comment -eq '{Owner}'}} | ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }}; Clear-DnsClientCache", token); - File.Delete(Journal); - } - - private static async Task RunAsync(string script, CancellationToken token) - { - using var process = new Process { StartInfo = SystemPowerShell.CreateStartInfo("$ErrorActionPreference='Stop'; " + script) }; - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(20)); - process.Start(); - try - { - var output = process.StandardOutput.ReadToEndAsync(timeout.Token); - var error = process.StandardError.ReadToEndAsync(timeout.Token); - await process.WaitForExitAsync(timeout.Token); await output; - if (process.ExitCode != 0) throw new IOException("代理域名 DNS 配置失败:" + await error); - } - finally { try { if (!process.HasExited) process.Kill(); } catch { } } - } -} +using System.Diagnostics; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +// Only proxy-domain DNS is sent through the tunnel. Existing LAN/Tailscale +// namespaces and physical adapter DNS settings are not replaced. +internal static class ProxyDnsPolicy +{ + internal const string Owner = "UCVL.VPNPlus.ProxyDNS.v1"; + private static string Journal => Path.Combine(AppPaths.DataDirectory, "proxy-dns-owned.json"); + private static readonly string[] SeedDomains = ["chatgpt.com", "openai.com", "oaistatic.com", "oaiusercontent.com", "google.com", "googleapis.com", "googleusercontent.com", "gstatic.com", "googlevideo.com", "youtube.com", "youtu.be", "ytimg.com", "ggpht.com"]; + + internal static string[] Namespaces(string config, IEnumerable<(string TargetType, string Target)> activeTargets) + { + var domains = new HashSet(SeedDomains, StringComparer.OrdinalIgnoreCase); + var exact = new HashSet(StringComparer.OrdinalIgnoreCase); + var root = JsonNode.Parse(config)!; + if (root["routing"]?["rules"] is JsonArray rules) + foreach (var rule in rules) + if (rule?["outboundTag"]?.GetValue() == "proxy" && rule["domain"] is JsonArray names) + foreach (var name in names) + { + var text = name?.GetValue() ?? ""; + if (text.StartsWith("domain:")) domains.Add(text[7..]); + if (text.StartsWith("full:")) exact.Add(text[5..]); + } + foreach (var item in activeTargets.Where(t => t.TargetType == "domain")) exact.Add(item.Target); + static bool Safe(string value) => value.Length <= 253 && value.Contains('.') + && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-') + && Uri.CheckHostName(value) == UriHostNameType.Dns; + // Never send the DNS required to reach our own transport over that transport. + return domains.Where(d => Safe(d) && !TailnetDnsPolicy.IsProtectedSuffix(d)) + .SelectMany(d => new[] { d, "." + d }) + .Concat(exact.Where(d => Safe(d) && !TailnetDnsPolicy.IsProtectedDomain(d))) + .Distinct(StringComparer.OrdinalIgnoreCase).Order().ToArray(); + } + + internal static async Task EnableAsync(string config, CancellationToken token) + { + var names = Namespaces(config, LearningStore.GetActiveTargets()); + if (names.Length == 0) return; + AppPaths.EnsureDirectory(); + // Intent first; a crash between policy creation and journal completion + // is still recovered by the unique ownership marker on next startup. + File.WriteAllText(Journal, System.Text.Json.JsonSerializer.Serialize(new { owner = Owner, names })); + var values = string.Join(",", names.Select(n => "'" + n + "'")); + await RunAsync($"$names=@({values}); $others=@(Get-DnsClientNrptRule | Where-Object {{$_.Comment -ne '{Owner}'}}); " + + "foreach ($r in $others) { foreach ($n in $r.Namespace) { if ($names -contains $n) { throw 'A managed DNS namespace already exists; it was not changed.' } } }; " + + $"Add-DnsClientNrptRule -Namespace $names -NameServers '8.8.8.8','1.1.1.1' -Comment '{Owner}' -DisplayName 'UCVL proxy domain DNS' | Out-Null; Clear-DnsClientCache", token); + AppPaths.WriteLog($"已为 {names.Length} 个代理域名范围启用隧道 DNS;保留现有内网/Tailscale DNS。"); + } + + internal static async Task RestoreAsync(CancellationToken token) + { + // No journal means this client has never installed a policy. On a + // process crash the intent journal is retained until cleanup succeeds. + if (!File.Exists(Journal)) return; + await RunAsync($"Get-DnsClientNrptRule | Where-Object {{$_.Comment -eq '{Owner}'}} | ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }}; Clear-DnsClientCache", token); + File.Delete(Journal); + } + + private static async Task RunAsync(string script, CancellationToken token) + { + using var process = new Process { StartInfo = SystemPowerShell.CreateStartInfo("$ErrorActionPreference='Stop'; " + script) }; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(20)); + process.Start(); + try + { + var output = process.StandardOutput.ReadToEndAsync(timeout.Token); + var error = process.StandardError.ReadToEndAsync(timeout.Token); + await process.WaitForExitAsync(timeout.Token); await output; + if (process.ExitCode != 0) throw new IOException("代理域名 DNS 配置失败:" + await error); + } + finally { try { if (!process.HasExited) process.Kill(); } catch { } } + } +} diff --git a/windows/README.md b/windows/README.md index 2eadb72..16215b6 100644 --- a/windows/README.md +++ b/windows/README.md @@ -1,90 +1,101 @@ -# 优创⁺纵横家 Windows 客户端 - -## Windows 0.3.8 - -管理平台已迁移至 https://vpn.ucvl.cn/。登录、注册和平台探测统一使用新域名,直连备用地址已随迁移更新。 - -宽屏主界面采用浅蓝山水背景、连接状态横幅、调度侧栏和独立流量监控区。上传/下载可单独查看;曲线、累计量和授权状态仍来自现有采集与账户数据。小窗口保留紧凑布局,并通过“更多”访问设置、关于和退出。 - - -## Windows 0.2.18-preview.1(主动下载验证) - -加入断开后手动节点选择,并保留默认AI自动调度。Zero3私有辅助接入客户端代码已有候选,但正式设备授权执行端尚未完成,生产仍关闭;ping可达不等于本版已能使用Zero3。公司内网及用户安排的Tailscale路径均按可达性考虑,不额外限速或配置网关。公共节点保留。 - -本次仅预览发布及私有源码备份,稳定更新通道不变,不推送全员更新,不部署后台。查看 `release/RELEASE-NOTES-0.2.18-preview.1.md` 和 `release/ACCEPTANCE-0.2.18-preview.1.md` 了解验收范围及未完项。该包由 `build/Package-PrivateAuxiliaryPreview.ps1` 封装已经过保护测试的原EXE,不临时重编译;普通本地编译使用项目自带.NET8 SDK。 - -以下0.2.17及更早内容为历史记录。 - -## Windows 0.2.17 - -切网恢复与蓝白卡片界面。保留套餐、双品牌 Logo 和自动调度,只显示当前工作节点。上传/下载速度与实时曲线放在一起,本期/本次代理用量与历史曲线放在一起,小窗口自动纵向排列并滚动。 - -### 网络切换 - -监测实际默认出口的网卡、IP、网关和 DNS,变化稳定3秒后先释放旧路由/DNS接管,再绑定新出口、重建当前已授权节点连接,不等待旧路由上的平台请求。离线时释放本软件接管,网络恢复后重试;失败退避最多30秒。主动断开或退出取消重连;切网不计为节点故障,平台401/403授权检查保持有效。 - -旧 TCP 流需要应用重连,不是无缝迁移。已通过隔离状态机和受保护的本机“模拟离线→真实内核/路由重建→接口复测”测试;当前没有接通有线网卡,物理 Wi-Fi/有线互切及 Codex 已登录长会话尚未完整验收。东京 VPN002 三轮 HTTP/DNS 探测可达,但间歇性服务端问题尚未定位,不代表长期稳定。 - -### 统计和升级 - -只统计代理流量,直连不计。本次累计与网速是本机,历史沿用套餐全部设备。历史可选12小时、1天、7天、1个月(30个自然日);小时/整月展示需要配套后台明细,尚未部署新后台时保留原7天,其他范围明确提示无数据,不伪造历史。小时从后台升级后按节点上报接收时间归档,未知桶显示缺口。 - -安装包和更新仅从公司 pro.ucvl.cn Git 提供,非强制:同意后下载、校验、覆盖原安装目录并保留用户配置,完成后重启;Windows 系统授权提示仍可能出现。0.2.16 在线升级已获用户实际确认成功,本版保留该流程。此轮仅 Windows,不涉及苹果版本、ERP 文件上传或全员通知。 - -发布状态以公司 Git Release 为准;构建与验收见 release/ACCEPTANCE-0.2.17.md。预览使用合成数据,不是实际账号或网速。 -构建:build/Build-Release.ps1 -Version 0.2.17 -UseExistingAssets。 - -## 以下为 0.2.16 及更早版本的历史记录 - -**2026-09-09 20:04 更新:用户明确要求发布 0.2.16 测试旧版升级提示,现已进入 0.2.15 可识别的 Git 发布通道;不是全量实机验收完成。** 非强制安装,其他兼容旧客户端也可能看到提示,0.2.15 保留,无全员通知。安装包仍是下文已绑定证据的原候选字节,未临时重编译;升级 UI/UAC/重启及 Codex 桌面长会话待验收,`acceptance_passed=false` 保留。最新发布验证见 `release/ACCEPTANCE-0.2.16.md` 顶部。 - -**0.2.16 正式候选,以 v0.2.5 为网络功能基线。** -0.2.11 和早期 0.2.12 经实机反馈失败,不再推荐安装,不推送这些版本。候选不等于完整验收或正式发布。 - -用户确认保留当前界面、自动选节点和在线升级提醒。网络接管和智能学习保持 0.2.5 基线,支持后台下发统一公网网关;更新检查和安装包下载只走 `pro.ucvl.cn` 公司公开 Git Release。0.2.16 候选调整代理域名 DNS 及传输探测,尚待真实 Codex 长连接验收。2026-09-08 本机已恢复完整 0.2.15,暂不安装或推送候选。详情见 release/ACCEPTANCE-0.2.16.md。 - -- 平台:Windows 10/11 x64;Xray-core v26.3.27。 -- 登录:平台用户名或邮箱与密码;会话用 Windows DPAPI 保存,不保存明文密码。 -- 本地端口:SOCKS 127.0.0.1:10808,HTTP 127.0.0.1:10809,仅限本机。 -- 节点:服务器自动分配 001/002/003,客户端只显示工作节点;旧美国 VPN000 已退役。003 是另行新增的硅谷服务器。 -- 界面:保留双品牌、个人信息、套餐、两块矮曲线;X 隐藏到托盘,“断开并退出”恢复网络。 - -## 连接与学习 - -按 0.2.5 顺序:无 TUN 配置校验 → 启动带 TUN 的内核 → 发现网卡 → 给 TUN 设置当前出口 DNS → 节点/DNS 旁路 → 两条 IPv4 /1 路由 → 等待 DNS。 -物理出口原默认路由与 DNS 保留,不额外强制开启系统 HTTP 代理。出站绑定实际 Wi-Fi、有线、手机热点或 Tailscale 出口。 -等待虚拟网卡 IPv4 地址就绪后,为代理域名添加本软件拥有的 NRPT 规则,查询经节点使用加密 DNS;内网及 Tailscale DNS 不改。断开时撤销本软件规则并刷新缓存。 -同机新版本之间使用跨进程独占网络租约。旧孤立内核必须校验 PID、二进制、配置路径及父进程后才能清理,活跃旧版不会被盲目结束。本机网卡故障不会将所有节点判成不可用。 -断开后撤销本软件路由和虚拟网卡。安装、更新及 TUN 连接需要管理员权限。IPv6 保留原网络路径,不能宣传全部 IPv6 接管。 - -学习恢复 0.2.5:5 分钟内同一目标 3 次有效失败才生成最长 7 天的本地规则,报告标准化失败观测。 -应用规则沿用旧版重启内核方式,可能中断已有流;不再宣传生产无中断热更或首次失败立即复测。 -服务器公司规则不因这次客户端回退被清空或重置。 - -保留自动故障切换:Codex URL 和 Google 或 OpenAI API 至少一个须取得响应;服务返回 401/403/404 只说明传输取得响应,不代表 Codex 账号和任务可用。每 5 秒调度,已健康线路至少间隔 20 秒探测、连续三轮异常才请求其他节点;新线路后台等待并容许一次重试。死亡内核不等待下一轮网络请求。实际恢复时间受探测耗时影响,学习重启期间不同时切节点;用户已断开或内核已变化后的迟到结果会被忽略。 - -## 统计与升级 - -速度和流量仅读取 Xray 的 outbound>>>proxy>>>traffic 计数器,不计 direct。 -近 5 分钟实时曲线每 5 秒采样,近 7 天代理用量来自服务端订阅聚合数据;采样失败显示暂不可用,不伪装为零。 - -升级先提示用户,同意后下载;只接受 `pro.ucvl.cn` HTTPS 公司公开 Git Release,且版本标签、安装包名称、长度和 SHA256 均通过才进入安装。 -候选升级流程:先启动安装器并校验完整临时包,再请求旧程序安全退出;备份旧文件、保存恢复记录并原子替换,主程序最后替换。失败回退,中断后重新运行安装包恢复,备份位于安装目录 `.ucvl-installer`。不触碰独立的账号和设备配置目录。成功后点击“重启纵横家”并尝试自动连接,不保证网络一定成功。系统必要的权限提示不能省略。 -程序载荷、卸载器、两个快捷方式及本软件十项 HKCU 登记统一提交;组件或登记失败时恢复旧值及其类型,不删除其它登记。记录仍待恢复时,普通客户端拒绝启动网络并提示重跑安装包。真实覆盖安装界面/UAC 尚待验收,不能把隔离事务测试当成整机升级完成。 -运行中每 15 分钟检查更新,用户暂不升级则 6 小时内不重复打扰。 -Git 版本列表和校验文件的完整读取合计限定 20 秒;尚未同意升级时查询失败约两分钟后可重试。下载完整包最多 10 分钟、连续 30 秒没有收到正文数据则停止;清理本次半包,保留已校验的旧下载,不启动安装器或断开现有连接。系统网络正常恢复后可再检查更新。 - -## 构建与验收 - -运行 build/Build-Release.ps1。构建前 Test-025Baseline.ps1 对照 Git 标签 v0.2.5: -生产路由/DNS函数和学习文件必须一致,连接顺序必须一致,自动选择和更新功能必须保留。 -构建后执行 startup、self、hot-routing 工具、api、route-lease 工具、update、network-owner、installation、uninstall 和 connection-health 十组自检。安装事务故障注入只在临时目录运行;热更工具测试通过不代表生产采用热更。 - -隔离 /32 TUN 入口、合成持续连接和计数测试,不等同于整个电脑两条 /1 接管、真实 Codex 任务或覆盖升级验收。 -更新测试采用内存 HTTP 响应和独立临时目录,不发布、不执行安装器。 -发布状态、实机结果和未完成项以当前版本验收记录为准;不将接口 401 或模拟更新检查称为真实 Codex 任务或安装验收。 - -## 分发边界 - -安装包尚未包含公司 Authenticode 签名,Windows 可能提示未知发布者。 -macOS 有独立绿色试用工程和本地候选包,尚缺 Mac 原生验收、Developer ID 和公证;状态以苹果工程验收记录为准。不要将本 Windows 包当作苹果客户端。 +# 优创⁺纵横家 Windows 客户端 + +## Windows 0.3.17 + +智能代理和全局代理优先验证已授权的 Tailscale 入口。内网代理端口或出口持续异常时,客户端通过同一节点的公网入口重新连接,并在收到经代理转发的 HTTPS 响应后显示连接成功。切换网络后重新验证代理出口,Tailscale 控制和中继流量使用直连路由。 + +### 正式发布流程 + +1. 验收客户端连接、断开及覆盖升级,发布同一构建的源码标签和安装包,从旧客户端核对更新提示及安装包摘要。 +2. 将同一版本登记到公司内部资源中心,并验证员工可下载。 +3. 在公司网站「公司动态」发布版本新闻并配一张产品图,匿名检查栏目、正文和配图。 +4. 经小小优运维发送本次更新通知,核对发送回执。发布重试时按产品、平台及版本查找现有记录。 + +## Windows 0.3.8 + +管理平台已迁移至 https://vpn.ucvl.cn/。登录、注册和平台探测统一使用新域名,直连备用地址已随迁移更新。 + +宽屏主界面采用浅蓝山水背景、连接状态横幅、调度侧栏和独立流量监控区。上传/下载可单独查看;曲线、累计量和授权状态仍来自现有采集与账户数据。小窗口保留紧凑布局,并通过“更多”访问设置、关于和退出。 + + +## Windows 0.2.18-preview.1(主动下载验证) + +加入断开后手动节点选择,并保留默认AI自动调度。Zero3私有辅助接入客户端代码已有候选,但正式设备授权执行端尚未完成,生产仍关闭;ping可达不等于本版已能使用Zero3。公司内网及用户安排的Tailscale路径均按可达性考虑,不额外限速或配置网关。公共节点保留。 + +本次仅预览发布及私有源码备份,稳定更新通道不变,不推送全员更新,不部署后台。查看 `release/RELEASE-NOTES-0.2.18-preview.1.md` 和 `release/ACCEPTANCE-0.2.18-preview.1.md` 了解验收范围及未完项。该包由 `build/Package-PrivateAuxiliaryPreview.ps1` 封装已经过保护测试的原EXE,不临时重编译;普通本地编译使用项目自带.NET8 SDK。 + +以下0.2.17及更早内容为历史记录。 + +## Windows 0.2.17 + +切网恢复与蓝白卡片界面。保留套餐、双品牌 Logo 和自动调度,只显示当前工作节点。上传/下载速度与实时曲线放在一起,本期/本次代理用量与历史曲线放在一起,小窗口自动纵向排列并滚动。 + +### 网络切换 + +监测实际默认出口的网卡、IP、网关和 DNS,变化稳定3秒后先释放旧路由/DNS接管,再绑定新出口、重建当前已授权节点连接,不等待旧路由上的平台请求。离线时释放本软件接管,网络恢复后重试;失败退避最多30秒。主动断开或退出取消重连;切网不计为节点故障,平台401/403授权检查保持有效。 + +旧 TCP 流需要应用重连,不是无缝迁移。已通过隔离状态机和受保护的本机“模拟离线→真实内核/路由重建→接口复测”测试;当前没有接通有线网卡,物理 Wi-Fi/有线互切及 Codex 已登录长会话尚未完整验收。东京 VPN002 三轮 HTTP/DNS 探测可达,但间歇性服务端问题尚未定位,不代表长期稳定。 + +### 统计和升级 + +只统计代理流量,直连不计。本次累计与网速是本机,历史沿用套餐全部设备。历史可选12小时、1天、7天、1个月(30个自然日);小时/整月展示需要配套后台明细,尚未部署新后台时保留原7天,其他范围明确提示无数据,不伪造历史。小时从后台升级后按节点上报接收时间归档,未知桶显示缺口。 + +安装包和更新仅从公司 pro.ucvl.cn Git 提供,非强制:同意后下载、校验、覆盖原安装目录并保留用户配置,完成后重启;Windows 系统授权提示仍可能出现。0.2.16 在线升级已获用户实际确认成功,本版保留该流程。此轮仅 Windows,不涉及苹果版本、ERP 文件上传或全员通知。 + +发布状态以公司 Git Release 为准;构建与验收见 release/ACCEPTANCE-0.2.17.md。预览使用合成数据,不是实际账号或网速。 +构建:build/Build-Release.ps1 -Version 0.2.17 -UseExistingAssets。 + +## 以下为 0.2.16 及更早版本的历史记录 + +**2026-09-09 20:04 更新:用户明确要求发布 0.2.16 测试旧版升级提示,现已进入 0.2.15 可识别的 Git 发布通道;不是全量实机验收完成。** 非强制安装,其他兼容旧客户端也可能看到提示,0.2.15 保留,无全员通知。安装包仍是下文已绑定证据的原候选字节,未临时重编译;升级 UI/UAC/重启及 Codex 桌面长会话待验收,`acceptance_passed=false` 保留。最新发布验证见 `release/ACCEPTANCE-0.2.16.md` 顶部。 + +**0.2.16 正式候选,以 v0.2.5 为网络功能基线。** +0.2.11 和早期 0.2.12 经实机反馈失败,不再推荐安装,不推送这些版本。候选不等于完整验收或正式发布。 + +用户确认保留当前界面、自动选节点和在线升级提醒。网络接管和智能学习保持 0.2.5 基线,支持后台下发统一公网网关;更新检查和安装包下载只走 `pro.ucvl.cn` 公司公开 Git Release。0.2.16 候选调整代理域名 DNS 及传输探测,尚待真实 Codex 长连接验收。2026-09-08 本机已恢复完整 0.2.15,暂不安装或推送候选。详情见 release/ACCEPTANCE-0.2.16.md。 + +- 平台:Windows 10/11 x64;Xray-core v26.3.27。 +- 登录:平台用户名或邮箱与密码;会话用 Windows DPAPI 保存,不保存明文密码。 +- 本地端口:SOCKS 127.0.0.1:10808,HTTP 127.0.0.1:10809,仅限本机。 +- 节点:服务器自动分配 001/002/003,客户端只显示工作节点;旧美国 VPN000 已退役。003 是另行新增的硅谷服务器。 +- 界面:保留双品牌、个人信息、套餐、两块矮曲线;X 隐藏到托盘,“断开并退出”恢复网络。 + +## 连接与学习 + +按 0.2.5 顺序:无 TUN 配置校验 → 启动带 TUN 的内核 → 发现网卡 → 给 TUN 设置当前出口 DNS → 节点/DNS 旁路 → 两条 IPv4 /1 路由 → 等待 DNS。 +物理出口原默认路由与 DNS 保留,不额外强制开启系统 HTTP 代理。出站绑定实际 Wi-Fi、有线、手机热点或 Tailscale 出口。 +等待虚拟网卡 IPv4 地址就绪后,为代理域名添加本软件拥有的 NRPT 规则,查询经节点使用加密 DNS;内网及 Tailscale DNS 不改。断开时撤销本软件规则并刷新缓存。 +同机新版本之间使用跨进程独占网络租约。旧孤立内核必须校验 PID、二进制、配置路径及父进程后才能清理,活跃旧版不会被盲目结束。本机网卡故障不会将所有节点判成不可用。 +断开后撤销本软件路由和虚拟网卡。安装、更新及 TUN 连接需要管理员权限。IPv6 保留原网络路径,不能宣传全部 IPv6 接管。 + +学习恢复 0.2.5:5 分钟内同一目标 3 次有效失败才生成最长 7 天的本地规则,报告标准化失败观测。 +应用规则沿用旧版重启内核方式,可能中断已有流;不再宣传生产无中断热更或首次失败立即复测。 +服务器公司规则不因这次客户端回退被清空或重置。 + +保留自动故障切换:Codex URL 和 Google 或 OpenAI API 至少一个须取得响应;服务返回 401/403/404 只说明传输取得响应,不代表 Codex 账号和任务可用。每 5 秒调度,已健康线路至少间隔 20 秒探测、连续三轮异常才请求其他节点;新线路后台等待并容许一次重试。死亡内核不等待下一轮网络请求。实际恢复时间受探测耗时影响,学习重启期间不同时切节点;用户已断开或内核已变化后的迟到结果会被忽略。 + +## 统计与升级 + +速度和流量仅读取 Xray 的 outbound>>>proxy>>>traffic 计数器,不计 direct。 +近 5 分钟实时曲线每 5 秒采样,近 7 天代理用量来自服务端订阅聚合数据;采样失败显示暂不可用,不伪装为零。 + +升级先提示用户,同意后下载;只接受 `pro.ucvl.cn` HTTPS 公司公开 Git Release,且版本标签、安装包名称、长度和 SHA256 均通过才进入安装。 +候选升级流程:先启动安装器并校验完整临时包,再请求旧程序安全退出;备份旧文件、保存恢复记录并原子替换,主程序最后替换。失败回退,中断后重新运行安装包恢复,备份位于安装目录 `.ucvl-installer`。不触碰独立的账号和设备配置目录。成功后点击“重启纵横家”并尝试自动连接,不保证网络一定成功。系统必要的权限提示不能省略。 +程序载荷、卸载器、两个快捷方式及本软件十项 HKCU 登记统一提交;组件或登记失败时恢复旧值及其类型,不删除其它登记。记录仍待恢复时,普通客户端拒绝启动网络并提示重跑安装包。真实覆盖安装界面/UAC 尚待验收,不能把隔离事务测试当成整机升级完成。 +运行中每 15 分钟检查更新,用户暂不升级则 6 小时内不重复打扰。 +Git 版本列表和校验文件的完整读取合计限定 20 秒;尚未同意升级时查询失败约两分钟后可重试。下载完整包最多 10 分钟、连续 30 秒没有收到正文数据则停止;清理本次半包,保留已校验的旧下载,不启动安装器或断开现有连接。系统网络正常恢复后可再检查更新。 + +## 构建与验收 + +运行 build/Build-Release.ps1。构建前 Test-025Baseline.ps1 对照 Git 标签 v0.2.5: +生产路由/DNS函数和学习文件必须一致,连接顺序必须一致,自动选择和更新功能必须保留。 +构建后执行 startup、self、hot-routing 工具、api、route-lease 工具、update、network-owner、installation、uninstall 和 connection-health 十组自检。安装事务故障注入只在临时目录运行;热更工具测试通过不代表生产采用热更。 + +隔离 /32 TUN 入口、合成持续连接和计数测试,不等同于整个电脑两条 /1 接管、真实 Codex 任务或覆盖升级验收。 +更新测试采用内存 HTTP 响应和独立临时目录,不发布、不执行安装器。 +发布状态、实机结果和未完成项以当前版本验收记录为准;不将接口 401 或模拟更新检查称为真实 Codex 任务或安装验收。 + +## 分发边界 + +安装包尚未包含公司 Authenticode 签名,Windows 可能提示未知发布者。 +macOS 有独立绿色试用工程和本地候选包,尚缺 Mac 原生验收、Developer ID 和公证;状态以苹果工程验收记录为准。不要将本 Windows 包当作苹果客户端。 diff --git a/windows/RouteLeaseSelfTest.cs b/windows/RouteLeaseSelfTest.cs index 2073424..dfd888b 100644 --- a/windows/RouteLeaseSelfTest.cs +++ b/windows/RouteLeaseSelfTest.cs @@ -1,97 +1,117 @@ -using System.Net; -using System.Text.Json; - -namespace UCVL.VPNPlus; - -internal static class RouteLeaseSelfTest -{ - private sealed class FakeTable : IRouteTable - { - internal readonly List Routes = []; - internal int FailAdd = -1, AddCount; - internal bool FailDelete; - public IReadOnlyList Snapshot() => Routes.ToArray(); - public Task AddAsync(Ipv4Route route, CancellationToken token) - { - token.ThrowIfCancellationRequested(); - if (AddCount++ == FailAdd) throw new IOException("Injected add failure"); - Routes.Add(route); - return Task.CompletedTask; - } - public Task DeleteAsync(Ipv4Route route, CancellationToken token) - { - if (FailDelete) throw new IOException("Injected delete failure"); - Routes.RemoveAll(route.SamePath); - return Task.CompletedTask; - } - } - - internal static async Task RunAsync() - { - var folder = Path.Combine(Path.GetTempPath(), "ucvl-route-unit-" + Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(folder); - var path = Path.Combine(folder, "routes.json"); - var table = new FakeTable(); - var lease = new NetworkRouteLease(path, table); - var original = new Ipv4Route("203.0.113.10", "255.255.255.255", "192.168.1.1", 10); - var split = new[] { new Ipv4Route("0.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5), - new Ipv4Route("128.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5) }; - var report = new Dictionary(); - try - { - var gateway = IPAddress.Parse("192.168.1.1"); - var physical = new TunRouting.PhysicalNetwork("Fixture Ethernet", 10, IPAddress.Parse("192.168.1.20"), - 24, gateway, [gateway]); - var management = new Ipv4Route("47.104.134.190", "255.255.255.255", "192.168.1.1", 10); - var tailnet = new Ipv4Route("100.99.142.38", "255.255.255.255", "0.0.0.0", 30); - var protectedRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(tailnet.Destination)], 20, preserveProxyRoute: true); - var publicRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(management.Destination)], 20, preserveProxyRoute: false); - report["management_ipv4_bypasses_tun_in_all_modes"] = - protectedRoutes.Count(management.SamePath) == 1 && publicRoutes.Count(management.SamePath) == 1 - && protectedRoutes.SkipLast(2).All(r => r.InterfaceIndex == physical.InterfaceIndex) - && protectedRoutes.TakeLast(2).SequenceEqual(split); - report["tailscale_and_private_proxy_routes_are_not_replaced"] = - protectedRoutes.All(r => r.Destination != tailnet.Destination) - && !TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true) - .Any(r => r.Destination == "172.16.0.111"); - table.Routes.AddRange([tailnet, management]); - await lease.ApplyAsync(protectedRoutes, CancellationToken.None); - await lease.RestoreAsync(CancellationToken.None); - report["existing_management_and_tailnet_paths_survive_cleanup"] = table.Routes.SequenceEqual([tailnet, management]); - table.Routes.Clear(); - table.AddCount = 0; - - table.Routes.Add(original); - table.FailAdd = 1; - try { await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None); } - catch (IOException) { } - report["partial_split_route_failure_rolled_back"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path); - table.FailAdd = -1; - await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None); - table.FailDelete = true; - try { await lease.RestoreAsync(CancellationToken.None); } catch (AggregateException) { } - report["failed_restore_retains_journal"] = File.Exists(path); - table.FailDelete = false; - await lease.RestoreAsync(CancellationToken.None); - report["retry_restores_without_deleting_preexisting_route"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path); - await lease.RestoreAsync(CancellationToken.None); - report["restore_is_idempotent"] = table.Routes.Count == 1; - using var cancelled = new CancellationTokenSource(); cancelled.Cancel(); - try { await lease.ApplyAsync(split, cancelled.Token); } catch (OperationCanceledException) { } - report["cancel_before_apply_preserves_original"] = table.Routes.Count == 1 && !File.Exists(path); - // Read-only native table validates the P/Invoke layout against this machine. - var native = new WindowsRouteTable().Snapshot(); - report["native_route_snapshot_has_loopback"] = native.Any(r => r.Destination == "127.0.0.0" && r.Mask == "255.0.0.0"); - report["native_on_link_hop_is_normalized"] = native.Any(r => r.Destination == "127.0.0.0" && r.NextHop == "0.0.0.0"); - report["passed"] = report.Values.All(v => v is true); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "route-lease-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); - return (bool)report["passed"] ? 0 : 31; - } - finally - { - if (File.Exists(path)) File.Delete(path); - if (File.Exists(path + ".new")) File.Delete(path + ".new"); - Directory.Delete(folder); - } - } -} +using System.Net; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class RouteLeaseSelfTest +{ + private sealed class FakeTable : IRouteTable + { + internal readonly List Routes = []; + internal int FailAdd = -1, AddCount; + internal bool FailDelete; + public IReadOnlyList Snapshot() => Routes.ToArray(); + public Task AddAsync(Ipv4Route route, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (AddCount++ == FailAdd) throw new IOException("Injected add failure"); + Routes.Add(route); + return Task.CompletedTask; + } + public Task DeleteAsync(Ipv4Route route, CancellationToken token) + { + if (FailDelete) throw new IOException("Injected delete failure"); + Routes.RemoveAll(route.SamePath); + return Task.CompletedTask; + } + } + + internal static async Task RunAsync() + { + var folder = Path.Combine(Path.GetTempPath(), "ucvl-route-unit-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + var path = Path.Combine(folder, "routes.json"); + var table = new FakeTable(); + var lease = new NetworkRouteLease(path, table); + var original = new Ipv4Route("203.0.113.10", "255.255.255.255", "192.168.1.1", 10); + var split = new[] { new Ipv4Route("0.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5), + new Ipv4Route("128.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5) }; + var report = new Dictionary(); + try + { + var gateway = IPAddress.Parse("192.168.1.1"); + var physical = new TunRouting.PhysicalNetwork("Fixture Ethernet", 10, IPAddress.Parse("192.168.1.20"), + 24, gateway, [gateway]); + var management = new Ipv4Route("47.104.134.190", "255.255.255.255", "192.168.1.1", 10); + var tailnet = new Ipv4Route("100.99.142.38", "255.255.255.255", "0.0.0.0", 30); + string[] derpAddresses = ["8.216.53.107", "47.254.94.29", "192.236.188.22"]; + var derpRoutes = derpAddresses.Select(address => new Ipv4Route(address, "255.255.255.255", "192.168.1.1", 10)).ToArray(); + var protectedRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(tailnet.Destination)], 20, preserveProxyRoute: true); + var publicRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(management.Destination)], 20, preserveProxyRoute: false); + var privateRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true); + report["management_ipv4_bypasses_tun_in_all_modes"] = + protectedRoutes.Count(management.SamePath) == 1 && publicRoutes.Count(management.SamePath) == 1 + && protectedRoutes.SkipLast(2).All(r => r.InterfaceIndex == physical.InterfaceIndex) + && protectedRoutes.TakeLast(2).SequenceEqual(split); + report["tailscale_and_private_proxy_routes_are_not_replaced"] = + protectedRoutes.All(r => r.Destination != tailnet.Destination) + && privateRoutes.All(r => r.Destination != "172.16.0.111"); + report["tailscale_derp_uses_physical_host_routes_before_tun_defaults"] = + derpRoutes.All(derp => protectedRoutes.SkipLast(2).Count(derp.SamePath) == 1) + && protectedRoutes.TakeLast(2).SequenceEqual(split); + report["derp_routes_are_added_only_for_tailscale"] = + derpRoutes.All(derp => !privateRoutes.Any(derp.SamePath) && !publicRoutes.Any(derp.SamePath)); + var preexisting = new[] { tailnet, management, derpRoutes[0] }; + table.Routes.AddRange(preexisting); + await lease.ApplyAsync(protectedRoutes, CancellationToken.None); + report["existing_derp_route_is_reused"] = table.Routes.Count(derpRoutes[0].SamePath) == 1; + await lease.RestoreAsync(CancellationToken.None); + report["existing_management_tailnet_and_derp_paths_survive_cleanup"] = + table.Routes.SequenceEqual(preexisting) && !File.Exists(path); + table.Routes.Remove(derpRoutes[0]); + var wifi = new TunRouting.PhysicalNetwork("Fixture Wi-Fi", 11, IPAddress.Parse("172.20.1.30"), + 24, IPAddress.Parse("172.20.1.1"), [IPAddress.Parse("172.20.1.1")]); + var rebound = TunRouting.CreateOwnedRoutes(wifi, [IPAddress.Parse(tailnet.Destination)], 21, preserveProxyRoute: true); + await lease.ApplyAsync(rebound, CancellationToken.None); + report["tailscale_derp_routes_rebind_to_new_physical_uplink"] = + derpRoutes.All(old => !table.Routes.Any(old.SamePath) + && table.Routes.Any((old with { InterfaceIndex = 11, NextHop = "172.20.1.1" }).SamePath)); + await lease.RestoreAsync(CancellationToken.None); + report["derp_rebind_cleanup_preserves_original_routes"] = table.Routes.SequenceEqual([tailnet, management]) && !File.Exists(path); + table.Routes.Clear(); + table.AddCount = 0; + + table.Routes.Add(original); + table.FailAdd = 1; + try { await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None); } + catch (IOException) { } + report["partial_split_route_failure_rolled_back"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path); + table.FailAdd = -1; + await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None); + table.FailDelete = true; + try { await lease.RestoreAsync(CancellationToken.None); } catch (AggregateException) { } + report["failed_restore_retains_journal"] = File.Exists(path); + table.FailDelete = false; + await lease.RestoreAsync(CancellationToken.None); + report["retry_restores_without_deleting_preexisting_route"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path); + await lease.RestoreAsync(CancellationToken.None); + report["restore_is_idempotent"] = table.Routes.Count == 1; + using var cancelled = new CancellationTokenSource(); cancelled.Cancel(); + try { await lease.ApplyAsync(split, cancelled.Token); } catch (OperationCanceledException) { } + report["cancel_before_apply_preserves_original"] = table.Routes.Count == 1 && !File.Exists(path); + // Read-only native table validates the P/Invoke layout against this machine. + var native = new WindowsRouteTable().Snapshot(); + report["native_route_snapshot_has_loopback"] = native.Any(r => r.Destination == "127.0.0.0" && r.Mask == "255.0.0.0"); + report["native_on_link_hop_is_normalized"] = native.Any(r => r.Destination == "127.0.0.0" && r.NextHop == "0.0.0.0"); + report["passed"] = report.Values.All(v => v is true); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "route-lease-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); + return (bool)report["passed"] ? 0 : 31; + } + finally + { + if (File.Exists(path)) File.Delete(path); + if (File.Exists(path + ".new")) File.Delete(path + ".new"); + Directory.Delete(folder); + } + } +} diff --git a/windows/TailnetDnsPolicy.cs b/windows/TailnetDnsPolicy.cs new file mode 100644 index 0000000..a9791d8 --- /dev/null +++ b/windows/TailnetDnsPolicy.cs @@ -0,0 +1,17 @@ +using System.Text.RegularExpressions; + +namespace UCVL.VPNPlus; + +// These namespaces carry the control, relay and MagicDNS traffic that the +// Tailscale transport itself depends on. +internal static class TailnetDnsPolicy +{ + private static readonly string[] Zones = ["tailscale.com", "ts.net"]; + internal static readonly string DomainPattern = @"(?i)(^|\.)(" + string.Join("|", Zones.Select(Regex.Escape)) + @")\.?$"; + private static readonly Regex ProtectedDomain = new(DomainPattern, RegexOptions.CultureInvariant); + + internal static bool IsProtectedDomain(string domain) => ProtectedDomain.IsMatch(domain); + + internal static bool IsProtectedSuffix(string suffix) => IsProtectedDomain(suffix) + || Zones.Any(zone => zone.EndsWith("." + suffix.TrimEnd('.'), StringComparison.OrdinalIgnoreCase)); +} diff --git a/windows/TailnetPingConfirmation.cs b/windows/TailnetEndpointConfirmation.cs similarity index 50% rename from windows/TailnetPingConfirmation.cs rename to windows/TailnetEndpointConfirmation.cs index e614c09..2ff2487 100644 --- a/windows/TailnetPingConfirmation.cs +++ b/windows/TailnetEndpointConfirmation.cs @@ -1,29 +1,32 @@ -namespace UCVL.VPNPlus; - -// A bounded round tolerates isolated ICMP loss. This is address reachability, -// never a substitute for an authenticated proxy grant or a business-site test. -internal static class TailnetPingConfirmation -{ - internal const int Attempts = 3; - internal static async Task ProbeAsync(Func> ping, - CancellationToken token, TimeSpan? budget = null) - { - token.ThrowIfCancellationRequested(); - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); - deadline.CancelAfter(budget ?? TimeSpan.FromSeconds(4)); - for (var attempt = 0; attempt < Attempts; attempt++) - { - try - { - var reachable = await ping(deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false); - token.ThrowIfCancellationRequested(); - if (reachable) return true; - } - catch (OperationCanceledException) when (!token.IsCancellationRequested && deadline.IsCancellationRequested) { return false; } - catch (OperationCanceledException) { throw; } - catch (Exception) { /* One failed ICMP attempt is inconclusive. */ } - token.ThrowIfCancellationRequested(); - } - return false; - } -} +namespace UCVL.VPNPlus; + +// Give an authorized port a full TCP probe budget. Quick failures may retry +// within the same round. The readiness policy schedules a confirmation round. +internal static class TailnetEndpointConfirmation +{ + private const int Attempts = 3; + internal static async Task ProbeAsync(Func> probe, + CancellationToken token, TimeSpan? budget = null) + { + token.ThrowIfCancellationRequested(); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(budget ?? TimeSpan.FromSeconds(TailnetTransport.EndpointProbeTimeoutSeconds)); + for (var attempt = 0; attempt < Attempts; attempt++) + { + token.ThrowIfCancellationRequested(); + if (deadline.IsCancellationRequested) return false; + try + { + var reachable = await probe(deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + if (deadline.IsCancellationRequested) return false; + if (reachable) return true; + } + catch (OperationCanceledException) when (!token.IsCancellationRequested && deadline.IsCancellationRequested) { return false; } + catch (OperationCanceledException) { throw; } + catch (Exception) { /* One failed TCP attempt is inconclusive. */ } + } + token.ThrowIfCancellationRequested(); + return false; + } +} diff --git a/windows/TailnetEndpointConfirmationSelfTest.cs b/windows/TailnetEndpointConfirmationSelfTest.cs new file mode 100644 index 0000000..f4003b3 --- /dev/null +++ b/windows/TailnetEndpointConfirmationSelfTest.cs @@ -0,0 +1,53 @@ +namespace UCVL.VPNPlus; + +internal static class TailnetEndpointConfirmationSelfTest +{ + internal static async Task> CheckAsync() + { + var checks = new Dictionary(); + var calls = 0; + var reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 2), CancellationToken.None); + checks["first_fast_tcp_failure_followed_by_success_is_reachable"] = reachable && calls == 2; + calls = 0; + reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 3), CancellationToken.None); + checks["two_fast_tcp_failures_followed_by_success_do_not_switch"] = reachable && calls == 3; + calls = 0; + reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => { calls++; return Task.FromResult(false); }, CancellationToken.None); + checks["three_fast_tcp_failures_are_one_failed_round"] = !reachable && calls == 3; + calls = 0; + reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => ++calls == 1 + ? Task.FromException(new IOException("fixture TCP failure")) : Task.FromResult(true), CancellationToken.None); + checks["one_tcp_exception_does_not_force_fallback"] = reachable && calls == 2; + calls = 0; + reachable = await TailnetEndpointConfirmation.ProbeAsync(async token => + { + calls++; + await Task.Delay(TimeSpan.FromMilliseconds(4_300), token); + return true; + }, CancellationToken.None); + checks["slow_tcp_connection_can_succeed_within_first_probe_budget"] = reachable && calls == 1; + + calls = 0; + reachable = await TailnetEndpointConfirmation.ProbeAsync(token => + { + calls++; + token.WaitHandle.WaitOne(TimeSpan.FromSeconds(2)); + return Task.FromResult(false); + }, CancellationToken.None, TimeSpan.FromMilliseconds(30)); + checks["expired_tcp_round_does_not_start_another_attempt"] = !reachable && calls == 1; + var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + reachable = await TailnetEndpointConfirmation.ProbeAsync(_ => pending.Task, CancellationToken.None, TimeSpan.FromMilliseconds(30)); + checks["uncooperative_tcp_callback_has_bounded_deadline"] = !reachable; + using var caller = new CancellationTokenSource(); caller.Cancel(); + var cancelled = false; + try { await TailnetEndpointConfirmation.ProbeAsync(_ => Task.FromResult(true), caller.Token); } + catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; } + checks["caller_cancellation_is_not_a_failed_tcp_probe"] = cancelled; + using var race = new CancellationTokenSource(); + cancelled = false; + try { await TailnetEndpointConfirmation.ProbeAsync(_ => { race.Cancel(); return Task.FromResult(true); }, race.Token); } + catch (OperationCanceledException error) { cancelled = error.CancellationToken == race.Token; } + checks["cancelled_successful_tcp_probe_cannot_publish_old_result"] = cancelled; + return checks; + } +} diff --git a/windows/TailnetPingConfirmationSelfTest.cs b/windows/TailnetPingConfirmationSelfTest.cs deleted file mode 100644 index 96df6d8..0000000 --- a/windows/TailnetPingConfirmationSelfTest.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace UCVL.VPNPlus; - -internal static class TailnetPingConfirmationSelfTest -{ - internal static async Task> CheckAsync() - { - var checks = new Dictionary(); - var calls = 0; - var reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 2), CancellationToken.None); - checks["single_lost_ping_followed_by_success_is_reachable"] = reachable && calls == 2; - calls = 0; - reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 3), CancellationToken.None); - checks["two_lost_pings_followed_by_success_do_not_switch"] = reachable && calls == 3; - calls = 0; - reachable = await TailnetPingConfirmation.ProbeAsync(_ => { calls++; return Task.FromResult(false); }, CancellationToken.None); - checks["three_failed_icmp_attempts_are_one_failed_round"] = !reachable && calls == 3; - calls = 0; - reachable = await TailnetPingConfirmation.ProbeAsync(_ => ++calls == 1 - ? Task.FromException(new IOException("fixture ping failure")) : Task.FromResult(true), CancellationToken.None); - checks["one_ping_exception_does_not_force_fallback"] = reachable && calls == 2; - var pending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - reachable = await TailnetPingConfirmation.ProbeAsync(_ => pending.Task, CancellationToken.None, TimeSpan.FromMilliseconds(30)); - checks["uncooperative_ping_callback_has_bounded_deadline"] = !reachable; - using var caller = new CancellationTokenSource(); caller.Cancel(); - var cancelled = false; - try { await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(true), caller.Token); } - catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; } - checks["caller_cancellation_is_not_a_failed_ping"] = cancelled; - using var race = new CancellationTokenSource(); - cancelled = false; - try { await TailnetPingConfirmation.ProbeAsync(_ => { race.Cancel(); return Task.FromResult(true); }, race.Token); } - catch (OperationCanceledException error) { cancelled = error.CancellationToken == race.Token; } - checks["cancelled_successful_ping_cannot_publish_old_result"] = cancelled; - return checks; - } -} diff --git a/windows/TailnetReadinessSelfTest.cs b/windows/TailnetReadinessSelfTest.cs index 8d81638..4d9cb90 100644 --- a/windows/TailnetReadinessSelfTest.cs +++ b/windows/TailnetReadinessSelfTest.cs @@ -1,63 +1,63 @@ -using System.Text.Json; - -namespace UCVL.VPNPlus; - -internal static class TailnetReadinessSelfTest -{ - internal static int Run() - { - var checks = new Dictionary(); - var policy = new TailnetReadinessPolicy(); - var current = new TailnetReadinessPolicy.Context(1, 10, true, false, true, false, true); - bool Begin(long now, out TailnetReadinessPolicy.ProbeTicket ticket) => policy.TryBegin(current, now, out ticket); - TailnetReadinessPolicy.Result Complete(TailnetReadinessPolicy.ProbeTicket ticket, long now, bool reachable) - => policy.Observe(ticket, current, now, reachable); - checks["connected_waits_ten_minutes_after_initial_selection"] = !Begin(0, out _) && policy.NextDue == 600_000; - checks["no_probe_before_ten_minutes"] = !Begin(599_999, out _); - checks["probe_due_at_ten_minutes"] = Begin(600_000, out var first); - checks["no_concurrent_probe"] = !Begin(600_001, out _); - checks["public_recovery_is_advisory"] = Complete(first, 600_100, true) == TailnetReadinessPolicy.Result.BecameReady && policy.IsReady; - checks["next_probe_ten_minutes_after_completion"] = policy.NextDue == 1_200_100 && !Begin(1_200_099, out _); - checks["ready_notifies_once"] = Begin(1_200_100, out var second) && Complete(second, 1_200_200, true) == TailnetReadinessPolicy.Result.Ready; - checks["public_failure_does_not_switch"] = Begin(1_800_200, out var failed) && Complete(failed, 1_800_300, false) == TailnetReadinessPolicy.Result.NotReady && !policy.IsReady; - checks["failure_keeps_ten_minute_interval"] = policy.NextDue == 2_400_300 && !Begin(2_400_299, out _); - checks["repeated_failure_keeps_ten_minutes"] = Begin(2_400_300, out failed) && Complete(failed, 2_400_400, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 3_000_400; - policy.Reset(); current = current with { UsesTailnet = true }; - checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000; - checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady; - checks["single_failed_round_does_not_switch_active_tailnet"] = Begin(5_200_100, out first) - && Complete(first, 5_200_200, false) == TailnetReadinessPolicy.Result.Confirming; - checks["confirmation_wait_is_bounded_five_seconds"] = !Begin(5_205_199, out _) - && Begin(5_205_200, out second); - checks["second_failed_round_confirms_domain_fallback"] = Complete(second, 5_205_300, false) == TailnetReadinessPolicy.Result.Fallback; - policy.Reset(); - checks["new_active_path_schedules_after_reset"] = !Begin(5_300_000, out _) && Begin(5_900_000, out first); - checks["loss_then_recovery_clears_confirmation"] = Complete(first, 5_900_100, false) == TailnetReadinessPolicy.Result.Confirming - && Begin(5_905_100, out second) && Complete(second, 5_905_200, true) == TailnetReadinessPolicy.Result.Ready - && policy.NextDue == 6_505_200; - policy.Reset(); - checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0; - checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first); - current = current with { Epoch = 2 }; - checks["session_epoch_fences_late_failure"] = Complete(first, 6_600_100, false) == TailnetReadinessPolicy.Result.Ignore; - checks["new_session_schedule_independent"] = policy.NextDue == 7_200_100 && !Begin(7_200_099, out _) && Begin(7_200_100, out second); - checks["old_ticket_cannot_consume_current_ticket"] = Complete(first, 7_200_101, false) == TailnetReadinessPolicy.Result.Ignore && Complete(second, 7_200_200, true) == TailnetReadinessPolicy.Result.Ready; - checks["core_change_fences_late_failure"] = Begin(7_800_200, out first) && policy.Observe(first, current with { CoreId = 11 }, 7_800_300, false) == TailnetReadinessPolicy.Result.Ignore; - current = current with { CoreId = 11 }; - checks["transport_change_fences_late_failure"] = Begin(8_400_300, out first) && policy.Observe(first, current with { UsesTailnet = false }, 8_400_400, false) == TailnetReadinessPolicy.Result.Ignore; - current = current with { UsesTailnet = false }; - checks["disconnect_fences_late_result"] = Begin(9_000_400, out first) && policy.Observe(first, current with { Wanted = false }, 9_000_500, true) == TailnetReadinessPolicy.Result.Ignore; - checks["reconnect_has_fresh_interval"] = !Begin(9_000_600, out _) && Begin(9_600_600, out first); - checks["grant_withdrawal_fences_late_result"] = policy.Observe(first, current with { HasAuthorizedCandidate = false }, 9_600_700, true) == TailnetReadinessPolicy.Result.Ignore; - checks["busy_does_not_start_probe"] = !policy.TryBegin(current with { Busy = true }, 10_000_000, out _); - checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore; - foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } }) - checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _); - foreach (var check in TailnetPingConfirmationSelfTest.CheckAsync().GetAwaiter().GetResult()) checks.Add(check.Key, check.Value); - var passed = checks.Values.All(v => v); - foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key); - Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks"); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "tailnet-readiness-self-test.json"), JsonSerializer.Serialize(new { kind = "ten_minute_tailnet_recheck_policy", network_modified = false, transport_switched = false, proxy_authenticated = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true })); - return passed ? 0 : 84; - } -} +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class TailnetReadinessSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + var policy = new TailnetReadinessPolicy(); + var current = new TailnetReadinessPolicy.Context(1, 10, true, false, true, false, true); + bool Begin(long now, out TailnetReadinessPolicy.ProbeTicket ticket) => policy.TryBegin(current, now, out ticket); + TailnetReadinessPolicy.Result Complete(TailnetReadinessPolicy.ProbeTicket ticket, long now, bool reachable) + => policy.Observe(ticket, current, now, reachable); + checks["connected_waits_ten_minutes_after_initial_selection"] = !Begin(0, out _) && policy.NextDue == 600_000; + checks["no_probe_before_ten_minutes"] = !Begin(599_999, out _); + checks["probe_due_at_ten_minutes"] = Begin(600_000, out var first); + checks["no_concurrent_probe"] = !Begin(600_001, out _); + checks["public_recovery_is_advisory"] = Complete(first, 600_100, true) == TailnetReadinessPolicy.Result.BecameReady && policy.IsReady; + checks["next_probe_ten_minutes_after_completion"] = policy.NextDue == 1_200_100 && !Begin(1_200_099, out _); + checks["ready_notifies_once"] = Begin(1_200_100, out var second) && Complete(second, 1_200_200, true) == TailnetReadinessPolicy.Result.Ready; + checks["public_failure_does_not_switch"] = Begin(1_800_200, out var failed) && Complete(failed, 1_800_300, false) == TailnetReadinessPolicy.Result.NotReady && !policy.IsReady; + checks["failure_keeps_ten_minute_interval"] = policy.NextDue == 2_400_300 && !Begin(2_400_299, out _); + checks["repeated_failure_keeps_ten_minutes"] = Begin(2_400_300, out failed) && Complete(failed, 2_400_400, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 3_000_400; + policy.Reset(); current = current with { UsesTailnet = true }; + checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000; + checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady; + checks["single_failed_round_does_not_switch_active_tailnet"] = Begin(5_200_100, out first) + && Complete(first, 5_200_200, false) == TailnetReadinessPolicy.Result.Confirming; + checks["confirmation_wait_is_bounded_five_seconds"] = !Begin(5_205_199, out _) + && Begin(5_205_200, out second); + checks["second_failed_round_confirms_domain_fallback"] = Complete(second, 5_205_300, false) == TailnetReadinessPolicy.Result.Fallback; + policy.Reset(); + checks["new_active_path_schedules_after_reset"] = !Begin(5_300_000, out _) && Begin(5_900_000, out first); + checks["loss_then_recovery_clears_confirmation"] = Complete(first, 5_900_100, false) == TailnetReadinessPolicy.Result.Confirming + && Begin(5_905_100, out second) && Complete(second, 5_905_200, true) == TailnetReadinessPolicy.Result.Ready + && policy.NextDue == 6_505_200; + policy.Reset(); + checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0; + checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first); + current = current with { Epoch = 2 }; + checks["session_epoch_fences_late_failure"] = Complete(first, 6_600_100, false) == TailnetReadinessPolicy.Result.Ignore; + checks["new_session_schedule_independent"] = policy.NextDue == 7_200_100 && !Begin(7_200_099, out _) && Begin(7_200_100, out second); + checks["old_ticket_cannot_consume_current_ticket"] = Complete(first, 7_200_101, false) == TailnetReadinessPolicy.Result.Ignore && Complete(second, 7_200_200, true) == TailnetReadinessPolicy.Result.Ready; + checks["core_change_fences_late_failure"] = Begin(7_800_200, out first) && policy.Observe(first, current with { CoreId = 11 }, 7_800_300, false) == TailnetReadinessPolicy.Result.Ignore; + current = current with { CoreId = 11 }; + checks["transport_change_fences_late_failure"] = Begin(8_400_300, out first) && policy.Observe(first, current with { UsesTailnet = false }, 8_400_400, false) == TailnetReadinessPolicy.Result.Ignore; + current = current with { UsesTailnet = false }; + checks["disconnect_fences_late_result"] = Begin(9_000_400, out first) && policy.Observe(first, current with { Wanted = false }, 9_000_500, true) == TailnetReadinessPolicy.Result.Ignore; + checks["reconnect_has_fresh_interval"] = !Begin(9_000_600, out _) && Begin(9_600_600, out first); + checks["grant_withdrawal_fences_late_result"] = policy.Observe(first, current with { HasAuthorizedCandidate = false }, 9_600_700, true) == TailnetReadinessPolicy.Result.Ignore; + checks["busy_does_not_start_probe"] = !policy.TryBegin(current with { Busy = true }, 10_000_000, out _); + checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore; + foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } }) + checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _); + foreach (var check in TailnetEndpointConfirmationSelfTest.CheckAsync().GetAwaiter().GetResult()) checks.Add(check.Key, check.Value); + var passed = checks.Values.All(v => v); + foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key); + Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks"); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "tailnet-readiness-self-test.json"), JsonSerializer.Serialize(new { kind = "ten_minute_tailnet_recheck_policy", network_modified = false, transport_switched = false, proxy_authenticated = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 84; + } +} diff --git a/windows/TailnetTransport.cs b/windows/TailnetTransport.cs index b742f19..92115b0 100644 --- a/windows/TailnetTransport.cs +++ b/windows/TailnetTransport.cs @@ -1,212 +1,212 @@ -using System.Net; -using System.Net.NetworkInformation; -using System.Net.Sockets; -using System.Text.Json.Nodes; - -namespace UCVL.VPNPlus; - -// A transport alternative for the SAME authorized public node. This does not -// start/configure Tailscale, change its ACLs, or turn reachability into identity. -internal static class TailnetTransport -{ - internal const string Marker = "ucvl_tailnet_transport"; - internal static bool IsTailnetAddress(string? value) => - IPAddress.TryParse(value, out var ip) && ip.AddressFamily == AddressFamily.InterNetwork - && ip.ToString() == value && ip.GetAddressBytes()[0] == 100 - && ip.GetAddressBytes()[1] is >= 64 and <= 127 - && value is not ("100.100.100.100" or "100.64.0.0" or "100.127.255.255"); - - internal static string? TryPrepare(ConfigResponse response, bool allowKnownEndpoints = false) - => TryPrepare(response, out _, allowKnownEndpoints); - - internal static string? TryPrepare(ConfigResponse response, out string reason, bool allowKnownEndpoints = false) - { - reason = "explicit_endpoint"; - var endpoint = response.TailscaleEndpoint; - if (endpoint is null) - { - if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; } - endpoint = KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints, out reason); - if (endpoint is null) return null; - } - var source = reason; - reason = "endpoint_contract_unsupported"; - if (endpoint.Contract != 1) return null; - reason = "endpoint_node_mismatch"; - if (endpoint.NodeSlug != response.Node.Slug || string.IsNullOrWhiteSpace(endpoint.NodeSlug)) return null; - reason = "endpoint_address_invalid"; - if (!IsTailnetAddress(endpoint.Address)) return null; - reason = "endpoint_port_invalid"; - if (endpoint.Port is < 1 or > 65535) return null; - reason = "config_contract_unsupported"; - if (response.ConfigContract != 2) return null; - reason = "scope_unsupported"; - if (response.ConnectionScope is not ("" or "public")) return null; - reason = "route_mode_unsupported"; - if (response.RouteMode is not ("smart" or "global")) return null; - try - { - var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject(); - reason = "config_scope_or_marker_invalid"; - if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null; - var proxy = Proxy(root); - reason = "proxy_identity_unsupported"; - if (proxy is null) return null; - var server = proxy["settings"]!["vnext"]![0]!.AsObject(); - // Preserve users/flow/encryption/Reality key/SNI/shortId and all rules. - // Never send the management access token to this endpoint. - server["address"] = endpoint.Address; - server["port"] = endpoint.Port; - root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port }; - reason = source; - return root.ToJsonString(); - } - catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException) - { reason = "config_invalid"; return null; } // Invalid optional metadata never breaks the original ingress. - } - - internal static JsonObject? Proxy(JsonObject root) - { - if (root["outbounds"] is not JsonArray outbounds) return null; - var proxies = outbounds.OfType().Where(o => o["tag"]?.GetValue() == "proxy").ToArray(); - if (proxies.Length != 1) return null; - var proxy = proxies[0]; - if (proxy["protocol"]?.GetValue() != "vless" - || proxy["settings"]?["vnext"] is not JsonArray { Count: 1 } servers - || servers[0]?["users"] is not JsonArray { Count: > 0 } - || proxy["streamSettings"]?["security"]?.GetValue() != "reality" - || proxy["streamSettings"]?["network"]?.GetValue() is not ("tcp" or "raw") - || proxy["streamSettings"]?["realitySettings"] is not JsonObject reality - || string.IsNullOrWhiteSpace(reality["serverName"]?.GetValue()) - || string.IsNullOrWhiteSpace((reality["password"] ?? reality["publicKey"])?.GetValue())) return null; - return proxy; - } - - internal static string? Address(JsonObject root) - { - if (!root.ContainsKey(Marker)) return null; - var address = root[Marker]?["address"]?.GetValue(); - var port = root[Marker]?["port"]?.GetValue(); - var proxy = Proxy(root); - if (!IsTailnetAddress(address) || port is null or < 1 or > 65535 || proxy is null - || proxy["settings"]!["vnext"]![0]!["address"]?.GetValue() != address - || proxy["settings"]!["vnext"]![0]!["port"]?.GetValue() != port) - throw new InvalidOperationException("Tailscale 入口与授权节点配置不一致。"); - return address; - } - - internal static string? Address(string json) => Address(JsonNode.Parse(json)!.AsObject()); - - internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue(); - - // Selection checks only ICMP through the existing OS network. It never - // queries or changes Tailscale; authenticated proxy health is checked after - // starting the chosen authorized transport, separately from reachability. - internal static async Task ProbeEndpointAsync(string address, int port, CancellationToken token) - { - token.ThrowIfCancellationRequested(); - if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false; - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); - deadline.CancelAfter(TimeSpan.FromSeconds(5)); - try - { - RequireProbeRoute(address); - // The first connection may need to establish a Tailscale path. - // Test the actual proxy listener instead of gating on ICMP. - using var socket = new TcpClient(AddressFamily.InterNetwork); - await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false); - return true; - } - catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; } - catch (Exception e) when (e is SocketException or NetworkInformationException - or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; } - } - - internal static bool SameAuthorizedFallback(string current, string? fallback) - { - if (fallback is null) return false; - try - { - var a = JsonNode.Parse(current)!.AsObject(); var b = JsonNode.Parse(fallback)!.AsObject(); - if (Address(a) is null || b.ContainsKey(Marker) || PrivateAuxiliaryRuntime.IsPrivate(b)) return false; - var bp = Proxy(b); if (bp is null) return false; - a.Remove(Marker); - var server = Proxy(a)!["settings"]!["vnext"]![0]!; - server["address"] = bp["settings"]!["vnext"]![0]!["address"]!.DeepClone(); - server["port"] = bp["settings"]!["vnext"]![0]!["port"]!.DeepClone(); - return JsonNode.DeepEquals(a, b); - } - catch { return false; } - } - - // Read only. No CLI/process/service dependency: user owns the underlying network. - // Ask Windows which existing interface owns this IP path, including a valid - // default route. No adapter-name, service or route-prefix prerequisite. - // This UDP Connect sends no payload. Refuse our own TUN to avoid recursion; - // no /32 or user route is manufactured or removed. - internal static string RequireExistingRoute(string address) => ResolveRoute(address, false); - - // Candidate discovery requires a specific existing route to the authorized - // Tailnet address. A generic internet default must not carry probe packets. - internal static void RequireProbeRoute(string address) => ResolveRoute(address, true); - - private static string ResolveRoute(string address, bool requireSpecificRoute) - { - if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。"); - using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - route.Connect(new IPEndPoint(IPAddress.Parse(address), 443)); - var local = (route.LocalEndPoint as IPEndPoint)?.Address; - var owner = NetworkInterface.GetAllNetworkInterfaces() - .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback - && !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase)) - .FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local))); - if (owner is null) - throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。"); - if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index - || SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet { index }) != index)) - throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。"); - return owner.Name; - } - - internal static int? SelectRoute(string address, IEnumerable routes, IReadOnlySet usable) - { - if (!IsTailnetAddress(address)) return null; - var target = IPAddress.Parse(address).GetAddressBytes(); - var matches = new List<(Ipv4Route Route, int Prefix)>(); - foreach (var route in routes) - { - if (!IPAddress.TryParse(route.Mask, out var mask) || mask.AddressFamily != AddressFamily.InterNetwork - || !IPAddress.TryParse(route.Destination, out var dest) || dest.AddressFamily != AddressFamily.InterNetwork) continue; - var m = mask.GetAddressBytes(); var d = dest.GetAddressBytes(); - var prefix = 0; var zero = false; var valid = true; - foreach (var b in m) for (var bit = 7; bit >= 0; bit--) - { - var one = (b & (1 << bit)) != 0; - if (one && zero) valid = false; - if (one) prefix++; else zero = true; - } - if (valid && prefix > 1 && Enumerable.Range(0, 4).All(i => (target[i] & m[i]) == (d[i] & m[i]))) - matches.Add((route, prefix)); - } - if (matches.Count == 0) return null; - var longest = matches.Max(r => r.Prefix); - var preferred = matches.Where(r => r.Prefix == longest).Select(r => r.Route).ToArray(); - // Ambiguous, down, or our own more-specific route: fail closed. - var indices = preferred.Select(r => r.InterfaceIndex).Distinct().ToArray(); - return indices.Length == 1 && usable.Contains(indices[0]) ? indices[0] : null; - } -} - -// Monotonic cooldown affects only NEW attempts, not healthy existing sessions. -internal sealed class TailnetPreference -{ - private readonly Dictionary _cooldowns = new(StringComparer.Ordinal); - internal bool DomainOnly { get; private set; } - // Only an explicit user connect action resets failures. Automatic recovery - // continues respecting the existing monotonic cooldown. - internal void ResetForUserConnect() { _cooldowns.Clear(); DomainOnly = false; } - internal void CommitDomainFallback() => DomainOnly = true; - internal void ReleaseDomainFallbackAfterNodeFailure() => DomainOnly = false; - internal bool MayTry(string slug, long now) => !DomainOnly && (!_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry); - internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000; -} +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +// A transport alternative for the SAME authorized public node. This does not +// start/configure Tailscale, change its ACLs, or turn reachability into identity. +internal static class TailnetTransport +{ + internal const string Marker = "ucvl_tailnet_transport"; + internal const int EndpointProbeTimeoutSeconds = 5; + internal static bool IsTailnetAddress(string? value) => + IPAddress.TryParse(value, out var ip) && ip.AddressFamily == AddressFamily.InterNetwork + && ip.ToString() == value && ip.GetAddressBytes()[0] == 100 + && ip.GetAddressBytes()[1] is >= 64 and <= 127 + && value is not ("100.100.100.100" or "100.64.0.0" or "100.127.255.255"); + + internal static string? TryPrepare(ConfigResponse response, bool allowKnownEndpoints = false) + => TryPrepare(response, out _, allowKnownEndpoints); + + internal static string? TryPrepare(ConfigResponse response, out string reason, bool allowKnownEndpoints = false) + { + reason = "explicit_endpoint"; + var endpoint = response.TailscaleEndpoint; + if (endpoint is null) + { + if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; } + endpoint = KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints, out reason); + if (endpoint is null) return null; + } + var source = reason; + reason = "endpoint_contract_unsupported"; + if (endpoint.Contract != 1) return null; + reason = "endpoint_node_mismatch"; + if (endpoint.NodeSlug != response.Node.Slug || string.IsNullOrWhiteSpace(endpoint.NodeSlug)) return null; + reason = "endpoint_address_invalid"; + if (!IsTailnetAddress(endpoint.Address)) return null; + reason = "endpoint_port_invalid"; + if (endpoint.Port is < 1 or > 65535) return null; + reason = "config_contract_unsupported"; + if (response.ConfigContract != 2) return null; + reason = "scope_unsupported"; + if (response.ConnectionScope is not ("" or "public")) return null; + reason = "route_mode_unsupported"; + if (response.RouteMode is not ("smart" or "global")) return null; + try + { + var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject(); + reason = "config_scope_or_marker_invalid"; + if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null; + var proxy = Proxy(root); + reason = "proxy_identity_unsupported"; + if (proxy is null) return null; + var server = proxy["settings"]!["vnext"]![0]!.AsObject(); + // Preserve users/flow/encryption/Reality key/SNI/shortId and all rules. + // Never send the management access token to this endpoint. + server["address"] = endpoint.Address; + server["port"] = endpoint.Port; + root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port }; + reason = source; + return root.ToJsonString(); + } + catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException) + { reason = "config_invalid"; return null; } // Invalid optional metadata never breaks the original ingress. + } + + internal static JsonObject? Proxy(JsonObject root) + { + if (root["outbounds"] is not JsonArray outbounds) return null; + var proxies = outbounds.OfType().Where(o => o["tag"]?.GetValue() == "proxy").ToArray(); + if (proxies.Length != 1) return null; + var proxy = proxies[0]; + if (proxy["protocol"]?.GetValue() != "vless" + || proxy["settings"]?["vnext"] is not JsonArray { Count: 1 } servers + || servers[0]?["users"] is not JsonArray { Count: > 0 } + || proxy["streamSettings"]?["security"]?.GetValue() != "reality" + || proxy["streamSettings"]?["network"]?.GetValue() is not ("tcp" or "raw") + || proxy["streamSettings"]?["realitySettings"] is not JsonObject reality + || string.IsNullOrWhiteSpace(reality["serverName"]?.GetValue()) + || string.IsNullOrWhiteSpace((reality["password"] ?? reality["publicKey"])?.GetValue())) return null; + return proxy; + } + + internal static string? Address(JsonObject root) + { + if (!root.ContainsKey(Marker)) return null; + var address = root[Marker]?["address"]?.GetValue(); + var port = root[Marker]?["port"]?.GetValue(); + var proxy = Proxy(root); + if (!IsTailnetAddress(address) || port is null or < 1 or > 65535 || proxy is null + || proxy["settings"]!["vnext"]![0]!["address"]?.GetValue() != address + || proxy["settings"]!["vnext"]![0]!["port"]?.GetValue() != port) + throw new InvalidOperationException("Tailscale 入口与授权节点配置不一致。"); + return address; + } + + internal static string? Address(string json) => Address(JsonNode.Parse(json)!.AsObject()); + + internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue(); + + // Check the authorized proxy port through the existing OS route. Proxy + // authentication and egress are verified separately after startup. + internal static async Task ProbeEndpointAsync(string address, int port, CancellationToken token) + { + token.ThrowIfCancellationRequested(); + if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false; + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds)); + try + { + RequireProbeRoute(address); + // The first connection may need to establish a Tailscale path. + // Test the actual proxy listener instead of gating on ICMP. + using var socket = new TcpClient(AddressFamily.InterNetwork); + await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false); + return true; + } + catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; } + catch (Exception e) when (e is SocketException or NetworkInformationException + or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; } + } + + internal static bool SameAuthorizedFallback(string current, string? fallback) + { + if (fallback is null) return false; + try + { + var a = JsonNode.Parse(current)!.AsObject(); var b = JsonNode.Parse(fallback)!.AsObject(); + if (Address(a) is null || b.ContainsKey(Marker) || PrivateAuxiliaryRuntime.IsPrivate(b)) return false; + var bp = Proxy(b); if (bp is null) return false; + a.Remove(Marker); + var server = Proxy(a)!["settings"]!["vnext"]![0]!; + server["address"] = bp["settings"]!["vnext"]![0]!["address"]!.DeepClone(); + server["port"] = bp["settings"]!["vnext"]![0]!["port"]!.DeepClone(); + return JsonNode.DeepEquals(a, b); + } + catch { return false; } + } + + // Read only. No CLI/process/service dependency: user owns the underlying network. + // Ask Windows which existing interface owns this IP path, including a valid + // default route. No adapter-name, service or route-prefix prerequisite. + // This UDP Connect sends no payload. Refuse our own TUN to avoid recursion; + // no /32 or user route is manufactured or removed. + internal static string RequireExistingRoute(string address) => ResolveRoute(address, false); + + // Candidate discovery requires a specific existing route to the authorized + // Tailnet address. A generic internet default must not carry probe packets. + internal static void RequireProbeRoute(string address) => ResolveRoute(address, true); + + private static string ResolveRoute(string address, bool requireSpecificRoute) + { + if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。"); + using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + route.Connect(new IPEndPoint(IPAddress.Parse(address), 443)); + var local = (route.LocalEndPoint as IPEndPoint)?.Address; + var owner = NetworkInterface.GetAllNetworkInterfaces() + .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback + && !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase)) + .FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local))); + if (owner is null) + throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。"); + if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index + || SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet { index }) != index)) + throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。"); + return owner.Name; + } + + internal static int? SelectRoute(string address, IEnumerable routes, IReadOnlySet usable) + { + if (!IsTailnetAddress(address)) return null; + var target = IPAddress.Parse(address).GetAddressBytes(); + var matches = new List<(Ipv4Route Route, int Prefix)>(); + foreach (var route in routes) + { + if (!IPAddress.TryParse(route.Mask, out var mask) || mask.AddressFamily != AddressFamily.InterNetwork + || !IPAddress.TryParse(route.Destination, out var dest) || dest.AddressFamily != AddressFamily.InterNetwork) continue; + var m = mask.GetAddressBytes(); var d = dest.GetAddressBytes(); + var prefix = 0; var zero = false; var valid = true; + foreach (var b in m) for (var bit = 7; bit >= 0; bit--) + { + var one = (b & (1 << bit)) != 0; + if (one && zero) valid = false; + if (one) prefix++; else zero = true; + } + if (valid && prefix > 1 && Enumerable.Range(0, 4).All(i => (target[i] & m[i]) == (d[i] & m[i]))) + matches.Add((route, prefix)); + } + if (matches.Count == 0) return null; + var longest = matches.Max(r => r.Prefix); + var preferred = matches.Where(r => r.Prefix == longest).Select(r => r.Route).ToArray(); + // Ambiguous, down, or our own more-specific route: fail closed. + var indices = preferred.Select(r => r.InterfaceIndex).Distinct().ToArray(); + return indices.Length == 1 && usable.Contains(indices[0]) ? indices[0] : null; + } +} + +// Monotonic cooldown affects only NEW attempts, not healthy existing sessions. +internal sealed class TailnetPreference +{ + private readonly Dictionary _cooldowns = new(StringComparer.Ordinal); + internal bool DomainOnly { get; private set; } + // Only an explicit user connect action resets failures. Automatic recovery + // continues respecting the existing monotonic cooldown. + internal void ResetForUserConnect() { _cooldowns.Clear(); DomainOnly = false; } + internal void CommitDomainFallback() => DomainOnly = true; + internal void ReleaseDomainFallbackAfterNodeFailure() => DomainOnly = false; + internal bool MayTry(string slug, long now) => !DomainOnly && (!_cooldowns.TryGetValue(slug, out var expiry) || now >= expiry); + internal void Failed(string slug, long now) => _cooldowns[slug] = now + 5 * 60_000; +} diff --git a/windows/TailnetTransportSelfTest.cs b/windows/TailnetTransportSelfTest.cs index 47605db..b359ba0 100644 --- a/windows/TailnetTransportSelfTest.cs +++ b/windows/TailnetTransportSelfTest.cs @@ -1,429 +1,479 @@ -using System.Text.Json; -using System.Text.Json.Nodes; - -namespace UCVL.VPNPlus; - -internal static class TailnetTransportSelfTest -{ - internal static async Task RunAsync() - { - var checks = new Dictionary(); - ConfigResponse Sample(Action? change = null) - { - var root = JsonNode.Parse(""" - { - "config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart", - "tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.99.142.38","port":10803}, - "config":{ - "inbounds":[],"outbounds":[ - {"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"002.vpn.toplc.cn","port":11082, - "users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]}, - "streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}}, - {"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}], - "routing":{"rules":[]}} - } - """)!.AsObject(); - change?.Invoke(root); - return JsonSerializer.Deserialize(root.ToJsonString())!; - } - string Host(string json) => JsonNode.Parse(json)!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]!.GetValue(); - var response = Sample(); - var original = response.GetRuntimeConfigJson(); - var prepared = TailnetTransport.TryPrepare(response)!; - var clone = JsonNode.Parse(prepared)!.AsObject(); - clone.Remove(TailnetTransport.Marker); - clone["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "002.vpn.toplc.cn"; - clone["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11082; - checks["only_address_port_metadata_change"] = JsonNode.DeepEquals(clone, JsonNode.Parse(original)); - checks["input_not_mutated"] = original == response.GetRuntimeConfigJson(); - checks["tokyo_uses_backend_not_ingress_port"] = JsonNode.Parse(prepared)!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]!.GetValue() == 10803; - checks["silicon_endpoint_supported"] = Host(TailnetTransport.TryPrepare(Sample(r => { - r["tailscale_endpoint"]!["address"] = "100.124.242.104"; r["tailscale_endpoint"]!["port"] = 11083; - }))!) == "100.124.242.104"; - foreach (var address in new[] { "127.0.0.1", "8.8.8.8", "172.16.0.111", "100.100.100.100", "100.64.0.0", "100.127.255.255", "100.128.0.1", "100.63.255.255", "100.099.142.38", "100.99.142.38/32", "::1", "example.com" }) - checks["reject_address_" + address] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["address"] = address)) is null; - foreach (var port in new[] { 0, -1, 65536 }) - checks["reject_port_" + port] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["port"] = port)) is null; - checks["wrong_node_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["node_slug"] = "other")) is null; - checks["wrong_contract_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["contract"] = 99)) is null; - checks["wrong_config_contract_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config_contract"] = 3)) is null; - checks["private_scope_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["connection_scope"] = "private_auxiliary")) is null; - checks["direct_mode_no_alternate"] = TailnetTransport.TryPrepare(Sample(r => r["route_mode"] = "direct")) is null; - checks["legacy_response_no_alternate"] = TailnetTransport.TryPrepare(Sample(r => r.Remove("tailscale_endpoint"))) is null; - checks["plaintext_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["security"] = "none")) is null; - checks["wrong_protocol_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["protocol"] = "socks")) is null; - checks["missing_identity_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["realitySettings"]!.AsObject().Remove("publicKey"))) is null; - checks["duplicate_proxy_rejected"] = TailnetTransport.TryPrepare(Sample(r => { - var o = r["config"]!["outbounds"]!.AsArray(); o.Add(o[0]!.DeepClone()); - })) is null; - var runtime = JsonNode.Parse(TunConfigBuilder.Build(prepared, "Phone", false, includeTun:false, tailnetInterfaceName:"UserNetwork"))!; - checks["proxy_binds_user_route"] = runtime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "UserNetwork"; - checks["direct_stays_physical"] = runtime["outbounds"]![1]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "Phone"; - checks["metadata_not_sent_to_xray"] = runtime[TailnetTransport.Marker] is null; - checks["no_tun_in_fixture"] = runtime["inbounds"]!.AsArray().Count == 0; - checks["missing_route_binding_rejected"] = Throws(() => TunConfigBuilder.Build(prepared, "Phone", false, includeTun:false)); - var altered = JsonNode.Parse(prepared)!.AsObject(); altered[TailnetTransport.Marker]!["address"] = "100.65.1.1"; - checks["metadata_config_mismatch_rejected"] = Throws(() => TailnetTransport.Address(altered)); - var usable = new HashSet { 9, 34 }; - var route = new Ipv4Route("100.64.0.0", "255.192.0.0", "0.0.0.0", 34); - checks["existing_overlay_route"] = TailnetTransport.SelectRoute("100.99.142.38", [route], usable) == 34; - checks["user_gateway_host_route"] = TailnetTransport.SelectRoute("100.99.142.38", [new("100.99.142.38","255.255.255.255","172.16.0.1",9)],usable)==9; - checks["default_and_tun_not_sufficient"] = TailnetTransport.SelectRoute("100.99.142.38", [new("0.0.0.0","0.0.0.0","1.1.1.1",9), new("0.0.0.0","128.0.0.0","0.0.0.0",34)], usable) is null; - checks["down_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route], new HashSet{9}) is null; - checks["more_specific_own_tun_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,new("100.99.142.38","255.255.255.255","0.0.0.0",99)],usable) is null; - checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null; - checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null; - checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null; - - var preference = new TailnetPreference(); - long tick = 100; - var starts = new List(); var stops = 0; var probes = 0; var routeReads = 0; - var statuses = new List(); - Task Start(string json, CancellationToken token) { token.ThrowIfCancellationRequested(); starts.Add(Host(json)); return Task.CompletedTask; } - Task Stop() { stops++; return Task.CompletedTask; } - Task Healthy(CancellationToken token) { token.ThrowIfCancellationRequested(); probes++; return Task.FromResult(true); } - void Route(string _) { routeReads++; } - var selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route, _=>{}, ()=>tick, CancellationToken.None); - checks["success_one_start_no_stop"] = selected && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==0 && probes==1; - starts.Clear(); probes=0; - selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, _=>Task.FromResult(false), Route,statuses.Add,()=>tick,CancellationToken.None); - checks["failed_proof_falls_back_same_node"] = !selected && starts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}) && stops==1; - checks["failed_proof_status_identifies_protocol_and_public_fallback"] = statuses.Last() == "Tailscale 协议或代理出口验证失败,回退同一节点公网入口"; - starts.Clear(); routeReads=0; - selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route,_=>{},()=>tick+299999,CancellationToken.None); - checks["cooldown_skips_route_and_probe"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && routeReads==0 && probes==0; - checks["domain_fallback_stays_sticky_after_five_minutes"] = !preference.MayTry("tokyo",tick+300000) - && !preference.MayTry("tokyo",tick+86_400_000); - checks["domain_fallback_blocks_other_internal_nodes_this_session"] = !preference.MayTry("silicon",tick); - preference.ResetForUserConnect(); - checks["explicit_user_connect_resets_domain_choice"] = preference.MayTry("tokyo",tick+1) && preference.MayTry("silicon",tick+1); - starts.Clear(); statuses.Clear(); - selected = await NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,_=>throw new IOException("SYNTHETIC_SECRET route unavailable"),statuses.Add,()=>tick,CancellationToken.None); - checks["route_read_failure_keeps_original"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - checks["route_failure_status_is_specific_and_redacted"] = statuses.SequenceEqual(new[]{"Tailscale 无独立内网路由,使用同一节点公网入口"}); - starts.Clear(); var failStarts=0; - selected = await NodeTransportConnector.ConnectAsync(response,new(),(json,token)=> { - failStarts++; if (failStarts==1) throw new IOException("fixture startup failure"); return Start(json,token); - },Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); - checks["start_failure_same_node_fallback"] = !selected && failStarts==2 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - starts.Clear(); - checks["restore_failure_stops_sequence"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(),Start, - ()=>throw new IOException("fixture restore failure"),_=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None)) - && starts.SequenceEqual(new[]{"100.99.142.38"}); - starts.Clear(); - checks["local_network_failure_no_fallback"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(), - (_,_)=>throw new LocalNetworkException("fixture local failure"),Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None)) && starts.Count==0; - using var cancel = new CancellationTokenSource(); starts.Clear(); var priorStops=stops; - checks["user_cancel_never_falls_back"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(), - (json,token)=> { starts.Add(Host(json)); cancel.Cancel(); token.ThrowIfCancellationRequested(); return Task.CompletedTask; }, - Stop,Healthy,Route,_=>{},()=>tick,cancel.Token)) && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==priorStops; - starts.Clear(); - checks["pre_cancel_has_no_side_effect"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,cancel.Token)) && starts.Count==0; - starts.Clear(); routeReads=0; probes=0; - selected = await NodeTransportConnector.ConnectAsync(Sample(r=>r.Remove("tailscale_endpoint")),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); - checks["old_backend_original_only"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && routeReads==0 && probes==0; - checks["fallback_same_authorization"] = TailnetTransport.SameAuthorizedFallback(prepared,original); - checks["fallback_changed_credentials_denied"] = !TailnetTransport.SameAuthorizedFallback(prepared, - original.Replace("11111111-1111-1111-1111-111111111111","22222222-2222-2222-2222-222222222222")); - checks["fallback_changed_identity_denied"] = !TailnetTransport.SameAuthorizedFallback(prepared,original.Replace("fixture-key","wrong-key")); - starts.Clear(); var beforeStops=stops; - var rebound = await NodeTransportConnector.RebindAsync(prepared,original,(json,token)=> { - starts.Add(Host(json)); if (TailnetTransport.Address(json) is not null) throw new IOException("new phone network has no overlay route"); - return Task.CompletedTask; - },Stop,Healthy,CancellationToken.None); - checks["handover_lost_overlay_same_node_fallback"] = rebound==original && starts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}) && stops==beforeStops+1; - starts.Clear(); beforeStops=stops; - rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None); - checks["handover_healthy_overlay_kept"] = rebound==prepared && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==beforeStops; - starts.Clear(); - checks["handover_missing_fallback_denied"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,null,Start,Stop,Healthy,CancellationToken.None)) && starts.Count==0; - starts.Clear(); - checks["handover_restore_failure_no_second_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,original,Start, - ()=>throw new IOException("fixture restore failure"),_=>Task.FromResult(false),CancellationToken.None)) && starts.Count==1; - starts.Clear(); - checks["handover_cancel_no_fallback"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,cancel.Token)) && starts.Count==0; - var merged = LearningPolicy.Merge(LearningPolicy.DirectFirst(prepared),new RoutingManifest { - Contract=1,Revision=new string('0',64),Rules=[] }); - var learningRouting=JsonNode.Parse(TunConfigBuilder.BuildLearningRouting(merged,"Phone",18091,18092,"UserNetwork"))!.AsObject(); - checks["real_learning_build_accepts_tailnet_binding"] = learningRouting.Count==1 && learningRouting["routing"] is JsonObject; - checks["learning_update_cannot_replace_outbounds"] = learningRouting["outbounds"] is null && learningRouting[TailnetTransport.Marker] is null; - var newNetwork = new TunRouting.PhysicalNetwork("PhoneFixture",9,System.Net.IPAddress.Parse("192.0.2.2"),24, - System.Net.IPAddress.Parse("192.0.2.1"),[System.Net.IPAddress.Parse("192.0.2.1")]); - var handoverRuntime = new HandoverFixture { BoundNetworkFingerprint="old-network", Current=prepared, - Rebind=()=>NodeTransportConnector.RebindAsync(prepared,original,(json,_)=> { - if (TailnetTransport.Address(json) is not null) throw new IOException("fixture route disappeared"); - return Task.CompletedTask; - },()=>Task.CompletedTask,_=>Task.FromResult(true),CancellationToken.None), - NextFingerprint=PhysicalUplink.Fingerprint(newNetwork) }; - var handover = new NetworkHandover(handoverRuntime,()=>3000); - await handover.ObserveAsync(new(true,newNetwork),0,CancellationToken.None); - var result = await handover.ObserveAsync(new(true,newNetwork),3000,CancellationToken.None); - checks["handover_pending_clears_after_same_node_fallback"] = result==NetworkHandover.Result.Recovered - && !handover.Pending && !handover.Settling && handoverRuntime.Current==original; - var cachedConfig = prepared; var failedStarts = new List(); - checks["handover_double_failure_retains_original"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(cachedConfig,original, - (json,_)=> { cachedConfig=json; failedStarts.Add(Host(json)); throw new IOException("fixture both paths unavailable"); }, - ()=>Task.CompletedTask,_=>Task.FromResult(false),CancellationToken.None)) - && cachedConfig==original && failedStarts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}); - starts.Clear(); probes=0; - rebound = await NodeTransportConnector.RebindAsync(cachedConfig,original,Start,Stop,Healthy,CancellationToken.None); - checks["handover_next_retry_public_only"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && probes==0; - starts.Clear(); var internalCancelledStarts=0; - selected = await NodeTransportConnector.ConnectAsync(response,new(),(json,token)=> { - if (++internalCancelledStarts==1) throw new OperationCanceledException("fixture internal deadline"); - return Start(json,token); - },Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); - checks["internal_timeout_falls_back_not_user_cancel"] = !selected && internalCancelledStarts==2 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - - ConfigResponse Known(Action? change = null) => Sample(r => { - r.Remove("tailscale_endpoint"); r["node"]!["slug"] = "aliyun-tokyo-002"; - change?.Invoke(r); - }); - var known = Known(); - var compatible = TailnetTransport.TryPrepare(known, allowKnownEndpoints: true)!; - checks["known_tokyo_compatibility_mapping"] = Host(compatible) == "100.99.142.38" && TailnetTransport.Port(compatible) == 10803; - checks["known_compatibility_still_same_authorization"] = TailnetTransport.SameAuthorizedFallback(compatible, known.GetRuntimeConfigJson()); - checks["known_compatibility_requires_mapping_permission"] = TailnetTransport.TryPrepare(known) is null; - checks["known_mapping_flag_is_not_identity_policy"] = KnownTailnetEndpoints.Resolve(known, allowCompatibilityMapping:true) is not null - && KnownTailnetEndpoints.Resolve(known, allowCompatibilityMapping:false) is null; - checks["explicit_null_disables_known_mapping"] = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = null), true) is null; - checks["invalid_explicit_metadata_never_uses_known_mapping"] = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject()), true) is null; - checks["unknown_named_node_does_not_use_known_mapping"] = TailnetTransport.TryPrepare(Sample(r => r.Remove("tailscale_endpoint")), true) is null; - checks["known_changed_public_host_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null; - checks["known_changed_public_port_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null; - checks["known_wrong_protocol_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["protocol"] = "socks"), true) is null; - checks["known_plaintext_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["security"] = "none"), true) is null; - checks["known_missing_reality_identity_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["realitySettings"]!.AsObject().Remove("publicKey")), true) is null; - checks["known_wrong_contract_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config_contract"] = 1), true) is null; - checks["known_private_scope_rejected"] = TailnetTransport.TryPrepare(Known(r => r["connection_scope"] = "private_auxiliary"), true) is null; - checks["known_direct_mode_unchanged"] = TailnetTransport.TryPrepare(Known(r => r["route_mode"] = "direct"), true) is null; - var silicon = TailnetTransport.TryPrepare(Known(r => { - r["node"]!["slug"] = "aliyun-siliconvalley-003"; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "003.vpn.toplc.cn"; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083; - }), true)!; - checks["known_silicon_exact_mapping"] = Host(silicon) == "100.124.242.104" && TailnetTransport.Port(silicon) == 11083; - ConfigResponse NewYork(Action? change = null) => Known(r => { - r["node"]!["slug"] = "racknerd-newyork-004"; r["node"]!["name"] = "VPN004"; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.toplc.cn"; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084; - change?.Invoke(r); - }); - var newYork = NewYork(); - var newYorkOriginal = newYork.GetRuntimeConfigJson(); - var newYorkPrepared = TailnetTransport.TryPrepare(newYork, true); - checks["known_newyork_exact_mapping"] = newYorkPrepared is not null - && Host(newYorkPrepared) == "100.67.30.7" && TailnetTransport.Port(newYorkPrepared) == 11084; - checks["known_newyork_requires_mapping_permission"] = TailnetTransport.TryPrepare(newYork) is null; - checks["known_newyork_same_authorized_fallback"] = newYorkPrepared is not null - && TailnetTransport.SameAuthorizedFallback(newYorkPrepared, newYorkOriginal); - var newYorkRestored = newYorkPrepared is null ? null : JsonNode.Parse(newYorkPrepared)!.AsObject(); - if (newYorkRestored is not null) - { - newYorkRestored.Remove(TailnetTransport.Marker); - newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.toplc.cn"; - newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084; - } - checks["known_newyork_preserves_all_credentials_and_rules"] = newYorkRestored is not null - && JsonNode.DeepEquals(newYorkRestored, JsonNode.Parse(newYorkOriginal)) - && newYork.GetRuntimeConfigJson() == newYorkOriginal; - checks["known_newyork_changed_host_rejected"] = TailnetTransport.TryPrepare(NewYork(r => - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null; - checks["known_newyork_changed_port_rejected"] = TailnetTransport.TryPrepare(NewYork(r => - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null; - checks["known_newyork_changed_slug_rejected"] = TailnetTransport.TryPrepare(NewYork(r => - r["node"]!["slug"] = "unapproved-newyork"), true) is null; - checks["known_newyork_explicit_null_disables_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = null), true) is null; - checks["known_newyork_invalid_metadata_never_uses_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject()), true) is null; - var newYorkExplicit = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject { - ["contract"] = 1, ["node_slug"] = "racknerd-newyork-004", ["address"] = "100.65.1.9", ["port"] = 2345 - }), true); - checks["known_newyork_server_metadata_remains_authoritative"] = newYorkExplicit is not null - && Host(newYorkExplicit) == "100.65.1.9" && TailnetTransport.Port(newYorkExplicit) == 2345; - var newYorkStarts = new List(); var newYorkStops = 0; var newYorkProbes = 0; - var newYorkSelected = await NodeTransportConnector.ConnectAsync(newYork, new(), - (json, _) => { newYorkStarts.Add(json); return Task.CompletedTask; }, - () => { newYorkStops++; return Task.CompletedTask; }, - _ => { newYorkProbes++; return Task.FromResult(false); }, _ => { }, _ => { }, () => tick, CancellationToken.None, - allowKnownEndpoints: true, endpointProbe: (address, port, _) => Task.FromResult(address == "100.67.30.7" && port == 11084)); - checks["known_newyork_failed_proxy_falls_back_only_same_authorized_node"] = !newYorkSelected - && newYorkStarts.Count == 2 && Host(newYorkStarts[0]) == "100.67.30.7" - && newYorkStarts[1] == newYorkOriginal && newYorkStops == 1 && newYorkProbes == 1; - var future = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject { - ["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345 - }), true)!; - checks["explicit_server_metadata_takes_priority"] = Host(future) == "100.65.1.9" && TailnetTransport.Port(future) == 2345; - var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.toplc.cn", ["ipv4"] = "59.110.91.17" }); - checks["compatibility_checks_node_before_gateway_rewrite"] = Host(TailnetTransport.TryPrepare(gatewayKnown, true)!) == "100.99.142.38"; - checks["compatibility_fallback_keeps_api_public_gateway"] = TailnetTransport.SameAuthorizedFallback( - TailnetTransport.TryPrepare(gatewayKnown, true)!, gatewayKnown.GetRuntimeConfigJson()) && Host(gatewayKnown.GetRuntimeConfigJson()) == "59.110.91.17"; - - starts.Clear(); beforeStops = stops; probes = 0; var preflights = 0; - selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(address,port,_)=> { - preflights++; checks["preflight_exact_tokyo_endpoint"] = address == "100.99.142.38" && port == 10803; - return Task.FromResult(true); - }); - checks["compatible_success_verified_before_label"] = selected && preflights == 1 && probes == 1 && stops == beforeStops - && starts.SequenceEqual(new[]{"100.99.142.38"}); - starts.Clear(); beforeStops = stops; probes = 0; statuses.Clear(); var deniedPreference = new TailnetPreference(); - selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,statuses.Add,()=>tick,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false)); - checks["closed_port_skips_tailnet_start_and_stop"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops == beforeStops && probes == 0; - checks["endpoint_unreachable_status_is_distinct_from_route_failure"] = statuses.Last() == "Tailscale 代理端口不可达,使用同一节点公网入口"; - checks["closed_port_sets_node_cooldown"] = !deniedPreference.MayTry(known.Node.Slug,tick+1); - starts.Clear(); - selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("must not probe during cooldown")); - checks["preflight_not_repeated_in_cooldown"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - deniedPreference.Failed("other-node",tick); - deniedPreference.ResetForUserConnect(); - checks["user_connect_reset_clears_node_cooldowns"] = deniedPreference.MayTry(known.Node.Slug,tick+1) && deniedPreference.MayTry("other-node",tick+1); - starts.Clear(); preflights = 0; probes = 0; - selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=> { preflights++; return Task.FromResult(true); }); - checks["manual_reset_reprobes_and_requires_protocol_health"] = selected && preflights == 1 && probes == 1 && starts.SequenceEqual(new[]{"100.99.142.38"}); - deniedPreference.Failed(known.Node.Slug,tick+2); - starts.Clear(); preflights = 0; probes = 0; - selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+3,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=> { preflights++; return Task.FromResult(true); }); - checks["automatic_retry_keeps_cooldown_after_later_failure"] = !selected && preflights == 0 && probes == 0 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - starts.Clear(); using var preflightCancel = new CancellationTokenSource(); - checks["preflight_cancel_keeps_both_paths_unstarted"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,preflightCancel.Token, - allowKnownEndpoints:true, endpointProbe:(_,_,ct)=> { preflightCancel.Cancel(); ct.ThrowIfCancellationRequested(); return Task.FromResult(true); })) && starts.Count == 0; - starts.Clear(); probes = 0; - selected = await NodeTransportConnector.ConnectAsync(Known(r=>r["tailscale_endpoint"]=null),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("explicit null must not probe")); - checks["explicit_disabled_transport_never_probed"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && probes == 0; - - TailnetTransport.TryPrepare(Known(r=>r["tailscale_endpoint"]=null), out var skipReason, true); - checks["diagnostic_explicit_null_is_not_missing_metadata"] = skipReason == "explicit_endpoint_disabled"; - TailnetTransport.TryPrepare(Known(r=>r["config_contract"]=1), out skipReason, true); - checks["diagnostic_unknown_contract_preserves_rejection"] = skipReason == "config_contract_unsupported"; - TailnetTransport.TryPrepare(Known(r=>r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="other.example.com"), out skipReason, true); - checks["diagnostic_known_ingress_mismatch_is_distinct"] = skipReason == "known_original_ingress_mismatch"; - TailnetTransport.TryPrepare(known, out skipReason, true); - checks["diagnostic_compatibility_source_identified"] = skipReason == "known_endpoint"; - var diagnostics = new List(); - starts.Clear(); beforeStops=stops; - selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, - allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false), diagnostic:diagnostics.Add); - checks["unreachable_tailnet_connects_same_node_without_public_probe"] = - !selected && starts.SequenceEqual(["002.vpn.toplc.cn"]) && stops==beforeStops; - checks["diagnostics_persist_specific_probe_failure"] = diagnostics.Any(d=>d.Event=="tailnet_skipped" && d.Reason=="endpoint_unreachable" && d.Node==known.Node.Slug); - starts.Clear(); diagnostics.Clear(); beforeStops=stops; - selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop, - _=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None,allowKnownEndpoints:true, - endpointProbe:(_,_,_)=>Task.FromResult(true),diagnostic:diagnostics.Add); - checks["failed_auth_cleans_up_before_same_node_public_fallback"] = !selected - && starts.SequenceEqual(["100.99.142.38", "002.vpn.toplc.cn"]) && stops==beforeStops+1; - starts.Clear(); diagnostics.Clear(); - var heldPreference = new TailnetPreference(); heldPreference.Failed(known.Node.Slug,tick); - selected = await NodeTransportConnector.ConnectAsync(known,heldPreference,Start,Stop,Healthy, - Route,_=>{},()=>tick+1,CancellationToken.None,allowKnownEndpoints:true,diagnostic:diagnostics.Add); - checks["tailnet_cooldown_keeps_same_node_public_route"] = !selected - && starts.SequenceEqual(["002.vpn.toplc.cn"]) && diagnostics.First().Reason=="cooldown_active"; - var safeDiagnostic = new TransportDiagnostic("selected\nconfig", "SYNTHETIC_SECRET?\r\n", new string('n',120)).SafeMessage; - checks["diagnostics_line_and_identifier_bounded"] = !safeDiagnostic.Contains('\n') && !safeDiagnostic.Contains('\r') && !safeDiagnostic.Contains('?') && safeDiagnostic.Length<260; - - starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear(); - rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, - preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add); - checks["handover_public_never_rechecks_or_promotes_internal"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) - && stops==beforeStops && preflights==0 && routeReads==0 && probes==0; - checks["handover_reports_public_choice"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="public_ingress"); - starts.Clear(); beforeStops=stops; probes=0; - rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, - preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false)); - checks["handover_unreachable_alternate_keeps_public_without_replacement_attempt"] = rebound==original - && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops==beforeStops && probes==0; - starts.Clear(); beforeStops=stops; - rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,_=>Task.FromResult(false),CancellationToken.None, - preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true)); - checks["handover_public_does_not_restart_internal_even_when_probe_would_succeed"] = rebound==original - && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops==beforeStops; - starts.Clear(); - try { - rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, - preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true)); - checks["handover_ignores_unused_preferred_credentials"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - } catch { checks["handover_ignores_unused_preferred_credentials"] = false; } - starts.Clear(); - try { - rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, - preferredTailnetConfig:prepared,requireRoute:Route); - checks["handover_public_needs_no_internal_probe"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - } catch { checks["handover_public_needs_no_internal_probe"] = false; } - starts.Clear(); - checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token, - preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0; - - // A failed primary does not suppress the backup's authorized Tailnet. - var backup = Sample(r=> { - r["node"]!["slug"]="silicon"; - r["tailscale_endpoint"]!["node_slug"]="silicon"; - r["tailscale_endpoint"]!["address"]="100.124.242.104"; - r["tailscale_endpoint"]!["port"]=11083; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="003.vpn.toplc.cn"; - r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]=11083; - }); - starts.Clear(); beforeStops=stops; - var retryPreference = new TailnetPreference(); - async Task FailPrimaryPublic(string config, CancellationToken token) - { - await Start(config, token); - if (Host(config) == "002.vpn.toplc.cn") throw new IOException("fixture public connection failure"); - } - var primaryFailed = await ThrowsAsync(() => NodeTransportConnector.ConnectAsync(response, retryPreference, - FailPrimaryPublic, Stop, _ => Task.FromResult(false), Route, _ => { }, () => tick, CancellationToken.None, - endpointProbe: (_, _, _) => Task.FromResult(true))); - retryPreference.ReleaseDomainFallbackAfterNodeFailure(); - var backupProbes = new List(); - var connectedSecond = await NodeTransportConnector.ConnectAsync(backup, retryPreference, Start, Stop, Healthy, - Route, _ => { }, () => tick + 1, CancellationToken.None, - endpointProbe: (address, _, _) => { backupProbes.Add(address); return Task.FromResult(true); }); - checks["confirmed_failure_tries_backup_after_same_node_public"] = primaryFailed && connectedSecond - && starts.SequenceEqual(["100.99.142.38", "002.vpn.toplc.cn", "100.124.242.104"]) && stops==beforeStops+1; - checks["alternate_probe_only_targets_its_authorized_tailnet_ip"] = backupProbes.SequenceEqual(["100.124.242.104"]); - checks["primary_cooldown_does_not_cool_other_node"] = !retryPreference.MayTry("tokyo",tick+1) - && retryPreference.MayTry("silicon",tick+1); - starts.Clear(); - rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None, - endpointProbe:(_,_,_)=>Task.FromResult(false)); - checks["handover_ping_failure_uses_domain_without_internal_start"] = rebound==original - && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); - var privateResponse = Sample(r => { - r["connection_scope"] = "private_auxiliary"; r["config_contract"] = 3; - r["config_expires_at"] = DateTimeOffset.UtcNow.AddMinutes(2).ToString("O"); - r["config"]!["outbounds"]![0] = new JsonObject { - ["tag"]="proxy",["protocol"]="socks",["settings"]=new JsonObject { - ["servers"]=new JsonArray(new JsonObject {["address"]="172.16.0.111",["port"]=18081}) } - }; - }); - var privatePreference = new TailnetPreference(); - await NodeTransportConnector.ConnectAsync(privateResponse,privatePreference,(_,_)=>Task.CompletedTask, - Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); - checks["private_ip_success_is_not_domain_fallback"] = !privatePreference.DomainOnly - && privatePreference.MayTry("tokyo",tick+1); - var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true, - production_network_actions=Array.Empty(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." }; - File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true})); - return report.passed ? 0 : 81; - } - private static bool Throws(Action action) { try { action(); return false; } catch { return true; } } - private static async Task ThrowsAsync(Func action) { try { await action(); return false; } catch { return true; } } - private sealed class HandoverFixture : IHandoverRuntime - { - public string? BoundNetworkFingerprint { get; set; } - public bool CanRebindNetwork => true; - public bool IsRunning => true; - internal string? NextFingerprint; - internal string Current = ""; - internal Func> Rebind = null!; - public Task SuspendForNetworkChangeAsync(CancellationToken token) => Task.CompletedTask; - public async Task RebindNetworkAsync(CancellationToken token) - { - token.ThrowIfCancellationRequested(); Current=await Rebind(); BoundNetworkFingerprint=NextFingerprint; - } - } -} +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +internal static class TailnetTransportSelfTest +{ + internal static async Task RunAsync() + { + var checks = new Dictionary(); + ConfigResponse Sample(Action? change = null) + { + var root = JsonNode.Parse(""" + { + "config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart", + "tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.99.142.38","port":10803}, + "config":{ + "inbounds":[],"outbounds":[ + {"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"002.vpn.toplc.cn","port":11082, + "users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]}, + "streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}}, + {"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}], + "routing":{"rules":[]}} + } + """)!.AsObject(); + change?.Invoke(root); + return JsonSerializer.Deserialize(root.ToJsonString())!; + } + string Host(string json) => JsonNode.Parse(json)!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]!.GetValue(); + var response = Sample(); + var original = response.GetRuntimeConfigJson(); + var prepared = TailnetTransport.TryPrepare(response)!; + var clone = JsonNode.Parse(prepared)!.AsObject(); + clone.Remove(TailnetTransport.Marker); + clone["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "002.vpn.toplc.cn"; + clone["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11082; + checks["only_address_port_metadata_change"] = JsonNode.DeepEquals(clone, JsonNode.Parse(original)); + checks["input_not_mutated"] = original == response.GetRuntimeConfigJson(); + checks["tokyo_uses_backend_not_ingress_port"] = JsonNode.Parse(prepared)!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]!.GetValue() == 10803; + checks["silicon_endpoint_supported"] = Host(TailnetTransport.TryPrepare(Sample(r => { + r["tailscale_endpoint"]!["address"] = "100.124.242.104"; r["tailscale_endpoint"]!["port"] = 11083; + }))!) == "100.124.242.104"; + foreach (var address in new[] { "127.0.0.1", "8.8.8.8", "172.16.0.111", "100.100.100.100", "100.64.0.0", "100.127.255.255", "100.128.0.1", "100.63.255.255", "100.099.142.38", "100.99.142.38/32", "::1", "example.com" }) + checks["reject_address_" + address] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["address"] = address)) is null; + foreach (var port in new[] { 0, -1, 65536 }) + checks["reject_port_" + port] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["port"] = port)) is null; + checks["wrong_node_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["node_slug"] = "other")) is null; + checks["wrong_contract_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["tailscale_endpoint"]!["contract"] = 99)) is null; + checks["wrong_config_contract_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config_contract"] = 3)) is null; + checks["private_scope_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["connection_scope"] = "private_auxiliary")) is null; + checks["direct_mode_no_alternate"] = TailnetTransport.TryPrepare(Sample(r => r["route_mode"] = "direct")) is null; + checks["legacy_response_no_alternate"] = TailnetTransport.TryPrepare(Sample(r => r.Remove("tailscale_endpoint"))) is null; + checks["plaintext_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["security"] = "none")) is null; + checks["wrong_protocol_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["protocol"] = "socks")) is null; + checks["missing_identity_rejected"] = TailnetTransport.TryPrepare(Sample(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["realitySettings"]!.AsObject().Remove("publicKey"))) is null; + checks["duplicate_proxy_rejected"] = TailnetTransport.TryPrepare(Sample(r => { + var o = r["config"]!["outbounds"]!.AsArray(); o.Add(o[0]!.DeepClone()); + })) is null; + var runtime = JsonNode.Parse(TunConfigBuilder.Build(prepared, "Phone", false, includeTun:false, tailnetInterfaceName:"UserNetwork"))!; + checks["proxy_binds_user_route"] = runtime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "UserNetwork"; + checks["direct_stays_physical"] = runtime["outbounds"]![1]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue() == "Phone"; + checks["metadata_not_sent_to_xray"] = runtime[TailnetTransport.Marker] is null; + checks["no_tun_in_fixture"] = runtime["inbounds"]!.AsArray().Count == 0; + checks["missing_route_binding_rejected"] = Throws(() => TunConfigBuilder.Build(prepared, "Phone", false, includeTun:false)); + var altered = JsonNode.Parse(prepared)!.AsObject(); altered[TailnetTransport.Marker]!["address"] = "100.65.1.1"; + checks["metadata_config_mismatch_rejected"] = Throws(() => TailnetTransport.Address(altered)); + var usable = new HashSet { 9, 34 }; + var route = new Ipv4Route("100.64.0.0", "255.192.0.0", "0.0.0.0", 34); + checks["existing_overlay_route"] = TailnetTransport.SelectRoute("100.99.142.38", [route], usable) == 34; + checks["user_gateway_host_route"] = TailnetTransport.SelectRoute("100.99.142.38", [new("100.99.142.38","255.255.255.255","172.16.0.1",9)],usable)==9; + checks["default_and_tun_not_sufficient"] = TailnetTransport.SelectRoute("100.99.142.38", [new("0.0.0.0","0.0.0.0","1.1.1.1",9), new("0.0.0.0","128.0.0.0","0.0.0.0",34)], usable) is null; + checks["down_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route], new HashSet{9}) is null; + checks["more_specific_own_tun_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,new("100.99.142.38","255.255.255.255","0.0.0.0",99)],usable) is null; + checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null; + checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null; + checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null; + + var preference = new TailnetPreference(); + long tick = 100; + var starts = new List(); var stops = 0; var probes = 0; var routeReads = 0; + var statuses = new List(); + Task Start(string json, CancellationToken token) { token.ThrowIfCancellationRequested(); starts.Add(Host(json)); return Task.CompletedTask; } + Task Stop() { stops++; return Task.CompletedTask; } + Task Healthy(CancellationToken token) { token.ThrowIfCancellationRequested(); probes++; return Task.FromResult(true); } + Task OnlyPublicHealthy(CancellationToken token) + { + token.ThrowIfCancellationRequested(); probes++; + return Task.FromResult(starts.Last() == "002.vpn.toplc.cn"); + } + void Route(string _) { routeReads++; } + var selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route, _=>{}, ()=>tick, CancellationToken.None); + checks["success_one_start_no_stop"] = selected && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==0 && probes==1; + starts.Clear(); probes=0; + selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, OnlyPublicHealthy, Route,statuses.Add,()=>tick,CancellationToken.None); + checks["failed_proof_falls_back_same_node"] = !selected && starts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}) && stops==1 && probes==2; + checks["failed_proof_status_identifies_protocol_and_public_fallback"] = statuses.Last() == "Tailscale 协议或代理出口验证失败,回退同一节点公网入口"; + starts.Clear(); routeReads=0; probes=0; + selected = await NodeTransportConnector.ConnectAsync(response, preference, Start, Stop, Healthy, Route,_=>{},()=>tick+299999,CancellationToken.None); + checks["cooldown_skips_tailnet_route_but_verifies_public"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && routeReads==0 && probes==1; + checks["domain_fallback_stays_sticky_after_five_minutes"] = !preference.MayTry("tokyo",tick+300000) + && !preference.MayTry("tokyo",tick+86_400_000); + checks["domain_fallback_blocks_other_internal_nodes_this_session"] = !preference.MayTry("silicon",tick); + preference.ResetForUserConnect(); + checks["explicit_user_connect_resets_domain_choice"] = preference.MayTry("tokyo",tick+1) && preference.MayTry("silicon",tick+1); + starts.Clear(); statuses.Clear(); + selected = await NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,_=>throw new IOException("SYNTHETIC_SECRET route unavailable"),statuses.Add,()=>tick,CancellationToken.None); + checks["route_read_failure_keeps_original"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + checks["route_failure_status_is_specific_and_redacted"] = statuses.SequenceEqual(new[]{"Tailscale 无独立内网路由,使用同一节点公网入口"}); + starts.Clear(); var failStarts=0; + selected = await NodeTransportConnector.ConnectAsync(response,new(),(json,token)=> { + failStarts++; if (failStarts==1) throw new IOException("fixture startup failure"); return Start(json,token); + },Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); + checks["start_failure_same_node_fallback"] = !selected && failStarts==2 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + starts.Clear(); + checks["restore_failure_stops_sequence"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(),Start, + ()=>throw new IOException("fixture restore failure"),_=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None)) + && starts.SequenceEqual(new[]{"100.99.142.38"}); + starts.Clear(); + checks["local_network_failure_no_fallback"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(), + (_,_)=>throw new LocalNetworkException("fixture local failure"),Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None)) && starts.Count==0; + using var cancel = new CancellationTokenSource(); starts.Clear(); var priorStops=stops; + checks["user_cancel_never_falls_back"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(), + (json,token)=> { starts.Add(Host(json)); cancel.Cancel(); token.ThrowIfCancellationRequested(); return Task.CompletedTask; }, + Stop,Healthy,Route,_=>{},()=>tick,cancel.Token)) && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==priorStops; + starts.Clear(); + checks["pre_cancel_has_no_side_effect"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(response,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,cancel.Token)) && starts.Count==0; + starts.Clear(); routeReads=0; probes=0; + selected = await NodeTransportConnector.ConnectAsync(Sample(r=>r.Remove("tailscale_endpoint")),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); + checks["old_backend_original_only"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && routeReads==0 && probes==1; + checks["fallback_same_authorization"] = TailnetTransport.SameAuthorizedFallback(prepared,original); + checks["fallback_changed_credentials_denied"] = !TailnetTransport.SameAuthorizedFallback(prepared, + original.Replace("11111111-1111-1111-1111-111111111111","22222222-2222-2222-2222-222222222222")); + checks["fallback_changed_identity_denied"] = !TailnetTransport.SameAuthorizedFallback(prepared,original.Replace("fixture-key","wrong-key")); + var publicOnly = Sample(r => r.Remove("tailscale_endpoint")); + starts.Clear(); probes = 0; + var publicDiagnostics = new List(); + checks["public_connect_rejects_unverified_egress"] = await ThrowsAsync(() => NodeTransportConnector.ConnectAsync( + publicOnly, new(), Start, Stop, _ => { probes++; return Task.FromResult(false); }, Route, _ => { }, + () => tick, CancellationToken.None, diagnostic: publicDiagnostics.Add)) + && starts.SequenceEqual(["002.vpn.toplc.cn"]) && probes == 1 + && publicDiagnostics.All(d => d.Event != "selected") + && publicDiagnostics.Any(d => d.Event == "public_failed" && d.Reason == "public_proxy_health_failed"); + starts.Clear(); publicDiagnostics.Clear(); + using var publicCancel = new CancellationTokenSource(); + var publicPreference = new TailnetPreference(); + try + { + await NodeTransportConnector.ConnectAsync(publicOnly, publicPreference, Start, Stop, + _ => { publicCancel.Cancel(); return Task.FromResult(false); }, Route, _ => { }, () => tick, + publicCancel.Token, diagnostic: publicDiagnostics.Add); + checks["cancelled_public_egress_never_commits_fallback"] = false; + } + catch (OperationCanceledException e) + { + checks["cancelled_public_egress_never_commits_fallback"] = e.CancellationToken == publicCancel.Token + && !publicPreference.DomainOnly && publicDiagnostics.All(d => d.Event != "selected"); + } + starts.Clear(); probes = 0; + checks["handover_fallback_rejects_unverified_public_egress"] = await ThrowsAsync(() => NodeTransportConnector.RebindAsync( + prepared, original, Start, Stop, _ => { probes++; return Task.FromResult(false); }, CancellationToken.None, + endpointProbe: (_, _, _) => Task.FromResult(false))) + && starts.SequenceEqual(["002.vpn.toplc.cn"]) && probes == 1; + starts.Clear(); probes = 0; + checks["handover_unverified_tailnet_and_public_egress_fails"] = await ThrowsAsync(() => NodeTransportConnector.RebindAsync( + prepared, original, Start, Stop, _ => { probes++; return Task.FromResult(false); }, CancellationToken.None)) + && starts.SequenceEqual(["100.99.142.38", "002.vpn.toplc.cn"]) && probes == 2; + starts.Clear(); var beforeStops=stops; + var rebound = await NodeTransportConnector.RebindAsync(prepared,original,(json,token)=> { + starts.Add(Host(json)); if (TailnetTransport.Address(json) is not null) throw new IOException("new phone network has no overlay route"); + return Task.CompletedTask; + },Stop,Healthy,CancellationToken.None); + checks["handover_lost_overlay_same_node_fallback"] = rebound==original && starts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}) && stops==beforeStops+1; + starts.Clear(); beforeStops=stops; + rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None); + checks["handover_healthy_overlay_kept"] = rebound==prepared && starts.SequenceEqual(new[]{"100.99.142.38"}) && stops==beforeStops; + starts.Clear(); + checks["handover_missing_fallback_denied"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,null,Start,Stop,Healthy,CancellationToken.None)) && starts.Count==0; + starts.Clear(); + checks["handover_restore_failure_no_second_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,original,Start, + ()=>throw new IOException("fixture restore failure"),_=>Task.FromResult(false),CancellationToken.None)) && starts.Count==1; + starts.Clear(); + checks["handover_cancel_no_fallback"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,cancel.Token)) && starts.Count==0; + var merged = LearningPolicy.Merge(LearningPolicy.DirectFirst(prepared),new RoutingManifest { + Contract=1,Revision=new string('0',64),Rules=[] }); + var learningRouting=JsonNode.Parse(TunConfigBuilder.BuildLearningRouting(merged,"Phone",18091,18092,"UserNetwork"))!.AsObject(); + checks["real_learning_build_accepts_tailnet_binding"] = learningRouting.Count==1 && learningRouting["routing"] is JsonObject; + checks["learning_update_cannot_replace_outbounds"] = learningRouting["outbounds"] is null && learningRouting[TailnetTransport.Marker] is null; + var newNetwork = new TunRouting.PhysicalNetwork("PhoneFixture",9,System.Net.IPAddress.Parse("192.0.2.2"),24, + System.Net.IPAddress.Parse("192.0.2.1"),[System.Net.IPAddress.Parse("192.0.2.1")]); + var handoverRuntime = new HandoverFixture { BoundNetworkFingerprint="old-network", Current=prepared, + Rebind=()=>NodeTransportConnector.RebindAsync(prepared,original,(json,_)=> { + if (TailnetTransport.Address(json) is not null) throw new IOException("fixture route disappeared"); + return Task.CompletedTask; + },()=>Task.CompletedTask,_=>Task.FromResult(true),CancellationToken.None), + NextFingerprint=PhysicalUplink.Fingerprint(newNetwork) }; + var handover = new NetworkHandover(handoverRuntime,()=>3000); + await handover.ObserveAsync(new(true,newNetwork),0,CancellationToken.None); + var result = await handover.ObserveAsync(new(true,newNetwork),3000,CancellationToken.None); + checks["handover_pending_clears_after_same_node_fallback"] = result==NetworkHandover.Result.Recovered + && !handover.Pending && !handover.Settling && handoverRuntime.Current==original; + var cachedConfig = prepared; var failedStarts = new List(); + checks["handover_double_failure_retains_original"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(cachedConfig,original, + (json,_)=> { cachedConfig=json; failedStarts.Add(Host(json)); throw new IOException("fixture both paths unavailable"); }, + ()=>Task.CompletedTask,_=>Task.FromResult(false),CancellationToken.None)) + && cachedConfig==original && failedStarts.SequenceEqual(new[]{"100.99.142.38","002.vpn.toplc.cn"}); + starts.Clear(); probes=0; + rebound = await NodeTransportConnector.RebindAsync(cachedConfig,original,Start,Stop,Healthy,CancellationToken.None); + checks["handover_next_retry_public_only"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && probes==1; + starts.Clear(); var internalCancelledStarts=0; + selected = await NodeTransportConnector.ConnectAsync(response,new(),(json,token)=> { + if (++internalCancelledStarts==1) throw new OperationCanceledException("fixture internal deadline"); + return Start(json,token); + },Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); + checks["internal_timeout_falls_back_not_user_cancel"] = !selected && internalCancelledStarts==2 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + + ConfigResponse Known(Action? change = null) => Sample(r => { + r.Remove("tailscale_endpoint"); r["node"]!["slug"] = "aliyun-tokyo-002"; + change?.Invoke(r); + }); + var known = Known(); + var compatible = TailnetTransport.TryPrepare(known, allowKnownEndpoints: true)!; + checks["known_tokyo_compatibility_mapping"] = Host(compatible) == "100.99.142.38" && TailnetTransport.Port(compatible) == 10803; + checks["known_compatibility_still_same_authorization"] = TailnetTransport.SameAuthorizedFallback(compatible, known.GetRuntimeConfigJson()); + checks["known_compatibility_requires_mapping_permission"] = TailnetTransport.TryPrepare(known) is null; + checks["known_mapping_flag_is_not_identity_policy"] = KnownTailnetEndpoints.Resolve(known, allowCompatibilityMapping:true) is not null + && KnownTailnetEndpoints.Resolve(known, allowCompatibilityMapping:false) is null; + checks["explicit_null_disables_known_mapping"] = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = null), true) is null; + checks["invalid_explicit_metadata_never_uses_known_mapping"] = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject()), true) is null; + checks["unknown_named_node_does_not_use_known_mapping"] = TailnetTransport.TryPrepare(Sample(r => r.Remove("tailscale_endpoint")), true) is null; + checks["known_changed_public_host_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null; + checks["known_changed_public_port_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null; + checks["known_wrong_protocol_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["protocol"] = "socks"), true) is null; + checks["known_plaintext_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["security"] = "none"), true) is null; + checks["known_missing_reality_identity_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config"]!["outbounds"]![0]!["streamSettings"]!["realitySettings"]!.AsObject().Remove("publicKey")), true) is null; + checks["known_wrong_contract_rejected"] = TailnetTransport.TryPrepare(Known(r => r["config_contract"] = 1), true) is null; + checks["known_private_scope_rejected"] = TailnetTransport.TryPrepare(Known(r => r["connection_scope"] = "private_auxiliary"), true) is null; + checks["known_direct_mode_unchanged"] = TailnetTransport.TryPrepare(Known(r => r["route_mode"] = "direct"), true) is null; + var silicon = TailnetTransport.TryPrepare(Known(r => { + r["node"]!["slug"] = "aliyun-siliconvalley-003"; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "003.vpn.toplc.cn"; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083; + }), true)!; + checks["known_silicon_exact_mapping"] = Host(silicon) == "100.124.242.104" && TailnetTransport.Port(silicon) == 11083; + ConfigResponse NewYork(Action? change = null) => Known(r => { + r["node"]!["slug"] = "racknerd-newyork-004"; r["node"]!["name"] = "VPN004"; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.toplc.cn"; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084; + change?.Invoke(r); + }); + var newYork = NewYork(); + var newYorkOriginal = newYork.GetRuntimeConfigJson(); + var newYorkPrepared = TailnetTransport.TryPrepare(newYork, true); + checks["known_newyork_exact_mapping"] = newYorkPrepared is not null + && Host(newYorkPrepared) == "100.67.30.7" && TailnetTransport.Port(newYorkPrepared) == 11084; + checks["known_newyork_requires_mapping_permission"] = TailnetTransport.TryPrepare(newYork) is null; + checks["known_newyork_same_authorized_fallback"] = newYorkPrepared is not null + && TailnetTransport.SameAuthorizedFallback(newYorkPrepared, newYorkOriginal); + var newYorkRestored = newYorkPrepared is null ? null : JsonNode.Parse(newYorkPrepared)!.AsObject(); + if (newYorkRestored is not null) + { + newYorkRestored.Remove(TailnetTransport.Marker); + newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.toplc.cn"; + newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084; + } + checks["known_newyork_preserves_all_credentials_and_rules"] = newYorkRestored is not null + && JsonNode.DeepEquals(newYorkRestored, JsonNode.Parse(newYorkOriginal)) + && newYork.GetRuntimeConfigJson() == newYorkOriginal; + checks["known_newyork_changed_host_rejected"] = TailnetTransport.TryPrepare(NewYork(r => + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null; + checks["known_newyork_changed_port_rejected"] = TailnetTransport.TryPrepare(NewYork(r => + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null; + checks["known_newyork_changed_slug_rejected"] = TailnetTransport.TryPrepare(NewYork(r => + r["node"]!["slug"] = "unapproved-newyork"), true) is null; + checks["known_newyork_explicit_null_disables_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = null), true) is null; + checks["known_newyork_invalid_metadata_never_uses_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject()), true) is null; + var newYorkExplicit = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject { + ["contract"] = 1, ["node_slug"] = "racknerd-newyork-004", ["address"] = "100.65.1.9", ["port"] = 2345 + }), true); + checks["known_newyork_server_metadata_remains_authoritative"] = newYorkExplicit is not null + && Host(newYorkExplicit) == "100.65.1.9" && TailnetTransport.Port(newYorkExplicit) == 2345; + var newYorkStarts = new List(); var newYorkStops = 0; var newYorkProbes = 0; + var newYorkSelected = await NodeTransportConnector.ConnectAsync(newYork, new(), + (json, _) => { newYorkStarts.Add(json); return Task.CompletedTask; }, + () => { newYorkStops++; return Task.CompletedTask; }, + _ => { newYorkProbes++; return Task.FromResult(newYorkStarts.Last() == newYorkOriginal); }, + _ => { }, _ => { }, () => tick, CancellationToken.None, + allowKnownEndpoints: true, endpointProbe: (address, port, _) => Task.FromResult(address == "100.67.30.7" && port == 11084)); + checks["known_newyork_failed_proxy_falls_back_only_same_authorized_node"] = !newYorkSelected + && newYorkStarts.Count == 2 && Host(newYorkStarts[0]) == "100.67.30.7" + && newYorkStarts[1] == newYorkOriginal && newYorkStops == 1 && newYorkProbes == 2; + var future = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject { + ["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345 + }), true)!; + checks["explicit_server_metadata_takes_priority"] = Host(future) == "100.65.1.9" && TailnetTransport.Port(future) == 2345; + var gatewayKnown = Known(r => r["gateway"] = new JsonObject { ["host"] = "vpn.toplc.cn", ["ipv4"] = "59.110.91.17" }); + checks["compatibility_checks_node_before_gateway_rewrite"] = Host(TailnetTransport.TryPrepare(gatewayKnown, true)!) == "100.99.142.38"; + checks["compatibility_fallback_keeps_api_public_gateway"] = TailnetTransport.SameAuthorizedFallback( + TailnetTransport.TryPrepare(gatewayKnown, true)!, gatewayKnown.GetRuntimeConfigJson()) && Host(gatewayKnown.GetRuntimeConfigJson()) == "59.110.91.17"; + + starts.Clear(); beforeStops = stops; probes = 0; var preflights = 0; + selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(address,port,_)=> { + preflights++; checks["preflight_exact_tokyo_endpoint"] = address == "100.99.142.38" && port == 10803; + return Task.FromResult(true); + }); + checks["compatible_success_verified_before_label"] = selected && preflights == 1 && probes == 1 && stops == beforeStops + && starts.SequenceEqual(new[]{"100.99.142.38"}); + starts.Clear(); beforeStops = stops; probes = 0; statuses.Clear(); var deniedPreference = new TailnetPreference(); + selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,statuses.Add,()=>tick,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false)); + checks["closed_port_skips_tailnet_start_and_stop"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops == beforeStops && probes == 1; + checks["endpoint_unreachable_status_is_distinct_from_route_failure"] = statuses.Last() == "Tailscale 代理端口不可达,使用同一节点公网入口"; + checks["closed_port_sets_node_cooldown"] = !deniedPreference.MayTry(known.Node.Slug,tick+1); + starts.Clear(); + selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("must not probe during cooldown")); + checks["preflight_not_repeated_in_cooldown"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + deniedPreference.Failed("other-node",tick); + deniedPreference.ResetForUserConnect(); + checks["user_connect_reset_clears_node_cooldowns"] = deniedPreference.MayTry(known.Node.Slug,tick+1) && deniedPreference.MayTry("other-node",tick+1); + starts.Clear(); preflights = 0; probes = 0; + selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=> { preflights++; return Task.FromResult(true); }); + checks["manual_reset_reprobes_and_requires_protocol_health"] = selected && preflights == 1 && probes == 1 && starts.SequenceEqual(new[]{"100.99.142.38"}); + deniedPreference.Failed(known.Node.Slug,tick+2); + starts.Clear(); preflights = 0; probes = 0; + selected = await NodeTransportConnector.ConnectAsync(known,deniedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+3,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=> { preflights++; return Task.FromResult(true); }); + checks["automatic_retry_keeps_cooldown_after_later_failure"] = !selected && preflights == 0 && probes == 1 && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + starts.Clear(); using var preflightCancel = new CancellationTokenSource(); + checks["preflight_cancel_keeps_both_paths_unstarted"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,preflightCancel.Token, + allowKnownEndpoints:true, endpointProbe:(_,_,ct)=> { preflightCancel.Cancel(); ct.ThrowIfCancellationRequested(); return Task.FromResult(true); })) && starts.Count == 0; + starts.Clear(); probes = 0; + selected = await NodeTransportConnector.ConnectAsync(Known(r=>r["tailscale_endpoint"]=null),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("explicit null must not probe")); + checks["explicitly_disabled_tailnet_uses_verified_public"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && probes == 1; + + TailnetTransport.TryPrepare(Known(r=>r["tailscale_endpoint"]=null), out var skipReason, true); + checks["diagnostic_explicit_null_is_not_missing_metadata"] = skipReason == "explicit_endpoint_disabled"; + TailnetTransport.TryPrepare(Known(r=>r["config_contract"]=1), out skipReason, true); + checks["diagnostic_unknown_contract_preserves_rejection"] = skipReason == "config_contract_unsupported"; + TailnetTransport.TryPrepare(Known(r=>r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="other.example.com"), out skipReason, true); + checks["diagnostic_known_ingress_mismatch_is_distinct"] = skipReason == "known_original_ingress_mismatch"; + TailnetTransport.TryPrepare(known, out skipReason, true); + checks["diagnostic_compatibility_source_identified"] = skipReason == "known_endpoint"; + var diagnostics = new List(); + starts.Clear(); beforeStops=stops; + selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None, + allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false), diagnostic:diagnostics.Add); + checks["unreachable_tailnet_connects_same_public_node"] = + !selected && starts.SequenceEqual(["002.vpn.toplc.cn"]) && stops==beforeStops; + checks["diagnostics_persist_specific_probe_failure"] = diagnostics.Any(d=>d.Event=="tailnet_skipped" && d.Reason=="endpoint_unreachable" && d.Node==known.Node.Slug); + starts.Clear(); diagnostics.Clear(); beforeStops=stops; + selected = await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop, + OnlyPublicHealthy,Route,_=>{},()=>tick,CancellationToken.None,allowKnownEndpoints:true, + endpointProbe:(_,_,_)=>Task.FromResult(true),diagnostic:diagnostics.Add); + checks["failed_auth_cleans_up_before_same_node_public_fallback"] = !selected + && starts.SequenceEqual(["100.99.142.38", "002.vpn.toplc.cn"]) && stops==beforeStops+1; + starts.Clear(); diagnostics.Clear(); + var heldPreference = new TailnetPreference(); heldPreference.Failed(known.Node.Slug,tick); + selected = await NodeTransportConnector.ConnectAsync(known,heldPreference,Start,Stop,Healthy, + Route,_=>{},()=>tick+1,CancellationToken.None,allowKnownEndpoints:true,diagnostic:diagnostics.Add); + checks["tailnet_cooldown_keeps_same_node_public_route"] = !selected + && starts.SequenceEqual(["002.vpn.toplc.cn"]) && diagnostics.First().Reason=="cooldown_active"; + var safeDiagnostic = new TransportDiagnostic("selected\nconfig", "SYNTHETIC_SECRET?\r\n", new string('n',120)).SafeMessage; + checks["diagnostics_line_and_identifier_bounded"] = !safeDiagnostic.Contains('\n') && !safeDiagnostic.Contains('\r') && !safeDiagnostic.Contains('?') && safeDiagnostic.Length<260; + + starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear(); + rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, + preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add); + checks["handover_public_never_rechecks_or_promotes_internal"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) + && stops==beforeStops && preflights==0 && routeReads==0 && probes==1; + checks["handover_reports_public_choice"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="public_ingress"); + starts.Clear(); beforeStops=stops; probes=0; + rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, + preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false)); + checks["handover_unreachable_alternate_keeps_public_without_replacement_attempt"] = rebound==original + && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops==beforeStops && probes==1; + starts.Clear(); beforeStops=stops; + var failedPublicRebind = await ThrowsAsync(() => NodeTransportConnector.RebindAsync(original,null,Start,Stop, + _=>Task.FromResult(false),CancellationToken.None, + preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))); + checks["handover_failed_public_proof_does_not_promote_tailnet"] = failedPublicRebind + && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops==beforeStops; + starts.Clear(); + try { + rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, + preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true)); + checks["handover_ignores_unused_preferred_credentials"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + } catch { checks["handover_ignores_unused_preferred_credentials"] = false; } + starts.Clear(); + try { + rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None, + preferredTailnetConfig:prepared,requireRoute:Route); + checks["handover_public_needs_no_internal_probe"] = rebound==original && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + } catch { checks["handover_public_needs_no_internal_probe"] = false; } + starts.Clear(); + checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token, + preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0; + + // A failed primary does not suppress the backup's authorized Tailnet. + var backup = Sample(r=> { + r["node"]!["slug"]="silicon"; + r["tailscale_endpoint"]!["node_slug"]="silicon"; + r["tailscale_endpoint"]!["address"]="100.124.242.104"; + r["tailscale_endpoint"]!["port"]=11083; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="003.vpn.toplc.cn"; + r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]=11083; + }); + starts.Clear(); beforeStops=stops; + var retryPreference = new TailnetPreference(); + async Task FailPrimaryPublic(string config, CancellationToken token) + { + await Start(config, token); + if (Host(config) == "002.vpn.toplc.cn") throw new IOException("fixture public connection failure"); + } + var primaryFailed = await ThrowsAsync(() => NodeTransportConnector.ConnectAsync(response, retryPreference, + FailPrimaryPublic, Stop, _ => Task.FromResult(false), Route, _ => { }, () => tick, CancellationToken.None, + endpointProbe: (_, _, _) => Task.FromResult(true))); + retryPreference.ReleaseDomainFallbackAfterNodeFailure(); + var backupProbes = new List(); + var connectedSecond = await NodeTransportConnector.ConnectAsync(backup, retryPreference, Start, Stop, Healthy, + Route, _ => { }, () => tick + 1, CancellationToken.None, + endpointProbe: (address, _, _) => { backupProbes.Add(address); return Task.FromResult(true); }); + checks["confirmed_failure_tries_backup_after_same_node_public"] = primaryFailed && connectedSecond + && starts.SequenceEqual(["100.99.142.38", "002.vpn.toplc.cn", "100.124.242.104"]) && stops==beforeStops+1; + checks["alternate_probe_only_targets_its_authorized_tailnet_ip"] = backupProbes.SequenceEqual(["100.124.242.104"]); + checks["primary_cooldown_does_not_cool_other_node"] = !retryPreference.MayTry("tokyo",tick+1) + && retryPreference.MayTry("silicon",tick+1); + starts.Clear(); + rebound = await NodeTransportConnector.RebindAsync(prepared,original,Start,Stop,Healthy,CancellationToken.None, + endpointProbe:(_,_,_)=>Task.FromResult(false)); + checks["handover_ping_failure_uses_domain_without_internal_start"] = rebound==original + && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}); + var privateResponse = Sample(r => { + r["connection_scope"] = "private_auxiliary"; r["config_contract"] = 3; + r["config_expires_at"] = DateTimeOffset.UtcNow.AddMinutes(2).ToString("O"); + r["config"]!["outbounds"]![0] = new JsonObject { + ["tag"]="proxy",["protocol"]="socks",["settings"]=new JsonObject { + ["servers"]=new JsonArray(new JsonObject {["address"]="172.16.0.111",["port"]=18081}) } + }; + }); + var privatePreference = new TailnetPreference(); + probes = 0; + await NodeTransportConnector.ConnectAsync(privateResponse,privatePreference,(_,_)=>Task.CompletedTask, + Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None); + checks["private_ip_success_is_not_domain_fallback"] = !privatePreference.DomainOnly + && privatePreference.MayTry("tokyo",tick+1) && probes == 0; + var directResponse = Sample(r => r["route_mode"] = "direct"); + starts.Clear(); probes = 0; + await NodeTransportConnector.ConnectAsync(directResponse, new(), Start, Stop, Healthy, Route, + _ => { }, () => tick, CancellationToken.None); + checks["direct_connect_skips_public_egress_probe"] = starts.Count == 1 && probes == 0; + starts.Clear(); probes = 0; + rebound = await NodeTransportConnector.RebindAsync(original, null, Start, Stop, Healthy, + CancellationToken.None, verifyPublicEgress: false); + checks["direct_or_private_rebind_without_public_probe"] = rebound == original && starts.Count == 1 && probes == 0; + var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true, + production_network_actions=Array.Empty(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." }; + File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true})); + return report.passed ? 0 : 81; + } + private static bool Throws(Action action) { try { action(); return false; } catch { return true; } } + private static async Task ThrowsAsync(Func action) { try { await action(); return false; } catch { return true; } } + private sealed class HandoverFixture : IHandoverRuntime + { + public string? BoundNetworkFingerprint { get; set; } + public bool CanRebindNetwork => true; + public bool IsRunning => true; + internal string? NextFingerprint; + internal string Current = ""; + internal Func> Rebind = null!; + public Task SuspendForNetworkChangeAsync(CancellationToken token) => Task.CompletedTask; + public async Task RebindNetworkAsync(CancellationToken token) + { + token.ThrowIfCancellationRequested(); Current=await Rebind(); BoundNetworkFingerprint=NextFingerprint; + } + } +} diff --git a/windows/TunConfigBuilder.cs b/windows/TunConfigBuilder.cs index a7f1397..bcf57cf 100644 --- a/windows/TunConfigBuilder.cs +++ b/windows/TunConfigBuilder.cs @@ -1,305 +1,321 @@ -using System.Text.Json.Nodes; - -namespace UCVL.VPNPlus; - -internal static class TunConfigBuilder -{ - internal static string OverrideProxyServerAddress(string baseConfigJson, string? gatewayAddress) - { - if (string.IsNullOrWhiteSpace(gatewayAddress)) return baseConfigJson; - var root = JsonNode.Parse(baseConfigJson)?.AsObject() - ?? throw new InvalidOperationException("服务端线路配置为空。"); - if (root["outbounds"] is not JsonArray outbounds) return baseConfigJson; - foreach (var node in outbounds) - { - if (node is not JsonObject outbound - || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) - || outbound["settings"]?["vnext"] is not JsonArray servers) - { - continue; - } - foreach (var server in servers) - if (server is JsonObject item) item["address"] = gatewayAddress.Trim(); - } - return root.ToJsonString(); - } - - // Production must capture native sockets as well as browser proxy traffic. - // Keep validation explicitly TUN-free: Xray -test starts its inbounds too. - internal static string BuildRuntime(string baseConfigJson, string physicalInterfaceName, - bool includeLocalLearning, int routingApiPort) - => Build(baseConfigJson, physicalInterfaceName, includeLocalLearning, - includeTun: true, routingApiPort: routingApiPort); - - internal static string Build( - string baseConfigJson, - string physicalInterfaceName, - bool includeLocalLearning, - bool includeTun = true, - int routingApiPort = 0, int learningProbePort = 0, int directProbePort = 0, - string? tailnetInterfaceName = null) - { - var root = JsonNode.Parse(baseConfigJson)?.AsObject() - ?? throw new InvalidOperationException("服务端线路配置为空。"); - var inbounds = root["inbounds"]?.AsArray() - ?? throw new InvalidOperationException("线路配置缺少入站定义。"); - var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(root); - var tailnet = TailnetTransport.Address(root) is not null; - if (tailnet && (privateAuxiliary || string.IsNullOrWhiteSpace(tailnetInterfaceName))) - throw new InvalidOperationException("Tailscale 入口缺少已验证的网络路径。"); - root.Remove(PrivateAuxiliaryRuntime.Marker); // Client metadata is not an Xray setting. - root.Remove(TailnetTransport.Marker); - if (includeTun) - { - inbounds.Insert(0, new JsonObject - { - ["tag"] = "tun-in", - ["port"] = 0, - ["protocol"] = "tun", - ["settings"] = new JsonObject - { - ["name"] = TunRouting.AdapterName, - ["MTU"] = 1500, - }, - ["sniffing"] = new JsonObject - { - ["enabled"] = true, - ["destOverride"] = new JsonArray("http", "tls", "quic"), - ["routeOnly"] = false, - }, - }); - } - - var outbounds = root["outbounds"]?.AsArray() - ?? throw new InvalidOperationException("线路配置缺少出站定义。"); - foreach (var node in outbounds) - { - if (node is not JsonObject outbound) continue; - if (outbound["streamSettings"] is not JsonObject streamSettings) - { - streamSettings = new JsonObject(); - outbound["streamSettings"] = streamSettings; - } - if (streamSettings["sockopt"] is not JsonObject sockopt) - { - sockopt = new JsonObject(); - streamSettings["sockopt"] = sockopt; - } - if (streamSettings["realitySettings"] is JsonObject realitySettings - && realitySettings["password"] is null - && realitySettings["publicKey"] is JsonNode legacyPublicKey) - { - realitySettings["password"] = legacyPublicKey.DeepClone(); - realitySettings.Remove("publicKey"); - } - sockopt["interface"] = physicalInterfaceName; - if (privateAuxiliary && outbound["tag"]?.GetValue() == "proxy") - sockopt.Remove("interface"); // Preserve the user's LAN/Tailscale route to .111. - if (tailnet && outbound["tag"]?.GetValue() == "proxy") - sockopt["interface"] = tailnetInterfaceName; // Only this socket uses the user's tailnet path. - } - - // Local rules now require same-network direct failure + proxy TLS proof. - // Do not load the old failure-only, seven-day learning file. - if (includeLocalLearning) - root["log"] = new JsonObject { ["loglevel"] = "info", ["access"] = "none" }; - // Windows NRPT queries for proxy domains must not follow the smart - // mode's default DIRECT rule. Use independent UDP resolvers through - // the proxy instead of DoH here. A single reused HTTP/2 DoH connection - // can stall every lookup when a mobile/NPM path briefly resets, which - // is especially visible as repeated Codex reconnects. - if (root["routing"]?["rules"] is JsonArray dnsRules) - { - root["dns"] = new JsonObject { - ["tag"] = "ucvl-dns-query", ["queryStrategy"] = "UseIPv4", - ["servers"] = privateAuxiliary - ? new JsonArray("https://8.8.8.8/dns-query", "https://1.1.1.1/dns-query") - : new JsonArray("1.1.1.1", "8.8.8.8") - }; - // Zero3 is TCP-only. Its DNS therefore uses HTTPS INSIDE the pinned - // proxy, never SOCKS UDP (which would not have the same TLS protection). - // Public 0.2.5-compatible UDP DNS above remains unchanged. - if (privateAuxiliary) - { - outbounds.Add(new JsonObject { ["tag"] = "ucvl-private-udp-block", ["protocol"] = "blackhole" }); - dnsRules.Insert(0, new JsonObject { ["type"] = "field", ["network"] = "udp", - ["outboundTag"] = "ucvl-private-udp-block" }); - } - outbounds.Add(new JsonObject { ["tag"] = "ucvl-dns-out", ["protocol"] = "dns", - ["settings"] = new JsonObject { ["nonIPQuery"] = "reject" } }); - dnsRules.Insert(0, new JsonObject { - ["type"] = "field", ["inboundTag"] = new JsonArray("tun-in"), - ["ip"] = new JsonArray("8.8.8.8", "1.1.1.1"), ["port"] = "53", - ["outboundTag"] = "ucvl-dns-out" - }); - dnsRules.Insert(0, new JsonObject { - ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-dns-query"), - ["outboundTag"] = "proxy" - }); - } - if (learningProbePort > 0) - { - inbounds.Add(new JsonObject { ["tag"] = "ucvl-learning-probe", ["listen"] = "127.0.0.1", - ["port"] = learningProbePort, ["protocol"] = "socks", - ["settings"] = new JsonObject { ["auth"] = "noauth", ["udp"] = false } }); - var probeRules = root["routing"]!["rules"]!.AsArray(); - probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), ["outboundTag"] = "proxy" }); - probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), - ["ip"] = new JsonArray("geoip:private"), ["outboundTag"] = "block" }); - } - if (directProbePort > 0) - { - // Independent, physical-interface-bound direct path, unaffected by learned rules. - // Never sniff or use domains on this listener: caller pins an already checked public IP. - inbounds.Add(new JsonObject { ["tag"]="ucvl-direct-probe", ["listen"]="127.0.0.1", - ["port"]=directProbePort, ["protocol"]="socks", ["settings"]=new JsonObject { ["auth"]="noauth", ["udp"]=false } }); - outbounds.Add(new JsonObject { ["tag"]="ucvl-learning-direct", ["protocol"]="freedom", - ["streamSettings"]=new JsonObject { ["sockopt"]=new JsonObject { ["interface"]=physicalInterfaceName } } }); - var rules = root["routing"]!["rules"]!.AsArray(); - rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["outboundTag"]="ucvl-learning-direct" }); - rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["ip"]=new JsonArray("geoip:private"), ["outboundTag"]="block" }); - } - if (routingApiPort > 0) - { - RoutingRuleBatches.TagInitialRules(root); - // Local control only: never expose the routing API on a LAN address. - root["api"] = new JsonObject - { - ["tag"] = "ucvl-routing-api", - ["listen"] = $"127.0.0.1:{routingApiPort}", - ["services"] = new JsonArray("RoutingService", "StatsService"), - }; - root["stats"] = new JsonObject(); - if (root["policy"] is not JsonObject policy) - { - policy = new JsonObject(); - root["policy"] = policy; - } - if (policy["system"] is not JsonObject system) - { - system = new JsonObject(); - policy["system"] = system; - } - system["statsOutboundUplink"] = true; - system["statsOutboundDownlink"] = true; - } - return root.ToJsonString(); - } - - internal static string BuildRoutingUpdate(string baseConfigJson) - { - var root = JsonNode.Parse(baseConfigJson)?.AsObject() - ?? throw new InvalidOperationException("线路配置为空。"); - AddLocalLearningRules(root); - return new JsonObject { ["routing"] = root["routing"]?.DeepClone() - ?? throw new InvalidOperationException("线路配置缺少路由规则。") }.ToJsonString(); - } - - internal static string BuildLearningRouting(string config, string physicalInterfaceName, - int learningProbePort, int directProbePort, string? tailnetInterfaceName) - { - var runtime = JsonNode.Parse(Build(config, physicalInterfaceName, includeLocalLearning:true, - includeTun:false, learningProbePort:learningProbePort, directProbePort:directProbePort, - tailnetInterfaceName:tailnetInterfaceName))!; - return new JsonObject { ["routing"] = runtime["routing"]!.DeepClone() }.ToJsonString(); - } - - internal static IReadOnlyList GetProxyServerHosts(string baseConfigJson) - { - var root = JsonNode.Parse(baseConfigJson)?.AsObject() - ?? throw new InvalidOperationException("服务端线路配置为空。"); - var hosts = new List(); - if (root["outbounds"] is not JsonArray outbounds) return hosts; - foreach (var node in outbounds) - { - if (node is not JsonObject outbound - || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) - || (outbound["settings"]?["vnext"] ?? (PrivateAuxiliaryRuntime.IsPrivate(root) - ? outbound["settings"]?["servers"] : null)) is not JsonArray servers) - { - continue; - } - foreach (var server in servers) - { - var address = server?["address"]?.GetValue()?.Trim(); - if (!string.IsNullOrWhiteSpace(address)) hosts.Add(address); - } - } - return hosts.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); - } - - internal static bool SelfTest() - { - const string sample = """ - { - "inbounds": [], - "outbounds": [ - { - "tag": "proxy", - "protocol": "vless", - "settings": {"vnext": [{"address": "203.0.113.10", "port": 443}]}, - "streamSettings": { - "security": "reality", - "realitySettings": {"publicKey": "legacy-key"} - } - }, - {"tag": "direct", "protocol": "freedom"} - ], - "routing": {"rules": []} - } - """; - var hosts = GetProxyServerHosts(sample); - var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.toplc.cn"))?.AsObject(); - var gatewayOutbound = gatewayConfig?["outbounds"]?.AsArray()[0]?.AsObject(); - var gatewayServer = gatewayOutbound?["settings"]?["vnext"]?.AsArray()[0]?.AsObject(); - var gatewayReality = gatewayOutbound?["streamSettings"]?["realitySettings"]?.AsObject(); - var config = JsonNode.Parse(BuildRuntime(sample, "Ethernet", includeLocalLearning: false, routingApiPort: 18090))?.AsObject(); - var validation = JsonNode.Parse(Build(sample, "Ethernet", includeLocalLearning: false, includeTun: false))?.AsObject(); - var tun = config?["inbounds"]?[0]; - var runtimeDnsServers = config?["dns"]?["servers"]?.AsArray(); - return hosts.Count == 1 - && hosts[0] == "203.0.113.10" - && gatewayServer?["address"]?.GetValue() == "vpn.toplc.cn" - && gatewayServer?["port"]?.GetValue() == 443 - && gatewayReality?["publicKey"]?.GetValue() == "legacy-key" - && tun?["protocol"]?.GetValue() == "tun" - && tun?["sniffing"]?["routeOnly"]?.GetValue() == false - && config?["api"]?["listen"]?.GetValue() == "127.0.0.1:18090" - && validation?["inbounds"]?.AsArray().Count == 0 - && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["password"]?.GetValue() == "legacy-key" - && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["publicKey"] is null - && config?["outbounds"]?[0]?["streamSettings"]?["sockopt"]?["interface"]?.GetValue() == "Ethernet" - && runtimeDnsServers?[0]?.GetValue() == "1.1.1.1" - && runtimeDnsServers?[1]?.GetValue() == "8.8.8.8"; - } - - private static void AddLocalLearningRules(JsonObject root) - { - if (root["routing"] is not JsonObject routing || routing["rules"] is not JsonArray rules) return; - var learned = LearningStore.GetActiveTargets(); - var domains = learned.Where(item => item.TargetType == "domain").Select(item => $"full:{item.Target}").Distinct().ToList(); - var ips = learned.Where(item => item.TargetType == "ip") - .Select(item => $"{item.Target}/{(item.Target.Contains(':') ? "128" : "32")}") - .Distinct() - .ToList(); - var insertAt = Math.Min(1, rules.Count); - if (ips.Count > 0) - { - rules.Insert(insertAt, new JsonObject - { - ["type"] = "field", - ["ip"] = new JsonArray(ips.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), - ["outboundTag"] = "proxy", - }); - } - if (domains.Count > 0) - { - rules.Insert(insertAt, new JsonObject - { - ["type"] = "field", - ["domain"] = new JsonArray(domains.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), - ["outboundTag"] = "proxy", - }); - } - } -} +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +internal static class TunConfigBuilder +{ + internal static string OverrideProxyServerAddress(string baseConfigJson, string? gatewayAddress) + { + if (string.IsNullOrWhiteSpace(gatewayAddress)) return baseConfigJson; + var root = JsonNode.Parse(baseConfigJson)?.AsObject() + ?? throw new InvalidOperationException("服务端线路配置为空。"); + if (root["outbounds"] is not JsonArray outbounds) return baseConfigJson; + foreach (var node in outbounds) + { + if (node is not JsonObject outbound + || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) + || outbound["settings"]?["vnext"] is not JsonArray servers) + { + continue; + } + foreach (var server in servers) + if (server is JsonObject item) item["address"] = gatewayAddress.Trim(); + } + return root.ToJsonString(); + } + + // Production must capture native sockets as well as browser proxy traffic. + // Keep validation explicitly TUN-free: Xray -test starts its inbounds too. + internal static string BuildRuntime(string baseConfigJson, string physicalInterfaceName, + bool includeLocalLearning, int routingApiPort) + => Build(baseConfigJson, physicalInterfaceName, includeLocalLearning, + includeTun: true, routingApiPort: routingApiPort); + + internal static string Build( + string baseConfigJson, + string physicalInterfaceName, + bool includeLocalLearning, + bool includeTun = true, + int routingApiPort = 0, int learningProbePort = 0, int directProbePort = 0, + string? tailnetInterfaceName = null) + { + var root = JsonNode.Parse(baseConfigJson)?.AsObject() + ?? throw new InvalidOperationException("服务端线路配置为空。"); + var inbounds = root["inbounds"]?.AsArray() + ?? throw new InvalidOperationException("线路配置缺少入站定义。"); + var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(root); + var tailnet = TailnetTransport.Address(root) is not null; + if (tailnet && (privateAuxiliary || string.IsNullOrWhiteSpace(tailnetInterfaceName))) + throw new InvalidOperationException("Tailscale 入口缺少已验证的网络路径。"); + root.Remove(PrivateAuxiliaryRuntime.Marker); // Client metadata is not an Xray setting. + root.Remove(TailnetTransport.Marker); + if (includeTun) + { + inbounds.Insert(0, new JsonObject + { + ["tag"] = "tun-in", + ["port"] = 0, + ["protocol"] = "tun", + ["settings"] = new JsonObject + { + ["name"] = TunRouting.AdapterName, + ["MTU"] = 1500, + }, + ["sniffing"] = new JsonObject + { + ["enabled"] = true, + ["destOverride"] = new JsonArray("http", "tls", "quic"), + ["routeOnly"] = false, + }, + }); + } + + var outbounds = root["outbounds"]?.AsArray() + ?? throw new InvalidOperationException("线路配置缺少出站定义。"); + foreach (var node in outbounds) + { + if (node is not JsonObject outbound) continue; + if (outbound["streamSettings"] is not JsonObject streamSettings) + { + streamSettings = new JsonObject(); + outbound["streamSettings"] = streamSettings; + } + if (streamSettings["sockopt"] is not JsonObject sockopt) + { + sockopt = new JsonObject(); + streamSettings["sockopt"] = sockopt; + } + if (streamSettings["realitySettings"] is JsonObject realitySettings + && realitySettings["password"] is null + && realitySettings["publicKey"] is JsonNode legacyPublicKey) + { + realitySettings["password"] = legacyPublicKey.DeepClone(); + realitySettings.Remove("publicKey"); + } + sockopt["interface"] = physicalInterfaceName; + if (privateAuxiliary && outbound["tag"]?.GetValue() == "proxy") + sockopt.Remove("interface"); // Preserve the user's LAN/Tailscale route to .111. + if (tailnet && outbound["tag"]?.GetValue() == "proxy") + sockopt["interface"] = tailnetInterfaceName; // Only this socket uses the user's tailnet path. + } + + // Local rules now require same-network direct failure + proxy TLS proof. + // Do not load the old failure-only, seven-day learning file. + if (includeLocalLearning) + root["log"] = new JsonObject { ["loglevel"] = "info", ["access"] = "none" }; + // Windows NRPT queries for proxy domains must not follow the smart + // mode's default DIRECT rule. Use independent UDP resolvers through + // the proxy instead of DoH here. A single reused HTTP/2 DoH connection + // can stall every lookup when a mobile/NPM path briefly resets, which + // is especially visible as repeated Codex reconnects. + if (root["routing"]?["rules"] is JsonArray dnsRules) + { + AddTailnetDirectRule(dnsRules); + root["dns"] = new JsonObject { + ["tag"] = "ucvl-dns-query", ["queryStrategy"] = "UseIPv4", + ["servers"] = privateAuxiliary + ? new JsonArray("https://8.8.8.8/dns-query", "https://1.1.1.1/dns-query") + : new JsonArray("1.1.1.1", "8.8.8.8") + }; + // Zero3 is TCP-only. Its DNS therefore uses HTTPS INSIDE the pinned + // proxy, never SOCKS UDP (which would not have the same TLS protection). + // Public 0.2.5-compatible UDP DNS above remains unchanged. + if (privateAuxiliary) + { + outbounds.Add(new JsonObject { ["tag"] = "ucvl-private-udp-block", ["protocol"] = "blackhole" }); + dnsRules.Insert(0, new JsonObject { ["type"] = "field", ["network"] = "udp", + ["outboundTag"] = "ucvl-private-udp-block" }); + } + outbounds.Add(new JsonObject { ["tag"] = "ucvl-dns-out", ["protocol"] = "dns", + ["settings"] = new JsonObject { ["nonIPQuery"] = "reject" } }); + dnsRules.Insert(0, new JsonObject { + ["type"] = "field", ["inboundTag"] = new JsonArray("tun-in"), + ["ip"] = new JsonArray("8.8.8.8", "1.1.1.1"), ["port"] = "53", + ["outboundTag"] = "ucvl-dns-out" + }); + dnsRules.Insert(0, new JsonObject { + ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-dns-query"), + ["outboundTag"] = "proxy" + }); + } + if (learningProbePort > 0) + { + inbounds.Add(new JsonObject { ["tag"] = "ucvl-learning-probe", ["listen"] = "127.0.0.1", + ["port"] = learningProbePort, ["protocol"] = "socks", + ["settings"] = new JsonObject { ["auth"] = "noauth", ["udp"] = false } }); + var probeRules = root["routing"]!["rules"]!.AsArray(); + probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), ["outboundTag"] = "proxy" }); + probeRules.Insert(0, new JsonObject { ["type"] = "field", ["inboundTag"] = new JsonArray("ucvl-learning-probe"), + ["ip"] = new JsonArray("geoip:private"), ["outboundTag"] = "block" }); + } + if (directProbePort > 0) + { + // Independent, physical-interface-bound direct path, unaffected by learned rules. + // Never sniff or use domains on this listener: caller pins an already checked public IP. + inbounds.Add(new JsonObject { ["tag"]="ucvl-direct-probe", ["listen"]="127.0.0.1", + ["port"]=directProbePort, ["protocol"]="socks", ["settings"]=new JsonObject { ["auth"]="noauth", ["udp"]=false } }); + outbounds.Add(new JsonObject { ["tag"]="ucvl-learning-direct", ["protocol"]="freedom", + ["streamSettings"]=new JsonObject { ["sockopt"]=new JsonObject { ["interface"]=physicalInterfaceName } } }); + var rules = root["routing"]!["rules"]!.AsArray(); + rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["outboundTag"]="ucvl-learning-direct" }); + rules.Insert(0, new JsonObject { ["type"]="field", ["inboundTag"]=new JsonArray("ucvl-direct-probe"), ["ip"]=new JsonArray("geoip:private"), ["outboundTag"]="block" }); + } + if (routingApiPort > 0) + { + RoutingRuleBatches.TagInitialRules(root); + // Local control only: never expose the routing API on a LAN address. + root["api"] = new JsonObject + { + ["tag"] = "ucvl-routing-api", + ["listen"] = $"127.0.0.1:{routingApiPort}", + ["services"] = new JsonArray("RoutingService", "StatsService"), + }; + root["stats"] = new JsonObject(); + if (root["policy"] is not JsonObject policy) + { + policy = new JsonObject(); + root["policy"] = policy; + } + if (policy["system"] is not JsonObject system) + { + system = new JsonObject(); + policy["system"] = system; + } + system["statsOutboundUplink"] = true; + system["statsOutboundDownlink"] = true; + } + return root.ToJsonString(); + } + + internal static string BuildRoutingUpdate(string baseConfigJson) + { + var root = JsonNode.Parse(baseConfigJson)?.AsObject() + ?? throw new InvalidOperationException("线路配置为空。"); + AddLocalLearningRules(root); + if (root["routing"]?["rules"] is JsonArray rules) + AddTailnetDirectRule(rules); + return new JsonObject { ["routing"] = root["routing"]?.DeepClone() + ?? throw new InvalidOperationException("线路配置缺少路由规则。") }.ToJsonString(); + } + + internal static string BuildLearningRouting(string config, string physicalInterfaceName, + int learningProbePort, int directProbePort, string? tailnetInterfaceName) + { + var runtime = JsonNode.Parse(Build(config, physicalInterfaceName, includeLocalLearning:true, + includeTun:false, learningProbePort:learningProbePort, directProbePort:directProbePort, + tailnetInterfaceName:tailnetInterfaceName))!; + return new JsonObject { ["routing"] = runtime["routing"]!.DeepClone() }.ToJsonString(); + } + + internal static IReadOnlyList GetProxyServerHosts(string baseConfigJson) + { + var root = JsonNode.Parse(baseConfigJson)?.AsObject() + ?? throw new InvalidOperationException("服务端线路配置为空。"); + var hosts = new List(); + if (root["outbounds"] is not JsonArray outbounds) return hosts; + foreach (var node in outbounds) + { + if (node is not JsonObject outbound + || !string.Equals(outbound["tag"]?.GetValue(), "proxy", StringComparison.OrdinalIgnoreCase) + || (outbound["settings"]?["vnext"] ?? (PrivateAuxiliaryRuntime.IsPrivate(root) + ? outbound["settings"]?["servers"] : null)) is not JsonArray servers) + { + continue; + } + foreach (var server in servers) + { + var address = server?["address"]?.GetValue()?.Trim(); + if (!string.IsNullOrWhiteSpace(address)) hosts.Add(address); + } + } + return hosts.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + + internal static bool SelfTest() + { + const string sample = """ + { + "inbounds": [], + "outbounds": [ + { + "tag": "proxy", + "protocol": "vless", + "settings": {"vnext": [{"address": "203.0.113.10", "port": 443}]}, + "streamSettings": { + "security": "reality", + "realitySettings": {"publicKey": "legacy-key"} + } + }, + {"tag": "direct", "protocol": "freedom"} + ], + "routing": {"rules": []} + } + """; + var hosts = GetProxyServerHosts(sample); + var gatewayConfig = JsonNode.Parse(OverrideProxyServerAddress(sample, "vpn.toplc.cn"))?.AsObject(); + var gatewayOutbound = gatewayConfig?["outbounds"]?.AsArray()[0]?.AsObject(); + var gatewayServer = gatewayOutbound?["settings"]?["vnext"]?.AsArray()[0]?.AsObject(); + var gatewayReality = gatewayOutbound?["streamSettings"]?["realitySettings"]?.AsObject(); + var config = JsonNode.Parse(BuildRuntime(sample, "Ethernet", includeLocalLearning: false, routingApiPort: 18090))?.AsObject(); + var validation = JsonNode.Parse(Build(sample, "Ethernet", includeLocalLearning: false, includeTun: false))?.AsObject(); + var tun = config?["inbounds"]?[0]; + var runtimeDnsServers = config?["dns"]?["servers"]?.AsArray(); + return hosts.Count == 1 + && hosts[0] == "203.0.113.10" + && gatewayServer?["address"]?.GetValue() == "vpn.toplc.cn" + && gatewayServer?["port"]?.GetValue() == 443 + && gatewayReality?["publicKey"]?.GetValue() == "legacy-key" + && tun?["protocol"]?.GetValue() == "tun" + && tun?["sniffing"]?["routeOnly"]?.GetValue() == false + && config?["api"]?["listen"]?.GetValue() == "127.0.0.1:18090" + && validation?["inbounds"]?.AsArray().Count == 0 + && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["password"]?.GetValue() == "legacy-key" + && config?["outbounds"]?[0]?["streamSettings"]?["realitySettings"]?["publicKey"] is null + && config?["outbounds"]?[0]?["streamSettings"]?["sockopt"]?["interface"]?.GetValue() == "Ethernet" + && runtimeDnsServers?[0]?.GetValue() == "1.1.1.1" + && runtimeDnsServers?[1]?.GetValue() == "8.8.8.8"; + } + + private static void AddTailnetDirectRule(JsonArray rules) + { + // Control and relay traffic must reach the underlay before any proxy rule + // can depend on the Tailscale connection. Internal DNS and probe rules + // are added ahead of this rule. + rules.Insert(0, new JsonObject + { + ["type"] = "field", + ["domain"] = new JsonArray("regexp:" + TailnetDnsPolicy.DomainPattern), + ["outboundTag"] = "direct", + }); + } + + private static void AddLocalLearningRules(JsonObject root) + { + if (root["routing"] is not JsonObject routing || routing["rules"] is not JsonArray rules) return; + var learned = LearningStore.GetActiveTargets(); + var domains = learned.Where(item => item.TargetType == "domain").Select(item => $"full:{item.Target}").Distinct().ToList(); + var ips = learned.Where(item => item.TargetType == "ip") + .Select(item => $"{item.Target}/{(item.Target.Contains(':') ? "128" : "32")}") + .Distinct() + .ToList(); + var insertAt = Math.Min(1, rules.Count); + if (ips.Count > 0) + { + rules.Insert(insertAt, new JsonObject + { + ["type"] = "field", + ["ip"] = new JsonArray(ips.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), + ["outboundTag"] = "proxy", + }); + } + if (domains.Count > 0) + { + rules.Insert(insertAt, new JsonObject + { + ["type"] = "field", + ["domain"] = new JsonArray(domains.Select(value => (JsonNode?)JsonValue.Create(value)).ToArray()), + ["outboundTag"] = "proxy", + }); + } + } +} diff --git a/windows/TunRouting.cs b/windows/TunRouting.cs index 492f8d7..feb9e62 100644 --- a/windows/TunRouting.cs +++ b/windows/TunRouting.cs @@ -1,321 +1,327 @@ -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); -} +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(); + private static readonly IPAddress[] CompanyDerpAddresses = + [IPAddress.Parse("8.216.53.107"), IPAddress.Parse("47.254.94.29"), IPAddress.Parse("192.236.188.22")]; + + 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); + // Keep the overlay target on Tailscale and its relay traffic on the physical uplink. + // A TUN default route could otherwise send the relay through the proxy that depends on it. + if (preserveProxyRoute && proxyIpv4Addresses.Any(address => TailnetTransport.IsTailnetAddress(address.ToString()))) + bypassAddresses = bypassAddresses.Concat(CompanyDerpAddresses); + 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); +} diff --git a/windows/VPNPlus.csproj b/windows/VPNPlus.csproj index 345228b..3d1497c 100644 --- a/windows/VPNPlus.csproj +++ b/windows/VPNPlus.csproj @@ -1,45 +1,45 @@ - - - WinExe - net8.0-windows10.0.19041.0 - true - enable - enable - VPNPlus - UCVL.VPNPlus - assets\zonghengjia-app-v1.ico - app.manifest - PerMonitorV2 - 0.3.14 - 0.3.14.0 - 0.3.14.0 - 0.3.14 - 纵横家 - 优创未来(UCVL) - 纵横家 Windows 智能网络客户端 - win-x64 - true - true - true - false - none - false - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - PreserveNewest - true - - - + + + WinExe + net8.0-windows10.0.19041.0 + true + enable + enable + VPNPlus + UCVL.VPNPlus + assets\zonghengjia-app-v1.ico + app.manifest + PerMonitorV2 + 0.3.17 + 0.3.17.0 + 0.3.17.0 + 0.3.17 + 纵横家 + 优创未来(UCVL) + 纵横家 Windows 智能网络客户端 + win-x64 + true + true + true + false + none + false + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + PreserveNewest + true + + + diff --git a/windows/XrayManager.cs b/windows/XrayManager.cs index 5f57219..f9f5bd9 100644 --- a/windows/XrayManager.cs +++ b/windows/XrayManager.cs @@ -1,713 +1,714 @@ -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 _learningCandidates = []; - private bool _needsRecovery; - private bool _disposed; - private NetworkOwnerLease? _ownerLease; - private bool _recoveryComplete; - private bool _stoppedCleanly; - private readonly CancellationTokenSource _systemShutdown = new(); - 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)? TailnetProbeEndpoint - { - get - { - var current = _baseConfigJson; - if (IsRunning && current is not null && UsesTailnet - && TailnetTransport.SameAuthorizedFallback(current, _tailnetFallbackConfigJson)) - return (TailnetTransport.Address(current)!, TailnetTransport.Port(current)); - return PreferredTailnetEndpoint; - } - } - 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; - - internal void ConfirmSessionShutdown() => _systemShutdown.Cancel(); - - public async Task SuspendForNetworkChangeAsync(CancellationToken token) - { - await _lifecycle.WaitAsync(token); - try { await StopCoreAsync(); } - finally { _lifecycle.Release(); } - } - - public async Task RebindNetworkAsync(CancellationToken token) - { - ValidateRuntime(); - await _lifecycle.WaitAsync(token); - var replacementStarted = false; - try - { - ValidateRuntime(); - if (!CanRebindNetwork) throw new InvalidOperationException("没有可恢复的已授权线路。"); - replacementStarted = true; - 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 { if (replacementStarted) 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 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 CheckProxyHealthAsync(CancellationToken token) - => !IsRunning || _learningProbePort == 0 ? Task.FromResult(false) - : NodeHealthProbe.CheckTransportAsync(token, _learningProbePort); - - internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted, bool BusinessUnavailable = false); - internal async Task CheckHealthWithRepairAsync(CancellationToken token) - { - var expectedCore = CoreId; - if (await CheckHealthAsync(token)) return new(true, false, false); - if (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. - var proxy = await NodeHealthProbe.CheckReportAsync(deadline.Token, _learningProbePort); - if (!proxy.TransportReachable) return new(false, false, false); - proxyHealthy = true; - if (CoreId != expectedCore) return new(false, true, false); - // The forced proxy authenticated the same transport and received - // TLS/HTTP from at least one site. A site's outage is a business - // diagnostic, not evidence that this node needs to be replaced. - if (_routeMode != "smart" || !proxy.BusinessHealthy) return new(false, true, false, true); - 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? ObservationDetectedAsync { get; set; } - internal Action? 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) - { - // Fail locally before ownership/recovery or stopping a healthy core. - ValidateRuntime(); - 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 StartupLearningWarmup.RunAsync(async beginLearning => { - await _lifecycle.WaitAsync(cancellationToken); - var replacementStarted = false; - try - { - // Recheck after waiting for the lifecycle; a file may change. - ValidateRuntime(); - replacementStarted = true; - await StopCoreAsync(); - _baseConfigJson = configJson; - _tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson; - _preferredTailnetConfigJson = preferred; - _routeMode = routeMode; - _nodeSlug = nodeSlug; - await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null); - } - catch - { - if (replacementStarted) await StopCoreAsync().ConfigureAwait(false); - throw; - } - finally { _lifecycle.Release(); } - if (_routeMode == "smart") StatusMessage?.Invoke("正在验证本地直连与代理路径…"); - }, warmupToken => - // Keep the same targets, direct/proxy proof and lifecycle-gated - // commits. Only their read-only transport work overlaps DNS setup. - 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" }, warmupToken))), - cancellationToken); - } - - 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 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, - Action? beginStartupLearning = null) - { - ValidateRuntime(); - if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。"); - _stoppedCleanly = false; - 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 (!ClientRuntime.Start(_process)) throw new ClientRuntimeException(XrayPath, ClientRuntimeFault.CannotStart); - _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); - beginStartupLearning?.Invoke(_learningEpoch.Token); - await ProxyDnsPolicy.EnableAsync(_baseConfigJson, cancellationToken); - // The DNS policy is applied above. Management readiness does not - // require resolving the HTTPS authority through any DNS provider. - StatusMessage?.Invoke("Windows 网卡和 DNS 配置已应用。"); - await Task.Delay(250, cancellationToken); - _boundNetwork = physicalNetwork; - SafeDeleteConfig(); - } - catch - { - await StopCoreAsync(); - throw; - } - } - - 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 || _stoppedCleanly) return; - _learningEpoch.Cancel(); - var proxyRestored = SystemProxy.Restore(); - Exception? restoreError = null; - var sessionToken = _systemShutdown.Token; - using var recovery = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); - recovery.CancelAfter(TimeSpan.FromSeconds(25)); - Exception? dnsRestoreError = null; - try { recovery.Token.ThrowIfCancellationRequested(); await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); } - catch (Exception error) { dnsRestoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); } - try { recovery.Token.ThrowIfCancellationRequested(); await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); } - catch (Exception error) { restoreError = error; if (!sessionToken.IsCancellationRequested) 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(); - } - // Confirmed system shutdown forbids launching fresh helper processes. - // Kill the already-owned core above, retain failed journals, and let - // startup recovery finish after Windows is ready again. - sessionToken.ThrowIfCancellationRequested(); - await TunRouting.CleanupOwnedAdapterAsync(sessionToken).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 = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); - retry.CancelAfter(TimeSpan.FromSeconds(15)); - retry.Token.ThrowIfCancellationRequested(); - await TunRouting.RestoreAsync(retry.Token).ConfigureAwait(false); - } - if (!proxyRestored && !SystemProxy.Restore()) - throw new IOException("系统代理恢复未完成,恢复记录已保留。请勿继续升级安装。"); - if (dnsRestoreError is not null) - { - using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); - retry.CancelAfter(TimeSpan.FromSeconds(25)); - retry.Token.ThrowIfCancellationRequested(); - await ProxyDnsPolicy.RestoreAsync(retry.Token).ConfigureAwait(false); - } - _stoppedCleanly = true; - } - - 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, - } - }; - ClientRuntime.Start(process); - 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> ResolveProxyServerAddressesAsync( - string baseConfigJson, - CancellationToken cancellationToken) - { - var addresses = new HashSet(); - 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; - } - - internal void ValidateRuntime() => ClientRuntime.Validate(AppContext.BaseDirectory); - - 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; } - } -} +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 _learningCandidates = []; + private bool _needsRecovery; + private bool _disposed; + private NetworkOwnerLease? _ownerLease; + private bool _recoveryComplete; + private bool _stoppedCleanly; + private readonly CancellationTokenSource _systemShutdown = new(); + 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)? TailnetProbeEndpoint + { + get + { + var current = _baseConfigJson; + if (IsRunning && current is not null && UsesTailnet + && TailnetTransport.SameAuthorizedFallback(current, _tailnetFallbackConfigJson)) + return (TailnetTransport.Address(current)!, TailnetTransport.Port(current)); + return PreferredTailnetEndpoint; + } + } + 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; + + internal void ConfirmSessionShutdown() => _systemShutdown.Cancel(); + + public async Task SuspendForNetworkChangeAsync(CancellationToken token) + { + await _lifecycle.WaitAsync(token); + try { await StopCoreAsync(); } + finally { _lifecycle.Release(); } + } + + public async Task RebindNetworkAsync(CancellationToken token) + { + ValidateRuntime(); + await _lifecycle.WaitAsync(token); + var replacementStarted = false; + try + { + ValidateRuntime(); + if (!CanRebindNetwork) throw new InvalidOperationException("没有可恢复的已授权线路。"); + replacementStarted = true; + 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), + verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!)); + } + catch { if (replacementStarted) 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 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 CheckProxyHealthAsync(CancellationToken token) + => !IsRunning || _learningProbePort == 0 ? Task.FromResult(false) + : NodeHealthProbe.CheckTransportAsync(token, _learningProbePort); + + internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted, bool BusinessUnavailable = false); + internal async Task CheckHealthWithRepairAsync(CancellationToken token) + { + var expectedCore = CoreId; + if (await CheckHealthAsync(token)) return new(true, false, false); + if (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. + var proxy = await NodeHealthProbe.CheckReportAsync(deadline.Token, _learningProbePort); + if (!proxy.TransportReachable) return new(false, false, false); + proxyHealthy = true; + if (CoreId != expectedCore) return new(false, true, false); + // The forced proxy authenticated the same transport and received + // TLS/HTTP from at least one site. A site's outage is a business + // diagnostic, not evidence that this node needs to be replaced. + if (_routeMode != "smart" || !proxy.BusinessHealthy) return new(false, true, false, true); + 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? ObservationDetectedAsync { get; set; } + internal Action? 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) + { + // Fail locally before ownership/recovery or stopping a healthy core. + ValidateRuntime(); + 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 StartupLearningWarmup.RunAsync(async beginLearning => { + await _lifecycle.WaitAsync(cancellationToken); + var replacementStarted = false; + try + { + // Recheck after waiting for the lifecycle; a file may change. + ValidateRuntime(); + replacementStarted = true; + await StopCoreAsync(); + _baseConfigJson = configJson; + _tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson; + _preferredTailnetConfigJson = preferred; + _routeMode = routeMode; + _nodeSlug = nodeSlug; + await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null); + } + catch + { + if (replacementStarted) await StopCoreAsync().ConfigureAwait(false); + throw; + } + finally { _lifecycle.Release(); } + if (_routeMode == "smart") StatusMessage?.Invoke("正在验证本地直连与代理路径…"); + }, warmupToken => + // Keep the same targets, direct/proxy proof and lifecycle-gated + // commits. Only their read-only transport work overlaps DNS setup. + 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" }, warmupToken))), + cancellationToken); + } + + 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 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, + Action? beginStartupLearning = null) + { + ValidateRuntime(); + if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。"); + _stoppedCleanly = false; + 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 (!ClientRuntime.Start(_process)) throw new ClientRuntimeException(XrayPath, ClientRuntimeFault.CannotStart); + _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); + beginStartupLearning?.Invoke(_learningEpoch.Token); + await ProxyDnsPolicy.EnableAsync(_baseConfigJson, cancellationToken); + // The DNS policy is applied above. Management readiness does not + // require resolving the HTTPS authority through any DNS provider. + StatusMessage?.Invoke("Windows 网卡和 DNS 配置已应用。"); + await Task.Delay(250, cancellationToken); + _boundNetwork = physicalNetwork; + SafeDeleteConfig(); + } + catch + { + await StopCoreAsync(); + throw; + } + } + + 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 || _stoppedCleanly) return; + _learningEpoch.Cancel(); + var proxyRestored = SystemProxy.Restore(); + Exception? restoreError = null; + var sessionToken = _systemShutdown.Token; + using var recovery = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); + recovery.CancelAfter(TimeSpan.FromSeconds(25)); + Exception? dnsRestoreError = null; + try { recovery.Token.ThrowIfCancellationRequested(); await ProxyDnsPolicy.RestoreAsync(recovery.Token).ConfigureAwait(false); } + catch (Exception error) { dnsRestoreError = error; if (!sessionToken.IsCancellationRequested) AppPaths.WriteError(error); } + try { recovery.Token.ThrowIfCancellationRequested(); await TunRouting.RestoreAsync(recovery.Token).ConfigureAwait(false); } + catch (Exception error) { restoreError = error; if (!sessionToken.IsCancellationRequested) 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(); + } + // Confirmed system shutdown forbids launching fresh helper processes. + // Kill the already-owned core above, retain failed journals, and let + // startup recovery finish after Windows is ready again. + sessionToken.ThrowIfCancellationRequested(); + await TunRouting.CleanupOwnedAdapterAsync(sessionToken).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 = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); + retry.CancelAfter(TimeSpan.FromSeconds(15)); + retry.Token.ThrowIfCancellationRequested(); + await TunRouting.RestoreAsync(retry.Token).ConfigureAwait(false); + } + if (!proxyRestored && !SystemProxy.Restore()) + throw new IOException("系统代理恢复未完成,恢复记录已保留。请勿继续升级安装。"); + if (dnsRestoreError is not null) + { + using var retry = CancellationTokenSource.CreateLinkedTokenSource(sessionToken); + retry.CancelAfter(TimeSpan.FromSeconds(25)); + retry.Token.ThrowIfCancellationRequested(); + await ProxyDnsPolicy.RestoreAsync(retry.Token).ConfigureAwait(false); + } + _stoppedCleanly = true; + } + + 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, + } + }; + ClientRuntime.Start(process); + 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> ResolveProxyServerAddressesAsync( + string baseConfigJson, + CancellationToken cancellationToken) + { + var addresses = new HashSet(); + 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; + } + + internal void ValidateRuntime() => ClientRuntime.Validate(AppContext.BaseDirectory); + + 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; } + } +}