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 20 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
10 years ago
12 years ago
12 years ago
12 years ago
10 years ago
10 years ago
12 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
10 years ago
10 years ago
12 years ago
10 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
10 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
10 years ago
12 years ago
10 years ago
12 years ago
12 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
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
12 years ago
10 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
12 years ago
10 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. using System.Timers;
  10. namespace Shadowsocks.Controller
  11. {
  12. class TCPRelay : Listener.Service
  13. {
  14. private ShadowsocksController _controller;
  15. public ISet<Handler> Handlers
  16. {
  17. get; set;
  18. }
  19. public TCPRelay(ShadowsocksController controller)
  20. {
  21. this._controller = controller;
  22. this.Handlers = new HashSet<Handler>();
  23. }
  24. public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
  25. {
  26. if (socket.ProtocolType != ProtocolType.Tcp)
  27. {
  28. return false;
  29. }
  30. if (length < 2 || firstPacket[0] != 5)
  31. {
  32. return false;
  33. }
  34. socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  35. Handler handler = new Handler();
  36. handler.connection = socket;
  37. handler.controller = _controller;
  38. handler.relay = this;
  39. handler.Start(firstPacket, length);
  40. lock (this.Handlers)
  41. {
  42. this.Handlers.Add(handler);
  43. Logging.Debug($"connections: {Handlers.Count}");
  44. }
  45. return true;
  46. }
  47. }
  48. class Handler
  49. {
  50. //public Encryptor encryptor;
  51. public IEncryptor encryptor;
  52. public Server server;
  53. // Client socket.
  54. public Socket remote;
  55. public Socket connection;
  56. public ShadowsocksController controller;
  57. public TCPRelay relay;
  58. private int retryCount = 0;
  59. private bool connected;
  60. private byte command;
  61. private byte[] _firstPacket;
  62. private int _firstPacketLength;
  63. // Size of receive buffer.
  64. public const int RecvSize = 8192;
  65. public const int BufferSize = RecvSize + 32;
  66. private int totalRead = 0;
  67. private int totalWrite = 0;
  68. // remote receive buffer
  69. private byte[] remoteRecvBuffer = new byte[RecvSize];
  70. // remote send buffer
  71. private byte[] remoteSendBuffer = new byte[BufferSize];
  72. // connection receive buffer
  73. private byte[] connetionRecvBuffer = new byte[RecvSize];
  74. // connection send buffer
  75. private byte[] connetionSendBuffer = new byte[BufferSize];
  76. // Received data string.
  77. private bool connectionShutdown = false;
  78. private bool remoteShutdown = false;
  79. private bool closed = false;
  80. private object encryptionLock = new object();
  81. private object decryptionLock = new object();
  82. private DateTime _startConnectTime;
  83. public void CreateRemote()
  84. {
  85. Server server = controller.GetAServer(IStrategyCallerType.TCP, (IPEndPoint)connection.RemoteEndPoint);
  86. if (server == null || server.server == "")
  87. {
  88. throw new ArgumentException("No server configured");
  89. }
  90. this.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
  91. this.server = server;
  92. }
  93. public void Start(byte[] firstPacket, int length)
  94. {
  95. this._firstPacket = firstPacket;
  96. this._firstPacketLength = length;
  97. this.HandshakeReceive();
  98. }
  99. private void CheckClose()
  100. {
  101. if (connectionShutdown && remoteShutdown)
  102. {
  103. this.Close();
  104. }
  105. }
  106. public void Close()
  107. {
  108. lock (relay.Handlers)
  109. {
  110. Logging.Debug($"connections: {relay.Handlers.Count}");
  111. relay.Handlers.Remove(this);
  112. }
  113. lock (this)
  114. {
  115. if (closed)
  116. {
  117. return;
  118. }
  119. closed = true;
  120. }
  121. if (connection != null)
  122. {
  123. try
  124. {
  125. connection.Shutdown(SocketShutdown.Both);
  126. connection.Close();
  127. }
  128. catch (Exception e)
  129. {
  130. Logging.LogUsefulException(e);
  131. }
  132. }
  133. if (remote != null)
  134. {
  135. try
  136. {
  137. remote.Shutdown(SocketShutdown.Both);
  138. remote.Close();
  139. }
  140. catch (Exception e)
  141. {
  142. Logging.LogUsefulException(e);
  143. }
  144. }
  145. lock (encryptionLock)
  146. {
  147. lock (decryptionLock)
  148. {
  149. if (encryptor != null)
  150. {
  151. ((IDisposable)encryptor).Dispose();
  152. }
  153. }
  154. }
  155. }
  156. private void HandshakeReceive()
  157. {
  158. if (closed)
  159. {
  160. return;
  161. }
  162. try
  163. {
  164. int bytesRead = _firstPacketLength;
  165. if (bytesRead > 1)
  166. {
  167. byte[] response = { 5, 0 };
  168. if (_firstPacket[0] != 5)
  169. {
  170. // reject socks 4
  171. response = new byte[] { 0, 91 };
  172. Console.WriteLine("socks 5 protocol error");
  173. }
  174. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(HandshakeSendCallback), null);
  175. }
  176. else
  177. {
  178. this.Close();
  179. }
  180. }
  181. catch (Exception e)
  182. {
  183. Logging.LogUsefulException(e);
  184. this.Close();
  185. }
  186. }
  187. private void HandshakeSendCallback(IAsyncResult ar)
  188. {
  189. if (closed)
  190. {
  191. return;
  192. }
  193. try
  194. {
  195. connection.EndSend(ar);
  196. // +----+-----+-------+------+----------+----------+
  197. // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  198. // +----+-----+-------+------+----------+----------+
  199. // | 1 | 1 | X'00' | 1 | Variable | 2 |
  200. // +----+-----+-------+------+----------+----------+
  201. // Skip first 3 bytes
  202. // TODO validate
  203. connection.BeginReceive(connetionRecvBuffer, 0, 3, 0,
  204. new AsyncCallback(handshakeReceive2Callback), null);
  205. }
  206. catch (Exception e)
  207. {
  208. Logging.LogUsefulException(e);
  209. this.Close();
  210. }
  211. }
  212. private void handshakeReceive2Callback(IAsyncResult ar)
  213. {
  214. if (closed)
  215. {
  216. return;
  217. }
  218. try
  219. {
  220. int bytesRead = connection.EndReceive(ar);
  221. if (bytesRead >= 3)
  222. {
  223. command = connetionRecvBuffer[1];
  224. if (command == 1)
  225. {
  226. byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
  227. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ResponseCallback), null);
  228. }
  229. else if (command == 3)
  230. {
  231. HandleUDPAssociate();
  232. }
  233. }
  234. else
  235. {
  236. Console.WriteLine("failed to recv data in handshakeReceive2Callback");
  237. this.Close();
  238. }
  239. }
  240. catch (Exception e)
  241. {
  242. Logging.LogUsefulException(e);
  243. this.Close();
  244. }
  245. }
  246. private void HandleUDPAssociate()
  247. {
  248. IPEndPoint endPoint = (IPEndPoint)connection.LocalEndPoint;
  249. byte[] address = endPoint.Address.GetAddressBytes();
  250. int port = endPoint.Port;
  251. byte[] response = new byte[4 + address.Length + 2];
  252. response[0] = 5;
  253. if (endPoint.AddressFamily == AddressFamily.InterNetwork)
  254. {
  255. response[3] = 1;
  256. }
  257. else if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
  258. {
  259. response[3] = 4;
  260. }
  261. address.CopyTo(response, 4);
  262. response[response.Length - 1] = (byte)(port & 0xFF);
  263. response[response.Length - 2] = (byte)((port >> 8) & 0xFF);
  264. connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ReadAll), true);
  265. }
  266. private void ReadAll(IAsyncResult ar)
  267. {
  268. if (closed)
  269. {
  270. return;
  271. }
  272. try
  273. {
  274. if (ar.AsyncState != null)
  275. {
  276. connection.EndSend(ar);
  277. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  278. new AsyncCallback(ReadAll), null);
  279. }
  280. else
  281. {
  282. int bytesRead = connection.EndReceive(ar);
  283. if (bytesRead > 0)
  284. {
  285. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  286. new AsyncCallback(ReadAll), null);
  287. }
  288. else
  289. {
  290. this.Close();
  291. }
  292. }
  293. }
  294. catch (Exception e)
  295. {
  296. Logging.LogUsefulException(e);
  297. this.Close();
  298. }
  299. }
  300. private void ResponseCallback(IAsyncResult ar)
  301. {
  302. try
  303. {
  304. connection.EndSend(ar);
  305. StartConnect();
  306. }
  307. catch (Exception e)
  308. {
  309. Logging.LogUsefulException(e);
  310. this.Close();
  311. }
  312. }
  313. private class ServerTimer : Timer
  314. {
  315. public Server Server;
  316. public ServerTimer(int p) :base(p)
  317. {
  318. }
  319. }
  320. private void StartConnect()
  321. {
  322. try
  323. {
  324. CreateRemote();
  325. // TODO async resolving
  326. IPAddress ipAddress;
  327. bool parsed = IPAddress.TryParse(server.server, out ipAddress);
  328. if (!parsed)
  329. {
  330. IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
  331. ipAddress = ipHostInfo.AddressList[0];
  332. }
  333. IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);
  334. remote = new Socket(ipAddress.AddressFamily,
  335. SocketType.Stream, ProtocolType.Tcp);
  336. remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  337. _startConnectTime = DateTime.Now;
  338. ServerTimer connectTimer = new ServerTimer(3000);
  339. connectTimer.AutoReset = false;
  340. connectTimer.Elapsed += connectTimer_Elapsed;
  341. connectTimer.Enabled = true;
  342. connectTimer.Server = server;
  343. connected = false;
  344. // Connect to the remote endpoint.
  345. remote.BeginConnect(remoteEP,
  346. new AsyncCallback(ConnectCallback), connectTimer);
  347. }
  348. catch (Exception e)
  349. {
  350. Logging.LogUsefulException(e);
  351. this.Close();
  352. }
  353. }
  354. private void connectTimer_Elapsed(object sender, ElapsedEventArgs e)
  355. {
  356. if (connected)
  357. {
  358. return;
  359. }
  360. Server server = ((ServerTimer)sender).Server;
  361. IStrategy strategy = controller.GetCurrentStrategy();
  362. if (strategy != null)
  363. {
  364. strategy.SetFailure(server);
  365. }
  366. Console.WriteLine(String.Format("{0} timed out", server.FriendlyName()));
  367. remote.Close();
  368. RetryConnect();
  369. }
  370. private void RetryConnect()
  371. {
  372. if (retryCount < 4)
  373. {
  374. Logging.Debug("Connection failed, retrying");
  375. StartConnect();
  376. retryCount++;
  377. }
  378. else
  379. {
  380. this.Close();
  381. }
  382. }
  383. private void ConnectCallback(IAsyncResult ar)
  384. {
  385. Server server = null;
  386. if (closed)
  387. {
  388. return;
  389. }
  390. try
  391. {
  392. ServerTimer timer = (ServerTimer)ar.AsyncState;
  393. server = timer.Server;
  394. timer.Elapsed -= connectTimer_Elapsed;
  395. timer.Enabled = false;
  396. timer.Dispose();
  397. // Complete the connection.
  398. remote.EndConnect(ar);
  399. connected = true;
  400. //Console.WriteLine("Socket connected to {0}",
  401. // remote.RemoteEndPoint.ToString());
  402. var latency = DateTime.Now - _startConnectTime;
  403. IStrategy strategy = controller.GetCurrentStrategy();
  404. if (strategy != null)
  405. {
  406. strategy.UpdateLatency(server, latency);
  407. }
  408. StartPipe();
  409. }
  410. catch (ArgumentException)
  411. {
  412. }
  413. catch (Exception e)
  414. {
  415. if (server != null)
  416. {
  417. IStrategy strategy = controller.GetCurrentStrategy();
  418. if (strategy != null)
  419. {
  420. strategy.SetFailure(server);
  421. }
  422. }
  423. Logging.LogUsefulException(e);
  424. RetryConnect();
  425. }
  426. }
  427. private void StartPipe()
  428. {
  429. if (closed)
  430. {
  431. return;
  432. }
  433. try
  434. {
  435. remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
  436. new AsyncCallback(PipeRemoteReceiveCallback), null);
  437. connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
  438. new AsyncCallback(PipeConnectionReceiveCallback), null);
  439. }
  440. catch (Exception e)
  441. {
  442. Logging.LogUsefulException(e);
  443. this.Close();
  444. }
  445. }
  446. private void PipeRemoteReceiveCallback(IAsyncResult ar)
  447. {
  448. if (closed)
  449. {
  450. return;
  451. }
  452. try
  453. {
  454. int bytesRead = remote.EndReceive(ar);
  455. totalRead += bytesRead;
  456. if (bytesRead > 0)
  457. {
  458. int bytesToSend;
  459. lock (decryptionLock)
  460. {
  461. if (closed)
  462. {
  463. return;
  464. }
  465. encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend);
  466. }
  467. connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null);
  468. IStrategy strategy = controller.GetCurrentStrategy();
  469. if (strategy != null)
  470. {
  471. strategy.UpdateLastRead(this.server);
  472. }
  473. }
  474. else
  475. {
  476. //Console.WriteLine("bytesRead: " + bytesRead.ToString());
  477. connection.Shutdown(SocketShutdown.Send);
  478. connectionShutdown = true;
  479. CheckClose();
  480. if (totalRead == 0)
  481. {
  482. // closed before anything received, reports as failure
  483. // disable this feature
  484. // controller.GetCurrentStrategy().SetFailure(this.server);
  485. }
  486. }
  487. }
  488. catch (Exception e)
  489. {
  490. Logging.LogUsefulException(e);
  491. this.Close();
  492. }
  493. }
  494. private void PipeConnectionReceiveCallback(IAsyncResult ar)
  495. {
  496. if (closed)
  497. {
  498. return;
  499. }
  500. try
  501. {
  502. int bytesRead = connection.EndReceive(ar);
  503. totalWrite += bytesRead;
  504. if (bytesRead > 0)
  505. {
  506. int bytesToSend;
  507. lock (encryptionLock)
  508. {
  509. if (closed)
  510. {
  511. return;
  512. }
  513. encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
  514. }
  515. remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
  516. IStrategy strategy = controller.GetCurrentStrategy();
  517. if (strategy != null)
  518. {
  519. strategy.UpdateLastWrite(this.server);
  520. }
  521. }
  522. else
  523. {
  524. remote.Shutdown(SocketShutdown.Send);
  525. remoteShutdown = true;
  526. CheckClose();
  527. }
  528. }
  529. catch (Exception e)
  530. {
  531. Logging.LogUsefulException(e);
  532. this.Close();
  533. }
  534. }
  535. private void PipeRemoteSendCallback(IAsyncResult ar)
  536. {
  537. if (closed)
  538. {
  539. return;
  540. }
  541. try
  542. {
  543. remote.EndSend(ar);
  544. connection.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0,
  545. new AsyncCallback(PipeConnectionReceiveCallback), null);
  546. }
  547. catch (Exception e)
  548. {
  549. Logging.LogUsefulException(e);
  550. this.Close();
  551. }
  552. }
  553. private void PipeConnectionSendCallback(IAsyncResult ar)
  554. {
  555. if (closed)
  556. {
  557. return;
  558. }
  559. try
  560. {
  561. connection.EndSend(ar);
  562. remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0,
  563. new AsyncCallback(PipeRemoteReceiveCallback), null);
  564. }
  565. catch (Exception e)
  566. {
  567. Logging.LogUsefulException(e);
  568. this.Close();
  569. }
  570. }
  571. }
  572. }