From fb8335be787c73b98f1bc77912515fa6cee6864e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Apr 2022 22:05:56 -0500 Subject: bump Soulseek.NET to 4.5.2 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index b4d28967..e0e83f41 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -69,7 +69,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 4204093f0610e1cfd645e74d335d6308cae0a64a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 13:09:43 -0500 Subject: add an option to disable HTTPS --- config/slskd.example.yml | 1 + src/slskd/Options.cs | 8 ++++++++ src/slskd/Program.cs | 33 ++++++++++++++++++--------------- 3 files changed, 27 insertions(+), 15 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index e0704fdd..fbf0371e 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -50,6 +50,7 @@ # web: # port: 5000 # https: +# disabled: false # port: 5001 # force: false # certificate: diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 507006a4..1003da1e 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1056,6 +1056,14 @@ namespace slskd /// public class HttpsOptions { + /// + /// Gets a value indicating whether HTTPS should be disabled. + /// + [Argument(default, "no-https")] + [EnvironmentVariable("NO_HTTPS")] + [Description("disable HTTPS")] + public bool Disabled { get; init; } = false; + /// /// Gets the HTTPS listen port. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 289e898c..bd92d36f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -369,7 +369,7 @@ namespace slskd } var webHost = WebHost.CreateDefaultBuilder(args) - .SuppressStatusMessages(true) + .UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True") .ConfigureAppConfiguration((hostingContext, builder) => { builder.Sources.Clear(); @@ -382,22 +382,25 @@ namespace slskd logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => + if (!OptionsAtStartup.Web.Https.Disabled) { - var cert = OptionsAtStartup.Web.Https.Certificate; - - if (!string.IsNullOrEmpty(cert.Pfx)) - { - logger.Information($"Using certificate from {cert.Pfx}"); - listenOptions.UseHttps(cert.Pfx, cert.Password); - } - else + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); + options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => { - logger.Information($"Using randomly generated self-signed certificate"); - listenOptions.UseHttps(X509.Generate(subject: AppName)); - } - }); + var cert = OptionsAtStartup.Web.Https.Certificate; + + if (!string.IsNullOrEmpty(cert.Pfx)) + { + logger.Information($"Using certificate from {cert.Pfx}"); + listenOptions.UseHttps(cert.Pfx, cert.Password); + } + else + { + logger.Information($"Using randomly generated self-signed certificate"); + listenOptions.UseHttps(X509.Generate(subject: AppName)); + } + }); + } }) .UseStartup() .Build(); -- cgit v1.2.3 From c2c3feb7ba8c7dca9d154db71c1fab89cef1552a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 13:09:59 -0500 Subject: whoops --- src/slskd/Program.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bd92d36f..ce1a3b92 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -369,7 +369,6 @@ namespace slskd } var webHost = WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True") .ConfigureAppConfiguration((hostingContext, builder) => { builder.Sources.Clear(); -- cgit v1.2.3 From 92c7d62908eb429f1b4e99d001b1ec9117c5ae22 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 13:17:22 -0500 Subject: whoops again --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ce1a3b92..a5c35dca 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -369,6 +369,7 @@ namespace slskd } var webHost = WebHost.CreateDefaultBuilder(args) + .SuppressStatusMessages(true) .ConfigureAppConfiguration((hostingContext, builder) => { builder.Sources.Clear(); -- cgit v1.2.3 From 1685db1508f13007c675df0fc717cdcafb44ce33 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 13:24:40 -0500 Subject: docs --- docs/config.md | 1 + slskd.sln | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/docs/config.md b/docs/config.md index e80de398..605b159b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -496,6 +496,7 @@ The application can produce a self-signed `.pfx` file and random password using | `-f\|--force-https` | `HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | | `--https-cert-pfx` | `HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | | `--https-cert-password` | `HTTPS_CERT_PASSWORD` | The password for the X509 certificate | +| `--no-https` | `NO_HTTPS` | Determines whether HTTPS is to be disabled | #### **YAML** ```yaml diff --git a/slskd.sln b/slskd.sln index 20b351d6..3633c010 100644 --- a/slskd.sln +++ b/slskd.sln @@ -42,6 +42,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "config", "config", "{98F684 config\slskd.example.yml = config\slskd.example.yml EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{53D80066-A655-42EC-9C8D-2591C3E4B034}" + ProjectSection(SolutionItems) = preProject + docs\config.md = docs\config.md + docs\docker.md = docs\docker.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU -- cgit v1.2.3 From 612a1574b040f5c2fc577ffbe4e37f11bedbe4b4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 13:25:49 -0500 Subject: changing HTTPS flag requires restart --- src/slskd/Options.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 1003da1e..00ae670e 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1062,6 +1062,7 @@ namespace slskd [Argument(default, "no-https")] [EnvironmentVariable("NO_HTTPS")] [Description("disable HTTPS")] + [RequiresRestart] public bool Disabled { get; init; } = false; /// -- cgit v1.2.3 From 03980512cbb91f150b52ae249626633c5b1be5cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 17:27:17 -0500 Subject: add ConsoleWriteLineLogger --- src/slskd/Common/Logging/ConsoleWriteLineLogger.cs | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/slskd/Common/Logging/ConsoleWriteLineLogger.cs diff --git a/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs new file mode 100644 index 00000000..4e829df6 --- /dev/null +++ b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs @@ -0,0 +1,34 @@ +// +// 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 Serilog.Events; + + /// + /// Logs messages to stdout via . + /// + public class ConsoleWriteLineLogger : Serilog.ILogger + { + /// + public void Write(LogEvent logEvent) + { + Console.WriteLine(logEvent.RenderMessage()); + } + } +} -- cgit v1.2.3 From 9bc54bc17c4bbb6146c416b84748492efde40754 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 17:27:33 -0500 Subject: refactor Program to use .NET 6 conventions --- src/slskd/Program.cs | 583 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 474 insertions(+), 109 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index a5c35dca..1e51cc5b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -26,19 +26,42 @@ namespace slskd using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; - using Microsoft.AspNetCore; + using System.Text; + using System.Text.Json.Serialization; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication.JwtBearer; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc.ApiExplorer; + using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; + using Microsoft.IdentityModel.Tokens; + using Microsoft.OpenApi.Models; + using Prometheus; using Prometheus.DotNetRuntime; + using Prometheus.SystemMetrics; using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; + using slskd.Authentication; using slskd.Configuration; + using slskd.Core.API; using slskd.Cryptography; + using slskd.Integrations.FTP; + using slskd.Integrations.Pushbullet; + using slskd.Messaging; + using slskd.Search; + using slskd.Search.API; + using slskd.Shares; + using slskd.Transfers; + using slskd.Users; using slskd.Validation; + using Soulseek; using Utility.CommandLine; using Utility.EnvironmentVariables; using IOFile = System.IO.File; @@ -154,6 +177,7 @@ namespace slskd private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); + private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -181,9 +205,10 @@ namespace slskd EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix); Arguments.Populate(clearExistingValues: false); + // if a user has used one of the arguments above, perform the requested task, then quit if (ShowVersion) { - Console.WriteLine(FullVersion); + Log.Information(FullVersion); return; } @@ -225,9 +250,8 @@ namespace slskd // if not, set it to the default. ConfigurationFile ??= DefaultConfigurationFile; - // verify(create if needed) default application - // directories. if the downloads or complete directories are overridden in config, those will be - // validated after the config is loaded. + // verify(create if needed) default application directories. if the downloads or complete + // directories are overridden in config, those will be validated after the config is loaded. try { VerifyDirectory(AppDirectory, createIfMissing: true, verifyWriteable: true); @@ -237,7 +261,7 @@ namespace slskd } catch (Exception ex) { - Console.WriteLine($"Filesystem exception: {ex.Message}"); + Log.Information($"Filesystem exception: {ex.Message}"); return; } @@ -253,114 +277,58 @@ namespace slskd if (OptionsAtStartup.Debug) { - Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}"); + Log.Information($"Configuration:\n{Configuration.GetDebugView()}"); } if (!OptionsAtStartup.TryValidate(out var result)) { - Console.WriteLine(result.GetResultView()); + Log.Information(result.GetResultView()); return; } } catch (Exception ex) { - Console.WriteLine($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); + Log.Information($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); return; } - Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) - .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) - .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) - .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) - .Enrich.WithProperty("InvocationId", InvocationId) - .Enrich.WithProperty("ProcessId", ProcessId) - .Enrich.FromLogContext() - .WriteTo.Console( - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => - config.File( - Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", - rollingInterval: RollingInterval.Day)) - .WriteTo.Conditional( - e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) - .WriteTo.Sink(new DelegatingSink(logEvent => - { - try - { - var record = new LogRecord() - { - Timestamp = logEvent.Timestamp.LocalDateTime, - Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), - SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, - Level = logEvent.Level.ToString(), - Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'), - }; - - LogBuffer.Enqueue(record); - LogEmitted?.Invoke(null, record); - } - catch (Exception ex) - { - Console.WriteLine($"Misconfigured delegating logger: {ex.Message}"); - } - })) - .CreateLogger(); - - var logger = Log.ForContext(typeof(Program)); + ConfigureGlobalLogger(); + Log = Serilog.Log.ForContext(typeof(Program)); if (!OptionsAtStartup.NoLogo) { PrintLogo(FullVersion); } - logger.Information("Version: {Version}", FullVersion); + Log.Information("Version: {Version}", FullVersion); if (IsDevelopment) { - logger.Warning("This is a Development build; YMMV"); + Log.Warning("This is a Development build; YMMV"); } if (IsCanary) { - logger.Warning("This is a canary build"); - logger.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN"); - logger.Warning($"Please report any issues here: {IssuesUrl}"); + Log.Warning("This is a canary build"); + Log.Warning("Canary builds are considered UNSTABLE and may be completely BROKEN"); + Log.Warning($"Please report any issues here: {IssuesUrl}"); } - logger.Information("Invocation ID: {InvocationId}", InvocationId); - logger.Information("Process ID: {ProcessId}", ProcessId); - logger.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); + Log.Information("Invocation ID: {InvocationId}", InvocationId); + Log.Information("Process ID: {ProcessId}", ProcessId); + Log.Information("Instance Name: {InstanceName}", OptionsAtStartup.InstanceName); - logger.Information("Using application directory {AppDirectory}", AppDirectory); - logger.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); + Log.Information("Using application directory {AppDirectory}", AppDirectory); + Log.Information("Using configuration file {ConfigurationFile}", ConfigurationFile); - // for convenience, try to copy the example configuration file to the application directory if no configuration - // file exists. if any part fails, just move on silently. - if (!IOFile.Exists(ConfigurationFile)) - { - try - { - logger.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", ConfigurationFile); - var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); - var destination = ConfigurationFile; - IOFile.Copy(source, destination); - } - catch (Exception ex) - { - logger.Error("Failed to create configuration file {ConfigurationFile}: {Message}", ConfigurationFile, ex.Message); - } - } + RecreateConfigurationFileIfMissing(ConfigurationFile); if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); + Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); } + // bootstrap the ASP.NET application try { if (OptionsAtStartup.Feature.Prometheus) @@ -368,59 +336,419 @@ namespace slskd using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } - var webHost = WebHost.CreateDefaultBuilder(args) - .SuppressStatusMessages(true) - .ConfigureAppConfiguration((hostingContext, builder) => - { - builder.Sources.Clear(); - builder.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); - }) - .UseSerilog() + var builder = WebApplication.CreateBuilder(args); + + builder.Configuration + .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); + + builder.Host + .UseSerilog(); + + builder.WebHost .UseUrls() .UseKestrel(options => { - logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); + Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); if (!OptionsAtStartup.Web.Https.Disabled) { - logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); + Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; if (!string.IsNullOrEmpty(cert.Pfx)) { - logger.Information($"Using certificate from {cert.Pfx}"); + Log.Information($"Using certificate from {cert.Pfx}"); listenOptions.UseHttps(cert.Pfx, cert.Password); } else { - logger.Information($"Using randomly generated self-signed certificate"); + Log.Information($"Using randomly generated self-signed certificate"); listenOptions.UseHttps(X509.Generate(subject: AppName)); } }); } - }) - .UseStartup() - .Build(); + }); + + var services = builder.Services; + + ConfigureAspDotNetServices(services); + ConfigureDependencyInjectionContainer(services); + + var app = builder.Build(); + + ConfigureAspDotNetPipeline(app); if (OptionsAtStartup.NoStart) { - logger.Information("Qutting because 'no-start' option is enabled"); + Log.Information("Qutting because 'no-start' option is enabled"); return; } - webHost.Run(); + app.Run(); } catch (Exception ex) { - logger.Fatal(ex, "Application terminated unexpectedly"); + Log.Fatal(ex, "Application terminated unexpectedly"); } finally { - Log.CloseAndFlush(); + Serilog.Log.CloseAndFlush(); + } + } + + private static void ConfigureDependencyInjectionContainer(IServiceCollection services) + { + // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but + // the values at startup are to be used (generally anything marked RequiresRestart). + services.AddSingleton(OptionsAtStartup); + + // add IOptionsMonitor and IOptionsSnapshot to DI. + // use when the current Options are to be used (generally anything not marked RequiresRestart) + // the monitor should be used for services with Singleton lifetime, snapshots for everything else + services.AddOptions() + .Bind(Configuration.GetSection(AppName), o => { o.BindNonPublicProperties = true; }) + .Validate(options => + { + if (!options.TryValidate(out var result)) + { + Log.Warning("Options (re)configuration rejected."); + Log.Warning(result.GetResultView()); + return false; + } + + return true; + }); + + // add IManagedState, IStateMutator, IStateMonitor, and IStateSnapshot state to DI. + // the mutator should be used any time application state needs to be mutated (as the name implies) + // as with options, the monitor should be used for services with Singleton lifetime, snapshots for everything else + // IManagedState should be used where state is being mutated and accessed in the same context + services.AddManagedState(); + + // add IHttpClientFactory + // use through 'using var http = HttpClientFactory.CreateClient()' wherever HTTP calls will be made + // this is important to prevent memory leaks + services.AddHttpClient(); + + // add a partially configured instance of SoulseekClient. the Application instance will + // complete configuration at startup. + services.AddSingleton(_ => + new SoulseekClient(options: new SoulseekClientOptions( + maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, + maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); + + // add the core application service to DI as well as a hosted service so that other services can + // access instance methods + services.AddSingleton(); + services.AddHostedService(p => p.GetRequiredService()); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); + + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + + // initialize DbContext instances to avoid race conditions when a db needs to be created from scratch. + // important: do this last + services.AddDbContextFactory(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", "search.db")}"); + }); + + services.InitializeDbContext(); + } + + private static void ConfigureAspDotNetServices(IServiceCollection services) + { + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder + .AllowAnyHeader() + .AllowAnyMethod() + .SetIsOriginAllowed((host) => true) + .AllowCredentials())); + + var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); + + services.AddSingleton(jwtSigningKey); + + if (!OptionsAtStartup.Web.Authentication.Disabled) + { + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ClockSkew = TimeSpan.FromMinutes(5), + RequireSignedTokens = true, + RequireExpirationTime = true, + ValidateLifetime = true, + ValidIssuer = AppName, + ValidateIssuer = true, + ValidateAudience = false, + IssuerSigningKey = jwtSigningKey, + ValidateIssuerSigningKey = true, + }; + + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + // assign the request token from the access_token query parameter + // but only if the destination is a SignalR hub + // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0 + if (context.HttpContext.Request.Path.StartsWithSegments("/hub")) + { + context.Token = context.Request.Query["access_token"]; + } + + return Task.CompletedTask; + }, + }; + }); + } + else + { + Log.Warning("Authentication of web requests is DISABLED"); + + services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) + .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => + { + options.Username = "Anonymous"; + options.Role = Role.Administrator; + }); + } + + services.AddRouting(options => options.LowercaseUrls = true); + services.AddControllers().AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new IPAddressConverter()); + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; + }); + + services.AddSignalR().AddJsonProtocol(options => + { + options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); + options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + }); + + services.AddHealthChecks(); + + services.AddApiVersioning(options => options.ReportApiVersions = true); + services.AddVersionedApiExplorer(options => + { + options.GroupNameFormat = "'v'VVV"; + options.SubstituteApiVersionInUrl = true; + }); + + if (OptionsAtStartup.Feature.Swagger) + { + services.AddSwaggerGen(options => + { + options.DescribeAllParametersInCamelCase(); + options.SwaggerDoc( + "v0", + new OpenApiInfo + { + Title = AppName, + Version = "v0", + }); + + if (System.IO.File.Exists(XmlDocumentationFile)) + { + options.IncludeXmlComments(XmlDocumentationFile); + } + else + { + Log.Warning($"Unable to find XML documentation in {XmlDocumentationFile}, Swagger will not include metadata"); + } + }); + } + + if (OptionsAtStartup.Feature.Prometheus) + { + services.AddSystemMetrics(); + } + } + + private static void ConfigureAspDotNetPipeline(WebApplication app) + { + app.UseExceptionHandler(a => a.Run(async context => + { + await context.Response.WriteAsJsonAsync(context.Features.Get().Error.Message); + })); + + app.UseCors("AllowAll"); + + if (OptionsAtStartup.Web.Https.Force) + { + app.UseHttpsRedirection(); + app.UseHsts(); + + Log.Information($"Forcing HTTP requests to HTTPS"); } + + // allow users to specify a custom path base, for use behind a reverse proxy + var urlBase = OptionsAtStartup.Web.UrlBase; + urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; + + 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("//")) + { + 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); + + if (!System.IO.Directory.Exists(contentPath)) + { + Log.Warning($"Static content disabled; cannot find content path '{contentPath}'"); + } + else + { + 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); + } + + if (OptionsAtStartup.Feature.Prometheus) + { + app.UseHttpMetrics(); + Log.Information("Publishing Prometheus metrics to /metrics"); + } + + if (OptionsAtStartup.Web.Logging) + { + app.UseSerilogRequestLogging(); + } + + app.UseAuthentication(); + + app.UseRouting(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => + { + endpoints.MapHub("/hub/application"); + endpoints.MapHub("/hub/logs"); + endpoints.MapHub("/hub/search"); + + endpoints.MapControllers(); + endpoints.MapHealthChecks("/health"); + + if (OptionsAtStartup.Feature.Prometheus) + { + endpoints.MapMetrics("/metrics"); + } + }); + + if (OptionsAtStartup.Feature.Swagger) + { + app.UseSwagger(); + app.UseSwaggerUI(options => app.Services.GetRequiredService().ApiVersionDescriptions.ToList() + .ForEach(description => options.SwaggerEndpoint($"{(urlBase == "/" ? string.Empty : urlBase)}/swagger/{description.GroupName}/swagger.json", description.GroupName))); + + 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 + app.Use(async (context, next) => + { + // exclude API routes which are not matched or return a 404 + if (!context.Request.Path.StartsWithSegments("/api")) + { + context.Request.Path = "/"; + } + + 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); + } + } + + private static void ConfigureGlobalLogger() + { + Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) + .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) + .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) + .Enrich.WithProperty("InvocationId", InvocationId) + .Enrich.WithProperty("ProcessId", ProcessId) + .Enrich.FromLogContext() + .WriteTo.Console( + outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(config => + config.File( + Path.Combine(AppDirectory, "logs", $"{AppName}-.log"), + outputTemplate: (OptionsAtStartup.Debug ? "[{SubContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + rollingInterval: RollingInterval.Day)) + .WriteTo.Conditional( + e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), + config => config.GrafanaLoki( + OptionsAtStartup.Logger.Loki ?? string.Empty, + outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + .WriteTo.Sink(new DelegatingSink(logEvent => + { + try + { + var record = new LogRecord() + { + Timestamp = logEvent.Timestamp.LocalDateTime, + Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), + SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, + Level = logEvent.Level.ToString(), + Message = logEvent.RenderMessage().TrimStart('"').TrimEnd('"'), + }; + + LogBuffer.Enqueue(record); + LogEmitted?.Invoke(null, record); + } + catch (Exception ex) + { + Log.Information($"Misconfigured delegating logger: {ex.Message}"); + } + })) + .CreateLogger(); } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile) @@ -457,16 +785,53 @@ namespace slskd commandLine: Environment.CommandLine); } + private static void InitializeDbContext(this IServiceCollection services) + where TContext : DbContext + { + Log.Debug($"Initializing database context {typeof(TContext).Name}"); + + try + { + using var ctx = services + .BuildServiceProvider() + .GetRequiredService>() + .CreateDbContext(); + } + catch (Exception ex) + { + Log.Error(ex, $"Failed to initialize database context {typeof(TContext).Name}: ${ex.Message}"); + throw; + } + } + + private static void RecreateConfigurationFileIfMissing(string configurationFile) + { + if (!IOFile.Exists(configurationFile)) + { + try + { + Log.Warning("Configuration file {ConfigurationFile} does not exist; creating from example", configurationFile); + var source = Path.Combine(AppContext.BaseDirectory, "config", $"{AppName}.example.yml"); + var destination = configurationFile; + IOFile.Copy(source, destination); + } + catch (Exception ex) + { + Log.Error("Failed to create configuration file {ConfigurationFile}: {Message}", configurationFile, ex.Message); + } + } + } + private static void GenerateX509Certificate(string password, string filename) { - Console.WriteLine("Generating X509 certificate..."); + Log.Information("Generating X509 certificate..."); filename = Path.Combine(AppContext.BaseDirectory, filename); var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); - Console.WriteLine($"Password: {password}"); - Console.WriteLine($"Certificate exported to {filename}"); + Log.Information($"Password: {password}"); + Log.Information($"Certificate exported to {filename}"); } private static void PrintCommandLineArguments(Type targetType) @@ -516,12 +881,12 @@ namespace slskd var longestItem = lines.Max(l => l.Item.Length); - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); + Log.Information("\nusage: slskd [arguments]\n"); + Log.Information("arguments:\n"); foreach (var line in lines) { - Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}"); + Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}"); } } @@ -570,11 +935,11 @@ namespace slskd var longestItem = lines.Max(l => l.Item.Length); - Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n"); + Log.Information("\nenvironment variables (arguments and config file have precedence):\n"); foreach (var line in lines) { - Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}"); + Log.Information($" {line.Item.PadRight(longestItem)} {line.Description}"); } } @@ -627,13 +992,13 @@ namespace slskd private static void VerifyDirectory(string directory, bool createIfMissing = true, bool verifyWriteable = true) { - if (!Directory.Exists(directory)) + if (!System.IO.Directory.Exists(directory)) { if (createIfMissing) { try { - Directory.CreateDirectory(directory); + System.IO.Directory.CreateDirectory(directory); } catch (Exception ex) { -- cgit v1.2.3 From 9ae756c433ab05d5c1531a347ac4928ee99f1188 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Apr 2022 17:27:41 -0500 Subject: remove deprecated startup --- src/slskd/Startup.cs | 409 --------------------------------------------------- 1 file changed, 409 deletions(-) delete mode 100644 src/slskd/Startup.cs diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs deleted file mode 100644 index 29f9717f..00000000 --- a/src/slskd/Startup.cs +++ /dev/null @@ -1,409 +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 -{ - using System; - using System.IO; - using System.Linq; - using System.Text; - using System.Text.Json.Serialization; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Diagnostics; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc.ApiExplorer; - using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.FileProviders; - using Microsoft.IdentityModel.Tokens; - using Microsoft.OpenApi.Models; - using Prometheus; - using Prometheus.SystemMetrics; - using Serilog; - using slskd.Authentication; - using slskd.Core.API; - using slskd.Integrations.FTP; - using slskd.Integrations.Pushbullet; - using slskd.Messaging; - using slskd.Search; - using slskd.Search.API; - using slskd.Shares; - using slskd.Transfers; - using slskd.Users; - using slskd.Validation; - using Soulseek; - - /// - /// ASP.NET Startup. - /// - public class Startup - { - /// - /// Initializes a new instance of the class. - /// - /// The application configuration root. - public Startup(IConfiguration configuration) - { - Configuration = configuration; - - OptionsAtStartup = new OptionsAtStartup(); - Configuration.GetSection(Program.AppName).Bind(OptionsAtStartup, (o) => - { - o.BindNonPublicProperties = true; - }); - - UrlBase = OptionsAtStartup.Web.UrlBase; - UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; - - ContentPath = Path.GetFullPath(OptionsAtStartup.Web.ContentPath); - - JwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); - } - - private IConfiguration Configuration { get; } - private string ContentPath { get; set; } - private SymmetricSecurityKey JwtSigningKey { get; set; } - private OptionsAtStartup OptionsAtStartup { get; } - private string UrlBase { get; set; } - - /// - /// Configure services. - /// - /// The service collection. - public void ConfigureServices(IServiceCollection services) - { - var logger = Log.ForContext(); - - // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but - // the values at startup are to be used. - services.AddSingleton(OptionsAtStartup); - - // add IOptionsMonitor and IOptionsSnapshot to DI. use when the current Options are to be used. - services.AddOptions() - .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; }) - .Validate(options => - { - if (!options.TryValidate(out var result)) - { - logger.Warning("Options (re)configuration rejected."); - logger.Warning(result.GetResultView()); - return false; - } - - return true; - }); - - services.AddManagedState(); - - services.AddCors(options => options.AddPolicy("AllowAll", builder => builder - .AllowAnyHeader() - .AllowAnyMethod() - .SetIsOriginAllowed((host) => true) - .AllowCredentials())); - - services.AddSingleton(JwtSigningKey); - - if (!OptionsAtStartup.Web.Authentication.Disabled) - { - services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { - options.TokenValidationParameters = new TokenValidationParameters - { - ClockSkew = TimeSpan.FromMinutes(5), - RequireSignedTokens = true, - RequireExpirationTime = true, - ValidateLifetime = true, - ValidIssuer = Program.AppName, - ValidateIssuer = true, - ValidateAudience = false, - IssuerSigningKey = JwtSigningKey, - ValidateIssuerSigningKey = true, - }; - - options.Events = new JwtBearerEvents - { - OnMessageReceived = context => - { - // assign the request token from the access_token query parameter - // but only if the destination is a SignalR hub - // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0 - if (context.HttpContext.Request.Path.StartsWithSegments("/hub")) - { - context.Token = context.Request.Query["access_token"]; - } - - return Task.CompletedTask; - }, - }; - }); - } - else - { - logger.Warning("Authentication of web requests is DISABLED"); - - services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) - .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => - { - options.Username = "Anonymous"; - options.Role = Role.Administrator; - }); - } - - services.AddRouting(options => options.LowercaseUrls = true); - services.AddControllers().AddJsonOptions(options => - { - options.JsonSerializerOptions.Converters.Add(new IPAddressConverter()); - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; - }); - - services.AddSignalR().AddJsonProtocol(options => - { - options.PayloadSerializerOptions.Converters.Add(new IPAddressConverter()); - options.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - }); - - services.AddHealthChecks(); - - services.AddApiVersioning(options => options.ReportApiVersions = true); - services.AddVersionedApiExplorer(options => - { - options.GroupNameFormat = "'v'VVV"; - options.SubstituteApiVersionInUrl = true; - }); - - if (OptionsAtStartup.Feature.Swagger) - { - services.AddSwaggerGen(options => - { - options.DescribeAllParametersInCamelCase(); - options.SwaggerDoc( - "v0", - new OpenApiInfo - { - Title = Program.AppName, - Version = "v0", - }); - - if (System.IO.File.Exists(Program.XmlDocumentationFile)) - { - options.IncludeXmlComments(Program.XmlDocumentationFile); - } - else - { - logger.Warning($"Unable to find XML documentation in {Program.XmlDocumentationFile}, Swagger will not include metadata"); - } - }); - } - - if (OptionsAtStartup.Feature.Prometheus) - { - services.AddSystemMetrics(); - } - - services.AddDbContextFactory(options => - { - options.UseSqlite($"Data Source={Path.Combine(Program.AppDirectory, "data", "search.db")}"); - }); - - services.AddHttpClient(); - - // add a partially configured instance of SoulseekClient. the Application instance will - // complete configuration at startup. - services.AddSingleton(_ => - new SoulseekClient(options: new SoulseekClientOptions( - maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, - maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); - - // add the core application service to DI as well as a hosted service so that other services can - // access instance methods - services.AddSingleton(); - services.AddHostedService(p => p.GetRequiredService()); - - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - - services.AddSingleton(); - - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - services.AddSingleton(); - services.AddSingleton(); - - services.AddSingleton(); - } - - /// - /// Configure middleware. - /// - /// The application builder. - /// The api version description provider. - public void Configure( - IApplicationBuilder app, - IApiVersionDescriptionProvider apiVersionDescriptionProvider) - { - var logger = Log.ForContext(); - - // initialize DbContext instances to avoid race conditions when a db needs to be - // created from scratch. note that this method needs to be updated to include each - // DbContext explicitly. - InitializeDbContexts(app); - - app.UseExceptionHandler(a => a.Run(async context => - { - await context.Response.WriteAsJsonAsync(context.Features.Get().Error.Message); - })); - - app.UseCors("AllowAll"); - - if (OptionsAtStartup.Web.Https.Force) - { - app.UseHttpsRedirection(); - app.UseHsts(); - - logger.Information($"Forcing HTTP requests to HTTPS"); - } - - // allow users to specify a custom path base, for use behind a reverse proxy - app.UsePathBase(UrlBase); - logger.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("//")) - { - context.Request.Path = new string(path.Skip(1).ToArray()); - } - - await next(); - }); - - FileServerOptions fileServerOptions = default; - - if (!System.IO.Directory.Exists(ContentPath)) - { - logger.Warning($"Static content disabled; cannot find content path '{ContentPath}'"); - } - else - { - fileServerOptions = new FileServerOptions - { - FileProvider = new PhysicalFileProvider(ContentPath), - RequestPath = string.Empty, - EnableDirectoryBrowsing = false, - EnableDefaultFiles = true, - }; - - app.UseFileServer(fileServerOptions); - logger.Information("Serving static content from {ContentPath}", ContentPath); - } - - if (OptionsAtStartup.Feature.Prometheus) - { - app.UseHttpMetrics(); - logger.Information("Publishing Prometheus metrics to /metrics"); - } - - if (OptionsAtStartup.Web.Logging) - { - app.UseSerilogRequestLogging(); - } - - app.UseAuthentication(); - - app.UseRouting(); - app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapHub("/hub/application"); - endpoints.MapHub("/hub/logs"); - endpoints.MapHub("/hub/search"); - - endpoints.MapControllers(); - endpoints.MapHealthChecks("/health"); - - if (OptionsAtStartup.Feature.Prometheus) - { - endpoints.MapMetrics("/metrics"); - } - }); - - if (OptionsAtStartup.Feature.Swagger) - { - app.UseSwagger(); - app.UseSwaggerUI(options => apiVersionDescriptionProvider.ApiVersionDescriptions.ToList() - .ForEach(description => options.SwaggerEndpoint($"{(UrlBase == "/" ? string.Empty : UrlBase)}/swagger/{description.GroupName}/swagger.json", description.GroupName))); - - logger.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 - app.Use(async (context, next) => - { - // exclude API routes which are not matched or return a 404 - if (!context.Request.Path.StartsWithSegments("/api")) - { - context.Request.Path = "/"; - } - - 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); - } - } - - private void InitializeDbContexts(IApplicationBuilder app) - { - var logger = Log.ForContext(); - - IDbContextFactory GetFactory() - where T : DbContext - => app.ApplicationServices.GetRequiredService>(); - - logger.Debug("Initializing database contexts"); - - try - { - using var search = GetFactory().CreateDbContext(); - } - catch (Exception ex) - { - logger.Error(ex, "Failed to initialize one or more application databases"); - throw; - } - } - } -} \ No newline at end of file -- cgit v1.2.3 From 5a30bbdee5779efb117f1de421397bd09621e1f7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Apr 2022 10:57:28 -0500 Subject: convert to extensions --- src/slskd/Program.cs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1e51cc5b..6e855ecf 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -372,14 +372,13 @@ namespace slskd } }); - var services = builder.Services; - - ConfigureAspDotNetServices(services); - ConfigureDependencyInjectionContainer(services); + builder.Services + .ConfigureAspDotNetServices() + .ConfigureDependencyInjectionContainer(); var app = builder.Build(); - ConfigureAspDotNetPipeline(app); + app.ConfigureAspDotNetPipeline(); if (OptionsAtStartup.NoStart) { @@ -399,7 +398,7 @@ namespace slskd } } - private static void ConfigureDependencyInjectionContainer(IServiceCollection services) + private static IServiceCollection ConfigureDependencyInjectionContainer(this IServiceCollection services) { // add the instance of OptionsAtStartup to DI as they were at startup. use when Options might change, but // the values at startup are to be used (generally anything marked RequiresRestart). @@ -471,9 +470,11 @@ namespace slskd }); services.InitializeDbContext(); + + return services; } - private static void ConfigureAspDotNetServices(IServiceCollection services) + private static IServiceCollection ConfigureAspDotNetServices(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder .AllowAnyHeader() @@ -583,9 +584,11 @@ namespace slskd { services.AddSystemMetrics(); } + + return services; } - private static void ConfigureAspDotNetPipeline(WebApplication app) + private static WebApplication ConfigureAspDotNetPipeline(this WebApplication app) { app.UseExceptionHandler(a => a.Run(async context => { @@ -703,6 +706,8 @@ namespace slskd { app.UseFileServer(fileServerOptions); } + + return app; } private static void ConfigureGlobalLogger() -- cgit v1.2.3 From 6a332e8c1c41c6adc293fd15fc2c1856e25e658c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Apr 2022 12:58:38 -0500 Subject: simplify addition of DbContexts --- src/slskd/Program.cs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6e855ecf..5e5594d8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -445,6 +445,8 @@ namespace slskd services.AddSingleton(); services.AddHostedService(p => p.GetRequiredService()); + services.AddDbContext("search.db"); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -462,15 +464,6 @@ namespace slskd services.AddSingleton(); - // initialize DbContext instances to avoid race conditions when a db needs to be created from scratch. - // important: do this last - services.AddDbContextFactory(options => - { - options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", "search.db")}"); - }); - - services.InitializeDbContext(); - return services; } @@ -790,21 +783,28 @@ namespace slskd commandLine: Environment.CommandLine); } - private static void InitializeDbContext(this IServiceCollection services) - where TContext : DbContext + private static IServiceCollection AddDbContext(this IServiceCollection services, string filename) + where T : DbContext { - Log.Debug($"Initializing database context {typeof(TContext).Name}"); + Log.Debug($"Initializing database context {typeof(T).Name}"); try { + services.AddDbContextFactory(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + }); + using var ctx = services .BuildServiceProvider() - .GetRequiredService>() + .GetRequiredService>() .CreateDbContext(); + + return services; } catch (Exception ex) { - Log.Error(ex, $"Failed to initialize database context {typeof(TContext).Name}: ${ex.Message}"); + Log.Error(ex, $"Failed to initialize database context {typeof(T).Name}: ${ex.Message}"); throw; } } -- cgit v1.2.3 From efd8fd01f134d206071771b38a0aa61167817250 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Apr 2022 17:38:32 -0500 Subject: hide Microsoft warnings --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5e5594d8..afdf4ab3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -706,7 +706,7 @@ namespace slskd private static void ConfigureGlobalLogger() { Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) - .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) + .MinimumLevel.Override("Microsoft", LogEventLevel.Error) .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) -- cgit v1.2.3 From 54be459ca2a7c9ea9a7161256eb139d1302fc130 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Apr 2022 20:20:42 -0500 Subject: resolve some warnings --- src/slskd/Application.cs | 3 +-- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 ++ src/slskd/Transfers/Uploads/UploadService.cs | 19 ++++++++++++++++++- src/slskd/Users/UserService.cs | 2 +- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 115d0b37..1064e56a 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -44,7 +44,7 @@ namespace slskd using slskd.Users; using Soulseek; using Soulseek.Diagnostics; - + public interface IApplication : IHostedService { public Task CheckVersionAsync(); @@ -892,7 +892,6 @@ namespace slskd private void State_OnChange((State Previous, State Current) state) { - //Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); _ = ApplicationHub.BroadcastStateAsync(state.Current); } diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index e5b8c5f5..de8cc031 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -199,7 +199,9 @@ namespace slskd.Transfers } } +#pragma warning disable S3241 // Methods should not return values that are never used private Upload Process() +#pragma warning restore S3241 // Methods should not return values that are never used { SyncRoot.Wait(); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 99f12df4..f88e80a8 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -1,4 +1,21 @@ -namespace slskd.Transfers.Uploads +// +// 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.Transfers.Uploads { /// /// Manages uploads. diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index aa2ae234..95fed12d 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -54,7 +54,7 @@ namespace slskd.Users // binding these events will cause multiple redundant round trips when initially watching a user // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics()); - Client.UserStatusChanged += (_, userStatus) => + Client.UserStatusChanged += (sender, userStatus) => { UpdateStatus(userStatus.Username, userStatus.ToStatus()); -- cgit v1.2.3 From 9bac7cfcdb9e92e9db26a71b3afa6ce5318b9225 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Apr 2022 08:29:56 -0500 Subject: send the room name in body when joining --- src/slskd/Messaging/API/Controllers/RoomsController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 743df527..79c06989 100644 --- a/src/slskd/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -236,11 +236,11 @@ namespace slskd.Messaging.API /// /// The request completed successfully. /// The room has already been joined. - [HttpPost("joined/{roomName}")] + [HttpPost("joined")] [Authorize] [ProducesResponseType(typeof(Room), 201)] [ProducesResponseType(304)] - public async Task JoinRoom([FromRoute]string roomName) + public async Task JoinRoom([FromBody]string roomName) { if (Tracker.Rooms.ContainsKey(roomName)) { -- cgit v1.2.3 From 4bc141d59931b56f2c90bad6d83a161404a8df1f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Apr 2022 08:30:28 -0500 Subject: room name in body --- src/web/src/lib/rooms.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js index c2a36187..bc081651 100644 --- a/src/web/src/lib/rooms.js +++ b/src/web/src/lib/rooms.js @@ -45,7 +45,7 @@ export const getUsers = async ({ roomName }) => { }; export const join = async ({ roomName }) => { - return api.post(`/rooms/joined/${roomName}`); + return api.post('/rooms/joined', roomName); }; export const leave = async ({ roomName }) => { -- cgit v1.2.3 From 988b3b1628679c26518e75450d588e8c86108a69 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Apr 2022 08:30:38 -0500 Subject: url encode room names --- src/web/src/lib/rooms.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js index bc081651..c30a7a15 100644 --- a/src/web/src/lib/rooms.js +++ b/src/web/src/lib/rooms.js @@ -23,7 +23,7 @@ export const getJoined = async () => { }; export const getMessages = async ({ roomName }) => { - const response = (await api.get(`/rooms/joined/${roomName}/messages`)).data; + const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/messages`)).data; if (!Array.isArray(response)) { console.warn('got non-array response from rooms API', response) @@ -34,7 +34,7 @@ export const getMessages = async ({ roomName }) => { }; export const getUsers = async ({ roomName }) => { - const response = (await api.get(`/rooms/joined/${roomName}/users`)).data; + const response = (await api.get(`/rooms/joined/${encodeURIComponent(roomName)}/users`)).data; if (!Array.isArray(response)) { console.warn('got non-array response from rooms API', response) @@ -49,9 +49,9 @@ export const join = async ({ roomName }) => { }; export const leave = async ({ roomName }) => { - return api.delete(`/rooms/joined/${roomName}`); + return api.delete(`/rooms/joined/${encodeURIComponent(roomName)}`); }; export const sendMessage = async ({ roomName, message }) => { - return api.post(`/rooms/joined/${roomName}/messages`, JSON.stringify(message)); + return api.post(`/rooms/joined/${encodeURIComponent(roomName)}/messages`, JSON.stringify(message)); }; \ No newline at end of file -- cgit v1.2.3 From 17dea9248e4fefba4afde46112485da8a60b4649 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Apr 2022 08:32:27 -0500 Subject: url encode usernames, remove deprecated bypassCache flag for info --- src/web/src/components/Users/Users.js | 2 +- src/web/src/lib/users.js | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/web/src/components/Users/Users.js b/src/web/src/components/Users/Users.js index d07772e7..7927b718 100644 --- a/src/web/src/components/Users/Users.js +++ b/src/web/src/components/Users/Users.js @@ -45,7 +45,7 @@ const Users = (props) => { try { const [info, status, endpoint] = await Promise.all([ - users.getInfo({ username: selectedUsername, bypassCache: true }), + users.getInfo({ username: selectedUsername }), users.getStatus({ username: selectedUsername }), users.getEndpoint({ username: selectedUsername }) ]); diff --git a/src/web/src/lib/users.js b/src/web/src/lib/users.js index a8cd4f88..f79cea20 100644 --- a/src/web/src/lib/users.js +++ b/src/web/src/lib/users.js @@ -1,21 +1,21 @@ import api from './api'; -export const getInfo = ({ username, bypassCache = false }) => { - return api.get(`/users/${username}/info?bypassCache=${bypassCache}`); +export const getInfo = ({ username }) => { + return api.get(`/users/${encodeURIComponent(username)}/info`); }; export const getStatus = ({ username }) => { - return api.get(`/users/${username}/status`); + return api.get(`/users/${encodeURIComponent(username)}/status`); }; export const getEndpoint = ({ username }) => { - return api.get(`/users/${username}/endpoint`); + return api.get(`/users/${encodeURIComponent(username)}/endpoint`); }; export const browse = async ({ username }) => { - return (await api.get(`/users/${username}/browse`)).data; + return (await api.get(`/users/${encodeURIComponent(username)}/browse`)).data; }; export const getBrowseStatus = ({ username }) => { - return api.get(`/users/${username}/browse/status`); + return api.get(`/users/${encodeURIComponent(username)}/browse/status`); }; \ No newline at end of file -- cgit v1.2.3 From 1b17e1d8a4bf63bedbf1b62683acb30b6b0298f8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 08:54:01 -0500 Subject: add GET /urlbase --- src/slskd/Core/API/Controllers/ApplicationController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 19360fe1..9f38a17f 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Core.API { using System; @@ -37,15 +39,18 @@ namespace slskd.Core.API public ApplicationController( IHostApplicationLifetime lifetime, IApplication application, + IOptionsMonitor optionsMonitor, IStateMonitor applicationStateMonitor) { Lifetime = lifetime; Application = application; + OptionsMonitor = optionsMonitor; ApplicationStateMonitor = applicationStateMonitor; } private IApplication Application { get; } private IStateMonitor ApplicationStateMonitor { get; } + private IOptionsMonitor OptionsMonitor { get; } private IHostApplicationLifetime Lifetime { get; } /// @@ -146,5 +151,11 @@ namespace slskd.Core.API return Ok(); } + + [HttpGet("urlbase")] + public IActionResult GetUrlBase() + { + return Ok(OptionsMonitor.CurrentValue.Web.UrlBase); + } } } -- cgit v1.2.3 From f17d21ac2c11405490ed81e897cd6847b0e2b8cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 08:54:10 -0500 Subject: add getUrlBase --- src/web/src/lib/application.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/web/src/lib/application.js b/src/web/src/lib/application.js index 0c8b8319..da5bbef5 100644 --- a/src/web/src/lib/application.js +++ b/src/web/src/lib/application.js @@ -4,6 +4,10 @@ export const getState = async () => { return (await api.get('/application')).data; }; +export const getUrlBase = async () => { + return (await api.get('/application/urlbase')).data; +} + export const restart = async () => { return api.put('/application'); }; -- cgit v1.2.3 From 5eca39f47ce7a9677325559c9d4ec0e1f2167564 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 08:56:41 -0500 Subject: force /searches --- src/web/src/components/App.js | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 3a22e0c8..19ea8d37 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -1,7 +1,8 @@ import React, { Component } from 'react'; -import { Route, Link, Switch } from "react-router-dom"; +import { Route, Link, Switch, Redirect } from "react-router-dom"; import * as session from '../lib/session'; +import * as application from '../lib/application'; import { connect, disconnect } from '../lib/server'; import { createApplicationHubConnection } from '../lib/hubFactory'; @@ -38,6 +39,7 @@ const initialState = { initialized: false, error: false, retriesExhausted: false, + urlBase: '', }; class App extends Component { @@ -50,7 +52,12 @@ class App extends Component { init = async () => { this.setState({ initialized: false }, async () => { try { - const securityEnabled = await session.getSecurityEnabled(); + const [urlBase, securityEnabled] = await Promise.all([ + application.getUrlBase(), + session.getSecurityEnabled()] + ); + + this.setState({ urlBase }); if (!securityEnabled) { console.debug('application security is not enabled, per api call') @@ -109,7 +116,7 @@ class App extends Component { }; render = () => { - const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state; + const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted, urlBase = '' } = this.state; const { version = {}, server } = applicationState; const { isUpdateAvailable, current, latest } = version; @@ -150,37 +157,37 @@ class App extends Component { {version.isCanary && Canary } - + Search - + Downloads - + Uploads - + Rooms - + Chat - + Users - + Browse @@ -221,7 +228,7 @@ class App extends Component { href="https://github.com/slskd/slskd/releases">See Release Notes } - + System @@ -242,14 +249,15 @@ class App extends Component { + this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> + this.withTokenCheck()}/> + -- cgit v1.2.3 From d4b096d2e638c33a19bfd593b3ca1ed956f527ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 08:56:50 -0500 Subject: make panes navigable by url --- src/web/src/components/System/System.js | 43 +++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js index 8b0ea4d4..ac6f5dfd 100644 --- a/src/web/src/components/System/System.js +++ b/src/web/src/components/System/System.js @@ -1,24 +1,35 @@ -import React, { Component } from 'react'; +import React from 'react'; +import { useRouteMatch } from "react-router-dom"; + import { Segment, Tab } from 'semantic-ui-react'; + import './System.css'; + import Info from './Info'; import Logs from './Logs'; import Options from './Options'; -class System extends Component { - render = () => { - return ( -
- - }, - { menuItem: 'Options', render: () => }, - { menuItem: 'Logs', render: () => }, - ]}/> - -
- ); - } -} +const System = ({ state = {}, options = {} }) => { + const { params: { tab }} = useRouteMatch(); + + const panes = [ + { route: 'info', menuItem: 'Info', render: () => }, + { route: 'options', menuItem: 'Options', render: () => }, + { route: 'logs', menuItem: 'Logs', render: () => }, + ] + + const activeIndex = panes.findIndex(pane => pane.route === tab) + + return ( +
+ + -1 ? activeIndex : 0} + panes={panes} + /> + +
+ ); +}; export default System; \ No newline at end of file -- cgit v1.2.3 From 12f2aded2257a7dcc9dbb00cbbd8bafc28579ad4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 09:23:02 -0500 Subject: navigate on tab click, set initial tab with redirect --- src/web/src/components/System/System.js | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/web/src/components/System/System.js b/src/web/src/components/System/System.js index ac6f5dfd..ca88c50d 100644 --- a/src/web/src/components/System/System.js +++ b/src/web/src/components/System/System.js @@ -1,5 +1,5 @@ import React from 'react'; -import { useRouteMatch } from "react-router-dom"; +import { useRouteMatch, useHistory, Redirect } from "react-router-dom"; import { Segment, Tab } from 'semantic-ui-react'; @@ -10,7 +10,8 @@ import Logs from './Logs'; import Options from './Options'; const System = ({ state = {}, options = {} }) => { - const { params: { tab }} = useRouteMatch(); + const { params: { tab }, ...route } = useRouteMatch(); + const history = useHistory(); const panes = [ { route: 'info', menuItem: 'Info', render: () => }, @@ -20,12 +21,21 @@ const System = ({ state = {}, options = {} }) => { const activeIndex = panes.findIndex(pane => pane.route === tab) + const onTabChange = (e, { activeIndex }) => { + history.push(panes[activeIndex].route) + } + + if (tab === undefined) { + return + } + return (
-1 ? activeIndex : 0} panes={panes} + onTabChange={onTabChange} />
-- cgit v1.2.3 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/Common/StrictUrlBaseMiddleware.cs | 80 +++++++++++++++++++++++++++++ src/slskd/Program.cs | 4 ++ 2 files changed, 84 insertions(+) create mode 100644 src/slskd/Common/StrictUrlBaseMiddleware.cs diff --git a/src/slskd/Common/StrictUrlBaseMiddleware.cs b/src/slskd/Common/StrictUrlBaseMiddleware.cs new file mode 100644 index 00000000..7efdd171 --- /dev/null +++ b/src/slskd/Common/StrictUrlBaseMiddleware.cs @@ -0,0 +1,80 @@ +// +// 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.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + using Serilog; + + /// + /// Adds the . + /// + public static class StrictUrlBaseMiddlewareExtensions + { + /// + /// Ensures that routes are prefixed with . + /// + /// + /// + /// + public static IApplicationBuilder EnforceUrlBase( + this IApplicationBuilder builder, string urlBase) + { + return builder.UseMiddleware(urlBase); + } + } + + /// + /// Ensures that routes are prefixed with UrlBase. + /// + public class StrictUrlBaseMiddleware + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase) + { + Next = next; + UrlBase = urlBase; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private RequestDelegate Next { get; } + private string UrlBase { get; } + + /// + /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase. + /// + /// + /// + public async Task InvokeAsync(HttpContext context) + { + if (!context.Request.Path.ToString().StartsWith(UrlBase)) + { + Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase); + context.Response.StatusCode = 404; + return; + } + + await Next(context); + } + } +} \ No newline at end of file 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 7d4045dfe84e096adcb66250ef849afd6a5d4500 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 17:47:53 -0500 Subject: remove urlbase? --- src/web/src/components/App.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 19ea8d37..9c64c1a9 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -157,37 +157,37 @@ class App extends Component { {version.isCanary && Canary } - + Search - + Downloads - + Uploads - + Rooms - + Chat - + Users - + Browse @@ -228,7 +228,7 @@ class App extends Component { href="https://github.com/slskd/slskd/releases">See Release Notes } - + System @@ -256,8 +256,8 @@ class App extends Component { this.withTokenCheck()}/> this.withTokenCheck()}/> this.withTokenCheck()}/> - this.withTokenCheck()}/> - + this.withTokenCheck()}/> + -- cgit v1.2.3 From 56d9a2a52a0efd67f9bf6a6e24c1644a0e9fb6c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:46:47 -0500 Subject: copy status files after each web build --- bin/build | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/bin/build b/bin/build index deb26fba..76bad614 100755 --- a/bin/build +++ b/bin/build @@ -65,16 +65,14 @@ else echo $'\n\t🛠️ npm run build\n' npm run build - if [ "$web_only" == false ]; then - # remove old build, but keep .gitkeep - rm -rf ../slskd/wwwroot - mkdir ../slskd/wwwroot - touch ../slskd/wwwroot/.gitkeep + # remove old build, but keep .gitkeep + rm -rf ../slskd/wwwroot + mkdir ../slskd/wwwroot + touch ../slskd/wwwroot/.gitkeep - # copy new files - echo $'\n\t🛠️ cp -r build/* ../slskd/wwwroot/\n' - cp -r build/* ../slskd/wwwroot/ - fi + # copy new files + echo $'\n\t🛠️ cp -r build/* ../slskd/wwwroot/\n' + cp -r build/* ../slskd/wwwroot/ cd ../.. fi -- cgit v1.2.3 From 536b9c3192929cced4a8925d9dbc8bec85736524 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:47:05 -0500 Subject: retrieve urlBase from window variables --- src/web/src/config.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/web/src/config.js b/src/web/src/config.js index ea71e9dd..8acec820 100644 --- a/src/web/src/config.js +++ b/src/web/src/config.js @@ -1,5 +1,7 @@ -const rootUrl = process.env.NODE_ENV === 'production' ? '' : 'http://localhost:5000/'; -const baseUrl = `${rootUrl}api/v0`; +const urlBase = window.urlBase || ''; +const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:5000${urlBase}`; +const apiBaseUrl = `${rootUrl}/api/v0`; +const hubBaseUrl = `${rootUrl}/hub`; const tokenKey = 'slskd-token'; const tokenPassthroughValue = 'n/a'; const activeChatKey = 'slskd-active-chat'; @@ -7,8 +9,10 @@ const activeRoomKey = 'slskd-active-room'; const activeUserInfoKey = 'slskd-active-user'; export { + urlBase, rootUrl, - baseUrl, + apiBaseUrl, + hubBaseUrl, tokenKey, tokenPassthroughValue, activeChatKey, -- cgit v1.2.3 From ab2b78f4466ee4c0535a775ca5f717c9b549055a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:47:25 -0500 Subject: use api and hub baseurls --- src/web/src/lib/api.js | 4 ++-- src/web/src/lib/hubFactory.js | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js index 73e75373..0e7d8050 100644 --- a/src/web/src/lib/api.js +++ b/src/web/src/lib/api.js @@ -1,8 +1,8 @@ import axios from 'axios'; -import { baseUrl } from '../config'; +import { apiBaseUrl } from '../config'; import * as session from './session'; -axios.defaults.baseURL = baseUrl; +axios.defaults.baseURL = apiBaseUrl; const api = axios.create({ withCredentials: true diff --git a/src/web/src/lib/hubFactory.js b/src/web/src/lib/hubFactory.js index a64c5c40..246e9d03 100644 --- a/src/web/src/lib/hubFactory.js +++ b/src/web/src/lib/hubFactory.js @@ -4,7 +4,7 @@ import { LogLevel } from '@microsoft/signalr' -import { rootUrl } from '../config'; +import { hubBaseUrl } from '../config'; import * as session from '../lib/session'; export const createHubConnection = ({ url }) => @@ -18,6 +18,6 @@ export const createHubConnection = ({ url }) => .configureLogging(LogLevel.Warning) .build(); -export const createApplicationHubConnection = () => createHubConnection({ url: `${rootUrl}hub/application` }); +export const createApplicationHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/application` }); -export const createLogsHubConnection = () => createHubConnection({ url: `${rootUrl}hub/logs` }); \ No newline at end of file +export const createLogsHubConnection = () => createHubConnection({ url: `${hubBaseUrl}/logs` }); \ No newline at end of file -- cgit v1.2.3 From 449fc05acf88e742849c2d83bc86fbf2fd77e5e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:47:40 -0500 Subject: remove getUrlBase --- src/web/src/lib/application.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/web/src/lib/application.js b/src/web/src/lib/application.js index da5bbef5..0c8b8319 100644 --- a/src/web/src/lib/application.js +++ b/src/web/src/lib/application.js @@ -4,10 +4,6 @@ export const getState = async () => { return (await api.get('/application')).data; }; -export const getUrlBase = async () => { - return (await api.get('/application/urlbase')).data; -} - export const restart = async () => { return api.put('/application'); }; -- cgit v1.2.3 From f62e6e4b63fabd32e32f3307f968f4e414a59152 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:48:07 -0500 Subject: explicitly append urlBase --- src/web/src/components/App.js | 46 +++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index 9c64c1a9..09f3f742 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -2,8 +2,8 @@ import React, { Component } from 'react'; import { Route, Link, Switch, Redirect } from "react-router-dom"; import * as session from '../lib/session'; -import * as application from '../lib/application'; import { connect, disconnect } from '../lib/server'; +import { urlBase } from '../config'; import { createApplicationHubConnection } from '../lib/hubFactory'; @@ -39,7 +39,6 @@ const initialState = { initialized: false, error: false, retriesExhausted: false, - urlBase: '', }; class App extends Component { @@ -52,12 +51,7 @@ class App extends Component { init = async () => { this.setState({ initialized: false }, async () => { try { - const [urlBase, securityEnabled] = await Promise.all([ - application.getUrlBase(), - session.getSecurityEnabled()] - ); - - this.setState({ urlBase }); + const securityEnabled = await session.getSecurityEnabled(); if (!securityEnabled) { console.debug('application security is not enabled, per api call') @@ -116,7 +110,7 @@ class App extends Component { }; render = () => { - const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted, urlBase = '' } = this.state; + const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state; const { version = {}, server } = applicationState; const { isUpdateAvailable, current, latest } = version; @@ -157,37 +151,37 @@ class App extends Component { {version.isCanary && Canary } - + Search - + Downloads - + Uploads - + Rooms - + Chat - + Users - + Browse @@ -228,7 +222,7 @@ class App extends Component { href="https://github.com/slskd/slskd/releases">See Release Notes } - + System @@ -249,15 +243,15 @@ class App extends Component { - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - this.withTokenCheck()}/> - + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + this.withTokenCheck()}/> + -- cgit v1.2.3 From 46e2581957aa747da161e25cf0fa3e4a99dfc04e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 20:49:42 -0500 Subject: remove GetUrlBase --- src/slskd/Core/API/Controllers/ApplicationController.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 9f38a17f..cd03d96f 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -114,7 +114,7 @@ namespace slskd.Core.API /// [HttpGet("version/latest")] [Authorize] - public async Task CheckVersion([FromQuery]bool forceCheck = false) + public async Task CheckVersion([FromQuery] bool forceCheck = false) { if (forceCheck) { @@ -151,11 +151,5 @@ namespace slskd.Core.API return Ok(); } - - [HttpGet("urlbase")] - public IActionResult GetUrlBase() - { - return Ok(OptionsMonitor.CurrentValue.Web.UrlBase); - } } } -- cgit v1.2.3 From dd76dd55f13aaab06249b64fe897287356bdeb02 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 21:21:17 -0500 Subject: remove homepage --- src/web/package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/web/package.json b/src/web/package.json index a8810d47..54fc6e0b 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -2,7 +2,6 @@ "name": "web", "version": "0.1.0", "private": true, - "homepage": ".", "dependencies": { "@codemirror/highlight": "^0.19.7", "@codemirror/legacy-modes": "^0.19.0", @@ -52,4 +51,4 @@ "not op_mini all" ] } -} +} \ No newline at end of file -- cgit v1.2.3 From ab66d41d8676ceda951f0bb1b7d940c09f2f1c2d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 21:21:31 -0500 Subject: add urlBase script to index --- src/web/public/index.html | 1 + src/web/src/config.js | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/web/public/index.html b/src/web/public/index.html index e452c8c8..fa11b640 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -10,3 +10,4 @@
+ \ No newline at end of file diff --git a/src/web/src/config.js b/src/web/src/config.js index 8acec820..6f899564 100644 --- a/src/web/src/config.js +++ b/src/web/src/config.js @@ -1,5 +1,5 @@ -const urlBase = window.urlBase || ''; -const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:5000${urlBase}`; +const urlBase = (window.urlBase === '/' ? '' : window.urlBase) || ''; +const rootUrl = process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:5000/${urlBase}`; const apiBaseUrl = `${rootUrl}/api/v0`; const hubBaseUrl = `${rootUrl}/hub`; const tokenKey = 'slskd-token'; -- cgit v1.2.3 From e52d636f8a2069394653992384ef7f3cdcafea5d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 3 May 2022 22:46:23 -0500 Subject: add homepage back --- src/web/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/web/package.json b/src/web/package.json index 54fc6e0b..62b72a55 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -2,6 +2,7 @@ "name": "web", "version": "0.1.0", "private": true, + "homepage": ".", "dependencies": { "@codemirror/highlight": "^0.19.7", "@codemirror/legacy-modes": "^0.19.0", -- 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(+) 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 e4762962e0849ef768519a7e053cd2cafc7973b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 May 2022 21:08:58 -0500 Subject: check that the content path exists --- src/slskd/Options.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 00ae670e..a1493ca4 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -965,6 +965,7 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] + [DirectoryExists] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; -- 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(-) 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 d4735cd0917a214d4ea8ec75cf44186d2fd04c15 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 4 May 2022 22:27:08 -0500 Subject: add CacheKey --- src/slskd/Common/CacheKey.cs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/slskd/Common/CacheKey.cs diff --git a/src/slskd/Common/CacheKey.cs b/src/slskd/Common/CacheKey.cs new file mode 100644 index 00000000..039d144d --- /dev/null +++ b/src/slskd/Common/CacheKey.cs @@ -0,0 +1,24 @@ +// +// 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 -- 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(-) 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 25b770b9fee1e2c429cf378d624f750963b146d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 20:17:29 -0500 Subject: move middleware --- .../Common/Middleware/StrictUrlBaseMiddleware.cs | 80 ++++++++++++++++++++++ src/slskd/Common/StrictUrlBaseMiddleware.cs | 80 ---------------------- 2 files changed, 80 insertions(+), 80 deletions(-) create mode 100644 src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs delete mode 100644 src/slskd/Common/StrictUrlBaseMiddleware.cs diff --git a/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs new file mode 100644 index 00000000..7efdd171 --- /dev/null +++ b/src/slskd/Common/Middleware/StrictUrlBaseMiddleware.cs @@ -0,0 +1,80 @@ +// +// 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.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + using Serilog; + + /// + /// Adds the . + /// + public static class StrictUrlBaseMiddlewareExtensions + { + /// + /// Ensures that routes are prefixed with . + /// + /// + /// + /// + public static IApplicationBuilder EnforceUrlBase( + this IApplicationBuilder builder, string urlBase) + { + return builder.UseMiddleware(urlBase); + } + } + + /// + /// Ensures that routes are prefixed with UrlBase. + /// + public class StrictUrlBaseMiddleware + { + /// + /// Initializes a new instance of the class. + /// + /// + /// + public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase) + { + Next = next; + UrlBase = urlBase; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private RequestDelegate Next { get; } + private string UrlBase { get; } + + /// + /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase. + /// + /// + /// + public async Task InvokeAsync(HttpContext context) + { + if (!context.Request.Path.ToString().StartsWith(UrlBase)) + { + Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase); + context.Response.StatusCode = 404; + return; + } + + await Next(context); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/StrictUrlBaseMiddleware.cs b/src/slskd/Common/StrictUrlBaseMiddleware.cs deleted file mode 100644 index 7efdd171..00000000 --- a/src/slskd/Common/StrictUrlBaseMiddleware.cs +++ /dev/null @@ -1,80 +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 -{ - using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - using Serilog; - - /// - /// Adds the . - /// - public static class StrictUrlBaseMiddlewareExtensions - { - /// - /// Ensures that routes are prefixed with . - /// - /// - /// - /// - public static IApplicationBuilder EnforceUrlBase( - this IApplicationBuilder builder, string urlBase) - { - return builder.UseMiddleware(urlBase); - } - } - - /// - /// Ensures that routes are prefixed with UrlBase. - /// - public class StrictUrlBaseMiddleware - { - /// - /// Initializes a new instance of the class. - /// - /// - /// - public StrictUrlBaseMiddleware(RequestDelegate next, string urlBase) - { - Next = next; - UrlBase = urlBase; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private RequestDelegate Next { get; } - private string UrlBase { get; } - - /// - /// Executes this middleware, returning a 404 response if the path is not prefixed with UrlBase. - /// - /// - /// - public async Task InvokeAsync(HttpContext context) - { - if (!context.Request.Path.ToString().StartsWith(UrlBase)) - { - Log.Debug("Request to {Path} rejected with 404; URL Base {UrlBase} is strictly enforced", context.Request.Path.ToString(), UrlBase); - context.Response.StatusCode = 404; - return; - } - - await Next(context); - } - } -} \ No newline at end of file -- cgit v1.2.3 From e3267df36b4a62d49658385c9d08b2d62df56ae0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 20:17:45 -0500 Subject: add HTMLInjectionMiddleware --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs new file mode 100644 index 00000000..ab41806c --- /dev/null +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -0,0 +1,60 @@ +namespace slskd +{ + using System; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + + public static class HTMLInjectionMiddlewareExtensions + { + public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html) + { + return builder.UseMiddleware(html); + } + } + + public class HTMLInjectionMiddleware + { + public HTMLInjectionMiddleware(RequestDelegate next, string html) + { + Next = next; + HTML = html; + } + + private string HTML { get; } + private RequestDelegate Next { get; } + + public async Task InvokeAsync(HttpContext context) + { + context.Request.Headers.TryGetValue("accept", out var accept); + var requestedTypes = accept.ToString().Split(','); + + var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + var isApiRoute = context.Request.Path.ToString().StartsWith("/api"); + var isGET = context.Request.Method == "GET"; + + var isInjectableType = requestedTypes + .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) + .Any(); + + if (!isApiRoute && isGET && isInjectableType) + { + context.Request.EnableBuffering(); + + await Next.Invoke(context); + + if (context.Response.StatusCode == 200) + { + await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(HTML)); + } + } + else + { + await Next.Invoke(context); + } + } + } +} -- 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(-) 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 eb1c6098957d992037ae20929fdc5ec5e1fa9520 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 20:34:38 -0500 Subject: remove urlbase script --- src/web/public/index.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/web/public/index.html b/src/web/public/index.html index fa11b640..5b30bc65 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -9,5 +9,4 @@
- - \ No newline at end of file + \ No newline at end of file -- cgit v1.2.3 From 7e9be73142ca1ddb3f5c7523c81367e6db55a895 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 20:44:02 -0500 Subject: docs --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 41 +++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index ab41806c..ba45c20b 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -1,4 +1,21 @@ -namespace slskd +// +// 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.Linq; @@ -7,16 +24,33 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; + /// + /// Adds the . + /// public static class HTMLInjectionMiddlewareExtensions { + /// + /// Injects the specified into html files. + /// + /// + /// + /// public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html) { return builder.UseMiddleware(html); } } + /// + /// Injects the specified HTML into html files. + /// public class HTMLInjectionMiddleware { + /// + /// Initializes a new instance of the class. + /// + /// + /// public HTMLInjectionMiddleware(RequestDelegate next, string html) { Next = next; @@ -26,6 +60,11 @@ private string HTML { get; } private RequestDelegate Next { get; } + /// + /// Executes this middleware, returning the contents of the requested HTML file with the specified HTML appended. + /// + /// + /// public async Task InvokeAsync(HttpContext context) { context.Request.Headers.TryGetValue("accept", out var accept); -- cgit v1.2.3 From 15b611ccd5cc3350743e1bae23def84938abe451 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 May 2022 21:56:54 -0500 Subject: refactor to work in production --- .../Common/Middleware/HTMLInjectionMiddleware.cs | 25 +++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index ba45c20b..41ceef51 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -18,8 +18,8 @@ namespace slskd { using System; + using System.IO; using System.Linq; - using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -81,14 +81,33 @@ namespace slskd if (!isApiRoute && isGET && isInjectableType) { - context.Request.EnableBuffering(); + 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) { - await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(HTML)); + // 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(body + HTML); } + + // 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 { -- 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 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 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(-) 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(-) 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