aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-02-02 22:06:47 -0600
committerGitHub <noreply@github.com>2021-02-02 22:06:47 -0600
commit761e6083819e292427ea2d4c6f37fa3c011be4ce (patch)
treeffd1a4e7000cf618133b7c3d93da2ef3a4bc5d44 /src
parentb35efd3792064e49b34823fb6b1bf4e3f7cd86a1 (diff)
parentd3011c281c118a20b41b9ab30367e3fc6d1fca5b (diff)
downloadslskd-761e6083819e292427ea2d4c6f37fa3c011be4ce.tar.gz
Merge pull request #30 from slskd/validate-config
Validate configuration
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Configuration/CommandLineArguments.cs2
-rw-r--r--src/slskd/Common/Configuration/CommandLineConfigurationSource.cs2
-rw-r--r--src/slskd/Common/Configuration/ConfigurationExtensions.cs14
-rw-r--r--src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs2
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs2
-rw-r--r--src/slskd/Common/Configuration/Options.cs (renamed from src/slskd/Options.cs)330
-rw-r--r--src/slskd/Common/Configuration/YamlConfigurationSource.cs2
-rw-r--r--src/slskd/Common/Validation/CompositeValidationResult.cs36
-rw-r--r--src/slskd/Common/Validation/ValidateAttribute.cs26
-rw-r--r--src/slskd/Common/Validation/ValidationExtensions.cs57
-rw-r--r--src/slskd/Controllers/SessionController.cs12
-rw-r--r--src/slskd/Controllers/TransfersController.cs9
-rw-r--r--src/slskd/Extensions.cs6
-rw-r--r--src/slskd/Program.cs78
-rw-r--r--src/slskd/Startup.cs7
-rw-r--r--src/slskd/slskd.yml6
16 files changed, 383 insertions, 208 deletions
diff --git a/src/slskd/Common/Configuration/CommandLineArguments.cs b/src/slskd/Common/Configuration/CommandLineArguments.cs
index 133fd334..491965e7 100644
--- a/src/slskd/Common/Configuration/CommandLineArguments.cs
+++ b/src/slskd/Common/Configuration/CommandLineArguments.cs
@@ -1,4 +1,4 @@
-namespace slskd
+namespace slskd.Configuration
{
using System;
using System.Collections;
diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
index c65e316b..fb479fd4 100644
--- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
@@ -1,4 +1,4 @@
-namespace slskd
+namespace slskd.Configuration
{
using Microsoft.Extensions.Configuration;
using System;
diff --git a/src/slskd/Common/Configuration/ConfigurationExtensions.cs b/src/slskd/Common/Configuration/ConfigurationExtensions.cs
new file mode 100644
index 00000000..77b59700
--- /dev/null
+++ b/src/slskd/Common/Configuration/ConfigurationExtensions.cs
@@ -0,0 +1,14 @@
+namespace slskd.Configuration
+{
+ public static class ConfigurationExtensions
+ {
+ public static CommandLineArgument ToCommandLineArgument(this Option option)
+ => new(option.ShortName, option.LongName, option.Type, option.Key, option.Description);
+
+ public static EnvironmentVariable ToEnvironmentVariable(this Option option)
+ => new(option.EnvironmentVariable, option.Type, option.Key, option.Description);
+
+ public static DefaultValue ToDefaultValue(this Option option)
+ => new(option.Key, option.Type, option.Default);
+ }
+}
diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
index 57fa2712..accc76c9 100644
--- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
@@ -1,4 +1,4 @@
-namespace slskd
+namespace slskd.Configuration
{
using Microsoft.Extensions.Configuration;
using System;
diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
index 2ace942b..a18faebc 100644
--- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
@@ -1,4 +1,4 @@
-namespace slskd
+namespace slskd.Configuration
{
using Microsoft.Extensions.Configuration;
using System;
diff --git a/src/slskd/Options.cs b/src/slskd/Common/Configuration/Options.cs
index a966f3dc..f10bd5a3 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Common/Configuration/Options.cs
@@ -1,24 +1,136 @@
-namespace slskd
+namespace slskd.Configuration
{
+ using slskd.Validation;
using Soulseek.Diagnostics;
using System;
using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
- public record Option(char ShortName, string LongName, string EnvironmentVariable, string Key, Type Type, object Default = null, string Description = null)
+ public record Option(char ShortName, string LongName, string EnvironmentVariable, string Key, Type Type, object Default = null, string Description = null);
+
+ public class Options
{
- public CommandLineArgument ToCommandLineArgument()
- => new (ShortName, LongName, Type, Key, Description);
+ public static Options Defaults { get; } = new Options();
- public EnvironmentVariable ToEnvironmentVariable()
- => new (EnvironmentVariable, Type, Key, Description);
+ public bool Debug { get; private set; } = Debugger.IsAttached;
+ public bool NoLogo { get; private set; } = false;
+ public string InstanceName { get; private set; } = "default";
+ [Validate]
+ public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
+ [Validate]
+ public WebOptions Web { get; private set; } = new WebOptions();
+ [Validate]
+ public LoggerOptions Logger { get; private set; } = new LoggerOptions();
+ [Validate]
+ public FeatureOptions Feature { get; private set; } = new FeatureOptions();
+ [Validate]
+ public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions();
- public DefaultValue ToDefaultValue()
- => new (Key, Type, Default);
- }
+ public class DirectoriesOptions
+ {
+ [Required]
+ public string Shared { get; private set; }
+ [Required]
+ public string Downloads { get; private set; }
+ }
+
+ public class FeatureOptions
+ {
+ public bool Prometheus { get; private set; } = false;
+ public bool Swagger { get; private set; } = false;
+ }
+
+ public class LoggerOptions
+ {
+ public string Loki { get; private set; } = null;
+ }
+
+ public class SoulseekOptions
+ {
+ [Required]
+ public string Password { get; private set; }
+ [Required]
+ public string Username { get; private set; }
+ [Range(1024, 65535)]
+ public int? ListenPort { get; private set; } = 50000;
+ public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info;
+ [Validate]
+ public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions();
+ [Validate]
+ public ConnectionOptions Connection { get; private set; } = new ConnectionOptions();
+
+ public class ConnectionOptions
+ {
+ [Validate]
+ public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions();
+ [Validate]
+ public BufferOptions Buffer { get; private set; } = new BufferOptions();
+
+ public class BufferOptions
+ {
+ [Range(1024, int.MaxValue)]
+ public int Read { get; private set; } = 16384;
+ [Range(1024, int.MaxValue)]
+ public int Write { get; private set; } = 16384;
+ }
+
+ public class TimeoutOptions
+ {
+ [Range(1000, int.MaxValue)]
+ public int Connect { get; private set; } = 5000;
+ [Range(1000, int.MaxValue)]
+ public int Inactivity { get; private set; } = 15000;
+ }
+ }
+
+ public class DistributedNetworkOptions
+ {
+ public bool Disabled { get; private set; } = false;
+ [Range(1, int.MaxValue)]
+ public int ChildLimit { get; private set; } = 25;
+ }
+ }
+
+ public class WebOptions
+ {
+ [Range(1, 65535)]
+ public int Port { get; private set; } = 5000;
+ [Validate]
+ public HttpsOptions Https { get; private set; } = new HttpsOptions();
+ public string UrlBase { get; private set; } = "/";
+ [Required(ErrorMessage = "A content root is required")]
+ public string ContentPath { get; private set; } = "wwwroot";
+ [Validate]
+ public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions();
+
+ public class AuthenticationOptions
+ {
+ public bool Disable { get; private set; } = false;
+ [Required]
+ public string Username { get; private set; } = "slskd";
+ [Required]
+ public string Password { get; private set; } = "slskd";
+ [Validate]
+ public JwtOptions Jwt { get; private set; } = new JwtOptions();
+
+ public class JwtOptions
+ {
+ [Required]
+ public string Key { get; private set; } = Guid.NewGuid().ToString();
+ [Range(3600, int.MaxValue)]
+ public int Ttl { get; private set; } = 604800000;
+ }
+ }
+
+ public class HttpsOptions
+ {
+ [Range(1, 65535)]
+ public int Port { get; private set; } = 5001;
+ public bool Force { get; private set; } = false;
+ }
+ }
- public class Options
- {
public static IEnumerable<Option> Map => new Option[]
{
new(
@@ -51,7 +163,7 @@
EnvironmentVariable: "DEBUG",
Key: "slskd:debug",
Type: typeof(bool),
- Default: Debugger.IsAttached,
+ Default: Defaults.Debug,
Description: "run in debug mode"),
new(
ShortName: 'n',
@@ -59,7 +171,7 @@
EnvironmentVariable: "NO_LOGO",
Key: "slskd:nologo",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.NoLogo,
Description: "suppress logo on startup"),
new(
ShortName: 'i',
@@ -67,7 +179,7 @@
EnvironmentVariable: "INSTANCE_NAME",
Key: "slskd:instancename",
Type: typeof(string),
- Default: "default",
+ Default: Defaults.InstanceName,
Description: "optional; a unique name for this instance"),
new(
ShortName: 'o',
@@ -75,7 +187,7 @@
EnvironmentVariable: "DOWNLOADS_DIR",
Key: "slskd:directories:downloads",
Type: typeof(string),
- Default: null,
+ Default: Defaults.Directories.Downloads,
Description: "the path where downloaded files are saved"),
new(
ShortName: 's',
@@ -83,7 +195,7 @@
EnvironmentVariable: "SHARED_DIR",
Key: "slskd:directories:shared",
Type: typeof(string),
- Default: null,
+ Default: Defaults.Directories.Shared,
Description: "the path to shared files"),
new(
ShortName: 'l',
@@ -91,7 +203,7 @@
EnvironmentVariable: "HTTP_PORT",
Key: "slskd:web:port",
Type: typeof(int),
- Default: 5000,
+ Default: Defaults.Web.Port,
Description: "HTTP listen port for web server"),
new(
ShortName: 'L',
@@ -99,7 +211,7 @@
EnvironmentVariable: "HTTPS_PORT",
Key: "slskd:web:https:port",
Type: typeof(int),
- Default: 5001,
+ Default: Defaults.Web.Https.Port,
Description: "HTTPS listen port for web server"),
new(
ShortName: 'f',
@@ -107,7 +219,7 @@
EnvironmentVariable: "HTTPS_FORCE",
Key: "slskd:web:https:force",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.Web.Https.Force,
Description: "redirect HTTP to HTTPS"),
new(
ShortName: default,
@@ -115,7 +227,7 @@
EnvironmentVariable: "URL_BASE",
Key: "slskd:web:urlbase",
Type: typeof(string),
- Default: "/",
+ Default: Defaults.Web.UrlBase,
Description: "base url for web requests"),
new(
ShortName: default,
@@ -123,7 +235,7 @@
EnvironmentVariable: "CONTENT_PATH",
Key: "slskd:web:contentpath",
Type: typeof(string),
- Default: "wwwroot",
+ Default: Defaults.Web.ContentPath,
Description: "path to static web content"),
new(
ShortName: 'x',
@@ -131,7 +243,7 @@
EnvironmentVariable: "NO_AUTH",
Key: "slskd:web:authentication:disable",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.Web.Authentication.Disable,
Description: "disable authentication for web requests"),
new(
ShortName: 'u',
@@ -139,7 +251,7 @@
EnvironmentVariable: "USERNAME",
Key: "slskd:web:authentication:username",
Type: typeof(string),
- Default: "slskd",
+ Default: Defaults.Web.Authentication.Username,
Description: "the username for the web UI"),
new(
ShortName: 'p',
@@ -147,23 +259,23 @@
EnvironmentVariable: "PASSWORD",
Key: "slskd:web:authentication:password",
Type: typeof(string),
- Default: "slskd",
+ Default: Defaults.Web.Authentication.Password,
Description: "the password for web UI"),
new(
ShortName: default,
LongName: "jwt-key",
EnvironmentVariable: "JWT_KEY",
- Key: "slskd:web:jwt:key",
+ Key: "slskd:web:authentication:jwt:key",
Type: typeof(string),
- Default: Guid.NewGuid(),
+ Default: Defaults.Web.Authentication.Jwt.Key,
Description: "the key with which to sign JWTs"),
new(
ShortName: default,
LongName: "jwt-ttl",
EnvironmentVariable: "JWT_TTL",
- Key: "slskd:web:jwt:ttl",
+ Key: "slskd:web:authentication:jwt:ttl",
Type: typeof(int),
- Default: 604800000,
+ Default: Defaults.Web.Authentication.Jwt.Ttl,
Description: "the TTL for JWTs"),
new(
ShortName: default,
@@ -171,7 +283,7 @@
EnvironmentVariable: "PROMETHEUS",
Key: "slskd:feature:prometheus",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.Feature.Prometheus,
Description: "enable collection and publishing of prometheus metrics"),
new(
ShortName: default,
@@ -179,7 +291,7 @@
EnvironmentVariable: "SWAGGER",
Key: "slskd:feature:swagger",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.Feature.Swagger,
Description: "enable swagger documentation and UI"),
new(
ShortName: default,
@@ -187,174 +299,88 @@
EnvironmentVariable: "LOKI",
Key: "slskd:logger:loki",
Type: typeof(string),
+ Default: Defaults.Logger.Loki,
Description: "optional; the url to a Grafana Loki instance to which to log"),
new(
ShortName: default,
- LongName: "soulseek-username",
- EnvironmentVariable: "SOULSEEK_USERNAME",
+ LongName: "slsk-username",
+ EnvironmentVariable: "SLSK_USERNAME",
Key: "slskd:soulseek:username",
Type: typeof(string),
+ Default: Defaults.Soulseek.Username,
Description: "the username for the Soulseek network"),
new(
ShortName: default,
- LongName: "soulseek-password",
- EnvironmentVariable: "SOULSEEK_PASSWORD",
+ LongName: "slsk-password",
+ EnvironmentVariable: "SLSK_PASSWORD",
Key: "slskd:soulseek:password",
Type: typeof(string),
+ Default: Defaults.Soulseek.Password,
Description: "the password for the Soulseek network"),
new(
ShortName: default,
- LongName: "soulseek-listen-port",
- EnvironmentVariable: "SOULSEEK_LISTEN_PORT",
+ LongName: "slsk-listen-port",
+ EnvironmentVariable: "SLSK_LISTEN_PORT",
Key: "slskd:soulseek:listenport",
Type: typeof(int),
- Default: 50000,
+ Default: Defaults.Soulseek.ListenPort,
Description: "the port on which to listen for incoming connections"),
new(
ShortName: default,
- LongName: "soulseek-diagnostic-level",
- EnvironmentVariable: "SOULSEEK_DIAGNOSTIC_LEVEL",
+ LongName: "slsk-diag-level",
+ EnvironmentVariable: "SLSK_DIAG_LEVEL",
Key: "slskd:soulseek:diagnosticlevel",
Type: typeof(DiagnosticLevel),
- Default: DiagnosticLevel.Info,
+ Default: Defaults.Soulseek.DiagnosticLevel,
Description: "the minimum diagnostic level (None, Warning, Info, Debug)"),
new(
ShortName: default,
- LongName: "soulseek-no-dnet",
- EnvironmentVariable: "SOULSEEK_NO_DNET",
+ LongName: "slsk-no-dnet",
+ EnvironmentVariable: "SLSK_NO_DNET",
Key: "slskd:soulseek:distributednetwork:disabled",
Type: typeof(bool),
- Default: false,
+ Default: Defaults.Soulseek.DistributedNetwork.Disabled,
Description: "disables the distributed network"),
new(
ShortName: default,
- LongName: "soulseek-dnet-children",
- EnvironmentVariable: "SOULSEEK_DNET_CHILDREN",
+ LongName: "slsk-dnet-children",
+ EnvironmentVariable: "SLSK_DNET_CHILDREN",
Key: "slskd:soulseek:distributednetwork:childlimit",
Type: typeof(int),
- Default: 25,
- Description: "sets the limit for the number of distributed children"),
+ Default: Defaults.Soulseek.DistributedNetwork.ChildLimit,
+ Description: "the limit for the number of distributed children"),
new(
ShortName: default,
- LongName: "soulseek-connection-timeout",
- EnvironmentVariable: "SOULSEEK_CONNECTION_TIMEOUT",
+ LongName: "slsk-connection-timeout",
+ EnvironmentVariable: "SLSK_CONNECTION_TIMEOUT",
Key: "slskd:soulseek:connection:timeout:connect",
Type: typeof(int),
- Default: 5000,
- Description: "sets the connection timeout, in miliseconds"),
+ Default: Defaults.Soulseek.Connection.Timeout.Connect,
+ Description: "the connection timeout, in miliseconds"),
new(
ShortName: default,
- LongName: "soulseek-inactivity-timeout",
- EnvironmentVariable: "SOULSEEK_INACTIVITY_TIMEOUT",
+ LongName: "slsk-inactivity-timeout",
+ EnvironmentVariable: "SLSK_INACTIVITY_TIMEOUT",
Key: "slskd:soulseek:connection:timeout:inactivity",
Type: typeof(int),
- Default: 15000,
- Description: "sets the connection inactivity timeout, in miliseconds"),
+ Default: Defaults.Soulseek.Connection.Timeout.Inactivity,
+ Description: "the connection inactivity timeout, in miliseconds"),
new(
ShortName: default,
- LongName: "soulseek-read-buffer",
- EnvironmentVariable: "SOULSEEK_READ_BUFFER",
+ LongName: "slsk-read-buffer",
+ EnvironmentVariable: "SLSK_READ_BUFFER",
Key: "slskd:soulseek:connection:buffer:read",
Type: typeof(int),
- Default: 16384,
- Description: "sets the read buffer size for connections"),
+ Default: Defaults.Soulseek.Connection.Buffer.Read,
+ Description: "the read buffer size for connections"),
new(
ShortName: default,
- LongName: "soulseek-write-buffer",
- EnvironmentVariable: "SOULSEEK_WRITE_BUFFER",
+ LongName: "slsk-write-buffer",
+ EnvironmentVariable: "SLSK_WRITE_BUFFER",
Key: "slskd:soulseek:connection:buffer:write",
Type: typeof(int),
- Default: 16384,
- Description: "sets the write buffer size for connections"),
+ Default: Defaults.Soulseek.Connection.Buffer.Write,
+ Description: "the write buffer size for connections"),
};
-
- public bool Debug { get; private set; } = Debugger.IsAttached;
- public bool NoLogo { get; private set; } = false;
- public string InstanceName { get; private set; } = "default";
- public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
- public WebOptions Web { get; private set; } = new WebOptions();
- public LoggerOptions Logger { get; private set; } = new LoggerOptions();
- public FeatureOptions Feature { get; private set; } = new FeatureOptions();
- public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions();
-
- public class DirectoriesOptions
- {
- public string Shared { get; private set; }
- public string Downloads { get; private set; }
- }
-
- public class FeatureOptions
- {
- public bool Prometheus { get; private set; } = false;
- public bool Swagger { get; private set; } = false;
- }
-
- public class LoggerOptions
- {
- public string Loki { get; private set; } = null;
- }
-
- public class SoulseekOptions
- {
- public string Password { get; private set; }
- public string Username { get; private set; }
- public int? ListenPort { get; private set; } = 50000;
- public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info;
- public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions();
- public ConnectionOptions Connection { get; private set; } = new ConnectionOptions();
-
- public class ConnectionOptions
- {
- public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions();
- public BufferOptions Buffer { get; private set; } = new BufferOptions();
-
- public class BufferOptions
- {
- public int Read { get; private set; } = 16384;
- public int Write { get; private set; } = 16384;
- }
-
- public class TimeoutOptions
- {
- public int Connect { get; private set; } = 5000;
- public int Inactivity { get; private set; } = 15000;
- }
- }
-
- public class DistributedNetworkOptions
- {
- public bool Disabled { get; private set; } = false;
- public int ChildLimit { get; private set; } = 25;
- }
- }
-
- public class WebOptions
- {
- public int Port { get; private set; } = 5000;
- public HttpsOptions Https { get; private set; } = new HttpsOptions();
- public string UrlBase { get; private set; } = "/";
- public string ContentPath { get; private set; } = "wwwroot";
- public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions();
- public JwtOptions Jwt { get; private set; } = new JwtOptions();
-
- public class AuthenticationOptions
- {
- public bool Disable { get; private set; } = false;
- public string Username { get; private set; } = "slskd";
- public string Password { get; private set; } = "slskd";
- }
-
- public class JwtOptions
- {
- public string Key { get; private set; } = Guid.NewGuid().ToString();
- public int Ttl { get; private set; } = 604800000;
- }
-
- public class HttpsOptions
- {
- public int Port { get; private set; } = 5001;
- public bool Force { get; private set; } = false;
- }
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
index 0ee5aa8a..27ca6fea 100644
--- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
@@ -1,4 +1,4 @@
-namespace slskd
+namespace slskd.Configuration
{
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
diff --git a/src/slskd/Common/Validation/CompositeValidationResult.cs b/src/slskd/Common/Validation/CompositeValidationResult.cs
new file mode 100644
index 00000000..f8cd8bc7
--- /dev/null
+++ b/src/slskd/Common/Validation/CompositeValidationResult.cs
@@ -0,0 +1,36 @@
+namespace slskd.Validation
+{
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+
+ public class CompositeValidationResult : ValidationResult
+ {
+ public CompositeValidationResult(string errorMessage)
+ : base(errorMessage)
+ {
+ }
+
+ public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames)
+ : base(errorMessage, memberNames)
+ {
+ }
+
+ public CompositeValidationResult(string errorMessage, IEnumerable<ValidationResult> validationResults)
+ : base(errorMessage)
+ {
+ ResultsList = (List<ValidationResult>)validationResults;
+ }
+
+ protected CompositeValidationResult(ValidationResult validationResult)
+ : base(validationResult)
+ {
+ }
+
+ public IEnumerable<ValidationResult> Results => ResultsList.AsReadOnly();
+
+ private List<ValidationResult> ResultsList { get; set; } = new List<ValidationResult>();
+
+ public void AddResult(ValidationResult validationResult)
+ => ResultsList.Add(validationResult);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs
new file mode 100644
index 00000000..b9daab28
--- /dev/null
+++ b/src/slskd/Common/Validation/ValidateAttribute.cs
@@ -0,0 +1,26 @@
+namespace slskd.Validation
+{
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+
+ public class ValidateAttribute : ValidationAttribute
+ {
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+ var context = new ValidationContext(value, null, null);
+
+ Validator.TryValidateObject(value, context, results, true);
+
+ if (results.Count != 0)
+ {
+ var compositeResults = new CompositeValidationResult(validationContext.DisplayName);
+ results.ForEach(compositeResults.AddResult);
+
+ return compositeResults;
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/ValidationExtensions.cs b/src/slskd/Common/Validation/ValidationExtensions.cs
new file mode 100644
index 00000000..f0186e76
--- /dev/null
+++ b/src/slskd/Common/Validation/ValidationExtensions.cs
@@ -0,0 +1,57 @@
+namespace slskd.Validation
+{
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+ using System.Linq;
+ using slskd.Configuration;
+
+ public static class ValidationExtensions
+ {
+ public static string GetResultView(this ValidationResult result, string message)
+ {
+ var view = result.GetResultView(0).ToList();
+
+ if (view.Count() > 0 && !string.IsNullOrEmpty(message))
+ {
+ view[0] = message;
+ }
+
+ return string.Join("\n", view);
+ }
+
+ private static IEnumerable<string> GetResultView(this ValidationResult result, int depth = 0)
+ {
+ var indent = new string(' ', depth * 2);
+
+ if (result is CompositeValidationResult composite)
+ {
+ var lines = new[] { indent + result + ":" }.ToList();
+
+ foreach (var child in composite.Results)
+ {
+ lines.AddRange(child.GetResultView(depth + 1));
+ }
+
+ return lines;
+ }
+ else
+ {
+ return new[] { indent + result };
+ }
+ }
+
+ public static bool TryValidate(this Options options, out CompositeValidationResult result)
+ {
+ result = null;
+ var results = new List<ValidationResult>();
+
+ if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true))
+ {
+ result = new CompositeValidationResult("Invalid configuration", results);
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs
index 235e65cf..7f6a78b2 100644
--- a/src/slskd/Controllers/SessionController.cs
+++ b/src/slskd/Controllers/SessionController.cs
@@ -1,4 +1,6 @@
-namespace slskd.Controllers
+using Microsoft.Extensions.Options;
+
+namespace slskd.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -8,9 +10,9 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using slskd.DTO;
- using Microsoft.Extensions.Options;
using slskd;
using System.Text.Json;
+ using slskd.Configuration;
/// <summary>
/// Session
@@ -22,11 +24,11 @@
[Consumes("application/json")]
public class SessionController : ControllerBase
{
- private slskd.Options Options { get; set; }
+ private Options Options { get; set; }
private SymmetricSecurityKey JwtSigningKey { get; set; }
public SessionController(
- IOptionsSnapshot<slskd.Options> optionsSnapshot,
+ IOptionsSnapshot<Options> optionsSnapshot,
SymmetricSecurityKey jwtSigningKey)
{
Options = optionsSnapshot.Value;
@@ -106,7 +108,7 @@
private JwtSecurityToken GetJwtSecurityToken(string username, Role role)
{
var issuedUtc = DateTime.UtcNow;
- var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Jwt.Ttl);
+ var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Authentication.Jwt.Ttl);
var claims = new List<Claim>()
{
diff --git a/src/slskd/Controllers/TransfersController.cs b/src/slskd/Controllers/TransfersController.cs
index 505e84e5..d19ec91d 100644
--- a/src/slskd/Controllers/TransfersController.cs
+++ b/src/slskd/Controllers/TransfersController.cs
@@ -1,8 +1,9 @@
-namespace slskd.Controllers
+using Microsoft.Extensions.Options;
+
+namespace slskd.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
using Soulseek;
using System;
using System.ComponentModel.DataAnnotations;
@@ -12,7 +13,7 @@
using System.Threading.Tasks;
using slskd.DTO;
using slskd.Trackers;
- using Microsoft.Extensions.Options;
+ using slskd.Configuration;
/// <summary>
/// Transfers
@@ -30,7 +31,7 @@
/// <param name="options"></param>
/// <param name="client"></param>
/// <param name="tracker"></param>
- public TransfersController(IOptionsSnapshot<slskd.Options> options, ISoulseekClient client, ITransferTracker tracker)
+ public TransfersController(IOptionsSnapshot<Options> options, ISoulseekClient client, ITransferTracker tracker)
{
OutputDirectory = options.Value.Directories.Downloads;
Client = client;
diff --git a/src/slskd/Extensions.cs b/src/slskd/Extensions.cs
index e4d8a582..44b0f721 100644
--- a/src/slskd/Extensions.cs
+++ b/src/slskd/Extensions.cs
@@ -40,10 +40,8 @@
/// <returns></returns>
public static string Sha1(this string str)
{
- using (var sha1 = new SHA1Managed())
- {
- return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
- }
+ using var sha1 = new SHA1Managed();
+ return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
}
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index c894257c..da4984fe 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -7,12 +7,14 @@
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Grafana.Loki;
+ using slskd.Configuration;
+ using slskd.Validation;
using System;
+ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
- using System.Text.Json;
-
+
public static class ProgramExtensions
{
public static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile)
@@ -56,6 +58,9 @@
[CommandLineArgument('v', "version", "display version information")]
private static bool ShowVersion { get; set; }
+ private static Options Options { get; } = new Options();
+ private static IConfigurationRoot Configuration { get; set; }
+
public static void Main(string[] args)
{
CommandLineArguments.Populate();
@@ -69,34 +74,47 @@
if (ShowHelp || ShowEnvironmentVariables)
{
if (!NoLogo) PrintLogo(Version);
- if (ShowHelp) PrintCommandLineArguments();
- if (ShowEnvironmentVariables) PrintEnvironmentVariables(EnvironmentVariablePrefix);
+ if (ShowHelp) PrintCommandLineArguments(Options.Map);
+ if (ShowEnvironmentVariables) PrintEnvironmentVariables(Options.Map, EnvironmentVariablePrefix);
return;
}
- var configuration = new ConfigurationBuilder()
- .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile)
- .Build();
+ try
+ {
+ Configuration = new ConfigurationBuilder()
+ .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile)
+ .Build();
- var options = new Options();
+ Configuration.GetSection("slskd")
+ .Bind(Options, (o) => { o.BindNonPublicProperties = true; });
- configuration.GetSection("slskd").Bind(options, (o) => { o.BindNonPublicProperties = true; });
+ if (!Options.TryValidate(out var result))
+ {
+ Console.WriteLine(result.GetResultView("Invalid configuration:"));
+ return;
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Invalid configuration: {ex.Message}");
+ return;
+ }
- if (!options.NoLogo)
+ if (!Options.NoLogo)
{
PrintLogo(Version);
}
- if (options.Debug)
+ if (Options.Debug)
{
- Console.WriteLine(configuration.GetDebugView());
- Console.WriteLine(JsonSerializer.Serialize(options, new JsonSerializerOptions() { WriteIndented = true }));
+ Console.WriteLine("Configuration:");
+ Console.WriteLine(Configuration.GetDebugView());
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.WithProperty("Version", Version)
- .Enrich.WithProperty("InstanceName", options.InstanceName)
+ .Enrich.WithProperty("InstanceName", Options.InstanceName)
.Enrich.WithProperty("InvocationId", InvocationId)
.Enrich.WithProperty("ProcessId", ProcessId)
.Enrich.FromLogContext()
@@ -108,9 +126,9 @@
outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day))
.WriteTo.Conditional(
- e => !string.IsNullOrEmpty(options.Logger.Loki),
+ e => !string.IsNullOrEmpty(Options.Logger.Loki),
config => config.GrafanaLoki(
- options.Logger.Loki ?? string.Empty,
+ Options.Logger.Loki ?? string.Empty,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
.CreateLogger();
}
@@ -121,7 +139,7 @@
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information)
.Enrich.WithProperty("Version", Version)
- .Enrich.WithProperty("InstanceName", options.InstanceName)
+ .Enrich.WithProperty("InstanceName", Options.InstanceName)
.Enrich.WithProperty("InvocationId", InvocationId)
.Enrich.WithProperty("ProcessId", ProcessId)
.Enrich.FromLogContext()
@@ -133,9 +151,9 @@
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day))
.WriteTo.Conditional(
- e => !string.IsNullOrEmpty(options.Logger.Loki),
+ e => !string.IsNullOrEmpty(Options.Logger.Loki),
config => config.GrafanaLoki(
- options.Logger.Loki ?? string.Empty,
+ Options.Logger.Loki ?? string.Empty,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
.CreateLogger();
}
@@ -143,18 +161,18 @@
var logger = Log.ForContext<Program>();
logger.Information("Version: {Version}", Version);
- logger.Information("Instance Name: {InstanceName}", options.InstanceName);
+ logger.Information("Instance Name: {InstanceName}", Options.InstanceName);
logger.Information("Invocation ID: {InvocationId}", InvocationId);
logger.Information("Process ID: {ProcessId}", ProcessId);
- if (!string.IsNullOrEmpty(options.Logger.Loki))
+ if (!string.IsNullOrEmpty(Options.Logger.Loki))
{
- logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", options.Logger.Loki);
+ logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", Options.Logger.Loki);
}
try
{
- if (options.Feature.Prometheus)
+ if (Options.Feature.Prometheus)
{
using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting();
}
@@ -170,7 +188,7 @@
//.UseUrls(
// $"http://0.0.0.0:{options.Web.Port}",
// $"https://0.0.0.0:{options.Web.Https.Port}")
- .UseUrls($"http://0.0.0.0:{options.Web.Port}")
+ .UseUrls($"http://0.0.0.0:{Options.Web.Port}")
.Build()
.Run();
}
@@ -184,17 +202,17 @@
}
}
- public static void PrintCommandLineArguments()
+ public static void PrintCommandLineArguments(IEnumerable<Option> map)
{
static string GetLongName(string longName, Type type)
=> type == typeof(bool) ? longName : $"{longName} <{type.Name.ToLowerInvariant()}>";
- var longestName = Options.Map.Where(a => !string.IsNullOrEmpty(a.LongName)).Select(a => GetLongName(a.LongName, a.Type)).Max(n => n.Length);
+ var longestName = map.Where(a => !string.IsNullOrEmpty(a.LongName)).Select(a => GetLongName(a.LongName, a.Type)).Max(n => n.Length);
Console.WriteLine("\nusage: slskd [arguments]\n");
Console.WriteLine("arguments:\n");
- foreach (Option item in Options.Map)
+ foreach (Option item in map)
{
var (shortName, longName, _, key, type, defaultValue, description) = item;
@@ -209,15 +227,15 @@
}
}
- public static void PrintEnvironmentVariables(string prefix)
+ public static void PrintEnvironmentVariables(IEnumerable<Option> map, string prefix)
{
static string GetName(string name, Type type) => $"{name} <{type.Name.ToLowerInvariant()}>";
- var longestName = Options.Map.Select(a => GetName(a.EnvironmentVariable, a.Type)).Max(n => n.Length);
+ var longestName = map.Select(a => GetName(a.EnvironmentVariable, a.Type)).Max(n => n.Length);
Console.WriteLine("\nenvironment variables (arguments and config.yml have precedence):\n");
- foreach (Option item in Options.Map)
+ foreach (Option item in map)
{
var (_, _, environmentVariable, key, type, defaultValue, description) = item;
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index d914e3e0..f093fa67 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -11,7 +11,6 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
@@ -30,7 +29,7 @@
using Microsoft.Extensions.FileProviders;
using Serilog.Events;
using slskd.Entities;
- using Microsoft.Extensions.Options;
+ using slskd.Configuration;
public class Startup
{
@@ -61,7 +60,7 @@
ContentPath = Path.GetFullPath(Options.Web.ContentPath);
- JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Jwt.Key));
+ JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Authentication.Jwt.Key));
}
private IConfiguration Configuration { get; }
@@ -158,12 +157,10 @@
public void Configure(
IApplicationBuilder app,
- IWebHostEnvironment env,
IApiVersionDescriptionProvider provider,
ITransferTracker tracker,
IBrowseTracker browseTracker,
IConversationTracker conversationTracker,
- IOptionsMonitor<Options> optionsMonitor,
IRoomTracker roomTracker)
{
var logger = Log.ForContext<Startup>();
diff --git a/src/slskd/slskd.yml b/src/slskd/slskd.yml
index e1808ffd..4bf36e56 100644
--- a/src/slskd/slskd.yml
+++ b/src/slskd/slskd.yml
@@ -13,9 +13,9 @@
# disable: false
# username: slskd
# password: slskd
-# jwt:
-# key: ~
-# ttl: 604800000
+# jwt:
+# key: ~
+# ttl: 604800000
# directories:
# shared: ~
# downloads: ~