194 lines
12 KiB
C#
194 lines
12 KiB
C#
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.NetworkInformation;
|
|
using System.Net.Sockets;
|
|
using System.Net.WebSockets;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
// Opt-in network integration test: creates a UNIQUE adapter and ONE /32 route
|
|
// in the benchmarking range. No default routes, DNS, proxy, tokens, or main
|
|
// client's state files are touched. A timer/process cleanup removes that route.
|
|
internal static class TunConnectivitySelfTest
|
|
{
|
|
internal static async Task<int> RunSavedNodeAsync(string slug)
|
|
{
|
|
// Keep the saved session and returned node credentials inside the app.
|
|
// No credential-export scripts or production configuration rewrites.
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
|
var token = TokenStore.Load();
|
|
if (string.IsNullOrWhiteSpace(token)) return 42;
|
|
using var api = new VpnApiClient();
|
|
var profile = await api.GetProfileAsync(token, timeout.Token);
|
|
if (!profile.Nodes.Any(n => n.Slug == slug) || slug.Contains('/') || slug.Contains('\\')) return 43;
|
|
var response = await api.GetConfigAsync(token, slug, "smart", timeout.Token);
|
|
var output = Path.Combine(AppContext.BaseDirectory, "tun-node-" + slug + ".json");
|
|
return await RunAsync(response.GetRuntimeConfigJson(), output);
|
|
}
|
|
|
|
internal static async Task<int> RunAsync(string? savedConfig = null, string? reportPath = null)
|
|
{
|
|
var input = Environment.GetEnvironmentVariable("UCVL_TUN_AUDIT_INPUT");
|
|
if (savedConfig is null && string.IsNullOrWhiteSpace(input)) throw new InvalidOperationException("Missing isolated audit input");
|
|
var output = reportPath ?? Environment.GetEnvironmentVariable("UCVL_TUN_AUDIT_OUTPUT")
|
|
?? throw new InvalidOperationException("Missing audit output");
|
|
if (!TunRouting.IsElevated()) throw new InvalidOperationException("Isolated TUN test requires administrator privileges");
|
|
var folder = Path.Combine(Path.GetTempPath(), "ucvl-tun-audit-" + Guid.NewGuid().ToString("N"));
|
|
Directory.CreateDirectory(folder);
|
|
var adapterName = "UCVL VPNPlus Audit " + Guid.NewGuid().ToString("N")[..8];
|
|
var fakeAddress = IPAddress.Parse("198.18.77.77");
|
|
var table = new WindowsRouteTable();
|
|
var lease = new NetworkRouteLease(Path.Combine(folder, "routes.json"), table);
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(180));
|
|
using var core = new Process();
|
|
var report = new Dictionary<string, object> { ["adapter"] = adapterName, ["time"] = DateTimeOffset.Now,
|
|
["default_route_changes"] = false, ["system_proxy_changes"] = false,
|
|
["authenticated_codex_task_tested"] = false };
|
|
var passed = false;
|
|
var xray = Path.Combine(AppContext.BaseDirectory, "xray", "xray.exe");
|
|
try
|
|
{
|
|
if (table.Snapshot().Any(r => r.Destination == fakeAddress.ToString()))
|
|
throw new IOException("Benchmark address already has a route; refusing to replace it.");
|
|
var baseConfig = savedConfig ?? await File.ReadAllTextAsync(input!, timeout.Token);
|
|
var addresses = new List<IPAddress>();
|
|
foreach (var host in TunConfigBuilder.GetProxyServerHosts(baseConfig))
|
|
addresses.AddRange(await Dns.GetHostAddressesAsync(host, timeout.Token));
|
|
var physical = TunRouting.GetPhysicalNetwork(addresses);
|
|
var apiPort = FreePort();
|
|
var root = JsonNode.Parse(TunConfigBuilder.BuildRuntime(baseConfig, physical.InterfaceName, false, apiPort))!.AsObject();
|
|
report["physical_interface"] = physical.InterfaceName;
|
|
foreach (var inbound in root["inbounds"]!.AsArray())
|
|
{
|
|
if (inbound!["protocol"]!.GetValue<string>() == "tun") inbound["settings"]!["name"] = adapterName;
|
|
else { inbound["port"] = FreePort(); inbound["listen"] = "127.0.0.1"; }
|
|
}
|
|
root["log"] = new JsonObject { ["loglevel"] = "none" };
|
|
// Ensure SYNTHETIC echo traffic uses the node, including smart mode.
|
|
root["routing"]!["rules"]!.AsArray().Insert(0, new JsonObject {
|
|
["type"] = "field", ["domain"] = new JsonArray("full:ws.postman-echo.com", "full:postman-echo.com"), ["outboundTag"] = "proxy" });
|
|
RoutingRuleBatches.TagInitialRules(root);
|
|
var configPath = Path.Combine(folder, "config.json");
|
|
await File.WriteAllTextAsync(configPath, root.ToJsonString(), timeout.Token);
|
|
core.StartInfo = new ProcessStartInfo { FileName = xray, WorkingDirectory = Path.GetDirectoryName(xray)!,
|
|
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
|
|
foreach (var arg in new[] { "run", "-c", configPath }) core.StartInfo.ArgumentList.Add(arg);
|
|
core.Start();
|
|
var stdout = core.StandardOutput.ReadToEndAsync(timeout.Token);
|
|
var stderr = core.StandardError.ReadToEndAsync(timeout.Token);
|
|
report["stage"] = "wait_ipv4_ready";
|
|
var adapter = await TunRouting.WaitForAdapterAsync(timeout.Token, adapterName, requireIpv4Ready: true);
|
|
if (core.HasExited) throw new IOException("Isolated core exited before adapter became ready");
|
|
var index = adapter.GetIPProperties().GetIPv4Properties()!.Index;
|
|
report["adapter_index"] = index;
|
|
report["adapter_addresses"] = adapter.GetIPProperties().UnicastAddresses.Select(a => new {
|
|
address = a.Address.ToString(), state = a.DuplicateAddressDetectionState.ToString() }).ToArray();
|
|
report["stage"] = "add_test_route";
|
|
await lease.ApplyAsync(new[] { new Ipv4Route(fakeAddress.ToString(), "255.255.255.255", "0.0.0.0", index, 5) }, timeout.Token);
|
|
report["test_route"] = table.Snapshot().Where(r => r.Destination == fakeAddress.ToString()).ToArray();
|
|
using var handler = new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(10),
|
|
ConnectCallback = async (_, token) => {
|
|
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
|
try { await socket.ConnectAsync(fakeAddress, 443, token); return new NetworkStream(socket, ownsSocket: true); }
|
|
catch { socket.Dispose(); throw; }
|
|
}};
|
|
using var client = new HttpClient(handler, disposeHandler: false) { Timeout = TimeSpan.FromSeconds(15) };
|
|
foreach (var (label, url, expected) in new[] {
|
|
("Google", "https://www.google.com/generate_204", 204),
|
|
("OpenAI", "https://api.openai.com/v1/models", 401),
|
|
("Codex", "https://chatgpt.com/backend-api/codex/models", 401) })
|
|
{
|
|
report["stage"] = "native_" + label;
|
|
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
|
|
report[label] = (int)response.StatusCode;
|
|
if ((int)response.StatusCode != expected) throw new IOException($"{label} native probe returned {(int)response.StatusCode}");
|
|
}
|
|
// The public HTTPS echo endpoint returned 500 for the large POST
|
|
// control, so it is not used as a release gate or a claimed success.
|
|
report["large_https_upload_verified"] = false;
|
|
// Independent WebSocket service, random diagnostic bytes only.
|
|
// This proves transport longevity, NOT an authenticated Codex task.
|
|
using var invoker = new HttpMessageInvoker(handler, disposeHandler: false);
|
|
report["stage"] = "websocket";
|
|
using var ws = new ClientWebSocket();
|
|
await ws.ConnectAsync(new Uri("wss://ws.postman-echo.com/raw"), invoker, timeout.Token);
|
|
report["websocket_handshake"] = true;
|
|
var watch = Stopwatch.StartNew();
|
|
var echoes = 0;
|
|
for (var i = 0; i < 5; i++)
|
|
{
|
|
if (i > 0) await Task.Delay(TimeSpan.FromSeconds(15), timeout.Token);
|
|
report["stage"] = "websocket_echo_" + i;
|
|
// This public echo service accepts TEXT and limits message
|
|
// size. Keep each message below 16 KiB, exercise >64 KiB total.
|
|
for (var message = 0; message < (i == 2 ? 8 : 1); message++)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(RandomNumberGenerator.GetBytes(8192)));
|
|
await ws.SendAsync(bytes.AsMemory(), WebSocketMessageType.Text, true, timeout.Token);
|
|
using var received = new MemoryStream();
|
|
var buffer = new byte[8192];
|
|
ValueWebSocketReceiveResult part;
|
|
do
|
|
{
|
|
part = await ws.ReceiveAsync(buffer.AsMemory(), timeout.Token);
|
|
if (part.MessageType == WebSocketMessageType.Close) throw new IOException("Echo WebSocket closed unexpectedly");
|
|
received.Write(buffer, 0, part.Count);
|
|
if (received.Length > bytes.Length) throw new IOException("Unexpected echo payload size");
|
|
} while (!part.EndOfMessage);
|
|
if (!bytes.SequenceEqual(received.ToArray())) throw new IOException("Echo payload mismatch");
|
|
echoes++;
|
|
report["websocket_echoes"] = echoes;
|
|
report["websocket_seconds"] = Math.Round(watch.Elapsed.TotalSeconds, 1);
|
|
}
|
|
if (i == 2)
|
|
{
|
|
report["stage"] = "hot_routing_update";
|
|
await XrayRoutingUpdater.ApplyAsync(xray, apiPort,
|
|
new JsonObject { ["routing"] = root["routing"]!.DeepClone() }.ToJsonString(), timeout.Token);
|
|
}
|
|
}
|
|
report["websocket_echoes"] = echoes;
|
|
report["websocket_seconds"] = Math.Round(watch.Elapsed.TotalSeconds, 1);
|
|
report["routing_hot_update_kept_websocket"] = !core.HasExited;
|
|
var counters = await XrayManager.ReadTrafficCountersAsync(xray, apiPort, timeout.Token);
|
|
report["proxy_bytes_counted"] = counters is { Up: > 65536, Down: > 65536 };
|
|
if (counters is not { Up: > 65536, Down: > 65536 }) throw new IOException("Native bytes were not counted as proxy traffic");
|
|
passed = true;
|
|
}
|
|
catch (Exception error) {
|
|
report["error"] = error.GetBaseException().Message;
|
|
report["error_type"] = error.GetBaseException().GetType().Name;
|
|
if (error.GetBaseException() is SocketException socketError) report["socket_error"] = socketError.SocketErrorCode.ToString();
|
|
}
|
|
finally
|
|
{
|
|
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
|
try { await lease.RestoreAsync(cleanup.Token); report["test_route_restored"] = true; }
|
|
catch (Exception error) { report["cleanup_error"] = error.Message; passed = false; }
|
|
try { if (!core.HasExited) { core.Kill(entireProcessTree: true); await core.WaitForExitAsync(cleanup.Token); } } catch { }
|
|
try
|
|
{
|
|
var digest = MD5.HashData(Encoding.UTF8.GetBytes(adapterName));
|
|
await NetworkCommand.RunAsync("pnputil.exe", $"/remove-device \"SWD\\Wintun\\{{{new Guid(digest).ToString().ToUpperInvariant()}}}\"", cleanup.Token);
|
|
}
|
|
catch (Exception error) { report["adapter_cleanup_warning"] = error.Message; }
|
|
report["passed"] = passed;
|
|
File.WriteAllText(output, JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
|
foreach (var name in new[] { "config.json", "routes.json.new" })
|
|
if (File.Exists(Path.Combine(folder, name))) File.Delete(Path.Combine(folder, name));
|
|
// Keep a failed route journal for manual inspection/retry.
|
|
if (!File.Exists(Path.Combine(folder, "routes.json"))) Directory.Delete(folder);
|
|
}
|
|
return passed ? 0 : 41;
|
|
}
|
|
private static int FreePort()
|
|
{
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port;
|
|
}
|
|
}
|