Files

102 lines
7.1 KiB
C#
Raw Permalink Normal View History

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace UCVL.VPNPlus;
// Real core + authorized nodes, loopback-only inbounds. Never acquires the network
// owner, installs TUN, changes DNS/route/proxy or touches the running installation.
internal static class LearningMatrixSelfTest
{
internal static async Task<int> RunAsync()
{
var results = new List<object>();
var passed = false;
string? errorType = null;
try
{
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(3));
using var api = new VpnApiClient();
var access = TokenStore.Load() ?? throw new IOException("No existing app session.");
var profile = await api.GetProfileAsync(access, timeout.Token);
var nodes = profile.Nodes.Where(n=>n.Name is "VPN002" or "VPN003").ToArray();
if (nodes.Length != 2) throw new IOException("Expected authorized public nodes absent.");
var nodePasses = new List<bool>();
foreach (var node in nodes)
{
var response = await api.GetConfigAsync(access,node.Slug,"smart",timeout.Token);
var config = LearningPolicy.DirectFirst(response.GetRuntimeConfigJson());
var addresses = new List<IPAddress>();
foreach (var host in TunConfigBuilder.GetProxyServerHosts(config)) addresses.AddRange(await Dns.GetHostAddressesAsync(host,timeout.Token));
var physical = TunRouting.GetPhysicalNetwork(addresses);
// Reserve simultaneously so port numbers cannot duplicate each other.
var listeners = Enumerable.Range(0,4).Select(_=>new TcpListener(IPAddress.Loopback,0)).ToArray();
foreach(var l in listeners) l.Start();
var ports = listeners.Select(l=>((IPEndPoint)l.LocalEndpoint).Port).ToArray();
foreach(var l in listeners) l.Stop();
var root=JsonNode.Parse(config)!.AsObject();
root["inbounds"]=new JsonArray(new JsonObject { ["tag"]="matrix-business",["listen"]="127.0.0.1",["port"]=ports[0],
["protocol"]="socks",["settings"]=new JsonObject { ["auth"]="noauth",["udp"]=false },
["sniffing"]=new JsonObject { ["enabled"]=true,["destOverride"]=new JsonArray("tls"),["routeOnly"]=false } });
config=root.ToJsonString();
string Runtime(string source) => TunConfigBuilder.Build(source,physical.InterfaceName,true,includeTun:false,
routingApiPort:ports[1],learningProbePort:ports[2],directProbePort:ports[3]);
var folder=Path.Combine(Path.GetTempPath(),"ucvl-learning-matrix-"+Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
var path=Path.Combine(folder,"config.json");
var xray=Path.Combine(AppContext.BaseDirectory,"xray","xray.exe");
Process? process=null;
try
{
await File.WriteAllTextAsync(path,Runtime(config),timeout.Token);
var start=new ProcessStartInfo(xray) { UseShellExecute=false,CreateNoWindow=true,RedirectStandardOutput=true,RedirectStandardError=true };
foreach(var arg in new[]{"run","-c",path}) start.ArgumentList.Add(arg);
process=Process.Start(start)!;
_=process.StandardOutput.ReadToEndAsync(); _=process.StandardError.ReadToEndAsync();
await Task.Delay(800,timeout.Token);
var originalPid=process.Id;
var comparisons=await Task.WhenAll(new[]{"www.google.com","chatgpt.com","www.baidu.com"}.Select(async host=> {
var watch=Stopwatch.StartNew();
var observation=new LearningObservation { Target=host,Port=443,AccessKind="http" };
var comparison=await ProxyProbe.CompareTlsAsync(observation,ports[3],ports[2],timeout.Token);
return (host,comparison,ms:watch.ElapsedMilliseconds);
}));
var learned=comparisons.Where(p=>p.comparison.ShouldProxy).Select(p=>new RoutingTarget {Target=p.host,TargetType="domain",MatchMode="exact"}).ToList();
var updated=LearningPolicy.Merge(config,new() {Contract=1,Revision=new string('0',64),Rules=learned});
var runtime=JsonNode.Parse(Runtime(updated))!;
await XrayRoutingUpdater.ApplyAsync(xray,ports[1],new JsonObject { ["routing"]=runtime["routing"]!.DeepClone() }.ToJsonString(),timeout.Token);
using var http=new HttpClient(new SocketsHttpHandler {UseProxy=true,Proxy=new WebProxy($"socks5://127.0.0.1:{ports[0]}"),AllowAutoRedirect=false}) { Timeout=TimeSpan.FromSeconds(12) };
int google=0;
try { using var reply=await http.GetAsync("https://www.google.com/generate_204",timeout.Token); google=(int)reply.StatusCode; } catch(HttpRequestException) { } catch(TaskCanceledException) when(!timeout.IsCancellationRequested) { }
bool businessTls;
// Uses the ordinary smart-routed listener, NOT the forced proxy listener.
businessTls=await ProxyProbe.ProbeTlsAsync(new(){Target="chatgpt.com",Port=443},ports[0],timeout.Token,resolverProxyPort:ports[2])==true;
var sameCore=!process.HasExited && process.Id==originalPid;
var ok=sameCore && google==204 && businessTls && comparisons.All(p=>p.comparison.DirectTls==true || p.comparison.ShouldProxy)
&& comparisons.Any(p=>p.comparison.DirectTls==true) && learned.Count>0;
results.Add(new {node=node.Name,passed=ok,comparisons=comparisons.Select(p=>new {target=p.host,direct_tls=p.comparison.DirectTls,proxy_tls=p.comparison.ProxyTls,promoted=p.comparison.ShouldProxy,elapsed_ms=p.ms}),
google_smart_http=google,chatgpt_smart_tls=businessTls,same_core_after_rule_update=sameCore});
nodePasses.Add(ok);
}
finally
{
if(process is not null) {try {if(!process.HasExited) process.Kill(true); await process.WaitForExitAsync();} finally {process.Dispose();} }
if(File.Exists(path)) File.Delete(path);
Directory.Delete(folder);
}
}
passed=nodePasses.Count==2 && nodePasses.All(x=>x);
}
catch(Exception error) {errorType=error.GetType().Name;}
finally
{
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"learning-matrix-self-test.json"),JsonSerializer.Serialize(new {
scope="real physical-interface direct TLS vs authorized-node proxy TLS, then loopback smart routing; NOT installed TUN or authenticated Codex acceptance",
passed,error_type=errorType,os_network_modified=false,production_observations_submitted=false,results},new JsonSerializerOptions{WriteIndented=true}));
}
return passed?0:33;
}
}