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.

Http2Socks5.cs 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using Shadowsocks.ForwardProxy;
  7. using Shadowsocks.Util.Sockets;
  8. namespace Shadowsocks.Controller.Service
  9. {
  10. class Http2Socks5 : Listener.Service
  11. {
  12. private readonly ByteSearch.SearchTarget _connectSearch =
  13. new ByteSearch.SearchTarget(Encoding.UTF8.GetBytes("HTTP"));
  14. private readonly int _socks5Port;
  15. public Http2Socks5(int socks5Port)
  16. {
  17. _socks5Port = socks5Port;
  18. }
  19. public override bool Handle(byte[] firstPacket, int length, Socket socket, object state)
  20. {
  21. if (socket.ProtocolType != ProtocolType.Tcp)
  22. {
  23. return false;
  24. }
  25. if (_connectSearch.SearchIn(firstPacket, 0, length) != -1)
  26. {
  27. new HttpHandler(_socks5Port, firstPacket, length, socket);
  28. return true;
  29. }
  30. return false;
  31. }
  32. private class HttpHandler
  33. {
  34. private const string HTTP_CRLF = "\r\n";
  35. private const string HTTP_CONNECT_200 =
  36. "HTTP/1.1 200 Connection established" + HTTP_CRLF +
  37. "Proxy-Connection: close" + HTTP_CRLF +
  38. "Proxy-Agent: Shadowsocks" + HTTP_CRLF +
  39. "" + HTTP_CRLF; // End with an empty line
  40. private readonly WrappedSocket _localSocket;
  41. private readonly int _socks5Port;
  42. private Socks5Proxy _socks5;
  43. private bool _closed = false;
  44. private bool _localShutdown = false;
  45. private bool _remoteShutdown = false;
  46. private readonly object _Lock = new object();
  47. private const int RecvSize = 16384;
  48. // remote receive buffer
  49. private readonly byte[] _remoteRecvBuffer = new byte[RecvSize];
  50. // connection receive buffer
  51. private readonly byte[] _connetionRecvBuffer = new byte[RecvSize];
  52. public HttpHandler(int socks5Port, byte[] firstPacket, int length, Socket socket)
  53. {
  54. _socks5Port = socks5Port;
  55. _localSocket = new WrappedSocket(socket);
  56. _localSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  57. new LineReader(_localSocket, firstPacket, 0, length, OnLineRead, OnException, OnFinish,
  58. Encoding.UTF8, HTTP_CRLF, 1024, null);
  59. }
  60. private void CheckClose()
  61. {
  62. if (_localShutdown && _remoteShutdown)
  63. {
  64. Close();
  65. }
  66. }
  67. private void Close()
  68. {
  69. lock (_Lock)
  70. {
  71. if (_closed)
  72. {
  73. return;
  74. }
  75. _closed = true;
  76. }
  77. _localSocket.Dispose();
  78. _socks5?.Close();
  79. }
  80. private byte[] _lastBytes;
  81. private int _lastBytesIndex;
  82. private int _lastBytesLength;
  83. #region Socks5 Process
  84. private void ProxyConnectCallback(IAsyncResult ar)
  85. {
  86. if (_closed)
  87. {
  88. return;
  89. }
  90. try
  91. {
  92. _socks5.EndConnectProxy(ar);
  93. _socks5.BeginConnectDest(SocketUtil.GetEndPoint(_targetHost, _targetPort), ConnectCallback, null);
  94. }
  95. catch (ArgumentException)
  96. {
  97. }
  98. catch (Exception e)
  99. {
  100. Logging.LogUsefulException(e);
  101. Close();
  102. }
  103. }
  104. private void ConnectCallback(IAsyncResult ar)
  105. {
  106. if (_closed)
  107. {
  108. return;
  109. }
  110. try
  111. {
  112. _socks5.EndConnectDest(ar);
  113. if (_isConnect)
  114. {
  115. // http connect response
  116. SendConnectResponse();
  117. }
  118. else
  119. {
  120. // send header
  121. SendHeader();
  122. }
  123. }
  124. catch (ArgumentException)
  125. {
  126. }
  127. catch (Exception e)
  128. {
  129. Logging.LogUsefulException(e);
  130. Close();
  131. }
  132. }
  133. #endregion
  134. #region CONNECT
  135. private void SendConnectResponse()
  136. {
  137. var b = Encoding.UTF8.GetBytes(HTTP_CONNECT_200);
  138. _localSocket.BeginSend(b, 0, b.Length, SocketFlags.None, Http200SendCallback, null);
  139. }
  140. private void Http200SendCallback(IAsyncResult ar)
  141. {
  142. if (_closed)
  143. {
  144. return;
  145. }
  146. try
  147. {
  148. _localSocket.EndSend(ar);
  149. StartPipe();
  150. }
  151. catch (ArgumentException)
  152. {
  153. }
  154. catch (Exception e)
  155. {
  156. Logging.LogUsefulException(e);
  157. Close();
  158. }
  159. }
  160. #endregion
  161. #region Other http method except CONNECT
  162. private void SendHeader()
  163. {
  164. var h = _headers.Dequeue() + HTTP_CRLF;
  165. var len = Encoding.UTF8.GetBytes(h, 0, h.Length, _connetionRecvBuffer, 0);
  166. _socks5.BeginSend(_connetionRecvBuffer, 0, len, SocketFlags.None, HeaderSendCallback, null);
  167. }
  168. private void HeaderSendCallback(IAsyncResult ar)
  169. {
  170. if (_closed)
  171. {
  172. return;
  173. }
  174. try
  175. {
  176. _socks5.EndSend(ar);
  177. if (_headers.Count > 0)
  178. {
  179. SendHeader();
  180. }
  181. else
  182. {
  183. StartPipe();
  184. }
  185. }
  186. catch (Exception e)
  187. {
  188. Logging.LogUsefulException(e);
  189. Close();
  190. }
  191. }
  192. #endregion
  193. #region Pipe
  194. private void StartPipe()
  195. {
  196. if (_closed)
  197. {
  198. return;
  199. }
  200. try
  201. {
  202. _socks5.BeginReceive(_remoteRecvBuffer, 0, RecvSize, 0,
  203. PipeRemoteReceiveCallback, null);
  204. if (_lastBytesLength > 0)
  205. {
  206. _socks5.BeginSend(_lastBytes, _lastBytesIndex, _lastBytesLength, SocketFlags.None,
  207. PipeRemoteSendCallback, null);
  208. }
  209. else
  210. {
  211. _localSocket.BeginReceive(_connetionRecvBuffer, 0, RecvSize, 0,
  212. PipeConnectionReceiveCallback, null);
  213. }
  214. }
  215. catch (Exception e)
  216. {
  217. Logging.LogUsefulException(e);
  218. Close();
  219. }
  220. }
  221. private void PipeRemoteReceiveCallback(IAsyncResult ar)
  222. {
  223. if (_closed)
  224. {
  225. return;
  226. }
  227. try
  228. {
  229. int bytesRead = _socks5.EndReceive(ar);
  230. Logging.Debug("Read from remote: " + bytesRead);
  231. if (bytesRead > 0)
  232. {
  233. _localSocket.BeginSend(_remoteRecvBuffer, 0, bytesRead, 0, PipeConnectionSendCallback, null);
  234. }
  235. else
  236. {
  237. _localSocket.Shutdown(SocketShutdown.Send);
  238. _localShutdown = true;
  239. CheckClose();
  240. }
  241. }
  242. catch (Exception e)
  243. {
  244. Logging.LogUsefulException(e);
  245. Close();
  246. }
  247. }
  248. private void PipeConnectionReceiveCallback(IAsyncResult ar)
  249. {
  250. if (_closed)
  251. {
  252. return;
  253. }
  254. try
  255. {
  256. int bytesRead = _localSocket.EndReceive(ar);
  257. Logging.Debug("Read from local: " + bytesRead);
  258. if (bytesRead > 0)
  259. {
  260. _socks5.BeginSend(_connetionRecvBuffer, 0, bytesRead, 0, PipeRemoteSendCallback, null);
  261. }
  262. else
  263. {
  264. _socks5.Shutdown(SocketShutdown.Send);
  265. _remoteShutdown = true;
  266. CheckClose();
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. Logging.LogUsefulException(e);
  272. Close();
  273. }
  274. }
  275. private void PipeRemoteSendCallback(IAsyncResult ar)
  276. {
  277. if (_closed)
  278. {
  279. return;
  280. }
  281. try
  282. {
  283. _socks5.EndSend(ar);
  284. _localSocket.BeginReceive(_connetionRecvBuffer, 0, RecvSize, 0,
  285. PipeConnectionReceiveCallback, null);
  286. }
  287. catch (Exception e)
  288. {
  289. Logging.LogUsefulException(e);
  290. Close();
  291. }
  292. }
  293. private void PipeConnectionSendCallback(IAsyncResult ar)
  294. {
  295. if (_closed)
  296. {
  297. return;
  298. }
  299. try
  300. {
  301. _localSocket.EndSend(ar);
  302. _socks5.BeginReceive(_remoteRecvBuffer, 0, RecvSize, 0,
  303. PipeRemoteReceiveCallback, null);
  304. }
  305. catch (Exception e)
  306. {
  307. Logging.LogUsefulException(e);
  308. Close();
  309. }
  310. }
  311. #endregion
  312. #region Header Parse
  313. private void OnException(Exception ex, object state)
  314. {
  315. throw ex;
  316. }
  317. private static readonly Regex HttpRequestHeaderRegex = new Regex(@"^([A-Z]+?) ([^\s]+) HTTP/1\.\d$");
  318. private int _requestLineCount = 0;
  319. private volatile bool _isConnect = false;
  320. private string _targetHost;
  321. private int _targetPort;
  322. private readonly Queue<string> _headers = new Queue<string>();
  323. private bool OnLineRead(string line, object state)
  324. {
  325. if (_closed)
  326. {
  327. return true;
  328. }
  329. Logging.Debug(line);
  330. if (!line.StartsWith("Proxy-"))
  331. {
  332. _headers.Enqueue(line);
  333. }
  334. if (_requestLineCount == 0)
  335. {
  336. var m = HttpRequestHeaderRegex.Match(line);
  337. if (m.Success)
  338. {
  339. var method = m.Groups[1].Value;
  340. if (method == "CONNECT")
  341. {
  342. _isConnect = true;
  343. var location = m.Groups[2].Value;
  344. var locs = location.Split(':');
  345. _targetHost = locs[0];
  346. if (locs.Length > 1)
  347. {
  348. if (!int.TryParse(locs[1], out _targetPort))
  349. {
  350. throw new Exception("Bad http header: " + line);
  351. }
  352. }
  353. else
  354. {
  355. _targetPort = 80;
  356. }
  357. }
  358. }
  359. }
  360. else
  361. {
  362. if (line.IsNullOrEmpty())
  363. {
  364. return true;
  365. }
  366. if (!_isConnect)
  367. {
  368. if (line.StartsWith("Host: "))
  369. {
  370. var location = line.Substring(6).Trim();
  371. var locs = location.Split(':');
  372. _targetHost = locs[0];
  373. if (locs.Length > 1)
  374. {
  375. if (!int.TryParse(locs[1], out _targetPort))
  376. {
  377. throw new Exception("Bad http header: " + line);
  378. }
  379. }
  380. else
  381. {
  382. _targetPort = 80;
  383. }
  384. }
  385. }
  386. }
  387. _requestLineCount++;
  388. return false;
  389. }
  390. private void OnFinish(byte[] lastBytes, int index, int length, object state)
  391. {
  392. if (_closed)
  393. {
  394. return;
  395. }
  396. if (_targetHost == null)
  397. {
  398. Logging.Error("Unkonwn host");
  399. Close();
  400. }
  401. else
  402. {
  403. if (length > 0)
  404. {
  405. _lastBytes = lastBytes;
  406. _lastBytesIndex = index;
  407. _lastBytesLength = length;
  408. }
  409. // Start socks5 conn
  410. _socks5 = new Socks5Proxy();
  411. _socks5.BeginConnectProxy(SocketUtil.GetEndPoint("127.0.0.1", _socks5Port), ProxyConnectCallback,
  412. null);
  413. }
  414. }
  415. #endregion
  416. }
  417. }
  418. }