Beispiel #1
0
        public async Task ConnectAsync(CancellationToken token = default)
        {
            _connection = await _factory.ConnectAsync(token).ConfigureAwait(false);

            _writer = new ModbusFrameWriter(_connection.Transport.Output);

            _readingTask = ReadMessages();
        }
Beispiel #2
0
            public async Task RunAsync()
            {
                var start = Console.ReadLine();

                Console.WriteLine("Starting");
                var connectionContext = await _connectionFactory.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 5555));

                var createStreamFeature = connectionContext.Features.Get <IQuicCreateStreamFeature>();
                var streamContext       = await createStreamFeature.StartBidirectionalStreamAsync();

                Console.CancelKeyPress += new ConsoleCancelEventHandler((sender, args) =>
                {
                    streamContext.Transport.Input.CancelPendingRead();
                    streamContext.Transport.Output.CancelPendingFlush();
                });

                var input = "asdf";

                while (true)
                {
                    try
                    {
                        //var input = Console.ReadLine();
                        if (input.Length == 0)
                        {
                            continue;
                        }
                        var flushResult = await streamContext.Transport.Output.WriteAsync(Encoding.ASCII.GetBytes(input));

                        if (flushResult.IsCanceled)
                        {
                            break;
                        }

                        var readResult = await streamContext.Transport.Input.ReadAsync();

                        if (readResult.IsCanceled)
                        {
                            break;
                        }
                        if (readResult.Buffer.Length > 0)
                        {
                            Console.WriteLine(Encoding.ASCII.GetString(readResult.Buffer.ToArray()));
                        }

                        streamContext.Transport.Input.AdvanceTo(readResult.Buffer.End);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        break;
                    }
                }

                await streamContext.Transport.Input.CompleteAsync();

                await streamContext.Transport.Output.CompleteAsync();
            }
Beispiel #3
0
        public async Task <IActionResult> Get(string payloadData)
        {
            var connection = await _connectionFactory.ConnectAsync(_settings);

            var producer = connection.GetProducer <Guid, Payload>(_settings.ChannelName, _messageAdapter);

            var message = await producer.ProduceAsync(Guid.NewGuid(), new Payload { Data = payloadData });

            _logger.LogInformation($"The Message (key: {message.Key}) has been sent to HermesMQ channel {message.ChannelName}");

            return(Ok(new { success = true }));
        }
        /// <summary>
        /// Returns `false` if the peer is already connected. otherwise return `true`.
        /// </summary>
        /// <param name="remoteEndPoint"></param>
        /// <param name="pubkey"></param>
        /// <param name="ct"></param>
        /// <returns>true if the peer is unknown</returns>
        public async ValueTask <bool> NewOutbound(EndPoint remoteEndPoint, PubKey pubkey, CancellationToken ct = default)
        {
            if (remoteEndPoint == null)
            {
                throw new ArgumentNullException(nameof(remoteEndPoint));
            }
            if (pubkey == null)
            {
                throw new ArgumentNullException(nameof(pubkey));
            }
            if (_connectionLoops.ContainsKey(remoteEndPoint))
            {
                _logger.LogError($"We have already connected to: {remoteEndPoint.ToEndpointString()}.");
                return(false);
            }

            try
            {
                var connectionContext = await _connectionFactory.ConnectAsync(remoteEndPoint, ct);

                var(descriptor, writeReceiver) = descriptorFactory.GetNewSocket(connectionContext.Transport.Output);
                var peerMan     = PeerManagerProvider.GetPeerManager("BTC");
                var initialSend = peerMan.NewOutboundConnection(descriptor, pubkey.ToBytes());
                await connectionContext.Transport.Output.WriteAsync(initialSend, ct);

                var flushResult = connectionContext.Transport.Output.FlushAsync(ct);
                if (!flushResult.IsCompleted)
                {
                    await flushResult.ConfigureAwait(false);
                }

                Func <Task> cleanup = async() =>
                {
                    _connectionLoops.TryRemove(connectionContext.RemoteEndPoint, out _);
                    await _repository.RemoveRemoteEndPoint(connectionContext.RemoteEndPoint, ct);
                };
                await _repository.SetRemoteEndPoint(remoteEndPoint, ct);

                var conn = new ConnectionLoop(connectionContext.Transport, descriptor, peerMan,
                                              writeReceiver, EventNotify.Writer, _loggerFactory.CreateLogger <ConnectionLoop>(), cleanup);
                _connectionLoops.TryAdd(remoteEndPoint, conn);
                Task.Run(() => conn.Start(ct));
            }

            catch (SocketException ex) when(ex.SocketErrorCode == SocketError.ConnectionRefused)
            {
                _logger.LogError($"{ex.Message}:{Environment.NewLine}{ex.StackTrace}");
                return(false);
            }

            return(true);
        }
Beispiel #5
0
        public Task <ConnectionContext> ConnectAsync(HubServiceEndpoint endpoint, TransferFormat transferFormat, string connectionId, string target, CancellationToken cancellationToken = default, IDictionary <string, string> headers = null)
        {
            if (headers == null)
            {
                headers = new Dictionary <string, string> {
                    { Constants.AsrsUserAgent, _productInfo }
                };
            }
            else
            {
                headers[Constants.AsrsUserAgent] = _productInfo;
            }

            return(_connectionFactory.ConnectAsync(endpoint, transferFormat, connectionId, target, cancellationToken, headers));
        }
Beispiel #6
0
        public async ValueTask <ConnectionContext> ConnectAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
        {
            var connection = await _connectionFactory.ConnectAsync(endpoint, cancellationToken).ConfigureAwait(false);

            // Since nothing is being returned from this middleware, we need to wait for the last middleware to run
            // until we yield this call. Stash a tcs in the items bag that allows this code to get notified
            // when the middleware ran
            var connectionContextWithDelegate = new ConnectionContextWithDelegate(connection, _application);

            // Execute the middleware pipeline
            connectionContextWithDelegate.Start();

            // Wait for it the most inner middleware to run
            return(await connectionContextWithDelegate.Initialized.Task.ConfigureAwait(false));
        }
 /// <inheritdoc />
 public async Task AddUserAsync(string email, string passwordHash)
 {
     using (var connection = await connectionFactory.ConnectAsync())
     {
         try
         {
             await connection.ExecuteSqlStatementAsync(
                 "INSERT INTO [dbo].[Users] (Email, PasswordHash) VALUES (@email, @passwordhash)",
                 new Dictionary <string, object>
             {
                 { "@email", email },
                 { "@passwordhash", passwordHash }
             });
         }
         catch (SqlException e) when(e.Message.Contains("Violation of UNIQUE KEY constraint"))
         {
             throw new InvalidEmailException($"Email address {email} is already associated with a user account.");
         }
     }
 }
Beispiel #8
0
 protected override Task <ConnectionContext> CreateConnection(string target = null)
 {
     return(_connectionFactory.ConnectAsync(HubEndpoint, TransferFormat.Binary, ConnectionId, target, headers: CustomHeader));
 }
    private async Task RunAsync()
    {
        try
        {
            var address = BindingAddress.Parse(Options.Url);

            if (!IPAddress.TryParse(address.Host, out var ip))
            {
                ip = Dns.GetHostEntry(address.Host).AddressList.First();
            }

            var endpoint = new IPEndPoint(ip, address.Port);

            _logger.LogInformation($"Connecting to '{endpoint}'.");

            await using var context = await _connectionFactory.ConnectAsync(endpoint);

            _logger.LogInformation($"Connected to '{endpoint}'.");

            var originalTransport     = context.Transport;
            IAsyncDisposable sslState = null;
            if (address.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                _logger.LogInformation("Starting TLS handshake.");

                var memoryPool        = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool;
                var inputPipeOptions  = new StreamPipeReaderOptions(memoryPool, memoryPool.GetMinimumSegmentSize(), memoryPool.GetMinimumAllocSize(), leaveOpen: true);
                var outputPipeOptions = new StreamPipeWriterOptions(pool: memoryPool, leaveOpen: true);

                var sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
                var sslStream     = sslDuplexPipe.Stream;
                sslState = sslDuplexPipe;

                context.Transport = sslDuplexPipe;

                await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions
                {
                    TargetHost = address.Host,
                    RemoteCertificateValidationCallback = (_, __, ___, ____) => true,
                    ApplicationProtocols = new List <SslApplicationProtocol> {
                        SslApplicationProtocol.Http2
                    },
                    EnabledSslProtocols = SslProtocols.Tls12,
                }, CancellationToken.None);

                _logger.LogInformation($"TLS handshake completed successfully.");
            }

            var http2Utilities = new Http2Utilities(context, _logger, _stopTokenSource.Token);

            try
            {
                await Options.Scenaro(http2Utilities);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "App error");
                throw;
            }
            finally
            {
                // Unwind Https for shutdown. This must happen before the context goes out of scope or else DisposeAsync will never complete
                context.Transport = originalTransport;

                if (sslState != null)
                {
                    await sslState.DisposeAsync();
                }
            }
        }
        finally
        {
            HostApplicationLifetime.StopApplication();
        }
    }
Beispiel #10
0
            public async Task RunAsync()
            {
                var endpoint = new IPEndPoint(IPAddress.Loopback, 5001);

                _logger.LogInformation($"Connecting to '{endpoint}'.");

                await using var context = await _connectionFactory.ConnectAsync(endpoint);

                _logger.LogInformation($"Connected to '{endpoint}'. Starting TLS handshake.");

                var memoryPool        = context.Features.Get <IMemoryPoolFeature>()?.MemoryPool;
                var inputPipeOptions  = new StreamPipeReaderOptions(memoryPool, memoryPool.GetMinimumSegmentSize(), memoryPool.GetMinimumAllocSize(), leaveOpen: true);
                var outputPipeOptions = new StreamPipeWriterOptions(pool: memoryPool, leaveOpen: true);

                await using var sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
                await using var sslStream     = sslDuplexPipe.Stream;

                var originalTransport = context.Transport;

                context.Transport = sslDuplexPipe;

                try
                {
                    await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions
                    {
                        TargetHost = "localhost",
                        RemoteCertificateValidationCallback = (_, __, ___, ____) => true,
                        ApplicationProtocols = new List <SslApplicationProtocol> {
                            SslApplicationProtocol.Http2
                        },
                        EnabledSslProtocols = SslProtocols.Tls12,
                    }, CancellationToken.None);

                    _logger.LogInformation($"TLS handshake completed successfully.");

                    var http2Utilities = new Http2Utilities(context);

                    await http2Utilities.InitializeConnectionAsync();

                    _logger.LogInformation("Initialized http2 connection. Starting stream 1.");

                    await http2Utilities.StartStreamAsync(1, Http2Utilities._browserRequestHeaders, endStream : true);

                    var headersFrame = await http2Utilities.ReceiveFrameAsync();

                    Trace.Assert(headersFrame.Type == Http2FrameType.HEADERS);
                    Trace.Assert((headersFrame.Flags & (byte)Http2HeadersFrameFlags.END_HEADERS) != 0);
                    Trace.Assert((headersFrame.Flags & (byte)Http2HeadersFrameFlags.END_STREAM) == 0);

                    _logger.LogInformation("Received headers in a single frame.");

                    var decodedHeaders = http2Utilities.DecodeHeaders(headersFrame);

                    foreach (var header in decodedHeaders)
                    {
                        _logger.LogInformation($"{header.Key}: {header.Value}");
                    }

                    var dataFrame = await http2Utilities.ReceiveFrameAsync();

                    Trace.Assert(dataFrame.Type == Http2FrameType.DATA);
                    Trace.Assert((dataFrame.Flags & (byte)Http2DataFrameFlags.END_STREAM) == 0);

                    _logger.LogInformation("Received data in a single frame.");

                    _logger.LogInformation(Encoding.UTF8.GetString(dataFrame.Payload.ToArray()));

                    var trailersFrame = await http2Utilities.ReceiveFrameAsync();

                    Trace.Assert(trailersFrame.Type == Http2FrameType.HEADERS);
                    Trace.Assert((trailersFrame.Flags & (byte)Http2DataFrameFlags.END_STREAM) == 1);

                    _logger.LogInformation("Received trailers in a single frame.");

                    http2Utilities._decodedHeaders.Clear();

                    var decodedTrailers = http2Utilities.DecodeHeaders(trailersFrame);

                    foreach (var header in decodedHeaders)
                    {
                        _logger.LogInformation($"{header.Key}: {header.Value}");
                    }

                    await http2Utilities.StopConnectionAsync(expectedLastStreamId : 1, ignoreNonGoAwayFrames : false);

                    _logger.LogInformation("Connection stopped.");
                }
                finally
                {
                    context.Transport = originalTransport;
                }
            }
Beispiel #11
0
 protected override Task <ConnectionContext> CreateConnection()
 {
     return(_connectionFactory.ConnectAsync(TransferFormat.Binary, _connectionId, _hubName));
 }
Beispiel #12
0
        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            _connection = await _connectionFactory.ConnectAsync(_settings);

            await base.StartAsync(cancellationToken);
        }
Beispiel #13
0
 public Task <ConnectionContext> ConnectAsync(TransferFormat transferFormat, CancellationToken cancellationToken = default)
 {
     ConnectTask = _innerFactory.ConnectAsync(transferFormat, cancellationToken);
     return(ConnectTask);
 }
Beispiel #14
0
 protected override Task <ConnectionContext> CreateConnection(string target = null)
 {
     return(_connectionFactory.ConnectAsync(TransferFormat.Binary, ConnectionId, target));
 }
 public static ValueTask <IConnection> ConnectAsync(this IConnectionFactory connectionFactory, HermesSettings hermesSettings) =>
 connectionFactory.ConnectAsync(hermesSettings.HostAddress, hermesSettings.Port);
Beispiel #16
0
 public ValueTask <ConnectionContext> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default)
 {
     ConnectTask = _innerFactory.ConnectAsync(endPoint, cancellationToken);
     return(ConnectTask);
 }
Beispiel #17
0
 public async Task ConnectAsync(IPAddress host, int port)
 {
     IPEndPoint = new IPEndPoint(host, port);
     socket     = await connectionFactory.ConnectAsync(IPEndPoint);
 }