DnscryptProxy.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using FastGithub.Configuration;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.NetworkInformation;
  10. using System.Net.Sockets;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace FastGithub.DomainResolve
  14. {
  15. /// <summary>
  16. /// DnscryptProxy服务
  17. /// </summary>
  18. sealed class DnscryptProxy
  19. {
  20. private const string PATH = "dnscrypt-proxy";
  21. private const string NAME = "dnscrypt-proxy";
  22. private readonly ILogger<DnscryptProxy> logger;
  23. /// <summary>
  24. /// 相关进程
  25. /// </summary>
  26. private Process? process;
  27. /// <summary>
  28. /// 获取监听的节点
  29. /// </summary>
  30. public IPEndPoint? LocalEndPoint { get; private set; }
  31. /// <summary>
  32. /// DnscryptProxy服务
  33. /// </summary>
  34. /// <param name="logger"></param>
  35. public DnscryptProxy(ILogger<DnscryptProxy> logger)
  36. {
  37. this.logger = logger;
  38. }
  39. /// <summary>
  40. /// 启动dnscrypt-proxy
  41. /// </summary>
  42. /// <param name="cancellationToken"></param>
  43. /// <returns></returns>
  44. public async Task StartAsync(CancellationToken cancellationToken)
  45. {
  46. try
  47. {
  48. await this.StartCoreAsync(cancellationToken);
  49. }
  50. catch (Exception ex)
  51. {
  52. this.logger.LogWarning($"{NAME}启动失败:{ex.Message}");
  53. }
  54. }
  55. /// <summary>
  56. /// 启动dnscrypt-proxy
  57. /// </summary>
  58. /// <param name="cancellationToken"></param>
  59. /// <returns></returns>
  60. private async Task StartCoreAsync(CancellationToken cancellationToken)
  61. {
  62. var tomlPath = Path.Combine(PATH, $"{NAME}.toml");
  63. var port = GetAvailablePort(IPAddress.Loopback.AddressFamily);
  64. var localEndPoint = new IPEndPoint(IPAddress.Loopback, port);
  65. await TomlUtil.SetListensAsync(tomlPath, localEndPoint, cancellationToken);
  66. await TomlUtil.SetEdnsClientSubnetAsync(tomlPath, cancellationToken);
  67. foreach (var process in Process.GetProcessesByName(NAME))
  68. {
  69. process.Kill();
  70. process.WaitForExit();
  71. }
  72. if (OperatingSystem.IsWindows())
  73. {
  74. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  75. StartDnscryptProxy("-service install")?.WaitForExit();
  76. StartDnscryptProxy("-service start")?.WaitForExit();
  77. this.process = Process.GetProcessesByName(NAME).FirstOrDefault(item => item.SessionId == 0);
  78. }
  79. else
  80. {
  81. this.process = StartDnscryptProxy(string.Empty);
  82. }
  83. if (this.process != null)
  84. {
  85. this.LocalEndPoint = localEndPoint;
  86. this.process.EnableRaisingEvents = true;
  87. this.process.Exited += Process_Exited;
  88. }
  89. }
  90. /// <summary>
  91. /// 停止服务
  92. /// </summary>
  93. public void Stop()
  94. {
  95. try
  96. {
  97. if (OperatingSystem.IsWindows())
  98. {
  99. StartDnscryptProxy("-service stop")?.WaitForExit();
  100. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  101. }
  102. if (this.process != null && this.process.HasExited == false)
  103. {
  104. this.process.Kill();
  105. }
  106. }
  107. catch (Exception ex)
  108. {
  109. this.logger.LogWarning($"{NAME}停止失败:{ex.Message }");
  110. }
  111. finally
  112. {
  113. this.LocalEndPoint = null;
  114. }
  115. }
  116. /// <summary>
  117. /// 获取可用的随机端口
  118. /// </summary>
  119. /// <param name="addressFamily"></param>
  120. /// <param name="min">最小值</param>
  121. /// <returns></returns>
  122. private static int GetAvailablePort(AddressFamily addressFamily, int min = 5533)
  123. {
  124. var hashSet = new HashSet<int>();
  125. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  126. var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
  127. foreach (var endPoint in tcpListeners.Concat(udpListeners))
  128. {
  129. if (endPoint.AddressFamily == addressFamily)
  130. {
  131. hashSet.Add(endPoint.Port);
  132. }
  133. }
  134. for (var port = min; port < IPEndPoint.MaxPort; port++)
  135. {
  136. if (hashSet.Contains(port) == false)
  137. {
  138. return port;
  139. }
  140. }
  141. throw new FastGithubException("当前无可用的端口");
  142. }
  143. /// <summary>
  144. /// 进程退出时
  145. /// </summary>
  146. /// <param name="sender"></param>
  147. /// <param name="e"></param>
  148. private void Process_Exited(object? sender, EventArgs e)
  149. {
  150. this.LocalEndPoint = null;
  151. }
  152. /// <summary>
  153. /// 启动DnscryptProxy进程
  154. /// </summary>
  155. /// <param name="arguments"></param>
  156. private static Process? StartDnscryptProxy(string arguments)
  157. {
  158. var fileName = OperatingSystem.IsWindows() ? $"{NAME}.exe" : NAME;
  159. return Process.Start(new ProcessStartInfo
  160. {
  161. FileName = Path.Combine(PATH, fileName),
  162. Arguments = arguments,
  163. WorkingDirectory = PATH,
  164. UseShellExecute = false,
  165. CreateNoWindow = true,
  166. WindowStyle = ProcessWindowStyle.Hidden
  167. });
  168. }
  169. /// <summary>
  170. /// 转换为字符串
  171. /// </summary>
  172. /// <returns></returns>
  173. public override string ToString()
  174. {
  175. return NAME;
  176. }
  177. }
  178. }