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

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