Publish Zonghengjia Windows 0.3.17 client source

This commit is contained in:
2026-11-15 21:33:18 +08:00
parent 36de255318
commit ebec81ceb1
25 changed files with 3745 additions and 3412 deletions
+13 -4
View File
@@ -33,11 +33,9 @@ internal sealed class ConnectionHealthPolicy
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.
if (currentCore is not null && businessUnavailable && proxyHealthy) {
Failures = 0; _nextProbe = now + 20_000;
var advisory = proxyHealthy ? Decision.WebsiteUnavailable : Decision.TailnetEgressUnverified;
const Decision advisory = Decision.WebsiteUnavailable;
var confirmed = _advisoryCandidate == advisory;
_advisoryCandidate = advisory;
return confirmed ? advisory : Decision.PendingAdvisory;
@@ -49,6 +47,17 @@ internal sealed class ConnectionHealthPolicy
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.
+6 -3
View File
@@ -59,9 +59,12 @@ internal static class ConnectionHealthSelfTest
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;
&& !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
+24
View File
@@ -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();
+6 -2
View File
@@ -33,7 +33,10 @@ internal static class LearningPolicy
&& !(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)
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;
@@ -69,8 +72,9 @@ internal static class LearningPolicy
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")
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");
}
+59
View File
@@ -1,5 +1,6 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
namespace UCVL.VPNPlus;
@@ -86,8 +87,66 @@ internal static class LearningSelfTest
var directOutbound = both["outbounds"]!.AsArray().Single(x=>x!["tag"]!.GetValue<string>()=="ucvl-learning-direct")!;
checks["direct_probe_binds_physical"] = directOutbound["streamSettings"]!["sockopt"]!["interface"]!.GetValue<string>() == "Ethernet";
checks["direct_probe_not_learned_route"] = both["routing"]!["rules"]![0]!["outboundTag"]!.GetValue<string>() == "block" && both["routing"]!["rules"]![1]!["outboundTag"]!.GetValue<string>() == "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<string, bool> 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<string>()).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<string>() == "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<string>() == "proxy"
&& rule["domain"]!.AsArray().Any(n => n!.GetValue<string>() == "regexp:.*"));
}
}
}
+8 -6
View File
@@ -5,6 +5,7 @@ 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)
@@ -47,9 +48,8 @@ internal sealed partial class MainForm
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.
// 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;
@@ -60,14 +60,16 @@ internal sealed partial class MainForm
return;
}
var reachable = false;
_checkingTailnetReadiness = true;
try
{
if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetPingConfirmation.ProbeAsync(
pingToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, pingToken), _lifetime.Token);
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;
@@ -78,7 +80,7 @@ internal sealed partial class MainForm
_tailnetPreference.CommitDomainFallback();
_transportRetryNodeSlug = slug;
_connectionHealth.Invalidate();
AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "ping_failed_same_node_domain_fallback", slug).SafeMessage);
AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "tcp_endpoint_failed_same_node_domain_fallback", slug).SafeMessage);
await ToggleConnectionAsync(suppressDialogs: true, reconnect: true);
return;
}
+1 -1
View File
@@ -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;
+22 -8
View File
@@ -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();
+12 -5
View File
@@ -104,24 +104,31 @@ internal static class NodeHealthProbe
internal static async Task<bool> CheckTransportAsync(CancellationToken token, int proxyPort)
=> (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable;
internal static async Task<Report> CheckReportAsync(CancellationToken token, int proxyPort = 0, bool transportOnly = false)
internal static async Task<Report> 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(new SocketsHttpHandler {
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 targets = new[] {
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(Accepts(index, status), AcceptsTransportStatus(status), $"http_{status}");
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"); }
@@ -136,7 +143,7 @@ internal static class NodeHealthProbe
try
{
var report = await AggregateReportAsync(probes, token, () => { }).ConfigureAwait(false);
if (!report.BusinessHealthy)
if (!report.BusinessHealthy && transport is null)
{
var path = proxyPort > 0 ? "forced_proxy" : "ordinary";
var outcomes = targets.Select((target, index) =>
+38
View File
@@ -1,3 +1,4 @@
using System.Net;
using System.Text.Json;
namespace UCVL.VPNPlus;
@@ -163,6 +164,27 @@ internal static class NodeHealthProbeSelfTest
.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;
@@ -183,6 +205,22 @@ internal static class NodeHealthProbeSelfTest
if (!condition) throw new InvalidOperationException(message);
}
private sealed class IndependentHttpsFixture : HttpMessageHandler
{
internal const string Anchor = "https://www.cloudflare.com/cdn-cgi/trace";
internal List<string> Seen { get; } = new();
protected override Task<HttpResponseMessage> 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<HttpResponseMessage>(new HttpRequestException("business service unavailable"));
}
}
private static async Task<bool> Finished(Task<bool> result)
{
try { return await result.WaitAsync(TimeSpan.FromSeconds(1)); }
+40 -11
View File
@@ -16,7 +16,7 @@ internal static class NodeTransportConnector
Func<CancellationToken, Task<bool>> proxyHealth, CancellationToken token,
string? preferredTailnetConfig = null, Action<string>? requireRoute = null,
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
Action<TransportDiagnostic>? diagnostic = null)
Action<TransportDiagnostic>? diagnostic = null, bool verifyPublicEgress = true)
{
token.ThrowIfCancellationRequested();
var tailnet = TailnetTransport.Address(current) is not null;
@@ -43,9 +43,15 @@ internal static class NodeTransportConnector
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();
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;
}
@@ -54,8 +60,9 @@ internal static class NodeTransportConnector
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();
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!;
}
}
@@ -140,13 +147,35 @@ internal static class NodeTransportConnector
}
}
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();
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<string, CancellationToken, Task> start, Func<CancellationToken, Task<bool>> 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("公网入口代理出口验证失败。");
}
}
+8 -5
View File
@@ -11,7 +11,7 @@ internal static class ProxyDnsPolicy
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)
internal static string[] Namespaces(string config, IEnumerable<(string TargetType, string Target)> activeTargets)
{
var domains = new HashSet<string>(SeedDomains, StringComparer.OrdinalIgnoreCase);
var exact = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
@@ -25,17 +25,20 @@ internal static class ProxyDnsPolicy
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);
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;
return domains.Where(Safe).SelectMany(d => new[] { d, "." + d })
.Concat(exact.Where(Safe)).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToArray();
// 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);
var names = Namespaces(config, LearningStore.GetActiveTargets());
if (names.Length == 0) return;
AppPaths.EnsureDirectory();
// Intent first; a crash between policy creation and journal completion
+11
View File
@@ -1,5 +1,16 @@
# 优创⁺纵横家 Windows 客户端
## Windows 0.3.17
智能代理和全局代理优先验证已授权的 Tailscale 入口。内网代理端口或出口持续异常时,客户端通过同一节点的公网入口重新连接,并在收到经代理转发的 HTTPS 响应后显示连接成功。切换网络后重新验证代理出口,Tailscale 控制和中继流量使用直连路由。
### 正式发布流程
1. 验收客户端连接、断开及覆盖升级,发布同一构建的源码标签和安装包,从旧客户端核对更新提示及安装包摘要。
2. 将同一版本登记到公司内部资源中心,并验证员工可下载。
3. 在公司网站「公司动态」发布版本新闻并配一张产品图,匿名检查栏目、正文和配图。
4. 经小小优运维发送本次更新通知,核对发送回执。发布重试时按产品、平台及版本查找现有记录。
## Windows 0.3.8
管理平台已迁移至 https://vpn.ucvl.cn/。登录、注册和平台探测统一使用新域名,直连备用地址已随迁移更新。
+24 -4
View File
@@ -44,20 +44,40 @@ internal static class RouteLeaseSelfTest
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)
&& !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]);
&& 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_and_tailnet_paths_survive_cleanup"] = table.Routes.SequenceEqual([tailnet, management]);
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;
+17
View File
@@ -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));
}
@@ -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
// 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
{
internal const int Attempts = 3;
internal static async Task<bool> ProbeAsync(Func<CancellationToken, Task<bool>> ping,
private const int Attempts = 3;
internal static async Task<bool> ProbeAsync(Func<CancellationToken, Task<bool>> probe,
CancellationToken token, TimeSpan? budget = null)
{
token.ThrowIfCancellationRequested();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(budget ?? TimeSpan.FromSeconds(4));
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 ping(deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
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 ICMP attempt is inconclusive. */ }
token.ThrowIfCancellationRequested();
catch (Exception) { /* One failed TCP attempt is inconclusive. */ }
}
token.ThrowIfCancellationRequested();
return false;
}
}
@@ -0,0 +1,53 @@
namespace UCVL.VPNPlus;
internal static class TailnetEndpointConfirmationSelfTest
{
internal static async Task<Dictionary<string, bool>> CheckAsync()
{
var checks = new Dictionary<string, bool>();
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<bool>(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<bool>(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;
}
}
@@ -1,36 +0,0 @@
namespace UCVL.VPNPlus;
internal static class TailnetPingConfirmationSelfTest
{
internal static async Task<Dictionary<string, bool>> CheckAsync()
{
var checks = new Dictionary<string, bool>();
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<bool>(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<bool>(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;
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ internal static class TailnetReadinessSelfTest
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);
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");
+4 -4
View File
@@ -10,6 +10,7 @@ namespace UCVL.VPNPlus;
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
@@ -99,15 +100,14 @@ internal static class TailnetTransport
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// 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.
// Check the authorized proxy port through the existing OS route. Proxy
// authentication and egress are verified separately after startup.
internal static async Task<bool> 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));
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
try
{
RequireProbeRoute(address);
+69 -19
View File
@@ -82,16 +82,21 @@ internal static class TailnetTransportSelfTest
Task Start(string json, CancellationToken token) { token.ThrowIfCancellationRequested(); starts.Add(Host(json)); return Task.CompletedTask; }
Task Stop() { stops++; return Task.CompletedTask; }
Task<bool> Healthy(CancellationToken token) { token.ThrowIfCancellationRequested(); probes++; return Task.FromResult(true); }
Task<bool> 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, _=>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;
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;
starts.Clear(); routeReads=0; probes=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["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);
@@ -121,11 +126,44 @@ internal static class TailnetTransportSelfTest
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["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<TransportDiagnostic>();
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");
@@ -167,7 +205,7 @@ internal static class TailnetTransportSelfTest
&& 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;
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");
@@ -244,11 +282,12 @@ internal static class TailnetTransportSelfTest
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,
_ => { 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 == 1;
&& 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)!;
@@ -269,7 +308,7 @@ internal static class TailnetTransportSelfTest
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["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();
@@ -287,14 +326,14 @@ internal static class TailnetTransportSelfTest
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"});
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["explicit_disabled_transport_never_probed"] = !selected && starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && probes == 0;
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";
@@ -308,12 +347,12 @@ internal static class TailnetTransportSelfTest
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"] =
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,
_=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None,allowKnownEndpoints:true,
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;
@@ -330,17 +369,18 @@ internal static class TailnetTransportSelfTest
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;
&& 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==0;
&& starts.SequenceEqual(new[]{"002.vpn.toplc.cn"}) && stops==beforeStops && probes==1;
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
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 {
@@ -401,10 +441,20 @@ internal static class TailnetTransportSelfTest
};
});
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);
&& 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<string>(), 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}));
+16
View File
@@ -110,6 +110,7 @@ internal static class TunConfigBuilder
// 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
@@ -191,6 +192,8 @@ internal static class TunConfigBuilder
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();
}
@@ -273,6 +276,19 @@ internal static class TunConfigBuilder
&& runtimeDnsServers?[1]?.GetValue<string>() == "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;
+6
View File
@@ -13,6 +13,8 @@ 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,
@@ -168,6 +170,10 @@ internal static class TunRouting
{
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)
+4 -4
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.3.14</Version>
<AssemblyVersion>0.3.14.0</AssemblyVersion>
<FileVersion>0.3.14.0</FileVersion>
<InformationalVersion>0.3.14</InformationalVersion>
<Version>0.3.17</Version>
<AssemblyVersion>0.3.17.0</AssemblyVersion>
<FileVersion>0.3.17.0</FileVersion>
<InformationalVersion>0.3.17</InformationalVersion>
<Product>纵横家</Product>
<Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description>
+2 -1
View File
@@ -95,7 +95,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
preferredTailnetConfig: _preferredTailnetConfigJson,
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
endpointProbe: TailnetTransport.ProbeEndpointAsync,
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
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(); }