128 lines
8.2 KiB
C#
128 lines
8.2 KiB
C#
using System.Text.Json;
|
|
using System.Security.AccessControl;
|
|
using System.Security.Principal;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal static class ClientRuntimeSelfTest
|
|
{
|
|
internal static async Task<Dictionary<string, bool>> CheckAsync()
|
|
{
|
|
var checks = new Dictionary<string, bool>();
|
|
var root = Path.Combine(Path.GetTempPath(), "ucvl-runtime-test-" + Guid.NewGuid().ToString("N"));
|
|
Directory.CreateDirectory(Path.Combine(root, "xray"));
|
|
// Tiny inert fixture files; none are executed or treated as real Xray.
|
|
void Seed() { foreach (var name in ClientRuntime.Components) File.WriteAllBytes(Path.Combine(root, "xray", name), [1, 2]); }
|
|
ClientRuntimeException? ReadFault()
|
|
{
|
|
try { ClientRuntime.Validate(root); return null; }
|
|
catch (ClientRuntimeException error) { return error; }
|
|
}
|
|
async Task<bool> RuntimeFailure(Func<Task> operation)
|
|
{
|
|
try { await operation(); return false; }
|
|
catch (ClientRuntimeException) { return true; }
|
|
}
|
|
try
|
|
{
|
|
Seed();
|
|
checks["four_readable_nonempty_components_accepted"] = ReadFault() is null;
|
|
foreach (var name in ClientRuntime.Components)
|
|
{
|
|
var path = Path.Combine(root, "xray", name);
|
|
File.Delete(path);
|
|
var missing = ReadFault();
|
|
checks["missing_" + name] = missing is { Fault: ClientRuntimeFault.Missing }
|
|
&& missing.ComponentPath == path && missing.Message.Contains("完整安装包") && missing.Message.Contains(path);
|
|
Seed();
|
|
File.WriteAllBytes(path, []);
|
|
checks["empty_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Empty };
|
|
Seed();
|
|
using (var locked = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
|
|
checks["locked_not_reported_missing_" + name] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
|
|
}
|
|
var deniedPath = Path.Combine(root, "xray", "xray.exe");
|
|
var originalAcl = new FileInfo(deniedPath).GetAccessControl();
|
|
try
|
|
{
|
|
var deniedAcl = new FileInfo(deniedPath).GetAccessControl();
|
|
deniedAcl.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User!, FileSystemRights.ReadData,
|
|
AccessControlType.Deny));
|
|
new FileInfo(deniedPath).SetAccessControl(deniedAcl);
|
|
checks["access_denied_not_reported_missing"] = ReadFault() is { Fault: ClientRuntimeFault.Unreadable };
|
|
}
|
|
finally { new FileInfo(deniedPath).SetAccessControl(originalAcl); }
|
|
var error = new ClientRuntimeException(Path.Combine(root, "xray", "xray.exe"), ClientRuntimeFault.Missing);
|
|
using (var absent = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
|
|
FileName=Path.Combine(root, "xray", "missing-fixture.exe"), UseShellExecute=false, CreateNoWindow=true,
|
|
} })
|
|
{
|
|
try { ClientRuntime.Start(absent); checks["disappeared_executable_is_local_failure"] = false; }
|
|
catch (ClientRuntimeException failure) { checks["disappeared_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.Missing; }
|
|
}
|
|
using (var invalid = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo {
|
|
FileName=Path.Combine(root, "xray", "xray.exe"), UseShellExecute=false, CreateNoWindow=true,
|
|
} })
|
|
{
|
|
try { ClientRuntime.Start(invalid); checks["invalid_executable_is_local_failure"] = false; }
|
|
catch (ClientRuntimeException failure) { checks["invalid_executable_is_local_failure"] = failure.Fault == ClientRuntimeFault.CannotStart; }
|
|
}
|
|
checks["diagnostic_contains_only_installation_identity"] = error.Diagnostic.Contains(error.ComponentPath)
|
|
&& error.Diagnostic.Contains(" process=") && error.Diagnostic.Contains(" version=")
|
|
&& !error.Diagnostic.Contains('\n') && !error.Diagnostic.Contains('\r');
|
|
var response = JsonSerializer.Deserialize<ConfigResponse>("""
|
|
{"config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart",
|
|
"tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.99.142.38","port":10803},
|
|
"config":{"inbounds":[],"outbounds":[
|
|
{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"002.vpn.toplc.cn","port":11082,"users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]},
|
|
"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}},
|
|
{"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[]}}}
|
|
""")!;
|
|
foreach (var stage in new[] { "route", "ping", "tailnet_start", "public_start" })
|
|
{
|
|
var preference = new TailnetPreference();
|
|
var starts = 0; var stops = 0; var probes = 0;
|
|
Task Start(string _, CancellationToken token) { starts++; if (stage is "tailnet_start" or "public_start") throw error; return Task.CompletedTask; }
|
|
Task Stop() { stops++; return Task.CompletedTask; }
|
|
Task<bool> Health(CancellationToken _) { probes++; return Task.FromResult(true); }
|
|
void Route(string _) { if (stage == "route") throw error; }
|
|
Task<bool> Ping(string _, int port, CancellationToken token) { if (stage == "ping") throw error; return Task.FromResult(true); }
|
|
var selectedResponse = stage == "public_start" ? new ConfigResponse {
|
|
Config=response.Config, ConfigContract=response.ConfigContract, ConnectionScope=response.ConnectionScope,
|
|
Node=response.Node, RouteMode=response.RouteMode, TailscaleEndpoint=null,
|
|
} : response;
|
|
var rejected = await RuntimeFailure(() => NodeTransportConnector.ConnectAsync(selectedResponse, preference, Start, Stop,
|
|
Health, Route, _ => { }, () => 100, CancellationToken.None, endpointProbe: Ping));
|
|
checks[stage + "_local_failure_propagates"] = rejected;
|
|
checks[stage + "_no_domain_or_cooldown_state_change"] = !preference.DomainOnly && preference.MayTry("tokyo", 101);
|
|
checks[stage + "_no_cleanup_or_health_attempt"] = stops == 0 && probes == 0;
|
|
checks[stage + "_no_second_start"] = starts == (stage is "tailnet_start" or "public_start" ? 1 : 0);
|
|
}
|
|
var tailnet = TailnetTransport.TryPrepare(response)!;
|
|
var rebindStarts = 0; var rebindStops = 0;
|
|
checks["rebind_local_failure_propagates_without_fallback"] = await RuntimeFailure(() => NodeTransportConnector.RebindAsync(
|
|
tailnet, response.GetRuntimeConfigJson(), (_, _) => { rebindStarts++; throw error; },
|
|
() => { rebindStops++; return Task.CompletedTask; }, _ => Task.FromResult(true), CancellationToken.None))
|
|
&& rebindStarts == 1 && rebindStops == 0;
|
|
}
|
|
finally
|
|
{
|
|
// Only these four known inert files in the fresh GUID directory.
|
|
foreach (var name in ClientRuntime.Components) File.Delete(Path.Combine(root, "xray", name));
|
|
Directory.Delete(Path.Combine(root, "xray"));
|
|
Directory.Delete(root);
|
|
}
|
|
return checks;
|
|
}
|
|
|
|
internal static async Task<int> RunAsync()
|
|
{
|
|
var checks = await CheckAsync();
|
|
var passed = checks.Values.All(value => value);
|
|
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-runtime-self-test.json"),
|
|
JsonSerializer.Serialize(new { passed, network_modified = false, installed_client_modified = false, installer_launched = false, checks },
|
|
new JsonSerializerOptions { WriteIndented=true }));
|
|
return passed ? 0 : 92;
|
|
}
|
|
}
|