Exemple #1
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // Use a length prefixed protocol
            var protocol = new LengthPrefixedProtocol();
            var reader   = connection.CreateReader();
            var writer   = connection.CreateWriter();

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

                    var message = result.Message;

                    _logger.LogInformation("Received a message of {Length} bytes", message.Payload.Length);

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    await writer.WriteAsync(protocol, message);
                }
                finally
                {
                    reader.Advance();
                }
            }
        }
Exemple #2
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            IServiceScope      scope         = null;
            BlazeClientContext clientContext = null;

            try
            {
                //Create connection scope
                scope = _serviceScopeFactory.CreateScope();
                var messageHandler = scope.ServiceProvider.GetRequiredService <IBlazeMessageHandler>();

                clientContext = (BlazeClientContext)scope.ServiceProvider.GetRequiredService <ClientContext>();
                clientContext.ConnectionContext = connection;
                _clientManager.Add(clientContext);

                var reader = connection.CreateReader();
                var writer = connection.CreateWriter();

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

                        var message = result.Message;

                        if (message != null)
                        {
                            var responses = await messageHandler.ProcessMessage(message, clientContext);

                            if (responses != null)
                            {
                                foreach (var response in responses)
                                {
                                    await writer.WriteAsync(_protocol, response);
                                }
                            }
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        reader.Advance();
                    }
                }
            }
            finally
            {
                if (clientContext != null)
                {
                    _clientManager.Remove(clientContext);
                }

                scope?.Dispose();
            }
        }
Exemple #3
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            ProtocolReader protocolReader = connection.CreateReader();
            CustomProtocol customProtocol = new();

            string        message = "first\n";
            Memory <byte> buffer  = connection.Transport.Output.GetMemory(0x10)[..0x10];
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // Use a length prefixed protocol
            var protocol = new MyRequestMessageReader();
            var reader   = connection.CreateReader();

            while (!_hostApplicationLifetime.ApplicationStopping.IsCancellationRequested)
            {
                try
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;

                    if (message is PayloadMessage payloadMessage)
                    {
                        _logger.LogInformation("Received a {MessageType} with an inner payload of {Length} bytes", typeof(PayloadMessage).Name, payloadMessage.Payload.Length);
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    reader.Advance();
                }
            }
        }
Exemple #5
0
        public MyClientProtocol(ConnectionContext connection)
        {
            _connection = connection;
            _reader     = connection.CreateReader();

            _messageWriter = new MyRequestMessageWriter();
        }
Exemple #6
0
        public CobbleConnection(ConnectionContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _reader  = context.CreateReader();
            _writer  = context.CreateWriter();

            _protocol = new HandshakingProtocol();
        }
Exemple #7
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            if (connection is null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            using IDisposable loggerScope = _logger.BeginScope("Peer {PeerId} connected to server {ServerEndpoint}", connection.ConnectionId, connection.LocalEndPoint);

            ProtocolReader reader = connection.CreateReader();
            INetworkProtocolMessageSerializer protocol = _serviceProvider.GetRequiredService <INetworkProtocolMessageSerializer>();

            using IPeerContext peerContext = _peerContextFactory.CreateIncomingPeerContext(connection.ConnectionId,
                                                                                           connection.LocalEndPoint !.AsIPEndPoint().EnsureIPv6(),
                                                                                           connection.RemoteEndPoint !.AsIPEndPoint().EnsureIPv6(),
                                                                                           new NetworkMessageWriter(protocol, connection.CreateWriter()));

            using CancellationTokenRegistration cancellationRegistration = peerContext.ConnectionCancellationTokenSource.Token.Register(() =>
            {
                connection.Abort(new ConnectionAbortedException("Requested by PeerContext"));
            });

            connection.Features.Set(peerContext);
            protocol.SetPeerContext(peerContext);

            if (EnsurePeerCanConnect(connection, peerContext))
            {
                _eventBus.Publish(new PeerConnected(peerContext));

                await _networkMessageProcessorFactory.StartProcessorsAsync(peerContext).ConfigureAwait(false);

                while (true)
                {
                    try
                    {
                        ProtocolReadResult <INetworkMessage> result = await reader.ReadAsync(protocol).ConfigureAwait(false);

                        if (result.IsCompleted)
                        {
                            break;
                        }

                        await ProcessMessageAsync(result.Message, peerContext, connection.ConnectionClosed).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogDebug(ex, "Unexpected connection terminated because of {DisconnectionReason}.", ex.Message);
                        break;
                    }
                    finally
                    {
                        reader.Advance();
                    }
                }

                return;
            }
        }
Exemple #8
0
 private HubProtocol(ConnectionContext connection, int?maximumMessageSize, IHubProtocol hubProtocol, IInvocationBinder invocationBinder)
 {
     _connection         = connection;
     _protocolReader     = connection.CreateReader();
     _protocolWriter     = connection.CreateWriter();
     _hubMessageReader   = new HubMessageReader(hubProtocol, invocationBinder);
     _hubMessageWriter   = new HubMessageWriter(hubProtocol);
     _maximumMessageSize = maximumMessageSize;
 }
Exemple #9
0
        public async Task ConnectAsync(EndPoint endPoint)
        {
            // REVIEW: Should this be a static factory?
            _connection = await _client.ConnectAsync(endPoint).ConfigureAwait(false);

            _writer      = _connection.CreateWriter();
            _reader      = _connection.CreateReader();
            _readingTask = ProcessReadsAsync();
        }
Exemple #10
0
        public MemcachedProtocol(ConnectionContext connection)
        {
            _connection = connection;

            _protocolReader = connection.CreateReader();
            _protocolWriter = connection.CreateWriter();

            _semaphore = new SemaphoreSlim(1);

            _memcachedMessageWriter = new MemcachedMessageWriter();
            _memcachedMessageReader = new MemcachedMessageReader();
        }
        /// <summary>
        ///     on connected as an asynchronous operation.
        /// </summary>
        /// <param name="connection">The new <see cref="T:Microsoft.AspNetCore.Connections.ConnectionContext" /></param>
        /// <returns>A Task representing the asynchronous operation.</returns>
        /// <autogeneratedoc />
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var protocol = _messageReader;
            var reader   = connection.CreateReader();

            while (!connection.ConnectionClosed.IsCancellationRequested)
            {
                try
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;


                    var returnMessage = _messageHandler.HandleMessage(connection, message);

                    if (returnMessage == null)
                    {
                        continue;
                    }

                    try
                    {
                        await _messageSender.TrySendAsync(returnMessage,
                                                          connection.ConnectionClosed);
                    }
                    catch (ConnectionNotFoundException e)
                    {
                        _logger.LogError($"connection not found: {e.Message}");
                    }
                    catch (ArgumentNullException e)
                    {
                        _logger.LogError($"Client {connection.ConnectionId} threw: Argument null exception: {e.Message}");
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"Connection {connection.ConnectionId} threw: {e.Message} /n trace: {e.StackTrace}");
                    }


                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                catch (ConnectionResetException)
                {
                    var newSource = new CancellationTokenSource();
                    newSource.Cancel();
                    connection.ConnectionClosed = newSource.Token;
                }
            }
Exemple #12
0
        public HttpClientProtocol(ConnectionContext connection)
        {
            _connection = connection;
            _reader     = connection.CreateReader();

            (string host, int port) = connection.RemoteEndPoint switch
            {
                UriEndPoint uriEndPoint => (uriEndPoint.Uri.Host, uriEndPoint.Uri.Port),
                IPEndPoint ip => (ip.Address.ToString(), ip.Port),
                _ => throw new NotSupportedException($"{connection.RemoteEndPoint} not supported")
            };
            _messageWriter = new Http1RequestMessageWriter(host, port);
        }
Exemple #13
0
        /// <summary>
        /// on connected as an asynchronous operation.
        /// </summary>
        /// <param name="connection">The new <see cref="T:Microsoft.AspNetCore.Connections.ConnectionContext" /></param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the connection lifetime. When the task completes, the connection is complete.</returns>
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            this.context = connection;
            this.reader  = connection.CreateReader();
            this.writer  = connection.CreateWriter();

            SessionManager.Singleton.AcceptSession(connection, writer, this.protocol);

            //IConnectionHeartbeatFeature heartbeatFeature = connection.Features.Get<IConnectionHeartbeatFeature>();
            //heartbeatFeature.OnHeartbeat(this.SendHeartbeat, null);

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

                    var message = result.Message;

                    _logger.LogInformation("Received a message of {Length} bytes", message.Payload.Length);

                    if (result.IsCompleted)
                    {
                        break;
                    }



                    await writer.WriteAsync(protocol, message);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    connection.Abort();
                    break;
                }
                finally
                {
                    reader.Advance();
                }
            }
        }
        private async Task ProcessInbound(CancellationToken cancellationToken)
        {
            await Task.Yield();

            var protocolReader = connection.CreateReader();
            var opReader       = new NatsOperationReader();

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var result = await protocolReader.ReadAsync(opReader, cancellationToken).ConfigureAwait(false);

                    if (result.IsCompleted)
                    {
                        Console.WriteLine("inbound connection closed");
                        break;
                    }
                    protocolReader.Advance();

                    await operationHandler.HandleOperation(result.Message);
                }
                catch (OperationCanceledException) { /* ignore cancellation */ }
                catch (Exception)
                {
                    if (!connection.ConnectionClosed.IsCancellationRequested)
                    {
                        throw;
                    }
                    break;
                }
            }

            Console.WriteLine("!!! exit inbound");
            operationHandler.ConnectionClosed();
        }
 public RespBedrockProtocol(ConnectionContext connection, object state = null) : base(state)
 {
     // _connection = connection;
     _reader = connection.CreateReader();
     _writer = connection.CreateWriter();
 }
 public RabbitMQClientProtocol(ConnectionContext connection)
 {
     _writer    = connection.CreateWriter();
     _reader    = connection.CreateReader();
     _formatter = new RabbitMQMessageFormatter();
 }
 public RedisProtocol(ConnectionContext connection)
 {
     _writer        = connection.CreateWriter();
     _reader        = connection.CreateReader();
     _commandWriter = new RedisCommandWriter();
 }
Exemple #18
0
 public RabbitMQProtocolReader(ConnectionContext ctx)
 {
     _protocol = ctx.CreateReader();
 }
Exemple #19
0
 public HttpClientProtocol(ConnectionContext connection)
 {
     _connection = connection;
     _reader     = connection.CreateReader();
 }
Exemple #20
0
 public RespBedrockProtocol(ConnectionContext connection)
 {
     // _connection = connection;
     _reader = connection.CreateReader();
     _writer = connection.CreateWriter();
 }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // TODO: we could register processors as Scoped per connection and create a scope here
            //using var serviceProviderScope = serviceProvider.CreateScope();

            if (connection is null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            using IDisposable logScope = _logger.BeginScope("Peer {PeerId} connected to outbound {PeerEndpoint}", connection.ConnectionId, connection.LocalEndPoint);

            ProtocolReader reader = connection.CreateReader();
            INetworkProtocolMessageSerializer protocol = _serviceProvider.GetRequiredService <INetworkProtocolMessageSerializer>();

            using IPeerContext peerContext = _peerContextFactory.CreateOutgoingPeerContext(connection.ConnectionId,
                                                                                           connection.LocalEndPoint !,
                                                                                           connection.Features.Get <OutgoingConnectionEndPoint>(),
                                                                                           new NetworkMessageWriter(protocol, connection.CreateWriter()));

            connection.ConnectionClosed = peerContext.ConnectionCancellationTokenSource.Token;
            connection.Features.Set(peerContext);

            protocol.SetPeerContext(peerContext);

            _eventBus.Publish(new PeerConnected(peerContext));


            await _networkMessageProcessorFactory.StartProcessorsAsync(peerContext).ConfigureAwait(false);


            while (true)
            {
                if (connection.ConnectionClosed.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    ProtocolReadResult <INetworkMessage> result =
                        await reader.ReadAsync(protocol, connection.ConnectionClosed).ConfigureAwait(false);

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    await ProcessMessageAsync(result.Message, peerContext, connection.ConnectionClosed)
                    .WithCancellationAsync(connection.ConnectionClosed)
                    .ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception e)
                {
                    _logger.LogError(new EventId(0), e, e.Message);
                    throw;
                }
                finally
                {
                    reader.Advance();
                }
            }

            return;
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            IServiceScope      scope         = null;
            BlazeClientContext clientContext = null;

            try
            {
                //Create connection scope
                scope = _serviceScopeFactory.CreateScope();
                var messageHandler = scope.ServiceProvider.GetRequiredService <IBlazeMessageHandler>();

                clientContext = (BlazeClientContext)scope.ServiceProvider.GetRequiredService <ClientContext>();
                clientContext.ConnectionContext = connection;
                clientContext.Reader            = connection.CreateReader();
                clientContext.Writer            = connection.CreateWriter();

                _clientManager.Add(clientContext);

                while (true)
                {
                    try
                    {
                        var result = await clientContext.Reader.ReadAsync(_protocol);

                        var message = result.Message;

                        if (message != null)
                        {
                            var response = await messageHandler.ProcessMessage(message);

                            if (response != null)
                            {
                                await clientContext.Writer.WriteAsync(_protocol, response);
                            }
                            //Send new notifications
                            while (clientContext.PendingNotifications.TryDequeue(out var notification))
                            {
                                await clientContext.Writer.WriteAsync(_protocol, notification);
                            }
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        clientContext.Reader.Advance();
                    }
                }
            }
            finally
            {
                if (clientContext != null)
                {
                    _clientManager.Remove(clientContext);
                }

                scope?.Dispose();
            }
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            Logger.Debug($"Redirecting to {_proxySettings.RedirectHost} {_proxySettings.RedirectIp}:{_proxySettings.LocalPort}");

            var blazeProtocol = new BlazeProxyProtocol();
            var localReader   = connection.CreateReader();
            var localWriter   = connection.CreateWriter();

            while (true)
            {
                try
                {
                    var result = await localReader.ReadAsync(blazeProtocol);

                    var message = result.Message;

                    if (message != null)
                    {
                        if (message.Header.Component == BlazeComponent.Redirector &&
                            message.Header.Command == (ushort)RedirectorCommand.ServerInfo)
                        {
                            var hostBytes = new List <byte>(Encoding.ASCII.GetBytes(_proxySettings.RedirectHost));
                            var payload   = new List <byte>();
                            payload.AddRange(new byte[] {
                                0x86, 0x49, 0x32, //ADDR
                                0xD0, 0x00,       //union(0)
                                0xDA, 0x1B, 0x35, //VALU
                                0x00,             //start struct
                                0xA2, 0xFC, 0xF4, //HOST
                            });
                            payload.AddRange(GetStringLengthBytes((uint)hostBytes.Count + 1));
                            payload.AddRange(hostBytes);
                            payload.AddRange(new byte[] {
                                0x00,             //endbyte for string
                                0xA7, 0x00, 0x00, //IP
                                0x74,             //uint32
                            });
                            var ipBytes = BitConverter.GetBytes(Convert.ToUInt32(IPAddress.Parse(_proxySettings.RedirectIp).Address));
                            Array.Reverse(ipBytes); //big endian
                            payload.AddRange(ipBytes);
                            payload.AddRange(new byte[] {
                                0xC2, 0xFC, 0xB4, //PORT
                                0x52,             //uint16
                            });
                            var portBytes = BitConverter.GetBytes(Convert.ToUInt16(_proxySettings.LocalPort));
                            Array.Reverse(portBytes); //big endian
                            payload.AddRange(portBytes);
                            payload.AddRange(new byte[] {
                                0x00,                   //end struct
                                0xCE, 0x58, 0xF5,       //SECU
                                0x21,                   //int8
                                0x00,                   //0
                                0xE2, 0x4B, 0xB3,       //XDNS
                                0x74,                   //uint32
                                0x00, 0x00, 0x00, 0x00, //0
                            });
                            var response = new BlazeMessageData
                            {
                                Header = new BlazeHeader
                                {
                                    Command     = message.Header.Command,
                                    Component   = message.Header.Component,
                                    MessageType = BlazeMessageType.Reply,
                                    MessageId   = message.Header.MessageId,
                                    ErrorCode   = 0
                                },
                                Payload = new ReadOnlySequence <byte>(payload.ToArray())
                            };
                            await localWriter.WriteAsync(blazeProtocol, response);
                        }
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    localReader.Advance();
                }
            }
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            Logger.Debug($"Connecting to {_proxySettings.RemoteHost}:{_proxySettings.RemotePort}");
            var proxyClient = new TcpClient();
            await proxyClient.ConnectAsync(_proxySettings.RemoteHost, _proxySettings.RemotePort);

            var ogStream = proxyClient.GetStream();

            Stream proxyStream = ogStream;

            if (_proxySettings.Secure)
            {
                var protocol = new TlsClientProtocol(proxyStream, new Org.BouncyCastle.Security.SecureRandom());
                protocol.Connect(new BlazeTlsClient());
                proxyStream = protocol.Stream;
            }

            var blazeProtocol = new BlazeProxyProtocol();
            var localReader   = connection.CreateReader();
            var localWriter   = connection.CreateWriter();

            var remoteReader = new ProtocolReader(proxyStream);
            var remoteWriter = new ProtocolWriter(proxyStream);


            while (true)
            {
                try
                {
                    var result = await localReader.ReadAsync(blazeProtocol);

                    var message = result.Message;

                    if (message != null)
                    {
                        var header = message.Header;
                        Logger.Debug(
                            $"Client -> Proxy; Length:{header.Length} Component:{header.Component} Command:0x{header.Command:X2} ErrorCode:{header.ErrorCode} MessageType:{header.MessageType} MessageId:{header.MessageId}");

                        var requestPayload = message.Payload;

                        if (!requestPayload.IsEmpty)
                        {
                            if (!_parser.TryParseBody(requestPayload))
                            {
                                Logger.Error("Failed to parse request message");
                            }
                        }

                        await remoteWriter.WriteAsync(blazeProtocol, message);
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    localReader.Advance();
                }

                do
                {
                    try
                    {
                        var result = await remoteReader.ReadAsync(blazeProtocol);

                        var message = result.Message;

                        if (message != null)
                        {
                            var header = message.Header;
                            Logger.Debug(
                                $"Proxy <- Server; Length:{header.Length} Component:{header.Component} Command:0x{header.Command:X2} ErrorCode:{header.ErrorCode} MessageType:{header.MessageType} MessageId:{header.MessageId}");

                            var responsePayload = message.Payload;

                            if (!responsePayload.IsEmpty)
                            {
                                if (!_parser.TryParseBody(responsePayload))
                                {
                                    Logger.Error("Failed to parse response message");
                                }
                            }

                            await localWriter.WriteAsync(blazeProtocol, message);
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        remoteReader.Advance();
                    }
                } while (ogStream.DataAvailable);
            }
        }
Exemple #25
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]);
                }
            }
        }