Esempio n. 1
0
    public MessagePump(IOptions <HttpSysOptions> 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 HttpSysListener(_options, loggerFactory);
        _logger  = loggerFactory.CreateLogger <MessagePump>();

        if (_options.Authentication.Schemes != AuthenticationSchemes.None)
        {
            authentication.AddScheme(new AuthenticationScheme(HttpSysDefaults.AuthenticationScheme, displayName: _options.Authentication.AuthenticationDisplayName, handlerType: typeof(AuthenticationHandler)));
        }

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

        if (HttpApi.SupportsDelegation)
        {
            Features.Set <IServerDelegationFeature>(this);
        }

        _maxAccepts = _options.MaxAccepts;
    }
Esempio n. 2
0
 internal static HttpSysListener CreateDynamicHttpServer(string basePath, out string root, out string baseAddress)
 {
     lock (PortLock)
     {
         while (NextPort < MaxPort)
         {
             var port   = NextPort++;
             var prefix = UrlPrefix.Create("http", "localhost", port, basePath);
             root        = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port;
             baseAddress = prefix.ToString();
             var listener = new HttpSysListener(new HttpSysOptions(), new LoggerFactory());
             listener.Options.UrlPrefixes.Add(prefix);
             try
             {
                 listener.Start();
                 return(listener);
             }
             catch (HttpSysException)
             {
                 listener.Dispose();
             }
         }
         NextPort = BasePort;
     }
     throw new Exception("Failed to locate a free port.");
 }
Esempio n. 3
0
 internal static HttpSysListener CreateDynamicHttpServer(string basePath, out string root, out string baseAddress)
 {
     lock (PortLock)
     {
         while (NextPort < MaxPort)
         {
             var port   = NextPort++;
             var prefix = UrlPrefix.Create("http", "localhost", port, basePath);
             root        = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port;
             baseAddress = prefix.ToString();
             var options = new HttpSysOptions();
             options.UrlPrefixes.Add(prefix);
             options.RequestQueueName = prefix.Port; // Convention for use with CreateServerOnExistingQueue
             var listener = new HttpSysListener(options, new LoggerFactory());
             try
             {
                 listener.Start();
                 return(listener);
             }
             catch (HttpSysException ex)
             {
                 listener.Dispose();
                 if (ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS &&
                     ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SHARING_VIOLATION &&
                     ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_ACCESS_DENIED)
                 {
                     throw;
                 }
             }
         }
         NextPort = BasePort;
     }
     throw new Exception("Failed to locate a free port.");
 }
Esempio n. 4
0
        /// <summary>
        /// AcceptAsync extension with timeout. This extension should be used in all tests to prevent
        /// unexpected hangs when a request does not arrive.
        /// </summary>
        internal static async Task <RequestContext> AcceptAsync(this HttpSysListener server, TimeSpan timeout)
        {
            var factory = new TestRequestContextFactory(server);

            using var acceptContext = new AsyncAcceptContext(server, factory);

            async Task <RequestContext> AcceptAsync()
            {
                while (true)
                {
                    var requestContext = await server.AcceptAsync(acceptContext);

                    if (server.ValidateRequest(requestContext))
                    {
                        requestContext.InitializeFeatures();
                        return(requestContext);
                    }
                }
            }

            var acceptTask    = AcceptAsync();
            var completedTask = await Task.WhenAny(acceptTask, Task.Delay(timeout));

            if (completedTask == acceptTask)
            {
                return(await acceptTask);
            }
            else
            {
                server.Dispose();
                throw new TimeoutException("AcceptAsync has timed out.");
            }
        }
        public async Task Request_MultiplePrefixes(string requestUri, string expectedPathBase, string expectedPath)
        {
            // TODO: We're just doing this to get a dynamic port. This can be removed later when we add support for hot-adding prefixes.
            string root;
            var    server = Utilities.CreateHttpServerReturnRoot("/", out root);

            server.Dispose();
            server = new HttpSysListener(new HttpSysOptions(), new LoggerFactory());
            using (server)
            {
                var uriBuilder = new UriBuilder(root);
                foreach (string path in new[] { "/", "/11", "/2/3", "/2", "/11/2" })
                {
                    server.Options.UrlPrefixes.Add(UrlPrefix.Create(uriBuilder.Scheme, uriBuilder.Host, uriBuilder.Port, path));
                }
                server.Start();

                Task <string> responseTask = SendRequestAsync(root + requestUri);

                var context = await server.AcceptAsync(Utilities.DefaultTimeout);

                var request = context.Request;

                Assert.Equal(expectedPath, request.Path);
                Assert.Equal(expectedPathBase, request.PathBase);

                context.Dispose();

                string response = await responseTask;
                Assert.Equal(string.Empty, response);
            }
        }
Esempio n. 6
0
        internal static HttpSysListener CreateServer(string scheme, string host, int port, string path)
        {
            var listener = new HttpSysListener(new HttpSysOptions(), new LoggerFactory());

            listener.Options.UrlPrefixes.Add(UrlPrefix.Create(scheme, host, port, path));
            listener.Start();
            return(listener);
        }
Esempio n. 7
0
    internal static HttpSysListener CreateServer(Action <HttpSysOptions> configureOptions)
    {
        var options = new HttpSysOptions();

        configureOptions(options);
        var listener = new HttpSysListener(options, new LoggerFactory());

        listener.Start();
        return(listener);
    }
Esempio n. 8
0
        public void Server_RegisterUnavailablePrefix_ThrowsActionableHttpSysException()
        {
            var options = new HttpSysOptions();

            options.UrlPrefixes.Add(UrlPrefix.Create("http", "example.org", "8080", ""));
            var listener = new HttpSysListener(options, new LoggerFactory());

            var exception = Assert.Throws <HttpSysException>(() => listener.Start());

            Assert.Equal((int)UnsafeNclNativeMethods.ErrorCodes.ERROR_ACCESS_DENIED, exception.ErrorCode);
            Assert.Contains($@"netsh http add urlacl url=http://example.org:8080/ user={Environment.UserDomainName}\{Environment.UserName}", exception.Message);
        }
Esempio n. 9
0
        internal static HttpSysListener CreateServerOnExistingQueue(AuthenticationSchemes authScheme, bool allowAnonymos, string requestQueueName)
        {
            var options = new HttpSysOptions();

            options.RequestQueueMode              = RequestQueueMode.Attach;
            options.RequestQueueName              = requestQueueName;
            options.Authentication.Schemes        = authScheme;
            options.Authentication.AllowAnonymous = allowAnonymos;
            var listener = new HttpSysListener(options, new LoggerFactory());

            listener.Start();
            return(listener);
        }
Esempio n. 10
0
    public void Server_RegisterUnavailablePrefix_ThrowsActionableHttpSysException()
    {
        using var server1 = Utilities.CreateHttpServer(out var address1);

        var options = new HttpSysOptions();

        options.UrlPrefixes.Add(address1);
        using var listener = new HttpSysListener(options, new LoggerFactory());

        var exception = Assert.Throws <HttpSysException>(() => listener.Start());

        Assert.Equal((int)UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS, exception.ErrorCode);
        Assert.Contains($"The prefix '{address1}' is already registered.", exception.Message);
    }
Esempio n. 11
0
        /// <summary>
        /// AcceptAsync extension with timeout. This extension should be used in all tests to prevent
        /// unexpected hangs when a request does not arrive.
        /// </summary>
        internal static async Task <RequestContext> AcceptAsync(this HttpSysListener server, TimeSpan timeout)
        {
            var acceptTask    = server.AcceptAsync();
            var completedTask = await Task.WhenAny(acceptTask, Task.Delay(timeout));

            if (completedTask == acceptTask)
            {
                return(await acceptTask);
            }
            else
            {
                server.Dispose();
                throw new TimeoutException("AcceptAsync has timed out.");
            }
        }
Esempio n. 12
0
 public RequestContext(HttpSysListener server, uint?bufferSize, ulong requestId)
     : base(server.MemoryPool, bufferSize, requestId, server.Options.UseLatin1RequestHeaders)
 {
     Server             = server;
     AllowSynchronousIO = server.Options.AllowSynchronousIO;
 }
Esempio n. 13
0
 public RequestContext(IHttpApplication <TContext> application, MessagePump messagePump, HttpSysListener server, uint?bufferSize, ulong requestId)
     : base(server, bufferSize, requestId)
 {
     _application = application;
     _messagePump = messagePump;
 }
Esempio n. 14
0
 public TestRequestContextFactory(HttpSysListener server)
 {
     _server = server;
 }
    private HttpSysListener CreateServerOnExistingQueue(AuthenticationSchemes authScheme, bool allowAnonymos, HttpSysListener baseServer, out string address)
    {
        string serverAddress     = null;
        var    baseServerAddress = baseServer.Options.UrlPrefixes.First().ToString();
        var    server            = Utilities.CreateServer(options =>
        {
            options.RequestQueueName              = baseServer.Options.RequestQueueName;
            options.Authentication.Schemes        = authScheme;
            options.Authentication.AllowAnonymous = allowAnonymos;
            serverAddress = ConfigureServer(options, baseServerAddress);
        });

        address = serverAddress;
        return(server);
    }