DnscryptProxy.cs 6.2 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. using static PInvoke.AdvApi32;
  14. namespace FastGithub.DomainResolve
  15. {
  16. /// <summary>
  17. /// DnscryptProxy服务
  18. /// </summary>
  19. sealed class DnscryptProxy
  20. {
  21. private readonly ILogger<DnscryptProxy> logger;
  22. private readonly string processName;
  23. private readonly string serviceName;
  24. private readonly string exeFilePath;
  25. private readonly string tomlFilePath;
  26. /// <summary>
  27. /// 相关进程
  28. /// </summary>
  29. private Process? process;
  30. /// <summary>
  31. /// 获取监听的节点
  32. /// </summary>
  33. public IPEndPoint? LocalEndPoint { get; private set; }
  34. /// <summary>
  35. /// DnscryptProxy服务
  36. /// </summary>
  37. /// <param name="logger"></param>
  38. public DnscryptProxy(ILogger<DnscryptProxy> logger)
  39. {
  40. const string PATH = "dnscrypt-proxy";
  41. const string NAME = "dnscrypt-proxy";
  42. this.logger = logger;
  43. this.processName = NAME;
  44. this.serviceName = $"{nameof(FastGithub)}.{NAME}";
  45. this.exeFilePath = Path.Combine(PATH, OperatingSystem.IsWindows() ? $"{NAME}.exe" : NAME);
  46. this.tomlFilePath = Path.Combine(PATH, $"{NAME}.toml");
  47. }
  48. /// <summary>
  49. /// 启动dnscrypt-proxy
  50. /// </summary>
  51. /// <param name="cancellationToken"></param>
  52. /// <returns></returns>
  53. public async Task StartAsync(CancellationToken cancellationToken)
  54. {
  55. try
  56. {
  57. await this.StartCoreAsync(cancellationToken);
  58. }
  59. catch (Exception ex)
  60. {
  61. this.logger.LogWarning($"{this.processName}启动失败:{ex.Message}");
  62. }
  63. }
  64. /// <summary>
  65. /// 启动dnscrypt-proxy
  66. /// </summary>
  67. /// <param name="cancellationToken"></param>
  68. /// <returns></returns>
  69. private async Task StartCoreAsync(CancellationToken cancellationToken)
  70. {
  71. var port = GetAvailablePort(IPAddress.Loopback.AddressFamily);
  72. var localEndPoint = new IPEndPoint(IPAddress.Loopback, port);
  73. await TomlUtil.SetListensAsync(this.tomlFilePath, localEndPoint, cancellationToken);
  74. await TomlUtil.SetLogLevelAsync(this.tomlFilePath, 6, cancellationToken);
  75. await TomlUtil.SetLBStrategyAsync(this.tomlFilePath, "ph", cancellationToken);
  76. await TomlUtil.SetMinMaxTTLAsync(this.tomlFilePath, TimeSpan.FromMinutes(1d), TimeSpan.FromMinutes(2d), cancellationToken);
  77. if (OperatingSystem.IsWindows() && Environment.UserInteractive == false)
  78. {
  79. ServiceInstallUtil.StopAndDeleteService(this.serviceName);
  80. ServiceInstallUtil.InstallAndStartService(this.serviceName, this.exeFilePath, ServiceStartType.SERVICE_DEMAND_START);
  81. this.process = Process.GetProcessesByName(this.processName).FirstOrDefault(item => item.SessionId == 0);
  82. }
  83. else
  84. {
  85. this.process = StartDnscryptProxy();
  86. }
  87. if (this.process != null)
  88. {
  89. this.LocalEndPoint = localEndPoint;
  90. this.process.EnableRaisingEvents = true;
  91. this.process.Exited += (s, e) => this.LocalEndPoint = null;
  92. }
  93. }
  94. /// <summary>
  95. /// 停止服务
  96. /// </summary>
  97. public void Stop()
  98. {
  99. try
  100. {
  101. if (OperatingSystem.IsWindows() && Environment.UserInteractive == false)
  102. {
  103. ServiceInstallUtil.StopAndDeleteService(this.serviceName);
  104. }
  105. if (this.process != null && this.process.HasExited == false)
  106. {
  107. this.process.Kill();
  108. }
  109. }
  110. catch (Exception ex)
  111. {
  112. this.logger.LogWarning($"{this.processName}停止失败:{ex.Message }");
  113. }
  114. finally
  115. {
  116. this.LocalEndPoint = null;
  117. }
  118. }
  119. /// <summary>
  120. /// 获取可用的随机端口
  121. /// </summary>
  122. /// <param name="addressFamily"></param>
  123. /// <param name="min">最小值</param>
  124. /// <returns></returns>
  125. private static int GetAvailablePort(AddressFamily addressFamily, int min = 5533)
  126. {
  127. var hashSet = new HashSet<int>();
  128. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  129. var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
  130. foreach (var endPoint in tcpListeners.Concat(udpListeners))
  131. {
  132. if (endPoint.AddressFamily == addressFamily)
  133. {
  134. hashSet.Add(endPoint.Port);
  135. }
  136. }
  137. for (var port = min; port < IPEndPoint.MaxPort; port++)
  138. {
  139. if (hashSet.Contains(port) == false)
  140. {
  141. return port;
  142. }
  143. }
  144. throw new FastGithubException("当前无可用的端口");
  145. }
  146. /// <summary>
  147. /// 启动DnscryptProxy进程
  148. /// </summary>
  149. /// <returns></returns>
  150. private Process? StartDnscryptProxy()
  151. {
  152. return Process.Start(new ProcessStartInfo
  153. {
  154. FileName = this.exeFilePath,
  155. WorkingDirectory = Path.GetDirectoryName(this.exeFilePath),
  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 this.processName;
  168. }
  169. }
  170. }