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