private void CompareServerVersion()
        {
            IsServerVersionNewer = false;

            // no server version (SHOULD NEVER OCCUR)
            if (ServerVersion == null)
            {
                IsServerVersionNewer = false;
                return;
            }

            // no server version (SHOULD NEVER OCCUR)
            if (ClientVersion == null)
            {
                IsServerVersionNewer = true;
                return;
            }

            // split versions parts
            string[] verServer = ServerVersion.Split('.');
            string[] verClient = ClientVersion.Split('.');

            // compare first part
            int f1 = Compare(verServer[0], verClient[0]);

            if (f1 > 0)
            {
                IsServerVersionNewer = true;
                return;
            }
            else if (f1 < 0)
            {
                IsServerVersionNewer = false;
                return;
            }

            // compare second part
            int f2 = Compare(verServer[1], verClient[1]);

            if (f2 > 0)
            {
                IsServerVersionNewer = true;
                return;
            }
        }
        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)
                    {
                        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;
            }
        }
Beispiel #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;
            }
        }