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.

ShadowsocksController.cs 22 kB

7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
7 years ago
11 years ago
7 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
11 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Web;
  11. using System.Windows.Forms;
  12. using NLog;
  13. using Shadowsocks.Controller.Service;
  14. using Shadowsocks.Controller.Strategy;
  15. using Shadowsocks.Model;
  16. using Shadowsocks.Util;
  17. namespace Shadowsocks.Controller
  18. {
  19. public class ShadowsocksController
  20. {
  21. private static Logger logger = LogManager.GetCurrentClassLogger();
  22. // controller:
  23. // handle user actions
  24. // manipulates UI
  25. // interacts with low level logic
  26. private Thread _ramThread;
  27. private Thread _trafficThread;
  28. private Listener _listener;
  29. private PACDaemon _pacDaemon;
  30. private PACServer _pacServer;
  31. private Configuration _config;
  32. private StrategyManager _strategyManager;
  33. private PrivoxyRunner privoxyRunner;
  34. private GFWListUpdater gfwListUpdater;
  35. private readonly ConcurrentDictionary<Server, Sip003Plugin> _pluginsByServer;
  36. public AvailabilityStatistics availabilityStatistics = AvailabilityStatistics.Instance;
  37. public StatisticsStrategyConfiguration StatisticsConfiguration { get; private set; }
  38. private long _inboundCounter = 0;
  39. private long _outboundCounter = 0;
  40. public long InboundCounter => Interlocked.Read(ref _inboundCounter);
  41. public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
  42. public Queue<TrafficPerSecond> trafficPerSecondQueue;
  43. private bool stopped = false;
  44. public class PathEventArgs : EventArgs
  45. {
  46. public string Path;
  47. }
  48. public class TrafficPerSecond
  49. {
  50. public long inboundCounter;
  51. public long outboundCounter;
  52. public long inboundIncreasement;
  53. public long outboundIncreasement;
  54. }
  55. public event EventHandler ConfigChanged;
  56. public event EventHandler EnableStatusChanged;
  57. public event EventHandler EnableGlobalChanged;
  58. public event EventHandler ShareOverLANStatusChanged;
  59. public event EventHandler VerboseLoggingStatusChanged;
  60. public event EventHandler ShowPluginOutputChanged;
  61. public event EventHandler TrafficChanged;
  62. // when user clicked Edit PAC, and PAC file has already created
  63. public event EventHandler<PathEventArgs> PACFileReadyToOpen;
  64. public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
  65. public event EventHandler<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
  66. public event ErrorEventHandler UpdatePACFromGFWListError;
  67. public event ErrorEventHandler Errored;
  68. public ShadowsocksController()
  69. {
  70. _config = Configuration.Load();
  71. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  72. _strategyManager = new StrategyManager(this);
  73. _pluginsByServer = new ConcurrentDictionary<Server, Sip003Plugin>();
  74. StartReleasingMemory();
  75. StartTrafficStatistics(61);
  76. }
  77. public void Start(bool regHotkeys = true)
  78. {
  79. Reload();
  80. if (regHotkeys)
  81. {
  82. HotkeyReg.RegAllHotkeys();
  83. }
  84. }
  85. protected void ReportError(Exception e)
  86. {
  87. Errored?.Invoke(this, new ErrorEventArgs(e));
  88. }
  89. public Server GetCurrentServer()
  90. {
  91. return _config.GetCurrentServer();
  92. }
  93. // always return copy
  94. public Configuration GetConfigurationCopy()
  95. {
  96. return Configuration.Load();
  97. }
  98. // always return current instance
  99. public Configuration GetCurrentConfiguration()
  100. {
  101. return _config;
  102. }
  103. public IList<IStrategy> GetStrategies()
  104. {
  105. return _strategyManager.GetStrategies();
  106. }
  107. public IStrategy GetCurrentStrategy()
  108. {
  109. foreach (var strategy in _strategyManager.GetStrategies())
  110. {
  111. if (strategy.ID == _config.strategy)
  112. {
  113. return strategy;
  114. }
  115. }
  116. return null;
  117. }
  118. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  119. {
  120. IStrategy strategy = GetCurrentStrategy();
  121. if (strategy != null)
  122. {
  123. return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
  124. }
  125. if (_config.index < 0)
  126. {
  127. _config.index = 0;
  128. }
  129. return GetCurrentServer();
  130. }
  131. public EndPoint GetPluginLocalEndPointIfConfigured(Server server)
  132. {
  133. var plugin = _pluginsByServer.GetOrAdd(
  134. server,
  135. x => Sip003Plugin.CreateIfConfigured(x, _config.showPluginOutput));
  136. if (plugin == null)
  137. {
  138. return null;
  139. }
  140. try
  141. {
  142. if (plugin.StartIfNeeded())
  143. {
  144. logger.Info(
  145. $"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. logger.Error("Failed to start SIP003 plugin: " + ex.Message);
  151. throw;
  152. }
  153. return plugin.LocalEndPoint;
  154. }
  155. public void SaveServers(List<Server> servers, int localPort, bool portableMode)
  156. {
  157. _config.configs = servers;
  158. _config.localPort = localPort;
  159. _config.portableMode = portableMode;
  160. Configuration.Save(_config);
  161. }
  162. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  163. {
  164. StatisticsConfiguration = configuration;
  165. StatisticsStrategyConfiguration.Save(configuration);
  166. }
  167. public bool AddServerBySSURL(string ssURL)
  168. {
  169. try
  170. {
  171. if (ssURL.IsNullOrEmpty() || ssURL.IsWhiteSpace())
  172. return false;
  173. var servers = Server.GetServers(ssURL);
  174. if (servers == null || servers.Count == 0)
  175. return false;
  176. foreach (var server in servers)
  177. {
  178. _config.configs.Add(server);
  179. }
  180. _config.index = _config.configs.Count - 1;
  181. SaveConfig(_config);
  182. return true;
  183. }
  184. catch (Exception e)
  185. {
  186. logger.LogUsefulException(e);
  187. return false;
  188. }
  189. }
  190. public void ToggleEnable(bool enabled)
  191. {
  192. _config.enabled = enabled;
  193. SaveConfig(_config);
  194. EnableStatusChanged?.Invoke(this, new EventArgs());
  195. }
  196. public void ToggleGlobal(bool global)
  197. {
  198. _config.global = global;
  199. SaveConfig(_config);
  200. EnableGlobalChanged?.Invoke(this, new EventArgs());
  201. }
  202. public void ToggleShareOverLAN(bool enabled)
  203. {
  204. _config.shareOverLan = enabled;
  205. SaveConfig(_config);
  206. ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
  207. }
  208. public void SaveProxy(ProxyConfig proxyConfig)
  209. {
  210. _config.proxy = proxyConfig;
  211. SaveConfig(_config);
  212. }
  213. public void ToggleVerboseLogging(bool enabled)
  214. {
  215. _config.isVerboseLogging = enabled;
  216. SaveConfig(_config);
  217. NLogConfig.LoadConfiguration(); // reload nlog
  218. VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
  219. }
  220. public void ToggleShowPluginOutput(bool enabled)
  221. {
  222. _config.showPluginOutput = enabled;
  223. SaveConfig(_config);
  224. ShowPluginOutputChanged?.Invoke(this, new EventArgs());
  225. }
  226. public void SelectServerIndex(int index)
  227. {
  228. _config.index = index;
  229. _config.strategy = null;
  230. SaveConfig(_config);
  231. }
  232. public void SelectStrategy(string strategyID)
  233. {
  234. _config.index = -1;
  235. _config.strategy = strategyID;
  236. SaveConfig(_config);
  237. }
  238. public void Stop()
  239. {
  240. if (stopped)
  241. {
  242. return;
  243. }
  244. stopped = true;
  245. if (_listener != null)
  246. {
  247. _listener.Stop();
  248. }
  249. StopPlugins();
  250. if (privoxyRunner != null)
  251. {
  252. privoxyRunner.Stop();
  253. }
  254. if (_config.enabled)
  255. {
  256. SystemProxy.Update(_config, true, null);
  257. }
  258. Encryption.RNG.Close();
  259. }
  260. private void StopPlugins()
  261. {
  262. foreach (var serverAndPlugin in _pluginsByServer)
  263. {
  264. serverAndPlugin.Value?.Dispose();
  265. }
  266. _pluginsByServer.Clear();
  267. }
  268. public void TouchPACFile()
  269. {
  270. string pacFilename = _pacDaemon.TouchPACFile();
  271. PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
  272. }
  273. public void TouchUserRuleFile()
  274. {
  275. string userRuleFilename = _pacDaemon.TouchUserRuleFile();
  276. UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
  277. }
  278. public string GetServerURLForCurrentServer()
  279. {
  280. Server server = GetCurrentServer();
  281. return GetServerURL(server);
  282. }
  283. public static string GetServerURL(Server server)
  284. {
  285. string tag = string.Empty;
  286. string url = string.Empty;
  287. if (string.IsNullOrWhiteSpace(server.plugin))
  288. {
  289. // For backwards compatiblity, if no plugin, use old url format
  290. string parts = $"{server.method}:{server.password}@{server.server}:{server.server_port}";
  291. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  292. url = base64;
  293. }
  294. else
  295. {
  296. // SIP002
  297. string parts = $"{server.method}:{server.password}";
  298. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  299. string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
  300. string pluginPart = server.plugin;
  301. if (!string.IsNullOrWhiteSpace(server.plugin_opts))
  302. {
  303. pluginPart += ";" + server.plugin_opts;
  304. }
  305. url = string.Format(
  306. "{0}@{1}:{2}/?plugin={3}",
  307. websafeBase64,
  308. server.FormatHostName(server.server),
  309. server.server_port,
  310. HttpUtility.UrlEncode(pluginPart, Encoding.UTF8));
  311. }
  312. if (!server.remarks.IsNullOrEmpty())
  313. {
  314. tag = $"#{HttpUtility.UrlEncode(server.remarks, Encoding.UTF8)}";
  315. }
  316. return $"ss://{url}{tag}";
  317. }
  318. public void UpdatePACFromGFWList()
  319. {
  320. if (gfwListUpdater != null)
  321. {
  322. gfwListUpdater.UpdatePACFromGFWList(_config);
  323. }
  324. }
  325. public void UpdateStatisticsConfiguration(bool enabled)
  326. {
  327. if (availabilityStatistics != null)
  328. {
  329. availabilityStatistics.UpdateConfiguration(this);
  330. _config.availabilityStatistics = enabled;
  331. SaveConfig(_config);
  332. }
  333. }
  334. public void SavePACUrl(string pacUrl)
  335. {
  336. _config.pacUrl = pacUrl;
  337. SaveConfig(_config);
  338. ConfigChanged?.Invoke(this, new EventArgs());
  339. }
  340. public void UseOnlinePAC(bool useOnlinePac)
  341. {
  342. _config.useOnlinePac = useOnlinePac;
  343. SaveConfig(_config);
  344. ConfigChanged?.Invoke(this, new EventArgs());
  345. }
  346. public void ToggleSecureLocalPac(bool enabled)
  347. {
  348. _config.secureLocalPac = enabled;
  349. SaveConfig(_config);
  350. ConfigChanged?.Invoke(this, new EventArgs());
  351. }
  352. public void ToggleCheckingUpdate(bool enabled)
  353. {
  354. _config.autoCheckUpdate = enabled;
  355. Configuration.Save(_config);
  356. ConfigChanged?.Invoke(this, new EventArgs());
  357. }
  358. public void ToggleCheckingPreRelease(bool enabled)
  359. {
  360. _config.checkPreRelease = enabled;
  361. Configuration.Save(_config);
  362. ConfigChanged?.Invoke(this, new EventArgs());
  363. }
  364. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  365. {
  366. _config.logViewer = newConfig;
  367. newConfig.SaveSize();
  368. Configuration.Save(_config);
  369. ConfigChanged?.Invoke(this, new EventArgs());
  370. }
  371. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  372. {
  373. _config.hotkey = newConfig;
  374. SaveConfig(_config);
  375. ConfigChanged?.Invoke(this, new EventArgs());
  376. }
  377. public void UpdateLatency(Server server, TimeSpan latency)
  378. {
  379. if (_config.availabilityStatistics)
  380. {
  381. availabilityStatistics.UpdateLatency(server, (int)latency.TotalMilliseconds);
  382. }
  383. }
  384. public void UpdateInboundCounter(Server server, long n)
  385. {
  386. Interlocked.Add(ref _inboundCounter, n);
  387. if (_config.availabilityStatistics)
  388. {
  389. availabilityStatistics.UpdateInboundCounter(server, n);
  390. }
  391. }
  392. public void UpdateOutboundCounter(Server server, long n)
  393. {
  394. Interlocked.Add(ref _outboundCounter, n);
  395. if (_config.availabilityStatistics)
  396. {
  397. availabilityStatistics.UpdateOutboundCounter(server, n);
  398. }
  399. }
  400. protected void Reload()
  401. {
  402. Encryption.RNG.Reload();
  403. // some logic in configuration updated the config when saving, we need to read it again
  404. _config = Configuration.Load();
  405. NLogConfig.LoadConfiguration();
  406. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  407. privoxyRunner = privoxyRunner ?? new PrivoxyRunner();
  408. _pacDaemon = _pacDaemon ?? new PACDaemon();
  409. _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;
  410. _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
  411. _pacServer = _pacServer ?? new PACServer(_pacDaemon);
  412. _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.
  413. gfwListUpdater = gfwListUpdater ?? new GFWListUpdater();
  414. gfwListUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
  415. gfwListUpdater.Error += PacServer_PACUpdateError;
  416. availabilityStatistics.UpdateConfiguration(this);
  417. _listener?.Stop();
  418. StopPlugins();
  419. // don't put PrivoxyRunner.Start() before pacServer.Stop()
  420. // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
  421. // though UseShellExecute is set to true now
  422. // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
  423. privoxyRunner.Stop();
  424. try
  425. {
  426. var strategy = GetCurrentStrategy();
  427. strategy?.ReloadServers();
  428. StartPlugin();
  429. privoxyRunner.Start(_config);
  430. TCPRelay tcpRelay = new TCPRelay(this, _config);
  431. UDPRelay udpRelay = new UDPRelay(this);
  432. List<Listener.IService> services = new List<Listener.IService>
  433. {
  434. tcpRelay,
  435. udpRelay,
  436. _pacServer,
  437. new PortForwarder(privoxyRunner.RunningPort)
  438. };
  439. _listener = new Listener(services);
  440. _listener.Start(_config);
  441. }
  442. catch (Exception e)
  443. {
  444. // translate Microsoft language into human language
  445. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  446. if (e is SocketException se)
  447. {
  448. if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)
  449. {
  450. e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e);
  451. }
  452. else if (se.SocketErrorCode == SocketError.AccessDenied)
  453. {
  454. e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
  455. }
  456. }
  457. logger.LogUsefulException(e);
  458. ReportError(e);
  459. }
  460. ConfigChanged?.Invoke(this, new EventArgs());
  461. UpdateSystemProxy();
  462. Utils.ReleaseMemory(true);
  463. }
  464. private void StartPlugin()
  465. {
  466. var server = _config.GetCurrentServer();
  467. GetPluginLocalEndPointIfConfigured(server);
  468. }
  469. protected void SaveConfig(Configuration newConfig)
  470. {
  471. Configuration.Save(newConfig);
  472. Reload();
  473. }
  474. private void UpdateSystemProxy()
  475. {
  476. SystemProxy.Update(_config, false, _pacServer);
  477. }
  478. private void PacDaemon_PACFileChanged(object sender, EventArgs e)
  479. {
  480. UpdateSystemProxy();
  481. }
  482. private void PacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  483. {
  484. UpdatePACFromGFWListCompleted?.Invoke(this, e);
  485. }
  486. private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)
  487. {
  488. UpdatePACFromGFWListError?.Invoke(this, e);
  489. }
  490. private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };
  491. private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)
  492. {
  493. if (!File.Exists(Utils.GetTempPath("gfwlist.txt")))
  494. {
  495. UpdatePACFromGFWList();
  496. }
  497. else
  498. {
  499. GFWListUpdater.MergeAndWritePACFile(FileManager.NonExclusiveReadAllText(Utils.GetTempPath("gfwlist.txt")));
  500. }
  501. UpdateSystemProxy();
  502. }
  503. public void CopyPacUrl()
  504. {
  505. Clipboard.SetDataObject(_pacServer.PacUrl);
  506. }
  507. #region Memory Management
  508. private void StartReleasingMemory()
  509. {
  510. _ramThread = new Thread(new ThreadStart(ReleaseMemory))
  511. {
  512. IsBackground = true
  513. };
  514. _ramThread.Start();
  515. }
  516. private void ReleaseMemory()
  517. {
  518. while (true)
  519. {
  520. Utils.ReleaseMemory(false);
  521. Thread.Sleep(30 * 1000);
  522. }
  523. }
  524. #endregion
  525. #region Traffic Statistics
  526. private void StartTrafficStatistics(int queueMaxSize)
  527. {
  528. trafficPerSecondQueue = new Queue<TrafficPerSecond>();
  529. for (int i = 0; i < queueMaxSize; i++)
  530. {
  531. trafficPerSecondQueue.Enqueue(new TrafficPerSecond());
  532. }
  533. _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))
  534. {
  535. IsBackground = true
  536. };
  537. _trafficThread.Start();
  538. }
  539. private void TrafficStatistics(int queueMaxSize)
  540. {
  541. TrafficPerSecond previous, current;
  542. while (true)
  543. {
  544. previous = trafficPerSecondQueue.Last();
  545. current = new TrafficPerSecond
  546. {
  547. inboundCounter = InboundCounter,
  548. outboundCounter = OutboundCounter
  549. };
  550. current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;
  551. current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;
  552. trafficPerSecondQueue.Enqueue(current);
  553. if (trafficPerSecondQueue.Count > queueMaxSize)
  554. trafficPerSecondQueue.Dequeue();
  555. TrafficChanged?.Invoke(this, new EventArgs());
  556. Thread.Sleep(1000);
  557. }
  558. }
  559. #endregion
  560. }
  561. }