HostsConflictSolver.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using FastGithub.Configuration;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Runtime.Versioning;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace FastGithub.PacketIntercept.Dns
  10. {
  11. /// <summary>
  12. /// host文件冲解决者
  13. /// </summary>
  14. [SupportedOSPlatform("windows")]
  15. sealed class HostsConflictSolver : IDnsConflictSolver
  16. {
  17. private readonly FastGithubConfig fastGithubConfig;
  18. private readonly ILogger<HostsConflictSolver> logger;
  19. /// <summary>
  20. /// host文件冲解决者
  21. /// </summary>
  22. /// <param name="fastGithubConfig"></param>
  23. /// <param name="logger"></param>
  24. public HostsConflictSolver(
  25. FastGithubConfig fastGithubConfig,
  26. ILogger<HostsConflictSolver> logger)
  27. {
  28. this.fastGithubConfig = fastGithubConfig;
  29. this.logger = logger;
  30. }
  31. /// <summary>
  32. /// 解决冲突
  33. /// </summary>
  34. /// <param name="cancellationToken"></param>
  35. /// <returns></returns>
  36. public async Task SolveAsync(CancellationToken cancellationToken)
  37. {
  38. var hostsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts");
  39. if (File.Exists(hostsPath) == false)
  40. {
  41. return;
  42. }
  43. var hasConflicting = false;
  44. var hostsBuilder = new StringBuilder();
  45. using var fileStream = new FileStream(hostsPath, FileMode.Open, FileAccess.Read);
  46. using var streamReader = new StreamReader(fileStream);
  47. while (streamReader.EndOfStream == false)
  48. {
  49. var line = await streamReader.ReadLineAsync();
  50. if (this.IsConflictingLine(line))
  51. {
  52. hasConflicting = true;
  53. hostsBuilder.AppendLine($"# {line}");
  54. }
  55. else
  56. {
  57. hostsBuilder.AppendLine(line);
  58. }
  59. }
  60. if (hasConflicting == true)
  61. {
  62. try
  63. {
  64. File.Move(hostsPath, Path.ChangeExtension(hostsPath, ".bak"), overwrite: true);
  65. await File.WriteAllTextAsync(hostsPath, hostsBuilder.ToString(), streamReader.CurrentEncoding, cancellationToken);
  66. }
  67. catch (Exception ex)
  68. {
  69. this.logger.LogWarning($"无法解决hosts文件冲突:{ex.Message}");
  70. }
  71. }
  72. }
  73. /// <summary>
  74. /// 恢复冲突
  75. /// </summary>
  76. /// <param name="cancellationToken"></param>
  77. /// <returns></returns>
  78. public Task RestoreAsync(CancellationToken cancellationToken)
  79. {
  80. return Task.CompletedTask;
  81. }
  82. /// <summary>
  83. /// 是否为冲突的行
  84. /// </summary>
  85. /// <param name="line"></param>
  86. /// <returns></returns>
  87. private bool IsConflictingLine(string? line)
  88. {
  89. if (line == null || line.TrimStart().StartsWith("#"))
  90. {
  91. return false;
  92. }
  93. var items = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
  94. if (items.Length < 2)
  95. {
  96. return false;
  97. }
  98. var domain = items[1];
  99. return this.fastGithubConfig.IsMatch(domain);
  100. }
  101. }
  102. }