Ejemplo n.º 1
0
        // methods
        /// <inheritdoc/>
        public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");
            Ensure.IsNotNull(description, "description");

            try
            {
                var command = new BsonDocument
                {
                    { "authenticate", 1 },
                    { "mechanism", Name },
                    { "user", _username }
                };
                var protocol = new CommandWireProtocol <BsonDocument>(
                    new DatabaseNamespace("$external"),
                    command,
                    true,
                    BsonDocumentSerializer.Instance,
                    null);
                await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoCommandException ex)
            {
                var message = string.Format("Unable to authenticate username '{0}' using protocol '{1}'.", _username, Name);
                throw new MongoAuthenticationException(connection.ConnectionId, message, ex);
            }
        }
 private async Task<string> GetNonceAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
 {
     var command = new BsonDocument("getnonce", 1);
     var protocol = new CommandWireProtocol(new DatabaseNamespace(_credential.Source), command, true, null);
     var document = await protocol.ExecuteAsync(connection, timeout, cancellationToken);
     return (string)document["nonce"];
 }
        // methods
        /// <inheritdoc/>
        public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));
            Ensure.IsNotNull(description, nameof(description));

            try
            {
                var command = new BsonDocument
                {
                    { "authenticate", 1 },
                    { "mechanism", Name },
                    { "user", _username }
                };
                var protocol = new CommandWireProtocol<BsonDocument>(
                    new DatabaseNamespace("$external"),
                    command,
                    true,
                    BsonDocumentSerializer.Instance,
                    null);
                await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
            }
            catch (MongoCommandException ex)
            {
                var message = string.Format("Unable to authenticate username '{0}' using protocol '{1}'.", _username, Name);
                throw new MongoAuthenticationException(connection.ConnectionId, message, ex);
            }
        }
        private async Task <string> GetNonceAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
        {
            var command  = new BsonDocument("getnonce", 1);
            var protocol = new CommandWireProtocol(new DatabaseNamespace(_credential.Source), command, true, null);
            var document = await protocol.ExecuteAsync(connection, timeout, cancellationToken);

            return((string)document["nonce"]);
        }
        // methods
        /// <inheritdoc/>
        public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");
            Ensure.IsNotNull(description, "description");

            using (var conversation = new SaslConversation(description.ConnectionId))
            {
                var currentStep = _mechanism.Initialize(connection, description);

                var command = new BsonDocument
                {
                    { "saslStart", 1 },
                    { "mechanism", _mechanism.Name },
                    { "payload", currentStep.BytesToSendToServer }
                };

                while (true)
                {
                    BsonDocument result;
                    try
                    {
                        var protocol = new CommandWireProtocol<BsonDocument>(
                            new DatabaseNamespace(DatabaseName),
                            command,
                            true,
                            BsonDocumentSerializer.Instance,
                            null);
                        result = await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
                    }
                    catch(MongoCommandException ex)
                    {
                        var message = string.Format("Unable to authenticate using sasl protocol mechanism {0}.", Name);
                        throw new MongoAuthenticationException(connection.ConnectionId, message, ex);
                    }

                    // we might be done here if the client is not expecting a reply from the server
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    currentStep = currentStep.Transition(conversation, result["payload"].AsByteArray);

                    // we might be done here if the client had some final verification it needed to do
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    command = new BsonDocument
                    {
                        { "saslContinue", 1 },
                        { "conversationId", result["conversationId"].AsInt32 },
                        { "payload", currentStep.BytesToSendToServer }
                    };
                }
            }
        }
Ejemplo n.º 6
0
        // methods
        /// <inheritdoc/>
        public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");
            Ensure.IsNotNull(description, "description");

            using (var conversation = new SaslConversation(description.ConnectionId))
            {
                var currentStep = _mechanism.Initialize(connection, description);

                var command = new BsonDocument
                {
                    { "saslStart", 1 },
                    { "mechanism", _mechanism.Name },
                    { "payload", currentStep.BytesToSendToServer }
                };

                while (true)
                {
                    BsonDocument result;
                    try
                    {
                        var protocol = new CommandWireProtocol <BsonDocument>(
                            new DatabaseNamespace(DatabaseName),
                            command,
                            true,
                            BsonDocumentSerializer.Instance,
                            null);
                        result = await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
                    }
                    catch (MongoCommandException ex)
                    {
                        var message = string.Format("Unable to authenticate using sasl protocol mechanism {0}.", Name);
                        throw new MongoAuthenticationException(connection.ConnectionId, message, ex);
                    }

                    // we might be done here if the client is not expecting a reply from the server
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    currentStep = currentStep.Transition(conversation, result["payload"].AsByteArray);

                    // we might be done here if the client had some final verification it needed to do
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    command = new BsonDocument
                    {
                        { "saslContinue", 1 },
                        { "conversationId", result["conversationId"].AsInt32 },
                        { "payload", currentStep.BytesToSendToServer }
                    };
                }
            }
        }
Ejemplo n.º 7
0
        private async Task <HeartbeatInfo> GetHeartbeatInfoAsync(IConnection connection, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (_heartbeatStartedEventHandler != null)
            {
                _heartbeatStartedEventHandler(new ServerHeartbeatStartedEvent(connection.ConnectionId));
            }

            try
            {
                var isMasterCommand = new CommandWireProtocol <BsonDocument>(
                    DatabaseNamespace.Admin,
                    new BsonDocument("isMaster", 1),
                    true,
                    BsonDocumentSerializer.Instance,
                    null);

                var stopwatch = Stopwatch.StartNew();
                var isMasterResultDocument = await isMasterCommand.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);

                stopwatch.Stop();
                var isMasterResult = new IsMasterResult(isMasterResultDocument);

                var buildInfoCommand = new CommandWireProtocol <BsonDocument>(
                    DatabaseNamespace.Admin,
                    new BsonDocument("buildInfo", 1),
                    true,
                    BsonDocumentSerializer.Instance,
                    null);

                var buildInfoResultRocument = await buildInfoCommand.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);

                var buildInfoResult = new BuildInfoResult(buildInfoResultRocument);

                if (_heartbeatSucceededEventHandler != null)
                {
                    _heartbeatSucceededEventHandler(new ServerHeartbeatSucceededEvent(connection.ConnectionId, stopwatch.Elapsed));
                }

                return(new HeartbeatInfo
                {
                    RoundTripTime = stopwatch.Elapsed,
                    IsMasterResult = isMasterResult,
                    BuildInfoResult = buildInfoResult
                });
            }
            catch (Exception ex)
            {
                if (_heartbeatFailedEventHandler != null)
                {
                    _heartbeatFailedEventHandler(new ServerHeartbeatFailedEvent(connection.ConnectionId, ex));
                }
                throw;
            }
        }
        private async Task <HeartbeatInfo> GetHeartbeatInfoAsync(IConnection connection, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (_listener != null)
            {
                _listener.ServerBeforeHeartbeating(connection.ConnectionId);
            }

            try
            {
                var slidingTimeout = new SlidingTimeout(_settings.HeartbeatTimeout);

                var isMasterCommand = new CommandWireProtocol(
                    DatabaseNamespace.Admin,
                    new BsonDocument("isMaster", 1),
                    true,
                    null);

                var stopwatch = Stopwatch.StartNew();
                var isMasterResultDocument = await isMasterCommand.ExecuteAsync(connection, slidingTimeout, cancellationToken);

                stopwatch.Stop();
                var isMasterResult = new IsMasterResult(isMasterResultDocument);

                var buildInfoCommand = new CommandWireProtocol(
                    DatabaseNamespace.Admin,
                    new BsonDocument("buildInfo", 1),
                    true,
                    null);

                var buildInfoResultRocument = await buildInfoCommand.ExecuteAsync(connection, slidingTimeout, cancellationToken);

                var buildInfoResult = new BuildInfoResult(buildInfoResultRocument);

                if (_listener != null)
                {
                    _listener.ServerAfterHeartbeating(connection.ConnectionId, stopwatch.Elapsed);
                }

                return(new HeartbeatInfo
                {
                    RoundTripTime = stopwatch.Elapsed,
                    IsMasterResult = isMasterResult,
                    BuildInfoResult = buildInfoResult
                });
            }
            catch (Exception ex)
            {
                if (_listener != null)
                {
                    _listener.ServerErrorHeartbeating(connection.ConnectionId, ex);
                }
                throw;
            }
        }
 private async Task AuthenticateAsync(IConnection connection, string nonce, TimeSpan timeout, CancellationToken cancellationToken)
 {
     var command = new BsonDocument
     {
         { "authenticate", 1 },
         { "user", _credential.Username },
         { "nonce", nonce },
         { "key", CreateKey(_credential.Username, _credential.Password, nonce) }
     };
     var protocol = new CommandWireProtocol(new DatabaseNamespace(_credential.Source), command, true, null);
     await protocol.ExecuteAsync(connection, timeout, cancellationToken);
 }
Ejemplo n.º 10
0
 private async Task AuthenticateAsync(IConnection connection, string nonce, TimeSpan timeout, CancellationToken cancellationToken)
 {
     var command = new BsonDocument
     {
         { "authenticate", 1 },
         { "user", _credential.Username },
         { "nonce", nonce },
         { "key", AuthenticationHelper.HexMD5(_credential.Username, _credential.Password, nonce) }
     };
     var protocol = new CommandWireProtocol(_credential.Source, command, true);
     await protocol.ExecuteAsync(connection, timeout, cancellationToken);
 }
 private async Task AuthenticateAsync(IConnection connection, string nonce, TimeSpan timeout, CancellationToken cancellationToken)
 {
     var command = new BsonDocument
     {
         { "authenticate", 1 },
         { "user", _credential.Username },
         { "nonce", nonce },
         { "key", AuthenticationHelper.HexMD5(_credential.Username, _credential.Password, nonce) }
     };
     var protocol = new CommandWireProtocol(new DatabaseNamespace(_credential.Source), command, true, null);
     await protocol.ExecuteAsync(connection, timeout, cancellationToken);
 }
        public async Task<ConnectionDescription> InitializeConnectionAsync(IConnection connection, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));

            var isMasterCommand = new BsonDocument("isMaster", 1);
            var isMasterProtocol = new CommandWireProtocol<BsonDocument>(
                DatabaseNamespace.Admin,
                isMasterCommand,
                true,
                BsonDocumentSerializer.Instance,
                null);
            var isMasterResult = new IsMasterResult(await isMasterProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false));

            var buildInfoCommand = new BsonDocument("buildInfo", 1);
            var buildInfoProtocol = new CommandWireProtocol<BsonDocument>(
                DatabaseNamespace.Admin,
                buildInfoCommand,
                true,
                BsonDocumentSerializer.Instance,
               null);
            var buildInfoResult = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false));

            var connectionId = connection.ConnectionId;
            var description = new ConnectionDescription(connectionId, isMasterResult, buildInfoResult);

            await AuthenticationHelper.AuthenticateAsync(connection, description, cancellationToken).ConfigureAwait(false);

            try
            {
                var getLastErrorCommand = new BsonDocument("getLastError", 1);
                var getLastErrorProtocol = new CommandWireProtocol<BsonDocument>(
                    DatabaseNamespace.Admin,
                    getLastErrorCommand,
                    true,
                    BsonDocumentSerializer.Instance,
                    null);
                var getLastErrorResult = await getLastErrorProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);

                BsonValue connectionIdBsonValue;
                if (getLastErrorResult.TryGetValue("connectionId", out connectionIdBsonValue))
                {
                    connectionId = connectionId.WithServerValue(connectionIdBsonValue.ToInt32());
                    description = description.WithConnectionId(connectionId);
                }
            }
            catch
            {
                // if we couldn't get the server's connection id, so be it.
            }

            return description;
        }
Ejemplo n.º 13
0
        public async Task <ConnectionDescription> InitializeConnectionAsync(IConnection connection, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, nameof(connection));

            var isMasterCommand  = new BsonDocument("isMaster", 1);
            var isMasterProtocol = new CommandWireProtocol <BsonDocument>(
                DatabaseNamespace.Admin,
                isMasterCommand,
                true,
                BsonDocumentSerializer.Instance,
                null);
            var isMasterResult = new IsMasterResult(await isMasterProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false));

            var buildInfoCommand  = new BsonDocument("buildInfo", 1);
            var buildInfoProtocol = new CommandWireProtocol <BsonDocument>(
                DatabaseNamespace.Admin,
                buildInfoCommand,
                true,
                BsonDocumentSerializer.Instance,
                null);
            var buildInfoResult = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false));

            var connectionId = connection.ConnectionId;
            var description  = new ConnectionDescription(connectionId, isMasterResult, buildInfoResult);

            await AuthenticationHelper.AuthenticateAsync(connection, description, cancellationToken).ConfigureAwait(false);

            try
            {
                var getLastErrorCommand  = new BsonDocument("getLastError", 1);
                var getLastErrorProtocol = new CommandWireProtocol <BsonDocument>(
                    DatabaseNamespace.Admin,
                    getLastErrorCommand,
                    true,
                    BsonDocumentSerializer.Instance,
                    null);
                var getLastErrorResult = await getLastErrorProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);

                BsonValue connectionIdBsonValue;
                if (getLastErrorResult.TryGetValue("connectionId", out connectionIdBsonValue))
                {
                    connectionId = connectionId.WithServerValue(connectionIdBsonValue.ToInt32());
                    description  = description.WithConnectionId(connectionId);
                }
            }
            catch
            {
                // if we couldn't get the server's connection id, so be it.
            }

            return(description);
        }
Ejemplo n.º 14
0
        // methods
        public async Task AuthenticateAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
        {
            using (var conversation = new SaslConversation())
            {
                var currentStep = _mechanism.Initialize(connection);

                var command = new BsonDocument
                {
                    { "saslStart", 1 },
                    { "mechanism", _mechanism.Name },
                    { "payload", currentStep.BytesToSendToServer }
                };

                var slidingTimeout = new SlidingTimeout(timeout);

                while (true)
                {
                    BsonDocument result;
                    try
                    {
                        var protocol = new CommandWireProtocol(DatabaseName, command, true);
                        result = await protocol.ExecuteAsync(connection, slidingTimeout, cancellationToken);
                    }
                    catch(MongoCommandException ex)
                    {
                        var message = string.Format("Unable to authenticate using sasl protocol mechanism {0}.", Name);
                        throw new MongoAuthenticationException(message, ex);
                    }

                    // we might be done here if the client is not expecting a reply from the server
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    currentStep = currentStep.Transition(conversation, result["payload"].AsByteArray);

                    // we might be done here if the client had some final verification it needed to do
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    command = new BsonDocument
                    {
                        { "saslContinue", 1 },
                        { "conversationId", result["conversationId"].AsInt32 },
                        { "payload", currentStep.BytesToSendToServer }
                    };
                }
            }
        }
Ejemplo n.º 15
0
        // methods
        public async Task AuthenticateAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
        {
            using (var conversation = new SaslConversation())
            {
                var currentStep = _mechanism.Initialize(connection);

                var command = new BsonDocument
                {
                    { "saslStart", 1 },
                    { "mechanism", _mechanism.Name },
                    { "payload", currentStep.BytesToSendToServer }
                };

                var slidingTimeout = new SlidingTimeout(timeout);

                while (true)
                {
                    BsonDocument result;
                    try
                    {
                        var protocol = new CommandWireProtocol(DatabaseName, command, true);
                        result = await protocol.ExecuteAsync(connection, slidingTimeout, cancellationToken);
                    }
                    catch (CommandException ex)
                    {
                        var message = string.Format("Unable to authenticate using sasl protocol mechanism {0}.", Name);
                        throw new AuthenticationException(message, ex);
                    }

                    // we might be done here if the client is not expecting a reply from the server
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    currentStep = currentStep.Transition(conversation, result["payload"].AsByteArray);

                    // we might be done here if the client had some final verification it needed to do
                    if (result.GetValue("done", false).ToBoolean() && currentStep.IsComplete)
                    {
                        break;
                    }

                    command = new BsonDocument
                    {
                        { "saslContinue", 1 },
                        { "conversationId", result["conversationId"].AsInt32 },
                        { "payload", currentStep.BytesToSendToServer }
                    };
                }
            }
        }
Ejemplo n.º 16
0
        private async Task <string> GetNonceAsync(IConnection connection, CancellationToken cancellationToken)
        {
            var command  = new BsonDocument("getnonce", 1);
            var protocol = new CommandWireProtocol <BsonDocument>(
                new DatabaseNamespace(_credential.Source),
                command,
                true,
                BsonDocumentSerializer.Instance,
                null);
            var document = await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);

            return((string)document["nonce"]);
        }
Ejemplo n.º 17
0
 private async Task AuthenticateAsync(IConnection connection, string nonce, CancellationToken cancellationToken)
 {
     var command = new BsonDocument
     {
         { "authenticate", 1 },
         { "user", _credential.Username },
         { "nonce", nonce },
         { "key", CreateKey(_credential.Username, _credential.Password, nonce) }
     };
     var protocol = new CommandWireProtocol <BsonDocument>(
         new DatabaseNamespace(_credential.Source),
         command,
         true,
         BsonDocumentSerializer.Instance,
         null);
     await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
 }
Ejemplo n.º 18
0
 internal static async Task<HelloResult> GetResultAsync(
     IConnection connection,
     CommandWireProtocol<BsonDocument> helloProtocol,
     CancellationToken cancellationToken)
 {
     try
     {
         var helloResultDocument = await helloProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
         return new HelloResult(helloResultDocument);
     }
     catch (MongoCommandException ex) when (ex.Code == 11)
     {
         // If the hello or legacy hello command fails with error code 11 (UserNotFound), drivers must consider authentication
         // to have failed.In such a case, drivers MUST raise an error that is equivalent to what they would have
         // raised if the authentication mechanism were specified and the server responded the same way.
         throw new MongoAuthenticationException(connection.ConnectionId, "User not found.", ex);
     }
 }
        // methods
        public async Task AuthenticateAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");

            try
            {
                var command = new BsonDocument
                {
                    { "authenticate", 1 },
                    { "mechanism", Name },
                    { "user", _username }
                };
                var protocol = new CommandWireProtocol(new DatabaseNamespace("$external"), command, true, null);
                await protocol.ExecuteAsync(connection, timeout, cancellationToken);
            }
            catch (MongoCommandException ex)
            {
                var message = string.Format("Unable to authenticate username '{0}' using protocol '{1}'.", _username, Name);
                throw new MongoAuthenticationException(message, ex);
            }
        }
        // methods
        public async Task AuthenticateAsync(IConnection connection, TimeSpan timeout, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");

            try
            {
                var command = new BsonDocument
                {
                    { "authenticate", 1 },
                    { "mechanism", Name },
                    { "user", _username }
                };
                var protocol = new CommandWireProtocol(new DatabaseNamespace("$external"), command, true, null);
                await protocol.ExecuteAsync(connection, timeout, cancellationToken);
            }
            catch (MongoCommandException ex)
            {
                var message = string.Format("Unable to authenticate username '{0}' using protocol '{1}'.", _username, Name);
                throw new MongoAuthenticationException(message, ex);
            }
        }
Ejemplo n.º 21
0
        public async Task <ConnectionDescription> InitializeConnectionAsync(IConnection connection, ConnectionId connectionId, TimeSpan timeout, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");
            Ensure.IsNotNull(connectionId, "connectionId");
            Ensure.IsInfiniteOrGreaterThanOrEqualToZero(timeout, "timeout");

            var slidingTimeout = new SlidingTimeout(timeout);

            var isMasterCommand  = new BsonDocument("isMaster", 1);
            var isMasterProtocol = new CommandWireProtocol("admin", isMasterCommand, true);
            var isMasterResult   = new IsMasterResult(await isMasterProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));

            // authentication is currently broken on arbiters
            if (!isMasterResult.IsArbiter)
            {
                foreach (var authenticator in connection.Settings.Authenticators)
                {
                    await authenticator.AuthenticateAsync(connection, slidingTimeout, cancellationToken);
                }
            }

            var buildInfoCommand  = new BsonDocument("buildInfo", 1);
            var buildInfoProtocol = new CommandWireProtocol("admin", buildInfoCommand, true);
            var buildInfoResult   = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));

            var getLastErrorCommand  = new BsonDocument("getLastError", 1);
            var getLastErrorProtocol = new CommandWireProtocol("admin", getLastErrorCommand, true);
            var getLastErrorResult   = await getLastErrorProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken);

            BsonValue connectionIdBsonValue;

            if (getLastErrorResult.TryGetValue("connectionId", out connectionIdBsonValue))
            {
                connectionId = connectionId.WithServerValue(connectionIdBsonValue.ToInt32());
            }

            return(new ConnectionDescription(connectionId, isMasterResult, buildInfoResult));
        }
        public async Task<ConnectionDescription> InitializeConnectionAsync(IConnection connection, ConnectionId connectionId, TimeSpan timeout, CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(connection, "connection");
            Ensure.IsNotNull(connectionId, "connectionId");
            Ensure.IsInfiniteOrGreaterThanOrEqualToZero(timeout, "timeout");

            var slidingTimeout = new SlidingTimeout(timeout);

            var isMasterCommand = new BsonDocument("isMaster", 1);
            var isMasterProtocol = new CommandWireProtocol("admin", isMasterCommand, true);
            var isMasterResult = new IsMasterResult(await isMasterProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));

            // authentication is currently broken on arbiters
            if (!isMasterResult.IsArbiter)
            {
                foreach (var authenticator in connection.Settings.Authenticators)
                {
                    await authenticator.AuthenticateAsync(connection, slidingTimeout, cancellationToken);
                }
            }

            var buildInfoCommand = new BsonDocument("buildInfo", 1);
            var buildInfoProtocol = new CommandWireProtocol("admin", buildInfoCommand, true);
            var buildInfoResult = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken));

            var getLastErrorCommand = new BsonDocument("getLastError", 1);
            var getLastErrorProtocol = new CommandWireProtocol("admin", getLastErrorCommand, true);
            var getLastErrorResult = await getLastErrorProtocol.ExecuteAsync(connection, slidingTimeout, cancellationToken);

            BsonValue connectionIdBsonValue;
            if (getLastErrorResult.TryGetValue("connectionId", out connectionIdBsonValue))
            {
                connectionId = connectionId.WithServerValue(connectionIdBsonValue.ToInt32());
            }

            return new ConnectionDescription(connectionId, isMasterResult, buildInfoResult);
        }
        public void ExecuteAsync_should_not_wait_for_response_when_CommandResponseHandling_is_Ignore()
        {
            var subject = new CommandWireProtocol<BsonDocument>(
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Ignore,
                true,
                BsonDocumentSerializer.Instance,
                new MessageEncoderSettings());

            var connection = Substitute.For<IConnection>();

            var result = subject.ExecuteAsync(connection, CancellationToken.None).GetAwaiter().GetResult();
            result.Should().BeNull();

            connection.ReceivedWithAnyArgs().ReceiveMessageAsync(0, null, null, CancellationToken.None);
        }
 private async Task<string> GetNonceAsync(IConnection connection, CancellationToken cancellationToken)
 {
     var command = new BsonDocument("getnonce", 1);
     var protocol = new CommandWireProtocol<BsonDocument>(
         new DatabaseNamespace(_credential.Source),
         command,
         true,
         BsonDocumentSerializer.Instance,
         null);
     var document = await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
     return (string)document["nonce"];
 }
 private async Task AuthenticateAsync(IConnection connection, string nonce, CancellationToken cancellationToken)
 {
     var command = new BsonDocument
     {
         { "authenticate", 1 },
         { "user", _credential.Username },
         { "nonce", nonce },
         { "key", CreateKey(_credential.Username, _credential.Password, nonce) }
     };
     var protocol = new CommandWireProtocol<BsonDocument>(
         new DatabaseNamespace(_credential.Source),
         command,
         true,
         BsonDocumentSerializer.Instance,
         null);
     await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
 }
        private async Task<HeartbeatInfo> GetHeartbeatInfoAsync(IConnection connection, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (_heartbeatStartedEventHandler != null)
            {
                _heartbeatStartedEventHandler(new ServerHeartbeatStartedEvent(connection.ConnectionId));
            }

            try
            {
                var isMasterCommand = new CommandWireProtocol<BsonDocument>(
                    DatabaseNamespace.Admin,
                    new BsonDocument("isMaster", 1),
                    true,
                    BsonDocumentSerializer.Instance,
                    null);

                var stopwatch = Stopwatch.StartNew();
                var isMasterResultDocument = await isMasterCommand.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
                stopwatch.Stop();
                var isMasterResult = new IsMasterResult(isMasterResultDocument);

                var buildInfoCommand = new CommandWireProtocol<BsonDocument>(
                    DatabaseNamespace.Admin,
                    new BsonDocument("buildInfo", 1),
                    true,
                    BsonDocumentSerializer.Instance,
                    null);

                var buildInfoResultRocument = await buildInfoCommand.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false);
                var buildInfoResult = new BuildInfoResult(buildInfoResultRocument);

                if (_heartbeatSucceededEventHandler != null)
                {
                    _heartbeatSucceededEventHandler(new ServerHeartbeatSucceededEvent(connection.ConnectionId, stopwatch.Elapsed));
                }

                return new HeartbeatInfo
                {
                    RoundTripTime = stopwatch.Elapsed,
                    IsMasterResult = isMasterResult,
                    BuildInfoResult = buildInfoResult
                };
            }
            catch (Exception ex)
            {
                if (_heartbeatFailedEventHandler != null)
                {
                    _heartbeatFailedEventHandler(new ServerHeartbeatFailedEvent(connection.ConnectionId, ex));
                }
                throw;
            }
        }
        public void ExecuteAsync_should_wait_for_response_when_CommandResponseHandling_is_Return()
        {
            var subject = new CommandWireProtocol<BsonDocument>(
                new DatabaseNamespace("test"),
                new BsonDocument("cmd", 1),
                NoOpElementNameValidator.Instance,
                () => CommandResponseHandling.Return,
                true,
                BsonDocumentSerializer.Instance,
                new MessageEncoderSettings());

            var connection = Substitute.For<IConnection>();

            var cmdResponse = MessageHelper.BuildReply(CreateRawBsonDocument(new BsonDocument("ok", 1)));
            connection.ReceiveMessageAsync(0, null, null, CancellationToken.None).ReturnsForAnyArgs(Task.FromResult<ResponseMessage>(cmdResponse));

            var result = subject.ExecuteAsync(connection, CancellationToken.None).GetAwaiter().GetResult();
            result.Should().Be("{ok: 1}");
        }