Beispiel #1
0
        public async Task StopAsyncCallsCompleteWhenFirstCallCompletes()
        {
            var options = new KestrelServerOptions
            {
                ListenOptions =
                {
                    new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
                }
            };

            var unbind = new SemaphoreSlim(0);
            var stop   = new SemaphoreSlim(0);

            var mockTransport = new Mock <ITransport>();

            mockTransport
            .Setup(transport => transport.BindAsync())
            .Returns(Task.CompletedTask);
            mockTransport
            .Setup(transport => transport.UnbindAsync())
            .Returns(async() => await unbind.WaitAsync());
            mockTransport
            .Setup(transport => transport.StopAsync())
            .Returns(async() => await stop.WaitAsync());

            var mockTransportFactory = new Mock <ITransportFactory>();

            mockTransportFactory
            .Setup(transportFactory => transportFactory.Create(It.IsAny <IEndPointInformation>(), It.IsAny <IConnectionHandler>()))
            .Returns(mockTransport.Object);

            var server = new KestrelServer(Options.Create(options), mockTransportFactory.Object, Mock.Of <LoggerFactory>());
            await server.StartAsync(new DummyApplication(), CancellationToken.None);

            var stopTask1 = server.StopAsync(default(CancellationToken));
            var stopTask2 = server.StopAsync(default(CancellationToken));
            var stopTask3 = server.StopAsync(default(CancellationToken));

            Assert.False(stopTask1.IsCompleted);
            Assert.False(stopTask2.IsCompleted);
            Assert.False(stopTask3.IsCompleted);

            unbind.Release();
            stop.Release();

            await Task.WhenAll(new[] { stopTask1, stopTask2, stopTask3 }).TimeoutAfter(TimeSpan.FromSeconds(10));

            mockTransport.Verify(transport => transport.UnbindAsync(), Times.Once);
            mockTransport.Verify(transport => transport.StopAsync(), Times.Once);
        }
Beispiel #2
0
    public static AddressBindContext CreateAddressBindContext(
        ServerAddressesFeature serverAddressesFeature,
        KestrelServerOptions serverOptions,
        ILogger logger,
        Func <ListenOptions, CancellationToken, Task> createBinding)
    {
        var context = new AddressBindContext(
            serverAddressesFeature,
            serverOptions,
            logger,
            createBinding);

        return(context);
    }
Beispiel #3
0
        public ServerKestrel()
        {
            var options = new KestrelServerOptions
            {
                AddServerHeader = false,
            };
            var optionsWrapper = new OptionsWrapper <KestrelServerOptions>(options);
            var loggerFactory  = new LoggerFactory();
            var lifeTime       = new ApplicationLifetime(loggerFactory.CreateLogger <ApplicationLifetime>());

            server = new KestrelServer(optionsWrapper, new LibuvTransportFactory(new OptionsManager <LibuvTransportOptions>(
                                                                                     new OptionsFactory <LibuvTransportOptions>(
                                                                                         new List <IConfigureOptions <LibuvTransportOptions> >(), new List <IPostConfigureOptions <LibuvTransportOptions> >())), lifeTime, loggerFactory), loggerFactory);
        }
        private KestrelServerOptions CreateServerOptions()
        {
            var serverOptions = new KestrelServerOptions();
            var env           = new HostingEnvironment {
                ApplicationName = "TestApplication"
            };

            serverOptions.ApplicationServices = new ServiceCollection()
                                                .AddLogging()
                                                .AddSingleton <IWebHostEnvironment>(env)
                                                .AddSingleton <IHostEnvironment>(env)
                                                .BuildServiceProvider();
            return(serverOptions);
        }
        public async Task WrapsAddressInUseExceptionAsIOException()
        {
            var addresses = new ServerAddressesFeature();

            addresses.Addresses.Add("http://localhost:5000");
            var options = new KestrelServerOptions();

            await Assert.ThrowsAsync <IOException>(() =>
                                                   AddressBinder.BindAsync(addresses,
                                                                           options,
                                                                           NullLogger.Instance,
                                                                           Mock.Of <IDefaultHttpsProvider>(),
                                                                           endpoint => throw new AddressInUseException("already in use")));
        }
Beispiel #6
0
        public static void ConfigureEndpoints(this KestrelServerOptions options, int port)
        {
            IPAddress address = IPAddress.Loopback;

            options.Listen(address, port, listenOptions =>
            {
                HttpsConnectionAdapterOptions httpOptions = new HttpsConnectionAdapterOptions
                {
                    ServerCertificate     = GetHttpsCertificate(),
                    ClientCertificateMode = ClientCertificateMode.NoCertificate
                };
                listenOptions.UseHttps(httpOptions);
            });
        }
Beispiel #7
0
        private static void SetupCommonProperties(IConfiguration configuration, KestrelServerOptions options)
        {
            _ = long.TryParse(configuration["devonfw:Kestrel:ExtraSettings:MaxConcurrentConnections"], out long maxConcurrentConnections);
            _ = long.TryParse(configuration["devonfw:Kestrel:ExtraSettings:MaxConcurrentUpgradedConnections"], out long maxConcurrentUpgradedConnections);
            _ = long.TryParse(configuration["devonfw:Kestrel:ExtraSettings:KeepAliveTimeout"], out long keepAliveTimeout);
            _ = double.TryParse(configuration["devonfw:Kestrel:ExtraSettings:MaxRequestBodySize"], out double maxRequestBodySize);
            _ = int.TryParse(configuration["devonfw:Kestrel:ExtraSettings:Http2MaxStreamsPerConnection"], out int http2MaxStreamsPerConnection);
            _ = int.TryParse(configuration["devonfw:Kestrel:ExtraSettings:Http2InitialConnectionWindowSize"], out int Http2InitialConnectionWindowSize);
            _ = int.TryParse(configuration["devonfw:Kestrel:ExtraSettings:Http2InitialStreamWindowSize"], out int http2InitialStreamWindowSize);
            _ = bool.TryParse(configuration["devonfw:Kestrel:ExtraSettings:AllowSynchronousIO"], out bool allowSynchronousIO);

            if (maxConcurrentConnections > 0)
            {
                options.Limits.MaxConcurrentConnections = maxConcurrentConnections;
            }
            if (maxConcurrentUpgradedConnections > 0)
            {
                options.Limits.MaxConcurrentUpgradedConnections = maxConcurrentUpgradedConnections;
            }
            if (keepAliveTimeout > 0)
            {
                options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(keepAliveTimeout);
            }

            if (maxRequestBodySize >= 1 && maxRequestBodySize <= 28.6)
            {
                options.Limits.MaxRequestBodySize = (long?)(maxRequestBodySize * 1048576);
            }

            if (http2MaxStreamsPerConnection > 0)
            {
                options.Limits.Http2.MaxStreamsPerConnection = http2MaxStreamsPerConnection;
            }

            if (Http2InitialConnectionWindowSize >= 65535 && Http2InitialConnectionWindowSize <= Math.Pow(2, 31))
            {
                options.Limits.Http2.InitialConnectionWindowSize = Http2InitialConnectionWindowSize;
            }

            if (http2InitialStreamWindowSize >= 65535 && http2InitialStreamWindowSize <= Math.Pow(2, 31))
            {
                options.Limits.Http2.InitialStreamWindowSize = http2InitialStreamWindowSize;
            }

            if (allowSynchronousIO)
            {
                options.AllowSynchronousIO = true;
            }
        }
Beispiel #8
0
        // David Fowler would really like us not to do this
        // https://github.com/aspnet/KestrelHttpServer/issues/2306#issuecomment-364478486
        public EndpointDetailsViewModel HackEndpointDetails()
        {
            var model = new EndpointDetailsViewModel();

            try {
                KestrelServer kestrel = server as KestrelServer;
                if (kestrel == null)
                {
                    model.NotKestrel = true;
                    return(model);
                }

                KestrelServerOptions options = kestrel.Options;

                // reflection voodoo
                Type                 kestrelServerOptionsType = typeof(KestrelServerOptions);
                PropertyInfo         listenOptionsProp        = kestrelServerOptionsType.GetProperty("ListenOptions", BindingFlags.Instance | BindingFlags.NonPublic);
                PropertyInfo         isTlsProp     = typeof(ListenOptions).GetProperty("IsTls", BindingFlags.Instance | BindingFlags.NonPublic);
                List <ListenOptions> listenOptions = (List <ListenOptions>)listenOptionsProp.GetValue(options);

                foreach (ListenOptions listenOption in listenOptions)
                {
                    bool isTls = (bool)isTlsProp.GetValue(listenOption);

                    // Grab all the details for this endpoint
                    EndpointDetail endpointDetail = new EndpointDetail
                    {
                        Address = listenOption.IPEndPoint.Address.ToString(),
                        Port    = listenOption.IPEndPoint.Port,
                        IsHttps = isTls
                    };
                    model.EndpointDetails.Add(endpointDetail);

                    if (isTls)
                    {
                        // it appears all middleware is configured for all listenOptions even if they aren't https
                        endpointDetail.Certificate = GetCertificateFromOptions(listenOption);
                    }
                }

                // Reflect the dev cert
                model.IsDevCertLoaded    = (bool)(kestrelServerOptionsType.GetProperty("IsDevCertLoaded", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(options));
                model.DefaultCertificate = kestrelServerOptionsType.GetProperty("DefaultCertificate", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(options) as X509Certificate2;
            } catch (Exception ex) {
                // because this is hacky enough that it'll likely fall down easily
                model.Exception = ex.Message;
            }
            return(model);
        }
        public static void ConfigureCashFlowService(this KestrelServerOptions ksoOptions)
        {
            var vCashFlowSrvConfig         = ksoOptions.ApplicationServices.GetRequiredService <IConfiguration>();
            var vCashFlowServerEnvironment = ksoOptions.ApplicationServices.GetRequiredService <IHostingEnvironment>();

            var vCashFlowSrvConfigItems = vCashFlowSrvConfig.GetSection("HttpServer:vCashFlowSrvConfigItems")
                                          .GetChildren()
                                          .ToDictionary(cfsSection => cfsSection.Key, cfsSection =>
            {
                var vCashFlowSrvConfigItem = new CashFlowServiceConfigurationDefinition();
                cfsSection.Bind(vCashFlowSrvConfigItem);
                return(vCashFlowSrvConfigItem);
            });

            foreach (var vCashFlowSrvConfigItem in vCashFlowSrvConfigItems)
            {
                var vCashFlowSrvconfig = vCashFlowSrvConfigItem.Value;
                var vCashFlowSrvPort   = vCashFlowSrvconfig.iPort ?? (vCashFlowSrvconfig.strScheme == "https" ? 443 : 80);
                //var vCashFlowSrvPort = vCashFlowSrvconfig.iPort;

                var vIpAddresses = new List <IPAddress>();
                if (vCashFlowSrvconfig.strHost == "localhost")
                {
                    vIpAddresses.Add(IPAddress.IPv6Loopback);
                    vIpAddresses.Add(IPAddress.Loopback);
                }
                else if (IPAddress.TryParse(vCashFlowSrvconfig.strHost, out var vCurrentIpAddress))
                {
                    vIpAddresses.Add(vCurrentIpAddress);
                }
                else
                {
                    vIpAddresses.Add(IPAddress.IPv6Any);
                }

                foreach (var vAddress in vIpAddresses)
                {
                    ksoOptions.Listen(vAddress, vCashFlowSrvPort,
                                      listenOptions =>
                    {
                        if (vCashFlowSrvconfig.strScheme == "https")
                        {
                            var vCashFlowSrvCertificate = LoadCashFlowSrvCertificate(vCashFlowSrvconfig, vCashFlowServerEnvironment);
                            listenOptions.UseHttps(vCashFlowSrvCertificate);
                        }
                    });
                }
            }
        }
Beispiel #10
0
        public KestrelOwinServer(KestrelServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var wrappedOptions = Options.Create(options);

            var lifetime = new ApplicationLifetime();

            var loggerFactory = new LoggerFactory();

            Server = new KestrelServer(wrappedOptions, lifetime, loggerFactory);
        }
Beispiel #11
0
        public void KestrelServerDoesNotThrowIfNoDefaultHttpsProviderButManualListenOptions()
        {
            var mockDefaultHttpsProvider = new Mock <IDefaultHttpsProvider>();

            var serverOptions = new KestrelServerOptions();

            serverOptions.Listen(new IPEndPoint(IPAddress.Loopback, 0));

            using (var server = CreateServer(serverOptions, defaultHttpsProvider: null))
            {
                server.Features.Get <IServerAddressesFeature>().Addresses.Add("https://127.0.0.1:0");

                StartDummyApplication(server);
            }
        }
Beispiel #12
0
        public static void ConfigureEndpoints(this KestrelServerOptions options, int port)
        {
            IPAddress address = IPAddress.Loopback;

            options.Listen(address, port, listenOptions =>
            {
                IOptions <CranSettingsDto> settings       = (IOptions <CranSettingsDto>)options.ApplicationServices.GetService(typeof(IOptions <CranSettingsDto>));
                HttpsConnectionAdapterOptions httpOptions = new HttpsConnectionAdapterOptions
                {
                    ServerCertificate     = GetHttpsCertificate(settings.Value.DevelopmentCertStorePath, settings.Value?.DevelopmentCertStorePw),
                    ClientCertificateMode = ClientCertificateMode.NoCertificate
                };
                listenOptions.UseHttps(httpOptions);
            });
        }
 private void Initialize(ILoggerFactory loggerFactory, IKestrelTrace kestrelTrace)
 {
     LoggerFactory          = loggerFactory;
     Log                    = kestrelTrace;
     Scheduler              = PipeScheduler.ThreadPool;
     MockSystemClock        = new MockSystemClock();
     SystemClock            = MockSystemClock;
     DateHeaderValueManager = new DateHeaderValueManager(MockSystemClock);
     ConnectionManager      = new ConnectionManager(Log, ResourceCounter.Unlimited);
     HttpParser             = new HttpParser <Http1ParsingHandler>(Log.IsEnabled(LogLevel.Information));
     ServerOptions          = new KestrelServerOptions
     {
         AddServerHeader = false
     };
 }
Beispiel #14
0
        private static void ConfigureKestrel(WebHostBuilderContext builderContext, KestrelServerOptions options)
        {
            options.AddServerHeader                   = false;
            options.Limits.MaxRequestLineSize         = 1024;
            options.Limits.MaxRequestBodySize         = 1 << 20;
            options.Limits.MaxRequestHeadersTotalSize = 8192;

            var kestrelSection = builderContext.Configuration.GetSection("Kestrel");

            options.Configure(kestrelSection);

            if (kestrelSection.Get <KestrelServerOptions>() is { } kestrelOptions)
            {
                options.Limits.MaxConcurrentConnections = kestrelOptions.Limits.MaxConcurrentConnections;
            }
Beispiel #15
0
        public static KestrelServerOptions ListenHttpAndGrpcProtocols(
            this KestrelServerOptions options,
            IConfiguration config,
            string appId)
        {
            options.Limits.MinRequestBodyDataRate = null;

            options.Listen(IPAddress.Any, config.GetHttpPort(appId));

            options.Listen(IPAddress.Any,
                           config.GetGrpcPort(appId),
                           listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; });

            return(options);
        }
    public static void ConfigureEndpoints(this KestrelServerOptions options)
    {
        var configuration = options.ApplicationServices.GetRequiredService <IConfiguration>();
        var environment   = options.ApplicationServices.GetRequiredService <IHostingEnvironment>();

        var endpoints = configuration.GetSection("HttpServer:Endpoints")
                        .GetChildren()
                        .ToDictionary(section => section.Key, section =>
        {
            var endpoint = new EndpointConfiguration();
            section.Bind(endpoint);
            return(endpoint);
        });

        foreach (var endpoint in endpoints)
        {
            var config = endpoint.Value;
            var port   = config.Port ?? (config.Scheme == "https" ? 443 : 80);

            var ipAddresses = new List <IPAddress>();
            if (config.Host == "localhost")
            {
                ipAddresses.Add(IPAddress.IPv6Loopback);
                ipAddresses.Add(IPAddress.Loopback);
            }
            else if (IPAddress.TryParse(config.Host, out var address))
            {
                ipAddresses.Add(address);
            }
            else
            {
                ipAddresses.Add(IPAddress.IPv6Any);
            }

            foreach (var address in ipAddresses)
            {
                options.Listen(address, port,
                               listenOptions =>
                {
                    if (config.Scheme == "https")
                    {
                        var certificate = LoadCertificate(config, environment);
                        listenOptions.UseHttps(certificate);
                    }
                });
            }
        }
    }
Beispiel #17
0
        internal static ListenOptions ParseAddress(string address, KestrelServerOptions serverOptions, IDefaultHttpsProvider defaultHttpsProvider)
        {
            var parsedAddress = ServerAddress.FromUrl(address);
            var 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);
            }

            if (https)
            {
                options.KestrelServerOptions = serverOptions;
                defaultHttpsProvider.ConfigureHttps(options);
            }

            return(options);
        }
Beispiel #18
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);
        }
Beispiel #19
0
    public async Task WrapsAddressInUseExceptionAsIOException()
    {
        var addresses = new ServerAddressesFeature();

        addresses.InternalCollection.Add("http://localhost:5000");
        var options = new KestrelServerOptions();

        var addressBindContext = TestContextFactory.CreateAddressBindContext(
            addresses,
            options,
            NullLogger.Instance,
            endpoint => throw new AddressInUseException("already in use"));

        await Assert.ThrowsAsync <IOException>(() =>
                                               AddressBinder.BindAsync(options.ListenOptions, addressBindContext, CancellationToken.None));
    }
Beispiel #20
0
        static void Main(string[] args)
        {
            var options = new KestrelServerOptions();

            options.NoDelay     = true;
            options.ThreadCount = 2;
            var applicationLifetime = new ApplicationLifetime();
            var server = new KestrelServer(new OptionsWrapper <KestrelServerOptions>(options), applicationLifetime,
                                           new LoggerFactory());

            server.Features.Get <IServerAddressesFeature>().Addresses.Add("http://localhost:8888");
            server.Start(new HttpApp());
            Console.WriteLine("Listening on 8888. Press Enter to stop.");
            Console.ReadLine();
            server.Dispose();
        }
Beispiel #21
0
        private static void AddDevelopmentPorts(
            KestrelServerOptions options,
            int?httpPort,
            int?httpsPort,
            X509Certificate2?certificate)
        {
            if (httpPort.HasValue)
            {
                AddListener(options, httpPort.Value, null);
            }

            if (httpsPort.HasValue && certificate != null)
            {
                AddListener(options, httpsPort.Value, certificate);
            }
        }
    private static void ConfigureKestrel(KestrelServerOptions options, SettingsModel settings)
    {
        options.AddServerHeader    = false;
        var(httpPorts, httpsPorts) = GetPorts(settings);
        foreach (var port in httpPorts)
        {
            options.Listen(IPAddress.Any, port);
        }

        foreach (var port in httpsPorts)
        {
            options.Listen(IPAddress.Any, port,
                           listenOptions =>
                           listenOptions.UseHttps(settings.Web.PfxPath, settings.Web.PfxPassword));
        }
    }
Beispiel #23
0
        private static void AddListener(
            KestrelServerOptions options,
            int port,
            X509Certificate2 certificate)
        {
            options.Listen(
                new IPEndPoint(IPAddress.Loopback, port),
                listenOptions =>
            {
                listenOptions.UseConnectionLogging();

                if (null != certificate)
                {
                    listenOptions.UseHttps(certificate);
                }
            });
        }
        /// <summary>
        /// Configures AirDrop defaults for Kestrel.
        /// </summary>
        /// <param name="options">A <see cref="KestrelServerOptions"/> instance to configure.</param>
        /// <param name="cert">An <see cref="X509Certificate2"/> representing the certificate to use for the AirDrop HTTPS endpoint.</param>
        public static void ConfigureAirDropDefaults(this KestrelServerOptions options, X509Certificate2 cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }

            var airDropOptions = options.ApplicationServices.GetRequiredService <IOptions <AirDropOptions> >();

            options.ConfigureEndpointDefaults(
                endpointDefaults =>
            {
                endpointDefaults.UseHttps(cert);
            });

            options.ListenAnyIP(airDropOptions.Value.ListenPort);
        }
        public static void ConfigureEndpoints(this KestrelServerOptions options)
        {
            var configuration = options.ApplicationServices.GetRequiredService <IConfiguration>();

            var endpoints = configuration.GetSection("HttpServer:Endpoints")
                            .GetChildren()
                            .ToDictionary(section => section.Key, section => {
                var endpoint = new EndpointConfigurationSettings();
                section.Bind(endpoint);
                return(endpoint);
            });

            foreach (var endpoint in endpoints)
            {
                CreateEndPoint(options, endpoint.Value);
            }
        }
Beispiel #26
0
        private static void ConfigureKestrel(WebHostBuilderContext context, KestrelServerOptions serverOptions)
        {
            Log.Debug("ConfigureKestrel");
            var config = context.Configuration.Get <StartUpConfiguration>();

            config.SetDefaultSettings();

            var listenIp = IPAddress.Parse(config.ListeningIP);

            if (config.HttpPort.HasValue && config.HttpPort.Value != 0)
            {
                serverOptions.Listen(listenIp, config.HttpPort.Value, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                });
            }

            if (config.HttpsPort.HasValue && config.HttpsPort.Value != 0)
            {
                var certPath = PathHelper.GetFullPath(config.HttpsCertPath);
                Log.Debug(certPath);
                serverOptions.Listen(listenIp, config.HttpsPort.Value, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                    listenOptions.UseHttps(PathHelper.GetFullPath(config.HttpsCertPath), config.HttpsCertPassword);
                });
            }

            var adminListenIp = IPAddress.Parse(config.AdminSettings.ListeningIP);

            serverOptions.Listen(adminListenIp, config.AdminSettings.HttpsPort, options =>
            {
                options.Protocols = HttpProtocols.Http1AndHttp2;
                options.UseHttps(PathHelper.GetFullPath(config.AdminSettings.HttpsCertPath),
                                 config.AdminSettings.HttpsCertPassword);
            });

            var idpListenIp = IPAddress.Parse(config.IdpSettings.ListeningIP);

            serverOptions.Listen(idpListenIp, config.IdpSettings.HttpsPort, options =>
            {
                options.Protocols = HttpProtocols.Http1AndHttp2;

                options.UseHttps(PathHelper.GetFullPath(config.IdpSettings.HttpsCertPath), config.IdpSettings.HttpsCertPassword);
            });
        }
Beispiel #27
0
        public static void UseSslAuth(this KestrelServerOptions options)
        {
            var serviceProvider = options.ApplicationServices;
            var kvClient        = serviceProvider.GetRequiredService <IKeyVaultClient>();
            var configuration   = serviceProvider.GetRequiredService <IConfiguration>();
            var httpsSettings   = configuration.GetConfiguredSettings <HttpsSettings>();

            if (httpsSettings != null)
            {
                Console.WriteLine(
                    $"serving web request... port: {httpsSettings.PortNumber}, cert: {httpsSettings.SslCertSecretName}");
                var vaultSettings = configuration.GetConfiguredSettings <VaultSettings>();
                var x509          = kvClient.GetX509CertificateAsync(vaultSettings.VaultUrl, httpsSettings.SslCertSecretName)
                                    .GetAwaiter().GetResult();
                options.ListenAnyIP(httpsSettings.PortNumber, listenOptions => { listenOptions.UseHttps(x509); });
            }
        }
Beispiel #28
0
        public void StartWarnsWhenIgnoringIServerAddressesFeature(string ignoredAddress)
        {
            var testLogger     = new TestApplicationErrorLogger();
            var kestrelOptions = new KestrelServerOptions();

            // Directly configuring an endpoint using Listen causes the IServerAddressesFeature to be ignored.
            kestrelOptions.Listen(IPAddress.Loopback, 0);

            using (var server = CreateServer(kestrelOptions, testLogger))
            {
                server.Features.Get <IServerAddressesFeature>().Addresses.Add(ignoredAddress);
                StartDummyApplication(server);

                var warning = testLogger.Messages.Single(log => log.LogLevel == LogLevel.Warning);
                Assert.Contains("Overriding", warning.Message);
            }
        }
Beispiel #29
0
        public async Task StopAsyncCallsCompleteWhenFirstCallCompletes()
        {
            var options = new KestrelServerOptions
            {
                CodeBackedListenOptions =
                {
                    new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0))
                }
            };

            var unbind = new SemaphoreSlim(0);
            var stop   = new SemaphoreSlim(0);

            var mockTransport        = new Mock <IConnectionListener>();
            var mockTransportFactory = new Mock <IConnectionListenerFactory>();

            mockTransportFactory
            .Setup(transportFactory => transportFactory.BindAsync(It.IsAny <EndPoint>(), It.IsAny <CancellationToken>()))
            .Returns <EndPoint, CancellationToken>((e, token) =>
            {
                mockTransport
                .Setup(transport => transport.AcceptAsync(It.IsAny <CancellationToken>()))
                .Returns(new ValueTask <ConnectionContext>((ConnectionContext)null));
                mockTransport
                .Setup(transport => transport.UnbindAsync(It.IsAny <CancellationToken>()))
                .Returns(() => new ValueTask(unbind.WaitAsync()));
                mockTransport
                .Setup(transport => transport.DisposeAsync())
                .Returns(() => new ValueTask(stop.WaitAsync()));
                mockTransport
                .Setup(transport => transport.EndPoint).Returns(e);

                return(new ValueTask <IConnectionListener>(mockTransport.Object));
            });

            var mockLoggerFactory = new Mock <ILoggerFactory>();
            var mockLogger        = new Mock <ILogger>();

            mockLoggerFactory.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            var server = new KestrelServer(Options.Create(options), new List <IConnectionListenerFactory>()
            {
                mockTransportFactory.Object
            }, mockLoggerFactory.Object);
            await server.StartAsync(new DummyApplication(), CancellationToken.None);

            var stopTask1 = server.StopAsync(default);
Beispiel #30
0
    private static void ConfigureKestrel(WebHostBuilderContext builderContext, KestrelServerOptions options)
    {
        options.AddServerHeader                   = false;
        options.Limits.MaxRequestBodySize         = 0;
        options.Limits.MaxRequestHeadersTotalSize = 4096;

        // To match all single-chunk files
        options.Limits.MaxResponseBufferSize = 257 << 10;

        var kestrelSection = builderContext.Configuration.GetSection("Kestrel");

        options.Configure(kestrelSection);

        if (kestrelSection.Get <KestrelServerOptions>() is { } kestrelOptions)
        {
            options.Limits.MaxConcurrentConnections = kestrelOptions.Limits.MaxConcurrentConnections;
        }