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.

PACServer.cs 9.8 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using Shadowsocks.Model;
  8. using Shadowsocks.Properties;
  9. using Shadowsocks.Util;
  10. namespace Shadowsocks.Controller
  11. {
  12. class PACServer : Listener.Service
  13. {
  14. public static readonly string PAC_FILE = "pac.txt";
  15. public static readonly string USER_RULE_FILE = "user-rule.txt";
  16. public static readonly string USER_ABP_FILE = "abp.txt";
  17. FileSystemWatcher PACFileWatcher;
  18. FileSystemWatcher UserRuleFileWatcher;
  19. private Configuration _config;
  20. public event EventHandler PACFileChanged;
  21. public event EventHandler UserRuleFileChanged;
  22. public PACServer()
  23. {
  24. this.WatchPacFile();
  25. this.WatchUserRuleFile();
  26. }
  27. public void UpdateConfiguration(Configuration config)
  28. {
  29. this._config = config;
  30. }
  31. public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
  32. {
  33. if (socket.ProtocolType != ProtocolType.Tcp)
  34. {
  35. return false;
  36. }
  37. try
  38. {
  39. string request = Encoding.UTF8.GetString(firstPacket, 0, length);
  40. string[] lines = request.Split('\r', '\n');
  41. bool hostMatch = false, pathMatch = false, useSocks = false;
  42. foreach (string line in lines)
  43. {
  44. string[] kv = line.Split(new char[] { ':' }, 2);
  45. if (kv.Length == 2)
  46. {
  47. if (kv[0] == "Host")
  48. {
  49. if (kv[1].Trim() == ((IPEndPoint)socket.LocalEndPoint).ToString())
  50. {
  51. hostMatch = true;
  52. }
  53. }
  54. //else if (kv[0] == "User-Agent")
  55. //{
  56. // // we need to drop connections when changing servers
  57. // if (kv[1].IndexOf("Chrome") >= 0)
  58. // {
  59. // useSocks = true;
  60. // }
  61. //}
  62. }
  63. else if (kv.Length == 1)
  64. {
  65. if (line.IndexOf("pac") >= 0)
  66. {
  67. pathMatch = true;
  68. }
  69. }
  70. }
  71. if (hostMatch && pathMatch)
  72. {
  73. SendResponse(firstPacket, length, socket, useSocks);
  74. return true;
  75. }
  76. return false;
  77. }
  78. catch (ArgumentException)
  79. {
  80. return false;
  81. }
  82. }
  83. public string TouchPACFile()
  84. {
  85. if (File.Exists(PAC_FILE))
  86. {
  87. return PAC_FILE;
  88. }
  89. else
  90. {
  91. FileManager.UncompressFile(PAC_FILE, Resources.proxy_pac_txt);
  92. return PAC_FILE;
  93. }
  94. }
  95. internal string TouchUserRuleFile()
  96. {
  97. if (File.Exists(USER_RULE_FILE))
  98. {
  99. return USER_RULE_FILE;
  100. }
  101. else
  102. {
  103. File.WriteAllText(USER_RULE_FILE, Resources.user_rule);
  104. return USER_RULE_FILE;
  105. }
  106. }
  107. private string GetPACContent()
  108. {
  109. if (File.Exists(PAC_FILE))
  110. {
  111. return File.ReadAllText(PAC_FILE, Encoding.UTF8);
  112. }
  113. else
  114. {
  115. return Utils.UnGzip(Resources.proxy_pac_txt);
  116. }
  117. }
  118. public void SendResponse(byte[] firstPacket, int length, Socket socket, bool useSocks)
  119. {
  120. try
  121. {
  122. string pac = GetPACContent();
  123. IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
  124. string proxy = GetPACAddress(firstPacket, length, localEndPoint, useSocks);
  125. pac = pac.Replace("__PROXY__", proxy);
  126. string text = String.Format(@"HTTP/1.1 200 OK
  127. Server: Shadowsocks
  128. Content-Type: application/x-ns-proxy-autoconfig
  129. Content-Length: {0}
  130. Connection: Close
  131. ", Encoding.UTF8.GetBytes(pac).Length) + pac;
  132. byte[] response = Encoding.UTF8.GetBytes(text);
  133. socket.BeginSend(response, 0, response.Length, 0, new AsyncCallback(SendCallback), socket);
  134. Utils.ReleaseMemory(true);
  135. }
  136. catch (Exception e)
  137. {
  138. Logging.LogUsefulException(e);
  139. socket.Close();
  140. }
  141. }
  142. private void SendCallback(IAsyncResult ar)
  143. {
  144. Socket conn = (Socket)ar.AsyncState;
  145. try
  146. {
  147. conn.Shutdown(SocketShutdown.Send);
  148. }
  149. catch
  150. { }
  151. }
  152. private void WatchPacFile()
  153. {
  154. if (PACFileWatcher != null)
  155. {
  156. PACFileWatcher.Dispose();
  157. }
  158. PACFileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory());
  159. PACFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  160. PACFileWatcher.Filter = PAC_FILE;
  161. PACFileWatcher.Changed += PACFileWatcher_Changed;
  162. PACFileWatcher.Created += PACFileWatcher_Changed;
  163. PACFileWatcher.Deleted += PACFileWatcher_Changed;
  164. PACFileWatcher.Renamed += PACFileWatcher_Changed;
  165. PACFileWatcher.EnableRaisingEvents = true;
  166. }
  167. private void WatchUserRuleFile()
  168. {
  169. if (UserRuleFileWatcher != null)
  170. {
  171. UserRuleFileWatcher.Dispose();
  172. }
  173. UserRuleFileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory());
  174. UserRuleFileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  175. UserRuleFileWatcher.Filter = USER_RULE_FILE;
  176. UserRuleFileWatcher.Changed += UserRuleFileWatcher_Changed;
  177. UserRuleFileWatcher.Created += UserRuleFileWatcher_Changed;
  178. UserRuleFileWatcher.Deleted += UserRuleFileWatcher_Changed;
  179. UserRuleFileWatcher.Renamed += UserRuleFileWatcher_Changed;
  180. UserRuleFileWatcher.EnableRaisingEvents = true;
  181. }
  182. #region FileSystemWatcher.OnChanged()
  183. // FileSystemWatcher Changed event is raised twice
  184. // http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
  185. private static Hashtable fileChangedTime = new Hashtable();
  186. private void PACFileWatcher_Changed(object sender, FileSystemEventArgs e)
  187. {
  188. string path = e.FullPath.ToString();
  189. string currentLastWriteTime = File.GetLastWriteTime(e.FullPath).ToString();
  190. // if there is no path info stored yet or stored path has different time of write then the one now is inspected
  191. if (!fileChangedTime.ContainsKey(path) || fileChangedTime[path].ToString() != currentLastWriteTime)
  192. {
  193. if (PACFileChanged != null)
  194. {
  195. Logging.Info($"Detected: PAC file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
  196. PACFileChanged(this, new EventArgs());
  197. }
  198. // lastly we update the last write time in the hashtable
  199. fileChangedTime[path] = currentLastWriteTime;
  200. }
  201. }
  202. private void UserRuleFileWatcher_Changed(object sender, FileSystemEventArgs e)
  203. {
  204. string path = e.FullPath.ToString();
  205. string currentLastWriteTime = File.GetLastWriteTime(e.FullPath).ToString();
  206. // if there is no path info stored yet or stored path has different time of write then the one now is inspected
  207. if (!fileChangedTime.ContainsKey(path) || fileChangedTime[path].ToString() != currentLastWriteTime)
  208. {
  209. if (UserRuleFileChanged != null)
  210. {
  211. Logging.Info($"Detected: User Rule file '{e.Name}' was {e.ChangeType.ToString().ToLower()}.");
  212. UserRuleFileChanged(this, new EventArgs());
  213. }
  214. // lastly we update the last write time in the hashtable
  215. fileChangedTime[path] = currentLastWriteTime;
  216. }
  217. }
  218. #endregion
  219. private string GetPACAddress(byte[] requestBuf, int length, IPEndPoint localEndPoint, bool useSocks)
  220. {
  221. //try
  222. //{
  223. // string requestString = Encoding.UTF8.GetString(requestBuf);
  224. // if (requestString.IndexOf("AppleWebKit") >= 0)
  225. // {
  226. // string address = "" + localEndPoint.Address + ":" + config.GetCurrentServer().local_port;
  227. // proxy = "SOCKS5 " + address + "; SOCKS " + address + ";";
  228. // }
  229. //}
  230. //catch (Exception e)
  231. //{
  232. // Logging.LogUsefulException(e);
  233. //}
  234. return (useSocks ? "SOCKS5 " : "PROXY ") + localEndPoint.Address + ":" + this._config.localPort + ";";
  235. }
  236. }
  237. }