// 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); } }
public void Authenticate_should_invoke_authenticators_when_they_exist( [Values(false, true)] bool async) { var description = new ConnectionDescription( new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017))), new IsMasterResult(new BsonDocument("ok", 1)), new BuildInfoResult(new BsonDocument("version", "2.8.0"))); var authenticator = Substitute.For<IAuthenticator>(); var settings = new ConnectionSettings(authenticators: new[] { authenticator }); var connection = Substitute.For<IConnection>(); connection.Description.Returns(description); connection.Settings.Returns(settings); if (async) { AuthenticationHelper.AuthenticateAsync(connection, description, CancellationToken.None).GetAwaiter().GetResult(); authenticator.ReceivedWithAnyArgs().AuthenticateAsync(null, null, CancellationToken.None); } else { AuthenticationHelper.Authenticate(connection, description, CancellationToken.None); authenticator.ReceivedWithAnyArgs().Authenticate(null, null, CancellationToken.None); } }
public async Task<ConnectionDescription> InitializeConnectionAsync(IConnection connection, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); var isMasterProtocol = CreateIsMasterProtocol(); var isMasterResult = new IsMasterResult(await isMasterProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false)); var buildInfoProtocol = CreateBuildInfoProtocol(); var buildInfoResult = new BuildInfoResult(await buildInfoProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false)); var description = new ConnectionDescription(connection.ConnectionId, isMasterResult, buildInfoResult); await AuthenticationHelper.AuthenticateAsync(connection, description, cancellationToken).ConfigureAwait(false); try { var getLastErrorProtocol = CreateGetLastErrorProtocol(); var getLastErrorResult = await getLastErrorProtocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false); description = UpdateConnectionIdWithServerValue(description, getLastErrorResult); } catch { // if we couldn't get the server's connection id, so be it. } return description; }
public void Authenticate_should_not_invoke_authenticators_when_connected_to_an_arbiter( [Values(false, true)] bool async) { var description = new ConnectionDescription( new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017))), new IsMasterResult(new BsonDocument("ok", 1).Add("setName", "rs").Add("arbiterOnly", true)), new BuildInfoResult(new BsonDocument("version", "2.8.0"))); var mockAuthenticator = new Mock<IAuthenticator>(); var settings = new ConnectionSettings(authenticators: new[] { mockAuthenticator.Object }); var mockConnection = new Mock<IConnection>(); mockConnection.SetupGet(c => c.Description).Returns(description); mockConnection.SetupGet(c => c.Settings).Returns(settings); if (async) { AuthenticationHelper.AuthenticateAsync(mockConnection.Object, description, CancellationToken.None).GetAwaiter().GetResult(); mockAuthenticator.Verify(a => a.AuthenticateAsync(It.IsAny<IConnection>(), It.IsAny<ConnectionDescription>(), It.IsAny<CancellationToken>()), Times.Never); } else { AuthenticationHelper.Authenticate(mockConnection.Object, description, CancellationToken.None); mockAuthenticator.Verify(a => a.Authenticate(It.IsAny<IConnection>(), It.IsAny<ConnectionDescription>(), It.IsAny<CancellationToken>()), Times.Never); } }
// methods /// <inheritdoc/> public void Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); using (var conversation = new SaslConversation(description.ConnectionId)) { var currentStep = _mechanism.Initialize(connection, description); var command = CreateStartCommand(currentStep); while (true) { BsonDocument result; try { var protocol = CreateCommandProtocol(command); result = protocol.Execute(connection, cancellationToken); } catch (MongoCommandException ex) { throw CreateException(connection, ex); } currentStep = Transition(conversation, currentStep, result); if (currentStep == null) { return; } command = CreateContinueCommand(currentStep, result); } } }
// methods /// <inheritdoc/> public void Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); var authenticator = CreateAuthenticator(description); authenticator.Authenticate(connection, description, cancellationToken); }
/// <inheritdoc/> public Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); var authenticator = CreateAuthenticator(description); return authenticator.AuthenticateAsync(connection, description, cancellationToken); }
// methods /// <inheritdoc/> public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(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 } }; } } }
private void ConnectionSettingsForm_Load(object sender, EventArgs e) { Text = "Connection settings for channel: " + this.channelId; var doc = new XmlDocument(); doc.Load(this.channelConfigurationFile); var xpath = string.Format("/configuration/channel[@id='{0}']/connections/connection", this.channelId); var connectionNodes = doc.SelectNodes(xpath); if (connectionNodes.Count == 0) { throw new Exception("Cannot find connection node for channel node with id=" + this.channelId + " in " + this.channelConfigurationFile); } var connections = new List<ConnectionDescription>(); foreach (XmlNode connection in connectionNodes) { var description = new ConnectionDescription(); description.Id = connection.Attributes["id"].Value; foreach (XmlNode parameter in connection.ChildNodes) { switch (parameter.Name) { case "ip": description.Ip = parameter.InnerText.Trim(); break; case "host-ip": description.HostIp = parameter.InnerText.Trim(); break; case "port": description.Port = Int32.Parse(parameter.InnerText.Trim()); break; case "type": description.Category = parameter.InnerText.Trim() + description.Category; break; case "feed": description.Category = description.Category + parameter.InnerText.Trim(); break; default: continue; } } connections.Add(description); } foreach (var item in connections) { this.dataGridViewConnections.Rows.Add(item.Id, item.Category, item.Ip, item.HostIp, item.Port); } }
private IAuthenticator CreateAuthenticator(ConnectionDescription description) { if (description.BuildInfoResult.ServerVersion >= __scramVersionRequirement) { return new ScramSha1Authenticator(_credential, _randomStringGenerator); } else { return new MongoDBCRAuthenticator(_credential); } }
private IAuthenticator CreateAuthenticator(ConnectionDescription description) { if (Feature.ScramSha1Authentication.IsSupported(description.ServerVersion)) { return new ScramSha1Authenticator(_credential, _randomStringGenerator); } else { return new MongoDBCRAuthenticator(_credential); } }
// methods public ISaslStep Initialize(IConnection connection, ConnectionDescription description) { Ensure.IsNotNull(connection, "connection"); Ensure.IsNotNull(description, "description"); var dataString = string.Format("\0{0}\0{1}", _credential.Username, _credential.GetInsecurePassword()); var bytes = Utf8Encodings.Strict.GetBytes(dataString); return new CompletedStep(bytes); }
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; }
public static async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); // authentication is currently broken on arbiters if (!description.IsMasterResult.IsArbiter) { foreach (var authenticator in connection.Settings.Authenticators) { await authenticator.AuthenticateAsync(connection, description, cancellationToken).ConfigureAwait(false); } } }
public static void Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); // authentication is currently broken on arbiters if (!description.IsMasterResult.IsArbiter) { foreach (var authenticator in connection.Settings.Authenticators) { authenticator.Authenticate(connection, description, cancellationToken); } } }
// public methods /// <inheritdoc/> public void Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); try { var protocol = CreateAuthenticateProtocol(); protocol.Execute(connection, cancellationToken); } catch (MongoCommandException ex) { throw CreateException(connection, ex); } }
/// <inheritdoc/> public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); try { var protocol = CreateAuthenticateProtocol(); await protocol.ExecuteAsync(connection, cancellationToken).ConfigureAwait(false); } catch (MongoCommandException ex) { throw CreateException(connection, ex); } }
// methods /// <inheritdoc/> public async Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, "connection"); Ensure.IsNotNull(description, "description"); try { var nonce = await GetNonceAsync(connection, cancellationToken).ConfigureAwait(false); await AuthenticateAsync(connection, nonce, cancellationToken).ConfigureAwait(false); } catch(MongoCommandException ex) { var message = string.Format("Unable to authenticate username '{0}' on database '{1}'.", _credential.Username, _credential.Source); throw new MongoAuthenticationException(connection.ConnectionId, message, ex); } }
// methods /// <inheritdoc/> public Task AuthenticateAsync(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, "connection"); Ensure.IsNotNull(description, "description"); IAuthenticator authenticator; if (description.BuildInfoResult.ServerVersion >= __scramVersionRequirement) { authenticator = new ScramSha1Authenticator(_credential, _randomStringGenerator); } else { authenticator = new MongoDBCRAuthenticator(_credential); } return authenticator.AuthenticateAsync(connection, description, cancellationToken); }
public void AuthenticateAsync_should_not_invoke_authenticators_when_connected_to_an_arbiter() { var description = new ConnectionDescription( new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017))), new IsMasterResult(new BsonDocument("ok", 1).Add("setName", "rs").Add("arbiterOnly", true)), new BuildInfoResult(new BsonDocument("version", "2.8.0"))); var authenticator = Substitute.For<IAuthenticator>(); var settings = new ConnectionSettings(authenticators: new[] { authenticator }); var connection = Substitute.For<IConnection>(); connection.Description.Returns(description); connection.Settings.Returns(settings); AuthenticationHelper.AuthenticateAsync(connection, description, CancellationToken.None).Wait(); authenticator.DidNotReceiveWithAnyArgs().AuthenticateAsync(null, null, CancellationToken.None); }
public ISaslStep Initialize(IConnection connection, ConnectionDescription description) { Ensure.IsNotNull(connection, "connection"); Ensure.IsNotNull(description, "description"); const string gs2Header = "n,,"; var username = "******" + PrepUsername(_credential.Username); var r = GenerateRandomString(); var nonce = "r=" + r; var clientFirstMessageBare = username + "," + nonce; var clientFirstMessage = gs2Header + clientFirstMessageBare; return new ClientFirst( Utf8Encodings.Strict.GetBytes(clientFirstMessage), clientFirstMessageBare, _credential, r); }
public void Equals_should_return_correct_results() { var connectionId1 = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27018)), 10); var connectionId2 = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27018)), 10); var isMasterResult1 = new IsMasterResult(new BsonDocument("x", 1)); var isMasterResult2 = new IsMasterResult(new BsonDocument("x", 2)); var buildInfoResult1 = new BuildInfoResult(new BsonDocument("version", "2.6.3")); var buildInfoResult2 = new BuildInfoResult(new BsonDocument("version", "2.4.10")); var subject1 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult1); var subject2 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult1); var subject3 = new ConnectionDescription(connectionId1, isMasterResult1, buildInfoResult2); var subject4 = new ConnectionDescription(connectionId1, isMasterResult2, buildInfoResult1); var subject5 = new ConnectionDescription(connectionId2, isMasterResult1, buildInfoResult1); subject1.Equals(subject2).Should().BeTrue(); subject1.Equals(subject3).Should().BeFalse(); subject1.Equals(subject4).Should().BeFalse(); subject1.Equals(subject5).Should().BeFalse(); }
// protected methods /// <inheritdoc /> protected override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, int attempt, long?transactionNumber) { var serverVersion = connectionDescription.ServerVersion; if (!Feature.Collation.IsSupported(serverVersion)) { if (_updates.Items.Skip(_updates.Offset).Take(_updates.Count).Any(u => u.Collation != null)) { throw new NotSupportedException($"Server version {serverVersion} does not support collations."); } } if (!Feature.ArrayFilters.IsSupported(serverVersion)) { if (_updates.Items.Skip(_updates.Offset).Take(_updates.Count).Any(u => u.ArrayFilters != null)) { throw new NotSupportedException($"Server version {serverVersion} does not support arrayFilters."); } } if (Feature.HintForUpdateAndReplaceOperations.DriverMustThrowIfNotSupported(serverVersion) || (WriteConcern != null && !WriteConcern.IsAcknowledged)) { if (_updates.Items.Skip(_updates.Offset).Take(_updates.Count).Any(u => u.Hint != null)) { throw new NotSupportedException($"Server version {serverVersion} does not support hints."); } } var writeConcern = WriteConcernHelper.GetWriteConcernForWriteCommand(session, WriteConcern); return(new BsonDocument { { "update", _collectionNamespace.CollectionName }, { "ordered", IsOrdered }, { "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue }, { "writeConcern", writeConcern, writeConcern != null }, { "txnNumber", () => transactionNumber.Value, transactionNumber.HasValue } }); }
public ISaslStep Initialize(IConnection connection, ConnectionDescription description) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); string hostName; var dnsEndPoint = connection.EndPoint as DnsEndPoint; if (dnsEndPoint != null) { hostName = dnsEndPoint.Host; } else if (connection.EndPoint is IPEndPoint) { hostName = ((IPEndPoint)connection.EndPoint).Address.ToString(); } else { throw new MongoAuthenticationException(connection.ConnectionId, "Only DnsEndPoint and IPEndPoint are supported for GSSAPI authentication."); } if (_canonicalizeHostName) { #if NETSTANDARD1_5 || NETSTANDARD1_6 var entry = Dns.GetHostEntryAsync(hostName).GetAwaiter().GetResult(); #else var entry = Dns.GetHostEntry(hostName); #endif if (entry != null) { hostName = entry.HostName; } } return(new FirstStep(_serviceName, hostName, _realm, _username, _password)); }
private ConnectionDescription genDefConnDescr(string scopeId) { ConnectionDescription connDescr = new ConnectionDescription(); connDescr.autopublishAudio = false; connDescr.autopublishVideo = false; connDescr.url = "dev04.saymama.com:7005/" + scopeId; connDescr.token = new Random().Next(1000) + ""; connDescr.lowVideoStream.maxBitRate = 32; connDescr.lowVideoStream.maxWidth = 160; connDescr.lowVideoStream.maxHeight = 120; connDescr.lowVideoStream.maxFps = 5; connDescr.lowVideoStream.publish = true; connDescr.lowVideoStream.receive = true; connDescr.highVideoStream.maxBitRate = 500; connDescr.highVideoStream.maxWidth = 320; connDescr.highVideoStream.maxHeight = 240; connDescr.highVideoStream.maxFps = 15; connDescr.highVideoStream.publish = true; connDescr.highVideoStream.receive = true; return(connDescr); }
public void testStats() { setupDevs(); string scopeId = "c_sharp_test_room"; ConnectionDescription connDescr = genDefConnDescr(scopeId); connDescr.autopublishAudio = true; connDescr.autopublishVideo = true; _service.connect(createVoidResponder(), connDescr); awaitVoidResult("connect", 10000); Thread.Sleep(1000); MediaStatsEvent lastE = null; dispatcher.MediaStats += delegate(object nothing, MediaStatsEvent e) { lastE = e; Console.Error.WriteLine("Got media event " + e.MediaType.StringValue); Console.Error.WriteLine("Bitrate: " + e.Stats.bitRate); Console.Error.WriteLine("RTT: " + e.Stats.rtt); }; _service.startMeasuringStatistics(createVoidResponder(), scopeId, 1); awaitVoidResult("startMeasuringStatistics"); Thread.Sleep(5000); Assert.IsNotNull(lastE); _service.stopMeasuringStatistics(createVoidResponder(), scopeId); awaitVoidResult("stopMeasuringStatistics"); Thread.Sleep(1000); lastE = null; Thread.Sleep(5000); Assert.IsNull(lastE); _service.disconnect(createVoidResponder(), scopeId); awaitVoidResult("disconnect"); }
// methods internal override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long?transactionNumber) { var serverVersion = connectionDescription.ServerVersion; Feature.Collation.ThrowIfNotSupported(serverVersion, Collation); var writeConcern = WriteConcernHelper.GetWriteConcernForCommand(session, WriteConcern, serverVersion, Feature.FindAndModifyWriteConcern); return(new BsonDocument { { "findAndModify", CollectionNamespace.CollectionName }, { "query", _filter }, { "update", _replacement }, { "new", true, _returnDocument == ReturnDocument.After }, { "sort", _sort, _sort != null }, { "fields", _projection, _projection != null }, { "upsert", true, _isUpsert }, { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue }, { "writeConcern", writeConcern, writeConcern != null }, { "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue&& Feature.BypassDocumentValidation.IsSupported(serverVersion) }, { "collation", () => Collation.ToBsonDocument(), Collation != null }, { "txnNumber", () => transactionNumber, transactionNumber.HasValue } }); }
// methods internal BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription) { var flags = GetFlags(); var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(session, _writeConcern); return(new BsonDocument { { "create", _collectionNamespace.CollectionName }, { "capped", () => _capped.Value, _capped.HasValue }, { "autoIndexId", () => _autoIndexId.Value, _autoIndexId.HasValue }, { "size", () => _maxSize.Value, _maxSize.HasValue }, { "max", () => _maxDocuments.Value, _maxDocuments.HasValue }, { "flags", () => (int)flags.Value, flags.HasValue }, { "storageEngine", () => _storageEngine, _storageEngine != null }, { "indexOptionDefaults", _indexOptionDefaults, _indexOptionDefaults != null }, { "validator", _validator, _validator != null }, { "validationAction", () => _validationAction.Value.ToString().ToLowerInvariant(), _validationAction.HasValue }, { "validationLevel", () => _validationLevel.Value.ToString().ToLowerInvariant(), _validationLevel.HasValue }, { "collation", () => _collation.ToBsonDocument(), _collation != null }, { "writeConcern", writeConcern, writeConcern != null }, { "expireAfterSeconds", () => _expireAfter.Value.TotalSeconds, _expireAfter.HasValue }, { "timeseries", () => _timeSeriesOptions.ToBsonDocument(), _timeSeriesOptions != null } }); }
// methods /// <inheritdoc/> public void Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken) { Ensure.IsNotNull(connection, nameof(connection)); Ensure.IsNotNull(description, nameof(description)); // If we don't have SaslSupportedMechs as part of the response, that means we didn't piggyback the initial // hello or legacy hello request and should query the server (provided that the server >= 4.0), merging results into // a new ConnectionDescription if (!description.HelloResult.HasSaslSupportedMechs && Feature.ScramSha256Authentication.IsSupported(description.MaxWireVersion)) { var command = CustomizeInitialHelloCommand(HelloHelper.CreateCommand(_serverApi)); var helloProtocol = HelloHelper.CreateProtocol(command, _serverApi); var helloResult = HelloHelper.GetResult(connection, helloProtocol, cancellationToken); var mergedHelloResult = new HelloResult(description.HelloResult.Wrapped.Merge(helloResult.Wrapped)); description = new ConnectionDescription( description.ConnectionId, mergedHelloResult); } var authenticator = GetOrCreateAuthenticator(connection, description); authenticator.Authenticate(connection, description, cancellationToken); }
internal BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription) { var readConcern = _readConcern != null ? ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern) : null; var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(session, _writeConcern); return(new BsonDocument { { "aggregate", _collectionNamespace == null ? (BsonValue)1 : _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(_pipeline) }, { "allowDiskUse", () => _allowDiskUse.Value, _allowDiskUse.HasValue }, { "bypassDocumentValidation", () => _bypassDocumentValidation.Value, _bypassDocumentValidation.HasValue }, { "maxTimeMS", () => MaxTimeHelper.ToMaxTimeMS(_maxTime.Value), _maxTime.HasValue }, { "collation", () => _collation.ToBsonDocument(), _collation != null }, { "readConcern", readConcern, readConcern != null }, { "writeConcern", writeConcern, writeConcern != null }, { "cursor", new BsonDocument() }, { "hint", () => _hint, _hint != null }, { "let", () => _let, _let != null }, { "comment", () => _comment, _comment != null } }); }
private async Task OpenAsyncHelperAsync(CancellationToken cancellationToken) { if (_openingEventHandler != null) { _openingEventHandler(new ConnectionOpeningEvent(_connectionId, _settings, EventContext.OperationId)); } try { var stopwatch = Stopwatch.StartNew(); _stream = await _streamFactory.CreateStreamAsync(_endPoint, cancellationToken).ConfigureAwait(false); _state.TryChange(State.Initializing); _description = await _connectionInitializer.InitializeConnectionAsync(this, cancellationToken).ConfigureAwait(false); stopwatch.Stop(); _connectionId = _description.ConnectionId; _state.TryChange(State.Open); if (_openedEventHandler != null) { _openedEventHandler(new ConnectionOpenedEvent(_connectionId, _settings, stopwatch.Elapsed, EventContext.OperationId)); } } catch (Exception ex) { _state.TryChange(State.Failed); var wrappedException = WrapException(ex, "opening a connection to the server"); if (_failedOpeningEventHandler != null) { _failedOpeningEventHandler(new ConnectionOpeningFailedEvent(_connectionId, _settings, wrappedException, EventContext.OperationId)); } throw wrappedException; } }
public void ServerVersion_should_return_buildInfoResult_ServerVersion() { var subject = new ConnectionDescription(__connectionId, __isMasterResult, __buildInfoResult); subject.ServerVersion.Should().Be(__buildInfoResult.ServerVersion); }
public ISaslStep Initialize(IConnection connection, ConnectionDescription description) { Ensure.IsNotNull(connection, "connection"); Ensure.IsNotNull(description, "description"); string hostName; var dnsEndPoint = connection.EndPoint as DnsEndPoint; if (dnsEndPoint != null) { hostName = dnsEndPoint.Host; } else if (connection.EndPoint is IPEndPoint) { hostName = ((IPEndPoint)connection.EndPoint).Address.ToString(); } else { throw new MongoAuthenticationException(connection.ConnectionId, "Only DnsEndPoint and IPEndPoint are supported for GSSAPI authentication."); } if (_canonicalizeHostName) { var entry = Dns.GetHostEntry(hostName); if (entry != null) { hostName = entry.HostName; } } return new FirstStep(_serviceName, hostName, _realm, _username, _password); }
private async Task OpenHelperAsync(CancellationToken cancellationToken) { var helper = new OpenConnectionHelper(this); try { helper.OpeningConnection(); _stream = await _streamFactory.CreateStreamAsync(_endPoint, cancellationToken).ConfigureAwait(false); helper.InitializingConnection(); _description = await _connectionInitializer.InitializeConnectionAsync(this, cancellationToken).ConfigureAwait(false); helper.OpenedConnection(); } catch (Exception ex) { var wrappedException = WrapException(ex, "opening a connection to the server"); helper.FailedOpeningConnection(wrappedException); throw wrappedException; } }
private static bool AreSessionsSupported(ConnectionDescription connectionDescription) => connectionDescription?.HelloResult.LogicalSessionTimeout != null || connectionDescription?.ServiceId != null;
public static BsonDocument GetReadConcernForFirstCommandInTransaction(ICoreSession session, ConnectionDescription connectionDescription) { var readConcern = session.CurrentTransaction.TransactionOptions.ReadConcern; return(ToBsonDocument(session, connectionDescription, readConcern)); }
// public methods /// <inheritdoc /> public override bool IsRetryable(ConnectionDescription connectionDescription) { return(!_isMulti); }
// methods public BsonDocument CreateCommand(ConnectionDescription connectionDescription, ICoreSession session) { var method = typeof(MapReduceOutputToCollectionOperation).GetMethod("CreateCommand", BindingFlags.NonPublic | BindingFlags.Instance); return((BsonDocument)method.Invoke(_instance, new object[] { connectionDescription, session })); }
private Type0CommandMessageSection <BsonDocument> CreateType0Section(ConnectionDescription connectionDescription) { var extraElements = new List <BsonElement>(); AddIfNotAlreadyAdded("$db", _databaseNamespace.DatabaseName); if (connectionDescription.IsMasterResult.ServerType != ServerType.Standalone && _readPreference != null && _readPreference != ReadPreference.Primary) { var readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(_readPreference); AddIfNotAlreadyAdded("$readPreference", readPreferenceDocument); } if (_session.Id != null) { if (IsSessionAcknowledged()) { AddIfNotAlreadyAdded("lsid", _session.Id); } else { if (_session.IsImplicit) { // do not set sessionId if session is implicit and write is unacknowledged } else { throw new InvalidOperationException("Explicit session must not be used with unacknowledged writes."); } } } if (_session.ClusterTime != null) { AddIfNotAlreadyAdded("$clusterTime", _session.ClusterTime); } #pragma warning disable 618 Action <BsonWriterSettings> writerSettingsConfigurator = null; if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { writerSettingsConfigurator = s => s.GuidRepresentation = GuidRepresentation.Unspecified; } #pragma warning restore 618 _session.AboutToSendCommand(); if (_session.IsInTransaction) { var transaction = _session.CurrentTransaction; AddIfNotAlreadyAdded("txnNumber", transaction.TransactionNumber); if (transaction.State == CoreTransactionState.Starting) { AddIfNotAlreadyAdded("startTransaction", true); var readConcern = ReadConcernHelper.GetReadConcernForFirstCommandInTransaction(_session, connectionDescription); if (readConcern != null) { AddIfNotAlreadyAdded("readConcern", readConcern); } } AddIfNotAlreadyAdded("autocommit", false); } var elementAppendingSerializer = new ElementAppendingSerializer <BsonDocument>(BsonDocumentSerializer.Instance, extraElements, writerSettingsConfigurator); return(new Type0CommandMessageSection <BsonDocument>(_command, elementAppendingSerializer)); void AddIfNotAlreadyAdded(string key, BsonValue value) { if (!_command.Contains(key)) { extraElements.Add(new BsonElement(key, value)); } } bool IsSessionAcknowledged() { if (_command.TryGetValue("writeConcern", out var writeConcernDocument)) { var writeConcern = WriteConcern.FromBsonDocument(writeConcernDocument.AsBsonDocument); return(writeConcern.IsAcknowledged); } else { return(true); } } }
// private methods private static bool IsInLoadBalancedMode(ConnectionDescription connectionDescription) => connectionDescription?.ServiceId.HasValue ?? false;
// private methods private IBsonSerializer <BatchableSource <UpdateRequest> > CreateBatchSerializer(ConnectionDescription connectionDescription, int attempt) { if (attempt == 1) { var maxBatchCount = Math.Min(MaxBatchCount ?? int.MaxValue, connectionDescription.MaxBatchCount); var maxItemSize = connectionDescription.MaxWireDocumentSize; var maxBatchSize = connectionDescription.MaxWireDocumentSize; return(new SizeLimitingBatchableSourceSerializer <UpdateRequest>(UpdateRequestSerializer.Instance, NoOpElementNameValidator.Instance, maxBatchCount, maxItemSize, maxBatchSize)); } else { var count = _updates.ProcessedCount; // as set by the first attempt return(new FixedCountBatchableSourceSerializer <UpdateRequest>(UpdateRequestSerializer.Instance, NoOpElementNameValidator.Instance, count)); } }
/// <inheritdoc/> protected internal override BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription) { Feature.ReadConcern.ThrowIfNotSupported(connectionDescription.ServerVersion, _readConcern); var command = base.CreateCommand(session, connectionDescription); var readConcern = ReadConcernHelper.GetReadConcernForCommand(session, connectionDescription, _readConcern); if (readConcern != null) { command.Add("readConcern", readConcern); } return(command); }
public UniqueConnectionDescription(Component component, ConnectionDescription connectionDescription) { Component = component; ConnectionDescription = connectionDescription; }
private ReadCommandOperation <BsonDocument> CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription) { var command = CreateCommand(session, connectionDescription); var operation = new ReadCommandOperation <BsonDocument>(CollectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, MessageEncoderSettings) { RetryRequested = false }; return(operation); }
public static BsonDocument GetReadConcernForCommand(ICoreSession session, ConnectionDescription connectionDescription, ReadConcern readConcern) { return(session.IsInTransaction ? null : ToBsonDocument(session, connectionDescription, readConcern)); }
private ProfileSettingsViewModel ToProfileSettingsVM(ConnectionDescription value) { return(new ProfileSettingsViewModel(value)); }
public static BsonDocument GetReadConcernForSnapshotSesssion(ICoreSession session, ConnectionDescription connectionDescription) { if (AreSessionsSupported(connectionDescription) && session.IsSnapshot) { Feature.SnapshotReads.ThrowIfNotSupported(connectionDescription.MaxWireVersion); var readConcernDocument = ReadConcern.Snapshot.ToBsonDocument(); if (session.SnapshotTime != null) { readConcernDocument.Add("atClusterTime", session.SnapshotTime); } return(readConcernDocument); } return(null); }
public static bool AreRetryableWritesSupported(ConnectionDescription connectionDescription) { return((bool)Reflector.InvokeStatic(typeof(RetryableWriteOperationExecutor), nameof(AreRetryableWritesSupported), connectionDescription)); }
private void OpenHelper(CancellationToken cancellationToken) { var helper = new OpenConnectionHelper(this); try { helper.OpeningConnection(); _stream = _streamFactory.CreateStream(_endPoint, cancellationToken); helper.InitializingConnection(); _description = _connectionInitializer.InitializeConnection(this, cancellationToken); helper.OpenedConnection(); } catch (Exception ex) { var wrappedException = WrapException(ex, "opening a connection to the server"); helper.FailedOpeningConnection(wrappedException); throw wrappedException; } }
// protected methods /// <summary> /// Creates the command. /// </summary> /// <param name="session">The session.</param> /// <param name="connectionDescription">The connection description.</param> /// <param name="attempt">The attempt.</param> /// <param name="transactionNumber">The transaction number.</param> /// <returns> /// A command. /// </returns> protected abstract BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, int attempt, long?transactionNumber);
// public methods /// <summary> /// Determines whether the request is retryable on a given connection. /// </summary> /// <param name="connectionDescription">The connection description.</param> /// <returns> /// <c>true</c> if the request is retryable; otherwise, <c>false</c>. /// </returns> public abstract bool IsRetryable(ConnectionDescription connectionDescription);
// constructors public UpdateBatchSerializer(ConnectionDescription connectionDescription, int maxBatchCount, int maxBatchLength) : base(connectionDescription, maxBatchCount, maxBatchLength) { }
// privates static methods private static bool AreRetryableWritesSupported(ConnectionDescription connectionDescription) { return(connectionDescription.IsMasterResult.LogicalSessionTimeout != null); }
private BsonDocument WrapCommandForQueryMessage(BsonDocument command, ConnectionDescription connectionDescription, out bool messageContainsSessionId) { messageContainsSessionId = false; var extraElements = new List <BsonElement>(); if (_session.Id != null) { var areSessionsSupported = connectionDescription.IsMasterResult.LogicalSessionTimeout.HasValue; if (areSessionsSupported) { var lsid = new BsonElement("lsid", _session.Id); extraElements.Add(lsid); messageContainsSessionId = true; } else { if (!_session.IsImplicit) { throw new MongoClientException("Sessions are not supported."); } } } if (_session.ClusterTime != null) { var clusterTime = new BsonElement("$clusterTime", _session.ClusterTime); extraElements.Add(clusterTime); } #pragma warning disable 618 Action <BsonWriterSettings> writerSettingsConfigurator = null; if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { writerSettingsConfigurator = s => s.GuidRepresentation = GuidRepresentation.Unspecified; } #pragma warning restore 618 var appendExtraElementsSerializer = new ElementAppendingSerializer <BsonDocument>(BsonDocumentSerializer.Instance, extraElements, writerSettingsConfigurator); var commandWithExtraElements = new BsonDocumentWrapper(command, appendExtraElementsSerializer); BsonDocument readPreferenceDocument = null; if (connectionDescription != null) { var serverType = connectionDescription.IsMasterResult.ServerType; readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(serverType, _readPreference); } var wrappedCommand = new BsonDocument { { "$query", commandWithExtraElements }, { "$readPreference", readPreferenceDocument, readPreferenceDocument != null } }; if (_additionalOptions != null) { wrappedCommand.Merge(_additionalOptions, overwriteExistingElements: false); } if (wrappedCommand.ElementCount == 1) { return(wrappedCommand["$query"].AsBsonDocument); } else { return(wrappedCommand); } }
// constructors public InsertBatchSerializer(ConnectionDescription connectionDescription, int maxBatchCount, int maxBatchLength, IElementNameValidator elementNameValidator) : base(connectionDescription, maxBatchCount, maxBatchLength) { _elementNameValidator = elementNameValidator; }
// methods protected override BatchSerializer CreateBatchSerializer(ConnectionDescription connectionDescription, int maxBatchCount, int maxBatchLength) { return new DeleteBatchSerializer(connectionDescription, maxBatchCount, maxBatchLength); }
// methods protected override BatchSerializer CreateBatchSerializer(ConnectionDescription connectionDescription, int maxBatchCount, int maxBatchLength) { return(new UpdateBatchSerializer(connectionDescription, maxBatchCount, maxBatchLength)); }
// constructors public DeleteBatchSerializer(ConnectionDescription connectionDescription, int maxBatchCount, int maxBatchLength) : base(connectionDescription, maxBatchCount, maxBatchLength) { }
private WriteCommandOperation <BsonDocument> CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription) { var command = CreateCommand(session, connectionDescription); return(new WriteCommandOperation <BsonDocument>(_databaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings)); }
public void ConnectionId_should_return_ConnectionId() { var subject = new ConnectionDescription(__connectionId, __isMasterResult, __buildInfoResult); subject.ConnectionId.Should().Be(__connectionId); }