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