diff options
| -rw-r--r-- | src/slskd/Application.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Common/Logging/ConsoleWriteLineLogger.cs | 34 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 588 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 409 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadQueue.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 19 | ||||
| -rw-r--r-- | src/slskd/Users/UserService.cs | 2 |
7 files changed, 535 insertions, 522 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/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 file="ConsoleWriteLineLogger.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using Serilog.Events; + + /// <summary> + /// Logs messages to stdout via <see cref="Console.WriteLine(string)"/>. + /// </summary> + public class ConsoleWriteLineLogger : Serilog.ILogger + { + /// <inheritdoc/> + public void Write(LogEvent logEvent) + { + Console.WriteLine(logEvent.RenderMessage()); + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index a5c35dca..afdf4ab3 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,417 @@ 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<Startup>() - .Build(); + }); + + builder.Services + .ConfigureAspDotNetServices() + .ConfigureDependencyInjectionContainer(); + + var app = builder.Build(); + + app.ConfigureAspDotNetPipeline(); 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 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). + 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<Options>() + .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<State>(); + + // 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<ISoulseekClient, SoulseekClient>(_ => + 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<IApplication, Application>(); + services.AddHostedService(p => p.GetRequiredService<IApplication>()); + + services.AddDbContext<SearchDbContext>("search.db"); + + services.AddSingleton<ITransferTracker, TransferTracker>(); + services.AddSingleton<IBrowseTracker, BrowseTracker>(); + services.AddSingleton<IConversationTracker, ConversationTracker>(); + services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); + + services.AddSingleton<ISharedFileCache, SharedFileCache>(); + + services.AddSingleton<ISearchService, SearchService>(); + services.AddSingleton<IUserService, UserService>(); + services.AddSingleton<IRoomService, RoomService>(); + services.AddSingleton<ITransferService, TransferService>(); + + services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); + services.AddSingleton<IFTPService, FTPService>(); + + services.AddSingleton<IPushbulletService, PushbulletService>(); + + return services; + } + + private static IServiceCollection ConfigureAspDotNetServices(this 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<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(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(); + } + + return services; + } + + private static WebApplication ConfigureAspDotNetPipeline(this WebApplication app) + { + app.UseExceptionHandler(a => a.Run(async context => + { + await context.Response.WriteAsJsonAsync(context.Features.Get<IExceptionHandlerPathFeature>().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<ApplicationHub>("/hub/application"); + endpoints.MapHub<LogsHub>("/hub/logs"); + endpoints.MapHub<SearchHub>("/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<IApiVersionDescriptionProvider>().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); + } + + return app; + } + + private static void ConfigureGlobalLogger() + { + Serilog.Log.Logger = (OptionsAtStartup.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information()) + .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) + .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 +783,60 @@ namespace slskd commandLine: Environment.CommandLine); } + private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string filename) + where T : DbContext + { + Log.Debug($"Initializing database context {typeof(T).Name}"); + + try + { + services.AddDbContextFactory<SearchDbContext>(options => + { + options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + }); + + using var ctx = services + .BuildServiceProvider() + .GetRequiredService<IDbContextFactory<T>>() + .CreateDbContext(); + + return services; + } + catch (Exception ex) + { + Log.Error(ex, $"Failed to initialize database context {typeof(T).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 +886,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 +940,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 +997,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) { 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 file="Startup.cs" company="slskd Team"> -// 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/. -// </copyright> - -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; - - /// <summary> - /// ASP.NET Startup. - /// </summary> - public class Startup - { - /// <summary> - /// Initializes a new instance of the <see cref="Startup"/> class. - /// </summary> - /// <param name="configuration">The application configuration root.</param> - 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; } - - /// <summary> - /// Configure services. - /// </summary> - /// <param name="services">The service collection.</param> - public void ConfigureServices(IServiceCollection services) - { - var logger = Log.ForContext<Startup>(); - - // 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<Options>() - .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<State>(); - - 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<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(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<SearchDbContext>(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<ISoulseekClient, SoulseekClient>(_ => - 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<IApplication, Application>(); - services.AddHostedService(p => p.GetRequiredService<IApplication>()); - - services.AddSingleton<ITransferTracker, TransferTracker>(); - services.AddSingleton<IBrowseTracker, BrowseTracker>(); - services.AddSingleton<IConversationTracker, ConversationTracker>(); - services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); - - services.AddSingleton<ISharedFileCache, SharedFileCache>(); - - services.AddSingleton<ISearchService, SearchService>(); - services.AddSingleton<IUserService, UserService>(); - services.AddSingleton<IRoomService, RoomService>(); - services.AddSingleton<ITransferService, TransferService>(); - - services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); - services.AddSingleton<IFTPService, FTPService>(); - - services.AddSingleton<IPushbulletService, PushbulletService>(); - } - - /// <summary> - /// Configure middleware. - /// </summary> - /// <param name="app">The application builder.</param> - /// <param name="apiVersionDescriptionProvider">The api version description provider.</param> - public void Configure( - IApplicationBuilder app, - IApiVersionDescriptionProvider apiVersionDescriptionProvider) - { - var logger = Log.ForContext<Startup>(); - - // 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<IExceptionHandlerPathFeature>().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<ApplicationHub>("/hub/application"); - endpoints.MapHub<LogsHub>("/hub/logs"); - endpoints.MapHub<SearchHub>("/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<Startup>(); - - IDbContextFactory<T> GetFactory<T>() - where T : DbContext - => app.ApplicationServices.GetRequiredService<IDbContextFactory<T>>(); - - logger.Debug("Initializing database contexts"); - - try - { - using var search = GetFactory<SearchDbContext>().CreateDbContext(); - } - catch (Exception ex) - { - logger.Error(ex, "Failed to initialize one or more application databases"); - throw; - } - } - } -}
\ No newline at end of file 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 file="UploadService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Transfers.Uploads { /// <summary> /// 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()); |
