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