Publish Zonghengjia Windows 0.3.20 client source
This commit is contained in:
+56
-55
@@ -1,55 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class AppPaths
|
||||
{
|
||||
internal static readonly string DataDirectory = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"UCVL",
|
||||
"VPNPlus");
|
||||
|
||||
internal static string DeviceIdFile => Path.Combine(DataDirectory, "device-id.txt");
|
||||
internal static string TokenFile => Path.Combine(DataDirectory, "session.bin");
|
||||
internal static string ProxyStateFile => Path.Combine(DataDirectory, "proxy-state.json");
|
||||
internal static string TunStateFile => Path.Combine(DataDirectory, "tun-state.json");
|
||||
internal static string LearnedRoutesFile => Path.Combine(DataDirectory, "learned-routes.json");
|
||||
internal static string ConfigFile => Path.Combine(DataDirectory, "xray-config.json");
|
||||
internal static string PidFile => Path.Combine(DataDirectory, "xray.pid");
|
||||
internal static string LogFile => Path.Combine(DataDirectory, "vpnplus.log");
|
||||
internal static string XrayLogFile => Path.Combine(DataDirectory, "xray.log");
|
||||
internal static string ConnectionSelfTestFile => Path.Combine(DataDirectory, "connection-self-test.json");
|
||||
|
||||
internal static void EnsureDirectory() => Directory.CreateDirectory(DataDirectory);
|
||||
|
||||
internal static string GetOrCreateDeviceId()
|
||||
{
|
||||
EnsureDirectory();
|
||||
if (File.Exists(DeviceIdFile))
|
||||
{
|
||||
var existing = File.ReadAllText(DeviceIdFile, Encoding.UTF8).Trim();
|
||||
if (Guid.TryParse(existing, out _))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
var deviceId = Guid.NewGuid().ToString("D");
|
||||
File.WriteAllText(DeviceIdFile, deviceId, new UTF8Encoding(false));
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
internal static void WriteLog(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureDirectory();
|
||||
File.AppendAllText(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}", Encoding.UTF8);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging must never prevent connecting or restoring the system proxy.
|
||||
}
|
||||
}
|
||||
|
||||
internal static void WriteError(Exception exception) => WriteLog($"ERROR {exception}");
|
||||
}
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class AppPaths
|
||||
{
|
||||
internal static readonly string DataDirectory = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"UCVL",
|
||||
"VPNPlus");
|
||||
|
||||
internal static string DeviceIdFile => Path.Combine(DataDirectory, "device-id.txt");
|
||||
internal static string TokenFile => Path.Combine(DataDirectory, "session.bin");
|
||||
internal static string ProxyStateFile => Path.Combine(DataDirectory, "proxy-state.json");
|
||||
internal static string TunStateFile => Path.Combine(DataDirectory, "tun-state.json");
|
||||
internal static string LearnedRoutesFile => Path.Combine(DataDirectory, "learned-routes.json");
|
||||
internal static string ConfigFile => Path.Combine(DataDirectory, "xray-config.json");
|
||||
internal static string PidFile => Path.Combine(DataDirectory, "xray.pid");
|
||||
internal static string LogFile => Path.Combine(DataDirectory, "vpnplus.log");
|
||||
internal static string XrayLogFile => Path.Combine(DataDirectory, "xray.log");
|
||||
internal static string ConnectionSelfTestFile => Path.Combine(DataDirectory, "connection-self-test.json");
|
||||
|
||||
internal static void EnsureDirectory() => Directory.CreateDirectory(DataDirectory);
|
||||
|
||||
internal static string GetOrCreateDeviceId()
|
||||
{
|
||||
EnsureDirectory();
|
||||
if (File.Exists(DeviceIdFile))
|
||||
{
|
||||
var existing = File.ReadAllText(DeviceIdFile, Encoding.UTF8).Trim();
|
||||
if (Guid.TryParse(existing, out _))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
var deviceId = Guid.NewGuid().ToString("D");
|
||||
File.WriteAllText(DeviceIdFile, deviceId, new UTF8Encoding(false));
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
internal static void WriteLog(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureDirectory();
|
||||
BoundedLog.Append(LogFile, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}",
|
||||
BoundedLog.ApplicationMaxBytes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Logging must never prevent connecting or restoring the system proxy.
|
||||
}
|
||||
}
|
||||
|
||||
internal static void WriteError(Exception exception) => WriteLog($"ERROR {exception}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal readonly record struct TailReadResult(string Text, int BytesRead);
|
||||
|
||||
internal static class BoundedLog
|
||||
{
|
||||
internal const long ApplicationMaxBytes = 4L * 1024 * 1024;
|
||||
internal const long XrayMaxBytes = 4L * 1024 * 1024;
|
||||
internal const int ErrorTailMaxBytes = 64 * 1024;
|
||||
|
||||
private static readonly UTF8Encoding Utf8 = new(false, false);
|
||||
private static readonly ConcurrentDictionary<string, object> Gates = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
internal static void Append(string path, string value, long maxBytes)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
if (maxBytes < 1 || maxBytes > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(maxBytes));
|
||||
|
||||
var content = FitToLimit(value, (int)maxBytes);
|
||||
path = Path.GetFullPath(path);
|
||||
var gate = Gates.GetOrAdd(path, static _ => new object());
|
||||
lock (gate)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrWhiteSpace(directory)) Directory.CreateDirectory(directory);
|
||||
var existingLength = File.Exists(path) ? new FileInfo(path).Length : 0;
|
||||
if (existingLength > 0 && existingLength + content.Length > maxBytes)
|
||||
Rotate(path, maxBytes);
|
||||
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read | FileShare.Delete);
|
||||
stream.Write(content);
|
||||
}
|
||||
}
|
||||
|
||||
internal static TailReadResult ReadTail(string path, int maxLines, int maxBytes)
|
||||
{
|
||||
if (maxLines < 1) throw new ArgumentOutOfRangeException(nameof(maxLines));
|
||||
if (maxBytes < 1) throw new ArgumentOutOfRangeException(nameof(maxBytes));
|
||||
if (!File.Exists(path)) return new("", 0);
|
||||
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read,
|
||||
FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, FileOptions.RandomAccess);
|
||||
var bytesToRead = (int)Math.Min(stream.Length, maxBytes);
|
||||
if (bytesToRead == 0) return new("", 0);
|
||||
var startedMidFile = stream.Length > bytesToRead;
|
||||
stream.Seek(-bytesToRead, SeekOrigin.End);
|
||||
var buffer = new byte[bytesToRead];
|
||||
var total = 0;
|
||||
while (total < buffer.Length)
|
||||
{
|
||||
var read = stream.Read(buffer, total, buffer.Length - total);
|
||||
if (read == 0) break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
var text = Utf8.GetString(buffer, 0, total).Replace("\0", "", StringComparison.Ordinal)
|
||||
.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n');
|
||||
var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
|
||||
if (startedMidFile) lines = lines.Skip(1);
|
||||
return new(string.Join(Environment.NewLine, lines.TakeLast(maxLines)), total);
|
||||
}
|
||||
|
||||
private static byte[] FitToLimit(string value, int maxBytes)
|
||||
{
|
||||
var content = Utf8.GetBytes(value);
|
||||
if (content.Length <= maxBytes) return content;
|
||||
|
||||
var start = content.Length - maxBytes;
|
||||
while (start < content.Length && (content[start] & 0xc0) == 0x80) start++;
|
||||
return content[start..];
|
||||
}
|
||||
|
||||
private static void Rotate(string path, long maxBytes)
|
||||
{
|
||||
var backup = path + ".1";
|
||||
var length = new FileInfo(path).Length;
|
||||
if (length <= maxBytes)
|
||||
{
|
||||
File.Move(path, backup, overwrite: true);
|
||||
return;
|
||||
}
|
||||
|
||||
// A pre-upgrade unbounded log is trimmed only when the next append
|
||||
// naturally triggers rotation; loading, building and upgrading do not touch it.
|
||||
using (var source = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
|
||||
using (var destination = new FileStream(backup, FileMode.Create, FileAccess.Write, FileShare.Read))
|
||||
{
|
||||
source.Seek(-maxBytes, SeekOrigin.End);
|
||||
source.CopyTo(destination);
|
||||
}
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class BoundedLogSelfTest
|
||||
{
|
||||
internal static bool Run()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "ucvl-bounded-log-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
const long limit = 192;
|
||||
var logPath = Path.Combine(directory, "rotation.log");
|
||||
var original = new string('a', 180) + "\n";
|
||||
File.WriteAllText(logPath, original, new UTF8Encoding(false));
|
||||
var originalLength = new FileInfo(logPath).Length;
|
||||
|
||||
// Reading and loading the helper must not delete or truncate an existing log.
|
||||
_ = BoundedLog.ReadTail(logPath, 1, 64);
|
||||
if (!File.Exists(logPath) || new FileInfo(logPath).Length != originalLength
|
||||
|| File.Exists(logPath + ".1")) return false;
|
||||
|
||||
BoundedLog.Append(logPath, "rotation-entry\n", limit);
|
||||
var backupPath = logPath + ".1";
|
||||
if (!File.Exists(backupPath)
|
||||
|| File.ReadAllText(backupPath, Encoding.UTF8) != original
|
||||
|| new FileInfo(logPath).Length > limit) return false;
|
||||
|
||||
for (var i = 0; i < 40; i++)
|
||||
BoundedLog.Append(logPath, $"line-{i:D2}-xxxxxxxx\n", limit);
|
||||
if (new FileInfo(logPath).Length > limit
|
||||
|| !File.Exists(backupPath)
|
||||
|| new FileInfo(backupPath).Length > limit
|
||||
|| File.Exists(logPath + ".2")) return false;
|
||||
|
||||
var legacyPath = Path.Combine(directory, "legacy-unbounded.log");
|
||||
File.WriteAllText(legacyPath, new string('l', 2048), new UTF8Encoding(false));
|
||||
if (new FileInfo(legacyPath).Length != 2048 || File.Exists(legacyPath + ".1")) return false;
|
||||
BoundedLog.Append(legacyPath, "new\n", limit);
|
||||
if (new FileInfo(legacyPath).Length > limit
|
||||
|| new FileInfo(legacyPath + ".1").Length > limit) return false;
|
||||
|
||||
var tailPath = Path.Combine(directory, "damaged-tail.log");
|
||||
var prefix = Encoding.UTF8.GetBytes("PREFIX-MUST-NOT-BE-READ\n" + new string('p', 4096) + "\n");
|
||||
var damagedTail = new List<byte>(prefix);
|
||||
damagedTail.AddRange([0x00, 0xC3, 0x28, (byte)'\n']);
|
||||
damagedTail.AddRange(Encoding.UTF8.GetBytes("tail-one\ntail-two\ntail-three\n"));
|
||||
File.WriteAllBytes(tailPath, damagedTail.ToArray());
|
||||
|
||||
var result = BoundedLog.ReadTail(tailPath, 3, 128);
|
||||
if (result.BytesRead > 128
|
||||
|| result.Text.Contains("PREFIX-MUST-NOT-BE-READ", StringComparison.Ordinal)
|
||||
|| result.Text.Contains('\0')
|
||||
|| !result.Text.Contains("tail-one", StringComparison.Ordinal)
|
||||
|| !result.Text.Contains("tail-two", StringComparison.Ordinal)
|
||||
|| !result.Text.Contains("tail-three", StringComparison.Ordinal)) return false;
|
||||
|
||||
var message = ProxyProbe.BuildFailureLog(new IOException("secret-target.example:443"));
|
||||
return message.Contains(nameof(IOException), StringComparison.Ordinal)
|
||||
&& !message.Contains("secret-target", StringComparison.OrdinalIgnoreCase)
|
||||
&& !message.Contains(":443", StringComparison.Ordinal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(directory, recursive: true); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
-76
@@ -1,76 +1,91 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
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
|
||||
{
|
||||
private const uint SemFailCriticalErrors = 0x0001;
|
||||
private const uint SemNoGpFaultErrorBox = 0x0002;
|
||||
private const uint SemNoOpenFileErrorBox = 0x8000;
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool SetThreadErrorMode(uint newMode, out uint oldMode);
|
||||
|
||||
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)
|
||||
{
|
||||
var changedErrorMode = SetThreadErrorMode(
|
||||
SemFailCriticalErrors | SemNoGpFaultErrorBox | SemNoOpenFileErrorBox, out var previousErrorMode);
|
||||
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);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (changedErrorMode) SetThreadErrorMode(previousErrorMode, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ internal sealed class ConnectionHealthPolicy
|
||||
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
|
||||
internal Decision Observe(long revision, int? testedCore, int? currentCore,
|
||||
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
|
||||
bool activeTailnet = false, bool businessUnavailable = false)
|
||||
bool activeTailnet = false, bool businessUnavailable = false, bool automaticSelection = false)
|
||||
{
|
||||
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
|
||||
return Decision.Ignore;
|
||||
@@ -34,10 +34,18 @@ internal sealed class ConnectionHealthPolicy
|
||||
return Decision.Keep;
|
||||
}
|
||||
if (currentCore is not null && businessUnavailable && proxyHealthy) {
|
||||
Failures = 0; _nextProbe = now + 20_000;
|
||||
_nextProbe = now + 20_000;
|
||||
const Decision advisory = Decision.WebsiteUnavailable;
|
||||
var confirmed = _advisoryCandidate == advisory;
|
||||
_advisoryCandidate = advisory;
|
||||
if (automaticSelection) {
|
||||
// Both the ordinary route and the forced proxy business probe
|
||||
// failed. An automatically selected node gets two advisory
|
||||
// rounds, then must yield instead of remaining degraded forever.
|
||||
Failures = confirmed ? Failures + 1 : 1;
|
||||
if (Failures >= 3) return Decision.Switch;
|
||||
}
|
||||
else Failures = 0;
|
||||
return confirmed ? advisory : Decision.PendingAdvisory;
|
||||
}
|
||||
_advisoryCandidate = null;
|
||||
|
||||
@@ -54,6 +54,9 @@ internal static class ConnectionHealthSelfTest
|
||||
== ConnectionHealthPolicy.Decision.Ignore;
|
||||
ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||
true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true);
|
||||
ConnectionHealthPolicy.Decision AutomaticWebsite(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||
true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true,
|
||||
automaticSelection: true);
|
||||
ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10,
|
||||
true, false, false, false, false, now, activeTailnet: true);
|
||||
|
||||
@@ -79,6 +82,21 @@ internal static class ConnectionHealthSelfTest
|
||||
checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory;
|
||||
checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null,
|
||||
true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch;
|
||||
policy.BeginCore(1_120_000);
|
||||
checks["automatic_business_failure_is_bounded"] =
|
||||
AutomaticWebsite(1_125_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||
&& AutomaticWebsite(1_145_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable
|
||||
&& AutomaticWebsite(1_165_000) == ConnectionHealthPolicy.Decision.Switch;
|
||||
checks["business_success_clears_automatic_failure_streak"] =
|
||||
Observe(true, 1_185_000) == ConnectionHealthPolicy.Decision.Keep
|
||||
&& AutomaticWebsite(1_205_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||
&& policy.Failures == 1;
|
||||
policy.BeginCore(1_220_000);
|
||||
checks["manual_business_failure_warns_without_switching"] =
|
||||
Website(1_225_000) == ConnectionHealthPolicy.Decision.PendingAdvisory
|
||||
&& Enumerable.Range(1, 5).All(index =>
|
||||
Website(1_225_000 + index * 20_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable)
|
||||
&& policy.Failures == 0;
|
||||
revision = policy.Revision;
|
||||
policy.Invalidate();
|
||||
checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// DERP relays change independently of the client release. Read only the
|
||||
// already-installed Tailscale client's current map; never manufacture or cache
|
||||
// relay addresses in the application.
|
||||
internal static class DerpRouteDiscovery
|
||||
{
|
||||
private const int MaxMapCharacters = 256 * 1024;
|
||||
private const int MaxRelayAddresses = 64;
|
||||
|
||||
internal static IReadOnlyList<IPAddress> ParsePublicIpv4Addresses(string json)
|
||||
{
|
||||
if (json.Length > MaxMapCharacters) throw new InvalidDataException("DERP Map 超过安全大小限制。");
|
||||
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 24 });
|
||||
if (!document.RootElement.TryGetProperty("Regions", out var regions)
|
||||
|| regions.ValueKind != JsonValueKind.Object)
|
||||
throw new InvalidDataException("DERP Map 缺少 Regions。");
|
||||
|
||||
var result = new HashSet<IPAddress>();
|
||||
foreach (var region in regions.EnumerateObject())
|
||||
{
|
||||
if (!region.Value.TryGetProperty("Nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array)
|
||||
continue;
|
||||
foreach (var node in nodes.EnumerateArray())
|
||||
{
|
||||
if (!node.TryGetProperty("IPv4", out var value) || value.ValueKind != JsonValueKind.String)
|
||||
continue;
|
||||
var text = value.GetString()?.Trim();
|
||||
if (!IPAddress.TryParse(text, out var address)
|
||||
|| address.AddressFamily != AddressFamily.InterNetwork
|
||||
|| !IsPublicIpv4(address))
|
||||
continue;
|
||||
result.Add(address);
|
||||
if (result.Count > MaxRelayAddresses)
|
||||
throw new InvalidDataException("DERP Map 节点数量超过安全限制。");
|
||||
}
|
||||
}
|
||||
return result.OrderBy(address => address.ToString(), StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
internal static async Task<IReadOnlyList<IPAddress>> DiscoverAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var executable = InstalledExecutable();
|
||||
if (executable is null) return [];
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
Process? process = null;
|
||||
try
|
||||
{
|
||||
process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = executable,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
StandardOutputEncoding = Encoding.UTF8,
|
||||
StandardErrorEncoding = Encoding.UTF8,
|
||||
}
|
||||
};
|
||||
process.StartInfo.ArgumentList.Add("debug");
|
||||
process.StartInfo.ArgumentList.Add("derp-map");
|
||||
if (!process.Start()) return [];
|
||||
var stdout = ReadBoundedAsync(process.StandardOutput, deadline.Token);
|
||||
var stderr = ReadBoundedAsync(process.StandardError, deadline.Token);
|
||||
await process.WaitForExitAsync(deadline.Token).ConfigureAwait(false);
|
||||
var map = await stdout.ConfigureAwait(false);
|
||||
_ = await stderr.ConfigureAwait(false);
|
||||
return process.ExitCode == 0 ? ParsePublicIpv4Addresses(map) : [];
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception error) when (error is OperationCanceledException or IOException
|
||||
or InvalidDataException or JsonException
|
||||
or System.ComponentModel.Win32Exception)
|
||||
{
|
||||
AppPaths.WriteLog($"DERP Map 未能读取,本次不添加未知中继旁路:{error.GetType().Name}");
|
||||
return [];
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (process is not null)
|
||||
{
|
||||
try { if (!process.HasExited) process.Kill(true); } catch { }
|
||||
process.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string? InstalledExecutable()
|
||||
{
|
||||
var roots = new[]
|
||||
{
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
};
|
||||
foreach (var root in roots.Where(root => !string.IsNullOrWhiteSpace(root)))
|
||||
{
|
||||
var candidate = Path.Combine(root, "Tailscale", "tailscale.exe");
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<string> ReadBoundedAsync(StreamReader reader, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = new char[4096];
|
||||
var value = new StringBuilder();
|
||||
while (true)
|
||||
{
|
||||
var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false);
|
||||
if (count == 0) return value.ToString();
|
||||
if (value.Length + count > MaxMapCharacters)
|
||||
throw new InvalidDataException("DERP Map 输出超过安全大小限制。");
|
||||
value.Append(buffer, 0, count);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsPublicIpv4(IPAddress address)
|
||||
{
|
||||
var bytes = address.GetAddressBytes();
|
||||
if (bytes[0] is 0 or 10 or 127 || bytes[0] >= 224) return false;
|
||||
if (bytes[0] == 100 && bytes[1] is >= 64 and <= 127) return false;
|
||||
if (bytes[0] == 169 && bytes[1] == 254) return false;
|
||||
if (bytes[0] == 172 && bytes[1] is >= 16 and <= 31) return false;
|
||||
if (bytes[0] == 192 && bytes[1] == 168) return false;
|
||||
if (bytes[0] == 198 && bytes[1] is 18 or 19) return false;
|
||||
if (bytes[0] == 192 && bytes[1] == 0 && bytes[2] is 0 or 2) return false;
|
||||
if (bytes[0] == 198 && bytes[1] == 51 && bytes[2] == 100) return false;
|
||||
if (bytes[0] == 203 && bytes[1] == 0 && bytes[2] == 113) return false;
|
||||
return !address.Equals(IPAddress.Broadcast);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -857,7 +857,7 @@ internal sealed partial class MainForm : Form
|
||||
var healthy = health.Healthy;
|
||||
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
|
||||
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
|
||||
_xray.UsesTailnet, health.BusinessUnavailable);
|
||||
_xray.UsesTailnet, health.BusinessUnavailable, automaticSelection: !ManualSelection);
|
||||
if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return;
|
||||
if (healthy && _xray.IsRunning) {
|
||||
if (_displayedHealthWarning is not null) {
|
||||
|
||||
@@ -130,6 +130,7 @@ internal static class NodeTransportConnector
|
||||
// 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("connection_phase", "proxy_verified_tailnet");
|
||||
Report("selected", "tailnet_verified");
|
||||
return true;
|
||||
}
|
||||
@@ -161,6 +162,7 @@ internal static class NodeTransportConnector
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (verifyPublicEgress) preference.CommitDomainFallback();
|
||||
if (verifyPublicEgress) Report("connection_phase", "proxy_verified_public");
|
||||
Report("selected", "public_ingress");
|
||||
return false;
|
||||
}
|
||||
|
||||
+184
-180
@@ -1,180 +1,184 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Net.Security;
|
||||
using System.Security.Authentication;
|
||||
using System.Text.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ProxyProbe
|
||||
{
|
||||
private const int SocksPort = 10808;
|
||||
|
||||
internal sealed record PathComparison(bool? DirectTls, bool? ProxyTls)
|
||||
{
|
||||
internal bool ShouldProxy => DirectTls == false && ProxyTls == true;
|
||||
}
|
||||
|
||||
internal static async Task<PathComparison> CompareTlsAsync(LearningObservation observation,
|
||||
int directPort, int proxyPort, CancellationToken token)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return new(null, null);
|
||||
var destination = await ResolvePublicAsync(observation, proxyPort, token);
|
||||
if (destination is null) return new(null, null); // Resolver/node failure is not direct-path failure.
|
||||
var direct = await TlsAtAsync(observation.Target, destination, directPort, 4, token);
|
||||
if (direct) return new(true, null); // Do not send business TLS over the proxy when direct works.
|
||||
var proxy = await TlsAtAsync(observation.Target, destination, proxyPort, 6, token);
|
||||
return new(false, proxy);
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeTlsAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token, int resolverProxyPort = 0)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return null;
|
||||
var destination = await ResolvePublicAsync(observation, resolverProxyPort > 0 ? resolverProxyPort : forcedProxyPort, token);
|
||||
return destination is not null && await TlsAtAsync(observation.Target, destination, forcedProxyPort, 6, token);
|
||||
}
|
||||
|
||||
private static async Task<IPAddress?> ResolvePublicAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
IPAddress? destination;
|
||||
if (observation.TargetType == "ip") destination = IPAddress.Parse(observation.Target);
|
||||
else
|
||||
{
|
||||
// Resolve through the already authorized node, not local poisoned DNS.
|
||||
// Pin the returned public IP into SOCKS CONNECT; TLS still verifies the
|
||||
// original hostname. No arbitrary HTTP URL, redirect or request replay.
|
||||
using var http = new HttpClient(new SocketsHttpHandler { UseProxy = true,
|
||||
Proxy = new WebProxy($"socks5://127.0.0.1:{forcedProxyPort}"), AllowAutoRedirect = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(4) }) { MaxResponseContentBufferSize = 32768 };
|
||||
var body = await http.GetStringAsync("https://8.8.8.8/resolve?type=A&name=" + Uri.EscapeDataString(observation.Target), timeout.Token);
|
||||
using var dns = JsonDocument.Parse(body);
|
||||
if (!dns.RootElement.TryGetProperty("Answer", out var answers)) return null;
|
||||
var ips = answers.EnumerateArray().Where(a => a.TryGetProperty("type", out var type) && type.GetInt32() == 1)
|
||||
.Select(a => IPAddress.TryParse(a.GetProperty("data").GetString(), out var ip) ? ip : null).ToArray();
|
||||
if (ips.Length == 0 || ips.Any(ip => ip is null || !LearningPolicy.PublicIp(ip))) return null;
|
||||
destination = ips[0];
|
||||
}
|
||||
return destination is not null && LearningPolicy.PublicIp(destination) ? destination : null;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return null; }
|
||||
}
|
||||
|
||||
internal static async Task<bool> TlsAtAsync(string target, IPAddress destination, int socksPort, int seconds, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, socksPort, timeout.Token);
|
||||
var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 5, 1, 0 }, timeout.Token);
|
||||
var greeting = new byte[2]; await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 5 || greeting[1] != 0) return false;
|
||||
await stream.WriteAsync(BuildConnectRequest("ip", destination.ToString(), 443), timeout.Token);
|
||||
var header = new byte[4]; await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 5 || header[1] != 0) return false;
|
||||
var length = header[3] switch { 1 => 4, 4 => 16, 3 => await ReadDomainLengthAsync(stream, timeout.Token), _ => 0 };
|
||||
if (length < 1) return false;
|
||||
await stream.ReadExactlyAsync(new byte[length + 2], timeout.Token);
|
||||
using var tls = new SslStream(stream, false); // Default platform certificate validation, no bypass.
|
||||
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = target }, timeout.Token);
|
||||
return tls.IsAuthenticated && tls.IsEncrypted;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return false; }
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeAsync(
|
||||
LearningObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(observation.Network, "tcp", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, SocksPort, timeout.Token);
|
||||
await using var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 0x05, 0x01, 0x00 }, timeout.Token);
|
||||
var greeting = new byte[2];
|
||||
await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 0x05 || greeting[1] != 0x00) return false;
|
||||
|
||||
var request = BuildConnectRequest(observation.TargetType, observation.Target, observation.Port);
|
||||
await stream.WriteAsync(request, timeout.Token);
|
||||
var header = new byte[4];
|
||||
await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 0x05 || header[1] != 0x00) return false;
|
||||
var addressLength = header[3] switch
|
||||
{
|
||||
0x01 => 4,
|
||||
0x04 => 16,
|
||||
0x03 => await ReadDomainLengthAsync(stream, timeout.Token),
|
||||
_ => 0,
|
||||
};
|
||||
if (addressLength <= 0) return false;
|
||||
var remainder = new byte[addressLength + 2];
|
||||
await stream.ReadExactlyAsync(remainder, timeout.Token);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
||||
{
|
||||
AppPaths.WriteLog($"vpn-ai 代理复测失败:{observation.Target}:{observation.Port} {exception.GetBaseException().Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
var domain = BuildConnectRequest("domain", "example.com", 443);
|
||||
var ipv4 = BuildConnectRequest("ip", "203.0.113.10", 8443);
|
||||
var ipv6 = BuildConnectRequest("ip", "2001:db8::10", 443);
|
||||
return domain[3] == 0x03
|
||||
&& domain[4] == "example.com".Length
|
||||
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
||||
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
||||
&& ipv6[3] == 0x04 && ipv6.Length == 22;
|
||||
}
|
||||
|
||||
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
||||
{
|
||||
if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
var request = new List<byte> { 0x05, 0x01, 0x00 };
|
||||
if (string.Equals(targetType, "ip", StringComparison.OrdinalIgnoreCase)
|
||||
&& IPAddress.TryParse(target.Trim('[', ']'), out var address))
|
||||
{
|
||||
request.Add(address.AddressFamily == AddressFamily.InterNetwork ? (byte)0x01 : (byte)0x04);
|
||||
request.AddRange(address.GetAddressBytes());
|
||||
}
|
||||
else
|
||||
{
|
||||
var ascii = new IdnMapping().GetAscii(target.Trim().TrimEnd('.'));
|
||||
var bytes = Encoding.ASCII.GetBytes(ascii);
|
||||
if (bytes.Length is < 1 or > 255) throw new ArgumentException("域名长度无效", nameof(target));
|
||||
request.Add(0x03);
|
||||
request.Add((byte)bytes.Length);
|
||||
request.AddRange(bytes);
|
||||
}
|
||||
request.Add((byte)(port >> 8));
|
||||
request.Add((byte)(port & 0xff));
|
||||
return request.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<int> ReadDomainLengthAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var length = new byte[1];
|
||||
await stream.ReadExactlyAsync(length, cancellationToken);
|
||||
return length[0];
|
||||
}
|
||||
}
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Net.Security;
|
||||
using System.Security.Authentication;
|
||||
using System.Text.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class ProxyProbe
|
||||
{
|
||||
private const int SocksPort = 10808;
|
||||
|
||||
internal sealed record PathComparison(bool? DirectTls, bool? ProxyTls)
|
||||
{
|
||||
internal bool ShouldProxy => DirectTls == false && ProxyTls == true;
|
||||
}
|
||||
|
||||
internal static async Task<PathComparison> CompareTlsAsync(LearningObservation observation,
|
||||
int directPort, int proxyPort, CancellationToken token)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return new(null, null);
|
||||
var destination = await ResolvePublicAsync(observation, proxyPort, token);
|
||||
if (destination is null) return new(null, null); // Resolver/node failure is not direct-path failure.
|
||||
var direct = await TlsAtAsync(observation.Target, destination, directPort, 4, token);
|
||||
if (direct) return new(true, null); // Do not send business TLS over the proxy when direct works.
|
||||
var proxy = await TlsAtAsync(observation.Target, destination, proxyPort, 6, token);
|
||||
return new(false, proxy);
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeTlsAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token, int resolverProxyPort = 0)
|
||||
{
|
||||
if (observation.Port != 443 || observation.Network != "tcp" || !LearningPolicy.Allowed(observation.TargetType, observation.Target)) return null;
|
||||
var destination = await ResolvePublicAsync(observation, resolverProxyPort > 0 ? resolverProxyPort : forcedProxyPort, token);
|
||||
return destination is not null && await TlsAtAsync(observation.Target, destination, forcedProxyPort, 6, token);
|
||||
}
|
||||
|
||||
private static async Task<IPAddress?> ResolvePublicAsync(LearningObservation observation, int forcedProxyPort, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
IPAddress? destination;
|
||||
if (observation.TargetType == "ip") destination = IPAddress.Parse(observation.Target);
|
||||
else
|
||||
{
|
||||
// Resolve through the already authorized node, not local poisoned DNS.
|
||||
// Pin the returned public IP into SOCKS CONNECT; TLS still verifies the
|
||||
// original hostname. No arbitrary HTTP URL, redirect or request replay.
|
||||
using var http = new HttpClient(new SocketsHttpHandler { UseProxy = true,
|
||||
Proxy = new WebProxy($"socks5://127.0.0.1:{forcedProxyPort}"), AllowAutoRedirect = false,
|
||||
ConnectTimeout = TimeSpan.FromSeconds(4) }) { MaxResponseContentBufferSize = 32768 };
|
||||
var body = await http.GetStringAsync("https://8.8.8.8/resolve?type=A&name=" + Uri.EscapeDataString(observation.Target), timeout.Token);
|
||||
using var dns = JsonDocument.Parse(body);
|
||||
if (!dns.RootElement.TryGetProperty("Answer", out var answers)) return null;
|
||||
var ips = answers.EnumerateArray().Where(a => a.TryGetProperty("type", out var type) && type.GetInt32() == 1)
|
||||
.Select(a => IPAddress.TryParse(a.GetProperty("data").GetString(), out var ip) ? ip : null).ToArray();
|
||||
if (ips.Length == 0 || ips.Any(ip => ip is null || !LearningPolicy.PublicIp(ip))) return null;
|
||||
destination = ips[0];
|
||||
}
|
||||
return destination is not null && LearningPolicy.PublicIp(destination) ? destination : null;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return null; }
|
||||
}
|
||||
|
||||
internal static async Task<bool> TlsAtAsync(string target, IPAddress destination, int socksPort, int seconds, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(seconds));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, socksPort, timeout.Token);
|
||||
var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 5, 1, 0 }, timeout.Token);
|
||||
var greeting = new byte[2]; await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 5 || greeting[1] != 0) return false;
|
||||
await stream.WriteAsync(BuildConnectRequest("ip", destination.ToString(), 443), timeout.Token);
|
||||
var header = new byte[4]; await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 5 || header[1] != 0) return false;
|
||||
var length = header[3] switch { 1 => 4, 4 => 16, 3 => await ReadDomainLengthAsync(stream, timeout.Token), _ => 0 };
|
||||
if (length < 1) return false;
|
||||
await stream.ReadExactlyAsync(new byte[length + 2], timeout.Token);
|
||||
using var tls = new SslStream(stream, false); // Default platform certificate validation, no bypass.
|
||||
await tls.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { TargetHost = target }, timeout.Token);
|
||||
return tls.IsAuthenticated && tls.IsEncrypted;
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||
catch (Exception error) when (error is IOException or SocketException or HttpRequestException or AuthenticationException
|
||||
or OperationCanceledException or JsonException or InvalidOperationException or FormatException) { return false; }
|
||||
}
|
||||
|
||||
internal static async Task<bool?> ProbeAsync(
|
||||
LearningObservation observation,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.Equals(observation.Network, "tcp", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient(AddressFamily.InterNetwork);
|
||||
await client.ConnectAsync(IPAddress.Loopback, SocksPort, timeout.Token);
|
||||
await using var stream = client.GetStream();
|
||||
await stream.WriteAsync(new byte[] { 0x05, 0x01, 0x00 }, timeout.Token);
|
||||
var greeting = new byte[2];
|
||||
await stream.ReadExactlyAsync(greeting, timeout.Token);
|
||||
if (greeting[0] != 0x05 || greeting[1] != 0x00) return false;
|
||||
|
||||
var request = BuildConnectRequest(observation.TargetType, observation.Target, observation.Port);
|
||||
await stream.WriteAsync(request, timeout.Token);
|
||||
var header = new byte[4];
|
||||
await stream.ReadExactlyAsync(header, timeout.Token);
|
||||
if (header[0] != 0x05 || header[1] != 0x00) return false;
|
||||
var addressLength = header[3] switch
|
||||
{
|
||||
0x01 => 4,
|
||||
0x04 => 16,
|
||||
0x03 => await ReadDomainLengthAsync(stream, timeout.Token),
|
||||
_ => 0,
|
||||
};
|
||||
if (addressLength <= 0) return false;
|
||||
var remainder = new byte[addressLength + 2];
|
||||
await stream.ReadExactlyAsync(remainder, timeout.Token);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ArgumentException)
|
||||
{
|
||||
AppPaths.WriteLog(BuildFailureLog(exception));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string BuildFailureLog(Exception exception) =>
|
||||
$"vpn-ai 代理复测失败;error={exception.GetBaseException().GetType().Name}";
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
var domain = BuildConnectRequest("domain", "example.com", 443);
|
||||
var ipv4 = BuildConnectRequest("ip", "203.0.113.10", 8443);
|
||||
var ipv6 = BuildConnectRequest("ip", "2001:db8::10", 443);
|
||||
return domain[3] == 0x03
|
||||
&& domain[4] == "example.com".Length
|
||||
&& domain[^2] == 0x01 && domain[^1] == 0xbb
|
||||
&& ipv4[3] == 0x01 && ipv4.Length == 10
|
||||
&& ipv6[3] == 0x04 && ipv6.Length == 22
|
||||
&& BoundedLogSelfTest.Run();
|
||||
}
|
||||
|
||||
private static byte[] BuildConnectRequest(string targetType, string target, int port)
|
||||
{
|
||||
if (port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(port));
|
||||
var request = new List<byte> { 0x05, 0x01, 0x00 };
|
||||
if (string.Equals(targetType, "ip", StringComparison.OrdinalIgnoreCase)
|
||||
&& IPAddress.TryParse(target.Trim('[', ']'), out var address))
|
||||
{
|
||||
request.Add(address.AddressFamily == AddressFamily.InterNetwork ? (byte)0x01 : (byte)0x04);
|
||||
request.AddRange(address.GetAddressBytes());
|
||||
}
|
||||
else
|
||||
{
|
||||
var ascii = new IdnMapping().GetAscii(target.Trim().TrimEnd('.'));
|
||||
var bytes = Encoding.ASCII.GetBytes(ascii);
|
||||
if (bytes.Length is < 1 or > 255) throw new ArgumentException("域名长度无效", nameof(target));
|
||||
request.Add(0x03);
|
||||
request.Add((byte)bytes.Length);
|
||||
request.AddRange(bytes);
|
||||
}
|
||||
request.Add((byte)(port >> 8));
|
||||
request.Add((byte)(port & 0xff));
|
||||
return request.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<int> ReadDomainLengthAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var length = new byte[1];
|
||||
await stream.ReadExactlyAsync(length, cancellationToken);
|
||||
return length[0];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# 优创⁺纵横家 Windows 客户端
|
||||
|
||||
## Windows 0.3.20
|
||||
|
||||
连接准备完成后立即验证真实代理出口,后台学习不再阻塞首次连接。自动调度线路连续出现业务级不可用时,会先从同节点 Tailscale 入口回退到青岛公网入口;同节点仍不可用时再冷却并选择其他可用节点。手动选定节点不会被自动切换。
|
||||
|
||||
Tailscale 中继旁路不再写死已退役的东京、硅谷和纽约公网地址,而是从本机 Tailscale 的当前 DERP Map 限时读取、校验并按当前物理网卡建立临时路由。日志改为有界轮换,错误尾部读取限制为 64 KiB,避免长期运行后日志无限增长拖慢启动和故障诊断。
|
||||
|
||||
损坏或不可执行的本地 `xray.exe` 现在会作为本机组件故障返回,不再触发 Windows 系统级错误对话框而卡住升级或关机。后台源码的默认公开域名、CSRF 来源和青岛入口统一为 `vpn.ucvl.cn` 与 `47.104.134.190`,环境变量覆盖仍保留。
|
||||
|
||||
## Windows 0.3.19
|
||||
|
||||
修复公司路由已经提供内网路径时,客户端仍跳过已授权代理入口的问题。客户端验证当前网卡能否访问节点代理端口,并将代理绑定到验证通过的网卡。持续检查使用当前连接的实际网卡。
|
||||
|
||||
@@ -1,80 +1,109 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only synthetic TEMP data; calls the actual production replacement method.
|
||||
internal static class ReplacementContinuitySelfTest
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFileAttributesW(string path);
|
||||
|
||||
internal static void Run(string root, Dictionary<string, bool> checks)
|
||||
{
|
||||
var dir = Path.Combine(root, "concurrent-replacement");
|
||||
Directory.CreateDirectory(dir);
|
||||
var first = Path.Combine(dir, "first.bin");
|
||||
var second = Path.Combine(dir, "second.bin");
|
||||
var target = Path.Combine(dir, "main.bin");
|
||||
File.WriteAllBytes(first, Enumerable.Repeat((byte)0x35, 4096).ToArray());
|
||||
File.WriteAllBytes(second, Enumerable.Repeat((byte)0x71, 4096).ToArray());
|
||||
File.Copy(first, target);
|
||||
var acl = new FileInfo(target).GetAccessControl();
|
||||
acl.SetAccessRuleProtection(true, true);
|
||||
new FileInfo(target).SetAccessControl(acl);
|
||||
const AccessControlSections sections = AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group;
|
||||
var oldSecurity = new FileInfo(target).GetAccessControl(sections).GetSecurityDescriptorSddlForm(sections);
|
||||
var errors = new Dictionary<string, int>();
|
||||
var observations = 0L;
|
||||
var completed = 0;
|
||||
var stop = 0;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var observer = new Thread(() => {
|
||||
ready.Set();
|
||||
while (Volatile.Read(ref stop) == 0)
|
||||
{
|
||||
if (GetFileAttributesW(target) == uint.MaxValue)
|
||||
{
|
||||
var error = Marshal.GetLastWin32Error().ToString();
|
||||
errors[error] = errors.GetValueOrDefault(error) + 1;
|
||||
}
|
||||
observations++;
|
||||
}
|
||||
});
|
||||
observer.Start(); ready.Wait();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var source = (i % 2 == 0) ? second : first;
|
||||
InstallationTransaction.Replace(source, target);
|
||||
if (!File.ReadAllBytes(source).SequenceEqual(File.ReadAllBytes(target)))
|
||||
throw new IOException("Replacement bytes do not match");
|
||||
completed++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref stop, 1); observer.Join();
|
||||
File.WriteAllText(Path.Combine(root, "replacement-observations.json"), JsonSerializer.Serialize(
|
||||
new { Completed = completed, Observations = observations, Win32Errors = errors }));
|
||||
}
|
||||
void Check(string key, bool ok) { checks[key] = ok; if (!ok) throw new IOException(key); }
|
||||
Check("concurrent_500_replacements_keep_public_path", completed == 500 && observations > 0 && errors.Count == 0);
|
||||
Check("replacement_keeps_owner_group_and_protected_dacl", new FileInfo(target).GetAccessControl(sections)
|
||||
.GetSecurityDescriptorSddlForm(sections) == oldSecurity);
|
||||
var before = InstallationTransaction.Digest(target);
|
||||
var refused = false;
|
||||
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
try { InstallationTransaction.Replace(second, target); }
|
||||
catch (IOException) { refused = true; }
|
||||
}
|
||||
Check("locked_replacement_preserves_exact_original", refused && InstallationTransaction.Digest(target) == before);
|
||||
Check("replacement_removes_only_own_staging_files", Directory.GetFiles(dir, "*.update-*.tmp").Length == 0);
|
||||
var fresh = Path.Combine(dir, "new.bin");
|
||||
InstallationTransaction.Replace(second, fresh);
|
||||
Check("replacement_new_file_matches_source", InstallationTransaction.Digest(second) == InstallationTransaction.Digest(fresh));
|
||||
}
|
||||
}
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Only synthetic TEMP data; calls the actual production replacement method.
|
||||
internal static class ReplacementContinuitySelfTest
|
||||
{
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern uint GetFileAttributesW(string path);
|
||||
|
||||
private sealed record SecuritySnapshot(string Owner, string Group, bool Protected, string[] Rules);
|
||||
|
||||
private static SecuritySnapshot Snapshot(string path)
|
||||
{
|
||||
var security = new FileInfo(path).GetAccessControl(
|
||||
AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
|
||||
var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier))
|
||||
.OfType<FileSystemAccessRule>()
|
||||
.Select(rule => string.Join('|',
|
||||
rule.IdentityReference.Value,
|
||||
(int)rule.AccessControlType,
|
||||
(int)rule.FileSystemRights,
|
||||
(int)rule.InheritanceFlags,
|
||||
(int)rule.PropagationFlags,
|
||||
rule.IsInherited))
|
||||
.OrderBy(value => value, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
return new(
|
||||
security.GetOwner(typeof(SecurityIdentifier))!.Value,
|
||||
security.GetGroup(typeof(SecurityIdentifier))!.Value,
|
||||
security.AreAccessRulesProtected,
|
||||
rules);
|
||||
}
|
||||
|
||||
private static bool SameSecurity(SecuritySnapshot expected, SecuritySnapshot actual) =>
|
||||
expected.Owner == actual.Owner
|
||||
&& expected.Group == actual.Group
|
||||
&& expected.Protected == actual.Protected
|
||||
&& expected.Rules.SequenceEqual(actual.Rules, StringComparer.Ordinal);
|
||||
|
||||
internal static void Run(string root, Dictionary<string, bool> checks)
|
||||
{
|
||||
var dir = Path.Combine(root, "concurrent-replacement");
|
||||
Directory.CreateDirectory(dir);
|
||||
var first = Path.Combine(dir, "first.bin");
|
||||
var second = Path.Combine(dir, "second.bin");
|
||||
var target = Path.Combine(dir, "main.bin");
|
||||
File.WriteAllBytes(first, Enumerable.Repeat((byte)0x35, 4096).ToArray());
|
||||
File.WriteAllBytes(second, Enumerable.Repeat((byte)0x71, 4096).ToArray());
|
||||
File.Copy(first, target);
|
||||
var acl = new FileInfo(target).GetAccessControl();
|
||||
acl.SetAccessRuleProtection(true, true);
|
||||
new FileInfo(target).SetAccessControl(acl);
|
||||
var oldSecurity = Snapshot(target);
|
||||
var errors = new Dictionary<string, int>();
|
||||
var observations = 0L;
|
||||
var completed = 0;
|
||||
var stop = 0;
|
||||
using var ready = new ManualResetEventSlim();
|
||||
var observer = new Thread(() => {
|
||||
ready.Set();
|
||||
while (Volatile.Read(ref stop) == 0)
|
||||
{
|
||||
if (GetFileAttributesW(target) == uint.MaxValue)
|
||||
{
|
||||
var error = Marshal.GetLastWin32Error().ToString();
|
||||
errors[error] = errors.GetValueOrDefault(error) + 1;
|
||||
}
|
||||
observations++;
|
||||
}
|
||||
});
|
||||
observer.Start(); ready.Wait();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < 500; i++)
|
||||
{
|
||||
var source = (i % 2 == 0) ? second : first;
|
||||
InstallationTransaction.Replace(source, target);
|
||||
if (!File.ReadAllBytes(source).SequenceEqual(File.ReadAllBytes(target)))
|
||||
throw new IOException("Replacement bytes do not match");
|
||||
completed++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref stop, 1); observer.Join();
|
||||
File.WriteAllText(Path.Combine(root, "replacement-observations.json"), JsonSerializer.Serialize(
|
||||
new { Completed = completed, Observations = observations, Win32Errors = errors }));
|
||||
}
|
||||
void Check(string key, bool ok) { checks[key] = ok; if (!ok) throw new IOException(key); }
|
||||
Check("concurrent_500_replacements_keep_public_path", completed == 500 && observations > 0 && errors.Count == 0);
|
||||
Check("replacement_keeps_owner_group_and_protected_dacl", SameSecurity(oldSecurity, Snapshot(target)));
|
||||
var before = InstallationTransaction.Digest(target);
|
||||
var refused = false;
|
||||
using (var held = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
try { InstallationTransaction.Replace(second, target); }
|
||||
catch (IOException) { refused = true; }
|
||||
}
|
||||
Check("locked_replacement_preserves_exact_original", refused && InstallationTransaction.Digest(target) == before);
|
||||
Check("replacement_removes_only_own_staging_files", Directory.GetFiles(dir, "*.update-*.tmp").Length == 0);
|
||||
var fresh = Path.Combine(dir, "new.bin");
|
||||
InstallationTransaction.Replace(second, fresh);
|
||||
Check("replacement_new_file_matches_source", InstallationTransaction.Digest(second) == InstallationTransaction.Digest(fresh));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,9 +44,23 @@ 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);
|
||||
const string currentAndFutureDerpMap = """
|
||||
{"Regions":{"902":{"RegionID":902,"RegionCode":"qingdao","Nodes":[
|
||||
{"Name":"qingdao-1","RegionID":902,"HostName":"ucvl.cn","IPv4":"47.104.134.190"},
|
||||
{"Name":"future-relay","RegionID":902,"HostName":"relay.example","IPv4":"1.1.1.1"}
|
||||
]}}}
|
||||
""";
|
||||
var discoveredDerpAddresses = DerpRouteDiscovery.ParsePublicIpv4Addresses(currentAndFutureDerpMap);
|
||||
var unsafeDerpAddresses = DerpRouteDiscovery.ParsePublicIpv4Addresses("""
|
||||
{"Regions":{"1":{"Nodes":[
|
||||
{"IPv4":"100.67.30.7"},{"IPv4":"192.168.8.1"},{"IPv4":"127.0.0.1"},
|
||||
{"IPv4":"203.0.113.10"},{"IPv4":"47.104.134.190"}
|
||||
]}}}
|
||||
""");
|
||||
string[] retiredDerpAddresses = ["8.216.53.107", "47.254.94.29", "192.236.188.22"];
|
||||
var retiredDerpRoutes = retiredDerpAddresses.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, discoveredDerpAddresses);
|
||||
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"] =
|
||||
@@ -56,26 +70,31 @@ internal static class RouteLeaseSelfTest
|
||||
report["tailscale_and_private_proxy_routes_are_not_replaced"] =
|
||||
protectedRoutes.All(r => r.Destination != tailnet.Destination)
|
||||
&& privateRoutes.All(r => r.Destination != "172.16.0.111");
|
||||
report["tailscale_derp_uses_physical_host_routes_before_tun_defaults"] =
|
||||
derpRoutes.All(derp => protectedRoutes.SkipLast(2).Count(derp.SamePath) == 1)
|
||||
report["tailscale_derp_uses_current_map_before_tun_defaults"] =
|
||||
discoveredDerpAddresses.All(address => protectedRoutes.SkipLast(2).Any(route => route.Destination == address.ToString()))
|
||||
&& protectedRoutes.TakeLast(2).SequenceEqual(split);
|
||||
report["retired_derp_routes_are_never_reintroduced"] =
|
||||
retiredDerpRoutes.All(derp => !protectedRoutes.Any(derp.SamePath));
|
||||
report["derp_map_accepts_only_public_non_test_ipv4"] =
|
||||
unsafeDerpAddresses.Select(address => address.ToString()).SequenceEqual(["47.104.134.190"]);
|
||||
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] };
|
||||
discoveredDerpAddresses.All(address => !privateRoutes.Any(route => route.Destination == address.ToString()
|
||||
&& route.Destination != management.Destination));
|
||||
var preexisting = new[] { tailnet, management };
|
||||
table.Routes.AddRange(preexisting);
|
||||
await lease.ApplyAsync(protectedRoutes, CancellationToken.None);
|
||||
report["existing_derp_route_is_reused"] = table.Routes.Count(derpRoutes[0].SamePath) == 1;
|
||||
report["existing_management_derp_route_is_reused"] = table.Routes.Count(management.SamePath) == 1;
|
||||
await lease.RestoreAsync(CancellationToken.None);
|
||||
report["existing_management_tailnet_and_derp_paths_survive_cleanup"] =
|
||||
table.Routes.SequenceEqual(preexisting) && !File.Exists(path);
|
||||
table.Routes.Remove(derpRoutes[0]);
|
||||
var wifi = new TunRouting.PhysicalNetwork("Fixture Wi-Fi", 11, IPAddress.Parse("172.20.1.30"),
|
||||
24, IPAddress.Parse("172.20.1.1"), [IPAddress.Parse("172.20.1.1")]);
|
||||
var rebound = TunRouting.CreateOwnedRoutes(wifi, [IPAddress.Parse(tailnet.Destination)], 21, preserveProxyRoute: true);
|
||||
var rebound = TunRouting.CreateOwnedRoutes(wifi, [IPAddress.Parse(tailnet.Destination)], 21,
|
||||
preserveProxyRoute: true, discoveredDerpAddresses);
|
||||
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));
|
||||
discoveredDerpAddresses.All(address => table.Routes.Any(route => route.Destination == address.ToString()
|
||||
&& route.InterfaceIndex == 11 && route.NextHop == "172.20.1.1"));
|
||||
await lease.RestoreAsync(CancellationToken.None);
|
||||
report["derp_rebind_cleanup_preserves_original_routes"] = table.Routes.SequenceEqual([tailnet, management]) && !File.Exists(path);
|
||||
table.Routes.Clear();
|
||||
|
||||
@@ -1,38 +1,67 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class StartupLearningWarmup
|
||||
{
|
||||
// The readiness callback starts only transport proof. The setup owner keeps
|
||||
// its lifecycle lock until DNS/network setup succeeds; rule commits wait on
|
||||
// that existing lock. Setup time never spends the post-setup learning budget.
|
||||
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
||||
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
using var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
||||
CancellationTokenSource? learning = null;
|
||||
Task? work = null;
|
||||
try
|
||||
{
|
||||
await setup(epoch => {
|
||||
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
||||
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
||||
learning.Token.ThrowIfCancellationRequested();
|
||||
work = learn(learning.Token);
|
||||
});
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (work is null) return;
|
||||
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
await work;
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
finally
|
||||
{
|
||||
// A failed setup must leave no outstanding proof/commit task. Drain
|
||||
// cancellation without replacing the original setup/learning error.
|
||||
learning?.Cancel();
|
||||
if (work is not null) try { await work; } catch { }
|
||||
learning?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class StartupLearningWarmup
|
||||
{
|
||||
// The readiness callback starts only transport learning. The setup owner
|
||||
// keeps its lifecycle lock until DNS/network setup succeeds; rule commits
|
||||
// wait on that existing lock. Once setup is ready, learning continues in a
|
||||
// bounded observed task and no longer delays the mandatory proxy proof.
|
||||
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
|
||||
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null,
|
||||
Action<Exception?>? onBackgroundCompleted = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
|
||||
CancellationTokenSource? learning = null;
|
||||
Task? work = null;
|
||||
try
|
||||
{
|
||||
await setup(epoch => {
|
||||
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
|
||||
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
|
||||
learning.Token.ThrowIfCancellationRequested();
|
||||
work = learn(learning.Token)
|
||||
?? throw new InvalidOperationException("Startup learning did not return a task.");
|
||||
});
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (work is null)
|
||||
{
|
||||
learning?.Dispose();
|
||||
budget.Dispose();
|
||||
return;
|
||||
}
|
||||
learning!.Token.ThrowIfCancellationRequested();
|
||||
budget.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
_ = ObserveBackgroundAsync(work, learning, budget, onBackgroundCompleted);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A failed setup must leave no outstanding proof/commit task. Drain
|
||||
// cancellation without replacing the original setup/learning error.
|
||||
learning?.Cancel();
|
||||
if (work is not null) try { await work; } catch { }
|
||||
learning?.Dispose();
|
||||
budget.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ObserveBackgroundAsync(Task work, CancellationTokenSource learning,
|
||||
CancellationTokenSource budget, Action<Exception?>? onCompleted)
|
||||
{
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
await work.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (learning.IsCancellationRequested) { }
|
||||
catch (Exception error) { failure = error; }
|
||||
finally
|
||||
{
|
||||
try { learning.Cancel(); } catch { }
|
||||
learning.Dispose();
|
||||
budget.Dispose();
|
||||
try { onCompleted?.Invoke(failure); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,6 @@ internal static class TunRouting
|
||||
{
|
||||
internal const string AdapterName = "UCVL VPNPlus";
|
||||
private static readonly string OwnedAdapterInstanceId = BuildOwnedAdapterInstanceId();
|
||||
private static readonly IPAddress[] CompanyDerpAddresses =
|
||||
[IPAddress.Parse("8.216.53.107"), IPAddress.Parse("47.254.94.29"), IPAddress.Parse("192.236.188.22")];
|
||||
|
||||
internal sealed record PhysicalNetwork(
|
||||
string InterfaceName,
|
||||
int InterfaceIndex,
|
||||
@@ -156,8 +153,11 @@ internal static class TunRouting
|
||||
if (preserveTailnetAddress is not null)
|
||||
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
|
||||
}
|
||||
var derpAddresses = preserveTailnetAddress is null
|
||||
? Array.Empty<IPAddress>()
|
||||
: await DerpRouteDiscovery.DiscoverAsync(cancellationToken).ConfigureAwait(false);
|
||||
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
|
||||
preservePrivateNodeRoute || preserveTailnetAddress is not null);
|
||||
preservePrivateNodeRoute || preserveTailnetAddress is not null, derpAddresses);
|
||||
// The journal records additions before applying them and skips exact
|
||||
// pre-existing routes. The user's LAN and Tailnet routes stay in place.
|
||||
await new NetworkRouteLease(AppPaths.TunStateFile, new WindowsRouteTable()).ApplyAsync(routes, cancellationToken);
|
||||
@@ -167,14 +167,15 @@ internal static class TunRouting
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<Ipv4Route> CreateOwnedRoutes(PhysicalNetwork physicalNetwork,
|
||||
IReadOnlyCollection<IPAddress> proxyIpv4Addresses, int tunIndex, bool preserveProxyRoute)
|
||||
IReadOnlyCollection<IPAddress> proxyIpv4Addresses, int tunIndex, bool preserveProxyRoute,
|
||||
IReadOnlyCollection<IPAddress>? derpAddresses = null)
|
||||
{
|
||||
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);
|
||||
bypassAddresses = bypassAddresses.Concat(derpAddresses ?? []);
|
||||
var routes = bypassAddresses.Distinct().Select(address =>
|
||||
{
|
||||
var nextHop = IsOnLink(address, physicalNetwork.Ipv4Address, physicalNetwork.Ipv4PrefixLength)
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.3.19</Version>
|
||||
<AssemblyVersion>0.3.19.0</AssemblyVersion>
|
||||
<FileVersion>0.3.19.0</FileVersion>
|
||||
<InformationalVersion>0.3.19</InformationalVersion>
|
||||
<Version>0.3.20</Version>
|
||||
<AssemblyVersion>0.3.20.0</AssemblyVersion>
|
||||
<FileVersion>0.3.20.0</FileVersion>
|
||||
<InformationalVersion>0.3.20</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+11
-5
@@ -273,7 +273,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
|
||||
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
|
||||
Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmupToken))),
|
||||
cancellationToken);
|
||||
cancellationToken,
|
||||
onBackgroundCompleted: error => AppPaths.WriteLog(new TransportDiagnostic(
|
||||
"connection_phase", error is null ? "learning_finished_or_cancelled" : "learning_failed_observed",
|
||||
_nodeSlug).SafeMessage));
|
||||
AppPaths.WriteLog(new TransportDiagnostic("connection_phase", "runtime_ready", _nodeSlug).SafeMessage);
|
||||
}
|
||||
|
||||
internal async Task StopAsync()
|
||||
@@ -642,7 +646,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
&& !value.Contains("Failed to start", StringComparison.OrdinalIgnoreCase)) return;
|
||||
try
|
||||
{
|
||||
File.AppendAllText(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}");
|
||||
BoundedLog.Append(AppPaths.XrayLogFile, $"{DateTimeOffset.Now:O} {value}{Environment.NewLine}",
|
||||
BoundedLog.XrayMaxBytes);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
@@ -704,9 +709,10 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(AppPaths.XrayLogFile)) return "";
|
||||
var lines = File.ReadLines(AppPaths.XrayLogFile).TakeLast(3);
|
||||
return $" {string.Join(" ", lines)}";
|
||||
var tail = BoundedLog.ReadTail(AppPaths.XrayLogFile, 3, BoundedLog.ErrorTailMaxBytes);
|
||||
return string.IsNullOrWhiteSpace(tail.Text)
|
||||
? ""
|
||||
: $" {tail.Text.Replace(Environment.NewLine, " ", StringComparison.Ordinal)}";
|
||||
}
|
||||
catch { return ""; }
|
||||
}
|
||||
|
||||
@@ -1,209 +1,256 @@
|
||||
using System.Text.Json;
|
||||
using UCVL.VPNPlus;
|
||||
|
||||
var checks = new Dictionary<string, bool>();
|
||||
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// The real coordinator receives controlled external setup/probe phases. The
|
||||
// semaphore is the same boundary used by XrayManager to defer rule commits.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
|
||||
var proofFinished = false; var committed = false; var setupFinished = false;
|
||||
var clock = new ManualClock();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
await tunReady.Task;
|
||||
begin(epoch.Token);
|
||||
nrptStarted.SetResult();
|
||||
await finishNrpt.Task;
|
||||
setupFinished = true;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = setupFinished; }
|
||||
finally { lifecycle.Release(); }
|
||||
}, CancellationToken.None, clock);
|
||||
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
||||
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
||||
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
||||
finishNrpt.SetResult(); await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["completed_proof_commits_after_setup"] = committed;
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
|
||||
var learningStarted = Signal(); var cancelled = false;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
||||
}, async token => {
|
||||
learningStarted.SetResult();
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { cancelled = true; }
|
||||
}, CancellationToken.None, clock);
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
||||
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMilliseconds(14_999));
|
||||
checks["learning_retains_fifteen_seconds_after_setup"] = !cancelled && !run.IsCompleted;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["learning_stops_at_post_setup_budget"] = cancelled;
|
||||
}
|
||||
|
||||
{
|
||||
var learningCalls = 0;
|
||||
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
|
||||
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
|
||||
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
|
||||
}
|
||||
|
||||
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
||||
var setupEntered = Signal(); var finishSetup = Signal(); var stopped = false; var active = false;
|
||||
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(epoch.Token); setupEntered.SetResult();
|
||||
await finishSetup.Task.WaitAsync(caller.Token);
|
||||
if (reason == "setup_failure") throw failure;
|
||||
}, async token => {
|
||||
active = true;
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { active = false; stopped = true; }
|
||||
}, caller.Token, new ManualClock());
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
if (reason == "caller_cancel") caller.Cancel();
|
||||
if (reason == "epoch_cancel") epoch.Cancel();
|
||||
finishSetup.TrySetResult();
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
|
||||
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
|
||||
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
|
||||
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
||||
}
|
||||
|
||||
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
|
||||
// lock. A proof already waiting to commit must not escape cleanup or apply late.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var proofFinished = false; var committed = false; var drained = false;
|
||||
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
|
||||
try
|
||||
{
|
||||
await StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
begin(epoch.Token);
|
||||
epoch.Cancel();
|
||||
throw failure;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = true; }
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { drained = true; }
|
||||
}, CancellationToken.None, new ManualClock());
|
||||
}
|
||||
catch (Exception error) { observed = error; }
|
||||
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
|
||||
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock();
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
|
||||
var learningStopped = false; var setupStarted = Signal();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupStarted.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, caller.Token);
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { learningStopped = true; }
|
||||
}, caller.Token, clock);
|
||||
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromSeconds(45));
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
|
||||
}
|
||||
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
|
||||
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
|
||||
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
|
||||
catch (OperationCanceledException) { }
|
||||
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
|
||||
}
|
||||
|
||||
// Production learning handlers absorb cancellation after cleaning up their own
|
||||
// probes. The startup owner must still propagate the user's cancelled connect.
|
||||
{
|
||||
using var caller = new CancellationTokenSource();
|
||||
var clock = new ManualClock(); var learnerFinishedNormally = false;
|
||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||
begin(CancellationToken.None); return Task.CompletedTask;
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
||||
}, caller.Token, clock);
|
||||
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
caller.Cancel();
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_cancellation_propagates_when_learning_swallows_it"] = cancelled && learnerFinishedNormally;
|
||||
}
|
||||
|
||||
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
|
||||
simulated_external_phases = true, network_modified = false, production_client_started = false };
|
||||
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 91;
|
||||
|
||||
sealed class ManualClock : TimeProvider
|
||||
{
|
||||
private readonly List<ManualTimer> timers = [];
|
||||
internal long ElapsedTicks { get; private set; }
|
||||
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
|
||||
timer.Change(dueTime, period); return timer;
|
||||
}
|
||||
internal void Advance(TimeSpan elapsed)
|
||||
{
|
||||
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
|
||||
foreach (var timer in snapshot) timer.FireIfDue();
|
||||
}
|
||||
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
private long? due; private bool disposed;
|
||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
if (disposed) return false;
|
||||
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
|
||||
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
|
||||
return true;
|
||||
}
|
||||
internal void FireIfDue()
|
||||
{
|
||||
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
|
||||
{ due = null; callback(state); }
|
||||
}
|
||||
public void Dispose() { disposed = true; due = null; }
|
||||
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
using System.Text.Json;
|
||||
using UCVL.VPNPlus;
|
||||
|
||||
var checks = new Dictionary<string, bool>();
|
||||
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// The real coordinator receives controlled external setup/probe phases. The
|
||||
// semaphore is the same boundary used by XrayManager to defer rule commits.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
|
||||
var allowCommit = Signal(); var learningFinished = Signal();
|
||||
var proofFinished = false; var committed = false; var setupFinished = false;
|
||||
var clock = new ManualClock();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
await tunReady.Task;
|
||||
begin(epoch.Token);
|
||||
nrptStarted.SetResult();
|
||||
await finishNrpt.Task;
|
||||
setupFinished = true;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
await allowCommit.Task.WaitAsync(token);
|
||||
committed = setupFinished;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, CancellationToken.None, clock);
|
||||
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
|
||||
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
|
||||
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
|
||||
finishNrpt.SetResult();
|
||||
var readyBeforeLearning = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||
checks["connection_readiness_does_not_wait_for_learning_commit"] = readyBeforeLearning && !committed;
|
||||
allowCommit.SetResult();
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["background_proof_commits_after_setup"] = committed;
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
|
||||
var learningStarted = Signal(); var learningFinished = Signal(); var cancelled = false;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
|
||||
}, async token => {
|
||||
learningStarted.SetResult();
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { cancelled = true; }
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, CancellationToken.None, clock);
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
|
||||
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
var readyBeforeBudget = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||
checks["connection_readiness_returns_while_learning_is_background"] = readyBeforeBudget && !cancelled;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(14_999));
|
||||
checks["background_learning_retains_fifteen_second_budget"] = !cancelled;
|
||||
clock.Advance(TimeSpan.FromMilliseconds(1));
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["background_learning_stops_at_post_setup_budget"] = cancelled;
|
||||
}
|
||||
|
||||
{
|
||||
var learningCalls = 0;
|
||||
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
|
||||
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
|
||||
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
|
||||
}
|
||||
|
||||
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
|
||||
var setupEntered = Signal(); var finishSetup = Signal(); var learningFinished = Signal();
|
||||
var stopped = false; var active = false;
|
||||
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(epoch.Token); setupEntered.SetResult();
|
||||
await finishSetup.Task.WaitAsync(caller.Token);
|
||||
if (reason == "setup_failure") throw failure;
|
||||
}, async token => {
|
||||
active = true;
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { active = false; stopped = true; learningFinished.TrySetResult(); }
|
||||
}, caller.Token, new ManualClock());
|
||||
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
if (reason == "caller_cancel") caller.Cancel();
|
||||
if (reason == "epoch_cancel") epoch.Cancel();
|
||||
finishSetup.TrySetResult();
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
|
||||
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
|
||||
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
|
||||
}
|
||||
|
||||
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
|
||||
// lock. A proof already waiting to commit must not escape cleanup or apply late.
|
||||
using (var epoch = new CancellationTokenSource())
|
||||
using (var lifecycle = new SemaphoreSlim(1, 1))
|
||||
{
|
||||
var proofFinished = false; var committed = false; var drained = false;
|
||||
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
|
||||
try
|
||||
{
|
||||
await StartupLearningWarmup.RunAsync(async begin => {
|
||||
await lifecycle.WaitAsync();
|
||||
try
|
||||
{
|
||||
begin(epoch.Token);
|
||||
epoch.Cancel();
|
||||
throw failure;
|
||||
}
|
||||
finally { lifecycle.Release(); }
|
||||
}, async token => {
|
||||
proofFinished = true;
|
||||
try
|
||||
{
|
||||
await lifecycle.WaitAsync(token);
|
||||
try { token.ThrowIfCancellationRequested(); committed = true; }
|
||||
finally { lifecycle.Release(); }
|
||||
}
|
||||
finally { drained = true; }
|
||||
}, CancellationToken.None, new ManualClock());
|
||||
}
|
||||
catch (Exception error) { observed = error; }
|
||||
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
|
||||
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
|
||||
}
|
||||
|
||||
{
|
||||
var clock = new ManualClock();
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
|
||||
var learningStopped = false; var setupStarted = Signal();
|
||||
var run = StartupLearningWarmup.RunAsync(async begin => {
|
||||
begin(CancellationToken.None); setupStarted.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, caller.Token);
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
finally { learningStopped = true; }
|
||||
}, caller.Token, clock);
|
||||
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
clock.Advance(TimeSpan.FromSeconds(45));
|
||||
var cancelled = false;
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
|
||||
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
|
||||
}
|
||||
|
||||
{
|
||||
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
|
||||
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
|
||||
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
|
||||
catch (OperationCanceledException) { }
|
||||
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
|
||||
}
|
||||
|
||||
// Production learning handlers absorb cancellation after cleaning up their own
|
||||
// probes. Once readiness has returned, later cancellation belongs only to the
|
||||
// bounded background learning run and cannot retroactively fail the connection.
|
||||
{
|
||||
using var caller = new CancellationTokenSource();
|
||||
var clock = new ManualClock(); var learningFinished = Signal(); var learnerFinishedNormally = false;
|
||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||
begin(CancellationToken.None); return Task.CompletedTask;
|
||||
}, async token => {
|
||||
try { await Task.Delay(Timeout.Infinite, token); }
|
||||
catch (OperationCanceledException) { learnerFinishedNormally = true; }
|
||||
finally { learningFinished.TrySetResult(); }
|
||||
}, caller.Token, clock);
|
||||
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
var readyBeforeCancel = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||
caller.Cancel();
|
||||
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch { }
|
||||
await learningFinished.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["post_readiness_cancellation_only_stops_background_learning"] =
|
||||
readyBeforeCancel && run.IsCompletedSuccessfully && learnerFinishedNormally;
|
||||
}
|
||||
|
||||
// A background learning fault must be observed and reported without changing a
|
||||
// readiness result that already completed successfully.
|
||||
{
|
||||
var releaseLearning = Signal(); var completionReported = Signal();
|
||||
var failure = new IOException("synthetic background learning failure"); Exception? observed = null;
|
||||
var run = StartupLearningWarmup.RunAsync(begin => {
|
||||
begin(CancellationToken.None); return Task.CompletedTask;
|
||||
}, async _ => {
|
||||
await releaseLearning.Task;
|
||||
throw failure;
|
||||
}, CancellationToken.None, new ManualClock(), onBackgroundCompleted: error => {
|
||||
observed = error;
|
||||
completionReported.TrySetResult();
|
||||
});
|
||||
var readyBeforeFault = await Task.WhenAny(run, Task.Delay(250)) == run;
|
||||
releaseLearning.SetResult();
|
||||
await run.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
await completionReported.Task.WaitAsync(TimeSpan.FromSeconds(3));
|
||||
checks["background_fault_is_observed_without_reversing_readiness"] =
|
||||
readyBeforeFault && run.IsCompletedSuccessfully && ReferenceEquals(observed, failure);
|
||||
}
|
||||
|
||||
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
|
||||
simulated_external_phases = true, network_modified = false, production_client_started = false };
|
||||
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 91;
|
||||
|
||||
sealed class ManualClock : TimeProvider
|
||||
{
|
||||
private readonly List<ManualTimer> timers = [];
|
||||
internal long ElapsedTicks { get; private set; }
|
||||
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
|
||||
timer.Change(dueTime, period); return timer;
|
||||
}
|
||||
internal void Advance(TimeSpan elapsed)
|
||||
{
|
||||
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
|
||||
foreach (var timer in snapshot) timer.FireIfDue();
|
||||
}
|
||||
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
|
||||
{
|
||||
private long? due; private bool disposed;
|
||||
public bool Change(TimeSpan dueTime, TimeSpan period)
|
||||
{
|
||||
if (disposed) return false;
|
||||
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
|
||||
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
|
||||
return true;
|
||||
}
|
||||
internal void FireIfDue()
|
||||
{
|
||||
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
|
||||
{ due = null; callback(state); }
|
||||
}
|
||||
public void Dispose() { disposed = true; due = null; }
|
||||
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# 纵横家 Windows 0.3.20
|
||||
|
||||
发布日期:2026-11-28
|
||||
|
||||
## 连接与故障切换
|
||||
|
||||
- 将首次连接中的规则学习移到受控后台任务;TUN、DNS 和 NRPT 就绪后立即进行代理 HTTPS 出口验证,不再为学习任务额外等待最多 15 秒。
|
||||
- 自动调度下,普通业务路径和强制代理业务探测连续三轮均不可用时执行故障切换。Tailscale 入口先回退到同一节点的青岛公网入口;公网入口仍不可用时才冷却该节点并选择其他可用节点。
|
||||
- 手动指定节点保持用户选择,只显示业务不可用提示,不擅自切换到另一节点。
|
||||
- Tailscale DERP 旁路地址改为从已安装的官方 Tailscale 客户端当前 DERP Map 动态读取。读取限时 2 秒、输出上限 256 KiB、最多 64 个经过公共 IPv4 校验的地址;失败时不制造未知旁路。
|
||||
|
||||
## 稳定性与诊断
|
||||
|
||||
- `vpnplus.log` 和 `xray.log` 各限制为 4 MiB 活动文件加一个轮换备份;旧版超大日志只在下一次自然写入时处理,安装和读取不会主动改写。
|
||||
- Xray 错误摘要最多读取末尾 64 KiB 和三行,并清理无效 NUL 字节;代理复测日志不再记录目标地址、端口或底层异常正文。
|
||||
- 启动不可执行或损坏的 `xray.exe` 时临时禁止 Windows 系统错误对话框,转为纵横家本机组件故障,保证自动升级、退出和关机流程不会被隐藏窗口阻塞。
|
||||
|
||||
## 后台源码
|
||||
|
||||
- 默认管理域名、允许主机、CSRF 来源和公开入口统一为 `vpn.ucvl.cn`。
|
||||
- 默认青岛公网入口为 `47.104.134.190`;部署环境仍可通过环境变量覆盖所有公开地址。
|
||||
- 新增生产默认值与环境覆盖测试,完整 Django 测试集保持通过。
|
||||
|
||||
## 验收边界
|
||||
|
||||
- Windows 自检均在隔离临时目录执行,不修改已安装客户端或现有网络。
|
||||
- 后台生产容器只有在取得 VPN004 Tailscale 管理入口的有效 SSH 授权、完成运行态备份和回滚核验后才能升级;源码发布不等于生产后台已经部署。
|
||||
- 安装包尚未包含公司 Authenticode 签名,Windows 仍可能显示未知发布者提示。
|
||||
Reference in New Issue
Block a user