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

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