public override async ValueTask Handle(P00ConnectionHandshake packet)
        {
            ProtocolOptions config   = options.Value;
            var             response = Packets.New <P01ConnectionResponse>();

            ProtocolOptions.Platform platform = config.Platforms.SingleOrDefault(p => p.Name == packet.ApplicationIdentifier);
            if (platform == null)
            {
                throw new ProtocolException($"Unsupported client {packet.ApplicationIdentifier}");
            }
            response.LatestVersion     = platform.VersionName;
            response.LatestVersionCode = platform.VersionCode;
            if (packet.ProtocolVersion != config.ProtocolVersion || packet.VersionCode < platform.ForceUpdateThreshold)
            {
                response.ConnectionState = ConnectionState.MustUpgrade;
            }
            else if (packet.VersionCode < platform.RecommendUpdateThreshold)
            {
                response.ConnectionState = ConnectionState.CanUpgrade;
            }
            else
            {
                response.ConnectionState = ConnectionState.Valid;
            }

            Client.Initialize(packet.ApplicationIdentifier, packet.VersionCode);

            await Client.Send(response).ConfigureAwait(false);
        }
        private Connection CreateConnection(ProtocolOptions protocolOptions = null, SocketOptions socketOptions = null, PoolingOptions poolingOptions = null)
        {
            if (socketOptions == null)
            {
                socketOptions = new SocketOptions();
            }
            if (protocolOptions == null)
            {
                protocolOptions = new ProtocolOptions();
            }
            var config = new Configuration(
                new Cassandra.Policies(),
                protocolOptions,
                poolingOptions,
                socketOptions,
                new ClientOptions(false, 20000, null),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator(),
                new StartupOptionsFactory(),
                new SessionFactoryBuilder(),
                new Dictionary <string, IExecutionProfile>(),
                new RequestOptionsMapper(),
                null,
                null);

            return(CreateConnection(GetProtocolVersion(), config));
        }
        public void Get_NotFound(GetOperation operation)
        {
            // Arrange
            var         options  = new ProtocolOptions();
            var         protocol = new DefaultProtocol(m_mockFactory.Object, options);
            var         datakey  = new DataKey <int>("Key1");
            var         key      = new byte[] { };
            ValuePacket packet   = null;

            m_mockEncoder.Setup(encoder => encoder.GetBytes("Key1")).Returns(key);
            m_mockCommandWriter.Setup(writer => writer.Get(operation, key));
            m_mockFactory.Setup(factory => factory.Context(key))
            .Returns <byte[]>(state => (Action2 <IClientConnection, object> action) =>
            {
                action(m_mockClientConnection.Object, state);
                return(true);
            });
            m_mockClientConnection.SetupGet(connection => connection.Writer).Returns(m_mockBinaryWriter.Object);
            m_mockPacketBuilder.Setup(builder => builder.WriteTo(m_mockBinaryWriter.Object)).Returns(0);
            m_mockClientConnection.SetupGet(connection => connection.Reader).Returns(m_mockBinaryReader.Object);
            m_mockFactory.Setup(factory => factory.CreatePacketParser(m_mockBinaryReader.Object, It.IsAny <Buffer <byte> >())).Returns(m_mockPacketParser.Object);
            m_mockFactory.Setup(factory => factory.CreateCommandReader(m_mockPacketParser.Object)).Returns(m_mockCommandReader.Object);
            m_mockCommandReader.Setup(reader => reader.ReadValue(operation == GetOperation.Gets)).Returns(packet);

            // Act
            var result = protocol.Get(operation, datakey);

            // Assert
            Assert.True(result);
            Assert.False(datakey.HasValue);
        }
        private IEndPointResolver Create()
        {
            var protocolOptions = new ProtocolOptions(
                EndPointResolverTests.Port, new SSLOptions().SetHostNameResolver(addr => addr.ToString()));

            return(new EndPointResolver(new ServerNameResolver(protocolOptions)));
        }
Exemple #5
0
        public Uri GetAbsoluteUri(
            Uri uriFromCaller,
            ProtocolOptions protocol)
        {
            // you can turn off SSL when testing
            if (ProtocolOptions.Https == protocol &&
                !SslIsEnabledInConfig())
            {
                protocol = ProtocolOptions.Http;
            }

            // deal with ~ (ASP.NET "AppRelative" paths)
            if (!uriFromCaller.IsAbsoluteUri)
            {
                uriFromCaller = Application
                                .ResolvePossibleAppRelativeUri(uriFromCaller);
            }

            if (uriFromCaller.IsAbsoluteUri)
            {
                UriBuilder builder = new UriBuilder(
                    SchemeFor(protocol), uriFromCaller.Host);
                PreservePortIfPossible(builder, uriFromCaller);
                builder.Path = uriFromCaller.GetComponents(
                    UriComponents.Path, UriFormat.Unescaped);

                // UriBuilder.Query unescapes escaped query strings,
                // which hoses me for stuff like ReturnUrl
                // so I'm doing that part manually
                //   builder.Query = uriFromCaller.GetComponents(
                //	 UriComponents.Query, UriFormat.UriEscaped);

                string query = uriFromCaller.GetComponents(
                    UriComponents.Query, UriFormat.UriEscaped);
                if (query.Length > 0)
                {
                    string uriWithoutQuery = builder.Uri.AbsoluteUri;
                    string absoluteUri     = string.Format("{0}?{1}",
                                                           uriWithoutQuery, query);
                    return(new Uri(absoluteUri, UriKind.Absolute));
                }
                else
                {
                    return(builder.Uri);
                }
            }
            else               // relative URI
            {
                Uri currentRequestUri = Application.CurrentRequestUri;

                UriBuilder builder = new UriBuilder(
                    SchemeFor(protocol), currentRequestUri.Host);
                PreservePortIfPossible(builder, currentRequestUri);
                builder.Path = currentRequestUri.GetComponents(
                    UriComponents.Path, UriFormat.Unescaped);
                return(new Uri(builder.Uri, uriFromCaller));
            }
        }
        public void GetMany(GetOperation operation)
        {
            // Arrange
            var options  = new ProtocolOptions();
            var protocol = new DefaultProtocol(m_mockFactory.Object, options);
            var datakey1 = new DataKey <int>("Key1");
            var datakey2 = new DataKey <bool>("Key2");
            var key1     = new byte[] { 1 };
            var key2     = new byte[] { 2 };

            byte[][] keys   = null;
            var      packet = new ValuePacket()
            {
                Flags   = 101,
                Key     = key1,
                Value   = new ArraySegment <byte>(new byte[] { }),
                Version = 245
            };

            m_mockEncoder.Setup(encoder => encoder.GetBytes("Key1")).Returns(key1);
            m_mockEncoder.Setup(encoder => encoder.GetBytes("Key2")).Returns(key2);
            m_mockFactory.Setup(factory => factory.Context(It.IsAny <byte[][]>()))
            .Returns <byte[][]>(state => (Action2 <IClientConnection, object> action) =>
            {
                keys = (byte[][])state;
                action(m_mockClientConnection.Object, state);
                return(true);
            });
            m_mockCommandWriter.Setup(writer => writer.GetMany(operation, It.IsAny <byte[][]>()));
            m_mockClientConnection.SetupGet(connection => connection.Writer).Returns(m_mockBinaryWriter.Object);
            m_mockPacketBuilder.Setup(builder => builder.WriteTo(m_mockBinaryWriter.Object)).Returns(0);
            m_mockClientConnection.SetupGet(connection => connection.Reader).Returns(m_mockBinaryReader.Object);
            m_mockFactory.Setup(factory => factory.CreatePacketParser(m_mockBinaryReader.Object, It.IsAny <Buffer <byte> >())).Returns(m_mockPacketParser.Object);
            m_mockFactory.Setup(factory => factory.CreateCommandReader(m_mockPacketParser.Object)).Returns(m_mockCommandReader.Object);
            m_mockCommandReader.Setup(reader => reader.ReadValue(operation == GetOperation.Gets)).Returns(() =>
            {
                var p = packet;
                if (packet != null)
                {
                    packet = null;
                }

                return(p);
            });
            m_mockObjectFormatter.Setup(formatter => formatter.Deserialize <int>(packet.Value, packet.Flags)).Returns(507);

            // Act
            var result = protocol.GetMany(operation, new DataKey[] { datakey1, datakey2 });

            // Assert
            Assert.True(result);
            Assert.True(datakey1.HasValue);
            Assert.Equal(245, datakey1.Version);
            Assert.Equal(507, datakey1.Value);
            Assert.False(datakey2.HasValue);
        }
Exemple #7
0
        private static ProtocolOptions SwitchPropertiesIfNotTheSameType(ProtocolOptions currentOptions, IConnectionPlugin plugin)
        {
            // prevent to reset properties
            if (currentOptions == null || currentOptions.GetType() != plugin.GetOptionsType())
            {
                return(plugin.CreateOptions());
            }

            return(currentOptions);
        }
        public void Store(StoreOperation operation, string optionsString, bool connectSucceed, bool storeSucceed)
        {
            // Arrange
            var options  = new ProtocolOptions(optionsString);
            var protocol = new DefaultProtocol(m_mockFactory.Object, options);
            var datakey  = new DataKey <int>("Key1")
            {
                Value   = 12345,
                Version = 556
            };
            int         flags  = 10101;
            var         key    = new byte[] { };
            var         value  = new ArraySegment <byte>(new byte[] { });
            StorePacket packet = null;

            m_mockObjectFormatter.Setup(formatter => formatter.Serialize <int>(12345, out flags)).Returns(value);
            m_mockEncoder.Setup(encoder => encoder.GetBytes("Key1")).Returns(key);
            m_mockCommandWriter.Setup(writer => writer.Store(It.IsAny <StorePacket>(), options.NoReply))
            .Callback <StorePacket, bool>((p, nr) => packet = p);
            m_mockFactory.Setup(factory => factory.Context(key))
            .Returns <byte[]>(state => (Action2 <IClientConnection, object> action) =>
            {
                if (connectSucceed)
                {
                    action(m_mockClientConnection.Object, state);
                }

                return(connectSucceed);
            });
            if (connectSucceed)
            {
                m_mockClientConnection.SetupGet(connection => connection.Writer).Returns(m_mockBinaryWriter.Object);
                m_mockPacketBuilder.Setup(builder => builder.WriteTo(m_mockBinaryWriter.Object)).Returns(0);
                if (!options.NoReply)
                {
                    m_mockClientConnection.SetupGet(connection => connection.Reader).Returns(m_mockBinaryReader.Object);
                    m_mockFactory.Setup(factory => factory.CreatePacketParser(m_mockBinaryReader.Object, It.IsAny <Buffer <byte> >())).Returns(m_mockPacketParser.Object);
                    m_mockFactory.Setup(factory => factory.CreateCommandReader(m_mockPacketParser.Object)).Returns(m_mockCommandReader.Object);
                    m_mockCommandReader.Setup(reader => reader.ReadStored()).Returns(storeSucceed);
                }
            }

            // Act
            var result = protocol.Store(operation, datakey, 100);

            // Assert
            Assert.Equal(connectSucceed && (options.NoReply || storeSucceed), result);
            Assert.NotNull(packet);
            Assert.Equal(100, packet.Expires);
            Assert.Equal(flags, packet.Flags);
            Assert.Equal(key, packet.Key);
            Assert.Equal(operation, packet.Operation);
            Assert.Equal(value, packet.Value);
            Assert.Equal(556, packet.Version);
        }
 public HostnameContactPoint(
     IDnsResolver dnsResolver,
     ProtocolOptions protocolOptions,
     IServerNameResolver serverNameResolver,
     bool keepContactPointsUnresolved,
     string hostname)
 {
     _dns                         = dnsResolver ?? throw new ArgumentNullException(nameof(dnsResolver));
     _protocolOptions             = protocolOptions ?? throw new ArgumentNullException(nameof(protocolOptions));
     _serverNameResolver          = serverNameResolver ?? throw new ArgumentNullException(nameof(serverNameResolver));
     _keepContactPointsUnresolved = keepContactPointsUnresolved;
     _hostname                    = hostname ?? throw new ArgumentNullException(nameof(hostname));
 }
 internal Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
 }
Exemple #11
0
        protected override void SaveTo(ProtocolOptions protocolOptions)
        {
            var sshOptions = protocolOptions as SshOptions;

            base.SaveTo(sshOptions);

            if (null != sshOptions)
            {
                sshOptions.X11Forwarding              = this.checkBoxX11Forwarding.Checked;
                sshOptions.EnableCompression          = this.checkBoxCompression.Checked;
                sshOptions.EnablePagentForwarding     = this.checkBoxEnablePagentForwarding.Checked;
                sshOptions.EnablePagentAuthentication = this.checkBoxEnablePagentAuthentication.Checked;
                sshOptions.SshVersion = (SshVersion)Enum.Parse(typeof(SshVersion), cmbSshVersion.SelectedValue.ToString());
            }
        }
 public Configuration(Policies policies,
                      ProtocolOptions protocolOptions,
                      PoolingOptions poolingOptions,
                      SocketOptions socketOptions,
                      ClientOptions clientOptions,
                      IAuthInfoProvider authProvider,
                      bool metricsEnabled)
 {
     this._policies = policies;
     this._protocolOptions = protocolOptions;
     this._poolingOptions = poolingOptions;
     this._socketOptions = socketOptions;
     this._clientOptions = clientOptions;
     this._authProvider = authProvider;
     this._metricsEnabled = metricsEnabled;
 }
Exemple #13
0
        public IReadOnlyDictionary <string, string> CreateStartupOptions(ProtocolOptions options)
        {
            var startupOptions = new Dictionary <string, string>
            {
                { StartupOptionsFactory.CqlVersionOption, StartupOptionsFactory.CqlVersion }
            };

            string compressionName = null;

            switch (options.Compression)
            {
            case CompressionType.LZ4:
                compressionName = StartupOptionsFactory.Lz4Compression;
                break;

            case CompressionType.Snappy:
                compressionName = StartupOptionsFactory.SnappyCompression;
                break;
            }

            if (compressionName != null)
            {
                startupOptions.Add(StartupOptionsFactory.CompressionOption, compressionName);
            }

            if (options.NoCompact)
            {
                startupOptions.Add(StartupOptionsFactory.NoCompactOption, "true");
            }

            startupOptions.Add(StartupOptionsFactory.DriverNameOption, AssemblyHelpers.GetAssemblyTitle(typeof(StartupOptionsFactory)));
            startupOptions.Add(
                StartupOptionsFactory.DriverVersionOption, AssemblyHelpers.GetAssemblyInformationalVersion(typeof(StartupOptionsFactory)));

            if (_appName != null)
            {
                startupOptions[StartupOptionsFactory.ApplicationNameOption] = _appName;
            }

            if (_appVersion != null)
            {
                startupOptions[StartupOptionsFactory.ApplicationVersionOption] = _appVersion;
            }

            startupOptions[StartupOptionsFactory.ClientIdOption] = _clusterId.ToString();
            return(startupOptions);
        }
Exemple #14
0
        private void CreateSession(VirtualSocket socket)
        {
            try
            {
                Console.WriteLine("New connection");

                var             options = new ProtocolOptions();
                ProtocolSession session = new ProtocolSession(socket, options);
                session.OnStreamOpened += session_OnStreamOpened;
                session.OnError        += session_OnError;
                session.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 internal Configuration(Policies policies,
                        ProtocolOptions protocolOptions,
                        PoolingOptions poolingOptions,
                        SocketOptions socketOptions,
                        ClientOptions clientOptions,
                        IAuthProvider authProvider,
                        IAuthInfoProvider authInfoProvider,
                        QueryOptions queryOptions)
 {
     _policies = policies;
     _protocolOptions = protocolOptions;
     _poolingOptions = poolingOptions;
     _socketOptions = socketOptions;
     _clientOptions = clientOptions;
     _authProvider = authProvider;
     _authInfoProvider = authInfoProvider;
     _queryOptions = queryOptions;
 }
        /// <summary>
        /// Processes the specified headers.
        /// </summary>
        /// <param name="headers">The headers.</param>
        /// <param name="type">The type.</param>
        /// <param name="options">Options.</param>
        /// <param name="flags">Flags.</param>
        public void Process(ref byte[] headers, DirectionProcessType type, ProtocolOptions options, int flags)
        {
            if (!options.UseCompression)
            {
                return;
            }

            byte[] result = null;

            if (type == DirectionProcessType.Inbound)
            {
                Decompress(headers, out result);
            }
            else
            {
                Compress(headers, out result);
            }

            headers = result;
        }
 private static string SchemeFor(ProtocolOptions protocol)
 {
     return ProtocolOptions.Https == protocol ?
         Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 }
        public Uri GetAbsoluteUri(Uri uriFromCaller, ProtocolOptions protocol)
        {


            // you can turn off SSL when testing
            if (ProtocolOptions.Https == protocol && !SslIsEnabledInConfig())
                protocol = ProtocolOptions.Http;

            // deal with ~ (ASP.NET "AppRelative" paths)
            if (!uriFromCaller.IsAbsoluteUri)
                uriFromCaller = Application.ResolvePossibleAppRelativeUri(uriFromCaller);

            if (uriFromCaller.IsAbsoluteUri)
            {
                UriBuilder builder = new UriBuilder(SchemeFor(protocol), uriFromCaller.Host);
                PreservePortIfPossible(builder, uriFromCaller);
                builder.Path = uriFromCaller.GetComponents(UriComponents.Path, UriFormat.Unescaped);

                // UriBuilder.Query unescapes escaped query strings,
                // which hoses me for stuff like ReturnUrl
                // so I'm doing that part manually
                //   builder.Query = uriFromCaller.GetComponents(
                //     UriComponents.Query, UriFormat.UriEscaped);

                string query = uriFromCaller.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
                if (query.Length > 0)
                {
                    string uriWithoutQuery = builder.Uri.AbsoluteUri;

                    string absoluteUri = string.Format("{0}?{1}", uriWithoutQuery, query);

                    return new Uri(absoluteUri, UriKind.Absolute);
                }
                else return builder.Uri;
            }
            else
            { // relative URI
                Uri currentRequestUri = Application.CurrentRequestUri;

                UriBuilder builder = new UriBuilder(SchemeFor(protocol), currentRequestUri.Host);
                PreservePortIfPossible(builder, currentRequestUri);

                builder.Path = currentRequestUri.GetComponents(
                    UriComponents.Path, UriFormat.Unescaped);
                return new Uri(builder.Uri, uriFromCaller);
            }
        }
Exemple #19
0
 /// <summary>
 /// Establishes a connection (using a specific resource manager context) between the calling application and a smart card contained by a specific reader. If no card exists in the specified reader, an error is returned.
 /// </summary>
 /// <param name="readerName">The name of the reader that contains the target card.</param>
 /// <param name="shareMode">A flag that indicates whether other applications may form connections to the card.</param>
 /// <param name="preferredProtocols">A bitmask of acceptable protocols for the connection. Possible values may be combined with the OR operation.</param>
 public void Connect(string readerName, ShareModeOptions shareMode, ProtocolOptions preferredProtocols)
 {
     if (_hContext == IntPtr.Zero)
         throw new SCardException("No card reader context established.  Must call SCard.EstablishContext() first.");
     if (_hCard != IntPtr.Zero)
         throw new SCardException("Already connected to card.  Must call SCard.Disconnect() first.");
     IntPtr hCard = IntPtr.Zero;
     int rtn = SCardDll.SCardConnectA(_hContext, readerName, (UInt32)shareMode, (UInt32)preferredProtocols, ref hCard, ref _protocol);
     EvalReturnCode(rtn);
     _hCard = hCard;
 }