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