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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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)
  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(server.plugin, server.plugin_opts, server.plugin_args, server.server, server.server_port);
  33. }
  34. private Sip003Plugin(string plugin, string pluginOpts, string pluginArgs, string serverAddress, int serverPort)
  35. {
  36. if (plugin == null) throw new ArgumentNullException(nameof(plugin));
  37. if (string.IsNullOrWhiteSpace(serverAddress))
  38. {
  39. throw new ArgumentException("Value cannot be null or whitespace.", nameof(serverAddress));
  40. }
  41. if (serverPort <= 0 || serverPort > 65535)
  42. {
  43. throw new ArgumentOutOfRangeException("serverPort");
  44. }
  45. var appPath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath);
  46. _pluginProcess = new Process
  47. {
  48. StartInfo = new ProcessStartInfo
  49. {
  50. FileName = plugin,
  51. Arguments = pluginArgs,
  52. UseShellExecute = false,
  53. CreateNoWindow = true,
  54. ErrorDialog = false,
  55. WindowStyle = ProcessWindowStyle.Hidden,
  56. WorkingDirectory = appPath ?? Environment.CurrentDirectory,
  57. Environment =
  58. {
  59. ["SS_REMOTE_HOST"] = serverAddress,
  60. ["SS_REMOTE_PORT"] = serverPort.ToString(),
  61. ["SS_PLUGIN_OPTIONS"] = pluginOpts
  62. }
  63. }
  64. };
  65. _pluginJob = new Job();
  66. }
  67. public bool StartIfNeeded()
  68. {
  69. if (_disposed)
  70. {
  71. throw new ObjectDisposedException(GetType().FullName);
  72. }
  73. lock (_startProcessLock)
  74. {
  75. if (_started && !_pluginProcess.HasExited)
  76. {
  77. return false;
  78. }
  79. var localPort = GetNextFreeTcpPort();
  80. LocalEndPoint = new IPEndPoint(IPAddress.Loopback, localPort);
  81. _pluginProcess.StartInfo.Environment["SS_LOCAL_HOST"] = LocalEndPoint.Address.ToString();
  82. _pluginProcess.StartInfo.Environment["SS_LOCAL_PORT"] = LocalEndPoint.Port.ToString();
  83. _pluginProcess.StartInfo.Arguments = ExpandEnvironmentVariables(_pluginProcess.StartInfo.Arguments, _pluginProcess.StartInfo.EnvironmentVariables);
  84. _pluginProcess.Start();
  85. _pluginJob.AddProcess(_pluginProcess.Handle);
  86. _started = true;
  87. }
  88. return true;
  89. }
  90. public string ExpandEnvironmentVariables(string name, StringDictionary environmentVariables = null)
  91. {
  92. // Expand the environment variables from the new process itself
  93. if (environmentVariables != null)
  94. {
  95. foreach(string key in environmentVariables.Keys)
  96. {
  97. name = name.Replace($"%{key}%", environmentVariables[key], StringComparison.OrdinalIgnoreCase);
  98. }
  99. }
  100. // Also expand the environment variables from current main process (system)
  101. name = Environment.ExpandEnvironmentVariables(name);
  102. return name;
  103. }
  104. static int GetNextFreeTcpPort()
  105. {
  106. var l = new TcpListener(IPAddress.Loopback, 0);
  107. l.Start();
  108. int port = ((IPEndPoint)l.LocalEndpoint).Port;
  109. l.Stop();
  110. return port;
  111. }
  112. public void Dispose()
  113. {
  114. if (_disposed)
  115. {
  116. return;
  117. }
  118. try
  119. {
  120. if (!_pluginProcess.HasExited)
  121. {
  122. _pluginProcess.Kill();
  123. _pluginProcess.WaitForExit();
  124. }
  125. }
  126. catch (Exception) { }
  127. finally
  128. {
  129. try
  130. {
  131. _pluginProcess.Dispose();
  132. _pluginJob.Dispose();
  133. }
  134. catch (Exception) { }
  135. _disposed = true;
  136. }
  137. }
  138. }
  139. }