DnscryptProxy.cs 5.2 KB

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