DnsClient.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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(1d);
  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. var addresses = await this.LookupAsync(dns, domain, cancellationToken);
  60. var value = Filter(hashSet, addresses).ToArray();
  61. if (value.Length > 0)
  62. {
  63. yield return value;
  64. }
  65. }
  66. static IEnumerable<IPAddress> Filter(HashSet<IPAddress> hashSet, IPAddress[] addresses)
  67. {
  68. foreach (var address in addresses)
  69. {
  70. if (hashSet.Add(address) == true)
  71. {
  72. yield return address;
  73. }
  74. }
  75. }
  76. }
  77. /// <summary>
  78. /// 获取dns服务
  79. /// </summary>
  80. /// <returns></returns>
  81. private IEnumerable<IPEndPoint> GetDnsServers()
  82. {
  83. var cryptDns = this.dnscryptProxy.LocalEndPoint;
  84. if (cryptDns != null)
  85. {
  86. yield return cryptDns;
  87. yield return cryptDns;
  88. }
  89. foreach (var fallbackDns in this.fastGithubConfig.FallbackDns)
  90. {
  91. yield return fallbackDns;
  92. }
  93. }
  94. /// <summary>
  95. /// 解析域名
  96. /// </summary>
  97. /// <param name="dns"></param>
  98. /// <param name="domain"></param>
  99. /// <param name="cancellationToken"></param>
  100. /// <returns></returns>
  101. private async Task<IPAddress[]> LookupAsync(IPEndPoint dns, string domain, CancellationToken cancellationToken = default)
  102. {
  103. var key = $"{dns}:{domain}";
  104. var semaphore = this.semaphoreSlims.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
  105. await semaphore.WaitAsync(CancellationToken.None);
  106. try
  107. {
  108. if (this.dnsCache.TryGetValue<IPAddress[]>(key, out var value) == false)
  109. {
  110. value = await this.LookupCoreAsync(dns, domain, cancellationToken);
  111. this.dnsCache.Set(key, value, this.dnsExpiration);
  112. var items = string.Join(", ", value.Select(item => item.ToString()));
  113. this.logger.LogInformation($"dns://{dns}:{domain}->[{items}]");
  114. }
  115. return value;
  116. }
  117. catch (Exception ex)
  118. {
  119. this.logger.LogWarning($"dns://{dns}无法解析{domain}:{ex.Message}");
  120. return Array.Empty<IPAddress>();
  121. }
  122. finally
  123. {
  124. semaphore.Release();
  125. }
  126. }
  127. /// <summary>
  128. /// 解析域名
  129. /// </summary>
  130. /// <param name="dns"></param>
  131. /// <param name="domain"></param>
  132. /// <param name="cancellationToken"></param>
  133. /// <returns></returns>
  134. private async Task<IPAddress[]> LookupCoreAsync(IPEndPoint dns, string domain, CancellationToken cancellationToken = default)
  135. {
  136. if (domain == LOCALHOST)
  137. {
  138. return new[] { IPAddress.Loopback };
  139. }
  140. var resolver = dns.Port == DNS_PORT
  141. ? (IRequestResolver)new TcpRequestResolver(dns)
  142. : new UdpRequestResolver(dns, new TcpRequestResolver(dns), this.resolveTimeout);
  143. var request = new Request
  144. {
  145. RecursionDesired = true,
  146. OperationCode = OperationCode.Query
  147. };
  148. request.Questions.Add(new Question(new Domain(domain), RecordType.A));
  149. var clientRequest = new ClientRequest(resolver, request);
  150. var response = await clientRequest.Resolve(cancellationToken);
  151. return response.AnswerRecords
  152. .OfType<IPAddressResourceRecord>()
  153. .Where(item => IPAddress.IsLoopback(item.IPAddress) == false)
  154. .Select(item => item.IPAddress)
  155. .ToArray();
  156. }
  157. }
  158. }