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