using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Json; namespace UCVL.VPNPlus; // DERP relays change independently of the client release. Read only the // already-installed Tailscale client's current map; never manufacture or cache // relay addresses in the application. internal static class DerpRouteDiscovery { private const int MaxMapCharacters = 256 * 1024; private const int MaxRelayAddresses = 64; internal static IReadOnlyList ParsePublicIpv4Addresses(string json) { if (json.Length > MaxMapCharacters) throw new InvalidDataException("DERP Map 超过安全大小限制。"); using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 24 }); if (!document.RootElement.TryGetProperty("Regions", out var regions) || regions.ValueKind != JsonValueKind.Object) throw new InvalidDataException("DERP Map 缺少 Regions。"); var result = new HashSet(); foreach (var region in regions.EnumerateObject()) { if (!region.Value.TryGetProperty("Nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array) continue; foreach (var node in nodes.EnumerateArray()) { if (!node.TryGetProperty("IPv4", out var value) || value.ValueKind != JsonValueKind.String) continue; var text = value.GetString()?.Trim(); if (!IPAddress.TryParse(text, out var address) || address.AddressFamily != AddressFamily.InterNetwork || !IsPublicIpv4(address)) continue; result.Add(address); if (result.Count > MaxRelayAddresses) throw new InvalidDataException("DERP Map 节点数量超过安全限制。"); } } return result.OrderBy(address => address.ToString(), StringComparer.Ordinal).ToArray(); } internal static async Task> DiscoverAsync(CancellationToken cancellationToken) { var executable = InstalledExecutable(); if (executable is null) return []; using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); deadline.CancelAfter(TimeSpan.FromSeconds(2)); Process? process = null; try { process = new Process { StartInfo = new ProcessStartInfo { FileName = executable, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8, } }; process.StartInfo.ArgumentList.Add("debug"); process.StartInfo.ArgumentList.Add("derp-map"); if (!process.Start()) return []; var stdout = ReadBoundedAsync(process.StandardOutput, deadline.Token); var stderr = ReadBoundedAsync(process.StandardError, deadline.Token); await process.WaitForExitAsync(deadline.Token).ConfigureAwait(false); var map = await stdout.ConfigureAwait(false); _ = await stderr.ConfigureAwait(false); return process.ExitCode == 0 ? ParsePublicIpv4Addresses(map) : []; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception error) when (error is OperationCanceledException or IOException or InvalidDataException or JsonException or System.ComponentModel.Win32Exception) { AppPaths.WriteLog($"DERP Map 未能读取,本次不添加未知中继旁路:{error.GetType().Name}"); return []; } finally { if (process is not null) { try { if (!process.HasExited) process.Kill(true); } catch { } process.Dispose(); } } } private static string? InstalledExecutable() { var roots = new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), }; foreach (var root in roots.Where(root => !string.IsNullOrWhiteSpace(root))) { var candidate = Path.Combine(root, "Tailscale", "tailscale.exe"); if (File.Exists(candidate)) return candidate; } return null; } private static async Task ReadBoundedAsync(StreamReader reader, CancellationToken cancellationToken) { var buffer = new char[4096]; var value = new StringBuilder(); while (true) { var count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); if (count == 0) return value.ToString(); if (value.Length + count > MaxMapCharacters) throw new InvalidDataException("DERP Map 输出超过安全大小限制。"); value.Append(buffer, 0, count); } } private static bool IsPublicIpv4(IPAddress address) { var bytes = address.GetAddressBytes(); if (bytes[0] is 0 or 10 or 127 || bytes[0] >= 224) return false; if (bytes[0] == 100 && bytes[1] is >= 64 and <= 127) return false; if (bytes[0] == 169 && bytes[1] == 254) return false; if (bytes[0] == 172 && bytes[1] is >= 16 and <= 31) return false; if (bytes[0] == 192 && bytes[1] == 168) return false; if (bytes[0] == 198 && bytes[1] is 18 or 19) return false; if (bytes[0] == 192 && bytes[1] == 0 && bytes[2] is 0 or 2) return false; if (bytes[0] == 198 && bytes[1] == 51 && bytes[2] == 100) return false; if (bytes[0] == 203 && bytes[1] == 0 && bytes[2] == 113) return false; return !address.Equals(IPAddress.Broadcast); } }