You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Sip003Plugin.cs 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using Shadowsocks.Model;
  8. using Shadowsocks.Util.ProcessManagement;
  9. namespace Shadowsocks.Controller.Service
  10. {
  11. // https://github.com/shadowsocks/shadowsocks-org/wiki/Plugin
  12. public sealed class Sip003Plugin : IDisposable
  13. {
  14. public IPEndPoint LocalEndPoint { get; private set; }
  15. public int ProcessId => _started ? _pluginProcess.Id : 0;
  16. private readonly object _startProcessLock = new object();
  17. private readonly Job _pluginJob;
  18. private readonly Process _pluginProcess;
  19. private bool _started;
  20. private bool _disposed;
  21. public static Sip003Plugin CreateIfConfigured(Server server, bool showPluginOutput)
  22. {
  23. if (server == null)
  24. {
  25. throw new ArgumentNullException(nameof(server));
  26. }
  27. if (string.IsNullOrWhiteSpace(server.plugin))
  28. {
  29. return null;
  30. }
  31. return new Sip003Plugin(
  32. server.plugin,
  33. server.plugin_opts,
  34. server.plugin_args,
  35. server.server,
  36. server.server_port,
  37. showPluginOutput);
  38. }
  39. private Sip003Plugin(string plugin, string pluginOpts, string pluginArgs, string serverAddress, int serverPort, bool showPluginOutput)
  40. {
  41. if (plugin == null) throw new ArgumentNullException(nameof(plugin));
  42. if (string.IsNullOrWhiteSpace(serverAddress))
  43. {
  44. throw new ArgumentException("Value cannot be null or whitespace.", nameof(serverAddress));
  45. }
  46. if (serverPort <= 0 || serverPort > 65535)
  47. {
  48. throw new ArgumentOutOfRangeException("serverPort");
  49. }
  50. _pluginProcess = new Process
  51. {
  52. StartInfo = new ProcessStartInfo
  53. {
  54. FileName = plugin,
  55. Arguments = pluginArgs,
  56. UseShellExecute = false,
  57. CreateNoWindow = !showPluginOutput,
  58. ErrorDialog = false,
  59. WindowStyle = ProcessWindowStyle.Hidden,
  60. WorkingDirectory = Program.WorkingDirectory ?? Environment.CurrentDirectory,
  61. Environment =
  62. {
  63. ["SS_REMOTE_HOST"] = serverAddress,
  64. ["SS_REMOTE_PORT"] = serverPort.ToString(),
  65. ["SS_PLUGIN_OPTIONS"] = pluginOpts
  66. }
  67. }
  68. };
  69. _pluginJob = new Job();
  70. }
  71. public bool StartIfNeeded()
  72. {
  73. if (_disposed)
  74. {
  75. throw new ObjectDisposedException(GetType().FullName);
  76. }
  77. lock (_startProcessLock)
  78. {
  79. if (_started && !_pluginProcess.HasExited)
  80. {
  81. return false;
  82. }
  83. var localPort = GetNextFreeTcpPort();
  84. LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);
  85. _pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
  86. _pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
  87. _pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);
  88. try
  89. {
  90. _pluginProcess.Start();
  91. }
  92. catch (System.ComponentModel.Win32Exception ex)
  93. {
  94. // do not use File.Exists(...), it can not handle the scenarios when the plugin file is in system environment path.
  95. // https://docs.microsoft.com/en-us/windows/win32/seccrypto/common-hresult-values
  96. //if ((uint)ex.ErrorCode == 0x80004005)
  97. // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
  98. if (ex.NativeErrorCode == 0x00000002)
  99. {
  100. throw new FileNotFoundException(I18N.GetString("Cannot find the plugin program file"), _pluginProcess.StartInfo.FileName, ex);
  101. }
  102. throw new ApplicationException(I18N.GetString("Plugin Program"), ex);
  103. }
  104. _pluginJob.AddProcess(_pluginProcess.Handle);
  105. _started = true;
  106. }
  107. return true;
  108. }
  109. public string ExpandEnvironmentVariables(string name, StringDictionary environmentVariables = null)
  110. {
  111. // Expand the environment variables from the new process itself
  112. if (environmentVariables != null)
  113. {
  114. foreach(string key in environmentVariables.Keys)
  115. {
  116. name = name.Replace($"%{key}%", environmentVariables[key], StringComparison.OrdinalIgnoreCase);
  117. }
  118. }
  119. // Also expand the environment variables from current main process (system)
  120. name = Environment.ExpandEnvironmentVariables(name);
  121. return name;
  122. }
  123. static int GetNextFreeTcpPort()
  124. {
  125. var l = new TcpListener(IPAddress.Loopback, 0);
  126. l.Start();
  127. int port = ((IPEndPoint)l.LocalEndpoint).Port;
  128. l.Stop();
  129. return port;
  130. }
  131. public void Dispose()
  132. {
  133. if (_disposed)
  134. {
  135. return;
  136. }
  137. try
  138. {
  139. if (!_pluginProcess.HasExited)
  140. {
  141. _pluginProcess.Kill();
  142. _pluginProcess.WaitForExit();
  143. }
  144. }
  145. catch (Exception) { }
  146. finally
  147. {
  148. try
  149. {
  150. _pluginProcess.Dispose();
  151. _pluginJob.Dispose();
  152. }
  153. catch (Exception) { }
  154. _disposed = true;
  155. }
  156. }
  157. }
  158. }