Use verified company gateway for authorized Tailscale nodes

This commit is contained in:
UCVL Release
2026-11-16 10:37:17 +08:00
parent eb90ef4042
commit 16ac8227ea
7 changed files with 166 additions and 38 deletions
+1 -2
View File
@@ -63,9 +63,8 @@ internal sealed partial class MainForm
_checkingTailnetReadiness = true; _checkingTailnetReadiness = true;
try try
{ {
if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetEndpointConfirmation.ProbeAsync( reachable = await TailnetEndpointConfirmation.ProbeAsync(
probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token); _xray.ProbeCurrentOrPreferredTailnetAsync, _lifetime.Token);
} }
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
+9 -3
View File
@@ -564,19 +564,25 @@ internal sealed partial class MainForm : Form
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate); var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
_currentNodeLabel.Text = $"{candidateName} · 正在连接"; _currentNodeLabel.Text = $"{candidateName} · 正在连接";
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}"); SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
TailnetTransport.RouteBinding? tailnetBinding = null;
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference, connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
async (config, connectionToken) => { async (config, connectionToken) => {
candidateStarted = true; candidateStarted = true;
replacementStarted = true; replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken, await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(), TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate)); preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate),
tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding);
}, _xray.StopAsync, _xray.CheckProxyHealthAsync, }, _xray.StopAsync, _xray.CheckProxyHealthAsync,
TailnetTransport.RequireProbeRoute, null,
message => { _statusDetail.Text = $"{candidateName} · {message}"; }, message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, connectionToken, () => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate, allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync, endpointProbe: async (address, port, probeToken) =>
{
tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return tailnetBinding is not null;
},
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage)); diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken)) if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。"); throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
+2 -2
View File
@@ -71,7 +71,7 @@ internal static class NodeTransportConnector
// No background race or periodic optimization may replace a healthy session. // No background race or periodic optimization may replace a healthy session.
internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference, internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference,
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth, Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
Action<string> requireRoute, Action<string> status, Func<long> ticks, Action<string>? requireRoute, Action<string> status, Func<long> ticks,
CancellationToken token, bool allowKnownEndpoints = false, CancellationToken token, bool allowKnownEndpoints = false,
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null, Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
Action<TransportDiagnostic>? diagnostic = null) Action<TransportDiagnostic>? diagnostic = null)
@@ -83,7 +83,7 @@ internal static class NodeTransportConnector
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug)); void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
if (tailnet is null) Report("tailnet_skipped", reason); if (tailnet is null) Report("tailnet_skipped", reason);
else Report("tailnet_candidate", reason); else Report("tailnet_candidate", reason);
if (tailnet is not null) if (tailnet is not null && requireRoute is not null)
{ {
try try
{ {
+76 -15
View File
@@ -100,9 +100,40 @@ internal static class TailnetTransport
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>(); internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// Check the authorized proxy port through the existing OS route. Proxy internal sealed record RouteBinding(string InterfaceName, int InterfaceIndex, IPAddress LocalAddress, IPAddress? Gateway = null);
// authentication and egress are verified separately after startup.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token) // A company router can forward the authorized address over its Tailscale even
// when Windows has only a default route. Bind the probe to the chosen interface.
// A TCP response only permits trying the node; the normal proxy proof still runs.
internal static async Task<RouteBinding?> ProbeAuthorizedRouteAsync(string address, int port, CancellationToken token,
Func<string, RouteBinding>? readSpecificRoute = null,
Func<PhysicalUplink.Reading>? readUplink = null,
Func<string, int, RouteBinding, CancellationToken, Task<bool>>? probe = null)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return null;
RouteBinding? binding;
try { binding = readSpecificRoute is null ? ResolveRoute(address, true) : readSpecificRoute(address); }
catch (Exception error) when (IsRouteUnavailable(error))
{
var uplink = readUplink is null ? PhysicalUplink.Read() : readUplink();
binding = uplink.Success ? GatewayBinding(uplink.Network) : null;
}
token.ThrowIfCancellationRequested();
if (binding is null) return null;
var reachable = await (probe ?? ProbeBoundEndpointAsync)(address, port, binding, token);
token.ThrowIfCancellationRequested();
return reachable ? binding : null;
}
private static RouteBinding? GatewayBinding(TunRouting.PhysicalNetwork? network)
{
if (network is null || network.InterfaceIndex <= 0 || network.Ipv4Gateway.Equals(IPAddress.Any)
|| IsTailnetAddress(network.Ipv4Address.ToString())) return null;
return new(network.InterfaceName, network.InterfaceIndex, network.Ipv4Address, network.Ipv4Gateway);
}
internal static async Task<bool> ProbeBoundEndpointAsync(string address, int port, RouteBinding binding, CancellationToken token)
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false; if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
@@ -110,16 +141,47 @@ internal static class TailnetTransport
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds)); deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
try try
{ {
RequireProbeRoute(address); using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// The first connection may need to establish a Tailscale path. // Winsock IP_UNICAST_IF expects the IPv4 interface index in network byte order.
// Test the actual proxy listener instead of gating on ICMP. const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
using var socket = new TcpClient(AddressFamily.InterNetwork); socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(binding.InterfaceIndex));
socket.Bind(new IPEndPoint(binding.LocalAddress, 0));
await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false); await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false);
return true; return true;
} }
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; } catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception e) when (e is SocketException or NetworkInformationException catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; } }
private static bool IsRouteUnavailable(Exception error) => error is SocketException or NetworkInformationException
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception;
internal static RouteBinding RequireCurrentBinding(string address, RouteBinding? binding, TunRouting.PhysicalNetwork physicalNetwork)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
if (binding?.Gateway is not null)
{
var uplink = PhysicalUplink.Read(binding.InterfaceIndex);
if (!uplink.Success || GatewayBinding(uplink.Network) != binding || GatewayBinding(physicalNetwork) != binding)
throw new InvalidOperationException("公司网关路径已变化,请重新检测内网入口。");
return binding;
}
var current = ResolveRoute(address, true);
if (binding is not null && current != binding)
throw new InvalidOperationException("Tailscale 路由已变化,请重新检测内网入口。");
return current;
}
// Strict native-route detection for private-node policy and the standalone probe.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
try
{
return await ProbeBoundEndpointAsync(address, port, ResolveRoute(address, true), token).ConfigureAwait(false);
}
catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
} }
internal static bool SameAuthorizedFallback(string current, string? fallback) internal static bool SameAuthorizedFallback(string current, string? fallback)
@@ -144,13 +206,13 @@ internal static class TailnetTransport
// default route. No adapter-name, service or route-prefix prerequisite. // default route. No adapter-name, service or route-prefix prerequisite.
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion; // This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
// no /32 or user route is manufactured or removed. // no /32 or user route is manufactured or removed.
internal static string RequireExistingRoute(string address) => ResolveRoute(address, false); internal static string RequireExistingRoute(string address) => ResolveRoute(address, false).InterfaceName;
// Candidate discovery requires a specific existing route to the authorized // Candidate discovery requires a specific existing route to the authorized
// Tailnet address. A generic internet default must not carry probe packets. // Tailnet address. A generic internet default must not carry probe packets.
internal static void RequireProbeRoute(string address) => ResolveRoute(address, true); internal static void RequireProbeRoute(string address) => ResolveRoute(address, true);
private static string ResolveRoute(string address, bool requireSpecificRoute) private static RouteBinding ResolveRoute(string address, bool requireSpecificRoute)
{ {
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。"); if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -160,12 +222,11 @@ internal static class TailnetTransport
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase)) && !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local))); .FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
if (owner is null) if (local is null || owner?.GetIPProperties().GetIPv4Properties()?.Index is not { } index)
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。"); throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index if (requireSpecificRoute && SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index)
|| SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index))
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。"); throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
return owner.Name; return new(owner.Name, index, local);
} }
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable) internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
+37
View File
@@ -1,3 +1,4 @@
using System.Net;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
@@ -74,6 +75,42 @@ internal static class TailnetTransportSelfTest
checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],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["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; 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;
const string target = "100.99.142.38";
const int targetPort = 10803;
var native = new TailnetTransport.RouteBinding("Tailscale", 34, IPAddress.Parse("100.65.4.8"));
var office = new TunRouting.PhysicalNetwork("Ethernet", 9, IPAddress.Parse("172.16.1.154"),
24, IPAddress.Parse("172.16.1.1"), [IPAddress.Parse("172.16.1.1")]);
var gateway = new TailnetTransport.RouteBinding(office.InterfaceName, office.InterfaceIndex,
office.Ipv4Address, office.Ipv4Gateway);
TailnetTransport.RouteBinding NoSpecificRoute(string _) => throw new InvalidOperationException();
PhysicalUplink.Reading OfficeUplink() => new(true, office);
var testedBindings = new List<TailnetTransport.RouteBinding>();
Task<bool> Reachable(string address, int port, TailnetTransport.RouteBinding binding, CancellationToken token)
{
token.ThrowIfCancellationRequested();
testedBindings.Add(binding);
return Task.FromResult(address == target && port == targetPort);
}
checks["native_route_precedes_gateway"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, _ => native, () => throw new InvalidOperationException("Unused uplink"), Reachable) == native
&& testedBindings.SequenceEqual([native]);
testedBindings.Clear();
checks["company_gateway_requires_authorized_port_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, Reachable) == gateway
&& testedBindings.SequenceEqual([gateway]);
checks["unreachable_company_gateway_falls_back"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, (_, _, _, _) => Task.FromResult(false)) is null;
checks["no_gateway_no_unbound_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, () => new(true, office with { Ipv4Gateway = IPAddress.Any }),
(_, _, _, _) => throw new InvalidOperationException("Unbound probe")) is null;
checks["non_tailnet_address_never_probed"] = await TailnetTransport.ProbeAuthorizedRouteAsync("198.51.100.20", targetPort,
CancellationToken.None, _ => throw new InvalidOperationException("Unexpected route lookup"), OfficeUplink, Reachable) is null;
var routerRuntime = JsonNode.Parse(TunConfigBuilder.Build(prepared, office.InterfaceName, false, includeTun: false,
tailnetInterfaceName: gateway.InterfaceName))!.AsObject();
checks["router_runtime_binds_only_chosen_physical_interface"] =
routerRuntime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue<string>() == office.InterfaceName
&& Host(prepared) == target;
var preference = new TailnetPreference(); var preference = new TailnetPreference();
long tick = 100; long tick = 100;
+4 -3
View File
@@ -112,7 +112,8 @@ internal static class TunRouting
IReadOnlyCollection<IPAddress> proxyServerAddresses, IReadOnlyCollection<IPAddress> proxyServerAddresses,
CancellationToken cancellationToken, CancellationToken cancellationToken,
bool preservePrivateNodeRoute = false, bool preservePrivateNodeRoute = false,
string? preserveTailnetAddress = null) string? preserveTailnetAddress = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。"); if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。");
var proxyIpv4Addresses = proxyServerAddresses var proxyIpv4Addresses = proxyServerAddresses
@@ -134,7 +135,6 @@ internal static class TunRouting
if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1 if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1
|| proxyIpv4Addresses[0].ToString() != preserveTailnetAddress) || proxyIpv4Addresses[0].ToString() != preserveTailnetAddress)
throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。"); throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。");
TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
} }
var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault(); var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault();
if (tunDnsServer is null) if (tunDnsServer is null)
@@ -153,7 +153,8 @@ internal static class TunRouting
if (preservePrivateNodeRoute || preserveTailnetAddress is not null) if (preservePrivateNodeRoute || preserveTailnetAddress is not null)
{ {
if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString()); if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString());
if (preserveTailnetAddress is not null) TailnetTransport.RequireExistingRoute(preserveTailnetAddress); if (preserveTailnetAddress is not null)
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
} }
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index, var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
preservePrivateNodeRoute || preserveTailnetAddress is not null); preservePrivateNodeRoute || preserveTailnetAddress is not null);
+36 -12
View File
@@ -32,7 +32,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
// A public fallback is sticky: automatic physical-network recovery must // A public fallback is sticky: automatic physical-network recovery must
// never promote it to this cached internal alternative. // never promote it to this cached internal alternative.
private string? _preferredTailnetConfigJson; private string? _preferredTailnetConfigJson;
private string? _tailnetInterfaceName; private TailnetTransport.RouteBinding? _tailnetBinding;
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null; internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
internal (string Address, int Port)? TailnetProbeEndpoint internal (string Address, int Port)? TailnetProbeEndpoint
{ {
@@ -56,6 +56,18 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred)); return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
} }
} }
internal async Task<bool> ProbeCurrentOrPreferredTailnetAsync(CancellationToken token)
{
if (TailnetProbeEndpoint is not { } endpoint) return false;
if (!UsesTailnet)
return await TailnetTransport.ProbeAuthorizedRouteAsync(endpoint.Address, endpoint.Port, token) is not null;
var binding = _tailnetBinding;
// For an active session, verify the path used by Xray. A healthy
// alternate interface must not conceal failure of the current one.
return binding is not null
&& await TailnetTransport.ProbeBoundEndpointAsync(endpoint.Address, endpoint.Port, binding, token);
}
private string _routeMode = "smart"; private string _routeMode = "smart";
private string _nodeSlug = ""; private string _nodeSlug = "";
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe"); private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
@@ -89,12 +101,20 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
replacementStarted = true; replacementStarted = true;
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests. await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
TailnetTransport.RouteBinding? binding = null;
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson, _baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); }, async (config, rebindToken) =>
{
_baseConfigJson = config;
await StartCoreAsync(rebindToken, tailnetBinding: TailnetTransport.Address(config) is null ? null : binding);
},
StopCoreAsync, CheckProxyHealthAsync, token, StopCoreAsync, CheckProxyHealthAsync, token,
preferredTailnetConfig: _preferredTailnetConfigJson, preferredTailnetConfig: _preferredTailnetConfigJson,
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); }, endpointProbe: async (address, port, probeToken) =>
endpointProbe: TailnetTransport.ProbeEndpointAsync, {
binding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return binding is not null;
},
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!)); verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!));
} }
@@ -209,7 +229,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
} }
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken, internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null) string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
// Fail locally before ownership/recovery or stopping a healthy core. // Fail locally before ownership/recovery or stopping a healthy core.
ValidateRuntime(); ValidateRuntime();
@@ -237,7 +258,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_preferredTailnetConfigJson = preferred; _preferredTailnetConfigJson = preferred;
_routeMode = routeMode; _routeMode = routeMode;
_nodeSlug = nodeSlug; _nodeSlug = nodeSlug;
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null); await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null, tailnetBinding);
} }
catch catch
{ {
@@ -264,7 +285,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_baseConfigJson = null; _baseConfigJson = null;
_tailnetFallbackConfigJson = null; _tailnetFallbackConfigJson = null;
_preferredTailnetConfigJson = null; _preferredTailnetConfigJson = null;
_tailnetInterfaceName = null; _tailnetBinding = null;
_nodeSlug = ""; _nodeSlug = "";
_boundNetwork = null; _boundNetwork = null;
} }
@@ -289,7 +310,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
} }
private async Task StartCoreAsync(CancellationToken cancellationToken, private async Task StartCoreAsync(CancellationToken cancellationToken,
Action<CancellationToken>? beginStartupLearning = null) Action<CancellationToken>? beginStartupLearning = null, TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
ValidateRuntime(); ValidateRuntime();
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。"); if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
@@ -299,10 +320,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost; var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson)); if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson));
var tailnetAddress = TailnetTransport.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 proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken);
var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses); var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses);
_tailnetBinding = tailnetAddress is null ? null : TailnetTransport.RequireCurrentBinding(tailnetAddress, tailnetBinding, physicalNetwork);
var tailnetInterface = _tailnetBinding?.InterfaceName;
if (_tailnetBinding?.Gateway is not null)
AppPaths.WriteLog(new TransportDiagnostic("tailnet_route", "authorized_port_reached_via_gateway", _nodeSlug).SafeMessage);
_learningEpoch = new CancellationTokenSource(); _learningEpoch = new CancellationTokenSource();
_learningBudget = new LearningProbeBudget(); _learningBudget = new LearningProbeBudget();
_networkLearned.Clear(); _networkLearned.Clear();
@@ -389,7 +412,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
try try
{ {
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken, preservePrivateRoute, tailnetAddress); await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken,
preservePrivateRoute, tailnetAddress, _tailnetBinding);
// Apply 0.2.5 routing first, then wait until Windows has completed // Apply 0.2.5 routing first, then wait until Windows has completed
// DAD before applications can use the tunnel's DNS/IPv4 path. // DAD before applications can use the tunnel's DNS/IPv4 path.
await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true); await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true);
@@ -534,7 +558,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1, var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1,
Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() }); Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() });
var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName, var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName,
_learningProbePort, _directProbePort, _tailnetInterfaceName); _learningProbePort, _directProbePort, _tailnetBinding?.InterfaceName);
await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token); await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token);
_networkLearned.Applied(); _networkLearned.Applied();
} }