2026-11-15 21:33:18 +08:00
using System.Diagnostics ;
using System.Text.Json.Nodes ;
namespace UCVL.VPNPlus ;
// Only proxy-domain DNS is sent through the tunnel. Existing LAN/Tailscale
// namespaces and physical adapter DNS settings are not replaced.
internal static class ProxyDnsPolicy
{
internal const string Owner = "UCVL.VPNPlus.ProxyDNS.v1" ;
private static string Journal => Path . Combine ( AppPaths . DataDirectory , "proxy-dns-owned.json" );
private static readonly string [] SeedDomains = [ "chatgpt.com" , "openai.com" , "oaistatic.com" , "oaiusercontent.com" , "google.com" , "googleapis.com" , "googleusercontent.com" , "gstatic.com" , "googlevideo.com" , "youtube.com" , "youtu.be" , "ytimg.com" , "ggpht.com" ];
internal static string [] Namespaces ( string config , IEnumerable <( string TargetType , string Target )> activeTargets )
{
var domains = new HashSet < string >( SeedDomains , StringComparer . OrdinalIgnoreCase );
var exact = new HashSet < string >( StringComparer . OrdinalIgnoreCase );
var root = JsonNode . Parse ( config )!;
if ( root [ "routing" ]?[ "rules" ] is JsonArray rules )
foreach ( var rule in rules )
if ( rule ?[ "outboundTag" ]?. GetValue < string >() == "proxy" && rule [ "domain" ] is JsonArray names )
foreach ( var name in names )
{
var text = name ?. GetValue < string >() ?? "" ;
if ( text . StartsWith ( "domain:" )) domains . Add ( text [ 7. .]);
if ( text . StartsWith ( "full:" )) exact . Add ( text [ 5. .]);
}
foreach ( var item in activeTargets . Where ( t => t . TargetType == "domain" )) exact . Add ( item . Target );
static bool Safe ( string value ) => value . Length <= 253 && value . Contains ( '.' )
&& value . All ( c => char . IsAsciiLetterOrDigit ( c ) || c is '.' or '-' )
&& Uri . CheckHostName ( value ) == UriHostNameType . Dns ;
// Never send the DNS required to reach our own transport over that transport.
return domains . Where ( d => Safe ( d ) && ! TailnetDnsPolicy . IsProtectedSuffix ( d ))
. SelectMany ( d => new [] { d , "." + d })
. Concat ( exact . Where ( d => Safe ( d ) && ! TailnetDnsPolicy . IsProtectedDomain ( d )))
. Distinct ( StringComparer . OrdinalIgnoreCase ). Order (). ToArray ();
}
internal static async Task EnableAsync ( string config , CancellationToken token )
{
var names = Namespaces ( config , LearningStore . GetActiveTargets ());
if ( names . Length == 0 ) return ;
AppPaths . EnsureDirectory ();
// Intent first; a crash between policy creation and journal completion
// is still recovered by the unique ownership marker on next startup.
File . WriteAllText ( Journal , System . Text . Json . JsonSerializer . Serialize ( new { owner = Owner , names }));
var values = string . Join ( "," , names . Select ( n => "'" + n + "'" ));
await RunAsync ( $"$names=@({values}); $others=@(Get-DnsClientNrptRule | Where-Object {{$_.Comment -ne '{Owner}'}}); " +
"foreach ($r in $others) { foreach ($n in $r.Namespace) { if ($names -contains $n) { throw 'A managed DNS namespace already exists; it was not changed.' } } }; " +
$"Add-DnsClientNrptRule -Namespace $names -NameServers '8.8.8.8','1.1.1.1' -Comment '{Owner}' -DisplayName 'UCVL proxy domain DNS' | Out-Null; Clear-DnsClientCache" , token );
AppPaths . WriteLog ( $"已为 {names.Length} 个代理域名范围启用隧道 DNS;保留现有内网/Tailscale DNS。" );
}
internal static async Task RestoreAsync ( CancellationToken token )
{
// No journal means this client has never installed a policy. On a
// process crash the intent journal is retained until cleanup succeeds.
if (! File . Exists ( Journal )) return ;
await RunAsync ( $"Get-DnsClientNrptRule | Where-Object {{$_.Comment -eq '{Owner}'}} | ForEach-Object {{ Remove-DnsClientNrptRule -Name $_.Name -Force }}; Clear-DnsClientCache" , token );
File . Delete ( Journal );
}
private static async Task RunAsync ( string script , CancellationToken token )
{
using var process = new Process { StartInfo = SystemPowerShell . CreateStartInfo ( "$ErrorActionPreference='Stop'; " + script ) };
using var timeout = CancellationTokenSource . CreateLinkedTokenSource ( token ); timeout . CancelAfter ( TimeSpan . FromSeconds ( 20 ));
process . Start ();
try
{
var output = process . StandardOutput . ReadToEndAsync ( timeout . Token );
var error = process . StandardError . ReadToEndAsync ( timeout . Token );
await process . WaitForExitAsync ( timeout . Token ); await output ;
if ( process . ExitCode != 0 ) throw new IOException ( "代理域名 DNS 配置失败:" + await error );
}
finally { try { if (! process . HasExited ) process . Kill (); } catch { } }
}
}