public ConnectionListener(Uri addressUri, string userInfo, IContainer container)
 {
     this.connections    = new HashSet <Connection>();
     this.saslMechanisms = CreateSaslMechanisms(userInfo);
     this.container      = container;
     this.address        = new Address(addressUri.Host, addressUri.Port, null, null, "/", addressUri.Scheme);
     if (addressUri.Scheme.Equals(Address.Amqp, StringComparison.OrdinalIgnoreCase))
     {
         this.listener = new TcpTransportListener(this, addressUri.Host, addressUri.Port);
     }
     else if (addressUri.Scheme.Equals(Address.Amqps, StringComparison.OrdinalIgnoreCase))
     {
         this.listener = new TlsTransportListener(this, addressUri.Host, addressUri.Port, container.ServiceCertificate);
     }
     else if (addressUri.Scheme.Equals(WebSocketTransport.WebSockets, StringComparison.OrdinalIgnoreCase))
     {
         this.listener = new WebSocketTransportListener(this, addressUri.Host, address.Port, address.Path, null);
     }
     else if (addressUri.Scheme.Equals(WebSocketTransport.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
     {
         this.listener = new WebSocketTransportListener(this, addressUri.Host, address.Port, address.Path, container.ServiceCertificate);
     }
     else
     {
         throw new NotSupportedException(addressUri.Scheme);
     }
 }
        /// <summary>
        /// Opens the listener.
        /// </summary>
        public void Open()
        {
            if (this.closed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            if (this.address.Scheme.Equals(Address.Amqp, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TcpTransportListener(this, this.address.Host, this.address.Port);
            }
            else if (this.address.Scheme.Equals(Address.Amqps, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TlsTransportListener(this, this.address.Host, this.address.Port, this.GetServiceCertificate());
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.WebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, null);
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, this.GetServiceCertificate());
            }
            else
            {
                throw new NotSupportedException(this.address.Scheme);
            }

            if (this.address.User != null)
            {
                this.SASL.EnablePlainMechanism(this.address.User, this.address.Password);
            }

            this.listener.Open();
        }
Example #3
0
        void OnAcceptTransport(TransportListener listener, TransportAsyncCallbackArgs args)
        {
            AmqpConnectionSettings connectionSettings = new AmqpConnectionSettings()
            {
                ContainerId  = this.containerId,
                MaxFrameSize = this.maxFrameSize
            };

            AmqpConnection connection = null;

            try
            {
                connection = this.CreateConnection(
                    args.Transport,
                    (ProtocolHeader)args.UserToken,
                    false,
                    this.settings,
                    connectionSettings);

                connection.BeginOpen(connection.DefaultOpenTimeout, this.OnConnectionOpenComplete, connection);
            }
            catch (Exception ex)
            {
                if (connection != null)
                {
                    connection.SafeClose(ex);
                }
            }
        }
        void OnAcceptTransport(TransportListener innerListener, TransportAsyncCallbackArgs args)
        {
            TransportBase  transport  = args.Transport;
            AmqpConnection connection = null;
            string         operation  = "Create";

            try
            {
                AmqpSettings           amqpSettings = this.listener.AmqpSettings; // no need to clone
                ProtocolHeader         header       = (ProtocolHeader)args.UserToken;
                AmqpConnectionSettings settings     = this.connectionSettings.Clone();
                connection = this.runtime.CreateConnection(transport, header, false, this.listener.AmqpSettings, settings);

                operation = "BeginOpen";
                connection.BeginOpen(AmqpConstants.DefaultTimeout, OnConnectionOpenComplete, Tuple.Create(this, innerListener, connection));
            }
            catch (Exception ex) when(!Fx.IsFatal(ex))
            {
                AmqpTrace.Provider.AmqpLogError(innerListener, operation, ex);

                if (connection != null)
                {
                    connection.SafeClose(ex);
                }
                else
                {
                    transport.Abort();
                }
            }
        }
Example #5
0
        public async Task StartAsync()
        {
            Events.Starting();

            var amqpWebSocketListener = new AmqpWebSocketListener(this.authenticator, this.clientCredentialsFactory);

            // This transport settings object sets up a listener for TLS over TCP and a listener for WebSockets.
            TransportListener[] listeners = { this.transportSettings.Settings.CreateListener(), amqpWebSocketListener };

            using (await this.syncLock.LockAsync())
            {
                this.amqpTransportListener = this.transportListenerProvider.Create(listeners, this.amqpSettings);
                await this.amqpTransportListener.OpenAsync(TimeSpan.FromMinutes(1));

                this.amqpTransportListener.Listen(this.OnAcceptTransport);
            }

            if (this.webSocketListenerRegistry.TryRegister(amqpWebSocketListener))
            {
                Events.RegisteredWebSocketListener();
            }
            else
            {
                Events.RegisterWebSocketListenerFailed();
            }

            // Preallocate buffers for AMQP transport
            ByteBuffer.InitBufferManagers();

            Events.Started();
        }
        private async Task CleanupAsync()
        {
            try
            {
                await TransportListener.StopAsync(CancellationToken);

                await Task.WhenAll(
                    ServerTransport.CloseAsync(CancellationToken),
                    ClientTransport.CloseAsync(CancellationToken));
            }
            catch {}
        }
        public async Task TearDown()
        {
            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
            {
                await(TransportListener?.StopAsync(cts.Token) ?? Task.CompletedTask);
            }

            TransportListener?.DisposeIfDisposable();
            CancellationTokenSource.Dispose();

            // Setting null is required because this instance may be reused by NUnit
            TransportListener = null;
        }
Example #8
0
 public TcpConnectionHandler(
     TransportListener listener,
     IEnvelopeSerializer envelopeSerializer,
     IOptions <LimeOptions> options)
 {
     _listener           = listener;
     _envelopeSerializer = envelopeSerializer;
     _portEndPoints      = options
                           .Value
                           .EndPoints
                           .Where(e => e.Transport == TransportType.Tcp)
                           .ToDictionary(e => e.EndPoint.Port, e => e);
 }
        protected async Task <(ITransport ClientTransport, ITransport ServerTransport)> GetAndOpenTargetsAsync()
        {
            TransportListener = CreateTransportListener(ListenerUri, EnvelopeSerializer);
            await TransportListener.StartAsync(CancellationToken);

            var clientTransport     = CreateClientTransport(EnvelopeSerializer);
            var serverTransportTask = TransportListener.AcceptTransportAsync(CancellationToken);
            await clientTransport.OpenAsync(ListenerUri, CancellationToken);

            var serverTransport = await serverTransportTask;
            await serverTransport.OpenAsync(ListenerUri, CancellationToken);

            return(clientTransport, serverTransport);
        }
Example #10
0
 public WebSocketMiddleware(
     RequestDelegate next,
     IEnvelopeSerializer envelopeSerializer,
     TransportListener listener,
     IOptions <LimeOptions> options)
 {
     _next = next;
     _envelopeSerializer = envelopeSerializer;
     _listener           = listener;
     _wsPorts            = options
                           .Value
                           .EndPoints.Where(e => e.Transport == TransportType.WebSocket)
                           .Select(e => e.EndPoint.Port)
                           .ToArray();
 }
Example #11
0
        public async Task CloseAsync(CancellationToken token)
        {
            if (this.amqpTransportListener != null)
            {
                using (await this.syncLock.LockAsync(token))
                {
                    if (this.amqpTransportListener != null)
                    {
                        this.amqpTransportListener.Close();
                        this.amqpTransportListener = null;
                    }
                }
            }

            // Close all existing connections
            this.SafeCloseExistingConnections();
        }
Example #12
0
        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));
        }
        private async Task SetupAsync()
        {
            TransportListener = CreateTransportListener();
            await TransportListener.StartAsync(CancellationToken);

            var serverTcpTransportTask = TransportListener.AcceptTransportAsync(CancellationToken);

            ClientTransport = CreateClientTransport();
            await ClientTransport.OpenAsync(Uri, CancellationToken);

            SynchronizedClientTransport = new SynchronizedTransportDecorator(ClientTransport);

            ServerTransport = await serverTcpTransportTask;
            await ServerTransport.OpenAsync(Uri, CancellationToken);

            SynchronizedServerTransport = new SynchronizedTransportDecorator(ServerTransport);

            Message = Dummy.CreateMessage(Dummy.CreateTextContent());
        }
Example #14
0
        /// <summary>
        /// Opens the listener.
        /// </summary>
        public void Open()
        {
            if (this.closed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            TransportProvider provider;

            if (this.container.CustomTransports.TryGetValue(this.address.Scheme, out provider))
            {
                this.listener = new CustomTransportListener(this, provider);
            }
            else if (this.address.Scheme.Equals(Address.Amqp, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TcpTransportListener(this, this.address.Host, this.address.Port);
            }
            else if (this.address.Scheme.Equals(Address.Amqps, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TlsTransportListener(this, this.address.Host, this.address.Port, this.GetServiceCertificate());
            }
#if NETFX
            else if (this.address.Scheme.Equals(WebSocketTransport.WebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, "HTTP", this.address.Host, address.Port, address.Path);
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, "HTTPS", this.address.Host, address.Port, address.Path);
            }
#endif
            else
            {
                throw new NotSupportedException(this.address.Scheme);
            }

            if (this.address.User != null)
            {
                this.SASL.EnablePlainMechanism(this.address.User, this.address.Password);
            }

            this.listener.Open();
        }
Example #15
0
            public void Open()
            {
                int port = this.container.addressUri.Port;

                if (port == -1)
                {
                    port = AmqpConstants.DefaultPort;
                }

                TcpTransportSettings tcpSettings = new TcpTransportSettings();

                tcpSettings.TcpBacklog    = 20;
                tcpSettings.TcpBufferSize = 4096;
                tcpSettings.SetEndPoint(this.container.addressUri.Host, port, true);
                TransportSettings transportSettings = tcpSettings;

                this.listener = transportSettings.CreateListener();
                this.listener.Listen(this.OnAcceptTransport);
            }
 public HttpMiddleware(
     RequestDelegate next,
     IEnvelopeSerializer envelopeSerializer,
     IOptions <LimeOptions> options,
     TransportListener transportListener,
     ILogger <HttpMiddleware> logger)
 {
     _next = next;
     _envelopeSerializer  = envelopeSerializer;
     _options             = options;
     _transportListener   = transportListener;
     _logger              = logger;
     _portEndPointOptions = options
                            .Value
                            .EndPoints.Where(e => e.Transport == TransportType.Http)
                            .ToDictionary(e => e.EndPoint.Port,
                                          e => e.Options as HttpEndPointOptions ?? new HttpEndPointOptions());
     ValidateOptions();
 }
Example #17
0
        private void Initialize(IDictionary properties, IServerChannelSinkProvider sinkProvider)
        {
            if (properties != null)
            {
                // read property values
                foreach (DictionaryEntry property in properties)
                {
                    switch ((string)property.Key)
                    {
                    case "name": _channelName = Convert.ToString(property.Value); break;

                    case "priority": _channelPriority = Convert.ToInt32(property.Value); break;

                    case "pipe": _pipe = Convert.ToString(property.Value); break;

                    case "securityDescriptor": _securityDescriptor = (property.Value as SecurityDescriptor); break;
                    }
                }
            }

            // setup pipe name
            _pipeName = new PipeName(@"\\.\pipe\" + _pipe);

            // create the chain of the sink providers that will process all messages
            _sinkProvider = ChannelHelper.ServerChannelCreateSinkProviderChain(sinkProvider);
            _channelData  = ChannelHelper.ServerChannelCreateDataStore(ChannelUri, _sinkProvider);

            // create transport sink
            IServerChannelSink nextSink = ChannelServices.CreateServerChannelSinkChain(_sinkProvider, this);

            _transportSink = new ServerTransportSink(nextSink);

            // create listener thread
            _transportListener           = new TransportListener(ChannelUri, typeof(PipeTransport));
            _listenerThread              = new Thread(new ThreadStart(ListenerStart));
            _listenerThread.IsBackground = true;

            _requestHandler = new ProcessRequestCallback(_transportSink.ProcessRequest);

            // start listening on the channel
            StartListening(null);
        }
Example #18
0
        public async Task StartAsync()
        {
            Events.Starting();

            // This transport settings object sets up a listener for TLS over TCP right now.
            TransportListener[] listeners = { this.transportSettings.Settings.CreateListener() };

            using (await this.syncLock.LockAsync())
            {
                this.amqpTransportListener = this.transportListenerProvider.Create(listeners, this.amqpSettings);
                await this.amqpTransportListener.OpenAsync(TimeSpan.FromMinutes(1));

                this.amqpTransportListener.Listen(this.OnAcceptTransport);
            }

            // Preallocate buffers for AMQP transport
            ByteBuffer.InitBufferManagers();

            Events.Started();
        }
Example #19
0
        internal static TransportBase AcceptServerTransport(TransportSettings settings)
        {
            ManualResetEvent complete = new ManualResetEvent(false);
            int           closed      = 0;
            TransportBase transport   = null;

            Action <TransportAsyncCallbackArgs> onTransport = (a) =>
            {
                if (a.Exception != null)
                {
                    Trace.WriteLine(a.Exception.Message);
                }
                else
                {
                    Trace.WriteLine("Listener accepted a transport.");
                    transport = a.Transport;
                }

                if (Interlocked.Exchange(ref closed, 1) == 0)
                {
                    complete.Set();
                }
            };

            TransportListener listener = settings.CreateListener();

            Trace.WriteLine("Listeners are waiting for connections...");
            listener.Listen(onTransport);

            complete.WaitOne();
            complete.Close();

            transport.Closed += (s, a) =>
            {
                listener.Close();
                Trace.WriteLine("Listeners Closed.");
            };

            return(transport);
        }
Example #20
0
        public async void TestStartAsyncThrowsIfOpenAsyncOrListenThrows(TransportListener amqpTransportListener)
        {
            AmqpSettings amqpSettings = AmqpSettingsProvider.GetDefaultAmqpSettings(IotHubHostName, Mock.Of <IAuthenticator>(), Mock.Of <IClientCredentialsFactory>(), Mock.Of <ILinkHandlerProvider>(), Mock.Of <IConnectionProvider>(), new NullCredentialsCache());

            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 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 Assert.ThrowsAsync <ApplicationException>(() => protocolHead.StartAsync());
        }
Example #21
0
 protected void SetUp(TransportEndPoint transportEndPoint = null)
 {
     TransportEndPoint = transportEndPoint ?? new TransportEndPoint();
     Options           = new LimeOptions()
     {
         EndPoints = new List <TransportEndPoint>()
         {
             TransportEndPoint
         }
     };
     EnvelopeSerializer  = new EnvelopeSerializer(new DocumentTypeResolver());
     ServiceScopeFactory = new Mock <IServiceScopeFactory>();
     TransportListener   = new TransportListener(
         Microsoft.Extensions.Options.Options.Create(Options),
         ServiceScopeFactory.Object,
         new ChannelProvider(),
         new Logger <TransportListener>(new LoggerFactory()));
     CancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
     Scope = new Mock <IServiceScope>();
     ServiceScopeFactory
     .Setup(s => s.CreateScope())
     .Returns(Scope.Object);
     ServiceProvider = new Mock <IServiceProvider>();
     Scope
     .SetupGet(s => s.ServiceProvider)
     .Returns(ServiceProvider.Object);
     ServiceProvider
     .Setup(s => s.GetService(typeof(ChannelContextProvider)))
     .Returns(() =>
     {
         var provider = new ChannelContextProvider();
         ChannelContextProviders.Add(provider);
         return(provider);
     });
     SenderChannel           = new Mock <ISenderChannel>();
     ChannelContextProviders = new List <ChannelContextProvider>();
 }
Example #22
0
        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);
        }
Example #23
0
        void OnAcceptTransport(TransportListener transportListener, TransportAsyncCallbackArgs args)
        {
            if (args.Exception != null)
            {
                Events.AcceptTransportInputError(args.Exception);
                ExceptionDispatchInfo.Capture(args.Exception).Throw();
            }

            AmqpConnection connection = null;

            try
            {
                connection = this.amqpSettings.RuntimeProvider.CreateConnection(
                    args.Transport,
                    (ProtocolHeader)args.UserToken,
                    false,
                    this.amqpSettings.Clone(),
                    this.connectionSettings.Clone());

                // Open the connection async but don't block waiting on it.
                this.OpenAmqpConnectionAsync(connection, AmqpConstants.DefaultTimeout)
                .ContinueWith(
                    task =>
                {
                    if (task.Exception != null)
                    {
                        Events.OpenConnectionError(task.Exception);
                    }
                },
                    TaskContinuationOptions.OnlyOnFaulted);
            }
            catch (Exception ex) when(ex.IsFatal() == false)
            {
                Events.AcceptTransportError(ex);
                connection?.SafeClose(ex);
            }
        }
        static void OnConnectionOpenComplete(IAsyncResult result)
        {
            var tuple = (Tuple <AmqpConnectionListener, TransportListener, AmqpConnection>)result.AsyncState;
            AmqpConnectionListener thisPtr       = tuple.Item1;
            TransportListener      innerListener = tuple.Item2;
            AmqpConnection         connection    = tuple.Item3;

            try
            {
                connection.EndOpen(result);
                lock (thisPtr.connections)
                {
                    thisPtr.connections.Add(connection);
                }

                connection.SafeAddClosed(thisPtr.onConnectionClosed);
            }
            catch (Exception ex) when(!Fx.IsFatal(ex))
            {
                AmqpTrace.Provider.AmqpLogError(connection, "EndOpen", ex);

                connection.SafeClose(ex);
            }
        }
        public async Task TearDown()
        {
            using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
            {
                if (ClientTransport != null && ClientTransport.IsConnected)
                {
                    try
                    {
                        await ClientTransport.CloseAsync(cts.Token);
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }

                await(TransportListener?.StopAsync(cts.Token) ?? Task.CompletedTask);
            }

            TransportListener?.DisposeIfDisposable();
            CancellationTokenSource.Dispose();

            // Setting null is required because this instance may be reused by NUnit
            TransportListener = null;
        }
        private void Initialize(IDictionary properties, IServerChannelSinkProvider sinkProvider)
        {
            if (properties != null)
            {
                // read property values
                foreach (DictionaryEntry property in properties)
                {
                    switch ((string)property.Key)
                    {
                    case "name": _channelName = Convert.ToString(property.Value); break;

                    case "priority": _channelPriority = Convert.ToInt32(property.Value); break;

                    case "port": _port = Convert.ToInt32(property.Value); break;

                    case "bindTo": _bindToAddr = IPAddress.Parse(Convert.ToString(property.Value)); break;

                    case "machineName": _machineName = Convert.ToString(property.Value); break;

                    case "useIpAddress": _useIpAddress = Convert.ToBoolean(property.Value); break;

                    case "rejectRemoteRequests": if (Convert.ToBoolean(property.Value))
                        {
                            _bindToAddr = IPAddress.Loopback;
                        }
                        break;
                    }
                }
            }

            if (_machineName == null)
            {
                // setup machine name
                if (_useIpAddress)
                {
                    if (_bindToAddr == IPAddress.Any)
                    {
                        _machineName = NetHelper.GetMachineIp();
                    }
                    else
                    {
                        _machineName = _bindToAddr.ToString();
                    }
                }
                else
                {
                    _machineName = NetHelper.GetMachineName();
                }
            }

            // create the chain of the sink providers that will process all messages
            _sinkProvider = ChannelHelper.ServerChannelCreateSinkProviderChain(sinkProvider);
            _channelData  = ChannelHelper.ServerChannelCreateDataStore(ChannelUri, _sinkProvider);

            // create transport sink
            IServerChannelSink nextSink = ChannelServices.CreateServerChannelSinkChain(_sinkProvider, this);

            _transportSink = new ServerTransportSink(nextSink);

            // create listener thread
            _transportListener           = new TransportListener(ListenerUri, typeof(TcpTransport));
            _listenerThread              = new Thread(new ThreadStart(ListenerStart));
            _listenerThread.IsBackground = true;

            _requestHandler = new ProcessRequestCallback(_transportSink.ProcessRequest);

            // start listening on the channel
            StartListening(null);
        }
Example #27
0
        /// <summary>
        /// Opens the listener.
        /// </summary>
        public void Open()
        {
            if (this.closed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }

            TransportProvider provider;
            if (this.container.CustomTransports.TryGetValue(this.address.Scheme, out provider))
            {
                this.listener = new CustomTransportListener(this, provider);
            }
            else if (this.address.Scheme.Equals(Address.Amqp, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TcpTransportListener(this, this.address.Host, this.address.Port);
            }
            else if (this.address.Scheme.Equals(Address.Amqps, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TlsTransportListener(this, this.address.Host, this.address.Port, this.GetServiceCertificate());
            }
#if NETFX
            else if (this.address.Scheme.Equals(WebSocketTransport.WebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, null);
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, this.GetServiceCertificate());
            }
#endif
            else
            {
                throw new NotSupportedException(this.address.Scheme);
            }

            if (this.address.User != null)
            {
                this.SASL.EnablePlainMechanism(this.address.User, this.address.Password);
            }

            this.listener.Open();
        }
        /// <summary>
        /// Opens the listener.
        /// </summary>
        public void Open()
        {
            if (this.address.Scheme.Equals(Address.Amqp, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TcpTransportListener(this, this.address.Host, this.address.Port);
            }
            else if (this.address.Scheme.Equals(Address.Amqps, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new TlsTransportListener(this, this.address.Host, this.address.Port, this.GetServiceCertificate());
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.WebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, null);
            }
            else if (this.address.Scheme.Equals(WebSocketTransport.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
            {
                this.listener = new WebSocketTransportListener(this, this.address.Host, address.Port, address.Path, this.GetServiceCertificate());
            }
            else
            {
                throw new NotSupportedException(this.address.Scheme);
            }

            if (this.address.User != null)
            {
                this.SASL.EnablePlainMechanism(this.address.User, this.address.Password);
            }

            this.listener.Open();
        }
Example #29
0
 /// <summary>
 /// Called when an error occurs when accepting a socket.
 /// </summary>
 /// <param name="listener">The transport listener.</param>
 /// <param name="willRetry">true if the listener will retry, or false otherwise.</param>
 /// <param name="error">The error message.</param>
 public virtual void AmqpListenSocketAcceptError(TransportListener listener, bool willRetry, string error)
 {
 }
Example #30
0
 protected override void Start(TransportSettings transportSettings)
 {
     this.listener = transportSettings.CreateListener();
     this.listener.Listen(this.OnAcceptTransport);
 }
Example #31
0
        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]);

                if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqps, StringComparison.OrdinalIgnoreCase))
                {
                    if (certificate == null)
                    {
                        throw new InvalidOperationException("/cert option was not set when amqps address is specified.");
                    }

                    TcpTransportSettings tcpSettings = new TcpTransportSettings()
                    {
                        Host = addressUri.Host, Port = addressUri.Port
                    };
                    TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings)
                    {
                        Certificate = certificate, IsInitiator = false
                    };
                    listeners[i] = tlsSettings.CreateListener();
                }
                else if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqp, StringComparison.OrdinalIgnoreCase))
                {
                    TcpTransportSettings tcpSettings = new TcpTransportSettings()
                    {
                        Host = addressUri.Host, Port = addressUri.Port
                    };
                    listeners[i] = tcpSettings.CreateListener();
                }
#if !NETSTANDARD
                else if (addressUri.Scheme.Equals("ws", StringComparison.OrdinalIgnoreCase))
                {
                    WebSocketTransportSettings wsSettings = new WebSocketTransportSettings()
                    {
                        Uri = addressUri
                    };
                    listeners[i] = wsSettings.CreateListener();
                }
#endif
                else
                {
                    throw new NotSupportedException(addressUri.Scheme);
                }
            }

            this.transportListener = new AmqpTransportListener(listeners, settings);
            this.settings          = settings;
        }
Example #32
0
 /**
  * Class constructor, instantiate server socket and create thread to
  * listen for TCP Clients
  *
  * @param address
  * @param port
  */
 public Broadcaster(string address, int port)
 {
     clients  = new ConcurrentDictionary <TransportClient, Client>();
     listener = new TransportListener(this, address, port);
     listener.Start();
 }