2
0

DnsClient.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using DNS.Client;
  2. using DNS.Client.RequestResolver;
  3. using DNS.Protocol;
  4. using DNS.Protocol.ResourceRecords;
  5. using FastGithub.Configuration;
  6. using Microsoft.Extensions.Caching.Memory;
  7. using Microsoft.Extensions.Logging;
  8. using Microsoft.Extensions.Options;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Runtime.CompilerServices;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace FastGithub.DomainResolve
  18. {
  19. /// <summary>
  20. /// DNS客户端
  21. /// </summary>
  22. sealed class DnsClient
  23. {
  24. private const int DNS_PORT = 53;
  25. private const string LOCALHOST = "localhost";
  26. private readonly DnscryptProxy dnscryptProxy;
  27. private readonly FastGithubConfig fastGithubConfig;
  28. private readonly ILogger<DnsClient> logger;
  29. private readonly ConcurrentDictionary<string, SemaphoreSlim> semaphoreSlims = new();
  30. private readonly IMemoryCache dnsCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
  31. private readonly TimeSpan dnsExpiration = TimeSpan.FromMinutes(2d);
  32. private readonly int resolveTimeout = (int)TimeSpan.FromSeconds(2d).TotalMilliseconds;
  33. /// <summary>
  34. /// DNS客户端
  35. /// </summary>
  36. /// <param name="dnscryptProxy"></param>
  37. /// <param name="fastGithubConfig"></param>
  38. /// <param name="logger"></param>
  39. public DnsClient(
  40. DnscryptProxy dnscryptProxy,
  41. FastGithubConfig fastGithubConfig,
  42. ILogger<DnsClient> logger)
  43. {
  44. this.dnscryptProxy = dnscryptProxy;
  45. this.fastGithubConfig = fastGithubConfig;
  46. this.logger = logger;
  47. }
  48. /// <summary>
  49. /// 解析域名
  50. /// </summary>
  51. /// <param name="domain">域名</param>
  52. /// <param name="cancellationToken"></param>
  53. /// <returns></returns>
  54. public async IAsyncEnumerable<IPAddress> ResolveAsync(string domain, [EnumeratorCancellation] CancellationToken cancellationToken)
  55. {
  56. var hashSet = new HashSet<IPAddress>();
  57. foreach (var dns in this.GetDnsServers())
  58. {
  59. foreach (var address in await this.LookupAsync(dns, domain, cancellationToken))
  60. {
  61. if (hashSet.Add(address) == true)
  62. {
  63. yield return address;
  64. }
  65. }
  66. }
  67. }
  68. /// <summary>
  69. /// 获取dns服务
  70. /// </summary>
  71. /// <returns></returns>
  72. private IEnumerable<IPEndPoint> GetDnsServers()
  73. {
  74. var cryptDns = this.dnscryptProxy.LocalEndPoint;
  75. if (cryptDns != null)
  76. {
  77. yield return cryptDns;
  78. }
  79. foreach (var fallbackDns in this.fastGithubConfig.FallbackDns)
  80. {
  81. yield return fallbackDns;
  82. }
  83. }
  84. /// <summary>
  85. /// 解析域名
  86. /// </summary>
  87. /// <param name="dns"></param>
  88. /// <param name="domain"></param>
  89. /// <param name="cancellationToken"></param>
  90. /// <returns></returns>
  91. private async Task<IPAddress[]> LookupAsync(IPEndPoint dns, string domain, CancellationToken cancellationToken = default)
  92. {
  93. var key = $"{dns}:{domain}";
  94. var semaphore = this.semaphoreSlims.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
  95. await semaphore.WaitAsync(CancellationToken.None);
  96. try
  97. {
  98. if (this.dnsCache.TryGetValue<IPAddress[]>(key, out var value) == false)
  99. {
  100. value = await this.LookupCoreAsync(dns, domain, cancellationToken);
  101. this.dnsCache.Set(key, value, this.dnsExpiration);
  102. }
  103. return value;
  104. }
  105. catch (Exception ex)
  106. {
  107. this.logger.LogWarning($"dns://{dns}无法解析{domain}:{ex.Message}");
  108. return Array.Empty<IPAddress>();
  109. }
  110. finally
  111. {
  112. semaphore.Release();
  113. }
  114. }
  115. /// <summary>
  116. /// 解析域名
  117. /// </summary>
  118. /// <param name="dns"></param>
  119. /// <param name="domain"></param>
  120. /// <param name="cancellationToken"></param>
  121. /// <returns></returns>
  122. private async Task<IPAddress[]> LookupCoreAsync(IPEndPoint dns, string domain, CancellationToken cancellationToken = default)
  123. {
  124. if (domain == LOCALHOST)
  125. {
  126. return new[] { IPAddress.Loopback };
  127. }
  128. var resolver = dns.Port == DNS_PORT
  129. ? (IRequestResolver)new TcpRequestResolver(dns)
  130. : new UdpRequestResolver(dns, new TcpRequestResolver(dns), this.resolveTimeout);
  131. var request = new Request
  132. {
  133. RecursionDesired = true,
  134. OperationCode = OperationCode.Query
  135. };
  136. request.Questions.Add(new Question(new Domain(domain), RecordType.A));
  137. var clientRequest = new ClientRequest(resolver, request);
  138. var response = await clientRequest.Resolve(cancellationToken);
  139. return response.AnswerRecords
  140. .OfType<IPAddressResourceRecord>()
  141. .Where(item => IPAddress.IsLoopback(item.IPAddress) == false)
  142. .Select(item => item.IPAddress)
  143. .ToArray();
  144. }
  145. }
  146. }