using FastGithub.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Dns
{
///
/// dns后台服务
///
sealed class DnsOverUdpHostedService : BackgroundService
{
private readonly DnsOverUdpServer dnsOverUdpServer;
private readonly IEnumerable conflictValidators;
private readonly ILogger logger;
///
/// dns后台服务
///
///
///
///
///
public DnsOverUdpHostedService(
DnsOverUdpServer dnsOverUdpServer,
IEnumerable conflictValidators,
IOptionsMonitor options,
ILogger logger)
{
this.dnsOverUdpServer = dnsOverUdpServer;
this.conflictValidators = conflictValidators;
this.logger = logger;
options.OnChange(opt => SystemDnsUtil.FlushResolverCache());
}
///
/// 启动dns
///
///
///
public override async Task StartAsync(CancellationToken cancellationToken)
{
try
{
const int DNS_PORT = 53;
this.dnsOverUdpServer.Listen(IPAddress.Any, DNS_PORT);
this.logger.LogInformation($"已监听udp端口{DNS_PORT},DNS服务启动完成");
}
catch (Exception ex)
{
this.logger.LogError($"DNS服务启动失败:{ex.Message}{Environment.NewLine}请配置系统或浏览器使用{nameof(FastGithub)}的DoH,或向系统hosts文件添加github相关域名的ip为127.0.0.1");
}
foreach (var item in this.conflictValidators)
{
await item.ValidateAsync();
}
await base.StartAsync(cancellationToken);
}
///
/// dns后台
///
///
///
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
return this.dnsOverUdpServer.HandleAsync(stoppingToken);
}
///
/// 停止dns服务
///
///
///
public override Task StopAsync(CancellationToken cancellationToken)
{
this.dnsOverUdpServer.Dispose();
return base.StopAsync(cancellationToken);
}
}
}