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