Exemplo n.º 1
0
        public void Start()
        {
            if (UseBroadcasting && BindingAddress.Equals(IPAddress.Any))
            {
                throw new NotSupportedException("Broadcasting can only be used on a specific interface. Please set the Server Binding Address properly.");
            }

            LogProvider.Log("Starting. Creating socket", "UDPSocket.Start", LogLevel.Verbose);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, AllowAddressReuse ? 1 : 0);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, UseBroadcasting ? 1 : 0);
            _socket.Bind(new IPEndPoint(BindingAddress, Port));
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

            if (UseBroadcasting)
            {
                _type = PacketType.BroadcastUDP;
            }

            // use a default message prefix
            MessagePrefixLength = 4;

            // begin receiving packets
            Receive();

            LogProvider.Log("Socket created. Listening for packets", "UDPSocket.Start", LogLevel.Verbose);
        }
Exemplo n.º 2
0
        public void Start()
        {
            var serverAddressesFeature = _server.Features?.Get <IServerAddressesFeature>();

            if (serverAddressesFeature == null || serverAddressesFeature.Addresses.Count == 0)
            {
                _logger.LogError("can not found IServerAddressesFeature in IServer,can not register service.");
                return;
            }
            //添加服务IPAndPort
            var ipPort        = NetHelper.GetIPAndPort(_grpcServerOptions.ServiceAddress);
            var serverAddress = BindingAddress.Parse(serverAddressesFeature.Addresses.First());

            MetaModel.StartTime = DateTime.Now;
            MetaModel.Ip        = ipPort.Item1;
            MetaModel.Port      = serverAddress.Port;
            Console.WriteLine($"server listening {MetaModel.Ip}:{MetaModel.Port}");
            //使用BaseServices
            Console.WriteLine($"use {_serviceRegister.GetType().Name} register");
            Console.WriteLine($"    DiscoveryUrl:{_grpcServerOptions.DiscoveryUrl}");
            Console.WriteLine($"    ServiceName:{_grpcServerOptions.DiscoveryServiceName}");
            var registerModel = _grpcServerOptions.ToJson().FromJson <ServiceRegisterModel>();

            registerModel.ServiceIp   = MetaModel.Ip;
            registerModel.ServicePort = MetaModel.Port;
            _serviceRegister.RegisterService(registerModel);
        }
Exemplo n.º 3
0
    private bool TryGetHttpsPort(out int port)
    {
        // The IServerAddressesFeature will not be ready until the middleware is Invoked,
        // Order for finding the HTTPS port:
        // 1. Set in the HttpsRedirectionOptions
        // 2. HTTPS_PORT environment variable
        // 3. IServerAddressesFeature
        // 4. Fail if not set

        port = -1;

        if (PortEvaluated)
        {
            port = HttpsPort ?? port;
            return(HttpsPort.HasValue);
        }
        PortEvaluated = true;

        HttpsPort = Config.GetValue <int?>("HTTPS_PORT");
        //if (HttpsPort.HasValue)
        //{
        //    port = HttpsPort.Value;
        //    return true;
        //}

        if (_serverAddressesFeature == null)
        {
            return(false);
        }

        int?httpsPort = null;

        foreach (var address in _serverAddressesFeature.Addresses)
        {
            var bindingAddress = BindingAddress.Parse(address);
            if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                // If we find multiple different https ports specified, throw
                if (httpsPort.HasValue && httpsPort != bindingAddress.Port)
                {
                    return(false);
                }
                else
                {
                    httpsPort = bindingAddress.Port;
                    break;
                }
            }
        }

        if (httpsPort.HasValue)
        {
            HttpsPort = httpsPort;
            port      = HttpsPort.Value;
            return(true);
        }

        return(false);
    }
 public void CorrectIPEndpointsAreCreated(string address, string expectedAddress, int expectedPort)
 {
     Assert.True(AddressBinder.TryCreateIPEndPoint(
                     BindingAddress.Parse(address), out var endpoint));
     Assert.NotNull(endpoint);
     Assert.Equal(IPAddress.Parse(expectedAddress), endpoint.Address);
     Assert.Equal(expectedPort, endpoint.Port);
 }
    //  Returns PortNotFound (-1) if we were unable to determine the port.
    private int TryGetHttpsPort()
    {
        // The IServerAddressesFeature will not be ready until the middleware is Invoked,
        // Order for finding the HTTPS port:
        // 1. Set in the HttpsRedirectionOptions
        // 2. HTTPS_PORT environment variable
        // 3. IServerAddressesFeature
        // 4. Fail if not sets

        var nullablePort = GetIntConfigValue("HTTPS_PORT") ?? GetIntConfigValue("ANCM_HTTPS_PORT");

        if (nullablePort.HasValue)
        {
            var port = nullablePort.Value;
            _logger.PortLoadedFromConfig(port);
            return(port);
        }

        if (_serverAddressesFeature == null)
        {
            _logger.FailedToDeterminePort();
            return(PortNotFound);
        }

        foreach (var address in _serverAddressesFeature.Addresses)
        {
            var bindingAddress = BindingAddress.Parse(address);
            if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                // If we find multiple different https ports specified, throw
                if (nullablePort.HasValue && nullablePort != bindingAddress.Port)
                {
                    throw new InvalidOperationException(
                              "Cannot determine the https port from IServerAddressesFeature, multiple values were found. " +
                              "Set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.");
                }
                else
                {
                    nullablePort = bindingAddress.Port;
                }
            }
        }

        if (nullablePort.HasValue)
        {
            var port = nullablePort.Value;
            _logger.PortFromServer(port);
            return(port);
        }

        _logger.FailedToDeterminePort();
        return(PortNotFound);

        int?GetIntConfigValue(string name) =>
        int.TryParse(_config[name], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var value) ? value : null;
    }
Exemplo n.º 6
0
    /// <summary>
    /// Returns an <see cref="IPEndPoint"/> for the given host an port.
    /// If the host parameter isn't "localhost" or an IP address, use IPAddress.Any.
    /// </summary>
    internal static bool TryCreateIPEndPoint(BindingAddress address, [NotNullWhen(true)] out IPEndPoint?endpoint)
    {
        if (!IPAddress.TryParse(address.Host, out var ip))
        {
            endpoint = null;
            return(false);
        }

        endpoint = new IPEndPoint(ip, address.Port);
        return(true);
    }
Exemplo n.º 7
0
        public void UrlsAreParsedCorrectly(string url, string scheme, string host, int port, string pathBase, string toString)
        {
            var serverAddress = BindingAddress.Parse(url);

            Assert.Equal(scheme, serverAddress.Scheme);
            Assert.Equal(host, serverAddress.Host);
            Assert.Equal(port, serverAddress.Port);
            Assert.Equal(pathBase, serverAddress.PathBase);

            Assert.Equal(toString ?? url, serverAddress.ToString());
        }
        public static BindingAddress CreateBindingAddress(this IConfiguration config)
        {
            var url = config["server.urls"] ?? config["urls"];

            if (string.IsNullOrEmpty(url))
            {
                return(BindingAddress.Parse("http://localhost:5000"));
            }

            return(BindingAddress.Parse(url));
        }
Exemplo n.º 9
0
        //  Returns PortNotFound (-1) if we were unable to determine the port.
        private int TryGetHttpsPort()
        {
            // The IServerAddressesFeature will not be ready until the middleware is Invoked,
            // Order for finding the HTTPS port:
            // 1. Set in the HttpsRedirectionOptions
            // 2. HTTPS_PORT environment variable
            // 3. IServerAddressesFeature
            // 4. Fail if not sets

            var nullablePort = _config.GetValue <int?>("HTTPS_PORT") ?? _config.GetValue <int?>("ANCM_HTTPS_PORT");

            if (nullablePort.HasValue)
            {
                var port = nullablePort.Value;
                _logger.PortLoadedFromConfig(port);
                return(port);
            }

            if (_serverAddressesFeature == null)
            {
                _logger.FailedToDeterminePort();
                return(PortNotFound);
            }

            foreach (var address in _serverAddressesFeature.Addresses)
            {
                var bindingAddress = BindingAddress.Parse(address);
                if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    // If we find multiple different https ports specified, throw
                    if (nullablePort.HasValue && nullablePort != bindingAddress.Port)
                    {
                        _logger.FailedMultiplePorts();
                        return(PortNotFound);
                    }
                    else
                    {
                        nullablePort = bindingAddress.Port;
                    }
                }
            }

            if (nullablePort.HasValue)
            {
                var port = nullablePort.Value;
                _logger.PortFromServer(port);
                return(port);
            }

            _logger.FailedToDeterminePort();
            return(PortNotFound);
        }
Exemplo n.º 10
0
        private static void DeleteOldSocketIfExists(IWebHost host)
        {
            // Delete UNIX pipe if it exists at startup (eg. previous process crashed before cleaning it up)
            // Workaround for https://github.com/aspnet/AspNetCore/issues/14134
            var addressFeature = host.ServerFeatures.Get <IServerAddressesFeature>();
            var url            = BindingAddress.Parse(addressFeature.Addresses.First());

            if (url.IsUnixPipe && File.Exists(url.UnixPipePath))
            {
                Console.WriteLine("UNIX pipe {0} already existed, deleting it.", url.UnixPipePath);
                File.Delete(url.UnixPipePath);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Configure the <see cref="KestrelServerOptions"/> with the specified URL.
        /// </summary>
        private bool Listen(KestrelServerOptions options, string url)
        {
            BindingAddress address = null;

            try
            {
                address = BindingAddress.Parse(url);
            }
            catch (Exception ex)
            {
                // Record the exception; it will be logged later through ILogger.
                Errors.Add(new AddressListenResult(url, ex));
                return(false);
            }

            Action <ListenOptions> configureListenOptions = (listenOptions) =>
            {
                if (address.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    listenOptions.UseHttps();
                }
            };

            try
            {
                if (address.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    options.ListenLocalhost(address.Port, configureListenOptions);
                }
                else if (IPAddress.TryParse(address.Host, out IPAddress ipAddress))
                {
                    options.Listen(ipAddress, address.Port, configureListenOptions);
                }
                else
                {
                    options.ListenAnyIP(address.Port, configureListenOptions);
                }
            }
            catch (InvalidOperationException ex)
            {
                // This binding failure is typically due to missing default certificate.
                // Record the exception; it will be logged later through ILogger.
                Errors.Add(new AddressListenResult(url, ex));
                return(false);
            }

            return(true);
        }
Exemplo n.º 12
0
        //This code is mostly taken from https://github.com/dotnet/aspnetcore/blob/master/src/Middleware/HttpsPolicy/src/HttpsRedirectionMiddleware.cs
        public static int TryGetHttpsPort(this IConfiguration configuration)
        {
            // Order for finding the HTTPS port:
            // 1. Set in the HttpsRedirectionOptions
            // 2. HTTPS_PORT environment variable
            // 3. IServerAddressesFeature
            // 4. Fail if not sets

            var nullablePort = configuration.GetValue <int?>("HTTPS_PORT") ?? configuration.GetValue <int?>("ANCM_HTTPS_PORT");

            if (nullablePort.HasValue)
            {
                var port = nullablePort.Value;
                return(port);
            }
            var addresses = configuration[WebHostDefaults.ServerUrlsKey];

            if (addresses == null)
            {
                return(PortNotFound);
            }
            foreach (var address in addresses.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var bindingAddress = BindingAddress.Parse(address);
                if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    // If we find multiple different https ports specified, throw
                    if (nullablePort.HasValue && nullablePort != bindingAddress.Port)
                    {
                        return(PortNotFound);
                    }
                    else
                    {
                        nullablePort = bindingAddress.Port;
                    }
                }
            }
            if (nullablePort.HasValue)
            {
                var port = nullablePort.Value;
                return(port);
            }
            return(PortNotFound);
        }
Exemplo n.º 13
0
    internal static ListenOptions ParseAddress(string address, out bool https)
    {
        var parsedAddress = BindingAddress.Parse(address);

        https = false;

        if (parsedAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
        {
            https = true;
        }
        else if (!parsedAddress.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(CoreStrings.FormatUnsupportedAddressScheme(address));
        }

        if (!string.IsNullOrEmpty(parsedAddress.PathBase))
        {
            throw new InvalidOperationException(CoreStrings.FormatConfigurePathBaseFromMethodCall($"{nameof(IApplicationBuilder)}.UsePathBase()"));
        }

        ListenOptions?options = null;

        if (parsedAddress.IsUnixPipe)
        {
            options = new ListenOptions(parsedAddress.UnixPipePath);
        }
        else if (string.Equals(parsedAddress.Host, "localhost", StringComparison.OrdinalIgnoreCase))
        {
            // "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
            options = new LocalhostListenOptions(parsedAddress.Port);
        }
        else if (TryCreateIPEndPoint(parsedAddress, out var endpoint))
        {
            options = new ListenOptions(endpoint);
        }
        else
        {
            // when address is 'http://hostname:port', 'http://*:port', or 'http://+:port'
            options = new AnyIPListenOptions(parsedAddress.Port);
        }

        return(options);
    }
Exemplo n.º 14
0
        private void CheckForHttpsPorts()
        {
            // The IServerAddressesFeature will not be ready until the middleware is Invoked,
            // Order for finding the HTTPS port:
            // 1. Set in the HttpsRedirectionOptions
            // 2. HTTPS_PORT environment variable
            // 3. IServerAddressesFeature
            // 4. 443 (or not set)

            _httpsPort = _config.GetValue <int?>("HTTPS_PORT");
            if (_httpsPort.HasValue)
            {
                return;
            }

            if (_serverAddressesFeature == null)
            {
                _httpsPort = 443;
                return;
            }

            int?httpsPort = null;

            foreach (var address in _serverAddressesFeature.Addresses)
            {
                var bindingAddress = BindingAddress.Parse(address);
                if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    // If we find multiple different https ports specified, throw
                    if (httpsPort.HasValue && httpsPort != bindingAddress.Port)
                    {
                        throw new ArgumentException("Cannot determine the https port from IServerAddressesFeature, multiple values were found. " +
                                                    "Please set the desired port explicitly on HttpsRedirectionOptions.HttpsPort.");
                    }
                    else
                    {
                        httpsPort = bindingAddress.Port;
                    }
                }
            }
            _httpsPort = httpsPort ?? 443;
        }
Exemplo n.º 15
0
        public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
        {
            var url = config["server.urls"] ?? config["urls"];

            if (string.IsNullOrEmpty(url))
            {
                return(new IPEndPoint(IPAddress.Loopback, 50051));
            }

            var address = BindingAddress.Parse(url);

            IPAddress ip;

            if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
            {
                ip = IPAddress.Loopback;
            }
            else if (!IPAddress.TryParse(address.Host, out ip))
            {
                ip = IPAddress.IPv6Any;
            }

            return(new IPEndPoint(ip, address.Port));
        }
        private static string[] ProcessMetricUrls(string[] metricUrls, MetricsOptions metricsOptions)
        {
            string metricUrlFromConfig = metricsOptions.Endpoints;

            if (!string.IsNullOrEmpty(metricUrlFromConfig))
            {
                metricUrls = ConfigurationHelper.SplitValue(metricUrlFromConfig);
            }

            //If we have custom metrics we want to upgrade the metrics transport channel to https, but
            //also respect the user's configuration to leave it insecure.
            if ((metricsOptions.Providers.Count > 0) &&
                (!metricsOptions.AllowInsecureChannelForCustomMetrics.GetValueOrDefault(false)) &&
                (metricsOptions.Providers.Any(provider =>
                                              !Monitoring.EventPipe.MonitoringSourceConfiguration.DefaultMetricProviders.Contains(provider.ProviderName, StringComparer.OrdinalIgnoreCase))))
            {
                for (int i = 0; i < metricUrls.Length; i++)
                {
                    BindingAddress metricUrl = BindingAddress.Parse(metricUrls[i]);

                    //Upgrade http to https by default.
                    if (metricUrl.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
                    {
                        //Based on BindAddress.ToString
                        metricUrls[i] = string.Concat(Uri.UriSchemeHttps.ToLowerInvariant(),
                                                      Uri.SchemeDelimiter,
                                                      metricUrl.Host.ToLowerInvariant(),
                                                      ":",
                                                      metricUrl.Port.ToString(System.Globalization.CultureInfo.InvariantCulture),
                                                      metricUrl.PathBase);
                    }
                }
            }

            return(metricUrls);
        }
 public void DoesNotCreateIPEndPointOnInvalidIPAddress(string address)
 {
     Assert.False(AddressBinder.TryCreateIPEndPoint(
                      BindingAddress.Parse(address), out var endpoint));
 }
Exemplo n.º 18
0
        private bool TryGetHttpsPort(out int port)
        {
            // The IServerAddressesFeature will not be ready until the middleware is Invoked,
            // Order for finding the HTTPS port:
            // 1. Set in the HttpsRedirectionOptions
            // 2. HTTPS_PORT environment variable
            // 3. IServerAddressesFeature
            // 4. Fail if not set

            port = -1;

            if (_portEvaluated)
            {
                port = _httpsPort ?? port;
                return(_httpsPort.HasValue);
            }

            _portEvaluated = true;

            _httpsPort = _config.GetValue <int?>("HTTPS_PORT");
            if (_httpsPort.HasValue)
            {
                port = _httpsPort.Value;
                //_logger.PortLoadedFromConfig(port);
                return(true);
            }

            if (_serverAddressesFeature == null)
            {
                //_logger.FailedToDeterminePort();
                return(false);
            }

            int?httpsPort = null;

            foreach (var address in _serverAddressesFeature.Addresses)
            {
                var bindingAddress = BindingAddress.Parse(address);
                if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    // If we find multiple different https ports specified, throw
                    if (httpsPort.HasValue && httpsPort != bindingAddress.Port)
                    {
                        //_logger.FailedMultiplePorts();
                        return(false);
                    }

                    httpsPort = bindingAddress.Port;
                }
            }

            if (httpsPort.HasValue)
            {
                _httpsPort = httpsPort;
                port       = _httpsPort.Value;
                //_logger.PortFromServer(port);
                return(true);
            }

            //_logger.FailedToDeterminePort();
            return(false);
        }
Exemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostApplicationLifetime lifetime,
            IWebHostEnvironment env,
            ExperimentalToolLogger exprLogger,
            IAuthOptions options,
            AddressListenResults listenResults,
            ILogger <Startup> logger)
        {
            exprLogger.LogExperimentMessage();

            // These errors are populated before Startup.Configure is called because
            // the KestrelServer class is configured as a prerequisite of
            // GenericWebHostServer being instantiated. The GenericWebHostServer invokes
            // Startup.Configure as part of its StartAsync method. This method is the
            // first opportunity to log anything through ILogger (a dedicated HostedService
            // could be written for this, but there is no guarantee that service would run
            // after the GenericWebHostServer is instantiated but before it is started).
            foreach (AddressListenResult result in listenResults.Errors)
            {
                logger.UnableToListenToAddress(result.Url, result.Exception);
            }

            // If we end up not listening on any ports, Kestrel defaults to port 5000. Make sure we don't attempt this.
            // Startup.Configure is called before KestrelServer is started
            // by the GenericWebHostServer, so there is no duplication of logging errors
            // and Kestrel does not bind to default ports.
            if (!listenResults.AnyAddresses)
            {
                // This is logged by GenericWebHostServer.StartAsync
                throw new MonitoringException("Unable to bind any urls.");
            }

            lifetime.ApplicationStarted.Register(() => LogBoundAddresses(app.ServerFeatures, listenResults, logger));

            if (options.KeyAuthenticationMode == KeyAuthenticationMode.NoAuth)
            {
                logger.NoAuthentication();
            }
            else
            {
                //Auth is enabled and we are binding on http. Make sure we log a warning.

                string   hostingUrl = Configuration.GetValue <string>(WebHostDefaults.ServerUrlsKey);
                string[] urls       = ConfigurationHelper.SplitValue(hostingUrl);
                foreach (string url in urls)
                {
                    BindingAddress address = null;
                    try
                    {
                        address = BindingAddress.Parse(url);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    if (string.Equals(Uri.UriSchemeHttp, address.Scheme, StringComparison.OrdinalIgnoreCase))
                    {
                        logger.InsecureAuthenticationConfiguration();
                        break;
                    }
                }
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            CorsConfiguration corsConfiguration = new CorsConfiguration();

            Configuration.Bind(nameof(CorsConfiguration), corsConfiguration);
            if (!string.IsNullOrEmpty(corsConfiguration.AllowedOrigins))
            {
                app.UseCors(builder => builder.WithOrigins(corsConfiguration.GetOrigins()).AllowAnyHeader().AllowAnyMethod());
            }

            app.UseResponseCompression();

            //Note this must be after UseRouting but before UseEndpoints
            app.UseMiddleware <Throttling>();

            app.UseEndpoints(builder =>
            {
                builder.MapControllers();
            });
        }
Exemplo n.º 20
0
 public void FromUriThrowsForUrlsWithoutHost(string url)
 {
     Assert.Throws <FormatException>(() => BindingAddress.Parse(url));
 }
Exemplo n.º 21
0
 public void FromUriThrowsForUrlsWithWrongFilePathOnWindows(string url)
 {
     Assert.Throws <FormatException>(() => BindingAddress.Parse(url));
 }
Exemplo n.º 22
0
    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();
        }
    }