async Task <AmqpConnection> CreateConnectionAsync(TimeSpan timeout)
        {
            string hostName    = this.Endpoint.Host;
            string networkHost = this.Endpoint.Host;
            int    port        = this.Endpoint.Port;

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            AmqpSettings  amqpSettings  = AmqpConnectionHelper.CreateAmqpSettings(
                amqpVersion: AmqpVersion,
                useSslStreamSecurity: true,
                hasTokenProvider: true);

            TransportSettings tpSettings = AmqpConnectionHelper.CreateTcpTransportSettings(
                networkHost: networkHost,
                hostName: hostName,
                port: port,
                useSslStreamSecurity: true);

            AmqpTransportInitiator initiator = new AmqpTransportInitiator(amqpSettings, tpSettings);
            TransportBase          transport = await initiator.ConnectTaskAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            string containerId = Guid.NewGuid().ToString();
            AmqpConnectionSettings amqpConnectionSettings = AmqpConnectionHelper.CreateAmqpConnectionSettings(AmqpConstants.DefaultMaxFrameSize, containerId, hostName);
            AmqpConnection         connection             = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
            await connection.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

            // Always create the CBS Link + Session
            AmqpCbsLink cbsLink = new AmqpCbsLink(connection);

            if (connection.Extensions.Find <AmqpCbsLink>() == null)
            {
                connection.Extensions.Add(cbsLink);
            }

            MessagingEventSource.Log.AmqpConnectionCreated(hostName, connection);

            return(connection);
        }
        internal static TransportBase AcceptServerTransport(TransportSettings settings)
        {
            ManualResetEvent complete = new ManualResetEvent(false);
            int           closed      = 0;
            TransportBase transport   = null;

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

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

            TransportListener listener = settings.CreateListener();

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

            complete.WaitOne();
            complete.Dispose();
            listener.Close();
            Debug.WriteLine("Listeners Closed.");

            return(transport);
        }
Beispiel #3
0
 internal AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, Microsoft.ServiceBus.Messaging.Amqp.AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : this(transport, protocolHeader, true, amqpSettings, connectionSettings)
 {
 }
Beispiel #4
0
 public AsyncFrameWriter(TransportBase transport, IIoHandler parent) : base(transport, parent)
 {
 }
Beispiel #5
0
 public NetworkServer(int serverPort, ushort maxConnections, int dataBufferSize, TransportBase transport)
 {
     _isActive       = false;
     ServerPort      = serverPort;
     _maxConnections = maxConnections;
     DataBufferSize  = dataBufferSize;
     InitializeServer();
     Transport = transport;
 }
Beispiel #6
0
        /// <summary>
        /// Creates an Uri instance from the given parameters.
        /// </summary>
        Uri IConnection.BuildUri(RequestTypes type, TransportBase transport)
        {
            lock (SyncRoot)
            {
                // make sure that the queryBuilder is reseted
                queryBuilder.Length = 0;

                UriBuilder uriBuilder = new UriBuilder(Uri);

                if (!uriBuilder.Path.EndsWith("/"))
                {
                    uriBuilder.Path += "/";
                }

                this.RequestCounter %= UInt64.MaxValue;

                switch (type)
                {
                case RequestTypes.Negotiate:
                    uriBuilder.Path += "negotiate";
                    goto default;

                case RequestTypes.Connect:
#if !BESTHTTP_DISABLE_WEBSOCKET
                    if (transport != null && transport.Type == TransportTypes.WebSocket)
                    {
                        uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
                    }
#endif

                    uriBuilder.Path += "connect";
                    goto default;

                case RequestTypes.Start:
                    uriBuilder.Path += "start";
                    goto default;

                case RequestTypes.Poll:
                    uriBuilder.Path += "poll";
                    if (this.LastReceivedMessage != null)
                    {
                        queryBuilder.Append("messageId=");
                        queryBuilder.Append(this.LastReceivedMessage.MessageId);
                    }
                    goto default;

                case RequestTypes.Send:
                    uriBuilder.Path += "send";
                    goto default;

                case RequestTypes.Reconnect:
#if !BESTHTTP_DISABLE_WEBSOCKET
                    if (transport != null && transport.Type == TransportTypes.WebSocket)
                    {
                        uriBuilder.Scheme = HTTPProtocolFactory.IsSecureProtocol(Uri) ? "wss" : "ws";
                    }
#endif

                    uriBuilder.Path += "reconnect";

                    if (this.LastReceivedMessage != null)
                    {
                        queryBuilder.Append("messageId=");
                        queryBuilder.Append(this.LastReceivedMessage.MessageId);
                    }

                    if (!string.IsNullOrEmpty(GroupsToken))
                    {
                        if (queryBuilder.Length > 0)
                        {
                            queryBuilder.Append("&");
                        }

                        queryBuilder.Append("groupsToken=");
                        queryBuilder.Append(GroupsToken);
                    }

                    goto default;

                case RequestTypes.Abort:
                    uriBuilder.Path += "abort";
                    goto default;

                case RequestTypes.Ping:
                    uriBuilder.Path += "ping";

                    queryBuilder.Append("&tid=");
                    queryBuilder.Append(this.RequestCounter++.ToString());

                    queryBuilder.Append("&_=");
                    queryBuilder.Append(Timestamp.ToString());

                    break;

                default:
                    if (queryBuilder.Length > 0)
                    {
                        queryBuilder.Append("&");
                    }

                    queryBuilder.Append("tid=");
                    queryBuilder.Append(this.RequestCounter++.ToString());

                    queryBuilder.Append("&_=");
                    queryBuilder.Append(Timestamp.ToString());

                    if (transport != null)
                    {
                        queryBuilder.Append("&transport=");
                        queryBuilder.Append(transport.Name);
                    }

                    queryBuilder.Append("&clientProtocol=");
                    queryBuilder.Append(ClientProtocols[(byte)Protocol]);

                    if (NegotiationResult != null && !string.IsNullOrEmpty(this.NegotiationResult.ConnectionToken))
                    {
                        queryBuilder.Append("&connectionToken=");
                        queryBuilder.Append(this.NegotiationResult.ConnectionToken);
                    }

                    if (this.Hubs != null && this.Hubs.Length > 0)
                    {
                        queryBuilder.Append("&connectionData=");
                        queryBuilder.Append(this.ConnectionData);
                    }

                    break;
                }

                // Query params are added to all uri
                if (this.AdditionalQueryParams != null && this.AdditionalQueryParams.Count > 0)
                {
                    queryBuilder.Append(this.QueryParams);
                }

                uriBuilder.Query = queryBuilder.ToString();

                // reset the string builder
                queryBuilder.Length = 0;

                return(uriBuilder.Uri);
            }
        }
 protected override TransportBase OnCreateTransport(TransportBase innerTransport, bool isInitiator)
 {
     return(new SaslTransport(innerTransport, this, isInitiator));
 }
Beispiel #8
0
 public AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) :
     this(transport, protocolHeader, true, amqpSettings, connectionSettings)
 {
 }
Beispiel #9
0
 AmqpConnection IConnectionFactory.CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
 {
     throw new NotImplementedException();
 }
Beispiel #10
0
 public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader,
                                        bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
 {
     return(new AmqpConnection(transport, protocolHeader, false, amqpSettings, connectionSettings));
 }
Beispiel #11
0
 public AsyncBufferReader(TransportBase transport)
 {
     this.transport = transport;
 }
Beispiel #12
0
 public AsyncBufferWriter(TransportBase transport)
 {
     this.transport = transport;
 }
 public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
 {
     connectionSettings.ContainerId = this.GetType().Name;
     return(new AmqpConnection(transport, protocolHeader, false, amqpSettings, connectionSettings));
 }
Beispiel #14
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;
            }
        }
Beispiel #15
0
 public FrameBufferReader(IIoHandler parent, TransportBase transport)
 {
     this.parent     = parent;
     this.transport  = transport;
     this.sizeBuffer = new byte[4];
 }
Beispiel #16
0
 public AsyncBufferReader(TransportBase transport)
 {
     this.transport      = transport;
     this.onReadComplete = this.OnReadComplete;
 }
Beispiel #17
0
 public SaslTransport(TransportBase transport, SaslTransportProvider provider, bool isInitiator)
 {
     this.innerTransport = transport;
     this.provider       = provider;
     this.isInitiator    = isInitiator;
 }
Beispiel #18
0
 public AsyncBufferWriter(TransportBase transport)
 {
     this.transport       = transport;
     this.onWriteComplete = this.OnWriteComplete;
 }
Beispiel #19
0
        public async Task OpenAsync(
            bool useWebSocket,
            X509Certificate2 clientCert,
            IWebProxy proxy,
            RemoteCertificateValidationCallback remoteCerificateValidationCallback,
            CancellationToken cancellationToken)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, $"{nameof(AmqpClientConnection)}.{nameof(OpenAsync)}");
            }

            string 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,
            };

            if (useWebSocket)
            {
                _transport = await CreateClientWebSocketTransportAsync(proxy, cancellationToken).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);
                    using var 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} operationPending: {operationPending} completedSynchronously: {args.CompletedSynchronously}");
                    }

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

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

                    await _transport.OpenAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            else
            {
                var tcpInitiator = new AmqpTransportInitiator(_amqpSettings, TransportSettings);
                _transport = await tcpInitiator.ConnectAsync(cancellationToken).ConfigureAwait(false);
            }

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

            IsConnectionClosed = false;
        }
 protected override TransportBase OnCreateTransport(TransportBase innerTransport, bool isInitiator)
 {
     return innerTransport;
 }
Beispiel #21
0
            public void RunServerTest(TransportTestContext testContext)
            {
                this.testContext = testContext;
                this.testContext.Success = true;
                this.transport = AcceptServerTransport(testContext.TransportSettings);

                try
                {
                    int expect = 1;
                    while (expect > 0)
                    {
                        int num = this.Read();
                        if (num == 0)
                        {
                            if (expect < this.testContext.MaxNumber)
                            {
                                Debug.WriteLine(string.Format("Got eof before finishing all numbers (expect={0})", expect));
                                this.testContext.Success = false;
                            }

                            break;
                        }
                        else if (num != expect)
                        {
                            Debug.WriteLine(string.Format("Expect {0} but got {1}", expect, num));
                            this.testContext.Success = false;
                            break;
                        }

                        this.Write(expect * 2);
                        ++expect;
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine("Server got exception: " + exception.ToString());
                    this.testContext.Success = false;
                }

                this.transport.Close();
                Debug.WriteLine("Done server.");
            }
Beispiel #22
0
 public AmqpConnection(TransportBase transport, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) :
     this(transport, amqpSettings.GetDefaultHeader(), true, amqpSettings, connectionSettings)
 {
 }
Beispiel #23
0
            public void RunClientTest(TransportTestContext testContext)
            {
                this.testContext = testContext;
                this.testContext.Success = true;
                this.transport = EstablistClientTransport(testContext.TransportSettings);

                try
                {
                    for (int i = 1; i < this.testContext.MaxNumber; ++i)
                    {
                        this.Write(i);
                        int num = this.Read();
                        if (num != i * 2)
                        {
                            Debug.WriteLine(string.Format("Wrote {0} but got {1}", i, num));
                            this.testContext.Success = false;
                            break;
                        }
                    }
                }
                catch(Exception exception)
                {
                    Debug.WriteLine("Client got exception: " + exception.ToString());
                    this.testContext.Success = false;
                }

                this.transport.Close();
                Debug.WriteLine("Done client.");
            }
 protected override TransportBase OnCreateTransport(TransportBase innerTransport, bool isInitiator)
 {
     return(innerTransport);
 }
Beispiel #25
0
 public void ClientMethod(TransportBase transportBase)
 {
     System.Console.WriteLine(transportBase.PrintMessageAboutDelive());
 }
 public SaslTransport(TransportBase transport, SaslTransportProvider provider, bool isInitiator) : base("sasl")
 {
     this.innerTransport = transport;
     this.negotiator     = new SaslNegotiator(this, provider, isInitiator);
 }
Beispiel #27
0
 public TestHelperAmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, bool
                                 isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
     : base(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings)
 {
 }
Beispiel #28
0
 internal AmqpConnection(TransportBase transport, Microsoft.ServiceBus.Messaging.Amqp.AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) : this(transport, amqpSettings.GetDefaultHeader(), true, amqpSettings, connectionSettings)
 {
 }
Beispiel #29
0
 public AsyncFrameWriter(TransportBase transport, int writeQueueFullLimit, int writeQueueEmptyLimit, IIoHandler parent)
     : base(transport, writeQueueFullLimit, writeQueueEmptyLimit, parent)
 {
 }
Beispiel #30
0
 public AmqpFrameConnection(AmqpStream parent, TransportBase transport, int maxFrameSize) :
     base(transport, new AmqpConnectionSettings() { MaxFrameSize = (uint)maxFrameSize })
 {
     this.parent  = parent;
     this.decoder = new FrameDecoder(maxFrameSize);
 }
Beispiel #31
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;
            }
        private async Task <AmqpSession> CreateSessionAsync(TimeSpan timeout)
        {
            Logging.Enter(this, timeout, nameof(CreateSessionAsync));

            TransportBase transport = null;

            try
            {
                var timeoutHelper = new TimeoutHelper(timeout);
                _refreshTokenTimer.Cancel();

                AmqpSettings amqpSettings = CreateAmqpSettings();
                if (_useWebSocketOnly)
                {
                    // Try only AMQP transport over WebSocket
                    transport = _clientWebSocketTransport = (ClientWebSocketTransport) await CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime())
                                                            .ConfigureAwait(false);
                }
                else
                {
                    TlsTransportSettings tlsTransportSettings = CreateTlsTransportSettings();
                    var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, tlsTransportSettings);
                    try
                    {
                        transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                    }
                    catch (Exception e) when(!(e is AuthenticationException))
                    {
                        Logging.Error(this, e, nameof(CreateSessionAsync));

                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }

                        // AMQP transport over TCP failed. Retry AMQP transport over WebSocket
                        if (timeoutHelper.RemainingTime() != TimeSpan.Zero)
                        {
                            transport = _clientWebSocketTransport = (ClientWebSocketTransport) await CreateClientWebSocketTransportAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                Logging.Info(this, $"Initialized {nameof(TransportBase)}, ws={_useWebSocketOnly}");

                var amqpConnectionSettings = new AmqpConnectionSettings
                {
                    MaxFrameSize = AmqpConstants.DefaultMaxFrameSize,
                    ContainerId  = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture), // Use a human readable link name to help with debugging
                    HostName     = ConnectionString.AmqpEndpoint.Host,
                };

                var amqpConnection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
                await amqpConnection.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                Logging.Info(this, $"{nameof(AmqpConnection)} opened.");

                var sessionSettings = new AmqpSessionSettings
                {
                    Properties = new Fields(),
                };

                try
                {
                    AmqpSession amqpSession = amqpConnection.CreateSession(sessionSettings);
                    await amqpSession.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    Logging.Info(this, $"{nameof(AmqpSession)} opened.");

                    // This adds itself to amqpConnection.Extensions
                    var cbsLink = new AmqpCbsLink(amqpConnection);
                    await SendCbsTokenAsync(cbsLink, timeoutHelper.RemainingTime()).ConfigureAwait(false);

                    return(amqpSession);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    Logging.Error(this, ex, nameof(CreateSessionAsync));

                    _clientWebSocketTransport?.Dispose();
                    _clientWebSocketTransport = null;

                    if (amqpConnection.TerminalException != null)
                    {
                        throw AmqpClientHelper.ToIotHubClientContract(amqpConnection.TerminalException);
                    }

                    amqpConnection.SafeClose(ex);
                    throw;
                }
            }
            finally
            {
                Logging.Exit(this, timeout, nameof(CreateSessionAsync));
            }
        }
Beispiel #33
0
 public AmqpConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings) :
     this((isInitiator ? "out" : "in") + "-connection", transport, protocolHeader, isInitiator, amqpSettings, connectionSettings)
 {
 }