DnscryptProxy.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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.SetlogLevelAsync(tomlPath, 6, cancellationToken);
  67. await TomlUtil.SetEdnsClientSubnetAsync(tomlPath, cancellationToken);
  68. foreach (var process in Process.GetProcessesByName(NAME))
  69. {
  70. process.Kill();
  71. process.WaitForExit();
  72. }
  73. if (OperatingSystem.IsWindows() && Process.GetCurrentProcess().SessionId == 0)
  74. {
  75. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  76. StartDnscryptProxy("-service install")?.WaitForExit();
  77. StartDnscryptProxy("-service start")?.WaitForExit();
  78. this.process = Process.GetProcessesByName(NAME).FirstOrDefault(item => item.SessionId == 0);
  79. }
  80. else
  81. {
  82. this.process = StartDnscryptProxy(string.Empty);
  83. }
  84. if (this.process != null)
  85. {
  86. this.LocalEndPoint = localEndPoint;
  87. this.process.EnableRaisingEvents = true;
  88. this.process.Exited += (s, e) => this.LocalEndPoint = null;
  89. }
  90. }
  91. /// <summary>
  92. /// 停止服务
  93. /// </summary>
  94. public void Stop()
  95. {
  96. try
  97. {
  98. if (OperatingSystem.IsWindows() && Process.GetCurrentProcess().SessionId == 0)
  99. {
  100. StartDnscryptProxy("-service stop")?.WaitForExit();
  101. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  102. }
  103. if (this.process != null && this.process.HasExited == false)
  104. {
  105. this.process.Kill();
  106. }
  107. }
  108. catch (Exception ex)
  109. {
  110. this.logger.LogWarning($"{NAME}停止失败:{ex.Message }");
  111. }
  112. finally
  113. {
  114. this.LocalEndPoint = null;
  115. }
  116. }
  117. /// <summary>
  118. /// 获取可用的随机端口
  119. /// </summary>
  120. /// <param name="addressFamily"></param>
  121. /// <param name="min">最小值</param>
  122. /// <returns></returns>
  123. private static int GetAvailablePort(AddressFamily addressFamily, int min = 5533)
  124. {
  125. var hashSet = new HashSet<int>();
  126. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  127. var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
  128. foreach (var endPoint in tcpListeners.Concat(udpListeners))
  129. {
  130. if (endPoint.AddressFamily == addressFamily)
  131. {
  132. hashSet.Add(endPoint.Port);
  133. }
  134. }
  135. for (var port = min; port < IPEndPoint.MaxPort; port++)
  136. {
  137. if (hashSet.Contains(port) == false)
  138. {
  139. return port;
  140. }
  141. }
  142. throw new FastGithubException("当前无可用的端口");
  143. }
  144. /// <summary>
  145. /// 启动DnscryptProxy进程
  146. /// </summary>
  147. /// <param name="arguments"></param>
  148. private static Process? StartDnscryptProxy(string arguments)
  149. {
  150. var fileName = OperatingSystem.IsWindows() ? $"{NAME}.exe" : NAME;
  151. return Process.Start(new ProcessStartInfo
  152. {
  153. FileName = Path.Combine(PATH, fileName),
  154. Arguments = arguments,
  155. WorkingDirectory = PATH,
  156. UseShellExecute = false,
  157. CreateNoWindow = true,
  158. WindowStyle = ProcessWindowStyle.Hidden
  159. });
  160. }
  161. /// <summary>
  162. /// 转换为字符串
  163. /// </summary>
  164. /// <returns></returns>
  165. public override string ToString()
  166. {
  167. return NAME;
  168. }
  169. }
  170. }