aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-05-20 08:30:41 -0500
committerGitHub <noreply@github.com>2021-05-20 08:30:41 -0500
commit510de3d91a58b60b59447a785b6b6a1b3ccc5bd7 (patch)
tree85b61c947b859f01706720bb42901aae65cca956 /src
parentf143466c2fec5c04b7c0b73499aa2d750d7e6ce3 (diff)
parent73a54cb7d47ba76274aac8908126cccb9fa3cb6b (diff)
downloadslskd-510de3d91a58b60b59447a785b6b6a1b3ccc5bd7.tar.gz
Merge pull request #76 from slskd/paths
Verify filesystem at startup
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Validation/X509CertificateAttribute.cs44
-rw-r--r--src/slskd/Options.cs1
-rw-r--r--src/slskd/Program.cs166
3 files changed, 123 insertions, 88 deletions
diff --git a/src/slskd/Common/Validation/X509CertificateAttribute.cs b/src/slskd/Common/Validation/X509CertificateAttribute.cs
new file mode 100644
index 00000000..1f0849f9
--- /dev/null
+++ b/src/slskd/Common/Validation/X509CertificateAttribute.cs
@@ -0,0 +1,44 @@
+// <copyright file="X509CertificateAttribute.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.Validation
+{
+ using System.ComponentModel.DataAnnotations;
+ using slskd.Common.Cryptography;
+ using static slskd.Options.WebOptions.HttpsOptions;
+
+ /// <summary>
+ /// Validates X509 certificate parameters specified through <see cref="CertificateOptions"/>.
+ /// </summary>
+ public class X509CertificateAttribute : ValidationAttribute
+ {
+ protected override ValidationResult IsValid(object value, ValidationContext validationContext)
+ {
+ if (value != null)
+ {
+ var cert = (CertificateOptions)value;
+
+ if (!string.IsNullOrEmpty(cert.Pfx) && !X509.TryValidate(cert.Pfx, cert.Password, out var certResult))
+ {
+ return new ValidationResult($"Invalid HTTPs certificate: {certResult}");
+ }
+ }
+
+ return ValidationResult.Success;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index efd689d5..bef9b962 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -521,6 +521,7 @@ namespace slskd
/// <summary>
/// Certificate options.
/// </summary>
+ [X509Certificate]
public class CertificateOptions
{
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index f7d3fd66..85a56e0f 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -55,7 +55,7 @@ namespace slskd
/// <summary>
/// The default application data directory.
/// </summary>
- public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
+ public static readonly string DefaultAppDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify), AppName);
/// <summary>
/// The default configuration filename.
@@ -183,7 +183,7 @@ namespace slskd
return;
}
- // the application isn't bein run in command mode. load all configuration values and proceed
+ // the application isn't being run in command mode. load all configuration values and proceed
// with bootstrapping.
try
{
@@ -199,14 +199,6 @@ namespace slskd
Console.WriteLine(result.GetResultView("Invalid configuration:"));
return;
}
-
- var cert = Options.Web.Https.Certificate;
-
- if (!string.IsNullOrEmpty(cert.Pfx) && !X509.TryValidate(cert.Pfx, cert.Password, out var certResult))
- {
- Console.WriteLine($"Invalid HTTPs certificate: {certResult}");
- return;
- }
}
catch (Exception ex)
{
@@ -214,98 +206,53 @@ namespace slskd
return;
}
- // ensure the application directory exists and is writeable. the most comprehensive way to test this is to try
- // to write a file to it.
- try
- {
- if (!Directory.Exists(Options.Directories.App))
- {
- Directory.CreateDirectory(Options.Directories.App);
- }
- }
- catch (Exception ex)
+ if (Options.Debug)
{
- Console.WriteLine($"App directory {Options.Directories.App} does not exist, and could not be created: {ex.Message}");
+ Console.WriteLine($"Configuration:\n{Configuration.GetDebugView()}");
}
try
{
- if (!Directory.Exists(Options.Directories.App))
- {
- Directory.CreateDirectory(Options.Directories.App);
- }
-
- var probe = Path.Combine(Options.Directories.App, "probe");
- File.WriteAllText(Path.Combine(Options.Directories.App, "probe"), string.Empty);
- File.Delete(probe);
+ VerifyOrCreateDirectory(Options.Directories.App);
+ VerifyOrCreateDirectory(Options.Directories.Incomplete);
+ VerifyOrCreateDirectory(Options.Directories.Downloads);
+ VerifyOrCreateDirectory(Options.Directories.Shared, verifyWriteable: false);
}
catch (Exception ex)
{
- Console.WriteLine($"App directory {Options.Directories.App} is not writeable: {ex.Message}");
+ Console.WriteLine($"Filesystem exception: {ex.Message}");
return;
}
+ Log.Logger = (Options.Debug ? new LoggerConfiguration().MinimumLevel.Debug() : new LoggerConfiguration().MinimumLevel.Information())
+ .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
+ .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information)
+ .Enrich.WithProperty("Version", Version)
+ .Enrich.WithProperty("InstanceName", Options.InstanceName)
+ .Enrich.WithProperty("InvocationId", InvocationId)
+ .Enrich.WithProperty("ProcessId", ProcessId)
+ .Enrich.FromLogContext()
+ .WriteTo.Console(
+ outputTemplate: (Options.Debug ? "[{SourceContext}] [{SoulseekContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
+ .WriteTo.Async(config =>
+ config.File(
+ Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"),
+ outputTemplate: (Options.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ rollingInterval: RollingInterval.Day))
+ .WriteTo.Conditional(
+ e => !string.IsNullOrEmpty(Options.Logger.Loki),
+ config => config.GrafanaLoki(
+ Options.Logger.Loki ?? string.Empty,
+ outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
+ .CreateLogger();
+
+ var logger = Log.ForContext(typeof(Program));
+
if (!Options.NoLogo)
{
PrintLogo(Version);
}
- if (Options.Debug)
- {
- Console.WriteLine("Configuration:");
- Console.WriteLine(Configuration.GetDebugView());
-
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Debug()
- .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
- .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information)
- .Enrich.WithProperty("Version", Version)
- .Enrich.WithProperty("InstanceName", Options.InstanceName)
- .Enrich.WithProperty("InvocationId", InvocationId)
- .Enrich.WithProperty("ProcessId", ProcessId)
- .Enrich.FromLogContext()
- .WriteTo.Console(
- outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
- .WriteTo.Async(config =>
- config.File(
- Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"),
- outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
- rollingInterval: RollingInterval.Day))
- .WriteTo.Conditional(
- e => !string.IsNullOrEmpty(Options.Logger.Loki),
- config => config.GrafanaLoki(
- Options.Logger.Loki ?? string.Empty,
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
- .CreateLogger();
- }
- else
- {
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
- .MinimumLevel.Override("slskd.API.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Information)
- .Enrich.WithProperty("Version", Version)
- .Enrich.WithProperty("InstanceName", Options.InstanceName)
- .Enrich.WithProperty("InvocationId", InvocationId)
- .Enrich.WithProperty("ProcessId", ProcessId)
- .Enrich.FromLogContext()
- .WriteTo.Console(
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
- .WriteTo.Async(config =>
- config.File(
- Path.Combine(AppContext.BaseDirectory, "logs", $"{AppName}-.log"),
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
- rollingInterval: RollingInterval.Day))
- .WriteTo.Conditional(
- e => !string.IsNullOrEmpty(Options.Logger.Loki),
- config => config.GrafanaLoki(
- Options.Logger.Loki ?? string.Empty,
- outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))
- .CreateLogger();
- }
-
- var logger = Log.ForContext(typeof(Program));
-
if (ConfigurationFile != DefaultConfigurationFile && !File.Exists(ConfigurationFile))
{
logger.Warning($"Specified configuration file '{ConfigurationFile}' could not be found and was not loaded.");
@@ -508,11 +455,24 @@ namespace slskd
var centeredVersion = new string(' ', paddingLeft) + version + new string(' ', paddingRight);
- var banner = @$"
+ var logos = new[]
+ {
+ $@"
▄▄▄▄ ▄▄▄▄ ▄▄▄▄
▄▄▄▄▄▄▄ █ █ ▄▄▄▄▄▄▄ █ █▄▄▄ ▄▄▄█ █
█__ --█ █ █ █__ --█ █ ◄█ █ - █
- █▄▄▄▄▄█ █▄▄█ █▄▄▄▄▄█ █▄▄█▄▄█ █▄▄▄▄▄█
+ █▄▄▄▄▄█ █▄▄█ █▄▄▄▄▄█ █▄▄█▄▄█ █▄▄▄▄▄█",
+ @$"
+ ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+ ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+ █__ --█ █__ --█ ◄█ - █
+ █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█",
+ };
+
+ var logo = logos[new Random().Next(0, logos.Length)];
+
+ var banner = @$"
+{logo}
╒════════════════════════════════════════════════════════╕
│ GNU AFFERO GENERAL PUBLIC LICENSE │
│ https://slskd.org │
@@ -522,5 +482,35 @@ namespace slskd
Console.WriteLine(banner);
}
+
+ private static void VerifyOrCreateDirectory(string directory, bool verifyWriteable = true)
+ {
+ try
+ {
+ if (!Directory.Exists(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+ }
+ catch (Exception ex)
+ {
+ throw new IOException($"Directory {directory} does not exist, and could not be created: {ex.Message}", ex);
+ }
+
+ if (verifyWriteable)
+ {
+ try
+ {
+ var file = Guid.NewGuid().ToString();
+ var probe = Path.Combine(directory, file);
+ File.WriteAllText(probe, string.Empty);
+ File.Delete(probe);
+ }
+ catch (Exception ex)
+ {
+ throw new IOException($"Directory {directory} is not writeable: {ex.Message}", ex);
+ }
+ }
+ }
}
} \ No newline at end of file