private void Connect()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
Пример #2
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout <= 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    DeactivatedAt = DateTime.UtcNow;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
                        var ctor = typeof(SslStream).GetConstructors()
                                   .First(x => x.GetParameters().Length == 5);

                        var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
                    }

                    sslStream.AuthenticateAsClient(Host);

                    if (!sslStream.IsEncrypted)
                    {
                        throw new Exception("Could not establish an encrypted connection to " + Host);
                    }

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (!string.IsNullOrEmpty(Password))
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                if (Client != null)
                {
                    SendExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0);
                        if (ServerVersionNumber <= 0)
                        {
                            var parts   = ServerVersion.Split('.');
                            var version = int.Parse(parts[0]) * 1000;
                            if (parts.Length > 1)
                            {
                                version += int.Parse(parts[1]) * 100;
                            }
                            if (parts.Length > 2)
                            {
                                version += int.Parse(parts[2]);
                            }

                            ServerVersionNumber = version;
                        }
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException)
            {
                log.Error(ErrorConnect.Fmt(Host, Port));
                throw;
            }
        }
Пример #3
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts   = ServerVersion.Split('.');
                        var version = int.Parse(parts[0]) * 1000;
                        if (parts.Length > 1)
                        {
                            version += int.Parse(parts[1]) * 100;
                        }
                        if (parts.Length > 2)
                        {
                            version += int.Parse(parts[2]);
                        }

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }