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.

TCPRelay.cs 15 kB

12 years ago
12 years ago
10 years ago
12 years ago
10 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
10 years ago
10 years ago
10 years ago
12 years ago
10 years ago
10 years ago
10 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
10 years ago
10 years ago
10 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
10 years ago
10 years ago
10 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
10 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
10 years ago
10 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using Shadowsocks.Encryption;
  7. using Shadowsocks.Model;
  8. using Shadowsocks.Controller.Strategy;
  9. namespace Shadowsocks.Controller
  10. {
  11. class TCPRelay : Listener.Service
  12. {
  13. private ShadowsocksController _controller;
  14. public TCPRelay(ShadowsocksController controller)
  15. {
  16. this._controller = controller;
  17. }
  18. public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
  19. {
  20. if (socket.ProtocolType != ProtocolType.Tcp)
  21. {
  22. return false;
  23. }
  24. if (length < 2 || firstPacket[0] != 5)
  25. {
  26. return false;
  27. }
  28. socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  29. Handler handler = new Handler();
  30. handler.connection = socket;
  31. Server server = _controller.GetCurrentStrategy().GetAServer(IStrategyCallerType.TCP, (IPEndPoint)socket.RemoteEndPoint);
  32. handler.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
  33. handler.server = server;
  34. handler.Start(firstPacket, length);
  35. return true;
  36. }
  37. }
  38. class Handler
  39. {
  40. //public Encryptor encryptor;
  41. public IEncryptor encryptor;
  42. public Server server;
  43. // Client socket.
  44. public Socket remote;
  45. public Socket connection;
  46. private byte command;
  47. private byte[] _firstPacket;
  48. private int _firstPacketLength;
  49. // Size of receive buffer.
  50. public const int RecvSize = 16384;
  51. public const int BufferSize = RecvSize + 32;
  52. // remote receive buffer
  53. private byte[] remoteRecvBuffer = new byte[RecvSize];
  54. // remote send buffer
  55. private byte[] remoteSendBuffer = new byte[BufferSize];
  56. // connection receive buffer
  57. private byte[] connetionRecvBuffer = new byte[RecvSize];
  58. // connection send buffer
  59. private byte[] connetionSendBuffer = new byte[BufferSize];
  60. // Received data string.
  61. private bool connectionShutdown = false;
  62. private bool remoteShutdown = false;
  63. private bool closed = false;
  64. private object encryptionLock = new object();
  65. private object decryptionLock = new object();
  66. public void Start(byte[] firstPacket, int length)
  67. {
  68. this._firstPacket = firstPacket;
  69. this._firstPacketLength = length;
  70. this.HandshakeReceive();
  71. }
  72. private void CheckClose()
  73. {
  74. if (connectionShutdown && remoteShutdown)
  75. {
  76. this.Close();
  77. }
  78. }
  79. public void Close()
  80. {
  81. lock (this)
  82. {
  83. if (closed)
  84. {
  85. return;
  86. }
  87. closed = true;
  88. }
  89. if (connection != null)
  90. {
  91. try
  92. {
  93. connection.Shutdown(SocketShutdown.Both);
  94. connection.Close();
  95. }
  96. catch (Exception e)
  97. {
  98. Logging.LogUsefulException(e);
  99. }
  100. }
  101. if (remote != null)
  102. {
  103. try
  104. {
  105. remote.Shutdown(SocketShutdown.Both);
  106. remote.Close();
  107. }
  108. catch (SocketException e)
  109. {
  110. Logging.LogUsefulException(e);
  111. }
  112. }
  113. lock (encryptionLock)
  114. {
  115. lock (decryptionLock)
  116. {
  117. ((IDisposable)encryptor).Dispose();
  118. }
  119. }
  120. }
  121. private void HandshakeReceive()
  122. {
  123. if (closed)
  124. {
  125. return;
  126. }
  127. try
  128. {
  129. int bytesRead = _firstPacketLength;
  130. if (bytesRead > 1)
  131. {
  132. byte[] response = { 5, 0 };
  133. if (_firstPacket[0] != 5)
  134. {
  135. // reject socks 4
  136. response = new byte[] { 0, 91 };
  137. Console.WriteLine("socks 5 protocol error");
  138. }
  139. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(HandshakeSendCallback), null);
  140. }
  141. else
  142. {
  143. this.Close();
  144. }
  145. }
  146. catch (Exception e)
  147. {
  148. Logging.LogUsefulException(e);
  149. this.Close();
  150. }
  151. }
  152. private void HandshakeSendCallback(IAsyncResult ar)
  153. {
  154. if (closed)
  155. {
  156. return;
  157. }
  158. try
  159. {
  160. connection.EndSend(ar);
  161. // +----+-----+-------+------+----------+----------+
  162. // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  163. // +----+-----+-------+------+----------+----------+
  164. // | 1 | 1 | X'00' | 1 | Variable | 2 |
  165. // +----+-----+-------+------+----------+----------+
  166. // Skip first 3 bytes
  167. // TODO validate
  168. connection.BeginReceive(connetionRecvBuffer, 0, 3, 0,
  169. new AsyncCallback(handshakeReceive2Callback), null);
  170. }
  171. catch (Exception e)
  172. {
  173. Logging.LogUsefulException(e);
  174. this.Close();
  175. }
  176. }
  177. private void handshakeReceive2Callback(IAsyncResult ar)
  178. {
  179. if (closed)
  180. {
  181. return;
  182. }
  183. try
  184. {
  185. int bytesRead = connection.EndReceive(ar);
  186. if (bytesRead >= 3)
  187. {
  188. command = connetionRecvBuffer[1];
  189. if (command == 1)
  190. {
  191. byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
  192. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(StartConnect), null);
  193. }
  194. else if (command == 3)
  195. {
  196. HandleUDPAssociate();
  197. }
  198. }
  199. else
  200. {
  201. Console.WriteLine("failed to recv data in handshakeReceive2Callback");
  202. this.Close();
  203. }
  204. }
  205. catch (Exception e)
  206. {
  207. Logging.LogUsefulException(e);
  208. this.Close();
  209. }
  210. }
  211. private void HandleUDPAssociate()
  212. {
  213. IPEndPoint endPoint = (IPEndPoint)connection.LocalEndPoint;
  214. byte[] address = endPoint.Address.GetAddressBytes();
  215. int port = endPoint.Port;
  216. byte[] response = new byte[4 + address.Length + 2];
  217. response[0] = 5;
  218. if (endPoint.AddressFamily == AddressFamily.InterNetwork)
  219. {
  220. response[3] = 1;
  221. }
  222. else if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
  223. {
  224. response[3] = 4;
  225. }
  226. address.CopyTo(response, 4);
  227. response[response.Length - 1] = (byte)(port & 0xFF);
  228. response[response.Length - 2] = (byte)((port >> 8) & 0xFF);
  229. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ReadAll), true);
  230. }
  231. private void ReadAll(IAsyncResult ar)
  232. {
  233. if (closed)
  234. {
  235. return;
  236. }
  237. try
  238. {
  239. if (ar.AsyncState != null)
  240. {
  241. connection.EndSend(ar);
  242. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  243. new AsyncCallback(ReadAll), null);
  244. }
  245. else
  246. {
  247. int bytesRead = connection.EndReceive(ar);
  248. if (bytesRead > 0)
  249. {
  250. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  251. new AsyncCallback(ReadAll), null);
  252. }
  253. else
  254. {
  255. this.Close();
  256. }
  257. }
  258. }
  259. catch (Exception e)
  260. {
  261. Logging.LogUsefulException(e);
  262. this.Close();
  263. }
  264. }
  265. private void StartConnect(IAsyncResult ar)
  266. {
  267. try
  268. {
  269. connection.EndSend(ar);
  270. // TODO async resolving
  271. IPAddress ipAddress;
  272. bool parsed = IPAddress.TryParse(server.server, out ipAddress);
  273. if (!parsed)
  274. {
  275. IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
  276. ipAddress = ipHostInfo.AddressList[0];
  277. }
  278. IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);
  279. remote = new Socket(ipAddress.AddressFamily,
  280. SocketType.Stream, ProtocolType.Tcp);
  281. remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  282. // Connect to the remote endpoint.
  283. remote.BeginConnect(remoteEP,
  284. new AsyncCallback(ConnectCallback), null);
  285. }
  286. catch (Exception e)
  287. {
  288. Logging.LogUsefulException(e);
  289. this.Close();
  290. }
  291. }
  292. private void ConnectCallback(IAsyncResult ar)
  293. {
  294. if (closed)
  295. {
  296. return;
  297. }
  298. try
  299. {
  300. // Complete the connection.
  301. remote.EndConnect(ar);
  302. //Console.WriteLine("Socket connected to {0}",
  303. // remote.RemoteEndPoint.ToString());
  304. StartPipe();
  305. }
  306. catch (Exception e)
  307. {
  308. Logging.LogUsefulException(e);
  309. this.Close();
  310. }
  311. }
  312. private void StartPipe()
  313. {
  314. if (closed)
  315. {
  316. return;
  317. }
  318. try
  319. {
  320. remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
  321. new AsyncCallback(PipeRemoteReceiveCallback), null);
  322. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  323. new AsyncCallback(PipeConnectionReceiveCallback), null);
  324. }
  325. catch (Exception e)
  326. {
  327. Logging.LogUsefulException(e);
  328. this.Close();
  329. }
  330. }
  331. private void PipeRemoteReceiveCallback(IAsyncResult ar)
  332. {
  333. if (closed)
  334. {
  335. return;
  336. }
  337. try
  338. {
  339. int bytesRead = remote.EndReceive(ar);
  340. if (bytesRead > 0)
  341. {
  342. int bytesToSend;
  343. lock (decryptionLock)
  344. {
  345. if (closed)
  346. {
  347. return;
  348. }
  349. encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend);
  350. }
  351. connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null);
  352. }
  353. else
  354. {
  355. //Console.WriteLine("bytesRead: " + bytesRead.ToString());
  356. connection.Shutdown(SocketShutdown.Send);
  357. connectionShutdown = true;
  358. CheckClose();
  359. }
  360. }
  361. catch (Exception e)
  362. {
  363. Logging.LogUsefulException(e);
  364. this.Close();
  365. }
  366. }
  367. private void PipeConnectionReceiveCallback(IAsyncResult ar)
  368. {
  369. if (closed)
  370. {
  371. return;
  372. }
  373. try
  374. {
  375. int bytesRead = connection.EndReceive(ar);
  376. if (bytesRead > 0)
  377. {
  378. int bytesToSend;
  379. lock (encryptionLock)
  380. {
  381. if (closed)
  382. {
  383. return;
  384. }
  385. encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
  386. }
  387. remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
  388. }
  389. else
  390. {
  391. remote.Shutdown(SocketShutdown.Send);
  392. remoteShutdown = true;
  393. CheckClose();
  394. }
  395. }
  396. catch (Exception e)
  397. {
  398. Logging.LogUsefulException(e);
  399. this.Close();
  400. }
  401. }
  402. private void PipeRemoteSendCallback(IAsyncResult ar)
  403. {
  404. if (closed)
  405. {
  406. return;
  407. }
  408. try
  409. {
  410. remote.EndSend(ar);
  411. connection.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0,
  412. new AsyncCallback(PipeConnectionReceiveCallback), null);
  413. }
  414. catch (Exception e)
  415. {
  416. Logging.LogUsefulException(e);
  417. this.Close();
  418. }
  419. }
  420. private void PipeConnectionSendCallback(IAsyncResult ar)
  421. {
  422. if (closed)
  423. {
  424. return;
  425. }
  426. try
  427. {
  428. connection.EndSend(ar);
  429. remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0,
  430. new AsyncCallback(PipeRemoteReceiveCallback), null);
  431. }
  432. catch (Exception e)
  433. {
  434. Logging.LogUsefulException(e);
  435. this.Close();
  436. }
  437. }
  438. }
  439. }