From 61c8202ab07d8cec93d0ba03e2910fa823aa2bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Feb 2021 08:46:34 -0600 Subject: add header --- src/slskd/Common/Cryptography/X509.cs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs index 19b1c4ba..2f5392fd 100644 --- a/src/slskd/Common/Cryptography/X509.cs +++ b/src/slskd/Common/Cryptography/X509.cs @@ -1,10 +1,27 @@ -namespace slskd.Common.Cryptography +// +// 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/. +// + +namespace slskd.Common.Cryptography { using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; - public class X509 + public static class X509 { public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet) { -- cgit v1.2.3 From 56c4baf89bacf7494f2f304861bae1394dad4e4a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Feb 2021 09:36:43 -0600 Subject: swap argument and envar libs for nuget packages --- .../Common/Configuration/CommandLineArguments.cs | 666 --------------------- .../CommandLineConfigurationSource.cs | 5 +- .../Common/Configuration/EnvironmentVariables.cs | 185 ------ src/slskd/Program.cs | 22 +- src/slskd/Startup.cs | 315 +++++----- src/slskd/slskd.csproj | 6 +- 6 files changed, 177 insertions(+), 1022 deletions(-) delete mode 100644 src/slskd/Common/Configuration/CommandLineArguments.cs delete mode 100644 src/slskd/Common/Configuration/EnvironmentVariables.cs (limited to 'src/slskd/Common') 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; - - /// - /// Provides extension method(s) for the CommandLineArguments namespace. - /// - public static class CommandLineArgumentsExtensions - { - /// - /// Gets the DeclaringType of the first method on the stack whose name matches the specified . - /// - /// The name of the calling method for which the DeclaringType is to be fetched. - /// The DeclaringType of the first method on the stack whose name matches the specified . - 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; - } - - /// - /// Removes the outermost pair of enclosing quotes. - /// - /// The string to trim. - /// The trimmed string. - 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; - } - } - - /// - /// Indicates that the property is to be used as a target for automatic population of values from command line arguments - /// when invoking the method. - /// - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class CommandLineArgumentAttribute : Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The short name of the argument, represented as a single character. - /// The long name of the argument. - /// The help text of the argument. - public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null) - { - ShortName = shortName; - LongName = longName; - HelpText = helpText; - } - - /// - /// Gets or sets the help text of the argument. - /// - public string HelpText { get; set; } - - /// - /// Gets or sets the long name of the argument. - /// - public string LongName { get; set; } - - /// - /// Gets or sets the short name of the argument. - /// - public char ShortName { get; set; } - } - - /// - /// Encapsulates argument names and help text. - /// - public class ArgumentInfo - { - /// - /// Initializes a new instance of the class. - /// - /// The short name of the argument. - /// The long name of the argument. - /// The help text for the argument. - /// The property with which the argument is associated. - public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property) - { - ShortName = shortName; - LongName = longName; - HelpText = helpText; - Property = property; - } - - /// - /// Gets the help text for the argument. - /// - public string HelpText { get; } - - /// - /// Gets a value indicating whether the argument backing Type is a collection. - /// - public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)); - - /// - /// Gets the long name of the argument. - /// - public string LongName { get; } - - /// - /// Gets the property with which the argument is associated. - /// - public PropertyInfo Property { get; } - - /// - /// Gets the short name of the argument. - /// - public char ShortName { get; } - } - - /// - /// 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. - /// - public class CommandLineArguments - { - /// - /// The regular expression with which to parse the command line string. - /// - private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; - - /// - /// The regular expression with which to parse the command line string, including the ability to specify forward slashes. - /// - private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; - - /// - /// The regular expression with which to parse argument-value groups. - /// - private const string GroupRegEx = "^-[^-]+"; - - /// - /// The regular expression with which to parse strings strictly containing operands. - /// - private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')"; - - /// - /// The regular expression with which to split the command line string explicitly among argument/value pairs and - /// operands, and strictly operands. - /// - /// - /// 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. - /// - private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)"; - - private CommandLineArguments(string commandLineString, List> argumentList, Dictionary argumentDictionary, List operandList, Type targetType = null) - { - CommandLineString = commandLineString; - ArgumentList = argumentList; - ArgumentDictionary = argumentDictionary; - OperandList = operandList; - TargetType = targetType; - } - - /// - /// Gets or sets a value indicating whether forward slashes are processed as argument delimiters. - /// - public static bool EnableForwardSlash { get; set; } = false; - - /// - /// Gets a dictionary containing the arguments and values specified in the command line arguments with which the - /// application was started. - /// - /// - /// This dictionary contains argument key/value pairs compiled from the and checked against - /// the to combine duplicated pairs into lists where the backing property is a collection, and - /// to overwrite where the backing property is not a collection. - /// - public Dictionary ArgumentDictionary { get; } - - /// - /// Gets the list of arguments specified in the command line arguments with which the application was started. - /// - /// - /// This list contains each argument key/value pair as supplied in the original string, preserving the original order - /// and any duplicated pairs. - /// - public List> ArgumentList { get; } - - /// - /// Gets the command line string from which the arguments were parsed. - /// - public string CommandLineString { get; } - - /// - /// Gets a list containing the operands specified in the command line arguments with which the application was started. - /// - public List OperandList { get; private set; } - - /// - /// Gets the target Type, if applicable. - /// - public Type TargetType { get; } - - private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash; - - /// - /// Gets the argument value corresponding to the specified . - /// - /// The index for which the value is to be retrieved. - /// The argument value corresponding to the specified index. - public object this[int index] - { - get - { - return ArgumentList[index].Value; - } - } - - /// - /// Gets the argument value corresponding to the specified from the - /// property. - /// - /// The key for which the value is to be retrieved. - /// The argument value corresponding to the specified key. - public object this[string key] - { - get - { - return ArgumentDictionary[key]; - } - } - - /// - /// Retrieves a collection of gathered from properties in the target - /// marked with the along with the short and long names and help text. - /// - /// The for which the matching properties are to be retrieived. - /// Internal parameter used to identify the calling method. - /// The retrieved collection of . - public static IEnumerable GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default) - { - type ??= CommandLineArgumentsExtensions.GetCallingType(caller); - var retVal = new List(); - - 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; - } - - /// - /// Returns a dictionary containing the values specified in the command line arguments with which the application was - /// started, keyed by argument name. - /// - /// The command line arguments with which the application was started. - /// The for which the command line string is to be parsed. - /// - /// The dictionary containing the arguments and values specified in the command line arguments with which the - /// application was started. - /// - public static CommandLineArguments Parse(string commandLineString = default, Type type = null) - { - commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString; - - List> argumentList; - List 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 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); - } - - /// - /// Populates the properties in the invoking class marked with the - /// with the values specified in the list of command line - /// arguments, if present. - /// - /// The command line arguments with which the application was started. - /// Whether to clear the properties before populating them. Defaults to true. - /// Internal parameter used to identify the calling method. - 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); - } - - /// - /// Populates the properties in the specified Type marked with the - /// with the values specified in the list of command line - /// arguments, if present. - /// - /// - /// The Type for which the static properties matching the list of command line arguments are to be populated. - /// - /// The command line arguments with which the application was started. - /// Whether to clear the properties before populating them. Defaults to true. - public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true) - { - Populate(type, Parse(commandLineString, type), clearExistingValues); - } - - /// - /// Populates the properties in the specified Type marked with the - /// with the values specified in the specified argument - /// dictionary, if present. All property values are set to null at the start of the routine. - /// - /// - /// The Type for which the static properties matching the list of command line arguments are to be populated. - /// - /// - /// The Arguments object containing the dictionary containing the argument-value pairs with which the destination - /// properties should be populated and the list of operands. - /// - /// Whether to clear the properties before populating them. Defaults to true. - 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 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)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))) - { - 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 properties) - { - foreach (string key in properties.Keys) - { - properties[key].SetValue(null, null); - } - } - - private static Dictionary GetArgumentDictionary(List> argumentList, Type targetType = null) - { - var dict = new ConcurrentDictionary(); - var argumentInfo = targetType == null ? new List() : 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)existingValue).Concat(new[] { arg.Value }).ToList() : (object)arg.Value); - added = true; - break; - } - } - - if (!added) - { - dict.TryAdd(arg.Key, info.IsCollection ? new List(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> GetArgumentList(string commandLineString) - { - var argumentList = new List>(); - - 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(charArray[i].ToString(CultureInfo.InvariantCulture), i == charArray.Length - 1 ? value : string.Empty)); - } - } - else - { - argumentList.Add(new KeyValuePair(argument, value)); - } - } - - return argumentList; - } - - private static Dictionary GetArgumentProperties(Type type) - { - Dictionary properties = new Dictionary(); - - 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 GetOperandList(string commandLineString) - { - List operands = new List(); - - 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 GetOperandListStrict(string operandListString) - { - List operands = new List(); - - 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)) - { - throw new InvalidCastException("The target for the Operands attribute must be of string[] or List."); - } - - return property; - } - } - - /// - /// Indicates that the property is to be used as the target for automatic population of command line operands when invoking - /// the method. - /// - [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..b1c83251 100644 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; + using Utility.CommandLine; /// /// Defines a command line argument mapping. @@ -86,7 +87,7 @@ private bool NormalizeKey { get; set; } /// - /// Initializes a new instance with the specified source. + /// Initializes a new instance of the class. /// /// The source settings. public CommandLineConfigurationProvider(CommandLineConfigurationSource source) @@ -101,7 +102,7 @@ /// public override void Load() { - var dictionary = CommandLineArguments.Parse(CommandLine).ArgumentDictionary; + var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary; foreach (CommandLineArgument item in Map) { 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; - - /// - /// Indicates that the property is to be used as a target for automatic population of values from environment variables - /// when invoking the method. - /// - [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] - public class EnvironmentVariableAttribute : Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The name of the environment variable - public EnvironmentVariableAttribute(string name) - { - Name = name; - } - - /// - /// Gets or sets the name of the environment variable. - /// - public string Name { get; set; } - } - - /// - /// Provides static methods used to populate properties from environment variable values. - /// - public static class EnvironmentVariables - { - /// - /// Populates the properties in the invoking class marked with the - /// with the values specified in environment variables. - /// - /// Internal parameter used to identify the calling method. - /// The optional prefix for variable names. - public static void Populate(string prefix = null, [CallerMemberName] string caller = default) - { - Populate(GetCallingType(caller), prefix); - } - - /// - /// Populates the properties in the invoking class marked with the - /// with the values specified in environment variables. - /// - /// - /// The Type for which the static properties matching the list of environment variables are to be populated. - /// - /// The optional prefix for variable names. - 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 GetTargetProperties(Type type) - { - Dictionary properties = new Dictionary(); - - 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/Program.cs b/src/slskd/Program.cs index 2f75c2a0..f803bb71 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -36,6 +36,8 @@ namespace slskd using slskd.Common.Cryptography; using slskd.Configuration; using slskd.Validation; + using Utility.CommandLine; + using Utility.EnvironmentVariables; public static class ProgramExtensions { @@ -50,8 +52,8 @@ namespace slskd prefix: environmentVariablePrefix, map: Options.Map.Select(o => o.ToEnvironmentVariable())) .AddYamlFile( - path: Path.GetFileName(configurationFile), - optional: true, + path: Path.GetFileName(configurationFile), + optional: true, reloadOnChange: false, provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) .AddCommandLine( @@ -65,30 +67,30 @@ namespace slskd public static readonly string AppName = "slskd"; public static readonly string DefaultConfigurationFile = $"{AppName}.yml"; public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; - + public static Guid InvocationId { get; } = Guid.NewGuid(); public static int ProcessId { get; } = Environment.ProcessId; public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version; public static string InformationalVersion { get; } = Assembly.GetExecutingAssembly().GetCustomAttribute().InformationalVersion; public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; - [CommandLineArgument('n', "no-logo", "suppress logo on startup")] + [Argument('n', "no-logo", "suppress logo on startup")] private static bool NoLogo { get; set; } - [CommandLineArgument('e', "envars", "display environment variables")] + [Argument('e', "envars", "display environment variables")] private static bool ShowEnvironmentVariables { get; set; } - [CommandLineArgument('h', "help", "display command line usage")] + [Argument('h', "help", "display command line usage")] private static bool ShowHelp { get; set; } - [CommandLineArgument('v', "version", "display version information")] + [Argument('v', "version", "display version information")] private static bool ShowVersion { get; set; } - [CommandLineArgument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] + [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } [EnvironmentVariable("CONFIG")] - [CommandLineArgument('c', "config", "path to configuration file")] + [Argument('c', "config", "path to configuration file")] private static string ConfigurationFile { get; set; } = DefaultConfigurationFile; private static Options Options { get; } = new Options(); @@ -97,7 +99,7 @@ namespace slskd public static void Main(string[] args) { EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix); - CommandLineArguments.Populate(clearExistingValues: false); + Arguments.Populate(clearExistingValues: false); if (ShowVersion) { diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 41ef747c..d02ec39f 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -48,15 +48,9 @@ namespace slskd public class Startup { - private readonly int MaxReconnectAttempts = 3; - private int CurrentReconnectAttempts = 0; private static readonly string XmlDocFile = Path.Combine(AppContext.BaseDirectory, Program.AppName + ".xml"); - - private SoulseekClient Client { get; set; } - private ISharedFileCache SharedFileCache { get; set; } - private string UrlBase { get; set; } - private string ContentPath { get; set; } - private SymmetricSecurityKey JwtSigningKey { get; set; } + private static readonly int MaxReconnectAttempts = 3; + private static int CurrentReconnectAttempts = 0; public Startup(IConfiguration configuration) { @@ -78,110 +72,20 @@ namespace slskd JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Authentication.Jwt.Key)); } + private SoulseekClient Client { get; set; } private IConfiguration Configuration { get; } - private Options Options { get; } + private string ContentPath { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); - - public void ConfigureServices(IServiceCollection services) - { - var logger = Log.ForContext(); - - services.AddOptions() - .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; }); - - services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); - - services.AddSingleton(JwtSigningKey); - - if (!Options.Web.Authentication.Disable) - { - services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { - options.TokenValidationParameters = new TokenValidationParameters - { - ClockSkew = TimeSpan.FromMinutes(5), - RequireSignedTokens = true, - RequireExpirationTime = true, - ValidateLifetime = true, - ValidIssuer = "slskd", - ValidateIssuer = true, - ValidateAudience = false, - IssuerSigningKey = JwtSigningKey, - ValidateIssuerSigningKey = true, - }; - }); - } - else - { - logger.Warning("Authentication of web requests is DISABLED"); - - services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) - .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => - { - options.Username = "n/a"; - }); - } - - services.AddRouting(options => options.LowercaseUrls = true); - services.AddControllers().AddJsonOptions(options => - { - options.JsonSerializerOptions.Converters.Add(new IPAddressConverter()); - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); - options.JsonSerializerOptions.IgnoreNullValues = true; - }); - - services.AddHealthChecks(); - - services.AddApiVersioning(options => options.ReportApiVersions = true); - services.AddVersionedApiExplorer(options => - { - options.GroupNameFormat = "'v'VVV"; - options.SubstituteApiVersionInUrl = true; - }); - - if (Options.Feature.Swagger) - { - services.AddSwaggerGen(options => - { - options.DescribeAllParametersInCamelCase(); - options.SwaggerDoc("v0", - new OpenApiInfo - { - Title = "slskd", - Version = "v0" - } - ); - - if (System.IO.File.Exists(XmlDocFile)) - { - options.IncludeXmlComments(XmlDocFile); - } - else - { - logger.Warning($"Unable to find XML documentation in {XmlDocFile}, Swagger will not include metadata"); - } - }); - } - - if (Options.Feature.Prometheus) - { - services.AddSystemMetrics(); - } - - services.AddSingleton(serviceProvider => Client); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); - } + private Options Options { get; } + private ISharedFileCache SharedFileCache { get; set; } + private string UrlBase { get; set; } public void Configure( - IApplicationBuilder app, - IApiVersionDescriptionProvider provider, - ITransferTracker tracker, - IBrowseTracker browseTracker, + IApplicationBuilder app, + IApiVersionDescriptionProvider provider, + ITransferTracker tracker, + IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker) { @@ -200,8 +104,7 @@ namespace slskd app.UsePathBase(UrlBase); logger.Information("Using base url {UrlBase}", UrlBase); - // remove any errant double forward slashes which may have been introduced - // by a reverse proxy or having the base path removed + // remove any errant double forward slashes which may have been introduced by a reverse proxy or having the base path removed app.Use(async (context, next) => { var path = context.Request.Path.ToString(); @@ -225,9 +128,9 @@ namespace slskd fileServerOptions = new FileServerOptions { FileProvider = new PhysicalFileProvider(ContentPath), - RequestPath = "", + RequestPath = string.Empty, EnableDirectoryBrowsing = false, - EnableDefaultFiles = true + EnableDefaultFiles = true, }; app.UseFileServer(fileServerOptions); @@ -266,8 +169,8 @@ namespace slskd logger.Information("Publishing Swagger documentation to /swagger"); } - // if we made it this far and the route still wasn't matched, return the index unless it's an api route - // this is required so that SPA routing (React Router, etc) can work properly + // if we made it this far and the route still wasn't matched, return the index unless it's an api route this is + // required so that SPA routing (React Router, etc) can work properly app.Use(async (context, next) => { // exclude API routes which are not matched or return a 404 @@ -279,16 +182,15 @@ namespace slskd await next(); }); - // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be returned - // otherwise it will throw a final 404 back to the client. + // finally, hit the fileserver again. if the path was modified to return the index above, the index document will be + // returned otherwise it will throw a final 404 back to the client. if (System.IO.Directory.Exists(ContentPath)) { app.UseFileServer(fileServerOptions); } // --------------------------------------------------------------------------------------------------------------------------------------------- - // begin SoulseekClient implementation - // --------------------------------------------------------------------------------------------------------------------------------------------- + // begin SoulseekClient implementation --------------------------------------------------------------------------------------------------------------------------------------------- var connectionOptions = new ConnectionOptions( readBufferSize: Options.Soulseek.Connection.Buffer.Read, writeBufferSize: Options.Soulseek.Connection.Buffer.Write, @@ -297,8 +199,7 @@ namespace slskd var defaults = new SoulseekClientOptions(); - // create options for the client. - // see the implementation of Func<> and Action<> options for detailed info. + // create options for the client. see the implementation of Func<> and Action<> options for detailed info. var clientOptions = new SoulseekClientOptions( listenPort: Options.Soulseek.ListenPort ?? defaults.ListenPort, enableListener: Options.Soulseek.ListenPort.HasValue, @@ -327,8 +228,8 @@ namespace slskd Client = new SoulseekClient(options: clientOptions); - // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event - // isn't bound the minimumDiagnosticLevel should be set to None. + // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the + // event isn't bound the minimumDiagnosticLevel should be set to None. Client.DiagnosticGenerated += (e, args) => { static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch @@ -345,7 +246,7 @@ namespace slskd logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); }; - // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs. + // bind transfer events. see TransferStateChangedEventArgs and TransferProgressEventArgs. Client.TransferStateChanged += (e, args) => { var direction = args.Transfer.Direction.ToString().ToUpper(); @@ -361,12 +262,13 @@ namespace slskd Client.TransferProgressUpdated += (e, args) => { - // this is really verbose. - // Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); + // this is really verbose. Console.WriteLine($"[{args.Transfer.Direction.ToString().ToUpper()}] + // [{args.Transfer.Username}/{Path.GetFileName(args.Transfer.Filename)}] + // {args.Transfer.BytesTransferred}/{args.Transfer.Size} {args.Transfer.PercentComplete}% {args.Transfer.AverageSpeed}kb/s"); }; - // bind BrowseProgressUpdated to track progress of browse response payload transfers. - // these can take a while depending on number of files shared. + // bind BrowseProgressUpdated to track progress of browse response payload transfers. these can take a while depending + // on number of files shared. Client.BrowseProgressUpdated += (e, args) => { browseTracker.AddOrUpdate(args.Username, args); @@ -416,9 +318,9 @@ namespace slskd { Console.WriteLine($"Disconnected from Soulseek server: {args.Message}"); - // don't reconnect if the disconnecting Exception is either of these types. - // if KickedFromServerException, another client was most likely signed in, and retrying will cause a connect loop. - // if ObjectDisposedException, the client is shutting down. + // don't reconnect if the disconnecting Exception is either of these types. if KickedFromServerException, another + // client was most likely signed in, and retrying will cause a connect loop. if ObjectDisposedException, the + // client is shutting down. if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) { Interlocked.Increment(ref CurrentReconnectAttempts); @@ -447,22 +349,99 @@ namespace slskd logger.Information("Connected and logged in as {Username}", username); } - /// - /// Creates and returns a object in response to a remote request. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// A Task resolving the UserInfo instance. - private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) + public void ConfigureServices(IServiceCollection services) { - var info = new UserInfo( - description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", - picture: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"), - uploadSlots: 1, - queueLength: 0, - hasFreeUploadSlot: false); + var logger = Log.ForContext(); - return Task.FromResult(info); + services.AddOptions() + .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; }); + + services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); + + services.AddSingleton(JwtSigningKey); + + if (!Options.Web.Authentication.Disable) + { + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(options => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ClockSkew = TimeSpan.FromMinutes(5), + RequireSignedTokens = true, + RequireExpirationTime = true, + ValidateLifetime = true, + ValidIssuer = "slskd", + ValidateIssuer = true, + ValidateAudience = false, + IssuerSigningKey = JwtSigningKey, + ValidateIssuerSigningKey = true, + }; + }); + } + else + { + logger.Warning("Authentication of web requests is DISABLED"); + + services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) + .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => + { + options.Username = "n/a"; + }); + } + + services.AddRouting(options => options.LowercaseUrls = true); + services.AddControllers().AddJsonOptions(options => + { + options.JsonSerializerOptions.Converters.Add(new IPAddressConverter()); + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); + options.JsonSerializerOptions.IgnoreNullValues = true; + }); + + services.AddHealthChecks(); + + services.AddApiVersioning(options => options.ReportApiVersions = true); + services.AddVersionedApiExplorer(options => + { + options.GroupNameFormat = "'v'VVV"; + options.SubstituteApiVersionInUrl = true; + }); + + if (Options.Feature.Swagger) + { + services.AddSwaggerGen(options => + { + options.DescribeAllParametersInCamelCase(); + options.SwaggerDoc( + "v0", + new OpenApiInfo + { + Title = "slskd", + Version = "v0", + }); + + if (System.IO.File.Exists(XmlDocFile)) + { + options.IncludeXmlComments(XmlDocFile); + } + else + { + logger.Warning($"Unable to find XML documentation in {XmlDocFile}, Swagger will not include metadata"); + } + }); + } + + if (Options.Feature.Prometheus) + { + services.AddSystemMetrics(); + } + + services.AddSingleton(serviceProvider => Client); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); } /// @@ -498,15 +477,20 @@ namespace slskd } /// - /// Invoked upon a remote request to download a file. + /// Invoked upon a remote request to download a file. /// /// The username of the requesting user. /// The IP endpoint of the requesting user. /// The filename of the requested file. /// (for example purposes) the ITransferTracker used to track progress. /// A Task representing the asynchronous operation. - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for security reasons. + /// + /// Thrown when the download is rejected. The Exception message will be passed to the remote user. + /// + /// + /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for + /// security reasons. + /// private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) { _ = endpoint; @@ -521,8 +505,7 @@ namespace slskd if (tracker.TryGet(TransferDirection.Upload, username, filename, out _)) { - // in this case, a re-requested file is a no-op. normally we'd want to respond with a - // PlaceInQueueResponse + // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]"); return Task.CompletedTask; } @@ -531,8 +514,8 @@ namespace slskd var cts = new CancellationTokenSource(); var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (t, c) => Task.Delay(1, c)); - // accept all download requests, and begin the upload immediately. - // normally there would be an internal queue, and uploads would be handled separately. + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. Task.Run(async () => { using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); @@ -557,14 +540,14 @@ namespace slskd { var defaultResponse = Task.FromResult(null); - // some bots continually query for very common strings. blacklist known names here. + // some bots continually query for very common strings. blacklist known names here. var blacklist = new[] { "Lola45", "Lolo51", "rajah" }; if (blacklist.Contains(username)) { return defaultResponse; } - // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. + // some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans. if (query.Query.Length < 3) { return defaultResponse; @@ -585,12 +568,30 @@ namespace slskd fileList: results)); } - // if no results, either return null or an instance of SearchResponse with a fileList of length 0 - // in either case, no response will be sent to the requestor. + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. return Task.FromResult(null); } - class IPAddressConverter : JsonConverter + /// + /// Creates and returns a object in response to a remote request. + /// + /// The username of the requesting user. + /// The IP endpoint of the requesting user. + /// A Task resolving the UserInfo instance. + private Task UserInfoResponseResolver(string username, IPEndPoint endpoint) + { + var info = new UserInfo( + description: $"Soulseek.NET Web Example! also, your username is {username}, and IP endpoint is {endpoint}", + picture: System.IO.File.ReadAllBytes(@"slsk_bird.jpg"), + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); + + return Task.FromResult(info); + } + + private class IPAddressConverter : JsonConverter { public override bool CanConvert(Type objectType) => (objectType == typeof(IPAddress)); @@ -599,7 +600,7 @@ namespace slskd public override void Write(Utf8JsonWriter writer, IPAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString()); } - class UserEndPointCache : IUserEndPointCache + private class UserEndPointCache : IUserEndPointCache { public UserEndPointCache() { diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 30f891a0..997e8022 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -38,13 +38,13 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + @@ -68,6 +68,8 @@ + + -- cgit v1.2.3 From fb228b5d1b94e143d3e36c5df56a3d8311ecec2b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Feb 2021 21:41:08 -0600 Subject: update docs --- .../CommandLineConfigurationSource.cs | 101 ++++++++++++-------- .../DefaultValueConfigurationSource.cs | 91 +++++++++++------- .../EnvironmentVariableConfigurationSource.cs | 103 +++++++++++++-------- .../Configuration/YamlConfigurationSource.cs | 86 ++++++++++------- 4 files changed, 233 insertions(+), 148 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs index b1c83251..75ecadc4 100644 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -1,9 +1,27 @@ -namespace slskd.Configuration +// +// 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/. +// + +#pragma warning disable SA1649 // File name should match first type name +namespace slskd.Configuration { - using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; + using Microsoft.Extensions.Configuration; using Utility.CommandLine; /// @@ -19,11 +37,13 @@ /// /// Adds a command line argument configuration soruce to . /// - /// The . + /// The to which to add. /// A list of command line argument mappings. /// The command line string from which to parse arguments. - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// The updated . public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable map, string commandLine = null, bool normalizeKey = true) { if (builder == null) @@ -42,61 +62,33 @@ /// /// Adds a command line argument configuration source to . /// - /// The . + /// The to which to add. /// Configures the source. - /// The . + /// The updated . public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action configureSource) => builder.Add(configureSource); } - /// - /// Represents command line arguments as an . - /// - public class CommandLineConfigurationSource : IConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); - - /// - /// Gets or sets a list of command line argument mappings. - /// - public IEnumerable Map { get; set; } - - /// - /// Gets or sets the command line string from which to parse arguments. - /// - public string CommandLine { get; set; } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKey { get; set; } - } - /// /// A command line argument . /// public class CommandLineConfigurationProvider : ConfigurationProvider { - private IEnumerable Map { get; set; } - private string CommandLine { get; set; } - private bool NormalizeKey { get; set; } - /// /// Initializes a new instance of the class. /// /// The source settings. - public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) { Map = source.Map; CommandLine = source.CommandLine; NormalizeKey = source.NormalizeKey; } + private string CommandLine { get; set; } + private IEnumerable Map { get; set; } + private bool NormalizeKey { get; set; } + /// /// Parses command line arguments from the specified string and maps them to the specified keys. /// @@ -137,4 +129,33 @@ } } } + + /// + /// Represents command line arguments as an . + /// + public class CommandLineConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets the command line string from which to parse arguments. + /// + public string CommandLine { get; set; } + + /// + /// Gets or sets a list of command line argument mappings. + /// + public IEnumerable Map { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKey { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + } } +#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs index accc76c9..5bbba10e 100644 --- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs +++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs @@ -1,9 +1,27 @@ -namespace slskd.Configuration +// +// 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/. +// + +#pragma warning disable SA1649 // File name should match first type name +namespace slskd.Configuration { - using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; + using Microsoft.Extensions.Configuration; /// /// Defines an default value mapping. @@ -18,10 +36,12 @@ /// /// Adds a default value configuration source to . /// - /// The to add to. + /// The to which to add. /// A list of default value mappings. - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// The . + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// The updated . public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable map, bool normalizeKey = true) { if (builder == null) @@ -39,49 +59,23 @@ /// /// Adds a default value configuration source to . /// - /// The to add to. + /// The to which to add. /// Configures the source. - /// The . + /// The updated . public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action configureSource) => builder.Add(configureSource); } - /// - /// Represents default values as an . - /// - public class DefaultValueConfigurationSource : IConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new DefaultValueConfigurationProvider(this); - } - - /// - /// Gets or sets a list of default value mappings. - /// - public IEnumerable Map { get; set; } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKey { get; set; } - } - /// /// A default value . /// public class DefaultValueConfigurationProvider : ConfigurationProvider { /// - /// Initializes a new instance with the specified source. + /// Initializes a new instance of the class. /// /// The source settings. - public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) + public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) { Map = source.Map; NormalizeKey = source.NormalizeKey; @@ -118,4 +112,31 @@ } } } + + /// + /// Represents default values as an . + /// + public class DefaultValueConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets a list of default value mappings. + /// + public IEnumerable Map { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKey { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DefaultValueConfigurationProvider(this); + } + } } +#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs index a18faebc..51ddf535 100644 --- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs +++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs @@ -1,9 +1,27 @@ -namespace slskd.Configuration +// +// 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/. +// + +#pragma warning disable SA1649 // File name should match first type name +namespace slskd.Configuration { - using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; + using Microsoft.Extensions.Configuration; /// /// Defines an environment variable mapping. @@ -18,11 +36,13 @@ /// /// Adds an environment variable configuration source to . /// - /// The to add to. + /// The to which to add. /// A list of environment variable mappings. /// A prefix to prepend to all variable names. - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// The . + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// The updated . public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map, string prefix = null, bool normalizeKey = true) { if (builder == null) @@ -41,54 +61,23 @@ /// /// Adds an enviroment variable configuration source to . /// - /// The to add to. + /// The to which to add. /// Configures the source. - /// The . + /// The updated . public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action configureSource) => builder.Add(configureSource); } - /// - /// Represents environment variables as an . - /// - public class EnvironmentVariableConfigurationSource : IConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A . - public IConfigurationProvider Build(IConfigurationBuilder builder) - { - return new EnvironmentVariableConfigurationProvider(this); - } - - /// - /// Gets or sets a list of enviroment variable mappings. - /// - public IEnumerable Map { get; set; } - - /// - /// Gets or sets a prefix to prepend to all variable names. - /// - public string Prefix { get; set; } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKey { get; set; } - } - /// /// An enviroment variable . /// public class EnvironmentVariableConfigurationProvider : ConfigurationProvider { /// - /// Initializes a new instance with the specified source. + /// Initializes a new instance of the class. /// /// The source settings. - public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) { Map = source.Map; Prefix = source.Prefix; @@ -126,7 +115,7 @@ } if (type == typeof(bool)) - { + { value = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) ? value : "false"; } @@ -134,4 +123,36 @@ } } } + + /// + /// Represents environment variables as an . + /// + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// + /// Gets or sets a list of enviroment variable mappings. + /// + public IEnumerable Map { get; set; } + + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKey { get; set; } + + /// + /// Gets or sets a prefix to prepend to all variable names. + /// + public string Prefix { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + } } +#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs index 27ca6fea..7766e14c 100644 --- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -1,10 +1,28 @@ -namespace slskd.Configuration +// +// 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/. +// + +#pragma warning disable SA1649 // File name should match first type name +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; @@ -17,11 +35,14 @@ /// Adds a YAML configuration source to . /// /// The to add to. - /// Path relative to the base path stored in - /// of . + /// + /// Path relative to the base path stored in of . + /// /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// /// The to use to access the file. /// The . public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) @@ -57,45 +78,23 @@ => builder.Add(configureSource); } - /// - /// Represents a YAML file as an . - /// - public class YamlConfigurationSource : FileConfigurationSource - { - /// - /// Builds the for this source. - /// - /// The . - /// A - public override IConfigurationProvider Build(IConfigurationBuilder builder) - { - EnsureDefaults(builder); - return new YamlConfigurationProvider(this); - } - - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKeys { get; set; } - } - /// /// A YAML file based . /// public class YamlConfigurationProvider : FileConfigurationProvider { /// - /// Initializes a new instance with the specified source. + /// Initializes a new instance of the class. /// /// The source settings. - 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 }; /// /// Loads the YAML data from a stream. @@ -157,4 +156,27 @@ } } } + + /// + /// Represents a YAML file as an . + /// + public class YamlConfigurationSource : FileConfigurationSource + { + /// + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// + public bool NormalizeKeys { get; set; } + + /// + /// Builds the for this source. + /// + /// The . + /// A . + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + } } +#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file -- cgit v1.2.3 From 1f3e7359ad8231c555589f787fa2455f26a90f95 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Feb 2021 08:26:28 -0600 Subject: rename pbkdf2 --- src/slskd/Common/Cryptography/PBKDF2.cs | 26 ------------------- src/slskd/Common/Cryptography/PBKDF21.cs | 43 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 26 deletions(-) delete mode 100644 src/slskd/Common/Cryptography/PBKDF2.cs create mode 100644 src/slskd/Common/Cryptography/PBKDF21.cs (limited to 'src/slskd/Common') 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; - - /// - /// PBKDF2/RFC 2898 implementation - /// - public static class PBKDF2 - { - /// - /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898 - /// - /// - /// - 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/PBKDF21.cs b/src/slskd/Common/Cryptography/PBKDF21.cs new file mode 100644 index 00000000..05770ad6 --- /dev/null +++ b/src/slskd/Common/Cryptography/PBKDF21.cs @@ -0,0 +1,43 @@ +// +// 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/. +// + +namespace slskd.Security +{ + using System.Security.Cryptography; + using Microsoft.AspNetCore.Cryptography.KeyDerivation; + + /// + /// PBKDF2/RFC 2898 utility methods. + /// + public static class PBKDF21 + { + /// + /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898. + /// + /// The password from which to derive the key. + /// The derived key. + 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); + } + } +} -- cgit v1.2.3 From acedfdc4da02f10c2271d94f13e4ca9c2a5cb6b3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Feb 2021 08:26:57 -0600 Subject: complete rename bump --- src/slskd/Common/Cryptography/PBKDF21.cs | 43 -------------------------------- src/slskd/Common/Cryptography/Pbkdf2.cs | 43 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 43 deletions(-) delete mode 100644 src/slskd/Common/Cryptography/PBKDF21.cs create mode 100644 src/slskd/Common/Cryptography/Pbkdf2.cs (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Cryptography/PBKDF21.cs b/src/slskd/Common/Cryptography/PBKDF21.cs deleted file mode 100644 index 05770ad6..00000000 --- a/src/slskd/Common/Cryptography/PBKDF21.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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/. -// - -namespace slskd.Security -{ - using System.Security.Cryptography; - using Microsoft.AspNetCore.Cryptography.KeyDerivation; - - /// - /// PBKDF2/RFC 2898 utility methods. - /// - public static class PBKDF21 - { - /// - /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898. - /// - /// The password from which to derive the key. - /// The derived key. - 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 (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/. +// + +namespace slskd.Security +{ + using System.Security.Cryptography; + using Microsoft.AspNetCore.Cryptography.KeyDerivation; + + /// + /// PBKDF2/RFC 2898 utility methods. + /// + public static class Pbkdf2 + { + /// + /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898. + /// + /// The password from which to derive the key. + /// The derived key. + 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); + } + } +} -- cgit v1.2.3 From 0ad3a9b5b584697b43b74f68e88a31e048b32822 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Feb 2021 08:27:10 -0600 Subject: docs --- src/slskd/Common/Cryptography/X509.cs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs index 2f5392fd..95743cc0 100644 --- a/src/slskd/Common/Cryptography/X509.cs +++ b/src/slskd/Common/Cryptography/X509.cs @@ -21,8 +21,18 @@ namespace slskd.Common.Cryptography using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; + /// + /// X509 utility methods. + /// public static class X509 { + /// + /// Generates an X509 certificate for the specified . + /// + /// The certificate subject. + /// The optional password for the certificate. + /// The optional key storage flags for the certificate. + /// The generated certificate. public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet) { password ??= Guid.NewGuid().ToString(); @@ -42,6 +52,13 @@ namespace slskd.Common.Cryptography return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); } + /// + /// Validates an X509 certificate given a PFX and optional . + /// + /// The path to the PFX certificate file to validate. + /// The optional password for the certificate. + /// The error message, if the certificate is invalid. + /// A value indicating whether the certificate is valid. public static bool TryValidate(string fileName, string password, out string result) { result = null; @@ -58,4 +75,4 @@ namespace slskd.Common.Cryptography } } } -} +} \ No newline at end of file -- cgit v1.2.3 From 39c66558cfedfbb28b11c37cd43ef39adcbe1d26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Feb 2021 08:27:36 -0600 Subject: more docs --- .../CommandLineConfigurationSource.cs | 24 ++------------ .../Configuration/ConfigurationExtensions.cs | 37 +++++++++++++++++++++- .../DefaultValueConfigurationSource.cs | 31 +++--------------- .../EnvironmentVariableConfigurationSource.cs | 17 ++-------- .../Configuration/YamlConfigurationSource.cs | 12 +++---- src/slskd/Options.cs | 34 ++++++++++++++++---- 6 files changed, 77 insertions(+), 78 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs index 75ecadc4..088d5ea6 100644 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -15,7 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -#pragma warning disable SA1649 // File name should match first type name namespace slskd.Configuration { using System; @@ -32,7 +31,7 @@ namespace slskd.Configuration /// /// Extension methods for adding . /// - public static class CommandLineExtensions + public static class CommandLineConfigurationExtensions { /// /// Adds a command line argument configuration soruce to . @@ -40,11 +39,8 @@ namespace slskd.Configuration /// The to which to add. /// A list of command line argument mappings. /// The command line string from which to parse arguments. - /// - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable map, string commandLine = null, bool normalizeKey = true) + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable map, string commandLine = null) { if (builder == null) { @@ -55,7 +51,6 @@ namespace slskd.Configuration { s.Map = map; s.CommandLine = commandLine ?? Environment.CommandLine; - s.NormalizeKey = normalizeKey; }); } @@ -82,12 +77,10 @@ namespace slskd.Configuration { Map = source.Map; CommandLine = source.CommandLine; - NormalizeKey = source.NormalizeKey; } private string CommandLine { get; set; } private IEnumerable Map { get; set; } - private bool NormalizeKey { get; set; } /// /// Parses command line arguments from the specified string and maps them to the specified keys. @@ -100,11 +93,6 @@ namespace slskd.Configuration { var (shortName, longName, type, key, _) = item; - if (NormalizeKey) - { - key = key?.Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant(); - } - if (string.IsNullOrEmpty(key)) { continue; @@ -145,11 +133,6 @@ namespace slskd.Configuration /// public IEnumerable Map { get; set; } - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKey { get; set; } - /// /// Builds the for this source. /// @@ -157,5 +140,4 @@ namespace slskd.Configuration /// A . public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); } -} -#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/ConfigurationExtensions.cs b/src/slskd/Common/Configuration/ConfigurationExtensions.cs index 77b59700..33385e0a 100644 --- a/src/slskd/Common/Configuration/ConfigurationExtensions.cs +++ b/src/slskd/Common/Configuration/ConfigurationExtensions.cs @@ -1,13 +1,48 @@ -namespace slskd.Configuration +// +// 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/. +// + +namespace slskd.Configuration { + /// + /// Extension methods for the Configuration namespace. + /// public static class ConfigurationExtensions { + /// + /// Converts an mapping to a mapping. + /// + /// The option mapping to convert. + /// The converted mapping. public static CommandLineArgument ToCommandLineArgument(this Option option) => new(option.ShortName, option.LongName, option.Type, option.Key, option.Description); + /// + /// Converts an mapping to a mapping. + /// + /// The option mapping to convert. + /// The converted mapping. public static EnvironmentVariable ToEnvironmentVariable(this Option option) => new(option.EnvironmentVariable, option.Type, option.Key, option.Description); + /// + /// Converts an mapping to a mapping. + /// + /// The option mapping to convert. + /// The converted mapping. 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 5bbba10e..07e4f1b7 100644 --- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs +++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs @@ -15,7 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -#pragma warning disable SA1649 // File name should match first type name namespace slskd.Configuration { using System; @@ -24,7 +23,7 @@ namespace slskd.Configuration using Microsoft.Extensions.Configuration; /// - /// Defines an default value mapping. + /// Defines a default value mapping. /// public record DefaultValue(string Key, Type Type, object Default); @@ -38,11 +37,8 @@ namespace slskd.Configuration /// /// The to which to add. /// A list of default value mappings. - /// - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// /// The updated . - public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable map, bool normalizeKey = true) + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable map) { if (builder == null) { @@ -52,7 +48,6 @@ namespace slskd.Configuration return builder.AddDefaultValues(s => { s.Map = map ?? Enumerable.Empty(); - s.NormalizeKey = normalizeKey; }); } @@ -78,11 +73,9 @@ namespace slskd.Configuration public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) { Map = source.Map; - NormalizeKey = source.NormalizeKey; } private IEnumerable Map { get; set; } - private bool NormalizeKey { get; set; } /// /// Sets the keys specified in the map to the specified default values. @@ -93,17 +86,7 @@ namespace slskd.Configuration { var (key, _, value) = item; - if (NormalizeKey) - { - key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant(); - } - - if (string.IsNullOrEmpty(key)) - { - continue; - } - - if (value == null) + if (string.IsNullOrEmpty(key) || value == null) { continue; } @@ -123,11 +106,6 @@ namespace slskd.Configuration /// public IEnumerable Map { get; set; } - /// - /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// - public bool NormalizeKey { get; set; } - /// /// Builds the for this source. /// @@ -138,5 +116,4 @@ namespace slskd.Configuration return new DefaultValueConfigurationProvider(this); } } -} -#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs index 51ddf535..21775689 100644 --- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs +++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs @@ -15,7 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -#pragma warning disable SA1649 // File name should match first type name namespace slskd.Configuration { using System; @@ -39,11 +38,8 @@ namespace slskd.Configuration /// The to which to add. /// A list of environment variable mappings. /// A prefix to prepend to all variable names. - /// - /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). - /// /// The updated . - public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map, string prefix = null, bool normalizeKey = true) + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable map, string prefix = null) { if (builder == null) { @@ -54,7 +50,6 @@ namespace slskd.Configuration { s.Map = map ?? Enumerable.Empty(); s.Prefix = prefix ?? string.Empty; - s.NormalizeKey = normalizeKey; }); } @@ -81,11 +76,9 @@ namespace slskd.Configuration { Map = source.Map; Prefix = source.Prefix; - NormalizeKey = source.NormalizeKey; } private IEnumerable Map { get; set; } - private bool NormalizeKey { get; set; } private string Prefix { get; set; } /// @@ -97,11 +90,6 @@ namespace slskd.Configuration { var (name, type, key, _) = item; - if (NormalizeKey) - { - key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant(); - } - if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name)) { continue; @@ -154,5 +142,4 @@ namespace slskd.Configuration return new EnvironmentVariableConfigurationProvider(this); } } -} -#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file +} \ No newline at end of file diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs index 7766e14c..332df647 100644 --- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -15,7 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -#pragma warning disable SA1649 // File name should match first type name namespace slskd.Configuration { using System; @@ -34,7 +33,7 @@ namespace slskd.Configuration /// /// Adds a YAML configuration source to . /// - /// The to add to. + /// The to which to add . /// /// Path relative to the base path stored in of . /// @@ -43,7 +42,7 @@ namespace slskd.Configuration /// /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). /// - /// The to use to access the file. + /// The updated to use to access the file. /// The . public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) { @@ -71,9 +70,9 @@ namespace slskd.Configuration /// /// Adds a YAML configuration source to . /// - /// The to add to. + /// The to which to add. /// Configures the source. - /// The . + /// The updated . public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action configureSource) => builder.Add(configureSource); } @@ -178,5 +177,4 @@ namespace slskd.Configuration return new YamlConfigurationProvider(this); } } -} -#pragma warning restore SA1649 // File name should match first type name \ No newline at end of file +} \ No newline at end of file diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index b48853ef..af78e68d 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1,12 +1,32 @@ -namespace slskd +// +// 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/. +// + +namespace slskd { - using slskd.Validation; - using Soulseek.Diagnostics; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; + using slskd.Validation; + using Soulseek.Diagnostics; + /// + /// Defines an option mapping. + /// public record Option(char ShortName, string LongName, string EnvironmentVariable, string Key, Type Type, object Default = null, string Description = null); public class Options @@ -17,11 +37,11 @@ public bool NoLogo { get; private set; } = false; public string InstanceName { get; private set; } = "default"; [Validate] - public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); + public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions(); [Validate] - public WebOptions Web { get; private set; } = new WebOptions(); + public WebOptions Web { get; private set; } = new WebOptions(); [Validate] - public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); [Validate] public FeatureOptions Feature { get; private set; } = new FeatureOptions(); [Validate] @@ -336,7 +356,7 @@ ShortName: default, LongName: "prometheus", EnvironmentVariable: "PROMETHEUS", - Key: "slskd:feature:prometheus", + Key: "slskd:feature:prometheus", Type: typeof(bool), Default: Defaults.Feature.Prometheus, Description: "enable collection and publishing of prometheus metrics"), -- cgit v1.2.3 From 62b44e06b3f311970e8835d647c97de5498f394e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Feb 2021 21:14:33 -0600 Subject: simplify option mapping --- .../CommandLineConfigurationSource.cs | 21 ++++------ .../Configuration/ConfigurationExtensions.cs | 49 ---------------------- .../DefaultValueConfigurationSource.cs | 19 +++------ .../EnvironmentVariableConfigurationSource.cs | 21 ++++------ src/slskd/Program.cs | 10 ++--- 5 files changed, 25 insertions(+), 95 deletions(-) delete mode 100644 src/slskd/Common/Configuration/ConfigurationExtensions.cs (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs index 088d5ea6..417e5729 100644 --- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -23,11 +23,6 @@ namespace slskd.Configuration using Microsoft.Extensions.Configuration; using Utility.CommandLine; - /// - /// Defines a command line argument mapping. - /// - public record CommandLineArgument(char ShortName, string LongName, Type Type, string Key, string Description = null); - /// /// Extension methods for adding . /// @@ -40,7 +35,7 @@ namespace slskd.Configuration /// A list of command line argument mappings. /// The command line string from which to parse arguments. /// The updated . - public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable map, string commandLine = null) + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable