diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-01-31 11:15:35 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-01-31 11:15:35 -0600 |
| commit | 36ecf12404338bacf1fdd90334c252f89c897b3e (patch) | |
| tree | 59772d1c8276bf363c33cd2875f395c9dba1ac5c /src | |
| parent | cec869b9456cf6fe5597847948b2d75b9846755a (diff) | |
| parent | c9cd2a67ea65570cbd8bd72f09ff5383b1a5c2fe (diff) | |
| download | slskd-36ecf12404338bacf1fdd90334c252f89c897b3e.tar.gz | |
Merge pull request #24 from slskd/config
Add app configuration
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Configuration/CommandLineArguments.cs | 666 | ||||
| -rw-r--r-- | src/slskd/Common/Configuration/CommandLineConfigurationSource.cs | 139 | ||||
| -rw-r--r-- | src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs | 121 | ||||
| -rw-r--r-- | src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs | 137 | ||||
| -rw-r--r-- | src/slskd/Common/Configuration/YamlConfigurationSource.cs | 158 | ||||
| -rw-r--r-- | src/slskd/Controllers/ApplicationController.cs | 59 | ||||
| -rw-r--r-- | src/slskd/Controllers/ServerController.cs | 6 | ||||
| -rw-r--r-- | src/slskd/Controllers/SessionController.cs | 34 | ||||
| -rw-r--r-- | src/slskd/DTO/RoomResponse.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Entities/Room.cs (renamed from src/slskd/Room.cs) | 3 | ||||
| -rw-r--r-- | src/slskd/Options.cs | 328 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 311 | ||||
| -rw-r--r-- | src/slskd/Security/Role.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Startup.cs | 205 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 11 | ||||
| -rw-r--r-- | src/slskd/slskd.yml | 37 |
16 files changed, 1945 insertions, 280 deletions
diff --git a/src/slskd/Common/Configuration/CommandLineArguments.cs b/src/slskd/Common/Configuration/CommandLineArguments.cs new file mode 100644 index 00000000..133fd334 --- /dev/null +++ b/src/slskd/Common/Configuration/CommandLineArguments.cs @@ -0,0 +1,666 @@ +namespace slskd +{ + using System; + using System.Collections; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Reflection; + using System.Runtime.CompilerServices; + using System.Text.RegularExpressions; + + /// <summary> + /// Provides extension method(s) for the CommandLineArguments namespace. + /// </summary> + public static class CommandLineArgumentsExtensions + { + /// <summary> + /// Gets the DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>. + /// </summary> + /// <param name="caller">The name of the calling method for which the DeclaringType is to be fetched.</param> + /// <returns>The DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>.</returns> + internal static Type GetCallingType(string caller) + { + var callingMethod = new StackTrace().GetFrames() + .Select(f => f.GetMethod()) + .FirstOrDefault(m => m.Name == caller); + + if (callingMethod == default) + { + throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type."); + } + + return callingMethod.DeclaringType; + } + + /// <summary> + /// Removes the outermost pair of enclosing quotes. + /// </summary> + /// <param name="value">The string to trim.</param> + /// <returns>The trimmed string.</returns> + internal static string TrimOuterQuotes(this string value) + { + if (value.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase)) + { + value = value.Trim('"'); + } + else if (value.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("'", StringComparison.InvariantCultureIgnoreCase)) + { + value = value.Trim('\''); + } + + return value; + } + } + + /// <summary> + /// Indicates that the property is to be used as a target for automatic population of values from command line arguments + /// when invoking the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method. + /// </summary> + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public class CommandLineArgumentAttribute : Attribute + { + /// <summary> + /// Initializes a new instance of the <see cref="CommandLineArgumentAttribute"/> class. + /// </summary> + /// <param name="shortName">The short name of the argument, represented as a single character.</param> + /// <param name="longName">The long name of the argument.</param> + /// <param name="helpText">The help text of the argument.</param> + public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null) + { + ShortName = shortName; + LongName = longName; + HelpText = helpText; + } + + /// <summary> + /// Gets or sets the help text of the argument. + /// </summary> + public string HelpText { get; set; } + + /// <summary> + /// Gets or sets the long name of the argument. + /// </summary> + public string LongName { get; set; } + + /// <summary> + /// Gets or sets the short name of the argument. + /// </summary> + public char ShortName { get; set; } + } + + /// <summary> + /// Encapsulates argument names and help text. + /// </summary> + public class ArgumentInfo + { + /// <summary> + /// Initializes a new instance of the <see cref="ArgumentInfo"/> class. + /// </summary> + /// <param name="shortName">The short name of the argument.</param> + /// <param name="longName">The long name of the argument.</param> + /// <param name="helpText">The help text for the argument.</param> + /// <param name="property">The property with which the argument is associated.</param> + public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property) + { + ShortName = shortName; + LongName = longName; + HelpText = helpText; + Property = property; + } + + /// <summary> + /// Gets the help text for the argument. + /// </summary> + public string HelpText { get; } + + /// <summary> + /// Gets a value indicating whether the argument backing Type is a collection. + /// </summary> + public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)); + + /// <summary> + /// Gets the long name of the argument. + /// </summary> + public string LongName { get; } + + /// <summary> + /// Gets the property with which the argument is associated. + /// </summary> + public PropertyInfo Property { get; } + + /// <summary> + /// Gets the short name of the argument. + /// </summary> + public char ShortName { get; } + } + + /// <summary> + /// Provides static methods used to retrieve the command line arguments and operands with which the application was + /// started, as well as a Type to contain them. + /// </summary> + public class CommandLineArguments + { + /// <summary> + /// The regular expression with which to parse the command line string. + /// </summary> + private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; + + /// <summary> + /// The regular expression with which to parse the command line string, including the ability to specify forward slashes. + /// </summary> + private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')"; + + /// <summary> + /// The regular expression with which to parse argument-value groups. + /// </summary> + private const string GroupRegEx = "^-[^-]+"; + + /// <summary> + /// The regular expression with which to parse strings strictly containing operands. + /// </summary> + private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')"; + + /// <summary> + /// The regular expression with which to split the command line string explicitly among argument/value pairs and + /// operands, and strictly operands. + /// </summary> + /// <remarks> + /// This regular expression effectively splits a string into two parts; the part before the first "--", and the part + /// after. Instances of "--" not surrounded by a word boundary and those enclosed in quotes are ignored. + /// </remarks> + private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)"; + + private CommandLineArguments(string commandLineString, List<KeyValuePair<string, string>> argumentList, Dictionary<string, object> argumentDictionary, List<string> operandList, Type targetType = null) + { + CommandLineString = commandLineString; + ArgumentList = argumentList; + ArgumentDictionary = argumentDictionary; + OperandList = operandList; + TargetType = targetType; + } + + /// <summary> + /// Gets or sets a value indicating whether forward slashes are processed as argument delimiters. + /// </summary> + public static bool EnableForwardSlash { get; set; } = false; + + /// <summary> + /// Gets a dictionary containing the arguments and values specified in the command line arguments with which the + /// application was started. + /// </summary> + /// <remarks> + /// This dictionary contains argument key/value pairs compiled from the <see cref="ArgumentList"/> and checked against + /// the <see cref="TargetType"/> to combine duplicated pairs into lists where the backing property is a collection, and + /// to overwrite where the backing property is not a collection. + /// </remarks> + public Dictionary<string, object> ArgumentDictionary { get; } + + /// <summary> + /// Gets the list of arguments specified in the command line arguments with which the application was started. + /// </summary> + /// <remarks> + /// This list contains each argument key/value pair as supplied in the original string, preserving the original order + /// and any duplicated pairs. + /// </remarks> + public List<KeyValuePair<string, string>> ArgumentList { get; } + + /// <summary> + /// Gets the command line string from which the arguments were parsed. + /// </summary> + public string CommandLineString { get; } + + /// <summary> + /// Gets a list containing the operands specified in the command line arguments with which the application was started. + /// </summary> + public List<string> OperandList { get; private set; } + + /// <summary> + /// Gets the target Type, if applicable. + /// </summary> + public Type TargetType { get; } + + private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash; + + /// <summary> + /// Gets the argument value corresponding to the specified <paramref name="index"/>. + /// </summary> + /// <param name="index">The index for which the value is to be retrieved.</param> + /// <returns>The argument value corresponding to the specified index.</returns> + public object this[int index] + { + get + { + return ArgumentList[index].Value; + } + } + + /// <summary> + /// Gets the argument value corresponding to the specified <paramref name="key"/> from the + /// <see cref="ArgumentDictionary"/> property. + /// </summary> + /// <param name="key">The key for which the value is to be retrieved.</param> + /// <returns>The argument value corresponding to the specified key.</returns> + public object this[string key] + { + get + { + return ArgumentDictionary[key]; + } + } + + /// <summary> + /// Retrieves a collection of <see cref="ArgumentInfo"/> gathered from properties in the target <paramref name="type"/> + /// marked with the <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> along with the short and long names and help text. + /// </summary> + /// <param name="type">The <see cref="Type"/> for which the matching properties are to be retrieived.</param> + /// <param name="caller">Internal parameter used to identify the calling method.</param> + /// <returns>The retrieved collection of <see cref="ArgumentInfo"/>.</returns> + public static IEnumerable<ArgumentInfo> GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default) + { + type ??= CommandLineArgumentsExtensions.GetCallingType(caller); + var retVal = new List<ArgumentInfo>(); + + foreach (PropertyInfo property in GetArgumentProperties(type).Values.Distinct()) + { + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name); + + if (attribute != default(CustomAttributeData)) + { + retVal.Add(new ArgumentInfo( + shortName: (char)attribute.ConstructorArguments[0].Value, + longName: (string)attribute.ConstructorArguments[1].Value, + helpText: (string)attribute.ConstructorArguments[2].Value, + property: property)); + } + } + + return retVal; + } + + /// <summary> + /// Returns a dictionary containing the values specified in the command line arguments with which the application was + /// started, keyed by argument name. + /// </summary> + /// <param name="commandLineString">The command line arguments with which the application was started.</param> + /// <param name="type">The <see cref="Type"/> for which the command line string is to be parsed.</param> + /// <returns> + /// The dictionary containing the arguments and values specified in the command line arguments with which the + /// application was started. + /// </returns> + public static CommandLineArguments Parse(string commandLineString = default, Type type = null) + { + commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString; + + List<KeyValuePair<string, string>> argumentList; + List<string> operandList; + + // use the strict operand regular expression to test for/extract the two halves of the string, if the operator is used. + MatchCollection matches = Regex.Matches(commandLineString, StrictOperandSplitRegEx); + + // if there is a match, the string contains the strict operand delimiter. parse the first and second matches accordingly. + if (matches.Count > 0) + { + // the first group of the first match will contain everything in the string prior to the strict operand delimiter, + // so extract the argument key/value pairs and list of operands from that string. + argumentList = GetArgumentList(matches[0].Groups[1].Value); + operandList = GetOperandList(matches[0].Groups[1].Value); + + // the first group of the second match will contain everything in the string after the strict operand delimiter, so + // extract the operands from that string using the strict method. + if (!string.IsNullOrEmpty(matches[0].Groups[3].Value)) + { + List<string> operandListStrict = GetOperandListStrict(matches[0].Groups[3].Value); + operandList.AddRange(operandListStrict); + } + } + else + { + argumentList = GetArgumentList(commandLineString); + operandList = GetOperandList(commandLineString); + } + + var argumentDictionary = GetArgumentDictionary(argumentList, type); + return new CommandLineArguments(commandLineString, argumentList, argumentDictionary, operandList, type); + } + + /// <summary> + /// Populates the properties in the invoking class marked with the + /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line + /// arguments, if present. + /// </summary> + /// <param name="commandLineString">The command line arguments with which the application was started.</param> + /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param> + /// <param name="caller">Internal parameter used to identify the calling method.</param> + public static void Populate(string commandLineString = default, bool clearExistingValues = true, [CallerMemberName] string caller = default) + { + var type = CommandLineArgumentsExtensions.GetCallingType(caller); + Populate(type, Parse(commandLineString, type), clearExistingValues); + } + + /// <summary> + /// Populates the properties in the specified Type marked with the + /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line + /// arguments, if present. + /// </summary> + /// <param name="type"> + /// The Type for which the static properties matching the list of command line arguments are to be populated. + /// </param> + /// <param name="commandLineString">The command line arguments with which the application was started.</param> + /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param> + public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true) + { + Populate(type, Parse(commandLineString, type), clearExistingValues); + } + + /// <summary> + /// Populates the properties in the specified Type marked with the + /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the specified argument + /// dictionary, if present. All property values are set to null at the start of the routine. + /// </summary> + /// <param name="type"> + /// The Type for which the static properties matching the list of command line arguments are to be populated. + /// </param> + /// <param name="arguments"> + /// The Arguments object containing the dictionary containing the argument-value pairs with which the destination + /// properties should be populated and the list of operands. + /// </param> + /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param> + public static void Populate(Type type, CommandLineArguments arguments, bool clearExistingValues = true) + { + // fetch any properties in the specified type marked with the ArgumentAttribute attribute and clear them + Dictionary<string, PropertyInfo> properties = GetArgumentProperties(type); + + if (clearExistingValues) + { + ClearProperties(properties); + } + + foreach (string propertyName in properties.Keys) + { + // if the argument dictionary contains a matching argument + if (arguments.ArgumentDictionary.ContainsKey(propertyName)) + { + // retrieve the property and type + PropertyInfo property = properties[propertyName]; + Type propertyType = property.PropertyType; + + // retrieve the value from the argument dictionary + object value = arguments.ArgumentDictionary[propertyName]; + + object convertedValue; + + // if the type of the property is bool and the argument value is empty set the property value to true, + // indicating the argument is present + if (propertyType == typeof(bool)) + { + convertedValue = true; + + // if a value is specified, a bool flag was followed by an operand and the parser interpreted this as key + // value pair because it wasn't aware the flag was backed by a bool. remove the argument from the original + // string and re-parse operands from it to preserve order. + if (!string.IsNullOrEmpty(value.ToString())) + { + var arg = Regex.Matches(arguments.CommandLineString, "(?:[-]{1,2}|\\/)" + propertyName)[0].Value; + arguments.OperandList = GetOperandList(arguments.CommandLineString.Replace(arg, string.Empty)); + } + } + else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>))) + { + convertedValue = value; + + // next, create a list with the same type as the target property + Type valueType; + + if (propertyType.IsArray) + { + valueType = propertyType.GetElementType(); + } + else + { + valueType = propertyType.GetGenericArguments()[0]; + } + + // create a list to store converted values + Type valueListType = typeof(List<>).MakeGenericType(valueType); + var valueList = (IList)Activator.CreateInstance(valueListType); + + // populate the list + foreach (object v in (List<object>)convertedValue) + { + valueList.Add(ChangeType(v, propertyName, valueType)); + } + + // if the target property is an array, create one and populate it from the list this is surprisingly + // difficult here because we created the source list with the Activator and ToArray() won't work easily. + if (propertyType.IsArray) + { + var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count); + + for (int i = 0; i < valueArray.Length; i++) + { + valueArray.SetValue(valueList[i], i); + } + + convertedValue = valueArray; + } + else + { + convertedValue = valueList; + } + } + else + { + convertedValue = ChangeType(value, propertyName, propertyType); + } + + // set the target properties' value to the converted value from the argument string + property.SetValue(null, convertedValue); + } + } + + PropertyInfo operandsProperty = GetOperandsProperty(type); + + // check to ensure the target class has a property marked with the Operands attribute; if not GetOperandsProperty() + // will return null. + if (operandsProperty != default) + { + if (operandsProperty.PropertyType.IsAssignableFrom(typeof(List<string>))) + { + operandsProperty.SetValue(null, arguments.OperandList); + } + else + { + operandsProperty.SetValue(null, arguments.OperandList.ToArray()); + } + } + } + + private static object ChangeType(object value, string argument, Type toType) + { + try + { + if (toType.IsEnum) + { + return Enum.Parse(toType, (string)value, true); + } + + return Convert.ChangeType(value, toType, CultureInfo.InvariantCulture); + } + catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) + { + string message = $"Specified value '{value}' for argument '{argument}' (expected type: {toType}). "; + message += "See inner exception for details."; + + throw new ArgumentException(message, ex); + } + } + + private static void ClearProperties(Dictionary<string, PropertyInfo> properties) + { + foreach (string key in properties.Keys) + { + properties[key].SetValue(null, null); + } + } + + private static Dictionary<string, object> GetArgumentDictionary(List<KeyValuePair<string, string>> argumentList, Type targetType = null) + { + var dict = new ConcurrentDictionary<string, object>(); + var argumentInfo = targetType == null ? new List<ArgumentInfo>() : GetArgumentInfo(targetType); + + foreach (var arg in argumentList) + { + var info = argumentInfo.SingleOrDefault(i => i.ShortName.ToString(CultureInfo.InvariantCulture) == arg.Key || i.LongName == arg.Key); + + if (info != default(ArgumentInfo)) + { + bool added = false; + + foreach (var k in new[] { info.ShortName.ToString(CultureInfo.InvariantCulture), info.LongName }) + { + if (dict.ContainsKey(k)) + { + dict.AddOrUpdate(k, arg.Value, (key, existingValue) => info.IsCollection ? ((List<object>)existingValue).Concat(new[] { arg.Value }).ToList() : (object)arg.Value); + added = true; + break; + } + } + + if (!added) + { + dict.TryAdd(arg.Key, info.IsCollection ? new List<object>(new[] { arg.Value }) : (object)arg.Value); + } + } + else + { + dict.AddOrUpdate(arg.Key, arg.Value, (key, existingValue) => arg.Value); + } + } + + return dict.ToDictionary(a => a.Key, a => a.Value); + } + + private static List<KeyValuePair<string, string>> GetArgumentList(string commandLineString) + { + var argumentList = new List<KeyValuePair<string, string>>(); + + foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx)) + { + // the first match of the regular expression used to parse the string will contain the argument name, if one was matched. + if (match.Groups[1].Value == default || string.IsNullOrEmpty(match.Groups[1].Value)) + { + continue; + } + + string fullMatch = match.Groups[0].Value; + string argument = match.Groups[1].Value; + string value = match.Groups[2].Value; + + value = value.TrimOuterQuotes(); + + // check to see if the argument uses a single dash. if so, split the argument name into a char array and add each + // to the list. if a value is specified, it belongs to the final character. + if (Regex.IsMatch(fullMatch, GroupRegEx)) + { + char[] charArray = argument.ToCharArray(); + + // iterate over the characters backwards to more easily assign the value + for (int i = 0; i < charArray.Length; i++) + { + argumentList.Add(new KeyValuePair<string, string>(charArray[i].ToString(CultureInfo.InvariantCulture), i == charArray.Length - 1 ? value : string.Empty)); + } + } + else + { + argumentList.Add(new KeyValuePair<string, string>(argument, value)); + } + } + + return argumentList; + } + + private static Dictionary<string, PropertyInfo> GetArgumentProperties(Type type) + { + Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>(); + + foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) + { + // attempt to fetch the ArgumentAttribute of the property + CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name); + + // if found, extract the Name property and add it to the dictionary + if (attribute != default(CustomAttributeData)) + { + char shortName = (char)attribute.ConstructorArguments[0].Value; + string longName = (string)attribute.ConstructorArguments[1].Value; + + if (!properties.ContainsKey(shortName.ToString(CultureInfo.InvariantCulture)) && !properties.ContainsKey(longName)) + { + properties.Add(shortName.ToString(CultureInfo.InvariantCulture), property); + properties.Add(longName, property); + } + } + } + + return properties; + } + + private static List<string> GetOperandList(string commandLineString) + { + List<string> operands = new List<string>(); + + foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx)) + { + // the 3rd match of the regular expression used to parse the string will contain the operand, if one was matched. + if (match.Groups[3].Value == default || string.IsNullOrEmpty(match.Groups[3].Value)) + { + continue; + } + + string operand = match.Groups[3].Value; + + operands.Add(operand.TrimOuterQuotes()); + } + + return operands; + } + + private static List<string> GetOperandListStrict(string operandListString) + { + List<string> operands = new List<string>(); + + foreach (Match match in Regex.Matches(operandListString, OperandRegEx)) + { + operands.Add(match.Groups[0].Value); + } + + return operands; + } + + private static PropertyInfo GetOperandsProperty(Type type) + { + PropertyInfo property = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) + .FirstOrDefault(p => p.CustomAttributes + .Any(a => a.AttributeType.Name == typeof(OperandsAttribute).Name)); + + if (property != default && property.PropertyType != typeof(string[]) && property.PropertyType != typeof(List<string>)) + { + throw new InvalidCastException("The target for the Operands attribute must be of string[] or List<string>."); + } + + return property; + } + } + + /// <summary> + /// Indicates that the property is to be used as the target for automatic population of command line operands when invoking + /// the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method. + /// </summary> + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + public class OperandsAttribute : Attribute + { + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs new file mode 100644 index 00000000..c65e316b --- /dev/null +++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs @@ -0,0 +1,139 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Defines a command line argument mapping. + /// </summary> + public record CommandLineArgument(char ShortName, string LongName, Type Type, string Key, string Description = null); + + /// <summary> + /// Extension methods for adding <see cref="CommandLineConfigurationProvider"/>. + /// </summary> + public static class CommandLineExtensions + { + /// <summary> + /// Adds a command line argument configuration soruce to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <param name="map">A list of command line argument mappings.</param> + /// <param name="commandLine">The command line string from which to parse arguments.</param> + /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param> + /// <returns></returns> + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable<CommandLineArgument> map, string commandLine = null, bool normalizeKey = true) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.AddCommandLine(s => + { + s.Map = map; + s.CommandLine = commandLine ?? Environment.CommandLine; + s.NormalizeKey = normalizeKey; + }); + } + + /// <summary> + /// Adds a command line argument configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <param name="configureSource">Configures the source.</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action<CommandLineConfigurationSource> configureSource) + => builder.Add(configureSource); + } + + /// <summary> + /// Represents command line arguments as an <see cref="IConfigurationSource"/>. + /// </summary> + public class CommandLineConfigurationSource : IConfigurationSource + { + /// <summary> + /// Builds the <see cref="CommandLineConfigurationProvider"/> for this source. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <returns>A <see cref="CommandLineConfigurationProvider"/>.</returns> + public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this); + + /// <summary> + /// Gets or sets a list of command line argument mappings. + /// </summary> + public IEnumerable<CommandLineArgument> Map { get; set; } + + /// <summary> + /// Gets or sets the command line string from which to parse arguments. + /// </summary> + public string CommandLine { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// </summary> + public bool NormalizeKey { get; set; } + } + + /// <summary> + /// A command line argument <see cref="ConfigurationProvider"/>. + /// </summary> + public class CommandLineConfigurationProvider : ConfigurationProvider + { + private IEnumerable<CommandLineArgument> Map { get; set; } + private string CommandLine { get; set; } + private bool NormalizeKey { get; set; } + + /// <summary> + /// Initializes a new instance with the specified source. + /// </summary> + /// <param name="source">The source settings.</param> + public CommandLineConfigurationProvider(CommandLineConfigurationSource source) + { + Map = source.Map; + CommandLine = source.CommandLine; + NormalizeKey = source.NormalizeKey; + } + + /// <summary> + /// Parses command line arguments from the specified string and maps them to the specified keys. + /// </summary> + public override void Load() + { + var dictionary = CommandLineArguments.Parse(CommandLine).ArgumentDictionary; + + foreach (CommandLineArgument item in Map) + { + var (shortName, longName, type, key, _) = item; + + if (NormalizeKey) + { + key = key?.Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant(); + } + + if (string.IsNullOrEmpty(key)) + { + continue; + } + + var arguments = new[] { shortName.ToString(), longName }.Where(i => !string.IsNullOrEmpty(i)); + + foreach (var argument in arguments) + { + if (dictionary.ContainsKey(argument)) + { + var value = dictionary[argument].ToString(); + + if (type == typeof(bool) && string.IsNullOrEmpty(value)) + { + value = "true"; + } + + Data[item.Key] = value; + } + } + } + } + } +} diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs new file mode 100644 index 00000000..57fa2712 --- /dev/null +++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs @@ -0,0 +1,121 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Defines an default value mapping. + /// </summary> + public record DefaultValue(string Key, Type Type, object Default); + + /// <summary> + /// Extension methods for adding <see cref="DefaultValueConfigurationProvider"/>. + /// </summary> + public static class DefaultValueConfigurationExtensions + { + /// <summary> + /// Adds a default value configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="map">A list of default value mappings.</param> + /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable<DefaultValue> map, bool normalizeKey = true) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.AddDefaultValues(s => + { + s.Map = map ?? Enumerable.Empty<DefaultValue>(); + s.NormalizeKey = normalizeKey; + }); + } + + /// <summary> + /// Adds a default value configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="configureSource">Configures the source.</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action<DefaultValueConfigurationSource> configureSource) + => builder.Add(configureSource); + } + + /// <summary> + /// Represents default values as an <see cref="IConfigurationSource"/>. + /// </summary> + public class DefaultValueConfigurationSource : IConfigurationSource + { + /// <summary> + /// Builds the <see cref="DefaultValueConfigurationProvider"/> for this source. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <returns>A <see cref="DefaultValueConfigurationProvider"/>.</returns> + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new DefaultValueConfigurationProvider(this); + } + + /// <summary> + /// Gets or sets a list of default value mappings. + /// </summary> + public IEnumerable<DefaultValue> Map { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// </summary> + public bool NormalizeKey { get; set; } + } + + /// <summary> + /// A default value <see cref="ConfigurationProvider"/>. + /// </summary> + public class DefaultValueConfigurationProvider : ConfigurationProvider + { + /// <summary> + /// Initializes a new instance with the specified source. + /// </summary> + /// <param name="source">The source settings.</param> + public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source) + { + Map = source.Map; + NormalizeKey = source.NormalizeKey; + } + + private IEnumerable<DefaultValue> Map { get; set; } + private bool NormalizeKey { get; set; } + + /// <summary> + /// Sets the keys specified in the map to the specified default values. + /// </summary> + public override void Load() + { + foreach (var item in Map) + { + var (key, _, value) = item; + + if (NormalizeKey) + { + key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant(); + } + + if (string.IsNullOrEmpty(key)) + { + continue; + } + + if (value == null) + { + continue; + } + + Data[item.Key] = value.ToString(); + } + } + } +} diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs new file mode 100644 index 00000000..2ace942b --- /dev/null +++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs @@ -0,0 +1,137 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using System; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Defines an environment variable mapping. + /// </summary> + public record EnvironmentVariable(string Name, Type Type, string Key, string Description = null); + + /// <summary> + /// Extension methods for adding <see cref="EnvironmentVariableConfigurationProvider"/>. + /// </summary> + public static class EnvironmentVariableConfigurationExtensions + { + /// <summary> + /// Adds an environment variable configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="map">A list of environment variable mappings.</param> + /// <param name="prefix">A prefix to prepend to all variable names.</param> + /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable<EnvironmentVariable> map, string prefix = null, bool normalizeKey = true) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + return builder.AddEnvironmentVariables(s => + { + s.Map = map ?? Enumerable.Empty<EnvironmentVariable>(); + s.Prefix = prefix ?? string.Empty; + s.NormalizeKey = normalizeKey; + }); + } + + /// <summary> + /// Adds an enviroment variable configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="configureSource">Configures the source.</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariableConfigurationSource> configureSource) + => builder.Add(configureSource); + } + + /// <summary> + /// Represents environment variables as an <see cref="IConfigurationSource"/>. + /// </summary> + public class EnvironmentVariableConfigurationSource : IConfigurationSource + { + /// <summary> + /// Builds the <see cref="EnvironmentVariableConfigurationProvider"/> for this source. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <returns>A <see cref="EnvironmentVariableConfigurationProvider"/>.</returns> + public IConfigurationProvider Build(IConfigurationBuilder builder) + { + return new EnvironmentVariableConfigurationProvider(this); + } + + /// <summary> + /// Gets or sets a list of enviroment variable mappings. + /// </summary> + public IEnumerable<EnvironmentVariable> Map { get; set; } + + /// <summary> + /// Gets or sets a prefix to prepend to all variable names. + /// </summary> + public string Prefix { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// </summary> + public bool NormalizeKey { get; set; } + } + + /// <summary> + /// An enviroment variable <see cref="ConfigurationProvider"/>. + /// </summary> + public class EnvironmentVariableConfigurationProvider : ConfigurationProvider + { + /// <summary> + /// Initializes a new instance with the specified source. + /// </summary> + /// <param name="source">The source settings.</param> + public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source) + { + Map = source.Map; + Prefix = source.Prefix; + NormalizeKey = source.NormalizeKey; + } + + private IEnumerable<EnvironmentVariable> Map { get; set; } + private bool NormalizeKey { get; set; } + private string Prefix { get; set; } + + /// <summary> + /// Loads environment variables and maps them to the specified keys. + /// </summary> + public override void Load() + { + foreach (var item in Map) + { + var (name, type, key, _) = item; + + if (NormalizeKey) + { + key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant(); + } + + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name)) + { + continue; + } + + var value = Environment.GetEnvironmentVariable(Prefix + name); + + if (string.IsNullOrEmpty(value)) + { + continue; + } + + if (type == typeof(bool)) + { + value = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) ? value : "false"; + } + + Data[item.Key] = value; + } + } + } +} diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs new file mode 100644 index 00000000..f95f39ca --- /dev/null +++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs @@ -0,0 +1,158 @@ +namespace slskd +{ + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.FileProviders; + using System; + using System.IO; + using System.Linq; + using YamlDotNet.Core; + using YamlDotNet.RepresentationModel; + + /// <summary> + /// Extension methods for adding <see cref="YamlConfigurationProvider"/>. + /// </summary> + public static class YamlConfigurationExtensions + { + /// <summary> + /// Adds a YAML configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="path">Path relative to the base path stored in + /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> + /// <param name="optional">Whether the file is optional.</param> + /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> + /// <param name="normalizeKeys">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param> + /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null) + { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentException("File path must be a non-empty string.", nameof(path)); + } + + return builder.AddYamlFile(s => + { + s.Path = path; + s.Optional = optional; + s.ReloadOnChange = reloadOnChange; + s.NormalizeKeys = normalizeKeys; + s.FileProvider = provider; + s.ResolveFileProvider(); + }); + } + + /// <summary> + /// Adds a YAML configuration source to <paramref name="builder"/>. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> + /// <param name="configureSource">Configures the source.</param> + /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> + public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action<YamlConfigurationSource> configureSource) + => builder.Add(configureSource); + } + + /// <summary> + /// Represents a YAML file as an <see cref="IConfigurationSource"/>. + /// </summary> + public class YamlConfigurationSource : FileConfigurationSource + { + /// <summary> + /// Builds the <see cref="YamlConfigurationProvider"/> for this source. + /// </summary> + /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param> + /// <returns>A <see cref="YamlConfigurationProvider"/></returns> + public override IConfigurationProvider Build(IConfigurationBuilder builder) + { + EnsureDefaults(builder); + return new YamlConfigurationProvider(this); + } + + /// <summary> + /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase). + /// </summary> + public bool NormalizeKeys { get; set; } + } + + /// <summary> + /// A YAML file based <see cref="FileConfigurationProvider"/>. + /// </summary> + public class YamlConfigurationProvider : FileConfigurationProvider + { + /// <summary> + /// Initializes a new instance with the specified source. + /// </summary> + /// <param name="source">The source settings.</param> + public YamlConfigurationProvider(YamlConfigurationSource source) + : base(source) + { + NormalizeKeys = source.NormalizeKeys; + } + + private bool NormalizeKeys { get; set; } + private string[] NullValues { get; } = new[] { "~", "null", "" }; + + /// <summary> + /// Loads the YAML data from a stream. + /// </summary> + /// <param name="stream">The stream to read.</param> + public override void Load(Stream stream) + { + try + { + using var reader = new StreamReader(stream); + + var yaml = new YamlStream(); + yaml.Load(reader); + + var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode; + + Traverse(rootNode); + } + catch (YamlException e) + { + throw new FormatException("Could not parse the YAML file.", e); + } + } + + private void Traverse(YamlNode root, string path = null) + { + string Normalize(string str) => NormalizeKeys ? str?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant() : str; + + if (root is YamlScalarNode scalar) + { + if (Data.ContainsKey(Normalize(path))) + { + throw new FormatException($"A duplicate key '{Normalize(path)}' was found."); + } + + var value = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + + if (value != null) + { + Data[Normalize(path)] = NullValues.Contains(scalar.Value.ToLower()) ? null : scalar.Value; + } + } + else if (root is YamlMappingNode map) + { + foreach (var node in map.Children) + { + var key = Normalize(((YamlScalarNode)node.Key).Value); + Traverse(node.Value, path == null ? key : ConfigurationPath.Combine(path, key)); + } + } + else if (root is YamlSequenceNode sequence) + { + for (int i = 0; i < sequence.Children.Count; i++) + { + Traverse(sequence.Children[i], ConfigurationPath.Combine(path, i.ToString())); + } + } + } + } +} diff --git a/src/slskd/Controllers/ApplicationController.cs b/src/slskd/Controllers/ApplicationController.cs new file mode 100644 index 00000000..cc9d56a1 --- /dev/null +++ b/src/slskd/Controllers/ApplicationController.cs @@ -0,0 +1,59 @@ +namespace slskd.Controllers +{ + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using System.Diagnostics; + using System; + using Microsoft.Extensions.Hosting; + using Soulseek; + + /// <summary> + /// Application + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class ApplicationController : ControllerBase + { + private ISoulseekClient Client { get; } + private IHostApplicationLifetime Lifetime { get; } + + public ApplicationController(ISoulseekClient client, IHostApplicationLifetime lifetime) + { + Client = client; + Lifetime = lifetime; + } + + /// <summary> + /// Stops the application. + /// </summary> + /// <returns></returns> + [HttpDelete] + [Authorize] + public IActionResult Shutdown() + { + Client.Disconnect("Shut down via API"); + + Lifetime.StopApplication(); + return NoContent(); + } + + /// <summary> + /// Restarts the application. + /// </summary> + /// <returns></returns> + [HttpPut] + [Authorize] + public IActionResult Restart() + { + Client.Disconnect("Restarted via API"); + + Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); + Lifetime.StopApplication(); + + return NoContent(); + } + } +} diff --git a/src/slskd/Controllers/ServerController.cs b/src/slskd/Controllers/ServerController.cs index 2502a05d..ed6e84c8 100644 --- a/src/slskd/Controllers/ServerController.cs +++ b/src/slskd/Controllers/ServerController.cs @@ -56,12 +56,6 @@ return Ok(); } - if (addr && port && !un && !pw) - { - await Client.ConnectAsync(req.Address, req.Port.Value); - return Ok(); - } - if (!addr && !port && un && pw) { await Client.ConnectAsync(req.Username, req.Password); diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs index 5c162708..235e65cf 100644 --- a/src/slskd/Controllers/SessionController.cs +++ b/src/slskd/Controllers/SessionController.cs @@ -8,6 +8,9 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using slskd.DTO; + using Microsoft.Extensions.Options; + using slskd; + using System.Text.Json; /// <summary> /// Session @@ -19,8 +22,16 @@ [Consumes("application/json")] public class SessionController : ControllerBase { - public SessionController() + private slskd.Options Options { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } + + public SessionController( + IOptionsSnapshot<slskd.Options> optionsSnapshot, + SymmetricSecurityKey jwtSigningKey) { + Options = optionsSnapshot.Value; + Console.WriteLine(JsonSerializer.Serialize(Options)); + JwtSigningKey = jwtSigningKey; } /// <summary> @@ -34,7 +45,7 @@ [ProducesResponseType(typeof(bool), 200)] public IActionResult Enabled() { - return Ok(!Program.DisableAuthentication); + return base.Ok(!Options.Web.Authentication.Disable); } /// <summary> @@ -71,7 +82,7 @@ [ProducesResponseType(400)] [ProducesResponseType(401)] [ProducesResponseType(typeof(string), 500)] - public IActionResult Login([FromBody]LoginRequest login) + public IActionResult Login([FromBody] LoginRequest login) { if (login == default) { @@ -83,29 +94,30 @@ return BadRequest("Username and/or Password missing or invalid"); } - if (login.Username == Startup.Username && login.Password == Startup.Password) + // only admin login for now + if (Options.Web.Authentication.Username == login.Username && Options.Web.Authentication.Password == login.Password) { - return Ok(new TokenResponse(GetJwtSecurityToken())); + return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); } return Unauthorized(); } - private JwtSecurityToken GetJwtSecurityToken() + private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Startup.SecurityTokenTTL); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(Options.Web.Jwt.Ttl); var claims = new List<Claim>() { - new Claim(ClaimTypes.Name, Startup.Username), + new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, "User"), - new Claim("name", Startup.Username), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()) }; - var credentials = new SigningCredentials(Startup.JwtSigningKey, SecurityAlgorithms.HmacSha256); + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "slskd", diff --git a/src/slskd/DTO/RoomResponse.cs b/src/slskd/DTO/RoomResponse.cs index 8bbaa855..22ea845a 100644 --- a/src/slskd/DTO/RoomResponse.cs +++ b/src/slskd/DTO/RoomResponse.cs @@ -1,5 +1,6 @@ namespace slskd.DTO { + using slskd.Entities; using System.Collections.Generic; using System.Linq; diff --git a/src/slskd/Room.cs b/src/slskd/Entities/Room.cs index 28abdedb..71b7f1fc 100644 --- a/src/slskd/Room.cs +++ b/src/slskd/Entities/Room.cs @@ -1,9 +1,8 @@ -namespace slskd +namespace slskd.Entities { using Soulseek; using System.Collections.Generic; using System.Linq; - using slskd.Entities; public class Room { diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs new file mode 100644 index 00000000..b5968b9f --- /dev/null +++ b/src/slskd/Options.cs @@ -0,0 +1,328 @@ +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using YamlDotNet.Serialization; + + public record Option(char ShortName, string LongName, string EnvironmentVariable, string Key, Type Type, object Default = null, string Description = null) + { + public CommandLineArgument ToCommandLineArgument() + => new (ShortName, LongName, Type, Key, Description); + + public EnvironmentVariable ToEnvironmentVariable() + => new (EnvironmentVariable, Type, Key, Description); + + public DefaultValue ToDefaultValue() + => new (Key, Type, Default); + } + + public class Options + { + public static IEnumerable<Option> Map => new Option[] + { + new( + ShortName: 'v', + LongName: "version", + EnvironmentVariable: null, + Key: null, + Type: typeof(bool), + Default: false, + Description: "display version information"), + new( + ShortName: 'h', + LongName: "help", + EnvironmentVariable: null, + Key: null, + Type: typeof(bool), + Default: false, + Description: "display command line usage"), + new( + ShortName: 'e', + LongName: "envars", + EnvironmentVariable: null, + Key: null, + Type: typeof(bool), + Default: false, + Description: "display environment variables"), + new( + ShortName: 'd', + LongName: "debug", + EnvironmentVariable: "DEBUG", + Key: "slskd:debug", + Type: typeof(bool), + Default: Debugger.IsAttached, + Description: "run in debug mode"), + new( + ShortName: 'n', + LongName: "no-logo", + EnvironmentVariable: "NO_LOGO", + Key: "slskd:nologo", + Type: typeof(bool), + Default: false, + Description: "suppress logo on startup"), + new( + ShortName: 'i', + LongName: "instance-name", + EnvironmentVariable: "INSTANCE_NAME", + Key: "slskd:instancename", + Type: typeof(string), + Default: "default", + Description: "optional; a unique name for this instance"), + new( + ShortName: 'l', + LongName: "http-port", + EnvironmentVariable: "HTTP_PORT", + Key: "slskd:web:port", + Type: typeof(int), + Default: 5000, + Description: "HTTP listen port for web server"), + new( + ShortName: 'L', + LongName: "https-port", + EnvironmentVariable: "HTTPS_PORT", + Key: "slskd:web:https:port", + Type: typeof(int), + Default: 5000, + Description: "HTTPS listen port for web server"), + new( + ShortName: 'f', + LongName: "force-https", + EnvironmentVariable: "HTTPS_FORCE", + Key: "slskd:web:https:force", + Type: typeof(bool), + Default: false, + Description: "redirect HTTP to HTTPS"), + new( + ShortName: default, + LongName: "url-base", + EnvironmentVariable: "URL_BASE", + Key: "slskd:web:urlbase", + Type: typeof(string), + Default: "/", + Description: "base url for web requests"), + new( + ShortName: default, + LongName: "content-path", + EnvironmentVariable: "CONTENT_PATH", + Key: "slskd:web:contentpath", + Type: typeof(string), + Default: "wwwroot", + Description: "path to static web content"), + new( + ShortName: 'x', + LongName: "no-auth", + EnvironmentVariable: "NO_AUTH", + Key: "slskd:web:authentication:disable", + Type: typeof(bool), + Default: false, + Description: "disable authentication for web requests"), + new( + ShortName: 'u', + LongName: "username", + EnvironmentVariable: "USERNAME", + Key: "slskd:web:authentication:username", + Type: typeof(string), + Default: "slskd", + Description: "the username for the web UI"), + new( + ShortName: 'p', + LongName: "password", + EnvironmentVariable: "PASSWORD", + Key: "slskd:web:authentication:password", + Type: typeof(string), + Default: "slskd", + Description: "the password for web UI"), + new( + ShortName: default, + LongName: "jwt-key", + EnvironmentVariable: "JWT_KEY", + Key: "slskd:web:jwt:key", + Type: typeof(string), + Default: Guid.NewGuid(), + Description: "the key with which to sign JWTs"), + new( + ShortName: default, + LongName: "jwt-ttl", + EnvironmentVariable: "JWT_TTL", + Key: "slskd:web:jwt:ttl", + Type: typeof(int), + Default: 604800000, + Description: "the TTL for JWTs"), + new( + ShortName: default, + LongName: "prometheus", + EnvironmentVariable: "PROMETHEUS", + Key: "slskd:feature:prometheus", + Type: typeof(bool), + Default: false, + Description: "enable collection and publishing of prometheus metrics"), + new( + ShortName: default, + LongName: "swagger", + EnvironmentVariable: "SWAGGER", + Key: "slskd:feature:swagger", + Type: typeof(bool), + Default: false, + Description: "enable swagger documentation and UI"), + new( + ShortName: default, + LongName: "loki", + EnvironmentVariable: "LOKI", + Key: "slskd:logger:loki", + Type: typeof(string), + Description: "optional; the url to a Grafana Loki instance to which to log"), + new( + ShortName: default, + LongName: "soulseek-username", + EnvironmentVariable: "SOULSEEK_USERNAME", + Key: "slskd:soulseek:username", + Type: typeof(string), + Description: "the username for the Soulseek network"), + new( + ShortName: default, + LongName: "soulseek-password", + EnvironmentVariable: "SOULSEEK_PASSWORD", + Key: "slskd:soulseek:password", + Type: typeof(string), + Description: "the password for the Soulseek network"), + new( + ShortName: default, + LongName: "soulseek-listen-port", + EnvironmentVariable: "SOULSEEK_LISTEN_PORT", + Key: "slskd:soulseek:listenport", + Type: typeof(int), + Default: 50000, + Description: "the port on which to listen for incoming connections"), + new( + ShortName: default, + LongName: "soulseek-no-dnet", + EnvironmentVariable: "SOULSEEK_NO_DNET", + Key: "slskd:soulseek:distributednetwork:disabled", + Type: typeof(bool), + Default: false, + Description: "disables the distributed network"), + new( + ShortName: default, + LongName: "soulseek-dnet-children", + EnvironmentVariable: "SOULSEEK_DNET_CHILDREN", + Key: "slskd:soulseek:distributednetwork:childlimit", + Type: typeof(int), + Default: 25, + Description: "sets the limit for the number of distributed children"), + new( + ShortName: default, + LongName: "soulseek-connection-timeout", + EnvironmentVariable: "SOULSEEK_CONNECTION_TIMEOUT", + Key: "slskd:soulseek:connection:timeout:connect", + Type: typeof(int), + Default: 5000, + Description: "sets the connection timeout, in miliseconds"), + new( + ShortName: default, + LongName: "soulseek-inactivity-timeout", + EnvironmentVariable: "SOULSEEK_INACTIVITY_TIMEOUT", + Key: "slskd:soulseek:connection:timeout:inactivity", + Type: typeof(int), + Default: 15000, + Description: "sets the connection inactivity timeout, in miliseconds"), + new( + ShortName: default, + LongName: "soulseek-read-buffer", + EnvironmentVariable: "SOULSEEK_READ_BUFFER", + Key: "slskd:soulseek:connection:buffer:read", + Type: typeof(int), + Default: 16384, + Description: "sets the read buffer size for connections"), + new( + ShortName: default, + LongName: "soulseek-write-buffer", + EnvironmentVariable: "SOULSEEK_WRITE_BUFFER", + Key: "slskd:soulseek:connection:buffer:write", + Type: typeof(int), + Default: 16384, + Description: "sets the write buffer size for connections"), + }; + + public bool Debug { get; private set; } = Debugger.IsAttached; + public bool NoLogo { get; private set; } = false; + public string InstanceName { get; private set; } = "default"; + public WebOptions Web { get; private set; } = new WebOptions(); + public LoggerOptions Logger { get; private set; } = new LoggerOptions(); + public FeatureOptions Feature { get; private set; } = new FeatureOptions(); + public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions(); + + public class FeatureOptions + { + public bool Prometheus { get; private set; } = false; + public bool Swagger { get; private set; } = false; + } + + public class LoggerOptions + { + public string Loki { get; private set; } = null; + } + + public class SoulseekOptions + { + public string Password { get; set; } + public string Username { get; set; } + public int? ListenPort { get; set; } = 50000; + public DistributedNetworkOptions DistributedNetwork { get; set; } = new DistributedNetworkOptions(); + public ConnectionOptions Connection { get; set; } = new ConnectionOptions(); + + public class ConnectionOptions + { + public TimeoutOptions Timeout { get; set; } = new TimeoutOptions(); + public BufferOptions Buffer { get; set; } = new BufferOptions(); + + public class BufferOptions + { + public int Read { get; set; } = 16384; + public int Write { get; set; } = 16384; + } + + public class TimeoutOptions + { + public int Connect { get; set; } = 5000; + public int Inactivity { get; set; } = 15000; + } + } + + public class DistributedNetworkOptions + { + public bool Disabled { get; set; } = false; + public int ChildLimit { get; set; } = 25; + } + } + + public class WebOptions + { + public int Port { get; private set; } = 5000; + public HttpsOptions Https { get; private set; } = new HttpsOptions(); + public string UrlBase { get; private set; } = "/"; + public string ContentPath { get; private set; } = "wwwroot"; + public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions(); + public JwtOptions Jwt { get; private set; } = new JwtOptions(); + + public class AuthenticationOptions + { + public bool Disable { get; private set; } = false; + public string Username { get; private set; } = "slskd"; + public string Password { get; private set; } = "slskd"; + } + + public class JwtOptions + { + public string Key { get; private set; } = Guid.NewGuid().ToString(); + public int Ttl { get; private set; } = 604800000; + } + + public class HttpsOptions + { + public int Port { get; private set; } = 5001; + public bool Force { get; private set; } = false; + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index dc3b7c05..6e3c0f3e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -8,80 +8,57 @@ using Serilog.Events; using Serilog.Sinks.Grafana.Loki; using System; - using System.Diagnostics; + using System.IO; using System.Linq; using System.Reflection; - using Utility.CommandLine; - using Utility.EnvironmentVariables; + using System.Text.Json; + + public static class ProgramExtensions + { + public static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile) + { + return builder + .AddDefaultValues( + map: Options.Map.Select(o => o.ToDefaultValue())) + .AddEnvironmentVariables( + prefix: environmentVariablePrefix, + map: Options.Map.Select(o => o.ToEnvironmentVariable())) + .AddYamlFile( + path: Path.Combine(Directory.GetCurrentDirectory(), configurationFile), + optional: true, + reloadOnChange: false) + .AddCommandLine( + commandLine: Environment.CommandLine, + map: Options.Map.Select(o => o.ToCommandLineArgument())); + } + } public class Program { - [Argument('h', "help", "print usage")] - public static bool ShowHelp { get; private set; } - - [Argument('v', "version", "display version information")] - public static bool ShowVersion { get; private set; } - - [Argument('d', "debug", "run in debug mode")] - [EnvironmentVariable("SLSKD_DEBUG")] - public static bool Debug { get; private set; } - - [Argument('n', "no-logo", "suppress logo on startup")] - [EnvironmentVariable("SLSKD_NO_LOGO")] - public static bool DisableLogo { get; private set; } - - [Argument('x', "no-auth", "disable authentication for web requests")] - [EnvironmentVariable("SLSKD_NO_AUTH")] - public static bool DisableAuthentication { get; private set; } - - [Argument('i', "instance-name", "optional; a unique name for this instance")] - [EnvironmentVariable("SLSKD_INSTANCE_NAME")] - public static string InstanceName { get; private set; } = "default"; - - [Argument('p', "prometheus", "enable collection and publish of prometheus metrics")] - [EnvironmentVariable("SLSKD_PROMETHEUS")] - public static bool EnablePrometheus { get; private set; } - - [Argument('s', "swagger", "enable swagger documentation")] - [EnvironmentVariable("SLSKD_SWAGGER")] - public static bool EnableSwagger { get; private set; } - - [Argument(default, "loki", "the url to a Grafana Loki instance to which to log")] - [EnvironmentVariable("SLSKD_LOKI")] - public static string LokiUrl { get; private set; } - - public static bool EnableLoki { get; private set; } - public static string Version { get; private set; } - public static Guid InvocationId { get; private set; } - public static int ProcessId { get; private set; } + private static readonly string ConfigurationFile = "slskd.yml"; + private static readonly string EnvironmentVariablePrefix = "SLSKD_"; - public static void Main(string[] args) - { - try - { - EnvironmentVariables.Populate(); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing environment variables: {ex.Message}"); - } + 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<AssemblyInformationalVersionAttribute>().InformationalVersion; + public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})"; - try - { - Arguments.Populate(clearExistingValues: false); - } - catch (Exception ex) - { - Console.WriteLine($"Error parsing input: {ex.Message}"); - } + [CommandLineArgument('n', "no-logo", "suppress logo on startup")] + private static bool NoLogo { get; set; } + + [CommandLineArgument('e', "envars", "display environment variables")] + private static bool ShowEnvironmentVariables { get; set; } + + [CommandLineArgument('h', "help", "display command line usage")] + private static bool ShowHelp { get; set; } - InvocationId = Guid.NewGuid(); - ProcessId = Environment.ProcessId; + [CommandLineArgument('v', "version", "display version information")] + private static bool ShowVersion { get; set; } - var assembly = Assembly.GetExecutingAssembly(); - var assemblyVersion = assembly.GetName().Version; - var informationVersion = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; - Version = $"{assemblyVersion} ({informationVersion})"; + public static void Main(string[] args) + { + CommandLineArguments.Populate(); if (ShowVersion) { @@ -89,41 +66,51 @@ return; } - if (ShowHelp) + if (ShowHelp || ShowEnvironmentVariables) { - if (!DisableLogo) - { - PrintBanner(Version); - } - - PrintHelp(); + if (!NoLogo) PrintLogo(Version); + if (ShowHelp) PrintCommandLineArguments(); + if (ShowEnvironmentVariables) PrintEnvironmentVariables(EnvironmentVariablePrefix); return; } - Debug = Debugger.IsAttached || Debug; - EnableLoki = !string.IsNullOrEmpty(LokiUrl); - - if (Debug) + var configuration = new ConfigurationBuilder() + .AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile) + .Build(); + + var options = new Options(); + + configuration.GetSection("slskd").Bind(options, (o) => { o.BindNonPublicProperties = true; }); + + if (!options.NoLogo) + { + PrintLogo(Version); + } + + if (options.Debug) { + Console.WriteLine(configuration.GetDebugView()); + Console.WriteLine(JsonSerializer.Serialize(options, new JsonSerializerOptions() { WriteIndented = true })); + Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) + .Enrich.WithProperty("InstanceName", options.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => + .WriteTo.Async(config => config.File( - "logs/slskd-.log", + "logs/slskd-.log", outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => EnableLoki, + e => !string.IsNullOrEmpty(options.Logger.Loki), config => config.GrafanaLoki( - LokiUrl ?? string.Empty, + options.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); } @@ -134,65 +121,57 @@ .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Security.PassthroughAuthenticationHandler", LogEventLevel.Information) .Enrich.WithProperty("Version", Version) - .Enrich.WithProperty("InstanceName", InstanceName) + .Enrich.WithProperty("InstanceName", options.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) .Enrich.FromLogContext() .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(config => + .WriteTo.Async(config => config.File( - "logs/slskd-.log", + "logs/slskd-.log", outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day)) .WriteTo.Conditional( - e => EnableLoki, + e => !string.IsNullOrEmpty(options.Logger.Loki), config => config.GrafanaLoki( - LokiUrl ?? string.Empty, + options.Logger.Loki ?? string.Empty, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) .CreateLogger(); } - if (!DisableLogo) - { - PrintBanner(Version); - } - var logger = Log.ForContext<Program>(); logger.Information("Version: {Version}", Version); - logger.Information("Instance Name: {InstanceName}", InstanceName); + logger.Information("Instance Name: {InstanceName}", options.InstanceName); logger.Information("Invocation ID: {InvocationId}", InvocationId); logger.Information("Process ID: {ProcessId}", ProcessId); - if (DisableAuthentication) + if (!string.IsNullOrEmpty(options.Logger.Loki)) { - logger.Warning("Authentication of web requests is DISABLED"); - } - - if (EnablePrometheus) - { - logger.Information("Publishing Prometheus metrics to /metrics"); - } - - if (EnableSwagger) - { - logger.Information("Publishing Swagger documentation to /swagger"); - } - - if (EnableLoki) - { - logger.Information("Logging to Loki instance at {LoggerLokiUrl}", LokiUrl); + logger.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", options.Logger.Loki); } try { - if (EnablePrometheus) + if (options.Feature.Prometheus) { using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); } - CreateWebHostBuilder(args).Build().Run(); + WebHost.CreateDefaultBuilder(args) + .ConfigureAppConfiguration((hostingContext, builder) => + { + builder.Sources.Clear(); + builder.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); + }) + .UseSerilog() + .UseStartup<Startup>() + .UseUrls( + $"http://0.0.0.0:{options.Web.Port}", + $"https://0.0.0.0:{options.Web.Https.Port}") + .Build() + .Run(); } catch (Exception ex) { @@ -204,17 +183,55 @@ } } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => + public static void PrintCommandLineArguments() + { + static string GetLongName(string longName, Type type) + => type == typeof(bool) ? longName : $"{longName} <{type.Name.ToLowerInvariant()}>"; + + var longestName = Options.Map.Where(a => !string.IsNullOrEmpty(a.LongName)).Select(a => GetLongName(a.LongName, a.Type)).Max(n => n.Length); + + Console.WriteLine("\nusage: slskd [arguments]\n"); + Console.WriteLine("arguments:\n"); + + foreach (Option item in Options.Map) + { + var (shortName, longName, _, key, type, defaultValue, description) = item; + + if (shortName == default && string.IsNullOrEmpty(longName)) + { + continue; + } + + var suffix = type == typeof(bool) ? string.Empty : $" (default: {defaultValue ?? "<null>"})"; + var result = $" {shortName}{(shortName == default ? " " : "|")}--{GetLongName(longName, type).PadRight(longestName + 3)}{description}{suffix}"; + Console.WriteLine(result); + } + } + + public static void PrintEnvironmentVariables(string prefix) + { + static string GetName(string name, Type type) => $"{name} <{type.Name.ToLowerInvariant()}>"; + + var longestName = Options.Map.Select(a => GetName(a.EnvironmentVariable, a.Type)).Max(n => n.Length); + + Console.WriteLine("\nenvironment variables (arguments and config.yml have precedence):\n"); + + foreach (Option item in Options.Map) + { + var (_, _, environmentVariable, key, type, defaultValue, description) = item; + + if (string.IsNullOrEmpty(environmentVariable) || string.IsNullOrEmpty(key)) { - config.AddEnvironmentVariables(prefix: "SLSK_"); - config.AddJsonFile("config.json", optional: true, reloadOnChange: false); - }) - .UseSerilog() - .UseStartup<Startup>(); + continue; + } + + var suffix = type == typeof(bool) ? string.Empty : $" (default: {defaultValue ?? "<null>"})"; + var result = $" {prefix}{GetName(environmentVariable, type).PadRight(longestName + 3)}{description}{suffix}"; + Console.WriteLine(result); + } + } - public static void PrintBanner(string version) + private static void PrintLogo(string version) { var padding = 56 - version.Length; var paddingLeft = padding / 2; @@ -236,57 +253,5 @@ Console.WriteLine(banner); } - - public static void PrintHelp() - { - PrintArguments(); - PrintEnvironmentVariables(); - } - - public static void PrintArguments() - { - static string GetLongName(ArgumentInfo info) - => info.Property.PropertyType == typeof(bool) ? info.LongName : $"{info.LongName} <{info.Property.PropertyType.Name.ToLowerInvariant()}>"; - - static string GetShortName(ArgumentInfo info) - => info.ShortName > 0 ? $"-{info.ShortName}|" : " "; - - var arguments = Arguments.GetArgumentInfo(typeof(Program)); - var longestName = arguments.Select(a => GetLongName(a)).Max(n => n.Length); - - Console.WriteLine("\nusage: slskd [arguments]\n"); - Console.WriteLine("arguments:\n"); - foreach (var info in arguments) - { - var envar = info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value; - - var result = $" {GetShortName(info)}--{GetLongName(info).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } - - public static void PrintEnvironmentVariables() - { - static string GetEnvironmentVariableName(ArgumentInfo info, bool includeType = false) - => info.Property.CustomAttributes - ?.Where(a => a.AttributeType == typeof(EnvironmentVariableAttribute)).FirstOrDefault() - ?.ConstructorArguments.FirstOrDefault().Value?.ToString() + (includeType ? $" <{info.Property.PropertyType.Name.ToLowerInvariant()}>" : ""); - - var arguments = Arguments.GetArgumentInfo(typeof(Program)); - var longestName = arguments.Select(a => GetEnvironmentVariableName(a, includeType: true)).Where(a => a !=null).Max(n => n.Length); - - Console.WriteLine("\nenvironment variables (arguments have precedence):\n"); - foreach (var info in arguments) - { - var envar = GetEnvironmentVariableName(info, includeType: false); - - if (string.IsNullOrEmpty(envar)) continue; - - var result = $" {GetEnvironmentVariableName(info, includeType: true).PadRight(longestName + 3)}{info.HelpText}"; - Console.WriteLine(result); - } - } } -} +}
\ No newline at end of file diff --git a/src/slskd/Security/Role.cs b/src/slskd/Security/Role.cs new file mode 100644 index 00000000..91c9e83c --- /dev/null +++ b/src/slskd/Security/Role.cs @@ -0,0 +1,9 @@ +namespace slskd +{ + public enum Role + { + ReadOnly = 0, + User = 1, + Administrator = 2 + } +} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 37a3c7cd..3479926b 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -10,100 +10,89 @@ using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.FileProviders; - using Microsoft.Extensions.Hosting; - using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Soulseek; using Soulseek.Diagnostics; - using slskd.Entities; - using slskd.Security; using slskd.Trackers; using System.Collections.Concurrent; + using Microsoft.IdentityModel.Tokens; + using slskd.Security; + using Microsoft.AspNetCore.Authentication.JwtBearer; + using Prometheus.SystemMetrics; using Serilog; - using Serilog.Events; - using Microsoft.Extensions.Logging; using Prometheus; - using Prometheus.SystemMetrics; + using Microsoft.Extensions.FileProviders; + using Serilog.Events; + using slskd.Entities; + using Microsoft.Extensions.Options; public class Startup { - internal static string Username { get; set; } - internal static string Password { get; set; } - internal static string BasePath { get; set; } - internal static string WebRoot { get; set; } - internal static int ListenPort { get; set; } + private readonly int MaxReconnectAttempts = 3; + private int CurrentReconnectAttempts = 0; + internal static string OutputDirectory { get; set; } internal static string SharedDirectory { get; set; } internal static long SharedCacheTTL { get; set; } - internal static bool EnableDistributedNetwork { get; set; } - internal static int DistributedChildLimit { get; set; } internal static DiagnosticLevel DiagnosticLevel { get; set; } - internal static int ConnectTimeout { get; set; } - internal static int InactivityTimeout { get; set; } - internal static int SecurityTokenTTL { get; set; } internal static int RoomMessageLimit { get; set; } - internal static int ReadBufferSize { get; set; } - internal static int WriteBufferSize { get; set; } internal static string XmlDocFile { get; set; } - internal static SymmetricSecurityKey JwtSigningKey { get; set; } - private SoulseekClient Client { get; set; } - private object ConsoleSyncRoot { get; } = new object(); private ISharedFileCache SharedFileCache { get; set; } + private string UrlBase { get; set; } + private string ContentPath { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; - Username = Configuration.GetValue<string>("USERNAME"); - Password = Configuration.GetValue<string>("PASSWORD"); - BasePath = Configuration.GetValue<string>("BASE_PATH"); - WebRoot = Configuration.GetValue<string>("WEB_ROOT", Path.Combine(Path.GetDirectoryName(new Uri(AppContext.BaseDirectory).AbsolutePath), "wwwroot")); - ListenPort = Configuration.GetValue<int>("LISTEN_PORT", 50000); + Options = new Options(); + Configuration.GetSection("slskd").Bind(Options, (o) => + { + o.BindNonPublicProperties = true; + }); + OutputDirectory = Configuration.GetValue<string>("OUTPUT_DIR"); SharedDirectory = Configuration.GetValue<string>("SHARED_DIR"); SharedCacheTTL = Configuration.GetValue<long>("SHARED_CACHE_TTL", 3600000); // 1 hour - EnableDistributedNetwork = Configuration.GetValue<bool>("ENABLE_DNET", true); - DistributedChildLimit = Configuration.GetValue<int>("DNET_CHILD_LIMIT", 10); DiagnosticLevel = Configuration.GetValue<DiagnosticLevel>("DIAGNOSTIC", DiagnosticLevel.Info); - ConnectTimeout = Configuration.GetValue<int>("CONNECT_TIMEOUT", 5000); - InactivityTimeout = Configuration.GetValue<int>("INACTIVITY_TIMEOUT", 15000); - SecurityTokenTTL = Configuration.GetValue<int>("SECURITY_TOKEN_TTL", 604800000); // 7 days RoomMessageLimit = Configuration.GetValue<int>("ROOM_MESSAGE_LIMIT", 250); - ReadBufferSize = Configuration.GetValue<int>("READ_BUFFER_SIZE", 16384); - WriteBufferSize = Configuration.GetValue<int>("WRITE_BUFFER_SIZE", 16384); XmlDocFile = Configuration.GetValue<string>("XML_DOC_FILE", Path.Combine(AppContext.BaseDirectory, typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".xml")); - - JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Password)); - + SharedFileCache = new SharedFileCache(SharedDirectory, SharedCacheTTL); + } - BasePath ??= "/"; - BasePath = BasePath.StartsWith("/") ? BasePath : $"/{BasePath}"; + private IConfiguration Configuration { get; } + private Options Options { get; } + private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); + public void ConfigureServices(IServiceCollection services) + { var logger = Log.ForContext<Startup>(); - logger.Information("Serving static content from {WebRoot}", WebRoot); - logger.Information("Using base request path {BasePath}", BasePath); - } + services.AddOptions<Options>() + .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; }); - public IConfiguration Configuration { get; } - public ConcurrentDictionary<string, Serilog.ILogger> Loggers { get; } = new ConcurrentDictionary<string, Serilog.ILogger>(); + UrlBase = Options.Web.UrlBase; + UrlBase = UrlBase.StartsWith("/") ? UrlBase : "/" + UrlBase; + + ContentPath = Path.GetFullPath(Options.Web.ContentPath); + + JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Jwt.Key)); - public void ConfigureServices(IServiceCollection services) - { services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); - if (!Program.DisableAuthentication) + services.AddSingleton(JwtSigningKey); + + if (!Options.Web.Authentication.Disable) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => @@ -124,10 +113,12 @@ } else { + logger.Warning("Authentication of web requests is DISABLED"); + services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) .AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options => { - options.Username = Username; + options.Username = "n/a"; }); } @@ -163,7 +154,7 @@ } }); - if (Program.EnablePrometheus) + if (Options.Feature.Prometheus) { services.AddSystemMetrics(); } @@ -179,20 +170,27 @@ public void Configure( IApplicationBuilder app, IWebHostEnvironment env, - ILoggerFactory loggerFactory, IApiVersionDescriptionProvider provider, ITransferTracker tracker, IBrowseTracker browseTracker, IConversationTracker conversationTracker, + IOptionsMonitor<Options> optionsMonitor, IRoomTracker roomTracker) { - if (!env.IsDevelopment()) + var logger = Log.ForContext<Startup>(); + + app.UseCors("AllowAll"); + + if (Options.Web.Https.Force) { + app.UseHttpsRedirection(); app.UseHsts(); + + logger.Information($"Forcing HTTP requests to HTTPS"); } - app.UseCors("AllowAll"); - app.UsePathBase(BasePath); + 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 @@ -208,23 +206,34 @@ await next(); }); - var fileServerOptions = new FileServerOptions + FileServerOptions fileServerOptions = default; + + if (!System.IO.Directory.Exists(ContentPath)) { - FileProvider = new PhysicalFileProvider(WebRoot), - RequestPath = "", - EnableDirectoryBrowsing = false, - EnableDefaultFiles = true - }; + logger.Warning($"Static content disabled; cannot find content path '{ContentPath}'"); + } + else + { + fileServerOptions = new FileServerOptions + { + FileProvider = new PhysicalFileProvider(ContentPath), + RequestPath = "", + EnableDirectoryBrowsing = false, + EnableDefaultFiles = true + }; - app.UseFileServer(fileServerOptions); + app.UseFileServer(fileServerOptions); + logger.Information("Serving static content from {ContentPath}", ContentPath); + } app.UseSerilogRequestLogging(); - if (Program.EnablePrometheus) + if (Options.Feature.Prometheus) { app.UseHttpMetrics(); + logger.Information("Publishing Prometheus metrics to /metrics"); } - + app.UseAuthentication(); app.UseRouting(); @@ -233,17 +242,19 @@ { endpoints.MapControllers(); - if (Program.EnablePrometheus) + if (Options.Feature.Prometheus) { endpoints.MapMetrics(); } }); - if (Program.EnableSwagger) + if (Options.Feature.Swagger) { app.UseSwagger(); app.UseSwaggerUI(options => provider.ApiVersionDescriptions.ToList() .ForEach(description => options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName))); + + 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 @@ -261,27 +272,30 @@ // 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. - app.UseFileServer(fileServerOptions); + if (System.IO.Directory.Exists(ContentPath)) + { + app.UseFileServer(fileServerOptions); + } // --------------------------------------------------------------------------------------------------------------------------------------------- // begin SoulseekClient implementation // --------------------------------------------------------------------------------------------------------------------------------------------- - - var logger = loggerFactory.CreateLogger<Startup>(); - var connectionOptions = new ConnectionOptions( - readBufferSize: ReadBufferSize, - writeBufferSize: WriteBufferSize, - connectTimeout: ConnectTimeout, - inactivityTimeout: InactivityTimeout); + readBufferSize: Options.Soulseek.Connection.Buffer.Read, + writeBufferSize: Options.Soulseek.Connection.Buffer.Write, + connectTimeout: Options.Soulseek.Connection.Timeout.Connect, + inactivityTimeout: Options.Soulseek.Connection.Timeout.Inactivity); + + var defaults = new SoulseekClientOptions(); // create options for the client. // see the implementation of Func<> and Action<> options for detailed info. var clientOptions = new SoulseekClientOptions( - listenPort: ListenPort, + listenPort: Options.Soulseek.ListenPort ?? defaults.ListenPort, + enableListener: Options.Soulseek.ListenPort.HasValue, userEndPointCache: new UserEndPointCache(), - distributedChildLimit: DistributedChildLimit, - enableDistributedNetwork: EnableDistributedNetwork, + distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit, + enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled, minimumDiagnosticLevel: DiagnosticLevel, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, @@ -294,6 +308,14 @@ enqueueDownloadAction: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, tracker), searchResponseResolver: SearchResponseResolver); + var username = Options.Soulseek.Username; + var password = Options.Soulseek.Password; + + if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) + { + throw new ArgumentException("Soulseek credentials are not configured"); + } + Client = new SoulseekClient(options: clientOptions); // bind the DiagnosticGenerated event so we can trap and display diagnostic messages. this is optional, and if the event @@ -310,7 +332,7 @@ }; var logger = Loggers.GetOrAdd(e.GetType().FullName, Log.ForContext("SourceContext", "Soulseek").ForContext("SoulseekContext", e.GetType().FullName)); - + logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); }; @@ -370,7 +392,7 @@ Client.RoomJoined += (e, args) => { - if (args.Username != Username) // this will fire when we join a room; track that through the join operation. + if (args.Username != username) // this will fire when we join a room; track that through the join operation. { roomTracker.TryAddUser(args.RoomName, args.UserData); } @@ -383,24 +405,37 @@ Client.Disconnected += async (e, args) => { - logger.LogWarning("Disconnected from Soulseek server: {Message}", args.Message, args.Exception); + 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. if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) { - logger.LogWarning("Attepting to reconnect..."); - await Client.ConnectAsync(Username, Password); + Interlocked.Increment(ref CurrentReconnectAttempts); + + if (CurrentReconnectAttempts <= MaxReconnectAttempts) + { + var wait = CurrentReconnectAttempts ^ 3; + Console.WriteLine($"Waiting {wait} second(s) before reconnect..."); + await Task.Delay(wait); + + Console.WriteLine($"Attepting to reconnect..."); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + } + else + { + Console.WriteLine($"Unable to reconnect after {CurrentReconnectAttempts} tries."); + } } }; Task.Run(async () => { - await Client.ConnectAsync(Username, Password); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); }).GetAwaiter().GetResult(); - logger.LogInformation("Connected and logged in as {Username}", Username); + logger.Information("Connected and logged in as {Username}", username); } /// <summary> @@ -533,7 +568,7 @@ Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}"); return Task.FromResult(new SearchResponse( - Username, + username, token, freeUploadSlots: 1, uploadSpeed: 0, diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 7377ea60..c177f6f7 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -23,6 +23,12 @@ </PropertyGroup> <ItemGroup> + <Content Include="slskd.yml"> + <CopyToOutputDirectory>Always</CopyToOutputDirectory> + </Content> + </ItemGroup> + + <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="4.2.0" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="5.0.2" /> @@ -38,11 +44,10 @@ <PackageReference Include="Serilog.Sinks.File" Version="4.1.0" /> <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.Http" Version="7.2.0" /> - <PackageReference Include="Soulseek" Version="1.0.1" /> + <PackageReference Include="Soulseek" Version="2.0.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" /> - <PackageReference Include="Utility.CommandLine.Arguments" Version="5.0.0" /> - <PackageReference Include="Utility.EnvironmentVariables" Version="1.0.3" /> + <PackageReference Include="YamlDotNet" Version="9.1.4" /> </ItemGroup> <ItemGroup> diff --git a/src/slskd/slskd.yml b/src/slskd/slskd.yml new file mode 100644 index 00000000..d698f8fb --- /dev/null +++ b/src/slskd/slskd.yml @@ -0,0 +1,37 @@ +slskd: + debug: false + no_logo: false + instance_name: default + web: + port: 5000 + https: + port: 5001 + force: false + url_base: / + content_path: wwwroot + authentication: + disable: false + username: slskd + password: slskd + jwt: + key: ~ + ttl: 604800000 + logger: + loki: ~ + feature: + prometheus: false + swagger: false + soulseek: + username: ~ + password: ~ + listen_port: 50000 + distributed_network: + disabled: false + child_limit: 25 + connection: + timeout: + connect: 5000 + inactivity: 15000 + buffer: + read: 16384 + write: 16384
\ No newline at end of file |
