移除ListenConfig

This commit is contained in:
老九 2021-09-08 14:11:36 +08:00
parent 6a1734111d
commit 0811f175c8
6 changed files with 49 additions and 81 deletions

View File

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

View File

@ -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;
}
}

View File

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

View File

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

View File

@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System; using System;
using System.Net; using System.Net;
@ -72,18 +71,17 @@ namespace FastGithub
/// <param name="kestrel"></param> /// <param name="kestrel"></param>
public static void ListenGithubSshProxy(this KestrelServerOptions kestrel) public static void ListenGithubSshProxy(this KestrelServerOptions kestrel)
{ {
var listenOptions = kestrel.ApplicationServices.GetRequiredService<IOptions<FastGithubOptions>>(); const int SSH_PORT = 22;
var sshPort = listenOptions.Value.Listen.SshPort;
var logger = kestrel.GetLogger(); 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 else
{ {
kestrel.Listen(IPAddress.Any, sshPort, listen => listen.UseConnectionHandler<GithubSshProxyHandler>()); kestrel.Listen(IPAddress.Any, SSH_PORT, listen => listen.UseConnectionHandler<GithubSshProxyHandler>());
logger.LogInformation($"已监听tcp端口{sshPort}github的ssh代理启动完成"); logger.LogInformation($"已监听tcp端口{SSH_PORT}github的ssh代理启动完成");
} }
} }

View File

@ -1,10 +1,6 @@
{ {
// appsettings.*.json // appsettings.*.json
"FastGithub": { "FastGithub": {
"Listen": {
"SshPort": 22, // ssh
"DnsPort": 53 // dns
},
"FallbackDns": [ // DomainConfigs "FallbackDns": [ // DomainConfigs
{ {
"IPAddress": "114.114.114.114", "IPAddress": "114.114.114.114",
@ -16,7 +12,7 @@
} }
], ],
"DomainConfigs": { "DomainConfigs": {
"*.x.y.z.com": { // *.0 "*.fastgithub.com": { // *.0
"TlsSni": false, // tlsSNI "TlsSni": false, // tlsSNI
"TlsSniPattern": null, // SNI@domain @ipaddressip @random "TlsSniPattern": null, // SNI@domain @ipaddressip @random
"TlsIgnoreNameMismatch": false, // SNIfalse "TlsIgnoreNameMismatch": false, // SNIfalse