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