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