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 21 kB

7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 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
7 years ago
11 years ago
11 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
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
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 PACServer _pacServer;
  28. private Configuration _config;
  29. private StrategyManager _strategyManager;
  30. private PrivoxyRunner privoxyRunner;
  31. private GFWListUpdater gfwListUpdater;
  32. private readonly ConcurrentDictionary<Server, Sip003Plugin> _pluginsByServer;
  33. public AvailabilityStatistics availabilityStatistics = AvailabilityStatistics.Instance;
  34. public StatisticsStrategyConfiguration StatisticsConfiguration { get; private set; }
  35. private long _inboundCounter = 0;
  36. private long _outboundCounter = 0;
  37. public long InboundCounter => Interlocked.Read(ref _inboundCounter);
  38. public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
  39. public Queue<TrafficPerSecond> trafficPerSecondQueue;
  40. private bool stopped = false;
  41. public class PathEventArgs : EventArgs
  42. {
  43. public string Path;
  44. }
  45. public class TrafficPerSecond
  46. {
  47. public long inboundCounter;
  48. public long outboundCounter;
  49. public long inboundIncreasement;
  50. public long outboundIncreasement;
  51. }
  52. public event EventHandler ConfigChanged;
  53. public event EventHandler EnableStatusChanged;
  54. public event EventHandler EnableGlobalChanged;
  55. public event EventHandler ShareOverLANStatusChanged;
  56. public event EventHandler VerboseLoggingStatusChanged;
  57. public event EventHandler TrafficChanged;
  58. // when user clicked Edit PAC, and PAC file has already created
  59. public event EventHandler<PathEventArgs> PACFileReadyToOpen;
  60. public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
  61. public event EventHandler<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
  62. public event ErrorEventHandler UpdatePACFromGFWListError;
  63. public event ErrorEventHandler Errored;
  64. public ShadowsocksController()
  65. {
  66. _config = Configuration.Load();
  67. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  68. _strategyManager = new StrategyManager(this);
  69. _pluginsByServer = new ConcurrentDictionary<Server, Sip003Plugin>();
  70. StartReleasingMemory();
  71. StartTrafficStatistics(61);
  72. }
  73. public void Start(bool regHotkeys = true)
  74. {
  75. Reload();
  76. if (regHotkeys)
  77. {
  78. HotkeyReg.RegAllHotkeys();
  79. }
  80. }
  81. protected void ReportError(Exception e)
  82. {
  83. Errored?.Invoke(this, new ErrorEventArgs(e));
  84. }
  85. public Server GetCurrentServer()
  86. {
  87. return _config.GetCurrentServer();
  88. }
  89. // always return copy
  90. public Configuration GetConfigurationCopy()
  91. {
  92. return Configuration.Load();
  93. }
  94. // always return current instance
  95. public Configuration GetCurrentConfiguration()
  96. {
  97. return _config;
  98. }
  99. public IList<IStrategy> GetStrategies()
  100. {
  101. return _strategyManager.GetStrategies();
  102. }
  103. public IStrategy GetCurrentStrategy()
  104. {
  105. foreach (var strategy in _strategyManager.GetStrategies())
  106. {
  107. if (strategy.ID == _config.strategy)
  108. {
  109. return strategy;
  110. }
  111. }
  112. return null;
  113. }
  114. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  115. {
  116. IStrategy strategy = GetCurrentStrategy();
  117. if (strategy != null)
  118. {
  119. return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
  120. }
  121. if (_config.index < 0)
  122. {
  123. _config.index = 0;
  124. }
  125. return GetCurrentServer();
  126. }
  127. public EndPoint GetPluginLocalEndPointIfConfigured(Server server)
  128. {
  129. var plugin = _pluginsByServer.GetOrAdd(server, Sip003Plugin.CreateIfConfigured);
  130. if (plugin == null)
  131. {
  132. return null;
  133. }
  134. try
  135. {
  136. if (plugin.StartIfNeeded())
  137. {
  138. Logging.Info(
  139. $"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
  140. }
  141. }
  142. catch (Exception ex)
  143. {
  144. Logging.Error("Failed to start SIP003 plugin: " + ex.Message);
  145. throw;
  146. }
  147. return plugin.LocalEndPoint;
  148. }
  149. public void SaveServers(List<Server> servers, int localPort, bool portableMode)
  150. {
  151. _config.configs = servers;
  152. _config.localPort = localPort;
  153. _config.portableMode = portableMode;
  154. Configuration.Save(_config);
  155. }
  156. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  157. {
  158. StatisticsConfiguration = configuration;
  159. StatisticsStrategyConfiguration.Save(configuration);
  160. }
  161. public bool AddServerBySSURL(string ssURL)
  162. {
  163. try
  164. {
  165. if (ssURL.IsNullOrEmpty() || ssURL.IsWhiteSpace())
  166. return false;
  167. var servers = Server.GetServers(ssURL);
  168. if (servers == null || servers.Count == 0)
  169. return false;
  170. foreach (var server in servers)
  171. {
  172. _config.configs.Add(server);
  173. }
  174. _config.index = _config.configs.Count - 1;
  175. SaveConfig(_config);
  176. return true;
  177. }
  178. catch (Exception e)
  179. {
  180. Logging.LogUsefulException(e);
  181. return false;
  182. }
  183. }
  184. public void ToggleEnable(bool enabled)
  185. {
  186. _config.enabled = enabled;
  187. SaveConfig(_config);
  188. EnableStatusChanged?.Invoke(this, new EventArgs());
  189. }
  190. public void ToggleGlobal(bool global)
  191. {
  192. _config.global = global;
  193. SaveConfig(_config);
  194. EnableGlobalChanged?.Invoke(this, new EventArgs());
  195. }
  196. public void ToggleShareOverLAN(bool enabled)
  197. {
  198. _config.shareOverLan = enabled;
  199. SaveConfig(_config);
  200. ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
  201. }
  202. public void SaveProxy(ProxyConfig proxyConfig)
  203. {
  204. _config.proxy = proxyConfig;
  205. SaveConfig(_config);
  206. }
  207. public void ToggleVerboseLogging(bool enabled)
  208. {
  209. _config.isVerboseLogging = enabled;
  210. SaveConfig(_config);
  211. VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
  212. }
  213. public void SelectServerIndex(int index)
  214. {
  215. _config.index = index;
  216. _config.strategy = null;
  217. SaveConfig(_config);
  218. }
  219. public void SelectStrategy(string strategyID)
  220. {
  221. _config.index = -1;
  222. _config.strategy = strategyID;
  223. SaveConfig(_config);
  224. }
  225. public void Stop()
  226. {
  227. if (stopped)
  228. {
  229. return;
  230. }
  231. stopped = true;
  232. if (_listener != null)
  233. {
  234. _listener.Stop();
  235. }
  236. StopPlugins();
  237. if (privoxyRunner != null)
  238. {
  239. privoxyRunner.Stop();
  240. }
  241. if (_config.enabled)
  242. {
  243. SystemProxy.Update(_config, true, null);
  244. }
  245. Encryption.RNG.Close();
  246. }
  247. private void StopPlugins()
  248. {
  249. foreach (var serverAndPlugin in _pluginsByServer)
  250. {
  251. serverAndPlugin.Value?.Dispose();
  252. }
  253. _pluginsByServer.Clear();
  254. }
  255. public void TouchPACFile()
  256. {
  257. string pacFilename = _pacServer.TouchPACFile();
  258. PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
  259. }
  260. public void TouchUserRuleFile()
  261. {
  262. string userRuleFilename = _pacServer.TouchUserRuleFile();
  263. UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
  264. }
  265. public string GetServerURLForCurrentServer()
  266. {
  267. Server server = GetCurrentServer();
  268. return GetServerURL(server);
  269. }
  270. public static string GetServerURL(Server server)
  271. {
  272. string tag = string.Empty;
  273. string url = string.Empty;
  274. if (string.IsNullOrWhiteSpace(server.plugin))
  275. {
  276. // For backwards compatiblity, if no plugin, use old url format
  277. string parts = $"{server.method}:{server.password}@{server.server}:{server.server_port}";
  278. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  279. url = base64;
  280. }
  281. else
  282. {
  283. // SIP002
  284. string parts = $"{server.method}:{server.password}";
  285. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  286. string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
  287. string pluginPart = server.plugin;
  288. if (!string.IsNullOrWhiteSpace(server.plugin_opts))
  289. {
  290. pluginPart += ";" + server.plugin_opts;
  291. }
  292. url = string.Format(
  293. "{0}@{1}:{2}/?plugin={3}",
  294. websafeBase64,
  295. server.FormatHostName(server.server),
  296. server.server_port,
  297. HttpUtility.UrlEncode(pluginPart, Encoding.UTF8));
  298. }
  299. if (!server.remarks.IsNullOrEmpty())
  300. {
  301. tag = $"#{HttpUtility.UrlEncode(server.remarks, Encoding.UTF8)}";
  302. }
  303. return $"ss://{url}{tag}";
  304. }
  305. public void UpdatePACFromGFWList()
  306. {
  307. if (gfwListUpdater != null)
  308. {
  309. gfwListUpdater.UpdatePACFromGFWList(_config);
  310. }
  311. }
  312. public void UpdateStatisticsConfiguration(bool enabled)
  313. {
  314. if (availabilityStatistics != null)
  315. {
  316. availabilityStatistics.UpdateConfiguration(this);
  317. _config.availabilityStatistics = enabled;
  318. SaveConfig(_config);
  319. }
  320. }
  321. public void SavePACUrl(string pacUrl)
  322. {
  323. _config.pacUrl = pacUrl;
  324. SaveConfig(_config);
  325. ConfigChanged?.Invoke(this, new EventArgs());
  326. }
  327. public void UseOnlinePAC(bool useOnlinePac)
  328. {
  329. _config.useOnlinePac = useOnlinePac;
  330. SaveConfig(_config);
  331. ConfigChanged?.Invoke(this, new EventArgs());
  332. }
  333. public void ToggleSecureLocalPac(bool enabled)
  334. {
  335. _config.secureLocalPac = enabled;
  336. SaveConfig(_config);
  337. ConfigChanged?.Invoke(this, new EventArgs());
  338. }
  339. public void ToggleCheckingUpdate(bool enabled)
  340. {
  341. _config.autoCheckUpdate = enabled;
  342. Configuration.Save(_config);
  343. ConfigChanged?.Invoke(this, new EventArgs());
  344. }
  345. public void ToggleCheckingPreRelease(bool enabled)
  346. {
  347. _config.checkPreRelease = enabled;
  348. Configuration.Save(_config);
  349. ConfigChanged?.Invoke(this, new EventArgs());
  350. }
  351. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  352. {
  353. _config.logViewer = newConfig;
  354. newConfig.SaveSize();
  355. Configuration.Save(_config);
  356. ConfigChanged?.Invoke(this, new EventArgs());
  357. }
  358. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  359. {
  360. _config.hotkey = newConfig;
  361. SaveConfig(_config);
  362. ConfigChanged?.Invoke(this, new EventArgs());
  363. }
  364. public void UpdateLatency(Server server, TimeSpan latency)
  365. {
  366. if (_config.availabilityStatistics)
  367. {
  368. availabilityStatistics.UpdateLatency(server, (int)latency.TotalMilliseconds);
  369. }
  370. }
  371. public void UpdateInboundCounter(Server server, long n)
  372. {
  373. Interlocked.Add(ref _inboundCounter, n);
  374. if (_config.availabilityStatistics)
  375. {
  376. availabilityStatistics.UpdateInboundCounter(server, n);
  377. }
  378. }
  379. public void UpdateOutboundCounter(Server server, long n)
  380. {
  381. Interlocked.Add(ref _outboundCounter, n);
  382. if (_config.availabilityStatistics)
  383. {
  384. availabilityStatistics.UpdateOutboundCounter(server, n);
  385. }
  386. }
  387. protected void Reload()
  388. {
  389. Encryption.RNG.Reload();
  390. // some logic in configuration updated the config when saving, we need to read it again
  391. _config = Configuration.Load();
  392. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  393. if (privoxyRunner == null)
  394. {
  395. privoxyRunner = new PrivoxyRunner();
  396. }
  397. if (_pacServer == null)
  398. {
  399. _pacServer = new PACServer();
  400. _pacServer.PACFileChanged += PacServer_PACFileChanged;
  401. _pacServer.UserRuleFileChanged += PacServer_UserRuleFileChanged;
  402. }
  403. _pacServer.UpdateConfiguration(_config);
  404. if (gfwListUpdater == null)
  405. {
  406. gfwListUpdater = new GFWListUpdater();
  407. gfwListUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
  408. gfwListUpdater.Error += PacServer_PACUpdateError;
  409. }
  410. availabilityStatistics.UpdateConfiguration(this);
  411. if (_listener != null)
  412. {
  413. _listener.Stop();
  414. }
  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. if (strategy != null)
  425. {
  426. strategy.ReloadServers();
  427. }
  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. Logging.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 PacServer_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 PacServer_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. }