public async void TestStartAsyncThrowsIfTransportListenerCallbackArgsHasException() { AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsStore()); var tcpTransportListener = new Mock <TransportListener>("TCP"); var amqpTransportSettings = new Mock <TransportSettings>(); amqpTransportSettings.Setup(ts => ts.CreateListener()).Returns(tcpTransportListener.Object); var transportSettings = new Mock <ITransportSettings>(); transportSettings.SetupGet(sp => sp.Settings).Returns(amqpTransportSettings.Object); var amqpTransportListener = new TestHelperTransportListener( "AMQP", new TransportAsyncCallbackArgs() { Exception = new ApplicationException("No donuts"), CompletedSynchronously = false }); var transportListenerProvider = new Mock <ITransportListenerProvider>(); transportListenerProvider.Setup(tlp => tlp.Create( It.Is <IEnumerable <TransportListener> >(listeners => listeners.Contains(tcpTransportListener.Object)), amqpSettings )).Returns(amqpTransportListener); var protocolHead = new AmqpProtocolHead(transportSettings.Object, amqpSettings, transportListenerProvider.Object); await Assert.ThrowsAsync <ApplicationException>(() => protocolHead.StartAsync()); }
public static ConnectionListener CreateSharedListener( Uri addressUri, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) { return new SharedConnectionListener(addressUri, amqpSettings, connectionSettings); }
public IModel Connect(AmqpSettings settings) { var factory = new ConnectionFactory { UserName = settings.user , Password = settings.password , HostName = settings.hostName , AutomaticRecoveryEnabled = true , NetworkRecoveryInterval = TimeSpan.FromSeconds(10); }; _connect = factory.CreateConnection(); _channel = _connect.CreateModel(); _channel.ExchangeDeclare(settings.exchangeName, ExchangeType.Direct); _channel.QueueDeclare(settings.queueName, false, false, false, null); _channel.QueueBind(settings.queueName, settings.exchangeName, settings.routingKey, null); return _channel; }
public async void TestStartAsyncDoesNotThrowIfCreateConnectionThrows() { AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsStore()); var runtimeProvider = new Mock <IRuntimeProvider>(); amqpSettings.RuntimeProvider = runtimeProvider.Object; runtimeProvider.Setup(rp => rp.CreateConnection(It.IsAny <TransportBase>(), It.IsAny <ProtocolHeader>(), false, It.IsAny <AmqpSettings>(), It.IsAny <AmqpConnectionSettings>())) .Throws(new ApplicationException("No donuts")); var tcpTransportListener = new Mock <TransportListener>("TCP"); var amqpTransportSettings = new Mock <TransportSettings>(); amqpTransportSettings.Setup(ts => ts.CreateListener()).Returns(tcpTransportListener.Object); var transportSettings = new Mock <ITransportSettings>(); transportSettings.SetupGet(sp => sp.Settings).Returns(amqpTransportSettings.Object); var amqpTransportListener = new TestHelperTransportListener( "AMQP", new TransportAsyncCallbackArgs() { CompletedSynchronously = false }); var transportListenerProvider = new Mock <ITransportListenerProvider>(); transportListenerProvider.Setup(tlp => tlp.Create( It.Is <IEnumerable <TransportListener> >(listeners => listeners.Contains(tcpTransportListener.Object)), amqpSettings )).Returns(amqpTransportListener); var protocolHead = new AmqpProtocolHead(transportSettings.Object, amqpSettings, transportListenerProvider.Object); await protocolHead.StartAsync(); }
internal AmqpConnector(AmqpTransportSettings amqpTransportSettings, string hostName) { AmqpTransportSettings = amqpTransportSettings; AmqpSettings = new AmqpSettings(); var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(amqpVersion_1_0_0); AmqpSettings.TransportProviders.Add(amqpTransportProvider); AmqpConnectionSettings = new AmqpConnectionSettings() { MaxFrameSize = AmqpConstants.DefaultMaxFrameSize, ContainerId = CommonResources.GetNewStringGuid(), HostName = hostName }; var tcpTransportSettings = new TcpTransportSettings() { Host = hostName, Port = AmqpConstants.DefaultSecurePort }; TlsTransportSettings = new TlsTransportSettings(tcpTransportSettings) { TargetHost = hostName, Certificate = null, CertificateValidationCallback = AmqpTransportSettings.RemoteCertificateValidationCallback ?? OnRemoteCertificateValidation }; if (AmqpTransportSettings.ClientCertificate != null) { TlsTransportSettings.Certificate = AmqpTransportSettings.ClientCertificate; } }
protected ConnectionListener( Uri addressUri, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) { amqpSettings.ValidateListenerSettings(); this.listenAddress = addressUri; this.amqpSettings = amqpSettings; this.connectionSettings = connectionSettings; this.onAcceptTransport = this.OnAcceptTransport; TcpTransportSettings tcpSettings = new TcpTransportSettings(); tcpSettings.SetEndPoint(addressUri.Host, addressUri.Port, true); TransportListener tpListener = null; if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqps, StringComparison.OrdinalIgnoreCase)) { TlsTransportProvider tlsProvider = this.amqpSettings.GetTransportProvider<TlsTransportProvider>(); if (tlsProvider == null) { throw Fx.Exception.ArgumentNull("TlsSecurityProvider"); } Fx.Assert(tlsProvider.Settings.Certificate != null, "Must have a valid certificate."); TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings, false); tlsSettings.Certificate = tlsProvider.Settings.Certificate; tpListener = tlsSettings.CreateListener(); } else { tpListener = tcpSettings.CreateListener(); } this.transportListener = new AmqpTransportListener(new TransportListener[] { tpListener }, this.amqpSettings); this.onConnectionOpenComplete = new AsyncCallback(this.OnConnectionOpenComplete); }
public AmqpProtocolHead( ITransportSettings transportSettings, AmqpSettings amqpSettings, ITransportListenerProvider transportListenerProvider, IWebSocketListenerRegistry webSocketListenerRegistry) { this.syncLock = new AsyncLock(); this.transportSettings = Preconditions.CheckNotNull(transportSettings, nameof(transportSettings)); this.amqpSettings = Preconditions.CheckNotNull(amqpSettings, nameof(amqpSettings)); this.transportListenerProvider = Preconditions.CheckNotNull(transportListenerProvider); this.webSocketListenerRegistry = Preconditions.CheckNotNull(webSocketListenerRegistry); this.connectionSettings = new AmqpConnectionSettings { ContainerId = "DeviceGateway_" + Guid.NewGuid().ToString("N"), HostName = transportSettings.HostName, // 'IdleTimeOut' on connection settings will be used to close connection if server hasn't // received any packet for 'IdleTimeout' // Open frame send to client will have the IdleTimeout set and the client will do heart beat // every 'IdleTimeout * 7 / 8' // If server doesn't receive any packet till 'ServiceMaxConnectionIdleTimeout' the connection will be closed IdleTimeOut = Constants.DefaultAmqpConnectionIdleTimeoutInMilliSeconds }; this.incomingConnectionMap = new ConcurrentDictionary <uint, AmqpConnection>(); }
public AmqpIoTTransport(AmqpSettings amqpSettings, AmqpTransportSettings amqpTransportSettings, string hostName, bool disableServerCertificateValidation) { _amqpSettings = amqpSettings; _amqpTransportSettings = amqpTransportSettings; _hostName = hostName; _disableServerCertificateValidation = disableServerCertificateValidation; var tcpTransportSettings = new TcpTransportSettings() { Host = hostName, Port = AmqpConstants.DefaultSecurePort }; _tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings) { TargetHost = hostName, Certificate = null, CertificateValidationCallback = _amqpTransportSettings.RemoteCertificateValidationCallback ?? OnRemoteCertificateValidation }; if (_amqpTransportSettings.ClientCertificate != null) { _tlsTransportSettings.Certificate = _amqpTransportSettings.ClientCertificate; } }
public static TransportBase CreateTransport(string host, int port, string sslHost, bool doSslUpgrade, SaslHandler saslHandler) { AmqpSettings settings = GetAmqpSettings(true, sslHost, doSslUpgrade, saslHandler); TransportSettings transportSettings = GetTcpSettings(host, port, false); if (!doSslUpgrade && sslHost != null) { TlsTransportSettings tlsSettings = new TlsTransportSettings(transportSettings); tlsSettings.TargetHost = sslHost; tlsSettings.CertificateValidationCallback = (s, c, h, e) => { return(true); }; transportSettings = tlsSettings; } ManualResetEvent complete = new ManualResetEvent(false); AmqpTransportInitiator initiator = new AmqpTransportInitiator(settings, transportSettings); TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs(); args.CompletedCallback = (a) => { complete.Set(); }; initiator.ConnectAsync(TimeSpan.FromSeconds(120), args); complete.WaitOne(); complete.Dispose(); if (args.Exception != null) { throw args.Exception; } return(args.Transport); }
protected override void Load(ContainerBuilder builder) { // ITransportSettings builder.Register(c => new DefaultTransportSettings(this.scheme, HostName, this.port, this.tlsCertificate)) .As <ITransportSettings>() .SingleInstance(); // ITransportListenerProvider builder.Register(c => new AmqpTransportListenerProvider()) .As <ITransportListenerProvider>() .SingleInstance(); // ILinkHandlerProvider builder.Register( c => { IMessageConverter <AmqpMessage> messageConverter = new AmqpMessageConverter(); IMessageConverter <AmqpMessage> twinMessageConverter = new AmqpTwinMessageConverter(); IMessageConverter <AmqpMessage> directMethodMessageConverter = new AmqpDirectMethodMessageConverter(); ILinkHandlerProvider linkHandlerProvider = new LinkHandlerProvider(messageConverter, twinMessageConverter, directMethodMessageConverter); return(linkHandlerProvider); }) .As <ILinkHandlerProvider>() .SingleInstance(); // Task<AmqpProtocolHead> builder.Register( async c => { var identityFactory = c.Resolve <IClientCredentialsFactory>(); var transportSettings = c.Resolve <ITransportSettings>(); var transportListenerProvider = c.Resolve <ITransportListenerProvider>(); var linkHandlerProvider = c.Resolve <ILinkHandlerProvider>(); var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); var authenticatorTask = c.Resolve <Task <IAuthenticator> >(); var connectionProviderTask = c.Resolve <Task <IConnectionProvider> >(); ICredentialsCache credentialsCache = await credentialsCacheTask; IAuthenticator authenticator = await authenticatorTask; IConnectionProvider connectionProvider = await connectionProviderTask; var webSocketListenerRegistry = c.Resolve <IWebSocketListenerRegistry>(); AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings( this.iotHubHostName, authenticator, identityFactory, linkHandlerProvider, connectionProvider, credentialsCache); return(new AmqpProtocolHead( transportSettings, amqpSettings, transportListenerProvider, webSocketListenerRegistry)); }) .As <Task <AmqpProtocolHead> >() .SingleInstance(); base.Load(builder); }
public static AmqpSettings CreateAmqpSettings( Version amqpVersion, bool useSslStreamSecurity, bool hasTokenProvider, string sslHostName = null, bool useWebSockets = false, bool sslStreamUpgrade = false, System.Net.NetworkCredential networkCredential = null, System.Net.Security.RemoteCertificateValidationCallback certificateValidationCallback = null, bool forceTokenProvider = true) { AmqpSettings settings = new AmqpSettings(); if (useSslStreamSecurity && !useWebSockets && sslStreamUpgrade) { var tlsSettings = new TlsTransportSettings { CertificateValidationCallback = certificateValidationCallback, TargetHost = sslHostName }; var tlsProvider = new TlsTransportProvider(tlsSettings); tlsProvider.Versions.Add(new AmqpVersion(amqpVersion)); settings.TransportProviders.Add(tlsProvider); } if (hasTokenProvider || networkCredential != null) { SaslTransportProvider saslProvider = new SaslTransportProvider(); saslProvider.Versions.Add(new AmqpVersion(amqpVersion)); settings.TransportProviders.Add(saslProvider); if (forceTokenProvider) { saslProvider.AddHandler(new SaslAnonymousHandler(CbsSaslMechanismName)); } else if (networkCredential != null) { var plainHandler = new SaslPlainHandler { AuthenticationIdentity = networkCredential.UserName, Password = networkCredential.Password }; saslProvider.AddHandler(plainHandler); } else { // old client behavior: keep it for validation only saslProvider.AddHandler(new SaslExternalHandler()); } } AmqpTransportProvider amqpProvider = new AmqpTransportProvider(); amqpProvider.Versions.Add(new AmqpVersion(amqpVersion)); settings.TransportProviders.Add(amqpProvider); return(settings); }
public async Task <AmqpIoTConnection> OpenConnectionAsync(TimeSpan timeout) { if (Logging.IsEnabled) { Logging.Enter(this, timeout, $"{nameof(OpenConnectionAsync)}"); } var amqpSettings = new AmqpSettings(); var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(s_amqpVersion_1_0_0); amqpSettings.TransportProviders.Add(amqpTransportProvider); var amqpConnectionSettings = new AmqpConnectionSettings() { MaxFrameSize = AmqpConstants.DefaultMaxFrameSize, ContainerId = CommonResources.GetNewStringGuid(), HostName = _hostName }; TimeSpan idleTimeout = _amqpTransportSettings.IdleTimeout; if (idleTimeout != null) { amqpConnectionSettings.IdleTimeOut = Convert.ToUInt32(idleTimeout.TotalMilliseconds); } var amqpIoTTransport = new AmqpIoTTransport(amqpSettings, _amqpTransportSettings, _hostName, s_disableServerCertificateValidation); TransportBase transportBase = await amqpIoTTransport.InitializeAsync(timeout).ConfigureAwait(false); try { var amqpConnection = new AmqpConnection(transportBase, amqpSettings, amqpConnectionSettings); AmqpIoTConnection amqpIoTConnection = new AmqpIoTConnection(amqpConnection); amqpConnection.Closed += amqpIoTConnection.AmqpConnectionClosed; await amqpConnection.OpenAsync(timeout).ConfigureAwait(false); if (Logging.IsEnabled) { Logging.Exit(this, timeout, $"{nameof(OpenConnectionAsync)}"); } return(amqpIoTConnection); } catch (Exception e) when(!e.IsFatal()) { transportBase?.Close(); throw; } finally { if (Logging.IsEnabled) { Logging.Exit(this, $"{nameof(OpenConnectionAsync)}"); } } }
public static AmqpSettings GetDefaultAmqpSettings( string iotHubHostName, IAuthenticator authenticator, IClientCredentialsFactory identityFactory, ILinkHandlerProvider linkHandlerProvider, IConnectionProvider connectionProvider, ICredentialsCache credentialsCache) { Preconditions.CheckNotNull(authenticator, nameof(authenticator)); Preconditions.CheckNotNull(identityFactory, nameof(identityFactory)); Preconditions.CheckNotNull(linkHandlerProvider, nameof(linkHandlerProvider)); Preconditions.CheckNonWhiteSpace(iotHubHostName, nameof(iotHubHostName)); Preconditions.CheckNotNull(connectionProvider, nameof(connectionProvider)); var settings = new AmqpSettings { AllowAnonymousConnection = true, RequireSecureTransport = true, RuntimeProvider = new AmqpRuntimeProvider(linkHandlerProvider, true, identityFactory, authenticator, iotHubHostName, connectionProvider, credentialsCache) }; // Add all transport providers we want to support. AddSaslProvider(); AddAmqpProvider(); return(settings); void AddSaslProvider() { var saslProvider = new SaslTransportProvider { MaxFrameSize = 65536, }; saslProvider.Versions.Add(Constants.AmqpVersion100); // TODO: Verify if this handler still needs to be added. It looks like at some point in the past // SASL EXTERNAL was used to do CBS. Since then we have moved away from that and are using // SASL ANONYMOUS to do CBS. So this may not be needed anymore depending on back-compat // needs (i.e. old clients that are still using EXTERNAL for CBS). // saslProvider.AddHandler(new SaslExternalHandler()); saslProvider.AddHandler(new SaslAnonymousHandler()); // CBS for other clients // This handler implements SAS key based auth. saslProvider.AddHandler(new SaslPlainHandler(new EdgeHubSaslPlainAuthenticator(authenticator, identityFactory, iotHubHostName))); settings.TransportProviders.Add(saslProvider); } void AddAmqpProvider() { var amqpProvider = new AmqpTransportProvider(); amqpProvider.Versions.Add(Constants.AmqpVersion100); settings.TransportProviders.Add(amqpProvider); } }
public virtual AmqpClientConnection CreateConnection(Uri uri, string idScope) { AmqpSettings settings = CreateAmqpSettings(idScope); var amqpProvider = new AmqpTransportProvider(); amqpProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); settings.TransportProviders.Add(amqpProvider); return(new AmqpClientConnection(uri, settings)); }
static AmqpSettings CreateAmqpSettings() { var amqpSettings = new AmqpSettings(); var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(AmqpVersion_1_0_0); amqpSettings.TransportProviders.Add(amqpTransportProvider); return amqpSettings; }
public TestHelperAmqpConnection( TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : base(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings) { }
public async void TestStartAsyncDoesNotThrowIfConnectionOpenAsyncThrows() { AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsCache()); var runtimeProvider = new Mock <IRuntimeProvider>(); amqpSettings.RuntimeProvider = runtimeProvider.Object; var tcpTransport = new Mock <TransportBase>("TCP"); TestHelperAmqpConnection amqpConnection = null; runtimeProvider.Setup(rp => rp.CreateConnection(tcpTransport.Object, It.IsAny <ProtocolHeader>(), false, It.IsAny <AmqpSettings>(), It.IsAny <AmqpConnectionSettings>())) .Callback( ( TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings settings, AmqpConnectionSettings connectionSettings) => { amqpConnection = new TestHelperAmqpConnection(transport, protocolHeader, isInitiator, settings, connectionSettings); amqpConnection.OnOpenInternal = () => throw new OperationCanceledException("No donuts for you"); }) .Returns(() => amqpConnection); var tcpTransportListener = new Mock <TransportListener>("TCP"); var amqpTransportSettings = new Mock <TransportSettings>(); amqpTransportSettings.Setup(ts => ts.CreateListener()).Returns(tcpTransportListener.Object); var transportSettings = new Mock <ITransportSettings>(); transportSettings.SetupGet(sp => sp.Settings).Returns(amqpTransportSettings.Object); var amqpTransportListener = new TestHelperTransportListener( "AMQP", new TransportAsyncCallbackArgs() { CompletedSynchronously = false, Transport = tcpTransport.Object }); var transportListenerProvider = new Mock <ITransportListenerProvider>(); transportListenerProvider.Setup( tlp => tlp.Create( It.Is <IEnumerable <TransportListener> >(listeners => listeners.Contains(tcpTransportListener.Object)), amqpSettings)).Returns(amqpTransportListener); var protocolHead = new AmqpProtocolHead(transportSettings.Object, amqpSettings, transportListenerProvider.Object, Mock.Of <IWebSocketListenerRegistry>(), Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()); await protocolHead.StartAsync(); // check if close on the connection was called Assert.NotNull(amqpConnection); Assert.True(amqpConnection.WasClosed); }
static ConnectionInfo() { Amqp.ConnectionFactory defaultCF = new Amqp.ConnectionFactory(); AmqpSettings defaultAMQPSettings = defaultCF.AMQP; DEFAULT_CHANNEL_MAX = defaultAMQPSettings.MaxSessionsPerConnection; DEFAULT_MAX_FRAME_SIZE = defaultAMQPSettings.MaxFrameSize; DEFAULT_IDLE_TIMEOUT = defaultAMQPSettings.IdleTimeout; DEFAULT_REQUEST_TIMEOUT = Convert.ToInt64(NMSConstants.defaultRequestTimeout.TotalMilliseconds); }
internal AmqpClientConnection(Uri uri, AmqpSettings amqpSettings) { _uri = uri; _amqpSettings = amqpSettings; AmqpConnectionSettings = new AmqpConnectionSettings { ContainerId = Guid.NewGuid().ToString(), HostName = _uri.Host }; }
/// <summary> /// Creates a set of dummy settings for testing purposes. /// </summary> /// private static AmqpSettings CreateMockAmqpSettings() { var transportProvider = new AmqpTransportProvider(); transportProvider.Versions.Add(new AmqpVersion(new Version(1, 0, 0, 0))); var amqpSettings = new AmqpSettings(); amqpSettings.TransportProviders.Add(transportProvider); return(amqpSettings); }
public void TestInvalidConstructorInputs() { X509Certificate2 tlsCertificate = CertificateHelper.GenerateSelfSignedCert("TestCert"); var transportSettings = new DefaultTransportSettings(Scheme, HostName, Port, tlsCertificate); AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsCache()); var transportListenerProvider = new Mock <ITransportListenerProvider>(); Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(null, amqpSettings, transportListenerProvider.Object)); Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, null, transportListenerProvider.Object)); Assert.Throws <ArgumentNullException>(() => new AmqpProtocolHead(transportSettings, amqpSettings, null)); Assert.NotNull(new AmqpProtocolHead(transportSettings, amqpSettings, transportListenerProvider.Object)); }
async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); this.refreshTokenTimer.Cancel(); AmqpSettings amqpSettings = this.CreateAmqpSettings(); TlsTransportSettings tlsTransportSettings = this.CreateTlsTransportSettings(); var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings); TransportBase transport; switch (this.amqpTransportSettings.GetTransportType()) { case TransportType.Amqp_WebSocket_Only: transport = await this.CreateClientWebSocketTransport(timeoutHelper.RemainingTime()); break; case TransportType.Amqp_Tcp_Only: transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()); break; default: throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly"); } var amqpConnectionSettings = new AmqpConnectionSettings() { MaxFrameSize = AmqpConstants.DefaultMaxFrameSize, ContainerId = Guid.NewGuid().ToString("N"), HostName = this.connectionString.AmqpEndpoint.Host }; var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings); await amqpConnection.OpenAsync(timeoutHelper.RemainingTime()); var sessionSettings = new AmqpSessionSettings() { Properties = new Fields() }; var amqpSession = amqpConnection.CreateSession(sessionSettings); await amqpSession.OpenAsync(timeoutHelper.RemainingTime()); // This adds itself to amqpConnection.Extensions var cbsLink = new AmqpCbsLink(amqpConnection); await this.SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime()); return(amqpSession); }
/// <summary> /// Creates an AMQP connection for a given scope. /// </summary> /// /// <param name="amqpVersion">The version of AMQP to use for the connection.</param> /// <param name="serviceEndpoint">The endpoint for the Service Bus service to which the scope is associated.</param> /// <param name="transportType">The type of transport to use for communication.</param> /// <param name="proxy">The proxy, if any, to use for communication.</param> /// <param name="scopeIdentifier">The unique identifier for the associated scope.</param> /// <param name="timeout">The timeout to consider when creating the connection.</param> /// /// <returns>An AMQP connection that may be used for communicating with the Service Bus service.</returns> /// protected virtual async Task <AmqpConnection> CreateAndOpenConnectionAsync( Version amqpVersion, Uri serviceEndpoint, ServiceBusTransportType transportType, IWebProxy proxy, string scopeIdentifier, TimeSpan timeout) { var hostName = serviceEndpoint.Host; AmqpSettings amqpSettings = CreateAmpqSettings(AmqpVersion); AmqpConnectionSettings connectionSetings = CreateAmqpConnectionSettings(hostName, scopeIdentifier); TransportSettings transportSettings = transportType.IsWebSocketTransport() ? CreateTransportSettingsForWebSockets(hostName, proxy) : CreateTransportSettingsforTcp(hostName, serviceEndpoint.Port); // Create and open the connection, respecting the timeout constraint // that was received. var stopWatch = Stopwatch.StartNew(); var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings); TransportBase transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false); var connection = new AmqpConnection(transport, amqpSettings, connectionSetings); await OpenAmqpObjectAsync(connection, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); stopWatch.Stop(); // Create the CBS link that will be used for authorization. The act of creating the link will associate // it with the connection. new AmqpCbsLink(connection); // When the connection is closed, close each of the links associated with it. EventHandler closeHandler = null; closeHandler = (snd, args) => { foreach (var link in ActiveLinks.Keys) { link.SafeClose(); } connection.Closed -= closeHandler; }; connection.Closed += closeHandler; return(connection); }
private static AmqpSettings CreateAmqpSettings() { var amqpSettings = new AmqpSettings(); var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(s_amqpVersion_1_0_0); amqpSettings.TransportProviders.Add(amqpTransportProvider); Logging.Info(s_amqpVersion_1_0_0, nameof(CreateAmqpSettings)); return(amqpSettings); }
public AmqpTcpListener(AmqpSettings settings, AmqpServerContext context) { this.settings = settings; this.context = context; try { this.listener = new TcpListener (new IPEndPoint (settings.IpAddress, settings.Port)); listener.Start (); Event.Publish (new AmqpServerStarted(this.settings.IpAddress, this.settings.Port)); } catch { Event.Publish (new AmqpServerFailedToStart(this.settings.IpAddress, this.settings.Port)); } }
protected virtual async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout) { this.OnCreateSession(); var timeoutHelper = new TimeoutHelper(timeout); AmqpSettings amqpSettings = CreateAmqpSettings(); TransportBase transport; switch (this.AmqpTransportSettings.GetTransportType()) { #if !WINDOWS_UWP case TransportType.Amqp_WebSocket_Only: transport = await this.CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime()); break; #endif case TransportType.Amqp_Tcp_Only: TlsTransportSettings tlsTransportSettings = this.CreateTlsTransportSettings(); var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings); transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()); break; default: throw new InvalidOperationException("AmqpTransportSettings must specify WebSocketOnly or TcpOnly"); } var amqpConnectionSettings = new AmqpConnectionSettings() { MaxFrameSize = AmqpConstants.DefaultMaxFrameSize, ContainerId = Guid.NewGuid().ToString("N"), HostName = this.hostName }; var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings); await amqpConnection.OpenAsync(timeoutHelper.RemainingTime()); var sessionSettings = new AmqpSessionSettings() { Properties = new Fields() }; var amqpSession = amqpConnection.CreateSession(sessionSettings); await amqpSession.OpenAsync(timeoutHelper.RemainingTime()); // This adds itself to amqpConnection.Extensions var cbsLink = new AmqpCbsLink(amqpConnection); return(amqpSession); }
private static AmqpSettings CreateAmqpSettings() { AmqpSettings amqpSetting = new AmqpSettings(); SaslTransportProvider saslTransportProvider = new SaslTransportProvider(); saslTransportProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); saslTransportProvider.AddHandler(new SaslExternalHandler()); amqpSetting.TransportProviders.Add(saslTransportProvider); AmqpTransportProvider amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); amqpSetting.TransportProviders.Add(amqpTransportProvider); return(amqpSetting); }
public static AmqpConnection CreateConnection(string host, int port, string sslHost, bool doSslUpgrade, SaslHandler saslHandler, int maxFrameSize, uint?idleTimeoutMs = null) { AmqpSettings settings = GetAmqpSettings(true, sslHost, doSslUpgrade, saslHandler); TransportBase transport = CreateTransport(host, port, sslHost, doSslUpgrade, saslHandler); AmqpConnectionSettings connSettings = GetConnectionSettings(maxFrameSize); if (idleTimeoutMs != null) { connSettings.IdleTimeOut = idleTimeoutMs; } connSettings.HostName = host; return(new AmqpConnection(transport, settings, connSettings)); }
public async void TestStartAsyncThrowsIfCreateListenerThrows() { AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsCache()); var amqpTransportSettings = new Mock <TransportSettings>(); amqpTransportSettings.Setup(ts => ts.CreateListener()).Throws(new ApplicationException("No donuts for you")); var transportSettings = new Mock <ITransportSettings>(); transportSettings.SetupGet(sp => sp.Settings).Returns(amqpTransportSettings.Object); var protocolHead = new AmqpProtocolHead(transportSettings.Object, amqpSettings, Mock.Of <ITransportListenerProvider>(), Mock.Of <IWebSocketListenerRegistry>(), Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>()); await Assert.ThrowsAsync <ApplicationException>(() => protocolHead.StartAsync()); }
public AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : base(transport, connectionSettings) { if (amqpSettings == null) { throw new ArgumentNullException("amqpSettings"); } this.initialHeader = protocolHeader; this.isInitiator = isInitiator; this.amqpSettings = amqpSettings; this.frameDecoder = new FrameDecoder((int)this.Settings.MaxFrameSize); this.sessionsByLocalHandle = new HandleTable<AmqpSession>(this.Settings.ChannelMax.Value); this.sessionsByRemoteHandle = new HandleTable<AmqpSession>(this.Settings.ChannelMax.Value); this.SessionFactory = this; }
public static void Main() { _settings = new AmqpSettings(); using (var amqp = new AmqpConnection()) using (_channel = amqp.Connect(_settings)) { _channel.ExchangeDeclare(_settings.exchangeName, ExchangeType.Direct); _channel.QueueDeclare(_settings.queueName, false, false, false, null); _channel.QueueBind(_settings.queueName, _settings.exchangeName, _settings.routingKey, null); var t = new Timer(TimerCallback, _channel, 0, 2000); Console.ReadLine(); } }
public AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : base((isInitiator ? "out" : "in") + "-connection", transport, connectionSettings, isInitiator) { if (amqpSettings == null) { throw new ArgumentNullException("amqpSettings"); } this.initialHeader = protocolHeader; this.isInitiator = isInitiator; this.amqpSettings = amqpSettings; this.sessionsByLocalHandle = new HandleTable<AmqpSession>(this.Settings.ChannelMax ?? AmqpConstants.DefaultMaxConcurrentChannels - 1); this.sessionsByRemoteHandle = new HandleTable<AmqpSession>(this.Settings.ChannelMax ?? AmqpConstants.DefaultMaxConcurrentChannels - 1); this.SessionFactory = this; this.heartBeat = HeartBeat.None; }
public override AmqpSettings CreateAmqpSettings(string idScope) { var settings = new AmqpSettings(); var saslProvider = new SaslTransportProvider(); saslProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); settings.TransportProviders.Add(saslProvider); byte[] ekBuffer = _security.GetEndorsementKey(); byte[] srkBuffer = _security.GetStorageRootKey(); SaslTpmHandler tpmHandler = new SaslTpmHandler(ekBuffer, srkBuffer, idScope, _security); saslProvider.AddHandler(tpmHandler); return(settings); }
public static AmqpTransportListener CreateListener(string host, int port, string certFindValue, bool doSslUpgrade, SaslHandler saslHandler) { AmqpSettings settings = GetAmqpSettings(false, certFindValue, doSslUpgrade, saslHandler); TransportSettings transportSettings = GetTcpSettings(host, port, true); if (!doSslUpgrade && certFindValue != null) { TlsTransportSettings tlsSettings = new TlsTransportSettings(transportSettings, false); tlsSettings.Certificate = GetCertificate(certFindValue); transportSettings = tlsSettings; } TransportListener listener = transportSettings.CreateListener(); return(new AmqpTransportListener(new TransportListener[] { listener }, settings)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //Configurations AmqpSettings amqpSettings = Configuration.GetSection("AmqpSettings").Get <AmqpSettings>(); services.AddSingleton(amqpSettings); var bus = RabbitHutch.CreateBus($"host={amqpSettings.Host};virtualHost={amqpSettings.VirtualHost};username={amqpSettings.Username};password={amqpSettings.Password};prefetchcount=1"); services.AddSingleton(bus); services.AddScoped <QueueConsumer>(); ApplicationSettings applicationSettings = Configuration.GetSection("ApplicationSettings").Get <ApplicationSettings>(); services.AddSingleton(applicationSettings); }
public static AmqpSettings CreateAmqpSettings( Version amqpVersion, bool useSslStreamSecurity, string sslHostName = null, bool useWebSockets = false, bool sslStreamUpgrade = false, System.Net.NetworkCredential networkCredential = null) { var amqpSettings = new AmqpSettings(); if (useSslStreamSecurity && !useWebSockets && sslStreamUpgrade) { var tlsSettings = new TlsTransportSettings { TargetHost = sslHostName }; var tlsProvider = new TlsTransportProvider(tlsSettings); tlsProvider.Versions.Add(new AmqpVersion(amqpVersion)); amqpSettings.TransportProviders.Add(tlsProvider); } if (networkCredential != null) { var saslTransportProvider = new SaslTransportProvider(); saslTransportProvider.Versions.Add(new AmqpVersion(amqpVersion)); amqpSettings.TransportProviders.Add(saslTransportProvider); if (networkCredential != null) { var plainHandler = new SaslPlainHandler { AuthenticationIdentity = networkCredential.UserName, Password = networkCredential.Password }; saslTransportProvider.AddHandler(plainHandler); } } var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(new AmqpVersion(amqpVersion)); amqpSettings.TransportProviders.Add(amqpTransportProvider); return(amqpSettings); }
public static AmqpSettings GetAmqpSettings(bool client, string sslValue, bool doSslUpgrade, params SaslHandler[] saslHandlers) { AmqpSettings settings = new AmqpSettings(); if ((client && doSslUpgrade) || (!client && sslValue != null)) { TlsTransportSettings tlsSettings = new TlsTransportSettings(); if (client) { tlsSettings.TargetHost = sslValue; tlsSettings.CertificateValidationCallback = (s, c, h, e) => { return true; }; } else { tlsSettings.IsInitiator = false; tlsSettings.Certificate = GetCertificate(sslValue); ; } TlsTransportProvider tlsProvider = new TlsTransportProvider(tlsSettings); tlsProvider.Versions.Add(new AmqpVersion(1, 0, 0)); settings.TransportProviders.Add(tlsProvider); } if (saslHandlers != null && saslHandlers.Length >= 1 && saslHandlers[0] != null) { SaslTransportProvider saslProvider = new SaslTransportProvider(); saslProvider.Versions.Add(new AmqpVersion(1, 0, 0)); foreach (SaslHandler handler in saslHandlers) { saslProvider.AddHandler(handler); } settings.TransportProviders.Add(saslProvider); } AmqpTransportProvider amqpProvider = new AmqpTransportProvider(); amqpProvider.Versions.Add(new AmqpVersion(1, 0, 0)); settings.TransportProviders.Add(amqpProvider); return settings; }
public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) { if (this.amqpSettings.RequireSecureTransport && !transport.IsSecure) { throw new AmqpException(AmqpError.NotAllowed, SR.AmqpTransportNotSecure); } AmqpConnection connection = new AmqpConnection(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings); Utils.Trace(TraceLevel.Info, "{0}: Created {1}", this, connection); return connection; }
public AmqpTransportListener(IEnumerable<TransportListener> listeners, AmqpSettings settings) { this.innerListeners = new List<TransportListener>(listeners); this.settings = settings; }
public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) { return new AmqpConnection(transport, protocolHeader, false, amqpSettings, connectionSettings); }
public Listener(Container container) { this.container = container; this.connections = new List<AmqpConnection>(); this.settings = new AmqpSettings() { RuntimeProvider = this }; TransportProvider provider = new AmqpTransportProvider(); provider.Versions.Add(new AmqpVersion(1, 0, 0)); this.settings.TransportProviders.Add(provider); this.nodes = new Dictionary<string, List<LinkAsyncResult>>(StringComparer.OrdinalIgnoreCase); this.syncRoot = new object(); }
public TestAmqpBroker(IList<string> endpoints, string userInfo, string sslValue, string[] queues) { this.containerId = "TestAmqpBroker-P" + Process.GetCurrentProcess().Id; this.maxFrameSize = 64 * 1024; this.txnManager = new TxnManager(); this.connections = new Dictionary<SequenceNumber, AmqpConnection>(); this.queues = new Dictionary<string, TestQueue>(); if (queues != null) { foreach (string q in queues) { this.queues.Add(q, new TestQueue(this)); } } else { this.implicitQueue = true; } // create and initialize AmqpSettings AmqpSettings settings = new AmqpSettings(); X509Certificate2 certificate = sslValue == null ? null : GetCertificate(sslValue); settings.RuntimeProvider = this; SaslHandler saslHandler; if (userInfo != null) { string[] creds = userInfo.Split(':'); string usernanme = Uri.UnescapeDataString(creds[0]); string password = creds.Length == 1 ? string.Empty : Uri.UnescapeDataString(creds[1]); saslHandler = new SaslPlainHandler(new TestPlainAuthenticator(userInfo, password)); } else { saslHandler = new SaslAnonymousHandler(); } SaslTransportProvider saslProvider = new SaslTransportProvider(); saslProvider.AddHandler(saslHandler); saslProvider.Versions.Add(new AmqpVersion(1, 0, 0)); settings.TransportProviders.Add(saslProvider); AmqpTransportProvider amqpProvider = new AmqpTransportProvider(); amqpProvider.Versions.Add(new AmqpVersion(1, 0, 0)); settings.TransportProviders.Add(amqpProvider); // create and initialize transport listeners TransportListener[] listeners = new TransportListener[endpoints.Count]; for (int i = 0; i < endpoints.Count; i++) { Uri addressUri = new Uri(endpoints[i]); TcpTransportSettings tcpSettings = new TcpTransportSettings() { Host = addressUri.Host, Port = addressUri.Port }; if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqps, StringComparison.OrdinalIgnoreCase)) { if (certificate == null) { throw new InvalidOperationException("/cert option was not set when amqps address is specified."); } TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings) { Certificate = certificate, IsInitiator = false }; listeners[i] = tlsSettings.CreateListener(); } else { listeners[i] = tcpSettings.CreateListener(); } } this.transportListener = new AmqpTransportListener(listeners, settings); this.settings = settings; }
public static ConnectionListener CreateExclusiveListener( Uri addressUri, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings, IConnectionHandler connectionHandler) { return new ExclusiveConnectionListener(addressUri, amqpSettings, connectionSettings, connectionHandler); }
/// <summary> /// This initiator establishes a base transport using the transport settings /// Then it iterates through the security provider list in the settings to upgrade /// the transport (e.g. tcp -> tls -> sasl). /// </summary> /// <param name="settings"></param> /// <param name="transportSettings"></param> public AmqpTransportInitiator(AmqpSettings settings, TransportSettings transportSettings) { settings.ValidateInitiatorSettings(); this.settings = settings; this.transportSettings = transportSettings; }
public ExclusiveConnectionListener( Uri addressUri, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings, IConnectionHandler connectionHandler) : base(addressUri, amqpSettings, connectionSettings) { Fx.Assert(connectionHandler != null, "Connection handler cannot be null."); this.connectionHandler = connectionHandler; }
public AmqpConnection(TransportBase transport, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : this(transport, amqpSettings.GetDefaultHeader(), true, amqpSettings, connectionSettings) { }
public AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : this(transport, protocolHeader, true, amqpSettings, connectionSettings) { }
public AmqpServer (AmqpSettingsBuilder settingsBuilder) { this.settings = settingsBuilder.Build (); this.context = new AmqpServerContext (new CancellationTokenSource ()); }
AmqpConnection IConnectionFactory.CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) { throw new NotImplementedException(); }
public ClientRequestProcessor (AmqpSettings settings) { this.settings = settings; }
AmqpSettings CreateAmqpSettings() { var amqpSettings = new AmqpSettings(); var amqpTransportProvider = new AmqpTransportProvider(); amqpTransportProvider.Versions.Add(AmqpVersion_1_0_0); amqpSettings.TransportProviders.Add(amqpTransportProvider); return amqpSettings; }
static void OnTransport(TransportAsyncCallbackArgs args) { OpenContainerAsyncResult thisPtr = (OpenContainerAsyncResult)args.UserToken; AmqpSettings settings = new AmqpSettings(); TransportProvider provider = new AmqpTransportProvider(); provider.Versions.Add(new AmqpVersion(1, 0, 0)); settings.TransportProviders.Add(provider); thisPtr.connection = new AmqpConnection(args.Transport, settings, new AmqpConnectionSettings() { ContainerId = thisPtr.parent.id }); thisPtr.connection.BeginOpen(TimeSpan.MaxValue, thisPtr.PrepareAsyncCompletion(onConnectionOpen), thisPtr); }
public SharedConnectionListener( Uri addressUri, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : base(addressUri, amqpSettings, connectionSettings) { this.connectionHandlers = new ConcurrentDictionary<string, IConnectionHandler>(StringComparer.OrdinalIgnoreCase); this.connectionOpenCallback = this.OnConnectionOpen; }