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

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
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
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using System.IO;
  2. using Shadowsocks.Model;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Net.Sockets;
  8. using Shadowsocks.Controller.Strategy;
  9. using System.Net;
  10. namespace Shadowsocks.Controller
  11. {
  12. public class ShadowsocksController
  13. {
  14. // controller:
  15. // handle user actions
  16. // manipulates UI
  17. // interacts with low level logic
  18. private Thread _ramThread;
  19. private Listener _listener;
  20. private PACServer _pacServer;
  21. private Configuration _config;
  22. private StrategyManager _strategyManager;
  23. private PolipoRunner polipoRunner;
  24. private GFWListUpdater gfwListUpdater;
  25. private AvailabilityStatistics _availabilityStatics;
  26. private bool stopped = false;
  27. private bool _systemProxyIsDirty = false;
  28. public class PathEventArgs : EventArgs
  29. {
  30. public string Path;
  31. }
  32. public event EventHandler ConfigChanged;
  33. public event EventHandler EnableStatusChanged;
  34. public event EventHandler EnableGlobalChanged;
  35. public event EventHandler ShareOverLANStatusChanged;
  36. // when user clicked Edit PAC, and PAC file has already created
  37. public event EventHandler<PathEventArgs> PACFileReadyToOpen;
  38. public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
  39. public event EventHandler<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
  40. public event ErrorEventHandler UpdatePACFromGFWListError;
  41. public event ErrorEventHandler Errored;
  42. public ShadowsocksController()
  43. {
  44. _config = Configuration.Load();
  45. _strategyManager = new StrategyManager(this);
  46. }
  47. public void Start()
  48. {
  49. Reload();
  50. }
  51. protected void ReportError(Exception e)
  52. {
  53. if (Errored != null)
  54. {
  55. Errored(this, new ErrorEventArgs(e));
  56. }
  57. }
  58. public Server GetCurrentServer()
  59. {
  60. return _config.GetCurrentServer();
  61. }
  62. // always return copy
  63. public Configuration GetConfigurationCopy()
  64. {
  65. return Configuration.Load();
  66. }
  67. // always return current instance
  68. public Configuration GetCurrentConfiguration()
  69. {
  70. return _config;
  71. }
  72. public IList<IStrategy> GetStrategies()
  73. {
  74. return _strategyManager.GetStrategies();
  75. }
  76. public IStrategy GetCurrentStrategy()
  77. {
  78. foreach (var strategy in _strategyManager.GetStrategies())
  79. {
  80. if (strategy.ID == this._config.strategy)
  81. {
  82. return strategy;
  83. }
  84. }
  85. return null;
  86. }
  87. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint)
  88. {
  89. IStrategy strategy = GetCurrentStrategy();
  90. if (strategy != null)
  91. {
  92. return strategy.GetAServer(type, localIPEndPoint);
  93. }
  94. if (_config.index < 0)
  95. {
  96. _config.index = 0;
  97. }
  98. return GetCurrentServer();
  99. }
  100. public void SaveServers(List<Server> servers, int localPort)
  101. {
  102. _config.configs = servers;
  103. _config.localPort = localPort;
  104. SaveConfig(_config);
  105. }
  106. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  107. {
  108. _config.statisticsStrategyConfiguration = configuration;
  109. SaveConfig(_config);
  110. }
  111. public bool AddServerBySSURL(string ssURL)
  112. {
  113. try
  114. {
  115. var server = new Server(ssURL);
  116. _config.configs.Add(server);
  117. _config.index = _config.configs.Count - 1;
  118. SaveConfig(_config);
  119. return true;
  120. }
  121. catch (Exception e)
  122. {
  123. Logging.LogUsefulException(e);
  124. return false;
  125. }
  126. }
  127. public void ToggleEnable(bool enabled)
  128. {
  129. _config.enabled = enabled;
  130. UpdateSystemProxy();
  131. SaveConfig(_config);
  132. if (EnableStatusChanged != null)
  133. {
  134. EnableStatusChanged(this, new EventArgs());
  135. }
  136. }
  137. public void ToggleGlobal(bool global)
  138. {
  139. _config.global = global;
  140. UpdateSystemProxy();
  141. SaveConfig(_config);
  142. if (EnableGlobalChanged != null)
  143. {
  144. EnableGlobalChanged(this, new EventArgs());
  145. }
  146. }
  147. public void ToggleShareOverLAN(bool enabled)
  148. {
  149. _config.shareOverLan = enabled;
  150. SaveConfig(_config);
  151. if (ShareOverLANStatusChanged != null)
  152. {
  153. ShareOverLANStatusChanged(this, new EventArgs());
  154. }
  155. }
  156. public void SelectServerIndex(int index)
  157. {
  158. _config.index = index;
  159. _config.strategy = null;
  160. SaveConfig(_config);
  161. }
  162. public void SelectStrategy(string strategyID)
  163. {
  164. _config.index = -1;
  165. _config.strategy = strategyID;
  166. SaveConfig(_config);
  167. }
  168. public void Stop()
  169. {
  170. if (stopped)
  171. {
  172. return;
  173. }
  174. stopped = true;
  175. if (_listener != null)
  176. {
  177. _listener.Stop();
  178. }
  179. if (polipoRunner != null)
  180. {
  181. polipoRunner.Stop();
  182. }
  183. if (_config.enabled)
  184. {
  185. SystemProxy.Update(_config, true);
  186. }
  187. }
  188. public void TouchPACFile()
  189. {
  190. string pacFilename = _pacServer.TouchPACFile();
  191. if (PACFileReadyToOpen != null)
  192. {
  193. PACFileReadyToOpen(this, new PathEventArgs() { Path = pacFilename });
  194. }
  195. }
  196. public void TouchUserRuleFile()
  197. {
  198. string userRuleFilename = _pacServer.TouchUserRuleFile();
  199. if (UserRuleFileReadyToOpen != null)
  200. {
  201. UserRuleFileReadyToOpen(this, new PathEventArgs() { Path = userRuleFilename });
  202. }
  203. }
  204. public string GetQRCodeForCurrentServer()
  205. {
  206. Server server = GetCurrentServer();
  207. return GetQRCode(server);
  208. }
  209. public static string GetQRCode(Server server)
  210. {
  211. string parts = server.method + ":" + server.password + "@" + server.server + ":" + server.server_port;
  212. string base64 = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  213. return "ss://" + base64;
  214. }
  215. public void UpdatePACFromGFWList()
  216. {
  217. if (gfwListUpdater != null)
  218. {
  219. gfwListUpdater.UpdatePACFromGFWList(_config);
  220. }
  221. }
  222. public void ToggleAvailabilityStatistics(bool enabled)
  223. {
  224. if (_availabilityStatics != null)
  225. {
  226. _availabilityStatics.Set(enabled);
  227. _config.availabilityStatistics = enabled;
  228. SaveConfig(_config);
  229. }
  230. }
  231. public void SavePACUrl(string pacUrl)
  232. {
  233. _config.pacUrl = pacUrl;
  234. UpdateSystemProxy();
  235. SaveConfig(_config);
  236. if (ConfigChanged != null)
  237. {
  238. ConfigChanged(this, new EventArgs());
  239. }
  240. }
  241. public void UseOnlinePAC(bool useOnlinePac)
  242. {
  243. _config.useOnlinePac = useOnlinePac;
  244. UpdateSystemProxy();
  245. SaveConfig(_config);
  246. if (ConfigChanged != null)
  247. {
  248. ConfigChanged(this, new EventArgs());
  249. }
  250. }
  251. protected void Reload()
  252. {
  253. // some logic in configuration updated the config when saving, we need to read it again
  254. _config = Configuration.Load();
  255. if (polipoRunner == null)
  256. {
  257. polipoRunner = new PolipoRunner();
  258. }
  259. if (_pacServer == null)
  260. {
  261. _pacServer = new PACServer();
  262. _pacServer.PACFileChanged += pacServer_PACFileChanged;
  263. }
  264. _pacServer.UpdateConfiguration(_config);
  265. if (gfwListUpdater == null)
  266. {
  267. gfwListUpdater = new GFWListUpdater();
  268. gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted;
  269. gfwListUpdater.Error += pacServer_PACUpdateError;
  270. }
  271. if (_availabilityStatics == null)
  272. {
  273. _availabilityStatics = new AvailabilityStatistics();
  274. }
  275. _availabilityStatics.UpdateConfiguration(_config);
  276. if (_listener != null)
  277. {
  278. _listener.Stop();
  279. }
  280. // don't put polipoRunner.Start() before pacServer.Stop()
  281. // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
  282. // though UseShellExecute is set to true now
  283. // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
  284. polipoRunner.Stop();
  285. try
  286. {
  287. var strategy = GetCurrentStrategy();
  288. if (strategy != null)
  289. {
  290. strategy.ReloadServers();
  291. }
  292. polipoRunner.Start(_config);
  293. TCPRelay tcpRelay = new TCPRelay(this);
  294. UDPRelay udpRelay = new UDPRelay(this);
  295. List<Listener.Service> services = new List<Listener.Service>();
  296. services.Add(tcpRelay);
  297. services.Add(udpRelay);
  298. services.Add(_pacServer);
  299. services.Add(new PortForwarder(polipoRunner.RunningPort));
  300. _listener = new Listener(services);
  301. _listener.Start(_config);
  302. }
  303. catch (Exception e)
  304. {
  305. // translate Microsoft language into human language
  306. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  307. if (e is SocketException)
  308. {
  309. SocketException se = (SocketException)e;
  310. if (se.SocketErrorCode == SocketError.AccessDenied)
  311. {
  312. e = new Exception(I18N.GetString("Port already in use"), e);
  313. }
  314. }
  315. Logging.LogUsefulException(e);
  316. ReportError(e);
  317. }
  318. if (ConfigChanged != null)
  319. {
  320. ConfigChanged(this, new EventArgs());
  321. }
  322. UpdateSystemProxy();
  323. Util.Utils.ReleaseMemory();
  324. }
  325. protected void SaveConfig(Configuration newConfig)
  326. {
  327. Configuration.Save(newConfig);
  328. Reload();
  329. }
  330. private void UpdateSystemProxy()
  331. {
  332. if (_config.enabled)
  333. {
  334. SystemProxy.Update(_config, false);
  335. _systemProxyIsDirty = true;
  336. }
  337. else
  338. {
  339. // only switch it off if we have switched it on
  340. if (_systemProxyIsDirty)
  341. {
  342. SystemProxy.Update(_config, false);
  343. _systemProxyIsDirty = false;
  344. }
  345. }
  346. }
  347. private void pacServer_PACFileChanged(object sender, EventArgs e)
  348. {
  349. UpdateSystemProxy();
  350. }
  351. private void pacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  352. {
  353. if (UpdatePACFromGFWListCompleted != null)
  354. UpdatePACFromGFWListCompleted(this, e);
  355. }
  356. private void pacServer_PACUpdateError(object sender, ErrorEventArgs e)
  357. {
  358. if (UpdatePACFromGFWListError != null)
  359. UpdatePACFromGFWListError(this, e);
  360. }
  361. private void StartReleasingMemory()
  362. {
  363. _ramThread = new Thread(new ThreadStart(ReleaseMemory));
  364. _ramThread.IsBackground = true;
  365. _ramThread.Start();
  366. }
  367. private void ReleaseMemory()
  368. {
  369. while (true)
  370. {
  371. Util.Utils.ReleaseMemory();
  372. Thread.Sleep(30 * 1000);
  373. }
  374. }
  375. }
  376. }