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