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