Quellcode durchsuchen

FastGithubConfig注册为服务

xljiulang vor 4 Jahren
Ursprung
Commit
8df6d3d368

+ 1 - 1
FastGithub.Core/DomainMatch.cs

@@ -5,7 +5,7 @@ namespace FastGithub
     /// <summary>
     /// 域名匹配
     /// </summary>
-    sealed class DomainMatch
+    public class DomainMatch
     {
         private readonly Regex regex;
         private readonly string domainPattern;

+ 5 - 1
FastGithub.Core/FastGithub.Core.csproj

@@ -3,6 +3,10 @@
 	<PropertyGroup>
 		<TargetFramework>net5.0</TargetFramework>
 		<RootNamespace>FastGithub</RootNamespace>
-	</PropertyGroup>  
+	</PropertyGroup>
+
+	<ItemGroup> 
+	  <PackageReference Include="Microsoft.Extensions.Options" Version="5.0.0" />
+	</ItemGroup>  
   
 </Project>

+ 41 - 14
FastGithub.Core/FastGithubConfig.cs

@@ -1,4 +1,6 @@
-using System.Collections.Generic;
+using Microsoft.Extensions.Options;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
 using System.Diagnostics.CodeAnalysis;
 using System.Linq;
 using System.Net;
@@ -10,27 +12,51 @@ namespace FastGithub
     /// </summary>
     public class FastGithubConfig
     {
-        private readonly Dictionary<DomainMatch, DomainConfig> domainConfigs;
+        /// <summary>
+        /// 域名与配置缓存
+        /// </summary>
+        [AllowNull]
+        private ConcurrentDictionary<string, DomainConfig?> domainConfigCache;
+
 
         /// <summary>
         /// 获取信任dns
         /// </summary>
-        public IPEndPoint TrustedDns { get; }
+        [AllowNull]
+        public IPEndPoint TrustedDns { get; private set; }
 
         /// <summary>
         /// 获取非信任dns
         /// </summary>
-        public IPEndPoint UnTrustedDns { get; }
+        [AllowNull]
+        public IPEndPoint UnTrustedDns { get; private set; }
+
+        /// <summary>
+        /// 获取域名配置
+        /// </summary>
+        [AllowNull]
+        public Dictionary<DomainMatch, DomainConfig> DomainConfigs { get; private set; }
 
         /// <summary>
         /// FastGithub配置
+        /// </summary> 
+        /// <param name="options"></param>
+        public FastGithubConfig(IOptionsMonitor<FastGithubOptions> options)
+        {
+            this.Init(options.CurrentValue);
+            options.OnChange(opt => this.Init(opt));
+        }
+
+        /// <summary>
+        /// 初始化
         /// </summary>
         /// <param name="options"></param>
-        public FastGithubConfig(FastGithubOptions options)
+        private void Init(FastGithubOptions options)
         {
+            this.domainConfigCache = new ConcurrentDictionary<string, DomainConfig?>();
             this.TrustedDns = options.TrustedDns.ToIPEndPoint();
             this.UnTrustedDns = options.UntrustedDns.ToIPEndPoint();
-            this.domainConfigs = options.DomainConfigs.ToDictionary(kv => new DomainMatch(kv.Key), kv => kv.Value);
+            this.DomainConfigs = options.DomainConfigs.ToDictionary(kv => new DomainMatch(kv.Key), kv => kv.Value);
         }
 
         /// <summary>
@@ -40,24 +66,25 @@ namespace FastGithub
         /// <returns></returns>
         public bool IsMatch(string domain)
         {
-            return this.domainConfigs.Keys.Any(item => item.IsMatch(domain));
+            return this.TryGetDomainConfig(domain, out _);
         }
 
         /// <summary>
         /// 尝试获取域名配置
         /// </summary>
         /// <param name="domain"></param>
-        /// <param name="domainConfig"></param>
+        /// <param name="value"></param>
         /// <returns></returns>
-        public bool TryGetDomainConfig(string domain, [MaybeNullWhen(false)] out DomainConfig domainConfig)
+        public bool TryGetDomainConfig(string domain, [MaybeNullWhen(false)] out DomainConfig value)
         {
-            var key = this.domainConfigs.Keys.FirstOrDefault(item => item.IsMatch(domain));
-            if (key == null)
+            value = this.domainConfigCache.GetOrAdd(domain, GetDomainConfig);
+            return value != null;
+
+            DomainConfig? GetDomainConfig(string domain)
             {
-                domainConfig = default;
-                return false;
+                var key = this.DomainConfigs.Keys.FirstOrDefault(item => item.IsMatch(domain));
+                return key == null ? null : this.DomainConfigs[key];
             }
-            return this.domainConfigs.TryGetValue(key, out domainConfig);
         }
     }
 }

+ 0 - 21
FastGithub.Core/FastGithubOptions.cs

@@ -21,26 +21,5 @@ namespace FastGithub
         /// 代理的域名配置
         /// </summary>
         public Dictionary<string, DomainConfig> DomainConfigs { get; set; } = new();
-
-
-
-        /// <summary>
-        /// 初始化选项为配置
-        /// </summary>
-        /// <exception cref="FastGithubException"></exception>
-        public void InitConfig()
-        {
-            this.fastGithubConfig = new FastGithubConfig(this);
-        }
-
-        /// <summary>
-        /// 配置
-        /// </summary>
-        private FastGithubConfig? fastGithubConfig;
-
-        /// <summary>
-        /// 获取配置
-        /// </summary>
-        public FastGithubConfig Config => this.fastGithubConfig!;
     }
 }

+ 7 - 5
FastGithub.Dns/DnsServerHostedService.cs

@@ -19,7 +19,7 @@ namespace FastGithub.Dns
     sealed class DnsServerHostedService : BackgroundService
     {
         private readonly RequestResolver requestResolver;
-        private readonly IOptionsMonitor<FastGithubOptions> options;
+        private readonly FastGithubConfig fastGithubConfig;
         private readonly ILogger<DnsServerHostedService> logger;
 
         private readonly Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -28,21 +28,23 @@ namespace FastGithub.Dns
 
         [SupportedOSPlatform("windows")]
         [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache", SetLastError = true)]
-        private static extern uint DnsFlushResolverCache();
+        private static extern void DnsFlushResolverCache();
 
         /// <summary>
         /// dns后台服务
         /// </summary>
         /// <param name="requestResolver"></param>
+        /// <param name="fastGithubConfig"></param>
         /// <param name="options"></param>
         /// <param name="logger"></param>
         public DnsServerHostedService(
             RequestResolver requestResolver,
+            FastGithubConfig fastGithubConfig,
             IOptionsMonitor<FastGithubOptions> options,
             ILogger<DnsServerHostedService> logger)
         {
             this.requestResolver = requestResolver;
-            this.options = options;
+            this.fastGithubConfig = fastGithubConfig;
             this.logger = logger;
             options.OnChange(opt => FlushResolverCache());
         }
@@ -80,7 +82,7 @@ namespace FastGithub.Dns
             }
 
             this.logger.LogInformation("dns服务启动成功");
-            var secondary = options.CurrentValue.Config.UnTrustedDns.Address;
+            var secondary = this.fastGithubConfig.UnTrustedDns.Address;
             this.dnsAddresses = this.SetNameServers(IPAddress.Loopback, secondary);
             FlushResolverCache();
 
@@ -108,7 +110,7 @@ namespace FastGithub.Dns
                 {
                     if (i == 0)
                     {
-                        throw;
+                        throw new FastGithubException($"无法监听{localEndPoint},{localEndPoint.Port}的udp端口已被其它程序占用");
                     }
                     await Task.Delay(delay, cancellationToken);
                 }

+ 19 - 7
FastGithub.Dns/RequestResolver.cs

@@ -16,23 +16,34 @@ namespace FastGithub.Dns
     /// </summary> 
     sealed class RequestResolver : IRequestResolver
     {
+        private IRequestResolver requestResolver;
+
         private readonly TimeSpan ttl = TimeSpan.FromMinutes(1d);
-        private readonly IRequestResolver untrustedResolver;
-        private readonly IOptionsMonitor<FastGithubOptions> options;
+        private readonly FastGithubConfig fastGithubConfig;
         private readonly ILogger<RequestResolver> logger;
 
         /// <summary>
         /// dns解析者
-        /// </summary> 
+        /// </summary>
+        /// <param name="fastGithubConfig"></param>
         /// <param name="options"></param>
         /// <param name="logger"></param>
         public RequestResolver(
+            FastGithubConfig fastGithubConfig,
             IOptionsMonitor<FastGithubOptions> options,
             ILogger<RequestResolver> logger)
         {
-            this.options = options;
+            this.fastGithubConfig = fastGithubConfig;
             this.logger = logger;
-            this.untrustedResolver = new UdpRequestResolver(options.CurrentValue.Config.TrustedDns);
+
+            this.requestResolver = new UdpRequestResolver(fastGithubConfig.UnTrustedDns);
+            options.OnChange(opt => DnsConfigChanged(opt.UntrustedDns));
+
+            void DnsConfigChanged(DnsConfig config)
+            {
+                var dns = config.ToIPEndPoint();
+                this.requestResolver = new UdpRequestResolver(dns);
+            }
         }
 
         /// <summary>
@@ -55,8 +66,9 @@ namespace FastGithub.Dns
                 return response;
             }
 
+            // 解析匹配的域名指向本机ip
             var domain = question.Name;
-            if (this.options.CurrentValue.Config.IsMatch(domain.ToString()) == true)
+            if (this.fastGithubConfig.IsMatch(domain.ToString()) == true)
             {
                 var localAddress = remoteEndPointRequest.GetLocalAddress() ?? IPAddress.Loopback;
                 var record = new IPAddressResourceRecord(domain, localAddress, this.ttl);
@@ -66,7 +78,7 @@ namespace FastGithub.Dns
                 return response;
             }
 
-            return await this.untrustedResolver.Resolve(request, cancellationToken);
+            return await this.requestResolver.Resolve(request, cancellationToken);
         }
     }
 }

+ 14 - 13
FastGithub.ReverseProxy/DomainResolver.cs

@@ -1,6 +1,5 @@
 using DNS.Client;
 using Microsoft.Extensions.Caching.Memory;
-using Microsoft.Extensions.Options;
 using System;
 using System.Linq;
 using System.Net;
@@ -10,24 +9,25 @@ using System.Threading.Tasks;
 namespace FastGithub.ReverseProxy
 {
     /// <summary>
-    /// 受信任的域名解析器
+    /// 域名解析器
     /// </summary> 
     sealed class DomainResolver
     {
         private readonly IMemoryCache memoryCache;
+        private readonly FastGithubConfig fastGithubConfig;
         private readonly TimeSpan cacheTimeSpan = TimeSpan.FromSeconds(10d);
-        private readonly IOptionsMonitor<FastGithubOptions> options;
 
         /// <summary>
-        /// 受信任的域名解析器
-        /// </summary> 
-        /// <param name="options"></param>
+        /// 域名解析器
+        /// </summary>
+        /// <param name="memoryCache"></param>
+        /// <param name="fastGithubConfig"></param>
         public DomainResolver(
             IMemoryCache memoryCache,
-            IOptionsMonitor<FastGithubOptions> options)
+            FastGithubConfig fastGithubConfig)
         {
             this.memoryCache = memoryCache;
-            this.options = options;
+            this.fastGithubConfig = fastGithubConfig;
         }
 
         /// <summary>
@@ -55,22 +55,22 @@ namespace FastGithub.ReverseProxy
         /// <returns></returns>
         private async Task<IPAddress> LookupAsync(string domain, CancellationToken cancellationToken)
         {
-            var endpoint = this.options.CurrentValue.TrustedDns.ToIPEndPoint();
             try
             {
-                var dnsClient = new DnsClient(endpoint);
+                var dns = this.fastGithubConfig.TrustedDns;
+                var dnsClient = new DnsClient(dns);
                 var addresses = await dnsClient.Lookup(domain, DNS.Protocol.RecordType.A, cancellationToken);
                 var address = addresses?.FirstOrDefault();
                 if (address == null)
                 {
-                    throw new FastGithubException($"dns({endpoint}):解析不到{domain}的ip");
+                    throw new FastGithubException($"dns({dns}):解析不到{domain}的ip");
                 }
 
                 // 受干扰的dns,常常返回127.0.0.1来阻断请求
                 // 如果解析到的ip为本机ip,会产生反向代理请求死循环
                 if (address.Equals(IPAddress.Loopback))
                 {
-                    throw new FastGithubException($"dns({endpoint}):解析{domain}被干扰为{address}");
+                    throw new FastGithubException($"dns({dns}):解析{domain}被干扰为{address}");
                 }
                 return address;
             }
@@ -80,7 +80,8 @@ namespace FastGithub.ReverseProxy
             }
             catch (Exception ex)
             {
-                throw new FastGithubException($"dns({endpoint}):{ex.Message}", ex);
+                var dns = this.fastGithubConfig.TrustedDns;
+                throw new FastGithubException($"dns({dns}):{ex.Message}", ex);
             }
         }
     }

+ 4 - 5
FastGithub.ReverseProxy/ReverseProxyMiddleware.cs

@@ -1,5 +1,4 @@
 using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Options;
 using System;
 using System.Net.Http;
 using System.Threading.Tasks;
@@ -15,18 +14,18 @@ namespace FastGithub.ReverseProxy
         private readonly IHttpForwarder httpForwarder;
         private readonly SniHttpClientHanlder sniHttpClientHanlder;
         private readonly NoSniHttpClientHanlder noSniHttpClientHanlder;
-        private readonly IOptionsMonitor<FastGithubOptions> options;
+        private readonly FastGithubConfig fastGithubConfig;
 
         public ReverseProxyMiddleware(
             IHttpForwarder httpForwarder,
             SniHttpClientHanlder sniHttpClientHanlder,
             NoSniHttpClientHanlder noSniHttpClientHanlder,
-            IOptionsMonitor<FastGithubOptions> options)
+            FastGithubConfig fastGithubConfig)
         {
             this.httpForwarder = httpForwarder;
             this.sniHttpClientHanlder = sniHttpClientHanlder;
             this.noSniHttpClientHanlder = noSniHttpClientHanlder;
-            this.options = options;
+            this.fastGithubConfig = fastGithubConfig;
         }
 
         /// <summary>
@@ -37,7 +36,7 @@ namespace FastGithub.ReverseProxy
         public async Task InvokeAsync(HttpContext context)
         {
             var host = context.Request.Host.Host;
-            if (this.options.CurrentValue.Config.TryGetDomainConfig(host, out var domainConfig) == false)
+            if (this.fastGithubConfig.TryGetDomainConfig(host, out var domainConfig) == false)
             {
                 await context.Response.WriteAsJsonAsync(new
                 {

+ 6 - 8
FastGithub/Program.cs

@@ -32,14 +32,12 @@ namespace FastGithub
                 })
                 .ConfigureServices((ctx, services) =>
                 {
-                    services
-                        .AddAppUpgrade()
-                        .AddDnsServer()
-                        .AddReverseProxy()
-                        .AddDnscryptProxy()
-                        .AddOptions<FastGithubOptions>()
-                            .Bind(ctx.Configuration.GetSection(nameof(FastGithub)))
-                            .PostConfigure(opt => opt.InitConfig());
+                    services.AddAppUpgrade();
+                    services.AddDnsServer();
+                    services.AddReverseProxy();
+                    services.AddDnscryptProxy();
+                    services.AddSingleton<FastGithubConfig>();
+                    services.Configure<FastGithubOptions>(ctx.Configuration.GetSection(nameof(FastGithub)));
                 })
                 .ConfigureWebHostDefaults(web =>
                 {