Beispiel #1
0
        public async Task OpenAsync(TimeSpan timeout, bool useWebSocket, X509Certificate2 clientCert)
        {
            var hostName = _uri.Host;

            var tcpSettings = new TcpTransportSettings {
                Host = hostName, Port = _uri.Port != -1 ? _uri.Port : AmqpConstants.DefaultSecurePort
            };

            TransportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost = hostName,
                CertificateValidationCallback = (sender, cert, chain, errors) => true,
                Certificate = clientCert
            };

            TransportBase transport;

            if (useWebSocket)
            {
                transport = await CreateClientWebSocketTransportAsync(timeout).ConfigureAwait(false);
            }
            else
            {
                var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings);
                transport = await tcpInitiator.ConnectTaskAsync(timeout).ConfigureAwait(false);
            }

            AmqpConnection = new AmqpConnection(transport, _amqpSettings, AmqpConnectionSettings);
            await AmqpConnection.OpenAsync(timeout).ConfigureAwait(false);

            _isConnectionClosed    = false;
            AmqpConnection.Closed += OnConnectionClosed;
        }
        public static TransportSettings CreateTcpTransportSettings(
            string networkHost,
            string hostName,
            int port,
            bool useSslStreamSecurity,
            bool sslStreamUpgrade = false,
            string sslHostName    = null,
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate            = null,
            System.Net.Security.RemoteCertificateValidationCallback certificateValidationCallback = null)
        {
            TcpTransportSettings tcpSettings = new TcpTransportSettings
            {
                Host = networkHost,
                Port = port < 0 ? AmqpConstants.DefaultSecurePort : port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            TransportSettings tpSettings = tcpSettings;

            if (useSslStreamSecurity && !sslStreamUpgrade)
            {
                TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings)
                {
                    TargetHost  = sslHostName ?? hostName,
                    Certificate = certificate,
                    CertificateValidationCallback = certificateValidationCallback
                };
                tpSettings = tlsSettings;
            }

            return(tpSettings);
        }
        TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings()
            {
                Host = this.hostName,
                Port = this.port
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost = this.hostName,
#if !WINDOWS_UWP // Not supported in UWP
                Certificate = null,
                CertificateValidationCallback = OnRemoteCertificateValidation
#endif
            };

#if !WINDOWS_UWP
            if (this.AmqpTransportSettings.ClientCertificate != null)
            {
                tlsTransportSettings.Certificate = this.AmqpTransportSettings.ClientCertificate;
            }
#endif

            return(tlsTransportSettings);
        }
Beispiel #4
0
        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;
            }
        }
Beispiel #5
0
            protected OpenAsyncResult(AmqpStream parent, string address, bool listen, TimeSpan timeout, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.parent            = parent;
                this.parent.isReceiver = listen;
                this.timeoutHelper     = new TimeoutHelper(timeout);

                Uri addressUri = new Uri(address);

                this.parent.node = addressUri.PathAndQuery;
                int port = addressUri.Port;

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

                TcpTransportSettings tcpSettings = new TcpTransportSettings();

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

                this.Start(transportSettings);
            }
        private AmqpTransportListener CreateTransportListener()
        {
            TransportListener    transportListener;
            TcpTransportSettings tcpTransportSetting = new TcpTransportSettings();
            int port = this.ListenUri.Port;

            if (port <= 0)
            {
                port = 5672;
            }
            tcpTransportSetting.Host = this.ListenUri.Host;
            tcpTransportSetting.Port = port;
            if (!this.ListenUri.Scheme.Equals("amqps", StringComparison.OrdinalIgnoreCase))
            {
                transportListener = tcpTransportSetting.CreateListener();
            }
            else
            {
                TlsTransportProvider transportProvider = this.amqpSettings.GetTransportProvider <TlsTransportProvider>();
                if (transportProvider == null)
                {
                    throw Fx.Exception.Argument("TlsSecurityProvider", "Tls provider must be set.");
                }
                TlsTransportSettings tlsTransportSetting = new TlsTransportSettings(tcpTransportSetting, false)
                {
                    Certificate = transportProvider.Settings.Certificate
                };
                transportListener = tlsTransportSetting.CreateListener();
            }
            return(new AmqpTransportListener(new TransportListener[] { transportListener }, this.amqpSettings));
        }
Beispiel #7
0
            public OpenContainerAsyncResult(Container parent, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.parent = parent;

                int port = this.parent.addressUri.Port;

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

                TcpTransportSettings tcpSettings = new TcpTransportSettings();

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

                TransportInitiator         initiator = transportSettings.CreateInitiator();
                TransportAsyncCallbackArgs args      = new TransportAsyncCallbackArgs();

                args.CompletedCallback = onTransport;
                args.UserToken         = this;
                if (!initiator.ConnectAsync(TimeSpan.MaxValue, args))
                {
                    OnTransport(args);
                }
            }
        public static TransportSettings CreateTcpTransportSettings(
            string networkHost,
            string hostName,
            int port,
            bool useSslStreamSecurity,
            bool sslStreamUpgrade = false,
            string sslHostName    = null)
        {
            var tcpTransportSettings = new TcpTransportSettings
            {
                Host = networkHost,
                Port = port < 0 ? AmqpConstants.DefaultSecurePort : port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            TransportSettings tpSettings = tcpTransportSettings;

            if (useSslStreamSecurity && !sslStreamUpgrade)
            {
                var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
                {
                    TargetHost = sslHostName ?? hostName
                };
                tpSettings = tlsTransportSettings;
            }

            return(tpSettings);
        }
Beispiel #9
0
        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;
            }
        }
Beispiel #10
0
        public static TcpTransportSettings GetTcpSettings(string host, int port, bool listen)
        {
            TcpTransportSettings tcpSettings = new TcpTransportSettings()
            {
                Host = host, Port = port
            };

            tcpSettings.TcpBacklog = 20;
            return(tcpSettings);
        }
        static AmqpTransportListener CreateListener(IEnumerable <string> addresses, AmqpSettings settings)
        {
            List <TransportListener> listeners = new List <TransportListener>();

            foreach (string address in addresses)
            {
                Uri  uri     = new Uri(address);
                bool isAmqps = string.Equals(AmqpConstants.SchemeAmqps, uri.Scheme, StringComparison.OrdinalIgnoreCase);
                TcpTransportSettings tcpSettings = new TcpTransportSettings()
                {
                    Host = uri.Host,
                    Port = uri.Port < 0 ? (isAmqps ? AmqpConstants.DefaultSecurePort : AmqpConstants.DefaultPort) : uri.Port
                };

                TransportListener tpListener;
                if (isAmqps)
                {
                    var tlsProvider = settings.GetTransportProvider <TlsTransportProvider>();
                    if (tlsProvider == null)
                    {
                        throw new InvalidOperationException($"TlsTransportProvider must be in AmqpSettings.TransportProviders for '{address}'.");
                    }

                    if (tlsProvider.Settings.Certificate == null)
                    {
                        throw new InvalidOperationException($"A server certificate is required in TlsTransportProvider for '{address}'.");
                    }

                    TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings, false);
                    tlsSettings.Certificate = tlsProvider.Settings.Certificate;
                    tlsSettings.CertificateValidationCallback = tlsProvider.Settings.CertificateValidationCallback;
                    tlsSettings.CheckCertificateRevocation    = tlsProvider.Settings.CheckCertificateRevocation;

                    tpListener = tlsSettings.CreateListener();
                }
                else
                {
                    tpListener = tcpSettings.CreateListener();
                }

                listeners.Add(tpListener);
            }

            if (settings.GetTransportProvider <AmqpTransportProvider>() == null)
            {
                var amqpProvider = new AmqpTransportProvider(AmqpVersion.V100);
                settings.TransportProviders.Add(amqpProvider);
            }

            return(new AmqpTransportListener(listeners, settings));
        }
Beispiel #12
0
        public async Task OpenAsync(TimeSpan timeout, bool useWebSocket, X509Certificate2 clientCert)
        {
            var hostName = _uri.Host;

            var tcpSettings = new TcpTransportSettings {
                Host = hostName, Port = _uri.Port != -1 ? _uri.Port : AmqpConstants.DefaultSecurePort
            };

            TransportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost  = hostName,
                Certificate = clientCert
            };

            TransportBase transport;

            if (useWebSocket)
            {
                transport = await CreateClientWebSocketTransportAsync(timeout).ConfigureAwait(false);

                SaslTransportProvider provider = _amqpSettings.GetTransportProvider <SaslTransportProvider>();
                if (provider != null)
                {
                    _sentHeader = new ProtocolHeader(provider.ProtocolId, provider.DefaultVersion);
                    ByteBuffer buffer = new ByteBuffer(new byte[AmqpConstants.ProtocolHeaderSize]);
                    _sentHeader.Encode(buffer);

                    var args = new TransportAsyncCallbackArgs();
                    args.SetBuffer(buffer.Buffer, buffer.Offset, buffer.Length);
                    args.CompletedCallback = OnWriteHeaderComplete;
                    args.Transport         = transport;
                    transport.WriteAsync(args);

                    _tcs      = new TaskCompletionSource <TransportBase>();
                    transport = await _tcs.Task.ConfigureAwait(false);

                    await transport.OpenAsync(timeout).ConfigureAwait(false);
                }
            }
            else
            {
                var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings);
                transport = await tcpInitiator.ConnectTaskAsync(timeout).ConfigureAwait(false);
            }

            AmqpConnection         = new AmqpConnection(transport, _amqpSettings, AmqpConnectionSettings);
            AmqpConnection.Closed += OnConnectionClosed;
            await AmqpConnection.OpenAsync(timeout).ConfigureAwait(false);

            _isConnectionClosed = false;
        }
Beispiel #13
0
        /// <summary>
        ///  Creates the transport settings for use with TCP.
        /// </summary>
        ///
        /// <param name="hostName">The host name of the Event Hubs service endpoint.</param>
        /// <param name="port">The port to use for connecting to the endpoint.</param>
        ///
        /// <returns>The settings to use for transport.</returns>
        ///
        private static TransportSettings CreateTransportSettingsforTcp(string hostName,
                                                                       int port)
        {
            var tcpSettings = new TcpTransportSettings
            {
                Host = hostName,
                Port = port < 0 ? AmqpConstants.DefaultSecurePort : port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            return(new TlsTransportSettings(tcpSettings)
            {
                TargetHost = hostName,
            });
        }
        TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings()
            {
                Host = this.connectionString.HostName,
                Port = this.connectionString.AmqpEndpoint.Port
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost  = this.connectionString.HostName,
                Certificate = null, // TODO: add client cert support
                CertificateValidationCallback = this.OnRemoteCertificateValidation
            };

            return(tlsTransportSettings);
        }
        public DefaultTransportSettings(
            string scheme,
            string hostName,
            int port,
            X509Certificate2 tlsCertificate,
            bool clientCertAuthAllowed,
            IAuthenticator authenticator,
            IClientCredentialsFactory clientCredentialsProvider,
            SslProtocols sslProtocols)
        {
            this.HostName = Preconditions.CheckNonWhiteSpace(hostName, nameof(hostName));
            Preconditions.CheckNotNull(clientCredentialsProvider, nameof(clientCredentialsProvider));
            Preconditions.CheckNotNull(authenticator, nameof(authenticator));

            var address = new UriBuilder
            {
                Host   = hostName,
                Port   = Preconditions.CheckRange(port, 0, ushort.MaxValue, nameof(port)),
                Scheme = Preconditions.CheckNonWhiteSpace(scheme, nameof(scheme))
            };

            var tcpSettings = new TcpTransportSettings()
            {
                Host = address.Host,
                Port = address.Port
            };

            var tlsSettings = new EdgeTlsTransportSettings(tcpSettings, false, authenticator, clientCredentialsProvider)
            {
                TargetHost  = address.Host,
                Certificate = Preconditions.CheckNotNull(tlsCertificate, nameof(tlsCertificate)),
                // NOTE: The following property doesn't appear to be used by the AMQP library.
                //       Not sure that setting this to true/false makes any difference!
                CheckCertificateRevocation = false,
                Protocols = sslProtocols
            };

            if (clientCertAuthAllowed == true)
            {
                tlsSettings.CertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            }

            this.Settings = tlsSettings;
        }
Beispiel #16
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);
            }
        private TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings
            {
                Host = ConnectionString.HostName,
                Port = ConnectionString.AmqpEndpoint.Port,
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost = ConnectionString.HostName,
#if !NETSTANDARD1_3
                Certificate = null, // TODO: add client cert support
                CertificateValidationCallback = OnRemoteCertificateValidation,
#endif
            };

            return(tlsTransportSettings);
        }
        private TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings
            {
                Host = ConnectionString.HostName,
                Port = ConnectionString.AmqpEndpoint.Port,
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost  = ConnectionString.HostName,
                Certificate = null, // TODO: add client cert support
                CertificateValidationCallback = OnRemoteCertificateValidation
            };

            Logging.Info($"host={tcpTransportSettings.Host}, port={tcpTransportSettings.Port}", nameof(CreateTlsTransportSettings));

            return(tlsTransportSettings);
        }
Beispiel #19
0
        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,
            };

            SslProtocols protocols = TlsVersions.Instance.Preferred;

#if NET451
            // Requires hardcoding in NET451 otherwise yields error:
            //    System.ArgumentException: The specified value is not valid in the 'SslProtocolType' enumeration.
            if (amqpTransportSettings.GetTransportType() == TransportType.Amqp_Tcp_Only &&
                protocols == SslProtocols.None)
            {
                protocols = TlsVersions.Instance.MinimumTlsVersions;
            }
#endif

            _tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost  = hostName,
                Certificate = null,
                CertificateValidationCallback = _amqpTransportSettings.RemoteCertificateValidationCallback
                                                ?? OnRemoteCertificateValidation,
                Protocols = protocols,
            };

            if (_amqpTransportSettings.ClientCertificate != null)
            {
                _tlsTransportSettings.Certificate = _amqpTransportSettings.ClientCertificate;
            }
        }
Beispiel #20
0
        TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings()
            {
                Host = this.hostName,
                Port = this.port
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost = this.hostName,
#if !WINDOWS_UWP                    // Not supported in UWP
                Certificate = null, // TODO: add client cert support
                CertificateValidationCallback = OnRemoteCertificateValidation
#endif
            };

            return(tlsTransportSettings);
        }
Beispiel #21
0
                public ConnectAsyncResult(string host, int port, AmqpSettings amqpSettings, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
                {
                    if (port <= 0)
                    {
                        port = 5672;
                    }
                    this.amqpSettings = amqpSettings;
                    TcpTransportSettings tcpTransportSetting = new TcpTransportSettings()
                    {
                        Host = host,
                        Port = port
                    };
                    AmqpTransportInitiator     amqpTransportInitiator    = new AmqpTransportInitiator(this.amqpSettings, tcpTransportSetting);
                    TransportAsyncCallbackArgs transportAsyncCallbackArg = new TransportAsyncCallbackArgs()
                    {
                        CompletedCallback = new Action <TransportAsyncCallbackArgs>(this.OnTransportCallback),
                        UserToken         = this
                    };

                    amqpTransportInitiator.ConnectAsync(timeout, transportAsyncCallbackArg);
                }
Beispiel #22
0
        TlsTransportSettings CreateTlsTransportSettings()
        {
            var tcpTransportSettings = new TcpTransportSettings()
            {
                Host = this.hostName,
                Port = this.port
            };

            var tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings)
            {
                TargetHost  = this.hostName,
                Certificate = null,
                CertificateValidationCallback = this.AmqpTransportSettings.RemoteCertificateValidationCallback ?? OnRemoteCertificateValidation
            };

            if (this.AmqpTransportSettings.ClientCertificate != null)
            {
                tlsTransportSettings.Certificate = this.AmqpTransportSettings.ClientCertificate;
            }

            return(tlsTransportSettings);
        }
        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 void ConnectTimeoutTest()
        {
            const int port    = 30888;
            IPAddress address = IPAddress.Loopback;
            // Creat a listener socket but do not listen on it
            var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };

            socket.Bind(new IPEndPoint(address, port));

            try
            {
                var tcp = new TcpTransportSettings()
                {
                    Host = "localhost", Port = port
                };
                var amqp = new AmqpSettings();
                amqp.TransportProviders.Add(new AmqpTransportProvider());
                var initiator = new AmqpTransportInitiator(amqp, tcp);
                var task      = initiator.ConnectTaskAsync(TimeSpan.FromSeconds(1));
                Assert.False(task.IsCompleted);

                Thread.Sleep(2000);
                Assert.True(task.IsFaulted);
                Assert.NotNull(task.Exception);

                var ex = task.Exception.GetBaseException() as SocketException;
                Assert.NotNull(ex);
                Assert.Equal(SocketError.TimedOut, (SocketError)ex.ErrorCode);
            }
            finally
            {
                socket.Close();
            }
        }
        public DefaultTransportSettings(
            string scheme,
            string hostName,
            int port,
            X509Certificate2 tlsCertificate)
        {
            this.HostName = Preconditions.CheckNonWhiteSpace(hostName, nameof(hostName));

            var address = new UriBuilder
            {
                Host   = hostName,
                Port   = Preconditions.CheckRange(port, 0, ushort.MaxValue, nameof(port)),
                Scheme = Preconditions.CheckNonWhiteSpace(scheme, nameof(scheme))
            };

            var tcpSettings = new TcpTransportSettings()
            {
                Host = address.Host,
                Port = address.Port
            };

            // NOTE:
            //  We don't support X509 client certs as an authentication mechanism
            //  yet. When we do, we'll want to incorporate that here.
            this.Settings = new TlsTransportSettings(tcpSettings, false)
            {
                TargetHost  = address.Host,
                Certificate = Preconditions.CheckNotNull(tlsCertificate, nameof(tlsCertificate)),
                // NOTE: The following property doesn't appear to be used by the AMQP library.
                //       Not sure that setting this to true/false makes any difference!
                CheckCertificateRevocation = false
            };

            // NOTE: We don't support X509 client cert auth yet. When we do the following
            //       line becomes relevant.
            // tlsSettings.CertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        }
Beispiel #26
0
 public static TcpTransportSettings GetTcpSettings(string host, int port, bool listen)
 {
     TcpTransportSettings tcpSettings = new TcpTransportSettings() { Host = host, Port = port };
     tcpSettings.TcpBacklog = 20;
     return tcpSettings;
 }
Beispiel #27
0
            protected override IEnumerator <IteratorTask <object> .TaskStep> GetTasks()
            {
                ConnectivityMode connectivityMode;
                object           obj  = null;
                bool             flag = false;

                try
                {
                    object thisLock = this.relay.ThisLock;
                    object obj1     = thisLock;
                    obj = thisLock;
                    Monitor.Enter(obj1, ref flag);
                    if (this.relay.State != AmqpObjectState.OpenReceived && this.relay.State != AmqpObjectState.Opened)
                    {
                        goto Label0;
                    }
                }
                finally
                {
                    if (flag)
                    {
                        Monitor.Exit(obj);
                    }
                }
                Microsoft.ServiceBus.Common.TimeoutHelper timeoutHelper = new Microsoft.ServiceBus.Common.TimeoutHelper(this.timeout);
                string       host        = this.relay.serviceBusUri.Host;
                AmqpSettings amqpSetting = AmqpRelay.ConnectTask.CreateAmqpSettings();

                connectivityMode = (this.relay.connectivitySettings != null ? this.relay.connectivitySettings.Mode : ServiceBusEnvironment.SystemConnectivity.Mode);
                ConnectivityMode connectivityMode1 = connectivityMode;

                if (connectivityMode1 == ConnectivityMode.Tcp)
                {
                    TcpTransportSettings tcpTransportSetting = new TcpTransportSettings()
                    {
                        Host = host,
                        Port = 5671
                    };
                    TlsTransportSettings tlsTransportSetting = new TlsTransportSettings(tcpTransportSetting)
                    {
                        TargetHost = host
                    };
                    AmqpTransportInitiator amqpTransportInitiator = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting);
                    yield return(base.CallTask(amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                }
                else if (connectivityMode1 == ConnectivityMode.Http || this.relay.httpConnectivitySettings != null)
                {
                    WebSocketTransportSettings webSocketTransportSetting = new WebSocketTransportSettings(this.relay.serviceBusUri);
                    AmqpTransportInitiator     amqpTransportInitiator1   = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting);
                    yield return(base.CallTask(amqpTransportInitiator1.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                }
                else
                {
                    TcpTransportSettings tcpTransportSetting1 = new TcpTransportSettings()
                    {
                        Host = host,
                        Port = 5671
                    };
                    TlsTransportSettings tlsTransportSetting1 = new TlsTransportSettings(tcpTransportSetting1)
                    {
                        TargetHost = host
                    };
                    AmqpTransportInitiator amqpTransportInitiator2 = new AmqpTransportInitiator(amqpSetting, tlsTransportSetting1);
                    yield return(base.CallTask(amqpTransportInitiator2.ConnectTaskAsync(Microsoft.ServiceBus.Common.TimeoutHelper.Divide(timeoutHelper.RemainingTime(), 2)), IteratorTask <TResult> .ExceptionPolicy.Continue));

                    if (base.LastTask.Exception != null)
                    {
                        if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
                        {
                            throw base.LastTask.Exception;
                        }
                        WebSocketTransportSettings webSocketTransportSetting1 = new WebSocketTransportSettings(this.relay.serviceBusUri);
                        AmqpTransportInitiator     amqpTransportInitiator3    = new AmqpTransportInitiator(amqpSetting, webSocketTransportSetting1);
                        yield return(base.CallTask(amqpTransportInitiator3.ConnectTaskAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));
                    }
                }
                TransportBase transportBase = base.LastTaskResult <TransportBase>();

                string[] strArrays = host.Split(new char[] { '.' });
                strArrays[0] = string.Concat(strArrays[0], "-relay");
                AmqpConnectionSettings amqpConnectionSetting = new AmqpConnectionSettings()
                {
                    ContainerId = Guid.NewGuid().ToString(),
                    HostName    = string.Join(".", strArrays)
                };

                this.relay.connection = new AmqpConnection(transportBase, amqpSetting, amqpConnectionSetting);
                yield return(base.CallTask(this.relay.connection.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                AmqpSessionSettings amqpSessionSetting = new AmqpSessionSettings();
                AmqpSession         amqpSession        = this.relay.connection.CreateSession(amqpSessionSetting);

                yield return(base.CallTask(amqpSession.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                AmqpLinkSettings amqpLinkSetting = new AmqpLinkSettings()
                {
                    Role = new bool?(false),
                    InitialDeliveryCount = new uint?(0),
                    LinkName             = string.Concat("HttpRelayServer_Link_", Guid.NewGuid()),
                    Target          = new Target(this.relay.serviceBusUri),
                    Source          = new Source(this.relay.serviceBusUri),
                    TotalLinkCredit = 1000,
                    AutoSendFlow    = true
                };
                AmqpLinkSettings amqpLinkSetting1 = amqpLinkSetting;

                if (this.relay.tokenRenewer != null)
                {
                    amqpLinkSetting1.AddProperty(AmqpConstants.SimpleWebTokenPropertyName, this.relay.tokenRenewer.CurrentToken.Token);
                }
                if (!this.relay.TransportSecurityRequired)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.TransportSecurityRequiredName, false);
                }
                if (!this.relay.RelayClientAuthorizationRequired)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.ClientAuthenticationRequiredName, false);
                }
                if (this.relay.PublishToRegistry)
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.RequiresPublicRegistry, true);
                }
                if (!string.IsNullOrEmpty(this.relay.ClientAgent))
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.ClientAgent, this.relay.ClientAgent);
                }
                if (!string.IsNullOrEmpty(this.relay.DisplayName))
                {
                    amqpLinkSetting1.AddProperty(ClientConstants.DisplayName, this.relay.DisplayName);
                }
                amqpLinkSetting1.AddProperty(ClientConstants.DynamicRelay, this.relay.IsDynamic);
                amqpLinkSetting1.AddProperty(ClientConstants.ListenerTypeName, this.relay.ListenerType.ToString());
                this.relay.link = new DuplexAmqpLink(amqpSession, amqpLinkSetting1);
                yield return(base.CallTask(this.relay.link.OpenAsync(timeoutHelper.RemainingTime()), IteratorTask <TResult> .ExceptionPolicy.Transfer));

                this.relay.link.SafeAddClosed(this.relay.onAmqpObjectClosed);
                this.relay.link.RegisterMessageListener((AmqpMessage msg) => this.relay.messageListener(this.relay.link, msg));
                this.relay.OnOnline();
Label0:
                yield break;
            }
Beispiel #28
0
        /// <summary>
        /// Opens a connection to the specified address.
        /// </summary>
        /// <param name="addressUri">The address Uri. User info is ignored.</param>
        /// <param name="saslHandler">The SASL handler which determines the SASL mechanism. Null means no SASL handshake.</param>
        /// <param name="timeout">The operation timeout.</param>
        /// <returns>An AMQP connection.</returns>
        public async Task <AmqpConnection> OpenConnectionAsync(Uri addressUri, SaslHandler saslHandler, TimeSpan timeout)
        {
            TransportSettings transportSettings;

            if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqp, StringComparison.OrdinalIgnoreCase))
            {
                transportSettings = new TcpTransportSettings()
                {
                    Host = addressUri.Host,
                    Port = addressUri.Port > -1 ? addressUri.Port : AmqpConstants.DefaultPort
                };
            }
            else if (addressUri.Scheme.Equals(AmqpConstants.SchemeAmqps, StringComparison.OrdinalIgnoreCase))
            {
                TcpTransportSettings tcpSettings = new TcpTransportSettings()
                {
                    Host = addressUri.Host,
                    Port = addressUri.Port > -1 ? addressUri.Port : AmqpConstants.DefaultSecurePort
                };

                var tls = new TlsTransportSettings(tcpSettings)
                {
                    TargetHost = addressUri.Host
                };
                TlsTransportProvider tlsProvider = this.settings.GetTransportProvider <TlsTransportProvider>();
                if (tlsProvider != null)
                {
                    tls.CertificateValidationCallback = tlsProvider.Settings.CertificateValidationCallback;
                    tls.CheckCertificateRevocation    = tlsProvider.Settings.CheckCertificateRevocation;
                    tls.Certificate = tlsProvider.Settings.Certificate;
                    tls.Protocols   = tlsProvider.Settings.Protocols;
                }

                transportSettings = tls;
            }
            else if (addressUri.Scheme.Equals(WebSocketTransportSettings.WebSockets, StringComparison.OrdinalIgnoreCase) ||
                     addressUri.Scheme.Equals(WebSocketTransportSettings.SecureWebSockets, StringComparison.OrdinalIgnoreCase))
            {
                transportSettings = new WebSocketTransportSettings()
                {
                    Uri = addressUri
                };
            }
            else
            {
                throw new NotSupportedException(addressUri.Scheme);
            }

            AmqpSettings settings = this.settings.Clone();

            settings.TransportProviders.Clear();

            if (saslHandler != null)
            {
                // Provider for "AMQP3100"
                SaslTransportProvider saslProvider = new SaslTransportProvider(AmqpVersion.V100);
                saslProvider.AddHandler(saslHandler);
                settings.TransportProviders.Add(saslProvider);
            }

            // Provider for "AMQP0100"
            AmqpTransportProvider amqpProvider = new AmqpTransportProvider(AmqpVersion.V100);

            settings.TransportProviders.Add(amqpProvider);

            AmqpTransportInitiator initiator = new AmqpTransportInitiator(settings, transportSettings);
            TransportBase          transport = await Task.Factory.FromAsync(
                (c, s) => initiator.BeginConnect(timeout, c, s),
                (r) => initiator.EndConnect(r),
                null).ConfigureAwait(false);

            try
            {
                AmqpConnectionSettings connectionSettings = new AmqpConnectionSettings()
                {
                    ContainerId = Guid.NewGuid().ToString(),
                    HostName    = addressUri.Host
                };

                AmqpConnection connection = new AmqpConnection(transport, settings, connectionSettings);
                await connection.OpenAsync(timeout).ConfigureAwait(false);

                return(connection);
            }
            catch
            {
                transport.Abort();
                throw;
            }
        }
        public async Task OpenAsync(TimeSpan timeout, bool useWebSocket, X509Certificate2 clientCert, IWebProxy proxy, RemoteCertificateValidationCallback remoteCerificateValidationCallback)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}");
            }

            var hostName = _uri.Host;

            var tcpSettings = new TcpTransportSettings {
                Host = hostName, Port = _uri.Port != -1 ? _uri.Port : AmqpConstants.DefaultSecurePort
            };

            TransportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost  = hostName,
                Certificate = clientCert,
                CertificateValidationCallback = remoteCerificateValidationCallback,
            };

            TransportBase transport;

            if (useWebSocket)
            {
                transport = await CreateClientWebSocketTransportAsync(timeout, proxy).ConfigureAwait(false);

                SaslTransportProvider provider = _amqpSettings.GetTransportProvider <SaslTransportProvider>();
                if (provider != null)
                {
                    if (Logging.IsEnabled)
                    {
                        Logging.Info(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: Using SaslTransport");
                    }

                    _sentHeader = new ProtocolHeader(provider.ProtocolId, provider.DefaultVersion);
                    ByteBuffer buffer = new ByteBuffer(new byte[AmqpConstants.ProtocolHeaderSize]);
                    _sentHeader.Encode(buffer);

                    _tcs = new TaskCompletionSource <TransportBase>();

                    var args = new TransportAsyncCallbackArgs();
                    args.SetBuffer(buffer.Buffer, buffer.Offset, buffer.Length);
                    args.CompletedCallback = OnWriteHeaderComplete;
                    args.Transport         = transport;
                    bool operationPending = transport.WriteAsync(args);

                    if (Logging.IsEnabled)
                    {
                        Logging.Info(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}: Sent Protocol Header: {_sentHeader.ToString()} operationPending: {operationPending} completedSynchronously: {args.CompletedSynchronously}");
                    }

                    if (!operationPending)
                    {
                        args.CompletedCallback(args);
                    }

                    transport = await _tcs.Task.ConfigureAwait(false);

                    await transport.OpenAsync(timeout).ConfigureAwait(false);
                }
            }
            else
            {
                var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings);
                transport = await tcpInitiator.ConnectTaskAsync(timeout).ConfigureAwait(false);
            }

            AmqpConnection         = new AmqpConnection(transport, _amqpSettings, AmqpConnectionSettings);
            AmqpConnection.Closed += OnConnectionClosed;
            await AmqpConnection.OpenAsync(timeout).ConfigureAwait(false);

            _isConnectionClosed = false;
        }
        /// <summary>
        /// Performs the tasks needed to build and open a connection to the IoT Hub
        /// service.
        /// </summary>
        /// <param name="serviceEndpoint">The endpoint of the IoT Hub service to connect to.</param>
        /// <param name="iotHubName">The name of the IoT Hub to connect to.</param>
        /// <param name="sharedAccessKeyName">The name of the shared access key being used for authentication.</param>
        /// <param name="sharedAccessKey">The shared access key being used for authentication.</param>
        /// <param name="timeout">The maximum amount of time that establishing the connection should be allowed to take.</param>
        /// <returns>An <see cref="AmqpConnection" /> to the requested IoT Hub.</returns>
        /// <seealso href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-amqp-support"/>
        private static async Task <AmqpConnection> CreateAndOpenConnectionAsync(
            Uri serviceEndpoint,
            string iotHubName,
            string sharedAccessKeyName,
            string sharedAccessKey,
            TimeSpan timeout)
        {
            var hostName  = serviceEndpoint.Host;
            var userName  = $"{ sharedAccessKeyName }@sas.root.{ iotHubName }";
            var signature = BuildSignature($"{ hostName }{ serviceEndpoint.AbsolutePath }", sharedAccessKeyName, sharedAccessKey, TimeSpan.FromMinutes(5));
            var port      = 5671;

            // Create the layers of settings needed to establish the connection.

            var amqpVersion = new Version(1, 0, 0, 0);

            var tcpSettings = new TcpTransportSettings
            {
                Host = hostName,
                Port = port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            var transportSettings = new TlsTransportSettings(tcpSettings)
            {
                TargetHost = hostName,
            };

            var connectionSettings = new AmqpConnectionSettings
            {
                IdleTimeOut  = (uint)TimeSpan.FromMinutes(1).TotalMilliseconds,
                MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                ContainerId  = Guid.NewGuid().ToString(),
                HostName     = hostName
            };

            var saslProvider = new SaslTransportProvider();

            saslProvider.Versions.Add(new AmqpVersion(amqpVersion));
            saslProvider.AddHandler(new SaslPlainHandler {
                AuthenticationIdentity = userName, Password = signature
            });

            var amqpProvider = new AmqpTransportProvider();

            amqpProvider.Versions.Add(new AmqpVersion(amqpVersion));

            var amqpSettings = new AmqpSettings();

            amqpSettings.TransportProviders.Add(saslProvider);
            amqpSettings.TransportProviders.Add(amqpProvider);

            // Create and open the connection, respecting the timeout constraint
            // that was received.

            var stopWatch = Stopwatch.StartNew();
            var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
            var transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false);

            try
            {
                var connection = new AmqpConnection(transport, amqpSettings, connectionSettings);
                await connection.OpenAsync(timeout.Subtract(stopWatch.Elapsed)).ConfigureAwait(false);

                return(connection);
            }
            catch
            {
                transport.Abort();
                throw;
            }
            finally
            {
                stopWatch.Stop();
            }
        }
Beispiel #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;
        }