2026-11-15 21:33:18 +08:00
|
|
|
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<string> RebindAsync(string current, string? original,
|
|
|
|
|
Func<string, CancellationToken, Task> start, Func<Task> stop,
|
|
|
|
|
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, 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<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference,
|
|
|
|
|
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
|
|
|
|
|
Action<string> requireRoute, Action<string> status, Func<long> ticks,
|
|
|
|
|
CancellationToken token, bool allowKnownEndpoints = false,
|
|
|
|
|
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
|
|
|
|
Action<TransportDiagnostic>? 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<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("公网入口代理出口验证失败。");
|
|
|
|
|
}
|
|
|
|
|
}
|