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); } }
private void ParseAddresses(ICollection <string> addresses, Microsoft.Net.Http.Server.WebListener listener) { foreach (var value in addresses) { listener.UrlPrefixes.Add(UrlPrefix.Create(value)); } }
private static void Listen(KestrelServerOptions options, IConfigurationRoot config, string url) { var urlPrefix = UrlPrefix.Create(url); var endpoint = CreateIPEndPoint(urlPrefix); options.Listen(endpoint, listenOptions => { var connectionFilter = GetConnectionFilter(config); if (connectionFilter != null) { listenOptions.ConnectionAdapters.Add(connectionFilter); } #if !NETCOREAPP2_0 && !NETCOREAPP2_1 if (Protocol.Equals("h2", StringComparison.OrdinalIgnoreCase)) { listenOptions.Protocols = HttpProtocols.Http1AndHttp2; } else if (Protocol.Equals("h2c", StringComparison.OrdinalIgnoreCase)) { listenOptions.Protocols = HttpProtocols.Http2; } #endif if (urlPrefix.IsHttps) { listenOptions.UseHttps("testCert.pfx", "testPassword"); } }); }
internal static IHost CreateDynamicHost(string basePath, out string root, out string baseAddress, Action <HttpSysOptions> configureOptions, RequestDelegate app) { var prefix = UrlPrefix.Create("http", "localhost", "0", basePath); var builder = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseHttpSys(options => { options.UrlPrefixes.Add(prefix); configureOptions(options); }) .Configure(appBuilder => appBuilder.Run(app)); }); var host = builder.Build(); host.Start(); var options = host.Services.GetRequiredService <IOptions <HttpSysOptions> >(); prefix = options.Value.UrlPrefixes.First(); // Has new port root = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port; baseAddress = prefix.ToString(); return(host); }
internal static IServer CreateDynamicHttpServer(string basePath, AuthenticationSchemes authType, out string root, out string baseAddress, RequestDelegate app) { 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 server = new MessagePump(Options.Create(new WebListenerOptions()), new LoggerFactory()); server.Features.Get <IServerAddressesFeature>().Addresses.Add(baseAddress); server.Listener.AuthenticationManager.AuthenticationSchemes = authType; try { server.Start(new DummyApplication(app)); return(server); } catch (WebListenerException) { } } NextPort = BasePort; } throw new Exception("Failed to locate a free port."); }
public void PathBaseIsNotNormalized() { var urlPrefix = UrlPrefix.Create("http://localhost:8080/p\u0041\u030Athbase"); Assert.False(urlPrefix.Path.IsNormalized(NormalizationForm.FormC)); Assert.Equal("/p\u0041\u030Athbase/", urlPrefix.Path); }
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."); }
internal static IServer CreateDynamicHttpsServer(string basePath, out string root, out string baseAddress, Action <HttpSysOptions> configureOptions, RequestDelegate app, ILoggerFactory loggerFactory = null) { lock (PortLock) { while (NextHttpsPort < MaxHttpsPort) { var port = NextHttpsPort++; var prefix = UrlPrefix.Create("https", "localhost", port, basePath); root = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port; baseAddress = prefix.ToString(); var server = CreatePump(loggerFactory); server.Features.Get <IServerAddressesFeature>().Addresses.Add(baseAddress); configureOptions(server.Listener.Options); try { server.StartAsync(new DummyApplication(app), CancellationToken.None).Wait(); return(server); } catch (HttpSysException) { } } NextHttpsPort = BaseHttpsPort; } throw new Exception("Failed to locate a free port."); }
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."); }
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); }
internal static IServer CreateServer(string scheme, string host, int port, string path, RequestDelegate app) { var server = new MessagePump(Options.Create(new WebListenerOptions()), new LoggerFactory()); server.Features.Get <IServerAddressesFeature>().Addresses.Add(UrlPrefix.Create(scheme, host, port, path).ToString()); server.Start(new DummyApplication(app)); return(server); }
protected override string ConfigureServer(HttpSysOptions options, string baseServerAddress) { options.RequestQueueMode = RequestQueueMode.CreateOrAttach; var basePrefix = UrlPrefix.Create(baseServerAddress); var prefix = UrlPrefix.Create(basePrefix.Scheme, basePrefix.Host, basePrefix.Port, "/server"); options.UrlPrefixes.Add(prefix); return(prefix.ToString()); }
public void UrlsAreParsedCorrectly(string url, string scheme, string host, string port, string pathBase, string toString) { var urlPrefix = UrlPrefix.Create(url); Assert.Equal(scheme, urlPrefix.Scheme); Assert.Equal(host, urlPrefix.Host); Assert.Equal(port, urlPrefix.Port); Assert.Equal(pathBase, urlPrefix.Path); Assert.Equal(toString ?? url, urlPrefix.ToString()); }
internal static AzureRelayListener CreateServer(string baseUrl, string path) { var listener = new AzureRelayListener(new AzureRelayOptions() { TokenProvider = Microsoft.Azure.Relay.AspNetCore.Utilities.CreateTokenProvider() }, new LoggerFactory()); listener.Options.UrlPrefixes.Add(UrlPrefix.Create(new Uri(new Uri(baseUrl), path).AbsoluteUri)); listener.Start(); return(listener); }
public static string RetrieveHostUrl(string url) { if (!string.IsNullOrEmpty(url)) { var uri = UrlPrefix.Create(url); if (uri.Host == "+" || uri.Host == "*") { return(uri.Scheme + "://localhost:" + uri.Port); } } return(url); }
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); }
public async Task Server_ConnectExistingQueueName_Success(RequestQueueMode queueMode) { string address; var queueName = Guid.NewGuid().ToString(); // First create the queue. HttpRequestQueueV2Handle requestQueueHandle = null; var statusCode = HttpApi.HttpCreateRequestQueue( HttpApi.Version, queueName, IntPtr.Zero, 0, out requestQueueHandle); Assert.True(statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS); // Now attach to the existing one using (Utilities.CreateHttpServer(out address, httpContext => { return(Task.FromResult(0)); }, options => { options.RequestQueueName = queueName; options.RequestQueueMode = queueMode; })) { var psi = new ProcessStartInfo("netsh", "http show servicestate view=requestq") { RedirectStandardOutput = true }; using var process = Process.Start(psi); process.Start(); var netshOutput = await process.StandardOutput.ReadToEndAsync(); Assert.Contains(queueName, netshOutput); var prefix = UrlPrefix.Create(address); switch (queueMode) { case RequestQueueMode.Attach: Assert.Equal("0", prefix.Port); break; case RequestQueueMode.CreateOrAttach: Assert.NotEqual("0", prefix.Port); Assert.Contains(address, netshOutput, StringComparison.OrdinalIgnoreCase); break; } } }
public void StartProcess(ProcessHostInfo host) { if (string.IsNullOrWhiteSpace(host?.Domain)) { return; } string startupArgs = $"/urls=\"{UrlPrefix.Create("http", host.Domain, host.Port, string.Empty)}\" /process=child"; var process = GetOrphanedProcess(startupArgs, host) ?? new ChildProcess(host, startupArgs, _logger); process.StartTime = DateTime.Now; StartProcess(process); }
internal static IServer CreateDynamicHttpServer(string basePath, out string root, out string baseAddress, Action <HttpSysOptions> configureOptions, RequestDelegate app) { var prefix = UrlPrefix.Create("http", "localhost", "0", basePath); var server = CreatePump(configureOptions); server.Features.Get <IServerAddressesFeature>().Addresses.Add(prefix.ToString()); server.StartAsync(new DummyApplication(app), CancellationToken.None).Wait(); prefix = server.Listener.Options.UrlPrefixes.First(); // Has new port root = prefix.Scheme + "://" + prefix.Host + ":" + prefix.Port; baseAddress = prefix.ToString(); return(server); }
private IServer CreateServer(out string root, RequestDelegate app) { // TODO: We're just doing this to get a dynamic port. This can be removed later when we add support for hot-adding prefixes. var dynamicServer = Utilities.CreateHttpServerReturnRoot("/", out root, app); dynamicServer.Dispose(); var rootUri = new Uri(root); var server = new MessagePump(Options.Create(new WebListenerOptions()), new LoggerFactory()); foreach (string path in new[] { "/", "/11", "/2/3", "/2", "/11/2" }) { server.Listener.UrlPrefixes.Add(UrlPrefix.Create(rootUri.Scheme, rootUri.Host, rootUri.Port, path)); } server.Start(new DummyApplication(app)); return(server); }
internal static AzureRelayListener CreateDynamicHttpServer(string basePath, out string root, out string baseAddress, TokenProvider tp = null) { if (basePath.StartsWith("/")) { basePath = basePath.Substring(1); } var rootUri = new Uri(Microsoft.Azure.Relay.AspNetCore.Utilities.GetRelayUrl()); var prefix = UrlPrefix.Create(new Uri(rootUri, basePath).AbsoluteUri, tp != null ? tp : CreateTokenProvider()); root = rootUri.ToString(); baseAddress = prefix.FullPrefix; var listener = new AzureRelayListener(new AzureRelayOptions(), new LoggerFactory()); listener.Options.UrlPrefixes.Add(prefix); listener.Start(); return(listener); }
private void BuildWebHost(string[] args) { IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args) .UseContentRoot(_contentRoot) .CaptureStartupErrors(true) .UseShutdownTimeout(TimeSpan.FromSeconds(15)) .UseHttpSys(o => { o.Authentication.AllowAnonymous = true; o.Authentication.Schemes = AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM; o.UrlPrefixes.Add(UrlPrefix.Create("http", "*", 5000, "/")); o.UrlPrefixes.Add(UrlPrefix.Create("https", "*", 5001, "/")); }) .UseStartup <Startup>(); _webHost = builder.Build(); }
private static void Listen(KestrelServerOptions options, IConfigurationRoot config, string url) { var urlPrefix = UrlPrefix.Create(url); var endpoint = CreateIPEndPoint(urlPrefix); options.Listen(endpoint, listenOptions => { var connectionFilter = GetConnectionFilter(config); if (connectionFilter != null) { listenOptions.ConnectionAdapters.Add(connectionFilter); } if (urlPrefix.IsHttps) { listenOptions.UseHttps("testCert.pfx", "testPassword"); } }); }
public async Task Server_SetQueueLimit_Success() { // This is just to get a dynamic port string address; using (Utilities.CreateHttpServer(out address, httpContext => Task.FromResult(0))) { } var server = new MessagePump(Options.Create(new WebListenerOptions()), new LoggerFactory()); server.Listener.UrlPrefixes.Add(UrlPrefix.Create(address)); server.Listener.SetRequestQueueLimit(1001); using (server) { server.Start(new DummyApplication(httpContext => Task.FromResult(0))); string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); } }
public async Task Server_SetQueueLimit_Success() { // This is just to get a dynamic port string address; using (Utilities.CreateHttpServer(out address, httpContext => Task.FromResult(0))) { } var server = Utilities.CreatePump(); server.Listener.Options.UrlPrefixes.Add(UrlPrefix.Create(address)); server.Listener.Options.RequestQueueLimit = 1001; using (server) { await server.StartAsync(new DummyApplication(), CancellationToken.None); string response = await SendRequestAsync(address); Assert.Equal(string.Empty, response); } }
public void CreateThrowsForUrlsWithoutHost(string url) { Assert.Throws <ArgumentNullException>(() => UrlPrefix.Create(url)); }
public void CreateThrowsForUrlsWithInvalidPorts(string url) { Assert.Throws <FormatException>(() => UrlPrefix.Create(url)); }
public void CreateThrowsForUrlsWithEmptyScheme(string url) { Assert.Throws <ArgumentOutOfRangeException>(() => UrlPrefix.Create(url)); }
public static async Task Run(string[] args) { using (WebListener listener = new WebListener()) { listener.UrlPrefixes.Add(UrlPrefix.Create("http://localhost:8080")); listener.Start(); Console.WriteLine("Running..."); while (true) { RequestContext context = await listener.GetContextAsync(); Console.WriteLine("Accepted"); // Context: // context.User; // context.DisconnectToken // context.Dispose() // context.Abort(); // Request // context.Request.ProtocolVersion // context.Request.Headers // context.Request.Method // context.Request.Body // Content-Length - long? // Content-Type - string // IsSecureConnection // HasEntityBody // TODO: Request fields // Content-Encoding - Encoding // Host // Client certs - GetCertAsync, CertErrors // Cookies // KeepAlive // QueryString (parsed) // RequestTraceIdentifier // RawUrl // URI // IsWebSocketRequest // LocalEndpoint vs LocalIP & LocalPort // RemoteEndpoint vs RemoteIP & RemotePort // AcceptTypes string[] // ServiceName // TransportContext // Response byte[] bytes = Encoding.ASCII.GetBytes("Hello World: " + DateTime.Now); if (context.IsWebSocketRequest()) { Console.WriteLine("WebSocket"); WebSocket webSocket = await context.AcceptWebSocketAsync(); await webSocket.SendAsync(new ArraySegment <byte>(bytes, 0, bytes.Length), WebSocketMessageType.Text, true, CancellationToken.None); await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Goodbye", CancellationToken.None); webSocket.Dispose(); } else { Console.WriteLine("Hello World"); context.Response.ContentLength = bytes.Length; context.Response.ContentType = "text/plain"; context.Response.Body.Write(bytes, 0, bytes.Length); context.Dispose(); } } } }
public void CreateThrowsForUrlsWithoutSchemeDelimiter(string url) { Assert.Throws <FormatException>(() => UrlPrefix.Create(url)); }