|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- using Shadowsocks.Encryption;
- using Shadowsocks.Model;
- using Shadowsocks.Controller.Strategy;
-
- namespace Shadowsocks.Controller
- {
-
- class TCPRelay : Listener.Service
- {
- private ShadowsocksController _controller;
- public TCPRelay(ShadowsocksController controller)
- {
- this._controller = controller;
- }
-
- public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
- {
- if (socket.ProtocolType != ProtocolType.Tcp)
- {
- return false;
- }
- if (length < 2 || firstPacket[0] != 5)
- {
- return false;
- }
- socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
- Handler handler = new Handler();
- handler.connection = socket;
- Server server = _controller.GetCurrentStrategy().GetAServer(IStrategyCallerType.TCP, (IPEndPoint)socket.RemoteEndPoint);
- handler.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
- handler.server = server;
-
- handler.Start(firstPacket, length);
- return true;
- }
- }
-
- class Handler
- {
- //public Encryptor encryptor;
- public IEncryptor encryptor;
- public Server server;
- // Client socket.
- public Socket remote;
- public Socket connection;
-
- private byte command;
- private byte[] _firstPacket;
- private int _firstPacketLength;
- // Size of receive buffer.
- public const int RecvSize = 16384;
- public const int BufferSize = RecvSize + 32;
- // remote receive buffer
- private byte[] remoteRecvBuffer = new byte[RecvSize];
- // remote send buffer
- private byte[] remoteSendBuffer = new byte[BufferSize];
- // connection receive buffer
- private byte[] connetionRecvBuffer = new byte[RecvSize];
- // connection send buffer
- private byte[] connetionSendBuffer = new byte[BufferSize];
- // Received data string.
-
- private bool connectionShutdown = false;
- private bool remoteShutdown = false;
- private bool closed = false;
-
- private object encryptionLock = new object();
- private object decryptionLock = new object();
-
- public void Start(byte[] firstPacket, int length)
- {
- this._firstPacket = firstPacket;
- this._firstPacketLength = length;
- this.HandshakeReceive();
- }
-
- private void CheckClose()
- {
- if (connectionShutdown && remoteShutdown)
- {
- this.Close();
- }
- }
-
- public void Close()
- {
- lock (this)
- {
- if (closed)
- {
- return;
- }
- closed = true;
- }
- if (connection != null)
- {
- try
- {
- connection.Shutdown(SocketShutdown.Both);
- connection.Close();
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- }
- }
- if (remote != null)
- {
- try
- {
- remote.Shutdown(SocketShutdown.Both);
- remote.Close();
- }
- catch (SocketException e)
- {
- Logging.LogUsefulException(e);
- }
- }
- lock (encryptionLock)
- {
- lock (decryptionLock)
- {
- ((IDisposable)encryptor).Dispose();
- }
- }
- }
-
-
- private void HandshakeReceive()
- {
- if (closed)
- {
- return;
- }
- try
- {
- int bytesRead = _firstPacketLength;
-
- if (bytesRead > 1)
- {
- byte[] response = { 5, 0 };
- if (_firstPacket[0] != 5)
- {
- // reject socks 4
- response = new byte[] { 0, 91 };
- Console.WriteLine("socks 5 protocol error");
- }
- connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(HandshakeSendCallback), null);
- }
- else
- {
- this.Close();
- }
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void HandshakeSendCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- connection.EndSend(ar);
-
- // +----+-----+-------+------+----------+----------+
- // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
- // +----+-----+-------+------+----------+----------+
- // | 1 | 1 | X'00' | 1 | Variable | 2 |
- // +----+-----+-------+------+----------+----------+
- // Skip first 3 bytes
- // TODO validate
- connection.BeginReceive(connetionRecvBuffer, 0, 3, 0,
- new AsyncCallback(handshakeReceive2Callback), null);
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void handshakeReceive2Callback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- int bytesRead = connection.EndReceive(ar);
-
- if (bytesRead >= 3)
- {
- command = connetionRecvBuffer[1];
- if (command == 1)
- {
- byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
- connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(StartConnect), null);
- }
- else if (command == 3)
- {
- HandleUDPAssociate();
- }
- }
- else
- {
- Console.WriteLine("failed to recv data in handshakeReceive2Callback");
- this.Close();
- }
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void HandleUDPAssociate()
- {
- IPEndPoint endPoint = (IPEndPoint)connection.LocalEndPoint;
- byte[] address = endPoint.Address.GetAddressBytes();
- int port = endPoint.Port;
- byte[] response = new byte[4 + address.Length + 2];
- response[0] = 5;
- if (endPoint.AddressFamily == AddressFamily.InterNetwork)
- {
- response[3] = 1;
- }
- else if (endPoint.AddressFamily == AddressFamily.InterNetworkV6)
- {
- response[3] = 4;
- }
- address.CopyTo(response, 4);
- response[response.Length - 1] = (byte)(port & 0xFF);
- response[response.Length - 2] = (byte)((port >> 8) & 0xFF);
- connection.BeginSend(response, 0, response.Length, 0, new AsyncCallback(ReadAll), true);
- }
-
- private void ReadAll(IAsyncResult ar)
- {
-
- if (closed)
- {
- return;
- }
- try
- {
- if (ar.AsyncState != null)
- {
- connection.EndSend(ar);
- connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(ReadAll), null);
- }
- else
- {
- int bytesRead = connection.EndReceive(ar);
- if (bytesRead > 0)
- {
- connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(ReadAll), null);
- }
- else
- {
- this.Close();
- }
- }
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void StartConnect(IAsyncResult ar)
- {
- try
- {
- connection.EndSend(ar);
-
- // TODO async resolving
- IPAddress ipAddress;
- bool parsed = IPAddress.TryParse(server.server, out ipAddress);
- if (!parsed)
- {
- IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
- ipAddress = ipHostInfo.AddressList[0];
- }
- IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);
-
-
- remote = new Socket(ipAddress.AddressFamily,
- SocketType.Stream, ProtocolType.Tcp);
- remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
-
- // Connect to the remote endpoint.
- remote.BeginConnect(remoteEP,
- new AsyncCallback(ConnectCallback), null);
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void ConnectCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- // Complete the connection.
- remote.EndConnect(ar);
-
- //Console.WriteLine("Socket connected to {0}",
- // remote.RemoteEndPoint.ToString());
-
- StartPipe();
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void StartPipe()
- {
- if (closed)
- {
- return;
- }
- try
- {
- remote.BeginReceive(remoteRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(PipeRemoteReceiveCallback), null);
- connection.BeginReceive(connetionRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(PipeConnectionReceiveCallback), null);
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void PipeRemoteReceiveCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- int bytesRead = remote.EndReceive(ar);
-
- if (bytesRead > 0)
- {
- int bytesToSend;
- lock (decryptionLock)
- {
- if (closed)
- {
- return;
- }
- encryptor.Decrypt(remoteRecvBuffer, bytesRead, remoteSendBuffer, out bytesToSend);
- }
- connection.BeginSend(remoteSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeConnectionSendCallback), null);
- }
- else
- {
- //Console.WriteLine("bytesRead: " + bytesRead.ToString());
- connection.Shutdown(SocketShutdown.Send);
- connectionShutdown = true;
- CheckClose();
- }
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void PipeConnectionReceiveCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- int bytesRead = connection.EndReceive(ar);
-
- if (bytesRead > 0)
- {
- int bytesToSend;
- lock (encryptionLock)
- {
- if (closed)
- {
- return;
- }
- encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
- }
- remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
- }
- else
- {
- remote.Shutdown(SocketShutdown.Send);
- remoteShutdown = true;
- CheckClose();
- }
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void PipeRemoteSendCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- remote.EndSend(ar);
- connection.BeginReceive(this.connetionRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(PipeConnectionReceiveCallback), null);
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
-
- private void PipeConnectionSendCallback(IAsyncResult ar)
- {
- if (closed)
- {
- return;
- }
- try
- {
- connection.EndSend(ar);
- remote.BeginReceive(this.remoteRecvBuffer, 0, RecvSize, 0,
- new AsyncCallback(PipeRemoteReceiveCallback), null);
- }
- catch (Exception e)
- {
- Logging.LogUsefulException(e);
- this.Close();
- }
- }
- }
-
- }
|