Files
ucvl-zonghengjia-open-source/windows/RouteLeaseSelfTest.cs

98 lines
5.6 KiB
C#

using System.Net;
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class RouteLeaseSelfTest
{
private sealed class FakeTable : IRouteTable
{
internal readonly List<Ipv4Route> Routes = [];
internal int FailAdd = -1, AddCount;
internal bool FailDelete;
public IReadOnlyList<Ipv4Route> Snapshot() => Routes.ToArray();
public Task AddAsync(Ipv4Route route, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (AddCount++ == FailAdd) throw new IOException("Injected add failure");
Routes.Add(route);
return Task.CompletedTask;
}
public Task DeleteAsync(Ipv4Route route, CancellationToken token)
{
if (FailDelete) throw new IOException("Injected delete failure");
Routes.RemoveAll(route.SamePath);
return Task.CompletedTask;
}
}
internal static async Task<int> RunAsync()
{
var folder = Path.Combine(Path.GetTempPath(), "ucvl-route-unit-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
var path = Path.Combine(folder, "routes.json");
var table = new FakeTable();
var lease = new NetworkRouteLease(path, table);
var original = new Ipv4Route("203.0.113.10", "255.255.255.255", "192.168.1.1", 10);
var split = new[] { new Ipv4Route("0.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5),
new Ipv4Route("128.0.0.0", "128.0.0.0", "0.0.0.0", 20, 5) };
var report = new Dictionary<string, object>();
try
{
var gateway = IPAddress.Parse("192.168.1.1");
var physical = new TunRouting.PhysicalNetwork("Fixture Ethernet", 10, IPAddress.Parse("192.168.1.20"),
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);
var protectedRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(tailnet.Destination)], 20, preserveProxyRoute: true);
var publicRoutes = TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse(management.Destination)], 20, preserveProxyRoute: false);
report["management_ipv4_bypasses_tun_in_all_modes"] =
protectedRoutes.Count(management.SamePath) == 1 && publicRoutes.Count(management.SamePath) == 1
&& protectedRoutes.SkipLast(2).All(r => r.InterfaceIndex == physical.InterfaceIndex)
&& protectedRoutes.TakeLast(2).SequenceEqual(split);
report["tailscale_and_private_proxy_routes_are_not_replaced"] =
protectedRoutes.All(r => r.Destination != tailnet.Destination)
&& !TunRouting.CreateOwnedRoutes(physical, [IPAddress.Parse("172.16.0.111")], 20, preserveProxyRoute: true)
.Any(r => r.Destination == "172.16.0.111");
table.Routes.AddRange([tailnet, management]);
await lease.ApplyAsync(protectedRoutes, CancellationToken.None);
await lease.RestoreAsync(CancellationToken.None);
report["existing_management_and_tailnet_paths_survive_cleanup"] = table.Routes.SequenceEqual([tailnet, management]);
table.Routes.Clear();
table.AddCount = 0;
table.Routes.Add(original);
table.FailAdd = 1;
try { await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None); }
catch (IOException) { }
report["partial_split_route_failure_rolled_back"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path);
table.FailAdd = -1;
await lease.ApplyAsync(new[] { original }.Concat(split), CancellationToken.None);
table.FailDelete = true;
try { await lease.RestoreAsync(CancellationToken.None); } catch (AggregateException) { }
report["failed_restore_retains_journal"] = File.Exists(path);
table.FailDelete = false;
await lease.RestoreAsync(CancellationToken.None);
report["retry_restores_without_deleting_preexisting_route"] = table.Routes.SequenceEqual(new[] { original }) && !File.Exists(path);
await lease.RestoreAsync(CancellationToken.None);
report["restore_is_idempotent"] = table.Routes.Count == 1;
using var cancelled = new CancellationTokenSource(); cancelled.Cancel();
try { await lease.ApplyAsync(split, cancelled.Token); } catch (OperationCanceledException) { }
report["cancel_before_apply_preserves_original"] = table.Routes.Count == 1 && !File.Exists(path);
// Read-only native table validates the P/Invoke layout against this machine.
var native = new WindowsRouteTable().Snapshot();
report["native_route_snapshot_has_loopback"] = native.Any(r => r.Destination == "127.0.0.0" && r.Mask == "255.0.0.0");
report["native_on_link_hop_is_normalized"] = native.Any(r => r.Destination == "127.0.0.0" && r.NextHop == "0.0.0.0");
report["passed"] = report.Values.All(v => v is true);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "route-lease-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
return (bool)report["passed"] ? 0 : 31;
}
finally
{
if (File.Exists(path)) File.Delete(path);
if (File.Exists(path + ".new")) File.Delete(path + ".new");
Directory.Delete(folder);
}
}
}