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.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. var localPort = GetNextFreeTcpPort();
  86. LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);
  87. _pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
  88. _pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
  89. _pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);
  90. _pluginProcess.Start();
  91. _pluginJob.AddProcess(_pluginProcess.Handle);
  92. _started = true;
  93. }
  94. return true;
  95. }
  96. public string ExpandEnvironmentVariables(string name, StringDictionary environmentVariables = null)
  97. {
  98. // Expand the environment variables from the new process itself
  99. if (environmentVariables != null)
  100. {
  101. foreach(string key in environmentVariables.Keys)
  102. {
  103. name = name.Replace($"%{key}%", environmentVariables[key], StringComparison.OrdinalIgnoreCase);
  104. }
  105. }
  106. // Also expand the environment variables from current main process (system)
  107. name = Environment.ExpandEnvironmentVariables(name);
  108. return name;
  109. }
  110. static int GetNextFreeTcpPort()
  111. {
  112. var l = new TcpListener(IPAddress.Loopback, 0);
  113. l.Start();
  114. int port = ((IPEndPoint)l.LocalEndpoint).Port;
  115. l.Stop();
  116. return port;
  117. }
  118. public void Dispose()
  119. {
  120. if (_disposed)
  121. {
  122. return;
  123. }
  124. try
  125. {
  126. if (!_pluginProcess.HasExited)
  127. {
  128. _pluginProcess.Kill();
  129. _pluginProcess.WaitForExit();
  130. }
  131. }
  132. catch (Exception) { }
  133. finally
  134. {
  135. try
  136. {
  137. _pluginProcess.Dispose();
  138. _pluginJob.Dispose();
  139. }
  140. catch (Exception) { }
  141. _disposed = true;
  142. }
  143. }
  144. }
  145. }