2026-11-15 21:33:18 +08:00
using System.Net ;
using System.Text.Json ;
using System.Text.Json.Nodes ;
using System.Text.RegularExpressions ;
namespace UCVL.VPNPlus ;
// Minimal transport observations, not URL/history collection or an HTTP status classifier.
internal static class LearningPolicy
{
private static readonly Regex Failure = new ( @"proxy/freedom: failed to open connection to (?<network>tcp|udp):(?<target>\[[0-9a-fA-F:]+\]|[A-Za-z0-9._-]+):(?<port>\d{1,5})" , RegexOptions . Compiled | RegexOptions . IgnoreCase );
private static readonly Regex DirectAttempt = new ( @"app/dispatcher: (?:Hit route rule: \[[^\[\]\r\n]{1,200}\] so )?taking detour \[direct\] for \[tcp:(?<target>[A-Za-z0-9._-]+):443\]" , RegexOptions . Compiled );
// An attempt is only a hint for a separate direct TLS check, never failure evidence.
// Probe outbounds have a different tag, preventing recursive self-observation.
internal static LearningObservation ? ParseAttempt ( string line , string node , string scope )
{
if ( line . Length > 8192 ) return null ;
var match = DirectAttempt . Match ( line );
var target = match . Groups [ "target" ]. Value . TrimEnd ( '.' ). ToLowerInvariant ();
if (! match . Success || ! Allowed ( "domain" , target )) return null ;
return new () { Target = target , TargetType = "domain" , Port = 443 , Network = "tcp" , AccessKind = "http" , Node = node , Scope = scope };
}
internal static bool PublicIp ( IPAddress ip )
{
if ( ip . IsIPv4MappedToIPv6 ) return PublicIp ( ip . MapToIPv4 ());
var b = ip . GetAddressBytes ();
if ( b . Length != 4 ) return false ; // Do not automatically promote IPv6 without equivalent validation.
return b [ 0 ] is > 0 and < 224 && b [ 0 ] != 10 && b [ 0 ] != 127
&& !( b [ 0 ] == 100 && b [ 1 ] is >= 64 and <= 127 )
&& !( b [ 0 ] == 169 && b [ 1 ] == 254 ) && !( b [ 0 ] == 172 && b [ 1 ] is >= 16 and <= 31 )
&& !( b [ 0 ] == 192 && ( b [ 1 ] == 168 || b [ 1 ] == 0 || b [ 1 ] == 2 ))
&& !( b [ 0 ] == 198 && ( b [ 1 ] is 18 or 19 || b [ 1 ] == 51 && b [ 2 ] == 100 ))
&& !( b [ 0 ] == 203 && b [ 1 ] == 0 && b [ 2 ] == 113 );
}
internal static bool Allowed ( string kind , string target ) => IsValidTarget ( kind , target )
&& !( kind == "domain" && TailnetDnsPolicy . IsProtectedDomain ( target ));
private static bool IsValidTarget ( string kind , string target )
{
if ( kind == "ip" ) return IPAddress . TryParse ( target , out var ip ) && PublicIp ( ip );
if ( kind != "domain" || IPAddress . TryParse ( target , out _ ) || target . Length > 253 || ! target . Contains ( '.' )) return false ;
if ( target . Split ( '.' ). Any ( label => ! Regex . IsMatch ( label , "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$" ))) return false ;
return ! new [] { "toplc.cn" , "ucvl.cn" , "ucvl.net" , "local" , "localhost" , "lan" , "internal" , "home" , "invalid" , "test" , "example" , "arpa" , "onion" }
. Any ( suffix => target == suffix || target . EndsWith ( "." + suffix , StringComparison . Ordinal ));
}
internal static LearningObservation ? Parse ( string line , string node , string scope )
{
if ( line . Length > 8192 ) return null ;
var match = Failure . Match ( line );
if (! match . Success || ! int . TryParse ( match . Groups [ "port" ]. Value , out var port ) || port is < 1 or > 65535 ) return null ;
var target = match . Groups [ "target" ]. Value . Trim ( '[' , ']' ). TrimEnd ( '.' ). ToLowerInvariant ();
var type = IPAddress . TryParse ( target , out _ ) ? "ip" : "domain" ;
if (! Allowed ( type , target )) return null ;
var failure = line . Contains ( "timeout" , StringComparison . OrdinalIgnoreCase ) || line . Contains ( "timed out" , StringComparison . OrdinalIgnoreCase ) ? "timeout"
: line . Contains ( "reset" , StringComparison . OrdinalIgnoreCase ) ? "reset"
: line . Contains ( "lookup" , StringComparison . OrdinalIgnoreCase ) || line . Contains ( "dns" , StringComparison . OrdinalIgnoreCase ) ? "dns"
: line . Contains ( "unreachable" , StringComparison . OrdinalIgnoreCase ) ? "unreachable" : "other" ;
return new LearningObservation { Target = target , TargetType = type , Port = port ,
Network = match . Groups [ "network" ]. Value . ToLowerInvariant (), AccessKind = port is 80 or 443 ? "http" : "socket" ,
FailureKind = failure , Node = node , Scope = scope };
}
internal static string Merge ( string baseConfig , RoutingManifest manifest )
{
if ( manifest . Contract != 1 || ! Regex . IsMatch ( manifest . Revision , "^[0-9a-f]{64}$" ) || manifest . Rules . Count > 2048 )
throw new InvalidDataException ( "智能规则版本或容量无效。" );
var root = JsonNode . Parse ( baseConfig )!. AsObject ();
var rules = root [ "routing" ]?[ "rules" ]?. AsArray () ?? throw new InvalidDataException ( "缺少原路由。" );
// Server tags only the replaceable learned bank; preserve LAN/company/DNS/default rules.
for ( var i = rules . Count - 1 ; i >= 0 ; i --)
if ( rules [ i ]?[ "ruleTag" ]?. GetValue < string >() == "ucvl-learned" ) rules . RemoveAt ( i );
var domains = new JsonArray (); var ips = new JsonArray ();
foreach ( var entry in manifest . Rules )
{
if (! IsValidTarget ( entry . TargetType , entry . Target ) || entry . MatchMode is not ( "exact" or "suffix" )
|| entry . TargetType == "ip" && entry . MatchMode != "exact" ) throw new InvalidDataException ( "不安全的智能目标。" );
if ( entry . TargetType == "domain" && TailnetDnsPolicy . IsProtectedDomain ( entry . Target )) continue ;
if ( entry . TargetType == "domain" ) domains . Add (( entry . MatchMode == "suffix" ? "domain:" : "full:" ) + entry . Target );
else ips . Add ( entry . Target + "/32" );
}
// After private-address DIRECT. Never insert ahead of this safety boundary.
var insertion = rules . Count > 0 ? 1 : 0 ;
if ( ips . Count > 0 ) rules . Insert ( insertion , new JsonObject { [ "type" ] = "field" , [ "ip" ] = ips , [ "network" ] = "tcp" , [ "port" ] = "443" , [ "outboundTag" ] = "proxy" , [ "ruleTag" ] = "ucvl-learned" });
if ( domains . Count > 0 ) rules . Insert ( insertion , new JsonObject { [ "type" ] = "field" , [ "domain" ] = domains , [ "network" ] = "tcp" , [ "port" ] = "443" , [ "outboundTag" ] = "proxy" , [ "ruleTag" ] = "ucvl-learned" });
return root . ToJsonString ();
}
internal static string DirectFirst ( string baseConfig )
{
var root = JsonNode . Parse ( baseConfig )!. AsObject ();
if ( root [ "routing" ]?[ "rules" ] is JsonArray rules )
for ( var i = rules . Count - 1 ; i >= 0 ; i --)
{
var rule = rules [ i ]!. AsObject ();
if ( rule [ "ruleTag" ]?. GetValue < string >() == "ucvl-learned" || rule [ "outboundTag" ]?. GetValue < string >() == "proxy"
&& ( rule [ "domain" ] is not null || rule [ "ip" ] is not null )
&& rule . All ( pair => pair . Key is "type" or "domain" or "ip" or "outboundTag" or "ruleTag" ))
rules . RemoveAt ( i ); // Shared/manual destination lists are hints in direct-first smart mode.
}
return root . ToJsonString ();
}
}
internal sealed class RoutingManifest
{
[System.Text.Json.Serialization.JsonPropertyName("contract")] public int Contract { get ; init ; }
[System.Text.Json.Serialization.JsonPropertyName("mode")] public string Mode { get ; init ; } = "" ;
[System.Text.Json.Serialization.JsonPropertyName("revision")] public string Revision { get ; init ; } = "" ;
[System.Text.Json.Serialization.JsonPropertyName("rules")] public List < RoutingTarget > Rules { get ; init ; } = [];
}
internal sealed class RoutingTarget
{
[System.Text.Json.Serialization.JsonPropertyName("target_type")] public string TargetType { get ; init ; } = "" ;
[System.Text.Json.Serialization.JsonPropertyName("target")] public string Target { get ; init ; } = "" ;
[System.Text.Json.Serialization.JsonPropertyName("match_mode")] public string MatchMode { get ; init ; } = "" ;
}