Exemplo n.º 1
0
 public PendingPublish(ConnectionContext connectionContext, string exchange, ulong publishTag)
 {
     _connectionContext = connectionContext;
     _exchange = exchange;
     _publishTag = publishTag;
     _source = new TaskCompletionSource<ulong>();
 }
Exemplo n.º 2
0
        public JsonResult GetRoles(string id)
        {
            var usr = Membership.GetUser(id);
            if (usr == null)
                return Json(null);

            using (var db = new ConnectionContext())
            {
                var roles = Roles.GetRolesForUser(usr.UserName);

                var roleChecks = from x in db.Facults
                                 orderby x.FacultId
                                 select new RoleCheck
                                 {
                                     Name = x.Name,
                                     RoleCheckId = SqlFunctions.StringConvert((double)x.FacultId).Trim(),
                                     IsChecked = roles.Contains(SqlFunctions.StringConvert((double)x.FacultId).Trim())
                                 };

                var model = new Member
                {
                    UserName = usr.UserName,
                    RoleChecks = (roleChecks).ToList()
                };
                model.RoleChecks.Add(new RoleCheck
                {
                    Name = "Администратор",
                    RoleCheckId = StaticData.AdminRoleName,
                    IsChecked = Roles.IsUserInRole(usr.UserName, StaticData.AdminRoleName),
                });

                return Json(model);
            }
        }
Exemplo n.º 3
0
 public ConnectionContext(ConnectionContext context)
     : base(context)
 {
     SocketInput = context.SocketInput;
     SocketOutput = context.SocketOutput;
     ConnectionControl = context.ConnectionControl;
 }
 public MessageSessionAsyncHandler(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, BrokeredMessage message)
 {
     _context = context;
     _supervisor = supervisor;
     _receiver = receiver;
     _session = session;
     _message = message;
 }
Exemplo n.º 5
0
		public Channel<ConnectionContext> GetChannel(ConnectionContext context)
		{
			string requestUri = context.GetRequestUri();

			Match match = _uriPatternMatcher.Match(requestUri);

			if (false == match.Success ||
			    false == _verbsSupported.Contains(context.Request.HttpMethod))
				return null;

			return CreateChannel(context);
		}
        static IEnumerable<ValueProvider> GetProvidersForConnection(ConnectionContext connectionContext)
        {
            if (connectionContext.Request.Cookies.Count > 0)
                yield return GetCookieCollection(connectionContext.Request);

            if (connectionContext.Request.ContentType.StartsWith("application/json"))
                yield return new JsonValueProvider(connectionContext.Request.InputStream);

            if (connectionContext.Request.QueryString.Count > 0)
                yield return GetQueryStringCollection(connectionContext.Request);

            if (connectionContext.Request.Headers.Count > 0)
                yield return GetHeaderCollection(connectionContext.Request);

            yield return new RequestContextValueProvider(connectionContext.Request);
        }
Exemplo n.º 7
0
        public SessionReceiver(ConnectionContext context, QueueClient queueClient, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings, IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _queueClient = queueClient;
            _inputAddress = inputAddress;
            _receivePipe = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;

            _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {inputAddress}", Stop);

            var options = new SessionHandlerOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = receiveSettings.AutoRenewTimeout,
                MaxConcurrentSessions = receiveSettings.MaxConcurrentCalls,
                MessageWaitTimeout = receiveSettings.MessageWaitTimeout
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Exception received on session receiver: {_inputAddress} during {x.Action}", x.Exception);
                }

                if (_currentPendingDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Session receiver shutdown completed: {0}", _inputAddress);

                    _participant.SetComplete();
                }
            };

            IMessageSessionAsyncHandlerFactory handlerFactory = new MessageSessionAsyncHandlerFactory(context, supervisor, this);
            queueClient.RegisterSessionHandlerFactoryAsync(handlerFactory, options);

            _participant.SetReady();
        }
Exemplo n.º 8
0
        public Receiver(ConnectionContext context, MessageReceiver messageReceiver, Uri inputAddress, IPipe<ReceiveContext> receivePipe, ReceiveSettings receiveSettings,
            IReceiveObserver receiveObserver, ITaskSupervisor supervisor)
        {
            _context = context;
            _messageReceiver = messageReceiver;
            _inputAddress = inputAddress;
            _receivePipe = receivePipe;
            _receiveSettings = receiveSettings;
            _receiveObserver = receiveObserver;

            _participant = supervisor.CreateParticipant($"{TypeMetadataCache<Receiver>.ShortName} - {inputAddress}", Stop);

            var options = new OnMessageOptions
            {
                AutoComplete = false,
                AutoRenewTimeout = receiveSettings.AutoRenewTimeout,
                MaxConcurrentCalls = receiveSettings.MaxConcurrentCalls
            };

            options.ExceptionReceived += (sender, x) =>
            {
                if (!(x.Exception is OperationCanceledException))
                {
                    if (_log.IsErrorEnabled)
                        _log.Error($"Exception received on receiver: {_inputAddress} during {x.Action}", x.Exception);
                }

                if (_currentPendingDeliveryCount == 0)
                {
                    if (_log.IsDebugEnabled)
                        _log.DebugFormat("Receiver shutdown completed: {0}", _inputAddress);

                    _participant.SetComplete();
                }
            };

            messageReceiver.OnMessageAsync(OnMessage, options);

            _participant.SetReady();
        }
        RabbitMqModelContext(ConnectionContext connectionContext, IModel model, IRabbitMqHost host, ITaskParticipant participant)
            : base(new PayloadCacheScope(connectionContext))
        {
            _connectionContext = connectionContext;
            _model = model;
            _host = host;

            _participant = participant;

            _published = new ConcurrentDictionary<ulong, PendingPublish>();
            _taskScheduler = new LimitedConcurrencyLevelTaskScheduler(1);

            _model.ModelShutdown += OnModelShutdown;
            _model.BasicAcks += OnBasicAcks;
            _model.BasicNacks += OnBasicNacks;
            _model.BasicReturn += OnBasicReturn;

            if (host.Settings.PublisherConfirmation)
            {
                _model.ConfirmSelect();
            }

            _participant.SetReady();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Assigns aSource to this instance of <see cref="UserToken"/>.
        /// </summary>
        /// <param name="aSource">A source object.</param>
        public override void AssignFromSource(object aSource)
        {
            if (!(aSource is AdminToken))
            {
                throw new ArgumentException("Invalid Assignment Source for AdminToken");
            }

            _userID = (aSource as AdminToken)._userID;
            _password = (aSource as AdminToken)._password;
            _url = (aSource as AdminToken)._url;
            _method = (aSource as AdminToken)._method;
            _context = (aSource as AdminToken)._context;
            _version = (aSource as AdminToken)._version;
        }
Exemplo n.º 11
0
		protected abstract Channel<ConnectionContext> CreateChannel(ConnectionContext context);
Exemplo n.º 12
0
 public Task OnConnectionAsync(ConnectionContext context)
 {
     return(Task.Run(() => InnerOnConnectionAsync(context)));
 }
Exemplo n.º 13
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var protocol         = new MessageReaderWriter();
            var reader           = connection.CreateReader();
            var writer           = connection.CreateWriter();
            var connectionTopics = new List <string>();

            try
            {
                while (true)
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    switch (message.MessageType)
                    {
                    case MessageType.Publish:
                    {
                        if (_topics.TryGetValue(message.Topic, out var topic))
                        {
                            var data = new Message
                            {
                                MessageType = MessageType.Data,
                                Payload     = message.Payload,
                                Topic       = message.Topic
                            };

                            topic.IncrementPublish();

                            // TODO: Use WhenAll
                            foreach (var pair in topic)
                            {
                                await pair.Value.WriteAsync(protocol, data);
                            }
                        }

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    case MessageType.Subscribe:
                    {
                        var topic = _topics.GetOrAdd(message.Topic);

                        topic.Add(connection.ConnectionId, writer);

                        connectionTopics.Add(message.Topic);

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    case MessageType.Unsubscribe:
                    {
                        RemoveTopic(connection, connectionTopics, message.Topic);

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    default:
                        break;
                    }

                    reader.Advance();
                }
            }
            finally
            {
                for (int i = connectionTopics.Count - 1; i >= 0; i--)
                {
                    RemoveTopic(connection, connectionTopics, connectionTopics[i]);
                }
            }
        }
Exemplo n.º 14
0
 public RabbitMqModelContext(ConnectionContext connectionContext, IModel model, ITaskScope taskScope, IRabbitMqHost host)
     : this(connectionContext, model, host,
            taskScope.CreateParticipant($"{TypeMetadataCache<RabbitMqModelContext>.ShortName} - {connectionContext.HostSettings.ToDebugString()}"))
 {
 }
Exemplo n.º 15
0
 public WebSocketProtocol(WebSocket websocket, ConnectionContext connection)
 {
     WebSocket  = websocket;
     Connection = connection;
 }
 public static MockHubConnectionContext CreateMock(ConnectionContext connection)
 {
     return(new MockHubConnectionContext(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance, TimeSpan.FromSeconds(15)));
 }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Main: {0}", Thread.CurrentThread.ManagedThreadId);

            // Use the factory
            LibuvTransportContext transport = new LibuvTransportContext
            {
                Options     = new LibuvTransportOptions(),
                AppLifetime = new ApplicationLifetime(null),
                Log         = new LibuvTrace(LoggerFactory.Create(builder =>
                {
                    builder.AddConsole();
                }).CreateLogger("core"))
            };

            LibuvThread uvThread = new LibuvThread(libUv, transport);

            uvThread.StartAsync().Wait();

            Task.Run(async() =>
            {
                Console.WriteLine("NIO: {0}", Thread.CurrentThread.ManagedThreadId);

                LibuvConnectionListener listener = new LibuvConnectionListener(libUv, transport, new IPEndPoint(IPAddress.Parse("0.0.0.0"), 2593));
                Console.WriteLine("Binding... ({0})", Thread.CurrentThread.ManagedThreadId);
                await listener.BindAsync();

                Console.WriteLine("Listening... ({0})", Thread.CurrentThread.ManagedThreadId);
                ConnectionContext connectionContext = await listener.AcceptAsync();
                Console.WriteLine("Accepted Connection from {0}", connectionContext.RemoteEndPoint);
                PipeReader reader = connectionContext.Transport.Input;

                while (true)
                {
                    ReadResult readResult = await reader.ReadAsync();
                    int packetId          = readResult.Buffer.FirstSpan[0];
                    Console.WriteLine($"[0x{packetId:X}] Processing Packet");
                    int length     = PacketLengths[packetId];
                    int bodyLength = length - 1;
                    int bodyStart  = 1;
                    if (length == 0)
                    {
                        length     = BinaryPrimitives.ReadUInt16BigEndian(readResult.Buffer.FirstSpan.Slice(1, 2));
                        bodyLength = length - 3;
                        bodyStart  = 3;
                    }
                    else if (length == 0xFFFF)
                    {
                        Console.WriteLine($"[0x{packetId:X}] Unknown Packet");
                        throw new Exception($"[0x{packetId:X}] Unknown Packet");
                    }
                    Console.WriteLine($"[0x{packetId:X}] Found length {length}");
                    Console.WriteLine($"Packet Data: {ByteArrayToString(readResult.Buffer.FirstSpan.ToArray()):X}");
                    Memory <byte> mem = new Memory <byte>(readResult.Buffer.FirstSpan.Slice(bodyStart, bodyLength).ToArray());
                    Console.WriteLine($"[0x{packetId:X}] Buffer length {mem.Length}");

                    _ = uvThread.PostAsync((Tuple <ConnectionContext, Memory <byte> > t) =>
                    {
                        // stuff
                        var(conn, mem) = t;
                        // Do stuff wtih memOwner.Memory.Span;
                        Console.WriteLine($"Packet ID: 0x{packetId:X} - Length: {length} - Data: 0x{ByteArrayToString(mem.ToArray())}");
                    }, Tuple.Create(connectionContext, mem));

                    reader.AdvanceTo(readResult.Buffer.GetPosition(length));
                }
            });

            // Manually putting something on the queue from another thread (or the main thread)
            uvThread.PostAsync <object>(_ =>
            {
                Console.WriteLine("Game: {0}", Thread.CurrentThread.ManagedThreadId);
            }, null);

            // Send an Initialization Request for Timers

            /*
             * uvThread.PostAsync<object>(_ =>
             * {
             * UvTimerHandle timerHandle = new UvTimerHandle(null);
             * timerHandle.Init(uvThread.Loop, (callback, handle) =>
             * {
             *  Console.WriteLine("Closed ({0})", Thread.CurrentThread.ManagedThreadId);
             * });
             * Console.WriteLine("Timer Stuff {0}", Thread.CurrentThread.ManagedThreadId);
             * int count = 10;
             * void cb2(UvTimerHandle handle)
             * {
             *  Console.WriteLine("Called!2 {0} ({1})", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
             *  timerHandle.Start(cb2, 2000, 0);
             * }
             * void cb1(UvTimerHandle handle)
             * {
             *  Console.WriteLine("Called!1 {0} ({1})", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
             *  count--;
             *  if (count < 0)
             *    timerHandle.Start(cb2, 2000, 0);
             *  else
             *    timerHandle.Start(cb1, 1000, 0);
             * }
             * timerHandle.Start(cb1, 1000, 0);
             * }, null);
             */

            Console.ReadLine();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Gets the <see cref="HttpContext"/> associated with the connection, if there is one.
 /// </summary>
 /// <param name="connection">The <see cref="ConnectionContext"/> representing the connection.</param>
 /// <returns>The <see cref="HttpContext"/> associated with the connection, or <see langword="null"/> if the connection is not HTTP-based.</returns>
 /// <remarks>
 /// SignalR connections can run on top of HTTP transports like WebSockets or Long Polling, or other non-HTTP transports. As a result,
 /// this method can sometimes return <see langword="null"/> depending on the configuration of your application.
 /// </remarks>
 public static HttpContext?GetHttpContext(this ConnectionContext connection)
 {
     return(connection.Features.Get <IHttpContextFeature>()?.HttpContext);
 }
Exemplo n.º 19
0
 public override async Task OnConnectedAsync(ConnectionContext connection)
 {
     while (await connection.Transport.In.WaitToReadAsync())
     {
     }
 }
Exemplo n.º 20
0
 public Channel <ConnectionContext> GetChannel(ConnectionContext message)
 {
     return(new BadRequestChannel());
 }
Exemplo n.º 21
0
 public override Task OnConnectedAsync(ConnectionContext connection)
 {
     return(Task.CompletedTask);
 }
Exemplo n.º 22
0
 public override Task OnConnectedAsync(ConnectionContext connection)
 {
     throw new InvalidOperationException();
 }
Exemplo n.º 23
0
 public override Task OnConnectedAsync(ConnectionContext connection)
 {
     connection.Transport.In.WaitToReadAsync().Wait();
     return(Task.CompletedTask);
 }
Exemplo n.º 24
0
        public override Task OnConnectedAsync(ConnectionContext connection)
        {
            var tcs = new TaskCompletionSource <object>();

            return(tcs.Task);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Returns a number expressing how closely the given shape matches the given context.
        ///
        /// Precondition: context is nonempty.
        /// </summary>
        /// <param name="shape"></param>
        /// <param name="context"></param>
        /// <returns>a double in the range [0, 1], where 1 represents a perfect match</returns>
        public double PercentMatched(Shape shape, ConnectionContext context)
        {
            List <string> neighborClasses = shape.ExternalConnectedShapes.ConvertAll(delegate(Shape s) { return(s.Classification); });

            return(PercentMatched(shape, context, neighborClasses));
        }
Exemplo n.º 26
0
 protected override Task DisposeConnection(ConnectionContext connection)
 {
     return(Task.CompletedTask);
 }
Exemplo n.º 27
0
 public DomainContext()
 {
     _ctx = new ConnectionContext();
 }
Exemplo n.º 28
0
        public static WebSocketProtocol CreateFromConnection(ConnectionContext connection, bool isServer, string subProtocol, TimeSpan keepAliveInterval)
        {
            var websocket = WebSocket.CreateFromStream(new DuplexPipeStream(connection.Transport.Input, connection.Transport.Output), isServer, subProtocol, keepAliveInterval);

            return(new WebSocketProtocol(websocket, connection));
        }
Exemplo n.º 29
0
 public byte[] BuildMessage(object obj, ConnectionContext context)
 {
     return(Encoding.ASCII.GetBytes(obj as string));
 }
Exemplo n.º 30
0
        void ConnectionComplete(ConnectionContext connectionContext)
        {
            connectionContext.End();

            int count = Interlocked.Decrement(ref _connectionCount);

            if (_closing)
            {
                if (count == 0)
                    ShutdownListener();
            }
        }
 public MessageSessionAsyncHandlerFactory(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver)
 {
     _context = context;
     _supervisor = supervisor;
     _receiver = receiver;
 }
 public SqlExecutionResult[] Run(ConnectionContext scriptExecutionContext, params DbParameter[] sqlParameters)
 {
     return SqlDatabaseTestClass.TestService.Execute(scriptExecutionContext, scriptExecutionContext, _action,
         sqlParameters);
 }
Exemplo n.º 33
0
    public (SslServerAuthenticationOptions, ClientCertificateMode) GetOptions(ConnectionContext connection, string serverName)
    {
        SniOptions?sniOptions = null;

        if (!string.IsNullOrEmpty(serverName) && !_exactNameOptions.TryGetValue(serverName, out sniOptions))
        {
            foreach (var(suffix, options) in _wildcardPrefixOptions)
            {
                if (serverName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
                {
                    sniOptions = options;
                    break;
                }
            }
        }

        // Fully wildcarded ("*") options can be used even when given an empty server name.
        sniOptions ??= _wildcardOptions;

        if (sniOptions is null)
        {
            if (serverName is null)
            {
                // There was no ALPN
                throw new AuthenticationException(CoreStrings.FormatSniNotConfiguredToAllowNoServerName(_endpointName));
            }
            else
            {
                throw new AuthenticationException(CoreStrings.FormatSniNotConfiguredForServerName(serverName, _endpointName));
            }
        }

        connection.Features.Set(new HttpProtocolsFeature(sniOptions.HttpProtocols));

        var sslOptions = sniOptions.SslOptions;

        if (sslOptions.ServerCertificate is null)
        {
            Debug.Assert(_fallbackServerCertificateSelector != null,
                         "The cached SniOptions ServerCertificate can only be null if there's a fallback certificate selector.");

            // If a ServerCertificateSelector doesn't return a cert, HttpsConnectionMiddleware doesn't fallback to the ServerCertificate.
            sslOptions = CloneSslOptions(sslOptions);
            var fallbackCertificate = _fallbackServerCertificateSelector(connection, serverName);

            if (fallbackCertificate != null)
            {
                HttpsConnectionMiddleware.EnsureCertificateIsAllowedForServerAuth(fallbackCertificate);
            }

            sslOptions.ServerCertificate = fallbackCertificate;
        }

        if (_onAuthenticateCallback != null)
        {
            // From doc comments: "This is called after all of the other settings have already been applied."
            sslOptions = CloneSslOptions(sslOptions);
            _onAuthenticateCallback(connection, sslOptions);
        }

        return(sslOptions, sniOptions.ClientCertificateMode);
    }
Exemplo n.º 34
0
        private async Task InnerOnConnectionAsync(ConnectionContext context)
        {
            bool certificateRequired;
            var  feature = new TlsConnectionFeature();

            context.Features.Set <ITlsConnectionFeature>(feature);
            context.Features.Set <ITlsHandshakeFeature>(feature);

            var memoryPool = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool;

            var inputPipeOptions = new StreamPipeReaderOptions
                                   (
                pool: memoryPool,
                bufferSize: memoryPool.GetMinimumSegmentSize(),
                minimumReadSize: memoryPool.GetMinimumAllocSize(),
                leaveOpen: true
                                   );

            var outputPipeOptions = new StreamPipeWriterOptions
                                    (
                pool: memoryPool,
                leaveOpen: true
                                    );

            SslDuplexPipe sslDuplexPipe = null;

            if (_options.RemoteCertificateMode == RemoteCertificateMode.NoCertificate)
            {
                sslDuplexPipe       = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
                certificateRequired = false;
            }
            else
            {
                sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions, s => new SslStream(
                                                      s,
                                                      leaveInnerStreamOpen: false,
                                                      userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) =>
                {
                    if (certificate == null)
                    {
                        return(_options.RemoteCertificateMode != RemoteCertificateMode.RequireCertificate);
                    }

                    if (_options.RemoteCertificateValidation == null)
                    {
                        if (sslPolicyErrors != SslPolicyErrors.None)
                        {
                            return(false);
                        }
                    }

                    var certificate2 = ConvertToX509Certificate2(certificate);
                    if (certificate2 == null)
                    {
                        return(false);
                    }

                    if (_options.RemoteCertificateValidation != null)
                    {
                        if (!_options.RemoteCertificateValidation(certificate2, chain, sslPolicyErrors))
                        {
                            return(false);
                        }
                    }

                    return(true);
                }));

                certificateRequired = true;
            }

            var sslStream = sslDuplexPipe.Stream;

            using (var cancellationTokeSource = new CancellationTokenSource(Debugger.IsAttached ? Timeout.InfiniteTimeSpan : _options.HandshakeTimeout))
            {
                try
                {
                    // Adapt to the SslStream signature
                    ServerCertificateSelectionCallback selector = null;
                    if (_certificateSelector != null)
                    {
                        selector = (sender, name) =>
                        {
                            context.Features.Set(sslStream);
                            var cert = _certificateSelector(context, name);
                            if (cert != null)
                            {
                                EnsureCertificateIsAllowedForServerAuth(cert);
                            }
                            return(cert);
                        };
                    }

                    var sslOptions = new SslServerAuthenticationOptions
                    {
                        ServerCertificate = _certificate,
                        ServerCertificateSelectionCallback = selector,
                        ClientCertificateRequired          = certificateRequired,
                        EnabledSslProtocols            = _options.SslProtocols,
                        CertificateRevocationCheckMode = _options.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
                        ApplicationProtocols           = new List <SslApplicationProtocol>()
                    };

                    _options.OnAuthenticateAsServer?.Invoke(context, sslOptions);

                    await sslStream.AuthenticateAsServerAsync(sslOptions, cancellationTokeSource.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    _logger?.LogDebug(2, "Authentication timed out");
                    await sslStream.DisposeAsync().ConfigureAwait(false);

                    return;
                }
                catch (Exception ex) when(ex is IOException || ex is AuthenticationException)
                {
                    _logger?.LogDebug(1, ex, "Authentication failed");
                    await sslStream.DisposeAsync().ConfigureAwait(false);

                    return;
                }
            }

            feature.ApplicationProtocol = sslStream.NegotiatedApplicationProtocol.Protocol;
            context.Features.Set <ITlsApplicationProtocolFeature>(feature);
            feature.LocalCertificate     = ConvertToX509Certificate2(sslStream.LocalCertificate);
            feature.RemoteCertificate    = ConvertToX509Certificate2(sslStream.RemoteCertificate);
            feature.CipherAlgorithm      = sslStream.CipherAlgorithm;
            feature.CipherStrength       = sslStream.CipherStrength;
            feature.HashAlgorithm        = sslStream.HashAlgorithm;
            feature.HashStrength         = sslStream.HashStrength;
            feature.KeyExchangeAlgorithm = sslStream.KeyExchangeAlgorithm;
            feature.KeyExchangeStrength  = sslStream.KeyExchangeStrength;
            feature.Protocol             = sslStream.SslProtocol;

            var originalTransport = context.Transport;

            try
            {
                context.Transport = sslDuplexPipe;

                // Disposing the stream will dispose the sslDuplexPipe
                await using (sslStream)
                    await using (sslDuplexPipe)
                    {
                        await _next(context).ConfigureAwait(false);

                        // Dispose the inner stream (SslDuplexPipe) before disposing the SslStream
                        // as the duplex pipe can hit an ODE as it still may be writing.
                    }
            }
            finally
            {
                // Restore the original so that it gets closed appropriately
                context.Transport = originalTransport;
            }
        }
Exemplo n.º 35
0
 /// <summary>
 /// TBD
 /// </summary>
 protected override void PreStart()
 {
     ConnectionContext.Remember(GetConnectionString());
     base.PreStart();
 }
 public ConnectionContextValueProvider(ConnectionContext connectionContext)
 {
     _provider = new MultipleValueProvider(GetProvidersForConnection(connectionContext).ToArray());
 }
Exemplo n.º 37
0
 public async override Task OnConnectedAsync(ConnectionContext connection)
 {
     await connection.Transport.Writer.WriteAsync(await connection.Transport.Reader.ReadAsync());
 }
Exemplo n.º 38
0
        public FrameContext(ConnectionContext context) : base(context)
        {

        }
Exemplo n.º 39
0
 private static void Complete(ConnectionContext connection)
 {
     connection.Transport.Output.Complete();
     connection.Transport.Input.Complete();
 }
Exemplo n.º 40
0
 public DomainContext()
 {
     _ctx = new ConnectionContext();
 }
 public MockHubConnectionContext(ConnectionContext connectionContext, TimeSpan keepAliveInterval, ILoggerFactory loggerFactory, TimeSpan clientTimeoutInterval)
     : base(connectionContext, keepAliveInterval, loggerFactory, clientTimeoutInterval)
 {
 }
Exemplo n.º 42
0
 protected abstract Connection CreateConnection(ConnectionContext context);
Exemplo n.º 43
0
 /// <summary>
 /// TBD
 /// </summary>
 protected override void PostStop()
 {
     base.PostStop();
     ConnectionContext.Forget(GetConnectionString());
 }
Exemplo n.º 44
0
 public RabbitMqModelContext(ConnectionContext connectionContext, IModel model, ITaskScope taskScope, IRabbitMqHost host)
     : this(connectionContext, model, host,
         taskScope.CreateParticipant($"{TypeMetadataCache<RabbitMqModelContext>.ShortName} - {connectionContext.HostSettings.ToDebugString()}"))
 {
 }
 public override async Task OnConnectedAsync(ConnectionContext connection)
 {
     await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes(_lastWill));
 }
            public override async Task OnConnectedAsync(ConnectionContext connection)
            {
                var ex = await _throwTcs.Task;

                throw ex;
            }
 public Task DisposeAsync(ConnectionContext connection)
 {
     return(_connectionFactory.DisposeAsync(connection));
 }