DnscryptProxy.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. 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.Concat(udpListeners))
  75. {
  76. if (endPoint.AddressFamily == addressFamily)
  77. {
  78. hashSet.Add(endPoint.Port);
  79. }
  80. }
  81. for (var port = min; port < IPEndPoint.MaxPort; port++)
  82. {
  83. if (hashSet.Contains(port) == false)
  84. {
  85. return port;
  86. }
  87. }
  88. throw new FastGithubException("当前无可用的端口");
  89. }
  90. /// <summary>
  91. /// 进程退出时
  92. /// </summary>
  93. /// <param name="sender"></param>
  94. /// <param name="e"></param>
  95. private void Process_Exited(object? sender, EventArgs e)
  96. {
  97. this.LocalEndPoint = null;
  98. }
  99. /// <summary>
  100. /// 停止dnscrypt-proxy
  101. /// </summary>
  102. public void Stop()
  103. {
  104. if (OperatingSystem.IsWindows())
  105. {
  106. StartDnscryptProxy("-service stop")?.WaitForExit();
  107. StartDnscryptProxy("-service uninstall")?.WaitForExit();
  108. }
  109. if (this.process != null && this.process.HasExited == false)
  110. {
  111. this.process.Kill();
  112. }
  113. this.LocalEndPoint = null;
  114. }
  115. /// <summary>
  116. /// 启动DnscryptProxy进程
  117. /// </summary>
  118. /// <param name="arguments"></param>
  119. private static Process? StartDnscryptProxy(string arguments)
  120. {
  121. var fileName = OperatingSystem.IsWindows() ? $"{NAME}.exe" : NAME;
  122. return Process.Start(new ProcessStartInfo
  123. {
  124. FileName = Path.Combine(PATH, fileName),
  125. Arguments = arguments,
  126. WorkingDirectory = PATH,
  127. UseShellExecute = false,
  128. CreateNoWindow = true,
  129. WindowStyle = ProcessWindowStyle.Hidden
  130. });
  131. }
  132. /// <summary>
  133. /// 转换为字符串
  134. /// </summary>
  135. /// <returns></returns>
  136. public override string ToString()
  137. {
  138. return NAME;
  139. }
  140. }
  141. }