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