GithubRequestResolver.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using DNS.Client.RequestResolver;
  2. using DNS.Protocol;
  3. using DNS.Protocol.ResourceRecords;
  4. using FastGithub.Scanner;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace FastGithub.Dns
  13. {
  14. /// <summary>
  15. /// github相关域名解析器
  16. /// </summary>
  17. [Service(ServiceLifetime.Singleton)]
  18. sealed class GithubRequestResolver : IRequestResolver
  19. {
  20. private readonly IGithubScanResults githubScanResults;
  21. private readonly IOptionsMonitor<DnsOptions> options;
  22. private readonly ILogger<GithubRequestResolver> logger;
  23. /// <summary>
  24. /// github相关域名解析器
  25. /// </summary>
  26. /// <param name="githubScanResults"></param>
  27. /// <param name="options"></param>
  28. /// <param name="logger"></param>
  29. public GithubRequestResolver(
  30. IGithubScanResults githubScanResults,
  31. IOptionsMonitor<DnsOptions> options,
  32. ILogger<GithubRequestResolver> logger)
  33. {
  34. this.githubScanResults = githubScanResults;
  35. this.options = options;
  36. this.logger = logger;
  37. }
  38. /// <summary>
  39. /// 解析域名
  40. /// </summary>
  41. /// <param name="request"></param>
  42. /// <param name="cancellationToken"></param>
  43. /// <returns></returns>
  44. public Task<IResponse> Resolve(IRequest request, CancellationToken cancellationToken = default)
  45. {
  46. var response = Response.FromRequest(request);
  47. var question = request.Questions.FirstOrDefault();
  48. if (question != null && question.Type == RecordType.A)
  49. {
  50. var domain = question.Name.ToString();
  51. var address = this.githubScanResults.FindBestAddress(domain);
  52. if (address != null)
  53. {
  54. address = IPAddress.Loopback;
  55. var ttl = this.options.CurrentValue.GithubTTL;
  56. var record = new IPAddressResourceRecord(question.Name, address, ttl);
  57. response.AnswerRecords.Add(record);
  58. this.logger.LogInformation(record.ToString());
  59. }
  60. }
  61. return Task.FromResult<IResponse>(response);
  62. }
  63. }
  64. }