HostsValidator.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using FastGithub.Configuration;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.NetworkInformation;
  9. using System.Threading.Tasks;
  10. namespace FastGithub.Dns
  11. {
  12. /// <summary>
  13. /// host文件配置验证器
  14. /// </summary>
  15. sealed class HostsValidator : IDnsValidator
  16. {
  17. private readonly FastGithubConfig fastGithubConfig;
  18. private readonly ILogger<HostsValidator> logger;
  19. /// <summary>
  20. /// host文件配置验证器
  21. /// </summary>
  22. /// <param name="fastGithubConfig"></param>
  23. /// <param name="logger"></param>
  24. public HostsValidator(
  25. FastGithubConfig fastGithubConfig,
  26. ILogger<HostsValidator> logger)
  27. {
  28. this.fastGithubConfig = fastGithubConfig;
  29. this.logger = logger;
  30. }
  31. /// <summary>
  32. /// 验证host文件的域名解析配置
  33. /// </summary>
  34. /// <returns></returns>
  35. public async Task ValidateAsync()
  36. {
  37. var hostsPath = @"/etc/hosts";
  38. if (OperatingSystem.IsWindows())
  39. {
  40. hostsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), $"drivers/{hostsPath}");
  41. }
  42. if (File.Exists(hostsPath) == false)
  43. {
  44. return;
  45. }
  46. var lines = await File.ReadAllLinesAsync(hostsPath);
  47. var records = lines.Where(item => item.TrimStart().StartsWith("#") == false);
  48. var localAddresses = GetLocalMachineIPAddress().ToArray();
  49. foreach (var record in records)
  50. {
  51. var items = record.Split(' ', StringSplitOptions.RemoveEmptyEntries);
  52. if (items.Length < 2)
  53. {
  54. continue;
  55. }
  56. if (IPAddress.TryParse(items[0], out var address) == false)
  57. {
  58. continue;
  59. }
  60. if (localAddresses.Contains(address))
  61. {
  62. continue;
  63. }
  64. var domain = items[1];
  65. if (this.fastGithubConfig.IsMatch(domain))
  66. {
  67. this.logger.LogError($"由于你的hosts文件设置了[{domain}->{address}],{nameof(FastGithub)}无法加速此域名");
  68. }
  69. }
  70. }
  71. /// <summary>
  72. /// 获取本机所有ip
  73. /// </summary>
  74. /// <returns></returns>
  75. private static IEnumerable<IPAddress> GetLocalMachineIPAddress()
  76. {
  77. yield return IPAddress.Loopback;
  78. yield return IPAddress.IPv6Loopback;
  79. foreach (var @interface in NetworkInterface.GetAllNetworkInterfaces())
  80. {
  81. foreach (var addressInfo in @interface.GetIPProperties().UnicastAddresses)
  82. {
  83. yield return addressInfo.Address;
  84. }
  85. }
  86. }
  87. }
  88. }