aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common
diff options
context:
space:
mode:
Diffstat (limited to 'src/slskd/Common')
-rw-r--r--src/slskd/Common/Configuration/CommandLineArguments.cs666
-rw-r--r--src/slskd/Common/Configuration/CommandLineConfigurationSource.cs172
-rw-r--r--src/slskd/Common/Configuration/ConfigurationExtensions.cs14
-rw-r--r--src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs145
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs166
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariables.cs185
-rw-r--r--src/slskd/Common/Configuration/YamlConfigurationSource.cs94
-rw-r--r--src/slskd/Common/Cryptography/PBKDF2.cs26
-rw-r--r--src/slskd/Common/Cryptography/Pbkdf2.cs43
-rw-r--r--src/slskd/Common/Cryptography/X509.cs40
-rw-r--r--src/slskd/Common/Extensions.cs119
-rw-r--r--src/slskd/Common/ISharedFileCache.cs34
-rw-r--r--src/slskd/Common/SharedFileCache.cs158
13 files changed, 713 insertions, 1149 deletions
diff --git a/src/slskd/Common/Configuration/CommandLineArguments.cs b/src/slskd/Common/Configuration/CommandLineArguments.cs
deleted file mode 100644
index 491965e7..00000000
--- a/src/slskd/Common/Configuration/CommandLineArguments.cs
+++ /dev/null
@@ -1,666 +0,0 @@
-namespace slskd.Configuration
-{
- using System;
- using System.Collections;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Text.RegularExpressions;
-
- /// <summary>
- /// Provides extension method(s) for the CommandLineArguments namespace.
- /// </summary>
- public static class CommandLineArgumentsExtensions
- {
- /// <summary>
- /// Gets the DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>.
- /// </summary>
- /// <param name="caller">The name of the calling method for which the DeclaringType is to be fetched.</param>
- /// <returns>The DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>.</returns>
- internal static Type GetCallingType(string caller)
- {
- var callingMethod = new StackTrace().GetFrames()
- .Select(f => f.GetMethod())
- .FirstOrDefault(m => m.Name == caller);
-
- if (callingMethod == default)
- {
- throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
- }
-
- return callingMethod.DeclaringType;
- }
-
- /// <summary>
- /// Removes the outermost pair of enclosing quotes.
- /// </summary>
- /// <param name="value">The string to trim.</param>
- /// <returns>The trimmed string.</returns>
- internal static string TrimOuterQuotes(this string value)
- {
- if (value.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase))
- {
- value = value.Trim('"');
- }
- else if (value.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("'", StringComparison.InvariantCultureIgnoreCase))
- {
- value = value.Trim('\'');
- }
-
- return value;
- }
- }
-
- /// <summary>
- /// Indicates that the property is to be used as a target for automatic population of values from command line arguments
- /// when invoking the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class CommandLineArgumentAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="CommandLineArgumentAttribute"/> class.
- /// </summary>
- /// <param name="shortName">The short name of the argument, represented as a single character.</param>
- /// <param name="longName">The long name of the argument.</param>
- /// <param name="helpText">The help text of the argument.</param>
- public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null)
- {
- ShortName = shortName;
- LongName = longName;
- HelpText = helpText;
- }
-
- /// <summary>
- /// Gets or sets the help text of the argument.
- /// </summary>
- public string HelpText { get; set; }
-
- /// <summary>
- /// Gets or sets the long name of the argument.
- /// </summary>
- public string LongName { get; set; }
-
- /// <summary>
- /// Gets or sets the short name of the argument.
- /// </summary>
- public char ShortName { get; set; }
- }
-
- /// <summary>
- /// Encapsulates argument names and help text.
- /// </summary>
- public class ArgumentInfo
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ArgumentInfo"/> class.
- /// </summary>
- /// <param name="shortName">The short name of the argument.</param>
- /// <param name="longName">The long name of the argument.</param>
- /// <param name="helpText">The help text for the argument.</param>
- /// <param name="property">The property with which the argument is associated.</param>
- public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property)
- {
- ShortName = shortName;
- LongName = longName;
- HelpText = helpText;
- Property = property;
- }
-
- /// <summary>
- /// Gets the help text for the argument.
- /// </summary>
- public string HelpText { get; }
-
- /// <summary>
- /// Gets a value indicating whether the argument backing Type is a collection.
- /// </summary>
- public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>));
-
- /// <summary>
- /// Gets the long name of the argument.
- /// </summary>
- public string LongName { get; }
-
- /// <summary>
- /// Gets the property with which the argument is associated.
- /// </summary>
- public PropertyInfo Property { get; }
-
- /// <summary>
- /// Gets the short name of the argument.
- /// </summary>
- public char ShortName { get; }
- }
-
- /// <summary>
- /// Provides static methods used to retrieve the command line arguments and operands with which the application was
- /// started, as well as a Type to contain them.
- /// </summary>
- public class CommandLineArguments
- {
- /// <summary>
- /// The regular expression with which to parse the command line string.
- /// </summary>
- private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to parse the command line string, including the ability to specify forward slashes.
- /// </summary>
- private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to parse argument-value groups.
- /// </summary>
- private const string GroupRegEx = "^-[^-]+";
-
- /// <summary>
- /// The regular expression with which to parse strings strictly containing operands.
- /// </summary>
- private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to split the command line string explicitly among argument/value pairs and
- /// operands, and strictly operands.
- /// </summary>
- /// <remarks>
- /// This regular expression effectively splits a string into two parts; the part before the first "--", and the part
- /// after. Instances of "--" not surrounded by a word boundary and those enclosed in quotes are ignored.
- /// </remarks>
- private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)";
-
- private CommandLineArguments(string commandLineString, List<KeyValuePair<string, string>> argumentList, Dictionary<string, object> argumentDictionary, List<string> operandList, Type targetType = null)
- {
- CommandLineString = commandLineString;
- ArgumentList = argumentList;
- ArgumentDictionary = argumentDictionary;
- OperandList = operandList;
- TargetType = targetType;
- }
-
- /// <summary>
- /// Gets or sets a value indicating whether forward slashes are processed as argument delimiters.
- /// </summary>
- public static bool EnableForwardSlash { get; set; } = false;
-
- /// <summary>
- /// Gets a dictionary containing the arguments and values specified in the command line arguments with which the
- /// application was started.
- /// </summary>
- /// <remarks>
- /// This dictionary contains argument key/value pairs compiled from the <see cref="ArgumentList"/> and checked against
- /// the <see cref="TargetType"/> to combine duplicated pairs into lists where the backing property is a collection, and
- /// to overwrite where the backing property is not a collection.
- /// </remarks>
- public Dictionary<string, object> ArgumentDictionary { get; }
-
- /// <summary>
- /// Gets the list of arguments specified in the command line arguments with which the application was started.
- /// </summary>
- /// <remarks>
- /// This list contains each argument key/value pair as supplied in the original string, preserving the original order
- /// and any duplicated pairs.
- /// </remarks>
- public List<KeyValuePair<string, string>> ArgumentList { get; }
-
- /// <summary>
- /// Gets the command line string from which the arguments were parsed.
- /// </summary>
- public string CommandLineString { get; }
-
- /// <summary>
- /// Gets a list containing the operands specified in the command line arguments with which the application was started.
- /// </summary>
- public List<string> OperandList { get; private set; }
-
- /// <summary>
- /// Gets the target Type, if applicable.
- /// </summary>
- public Type TargetType { get; }
-
- private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash;
-
- /// <summary>
- /// Gets the argument value corresponding to the specified <paramref name="index"/>.
- /// </summary>
- /// <param name="index">The index for which the value is to be retrieved.</param>
- /// <returns>The argument value corresponding to the specified index.</returns>
- public object this[int index]
- {
- get
- {
- return ArgumentList[index].Value;
- }
- }
-
- /// <summary>
- /// Gets the argument value corresponding to the specified <paramref name="key"/> from the
- /// <see cref="ArgumentDictionary"/> property.
- /// </summary>
- /// <param name="key">The key for which the value is to be retrieved.</param>
- /// <returns>The argument value corresponding to the specified key.</returns>
- public object this[string key]
- {
- get
- {
- return ArgumentDictionary[key];
- }
- }
-
- /// <summary>
- /// Retrieves a collection of <see cref="ArgumentInfo"/> gathered from properties in the target <paramref name="type"/>
- /// marked with the <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> along with the short and long names and help text.
- /// </summary>
- /// <param name="type">The <see cref="Type"/> for which the matching properties are to be retrieived.</param>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- /// <returns>The retrieved collection of <see cref="ArgumentInfo"/>.</returns>
- public static IEnumerable<ArgumentInfo> GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default)
- {
- type ??= CommandLineArgumentsExtensions.GetCallingType(caller);
- var retVal = new List<ArgumentInfo>();
-
- foreach (PropertyInfo property in GetArgumentProperties(type).Values.Distinct())
- {
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name);
-
- if (attribute != default(CustomAttributeData))
- {
- retVal.Add(new ArgumentInfo(
- shortName: (char)attribute.ConstructorArguments[0].Value,
- longName: (string)attribute.ConstructorArguments[1].Value,
- helpText: (string)attribute.ConstructorArguments[2].Value,
- property: property));
- }
- }
-
- return retVal;
- }
-
- /// <summary>
- /// Returns a dictionary containing the values specified in the command line arguments with which the application was
- /// started, keyed by argument name.
- /// </summary>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="type">The <see cref="Type"/> for which the command line string is to be parsed.</param>
- /// <returns>
- /// The dictionary containing the arguments and values specified in the command line arguments with which the
- /// application was started.
- /// </returns>
- public static CommandLineArguments Parse(string commandLineString = default, Type type = null)
- {
- commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString;
-
- List<KeyValuePair<string, string>> argumentList;
- List<string> operandList;
-
- // use the strict operand regular expression to test for/extract the two halves of the string, if the operator is used.
- MatchCollection matches = Regex.Matches(commandLineString, StrictOperandSplitRegEx);
-
- // if there is a match, the string contains the strict operand delimiter. parse the first and second matches accordingly.
- if (matches.Count > 0)
- {
- // the first group of the first match will contain everything in the string prior to the strict operand delimiter,
- // so extract the argument key/value pairs and list of operands from that string.
- argumentList = GetArgumentList(matches[0].Groups[1].Value);
- operandList = GetOperandList(matches[0].Groups[1].Value);
-
- // the first group of the second match will contain everything in the string after the strict operand delimiter, so
- // extract the operands from that string using the strict method.
- if (!string.IsNullOrEmpty(matches[0].Groups[3].Value))
- {
- List<string> operandListStrict = GetOperandListStrict(matches[0].Groups[3].Value);
- operandList.AddRange(operandListStrict);
- }
- }
- else
- {
- argumentList = GetArgumentList(commandLineString);
- operandList = GetOperandList(commandLineString);
- }
-
- var argumentDictionary = GetArgumentDictionary(argumentList, type);
- return new CommandLineArguments(commandLineString, argumentList, argumentDictionary, operandList, type);
- }
-
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line
- /// arguments, if present.
- /// </summary>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- public static void Populate(string commandLineString = default, bool clearExistingValues = true, [CallerMemberName] string caller = default)
- {
- var type = CommandLineArgumentsExtensions.GetCallingType(caller);
- Populate(type, Parse(commandLineString, type), clearExistingValues);
- }
-
- /// <summary>
- /// Populates the properties in the specified Type marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line
- /// arguments, if present.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of command line arguments are to be populated.
- /// </param>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true)
- {
- Populate(type, Parse(commandLineString, type), clearExistingValues);
- }
-
- /// <summary>
- /// Populates the properties in the specified Type marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the specified argument
- /// dictionary, if present. All property values are set to null at the start of the routine.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of command line arguments are to be populated.
- /// </param>
- /// <param name="arguments">
- /// The Arguments object containing the dictionary containing the argument-value pairs with which the destination
- /// properties should be populated and the list of operands.
- /// </param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- public static void Populate(Type type, CommandLineArguments arguments, bool clearExistingValues = true)
- {
- // fetch any properties in the specified type marked with the ArgumentAttribute attribute and clear them
- Dictionary<string, PropertyInfo> properties = GetArgumentProperties(type);
-
- if (clearExistingValues)
- {
- ClearProperties(properties);
- }
-
- foreach (string propertyName in properties.Keys)
- {
- // if the argument dictionary contains a matching argument
- if (arguments.ArgumentDictionary.ContainsKey(propertyName))
- {
- // retrieve the property and type
- PropertyInfo property = properties[propertyName];
- Type propertyType = property.PropertyType;
-
- // retrieve the value from the argument dictionary
- object value = arguments.ArgumentDictionary[propertyName];
-
- object convertedValue;
-
- // if the type of the property is bool and the argument value is empty set the property value to true,
- // indicating the argument is present
- if (propertyType == typeof(bool))
- {
- convertedValue = true;
-
- // if a value is specified, a bool flag was followed by an operand and the parser interpreted this as key
- // value pair because it wasn't aware the flag was backed by a bool. remove the argument from the original
- // string and re-parse operands from it to preserve order.
- if (!string.IsNullOrEmpty(value.ToString()))
- {
- var arg = Regex.Matches(arguments.CommandLineString, "(?:[-]{1,2}|\\/)" + propertyName)[0].Value;
- arguments.OperandList = GetOperandList(arguments.CommandLineString.Replace(arg, string.Empty));
- }
- }
- else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
- {
- convertedValue = value;
-
- // next, create a list with the same type as the target property
- Type valueType;
-
- if (propertyType.IsArray)
- {
- valueType = propertyType.GetElementType();
- }
- else
- {
- valueType = propertyType.GetGenericArguments()[0];
- }
-
- // create a list to store converted values
- Type valueListType = typeof(List<>).MakeGenericType(valueType);
- var valueList = (IList)Activator.CreateInstance(valueListType);
-
- // populate the list
- foreach (object v in (List<object>)convertedValue)
- {
- valueList.Add(ChangeType(v, propertyName, valueType));
- }
-
- // if the target property is an array, create one and populate it from the list this is surprisingly
- // difficult here because we created the source list with the Activator and ToArray() won't work easily.
- if (propertyType.IsArray)
- {
- var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count);
-
- for (int i = 0; i < valueArray.Length; i++)
- {
- valueArray.SetValue(valueList[i], i);
- }
-
- convertedValue = valueArray;
- }
- else
- {
- convertedValue = valueList;
- }
- }
- else
- {
- convertedValue = ChangeType(value, propertyName, propertyType);
- }
-
- // set the target properties' value to the converted value from the argument string
- property.SetValue(null, convertedValue);
- }
- }
-
- PropertyInfo operandsProperty = GetOperandsProperty(type);
-
- // check to ensure the target class has a property marked with the Operands attribute; if not GetOperandsProperty()
- // will return null.
- if (operandsProperty != default)
- {
- if (operandsProperty.PropertyType.IsAssignableFrom(typeof(List<string>)))
- {
- operandsProperty.SetValue(null, arguments.OperandList);
- }
- else
- {
- operandsProperty.SetValue(null, arguments.OperandList.ToArray());
- }
- }
- }
-
- private static object ChangeType(object value, string argument, Type toType)
- {
- try
- {
- if (toType.IsEnum)
- {
- return Enum.Parse(toType, (string)value, true);
- }
-
- return Convert.ChangeType(value, toType, CultureInfo.InvariantCulture);
- }
- catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
- {
- string message = $"Specified value '{value}' for argument '{argument}' (expected type: {toType}). ";
- message += "See inner exception for details.";
-
- throw new ArgumentException(message, ex);
- }
- }
-
- private static void ClearProperties(Dictionary<string, PropertyInfo> properties)
- {
- foreach (string key in properties.Keys)
- {
- properties[key].SetValue(null, null);
- }
- }
-
- private static Dictionary<string, object> GetArgumentDictionary(List<KeyValuePair<string, string>> argumentList, Type targetType = null)
- {
- var dict = new ConcurrentDictionary<string, object>();
- var argumentInfo = targetType == null ? new List<ArgumentInfo>() : GetArgumentInfo(targetType);
-
- foreach (var arg in argumentList)
- {
- var info = argumentInfo.SingleOrDefault(i => i.ShortName.ToString(CultureInfo.InvariantCulture) == arg.Key || i.LongName == arg.Key);
-
- if (info != default(ArgumentInfo))
- {
- bool added = false;
-
- foreach (var k in new[] { info.ShortName.ToString(CultureInfo.InvariantCulture), info.LongName })
- {
- if (dict.ContainsKey(k))
- {
- dict.AddOrUpdate(k, arg.Value, (key, existingValue) => info.IsCollection ? ((List<object>)existingValue).Concat(new[] { arg.Value }).ToList() : (object)arg.Value);
- added = true;
- break;
- }
- }
-
- if (!added)
- {
- dict.TryAdd(arg.Key, info.IsCollection ? new List<object>(new[] { arg.Value }) : (object)arg.Value);
- }
- }
- else
- {
- dict.AddOrUpdate(arg.Key, arg.Value, (key, existingValue) => arg.Value);
- }
- }
-
- return dict.ToDictionary(a => a.Key, a => a.Value);
- }
-
- private static List<KeyValuePair<string, string>> GetArgumentList(string commandLineString)
- {
- var argumentList = new List<KeyValuePair<string, string>>();
-
- foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx))
- {
- // the first match of the regular expression used to parse the string will contain the argument name, if one was matched.
- if (match.Groups[1].Value == default || string.IsNullOrEmpty(match.Groups[1].Value))
- {
- continue;
- }
-
- string fullMatch = match.Groups[0].Value;
- string argument = match.Groups[1].Value;
- string value = match.Groups[2].Value;
-
- value = value.TrimOuterQuotes();
-
- // check to see if the argument uses a single dash. if so, split the argument name into a char array and add each
- // to the list. if a value is specified, it belongs to the final character.
- if (Regex.IsMatch(fullMatch, GroupRegEx))
- {
- char[] charArray = argument.ToCharArray();
-
- // iterate over the characters backwards to more easily assign the value
- for (int i = 0; i < charArray.Length; i++)
- {
- argumentList.Add(new KeyValuePair<string, string>(charArray[i].ToString(CultureInfo.InvariantCulture), i == charArray.Length - 1 ? value : string.Empty));
- }
- }
- else
- {
- argumentList.Add(new KeyValuePair<string, string>(argument, value));
- }
- }
-
- return argumentList;
- }
-
- private static Dictionary<string, PropertyInfo> GetArgumentProperties(Type type)
- {
- Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
-
- foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
- {
- // attempt to fetch the ArgumentAttribute of the property
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name);
-
- // if found, extract the Name property and add it to the dictionary
- if (attribute != default(CustomAttributeData))
- {
- char shortName = (char)attribute.ConstructorArguments[0].Value;
- string longName = (string)attribute.ConstructorArguments[1].Value;
-
- if (!properties.ContainsKey(shortName.ToString(CultureInfo.InvariantCulture)) && !properties.ContainsKey(longName))
- {
- properties.Add(shortName.ToString(CultureInfo.InvariantCulture), property);
- properties.Add(longName, property);
- }
- }
- }
-
- return properties;
- }
-
- private static List<string> GetOperandList(string commandLineString)
- {
- List<string> operands = new List<string>();
-
- foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx))
- {
- // the 3rd match of the regular expression used to parse the string will contain the operand, if one was matched.
- if (match.Groups[3].Value == default || string.IsNullOrEmpty(match.Groups[3].Value))
- {
- continue;
- }
-
- string operand = match.Groups[3].Value;
-
- operands.Add(operand.TrimOuterQuotes());
- }
-
- return operands;
- }
-
- private static List<string> GetOperandListStrict(string operandListString)
- {
- List<string> operands = new List<string>();
-
- foreach (Match match in Regex.Matches(operandListString, OperandRegEx))
- {
- operands.Add(match.Groups[0].Value);
- }
-
- return operands;
- }
-
- private static PropertyInfo GetOperandsProperty(Type type)
- {
- PropertyInfo property = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
- .FirstOrDefault(p => p.CustomAttributes
- .Any(a => a.AttributeType.Name == typeof(OperandsAttribute).Name));
-
- if (property != default && property.PropertyType != typeof(string[]) && property.PropertyType != typeof(List<string>))
- {
- throw new InvalidCastException("The target for the Operands attribute must be of string[] or List<string>.");
- }
-
- return property;
- }
- }
-
- /// <summary>
- /// Indicates that the property is to be used as the target for automatic population of command line operands when invoking
- /// the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class OperandsAttribute : Attribute
- {
- }
-} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
index fb479fd4..6cf59808 100644
--- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
@@ -1,139 +1,157 @@
-namespace slskd.Configuration
+// <copyright file="CommandLineConfigurationSource.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.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines a command line argument mapping.
- /// </summary>
- public record CommandLineArgument(char ShortName, string LongName, Type Type, string Key, string Description = null);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
+ using Utility.CommandLine;
/// <summary>
/// Extension methods for adding <see cref="CommandLineConfigurationProvider"/>.
/// </summary>
- public static class CommandLineExtensions
+ public static class CommandLineConfigurationExtensions
{
/// <summary>
/// Adds a command line argument configuration soruce to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <param name="map">A list of command line argument mappings.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to map properties.</param>
/// <param name="commandLine">The command line string from which to parse arguments.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns></returns>
- public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable<CommandLineArgument> map, string commandLine = null, bool normalizeKey = true)
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddCommandLine(s =>
{
- s.Map = map;
+ s.TargetType = targetType;
s.CommandLine = commandLine ?? Environment.CommandLine;
- s.NormalizeKey = normalizeKey;
});
}
/// <summary>
/// Adds a command line argument configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action<CommandLineConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents command line arguments as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class CommandLineConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="CommandLineConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="CommandLineConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this);
-
- /// <summary>
- /// Gets or sets a list of command line argument mappings.
- /// </summary>
- public IEnumerable<CommandLineArgument> Map { get; set; }
-
- /// <summary>
- /// Gets or sets the command line string from which to parse arguments.
- /// </summary>
- public string CommandLine { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// A command line argument <see cref="ConfigurationProvider"/>.
/// </summary>
public class CommandLineConfigurationProvider : ConfigurationProvider
{
- private IEnumerable<CommandLineArgument> Map { get; set; }
- private string CommandLine { get; set; }
- private bool NormalizeKey { get; set; }
-
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="CommandLineConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public CommandLineConfigurationProvider(CommandLineConfigurationSource source)
+ public CommandLineConfigurationProvider(CommandLineConfigurationSource source)
{
- Map = source.Map;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
CommandLine = source.CommandLine;
- NormalizeKey = source.NormalizeKey;
}
+ private string CommandLine { get; set; }
+ private string Namespace { get; set; }
+ private Type TargetType { get; set; }
+
/// <summary>
- /// Parses command line arguments from the specified string and maps them to the specified keys.
+ /// Parses command line arguments from the specified string and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- var dictionary = CommandLineArguments.Parse(CommandLine).ArgumentDictionary;
+ var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary;
- foreach (CommandLineArgument item in Map)
+ void Map(Type type, string path)
{
- var (shortName, longName, type, key, _) = item;
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (NormalizeKey)
+ foreach (PropertyInfo property in props)
{
- key = key?.Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant();
- }
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute));
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
- if (string.IsNullOrEmpty(key))
- {
- continue;
- }
-
- var arguments = new[] { shortName.ToString(), longName }.Where(i => !string.IsNullOrEmpty(i));
-
- foreach (var argument in arguments)
- {
- if (dictionary.ContainsKey(argument))
+ if (attribute != default)
{
- var value = dictionary[argument].ToString();
+ var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString();
+ var longName = (string)attribute.ConstructorArguments[1].Value;
+ var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i));
- if (type == typeof(bool) && string.IsNullOrEmpty(value))
+ foreach (var argument in arguments)
{
- value = "true";
- }
+ if (dictionary.ContainsKey(argument))
+ {
+ var value = dictionary[argument].ToString();
- Data[item.Key] = value;
+ if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value))
+ {
+ value = "true";
+ }
+
+ Data[key] = value;
+ }
+ }
+ }
+ else
+ {
+ Map(property.PropertyType, key);
}
}
}
+
+ Map(TargetType, Namespace);
}
}
-}
+
+ /// <summary>
+ /// Represents command line arguments as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class CommandLineConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the command line string from which to parse arguments.
+ /// </summary>
+ public string CommandLine { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="CommandLineConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="CommandLineConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/ConfigurationExtensions.cs b/src/slskd/Common/Configuration/ConfigurationExtensions.cs
deleted file mode 100644
index 77b59700..00000000
--- a/src/slskd/Common/Configuration/ConfigurationExtensions.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-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 accc76c9..15cf4070 100644
--- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
@@ -1,14 +1,26 @@
-namespace slskd.Configuration
+// <copyright file="DefaultValueConfigurationSource.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.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines an default value mapping.
- /// </summary>
- public record DefaultValue(string Key, Type Type, object Default);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
/// <summary>
/// Extension methods for adding <see cref="DefaultValueConfigurationProvider"/>.
@@ -18,104 +30,107 @@
/// <summary>
/// Adds a default value configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="map">A list of default value mappings.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable<DefaultValue> map, bool normalizeKey = true)
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to load default values.</param>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddDefaultValues(s =>
{
- s.Map = map ?? Enumerable.Empty<DefaultValue>();
- s.NormalizeKey = normalizeKey;
+ s.TargetType = targetType;
});
}
/// <summary>
/// Adds a default value configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action<DefaultValueConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents default values as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class DefaultValueConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="DefaultValueConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="DefaultValueConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- return new DefaultValueConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a list of default value mappings.
- /// </summary>
- public IEnumerable<DefaultValue> Map { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// A default value <see cref="ConfigurationProvider"/>.
/// </summary>
public class DefaultValueConfigurationProvider : ConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="DefaultValueConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source)
+ public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source)
{
- Map = source.Map;
- NormalizeKey = source.NormalizeKey;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
}
- private IEnumerable<DefaultValue> Map { get; set; }
- private bool NormalizeKey { get; set; }
+ private string Namespace { get; set; }
+ private Type TargetType { get; set; }
/// <summary>
- /// Sets the keys specified in the map to the specified default values.
+ /// Loads default values from the specified <see cref="TargetType"/> and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- foreach (var item in Map)
+ void Map(Type type, string path)
{
- var (key, _, value) = item;
+ var defaults = Activator.CreateInstance(type);
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (NormalizeKey)
+ foreach (PropertyInfo property in props)
{
- key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant();
- }
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
- if (string.IsNullOrEmpty(key))
- {
- continue;
- }
+ if (property.PropertyType.Namespace.StartsWith(Namespace))
+ {
+ Map(property.PropertyType, key);
+ }
+ else
+ {
+ var value = property.GetValue(defaults);
- if (value == null)
- {
- continue;
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
+ }
}
-
- Data[item.Key] = value.ToString();
}
+
+ Map(TargetType, Namespace);
+ }
+ }
+
+ /// <summary>
+ /// Represents default values as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class DefaultValueConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="DefaultValueConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="DefaultValueConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new DefaultValueConfigurationProvider(this);
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
index a18faebc..9a09d4e1 100644
--- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
@@ -1,14 +1,27 @@
-namespace slskd.Configuration
+// <copyright file="EnvironmentVariableConfigurationSource.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.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines an environment variable mapping.
- /// </summary>
- public record EnvironmentVariable(string Name, Type Type, string Key, string Description = null);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
+ using Utility.EnvironmentVariables;
/// <summary>
/// Extension methods for adding <see cref="EnvironmentVariableConfigurationProvider"/>.
@@ -18,120 +31,121 @@
/// <summary>
/// Adds an environment variable configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="map">A list of environment variable mappings.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to map properties.</param>
/// <param name="prefix">A prefix to prepend to all variable names.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable<EnvironmentVariable> map, string prefix = null, bool normalizeKey = true)
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddEnvironmentVariables(s =>
{
- s.Map = map ?? Enumerable.Empty<EnvironmentVariable>();
+ s.TargetType = targetType;
s.Prefix = prefix ?? string.Empty;
- s.NormalizeKey = normalizeKey;
});
}
/// <summary>
/// Adds an enviroment variable configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariableConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents environment variables as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class EnvironmentVariableConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="EnvironmentVariableConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="EnvironmentVariableConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- return new EnvironmentVariableConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a list of enviroment variable mappings.
- /// </summary>
- public IEnumerable<EnvironmentVariable> Map { get; set; }
-
- /// <summary>
- /// Gets or sets a prefix to prepend to all variable names.
- /// </summary>
- public string Prefix { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// An enviroment variable <see cref="ConfigurationProvider"/>.
/// </summary>
public class EnvironmentVariableConfigurationProvider : ConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="EnvironmentVariableConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source)
+ public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source)
{
- Map = source.Map;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
Prefix = source.Prefix;
- NormalizeKey = source.NormalizeKey;
}
- private IEnumerable<EnvironmentVariable> Map { get; set; }
- private bool NormalizeKey { get; set; }
+ private Type TargetType { get; set; }
+ private string Namespace { get; set; }
private string Prefix { get; set; }
/// <summary>
- /// Loads environment variables and maps them to the specified keys.
+ /// Loads environment variables and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- foreach (var item in Map)
+ void Map(Type type, string path)
{
- var (name, type, key, _) = item;
-
- if (NormalizeKey)
- {
- key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant();
- }
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name))
+ foreach (PropertyInfo property in props)
{
- continue;
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute));
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
+
+ if (attribute != default)
+ {
+ var name = (string)attribute.ConstructorArguments[0].Value;
+
+ if (!string.IsNullOrEmpty(name))
+ {
+ var value = Environment.GetEnvironmentVariable(Prefix + name);
+
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
+ }
+ }
+ else
+ {
+ Map(property.PropertyType, key);
+ }
}
+ }
- var value = Environment.GetEnvironmentVariable(Prefix + name);
+ Map(TargetType, Namespace);
+ }
+ }
- if (string.IsNullOrEmpty(value))
- {
- continue;
- }
+ /// <summary>
+ /// Represents environment variables as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class EnvironmentVariableConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
- if (type == typeof(bool))
- {
- value = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) ? value : "false";
- }
+ /// <summary>
+ /// Gets or sets a prefix to prepend to all variable names.
+ /// </summary>
+ public string Prefix { get; set; }
- Data[item.Key] = value;
- }
+ /// <summary>
+ /// Builds the <see cref="EnvironmentVariableConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="EnvironmentVariableConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new EnvironmentVariableConfigurationProvider(this);
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/EnvironmentVariables.cs b/src/slskd/Common/Configuration/EnvironmentVariables.cs
deleted file mode 100644
index 0ccda3cb..00000000
--- a/src/slskd/Common/Configuration/EnvironmentVariables.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-namespace slskd.Configuration
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.CompilerServices;
-
- /// <summary>
- /// Indicates that the property is to be used as a target for automatic population of values from environment variables
- /// when invoking the <see cref="EnvironmentVariables.Populate(Type, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class EnvironmentVariableAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="EnvironmentVariableAttribute"/> class.
- /// </summary>
- /// <param name="name">The name of the environment variable</param>
- public EnvironmentVariableAttribute(string name)
- {
- Name = name;
- }
-
- /// <summary>
- /// Gets or sets the name of the environment variable.
- /// </summary>
- public string Name { get; set; }
- }
-
- /// <summary>
- /// Provides static methods used to populate properties from environment variable values.
- /// </summary>
- public static class EnvironmentVariables
- {
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables.
- /// </summary>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- /// <param name="prefix">The optional prefix for variable names.</param>
- public static void Populate(string prefix = null, [CallerMemberName] string caller = default)
- {
- Populate(GetCallingType(caller), prefix);
- }
-
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of environment variables are to be populated.
- /// </param>
- /// <param name="prefix">The optional prefix for variable names.</param>
- public static void Populate(Type type, string prefix = "")
- {
- prefix ??= string.Empty;
-
- var targetProperties = GetTargetProperties(type);
-
- foreach (var property in targetProperties)
- {
- var propertyType = property.Value.PropertyType;
-
- string value = Environment.GetEnvironmentVariable(prefix + property.Key);
-
- if (string.IsNullOrEmpty(value))
- {
- continue;
- }
-
- object convertedValue;
-
- if (propertyType == typeof(bool))
- {
- convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false;
- }
- else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
- {
- Type valueType;
-
- if (propertyType.IsArray)
- {
- valueType = propertyType.GetElementType();
- }
- else
- {
- valueType = propertyType.GetGenericArguments()[0];
- }
-
- // create a list to store converted values
- Type valueListType = typeof(List<>).MakeGenericType(valueType);
- var valueList = (IList)Activator.CreateInstance(valueListType);
-
- // populate the list
- foreach (object v in value.Split(',').Select(s => s.Trim()))
- {
- valueList.Add(ChangeType(v, property.Key, valueType));
- }
-
- if (propertyType.IsArray)
- {
- var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count);
-
- for (int i = 0; i < valueArray.Length; i++)
- {
- valueArray.SetValue(valueList[i], i);
- }
-
- convertedValue = valueArray;
- }
- else
- {
- convertedValue = valueList;
- }
- }
- else
- {
- convertedValue = ChangeType(value, property.Key, property.Value.PropertyType);
- }
-
- property.Value.SetValue(null, convertedValue);
- }
- }
-
- private static Type GetCallingType(string caller)
- {
- var callingMethod = new StackTrace().GetFrames()
- .Select(f => f.GetMethod())
- .FirstOrDefault(m => m.Name == caller);
-
- if (callingMethod == default)
- {
- throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
- }
-
- return callingMethod.DeclaringType;
- }
-
- private static object ChangeType(object value, string name, Type type)
- {
- try
- {
- if (type.IsEnum)
- {
- return Enum.Parse(type, (string)value, true);
- }
-
- return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
- }
- catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
- {
- string message = $"Failed to convert value '{value}' to target type {type}";
- throw new ArgumentException(message, name, ex);
- }
- }
-
- private static Dictionary<string, PropertyInfo> GetTargetProperties(Type type)
- {
- Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
-
- foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
- {
- // attempt to fetch the ArgumentAttribute of the property
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(EnvironmentVariableAttribute).Name);
-
- // if found, extract the Name property and add it to the dictionary
- if (attribute != default(CustomAttributeData))
- {
- string name = (string)attribute.ConstructorArguments[0].Value;
-
- if (!properties.ContainsKey(name))
- {
- properties.Add(name, property);
- }
- }
- }
-
- return properties;
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
index 27ca6fea..332df647 100644
--- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
@@ -1,10 +1,27 @@
-namespace slskd.Configuration
+// <copyright file="YamlConfigurationSource.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.Configuration
{
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.FileProviders;
using System;
using System.IO;
using System.Linq;
+ using Microsoft.Extensions.Configuration;
+ using Microsoft.Extensions.FileProviders;
using YamlDotNet.Core;
using YamlDotNet.RepresentationModel;
@@ -16,13 +33,16 @@
/// <summary>
/// Adds a YAML configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="path">Path relative to the base path stored in
- /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add .</param>
+ /// <param name="path">
+ /// Path relative to the base path stored in <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.
+ /// </param>
/// <param name="optional">Whether the file is optional.</param>
/// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
- /// <param name="normalizeKeys">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param>
+ /// <param name="normalizeKeys">
+ /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
+ /// </param>
+ /// <param name="provider">The updated <see cref="IFileProvider"/> to use to access the file.</param>
/// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null)
{
@@ -50,52 +70,30 @@
/// <summary>
/// Adds a YAML configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action<YamlConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents a YAML file as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class YamlConfigurationSource : FileConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="YamlConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="YamlConfigurationProvider"/></returns>
- public override IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- EnsureDefaults(builder);
- return new YamlConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKeys { get; set; }
- }
-
- /// <summary>
/// A YAML file based <see cref="FileConfigurationProvider"/>.
/// </summary>
public class YamlConfigurationProvider : FileConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="YamlConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public YamlConfigurationProvider(YamlConfigurationSource source)
- : base(source)
+ public YamlConfigurationProvider(YamlConfigurationSource source)
+ : base(source)
{
NormalizeKeys = source.NormalizeKeys;
}
private bool NormalizeKeys { get; set; }
- private string[] NullValues { get; } = new[] { "~", "null", "" };
+ private string[] NullValues { get; } = new[] { "~", "null", string.Empty };
/// <summary>
/// Loads the YAML data from a stream.
@@ -157,4 +155,26 @@
}
}
}
-}
+
+ /// <summary>
+ /// Represents a YAML file as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class YamlConfigurationSource : FileConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
+ /// </summary>
+ public bool NormalizeKeys { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="YamlConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="YamlConfigurationProvider"/>.</returns>
+ public override IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ EnsureDefaults(builder);
+ return new YamlConfigurationProvider(this);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Cryptography/PBKDF2.cs b/src/slskd/Common/Cryptography/PBKDF2.cs
deleted file mode 100644
index 4b8b83e4..00000000
--- a/src/slskd/Common/Cryptography/PBKDF2.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-namespace slskd.Security
-{
- using Microsoft.AspNetCore.Cryptography.KeyDerivation;
- using System.Security.Cryptography;
-
- /// <summary>
- /// PBKDF2/RFC 2898 implementation
- /// </summary>
- public static class PBKDF2
- {
- /// <summary>
- /// Gets a 256 bit (32 byte) key derived from the specified <paramref name="password"/> using PBKDF2/RFC 2898
- /// </summary>
- /// <param name="password"></param>
- /// <returns></returns>
- public static byte[] GetKey(string password)
- {
- byte[] salt = new byte[16];
- int iterations = 1000;
-
- using var rng = RandomNumberGenerator.Create();
- rng.GetBytes(salt);
- return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
- }
- }
-}
diff --git a/src/slskd/Common/Cryptography/Pbkdf2.cs b/src/slskd/Common/Cryptography/Pbkdf2.cs
new file mode 100644
index 00000000..f6509a73
--- /dev/null
+++ b/src/slskd/Common/Cryptography/Pbkdf2.cs
@@ -0,0 +1,43 @@
+// <copyright file="Pbkdf2.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.Security
+{
+ using System.Security.Cryptography;
+ using Microsoft.AspNetCore.Cryptography.KeyDerivation;
+
+ /// <summary>
+ /// PBKDF2/RFC 2898 utility methods.
+ /// </summary>
+ public static class Pbkdf2
+ {
+ /// <summary>
+ /// Gets a 256 bit (32 byte) key derived from the specified <paramref name="password"/> using PBKDF2/RFC 2898.
+ /// </summary>
+ /// <param name="password">The password from which to derive the key.</param>
+ /// <returns>The derived key.</returns>
+ public static byte[] GetKey(string password)
+ {
+ byte[] salt = new byte[16];
+ int iterations = 1000;
+
+ using var rng = RandomNumberGenerator.Create();
+ rng.GetBytes(salt);
+ return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
+ }
+ }
+}
diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs
index 19b1c4ba..95743cc0 100644
--- a/src/slskd/Common/Cryptography/X509.cs
+++ b/src/slskd/Common/Cryptography/X509.cs
@@ -1,11 +1,38 @@
-namespace slskd.Common.Cryptography
+// <copyright file="X509.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.Common.Cryptography
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
- public class X509
+ /// <summary>
+ /// X509 utility methods.
+ /// </summary>
+ public static class X509
{
+ /// <summary>
+ /// Generates an X509 certificate for the specified <paramref name="subject"/>.
+ /// </summary>
+ /// <param name="subject">The certificate subject.</param>
+ /// <param name="password">The optional password for the certificate.</param>
+ /// <param name="x509KeyStorageFlags">The optional key storage flags for the certificate.</param>
+ /// <returns>The generated certificate.</returns>
public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet)
{
password ??= Guid.NewGuid().ToString();
@@ -25,6 +52,13 @@
return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
}
+ /// <summary>
+ /// Validates an X509 certificate given a PFX <paramref name="fileName"/> and optional <paramref name="password"/>.
+ /// </summary>
+ /// <param name="fileName">The path to the PFX certificate file to validate.</param>
+ /// <param name="password">The optional password for the certificate.</param>
+ /// <param name="result">The error message, if the certificate is invalid.</param>
+ /// <returns>A value indicating whether the certificate is valid.</returns>
public static bool TryValidate(string fileName, string password, out string result)
{
result = null;
@@ -41,4 +75,4 @@
}
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
new file mode 100644
index 00000000..b7243549
--- /dev/null
+++ b/src/slskd/Common/Extensions.cs
@@ -0,0 +1,119 @@
+// <copyright file="Extensions.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using slskd.Validation;
+
+ /// <summary>
+ /// Extensions.
+ /// </summary>
+ public static class Extensions
+ {
+ /// <summary>
+ /// Returns the directory from the given path, regardless of separator format.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <returns>The directory.</returns>
+ public static string DirectoryName(this string path)
+ {
+ var separator = path.Contains('\\') ? '\\' : '/';
+ var parts = path.Split(separator);
+ return string.Join(separator, parts.Take(parts.Length - 1));
+ }
+
+ /// <summary>
+ /// Returns the SHA1 hash of the given string.
+ /// </summary>
+ /// <param name="str">The string to hash.</param>
+ /// <returns>The hash.</returns>
+ public static string Sha1(this string str)
+ {
+ using var sha1 = new SHA1Managed();
+ return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
+ }
+
+ /// <summary>
+ /// Formats byte to nearest size (KB, MB, etc.)
+ /// </summary>
+ /// <param name="value">The value to format.</param>
+ /// <param name="decimalPlaces">The number of decimal places to include.</param>
+ /// <returns>The formatted string.</returns>
+ public static string SizeSuffix(this double value, int decimalPlaces = 1)
+ {
+ string[] sizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
+
+ if (value < 0) { return "-" + SizeSuffix(-value); }
+ if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
+
+ // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
+ int mag = (int)Math.Log(value, 1024);
+
+ // 1L << (mag * 10) == 2 ^ (10 * mag) [i.e. the number of bytes in the unit corresponding to mag]
+ decimal adjustedSize = (decimal)value / (1L << (mag * 10));
+
+ // make adjustment when the value is large enough that it would round up to 1000 or more
+ if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
+ {
+ mag += 1;
+ adjustedSize /= 1024;
+ }
+
+ return string.Format(
+ "{0:n" + decimalPlaces + "} {1}",
+ adjustedSize,
+ sizeSuffixes[mag]);
+ }
+
+ /// <summary>
+ /// Converts the given path to the local format (normalizes path separators).
+ /// </summary>
+ /// <param name="path">The path to convert.</param>
+ /// <returns>The converted path.</returns>
+ public static string ToLocalOSPath(this string path)
+ {
+ return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
+ }
+
+ /// <summary>
+ /// Validates options.
+ /// </summary>
+ /// <param name="options">The options instance to validate.</param>
+ /// <param name="result">The result of the validation, if invalid.</param>
+ /// <returns>A value indicating whether the instance is valid.</returns>
+ 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;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/ISharedFileCache.cs b/src/slskd/Common/ISharedFileCache.cs
new file mode 100644
index 00000000..53070777
--- /dev/null
+++ b/src/slskd/Common/ISharedFileCache.cs
@@ -0,0 +1,34 @@
+// <copyright file="ISharedFileCache.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using Soulseek;
+
+ internal interface ISharedFileCache
+ {
+ string Directory { get; }
+ DateTime? LastFill { get; }
+ long TTL { get; }
+
+ void Fill();
+
+ IEnumerable<Soulseek.File> Search(SearchQuery query);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/SharedFileCache.cs b/src/slskd/Common/SharedFileCache.cs
new file mode 100644
index 00000000..208eab24
--- /dev/null
+++ b/src/slskd/Common/SharedFileCache.cs
@@ -0,0 +1,158 @@
+// <copyright file="SharedFileCache.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.IO;
+ using System.Linq;
+ using System.Threading;
+ using Microsoft.Data.Sqlite;
+ using Soulseek;
+
+ /// <summary>
+ /// Caches shared files.
+ /// </summary>
+ public class SharedFileCache : ISharedFileCache
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SharedFileCache"/> class.
+ /// </summary>
+ /// <param name="directory"></param>
+ /// <param name="ttl"></param>
+ public SharedFileCache(string directory, long ttl)
+ {
+ Directory = directory;
+ TTL = ttl;
+ }
+
+ public string Directory { get; }
+ private Dictionary<string, Soulseek.File> Files { get; set; }
+ public DateTime? LastFill { get; set; }
+ private SqliteConnection SQLite { get; set; }
+ private ReaderWriterLockSlim SyncRoot { get; } = new ReaderWriterLockSlim();
+ public long TTL { get; }
+
+ /// <summary>
+ /// Scans the configured <see cref="Directory"/> and fills the cache.
+ /// </summary>
+ public void Fill()
+ {
+ var sw = new Stopwatch();
+ sw.Start();
+
+ Console.WriteLine($"[SHARED FILE CACHE]: Refreshing...");
+
+ SyncRoot.EnterWriteLock();
+
+ try
+ {
+ CreateTable();
+
+ Files = System.IO.Directory.GetFiles(Directory, "*", SearchOption.AllDirectories)
+ .Select(f => new Soulseek.File(1, f, new FileInfo(f).Length, Path.GetExtension(f)))
+ .ToDictionary(f => f.Filename, f => f);
+
+ // potentially optimize with multi-valued insert
+ // https://stackoverflow.com/questions/16055566/insert-multiple-rows-in-sqlite
+ foreach (var file in Files)
+ {
+ InsertFilename(file.Key);
+ }
+ }
+ finally
+ {
+ SyncRoot.ExitWriteLock();
+ }
+
+ sw.Stop();
+
+ Console.WriteLine($"[SHARED FILE CACHE]: Refreshed in {sw.ElapsedMilliseconds}ms. Found {Files.Count} files.");
+ LastFill = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Searches the cache for files matching the specified <paramref name="query"/>.
+ /// </summary>
+ /// <param name="query"></param>
+ /// <returns></returns>
+ public IEnumerable<Soulseek.File> Search(SearchQuery query)
+ {
+ if (!LastFill.HasValue || LastFill.Value.AddMilliseconds(TTL) < DateTime.UtcNow)
+ {
+ Fill();
+ }
+
+ return QueryTable(query.Query);
+ }
+
+ private void CreateTable()
+ {
+ SQLite = new SqliteConnection("Data Source=:memory:");
+ SQLite.Open();
+
+ using var cmd = new SqliteCommand("CREATE VIRTUAL TABLE cache USING fts5(filename)", SQLite);
+ cmd.ExecuteNonQuery();
+ }
+
+ private void InsertFilename(string filename)
+ {
+ using var cmd = new SqliteCommand($"INSERT INTO cache(filename) VALUES('{filename.Replace("'", "''")}')", SQLite);
+ cmd.ExecuteNonQuery();
+ }
+
+ private IEnumerable<Soulseek.File> QueryTable(string text)
+ {
+ // sanitize the query string. there's probably more to it than this.
+ text = text
+ .Replace("/", " ")
+ .Replace("\\", " ")
+ .Replace(":", " ")
+ .Replace("\"", " ");
+
+ var query = $"SELECT * FROM cache WHERE cache MATCH '\"{text.Replace("'", "''")}\"'";
+
+ SyncRoot.EnterReadLock();
+
+ try
+ {
+ using var cmd = new SqliteCommand(query, SQLite);
+ var results = new List<string>();
+ var reader = cmd.ExecuteReader();
+
+ while (reader.Read())
+ {
+ results.Add(reader.GetString(0));
+ }
+
+ return results.Select(r => Files[r.Replace("''", "'")]);
+ }
+ catch (Exception ex)
+ {
+ // temporary error trap to refine substitution rules
+ Console.WriteLine($"[MALFORMED QUERY]: {query} ({ex.Message})");
+ return Enumerable.Empty<Soulseek.File>();
+ }
+ finally
+ {
+ SyncRoot.ExitReadLock();
+ }
+ }
+ }
+} \ No newline at end of file