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

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
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
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 void AskAddServerBySSURL(string ssURL)
  189. {
  190. var dr = MessageBox.Show(I18N.GetString("Import from URL: {0} ?", ssURL), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo);
  191. if (dr == DialogResult.Yes)
  192. {
  193. AddServerBySSURL(ssURL);
  194. }
  195. }
  196. public bool AddServerBySSURL(string ssURL)
  197. {
  198. try
  199. {
  200. if (ssURL.IsNullOrEmpty() || ssURL.IsWhiteSpace())
  201. return false;
  202. var servers = Server.GetServers(ssURL);
  203. if (servers == null || servers.Count == 0)
  204. return false;
  205. foreach (var server in servers)
  206. {
  207. _config.configs.Add(server);
  208. }
  209. _config.index = _config.configs.Count - 1;
  210. SaveConfig(_config);
  211. return true;
  212. }
  213. catch (Exception e)
  214. {
  215. logger.LogUsefulException(e);
  216. return false;
  217. }
  218. }
  219. public void ToggleEnable(bool enabled)
  220. {
  221. _config.enabled = enabled;
  222. SaveConfig(_config);
  223. EnableStatusChanged?.Invoke(this, new EventArgs());
  224. }
  225. public void ToggleGlobal(bool global)
  226. {
  227. _config.global = global;
  228. SaveConfig(_config);
  229. EnableGlobalChanged?.Invoke(this, new EventArgs());
  230. }
  231. public void ToggleShareOverLAN(bool enabled)
  232. {
  233. _config.shareOverLan = enabled;
  234. SaveConfig(_config);
  235. ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
  236. }
  237. public void SaveProxy(ProxyConfig proxyConfig)
  238. {
  239. _config.proxy = proxyConfig;
  240. SaveConfig(_config);
  241. }
  242. public void ToggleVerboseLogging(bool enabled)
  243. {
  244. _config.isVerboseLogging = enabled;
  245. SaveConfig(_config);
  246. NLogConfig.LoadConfiguration(); // reload nlog
  247. VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
  248. }
  249. public void ToggleShowPluginOutput(bool enabled)
  250. {
  251. _config.showPluginOutput = enabled;
  252. SaveConfig(_config);
  253. ShowPluginOutputChanged?.Invoke(this, new EventArgs());
  254. }
  255. public void SelectServerIndex(int index)
  256. {
  257. _config.index = index;
  258. _config.strategy = null;
  259. SaveConfig(_config);
  260. }
  261. public void SelectStrategy(string strategyID)
  262. {
  263. _config.index = -1;
  264. _config.strategy = strategyID;
  265. SaveConfig(_config);
  266. }
  267. public void Stop()
  268. {
  269. if (stopped)
  270. {
  271. return;
  272. }
  273. stopped = true;
  274. if (_listener != null)
  275. {
  276. _listener.Stop();
  277. }
  278. StopPlugins();
  279. if (privoxyRunner != null)
  280. {
  281. privoxyRunner.Stop();
  282. }
  283. if (_config.enabled)
  284. {
  285. SystemProxy.Update(_config, true, null);
  286. }
  287. Encryption.RNG.Close();
  288. }
  289. private void StopPlugins()
  290. {
  291. foreach (var serverAndPlugin in _pluginsByServer)
  292. {
  293. serverAndPlugin.Value?.Dispose();
  294. }
  295. _pluginsByServer.Clear();
  296. }
  297. public void TouchPACFile()
  298. {
  299. string pacFilename = _pacDaemon.TouchPACFile();
  300. PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
  301. }
  302. public void TouchUserRuleFile()
  303. {
  304. string userRuleFilename = _pacDaemon.TouchUserRuleFile();
  305. UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
  306. }
  307. public string GetServerURLForCurrentServer()
  308. {
  309. Server server = GetCurrentServer();
  310. return GetServerURL(server);
  311. }
  312. public static string GetServerURL(Server server)
  313. {
  314. string tag = string.Empty;
  315. string url = string.Empty;
  316. if (string.IsNullOrWhiteSpace(server.plugin))
  317. {
  318. // For backwards compatiblity, if no plugin, use old url format
  319. string parts = $"{server.method}:{server.password}@{server.server}:{server.server_port}";
  320. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  321. url = base64;
  322. }
  323. else
  324. {
  325. // SIP002
  326. string parts = $"{server.method}:{server.password}";
  327. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  328. string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
  329. string pluginPart = server.plugin;
  330. if (!string.IsNullOrWhiteSpace(server.plugin_opts))
  331. {
  332. pluginPart += ";" + server.plugin_opts;
  333. }
  334. url = string.Format(
  335. "{0}@{1}:{2}/?plugin={3}",
  336. websafeBase64,
  337. server.FormatHostName(server.server),
  338. server.server_port,
  339. HttpUtility.UrlEncode(pluginPart, Encoding.UTF8));
  340. }
  341. if (!server.remarks.IsNullOrEmpty())
  342. {
  343. tag = $"#{HttpUtility.UrlEncode(server.remarks, Encoding.UTF8)}";
  344. }
  345. return $"ss://{url}{tag}";
  346. }
  347. public void UpdatePACFromGFWList()
  348. {
  349. if (gfwListUpdater != null)
  350. {
  351. gfwListUpdater.UpdatePACFromGFWList(_config);
  352. }
  353. }
  354. public void UpdateStatisticsConfiguration(bool enabled)
  355. {
  356. if (availabilityStatistics != null)
  357. {
  358. availabilityStatistics.UpdateConfiguration(this);
  359. _config.availabilityStatistics = enabled;
  360. SaveConfig(_config);
  361. }
  362. }
  363. public void SavePACUrl(string pacUrl)
  364. {
  365. _config.pacUrl = pacUrl;
  366. SaveConfig(_config);
  367. ConfigChanged?.Invoke(this, new EventArgs());
  368. }
  369. public void UseOnlinePAC(bool useOnlinePac)
  370. {
  371. _config.useOnlinePac = useOnlinePac;
  372. SaveConfig(_config);
  373. ConfigChanged?.Invoke(this, new EventArgs());
  374. }
  375. public void ToggleSecureLocalPac(bool enabled)
  376. {
  377. _config.secureLocalPac = enabled;
  378. SaveConfig(_config);
  379. ConfigChanged?.Invoke(this, new EventArgs());
  380. }
  381. public void ToggleCheckingUpdate(bool enabled)
  382. {
  383. _config.autoCheckUpdate = enabled;
  384. Configuration.Save(_config);
  385. ConfigChanged?.Invoke(this, new EventArgs());
  386. }
  387. public void ToggleCheckingPreRelease(bool enabled)
  388. {
  389. _config.checkPreRelease = enabled;
  390. Configuration.Save(_config);
  391. ConfigChanged?.Invoke(this, new EventArgs());
  392. }
  393. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  394. {
  395. _config.logViewer = newConfig;
  396. newConfig.SaveSize();
  397. Configuration.Save(_config);
  398. ConfigChanged?.Invoke(this, new EventArgs());
  399. }
  400. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  401. {
  402. _config.hotkey = newConfig;
  403. SaveConfig(_config);
  404. ConfigChanged?.Invoke(this, new EventArgs());
  405. }
  406. public void UpdateLatency(Server server, TimeSpan latency)
  407. {
  408. if (_config.availabilityStatistics)
  409. {
  410. availabilityStatistics.UpdateLatency(server, (int)latency.TotalMilliseconds);
  411. }
  412. }
  413. public void UpdateInboundCounter(Server server, long n)
  414. {
  415. Interlocked.Add(ref _inboundCounter, n);
  416. if (_config.availabilityStatistics)
  417. {
  418. availabilityStatistics.UpdateInboundCounter(server, n);
  419. }
  420. }
  421. public void UpdateOutboundCounter(Server server, long n)
  422. {
  423. Interlocked.Add(ref _outboundCounter, n);
  424. if (_config.availabilityStatistics)
  425. {
  426. availabilityStatistics.UpdateOutboundCounter(server, n);
  427. }
  428. }
  429. protected void Reload()
  430. {
  431. Encryption.RNG.Reload();
  432. // some logic in configuration updated the config when saving, we need to read it again
  433. _config = Configuration.Load();
  434. NLogConfig.LoadConfiguration();
  435. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  436. privoxyRunner = privoxyRunner ?? new PrivoxyRunner();
  437. _pacDaemon = _pacDaemon ?? new PACDaemon();
  438. _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;
  439. _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
  440. _pacServer = _pacServer ?? new PACServer(_pacDaemon);
  441. _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.
  442. gfwListUpdater = gfwListUpdater ?? new GFWListUpdater();
  443. gfwListUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
  444. gfwListUpdater.Error += PacServer_PACUpdateError;
  445. availabilityStatistics.UpdateConfiguration(this);
  446. _listener?.Stop();
  447. StopPlugins();
  448. // don't put PrivoxyRunner.Start() before pacServer.Stop()
  449. // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
  450. // though UseShellExecute is set to true now
  451. // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
  452. privoxyRunner.Stop();
  453. try
  454. {
  455. var strategy = GetCurrentStrategy();
  456. strategy?.ReloadServers();
  457. StartPlugin();
  458. privoxyRunner.Start(_config);
  459. TCPRelay tcpRelay = new TCPRelay(this, _config);
  460. UDPRelay udpRelay = new UDPRelay(this);
  461. List<Listener.IService> services = new List<Listener.IService>
  462. {
  463. tcpRelay,
  464. udpRelay,
  465. _pacServer,
  466. new PortForwarder(privoxyRunner.RunningPort)
  467. };
  468. _listener = new Listener(services);
  469. _listener.Start(_config);
  470. }
  471. catch (Exception e)
  472. {
  473. // translate Microsoft language into human language
  474. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  475. if (e is SocketException se)
  476. {
  477. if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)
  478. {
  479. e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e);
  480. }
  481. else if (se.SocketErrorCode == SocketError.AccessDenied)
  482. {
  483. e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
  484. }
  485. }
  486. logger.LogUsefulException(e);
  487. ReportError(e);
  488. }
  489. ConfigChanged?.Invoke(this, new EventArgs());
  490. UpdateSystemProxy();
  491. Utils.ReleaseMemory(true);
  492. }
  493. private void StartPlugin()
  494. {
  495. var server = _config.GetCurrentServer();
  496. GetPluginLocalEndPointIfConfigured(server);
  497. }
  498. protected void SaveConfig(Configuration newConfig)
  499. {
  500. Configuration.Save(newConfig);
  501. Reload();
  502. }
  503. private void UpdateSystemProxy()
  504. {
  505. SystemProxy.Update(_config, false, _pacServer);
  506. }
  507. private void PacDaemon_PACFileChanged(object sender, EventArgs e)
  508. {
  509. UpdateSystemProxy();
  510. }
  511. private void PacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  512. {
  513. UpdatePACFromGFWListCompleted?.Invoke(this, e);
  514. }
  515. private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)
  516. {
  517. UpdatePACFromGFWListError?.Invoke(this, e);
  518. }
  519. private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };
  520. private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)
  521. {
  522. if (!File.Exists(Utils.GetTempPath("gfwlist.txt")))
  523. {
  524. UpdatePACFromGFWList();
  525. }
  526. else
  527. {
  528. GFWListUpdater.MergeAndWritePACFile(FileManager.NonExclusiveReadAllText(Utils.GetTempPath("gfwlist.txt")));
  529. }
  530. UpdateSystemProxy();
  531. }
  532. public void CopyPacUrl()
  533. {
  534. Clipboard.SetDataObject(_pacServer.PacUrl);
  535. }
  536. #region Memory Management
  537. private void StartReleasingMemory()
  538. {
  539. _ramThread = new Thread(new ThreadStart(ReleaseMemory))
  540. {
  541. IsBackground = true
  542. };
  543. _ramThread.Start();
  544. }
  545. private void ReleaseMemory()
  546. {
  547. while (true)
  548. {
  549. Utils.ReleaseMemory(false);
  550. Thread.Sleep(30 * 1000);
  551. }
  552. }
  553. #endregion
  554. #region Traffic Statistics
  555. private void StartTrafficStatistics(int queueMaxSize)
  556. {
  557. trafficPerSecondQueue = new Queue<TrafficPerSecond>();
  558. for (int i = 0; i < queueMaxSize; i++)
  559. {
  560. trafficPerSecondQueue.Enqueue(new TrafficPerSecond());
  561. }
  562. _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))
  563. {
  564. IsBackground = true
  565. };
  566. _trafficThread.Start();
  567. }
  568. private void TrafficStatistics(int queueMaxSize)
  569. {
  570. TrafficPerSecond previous, current;
  571. while (true)
  572. {
  573. previous = trafficPerSecondQueue.Last();
  574. current = new TrafficPerSecond
  575. {
  576. inboundCounter = InboundCounter,
  577. outboundCounter = OutboundCounter
  578. };
  579. current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;
  580. current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;
  581. trafficPerSecondQueue.Enqueue(current);
  582. if (trafficPerSecondQueue.Count > queueMaxSize)
  583. trafficPerSecondQueue.Dequeue();
  584. TrafficChanged?.Invoke(this, new EventArgs());
  585. Thread.Sleep(1000);
  586. }
  587. }
  588. #endregion
  589. }
  590. }