126 lines
4.7 KiB
C#
126 lines
4.7 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
|
|
namespace UCVL.VPNPlus;
|
|
|
|
internal static class LearningStore
|
|
{
|
|
private static readonly object Sync = new();
|
|
private static readonly Dictionary<string, Queue<DateTimeOffset>> Failures = new(StringComparer.OrdinalIgnoreCase);
|
|
private static readonly TimeSpan FailureWindow = TimeSpan.FromMinutes(5);
|
|
private static readonly TimeSpan LocalRuleLifetime = TimeSpan.FromDays(7);
|
|
|
|
private sealed class LearnedTarget
|
|
{
|
|
public string TargetType { get; init; } = "domain";
|
|
public string Target { get; init; } = "";
|
|
public DateTimeOffset CreatedAt { get; init; }
|
|
public DateTimeOffset ExpiresAt { get; init; }
|
|
}
|
|
|
|
internal static bool RecordFailureAndLearn(LearningObservation observation)
|
|
{
|
|
if (!IsAllowed(observation.TargetType, observation.Target)) return false;
|
|
lock (Sync)
|
|
{
|
|
var targets = LoadUnsafe();
|
|
var now = DateTimeOffset.UtcNow;
|
|
if (targets.Any(item =>
|
|
item.ExpiresAt > now
|
|
&& item.TargetType == observation.TargetType
|
|
&& string.Equals(item.Target, observation.Target, StringComparison.OrdinalIgnoreCase)))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var key = $"{observation.TargetType}:{observation.Target}";
|
|
if (!Failures.TryGetValue(key, out var queue))
|
|
{
|
|
queue = new Queue<DateTimeOffset>();
|
|
Failures[key] = queue;
|
|
}
|
|
while (queue.Count > 0 && now - queue.Peek() > FailureWindow) queue.Dequeue();
|
|
queue.Enqueue(now);
|
|
if (queue.Count < 3) return false;
|
|
|
|
queue.Clear();
|
|
targets.RemoveAll(item => item.ExpiresAt <= now);
|
|
targets.Add(new LearnedTarget
|
|
{
|
|
TargetType = observation.TargetType,
|
|
Target = observation.Target,
|
|
CreatedAt = now,
|
|
ExpiresAt = now + LocalRuleLifetime,
|
|
});
|
|
SaveUnsafe(targets);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
internal static IReadOnlyList<(string TargetType, string Target)> GetActiveTargets()
|
|
{
|
|
lock (Sync)
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
var targets = LoadUnsafe();
|
|
var active = targets.Where(item => item.ExpiresAt > now && IsAllowed(item.TargetType, item.Target)).ToList();
|
|
if (active.Count != targets.Count) SaveUnsafe(active);
|
|
return active.Select(item => (item.TargetType, item.Target)).ToList();
|
|
}
|
|
}
|
|
|
|
private static List<LearnedTarget> LoadUnsafe()
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(AppPaths.LearnedRoutesFile)) return [];
|
|
return JsonSerializer.Deserialize<List<LearnedTarget>>(File.ReadAllText(AppPaths.LearnedRoutesFile)) ?? [];
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
AppPaths.WriteError(exception);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
private static void SaveUnsafe(List<LearnedTarget> targets)
|
|
{
|
|
AppPaths.EnsureDirectory();
|
|
File.WriteAllText(AppPaths.LearnedRoutesFile, JsonSerializer.Serialize(targets));
|
|
}
|
|
|
|
private static bool IsAllowed(string targetType, string target)
|
|
{
|
|
if (targetType == "ip")
|
|
{
|
|
return IPAddress.TryParse(target, out var address)
|
|
&& !IPAddress.IsLoopback(address)
|
|
&& !IsPrivate(address);
|
|
}
|
|
if (targetType != "domain") return false;
|
|
var domain = target.Trim().TrimEnd('.').ToLowerInvariant();
|
|
if (!domain.Contains('.') || domain is "toplc.cn" or "ucvl.cn" or "ucvl.net" or "localhost") return false;
|
|
return !domain.EndsWith(".local", StringComparison.Ordinal)
|
|
&& !domain.EndsWith(".toplc.cn", StringComparison.Ordinal)
|
|
&& !domain.EndsWith(".ucvl.cn", StringComparison.Ordinal)
|
|
&& !domain.EndsWith(".ucvl.net", StringComparison.Ordinal);
|
|
}
|
|
|
|
private static bool IsPrivate(IPAddress address)
|
|
{
|
|
if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
|
|
{
|
|
var bytes = address.GetAddressBytes();
|
|
return bytes[0] == 10
|
|
|| bytes[0] == 127
|
|
|| bytes[0] == 0
|
|
|| (bytes[0] == 169 && bytes[1] == 254)
|
|
|| (bytes[0] == 172 && bytes[1] is >= 16 and <= 31)
|
|
|| (bytes[0] == 192 && bytes[1] == 168)
|
|
|| bytes[0] >= 224;
|
|
}
|
|
return address.IsIPv6LinkLocal || address.IsIPv6Multicast || address.Equals(IPAddress.IPv6Loopback)
|
|
|| (address.GetAddressBytes()[0] & 0xfe) == 0xfc;
|
|
}
|
|
}
|