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 21 kB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Web;
  9. using System.Windows.Forms;
  10. using Newtonsoft.Json;
  11. using Shadowsocks.Controller.Service;
  12. using Shadowsocks.Controller.Strategy;
  13. using Shadowsocks.Model;
  14. using Shadowsocks.Properties;
  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 PACServer _pacServer;
  28. private Configuration _config;
  29. private StrategyManager _strategyManager;
  30. private GFWListUpdater gfwListUpdater;
  31. public AvailabilityStatistics availabilityStatistics = AvailabilityStatistics.Instance;
  32. public StatisticsStrategyConfiguration StatisticsConfiguration { get; private set; }
  33. private long _inboundCounter = 0;
  34. private long _outboundCounter = 0;
  35. public long InboundCounter => Interlocked.Read(ref _inboundCounter);
  36. public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
  37. public QueueLast<TrafficPerSecond> traffic;
  38. private bool stopped = false;
  39. private bool _systemProxyIsDirty = false;
  40. public class PathEventArgs : EventArgs
  41. {
  42. public string Path;
  43. }
  44. public class QueueLast<T> : Queue<T>
  45. {
  46. public T Last { get; private set; }
  47. public new void Enqueue(T item)
  48. {
  49. Last = item;
  50. base.Enqueue(item);
  51. }
  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 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<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
  70. public event ErrorEventHandler UpdatePACFromGFWListError;
  71. public event ErrorEventHandler Errored;
  72. public ShadowsocksController()
  73. {
  74. _config = Configuration.Load();
  75. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  76. _strategyManager = new StrategyManager(this);
  77. StartReleasingMemory();
  78. StartTrafficStatistics(61);
  79. }
  80. public void Start()
  81. {
  82. Reload();
  83. }
  84. protected void ReportError(Exception e)
  85. {
  86. if (Errored != null)
  87. {
  88. Errored(this, new ErrorEventArgs(e));
  89. }
  90. }
  91. public Server GetCurrentServer()
  92. {
  93. return _config.GetCurrentServer();
  94. }
  95. // always return copy
  96. public Configuration GetConfigurationCopy()
  97. {
  98. return Configuration.Load();
  99. }
  100. // always return current instance
  101. public Configuration GetCurrentConfiguration()
  102. {
  103. return _config;
  104. }
  105. public IList<IStrategy> GetStrategies()
  106. {
  107. return _strategyManager.GetStrategies();
  108. }
  109. public IStrategy GetCurrentStrategy()
  110. {
  111. foreach (var strategy in _strategyManager.GetStrategies())
  112. {
  113. if (strategy.ID == this._config.strategy)
  114. {
  115. return strategy;
  116. }
  117. }
  118. return null;
  119. }
  120. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  121. {
  122. IStrategy strategy = GetCurrentStrategy();
  123. if (strategy != null)
  124. {
  125. return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
  126. }
  127. if (_config.index < 0)
  128. {
  129. _config.index = 0;
  130. }
  131. return GetCurrentServer();
  132. }
  133. public void SaveServers(List<Server> servers, int localPort)
  134. {
  135. _config.configs = servers;
  136. _config.localPort = localPort;
  137. Configuration.Save(_config);
  138. }
  139. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  140. {
  141. StatisticsConfiguration = configuration;
  142. StatisticsStrategyConfiguration.Save(configuration);
  143. }
  144. public bool AddServerBySSURL(string ssURL)
  145. {
  146. try
  147. {
  148. var server = new Server(ssURL);
  149. _config.configs.Add(server);
  150. _config.index = _config.configs.Count - 1;
  151. SaveConfig(_config);
  152. return true;
  153. }
  154. catch (Exception e)
  155. {
  156. Logging.LogUsefulException(e);
  157. return false;
  158. }
  159. }
  160. public void ToggleEnable(bool enabled)
  161. {
  162. _config.enabled = enabled;
  163. SaveConfig(_config);
  164. if (EnableStatusChanged != null)
  165. {
  166. EnableStatusChanged(this, new EventArgs());
  167. }
  168. }
  169. public void ToggleGlobal(bool global)
  170. {
  171. _config.global = global;
  172. SaveConfig(_config);
  173. if (EnableGlobalChanged != null)
  174. {
  175. EnableGlobalChanged(this, new EventArgs());
  176. }
  177. }
  178. public void ToggleShareOverLAN(bool enabled)
  179. {
  180. _config.shareOverLan = enabled;
  181. SaveConfig(_config);
  182. if (ShareOverLANStatusChanged != null)
  183. {
  184. ShareOverLANStatusChanged(this, new EventArgs());
  185. }
  186. }
  187. public void DisableProxy()
  188. {
  189. _config.proxy.useProxy = false;
  190. SaveConfig(_config);
  191. }
  192. public void EnableProxy(int type, string proxy, int port, int timeout)
  193. {
  194. _config.proxy.useProxy = true;
  195. _config.proxy.proxyType = type;
  196. _config.proxy.proxyServer = proxy;
  197. _config.proxy.proxyPort = port;
  198. _config.proxy.proxyTimeout = timeout;
  199. SaveConfig(_config);
  200. }
  201. public void ToggleVerboseLogging(bool enabled)
  202. {
  203. _config.isVerboseLogging = enabled;
  204. SaveConfig(_config);
  205. if ( VerboseLoggingStatusChanged != null ) {
  206. VerboseLoggingStatusChanged(this, new EventArgs());
  207. }
  208. }
  209. public void SelectServerIndex(int index)
  210. {
  211. _config.index = index;
  212. _config.strategy = null;
  213. SaveConfig(_config);
  214. }
  215. public void SelectStrategy(string strategyID)
  216. {
  217. _config.index = -1;
  218. _config.strategy = strategyID;
  219. SaveConfig(_config);
  220. }
  221. public void Stop()
  222. {
  223. if (stopped)
  224. {
  225. return;
  226. }
  227. stopped = true;
  228. if (_listener != null)
  229. {
  230. _listener.Stop();
  231. }
  232. if (_config.enabled)
  233. {
  234. SystemProxy.Update(_config, true, null);
  235. }
  236. Encryption.RNG.Close();
  237. }
  238. public void TouchPACFile()
  239. {
  240. string pacFilename = _pacServer.TouchPACFile();
  241. if (PACFileReadyToOpen != null)
  242. {
  243. PACFileReadyToOpen(this, new PathEventArgs() { Path = pacFilename });
  244. }
  245. }
  246. public void TouchUserRuleFile()
  247. {
  248. string userRuleFilename = _pacServer.TouchUserRuleFile();
  249. if (UserRuleFileReadyToOpen != null)
  250. {
  251. UserRuleFileReadyToOpen(this, new PathEventArgs() { Path = userRuleFilename });
  252. }
  253. }
  254. public string GetQRCodeForCurrentServer()
  255. {
  256. Server server = GetCurrentServer();
  257. return GetQRCode(server);
  258. }
  259. public static string GetQRCode(Server server)
  260. {
  261. string tag = string.Empty;
  262. string auth = server.auth ? "-auth" : string.Empty;
  263. string parts = $"{server.method}{auth}:{server.password}@{server.server}:{server.server_port}";
  264. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  265. if(!server.remarks.IsNullOrEmpty())
  266. {
  267. tag = $"#{HttpUtility.UrlEncode(server.remarks, Encoding.UTF8)}";
  268. }
  269. return $"ss://{base64}{tag}";
  270. }
  271. public void UpdatePACFromGFWList()
  272. {
  273. if (gfwListUpdater != null)
  274. {
  275. gfwListUpdater.UpdatePACFromGFWList(_config);
  276. }
  277. }
  278. public void UpdateStatisticsConfiguration(bool enabled)
  279. {
  280. if (availabilityStatistics == null) return;
  281. availabilityStatistics.UpdateConfiguration(this);
  282. _config.availabilityStatistics = enabled;
  283. SaveConfig(_config);
  284. }
  285. public void SavePACUrl(string pacUrl)
  286. {
  287. _config.pacUrl = pacUrl;
  288. SaveConfig(_config);
  289. if (ConfigChanged != null)
  290. {
  291. ConfigChanged(this, new EventArgs());
  292. }
  293. }
  294. public void UseOnlinePAC(bool useOnlinePac)
  295. {
  296. _config.useOnlinePac = useOnlinePac;
  297. SaveConfig(_config);
  298. if (ConfigChanged != null)
  299. {
  300. ConfigChanged(this, new EventArgs());
  301. }
  302. }
  303. public void ToggleSecureLocalPac(bool enabled)
  304. {
  305. _config.secureLocalPac = enabled;
  306. SaveConfig(_config);
  307. if (ConfigChanged != null)
  308. {
  309. ConfigChanged(this, new EventArgs());
  310. }
  311. }
  312. public void ToggleCheckingUpdate(bool enabled)
  313. {
  314. _config.autoCheckUpdate = enabled;
  315. Configuration.Save(_config);
  316. if (ConfigChanged != null)
  317. {
  318. ConfigChanged(this, new EventArgs());
  319. }
  320. }
  321. public void ToggleCheckingPreRelease(bool enabled)
  322. {
  323. _config.checkPreRelease = enabled;
  324. Configuration.Save(_config);
  325. if (ConfigChanged != null)
  326. {
  327. ConfigChanged(this, new EventArgs());
  328. }
  329. }
  330. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  331. {
  332. _config.logViewer = newConfig;
  333. newConfig.SaveSize();
  334. Configuration.Save(_config);
  335. if (ConfigChanged != null)
  336. {
  337. ConfigChanged(this, new EventArgs());
  338. }
  339. }
  340. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  341. {
  342. _config.hotkey = newConfig;
  343. SaveConfig(_config);
  344. if (ConfigChanged != null)
  345. {
  346. ConfigChanged(this, new EventArgs());
  347. }
  348. }
  349. public void UpdateLatency(Server server, TimeSpan latency)
  350. {
  351. if (_config.availabilityStatistics)
  352. {
  353. availabilityStatistics.UpdateLatency(server, (int)latency.TotalMilliseconds);
  354. }
  355. }
  356. public void UpdateInboundCounter(Server server, long n)
  357. {
  358. Interlocked.Add(ref _inboundCounter, n);
  359. if (_config.availabilityStatistics)
  360. {
  361. availabilityStatistics.UpdateInboundCounter(server, n);
  362. }
  363. }
  364. public void UpdateOutboundCounter(Server server, long n)
  365. {
  366. Interlocked.Add(ref _outboundCounter, n);
  367. if (_config.availabilityStatistics)
  368. {
  369. availabilityStatistics.UpdateOutboundCounter(server, n);
  370. }
  371. }
  372. protected void Reload()
  373. {
  374. Encryption.RNG.Reload();
  375. // some logic in configuration updated the config when saving, we need to read it again
  376. _config = Configuration.Load();
  377. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  378. if (_pacServer == null)
  379. {
  380. _pacServer = new PACServer();
  381. _pacServer.PACFileChanged += pacServer_PACFileChanged;
  382. _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged;
  383. }
  384. _pacServer.UpdateConfiguration(_config);
  385. if (gfwListUpdater == null)
  386. {
  387. gfwListUpdater = new GFWListUpdater();
  388. gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted;
  389. gfwListUpdater.Error += pacServer_PACUpdateError;
  390. }
  391. availabilityStatistics.UpdateConfiguration(this);
  392. if (_listener != null)
  393. {
  394. _listener.Stop();
  395. }
  396. try
  397. {
  398. var strategy = GetCurrentStrategy();
  399. if (strategy != null)
  400. {
  401. strategy.ReloadServers();
  402. }
  403. TCPRelay tcpRelay = new TCPRelay(this, _config);
  404. UDPRelay udpRelay = new UDPRelay(this);
  405. List<Listener.IService> services = new List<Listener.IService>();
  406. services.Add(_pacServer);
  407. services.Add(tcpRelay);
  408. services.Add(udpRelay);
  409. //services.Add(new Http2Socks5(_config.localPort));
  410. _listener = new Listener(services);
  411. _listener.Start(_config);
  412. }
  413. catch (Exception e)
  414. {
  415. // translate Microsoft language into human language
  416. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  417. if (e is SocketException)
  418. {
  419. SocketException se = (SocketException)e;
  420. if (se.SocketErrorCode == SocketError.AccessDenied)
  421. {
  422. e = new Exception(I18N.GetString("Port already in use"), e);
  423. }
  424. }
  425. Logging.LogUsefulException(e);
  426. ReportError(e);
  427. }
  428. if (ConfigChanged != null)
  429. {
  430. ConfigChanged(this, new EventArgs());
  431. }
  432. UpdateSystemProxy();
  433. Utils.ReleaseMemory(true);
  434. }
  435. protected void SaveConfig(Configuration newConfig)
  436. {
  437. Configuration.Save(newConfig);
  438. Reload();
  439. }
  440. private void UpdateSystemProxy()
  441. {
  442. if (_config.enabled)
  443. {
  444. SystemProxy.Update(_config, false, _pacServer);
  445. _systemProxyIsDirty = true;
  446. }
  447. else
  448. {
  449. // only switch it off if we have switched it on
  450. if (_systemProxyIsDirty)
  451. {
  452. SystemProxy.Update(_config, false, _pacServer);
  453. _systemProxyIsDirty = false;
  454. }
  455. }
  456. }
  457. private void pacServer_PACFileChanged(object sender, EventArgs e)
  458. {
  459. UpdateSystemProxy();
  460. }
  461. private void pacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  462. {
  463. if (UpdatePACFromGFWListCompleted != null)
  464. UpdatePACFromGFWListCompleted(this, e);
  465. }
  466. private void pacServer_PACUpdateError(object sender, ErrorEventArgs e)
  467. {
  468. if (UpdatePACFromGFWListError != null)
  469. UpdatePACFromGFWListError(this, e);
  470. }
  471. private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };
  472. private void pacServer_UserRuleFileChanged(object sender, EventArgs e)
  473. {
  474. // TODO: this is a dirty hack. (from code GListUpdater.http_DownloadStringCompleted())
  475. if (!File.Exists(Utils.GetTempPath("gfwlist.txt")))
  476. {
  477. UpdatePACFromGFWList();
  478. return;
  479. }
  480. List<string> lines = GFWListUpdater.ParseResult(File.ReadAllText(Utils.GetTempPath("gfwlist.txt")));
  481. if (File.Exists(PACServer.USER_RULE_FILE))
  482. {
  483. string local = File.ReadAllText(PACServer.USER_RULE_FILE, Encoding.UTF8);
  484. using (var sr = new StringReader(local))
  485. {
  486. foreach (var rule in sr.NonWhiteSpaceLines())
  487. {
  488. if (rule.BeginWithAny(IgnoredLineBegins))
  489. continue;
  490. lines.Add(rule);
  491. }
  492. }
  493. }
  494. string abpContent;
  495. if (File.Exists(PACServer.USER_ABP_FILE))
  496. {
  497. abpContent = File.ReadAllText(PACServer.USER_ABP_FILE, Encoding.UTF8);
  498. }
  499. else
  500. {
  501. abpContent = Utils.UnGzip(Resources.abp_js);
  502. }
  503. abpContent = abpContent.Replace("__RULES__", JsonConvert.SerializeObject(lines, Formatting.Indented));
  504. if (File.Exists(PACServer.PAC_FILE))
  505. {
  506. string original = File.ReadAllText(PACServer.PAC_FILE, Encoding.UTF8);
  507. if (original == abpContent)
  508. {
  509. return;
  510. }
  511. }
  512. File.WriteAllText(PACServer.PAC_FILE, abpContent, Encoding.UTF8);
  513. }
  514. public void CopyPacUrl()
  515. {
  516. Clipboard.SetDataObject(_pacServer.PacUrl);
  517. }
  518. #region Memory Management
  519. private void StartReleasingMemory()
  520. {
  521. _ramThread = new Thread(new ThreadStart(ReleaseMemory));
  522. _ramThread.IsBackground = true;
  523. _ramThread.Start();
  524. }
  525. private void ReleaseMemory()
  526. {
  527. while (true)
  528. {
  529. Utils.ReleaseMemory(false);
  530. Thread.Sleep(30 * 1000);
  531. }
  532. }
  533. #endregion
  534. #region Traffic Statistics
  535. private void StartTrafficStatistics(int queueMaxSize)
  536. {
  537. traffic = new QueueLast<TrafficPerSecond>();
  538. for (int i = 0; i < queueMaxSize; i++)
  539. {
  540. traffic.Enqueue(new TrafficPerSecond());
  541. }
  542. _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)));
  543. _trafficThread.IsBackground = true;
  544. _trafficThread.Start();
  545. }
  546. private void TrafficStatistics(int queueMaxSize)
  547. {
  548. while (true)
  549. {
  550. TrafficPerSecond previous = traffic.Last;
  551. TrafficPerSecond current = new TrafficPerSecond();
  552. var inbound = current.inboundCounter = InboundCounter;
  553. var outbound = current.outboundCounter = OutboundCounter;
  554. current.inboundIncreasement = inbound - previous.inboundCounter;
  555. current.outboundIncreasement = outbound - previous.outboundCounter;
  556. traffic.Enqueue(current);
  557. if (traffic.Count > queueMaxSize)
  558. traffic.Dequeue();
  559. TrafficChanged?.Invoke(this, new EventArgs());
  560. Thread.Sleep(1000);
  561. }
  562. }
  563. #endregion
  564. }
  565. }