コード例 #1
0
        public async Task WrapsAddressInUseExceptionAsIOException()
        {
            var addresses = new ServerAddressesFeature();

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

            var addressBindContext = new AddressBindContext
            {
                ServerAddressesFeature = addresses,
                ServerOptions          = options,
                Logger        = NullLogger.Instance,
                CreateBinding = endpoint => throw new AddressInUseException("already in use"),
            };

            await Assert.ThrowsAsync <IOException>(() =>
                                                   AddressBinder.BindAsync(options.ListenOptions, addressBindContext));
        }
コード例 #2
0
        public async Task DefaultAddressBinderWithoutDevCertButHttpsConfiguredBindsToHttpsPorts()
        {
            var x509Certificate2 = TestResources.GetTestCertificate();
            var logger           = new MockLogger();
            var addresses        = new ServerAddressesFeature();
            var services         = new ServiceCollection();

            services.AddLogging();
            var options = new KestrelServerOptions()
            {
                // This stops the dev cert from being loaded
                IsDevCertLoaded     = true,
                ApplicationServices = services.BuildServiceProvider()
            };

            options.ConfigureEndpointDefaults(e =>
            {
                if (e.IPEndPoint.Port == 5001)
                {
                    e.UseHttps(new HttpsConnectionAdapterOptions {
                        ServerCertificate = x509Certificate2
                    });
                }
            });

            var endpoints = new List <ListenOptions>();

            var addressBindContext = new AddressBindContext
            {
                ServerAddressesFeature = addresses,
                ServerOptions          = options,
                Logger        = logger,
                CreateBinding = listenOptions =>
                {
                    endpoints.Add(listenOptions);
                    return(Task.CompletedTask);
                },
            };

            await AddressBinder.BindAsync(options.ListenOptions, addressBindContext);

            Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5000 && !e.IsTls);
            Assert.Contains(endpoints, e => e.IPEndPoint.Port == 5001 && e.IsTls);
        }
コード例 #3
0
        public static void BuildDispatcherWithConfiguration_XmlSerializer()
        {
            var serviceAddress = "http://localhost/dummy";

            var services = new ServiceCollection();

            services.AddServiceModelServices();

            var serverAddressesFeature = new ServerAddressesFeature();

            serverAddressesFeature.Addresses.Add(serviceAddress);

            IServer server = new MockServer();

            server.Features.Set <IServerAddressesFeature>(serverAddressesFeature);
            services.AddSingleton(server);

            var serviceProvider = services.BuildServiceProvider();
            var serviceBuilder  = serviceProvider.GetRequiredService <IServiceBuilder>();

            serviceBuilder.AddService <SimpleXmlSerializerService>();

            var binding = new CustomBinding("BindingName", "BindingNS");

            binding.Elements.Add(new MockTransportBindingElement());
            serviceBuilder.AddServiceEndpoint <SimpleXmlSerializerService, ISimpleXmlSerializerService>(binding, serviceAddress);

            var dispatcherBuilder = serviceProvider.GetRequiredService <IDispatcherBuilder>();
            var dispatchers       = dispatcherBuilder.BuildDispatchers(typeof(SimpleXmlSerializerService));

            Assert.Single(dispatchers);

            var serviceDispatcher = dispatchers[0];

            Assert.Equal("foo", serviceDispatcher.Binding.Scheme);
            Assert.Equal(serviceAddress, serviceDispatcher.BaseAddress.ToString());

            IChannel mockChannel    = new MockReplyChannel(serviceProvider);
            var      dispatcher     = serviceDispatcher.CreateServiceChannelDispatcher(mockChannel);
            var      requestContext = XmlSerializerTestRequestContext.Create(serviceAddress);

            dispatcher.DispatchAsync(requestContext, CancellationToken.None).Wait();
            requestContext.ValidateReply();
        }
コード例 #4
0
        public MessagePump(IOptions <AzureRelayOptions> options, ILoggerFactory loggerFactory, IAuthenticationSchemeProvider authentication)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            _options = options.Value;
            Listener = new AzureRelayListener(_options, loggerFactory, ProcessRequest);
            _logger  = LogHelper.CreateLogger(loggerFactory, typeof(MessagePump));

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);

            _processRequest = new Action <object>(ProcessRequestAsync);
        }
コード例 #5
0
    public async Task FlowsCancellationTokenToCreateBinddingCallback()
    {
        var addresses = new ServerAddressesFeature();

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

        var addressBindContext = TestContextFactory.CreateAddressBindContext(
            addresses,
            options,
            NullLogger.Instance,
            (endpoint, cancellationToken) =>
        {
            cancellationToken.ThrowIfCancellationRequested();
            return(Task.CompletedTask);
        });

        await Assert.ThrowsAsync <OperationCanceledException>(() =>
                                                              AddressBinder.BindAsync(options.ListenOptions, addressBindContext, new CancellationToken(true)));
    }
コード例 #6
0
        public Task Start(string url, Action <BuildFunc> configure, CancellationToken cancellationToken)
        {
            var application = ConfigureApplication(configure);

            var addresses = Server.Features.Get <IServerAddressesFeature>();

            if (addresses == null)
            {
                Server.Features.Set(addresses = new ServerAddressesFeature());
            }

            addresses.Addresses.Add(url);

            foreach (var address in addresses.Addresses)
            {
                Console.WriteLine($"Now listening on: {address}");
            }

            return(Server.StartAsync(application, cancellationToken));
        }
コード例 #7
0
        public void Start(string url, Action <BuildFunc> configure)
        {
            var application = ConfigureApplication(configure);

            var addresses = Server.Features.Get <IServerAddressesFeature>();

            if (addresses == null)
            {
                Server.Features.Set(addresses = new ServerAddressesFeature());
            }

            addresses.Addresses.Add(url);

            foreach (var address in addresses.Addresses)
            {
                Console.WriteLine($"Now listening on: {address}");
            }

            Server.Start(application);
        }
コード例 #8
0
        public async Task DefaultsToIPv6AnyOnInvalidIPAddress(string host)
        {
            var addresses = new ServerAddressesFeature();

            addresses.Addresses.Add($"http://{host}");
            var options = new List <ListenOptions>();

            var tcs = new TaskCompletionSource <ListenOptions>();
            await AddressBinder.BindAsync(addresses,
                                          options,
                                          NullLogger.Instance,
                                          endpoint =>
            {
                tcs.TrySetResult(endpoint);
                return(Task.CompletedTask);
            });

            var result = await tcs.Task;

            Assert.Equal(IPAddress.IPv6Any, result.IPEndPoint.Address);
        }
コード例 #9
0
        public MessagePump(IOptions <WebListenerOptions> options, ILoggerFactory loggerFactory)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }

            _listener        = options.Value?.Listener ?? new Microsoft.Net.Http.Server.WebListener(loggerFactory);
            _logger          = LogHelper.CreateLogger(loggerFactory, typeof(MessagePump));
            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);

            _processRequest = new Action <object>(ProcessRequestAsync);
            _maxAccepts     = DefaultMaxAccepts;
            _shutdownSignal = new ManualResetEvent(false);
        }
コード例 #10
0
        public async Task Start_Should_Register_When_RegisterMDNSsIsTrue()
        {
            _option.RegistermDNS = true;
            _option.ServerName   = string.Empty;

            var addresses = new ServerAddressesFeature();

            addresses.Addresses.Add("local:8888");
            _server.Features.Get <IServerAddressesFeature>().Returns(addresses);

            _things.Add(new FakeThing());

            var find = false;

            using var discovery          = new ServiceDiscovery();
            discovery.ServiceDiscovered += (sender, name) =>
            {
                if (name.Labels.Contains("Fake"))
                {
                    find = true;
                }
            };

            discovery.ServiceInstanceDiscovered += (sender, args) =>
            {
                if (args.ServiceInstanceName.Labels.Contains("Fake"))
                {
                    find = true;
                }
            };

            var host = new MDnsRegisterHostedService(_server, _option, _things, _logger);
            await host.StartAsync(CancellationToken.None);

            await Task.Delay(TimeSpan.FromSeconds(10));

            find.Should().BeTrue();

            await host.StopAsync(CancellationToken.None);
        }
コード例 #11
0
        public async Task FallbackToIPv4WhenIPv6AnyBindFails(string address)
        {
            var logger    = new MockLogger();
            var addresses = new ServerAddressesFeature();

            addresses.InternalCollection.Add(address);
            var options = new KestrelServerOptions();

            var ipV6Attempt = false;
            var ipV4Attempt = false;

            var addressBindContext = new AddressBindContext
            {
                ServerAddressesFeature = addresses,
                ServerOptions          = options,
                Logger        = logger,
                CreateBinding = endpoint =>
                {
                    if (endpoint.IPEndPoint.Address == IPAddress.IPv6Any)
                    {
                        ipV6Attempt = true;
                        throw new InvalidOperationException("EAFNOSUPPORT");
                    }

                    if (endpoint.IPEndPoint.Address == IPAddress.Any)
                    {
                        ipV4Attempt = true;
                    }

                    return(Task.CompletedTask);
                },
            };

            await AddressBinder.BindAsync(options.ListenOptions, addressBindContext);

            Assert.True(ipV4Attempt, "Should have attempted to bind to IPAddress.Any");
            Assert.True(ipV6Attempt, "Should have attempted to bind to IPAddress.IPv6Any");
            Assert.Contains(logger.Messages, f => f.Equals(CoreStrings.FormatFallbackToIPv4Any(80)));
        }
コード例 #12
0
        public void Test1()
        {
            var webHostBuilder = new WebHostBuilder();

            var Features         = new FeatureCollection();
            var _serverAddresses = new ServerAddressesFeature();

            Features.Set <IServerAddressesFeature>(_serverAddresses);

            _serverAddresses.Addresses.Add("http://localhost");

            var _server = new TestServer(webHostBuilder.UseStartup <UnitTest1>(), Features);

            var _client = _server.CreateClient();

            IServiceCollection services = new ServiceCollection();

            services.AddOptions();
            services.AddLogging();
            services.AddTransient <IServer, TestServer>(p => _server);

            services.AddTransient(p => Task.CompletedTask);

            var configurationBuilder = new ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var configuration = configurationBuilder.Build();

            services.UseConsul(configuration);

            var provider = services.BuildServiceProvider();

            var hostservice = provider.GetService <IHostedService>();

            Assert.IsType <ConsulHostedService>(hostservice);

            hostservice.StartAsync(CancellationToken.None).GetAwaiter().GetResult();
        }
コード例 #13
0
        public static void BuildDispatcherWithConfiguration_Singleton_WellKnown()
        {
            string serviceAddress = "http://localhost/dummy";
            var    services       = new ServiceCollection();

            services.AddLogging();
            services.AddServiceModelServices();
            var serverAddressesFeature = new ServerAddressesFeature();

            serverAddressesFeature.Addresses.Add(serviceAddress);
            IServer server = new MockServer();

            server.Features.Set <IServerAddressesFeature>(serverAddressesFeature);
            services.AddSingleton(server);
            services.AddSingleton(new SimpleSingletonService());
            var serviceProvider = services.BuildServiceProvider();
            var serviceBuilder  = serviceProvider.GetRequiredService <IServiceBuilder>();

            serviceBuilder.AddService <SimpleSingletonService>();
            var binding = new CustomBinding("BindingName", "BindingNS");

            binding.Elements.Add(new MockTransportBindingElement());
            serviceBuilder.AddServiceEndpoint <SimpleSingletonService, ISimpleService>(binding, serviceAddress);
            var dispatcherBuilder = serviceProvider.GetRequiredService <IDispatcherBuilder>();
            var dispatchers       = dispatcherBuilder.BuildDispatchers(typeof(SimpleSingletonService));

            Assert.Single(dispatchers);
            var serviceDispatcher = dispatchers[0];

            Assert.Equal("foo", serviceDispatcher.Binding.Scheme);
            Assert.Equal(serviceAddress, serviceDispatcher.BaseAddress.ToString());
            IChannel mockChannel    = new MockReplyChannel(serviceProvider);
            var      dispatcher     = serviceDispatcher.CreateServiceChannelDispatcherAsync(mockChannel).Result;
            var      requestContext = TestRequestContext.Create(serviceAddress);

            dispatcher.DispatchAsync(requestContext).Wait();
            Assert.True(requestContext.WaitForReply(TimeSpan.FromSeconds(5)), "Dispatcher didn't send reply");
            requestContext.ValidateReply();
        }
コード例 #14
0
        private static IServiceDispatcher BuildDispatcher <TService>(ServiceCollection services, string serviceAddress) where TService : class, ISimpleService
        {
            services.AddServiceModelServices();
            var serverAddressesFeature = new ServerAddressesFeature();

            serverAddressesFeature.Addresses.Add(serviceAddress);
            IServer server = new MockServer();

            server.Features.Set <IServerAddressesFeature>(serverAddressesFeature);
            services.AddSingleton(server);
            var serviceProvider = services.BuildServiceProvider();
            var serviceBuilder  = serviceProvider.GetRequiredService <IServiceBuilder>();

            serviceBuilder.AddService <TService>();
            var binding = new CustomBinding("BindingName", "BindingNS");

            binding.Elements.Add(new MockTransportBindingElement());
            serviceBuilder.AddServiceEndpoint <TService, ISimpleService>(binding, serviceAddress);
            var dispatcherBuilder = serviceProvider.GetRequiredService <IDispatcherBuilder>();
            var dispatchers       = dispatcherBuilder.BuildDispatchers(typeof(TService));

            return(dispatchers[0]);
        }
コード例 #15
0
ファイル: Server.cs プロジェクト: Neurosploit/TCPServer
        public Server(IServiceProvider serviceProvider, ServerOptions options)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _Options = options;

            var serverAddressesFeature = new ServerAddressesFeature();

            serverAddressesFeature.Addresses.Add(new UriBuilder("http", options.EndPoint.Address.ToString(), options.EndPoint.Port).Uri.AbsoluteUri);

            Features.Set <IHttpRequestFeature>(new HttpRequestFeature());
            Features.Set <IHttpResponseFeature>(new HttpResponseFeature());
            Features.Set <IServerAddressesFeature>(serverAddressesFeature);
            Features.Set <IServiceProvidersFeature>(new ServiceProvidersFeature()
            {
                RequestServices = serviceProvider
            });
        }
コード例 #16
0
        public async Task StartAsync <TContext>(IHttpApplication <TContext> application, CancellationToken cancellationToken)
        {
            logger.LogDebug("The server is starting...");

            if (session.Session == null)
            {
                throw new InvalidOperationException("The session has not been started.");
            }

            loggingScope?.Dispose();
            loggingScope = logger.BeginScope(new
            {
                host = session.Session.Properties.Host,
                vpn  = session.Session.Properties.VPNName
            });

            logger.LogDebug("Creating topics...");

            var addressFeature = new ServerAddressesFeature();

            foreach (var topic in options.Value.Topics)
            {
                topics.Add(ContextFactory.Instance.CreateTopic(topic));
                addressFeature.Addresses.Add(topic);
            }

            Features.Set <IServerAddressesFeature>(addressFeature);

            foreach (var topic in topics)
            {
                using var scope = logger.BeginScope(new { topic = topic.Name });

                logger.LogDebug("Subscribing...");

                var subscribed = session.SessionEvents
                                 .FirstAsync(e =>
                                             e.Event == SessionEvent.SubscriptionOk ||
                                             e.Event == SessionEvent.SubscriptionError)
                                 .RunAsync(cancellationToken);
                var subscribeReturnCode = session.Session.Subscribe(topic, false);

                if (subscribeReturnCode == ReturnCode.SOLCLIENT_OK)
                {
                    logger.LogDebug("Subscribed Solace topic.");
                }
                else if (subscribeReturnCode == ReturnCode.SOLCLIENT_IN_PROGRESS)
                {
                    var subscribedEvent = await subscribed;

                    if (subscribedEvent.Event == SessionEvent.SubscriptionOk)
                    {
                        logger.LogDebug("Subscribed Solace topic.");
                    }
                    else
                    {
                        using (logger.BeginScope(new { sessionEvent = subscribedEvent.Event }))
                            logger.LogError("Error subscribing Solace topic: " + subscribedEvent.Info);
                    }
                    subscribed.Dispose();
                }
                else
                {
                    using (logger.BeginScope(new { code = subscribeReturnCode }))
                        logger.LogError("Error subscribing Solace topic.");
                    subscribed.Dispose();
                }
            }

            logger.LogDebug("Starting message processing loop...");

            messageProcessingSubject = session
                                       .Messages
                                       .Where(ShouldProcessMessage)
                                       .SelectMany(message => ProcessMessages(application, message, GetData(message)))
                                       .RunAsync(messageProcessingCancellation.Token);

            logger.LogInformation("The server has started successfully.");
        }