DnscryptProxy.cs 6.1 KB

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