From dfebc0b5af7ea9828c4434c95de5fd70570fefad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 17:40:39 -0500 Subject: strictly enforce urlbase --- src/slskd/Program.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index afdf4ab3..5ce6bfd4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -602,6 +602,10 @@ namespace slskd var urlBase = OptionsAtStartup.Web.UrlBase; urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; + // 404 if a custom urlBase is set, but the request doesn't include it + app.EnforceUrlBase(urlBase); + + // use urlBase. this effectively just removes urlBase from the path app.UsePathBase(urlBase); Log.Information("Using base url {UrlBase}", urlBase); -- cgit v1.2.3 From cd2a45dcc097d1a5a3ec299a644a630acd63158d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 22:46:39 -0500 Subject: stub file rewriting --- src/slskd/Program.cs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5ce6bfd4..7510f59a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -633,6 +633,8 @@ namespace slskd } else { + RewriteStaticContentUrls(contentPath, urlBase); + fileServerOptions = new FileServerOptions { FileProvider = new PhysicalFileProvider(contentPath), @@ -831,6 +833,54 @@ namespace slskd } } + private static void RewriteStaticContentUrls(string contentPath, string urlBase) + { + if (string.IsNullOrEmpty(urlBase) || urlBase == "/") + { + // nothing to rewrite + return; + } + + // Log.Warning("Rewriting URLs in static content to reflect custom base url {UrlBase}", urlBase); + // Log.Warning("This is a one-time operation"); + + // var rewrittenFiles = 0; + // var files = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories); + + // foreach (var file in files) + // { + // bool rewritten = false; + // var contents = System.IO.File.ReadAllText(file); + + // if (contents.Contains("../../static") || contents.Contains("./static")) + // { + // contents = contents.Replace("../../static", $"{urlBase}/static"); + // contents = contents.Replace("./static", $"{urlBase}/static"); + // System.IO.File.WriteAllText(file, contents); + // Log.Warning("Rewrote paths in {File}", Path.GetFileName(file)); + // rewritten = true; + // } + + // if (contents.Contains("window.urlBase=\"/\"")) + // { + // contents = contents.Replace("window.urlBase=\"/\"", $"window.urlBase=\"{urlBase}\""); + // System.IO.File.WriteAllText(file, contents); + // Log.Warning("Rewrote urlBase in {File}", Path.GetFileName(file)); + // rewritten = true; + // } + + // if (rewritten) + // { + // rewrittenFiles++; + // } + // } + + // if (rewrittenFiles == 0) + // { + // Log.Warning("No files were rewritten."); + // } + } + private static void GenerateX509Certificate(string password, string filename) { Log.Information("Generating X509 certificate..."); -- cgit v1.2.3 From 3799b674f80e8af85fab1270db3c91495f7e5b3f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 May 2022 21:09:23 -0500 Subject: refactor pipeline --- src/slskd/Program.cs | 155 +++++++++++++++++++++++++-------------------------- 1 file changed, 77 insertions(+), 78 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 7510f59a..fa6b8c35 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -602,50 +602,46 @@ namespace slskd var urlBase = OptionsAtStartup.Web.UrlBase; urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; - // 404 if a custom urlBase is set, but the request doesn't include it + // 404 if a custom urlBase is set, but the request doesn't include it. + // this is necessary to make sure the development-time and run-time behavior + // are consistent. app.EnforceUrlBase(urlBase); - // use urlBase. this effectively just removes urlBase from the path + // use urlBase. this effectively just removes urlBase from the path, which is + // why the enforcement behavior exists above (the actually requested path becomes ambiguous) app.UsePathBase(urlBase); Log.Information("Using base url {UrlBase}", urlBase); // remove any errant double forward slashes which may have been introduced by manipulating the path base - app.Use(async (context, next) => - { - var path = context.Request.Path.ToString(); + //app.Use(async (context, next) => + //{ + // var path = context.Request.Path.ToString(); - if (path.StartsWith("//")) - { - context.Request.Path = new string(path.Skip(1).ToArray()); - } + // if (path.StartsWith("//")) + // { + // Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!! fixing path"); + // context.Request.Path = new string(path.Skip(1).ToArray()); + // } - await next(); - }); + // await next(); + //}); // serve static content from the configured path FileServerOptions fileServerOptions = default; - var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - if (!System.IO.Directory.Exists(contentPath)) - { - Log.Warning($"Static content disabled; cannot find content path '{contentPath}'"); - } - else + InjectUrlBaseIntoIndex(contentPath, urlBase); + + fileServerOptions = new FileServerOptions { - RewriteStaticContentUrls(contentPath, urlBase); + FileProvider = new PhysicalFileProvider(contentPath), + RequestPath = string.Empty, + EnableDirectoryBrowsing = false, + EnableDefaultFiles = true, + }; - fileServerOptions = new FileServerOptions - { - FileProvider = new PhysicalFileProvider(contentPath), - RequestPath = string.Empty, - EnableDirectoryBrowsing = false, - EnableDefaultFiles = true, - }; - - app.UseFileServer(fileServerOptions); - Log.Information("Serving static content from {ContentPath}", contentPath); - } + app.UseFileServer(fileServerOptions); + Log.Information("Serving static content from {ContentPath}", contentPath); if (OptionsAtStartup.Feature.Prometheus) { @@ -677,6 +673,18 @@ namespace slskd } }); + // if this is an /api route and no API controller was matched, give up and return a 404. + app.Use(async (context, next) => + { + if (context.Request.Path.StartsWithSegments("/api")) + { + context.Response.StatusCode = 404; + return; + } + + await next(); + }); + if (OptionsAtStartup.Feature.Swagger) { app.UseSwagger(); @@ -686,25 +694,48 @@ namespace slskd Log.Information("Publishing Swagger documentation to /swagger"); } - // if we made it this far and the route still wasn't matched, return the index unless it's an api route. this is - // required so that SPA routing (React Router, etc) can work properly + // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. + // optimistically search the dictionary of static files to see if we have a file that matches, and serve it if so. app.Use(async (context, next) => { - // exclude API routes which are not matched or return a 404 - if (!context.Request.Path.StartsWithSegments("/api")) + var path = context.Request.Path.ToString(); + + // if there is no extension, the caller is looking for a directory (an index file) + // modify the request to get the canonical default index + if (Path.GetExtension(path) == string.Empty) { context.Request.Path = "/"; } + else + { + // the caller is looking for a specific file; try and find it among the known files in the content directory + var knownFiles = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories) + .Select(file => file.Replace(contentPath, string.Empty).TrimStart('/', '\\').Replace('\\', '/')) + .ToHashSet(); + + var pathParts = path.Split('/'); + + for (int i = 1; i <= pathParts.Length; i++) + { + path = string.Join('/', pathParts.Skip(i)); + + if (knownFiles.Contains(path, StringComparer.InvariantCultureIgnoreCase)) + { + // the request is for a static file we have, but the route contains extra segments + // correct the route and continue to the next middleware, which should serve the file from + // disk. + context.Request.Path = '/' + path; + break; + } + } + } await next(); }); - // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be - // returned. otherwise it will throw a final 404 back to the client. - if (System.IO.Directory.Exists(contentPath)) - { - app.UseFileServer(fileServerOptions); - } + // the request path may have been rewritten above, in which case we're likely to have better luck finding + // a match with the file server middleware. let it try, and if it fails let it return a 404. + app.UseFileServer(fileServerOptions); return app; } @@ -833,7 +864,7 @@ namespace slskd } } - private static void RewriteStaticContentUrls(string contentPath, string urlBase) + private static void InjectUrlBaseIntoIndex(string contentPath, string urlBase) { if (string.IsNullOrEmpty(urlBase) || urlBase == "/") { @@ -841,44 +872,12 @@ namespace slskd return; } - // Log.Warning("Rewriting URLs in static content to reflect custom base url {UrlBase}", urlBase); - // Log.Warning("This is a one-time operation"); - - // var rewrittenFiles = 0; - // var files = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories); - - // foreach (var file in files) - // { - // bool rewritten = false; - // var contents = System.IO.File.ReadAllText(file); - - // if (contents.Contains("../../static") || contents.Contains("./static")) - // { - // contents = contents.Replace("../../static", $"{urlBase}/static"); - // contents = contents.Replace("./static", $"{urlBase}/static"); - // System.IO.File.WriteAllText(file, contents); - // Log.Warning("Rewrote paths in {File}", Path.GetFileName(file)); - // rewritten = true; - // } - - // if (contents.Contains("window.urlBase=\"/\"")) - // { - // contents = contents.Replace("window.urlBase=\"/\"", $"window.urlBase=\"{urlBase}\""); - // System.IO.File.WriteAllText(file, contents); - // Log.Warning("Rewrote urlBase in {File}", Path.GetFileName(file)); - // rewritten = true; - // } - - // if (rewritten) - // { - // rewrittenFiles++; - // } - // } - - // if (rewrittenFiles == 0) - // { - // Log.Warning("No files were rewritten."); - // } + var files = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories); + + foreach (var file in files) + { + Console.WriteLine(file); + } } private static void GenerateX509Certificate(string password, string filename) -- cgit v1.2.3 From a47bc0d0872b4ef69defce264a4f2e03ed55bf0f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 May 2022 23:51:37 -0500 Subject: patch index file on start --- src/slskd/Program.cs | 98 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 27 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index fa6b8c35..efcf8698 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -28,6 +28,7 @@ namespace slskd using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json.Serialization; + using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -36,6 +37,7 @@ namespace slskd using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; @@ -178,6 +180,7 @@ namespace slskd private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); + private static MemoryCache Cache { get; } = new MemoryCache(new MemoryCacheOptions()); [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -612,25 +615,18 @@ namespace slskd app.UsePathBase(urlBase); Log.Information("Using base url {UrlBase}", urlBase); - // remove any errant double forward slashes which may have been introduced by manipulating the path base - //app.Use(async (context, next) => - //{ - // var path = context.Request.Path.ToString(); - - // if (path.StartsWith("//")) - // { - // Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!! fixing path"); - // context.Request.Path = new string(path.Skip(1).ToArray()); - // } - - // await next(); - //}); - // serve static content from the configured path FileServerOptions fileServerOptions = default; var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - InjectUrlBaseIntoIndex(contentPath, urlBase); + if (TryPatchIndexWithUrlBase(contentPath, urlBase, out var index)) + { + Log.Information("Patched static index file {Index} with base url {UrlBase}", index, urlBase); + } + else + { + Log.Warning("Failed to patch static content with custom base url {UrlBase}; the UI may not work properly."); + } fileServerOptions = new FileServerOptions { @@ -708,10 +704,16 @@ namespace slskd } else { - // the caller is looking for a specific file; try and find it among the known files in the content directory - var knownFiles = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories) - .Select(file => file.Replace(contentPath, string.Empty).TrimStart('/', '\\').Replace('\\', '/')) - .ToHashSet(); + HashSet staticFiles; + + if (!Cache.TryGetValue(CacheKey.StaticFiles, out staticFiles)) + { + staticFiles = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories) + .Select(file => file.Replace(contentPath, string.Empty).TrimStart('/', '\\').Replace('\\', '/')) + .ToHashSet(); + + Cache.Set(CacheKey.StaticFiles, staticFiles); + } var pathParts = path.Split('/'); @@ -719,7 +721,7 @@ namespace slskd { path = string.Join('/', pathParts.Skip(i)); - if (knownFiles.Contains(path, StringComparer.InvariantCultureIgnoreCase)) + if (staticFiles.Contains(path, StringComparer.InvariantCultureIgnoreCase)) { // the request is for a static file we have, but the route contains extra segments // correct the route and continue to the next middleware, which should serve the file from @@ -864,20 +866,62 @@ namespace slskd } } - private static void InjectUrlBaseIntoIndex(string contentPath, string urlBase) + private static bool TryPatchIndexWithUrlBase(string contentPath, string urlBase, out string index) { - if (string.IsNullOrEmpty(urlBase) || urlBase == "/") + index = null; + + bool exists(string file) => System.IO.File.Exists(Path.Combine(contentPath, file)); + + if (exists("index.html")) { - // nothing to rewrite - return; + index = "index.html"; + } + else if (exists("index.htm")) + { + index = "index.htm"; + } + else if (exists("Default.htm")) + { + index = "Default.htm"; + } + else + { + Log.Warning("Failed to locate an index file in content path {ContentPath}; expected one of: {Defaults}", contentPath, "index.html, index.htm, Default.htm"); + return false; } - var files = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories); + var indexFQN = Path.Combine(contentPath, index); + var pattern = ""; + + if (!Regex.IsMatch(contents, pattern, RegexOptions.Multiline)) + { + Log.Debug("Index does not contain a urlBase script tag; appending {Patch} to the end of the file", patch); + contents += patch; + } + else + { + var code = $"window.urlBase=\"{urlBase}\""; + Log.Debug("Index contains a urlBase script tag; replacing tag contents with {Patch}", patch); + contents = Regex.Replace(contents, pattern, patch); + } + + System.IO.File.WriteAllText(indexFQN, contents); } + catch (Exception ex) + { + Log.Warning("Failed to patch index file {File}: {Message}", index, ex.Message); + return false; + } + + return true; } private static void GenerateX509Certificate(string password, string filename) -- cgit v1.2.3 From 09b307f9bea08d543e9a2146a07d0b36d09b2e47 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 20:18:03 -0500 Subject: use injection middleware --- src/slskd/Program.cs | 69 ++-------------------------------------------------- 1 file changed, 2 insertions(+), 67 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index efcf8698..0103688b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -612,22 +612,15 @@ namespace slskd // use urlBase. this effectively just removes urlBase from the path, which is // why the enforcement behavior exists above (the actually requested path becomes ambiguous) + // inject urlBase into any html files we serve app.UsePathBase(urlBase); + app.UseHTMLInjection($""); Log.Information("Using base url {UrlBase}", urlBase); // serve static content from the configured path FileServerOptions fileServerOptions = default; var contentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - if (TryPatchIndexWithUrlBase(contentPath, urlBase, out var index)) - { - Log.Information("Patched static index file {Index} with base url {UrlBase}", index, urlBase); - } - else - { - Log.Warning("Failed to patch static content with custom base url {UrlBase}; the UI may not work properly."); - } - fileServerOptions = new FileServerOptions { FileProvider = new PhysicalFileProvider(contentPath), @@ -866,64 +859,6 @@ namespace slskd } } - private static bool TryPatchIndexWithUrlBase(string contentPath, string urlBase, out string index) - { - index = null; - - bool exists(string file) => System.IO.File.Exists(Path.Combine(contentPath, file)); - - if (exists("index.html")) - { - index = "index.html"; - } - else if (exists("index.htm")) - { - index = "index.htm"; - } - else if (exists("Default.htm")) - { - index = "Default.htm"; - } - else - { - Log.Warning("Failed to locate an index file in content path {ContentPath}; expected one of: {Defaults}", contentPath, "index.html, index.htm, Default.htm"); - return false; - } - - var indexFQN = Path.Combine(contentPath, index); - var pattern = ""; - - if (!Regex.IsMatch(contents, pattern, RegexOptions.Multiline)) - { - Log.Debug("Index does not contain a urlBase script tag; appending {Patch} to the end of the file", patch); - contents += patch; - } - else - { - var code = $"window.urlBase=\"{urlBase}\""; - Log.Debug("Index contains a urlBase script tag; replacing tag contents with {Patch}", patch); - contents = Regex.Replace(contents, pattern, patch); - } - - System.IO.File.WriteAllText(indexFQN, contents); - } - catch (Exception ex) - { - Log.Warning("Failed to patch index file {File}: {Message}", index, ex.Message); - return false; - } - - return true; - } - private static void GenerateX509Certificate(string password, string filename) { Log.Information("Generating X509 certificate..."); -- cgit v1.2.3 From 399ca91729cdcd564eb367449c64c05c54258b52 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 May 2022 09:13:03 -0500 Subject: add middleware to rewrite HTML --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 2 +- .../Common/Middleware/HTMLRewriteMiddleware.cs | 124 +++++++++++++++++++++ src/slskd/Program.cs | 30 +---- 3 files changed, 126 insertions(+), 30 deletions(-) create mode 100644 src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index 41ceef51..217b2bce 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -42,7 +42,7 @@ namespace slskd } /// - /// Injects the specified HTML into html files. + /// Injects content into html files. /// public class HTMLInjectionMiddleware { diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs new file mode 100644 index 00000000..a15ba1e0 --- /dev/null +++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs @@ -0,0 +1,124 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.IO; + using System.Linq; + using System.Text.RegularExpressions; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + /// + /// Adds the . + /// + public static class HTMLRewriteMiddlewareExtensions + { + /// + /// Replaces the specified with the specified . + /// + /// + /// + /// + /// + public static IApplicationBuilder UseHTMLRewrite(this IApplicationBuilder builder, string pattern, string replacement) + { + return builder.UseMiddleware(pattern, replacement); + } + } + + /// + /// Replaces parts of HTML files. + /// + public class HTMLRewriteMiddleware + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// + public HTMLRewriteMiddleware(RequestDelegate next, string pattern, string replacement) + { + Next = next; + Pattern = pattern; + Replacement = replacement; + } + + private string Pattern { get; } + private string Replacement { get; } + private RequestDelegate Next { get; } + + /// + /// Executes this middleware, returning the contents of the requested HTML file with the specified replacesments made. + /// + /// + /// + public async Task InvokeAsync(HttpContext context) + { + context.Request.Headers.TryGetValue("accept", out var accept); + var requestedTypes = accept.ToString().Split(','); + + var rewriteableType = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + var isApiRoute = context.Request.Path.ToString().StartsWith("/api"); + var isGET = context.Request.Method == "GET"; + + var isRewriteableType = requestedTypes + .Intersect(rewriteableType, StringComparer.InvariantCultureIgnoreCase) + .Any(); + + if (!isApiRoute && isGET && isRewriteableType) + { + var originalStream = context.Response.Body; + + // swap the response body out with a memory stream so we can manipulate it later + // the downstream middleware will write the response to it + var stream = new MemoryStream(); + context.Response.Body = stream; + + await Next.Invoke(context); + + if (context.Response.StatusCode == 200) + { + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the appended HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + context.Response.Clear(); + + await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + } + + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + + // swap the original stream back in + context.Response.Body = originalStream; + } + else + { + await Next.Invoke(context); + } + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0103688b..5a0749a1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -614,6 +614,7 @@ namespace slskd // why the enforcement behavior exists above (the actually requested path becomes ambiguous) // inject urlBase into any html files we serve app.UsePathBase(urlBase); + app.UseHTMLRewrite("((\\.)?\\/static)", $"{urlBase}/static"); app.UseHTMLInjection($""); Log.Information("Using base url {UrlBase}", urlBase); @@ -695,35 +696,6 @@ namespace slskd { context.Request.Path = "/"; } - else - { - HashSet staticFiles; - - if (!Cache.TryGetValue(CacheKey.StaticFiles, out staticFiles)) - { - staticFiles = System.IO.Directory.GetFiles(contentPath, "*", SearchOption.AllDirectories) - .Select(file => file.Replace(contentPath, string.Empty).TrimStart('/', '\\').Replace('\\', '/')) - .ToHashSet(); - - Cache.Set(CacheKey.StaticFiles, staticFiles); - } - - var pathParts = path.Split('/'); - - for (int i = 1; i <= pathParts.Length; i++) - { - path = string.Join('/', pathParts.Skip(i)); - - if (staticFiles.Contains(path, StringComparer.InvariantCultureIgnoreCase)) - { - // the request is for a static file we have, but the route contains extra segments - // correct the route and continue to the next middleware, which should serve the file from - // disk. - context.Request.Path = '/' + path; - break; - } - } - } await next(); }); -- cgit v1.2.3 From 183bca6fbb0dffddc8f7417b1b9290f63876096d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 6 May 2022 21:34:51 -0500 Subject: remove memorycache --- src/slskd/Common/CacheKey.cs | 24 ------------------------ src/slskd/Program.cs | 3 --- 2 files changed, 27 deletions(-) delete mode 100644 src/slskd/Common/CacheKey.cs (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Common/CacheKey.cs b/src/slskd/Common/CacheKey.cs deleted file mode 100644 index 039d144d..00000000 --- a/src/slskd/Common/CacheKey.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - public static class CacheKey - { - public static readonly string StaticFiles = "StaticFiles"; - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5a0749a1..12777a77 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -28,7 +28,6 @@ namespace slskd using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json.Serialization; - using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; @@ -37,7 +36,6 @@ namespace slskd using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; @@ -180,7 +178,6 @@ namespace slskd private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); - private static MemoryCache Cache { get; } = new MemoryCache(new MemoryCacheOptions()); [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } -- cgit v1.2.3 From 022905ad5d076bbf2969328a6cb5c2daee182763 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 May 2022 13:53:15 -0500 Subject: docs --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 12777a77..91ce72f7 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -609,7 +609,8 @@ namespace slskd // use urlBase. this effectively just removes urlBase from the path, which is // why the enforcement behavior exists above (the actually requested path becomes ambiguous) - // inject urlBase into any html files we serve + // inject urlBase into any html files we serve, and rewrite links to ./static or /static to + // prepend the url base. app.UsePathBase(urlBase); app.UseHTMLRewrite("((\\.)?\\/static)", $"{urlBase}/static"); app.UseHTMLInjection($""); -- cgit v1.2.3 From 2391114fbcadba7378451c8a066fb466269fdb13 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 May 2022 13:55:22 -0500 Subject: docs --- src/slskd/Program.cs | 14 +++++--------- src/web/package.json | 2 +- src/web/public/index.html | 2 +- 3 files changed, 7 insertions(+), 11 deletions(-) (limited to 'src/slskd/Program.cs') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 91ce72f7..ecf028b4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -612,7 +612,7 @@ namespace slskd // inject urlBase into any html files we serve, and rewrite links to ./static or /static to // prepend the url base. app.UsePathBase(urlBase); - app.UseHTMLRewrite("((\\.)?\\/static)", $"{urlBase}/static"); + app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static"); app.UseHTMLInjection($""); Log.Information("Using base url {UrlBase}", urlBase); @@ -683,14 +683,11 @@ namespace slskd } // if we made it this far, the caller is either looking for a route that was synthesized with a SPA router, or is genuinely confused. - // optimistically search the dictionary of static files to see if we have a file that matches, and serve it if so. + // if the request is for a directory, modify the request to redirect it to the index, otherwise leave it alone and let it 404 in the next + // middleware app.Use(async (context, next) => { - var path = context.Request.Path.ToString(); - - // if there is no extension, the caller is looking for a directory (an index file) - // modify the request to get the canonical default index - if (Path.GetExtension(path) == string.Empty) + if (Path.GetExtension(context.Request.Path.ToString()) == string.Empty) { context.Request.Path = "/"; } @@ -698,8 +695,7 @@ namespace slskd await next(); }); - // the request path may have been rewritten above, in which case we're likely to have better luck finding - // a match with the file server middleware. let it try, and if it fails let it return a 404. + // either serve the index, or 404 app.UseFileServer(fileServerOptions); return app; diff --git a/src/web/package.json b/src/web/package.json index 62b72a55..a8810d47 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -52,4 +52,4 @@ "not op_mini all" ] } -} \ No newline at end of file +} diff --git a/src/web/public/index.html b/src/web/public/index.html index 5b30bc65..e452c8c8 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -9,4 +9,4 @@
- \ No newline at end of file + -- cgit v1.2.3