DnsClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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.Net.Sockets;
  15. using System.Runtime.CompilerServices;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace FastGithub.DomainResolve
  19. {
  20. /// <summary>
  21. /// DNS客户端
  22. /// </summary>
  23. sealed class DnsClient
  24. {
  25. private const int DNS_PORT = 53;
  26. private const string LOCALHOST = "localhost";
  27. private readonly DnscryptProxy dnscryptProxy;
  28. private readonly FastGithubConfig fastGithubConfig;
  29. private readonly ILogger<DnsClient> logger;
  30. private readonly ConcurrentDictionary<string, SemaphoreSlim> semaphoreSlims = new();
  31. private readonly IMemoryCache dnsCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
  32. private readonly TimeSpan minTimeToLive = TimeSpan.FromSeconds(30d);
  33. private readonly TimeSpan maxTimeToLive = TimeSpan.FromMinutes(10d);
  34. private readonly int resolveTimeout = (int)TimeSpan.FromSeconds(2d).TotalMilliseconds;
  35. private static readonly TimeSpan connectTimeout = TimeSpan.FromSeconds(2d);
  36. private record LookupResult(IPAddress[] Addresses, TimeSpan TimeToLive);
  37. /// <summary>
  38. /// DNS客户端
  39. /// </summary>
  40. /// <param name="dnscryptProxy"></param>
  41. /// <param name="fastGithubConfig"></param>
  42. /// <param name="logger"></param>
  43. public DnsClient(
  44. DnscryptProxy dnscryptProxy,
  45. FastGithubConfig fastGithubConfig,
  46. ILogger<DnsClient> logger)
  47. {
  48. this.dnscryptProxy = dnscryptProxy;
  49. this.fastGithubConfig = fastGithubConfig;
  50. this.logger = logger;
  51. }
  52. /// <summary>
  53. /// 解析域名
  54. /// </summary>
  55. /// <param name="endPoint">远程结节</param>
  56. /// <param name="cancellationToken"></param>
  57. /// <returns></returns>
  58. public async IAsyncEnumerable<IPAddress> ResolveAsync(DnsEndPoint endPoint, [EnumeratorCancellation] CancellationToken cancellationToken)
  59. {
  60. var hashSet = new HashSet<IPAddress>();
  61. foreach (var dns in this.GetDnsServers())
  62. {
  63. var addresses = await this.LookupAsync(dns, endPoint, cancellationToken);
  64. foreach (var address in addresses)
  65. {
  66. if (hashSet.Add(address) == true)
  67. {
  68. yield return address;
  69. }
  70. }
  71. }
  72. }
  73. /// <summary>
  74. /// 获取dns服务
  75. /// </summary>
  76. /// <returns></returns>
  77. private IEnumerable<IPEndPoint> GetDnsServers()
  78. {
  79. var cryptDns = this.dnscryptProxy.LocalEndPoint;
  80. if (cryptDns != null)
  81. {
  82. yield return cryptDns;
  83. yield return cryptDns;
  84. }
  85. foreach (var fallbackDns in this.fastGithubConfig.FallbackDns)
  86. {
  87. if (Socket.OSSupportsIPv6 || fallbackDns.AddressFamily != AddressFamily.InterNetworkV6)
  88. {
  89. yield return fallbackDns;
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// 解析域名
  95. /// </summary>
  96. /// <param name="dns"></param>
  97. /// <param name="endPoint"></param>
  98. /// <param name="cancellationToken"></param>
  99. /// <returns></returns>
  100. private async Task<IPAddress[]> LookupAsync(IPEndPoint dns, DnsEndPoint endPoint, CancellationToken cancellationToken = default)
  101. {
  102. var key = $"{dns}/{endPoint}";
  103. var semaphore = this.semaphoreSlims.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
  104. await semaphore.WaitAsync(CancellationToken.None);
  105. try
  106. {
  107. if (this.dnsCache.TryGetValue<IPAddress[]>(key, out var value))
  108. {
  109. return value;
  110. }
  111. var result = await this.LookupCoreAsync(dns, endPoint, cancellationToken);
  112. this.dnsCache.Set(key, result.Addresses, result.TimeToLive);
  113. return result.Addresses;
  114. }
  115. catch (OperationCanceledException)
  116. {
  117. this.logger.LogWarning($"dns://{dns}无法解析{endPoint.Host}:请求超时");
  118. return Array.Empty<IPAddress>();
  119. }
  120. catch (Exception ex)
  121. {
  122. this.logger.LogWarning($"dns://{dns}无法解析{endPoint.Host}:{ex.Message}");
  123. return Array.Empty<IPAddress>();
  124. }
  125. finally
  126. {
  127. semaphore.Release();
  128. }
  129. }
  130. /// <summary>
  131. /// 解析域名
  132. /// </summary>
  133. /// <param name="dns"></param>
  134. /// <param name="endPoint"></param>
  135. /// <param name="cancellationToken"></param>
  136. /// <returns></returns>
  137. private async Task<LookupResult> LookupCoreAsync(IPEndPoint dns, DnsEndPoint endPoint, CancellationToken cancellationToken = default)
  138. {
  139. if (endPoint.Host == LOCALHOST)
  140. {
  141. return new LookupResult(new[] { IPAddress.Loopback }, TimeSpan.MaxValue);
  142. }
  143. var resolver = dns.Port == DNS_PORT
  144. ? (IRequestResolver)new TcpRequestResolver(dns)
  145. : new UdpRequestResolver(dns, new TcpRequestResolver(dns), this.resolveTimeout);
  146. var addressRecords = await GetAddressRecordsAsync(resolver, endPoint.Host, cancellationToken);
  147. var addresses = addressRecords
  148. .Where(item => IPAddress.IsLoopback(item.IPAddress) == false)
  149. .Select(item => item.IPAddress)
  150. .ToArray();
  151. if (addresses.Length == 0)
  152. {
  153. return new LookupResult(addresses, this.minTimeToLive);
  154. }
  155. if (addresses.Length > 1)
  156. {
  157. addresses = await OrderByConnectAnyAsync(addresses, endPoint.Port, cancellationToken);
  158. }
  159. var timeToLive = addressRecords.Min(item => item.TimeToLive);
  160. if (timeToLive <= TimeSpan.Zero)
  161. {
  162. timeToLive = this.minTimeToLive;
  163. }
  164. else if (timeToLive > this.maxTimeToLive)
  165. {
  166. timeToLive = this.maxTimeToLive;
  167. }
  168. return new LookupResult(addresses, timeToLive);
  169. }
  170. /// <summary>
  171. /// 获取IP记录
  172. /// </summary>
  173. /// <param name="resolver"></param>
  174. /// <param name="domain"></param>
  175. /// <param name="cancellationToken"></param>
  176. /// <returns></returns>
  177. private static async Task<IList<IPAddressResourceRecord>> GetAddressRecordsAsync(IRequestResolver resolver, string domain, CancellationToken cancellationToken)
  178. {
  179. var addressRecords = new List<IPAddressResourceRecord>();
  180. if (Socket.OSSupportsIPv4 == true)
  181. {
  182. var records = await GetRecordsAsync(RecordType.A);
  183. addressRecords.AddRange(records);
  184. }
  185. if (Socket.OSSupportsIPv6 == true)
  186. {
  187. var records = await GetRecordsAsync(RecordType.AAAA);
  188. addressRecords.AddRange(records);
  189. }
  190. return addressRecords;
  191. async Task<IEnumerable<IPAddressResourceRecord>> GetRecordsAsync(RecordType recordType)
  192. {
  193. var request = new Request
  194. {
  195. RecursionDesired = true,
  196. OperationCode = OperationCode.Query
  197. };
  198. request.Questions.Add(new Question(new Domain(domain), recordType));
  199. var clientRequest = new ClientRequest(resolver, request);
  200. var response = await clientRequest.Resolve(cancellationToken);
  201. return response.AnswerRecords.OfType<IPAddressResourceRecord>();
  202. }
  203. }
  204. /// <summary>
  205. /// 连接速度排序
  206. /// </summary>
  207. /// <param name="addresses"></param>
  208. /// <param name="port"></param>
  209. /// <param name="cancellationToken"></param>
  210. /// <returns></returns>
  211. private static async Task<IPAddress[]> OrderByConnectAnyAsync(IPAddress[] addresses, int port, CancellationToken cancellationToken)
  212. {
  213. var tasks = addresses.Select(address => ConnectAsync(address, port, cancellationToken));
  214. var fastestAddress = await await Task.WhenAny(tasks);
  215. if (fastestAddress == null)
  216. {
  217. return addresses;
  218. }
  219. var list = new List<IPAddress> { fastestAddress };
  220. foreach (var address in addresses)
  221. {
  222. if (address.Equals(fastestAddress) == false)
  223. {
  224. list.Add(address);
  225. }
  226. }
  227. return list.ToArray();
  228. }
  229. /// <summary>
  230. /// 连接指定ip和端口
  231. /// </summary>
  232. /// <param name="address"></param>
  233. /// <param name="port"></param>
  234. /// <param name="cancellationToken"></param>
  235. /// <returns></returns>
  236. private static async Task<IPAddress?> ConnectAsync(IPAddress address, int port, CancellationToken cancellationToken)
  237. {
  238. try
  239. {
  240. using var timeoutTokenSource = new CancellationTokenSource(connectTimeout);
  241. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutTokenSource.Token);
  242. using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  243. await socket.ConnectAsync(address, port, linkedTokenSource.Token);
  244. return address;
  245. }
  246. catch (Exception)
  247. {
  248. return default;
  249. }
  250. }
  251. }
  252. }