Windows 0.3.6 runtime preflight and update download reliability source delta; connection fixes retained; no private history or other platform changes

This commit is contained in:
2026-11-06 15:28:10 +00:00
parent 23a87387b8
commit ac40dd3a6c
18 changed files with 599 additions and 58 deletions
+76
View File
@@ -0,0 +1,76 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
namespace UCVL.VPNPlus;
internal enum ClientRuntimeFault { Missing, Unreadable, Empty, CannotStart }
// An installation failure is local to every node. Never feed it into node or
// transport health/cooldown, or retry it by changing the user's network route.
internal sealed class ClientRuntimeException(string componentPath, ClientRuntimeFault fault, Exception? inner = null)
: IOException(MessageFor(componentPath, fault), inner)
{
internal string ComponentPath { get; } = Path.GetFullPath(componentPath);
internal ClientRuntimeFault Fault { get; } = fault;
private static string MessageFor(string path, ClientRuntimeFault fault)
{
var issue = fault switch
{
ClientRuntimeFault.Missing => "缺失",
ClientRuntimeFault.Empty => "为空或已损坏",
ClientRuntimeFault.CannotStart => "无法启动(程序文件或依赖异常)",
_ => "无法读取(权限或文件占用)",
};
return $"本机客户端组件{issue}:{Path.GetFileName(path)}\n位置:{Path.GetFullPath(path)}\n\n"
+ "请重新运行纵横家最新完整安装包,在原安装目录修复。账号和配置会保留。";
}
// Only local installation identity. No token, node config or credentials.
internal string Diagnostic => $"client_runtime fault={Fault} component={Clean(ComponentPath)}"
+ $" process={Clean(Environment.ProcessPath ?? "unknown")} version={Clean(Application.ProductVersion)}";
private static string Clean(string value) => value.Replace('\r', ' ').Replace('\n', ' ');
}
internal static class ClientRuntime
{
internal static readonly string[] Components = ["xray.exe", "geoip.dat", "geosite.dat", "wintun.dll"];
internal static void Validate(string installationDirectory)
{
// Resolve exclusively beside this application, never the current
// working directory, PATH, or an unrelated installed Xray binary.
var directory = Path.Combine(Path.GetFullPath(installationDirectory), "xray");
foreach (var name in Components)
{
var path = Path.Combine(directory, name);
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete);
if (stream.Length == 0 || stream.ReadByte() < 0)
throw new ClientRuntimeException(path, ClientRuntimeFault.Empty);
}
catch (ClientRuntimeException) { throw; }
catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Missing, error); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException or SecurityException)
{ throw new ClientRuntimeException(path, ClientRuntimeFault.Unreadable, error); }
}
}
internal static bool Start(Process process)
{
try { return process.Start(); }
// The executable can disappear or become blocked after preflight.
// Classify only known local CreateProcess failures, not socket errors,
// arbitrary IO, or remote Reality/TLS/configuration failures.
catch (Win32Exception error) when (error.NativeErrorCode is 2 or 3 or 5 or 32 or 33 or 126 or 193 or 216 or 225 or 740)
{
var fault = error.NativeErrorCode is 2 or 3 ? ClientRuntimeFault.Missing
: error.NativeErrorCode is 5 or 32 or 33 ? ClientRuntimeFault.Unreadable : ClientRuntimeFault.CannotStart;
throw new ClientRuntimeException(process.StartInfo.FileName, fault, error);
}
}
}
+127
View File
@@ -0,0 +1,127 @@
using System.Text.Json;
using System.Security.AccessControl;
using System.Security.Principal;
namespace UCVL.VPNPlus;
internal static class ClientRuntimeSelfTest
{
internal static async Task<Dictionary<string, bool>> CheckAsync()
{
var checks = new Dictionary<string, bool>();
var root = Path.Combine(Path.GetTempPath(), "ucvl-runtime-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.Combine(root, "xray"));
// Tiny inert fixture files; none are executed or treated as real Xray.
void Seed() { foreach (var name in ClientRuntime.Components) File.WriteAllBytes(Path.Combine(root, "xray", name), [1, 2]); }
ClientRuntimeException? ReadFault()
{
try { ClientRuntime.Validate(root); return null; }
catch (ClientRuntimeException error) { return error; }
}
async Task<bool> RuntimeFailure(Func<Task> operation)
{
try { await operation(); return false; }
catch (ClientRuntimeException) { return true; }
}
try
{
Seed();
checks["four_readable_nonempty_components_accepted"] = ReadFault() is null;
foreach (var name in ClientRuntime.Components)
{
var path = Path.Combine(root, "xray", name);
File.Delete(path);
var missing = ReadFault();
checks["missing_" + name] = missing is { Fault: ClientRuntimeFault.Missing }
&& missing.ComponentPath == path && missing.Message.Contains("完整安装包") && missing.Message.Contains(path);
Seed();
File.WriteAllBytes(path, []);
checks["empty_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Empty };
Seed();
using (var locked = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
checks["locked_not_reported_missing_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
}
var deniedPath = Path.Combine(root, "xray", "xray.exe");
var originalAcl = new FileInfo(deniedPath).GetAccessControl();
try
{
var deniedAcl = new FileInfo(deniedPath).GetAccessControl();
deniedAcl.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User!, FileSystemRights.ReadData,
AccessControlType.Deny));
new FileInfo(deniedPath).SetAccessControl(deniedAcl);
checks["access_denied_not_reported_missing"] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
}
finally { new FileInfo(deniedPath).SetAccessControl(originalAcl); }
var error = new ClientRuntimeException(Path.Combine(root, "xray", "xray.exe"), ClientRuntimeFault.Missing);
using (var absent = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName=Path.Combine(root, "xray", "missing-fixture.exe"), UseShellExecute=false, CreateNoWindow=true,
} })
{
try { ClientRuntime.Start(absent); checks["disappeared_executable_is_local_failure"] = false; }
catch (ClientRuntimeException failure) { checks["disappeared_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.Missing; }
}
using (var invalid = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName=Path.Combine(root, "xray", "xray.exe"), UseShellExecute=false, CreateNoWindow=true,
} })
{
try { ClientRuntime.Start(invalid); checks["invalid_executable_is_local_failure"] = false; }
catch (ClientRuntimeException failure) { checks["invalid_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.CannotStart; }
}
checks["diagnostic_contains_only_installation_identity"] = error.Diagnostic.Contains(error.ComponentPath)
&& error.Diagnostic.Contains(" process=") && error.Diagnostic.Contains(" version=")
&& !error.Diagnostic.Contains('\n') && !error.Diagnostic.Contains('\r');
var response = JsonSerializer.Deserialize<ConfigResponse>("""
{"config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart",
"tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.64.0.2","port":10803},
"config":{"inbounds":[],"outbounds":[
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"vpn002.example.invalid","port":11082,"users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]},
"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}},
{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[]}}}
""")!;
foreach (var stage in new[] { "route", "ping", "tailnet_start", "public_start" })
{
var preference = new TailnetPreference();
var starts = 0; var stops = 0; var probes = 0;
Task Start(string _, CancellationToken token) { starts++; if (stage is "tailnet_start" or "public_start") throw error; return Task.CompletedTask; }
Task Stop() { stops++; return Task.CompletedTask; }
Task<bool> Health(CancellationToken _) { probes++; return Task.FromResult(true); }
void Route(string _) { if (stage == "route") throw error; }
Task<bool> Ping(string _, int port, CancellationToken token) { if (stage == "ping") throw error; return Task.FromResult(true); }
var selectedResponse = stage == "public_start" ? new ConfigResponse {
Config=response.Config, ConfigContract=response.ConfigContract, ConnectionScope=response.ConnectionScope,
Node=response.Node, RouteMode=response.RouteMode, TailscaleEndpoint=null,
} : response;
var rejected = await RuntimeFailure(() => NodeTransportConnector.ConnectAsync(selectedResponse, preference, Start, Stop,
Health, Route, _ => { }, () => 100, CancellationToken.None, endpointProbe: Ping));
checks[stage + "_local_failure_propagates"] = rejected;
checks[stage + "_no_domain_or_cooldown_state_change"] = !preference.DomainOnly && preference.MayTry("tokyo", 101);
checks[stage + "_no_cleanup_or_health_attempt"] = stops == 0 && probes == 0;
checks[stage + "_no_second_start"] = starts == (stage is "tailnet_start" or "public_start" ? 1 : 0);
}
var tailnet = TailnetTransport.TryPrepare(response)!;
var rebindStarts = 0; var rebindStops = 0;
checks["rebind_local_failure_propagates_without_fallback"] = await RuntimeFailure(() => NodeTransportConnector.RebindAsync(
tailnet, response.GetRuntimeConfigJson(), (_, _) => { rebindStarts++; throw error; },
() => { rebindStops++; return Task.CompletedTask; }, _ => Task.FromResult(true), CancellationToken.None))
&& rebindStarts == 1 && rebindStops == 0;
}
finally
{
// Only these four known inert files in the fresh GUID directory.
foreach (var name in ClientRuntime.Components) File.Delete(Path.Combine(root, "xray", name));
Directory.Delete(Path.Combine(root, "xray"));
Directory.Delete(root);
}
return checks;
}
internal static async Task<int> RunAsync()
{
var checks = await CheckAsync();
var passed = checks.Values.All(value => value);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-runtime-self-test.json"),
JsonSerializer.Serialize(new { passed, network_modified = false, installed_client_modified = false, installer_launched = false, checks },
new JsonSerializerOptions { WriteIndented=true }));
return passed ? 0 : 92;
}
}
+4 -1
View File
@@ -6,6 +6,9 @@ namespace UCVL.VPNPlus;
internal static class ClientUpdater
{
private const long MaximumInstallerBytes = 200L * 1024 * 1024;
// A 200 MiB package takes 1024 seconds on a slow 200 KiB/s link.
// Keep a bounded transfer budget with headroom; idle reads still stop at 30s.
internal static readonly TimeSpan DefaultTotalTimeout = TimeSpan.FromMinutes(20);
internal static bool IsNewerVersion(string candidate, string? current = null)
{
@@ -88,7 +91,7 @@ internal static class ClientUpdater
// Bound the entire transfer and each body read independently; a stalled
// download must not leave the update UI disabled indefinitely.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(totalTimeout ?? TimeSpan.FromMinutes(10));
deadline.CancelAfter(totalTimeout ?? DefaultTotalTimeout);
var idleLimit = idleTimeout ?? TimeSpan.FromSeconds(30);
try
{
+3 -2
View File
@@ -2,8 +2,8 @@ using System.Text.Json.Nodes;
namespace UCVL.VPNPlus;
// Compatibility addresses explicitly supplied by the operator and authenticated
// against these two existing nodes on 2026-09-26. Not new nodes or login grants.
// Operator-supplied compatibility addresses for already-authorized nodes.
// These are same-node transports, not new nodes or login grants.
// The authenticated API config remains the authority for credentials and identity.
internal static class KnownTailnetEndpoints
{
@@ -30,6 +30,7 @@ internal static class KnownTailnetEndpoints
{
"aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803),
"aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083),
"racknerd-newyork-004" => (Host: "004.vpn.example.invalid", PublicPort: 11084, Address: "100.64.0.44", Port: 11084),
_ => default
};
reason = "known_node_unmapped";
+6 -4
View File
@@ -38,14 +38,15 @@ internal sealed partial class MainForm
private async Task CheckUplinkAsync()
{
if (_preview || _uiOnly || _exiting || !_wantConnected || _busy || _uplinkChecking || _xray.IsTransitioning || !_xray.CanRebindNetwork) return;
if (_runtimeRepairRequired || _preview || _uiOnly || _exiting || !_wantConnected || _busy || _uplinkChecking || _xray.IsTransitioning || !_xray.CanRebindNetwork) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
_uplinkChecking = true;
var refreshAuthorization = false;
var operating = false;
try
{
var reading = await Task.Run(() => PhysicalUplink.Read(_xray.BoundNetwork?.InterfaceIndex));
if (_exiting || !_wantConnected || _busy || _xray.IsTransitioning) return;
if (_runtimeRepairRequired || _exiting || !_wantConnected || _busy || _xray.IsTransitioning) return;
if (!reading.Success) return;
if (!_handover.Pending && PhysicalUplink.Fingerprint(reading.Network) == _xray.BoundNetworkFingerprint && reading.Network is not null)
{
@@ -61,7 +62,7 @@ internal sealed partial class MainForm
_connectButton.Enabled = true;
_connectButton.Text = "断开";
var result = await _handover.ObserveAsync(reading, Environment.TickCount64, _handoverCancellation.Token);
if (!_wantConnected || _exiting) return;
if (_runtimeRepairRequired || !_wantConnected || _exiting) return;
if (result == NetworkHandover.Result.Recovered)
{
if (_currentNodeUsesTailnet && !_xray.UsesTailnet)
@@ -89,10 +90,11 @@ internal sealed partial class MainForm
}
}
catch (OperationCanceledException) { }
catch (ClientRuntimeException error) { HandleClientRuntimeFailure(error, suppressDialogs: true); }
catch (Exception error)
{
AppPaths.WriteError(error);
if (_wantConnected && !_exiting)
if (!_runtimeRepairRequired && _wantConnected && !_exiting)
{
SetConnectionState(false, "等待网络恢复", "本地网络尚未就绪,将自动重试;可点击断开取消。");
DisplayTraffic(null, null, "等待网络恢复");
+10 -1
View File
@@ -11,6 +11,12 @@ internal sealed partial class MainForm
{
_connectionAttemptCancellation?.Cancel();
_accessToken = token;
if (token is null)
{
_runtimeRepairRequired = false;
_statusDetail.AccessibleDescription = null;
_runtimeRepairTip.SetToolTip(_statusDetail, null);
}
_connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64);
_connectionHealth.Invalidate();
_sessionRevision++;
@@ -46,7 +52,8 @@ internal sealed partial class MainForm
// retries the same node's domain through the normal fresh-grant connector.
private async Task CheckTailnetReadinessAsync()
{
if (_uiOnly || _preview) return;
if (_runtimeRepairRequired || !_wantConnected || _uiOnly || _preview) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket))
{
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting;
@@ -63,6 +70,7 @@ internal sealed partial class MainForm
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
if (_exiting || IsDisposed || Disposing) return;
if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return;
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy;
if (result == TailnetReadinessPolicy.Result.Fallback && _currentNodeSlug is { } slug)
{
@@ -86,6 +94,7 @@ internal sealed partial class MainForm
{
if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning
|| _xray.UsesTailnet || !_tailnetReadiness.IsReady) return;
if (!PreflightClientRuntime(suppressDialogs: false, clearRepair: true)) return;
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
_tailnetPreference.ResetForUserConnect();
+60 -3
View File
@@ -78,6 +78,8 @@ internal sealed partial class MainForm : Form
private bool _updateCheckRunning;
private DateTimeOffset _nextUpdateCheckAt = DateTimeOffset.MinValue;
private bool _installerLaunched;
private bool _runtimeRepairRequired;
private readonly ToolTip _runtimeRepairTip = new() { AutoPopDelay = 20_000 };
internal bool WindowExitSelfTestPassed { get; private set; }
internal bool NetworkRecoveryFailed { get; private set; }
@@ -489,6 +491,9 @@ internal sealed partial class MainForm : Form
return;
}
if (reconnect && _runtimeRepairRequired) return;
if (!PreflightClientRuntime(suppressDialogs, clearRepair: !reconnect)) return;
ConnectionSelection selection;
try
{
@@ -514,6 +519,7 @@ internal sealed partial class MainForm : Form
foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug);
SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…");
var replacementStarted = false;
var runtimeFailure = false;
try
{
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
@@ -597,6 +603,7 @@ internal sealed partial class MainForm : Form
break;
}
catch (LocalNetworkException) { throw; }
catch (ClientRuntimeException) { throw; }
catch (TailnetUnavailableException)
{
// Connector cleans up only a core it actually attempted.
@@ -646,6 +653,11 @@ internal sealed partial class MainForm : Form
_notifyIcon.Text = "纵横家 · 已连接";
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
}
catch (ClientRuntimeException exception)
{
runtimeFailure = true;
HandleClientRuntimeFailure(exception, suppressDialogs);
}
catch (Exception) when (connectionToken.IsCancellationRequested)
{
if (!_exiting) await DisconnectAsync();
@@ -682,12 +694,52 @@ internal sealed partial class MainForm : Form
}
finally
{
if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
if (!runtimeFailure && !_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null;
SetBusy(false);
}
}
private void HandleClientRuntimeFailure(ClientRuntimeException exception, bool suppressDialogs)
{
var firstNotice = !_runtimeRepairRequired;
_runtimeRepairRequired = true;
AppPaths.WriteLog(exception.Diagnostic);
// Component repair requires the installer, not another node or route.
// A running core retains its existing configuration and network state.
var connected = _xray.IsRunning;
_wantConnected = connected;
_nextReconnect = DateTimeOffset.MaxValue;
_connectionHealth.Invalidate();
_connectionHealth.ResetFailures();
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
_handover.Reset();
SetConnectionState(connected, connected ? "组件需修复 · 保留原连接" : "客户端组件需要修复",
exception.Message.Replace('\n', ' '));
_statusDetail.AccessibleDescription = exception.Message;
_runtimeRepairTip.SetToolTip(_statusDetail, exception.Message);
if (connected) _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点";
if (!suppressDialogs) MessageBox.Show(exception.Message, "客户端安装需要修复", MessageBoxButtons.OK, MessageBoxIcon.Warning);
else if (firstNotice) _notifyIcon.ShowBalloonTip(7000, "客户端安装需要修复", exception.Message, ToolTipIcon.Warning);
}
private bool PreflightClientRuntime(bool suppressDialogs, bool clearRepair = false)
{
try
{
_xray.ValidateRuntime();
if (clearRepair)
{
_runtimeRepairRequired = false;
_statusDetail.AccessibleDescription = null;
_runtimeRepairTip.SetToolTip(_statusDetail, null);
}
return true;
}
catch (ClientRuntimeException error) { HandleClientRuntimeFailure(error, suppressDialogs); return false; }
}
private async Task DisconnectAsync(bool cancelPending = true)
{
_wantConnected = false;
@@ -788,6 +840,8 @@ internal sealed partial class MainForm : Form
} finally { _healthChecking = false; }
return;
}
// Keep authorization expiry enforcement above this local repair gate.
if (_runtimeRepairRequired) return;
await CheckUplinkAsync();
if (_uplinkChecking || _handover.Pending || _handover.Settling) return;
if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return;
@@ -801,6 +855,7 @@ internal sealed partial class MainForm : Form
var revision = _connectionHealth.Revision;
var testedCore = _xray.CoreId;
var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token);
if (_runtimeRepairRequired) return;
var healthy = health.Healthy;
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
@@ -836,6 +891,7 @@ internal sealed partial class MainForm : Form
}
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
if (decision != ConnectionHealthPolicy.Decision.Switch) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
if (_currentNodeSlug is not null)
{
if (_currentNodeUsesTailnet)
@@ -935,11 +991,11 @@ internal sealed partial class MainForm : Form
private void ShowAiStatus(string message)
{
if (_exiting || IsDisposed || Disposing) return;
if (_runtimeRepairRequired || _exiting || IsDisposed || Disposing) return;
var reportingCore = _xray.CoreId;
PostUi(() =>
{
if (_dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore)
if (!_runtimeRepairRequired && _dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore)
_statusDetail.Text = NodePresentation.LearningDetail(_selectionUiConnected, _currentNodeName, message);
});
}
@@ -1257,6 +1313,7 @@ internal sealed partial class MainForm : Form
_api.Dispose();
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
_runtimeRepairTip.Dispose();
}
protected override void WndProc(ref Message message)
+10 -7
View File
@@ -54,7 +54,7 @@ internal static class NodeTransportConnector
diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", ""));
return selected;
}
catch (Exception e) when (tailnet && e is not LocalNetworkException && !token.IsCancellationRequested)
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();
@@ -88,7 +88,7 @@ internal static class NodeTransportConnector
requireRoute(TailnetTransport.Address(tailnet)!);
token.ThrowIfCancellationRequested();
}
catch (Exception e) when (e is not OperationCanceledException)
catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException)
{
preference.Failed(response.Node.Slug, ticks());
tailnet = null;
@@ -106,7 +106,7 @@ internal static class NodeTransportConnector
throw new IOException("代理内网 IP Ping 不通。");
token.ThrowIfCancellationRequested();
}
catch (Exception e) when (e is not OperationCanceledException)
catch (Exception e) when (e is not OperationCanceledException && e is not ClientRuntimeException)
{
preference.Failed(response.Node.Slug, ticks());
tailnet = null;
@@ -132,6 +132,7 @@ internal static class NodeTransportConnector
return true;
}
catch (LocalNetworkException) { throw; }
catch (ClientRuntimeException) { throw; }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch (Exception)
{
@@ -147,11 +148,13 @@ internal static class NodeTransportConnector
// Automatic selection can test ALL authorized Tailnet nodes first. A
// failed alternate must not launch public ingress before that pass ends.
if (tailnetOnly) throw new TailnetUnavailableException(reason);
if (response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global")
preference.CommitDomainFallback();
Report("selected", "public_ingress");
await start(response.GetRuntimeConfigJson(), token);
var commitDomain = response.ConnectionScope != PrivateAuxiliaryRouting.Scope && response.RouteMode is "smart" or "global";
try { await start(response.GetRuntimeConfigJson(), token); }
catch (ClientRuntimeException) { throw; }
catch { if (commitDomain) preference.CommitDomainFallback(); throw; }
if (commitDomain) preference.CommitDomainFallback();
token.ThrowIfCancellationRequested();
Report("selected", "public_ingress");
return false;
}
}
+2
View File
@@ -17,6 +17,8 @@ internal static class Program
if (args.Any(a => a.StartsWith("--installer-guardian-", StringComparison.OrdinalIgnoreCase))) return InstallerGuardianGate.Invalid;
if (args.Length == 1 && args[0] == "--platform-bootstrap-self-test")
return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--client-runtime-self-test")
return ClientRuntimeSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--tailnet-transport-self-test")
return TailnetTransportSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--public-tailnet-selection-self-test")
+3 -3
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.5 开源源码
# 纵横家 Windows 0.3.6 开源源码
基于已冻结的 0.3.5 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
基于已冻结的 0.3.6 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建
@@ -17,4 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
0.3.5:为本机代理及各服务器显示独立流量趋势,清晰区分上传、下载及累计数值,保持固定紧凑主界面。保留0.3.4连接容错与授权有效期处理;本次只更新界面,不改变调度、节点优先级或网络路由,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
0.3.6:连接前检查本机Xray及必要运行文件;组件缺失时一次性明确提示修复安装,避免逐节点重复失败。延长受限速环境下完整升级包下载的总时间预算。保留0.3.5本机和服务器趋势图、连接容错、调度与路由规则,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
+46
View File
@@ -203,6 +203,52 @@ internal static class TailnetTransportSelfTest
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083;
}), true)!;
checks["known_silicon_exact_mapping"] = Host(silicon) == "100.64.0.3" && TailnetTransport.Port(silicon) == 11083;
ConfigResponse NewYork(Action<JsonObject>? change = null) => Known(r => {
r["node"]!["slug"] = "racknerd-newyork-004"; r["node"]!["name"] = "VPN004";
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.example.invalid";
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084;
change?.Invoke(r);
});
var newYork = NewYork();
var newYorkOriginal = newYork.GetRuntimeConfigJson();
var newYorkPrepared = TailnetTransport.TryPrepare(newYork, true);
checks["known_newyork_exact_mapping"] = newYorkPrepared is not null
&& Host(newYorkPrepared) == "100.64.0.44" && TailnetTransport.Port(newYorkPrepared) == 11084;
checks["known_newyork_requires_mapping_permission"] = TailnetTransport.TryPrepare(newYork) is null;
checks["known_newyork_same_authorized_fallback"] = newYorkPrepared is not null
&& TailnetTransport.SameAuthorizedFallback(newYorkPrepared, newYorkOriginal);
var newYorkRestored = newYorkPrepared is null ? null : JsonNode.Parse(newYorkPrepared)!.AsObject();
if (newYorkRestored is not null)
{
newYorkRestored.Remove(TailnetTransport.Marker);
newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "004.vpn.example.invalid";
newYorkRestored["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11084;
}
checks["known_newyork_preserves_all_credentials_and_rules"] = newYorkRestored is not null
&& JsonNode.DeepEquals(newYorkRestored, JsonNode.Parse(newYorkOriginal))
&& newYork.GetRuntimeConfigJson() == newYorkOriginal;
checks["known_newyork_changed_host_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"] = "other.example.com"), true) is null;
checks["known_newyork_changed_port_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"] = 11083), true) is null;
checks["known_newyork_changed_slug_rejected"] = TailnetTransport.TryPrepare(NewYork(r =>
r["node"]!["slug"] = "unapproved-newyork"), true) is null;
checks["known_newyork_explicit_null_disables_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = null), true) is null;
checks["known_newyork_invalid_metadata_never_uses_mapping"] = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject()), true) is null;
var newYorkExplicit = TailnetTransport.TryPrepare(NewYork(r => r["tailscale_endpoint"] = new JsonObject {
["contract"] = 1, ["node_slug"] = "racknerd-newyork-004", ["address"] = "100.65.1.9", ["port"] = 2345
}), true);
checks["known_newyork_server_metadata_remains_authoritative"] = newYorkExplicit is not null
&& Host(newYorkExplicit) == "100.65.1.9" && TailnetTransport.Port(newYorkExplicit) == 2345;
var newYorkStarts = new List<string>(); var newYorkStops = 0; var newYorkProbes = 0;
var newYorkSelected = await NodeTransportConnector.ConnectAsync(newYork, new(),
(json, _) => { newYorkStarts.Add(json); return Task.CompletedTask; },
() => { newYorkStops++; return Task.CompletedTask; },
_ => { newYorkProbes++; return Task.FromResult(false); }, _ => { }, _ => { }, () => tick, CancellationToken.None,
allowKnownEndpoints: true, endpointProbe: (address, port, _) => Task.FromResult(address == "100.64.0.44" && port == 11084));
checks["known_newyork_failed_proxy_falls_back_only_same_authorized_node"] = !newYorkSelected
&& newYorkStarts.Count == 2 && Host(newYorkStarts[0]) == "100.64.0.44"
&& newYorkStarts[1] == newYorkOriginal && newYorkStops == 1 && newYorkProbes == 1;
var future = TailnetTransport.TryPrepare(Known(r => r["tailscale_endpoint"] = new JsonObject {
["contract"] = 1, ["node_slug"] = "aliyun-tokyo-002", ["address"] = "100.65.1.9", ["port"] = 2345
}), true)!;
+3
View File
@@ -68,6 +68,9 @@ internal static class UpdateSelfTest
};
try
{
report["largest_allowed_package_fits_slow_200kib_link_with_headroom"] = ClientUpdater.DefaultTotalTimeout
>= TimeSpan.FromSeconds(200.0 * 1024 * 1024 / (200 * 1024) + 60);
report["update_total_deadline_remains_bounded"] = ClientUpdater.DefaultTotalTimeout <= TimeSpan.FromMinutes(20);
var bytes = RandomNumberGenerator.GetBytes(300_000); // Test data, not an executable.
var hash = Convert.ToHexString(SHA256.HashData(bytes));
ClientUpdateInfo Info(string digest, bool available = true) => new() {
+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.5</Version>
<AssemblyVersion>0.3.5.0</AssemblyVersion>
<FileVersion>0.3.5.0</FileVersion>
<InformationalVersion>0.3.5</InformationalVersion>
<Version>0.3.6</Version>
<AssemblyVersion>0.3.6.0</AssemblyVersion>
<FileVersion>0.3.6.0</FileVersion>
<InformationalVersion>0.3.6</InformationalVersion>
<Product>纵横家</Product>
<Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description>
+16 -18
View File
@@ -75,10 +75,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
public async Task RebindNetworkAsync(CancellationToken token)
{
ValidateRuntime();
await _lifecycle.WaitAsync(token);
var replacementStarted = false;
try
{
ValidateRuntime();
if (!CanRebindNetwork) throw new InvalidOperationException("没有可恢复的已授权线路。");
replacementStarted = true;
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
token.ThrowIfCancellationRequested();
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
@@ -89,7 +93,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
endpointProbe: TailnetTransport.ProbeEndpointAsync,
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
}
catch { await StopCoreAsync(); throw; }
catch { if (replacementStarted) await StopCoreAsync(); throw; }
finally { _lifecycle.Release(); }
}
@@ -202,6 +206,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
{
// Fail locally before ownership/recovery or stopping a healthy core.
ValidateRuntime();
if (TailnetTransport.Address(configJson) is not null
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。");
@@ -214,8 +220,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
await InitializeAsync(cancellationToken);
await StartupLearningWarmup.RunAsync(async beginLearning => {
await _lifecycle.WaitAsync(cancellationToken);
var replacementStarted = false;
try
{
// Recheck after waiting for the lifecycle; a file may change.
ValidateRuntime();
replacementStarted = true;
await StopCoreAsync();
_baseConfigJson = configJson;
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
@@ -226,7 +236,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
}
catch
{
await StopCoreAsync().ConfigureAwait(false);
if (replacementStarted) await StopCoreAsync().ConfigureAwait(false);
throw;
}
finally { _lifecycle.Release(); }
@@ -276,7 +286,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
private async Task StartCoreAsync(CancellationToken cancellationToken,
Action<CancellationToken>? beginStartupLearning = null)
{
EnsureRuntime();
ValidateRuntime();
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
PrivateAuxiliaryRuntime.ValidateLifetime(_baseConfigJson);
var privateAuxiliary = PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson);
@@ -354,7 +364,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_process.ErrorDataReceived += (_, eventArgs) => AppendXrayLog(eventArgs.Data);
var startedProcess = _process;
_process.Exited += (_, _) => _ = HandleCoreExitAsync(startedProcess);
if (!_process.Start()) throw new InvalidOperationException("Xray 内核无法启动。");
if (!ClientRuntime.Start(_process)) throw new ClientRuntimeException(XrayPath, ClientRuntimeFault.CannotStart);
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
File.WriteAllText(AppPaths.PidFile, _process.Id.ToString());
@@ -557,7 +567,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
StandardErrorEncoding = Encoding.UTF8,
}
};
process.Start();
ClientRuntime.Start(process);
var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken);
var stderr = process.StandardError.ReadToEndAsync(cancellationToken);
await process.WaitForExitAsync(cancellationToken);
@@ -593,19 +603,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
return addresses;
}
private void EnsureRuntime()
{
foreach (var file in new[]
{
XrayPath,
Path.Combine(_xrayDirectory, "geoip.dat"),
Path.Combine(_xrayDirectory, "geosite.dat"),
Path.Combine(_xrayDirectory, "wintun.dll"),
})
{
if (!File.Exists(file)) throw new FileNotFoundException($"客户端组件缺失:{Path.GetFileName(file)}");
}
}
internal void ValidateRuntime() => ClientRuntime.Validate(AppContext.BaseDirectory);
private async Task RecoverStaleStateAsync(CancellationToken cancellationToken)
{
+13
View File
@@ -0,0 +1,13 @@
# 纵横家 Windows 0.3.6
本次维护修复本机运行组件故障被重复显示为多个节点连接失败的问题。
- 建立连接前检查程序目录中的运行组件,区分文件缺失、读取受限和空文件,显示具体位置及完整安装包修复方法。
- 本机组件故障直接进入安装修复提示,保留仍在运行的连接,避免重复重试节点和误记 Tailscale 故障。
- 自动升级的整包下载期限调整为 20 分钟,保留单次读取超时、取消、完整长度及 SHA-256 校验,适应低速网络。
- 补齐 VPN004 的 Tailscale 兼容入口识别,沿用已授权的同节点配置,内网可达时优先使用内网入口。
- 保留 0.3.5 的本机与服务器独立流量趋势图和紧凑累计数值。
完整安装包包含 Xray、Wintun 及路由数据文件。覆盖安装会保留账号、设备标识和用户配置。组件读取受限时应先排查该文件的访问权限,再运行完整安装包修复。
发布验证范围包括同包离线回归、缺件修复的隔离文件事务、运行组件故障的模拟连接及升级下载边界测试。离线和隔离结果不代表真实 TUN 切换、生产覆盖安装或多节点分流已经验收。