189 lines
8.4 KiB
C#
189 lines
8.4 KiB
C#
|
|
using System.ComponentModel;
|
||
|
|
using System.Diagnostics;
|
||
|
|
using System.Net;
|
||
|
|
using System.Runtime.InteropServices;
|
||
|
|
using System.Text.Json;
|
||
|
|
|
||
|
|
namespace UCVL.VPNPlus;
|
||
|
|
|
||
|
|
internal sealed record Ipv4Route(string Destination, string Mask, string NextHop, int InterfaceIndex, int Metric = 1)
|
||
|
|
{
|
||
|
|
internal bool SamePath(Ipv4Route other) => Destination == other.Destination && Mask == other.Mask
|
||
|
|
&& NextHop == other.NextHop && InterfaceIndex == other.InterfaceIndex;
|
||
|
|
internal void Validate()
|
||
|
|
{
|
||
|
|
foreach (var value in new[] { Destination, Mask, NextHop })
|
||
|
|
if (!IPAddress.TryParse(value, out var ip) || ip.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
|
||
|
|
throw new InvalidDataException("Invalid IPv4 route journal.");
|
||
|
|
if (InterfaceIndex <= 0 || Metric < 0) throw new InvalidDataException("Invalid route interface/metric.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal interface IRouteTable
|
||
|
|
{
|
||
|
|
IReadOnlyList<Ipv4Route> Snapshot();
|
||
|
|
Task AddAsync(Ipv4Route route, CancellationToken token);
|
||
|
|
Task DeleteAsync(Ipv4Route route, CancellationToken token);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Journal BEFORE each mutation so cancellation/crashes between two /1 routes
|
||
|
|
// cannot leave the first half of the internet captured. Never lease an existing route.
|
||
|
|
internal sealed class NetworkRouteLease(string stateFile, IRouteTable table)
|
||
|
|
{
|
||
|
|
private sealed class State
|
||
|
|
{
|
||
|
|
public int SchemaVersion { get; set; } = 2;
|
||
|
|
public List<Ipv4Route> Routes { get; set; } = [];
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Save(State state)
|
||
|
|
{
|
||
|
|
Directory.CreateDirectory(Path.GetDirectoryName(stateFile)!);
|
||
|
|
var temporary = stateFile + ".new";
|
||
|
|
using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
|
||
|
|
{
|
||
|
|
JsonSerializer.Serialize(file, state);
|
||
|
|
file.Flush(flushToDisk: true);
|
||
|
|
}
|
||
|
|
File.Move(temporary, stateFile, overwrite: true);
|
||
|
|
}
|
||
|
|
|
||
|
|
internal async Task ApplyAsync(IEnumerable<Ipv4Route> routes, CancellationToken token)
|
||
|
|
{
|
||
|
|
if (File.Exists(stateFile)) throw new IOException("上次网络恢复未完成,请先恢复后再连接。");
|
||
|
|
var state = new State();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
foreach (var route in routes)
|
||
|
|
{
|
||
|
|
token.ThrowIfCancellationRequested();
|
||
|
|
route.Validate();
|
||
|
|
if (table.Snapshot().Any(route.SamePath)) continue;
|
||
|
|
state.Routes.Add(route);
|
||
|
|
Save(state);
|
||
|
|
await table.AddAsync(route, token).ConfigureAwait(false);
|
||
|
|
if (!table.Snapshot().Any(route.SamePath))
|
||
|
|
throw new IOException($"新建路由未生效:{route.Destination} IF {route.InterfaceIndex};实际记录:" +
|
||
|
|
JsonSerializer.Serialize(table.Snapshot().Where(item => item.Destination == route.Destination)));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
catch (Exception original)
|
||
|
|
{
|
||
|
|
using var rollback = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
||
|
|
try { await RestoreAsync(rollback.Token).ConfigureAwait(false); }
|
||
|
|
catch (Exception recovery) { throw new AggregateException("连接失败,仍有网络恢复记录待重试。", original, recovery); }
|
||
|
|
throw;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal async Task RestoreAsync(CancellationToken token)
|
||
|
|
{
|
||
|
|
if (!File.Exists(stateFile)) return;
|
||
|
|
var state = JsonSerializer.Deserialize<State>(File.ReadAllText(stateFile))
|
||
|
|
?? throw new InvalidDataException("无法读取路由恢复记录。");
|
||
|
|
if (state.SchemaVersion != 2) throw new InvalidDataException("未知路由恢复格式。");
|
||
|
|
var errors = new List<Exception>();
|
||
|
|
// Default split routes were created last and must be removed first.
|
||
|
|
foreach (var route in state.Routes.ToArray().Reverse())
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
route.Validate();
|
||
|
|
if (table.Snapshot().Any(route.SamePath))
|
||
|
|
await table.DeleteAsync(route, token).ConfigureAwait(false);
|
||
|
|
if (table.Snapshot().Any(route.SamePath)) throw new IOException("路由尚未撤销。");
|
||
|
|
state.Routes.Remove(route);
|
||
|
|
Save(state);
|
||
|
|
}
|
||
|
|
catch (Exception error) { errors.Add(error); }
|
||
|
|
}
|
||
|
|
if (state.Routes.Count == 0) File.Delete(stateFile);
|
||
|
|
else throw new AggregateException("本地网络恢复未完成,记录已保留,稍后可重试。", errors);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal sealed class WindowsRouteTable : IRouteTable
|
||
|
|
{
|
||
|
|
// Documented MIB_IPFORWARDROW consists of 14 DWORDs (56 bytes).
|
||
|
|
[StructLayout(LayoutKind.Sequential)]
|
||
|
|
private struct Row
|
||
|
|
{
|
||
|
|
public uint Destination, Mask, Policy, NextHop, InterfaceIndex, Type, Protocol, Age,
|
||
|
|
NextHopAs, Metric1, Metric2, Metric3, Metric4, Metric5;
|
||
|
|
}
|
||
|
|
[DllImport("iphlpapi.dll")]
|
||
|
|
private static extern uint GetIpForwardTable(IntPtr table, ref uint size, [MarshalAs(UnmanagedType.Bool)] bool order);
|
||
|
|
|
||
|
|
public IReadOnlyList<Ipv4Route> Snapshot()
|
||
|
|
{
|
||
|
|
uint size = 0;
|
||
|
|
GetIpForwardTable(IntPtr.Zero, ref size, false);
|
||
|
|
for (var attempt = 0; attempt < 3; attempt++)
|
||
|
|
{
|
||
|
|
if (size is < 4 or > 16_000_000) throw new IOException("无法读取 Windows 路由表。");
|
||
|
|
var buffer = Marshal.AllocHGlobal((int)size);
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var result = GetIpForwardTable(buffer, ref size, false);
|
||
|
|
if (result == 122) continue;
|
||
|
|
if (result != 0) throw new Win32Exception((int)result);
|
||
|
|
var count = Marshal.ReadInt32(buffer);
|
||
|
|
var stride = Marshal.SizeOf<Row>();
|
||
|
|
if (count < 0 || 4L + count * stride > size) throw new IOException("Windows 路由表格式异常。");
|
||
|
|
var routes = new List<Ipv4Route>(count);
|
||
|
|
for (var i = 0; i < count; i++)
|
||
|
|
{
|
||
|
|
var row = Marshal.PtrToStructure<Row>(buffer + 4 + i * stride);
|
||
|
|
// Legacy GetIpForwardTable can report the interface's own
|
||
|
|
// address for DIRECT/on-link entries. route.exe and the
|
||
|
|
// modern Windows table use 0.0.0.0 for that same next hop.
|
||
|
|
routes.Add(new Ipv4Route(Address(row.Destination), Address(row.Mask),
|
||
|
|
row.Type == 3 ? "0.0.0.0" : Address(row.NextHop),
|
||
|
|
(int)row.InterfaceIndex, (int)Math.Min(row.Metric1, int.MaxValue)));
|
||
|
|
}
|
||
|
|
return routes;
|
||
|
|
}
|
||
|
|
finally { Marshal.FreeHGlobal(buffer); }
|
||
|
|
}
|
||
|
|
throw new IOException("Windows 路由表变化过快,请重试。");
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string Address(uint value) => new IPAddress(BitConverter.GetBytes(value)).ToString();
|
||
|
|
public Task AddAsync(Ipv4Route route, CancellationToken token)
|
||
|
|
{
|
||
|
|
route.Validate();
|
||
|
|
return NetworkCommand.RunAsync("route.exe", $"ADD {route.Destination} MASK {route.Mask} {route.NextHop} IF {route.InterfaceIndex} METRIC {route.Metric}", token);
|
||
|
|
}
|
||
|
|
public Task DeleteAsync(Ipv4Route route, CancellationToken token)
|
||
|
|
{
|
||
|
|
route.Validate();
|
||
|
|
return NetworkCommand.RunAsync("route.exe", $"DELETE {route.Destination} MASK {route.Mask} {route.NextHop} IF {route.InterfaceIndex}", token);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
internal static class NetworkCommand
|
||
|
|
{
|
||
|
|
internal static async Task RunAsync(string fileName, string arguments, CancellationToken token)
|
||
|
|
{
|
||
|
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||
|
|
deadline.CancelAfter(TimeSpan.FromSeconds(8));
|
||
|
|
using var process = new Process { StartInfo = new ProcessStartInfo {
|
||
|
|
FileName = fileName, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true,
|
||
|
|
RedirectStandardOutput = true, RedirectStandardError = true,
|
||
|
|
}};
|
||
|
|
try
|
||
|
|
{
|
||
|
|
process.Start();
|
||
|
|
var output = process.StandardOutput.ReadToEndAsync(deadline.Token);
|
||
|
|
var error = process.StandardError.ReadToEndAsync(deadline.Token);
|
||
|
|
await process.WaitForExitAsync(deadline.Token).ConfigureAwait(false);
|
||
|
|
var details = (await output.ConfigureAwait(false)) + (await error.ConfigureAwait(false));
|
||
|
|
if (process.ExitCode != 0) throw new IOException($"Windows 网络操作失败({fileName}, {process.ExitCode}):{details.Trim()}");
|
||
|
|
}
|
||
|
|
finally
|
||
|
|
{
|
||
|
|
try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { }
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|