//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ 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, version 3.
// │
// │ 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/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
using Microsoft.Extensions.Options;
namespace slskd
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using FluentFTP;
using NetTools;
using slskd.Authentication;
using slskd.Configuration;
using slskd.Events;
using slskd.Relay;
using slskd.Shares;
using slskd.Transfers;
using slskd.Validation;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
using YamlDotNet.Serialization;
using SoulseekDiagnostics = Soulseek.Diagnostics;
///
/// Disambiguates options derived at startup from options that may update at run time.
///
///
/// This class is added directly to dependency injection, but is not, so consumers must inject
/// instead of to make it clear that these options will not change. Options that may change should be accessed by injecting
/// or , depending on the lifetime of the component.
///
public class OptionsAtStartup : Options
{
}
///
/// Application options.
///
///
///
/// This class contains all application options, which may be sourced from (in order of precedence):
///
/// -
/// Defaults
/// Default values, statically defined in this class.
///
/// -
/// Environment Variables
/// Environment variables set at either the system or user scope.
///
/// -
/// YAML Configuration File
/// A YAML file containing a mapping of this class.
///
/// -
/// Command Line
/// Options provided via the command line when starting the application.
///
///
///
///
/// Only the YAML configuration source can change at runtime and consumers of this class must be aware of this, either injecting
/// in components with a singleton lifetime, or for transient or scoped lifetimes.
///
///
/// To obtain the Options specified at startup (discarding any updates that may have been applied since), inject .
///
///
/// Options specified via the command line can not be overwritten by changes to the YAML file. This is by design due to the immutable
/// nature of the command line string after the application is started.
///
///
public class Options : IValidatableObject
{
///
/// Gets a value indicating whether to display the application version.
///
[Argument('v', "version")]
[Description("display version information")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowVersion { get; init; } = false;
///
/// Gets a value indicating whether to display a list of command line arguments.
///
[Argument('h', "help")]
[Description("display command line usage")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowHelp { get; init; } = false;
///
/// Gets a value indicating whether to display a list of configuration environment variables.
///
[Argument(default, "envars")]
[Description("display environment variables")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool ShowEnvironmentVariables { get; init; } = false;
///
/// Gets a value indicating whether to generate an X509 certificate and password.
///
[Argument(default, "generate-cert")]
[Description("generate X509 certificate and password for HTTPS")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool GenerateCertificate { get; init; } = false;
///
/// Gets a value indicating whether to generate a random secret.
///
[Argument(default, "generate-secret")]
[Description("generate random secret of the specified length")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public bool GenerateSecret { get; init; } = false;
///
/// Gets a value indicating whether the application should run in debug mode.
///
[Argument('d', "debug")]
[EnvironmentVariable("DEBUG")]
[Description("run in debug mode")]
[RequiresRestart]
public bool Debug { get; init; } = Debugger.IsAttached;
///
/// Gets a value indicating whether the application should run in headless (no web UI) mode.
///
[Argument('H', "headless")]
[EnvironmentVariable("HEADLESS")]
[Description("run in headless (no web UI) mode")]
[RequiresRestart]
public bool Headless { get; init; } = false;
///
/// Gets a value indicating whether remote configuration of options is allowed.
///
[Argument(default, "remote-configuration")]
[EnvironmentVariable("REMOTE_CONFIGURATION")]
[Description("allow remote configuration")]
public bool RemoteConfiguration { get; init; } = false;
///
/// Gets a value indicating whether remote file management is allowed.
///
[Argument(default, "remote-file-management")]
[EnvironmentVariable("REMOTE_FILE_MANAGEMENT")]
[Description("allow remote file management")]
public bool RemoteFileManagement { get; init; } = false;
///
/// Gets the unique name for this instance.
///
[Argument('i', "instance-name")]
[EnvironmentVariable("INSTANCE_NAME")]
[Description("optional; a unique name for this instance")]
[RequiresRestart]
public string InstanceName { get; init; } = "default";
///
/// Gets optional flags.
///
[Validate]
public FlagsOptions Flags { get; init; } = new FlagsOptions();
///
/// Gets the path where application data is saved.
///
[Argument('a', "app-dir")]
[EnvironmentVariable("APP_DIR")]
[Description("path where application data is saved")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public string AppDirectory { get; init; } = Program.DefaultAppDirectory;
///
/// Gets the path where application data is saved.
///
[Argument('c', "config")]
[EnvironmentVariable("CONFIG")]
[Description("path to configuration file")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
[YamlIgnore]
public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile;
///
/// Gets relay options.
///
[Validate]
public RelayOptions Relay { get; init; } = new RelayOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")]
public object Permissions { get; init; } = null;
///
/// Gets directory options.
///
[Validate]
[RequiresRestart]
public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions();
///
/// Gets share options.
///
[Validate]
public SharesOptions Shares { get; init; } = new SharesOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers instead.")]
public object Global { get; init; } = null;
[Obsolete("temporary sentinel to warn users about breaking change. use Transfers instead.")]
public object Groups { get; init; } = null;
///
/// Gets transfer options.
///
[Validate]
public TransfersOptions Transfers { get; init; } = new TransfersOptions();
///
/// Gets blacklist options.
///
[Validate]
public BlacklistOptions Blacklist { get; init; } = new BlacklistOptions();
///
/// Gets filter options.
///
[Validate]
public FiltersOptions Filters { get; init; } = new FiltersOptions();
///
/// Gets a list of rooms to automatically join upon connection.
///
[Argument(default, "rooms")]
[EnvironmentVariable("ROOMS")]
[Description("a list of rooms to automatically join")]
public string[] Rooms { get; init; } = Array.Empty();
///
/// Gets options for the web UI.
///
[Validate]
public WebOptions Web { get; init; } = new WebOptions();
///
/// Gets retention options.
///
[Validate]
public RetentionOptions Retention { get; init; } = new RetentionOptions();
///
/// Gets throttling options.
///
[Validate]
public ThrottlingOptions Throttling { get; init; } = new ThrottlingOptions();
///
/// Gets logger options.
///
[Validate]
[RequiresRestart]
public LoggerOptions Logger { get; init; } = new LoggerOptions();
///
/// Gets metrics options.
///
[Validate]
[RequiresRestart]
public MetricsOptions Metrics { get; init; } = new MetricsOptions();
///
/// Gets feature options.
///
[Validate]
[RequiresRestart]
public FeatureOptions Feature { get; init; } = new FeatureOptions();
///
/// Gets options for the Soulseek client.
///
[Validate]
public SoulseekOptions Soulseek { get; init; } = new SoulseekOptions();
[Obsolete("temporary sentinel to warn users about breaking change. use Integrations instead.")]
public object Integration { get; init; } = null;
///
/// Gets options for external integrations.
///
[Validate]
public IntegrationsOptions Integrations { get; init; } = new IntegrationsOptions();
///
/// Handles top-level validation that doesn't fit anywhere else.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (InstanceName == Program.LocalHostName && Relay.Mode.ToEnum() == RelayMode.Agent)
{
results.Add(new ValidationResult($"Instance name must be something other than '{Program.LocalHostName}' when operating in Relay Agent mode"));
}
#pragma warning disable CS0618 // Type or member is obsolete
if (Groups is not null || Global is not null)
{
results.Add(new ValidationResult("The 'global' and 'groups' keys have been moved under a new 'transfers' key. See https://github.com/slskd/slskd/pull/1672 for details, and make the necessary changes to remove this error"));
}
if (Integration is not null)
{
results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)"));
}
if (Permissions is not null)
{
results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details"));
}
#pragma warning restore CS0618 // Type or member is obsolete
return results;
}
///
/// Optional flags.
///
public class FlagsOptions
{
///
/// Gets a value indicating whether the logo should be suppressed on startup.
///
[Argument('n', "no-logo")]
[EnvironmentVariable("NO_LOGO")]
[Description("suppress logo on startup")]
[RequiresRestart]
public bool NoLogo { get; init; } = false;
///
/// Gets a value indicating whether the application should quit after initialization.
///
[Argument('x', "no-start")]
[EnvironmentVariable("NO_START")]
[Description("quit the application after initialization")]
[RequiresRestart]
public bool NoStart { get; init; } = false;
///
/// Gets a value indicating whether the application should watch the configuration file for changes.
///
[Argument(default, "no-config-watch")]
[EnvironmentVariable("NO_CONFIG_WATCH")]
[Description("do not watch the config file for changes")]
[RequiresRestart]
public bool NoConfigWatch { get; init; } = false;
///
/// Gets a value indicating whether the application should connect to the Soulseek network on startup.
///
[Argument(default, "no-connect")]
[EnvironmentVariable("NO_CONNECT")]
[Description("do not connect to the Soulseek network on startup")]
[RequiresRestart]
public bool NoConnect { get; init; } = false;
///
/// Gets a value indicating whether the application should scan shared directories on startup.
///
[Argument(default, "no-share-scan")]
[EnvironmentVariable("NO_SHARE_SCAN")]
[Description("do not scan shares on startup")]
[RequiresRestart]
public bool NoShareScan { get; init; } = false;
///
/// Gets a value indicating whether shares should be forcibly re-scanned on startup.
///
[Argument(default, "force-share-scan")]
[EnvironmentVariable("FORCE_SHARE_SCAN")]
[Description("force a share scan on startup")]
[RequiresRestart]
public bool ForceShareScan { get; init; } = false;
///
/// Gets a value indicating whether to force database migrations to be applied on startup.
///
[Argument(default, "force-migrations")]
[EnvironmentVariable("FORCE_MIGRATIONS")]
[Description("force database migrations to be applied on startup")]
public bool ForceMigrations { get; init; } = false;
///
/// Gets a value indicating whether the application should check for a newer version on startup.
///
[Argument(default, "no-version-check")]
[EnvironmentVariable("NO_VERSION_CHECK")]
[Description("do not check for newer version at startup")]
[RequiresRestart]
public bool NoVersionCheck { get; init; } = false;
///
/// Gets a value indicating whether Entity Framework queries should be logged.
///
[Argument(default, "log-sql")]
[EnvironmentVariable("LOG_SQL")]
[Description("log SQL queries generated by Entity Framework")]
[RequiresRestart]
public bool LogSQL { get; init; } = false;
///
/// Gets a value indicating whether to log unobserved Exceptions.
///
[Argument(default, "log-unobserved-exceptions")]
[EnvironmentVariable("LOG_UNOBSERVED_EXCEPTIONS")]
[Description("log unobserved exceptions (caution: verbose)")]
[RequiresRestart]
public bool LogUnobservedExceptions { get; init; } = false;
///
/// Gets a value indicating whether the application should run in experimental mode.
///
[Argument(default, "experimental")]
[EnvironmentVariable("EXPERIMENTAL")]
[Description("run in experimental mode")]
[RequiresRestart]
public bool Experimental { get; init; } = false;
///
/// Gets a value indicating whether the application should run in volatile mode.
///
[Argument(default, "volatile")]
[EnvironmentVariable("VOLATILE")]
[Description("use volatile data storage (all data will be lost at shutdown)")]
[RequiresRestart]
public bool Volatile { get; init; } = false;
///
/// Gets a value indicating whether user-defined regular expressions are case sensitive.
///
[Argument(default, "case-sensitive-regex")]
[EnvironmentVariable("CASE_SENSITIVE_REGEX")]
[Description("user-defined regular expressions are case sensitive")]
[RequiresRestart]
public bool CaseSensitiveRegEx { get; init; } = false;
///
/// Gets a value indicating whether to use legacy TCP keepalive options, for Windows
/// versions prior to Windows 10, version 1709 (and associated Server SKUs).
///
[Argument(default, "legacy-windows-tcp-keepalive")]
[EnvironmentVariable("LEGACY_WINDOWS_TCP_KEEPALIVE")]
[Description("use a legacy TCP keepalive strategy for older Windows versions")]
public bool LegacyWindowsTcpKeepalive { get; init; } = false;
///
/// Gets a value indicating whether to use the uploaded shares from Relay agents as the source of
/// truth for file existence and size, instead of querying the agent prior to enqueueing the file.
///
[Argument(default, "optimistic-relay-file-info")]
[EnvironmentVariable("OPTIMISTIC_RELAY_FILE_INFO")]
[Description("use uploaded relay shares as source of truth for file existence and size")]
public bool OptimisticRelayFileInfo { get; init; } = false;
///
/// Gets a value indicating whether SQLite pooling should be disabled.
///
[Argument(default, "no-sqlite-pooling")]
[EnvironmentVariable("NO_SQLITE_POOLING")]
[Description("disable SQLite pooling")]
public bool NoSqlitePooling { get; init; } = false;
}
///
/// Relay options.
///
public class RelayOptions : IValidatableObject
{
///
/// Gets a value indicating whether the relay is enabled.
///
[Argument('r', "relay")]
[EnvironmentVariable("RELAY")]
[Description("enable relay")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
///
/// Gets the relay mode.
///
[Argument('m', "relay-mode")]
[EnvironmentVariable("RELAY_MODE")]
[Description("relay mode; controller, agent")]
[RequiresRestart]
[Enum(typeof(RelayMode))]
public string Mode { get; init; } = RelayMode.Controller.ToString().ToLowerInvariant();
///
/// Gets the controller configuration.
///
public RelayControllerConfigurationOptions Controller { get; init; } = new RelayControllerConfigurationOptions();
///
/// Gets the agent configuration.
///
public Dictionary Agents { get; init; } = new();
public IEnumerable Validate(ValidationContext validationContext)
{
var mode = Mode.ToEnum();
var results = new List();
var modeResults = new List();
if (mode == RelayMode.Agent && !Validator.TryValidateObject(Controller, new ValidationContext(Controller), modeResults, validateAllProperties: true))
{
results.Add(new CompositeValidationResult("Controller", modeResults));
}
else
{
// determine whether any InstanceName is used more than once
var instanceNames = Agents.Values.Select(a => a.InstanceName);
if (instanceNames.Count() != instanceNames.Distinct().Count())
{
modeResults.Add(new ValidationResult("One or more Agent instance names are duplicated. Ensure instance names are unique."));
}
foreach (var (name, agent) in Agents)
{
var res = new List();
if (!Validator.TryValidateObject(agent, new ValidationContext(agent), res, validateAllProperties: true))
{
modeResults.Add(new CompositeValidationResult(name, res));
}
}
if (modeResults.Any())
{
results.Add(new CompositeValidationResult("Agents", modeResults));
}
}
return results;
}
///
/// Relay controller configuration options.
///
public class RelayControllerConfigurationOptions
{
///
/// Gets the controller address.
///
[Argument(default, "controller-address")]
[EnvironmentVariable("CONTROLLER_ADDRESS")]
[Description("controller address url")]
[Url]
[NotNullOrWhiteSpace]
public string Address { get; init; }
///
/// Gets a value indicating whether controller certificate errors should be ignored.
///
[Argument(default, "controller-ignore-certificate-errors")]
[EnvironmentVariable("CONTROLLER_IGNORE_CERTIFICATE_ERRORS")]
[Description("ignore controller certificate errors")]
public bool IgnoreCertificateErrors { get; init; } = false;
///
/// Gets the controller API key.
///
[Argument(default, "controller-api-key")]
[EnvironmentVariable("CONTROLLER_API_KEY")]
[Description("controller api key")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string ApiKey { get; init; }
///
/// Gets the controller secret.
///
[Argument(default, "controller-secret")]
[EnvironmentVariable("CONTROLLER_SECRET")]
[Description("shared secret")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string Secret { get; init; }
///
/// Gets a value indicating whether to receive completed downloads from the controller.
///
[Argument(default, "controller-downloads")]
[EnvironmentVariable("CONTROLLER_DOWNLOADS")]
[Description("receive completed downloads from the controller")]
public bool Downloads { get; init; } = false;
}
///
/// Relay agent configuration options.
///
public class RelayAgentConfigurationOptions : IValidatableObject
{
///
/// Gets the agent instance name.
///
[Description("the name for this agent")]
[StringLength(255, MinimumLength = 1)]
[NotNullOrWhiteSpace]
[Secret]
public string InstanceName { get; init; }
///
/// Gets the agent secret.
///
[Description("shared secret for this agent")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
public string Secret { get; init; }
///
/// Gets the comma separated list of CIDRs that are authorized to connect as this agent.
///
[Description("optional; comma separated list of CIDRs that are authorized to connect as this agent")]
public string Cidr { get; init; } = "0.0.0.0/0,::/0";
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
foreach (var cidr in Cidr.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
}
///
/// Directory options.
///
public class DirectoriesOptions
{
///
/// Gets the path where incomplete downloads are saved.
///
[Argument(default, "incomplete")]
[EnvironmentVariable("INCOMPLETE_DIR")]
[Description("path where incomplete downloads are saved")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory;
///
/// Gets the path where downloaded files are saved.
///
[Argument('o', "downloads")]
[EnvironmentVariable("DOWNLOADS_DIR")]
[Description("path where downloaded files are saved")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[DirectoryExists(ensureWriteable: true)]
[RequiresRestart]
public string Downloads { get; init; } = Program.DefaultDownloadsDirectory;
}
///
/// Share options.
///
public class SharesOptions : IValidatableObject
{
///
/// Gets the list of paths to shared files.
///
[Argument('s', "shared")]
[EnvironmentVariable("SHARED_DIR")]
[Description("paths to shared files")]
public string[] Directories { get; init; } = Array.Empty();
///
/// Gets the list of shared file filters.
///
[Argument(default, "share-filter")]
[EnvironmentVariable("SHARE_FILTER")]
[Description("regular expressions to filter files from shares")]
public string[] Filters { get; init; } = Array.Empty();
///
/// Share caching options.
///
[Validate]
public ShareCacheOptions Cache { get; init; } = new ShareCacheOptions();
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
results.AddRange(ValidateShares());
results.AddRange(ValidateFilters());
return results;
}
private IEnumerable ValidateShares()
{
var results = new List();
var directories = Directories ?? Enumerable.Empty();
bool IsBlankPath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])$");
directories?.Where(share => IsBlankPath(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} does not specify a path")));
bool IsRootMount(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])/$");
directories?.Where(share => IsRootMount(share)).ToList()
.ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported.")));
// starts with '/', 'X:', or '\\'
bool IsAbsolutePath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$");
directories?.Where(share => !IsAbsolutePath(share)).ToList()
.ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported.")));
// contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /..
// which is resolved by some OS and will cause weird, unintended side effects
bool ContainsTraversalSegments(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$");
directories?.Where(share => ContainsTraversalSegments(share)).ToList()
.ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment.")));
(string Raw, string Alias, string Path) Digest(string share)
{
var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$");
if (matches.Any())
{
return (share, matches[0].Groups[2].Value, matches[0].Groups[3].Value);
}
#pragma warning disable S3878 // Arrays should not be created for params parameters
return (share, share.Split(new[] { '/', '\\' }).Last(), share);
#pragma warning restore S3878 // Arrays should not be created for params parameters
}
var digestedShared = directories
.Select(share => Digest(share.TrimEnd('/', '\\')))
.ToHashSet();
// make sure all aliases are distinct
digestedShared.GroupBy(share => share.Alias).Where(group => group.Count() > 1).ToList()
.ForEach(overlap => results.Add(new ValidationResult($"Shares {string.Join(", ", overlap.Select(s => $"'{s.Raw}'"))} collide. Specify an alias for one or both to disambiguate them.")));
// make sure the same path hasn't been specified twice, under different aliases
digestedShared.GroupBy(share => share.Path).Where(group => group.Count() > 1).ToList()
.ForEach(dupe => results.Add(new ValidationResult($"Shares {string.Join(", ", dupe.Select(s => $"'{s.Raw}'"))} alias the same path")));
// make sure each share has an alias, or is alias-able, and that the alias is valid
foreach (var share in digestedShared)
{
if (string.IsNullOrWhiteSpace(share.Alias))
{
results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; alias may not be null, empty or consist of only whitespace"));
}
else if (share.Alias.Contains('\\') || share.Alias.Contains('/'))
{
results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'"));
}
}
return results;
}
private IEnumerable ValidateFilters()
{
var results = new List();
foreach (var filter in Filters)
{
if (!filter.IsValidRegex())
{
results.Add(new ValidationResult($"Share filter '{filter}' is not a valid regular expression"));
}
}
return results;
}
///
/// Share caching options.
///
public class ShareCacheOptions
{
///
/// Gets the type of storage to use for the share cache.
///
[Argument(default, "share-cache-storage-mode")]
[EnvironmentVariable("SHARE_CACHE_STORAGE_MODE")]
[Description("the type of storage to use for the cache")]
[Enum(typeof(StorageMode))]
[RequiresRestart]
public string StorageMode { get; init; } = slskd.Shares.StorageMode.Memory.ToString().ToLowerInvariant();
///
/// Gets the number of workers to use while scanning shares.
///
[Argument(default, "share-cache-workers")]
[EnvironmentVariable("SHARE_CACHE_WORKERS")]
[Description("the number of workers to use while scanning shares")]
[Range(1, 128)]
[RequiresRestart]
public int Workers { get; init; } = Environment.ProcessorCount;
///
/// Gets the time to retain the cache (the interval on which to re-scan automatically), in minutes.
///
[Argument(default, "share-cache-retention")]
[EnvironmentVariable("SHARE_CACHE_RETENTION")]
[Description("the time to retain the cache (re-scan interval), in minutes")]
[Range(60, int.MaxValue)]
public int? Retention { get; init; } = null;
}
}
///
/// Transfer options.
///
public class TransfersOptions
{
///
/// Gets global upload options.
///
[Validate]
public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions();
///
/// Gets global download options.
///
[Validate]
public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions();
///
/// Gets user groups.
///
[Validate]
public GroupsOptions Groups { get; init; } = new GroupsOptions();
///
/// Global upload options.
///
public class GlobalUploadOptions
{
///
/// Gets the limit for the total number of upload slots.
///
[Argument(default, "upload-slots")]
[EnvironmentVariable("UPLOAD_SLOTS")]
[Description("the total number of upload slots")]
[RequiresRestart]
[Range(1, int.MaxValue)]
public int Slots { get; init; } = 10;
///
/// Gets the total upload speed limit, in kibibytes.
///
[Argument(default, "upload-speed-limit")]
[EnvironmentVariable("UPLOAD_SPEED_LIMIT")]
[Description("the total upload speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
///
/// Gets global limits.
///
[Validate]
public LimitsOptions Limits { get; init; } = new LimitsOptions();
}
///
/// Gets global download options.
///
public class GlobalDownloadOptions
{
///
/// Gets the limit for the total number of download slots.
///
[Argument(default, "download-slots")]
[EnvironmentVariable("DOWNLOAD_SLOTS")]
[Description("the total number of download slots")]
[RequiresRestart]
[Range(1, int.MaxValue)]
public int Slots { get; init; } = int.MaxValue;
///
/// Gets the total download speed limit, in kibibytes.
///
[Argument(default, "download-speed-limit")]
[EnvironmentVariable("DOWNLOAD_SPEED_LIMIT")]
[Description("the total download speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
///
/// Gets download retry options.
///
[Validate]
public RetryOptions Retry { get; init; } = new RetryOptions();
///
/// Gets download destination options.
///
[Validate]
public DestinationOptions Destination { get; init; } = new DestinationOptions();
///
/// Download retry options.
///
public class RetryOptions
{
///
/// Gets the maximum number of times to retry a failed transfer.
///
[Range(1, int.MaxValue)]
public int Attempts { get; init; } = 3;
///
/// Gets the base time to wait between retry attempts, in milliseconds.
///
[Range(1000, int.MaxValue)]
public int Delay { get; init; } = 5000;
///
/// Gets the maximum time to wait between retry attempts, in milliseconds.
///
[Range(30_000, int.MaxValue)]
public int MaxDelay { get; init; } = 60_000;
///
/// Gets the strategy for handling partial files upon retry.
///
[Enum(typeof(RetryPartialStrategy))]
public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant();
}
///
/// Download destination options.
///
public class DestinationOptions
{
///
/// Gets the destination subdirectory for the files in the batch.
///
[RelativePath(OperatingSystem.All)]
[NonTraversingPath]
[String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)]
public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}";
///
/// Gets the strategy for handling existing files on disk.
///
[Enum(typeof(DestinationExistsStrategy))]
public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant();
///
/// Gets the permissions to apply to downloaded files and directories.
///
[Validate]
public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions();
///
/// Download destination permission options.
///
public class DestinationPermissionsOptions : IValidatableObject
{
///
/// Gets the permissions to apply to newly created files.
///
///
/// Applicable to non-Windows operating systems, only.
///
public string Mode { get; init; }
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (!string.IsNullOrEmpty(Mode))
{
var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled);
if (!regEx.IsMatch(Mode))
{
results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)"));
}
}
return results;
}
}
}
}
///
/// User groups.
///
public class GroupsOptions : IValidatableObject
{
///
/// Gets options for the default user group.
///
///
/// These options apply to users that are not privileged, have not been identified as leechers,
/// and have not been added as a member of any group.
///
[Validate]
public BaseGroupOptions Default { get; init; } = new BaseGroupOptions();
///
/// Gets options for the leecher user group.
///
///
/// These options apply to users that have been identified as leechers, and have not been added as a member of any group.
///
[Validate]
public LeecherOptions Leechers { get; init; } = new LeecherOptions();
///
/// Gets options for the blacklisted user group.
///
[Validate]
public BlacklistedOptions Blacklisted { get; init; } = new BlacklistedOptions();
///
/// Gets user defined groups and options.
///
[Validate]
public Dictionary UserDefined { get; init; } = new Dictionary();
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup };
var intersection = UserDefined.Keys.Intersect(builtInGroups);
return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name."));
}
///
/// Options that are common to all groups.
///
public class BaseGroupOptions
{
///
/// Gets upload options.
///
[Validate]
public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions();
///
/// User group upload options.
///
public class GroupUploadOptions
{
///
/// Gets the priority of the group.
///
[Range(1, int.MaxValue)]
public int Priority { get; init; } = 1;
///
/// Gets the queue strategy for the group.
///
[Enum(typeof(Transfers.QueueStrategy))]
public string Strategy { get; init; } = slskd.Transfers.QueueStrategy.RoundRobin.ToString().ToLowerInvariant();
///
/// Gets the limit for the total number of upload slots for the group.
///
[Range(1, int.MaxValue)]
public int Slots { get; init; } = int.MaxValue;
///
/// Gets the total upload speed limit for the group, in kibibytes.
///
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
///
/// Gets limit options.
///
[Validate]
public LimitsOptions Limits { get; init; } = new LimitsOptions();
}
}
///
/// Built in leecher group options.
///
public class LeecherOptions : BaseGroupOptions
{
///
/// Gets leecher threshold options.
///
[Validate]
public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions();
///
/// Leecher threshold options.
///
public class ThresholdOptions
{
///
/// Gets the minimum number of shared files required to avoid being classified as a leecher.
///
[Range(1, int.MaxValue)]
public int Files { get; init; } = 1;
///
/// Gets the minimum number of shared directories required to avoid being classified as a leecher.
///
[Range(1, int.MaxValue)]
public int Directories { get; init; } = 1;
}
}
///
/// Built in blacklisted group options.
///
public class BlacklistedOptions : IValidatableObject
{
///
/// Gets the list of group member usernames.
///
public string[] Members { get; init; } = Array.Empty();
///
/// Gets the list of regular expression patterns matched against usernames.
///
public string[] Patterns { get; init; } = Array.Empty();
///
/// Gets the list of group CIDRs.
///
public string[] Cidrs { get; init; } = Array.Empty();
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
foreach (var pattern in Patterns ?? Array.Empty())
{
if (!pattern.IsValidRegex())
{
results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression"));
}
}
foreach (var cidr in Cidrs ?? Array.Empty())
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
///
/// User defined user group options.
///
public class UserDefinedOptions : BaseGroupOptions
{
///
/// Gets the list of group member usernames.
///
public string[] Members { get; init; } = Array.Empty();
}
}
///
/// Limit options.
///
public class LimitsOptions
{
///
/// Gets limits for queued transfers.
///
[Validate]
public Limits Queued { get; init; } = new Limits();
///
/// Gets daily limits for transfers.
///
[Validate]
public Limits Daily { get; init; } = new Limits();
///
/// Gets weekly limits for transfers.
///
[Validate]
public Limits Weekly { get; init; } = new Limits();
///
/// Limits.
///
public class Limits
{
///
/// Gets the limit for number of files.
///
[Range(1, int.MaxValue)]
public int? Files { get; init; } = null;
///
/// Gets the limit for number of megabytes.
///
[Range(1, int.MaxValue)]
public int? Megabytes { get; init; } = null;
///
/// Gets the limit for number of failures.
///
[Range(1, int.MaxValue)]
public int? Failures { get; init; } = null;
}
}
}
///
/// Feature options.
///
public class FeatureOptions
{
///
/// Gets a value indicating whether swagger documentation and UI should be enabled.
///
[Argument(default, "swagger")]
[EnvironmentVariable("SWAGGER")]
[Description("enable swagger documentation and UI")]
[RequiresRestart]
public bool Swagger { get; init; } = false;
}
///
/// Blacklist options.
///
public class BlacklistOptions : IValidatableObject
{
///
/// Gets a value indicating whether blacklist file support should be enabled.
///
[Argument(default, "enable-blacklist")]
[EnvironmentVariable("BLACKLIST")]
[Description("enable blacklist file support")]
[RequiresRestart]
public bool Enabled { get; init; }
///
/// Gets the path to the blacklist file.
///
[Argument(default, "blacklist-file")]
[EnvironmentVariable("BLACKLIST_FILE")]
[Description("path to blacklist file")]
[FileExists(FileAccess.Read)]
public string File { get; init; }
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (!Enabled)
{
return results;
}
if (string.IsNullOrWhiteSpace(File))
{
results.Add(new ValidationResult("The Enabled field is true, but no File has been specified."));
return results;
}
// loading/validating the entire list will be costly on low spec systems
// just make sure that we can detect a valid format and leave it at that
// if there's a problem with any of the entries, the load will fail and
// kill the application
try
{
// async not supported here, .Result is all we have
_ = slskd.Blacklist.DetectFormat(File).Result;
}
catch
{
results.Add(new ValidationResult("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"));
}
return results;
}
}
///
/// Filter options.
///
public class FiltersOptions
{
///
/// Gets search filter options.
///
[Validate]
public SearchOptions Search { get; init; } = new SearchOptions();
///
/// Search filter options.
///
public class SearchOptions : IValidatableObject
{
///
/// Gets the list of search request filters.
///
[Argument(default, "search-request-filter")]
[EnvironmentVariable("SEARCH_REQUEST_FILTER")]
[Description("regular expressions to filter incoming search requests")]
public string[] Request { get; init; } = Array.Empty();
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
foreach (var filter in Request)
{
if (!filter.IsValidRegex())
{
results.Add(new ValidationResult($"Search request filter '{filter}' is not a valid regular expression"));
}
}
return results;
}
}
}
///
/// Logger options.
///
public class LoggerOptions
{
///
/// Gets the URL to a Grafana Loki instance to which to log.
///
[Argument(default, "loki")]
[EnvironmentVariable("LOKI")]
[Description("optional; url to a Grafana Loki instance to which to log")]
[RequiresRestart]
[Secret]
public string Loki { get; init; } = null;
///
/// Gets a value indicating whether to write logs to disk.
///
[Argument(default, "no-disk-logger")]
[EnvironmentVariable("NO_DISK_LOGGER")]
[Description("disable logging to disk")]
[RequiresRestart]
public bool NoDisk { get; init; } = false;
///
/// Gets a value indicating whether to suppress colorization of console logs.
///
[Argument(default, "no-color")]
[EnvironmentVariable("NO_COLOR")]
[Description("disable console log colors")]
[RequiresRestart]
public bool NoColor { get; init; } = false;
}
///
/// Retention options.
///
public class RetentionOptions
{
///
/// Gets the time to retain searches, in minutes.
///
[Range(5, maximum: int.MaxValue)]
public int? Search { get; init; } = null;
///
/// Gets transfer retention options.
///
[Validate]
public TransferRetentionOptions Transfers { get; init; } = new TransferRetentionOptions();
///
/// Gets file retention options.
///
[Validate]
public FileRetentionOptions Files { get; init; } = new FileRetentionOptions();
///
/// Gets the time to retain logs, in days.
///
[Range(2, maximum: int.MaxValue)]
public int Logs { get; init; } = 14;
///
/// Transfer retention options.
///
public class TransferRetentionOptions
{
///
/// Gets upload retention options.
///
[Validate]
public TransferTypeRetentionOptions Upload { get; init; } = new TransferTypeRetentionOptions();
///
/// Gets download retention options.
///
[Validate]
public TransferTypeRetentionOptions Download { get; init; } = new TransferTypeRetentionOptions();
///
/// Transfer retention options.
///
public class TransferTypeRetentionOptions
{
///
/// Gets the time to retain successful transfers, in minutes.
///
[Range(5, maximum: int.MaxValue)]
public int? Succeeded { get; init; } = null;
///
/// Gets the time to retain errored transfers, in minutes.
///
[Range(5, maximum: int.MaxValue)]
public int? Errored { get; init; } = null;
///
/// Gets the time to retain cancelled transfers, in minutes.
///
[Range(5, maximum: int.MaxValue)]
public int? Cancelled { get; init; } = null;
///
/// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes.
///
[Range(5, maximum: int.MaxValue)]
public int? Failed { get; init; } = null;
}
}
///
/// File retention options.
///
public class FileRetentionOptions
{
///
/// Gets the time to retain completed files, in minutes.
///
[Range(30, maximum: int.MaxValue)]
public int? Complete { get; init; } = null;
///
/// Gets the time to retain incomplete files, in minutes.
///
[Range(30, maximum: int.MaxValue)]
public int? Incomplete { get; init; } = null;
}
}
///
/// Throttling options.
///
public class ThrottlingOptions
{
///
/// Gets search throttling options.
///
[Validate]
public SearchThrottlingOptions Search { get; init; } = new SearchThrottlingOptions();
///
/// Search throttling options.
///
public class SearchThrottlingOptions
{
///
/// Gets incoming search throttling options.
///
[Validate]
public IncomingSearchThrottlingOptions Incoming { get; init; } = new IncomingSearchThrottlingOptions();
///
/// Search response throttling options.
///
public class IncomingSearchThrottlingOptions
{
///
/// Gets the limit for the number of concurrent search response operations.
///
[Argument(default, "throttling-search-incoming-concurrency")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CONCURRENCY")]
[Range(1, 100)]
[RequiresRestart]
public int Concurrency { get; init; } = 10;
///
/// Gets the limit for the number of queued search response operations, after which requests will be discarded.
///
[Argument(default, "throttling-search-incoming-circuit-breaker")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")]
[Range(100, 10000)]
public int CircuitBreaker { get; init; } = 500;
///
/// Gets the limit for the number of files that can be returned in a single search request.
///
[Argument(default, "throttling-search-incoming-response-file-limit")]
[EnvironmentVariable("THROTTLING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT")]
[Range(100, 5000)]
public int ResponseFileLimit { get; init; } = 500;
}
}
}
///
/// Metrics options.
///
public class MetricsOptions
{
///
/// Gets a value indicating whether the metrics endpoint should be enabled.
///
[Argument(default, "metrics")]
[EnvironmentVariable("METRICS")]
[Description("enable metrics")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
///
/// Gets the url for the metrics endpoint.
///
[Argument(default, "metrics-url")]
[EnvironmentVariable("METRICS_URL")]
[Description("url for metrics")]
[RequiresRestart]
public string Url { get; init; } = "/metrics";
///
/// Gets metrics endpoint authentication options.
///
[Validate]
public MetricsAuthenticationOptions Authentication { get; init; } = new MetricsAuthenticationOptions();
///
/// Metrics endpoint authentication options.
///
public class MetricsAuthenticationOptions
{
///
/// Gets a value indicating whether authentication should be disabled.
///
[Argument(default, "metrics-no-auth")]
[EnvironmentVariable("METRICS_NO_AUTH")]
[Description("disable authentication for metrics requests")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
///
/// Gets the username for the metrics endpoint.
///
[Argument(default, "metrics-username")]
[EnvironmentVariable("METRICS_USERNAME")]
[Description("username for metrics")]
[StringLength(255, MinimumLength = 1)]
[RequiresRestart]
public string Username { get; init; } = Program.AppName;
///
/// Gets the password for the metrics endpoint.
///
[Argument(default, "metrics-password")]
[EnvironmentVariable("METRICS_PASSWORD")]
[Description("password for metrics")]
[StringLength(255, MinimumLength = 1)]
[Secret]
[RequiresRestart]
public string Password { get; init; } = Program.AppName;
}
}
///
/// Soulseek client options.
///
public class SoulseekOptions
{
///
/// Gets the address of the Soulseek server.
///
[Argument(default, "slsk-address")]
[EnvironmentVariable("SLSK_ADDRESS")]
[Description("address of the Soulseek server")]
[RequiresReconnect]
public string Address { get; init; } = "vps.slsknet.org";
///
/// Gets the port of the Soulseek server.
///
[Argument(default, "slsk-port")]
[EnvironmentVariable("SLSK_PORT")]
[Description("port of the Soulseek server")]
[RequiresReconnect]
[Range(1024, 65535)]
public int Port { get; init; } = 2271;
///
/// Gets the username for the Soulseek network.
///
[Argument(default, "slsk-username")]
[EnvironmentVariable("SLSK_USERNAME")]
[Description("username for the Soulseek network")]
[RequiresReconnect]
public string Username { get; init; } = null;
///
/// Gets the password for the Soulseek network.
///
[Argument(default, "slsk-password")]
[EnvironmentVariable("SLSK_PASSWORD")]
[Description("password for the Soulseek network")]
[Secret]
[RequiresReconnect]
public string Password { get; init; } = null;
///
/// Gets the description of the Soulseek user.
///
[Argument(default, "slsk-description")]
[EnvironmentVariable("SLSK_DESCRIPTION")]
[Description("user description for the Soulseek network")]
public string Description { get; init; } = "A slskd user. https://github.com/slskd/slskd";
///
/// Gets the file path for the user's profile picture.
///
[Argument(default, "slsk-picture")]
[EnvironmentVariable("SLSK_PICTURE")]
[Description("user picture for the Soulseek network")]
[FileExists(FileAccess.Read)]
public string Picture { get; init; } = null;
///
/// Gets the local IP address on which to listen for incoming connections.
///
[Argument(default, "slsk-listen-ip-address")]
[EnvironmentVariable("SLSK_LISTEN_IP_ADDRESS")]
[Description("local IP address on which to listen for incoming connections")]
[IPAddress]
public string ListenIpAddress { get; init; } = "0.0.0.0";
///
/// Gets the port on which to listen for incoming connections.
///
[Argument(default, "slsk-listen-port")]
[EnvironmentVariable("SLSK_LISTEN_PORT")]
[Description("port on which to listen for incoming connections")]
[Range(1024, 65535)]
public int ListenPort { get; init; } = 50300;
///
/// Gets the minimum diagnostic level.
///
[Argument(default, "slsk-diag-level")]
[EnvironmentVariable("SLSK_DIAG_LEVEL")]
[Description("minimum diagnostic level (None, Warning, Info, Debug)")]
[Enum(typeof(SoulseekDiagnostics.DiagnosticLevel))]
[RequiresRestart]
public string DiagnosticLevel { get; init; } = SoulseekDiagnostics.DiagnosticLevel.Info.ToString().ToLowerInvariant();
///
/// Gets options for the distributed network.
///
[Validate]
public DistributedNetworkOptions DistributedNetwork { get; init; } = new DistributedNetworkOptions();
///
/// Gets connection options.
///
[Validate]
public ConnectionOptions Connection { get; init; } = new ConnectionOptions();
///
/// Connection options.
///
public class ConnectionOptions
{
///
/// Gets connection timeout options.
///
[Validate]
public TimeoutOptions Timeout { get; init; } = new TimeoutOptions();
///
/// Gets connection buffer options.
///
[Validate]
public BufferOptions Buffer { get; init; } = new BufferOptions();
///
/// Gets connection proxy options.
///
[Validate]
public ProxyOptions Proxy { get; init; } = new ProxyOptions();
///
/// Gets the MTU to use for the server connection, or null to use the OS default.
///
[Argument(default, "slsk-server-mtu")]
[EnvironmentVariable("SLSK_SERVER_MTU")]
[Description("MTU to use for the server connection")]
[Range(576, 65535)]
[RequiresReconnect]
public int? Mtu { get; init; } = null;
///
/// Connection buffer options.
///
public class BufferOptions
{
///
/// Gets the connection read buffer size, in bytes.
///
[Argument(default, "slsk-read-buffer")]
[EnvironmentVariable("SLSK_READ_BUFFER")]
[Description("read buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Read { get; init; } = 16384;
///
/// Gets the connection write buffer size, in bytes.
///
[Argument(default, "slsk-write-buffer")]
[EnvironmentVariable("SLSK_WRITE_BUFFER")]
[Description("write buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Write { get; init; } = 16384;
///
/// Gets the read/write buffer size for transfers, in bytes.
///
[Argument(default, "slsk-transfer-buffer")]
[EnvironmentVariable("SLSK_TRANSFER_BUFFER")]
[Description("read/write buffer size for transfers")]
[Range(81920, int.MaxValue)]
public int Transfer { get; init; } = 262144;
///
/// Gets the size of the queue for double buffered writes.
///
[Argument(default, "slsk-write-queue")]
[EnvironmentVariable("SLSK_WRITE_QUEUE")]
[Description("queue size for double buffered writes")]
[Range(5, 5000)]
public int WriteQueue { get; init; } = 50;
}
///
/// Connection timeout options.
///
public class TimeoutOptions
{
///
/// Gets the connection timeout value, in milliseconds.
///
[Argument(default, "slsk-connection-timeout")]
[EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")]
[Description("connection timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Connect { get; init; } = 10000;
///
/// Gets the connection inactivity timeout, in milliseconds.
///
[Argument(default, "slsk-inactivity-timeout")]
[EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")]
[Description("connection inactivity timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Inactivity { get; init; } = 15000;
///
/// Gets the transfer connection timeout, in milliseconds.
///
[Argument(default, "slsk-transfer-timeout")]
[EnvironmentVariable("SLSK_TRANSFER_TIMEOUT")]
[Description("transfer connection timeout, in milliseconds")]
[Range(30_000, int.MaxValue)]
public int Transfer { get; init; } = 60000;
}
///
/// Connection proxy options.
///
public class ProxyOptions : IValidatableObject
{
///
/// Gets a value indicating whether the proxy is enabled.
///
[Argument(default, "slsk-proxy")]
[EnvironmentVariable("SLSK_PROXY_ENABLED")]
[Description("enable connection proxy")]
public bool Enabled { get; init; } = false;
///
/// Gets the proxy address.
///
[Argument(default, "slsk-proxy-address")]
[EnvironmentVariable("SLSK_PROXY_ADDRESS")]
[Description("connection proxy address")]
[StringLength(255, MinimumLength = 1)]
public string Address { get; init; }
///
/// Gets the proxy port.
///
[Argument(default, "slsk-proxy-port")]
[EnvironmentVariable("SLSK_PROXY_PORT")]
[Description("connection proxy port")]
[Range(1, 65535)]
public int? Port { get; init; }
///
/// Gets the proxy username, if applicable.
///
[Argument(default, "slsk-proxy-username")]
[EnvironmentVariable("SLSK_PROXY_USERNAME")]
[Description("connection proxy username")]
[StringLength(255, MinimumLength = 1)]
public string Username { get; init; }
///
/// Gets the proxy password, if applicable.
///
[Argument(default, "slsk-proxy-password")]
[EnvironmentVariable("SLSK_PROXY_PASSWORD")]
[Description("connection proxy password")]
[StringLength(255, MinimumLength = 1)]
[Secret]
public string Password { get; init; }
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (Enabled && string.IsNullOrWhiteSpace(Address))
{
results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified."));
}
if (Enabled && !Port.HasValue)
{
results.Add(new ValidationResult($"The Enabled field is true, but no Port has been specified."));
}
return results;
}
}
}
///
/// Distributed network options.
///
public class DistributedNetworkOptions
{
///
/// Gets a value indicating whether the distributed network should be disabled.
///
[Argument(default, "slsk-no-dnet")]
[EnvironmentVariable("SLSK_NO_DNET")]
[Description("disable the distributed network")]
public bool Disabled { get; init; } = false;
///
/// Gets a value indicating whether to accept distributed child connections.
///
[Argument(default, "slsk-dnet-no-children")]
[EnvironmentVariable("SLSK_DNET_NO_CHILDREN")]
[Description("do not accept distributed children")]
public bool DisableChildren { get; init; } = false;
///
/// Gets the distributed child connection limit.
///
[Argument(default, "slsk-dnet-children")]
[EnvironmentVariable("SLSK_DNET_CHILDREN")]
[Description("max number of distributed children")]
[Range(1, int.MaxValue)]
public int ChildLimit { get; init; } = 25;
///
/// Gets a value indicating whether distributed network logging should be enabled.
///
[Argument(default, "slsk-dnet-logging")]
[EnvironmentVariable("SLSK_DNET_LOGGING")]
[Description("enable distributed network logging")]
public bool Logging { get; init; } = false;
}
}
///
/// Web server options.
///
public class WebOptions
{
///
/// Gets the HTTP listen port.
///
[Argument('l', "http-port")]
[EnvironmentVariable("HTTP_PORT")]
[Description("HTTP listen port for web UI")]
[Range(1, 65535)]
[RequiresRestart]
public int Port { get; init; } = 5030;
///
/// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests.
///
[Argument(default, "http-ip-address")]
[EnvironmentVariable("HTTP_IP_ADDRESS")]
[Description("IP addresses on which to listen for HTTP requests")]
[IPAddress(allowCommaSeparatedValues: true)]
[RequiresRestart]
public string IpAddress { get; init; }
///
/// Gets the HTTP listen unix domain socket (UDS) path.
///
[Argument(default, "http-socket")]
[EnvironmentVariable("HTTP_SOCKET")]
[Description("HTTP listen unix domain socket (UDS) path for web UI")]
[AbsolutePath(OperatingSystem.Current)]
[NonTraversingPath]
[RequiresRestart]
public string Socket { get; init; }
///
/// Gets HTTPS options.
///
[Validate]
[RequiresRestart]
public HttpsOptions Https { get; init; } = new HttpsOptions();
///
/// Gets the base url for web requests.
///
[Argument(default, "url-base")]
[EnvironmentVariable("URL_BASE")]
[Description("base url for web requests")]
[RequiresRestart]
public string UrlBase { get; init; } = "/";
///
/// Gets the path to static web content.
///
[Argument(default, "content-path")]
[EnvironmentVariable("CONTENT_PATH")]
[Description("path to static web content")]
[StringLength(255, MinimumLength = 1)]
[DirectoryExists(relativeToApplicationDirectory: true)]
[RequiresRestart]
public string ContentPath { get; init; } = "wwwroot";
///
/// Gets a value indicating whether HTTP request logging should be enabled.
///
[Argument(default, "http-logging")]
[EnvironmentVariable("HTTP_LOGGING")]
[Description("enable http request logging")]
[RequiresRestart]
public bool Logging { get; init; } = false;
///
/// Gets authentication options.
///
[Validate]
public WebAuthenticationOptions Authentication { get; init; } = new WebAuthenticationOptions();
///
/// Gets CORS options.
///
[Validate]
public CorsOptions Cors { get; init; } = new CorsOptions();
///
/// Authentication options.
///
public class WebAuthenticationOptions : IValidatableObject
{
///
/// Gets a value indicating whether authentication should be disabled.
///
[Argument('X', "no-auth")]
[EnvironmentVariable("NO_AUTH")]
[Description("disable authentication for web requests")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
///
/// Gets the username for the web UI.
///
[Argument('u', "username")]
[EnvironmentVariable("USERNAME")]
[Description("username for web UI")]
[StringLength(255, MinimumLength = 1)]
public string Username { get; init; } = Program.AppName;
///
/// Gets the password for the web UI.
///
[Argument('p', "password")]
[EnvironmentVariable("PASSWORD")]
[Description("password for web UI")]
[StringLength(255, MinimumLength = 1)]
[Secret]
public string Password { get; init; } = Program.AppName;
///
/// Gets JWT options.
///
[Validate]
[RequiresRestart]
public JwtOptions Jwt { get; init; } = new JwtOptions();
///
/// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'.
/// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'.
///
[Argument('k', "api-key")]
[EnvironmentVariable("API_KEY")]
[Description("primary API key value")]
[Secret]
[RequiresRestart]
public string ApiKey { get; init; }
///
/// Gets API keys.
///
[Validate]
public Dictionary ApiKeys { get; init; } = new Dictionary();
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (string.IsNullOrWhiteSpace(ApiKey))
{
return results;
}
var tuples = ApiKey.Split(';');
// if only one tuple is supplied, it's just the key, no role or list of CIDRs
if (tuples.Length == 1)
{
var key = tuples.FirstOrDefault();
if (key?.Length < 16 || key?.Length > 255)
{
results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
}
return results;
}
/*
if multiple tuples are supplied, verify that:
* if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values
* if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid
* if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters
*/
foreach (var tuple in tuples)
{
if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
{
var role = tuple.Split('=').LastOrDefault();
var roleResult = new EnumAttribute(typeof(Role), ignoreCase: true)
.GetValidationResult(role, new ValidationContext(this) { MemberName = nameof(ApiKey), DisplayName = "API key role" });
if (roleResult != ValidationResult.Success)
{
results.Add(new ValidationResult(roleResult.ErrorMessage));
}
}
else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
{
var cidrs = tuple.Split('=').LastOrDefault();
foreach (var cidr in cidrs.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}"));
}
}
}
else if (tuple?.Length < 16 || tuple?.Length > 255)
{
results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
}
}
return results;
}
///
/// JWT options.
///
public class JwtOptions
{
///
/// Gets the key with which to sign JWTs.
///
[Argument(default, "jwt-key")]
[EnvironmentVariable("JWT_KEY")]
[Description("JWT signing key")]
[StringLength(255, MinimumLength = 32)]
[Secret]
[RequiresRestart]
public string Key { get; init; } = Cryptography.Random.GetBytes(32).ToBase62();
///
/// Gets the TTL for JWTs, in milliseconds.
///
[Argument(default, "jwt-ttl")]
[EnvironmentVariable("JWT_TTL")]
[Description("TTL for JWTs")]
[Range(3600000, int.MaxValue)]
[RequiresRestart]
public int Ttl { get; init; } = 604800000;
}
///
/// API key options.
///
public class ApiKeyOptions : IValidatableObject
{
///
/// Gets the API key value.
///
[Description("API key value")]
[StringLength(255, MinimumLength = 16)]
[Secret]
public string Key { get; init; }
///
/// Gets the role for the key.
///
[Description("user role for the key; readonly, readwrite, administrator")]
[Enum(typeof(Role))]
public string Role { get; init; } = slskd.Authentication.Role.ReadOnly.ToString();
///
/// Gets the comma separated list of CIDRs that are authorized to use the key.
///
[Description("optional; comma separated list of CIDRs that are authorized to use the key")]
public string Cidr { get; init; } = "0.0.0.0/0,::/0";
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
foreach (var cidr in Cidr.Split(','))
{
try
{
if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase))
{
throw new Exception("IPv4 mapped IPv6 addresses are not allowed");
}
_ = IPAddressRange.Parse(cidr);
}
catch (Exception ex)
{
results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}"));
}
}
return results;
}
}
}
///
/// HTTPS options.
///
public class HttpsOptions
{
///
/// Gets a value indicating whether HTTPS should be disabled.
///
[Argument(default, "no-https")]
[EnvironmentVariable("NO_HTTPS")]
[Description("disable HTTPS")]
[RequiresRestart]
public bool Disabled { get; init; } = false;
///
/// Gets the HTTPS listen port.
///
[Argument('L', "https-port")]
[EnvironmentVariable("HTTPS_PORT")]
[Description("HTTPS listen port for web UI")]
[Range(1, 65535)]
[RequiresRestart]
public int Port { get; init; } = 5031;
///
/// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests.
///
[Argument(default, "https-ip-address")]
[EnvironmentVariable("HTTPS_IP_ADDRESS")]
[Description("IP addresses on which to listen for HTTPS requests")]
[IPAddress(allowCommaSeparatedValues: true)]
[RequiresRestart]
public string IpAddress { get; init; }
///
/// Gets a value indicating whether HTTP requests should be redirected to HTTPS.
///
[Argument('f', "force-https")]
[EnvironmentVariable("HTTPS_FORCE")]
[Description("redirect HTTP to HTTPS")]
[RequiresRestart]
public bool Force { get; init; } = false;
///
/// Gets certificate options.
///
[Validate]
[RequiresRestart]
public CertificateOptions Certificate { get; init; } = new CertificateOptions();
///
/// Certificate options.
///
[X509Certificate]
public class CertificateOptions
{
///
/// Gets the path to the the X509 certificate .pfx file.
///
[Argument(default, "https-cert-pfx")]
[EnvironmentVariable("HTTPS_CERT_PFX")]
[Description("path to X509 certificate .pfx")]
[FileExists(FileAccess.Read)]
[RequiresRestart]
public string Pfx { get; init; }
///
/// Gets the password for the X509 certificate.
///
[Argument(default, "https-cert-password")]
[EnvironmentVariable("HTTPS_CERT_PASSWORD")]
[Description("X509 certificate password")]
[RequiresRestart]
[Secret]
public string Password { get; init; }
}
}
///
/// CORS options.
///
public class CorsOptions : IValidatableObject
{
///
/// Gets the list of CORS allowed origins.
///
[Argument(default, "cors-allowed-origins")]
[EnvironmentVariable("CORS_ALLOWED_ORIGINS")]
[Description("list of allowed CORS origins")]
public string[] AllowedOrigins { get; init; } = null;
///
/// Gets a value indicating whether CORS requests may include credentials.
///
[Argument(default, "cors-allow-credentials")]
[EnvironmentVariable("CORS_ALLOW_CREDENTIALS")]
[Description("allow CORS credentials for allowed origins")]
public bool AllowCredentials { get; init; } = false;
public IEnumerable Validate(ValidationContext validationContext)
{
if (AllowedOrigins?.Count(x => x == "*") > 1)
{
yield return new ValidationResult("Specify only one wildcard origin (\"*\")");
}
foreach (var origin in (AllowedOrigins ?? []).Where(o => o != "*"))
{
if (origin.Contains('*'))
{
yield return new ValidationResult($"Origin {origin} must not contain a wildcard");
}
if (!Uri.TryCreate(origin, default(UriCreationOptions), out var o))
{
yield return new ValidationResult($"Origin {origin} is not a valid URI");
continue;
}
if (!o.IsAbsoluteUri)
{
yield return new ValidationResult($"Origin {origin} must be an absolute URI");
}
string[] validSchemes = ["http", "https"];
if (!validSchemes.Contains(o.Scheme, StringComparer.OrdinalIgnoreCase))
{
yield return new ValidationResult($"Origin {origin} must use the HTTP or HTTPS scheme");
}
var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder().WithOrigins(origin).Build();
var browserOrigin = $"{o.Scheme}://{o.IdnHost}{(o.IsDefaultPort ? string.Empty : $":{o.Port}")}";
if (!policy.IsOriginAllowed(browserOrigin))
{
yield return new ValidationResult($"Origin {origin} is malformed and will never match a browser request; rewrite it as {browserOrigin}");
}
}
if ((AllowedOrigins is null || AllowedOrigins.Length == 0 || AllowedOrigins.Contains("*")) && AllowCredentials)
{
yield return new ValidationResult("Credentials can not be allowed while allowing all origins");
}
}
}
}
///
/// Options for external integrations.
///
public class IntegrationsOptions
{
///
/// Gets VPN options.
///
[Validate]
public VpnOptions Vpn { get; init; } = new();
///
/// Gets webhook configuration.
///
[Validate]
public Dictionary Webhooks { get; init; } = [];
///
/// Gets script configuration.
///
[Validate]
public Dictionary Scripts { get; init; } = [];
///
/// Gets FTP options.
///
[Validate]
public FtpOptions Ftp { get; init; } = new FtpOptions();
///
/// Gets Pushbullet options.
///
[Validate]
public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions();
///
/// VPN options.
///
public class VpnOptions : IValidatableObject
{
///
/// Gets a value indicating whether the VPN integration is enabled.
///
[Argument(default, "vpn")]
[EnvironmentVariable("VPN")]
[Description("enable VPN integration")]
[RequiresRestart]
public bool Enabled { get; init; } = false;
///
/// Gets a value indicating whether the configured VPN supports dynamic port forwarding.
///
[Argument(default, "vpn-port-forwarding")]
[EnvironmentVariable("VPN_PORT_FORWARDING")]
[Description("VPN supports dynamic port forwarding")]
public bool PortForwarding { get; init; } = false;
///
/// Gets the rate at which to poll the configured VPN client for status updates, in milliseconds.
///
[Argument(default, "vpn-polling-interval")]
[EnvironmentVariable("VPN_POLLING_INTERVAL")]
[Description("VPN client status polling interval")]
[Range(500, int.MaxValue)]
[RequiresRestart]
public int PollingInterval { get; init; } = 2500;
///
/// Gets Gluetun options.
///
[Validate]
public GluetunVpnOptions Gluetun { get; init; } = new GluetunVpnOptions();
public IEnumerable Validate(ValidationContext validationContext)
{
if (Enabled)
{
// as/if more VPN clients are added, update this logic to ensure that exactly one is configured
if (string.IsNullOrWhiteSpace(Gluetun?.Url))
{
yield return new ValidationResult("VPN is enabled but no client is configured");
yield break;
}
if (!Uri.TryCreate(Gluetun.Url, UriKind.Absolute, out _))
{
yield return new ValidationResult("The gluetun URL must be absolute, e.g. 'http://127.0.0.1:8000'");
}
}
}
///
/// Gluetun options.
///
public class GluetunVpnOptions
{
///
/// Gets the Gluetun integration version.
///
///
/// Only v1 of the Gluetun API exists right now; this is to ease a transition if there's ever a v2.
///
[Range(1, 1)]
public int Version { get; init; } = 1;
///
/// Gets the fully qualified root URL for the Gluetun control server.
///
[Argument(default, "vpn-gluetun-url")]
[EnvironmentVariable("VPN_GLUETUN_URL")]
[Description("URL for gluetun control server")]
public string Url { get; init; }
///
/// Gets the timeout for HTTP requests to the Gluetun control server, in milliseconds.
///
[Argument(default, "vpn-gluetun-timeout")]
[EnvironmentVariable("VPN_GLUETUN_TIMEOUT")]
[Description("timeout for HTTP requests to gluetun control server")]
[Range(500, 10_000)]
public int Timeout { get; init; } = 1000;
///
/// Gets the username used for basic auth.
///
[Argument(default, "vpn-gluetun-username")]
[EnvironmentVariable("VPN_GLUETUN_USERNAME")]
[Description("username for gluetun control server")]
public string Username { get; init; }
///
/// Gets the password used for basic auth.
///
[Argument(default, "vpn-gluetun-password")]
[EnvironmentVariable("VPN_GLUETUN_PASSWORD")]
[Description("password for gluetun control server")]
[Secret]
public string Password { get; init; }
///
/// Gets the API key used for API key auth.
///
[Argument(default, "vpn-gluetun-api-key")]
[EnvironmentVariable("VPN_GLUETUN_API_KEY")]
[Description("API key for gluetun control server")]
[Secret]
public string ApiKey { get; init; }
}
}
///
/// Webhook configuration.
///
public class WebhookOptions
{
///
/// Gets the list of Event types that trigger the webhook.
///
[Enum(typeof(EventType))]
public string[] On { get; init; } = Array.Empty();
///
/// Gets details about the webhook call.
///
[Validate]
public WebhookHttpOptions Call { get; init; } = new WebhookHttpOptions();
///
/// Gets the time to wait before timing out, in milliseconds.
///
[Range(500, int.MaxValue)]
public int Timeout { get; init; } = 5000;
///
/// Gets the retry configuration.
///
[Validate]
public RetryOptions Retry { get; init; } = new RetryOptions();
}
///
/// Webhook HTTP options.
///
public class WebhookHttpOptions : IValidatableObject
{
///
/// Gets the fully qualified URL for the webhook.
///
[NotNullOrWhiteSpace]
[Secret]
public string Url { get; init; }
///
/// Gets the HTTP headers to include with the webhook.
///
[Validate]
public WebhookHttpHeader[] Headers { get; init; } = [];
///
/// Gets a value indicating whether HTTPS certificate errors should be ignored.
///
public bool IgnoreCertificateErrors { get; init; } = false;
public IEnumerable Validate(ValidationContext validationContext)
{
if (!Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
yield return new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)");
}
}
}
///
/// Webhook HTTP header configuration.
///
public class WebhookHttpHeader
{
///
/// Gets the name of the header.
///
[NotNullOrWhiteSpace]
public string Name { get; init; }
///
/// Gets the header's value.
///
[Secret]
public string Value { get; init; }
}
///
/// Retry configuration.
///
public class RetryOptions
{
///
/// Gets the number of attempts to make before failing.
///
[Range(1, int.MaxValue)]
public int Attempts { get; init; } = 1;
}
///
/// Script configuration.
///
public class ScriptOptions
{
///
/// Gets the list of Event types that trigger the script.
///
[Enum(typeof(EventType))]
public string[] On { get; init; } = Array.Empty();
///
/// Gets the shell script to invoke.
///
public ScriptRunOptions Run { get; init; } = new ScriptRunOptions();
}
///
/// Script run options.
///
public class ScriptRunOptions : IValidatableObject
{
///
/// Gets the shell command to run.
///
[Secret]
public string Command { get; init; }
///
/// Gets the executable to start.
///
public string Executable { get; init; }
///
/// Gets the arguments to pass to the executable.
///
///
/// Mutually exclusive with .
///
[Secret]
public string Args { get; init; }
///
/// Gets the list of arguments to pass to the executable.
///
///
/// Mutually exclusive with .
///
public string[] Arglist { get; init; } = null;
public IEnumerable Validate(ValidationContext validationContext)
{
var cmdIsSet = !string.IsNullOrWhiteSpace(Command);
var exeIsSet = !string.IsNullOrWhiteSpace(Executable);
if ((cmdIsSet && exeIsSet) || (!cmdIsSet && !exeIsSet))
{
yield return new ValidationResult($"One and only one of the fields {nameof(Command)} or {nameof(Executable)} may be specified for a single script. If you intend to use the system shell, omit 'executable'. If you intend to use an executable other than the system shell, omit 'command' and specify either 'args' or 'args_list'.");
}
var argsIsSet = !string.IsNullOrWhiteSpace(Args);
var argsListIsSet = Arglist is not null;
if (argsIsSet && argsListIsSet)
{
yield return new ValidationResult($"Only one of the fields {nameof(Args)} or {nameof(Arglist)} may be specified for a single script. Specify 'args' if you intend to construct a single quoted string yourself, and specify 'args_list' if you'd like slskd to handle quoting for you.");
}
}
}
///
/// FTP options.
///
public class FtpOptions : IValidatableObject
{
///
/// Gets a value indicating whether the FTP integration is enabled.
///
[Argument(default, "ftp")]
[EnvironmentVariable("FTP")]
[Description("enable FTP integration")]
public bool Enabled { get; init; }
///
/// Gets the FTP address.
///
[Argument(default, "ftp-address")]
[EnvironmentVariable("FTP_ADDRESS")]
[Description("FTP address")]
public string Address { get; init; }
///
/// Gets the FTP port.
///
[Argument(default, "ftp-port")]
[EnvironmentVariable("FTP_PORT")]
[Description("FTP port")]
[Range(1, 65535)]
public int Port { get; init; } = 21;
///
/// Gets the FTP encryption mode.
///
[Argument(default, "ftp-encryption-mode")]
[EnvironmentVariable("FTP_ENCRYPTION_MODE")]
[Description("FTP encryption mode; none, implicit, explicit, auto")]
[Enum(typeof(FtpEncryptionMode))]
public string EncryptionMode { get; init; } = FtpEncryptionMode.Auto.ToString().ToLowerInvariant();
///
/// Gets a value indicating whether FTP certificate errors should be ignored.
///
[Argument(default, "ftp-ignore-certificate-errors")]
[EnvironmentVariable("FTP_IGNORE_CERTIFICATE_ERRORS")]
[Description("ignore FTP certificate errors")]
public bool IgnoreCertificateErrors { get; init; } = false;
///
/// Gets the FTP username.
///
[Argument(default, "ftp-username")]
[EnvironmentVariable("FTP_USERNAME")]
[Description("FTP username")]
public string Username { get; init; }
///
/// Gets the FTP password.
///
[Argument(default, "ftp-password")]
[EnvironmentVariable("FTP_PASSWORD")]
[Description("FTP password")]
[Secret]
public string Password { get; init; }
///
/// Gets the remote path for uploads.
///
[Argument(default, "ftp-remote-path")]
[EnvironmentVariable("FTP_REMOTE_PATH")]
[Description("remote path for FTP uploads")]
public string RemotePath { get; init; } = "/";
///
/// Gets a value indicating whether existing files should be overwritten.
///
[Argument(default, "ftp-overwrite-existing")]
[EnvironmentVariable("FTP_OVERWRITE_EXISTING")]
[Description("overwrite existing files when uploading to FTP")]
public bool OverwriteExisting { get; init; } = true;
///
/// Gets the connection timeout value, in milliseconds.
///
[Argument(default, "ftp-connection-timeout")]
[EnvironmentVariable("FTP_CONNECTION_TIMEOUT")]
[Description("FTP connection timeout, in milliseconds")]
[Range(0, int.MaxValue)]
public int ConnectionTimeout { get; init; } = 5000;
///
/// Gets the number of times failing uploads will be retried.
///
[Argument(default, "ftp-retry-attempts")]
[EnvironmentVariable("FTP_RETRY_ATTEMPTS")]
[Description("number of times failing FTP uploads will be retried")]
[Range(0, 5)]
public int RetryAttempts { get; init; } = 3;
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (Enabled && string.IsNullOrWhiteSpace(Address))
{
results.Add(new ValidationResult($"The Enabled field is true, but no Address has been specified."));
}
return results;
}
}
///
/// Pushbullet options.
///
public class PushbulletOptions : IValidatableObject
{
///
/// Gets a value indicating whether the Pushbullet integration is enabled.
///
[Argument(default, "pushbullet")]
[EnvironmentVariable("PUSHBULLET")]
[Description("enable Pushbullet integration")]
public bool Enabled { get; init; } = false;
///
/// Gets the Pushbullet API access token.
///
[Argument(default, "pushbullet-token")]
[EnvironmentVariable("PUSHBULLET_ACCESS_TOKEN")]
[Description("Pushbullet access token")]
[Secret]
public string AccessToken { get; init; }
///
/// Gets the prefix for Pushbullet notification titles.
///
[Argument(default, "pushbullet-prefix")]
[EnvironmentVariable("PUSHBULLET_NOTIFICATION_PREFIX")]
[Description("prefix for Pushbullet notification titles")]
public string NotificationPrefix { get; init; } = "From slskd:";
///
/// Gets a value indicating whether a Pushbullet notification should be sent when a private message is received.
///
[Argument(default, "pushbullet-notify-on-pm")]
[EnvironmentVariable("PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE")]
[Description("send Pushbullet notifications when private messages are received")]
public bool NotifyOnPrivateMessage { get; init; } = true;
///
/// Gets a value indicating whether a Pushbullet notification should be sent when the currently logged
/// in user's username is mentioned in a room.
///
[Argument(default, "pushbullet-notify-on-room-mention")]
[EnvironmentVariable("PUSHBULLET_NOTIFY_ON_ROOM_MENTION")]
[Description("send Pushbullet notifications when your username is mentioned in a room")]
public bool NotifyOnRoomMention { get; init; } = true;
///
/// Gets the number of times failing Pushbullet notifications will be retried.
///
[Argument(default, "pushbullet-retry-attempts")]
[EnvironmentVariable("PUSHBULLET_RETRY_ATTEMPTS")]
[Description("number of times failing Pushbullet notifications will be retried")]
[Range(0, 5)]
public int RetryAttempts { get; init; } = 3;
///
/// Gets the cooldown time for Pushbullet notifications, in milliseconds.
///
[Argument(default, "pushbullet-cooldown")]
[EnvironmentVariable("PUSHBULLET_COOLDOWN_TIME")]
[Description("cooldown time for Pushbullet notifications, in milliseconds")]
public int CooldownTime { get; init; } = 900000; // 15 minutes
///
/// Extended validation.
///
///
///
public IEnumerable Validate(ValidationContext validationContext)
{
var results = new List();
if (Enabled && string.IsNullOrWhiteSpace(AccessToken))
{
results.Add(new ValidationResult($"The Enabled field is true, but no AccessToken has been specified."));
}
return results;
}
}
}
}
}