DnscryptProxy.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 = "dnscryptproxy";
  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. foreach (var process in Process.GetProcessesByName(NAME))
  41. {
  42. process.Kill();
  43. process.WaitForExit();
  44. }
  45. if (OperatingSystem.IsWindows())
  46. {
  47. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  48. StartDnscryptProxy("-service install")?.WaitForExit();
  49. StartDnscryptProxy("-service start")?.WaitForExit();
  50. this.process = Process.GetProcessesByName(NAME).FirstOrDefault(item => item.SessionId == 0);
  51. }
  52. else
  53. {
  54. this.process = StartDnscryptProxy(string.Empty);
  55. }
  56. if (this.process != null)
  57. {
  58. this.LocalEndPoint = localEndPoint;
  59. this.process.EnableRaisingEvents = true;
  60. this.process.Exited += Process_Exited;
  61. }
  62. }
  63. /// <summary>
  64. /// 获取可用的随机端口
  65. /// </summary>
  66. /// <param name="addressFamily"></param>
  67. /// <param name="min">最小值</param>
  68. /// <returns></returns>
  69. private static int GetAvailablePort(AddressFamily addressFamily, int min = 5533)
  70. {
  71. var hashSet = new HashSet<int>();
  72. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  73. var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
  74. foreach (var endPoint in tcpListeners)
  75. {
  76. if (endPoint.AddressFamily == addressFamily)
  77. {
  78. hashSet.Add(endPoint.Port);
  79. }
  80. }
  81. foreach (var endPoint in udpListeners)
  82. {
  83. if (endPoint.AddressFamily == addressFamily)
  84. {
  85. hashSet.Add(endPoint.Port);
  86. }
  87. }
  88. for (var port = min; port < IPEndPoint.MaxPort; port++)
  89. {
  90. if (hashSet.Contains(port) == false)
  91. {
  92. return port;
  93. }
  94. }
  95. throw new FastGithubException("当前无可用的端口");
  96. }
  97. /// <summary>
  98. /// 进程退出时
  99. /// </summary>
  100. /// <param name="sender"></param>
  101. /// <param name="e"></param>
  102. private void Process_Exited(object? sender, EventArgs e)
  103. {
  104. this.LocalEndPoint = null;
  105. }
  106. /// <summary>
  107. /// 停止dnscrypt-proxy
  108. /// </summary>
  109. public void Stop()
  110. {
  111. if (OperatingSystem.IsWindows())
  112. {
  113. StartDnscryptProxy("-service stop")?.WaitForExit();
  114. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  115. }
  116. if (this.process != null && this.process.HasExited == false)
  117. {
  118. this.process.Kill();
  119. }
  120. this.LocalEndPoint = null;
  121. }
  122. /// <summary>
  123. /// 启动DnscryptProxy进程
  124. /// </summary>
  125. /// <param name="arguments"></param>
  126. private static Process? StartDnscryptProxy(string arguments)
  127. {
  128. var fileName = OperatingSystem.IsWindows() ? $"{NAME}.exe" : NAME;
  129. return Process.Start(new ProcessStartInfo
  130. {
  131. FileName = Path.Combine(PATH, fileName),
  132. Arguments = arguments,
  133. WorkingDirectory = PATH,
  134. UseShellExecute = false,
  135. CreateNoWindow = true,
  136. WindowStyle = ProcessWindowStyle.Hidden
  137. });
  138. }
  139. /// <summary>
  140. /// 转换为字符串
  141. /// </summary>
  142. /// <returns></returns>
  143. public override string ToString()
  144. {
  145. return NAME;
  146. }
  147. }
  148. }