Exemplo n.º 1
0
    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.");
    }
Exemplo n.º 2
0
        public void RemoveLeadingSegmentsCanMatchEntireUrl()
        {
            var prefix = new UrlPrefix("foo");

            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/"), ("~/"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/foo"), ("~/"));
        }
Exemplo n.º 3
0
        public void RemoveLeadingSegmentsIsCaseInsensitive()
        {
            var prefix = new UrlPrefix("Foo");

            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/bar"), ("~/bar"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/FOO/BAR"), ("~/BAR"));
        }
Exemplo n.º 4
0
    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);
    }
Exemplo n.º 5
0
        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");
                }
            });
        }
        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);
            }
        }
Exemplo n.º 7
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.");
 }
Exemplo n.º 8
0
 private void ParseAddresses(ICollection <string> addresses, Microsoft.Net.Http.Server.WebListener listener)
 {
     foreach (var value in addresses)
     {
         listener.UrlPrefixes.Add(UrlPrefix.Create(value));
     }
 }
Exemplo n.º 9
0
        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.");
        }
Exemplo n.º 10
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.");
 }
Exemplo n.º 11
0
    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);
    }
Exemplo n.º 12
0
        public void PrependLeadingSegmentsPreservesNatureOfIncomingPath()
        {
            var prefix = new UrlPrefix("foo");

            Assert.Equal(prefix.PrependLeadingSegments("~/bar"), ("~/foo/bar"));
            Assert.Equal(prefix.PrependLeadingSegments("/bar"), ("/foo/bar"));
            Assert.Equal(prefix.PrependLeadingSegments("bar"), ("foo/bar"));
        }
Exemplo n.º 13
0
        public void RemoveLeadingSegmentsMayContainSlash()
        {
            var prefix = new UrlPrefix("foo/quux");

            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/quux/bar"), ("~/bar"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/bar"), ("~/foo/bar"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/quux/bar"), ("~/quux/bar"));
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        public void RemoveLeadingSegmentsOnlyMatchesFullSegment()
        {
            var prefix = new UrlPrefix("foo");

            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/bar"), ("~/bar"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/fooo/bar"), ("~/fooo/bar"));
            Assert.Equal(prefix.RemoveLeadingSegments("~/fo/bar"), ("~/fo/bar"));
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        public void PrependLeadingSegmentsHandlesShortUrlConditionsAppropriately()
        {
            var prefix = new UrlPrefix("foo");

            Assert.Equal(prefix.PrependLeadingSegments("~/"), ("~/foo/"));
            Assert.Equal(prefix.PrependLeadingSegments("/"), ("/foo/"));
            Assert.Equal(prefix.PrependLeadingSegments("~"), ("~/foo/"));
            Assert.Equal(prefix.PrependLeadingSegments(""), ("foo/"));
        }
    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 WidgetsContainerPartHandler(
            IContentManager contentManager,
            IWidgetManager widgetManager,
            ILocalizationService localizationService,
            ShellSettings shellSettings,
            ITaxonomyService taxonomyService)
        {
            _contentManager      = contentManager;
            _widgetManager       = widgetManager;
            _localizationService = localizationService;
            _shellSettings       = shellSettings;
            _taxonomyService     = taxonomyService;
            if (!string.IsNullOrEmpty(_shellSettings.RequestUrlPrefix))
            {
                _urlPrefix = new UrlPrefix(_shellSettings.RequestUrlPrefix);
            }
            T = NullLocalizer.Instance;

            OnRemoved <WidgetsContainerPart>((context, part) => {
                DeleteWidgets(part);
            });
            OnUpdateEditorShape <WidgetsContainerPart>((context, part) => {
                var lPart = part.ContentItem.As <LocalizationPart>();
                if (lPart != null)
                {
                    var settings = part.Settings.GetModel <WidgetsContainerSettings>();
                    if (settings.TryToLocalizeItems)
                    {
                        var culture = lPart.Culture;
                        var widgets = _widgetManager.GetWidgets(part.ContentItem.Id, part.ContentItem.IsPublished())
                                      .Where(p => p.ContentItem.Has <LocalizationPart>() &&
                                             p.ContentItem.Get <LocalizationPart>().Culture == null);
                        foreach (var widget in widgets)
                        {
                            var ci = widget.ContentItem;
                            _localizationService.SetContentCulture(ci, culture.Culture);
                            // manage taxonomy field out of the normal flow:
                            // gets translations of selected terms in taxonomy fields before BuildEditor()
                            var translatedTaxo = TranslateTaxonomies(ci, culture, _localizationService);

                            // simulates a user that opens in edit model the widget and saves it
                            // to trigger all handlers and drivers
                            var shapeWidget = _contentManager.BuildEditor(ci);
                            var shapeUpdate = _contentManager.UpdateEditor(ci, new CustomUpdater(shapeWidget, culture.Culture, Logger));

                            // sets translated terms in taxonomy fields after UpdateEditor()
                            ApplyTranslatedTaxonomies(ci, translatedTaxo, _taxonomyService);

                            ci.VersionRecord.Published = false;
                            _contentManager.Publish(ci);
                        }
                    }
                }
            });
        }
Exemplo n.º 20
0
    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);
        }
Exemplo n.º 22
0
 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);
 }
Exemplo n.º 23
0
        public void RemoveLeadingSegmentsIgnoreLeadingAndTrailingCharactersOnInput()
        {
            var prefix = new UrlPrefix("foo");

            Assert.Equal(prefix.RemoveLeadingSegments("~/foo/bar"), ("~/bar"));
            var prefix2 = new UrlPrefix("~/foo");

            Assert.Equal(prefix2.RemoveLeadingSegments("~/foo/bar"), ("~/bar"));
            var prefix3 = new UrlPrefix("foo/");

            Assert.Equal(prefix3.RemoveLeadingSegments("~/foo/bar"), ("~/bar"));
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
    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;
            }
        }
    }
Exemplo n.º 26
0
        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);
        }
Exemplo n.º 27
0
        private static IPEndPoint CreateIPEndPoint(UrlPrefix urlPrefix)
        {
            IPAddress ip;

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

            return(new IPEndPoint(ip, urlPrefix.PortValue));
        }
Exemplo n.º 28
0
    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);
    }
Exemplo n.º 29
0
        public bool TryAdd(object instanceOrReplica, out PathString urlPrefix)
        {
            if (instanceOrReplica == null)
            {
                throw new ArgumentNullException(nameof(instanceOrReplica));
            }

            if (!(instanceOrReplica is IStatelessServiceInstance) && !(instanceOrReplica is IStatefulServiceReplica))
            {
                throw new ArgumentException(null, nameof(instanceOrReplica));
            }

            urlPrefix = UrlPrefix.NewUrlPrefix();

            return(ImmutableInterlocked.TryAdd(ref _entries, urlPrefix, instanceOrReplica));
        }
Exemplo n.º 30
0
        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);
        }