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 5.8 kB

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