Exemplo n.º 1
0
        public bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (length < 2 || firstPacket[0] != 5)
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Handler handler = new Handler();
            handler.connection = socket;
            Server server = _config.GetCurrentServer();
            handler.encryptor = EncryptorFactory.GetEncryptor(server.method, server.password);
            handler.server = server;

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 2
0
        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;
            handler.controller = _controller;
            handler.relay = this;

            handler.Start(firstPacket, length);
            IList<Handler> handlersToClose = new List<Handler>();
            lock (this.Handlers)
            {
                this.Handlers.Add(handler);
                Logging.Debug($"connections: {Handlers.Count}");
                DateTime now = DateTime.Now;
                if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
                {
                    _lastSweepTime = now;
                    foreach (Handler handler1 in this.Handlers)
                    {
                        if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
                        {
                            handlersToClose.Add(handler1);
                        }
                    }
                }
            }
            foreach (Handler handler1 in handlersToClose)
            {
                Logging.Debug("Closing timed out connection");
                handler1.Close();
            }
        return true;
        }
Exemplo n.º 3
0
        public bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (length < 2
                || (firstPacket[0] != 5 && firstPacket[0] != 4))
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Handler handler = new Handler();

            //handler.config = _config;
            handler.getCurrentServer = delegate (bool usingRandom, bool forceRandom) { return _config.GetCurrentServer(usingRandom, forceRandom); };
            handler.connection = socket;
            handler.reconnectTimesRemain = _config.reconnectTimes;

            handler.server = _config.GetCurrentServer(true);
            if (_config.socks5enable)
            {
                handler.socks5RemoteHost = _config.socks5Host;
                handler.socks5RemotePort = _config.socks5Port;
                handler.socks5RemoteUsername = _config.socks5User;
                handler.socks5RemotePassword = _config.socks5Pass;
            }
            handler.obfs = ObfsFactory.GetObfs(handler.server.obfs);
            handler.TTL = _config.TTL;
            handler.autoSwitchOff = _config.autoban;

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 4
0
        public bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (!Accept(firstPacket, length))
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Handler handler = new Handler();

            handler.getCurrentServer = delegate (bool usingRandom, bool forceRandom) { return _config.GetCurrentServer(usingRandom, forceRandom); };
            handler.connection = socket;
            handler.reconnectTimesRemain = _config.reconnectTimes;
            handler.forceRandom = _config.random;

            handler.server = _config.GetCurrentServer(true);
            if (_config.proxyEnable)
            {
                handler.proxyType = _config.proxyType;
                handler.socks5RemoteHost = _config.proxyHost;
                handler.socks5RemotePort = _config.proxyPort;
                handler.socks5RemoteUsername = _config.proxyAuthUser;
                handler.socks5RemotePassword = _config.proxyAuthPass;
            }
            handler.TTL = _config.TTL;
            handler.autoSwitchOff = _config.autoban;
            if (_config.authUser != null && _config.authUser.Length > 0)
            {
                handler.authConnection = AuthConnection;
                handler.authUser = _config.authUser ?? "";
                handler.authPass = _config.authPass ?? "";
            }
            if (!EncryptorLoaded)
            {
                try
                {
                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(handler.server.method, handler.server.password);
                    encryptor.Dispose();
                }
                catch
                {

                }
                finally
                {
                    EncryptorLoaded = true;
                }
            }

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 5
0
        public bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (!Accept(firstPacket, length))
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Handler handler = new Handler();

            handler.getCurrentServer = delegate (bool usingRandom, bool forceRandom) { return _config.GetCurrentServer(usingRandom, forceRandom); };
            handler.connection = socket;
            handler.reconnectTimesRemain = _config.reconnectTimes;

            handler.server = _config.GetCurrentServer(true);
            if (_config.socks5enable)
            {
                handler.socks5RemoteHost = _config.socks5Host;
                handler.socks5RemotePort = _config.socks5Port;
                handler.socks5RemoteUsername = _config.socks5User;
                handler.socks5RemotePassword = _config.socks5Pass;
            }
            handler.TTL = _config.TTL;
            handler.autoSwitchOff = _config.autoban;
            if (_config.authUser != null && _config.authUser.Length > 0)
            {
                string authStr = _config.authUser + ":" + (_config.authPass ?? "");
                handler.httpAuthString = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(authStr));
            }
            if (!EncryptorLoaded)
            {
                try
                {
                    IEncryptor encryptor = EncryptorFactory.GetEncryptor(handler.server.method, handler.server.password);
                    encryptor.Dispose();
                }
                catch (Exception)
                {

                }
                finally
                {
                    EncryptorLoaded = true;
                }
            }

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 6
0
        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;
            handler.controller = _controller;

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 7
0
        public void AcceptCallback(IAsyncResult ar)
        {
            Socket listener = (Socket)ar.AsyncState;
            try
            {
                Socket conn = listener.EndAccept(ar);
                conn.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                Handler handler = new Handler();
                handler.connection = conn;
                handler.encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);
                handler.config = _server;

                handler.Start();
            }
            catch
            {
                //Console.WriteLine(e.Message);
            }
            finally
            {
                try
                {
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);
                }
                catch
                {
                    //Console.WriteLine(e.Message);
                }
            }
        }
Exemplo n.º 8
0
        public bool Handle(byte[] firstPacket, int length, Socket socket)
        {
            if (length < 2)
            {
                return false;
            }
            bool accept = false;
            if (firstPacket[0] == 5 || firstPacket[0] == 4)
            {
                accept = true;
            }
            else if (length > 8
                && firstPacket[0] == 'C'
                && firstPacket[1] == 'O'
                && firstPacket[2] == 'N'
                && firstPacket[3] == 'N'
                && firstPacket[4] == 'E'
                && firstPacket[5] == 'C'
                && firstPacket[6] == 'T'
                && firstPacket[7] == ' ')
            {
                accept = true;
            }
            else if (_config.buildinHttpProxy)
            {
                if (length > 8
                  && firstPacket[0] == 'G'
                  && firstPacket[1] == 'E'
                  && firstPacket[2] == 'T'
                  && firstPacket[3] == ' '
                  && firstPacket[4] == 'h'
                  && firstPacket[5] == 't'
                  && firstPacket[6] == 't'
                  && firstPacket[7] == 'p'
                  && firstPacket[8] == ':'
                  )
                {
                    accept = true;
                }
                else if (length > 9
                    && firstPacket[0] == 'P'
                    && firstPacket[1] == 'O'
                    && firstPacket[2] == 'S'
                    && firstPacket[3] == 'T'
                    && firstPacket[4] == ' '
                    && firstPacket[5] == 'h'
                    && firstPacket[6] == 't'
                    && firstPacket[7] == 't'
                    && firstPacket[8] == 'p'
                    && firstPacket[9] == ':'
                    )
                {
                    accept = true;
                }
                else if (length > 9
                    && firstPacket[0] == 'H'
                    && firstPacket[1] == 'E'
                    && firstPacket[2] == 'A'
                    && firstPacket[3] == 'D'
                    && firstPacket[4] == ' '
                    && firstPacket[5] == 'h'
                    && firstPacket[6] == 't'
                    && firstPacket[7] == 't'
                    && firstPacket[8] == 'p'
                    && firstPacket[9] == ':'
                    )
                {
                    accept = true;
                }
            }
            if (!accept)
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            Handler handler = new Handler();

            //handler.config = _config;
            handler.getCurrentServer = delegate (bool usingRandom, bool forceRandom) { return _config.GetCurrentServer(usingRandom, forceRandom); };
            handler.connection = socket;
            handler.reconnectTimesRemain = _config.reconnectTimes;

            handler.server = _config.GetCurrentServer(true);
            if (_config.socks5enable)
            {
                handler.socks5RemoteHost = _config.socks5Host;
                handler.socks5RemotePort = _config.socks5Port;
                handler.socks5RemoteUsername = _config.socks5User;
                handler.socks5RemotePassword = _config.socks5Pass;
            }
            handler.TTL = _config.TTL;
            handler.autoSwitchOff = _config.autoban;
            if (_config.authUser != null && _config.authUser.Length > 0)
            {
                string authStr = _config.authUser + ":" + (_config.authPass ?? "");
                handler.httpAuthString = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(authStr));
            }

            handler.Start(firstPacket, length);
            return true;
        }
Exemplo n.º 9
0
        private void Connect()
        {
            Handler.GetCurrentServer  getCurrentServer  = delegate(ServerSelectStrategy.FilterFunc filter, string targetURI, bool cfgRandom, bool usingRandom, bool forceRandom) { return(_config.GetCurrentServer(filter, targetURI, cfgRandom, usingRandom, forceRandom)); };
            Handler.KeepCurrentServer keepCurrentServer = delegate(string targetURI, string id) { _config.KeepCurrentServer(targetURI, id); };

            int     local_port = ((IPEndPoint)_connection.LocalEndPoint).Port;
            Handler handler    = new Handler();

            handler.getCurrentServer         = getCurrentServer;
            handler.keepCurrentServer        = keepCurrentServer;
            handler.connection               = new ProxySocketTunLocal(_connection);
            handler.connectionUDP            = _connectionUDP;
            handler.cfg.reconnectTimesRemain = _config.reconnectTimes;
            handler.cfg.random               = _config.random;
            handler.cfg.forceRandom          = _config.random;
            handler.setServerTransferTotal(_transfer);
            if (_config.proxyEnable)
            {
                handler.cfg.proxyType            = _config.proxyType;
                handler.cfg.socks5RemoteHost     = _config.proxyHost;
                handler.cfg.socks5RemotePort     = _config.proxyPort;
                handler.cfg.socks5RemoteUsername = _config.proxyAuthUser;
                handler.cfg.socks5RemotePassword = _config.proxyAuthPass;
                handler.cfg.proxyUserAgent       = _config.proxyUserAgent;
            }
            handler.cfg.TTL             = _config.TTL;
            handler.cfg.connect_timeout = _config.connect_timeout;
            handler.cfg.autoSwitchOff   = _config.autoBan;
            if (!string.IsNullOrEmpty(_config.dns_server))
            {
                handler.cfg.dns_servers = _config.dns_server;
            }
            if (_config.GetPortMapCache().ContainsKey(local_port))
            {
                PortMapConfigCache cfg = _config.GetPortMapCache()[local_port];
                if (cfg.server == null || cfg.id == cfg.server.id)
                {
                    if (cfg.server != null)
                    {
                        handler.select_server = delegate(Server server, Server selServer) { return(server.id == cfg.server.id); };
                    }
                    else if (!string.IsNullOrEmpty(cfg.id))
                    {
                        handler.select_server = delegate(Server server, Server selServer) { return(server.group == cfg.id); };
                    }
                    if (cfg.type == PortMapType.Forward) // tunnel
                    {
                        byte[] addr           = System.Text.Encoding.UTF8.GetBytes(cfg.server_addr);
                        byte[] newFirstPacket = new byte[_firstPacketLength + addr.Length + 4];
                        newFirstPacket[0] = 3;
                        newFirstPacket[1] = (byte)addr.Length;
                        Array.Copy(addr, 0, newFirstPacket, 2, addr.Length);
                        newFirstPacket[addr.Length + 2] = (byte)(cfg.server_port / 256);
                        newFirstPacket[addr.Length + 3] = (byte)(cfg.server_port % 256);
                        Array.Copy(_firstPacket, 0, newFirstPacket, addr.Length + 4, _firstPacketLength);
                        _remoteHeaderSendBuffer = newFirstPacket;
                        handler.Start(_remoteHeaderSendBuffer, _remoteHeaderSendBuffer.Length, null);
                    }
                    else if (_connectionUDP == null && cfg.type == PortMapType.RuleProxy &&
                             (new Socks5Forwarder(_config, _IPRange)).Handle(_remoteHeaderSendBuffer, _remoteHeaderSendBuffer.Length, _connection, local_sendback_protocol))
                    {
                    }
                    else
                    {
                        handler.Start(_remoteHeaderSendBuffer, _remoteHeaderSendBuffer.Length, "socks5");
                    }
                    return;
                }
            }
            else
            {
                if (_connectionUDP == null && new Socks5Forwarder(_config, _IPRange).Handle(_remoteHeaderSendBuffer, _remoteHeaderSendBuffer.Length, _connection, local_sendback_protocol))
                {
                }
                else
                {
                    handler.Start(_remoteHeaderSendBuffer, _remoteHeaderSendBuffer.Length, local_sendback_protocol);
                }
                return;
            }
            Close();
        }
Exemplo n.º 10
0
        public bool Handle(byte[] firstPacket, int length, Socket socket, object state)
        {
            if (socket.ProtocolType != ProtocolType.Tcp)
            {
                return false;
            }
            /*
             建立与 SOCKS5 服务器的TCP连接后,客户端需要先发送请求来协商版本及认证方式。
                   +----+----------+----------+
                   |VER | NMETHODS | METHODS  |
                   +----+----------+----------+
                   | 1  |    1     | 1 to 255 |
                   +----+----------+----------+
             VER 是 SOCKS 版本,这里应该是 0x05;
             NMETHODS 是 METHODS 部分的长度;
             METHODS 是客户端支持的认证方式列表,每个方法占1字节。当前的定义是:
               0x00 不需要认证
               0x01 GSSAPI
               0x02 用户名、密码认证
               0x03 - 0x7F 由IANA分配(保留)
               0x80 - 0xFE 为私人方法保留
               0xFF 无可接受的方法
            */
            if (length < 2 || firstPacket[0] != 5)
            {
                return false;
            }
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

            // 此处没有对Handler设置构造器, 分别对connection,controller,relay赋值, 可读性不如UDPRelay的处理
            // :-1:
            // 看了下python版本的代码,其对TcpRelayHandler也用了构造器,为什么这里没有?
            // 作者:怪我咯?
            Handler handler = new Handler();
            handler.connection = socket;
            handler.controller = _controller;
            handler.relay = this;

            handler.Start(firstPacket, length);
            IList<Handler> handlersToClose = new List<Handler>(); // 用于缓存长时间不活动的tcp处理对象,并将其清理
            lock (this.Handlers)
            {
                this.Handlers.Add(handler);
                Logging.Debug($"connections: {Handlers.Count}");
                DateTime now = DateTime.Now;
                // 每超过1秒清理一下长时间不活动的tcp连接
                if (now - _lastSweepTime > TimeSpan.FromSeconds(1))
                {
                    _lastSweepTime = now;
                    foreach (Handler handler1 in this.Handlers)
                    {
                        if (now - handler1.lastActivity > TimeSpan.FromSeconds(900))
                        {
                            handlersToClose.Add(handler1);
                        }
                    }
                }
            }
            foreach (Handler handler1 in handlersToClose)
            {
                Logging.Debug("Closing timed out connection");
                handler1.Close();
            }
            return true;
        }