Jelajahi Sumber

移除ListenConfig

老九 4 tahun lalu
induk
melakukan
0811f175c8

+ 0 - 5
FastGithub.Configuration/FastGithubOptions.cs

@@ -8,11 +8,6 @@ namespace FastGithub.Configuration
     /// </summary>
     public class FastGithubOptions
     {
-        /// <summary>
-        /// 监听配置
-        /// </summary>
-        public ListenConfig Listen { get; set; } = new ListenConfig();
-
         /// <summary>
         /// 回退的dns
         /// </summary>

+ 0 - 18
FastGithub.Configuration/ListenConfig.cs

@@ -1,18 +0,0 @@
-namespace FastGithub.Configuration
-{
-    /// <summary>
-    /// 监听配置
-    /// </summary>
-    public record ListenConfig
-    {
-        /// <summary>
-        /// 监听的ssh端口
-        /// </summary>
-        public int SshPort { get; init; } = 22;
-
-        /// <summary>
-        /// 监听的dns端口
-        /// </summary>
-        public int DnsPort { get; init; } = 53;
-    }
-}

+ 8 - 36
FastGithub.Dns/DnsOverUdpHostedService.cs

@@ -17,15 +17,15 @@ namespace FastGithub.Dns
     {
         private readonly DnsOverUdpServer dnsOverUdpServer;
         private readonly IEnumerable<IConflictValidator> conflictValidators;
-        private readonly IOptionsMonitor<FastGithubOptions> options;
         private readonly ILogger<DnsOverUdpHostedService> logger;
 
+
         /// <summary>
         /// dns后台服务
         /// </summary>
         /// <param name="dnsOverUdpServer"></param>
         /// <param name="conflictValidators"></param>
-        /// <param name="options"></param> 
+        /// <param name="options"></param>
         /// <param name="logger"></param>
         public DnsOverUdpHostedService(
             DnsOverUdpServer dnsOverUdpServer,
@@ -35,9 +35,7 @@ namespace FastGithub.Dns
         {
             this.dnsOverUdpServer = dnsOverUdpServer;
             this.conflictValidators = conflictValidators;
-            this.options = options;
             this.logger = logger;
-
             options.OnChange(opt => SystemDnsUtil.FlushResolverCache());
         }
 
@@ -48,26 +46,15 @@ namespace FastGithub.Dns
         /// <returns></returns>
         public override async Task StartAsync(CancellationToken cancellationToken)
         {
-            var dnsPort = this.options.CurrentValue.Listen.DnsPort;
-            this.dnsOverUdpServer.Bind(IPAddress.Any, dnsPort);
-            this.logger.LogInformation($"已监听udp端口{dnsPort},DNS服务启动完成");
-
-            const int STANDARD_DNS_PORT = 53;
-            if (dnsPort == STANDARD_DNS_PORT)
+            try
             {
-                try
-                {
-                    SystemDnsUtil.SetAsPrimitiveDns();
-                    SystemDnsUtil.FlushResolverCache();
-                }
-                catch (Exception ex)
-                {
-                    this.logger.LogWarning(ex.Message);
-                }
+                const int DNS_PORT = 53;
+                this.dnsOverUdpServer.Listen(IPAddress.Any, DNS_PORT);
+                this.logger.LogInformation($"已监听udp端口{DNS_PORT},DNS服务启动完成");
             }
-            else
+            catch (Exception ex)
             {
-                this.logger.LogWarning($"由于使用了非标准DNS端口{dnsPort},你需要将{nameof(FastGithub)}设置为标准DNS的上游");
+                this.logger.LogError($"DNS服务启动失败:{ex.Message}{Environment.NewLine}请配置系统或浏览器使用{nameof(FastGithub)}的DoH,或向系统hosts文件添加github相关域名的ip为127.0.0.1");
             }
 
             foreach (var item in this.conflictValidators)
@@ -96,21 +83,6 @@ namespace FastGithub.Dns
         public override Task StopAsync(CancellationToken cancellationToken)
         {
             this.dnsOverUdpServer.Dispose();
-            this.logger.LogInformation("DNS服务已停止");
-
-            try
-            {
-                SystemDnsUtil.RemoveFromPrimitiveDns();
-            }
-            catch (Exception ex)
-            {
-                this.logger.LogWarning(ex.Message);
-            }
-            finally
-            {
-                SystemDnsUtil.FlushResolverCache();
-            }
-
             return base.StopAsync(cancellationToken);
         }
     }

+ 35 - 10
FastGithub.Dns/DnsOverUdpServer.cs

@@ -19,6 +19,8 @@ namespace FastGithub.Dns
         private readonly Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         private readonly byte[] buffer = new byte[ushort.MaxValue];
 
+        private bool listened = false;
+
         /// <summary>
         /// dns服务器
         /// </summary>
@@ -33,12 +35,13 @@ namespace FastGithub.Dns
         }
 
         /// <summary>
-        /// 绑定地址和端口
+        /// 监听IP地址和端口
         /// </summary>
         /// <param name="address"></param>
         /// <param name="port"></param> 
-        /// <returns></returns>
-        public void Bind(IPAddress address, int port)
+        /// <exception cref="SocketException"></exception>
+        /// <exception cref="FastGithubException"></exception>
+        public void Listen(IPAddress address, int port)
         {
             if (OperatingSystem.IsWindows())
             {
@@ -56,17 +59,17 @@ namespace FastGithub.Dns
                 this.socket.IOControl(SIO_UDP_CONNRESET, new byte[4], new byte[4]);
             }
 
+            this.socket.Bind(new IPEndPoint(address, port));
+            this.listened = true;
+
             try
             {
-                this.socket.Bind(new IPEndPoint(address, port));
+                SystemDnsUtil.SetAsPrimitiveDns();
+                SystemDnsUtil.FlushResolverCache();
             }
-            catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AccessDenied)
+            catch (Exception ex)
             {
-                if (OperatingSystem.IsLinux())
-                {
-                    throw new FastGithubException($"请以root身份运行", ex);
-                }
-                throw;
+                this.logger.LogWarning(ex.Message);
             }
         }
 
@@ -77,6 +80,11 @@ namespace FastGithub.Dns
         /// <returns></returns>
         public async Task HandleAsync(CancellationToken cancellationToken)
         {
+            if (this.listened == false)
+            {
+                return;
+            }
+
             var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
             while (cancellationToken.IsCancellationRequested == false)
             {
@@ -121,6 +129,23 @@ namespace FastGithub.Dns
         public void Dispose()
         {
             this.socket.Dispose();
+            if (this.listened == false)
+            {
+                return;
+            }
+
+            try
+            {
+                SystemDnsUtil.RemoveFromPrimitiveDns();
+            }
+            catch (Exception ex)
+            {
+                this.logger.LogWarning(ex.Message);
+            }
+            finally
+            {
+                SystemDnsUtil.FlushResolverCache();
+            }
         }
     }
 }

+ 5 - 7
FastGithub.ReverseProxy/KestrelServerOptionsExtensions.cs

@@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Server.Kestrel.Core;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
 using System;
 using System.Net;
 
@@ -72,18 +71,17 @@ namespace FastGithub
         /// <param name="kestrel"></param>
         public static void ListenGithubSshProxy(this KestrelServerOptions kestrel)
         {
-            var listenOptions = kestrel.ApplicationServices.GetRequiredService<IOptions<FastGithubOptions>>();
-            var sshPort = listenOptions.Value.Listen.SshPort;
+            const int SSH_PORT = 22;
             var logger = kestrel.GetLogger();
 
-            if (LocalMachine.CanListenTcp(sshPort) == false)
+            if (LocalMachine.CanListenTcp(SSH_PORT) == false)
             {
-                logger.LogWarning($"由于tcp端口{sshPort}已经被其它进程占用,github的ssh代理功能将受限");
+                logger.LogWarning($"由于tcp端口{SSH_PORT}已经被其它进程占用,github的ssh代理功能将受限");
             }
             else
             {
-                kestrel.Listen(IPAddress.Any, sshPort, listen => listen.UseConnectionHandler<GithubSshProxyHandler>());
-                logger.LogInformation($"已监听tcp端口{sshPort},github的ssh代理启动完成");
+                kestrel.Listen(IPAddress.Any, SSH_PORT, listen => listen.UseConnectionHandler<GithubSshProxyHandler>());
+                logger.LogInformation($"已监听tcp端口{SSH_PORT},github的ssh代理启动完成");
             }
         }
 

+ 1 - 5
FastGithub/appsettings.json

@@ -1,10 +1,6 @@
 {
   // 新增的子配置文件appsettings.*.json,重启应用程序才生效
   "FastGithub": {
-    "Listen": {
-      "SshPort": 22, // ssh监听的端口,修改后重启应用才生效
-      "DnsPort": 53 // dns监听的端口,修改后重启应用才生效
-    },
     "FallbackDns": [ // 用于解析不在DomainConfigs的域名
       {
         "IPAddress": "114.114.114.114",
@@ -16,7 +12,7 @@
       }
     ],
     "DomainConfigs": {
-      "*.x.y.z.com": { // 域名的*表示除.之外0到多个任意字符
+      "*.fastgithub.com": { // 域名的*表示除.之外0到多个任意字符
         "TlsSni": false, // 指示tls握手时是否发送SNI
         "TlsSniPattern": null, // SNI表达式,@domain变量表示取域名值 @ipaddress变量表示取ip @random变量表示取随机值,其它字符保留不替换
         "TlsIgnoreNameMismatch": false, // 是否忽略服务器证书域名不匹配,当不发送SNI时服务器可能发回域名不匹配的证书,默认为false