aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore6
-rw-r--r--src/slskd/.gitignore352
-rw-r--r--src/slskd/API/Authentication/PassthroughAuthentication.cs91
-rw-r--r--src/slskd/API/Controllers/ApplicationController.cs (renamed from src/slskd/Controllers/ApplicationController.cs)2
-rw-r--r--src/slskd/API/Controllers/ConversationsController.cs (renamed from src/slskd/Controllers/ConversationsController.cs)4
-rw-r--r--src/slskd/API/Controllers/PublicChatController.cs (renamed from src/slskd/Controllers/PublicChatController.cs)2
-rw-r--r--src/slskd/API/Controllers/RoomsController.cs (renamed from src/slskd/Controllers/RoomsController.cs)4
-rw-r--r--src/slskd/API/Controllers/SearchesController.cs (renamed from src/slskd/Controllers/SearchesController.cs)4
-rw-r--r--src/slskd/API/Controllers/ServerController.cs (renamed from src/slskd/Controllers/ServerController.cs)4
-rw-r--r--src/slskd/API/Controllers/SessionController.cs (renamed from src/slskd/Controllers/SessionController.cs)6
-rw-r--r--src/slskd/API/Controllers/TransfersController.cs (renamed from src/slskd/Controllers/TransfersController.cs)4
-rw-r--r--src/slskd/API/Controllers/UserController.cs (renamed from src/slskd/Controllers/UserController.cs)4
-rw-r--r--src/slskd/API/DTO/ConnectRequest.cs (renamed from src/slskd/DTO/ConnectRequest.cs)2
-rw-r--r--src/slskd/API/DTO/LoginRequest.cs (renamed from src/slskd/DTO/LoginRequest.cs)2
-rw-r--r--src/slskd/API/DTO/PrivateMessageResponse.cs (renamed from src/slskd/DTO/PrivateMessageResponse.cs)2
-rw-r--r--src/slskd/API/DTO/QueueDownloadRequest.cs (renamed from src/slskd/DTO/QueueDownloadRequest.cs)2
-rw-r--r--src/slskd/API/DTO/RoomInfoResponse.cs (renamed from src/slskd/DTO/RoomInfoResponse.cs)2
-rw-r--r--src/slskd/API/DTO/RoomMessageResponse.cs (renamed from src/slskd/DTO/RoomMessageResponse.cs)2
-rw-r--r--src/slskd/API/DTO/RoomResponse.cs (renamed from src/slskd/DTO/RoomResponse.cs)2
-rw-r--r--src/slskd/API/DTO/SearchRequest.cs (renamed from src/slskd/DTO/SearchRequest.cs)2
-rw-r--r--src/slskd/API/DTO/TokenResponse.cs (renamed from src/slskd/DTO/TokenResponse.cs)2
-rw-r--r--src/slskd/API/DTO/Transfer.cs (renamed from src/slskd/DTO/Transfer.cs)2
-rw-r--r--src/slskd/API/DTO/UserAddress.cs (renamed from src/slskd/DTO/UserAddress.cs)2
-rw-r--r--src/slskd/API/DTO/UserDataResponse.cs (renamed from src/slskd/DTO/UserDataResponse.cs)2
-rw-r--r--src/slskd/Common/Configuration/CommandLineArguments.cs666
-rw-r--r--src/slskd/Common/Configuration/CommandLineConfigurationSource.cs172
-rw-r--r--src/slskd/Common/Configuration/ConfigurationExtensions.cs14
-rw-r--r--src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs145
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs166
-rw-r--r--src/slskd/Common/Configuration/EnvironmentVariables.cs185
-rw-r--r--src/slskd/Common/Configuration/YamlConfigurationSource.cs94
-rw-r--r--src/slskd/Common/Cryptography/PBKDF2.cs26
-rw-r--r--src/slskd/Common/Cryptography/Pbkdf2.cs43
-rw-r--r--src/slskd/Common/Cryptography/X509.cs40
-rw-r--r--src/slskd/Common/Extensions.cs119
-rw-r--r--src/slskd/Common/ISharedFileCache.cs34
-rw-r--r--src/slskd/Common/SharedFileCache.cs (renamed from src/slskd/SharedFileCache.cs)23
-rw-r--r--src/slskd/Extensions.cs80
-rw-r--r--src/slskd/ISharedFileCache.cs17
-rw-r--r--src/slskd/Options.cs675
-rw-r--r--src/slskd/Program.cs285
-rw-r--r--src/slskd/Properties/analysis.ruleset48
-rw-r--r--src/slskd/Properties/launchSettings.json8
-rw-r--r--src/slskd/Properties/slskd.yml (renamed from src/slskd/slskd.yml)0
-rw-r--r--src/slskd/Properties/stylecop.json27
-rw-r--r--src/slskd/Security/PassthroughAuthentication.cs40
-rw-r--r--src/slskd/Startup.cs253
-rw-r--r--src/slskd/Trackers/ITransferTracker.cs25
-rw-r--r--src/slskd/Trackers/TransferTracker.cs59
-rw-r--r--src/slskd/slskd.csproj66
50 files changed, 1584 insertions, 2233 deletions
diff --git a/.gitignore b/.gitignore
index e3e14587..c460b420 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
.vs
dist/
-logs/ \ No newline at end of file
+logs/
+src/slskd/bin/
+src/slskd/obj/
+src/slskd/wwwroot/
+src/slskd/slskd.csproj.user \ No newline at end of file
diff --git a/src/slskd/.gitignore b/src/slskd/.gitignore
deleted file mode 100644
index 3eabeee4..00000000
--- a/src/slskd/.gitignore
+++ /dev/null
@@ -1,352 +0,0 @@
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-##
-## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
-
-# User-specific files
-*.rsuser
-*.suo
-*.user
-*.userosscache
-*.sln.docstates
-
-# User-specific files (MonoDevelop/Xamarin Studio)
-*.userprefs
-
-# Mono auto generated files
-mono_crash.*
-
-# Build results
-[Dd]ebug/
-[Dd]ebugPublic/
-[Rr]elease/
-[Rr]eleases/
-x64/
-x86/
-[Aa][Rr][Mm]/
-[Aa][Rr][Mm]64/
-bld/
-[Bb]in/
-[Oo]bj/
-[Ll]og/
-[Ll]ogs/
-
-# Visual Studio 2015/2017 cache/options directory
-.vs/
-# Uncomment if you have tasks that create the project's static files in wwwroot
-#wwwroot/
-
-# Visual Studio 2017 auto generated files
-Generated\ Files/
-
-# MSTest test Results
-[Tt]est[Rr]esult*/
-[Bb]uild[Ll]og.*
-
-# NUnit
-*.VisualState.xml
-TestResult.xml
-nunit-*.xml
-
-# Build Results of an ATL Project
-[Dd]ebugPS/
-[Rr]eleasePS/
-dlldata.c
-
-# Benchmark Results
-BenchmarkDotNet.Artifacts/
-
-# .NET Core
-project.lock.json
-project.fragment.lock.json
-artifacts/
-
-# StyleCop
-StyleCopReport.xml
-
-# Files built by Visual Studio
-*_i.c
-*_p.c
-*_h.h
-*.ilk
-*.meta
-*.obj
-*.iobj
-*.pch
-*.pdb
-*.ipdb
-*.pgc
-*.pgd
-*.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
-*.tmp
-*.tmp_proj
-*_wpftmp.csproj
-*.log
-*.vspscc
-*.vssscc
-.builds
-*.pidb
-*.svclog
-*.scc
-
-# Chutzpah Test files
-_Chutzpah*
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opendb
-*.opensdf
-*.sdf
-*.cachefile
-*.VC.db
-*.VC.VC.opendb
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-*.sap
-
-# Visual Studio Trace Files
-*.e2e
-
-# TFS 2012 Local Workspace
-$tf/
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*/
-*.[Rr]e[Ss]harper
-*.DotSettings.user
-
-# TeamCity is a build add-in
-_TeamCity*
-
-# DotCover is a Code Coverage Tool
-*.dotCover
-
-# AxoCover is a Code Coverage Tool
-.axoCover/*
-!.axoCover/settings.json
-
-# Visual Studio code coverage results
-*.coverage
-*.coveragexml
-
-# NCrunch
-_NCrunch_*
-.*crunch*.local.xml
-nCrunchTemp_*
-
-# MightyMoose
-*.mm.*
-AutoTest.Net/
-
-# Web workbench (sass)
-.sass-cache/
-
-# Installshield output folder
-[Ee]xpress/
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish/
-
-# Publish Web Output
-*.[Pp]ublish.xml
-*.azurePubxml
-# Note: Comment the next line if you want to checkin your web deploy settings,
-# but database connection strings (with potential passwords) will be unencrypted
-*.pubxml
-*.publishproj
-
-# Microsoft Azure Web App publish settings. Comment the next line if you want to
-# checkin your Azure Web App publish settings, but sensitive information contained
-# in these scripts will be unencrypted
-PublishScripts/
-
-# NuGet Packages
-*.nupkg
-# NuGet Symbol Packages
-*.snupkg
-# The packages folder can be ignored because of Package Restore
-**/[Pp]ackages/*
-# except build/, which is used as an MSBuild target.
-!**/[Pp]ackages/build/
-# Uncomment if necessary however generally it will be regenerated when needed
-#!**/[Pp]ackages/repositories.config
-# NuGet v3's project.json files produces more ignorable files
-*.nuget.props
-*.nuget.targets
-
-# Microsoft Azure Build Output
-csx/
-*.build.csdef
-
-# Microsoft Azure Emulator
-ecf/
-rcf/
-
-# Windows Store app package directories and files
-AppPackages/
-BundleArtifacts/
-Package.StoreAssociation.xml
-_pkginfo.txt
-*.appx
-*.appxbundle
-*.appxupload
-
-# Visual Studio cache files
-# files ending in .cache can be ignored
-*.[Cc]ache
-# but keep track of directories ending in .cache
-!?*.[Cc]ache/
-
-# Others
-ClientBin/
-~$*
-*~
-*.dbmdl
-*.dbproj.schemaview
-*.jfm
-*.pfx
-*.publishsettings
-orleans.codegen.cs
-
-# Including strong name files can present a security risk
-# (https://github.com/github/gitignore/pull/2483#issue-259490424)
-#*.snk
-
-# Since there are multiple workflows, uncomment next line to ignore bower_components
-# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
-#bower_components/
-
-# RIA/Silverlight projects
-Generated_Code/
-
-# Backup & report files from converting an old project file
-# to a newer Visual Studio version. Backup files are not needed,
-# because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-UpgradeLog*.htm
-ServiceFabricBackup/
-*.rptproj.bak
-
-# SQL Server files
-*.mdf
-*.ldf
-*.ndf
-
-# Business Intelligence projects
-*.rdl.data
-*.bim.layout
-*.bim_*.settings
-*.rptproj.rsuser
-*- [Bb]ackup.rdl
-*- [Bb]ackup ([0-9]).rdl
-*- [Bb]ackup ([0-9][0-9]).rdl
-
-# Microsoft Fakes
-FakesAssemblies/
-
-# GhostDoc plugin setting file
-*.GhostDoc.xml
-
-# Node.js Tools for Visual Studio
-.ntvs_analysis.dat
-node_modules/
-
-# Visual Studio 6 build log
-*.plg
-
-# Visual Studio 6 workspace options file
-*.opt
-
-# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
-*.vbw
-
-# Visual Studio LightSwitch build output
-**/*.HTMLClient/GeneratedArtifacts
-**/*.DesktopClient/GeneratedArtifacts
-**/*.DesktopClient/ModelManifest.xml
-**/*.Server/GeneratedArtifacts
-**/*.Server/ModelManifest.xml
-_Pvt_Extensions
-
-# Paket dependency manager
-.paket/paket.exe
-paket-files/
-
-# FAKE - F# Make
-.fake/
-
-# CodeRush personal settings
-.cr/personal
-
-# Python Tools for Visual Studio (PTVS)
-__pycache__/
-*.pyc
-
-# Cake - Uncomment if you are using it
-# tools/**
-# !tools/packages.config
-
-# Tabs Studio
-*.tss
-
-# Telerik's JustMock configuration file
-*.jmconfig
-
-# BizTalk build output
-*.btp.cs
-*.btm.cs
-*.odx.cs
-*.xsd.cs
-
-# OpenCover UI analysis results
-OpenCover/
-
-# Azure Stream Analytics local run output
-ASALocalRun/
-
-# MSBuild Binary and Structured Log
-*.binlog
-
-# NVidia Nsight GPU debugger configuration file
-*.nvuser
-
-# MFractors (Xamarin productivity tool) working folder
-.mfractor/
-
-# Local History for Visual Studio
-.localhistory/
-
-# BeatPulse healthcheck temp database
-healthchecksdb
-
-# Backup folder for Package Reference Convert tool in Visual Studio 2017
-MigrationBackup/
-
-# Ionide (cross platform F# VS Code tools) working folder
-.ionide/
-
-wwwroot \ No newline at end of file
diff --git a/src/slskd/API/Authentication/PassthroughAuthentication.cs b/src/slskd/API/Authentication/PassthroughAuthentication.cs
new file mode 100644
index 00000000..65bbb7db
--- /dev/null
+++ b/src/slskd/API/Authentication/PassthroughAuthentication.cs
@@ -0,0 +1,91 @@
+// <copyright file="PassthroughAuthentication.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.API.Authentication
+{
+ using System.Security.Principal;
+ using System.Text.Encodings.Web;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authentication;
+ using Microsoft.Extensions.Logging;
+ using Microsoft.Extensions.Options;
+
+ /// <summary>
+ /// Passthrough authentication.
+ /// </summary>
+ public static class PassthroughAuthentication
+ {
+ /// <summary>
+ /// Gets the Passthrough authentication scheme name.
+ /// </summary>
+ public static string AuthenticationScheme { get; } = "Passthrough";
+ }
+
+ /// <summary>
+ /// Handles passthrough authentication.
+ /// </summary>
+ public class PassthroughAuthenticationHandler : AuthenticationHandler<PassthroughAuthenticationOptions>
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PassthroughAuthenticationHandler"/> class.
+ /// </summary>
+ /// <param name="optionsMonitor">An options monitor.</param>
+ /// <param name="logger">A logger factory.</param>
+ /// <param name="urlEncoder">A url encoder.</param>
+ /// <param name="systemClock">A system clock interface.</param>
+ public PassthroughAuthenticationHandler(IOptionsMonitor<PassthroughAuthenticationOptions> optionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock)
+ : base(optionsMonitor, logger, urlEncoder, systemClock)
+ {
+ }
+
+ /// <summary>
+ /// Authenticates using the configured <see cref="PassthroughAuthenticationOptions.Username"/> and <see cref="PassthroughAuthenticationOptions.Role"/>.
+ /// </summary>
+ /// <returns>A successful authentication result containing a default ticket.</returns>
+ protected override Task<AuthenticateResult> HandleAuthenticateAsync()
+ {
+ var identity = new GenericIdentity(Options.Username);
+ var principal = new GenericPrincipal(identity, new[] { Options.Role.ToString() });
+ var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), PassthroughAuthentication.AuthenticationScheme);
+
+ return Task.FromResult(AuthenticateResult.Success(ticket));
+ }
+ }
+
+ /// <summary>
+ /// Passthrough authentication options.
+ /// </summary>
+ public class PassthroughAuthenticationOptions : AuthenticationSchemeOptions
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PassthroughAuthenticationOptions"/> class.
+ /// </summary>
+ public PassthroughAuthenticationOptions()
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the username for the passed-through authentication ticket.
+ /// </summary>
+ public string Username { get; set; } = "Anonymous";
+
+ /// <summary>
+ /// Gets or sets the role for the passed-through authentication ticket.
+ /// </summary>
+ public Role Role { get; set; } = Role.Administrator;
+ }
+}
diff --git a/src/slskd/Controllers/ApplicationController.cs b/src/slskd/API/Controllers/ApplicationController.cs
index cc9d56a1..40353afa 100644
--- a/src/slskd/Controllers/ApplicationController.cs
+++ b/src/slskd/API/Controllers/ApplicationController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
diff --git a/src/slskd/Controllers/ConversationsController.cs b/src/slskd/API/Controllers/ConversationsController.cs
index ccebf7c5..10819b86 100644
--- a/src/slskd/Controllers/ConversationsController.cs
+++ b/src/slskd/API/Controllers/ConversationsController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using System;
using System.Collections.Generic;
@@ -7,7 +7,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Soulseek;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd.Entities;
using slskd.Trackers;
diff --git a/src/slskd/Controllers/PublicChatController.cs b/src/slskd/API/Controllers/PublicChatController.cs
index 10ad9234..63a91ff4 100644
--- a/src/slskd/Controllers/PublicChatController.cs
+++ b/src/slskd/API/Controllers/PublicChatController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
diff --git a/src/slskd/Controllers/RoomsController.cs b/src/slskd/API/Controllers/RoomsController.cs
index 34557d27..29693bbc 100644
--- a/src/slskd/Controllers/RoomsController.cs
+++ b/src/slskd/API/Controllers/RoomsController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
@@ -8,7 +8,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd.Entities;
using slskd.Trackers;
diff --git a/src/slskd/Controllers/SearchesController.cs b/src/slskd/API/Controllers/SearchesController.cs
index 28637262..46b6ec3e 100644
--- a/src/slskd/Controllers/SearchesController.cs
+++ b/src/slskd/API/Controllers/SearchesController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using System;
using System.Collections.Concurrent;
@@ -8,7 +8,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Soulseek;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd.Trackers;
/// <summary>
diff --git a/src/slskd/Controllers/ServerController.cs b/src/slskd/API/Controllers/ServerController.cs
index ed6e84c8..fb194974 100644
--- a/src/slskd/Controllers/ServerController.cs
+++ b/src/slskd/API/Controllers/ServerController.cs
@@ -1,10 +1,10 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Soulseek;
using System.Threading.Tasks;
- using slskd.DTO;
+ using slskd.API.DTO;
/// <summary>
/// Server
diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/API/Controllers/SessionController.cs
index 34563623..d5b2c81a 100644
--- a/src/slskd/Controllers/SessionController.cs
+++ b/src/slskd/API/Controllers/SessionController.cs
@@ -1,6 +1,6 @@
using Microsoft.Extensions.Options;
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -9,7 +9,7 @@ namespace slskd.Controllers
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd;
using slskd.Configuration;
@@ -120,7 +120,7 @@ namespace slskd.Controllers
var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
- issuer: "slskd",
+ issuer: Program.AppName,
claims: claims,
notBefore: issuedUtc,
expires: expiresUtc,
diff --git a/src/slskd/Controllers/TransfersController.cs b/src/slskd/API/Controllers/TransfersController.cs
index d19ec91d..948bf7ff 100644
--- a/src/slskd/Controllers/TransfersController.cs
+++ b/src/slskd/API/Controllers/TransfersController.cs
@@ -1,6 +1,6 @@
using Microsoft.Extensions.Options;
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -11,7 +11,7 @@ namespace slskd.Controllers
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd.Trackers;
using slskd.Configuration;
diff --git a/src/slskd/Controllers/UserController.cs b/src/slskd/API/Controllers/UserController.cs
index e4a0859f..73efca0f 100644
--- a/src/slskd/Controllers/UserController.cs
+++ b/src/slskd/API/Controllers/UserController.cs
@@ -1,4 +1,4 @@
-namespace slskd.Controllers
+namespace slskd.API.Controllers
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
@@ -6,7 +6,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Soulseek;
- using slskd.DTO;
+ using slskd.API.DTO;
using slskd.Trackers;
/// <summary>
diff --git a/src/slskd/DTO/ConnectRequest.cs b/src/slskd/API/DTO/ConnectRequest.cs
index 6d2203b7..5d90073f 100644
--- a/src/slskd/DTO/ConnectRequest.cs
+++ b/src/slskd/API/DTO/ConnectRequest.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
public class ConnectRequest
{
diff --git a/src/slskd/DTO/LoginRequest.cs b/src/slskd/API/DTO/LoginRequest.cs
index 04c3dd65..269a489b 100644
--- a/src/slskd/DTO/LoginRequest.cs
+++ b/src/slskd/API/DTO/LoginRequest.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
public class LoginRequest
{
diff --git a/src/slskd/DTO/PrivateMessageResponse.cs b/src/slskd/API/DTO/PrivateMessageResponse.cs
index fb60be32..e20ce637 100644
--- a/src/slskd/DTO/PrivateMessageResponse.cs
+++ b/src/slskd/API/DTO/PrivateMessageResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using System;
using slskd.Entities;
diff --git a/src/slskd/DTO/QueueDownloadRequest.cs b/src/slskd/API/DTO/QueueDownloadRequest.cs
index c2c1c2d4..fcd279ab 100644
--- a/src/slskd/DTO/QueueDownloadRequest.cs
+++ b/src/slskd/API/DTO/QueueDownloadRequest.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
public class QueueDownloadRequest
{
diff --git a/src/slskd/DTO/RoomInfoResponse.cs b/src/slskd/API/DTO/RoomInfoResponse.cs
index 0b0aadf0..8b9a3cb6 100644
--- a/src/slskd/DTO/RoomInfoResponse.cs
+++ b/src/slskd/API/DTO/RoomInfoResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using Soulseek;
diff --git a/src/slskd/DTO/RoomMessageResponse.cs b/src/slskd/API/DTO/RoomMessageResponse.cs
index b64bedf3..3a804b65 100644
--- a/src/slskd/DTO/RoomMessageResponse.cs
+++ b/src/slskd/API/DTO/RoomMessageResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using System;
using slskd.Entities;
diff --git a/src/slskd/DTO/RoomResponse.cs b/src/slskd/API/DTO/RoomResponse.cs
index 22ea845a..d7708da7 100644
--- a/src/slskd/DTO/RoomResponse.cs
+++ b/src/slskd/API/DTO/RoomResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using slskd.Entities;
using System.Collections.Generic;
diff --git a/src/slskd/DTO/SearchRequest.cs b/src/slskd/API/DTO/SearchRequest.cs
index 7123a348..2e6c61e6 100644
--- a/src/slskd/DTO/SearchRequest.cs
+++ b/src/slskd/API/DTO/SearchRequest.cs
@@ -1,7 +1,7 @@
using Soulseek;
using System;
-namespace slskd.DTO
+namespace slskd.API.DTO
{
/// <summary>
/// A search request.
diff --git a/src/slskd/DTO/TokenResponse.cs b/src/slskd/API/DTO/TokenResponse.cs
index fb1b81ee..3490d570 100644
--- a/src/slskd/DTO/TokenResponse.cs
+++ b/src/slskd/API/DTO/TokenResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using System;
using System.IdentityModel.Tokens.Jwt;
diff --git a/src/slskd/DTO/Transfer.cs b/src/slskd/API/DTO/Transfer.cs
index dfefa5c8..34639a40 100644
--- a/src/slskd/DTO/Transfer.cs
+++ b/src/slskd/API/DTO/Transfer.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using Soulseek;
using System;
diff --git a/src/slskd/DTO/UserAddress.cs b/src/slskd/API/DTO/UserAddress.cs
index 1a69bf7f..4fe7dc4a 100644
--- a/src/slskd/DTO/UserAddress.cs
+++ b/src/slskd/API/DTO/UserAddress.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
/// <summary>
/// A user's IP address and port.
diff --git a/src/slskd/DTO/UserDataResponse.cs b/src/slskd/API/DTO/UserDataResponse.cs
index fcbf8899..5d79639c 100644
--- a/src/slskd/DTO/UserDataResponse.cs
+++ b/src/slskd/API/DTO/UserDataResponse.cs
@@ -1,4 +1,4 @@
-namespace slskd.DTO
+namespace slskd.API.DTO
{
using Soulseek;
diff --git a/src/slskd/Common/Configuration/CommandLineArguments.cs b/src/slskd/Common/Configuration/CommandLineArguments.cs
deleted file mode 100644
index 491965e7..00000000
--- a/src/slskd/Common/Configuration/CommandLineArguments.cs
+++ /dev/null
@@ -1,666 +0,0 @@
-namespace slskd.Configuration
-{
- using System;
- using System.Collections;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Text.RegularExpressions;
-
- /// <summary>
- /// Provides extension method(s) for the CommandLineArguments namespace.
- /// </summary>
- public static class CommandLineArgumentsExtensions
- {
- /// <summary>
- /// Gets the DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>.
- /// </summary>
- /// <param name="caller">The name of the calling method for which the DeclaringType is to be fetched.</param>
- /// <returns>The DeclaringType of the first method on the stack whose name matches the specified <paramref name="caller"/>.</returns>
- internal static Type GetCallingType(string caller)
- {
- var callingMethod = new StackTrace().GetFrames()
- .Select(f => f.GetMethod())
- .FirstOrDefault(m => m.Name == caller);
-
- if (callingMethod == default)
- {
- throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
- }
-
- return callingMethod.DeclaringType;
- }
-
- /// <summary>
- /// Removes the outermost pair of enclosing quotes.
- /// </summary>
- /// <param name="value">The string to trim.</param>
- /// <returns>The trimmed string.</returns>
- internal static string TrimOuterQuotes(this string value)
- {
- if (value.StartsWith("\"", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("\"", StringComparison.InvariantCultureIgnoreCase))
- {
- value = value.Trim('"');
- }
- else if (value.StartsWith("'", StringComparison.InvariantCultureIgnoreCase) && value.EndsWith("'", StringComparison.InvariantCultureIgnoreCase))
- {
- value = value.Trim('\'');
- }
-
- return value;
- }
- }
-
- /// <summary>
- /// Indicates that the property is to be used as a target for automatic population of values from command line arguments
- /// when invoking the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class CommandLineArgumentAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="CommandLineArgumentAttribute"/> class.
- /// </summary>
- /// <param name="shortName">The short name of the argument, represented as a single character.</param>
- /// <param name="longName">The long name of the argument.</param>
- /// <param name="helpText">The help text of the argument.</param>
- public CommandLineArgumentAttribute(char shortName, string longName, string helpText = null)
- {
- ShortName = shortName;
- LongName = longName;
- HelpText = helpText;
- }
-
- /// <summary>
- /// Gets or sets the help text of the argument.
- /// </summary>
- public string HelpText { get; set; }
-
- /// <summary>
- /// Gets or sets the long name of the argument.
- /// </summary>
- public string LongName { get; set; }
-
- /// <summary>
- /// Gets or sets the short name of the argument.
- /// </summary>
- public char ShortName { get; set; }
- }
-
- /// <summary>
- /// Encapsulates argument names and help text.
- /// </summary>
- public class ArgumentInfo
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="ArgumentInfo"/> class.
- /// </summary>
- /// <param name="shortName">The short name of the argument.</param>
- /// <param name="longName">The long name of the argument.</param>
- /// <param name="helpText">The help text for the argument.</param>
- /// <param name="property">The property with which the argument is associated.</param>
- public ArgumentInfo(char shortName, string longName, string helpText, PropertyInfo property)
- {
- ShortName = shortName;
- LongName = longName;
- HelpText = helpText;
- Property = property;
- }
-
- /// <summary>
- /// Gets the help text for the argument.
- /// </summary>
- public string HelpText { get; }
-
- /// <summary>
- /// Gets a value indicating whether the argument backing Type is a collection.
- /// </summary>
- public bool IsCollection => Property.PropertyType.IsArray || (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(List<>));
-
- /// <summary>
- /// Gets the long name of the argument.
- /// </summary>
- public string LongName { get; }
-
- /// <summary>
- /// Gets the property with which the argument is associated.
- /// </summary>
- public PropertyInfo Property { get; }
-
- /// <summary>
- /// Gets the short name of the argument.
- /// </summary>
- public char ShortName { get; }
- }
-
- /// <summary>
- /// Provides static methods used to retrieve the command line arguments and operands with which the application was
- /// started, as well as a Type to contain them.
- /// </summary>
- public class CommandLineArguments
- {
- /// <summary>
- /// The regular expression with which to parse the command line string.
- /// </summary>
- private const string ArgumentRegExWithoutForwardSlash = "(?:[-]{1,2})([^=: ]+)[=: ]?([^-'\"]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to parse the command line string, including the ability to specify forward slashes.
- /// </summary>
- private const string ArgumentRegExWithForwardSlash = "(?:[-]{1,2}|\\/)([^=: ]+)[=: ]?([^-'\"\\/]\\S*|\\\"[^\"]*\\\"|\\\'[^']*\\\')?|([^ ([^'\\\"]+|\"[^\\\"]+\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to parse argument-value groups.
- /// </summary>
- private const string GroupRegEx = "^-[^-]+";
-
- /// <summary>
- /// The regular expression with which to parse strings strictly containing operands.
- /// </summary>
- private const string OperandRegEx = "([^ ([^'\\\"]+|\\\"[^\\\"]+\\\"|\\\'[^']+\\\')";
-
- /// <summary>
- /// The regular expression with which to split the command line string explicitly among argument/value pairs and
- /// operands, and strictly operands.
- /// </summary>
- /// <remarks>
- /// This regular expression effectively splits a string into two parts; the part before the first "--", and the part
- /// after. Instances of "--" not surrounded by a word boundary and those enclosed in quotes are ignored.
- /// </remarks>
- private const string StrictOperandSplitRegEx = "(.*?[^\\\"\\\'])?(\\B-{2}\\B)[^\\\"\\\']?(.*)";
-
- private CommandLineArguments(string commandLineString, List<KeyValuePair<string, string>> argumentList, Dictionary<string, object> argumentDictionary, List<string> operandList, Type targetType = null)
- {
- CommandLineString = commandLineString;
- ArgumentList = argumentList;
- ArgumentDictionary = argumentDictionary;
- OperandList = operandList;
- TargetType = targetType;
- }
-
- /// <summary>
- /// Gets or sets a value indicating whether forward slashes are processed as argument delimiters.
- /// </summary>
- public static bool EnableForwardSlash { get; set; } = false;
-
- /// <summary>
- /// Gets a dictionary containing the arguments and values specified in the command line arguments with which the
- /// application was started.
- /// </summary>
- /// <remarks>
- /// This dictionary contains argument key/value pairs compiled from the <see cref="ArgumentList"/> and checked against
- /// the <see cref="TargetType"/> to combine duplicated pairs into lists where the backing property is a collection, and
- /// to overwrite where the backing property is not a collection.
- /// </remarks>
- public Dictionary<string, object> ArgumentDictionary { get; }
-
- /// <summary>
- /// Gets the list of arguments specified in the command line arguments with which the application was started.
- /// </summary>
- /// <remarks>
- /// This list contains each argument key/value pair as supplied in the original string, preserving the original order
- /// and any duplicated pairs.
- /// </remarks>
- public List<KeyValuePair<string, string>> ArgumentList { get; }
-
- /// <summary>
- /// Gets the command line string from which the arguments were parsed.
- /// </summary>
- public string CommandLineString { get; }
-
- /// <summary>
- /// Gets a list containing the operands specified in the command line arguments with which the application was started.
- /// </summary>
- public List<string> OperandList { get; private set; }
-
- /// <summary>
- /// Gets the target Type, if applicable.
- /// </summary>
- public Type TargetType { get; }
-
- private static string ArgumentRegEx => EnableForwardSlash ? ArgumentRegExWithForwardSlash : ArgumentRegExWithoutForwardSlash;
-
- /// <summary>
- /// Gets the argument value corresponding to the specified <paramref name="index"/>.
- /// </summary>
- /// <param name="index">The index for which the value is to be retrieved.</param>
- /// <returns>The argument value corresponding to the specified index.</returns>
- public object this[int index]
- {
- get
- {
- return ArgumentList[index].Value;
- }
- }
-
- /// <summary>
- /// Gets the argument value corresponding to the specified <paramref name="key"/> from the
- /// <see cref="ArgumentDictionary"/> property.
- /// </summary>
- /// <param name="key">The key for which the value is to be retrieved.</param>
- /// <returns>The argument value corresponding to the specified key.</returns>
- public object this[string key]
- {
- get
- {
- return ArgumentDictionary[key];
- }
- }
-
- /// <summary>
- /// Retrieves a collection of <see cref="ArgumentInfo"/> gathered from properties in the target <paramref name="type"/>
- /// marked with the <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> along with the short and long names and help text.
- /// </summary>
- /// <param name="type">The <see cref="Type"/> for which the matching properties are to be retrieived.</param>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- /// <returns>The retrieved collection of <see cref="ArgumentInfo"/>.</returns>
- public static IEnumerable<ArgumentInfo> GetArgumentInfo(Type type = null, [CallerMemberName] string caller = default)
- {
- type ??= CommandLineArgumentsExtensions.GetCallingType(caller);
- var retVal = new List<ArgumentInfo>();
-
- foreach (PropertyInfo property in GetArgumentProperties(type).Values.Distinct())
- {
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name);
-
- if (attribute != default(CustomAttributeData))
- {
- retVal.Add(new ArgumentInfo(
- shortName: (char)attribute.ConstructorArguments[0].Value,
- longName: (string)attribute.ConstructorArguments[1].Value,
- helpText: (string)attribute.ConstructorArguments[2].Value,
- property: property));
- }
- }
-
- return retVal;
- }
-
- /// <summary>
- /// Returns a dictionary containing the values specified in the command line arguments with which the application was
- /// started, keyed by argument name.
- /// </summary>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="type">The <see cref="Type"/> for which the command line string is to be parsed.</param>
- /// <returns>
- /// The dictionary containing the arguments and values specified in the command line arguments with which the
- /// application was started.
- /// </returns>
- public static CommandLineArguments Parse(string commandLineString = default, Type type = null)
- {
- commandLineString = commandLineString == default || string.IsNullOrEmpty(commandLineString) ? Environment.CommandLine : commandLineString;
-
- List<KeyValuePair<string, string>> argumentList;
- List<string> operandList;
-
- // use the strict operand regular expression to test for/extract the two halves of the string, if the operator is used.
- MatchCollection matches = Regex.Matches(commandLineString, StrictOperandSplitRegEx);
-
- // if there is a match, the string contains the strict operand delimiter. parse the first and second matches accordingly.
- if (matches.Count > 0)
- {
- // the first group of the first match will contain everything in the string prior to the strict operand delimiter,
- // so extract the argument key/value pairs and list of operands from that string.
- argumentList = GetArgumentList(matches[0].Groups[1].Value);
- operandList = GetOperandList(matches[0].Groups[1].Value);
-
- // the first group of the second match will contain everything in the string after the strict operand delimiter, so
- // extract the operands from that string using the strict method.
- if (!string.IsNullOrEmpty(matches[0].Groups[3].Value))
- {
- List<string> operandListStrict = GetOperandListStrict(matches[0].Groups[3].Value);
- operandList.AddRange(operandListStrict);
- }
- }
- else
- {
- argumentList = GetArgumentList(commandLineString);
- operandList = GetOperandList(commandLineString);
- }
-
- var argumentDictionary = GetArgumentDictionary(argumentList, type);
- return new CommandLineArguments(commandLineString, argumentList, argumentDictionary, operandList, type);
- }
-
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line
- /// arguments, if present.
- /// </summary>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- public static void Populate(string commandLineString = default, bool clearExistingValues = true, [CallerMemberName] string caller = default)
- {
- var type = CommandLineArgumentsExtensions.GetCallingType(caller);
- Populate(type, Parse(commandLineString, type), clearExistingValues);
- }
-
- /// <summary>
- /// Populates the properties in the specified Type marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the list of command line
- /// arguments, if present.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of command line arguments are to be populated.
- /// </param>
- /// <param name="commandLineString">The command line arguments with which the application was started.</param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- public static void Populate(Type type, string commandLineString = default, bool clearExistingValues = true)
- {
- Populate(type, Parse(commandLineString, type), clearExistingValues);
- }
-
- /// <summary>
- /// Populates the properties in the specified Type marked with the
- /// <see cref="CommandLineArgumentAttribute"/><see cref="Attribute"/> with the values specified in the specified argument
- /// dictionary, if present. All property values are set to null at the start of the routine.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of command line arguments are to be populated.
- /// </param>
- /// <param name="arguments">
- /// The Arguments object containing the dictionary containing the argument-value pairs with which the destination
- /// properties should be populated and the list of operands.
- /// </param>
- /// <param name="clearExistingValues">Whether to clear the properties before populating them. Defaults to true.</param>
- public static void Populate(Type type, CommandLineArguments arguments, bool clearExistingValues = true)
- {
- // fetch any properties in the specified type marked with the ArgumentAttribute attribute and clear them
- Dictionary<string, PropertyInfo> properties = GetArgumentProperties(type);
-
- if (clearExistingValues)
- {
- ClearProperties(properties);
- }
-
- foreach (string propertyName in properties.Keys)
- {
- // if the argument dictionary contains a matching argument
- if (arguments.ArgumentDictionary.ContainsKey(propertyName))
- {
- // retrieve the property and type
- PropertyInfo property = properties[propertyName];
- Type propertyType = property.PropertyType;
-
- // retrieve the value from the argument dictionary
- object value = arguments.ArgumentDictionary[propertyName];
-
- object convertedValue;
-
- // if the type of the property is bool and the argument value is empty set the property value to true,
- // indicating the argument is present
- if (propertyType == typeof(bool))
- {
- convertedValue = true;
-
- // if a value is specified, a bool flag was followed by an operand and the parser interpreted this as key
- // value pair because it wasn't aware the flag was backed by a bool. remove the argument from the original
- // string and re-parse operands from it to preserve order.
- if (!string.IsNullOrEmpty(value.ToString()))
- {
- var arg = Regex.Matches(arguments.CommandLineString, "(?:[-]{1,2}|\\/)" + propertyName)[0].Value;
- arguments.OperandList = GetOperandList(arguments.CommandLineString.Replace(arg, string.Empty));
- }
- }
- else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
- {
- convertedValue = value;
-
- // next, create a list with the same type as the target property
- Type valueType;
-
- if (propertyType.IsArray)
- {
- valueType = propertyType.GetElementType();
- }
- else
- {
- valueType = propertyType.GetGenericArguments()[0];
- }
-
- // create a list to store converted values
- Type valueListType = typeof(List<>).MakeGenericType(valueType);
- var valueList = (IList)Activator.CreateInstance(valueListType);
-
- // populate the list
- foreach (object v in (List<object>)convertedValue)
- {
- valueList.Add(ChangeType(v, propertyName, valueType));
- }
-
- // if the target property is an array, create one and populate it from the list this is surprisingly
- // difficult here because we created the source list with the Activator and ToArray() won't work easily.
- if (propertyType.IsArray)
- {
- var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count);
-
- for (int i = 0; i < valueArray.Length; i++)
- {
- valueArray.SetValue(valueList[i], i);
- }
-
- convertedValue = valueArray;
- }
- else
- {
- convertedValue = valueList;
- }
- }
- else
- {
- convertedValue = ChangeType(value, propertyName, propertyType);
- }
-
- // set the target properties' value to the converted value from the argument string
- property.SetValue(null, convertedValue);
- }
- }
-
- PropertyInfo operandsProperty = GetOperandsProperty(type);
-
- // check to ensure the target class has a property marked with the Operands attribute; if not GetOperandsProperty()
- // will return null.
- if (operandsProperty != default)
- {
- if (operandsProperty.PropertyType.IsAssignableFrom(typeof(List<string>)))
- {
- operandsProperty.SetValue(null, arguments.OperandList);
- }
- else
- {
- operandsProperty.SetValue(null, arguments.OperandList.ToArray());
- }
- }
- }
-
- private static object ChangeType(object value, string argument, Type toType)
- {
- try
- {
- if (toType.IsEnum)
- {
- return Enum.Parse(toType, (string)value, true);
- }
-
- return Convert.ChangeType(value, toType, CultureInfo.InvariantCulture);
- }
- catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
- {
- string message = $"Specified value '{value}' for argument '{argument}' (expected type: {toType}). ";
- message += "See inner exception for details.";
-
- throw new ArgumentException(message, ex);
- }
- }
-
- private static void ClearProperties(Dictionary<string, PropertyInfo> properties)
- {
- foreach (string key in properties.Keys)
- {
- properties[key].SetValue(null, null);
- }
- }
-
- private static Dictionary<string, object> GetArgumentDictionary(List<KeyValuePair<string, string>> argumentList, Type targetType = null)
- {
- var dict = new ConcurrentDictionary<string, object>();
- var argumentInfo = targetType == null ? new List<ArgumentInfo>() : GetArgumentInfo(targetType);
-
- foreach (var arg in argumentList)
- {
- var info = argumentInfo.SingleOrDefault(i => i.ShortName.ToString(CultureInfo.InvariantCulture) == arg.Key || i.LongName == arg.Key);
-
- if (info != default(ArgumentInfo))
- {
- bool added = false;
-
- foreach (var k in new[] { info.ShortName.ToString(CultureInfo.InvariantCulture), info.LongName })
- {
- if (dict.ContainsKey(k))
- {
- dict.AddOrUpdate(k, arg.Value, (key, existingValue) => info.IsCollection ? ((List<object>)existingValue).Concat(new[] { arg.Value }).ToList() : (object)arg.Value);
- added = true;
- break;
- }
- }
-
- if (!added)
- {
- dict.TryAdd(arg.Key, info.IsCollection ? new List<object>(new[] { arg.Value }) : (object)arg.Value);
- }
- }
- else
- {
- dict.AddOrUpdate(arg.Key, arg.Value, (key, existingValue) => arg.Value);
- }
- }
-
- return dict.ToDictionary(a => a.Key, a => a.Value);
- }
-
- private static List<KeyValuePair<string, string>> GetArgumentList(string commandLineString)
- {
- var argumentList = new List<KeyValuePair<string, string>>();
-
- foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx))
- {
- // the first match of the regular expression used to parse the string will contain the argument name, if one was matched.
- if (match.Groups[1].Value == default || string.IsNullOrEmpty(match.Groups[1].Value))
- {
- continue;
- }
-
- string fullMatch = match.Groups[0].Value;
- string argument = match.Groups[1].Value;
- string value = match.Groups[2].Value;
-
- value = value.TrimOuterQuotes();
-
- // check to see if the argument uses a single dash. if so, split the argument name into a char array and add each
- // to the list. if a value is specified, it belongs to the final character.
- if (Regex.IsMatch(fullMatch, GroupRegEx))
- {
- char[] charArray = argument.ToCharArray();
-
- // iterate over the characters backwards to more easily assign the value
- for (int i = 0; i < charArray.Length; i++)
- {
- argumentList.Add(new KeyValuePair<string, string>(charArray[i].ToString(CultureInfo.InvariantCulture), i == charArray.Length - 1 ? value : string.Empty));
- }
- }
- else
- {
- argumentList.Add(new KeyValuePair<string, string>(argument, value));
- }
- }
-
- return argumentList;
- }
-
- private static Dictionary<string, PropertyInfo> GetArgumentProperties(Type type)
- {
- Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
-
- foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
- {
- // attempt to fetch the ArgumentAttribute of the property
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(CommandLineArgumentAttribute).Name);
-
- // if found, extract the Name property and add it to the dictionary
- if (attribute != default(CustomAttributeData))
- {
- char shortName = (char)attribute.ConstructorArguments[0].Value;
- string longName = (string)attribute.ConstructorArguments[1].Value;
-
- if (!properties.ContainsKey(shortName.ToString(CultureInfo.InvariantCulture)) && !properties.ContainsKey(longName))
- {
- properties.Add(shortName.ToString(CultureInfo.InvariantCulture), property);
- properties.Add(longName, property);
- }
- }
- }
-
- return properties;
- }
-
- private static List<string> GetOperandList(string commandLineString)
- {
- List<string> operands = new List<string>();
-
- foreach (Match match in Regex.Matches(commandLineString, ArgumentRegEx))
- {
- // the 3rd match of the regular expression used to parse the string will contain the operand, if one was matched.
- if (match.Groups[3].Value == default || string.IsNullOrEmpty(match.Groups[3].Value))
- {
- continue;
- }
-
- string operand = match.Groups[3].Value;
-
- operands.Add(operand.TrimOuterQuotes());
- }
-
- return operands;
- }
-
- private static List<string> GetOperandListStrict(string operandListString)
- {
- List<string> operands = new List<string>();
-
- foreach (Match match in Regex.Matches(operandListString, OperandRegEx))
- {
- operands.Add(match.Groups[0].Value);
- }
-
- return operands;
- }
-
- private static PropertyInfo GetOperandsProperty(Type type)
- {
- PropertyInfo property = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
- .FirstOrDefault(p => p.CustomAttributes
- .Any(a => a.AttributeType.Name == typeof(OperandsAttribute).Name));
-
- if (property != default && property.PropertyType != typeof(string[]) && property.PropertyType != typeof(List<string>))
- {
- throw new InvalidCastException("The target for the Operands attribute must be of string[] or List<string>.");
- }
-
- return property;
- }
- }
-
- /// <summary>
- /// Indicates that the property is to be used as the target for automatic population of command line operands when invoking
- /// the <see cref="CommandLineArguments.Populate(string, bool, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class OperandsAttribute : Attribute
- {
- }
-} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
index fb479fd4..6cf59808 100644
--- a/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/CommandLineConfigurationSource.cs
@@ -1,139 +1,157 @@
-namespace slskd.Configuration
+// <copyright file="CommandLineConfigurationSource.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines a command line argument mapping.
- /// </summary>
- public record CommandLineArgument(char ShortName, string LongName, Type Type, string Key, string Description = null);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
+ using Utility.CommandLine;
/// <summary>
/// Extension methods for adding <see cref="CommandLineConfigurationProvider"/>.
/// </summary>
- public static class CommandLineExtensions
+ public static class CommandLineConfigurationExtensions
{
/// <summary>
/// Adds a command line argument configuration soruce to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <param name="map">A list of command line argument mappings.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to map properties.</param>
/// <param name="commandLine">The command line string from which to parse arguments.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns></returns>
- public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, IEnumerable<CommandLineArgument> map, string commandLine = null, bool normalizeKey = true)
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Type targetType, string commandLine = null)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddCommandLine(s =>
{
- s.Map = map;
+ s.TargetType = targetType;
s.CommandLine = commandLine ?? Environment.CommandLine;
- s.NormalizeKey = normalizeKey;
});
}
/// <summary>
/// Adds a command line argument configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddCommandLine(this IConfigurationBuilder builder, Action<CommandLineConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents command line arguments as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class CommandLineConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="CommandLineConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="CommandLineConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this);
-
- /// <summary>
- /// Gets or sets a list of command line argument mappings.
- /// </summary>
- public IEnumerable<CommandLineArgument> Map { get; set; }
-
- /// <summary>
- /// Gets or sets the command line string from which to parse arguments.
- /// </summary>
- public string CommandLine { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// A command line argument <see cref="ConfigurationProvider"/>.
/// </summary>
public class CommandLineConfigurationProvider : ConfigurationProvider
{
- private IEnumerable<CommandLineArgument> Map { get; set; }
- private string CommandLine { get; set; }
- private bool NormalizeKey { get; set; }
-
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="CommandLineConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public CommandLineConfigurationProvider(CommandLineConfigurationSource source)
+ public CommandLineConfigurationProvider(CommandLineConfigurationSource source)
{
- Map = source.Map;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
CommandLine = source.CommandLine;
- NormalizeKey = source.NormalizeKey;
}
+ private string CommandLine { get; set; }
+ private string Namespace { get; set; }
+ private Type TargetType { get; set; }
+
/// <summary>
- /// Parses command line arguments from the specified string and maps them to the specified keys.
+ /// Parses command line arguments from the specified string and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- var dictionary = CommandLineArguments.Parse(CommandLine).ArgumentDictionary;
+ var dictionary = Arguments.Parse(CommandLine).ArgumentDictionary;
- foreach (CommandLineArgument item in Map)
+ void Map(Type type, string path)
{
- var (shortName, longName, type, key, _) = item;
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (NormalizeKey)
+ foreach (PropertyInfo property in props)
{
- key = key?.Replace("-", string.Empty).Replace("_", string.Empty).ToLowerInvariant();
- }
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute));
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
- if (string.IsNullOrEmpty(key))
- {
- continue;
- }
-
- var arguments = new[] { shortName.ToString(), longName }.Where(i => !string.IsNullOrEmpty(i));
-
- foreach (var argument in arguments)
- {
- if (dictionary.ContainsKey(argument))
+ if (attribute != default)
{
- var value = dictionary[argument].ToString();
+ var shortName = ((char)attribute.ConstructorArguments[0].Value).ToString();
+ var longName = (string)attribute.ConstructorArguments[1].Value;
+ var arguments = new[] { shortName, longName }.Where(i => !string.IsNullOrEmpty(i));
- if (type == typeof(bool) && string.IsNullOrEmpty(value))
+ foreach (var argument in arguments)
{
- value = "true";
- }
+ if (dictionary.ContainsKey(argument))
+ {
+ var value = dictionary[argument].ToString();
- Data[item.Key] = value;
+ if (property.PropertyType == typeof(bool) && string.IsNullOrEmpty(value))
+ {
+ value = "true";
+ }
+
+ Data[key] = value;
+ }
+ }
+ }
+ else
+ {
+ Map(property.PropertyType, key);
}
}
}
+
+ Map(TargetType, Namespace);
}
}
-}
+
+ /// <summary>
+ /// Represents command line arguments as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class CommandLineConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the command line string from which to parse arguments.
+ /// </summary>
+ public string CommandLine { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="CommandLineConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="CommandLineConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder) => new CommandLineConfigurationProvider(this);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/ConfigurationExtensions.cs b/src/slskd/Common/Configuration/ConfigurationExtensions.cs
deleted file mode 100644
index 77b59700..00000000
--- a/src/slskd/Common/Configuration/ConfigurationExtensions.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace slskd.Configuration
-{
- public static class ConfigurationExtensions
- {
- public static CommandLineArgument ToCommandLineArgument(this Option option)
- => new(option.ShortName, option.LongName, option.Type, option.Key, option.Description);
-
- public static EnvironmentVariable ToEnvironmentVariable(this Option option)
- => new(option.EnvironmentVariable, option.Type, option.Key, option.Description);
-
- public static DefaultValue ToDefaultValue(this Option option)
- => new(option.Key, option.Type, option.Default);
- }
-}
diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
index accc76c9..15cf4070 100644
--- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
@@ -1,14 +1,26 @@
-namespace slskd.Configuration
+// <copyright file="DefaultValueConfigurationSource.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines an default value mapping.
- /// </summary>
- public record DefaultValue(string Key, Type Type, object Default);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
/// <summary>
/// Extension methods for adding <see cref="DefaultValueConfigurationProvider"/>.
@@ -18,104 +30,107 @@
/// <summary>
/// Adds a default value configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="map">A list of default value mappings.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, IEnumerable<DefaultValue> map, bool normalizeKey = true)
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to load default values.</param>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Type targetType)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddDefaultValues(s =>
{
- s.Map = map ?? Enumerable.Empty<DefaultValue>();
- s.NormalizeKey = normalizeKey;
+ s.TargetType = targetType;
});
}
/// <summary>
/// Adds a default value configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddDefaultValues(this IConfigurationBuilder builder, Action<DefaultValueConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents default values as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class DefaultValueConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="DefaultValueConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="DefaultValueConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- return new DefaultValueConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a list of default value mappings.
- /// </summary>
- public IEnumerable<DefaultValue> Map { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// A default value <see cref="ConfigurationProvider"/>.
/// </summary>
public class DefaultValueConfigurationProvider : ConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="DefaultValueConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source)
+ public DefaultValueConfigurationProvider(DefaultValueConfigurationSource source)
{
- Map = source.Map;
- NormalizeKey = source.NormalizeKey;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
}
- private IEnumerable<DefaultValue> Map { get; set; }
- private bool NormalizeKey { get; set; }
+ private string Namespace { get; set; }
+ private Type TargetType { get; set; }
/// <summary>
- /// Sets the keys specified in the map to the specified default values.
+ /// Loads default values from the specified <see cref="TargetType"/> and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- foreach (var item in Map)
+ void Map(Type type, string path)
{
- var (key, _, value) = item;
+ var defaults = Activator.CreateInstance(type);
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (NormalizeKey)
+ foreach (PropertyInfo property in props)
{
- key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant();
- }
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
- if (string.IsNullOrEmpty(key))
- {
- continue;
- }
+ if (property.PropertyType.Namespace.StartsWith(Namespace))
+ {
+ Map(property.PropertyType, key);
+ }
+ else
+ {
+ var value = property.GetValue(defaults);
- if (value == null)
- {
- continue;
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
+ }
}
-
- Data[item.Key] = value.ToString();
}
+
+ Map(TargetType, Namespace);
+ }
+ }
+
+ /// <summary>
+ /// Represents default values as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class DefaultValueConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="DefaultValueConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="DefaultValueConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new DefaultValueConfigurationProvider(this);
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
index a18faebc..9a09d4e1 100644
--- a/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/EnvironmentVariableConfigurationSource.cs
@@ -1,14 +1,27 @@
-namespace slskd.Configuration
+// <copyright file="EnvironmentVariableConfigurationSource.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Configuration
{
- using Microsoft.Extensions.Configuration;
using System;
- using System.Collections.Generic;
using System.Linq;
-
- /// <summary>
- /// Defines an environment variable mapping.
- /// </summary>
- public record EnvironmentVariable(string Name, Type Type, string Key, string Description = null);
+ using System.Reflection;
+ using Microsoft.Extensions.Configuration;
+ using Utility.EnvironmentVariables;
/// <summary>
/// Extension methods for adding <see cref="EnvironmentVariableConfigurationProvider"/>.
@@ -18,120 +31,121 @@
/// <summary>
/// Adds an environment variable configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="map">A list of environment variable mappings.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
+ /// <param name="targetType">The type from which to map properties.</param>
/// <param name="prefix">A prefix to prepend to all variable names.</param>
- /// <param name="normalizeKey">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
- public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, IEnumerable<EnvironmentVariable> map, string prefix = null, bool normalizeKey = true)
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
+ public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Type targetType, string prefix = null)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+
return builder.AddEnvironmentVariables(s =>
{
- s.Map = map ?? Enumerable.Empty<EnvironmentVariable>();
+ s.TargetType = targetType;
s.Prefix = prefix ?? string.Empty;
- s.NormalizeKey = normalizeKey;
});
}
/// <summary>
/// Adds an enviroment variable configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddEnvironmentVariables(this IConfigurationBuilder builder, Action<EnvironmentVariableConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents environment variables as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class EnvironmentVariableConfigurationSource : IConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="EnvironmentVariableConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="EnvironmentVariableConfigurationProvider"/>.</returns>
- public IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- return new EnvironmentVariableConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a list of enviroment variable mappings.
- /// </summary>
- public IEnumerable<EnvironmentVariable> Map { get; set; }
-
- /// <summary>
- /// Gets or sets a prefix to prepend to all variable names.
- /// </summary>
- public string Prefix { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKey { get; set; }
- }
-
- /// <summary>
/// An enviroment variable <see cref="ConfigurationProvider"/>.
/// </summary>
public class EnvironmentVariableConfigurationProvider : ConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="EnvironmentVariableConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source)
+ public EnvironmentVariableConfigurationProvider(EnvironmentVariableConfigurationSource source)
{
- Map = source.Map;
+ TargetType = source.TargetType;
+ Namespace = TargetType.Namespace.Split('.').First();
Prefix = source.Prefix;
- NormalizeKey = source.NormalizeKey;
}
- private IEnumerable<EnvironmentVariable> Map { get; set; }
- private bool NormalizeKey { get; set; }
+ private Type TargetType { get; set; }
+ private string Namespace { get; set; }
private string Prefix { get; set; }
/// <summary>
- /// Loads environment variables and maps them to the specified keys.
+ /// Loads environment variables and maps them to the corresponding keys.
/// </summary>
public override void Load()
{
- foreach (var item in Map)
+ void Map(Type type, string path)
{
- var (name, type, key, _) = item;
-
- if (NormalizeKey)
- {
- key = key?.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant();
- }
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(name))
+ foreach (PropertyInfo property in props)
{
- continue;
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute));
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
+
+ if (attribute != default)
+ {
+ var name = (string)attribute.ConstructorArguments[0].Value;
+
+ if (!string.IsNullOrEmpty(name))
+ {
+ var value = Environment.GetEnvironmentVariable(Prefix + name);
+
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
+ }
+ }
+ else
+ {
+ Map(property.PropertyType, key);
+ }
}
+ }
- var value = Environment.GetEnvironmentVariable(Prefix + name);
+ Map(TargetType, Namespace);
+ }
+ }
- if (string.IsNullOrEmpty(value))
- {
- continue;
- }
+ /// <summary>
+ /// Represents environment variables as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class EnvironmentVariableConfigurationSource : IConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets the type from which to map properties.
+ /// </summary>
+ public Type TargetType { get; set; }
- if (type == typeof(bool))
- {
- value = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) ? value : "false";
- }
+ /// <summary>
+ /// Gets or sets a prefix to prepend to all variable names.
+ /// </summary>
+ public string Prefix { get; set; }
- Data[item.Key] = value;
- }
+ /// <summary>
+ /// Builds the <see cref="EnvironmentVariableConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="EnvironmentVariableConfigurationProvider"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return new EnvironmentVariableConfigurationProvider(this);
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/EnvironmentVariables.cs b/src/slskd/Common/Configuration/EnvironmentVariables.cs
deleted file mode 100644
index 0ccda3cb..00000000
--- a/src/slskd/Common/Configuration/EnvironmentVariables.cs
+++ /dev/null
@@ -1,185 +0,0 @@
-namespace slskd.Configuration
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.CompilerServices;
-
- /// <summary>
- /// Indicates that the property is to be used as a target for automatic population of values from environment variables
- /// when invoking the <see cref="EnvironmentVariables.Populate(Type, string)"/> method.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
- public class EnvironmentVariableAttribute : Attribute
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="EnvironmentVariableAttribute"/> class.
- /// </summary>
- /// <param name="name">The name of the environment variable</param>
- public EnvironmentVariableAttribute(string name)
- {
- Name = name;
- }
-
- /// <summary>
- /// Gets or sets the name of the environment variable.
- /// </summary>
- public string Name { get; set; }
- }
-
- /// <summary>
- /// Provides static methods used to populate properties from environment variable values.
- /// </summary>
- public static class EnvironmentVariables
- {
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables.
- /// </summary>
- /// <param name="caller">Internal parameter used to identify the calling method.</param>
- /// <param name="prefix">The optional prefix for variable names.</param>
- public static void Populate(string prefix = null, [CallerMemberName] string caller = default)
- {
- Populate(GetCallingType(caller), prefix);
- }
-
- /// <summary>
- /// Populates the properties in the invoking class marked with the
- /// <see cref="EnvironmentVariableAttribute"/><see cref="Attribute"/> with the values specified in environment variables.
- /// </summary>
- /// <param name="type">
- /// The Type for which the static properties matching the list of environment variables are to be populated.
- /// </param>
- /// <param name="prefix">The optional prefix for variable names.</param>
- public static void Populate(Type type, string prefix = "")
- {
- prefix ??= string.Empty;
-
- var targetProperties = GetTargetProperties(type);
-
- foreach (var property in targetProperties)
- {
- var propertyType = property.Value.PropertyType;
-
- string value = Environment.GetEnvironmentVariable(prefix + property.Key);
-
- if (string.IsNullOrEmpty(value))
- {
- continue;
- }
-
- object convertedValue;
-
- if (propertyType == typeof(bool))
- {
- convertedValue = value?.Equals("true", StringComparison.InvariantCultureIgnoreCase) ?? false;
- }
- else if (propertyType.IsArray || (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List<>)))
- {
- Type valueType;
-
- if (propertyType.IsArray)
- {
- valueType = propertyType.GetElementType();
- }
- else
- {
- valueType = propertyType.GetGenericArguments()[0];
- }
-
- // create a list to store converted values
- Type valueListType = typeof(List<>).MakeGenericType(valueType);
- var valueList = (IList)Activator.CreateInstance(valueListType);
-
- // populate the list
- foreach (object v in value.Split(',').Select(s => s.Trim()))
- {
- valueList.Add(ChangeType(v, property.Key, valueType));
- }
-
- if (propertyType.IsArray)
- {
- var valueArray = Array.CreateInstance(propertyType.GetElementType(), valueList.Count);
-
- for (int i = 0; i < valueArray.Length; i++)
- {
- valueArray.SetValue(valueList[i], i);
- }
-
- convertedValue = valueArray;
- }
- else
- {
- convertedValue = valueList;
- }
- }
- else
- {
- convertedValue = ChangeType(value, property.Key, property.Value.PropertyType);
- }
-
- property.Value.SetValue(null, convertedValue);
- }
- }
-
- private static Type GetCallingType(string caller)
- {
- var callingMethod = new StackTrace().GetFrames()
- .Select(f => f.GetMethod())
- .FirstOrDefault(m => m.Name == caller);
-
- if (callingMethod == default)
- {
- throw new InvalidOperationException($"Unable to determine the containing type of the calling method '{caller}'. Explicitly specify the originating Type.");
- }
-
- return callingMethod.DeclaringType;
- }
-
- private static object ChangeType(object value, string name, Type type)
- {
- try
- {
- if (type.IsEnum)
- {
- return Enum.Parse(type, (string)value, true);
- }
-
- return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
- }
- catch (Exception ex) when (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
- {
- string message = $"Failed to convert value '{value}' to target type {type}";
- throw new ArgumentException(message, name, ex);
- }
- }
-
- private static Dictionary<string, PropertyInfo> GetTargetProperties(Type type)
- {
- Dictionary<string, PropertyInfo> properties = new Dictionary<string, PropertyInfo>();
-
- foreach (PropertyInfo property in type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
- {
- // attempt to fetch the ArgumentAttribute of the property
- CustomAttributeData attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == typeof(EnvironmentVariableAttribute).Name);
-
- // if found, extract the Name property and add it to the dictionary
- if (attribute != default(CustomAttributeData))
- {
- string name = (string)attribute.ConstructorArguments[0].Value;
-
- if (!properties.ContainsKey(name))
- {
- properties.Add(name, property);
- }
- }
- }
-
- return properties;
- }
- }
-} \ No newline at end of file
diff --git a/src/slskd/Common/Configuration/YamlConfigurationSource.cs b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
index 27ca6fea..332df647 100644
--- a/src/slskd/Common/Configuration/YamlConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/YamlConfigurationSource.cs
@@ -1,10 +1,27 @@
-namespace slskd.Configuration
+// <copyright file="YamlConfigurationSource.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Configuration
{
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.FileProviders;
using System;
using System.IO;
using System.Linq;
+ using Microsoft.Extensions.Configuration;
+ using Microsoft.Extensions.FileProviders;
using YamlDotNet.Core;
using YamlDotNet.RepresentationModel;
@@ -16,13 +33,16 @@
/// <summary>
/// Adds a YAML configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
- /// <param name="path">Path relative to the base path stored in
- /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add .</param>
+ /// <param name="path">
+ /// Path relative to the base path stored in <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.
+ /// </param>
/// <param name="optional">Whether the file is optional.</param>
/// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
- /// <param name="normalizeKeys">A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).</param>
- /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param>
+ /// <param name="normalizeKeys">
+ /// A value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
+ /// </param>
+ /// <param name="provider">The updated <see cref="IFileProvider"/> to use to access the file.</param>
/// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, string path, bool optional = true, bool reloadOnChange = false, bool normalizeKeys = true, IFileProvider provider = null)
{
@@ -50,52 +70,30 @@
/// <summary>
/// Adds a YAML configuration source to <paramref name="builder"/>.
/// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/> to which to add.</param>
/// <param name="configureSource">Configures the source.</param>
- /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
+ /// <returns>The updated <see cref="IConfigurationBuilder"/>.</returns>
public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, Action<YamlConfigurationSource> configureSource)
=> builder.Add(configureSource);
}
/// <summary>
- /// Represents a YAML file as an <see cref="IConfigurationSource"/>.
- /// </summary>
- public class YamlConfigurationSource : FileConfigurationSource
- {
- /// <summary>
- /// Builds the <see cref="YamlConfigurationProvider"/> for this source.
- /// </summary>
- /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
- /// <returns>A <see cref="YamlConfigurationProvider"/></returns>
- public override IConfigurationProvider Build(IConfigurationBuilder builder)
- {
- EnsureDefaults(builder);
- return new YamlConfigurationProvider(this);
- }
-
- /// <summary>
- /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
- /// </summary>
- public bool NormalizeKeys { get; set; }
- }
-
- /// <summary>
/// A YAML file based <see cref="FileConfigurationProvider"/>.
/// </summary>
public class YamlConfigurationProvider : FileConfigurationProvider
{
/// <summary>
- /// Initializes a new instance with the specified source.
+ /// Initializes a new instance of the <see cref="YamlConfigurationProvider"/> class.
/// </summary>
/// <param name="source">The source settings.</param>
- public YamlConfigurationProvider(YamlConfigurationSource source)
- : base(source)
+ public YamlConfigurationProvider(YamlConfigurationSource source)
+ : base(source)
{
NormalizeKeys = source.NormalizeKeys;
}
private bool NormalizeKeys { get; set; }
- private string[] NullValues { get; } = new[] { "~", "null", "" };
+ private string[] NullValues { get; } = new[] { "~", "null", string.Empty };
/// <summary>
/// Loads the YAML data from a stream.
@@ -157,4 +155,26 @@
}
}
}
-}
+
+ /// <summary>
+ /// Represents a YAML file as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ public class YamlConfigurationSource : FileConfigurationSource
+ {
+ /// <summary>
+ /// Gets or sets a value indicating whether configuration keys should be normalized (_, - removed, changed to lowercase).
+ /// </summary>
+ public bool NormalizeKeys { get; set; }
+
+ /// <summary>
+ /// Builds the <see cref="YamlConfigurationProvider"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="YamlConfigurationProvider"/>.</returns>
+ public override IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ EnsureDefaults(builder);
+ return new YamlConfigurationProvider(this);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Cryptography/PBKDF2.cs b/src/slskd/Common/Cryptography/PBKDF2.cs
deleted file mode 100644
index 4b8b83e4..00000000
--- a/src/slskd/Common/Cryptography/PBKDF2.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-namespace slskd.Security
-{
- using Microsoft.AspNetCore.Cryptography.KeyDerivation;
- using System.Security.Cryptography;
-
- /// <summary>
- /// PBKDF2/RFC 2898 implementation
- /// </summary>
- public static class PBKDF2
- {
- /// <summary>
- /// Gets a 256 bit (32 byte) key derived from the specified <paramref name="password"/> using PBKDF2/RFC 2898
- /// </summary>
- /// <param name="password"></param>
- /// <returns></returns>
- public static byte[] GetKey(string password)
- {
- byte[] salt = new byte[16];
- int iterations = 1000;
-
- using var rng = RandomNumberGenerator.Create();
- rng.GetBytes(salt);
- return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
- }
- }
-}
diff --git a/src/slskd/Common/Cryptography/Pbkdf2.cs b/src/slskd/Common/Cryptography/Pbkdf2.cs
new file mode 100644
index 00000000..f6509a73
--- /dev/null
+++ b/src/slskd/Common/Cryptography/Pbkdf2.cs
@@ -0,0 +1,43 @@
+// <copyright file="Pbkdf2.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Security
+{
+ using System.Security.Cryptography;
+ using Microsoft.AspNetCore.Cryptography.KeyDerivation;
+
+ /// <summary>
+ /// PBKDF2/RFC 2898 utility methods.
+ /// </summary>
+ public static class Pbkdf2
+ {
+ /// <summary>
+ /// Gets a 256 bit (32 byte) key derived from the specified <paramref name="password"/> using PBKDF2/RFC 2898.
+ /// </summary>
+ /// <param name="password">The password from which to derive the key.</param>
+ /// <returns>The derived key.</returns>
+ public static byte[] GetKey(string password)
+ {
+ byte[] salt = new byte[16];
+ int iterations = 1000;
+
+ using var rng = RandomNumberGenerator.Create();
+ rng.GetBytes(salt);
+ return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32);
+ }
+ }
+}
diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs
index 19b1c4ba..95743cc0 100644
--- a/src/slskd/Common/Cryptography/X509.cs
+++ b/src/slskd/Common/Cryptography/X509.cs
@@ -1,11 +1,38 @@
-namespace slskd.Common.Cryptography
+// <copyright file="X509.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Common.Cryptography
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
- public class X509
+ /// <summary>
+ /// X509 utility methods.
+ /// </summary>
+ public static class X509
{
+ /// <summary>
+ /// Generates an X509 certificate for the specified <paramref name="subject"/>.
+ /// </summary>
+ /// <param name="subject">The certificate subject.</param>
+ /// <param name="password">The optional password for the certificate.</param>
+ /// <param name="x509KeyStorageFlags">The optional key storage flags for the certificate.</param>
+ /// <returns>The generated certificate.</returns>
public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet)
{
password ??= Guid.NewGuid().ToString();
@@ -25,6 +52,13 @@
return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags);
}
+ /// <summary>
+ /// Validates an X509 certificate given a PFX <paramref name="fileName"/> and optional <paramref name="password"/>.
+ /// </summary>
+ /// <param name="fileName">The path to the PFX certificate file to validate.</param>
+ /// <param name="password">The optional password for the certificate.</param>
+ /// <param name="result">The error message, if the certificate is invalid.</param>
+ /// <returns>A value indicating whether the certificate is valid.</returns>
public static bool TryValidate(string fileName, string password, out string result)
{
result = null;
@@ -41,4 +75,4 @@
}
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs
new file mode 100644
index 00000000..b7243549
--- /dev/null
+++ b/src/slskd/Common/Extensions.cs
@@ -0,0 +1,119 @@
+// <copyright file="Extensions.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel.DataAnnotations;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using slskd.Validation;
+
+ /// <summary>
+ /// Extensions.
+ /// </summary>
+ public static class Extensions
+ {
+ /// <summary>
+ /// Returns the directory from the given path, regardless of separator format.
+ /// </summary>
+ /// <param name="path">The path.</param>
+ /// <returns>The directory.</returns>
+ public static string DirectoryName(this string path)
+ {
+ var separator = path.Contains('\\') ? '\\' : '/';
+ var parts = path.Split(separator);
+ return string.Join(separator, parts.Take(parts.Length - 1));
+ }
+
+ /// <summary>
+ /// Returns the SHA1 hash of the given string.
+ /// </summary>
+ /// <param name="str">The string to hash.</param>
+ /// <returns>The hash.</returns>
+ public static string Sha1(this string str)
+ {
+ using var sha1 = new SHA1Managed();
+ return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
+ }
+
+ /// <summary>
+ /// Formats byte to nearest size (KB, MB, etc.)
+ /// </summary>
+ /// <param name="value">The value to format.</param>
+ /// <param name="decimalPlaces">The number of decimal places to include.</param>
+ /// <returns>The formatted string.</returns>
+ public static string SizeSuffix(this double value, int decimalPlaces = 1)
+ {
+ string[] sizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
+
+ if (value < 0) { return "-" + SizeSuffix(-value); }
+ if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
+
+ // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
+ int mag = (int)Math.Log(value, 1024);
+
+ // 1L << (mag * 10) == 2 ^ (10 * mag) [i.e. the number of bytes in the unit corresponding to mag]
+ decimal adjustedSize = (decimal)value / (1L << (mag * 10));
+
+ // make adjustment when the value is large enough that it would round up to 1000 or more
+ if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
+ {
+ mag += 1;
+ adjustedSize /= 1024;
+ }
+
+ return string.Format(
+ "{0:n" + decimalPlaces + "} {1}",
+ adjustedSize,
+ sizeSuffixes[mag]);
+ }
+
+ /// <summary>
+ /// Converts the given path to the local format (normalizes path separators).
+ /// </summary>
+ /// <param name="path">The path to convert.</param>
+ /// <returns>The converted path.</returns>
+ public static string ToLocalOSPath(this string path)
+ {
+ return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
+ }
+
+ /// <summary>
+ /// Validates options.
+ /// </summary>
+ /// <param name="options">The options instance to validate.</param>
+ /// <param name="result">The result of the validation, if invalid.</param>
+ /// <returns>A value indicating whether the instance is valid.</returns>
+ public static bool TryValidate(this Options options, out CompositeValidationResult result)
+ {
+ result = null;
+ var results = new List<ValidationResult>();
+
+ if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true))
+ {
+ result = new CompositeValidationResult("Invalid configuration", results);
+ return false;
+ }
+
+ return true;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/ISharedFileCache.cs b/src/slskd/Common/ISharedFileCache.cs
new file mode 100644
index 00000000..53070777
--- /dev/null
+++ b/src/slskd/Common/ISharedFileCache.cs
@@ -0,0 +1,34 @@
+// <copyright file="ISharedFileCache.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Collections.Generic;
+ using Soulseek;
+
+ internal interface ISharedFileCache
+ {
+ string Directory { get; }
+ DateTime? LastFill { get; }
+ long TTL { get; }
+
+ void Fill();
+
+ IEnumerable<Soulseek.File> Search(SearchQuery query);
+ }
+} \ No newline at end of file
diff --git a/src/slskd/SharedFileCache.cs b/src/slskd/Common/SharedFileCache.cs
index ba88b31a..208eab24 100644
--- a/src/slskd/SharedFileCache.cs
+++ b/src/slskd/Common/SharedFileCache.cs
@@ -1,13 +1,30 @@
-namespace slskd
+// <copyright file="SharedFileCache.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
{
- using Microsoft.Data.Sqlite;
- using Soulseek;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
+ using Microsoft.Data.Sqlite;
+ using Soulseek;
/// <summary>
/// Caches shared files.
diff --git a/src/slskd/Extensions.cs b/src/slskd/Extensions.cs
deleted file mode 100644
index 44b0f721..00000000
--- a/src/slskd/Extensions.cs
+++ /dev/null
@@ -1,80 +0,0 @@
-namespace slskd
-{
- using System;
- using System.IO;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
-
- /// <summary>
- /// Extensions.
- /// </summary>
- public static class Extensions
- {
- /// <summary>
- /// Converts the given path to the local format (normalizes path separators).
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static string ToLocalOSPath(this string path)
- {
- return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
- }
-
- /// <summary>
- /// Returns the directory from the given path, regardless of separator format.
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static string DirectoryName(this string path)
- {
- var separator = path.Contains('\\') ? '\\' : '/';
- var parts = path.Split(separator);
- return string.Join(separator, parts.Take(parts.Length - 1));
- }
-
- /// <summary>
- /// Returns the SHA1 hash of the given string.
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string Sha1(this string str)
- {
- using var sha1 = new SHA1Managed();
- return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
- }
-
- /// <summary>
- /// Formats byte to nearest size (KB, MB, etc.)
- /// </summary>
- /// <param name="value"></param>
- /// <param name="decimalPlaces"></param>
- /// <returns></returns>
- public static string SizeSuffix(this double value, int decimalPlaces = 1)
- {
- string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
-
- if (value < 0) { return "-" + SizeSuffix(-value); }
- if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
-
- // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
- int mag = (int)Math.Log(value, 1024);
-
- // 1L << (mag * 10) == 2 ^ (10 * mag)
- // [i.e. the number of bytes in the unit corresponding to mag]
- decimal adjustedSize = (decimal)value / (1L << (mag * 10));
-
- // make adjustment when the value is large enough that
- // it would round up to 1000 or more
- if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
- {
- mag += 1;
- adjustedSize /= 1024;
- }
-
- return string.Format("{0:n" + decimalPlaces + "} {1}",
- adjustedSize,
- SizeSuffixes[mag]);
- }
- }
-}
diff --git a/src/slskd/ISharedFileCache.cs b/src/slskd/ISharedFileCache.cs
deleted file mode 100644
index f3c75f71..00000000
--- a/src/slskd/ISharedFileCache.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace slskd
-{
- using Soulseek;
- using System;
- using System.Collections.Generic;
-
- internal interface ISharedFileCache
- {
- string Directory { get; }
- DateTime? LastFill { get; }
- long TTL { get; }
-
- void Fill();
-
- IEnumerable<Soulseek.File> Search(SearchQuery query);
- }
-} \ No newline at end of file
diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs
index b48853ef..527cfc42 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Options.cs
@@ -1,441 +1,484 @@
-namespace slskd
+// <copyright file="Options.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
{
- using slskd.Validation;
- using Soulseek.Diagnostics;
using System;
- using System.Collections.Generic;
+ using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
+ using slskd.Validation;
+ using Soulseek.Diagnostics;
+ using Utility.CommandLine;
+ using Utility.EnvironmentVariables;
- public record Option(char ShortName, string LongName, string EnvironmentVariable, string Key, Type Type, object Default = null, string Description = null);
-
+ /// <summary>
+ /// Application options.
+ /// </summary>
public class Options
{
- public static Options Defaults { get; } = new Options();
+ /// <summary>
+ /// Gets a value indicating whether to display the application version.
+ /// </summary>
+ [Argument('v', "version")]
+ [Description("display version information")]
+ public bool ShowVersion { get; private set; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether to display a list of command line arguments.
+ /// </summary>
+ [Argument('h', "help")]
+ [Description("display command line usage")]
+ public bool ShowHelp { get; private set; } = false;
+ /// <summary>
+ /// Gets a value indicating whether to display a list of configuration environment variables.
+ /// </summary>
+ [Argument('e', "envars")]
+ [Description("display environment variables")]
+ public bool ShowEnvironmentVariables { get; private set; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether to generate an X509 certificate and password.
+ /// </summary>
+ [Argument('g', "generate-cert")]
+ [Description("generate X509 certificate and password for HTTPs")]
+ public bool GenerateCertificate { get; private set; } = false;
+
+ /// <summary>
+ /// Gets the path to the application configuration file.
+ /// </summary>
+ [Argument('c', "config")]
+ [EnvironmentVariable("CONFIG")]
+ [Description("path to configuration file")]
+ public string ConfigurationFile { get; private set; } = Program.DefaultConfigurationFile;
+
+ /// <summary>
+ /// Gets a value indicating whether the application should run in debug mode.
+ /// </summary>
+ [Argument('d', "debug")]
+ [EnvironmentVariable("DEBUG")]
+ [Description("run in debug mode")]
public bool Debug { get; private set; } = Debugger.IsAttached;
+
+ /// <summary>
+ /// Gets a value indicating whether the logo should be suppressed on startup.
+ /// </summary>
+ [Argument('n', "no-logo")]
+ [EnvironmentVariable("NO_LOGO")]
+ [Description("suppress logo on startup")]
public bool NoLogo { get; private set; } = false;
+
+ /// <summary>
+ /// Gets the unique name for this instance.
+ /// </summary>
+ [Argument('i', "instance-name")]
+ [EnvironmentVariable("INSTANCE_NAME")]
+ [Description("optional; a unique name for this instance")]
public string InstanceName { get; private set; } = "default";
+
+ /// <summary>
+ /// Gets directory options.
+ /// </summary>
[Validate]
- public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
+ public DirectoriesOptions Directories { get; private set; } = new DirectoriesOptions();
+
+ /// <summary>
+ /// Gets options for the web UI.
+ /// </summary>
[Validate]
- public WebOptions Web { get; private set; } = new WebOptions();
+ public WebOptions Web { get; private set; } = new WebOptions();
+
+ /// <summary>
+ /// Gets logger options.
+ /// </summary>
[Validate]
- public LoggerOptions Logger { get; private set; } = new LoggerOptions();
+ public LoggerOptions Logger { get; private set; } = new LoggerOptions();
+
+ /// <summary>
+ /// Gets feature options.
+ /// </summary>
[Validate]
public FeatureOptions Feature { get; private set; } = new FeatureOptions();
+
+ /// <summary>
+ /// Gets options for the Soulseek client.
+ /// </summary>
[Validate]
public SoulseekOptions Soulseek { get; private set; } = new SoulseekOptions();
+ /// <summary>
+ /// Directory options.
+ /// </summary>
public class DirectoriesOptions
{
+ /// <summary>
+ /// Gets the path to shared files.
+ /// </summary>
+ [Argument('s', "shared")]
+ [EnvironmentVariable("SHARED_DIR")]
+ [Description("path to shared files")]
[Required]
- public string Shared { get; private set; }
+ public string Shared { get; private set; } = null;
+
+ /// <summary>
+ /// Gets the path where downloaded files are saved.
+ /// </summary>
+ [Argument('o', "downloads")]
+ [EnvironmentVariable("DOWNLOADS_DIR")]
+ [Description("path where downloaded files are saved")]
[Required]
- public string Downloads { get; private set; }
+ public string Downloads { get; private set; } = null;
}
+ /// <summary>
+ /// Feature options.
+ /// </summary>
public class FeatureOptions
{
+ /// <summary>
+ /// Gets a value indicating whether prometheus metrics should be collected and published.
+ /// </summary>
+ [Argument(default, "prometheus")]
+ [EnvironmentVariable("PROMETHEUS")]
+ [Description("enable collection and publishing of prometheus metrics")]
public bool Prometheus { get; private set; } = false;
+
+ /// <summary>
+ /// Gets a value indicating whether swagger documentation and UI should be enabled.
+ /// </summary>
+ [Argument(default, "swagger")]
+ [EnvironmentVariable("SWAGGER")]
+ [Description("enable swagger documentation and UI")]
public bool Swagger { get; private set; } = false;
}
+ /// <summary>
+ /// Logger options.
+ /// </summary>
public class LoggerOptions
{
+ /// <summary>
+ /// Gets the URL to a Grafana Loki instance to which to log.
+ /// </summary>
+ [Argument(default, "loki")]
+ [EnvironmentVariable("LOKI")]
+ [Description("optional; url to a Grafana Loki instance to which to log")]
public string Loki { get; private set; } = null;
}
+ /// <summary>
+ /// Soulseek client options.
+ /// </summary>
public class SoulseekOptions
{
+ /// <summary>
+ /// Gets the password for the Soulseek network.
+ /// </summary>
+ [Argument(default, "slsk-password")]
+ [EnvironmentVariable("SLSK_PASSWORD")]
+ [Description("password for the Soulseek network")]
[Required]
- public string Password { get; private set; }
+ public string Password { get; private set; } = null;
+
+ /// <summary>
+ /// Gets the username for the Soulseek network.
+ /// </summary>
+ [Argument(default, "slsk-username")]
+ [EnvironmentVariable("SLSK_USERNAME")]
+ [Description("username for the Soulseek network")]
[Required]
- public string Username { get; private set; }
+ public string Username { get; private set; } = null;
+
+ /// <summary>
+ /// Gets the port on which to listen for incoming connections.
+ /// </summary>
+ [Argument(default, "slsk-listen-port")]
+ [EnvironmentVariable("SLSK_LISTEN_PORT")]
+ [Description("port on which to listen for incoming connections")]
[Range(1024, 65535)]
- public int? ListenPort { get; private set; } = 50000;
+ public int ListenPort { get; private set; } = 50000;
+
+ /// <summary>
+ /// Gets the minimum diagnostic level.
+ /// </summary>
+ [Argument(default, "slsk-diag-level")]
+ [EnvironmentVariable("SLSK_DIAG_LEVEL")]
+ [Description("minimum diagnostic level (None, Warning, Info, Debug)")]
public DiagnosticLevel DiagnosticLevel { get; private set; } = DiagnosticLevel.Info;
+
+ /// <summary>
+ /// Gets options for the distributed network.
+ /// </summary>
[Validate]
public DistributedNetworkOptions DistributedNetwork { get; private set; } = new DistributedNetworkOptions();
+
+ /// <summary>
+ /// Gets connection options.
+ /// </summary>
[Validate]
public ConnectionOptions Connection { get; private set; } = new ConnectionOptions();
+ /// <summary>
+ /// Connection options.
+ /// </summary>
public class ConnectionOptions
{
+ /// <summary>
+ /// Gets connection timeout options.
+ /// </summary>
[Validate]
public TimeoutOptions Timeout { get; private set; } = new TimeoutOptions();
+
+ /// <summary>
+ /// Gets connection buffer options.
+ /// </summary>
[Validate]
public BufferOptions Buffer { get; private set; } = new BufferOptions();
+ /// <summary>
+ /// Connection buffer options.
+ /// </summary>
public class BufferOptions
{
+ /// <summary>
+ /// Gets the connection read buffer size.
+ /// </summary>
+ [Argument(default, "slsk-read-buffer")]
+ [EnvironmentVariable("SLSK_READ_BUFFER")]
+ [Description("read buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Read { get; private set; } = 16384;
+
+ /// <summary>
+ /// Gets the connection write buffer size.
+ /// </summary>
+ [Argument(default, "slsk-write-buffer")]
+ [EnvironmentVariable("SLSK_WRITE_BUFFER")]
+ [Description("write buffer size for connections")]
[Range(1024, int.MaxValue)]
public int Write { get; private set; } = 16384;
}
+ /// <summary>
+ /// Connection timeout options.
+ /// </summary>
public class TimeoutOptions
{
+ /// <summary>
+ /// Gets the connection timeout value, in milliseconds.
+ /// </summary>
+ [Argument(default, "slsk-connection-timeout")]
+ [EnvironmentVariable("SLSK_CONNECTION_TIMEOUT")]
+ [Description("connection timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Connect { get; private set; } = 5000;
+
+ /// <summary>
+ /// Gets the connection inactivity timeout, in milliseconds.
+ /// </summary>
+ [Argument(default, "slsk-inactivity-timeout")]
+ [EnvironmentVariable("SLSK_INACTIVITY_TIMEOUT")]
+ [Description("connection inactivity timeout, in milliseconds")]
[Range(1000, int.MaxValue)]
public int Inactivity { get; private set; } = 15000;
}
}
+ /// <summary>
+ /// Distributed network options.
+ /// </summary>
public class DistributedNetworkOptions
{
+ /// <summary>
+ /// Gets a value indicating whether the distributed network should be disabled.
+ /// </summary>
+ [Argument(default, "slsk-no-dnet")]
+ [EnvironmentVariable("SLSK_NO_DNET")]
+ [Description("disable the distributed network")]
public bool Disabled { get; private set; } = false;
+
+ /// <summary>
+ /// Gets the distributed child connection limit.
+ /// </summary>
+ [Argument(default, "slsk-dnet-children")]
+ [EnvironmentVariable("SLSK_DNET_CHILDREN")]
+ [Description("max number of distributed children")]
[Range(1, int.MaxValue)]
public int ChildLimit { get; private set; } = 25;
}
}
+ /// <summary>
+ /// Web server options.
+ /// </summary>
public class WebOptions
{
+ /// <summary>
+ /// Gets the HTTP listen port.
+ /// </summary>
+ [Argument('l', "http-port")]
+ [EnvironmentVariable("HTTP_PORT")]
+ [Description("HTTP listen port for web UI")]
[Range(1, 65535)]
public int Port { get; private set; } = 5000;
+
+ /// <summary>
+ /// Gets HTTPS options.
+ /// </summary>
[Validate]
public HttpsOptions Https { get; private set; } = new HttpsOptions();
+
+ /// <summary>
+ /// Gets the base url for web requests.
+ /// </summary>
+ [Argument(default, "url-base")]
+ [EnvironmentVariable("URL_BASE")]
+ [Description("base url for web requests")]
public string UrlBase { get; private set; } = "/";
- [Required(ErrorMessage = "A content root is required")]
+
+ /// <summary>
+ /// Gets the path to static web content.
+ /// </summary>
+ [Argument(default, "content-path")]
+ [EnvironmentVariable("CONTENT_PATH")]
+ [Description("path to static web content")]
+ [Required]
public string ContentPath { get; private set; } = "wwwroot";
+
+ /// <summary>
+ /// Gets authentication options.
+ /// </summary>
[Validate]
public AuthenticationOptions Authentication { get; private set; } = new AuthenticationOptions();
+ /// <summary>
+ /// Authentication options.
+ /// </summary>
public class AuthenticationOptions
{
+ /// <summary>
+ /// Gets a value indicating whether authentication should be disabled.
+ /// </summary>
+ [Argument('x', "no-auth")]
+ [EnvironmentVariable("NO_AUTH")]
+ [Description("disable authentication for web requests")]
public bool Disable { get; private set; } = false;
+
+ /// <summary>
+ /// Gets the username for the web UI.
+ /// </summary>
+ [Argument('u', "username")]
+ [EnvironmentVariable("USERNAME")]
+ [Description("username for web UI")]
[Required]
- public string Username { get; private set; } = "slskd";
+ public string Username { get; private set; } = Program.AppName;
+
+ /// <summary>
+ /// Gets the password for the web UI.
+ /// </summary>
+ [Argument('p', "password")]
+ [EnvironmentVariable("PASSWORD")]
+ [Description("password for web UI")]
[Required]
- public string Password { get; private set; } = "slskd";
+ public string Password { get; private set; } = Program.AppName;
+
+ /// <summary>
+ /// Gets JWT options.
+ /// </summary>
[Validate]
public JwtOptions Jwt { get; private set; } = new JwtOptions();
+ /// <summary>
+ /// JWT options.
+ /// </summary>
public class JwtOptions
{
+ /// <summary>
+ /// Gets the key with which to sign JWTs.
+ /// </summary>
+ [Argument(default, "jwt-key")]
+ [EnvironmentVariable("JWT_KEY")]
+ [Description("JWT signing key")]
[Required]
public string Key { get; private set; } = Guid.NewGuid().ToString();
+
+ /// <summary>
+ /// Gets the TTL for JWTs.
+ /// </summary>
+ [Argument(default, "jwt-ttl")]
+ [EnvironmentVariable("JWT_TTL")]
+ [Description("TTL for JWTs")]
[Range(3600, int.MaxValue)]
public int Ttl { get; private set; } = 604800000;
}
}
+ /// <summary>
+ /// HTTPS options.
+ /// </summary>
public class HttpsOptions
{
+ /// <summary>
+ /// Gets the HTTPS listen port.
+ /// </summary>
+ [Argument('L', "https-port")]
+ [EnvironmentVariable("HTTPS_PORT")]
+ [Description("HTTPS listen port for web UI")]
[Range(1, 65535)]
public int Port { get; private set; } = 5001;
+
+ /// <summary>
+ /// Gets a value indicating whether HTTP requests should be redirected to HTTPS.
+ /// </summary>
+ [Argument('f', "force-https")]
+ [EnvironmentVariable("HTTPS_FORCE")]
+ [Description("redirect HTTP to HTTPS")]
public bool Force { get; private set; } = false;
+
+ /// <summary>
+ /// Gets certificate options.
+ /// </summary>
[Validate]
public CertificateOptions Certificate { get; private set; } = new CertificateOptions();
+ /// <summary>
+ /// Certificate options.
+ /// </summary>
public class CertificateOptions
{
+ /// <summary>
+ /// Gets the path to the the X509 certificate .pfx file.
+ /// </summary>
+ [Argument(default, "https-cert-pfx")]
+ [EnvironmentVariable("HTTPS_CERT_PFX")]
+ [Description("path to X509 certificate .pfx")]
[FileExists]
public string Pfx { get; private set; }
+
+ /// <summary>
+ /// Gets the password for the X509 certificate.
+ /// </summary>
+ [Argument(default, "https-cert-password")]
+ [EnvironmentVariable("HTTPS_CERT_PASSWORD")]
+ [Description("X509 certificate password")]
public string Password { get; private set; }
}
}
}
-
- public bool TryValidate(out CompositeValidationResult result)
- {
- result = null;
- var results = new List<ValidationResult>();
-
- if (!Validator.TryValidateObject(this, new ValidationContext(this), results, true))
- {
- result = new CompositeValidationResult("Invalid configuration", results);
- return false;
- }
-
- return true;
- }
-
- 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: 'g',
- LongName: "generate-cert",
- EnvironmentVariable: null,
- Key: null,
- Type: typeof(bool),
- Default: false,
- Description: "generate X509 certificate and password for HTTPs"),
- new(
- ShortName: 'c',
- LongName: "config",
- EnvironmentVariable: "CONFIG",
- Key: null,
- Type: typeof(string),
- Default: Program.DefaultConfigurationFile,
- Description: "path to configuration file"),
- new(
- ShortName: 'd',
- LongName: "debug",
- EnvironmentVariable: "DEBUG",
- Key: "slskd:debug",
- Type: typeof(bool),
- Default: Defaults.Debug,
- Description: "run in debug mode"),
- new(
- ShortName: 'n',
- LongName: "no-logo",
- EnvironmentVariable: "NO_LOGO",
- Key: "slskd:nologo",
- Type: typeof(bool),
- Default: Defaults.NoLogo,
- Description: "suppress logo on startup"),
- new(
- ShortName: 'i',
- LongName: "instance-name",
- EnvironmentVariable: "INSTANCE_NAME",
- Key: "slskd:instancename",
- Type: typeof(string),
- Default: Defaults.InstanceName,
- Description: "optional; a unique name for this instance"),
- new(
- ShortName: 'o',
- LongName: "downloads",
- EnvironmentVariable: "DOWNLOADS_DIR",
- Key: "slskd:directories:downloads",
- Type: typeof(string),
- Default: Defaults.Directories.Downloads,
- Description: "path where downloaded files are saved"),
- new(
- ShortName: 's',
- LongName: "shared",
- EnvironmentVariable: "SHARED_DIR",
- Key: "slskd:directories:shared",
- Type: typeof(string),
- Default: Defaults.Directories.Shared,
- Description: "path to shared files"),
- new(
- ShortName: 'l',
- LongName: "http-port",
- EnvironmentVariable: "HTTP_PORT",
- Key: "slskd:web:port",
- Type: typeof(int),
- Default: Defaults.Web.Port,
- 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: Defaults.Web.Https.Port,
- 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: Defaults.Web.Https.Force,
- Description: "redirect HTTP to HTTPS"),
- new(
- ShortName: default,
- LongName: "https-cert-pfx",
- EnvironmentVariable: "HTTPS_CERT_PFX",
- Key: "slskd:web:https:certificate:pfx",
- Type: typeof(string),
- Default: Defaults.Web.Https.Certificate.Pfx,
- Description: "path to X509 certificate .pfx"),
- new(
- ShortName: default,
- LongName: "https-cert-password",
- EnvironmentVariable: "HTTPS_CERT_PASSWORD",
- Key: "slskd:web:https:certificate:password",
- Type: typeof(string),
- Default: Defaults.Web.Https.Certificate.Password,
- Description: "X509 certificate password"),
- new(
- ShortName: default,
- LongName: "url-base",
- EnvironmentVariable: "URL_BASE",
- Key: "slskd:web:urlbase",
- Type: typeof(string),
- Default: Defaults.Web.UrlBase,
- Description: "base url for web requests"),
- new(
- ShortName: default,
- LongName: "content-path",
- EnvironmentVariable: "CONTENT_PATH",
- Key: "slskd:web:contentpath",
- Type: typeof(string),
- Default: Defaults.Web.ContentPath,
- Description: "path to static web content"),
- new(
- ShortName: 'x',
- LongName: "no-auth",
- EnvironmentVariable: "NO_AUTH",
- Key: "slskd:web:authentication:disable",
- Type: typeof(bool),
- Default: Defaults.Web.Authentication.Disable,
- Description: "disable authentication for web requests"),
- new(
- ShortName: 'u',
- LongName: "username",
- EnvironmentVariable: "USERNAME",
- Key: "slskd:web:authentication:username",
- Type: typeof(string),
- Default: Defaults.Web.Authentication.Username,
- Description: "the username for web UI"),
- new(
- ShortName: 'p',
- LongName: "password",
- EnvironmentVariable: "PASSWORD",
- Key: "slskd:web:authentication:password",
- Type: typeof(string),
- Default: Defaults.Web.Authentication.Password,
- Description: "the password for web UI"),
- new(
- ShortName: default,
- LongName: "jwt-key",
- EnvironmentVariable: "JWT_KEY",
- Key: "slskd:web:authentication:jwt:key",
- Type: typeof(string),
- Default: Defaults.Web.Authentication.Jwt.Key,
- Description: "JWT signing key"),
- new(
- ShortName: default,
- LongName: "jwt-ttl",
- EnvironmentVariable: "JWT_TTL",
- Key: "slskd:web:authentication:jwt:ttl",
- Type: typeof(int),
- Default: Defaults.Web.Authentication.Jwt.Ttl,
- Description: "TTL for JWTs"),
- new(
- ShortName: default,
- LongName: "prometheus",
- EnvironmentVariable: "PROMETHEUS",
- Key: "slskd:feature:prometheus",
- Type: typeof(bool),
- Default: Defaults.Feature.Prometheus,
- Description: "enable collection and publishing of prometheus metrics"),
- new(
- ShortName: default,
- LongName: "swagger",
- EnvironmentVariable: "SWAGGER",
- Key: "slskd:feature:swagger",
- Type: typeof(bool),
- Default: Defaults.Feature.Swagger,
- Description: "enable swagger documentation and UI"),
- new(
- ShortName: default,
- LongName: "loki",
- EnvironmentVariable: "LOKI",
- Key: "slskd:logger:loki",
- Type: typeof(string),
- Default: Defaults.Logger.Loki,
- Description: "optional; url to a Grafana Loki instance to which to log"),
- new(
- ShortName: default,
- LongName: "slsk-username",
- EnvironmentVariable: "SLSK_USERNAME",
- Key: "slskd:soulseek:username",
- Type: typeof(string),
- Default: Defaults.Soulseek.Username,
- Description: "username for the Soulseek network"),
- new(
- ShortName: default,
- LongName: "slsk-password",
- EnvironmentVariable: "SLSK_PASSWORD",
- Key: "slskd:soulseek:password",
- Type: typeof(string),
- Default: Defaults.Soulseek.Password,
- Description: "password for the Soulseek network"),
- new(
- ShortName: default,
- LongName: "slsk-listen-port",
- EnvironmentVariable: "SLSK_LISTEN_PORT",
- Key: "slskd:soulseek:listenport",
- Type: typeof(int),
- Default: Defaults.Soulseek.ListenPort,
- Description: "port on which to listen for incoming connections"),
- new(
- ShortName: default,
- LongName: "slsk-diag-level",
- EnvironmentVariable: "SLSK_DIAG_LEVEL",
- Key: "slskd:soulseek:diagnosticlevel",
- Type: typeof(DiagnosticLevel),
- Default: Defaults.Soulseek.DiagnosticLevel,
- Description: "minimum diagnostic level (None, Warning, Info, Debug)"),
- new(
- ShortName: default,
- LongName: "slsk-no-dnet",
- EnvironmentVariable: "SLSK_NO_DNET",
- Key: "slskd:soulseek:distributednetwork:disabled",
- Type: typeof(bool),
- Default: Defaults.Soulseek.DistributedNetwork.Disabled,
- Description: "disable the distributed network"),
- new(
- ShortName: default,
- LongName: "slsk-dnet-children",
- EnvironmentVariable: "SLSK_DNET_CHILDREN",
- Key: "slskd:soulseek:distributednetwork:childlimit",
- Type: typeof(int),
- Default: Defaults.Soulseek.DistributedNetwork.ChildLimit,
- Description: "max number of distributed children"),
- new(
- ShortName: default,
- LongName: "slsk-connection-timeout",
- EnvironmentVariable: "SLSK_CONNECTION_TIMEOUT",
- Key: "slskd:soulseek:connection:timeout:connect",
- Type: typeof(int),
- Default: Defaults.Soulseek.Connection.Timeout.Connect,
- Description: "connection timeout, in miliseconds"),
- new(
- ShortName: default,
- LongName: "slsk-inactivity-timeout",
- EnvironmentVariable: "SLSK_INACTIVITY_TIMEOUT",
- Key: "slskd:soulseek:connection:timeout:inactivity",
- Type: typeof(int),
- Default: Defaults.Soulseek.Connection.Timeout.Inactivity,
- Description: "connection inactivity timeout, in miliseconds"),
- new(
- ShortName: default,
- LongName: "slsk-read-buffer",
- EnvironmentVariable: "SLSK_READ_BUFFER",
- Key: "slskd:soulseek:connection:buffer:read",
- Type: typeof(int),
- Default: Defaults.Soulseek.Connection.Buffer.Read,
- Description: "read buffer size for connections"),
- new(
- ShortName: default,
- LongName: "slsk-write-buffer",
- EnvironmentVariable: "SLSK_WRITE_BUFFER",
- Key: "slskd:soulseek:connection:buffer:write",
- Type: typeof(int),
- Default: Defaults.Soulseek.Connection.Buffer.Write,
- Description: "write buffer size for connections"),
- };
}
} \ No newline at end of file
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 7c6736a3..750ed8f2 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -1,5 +1,30 @@
-namespace slskd
+// <copyright file="Program.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel;
+ using System.IO;
+ using System.Linq;
+ using System.Net;
+ using System.Reflection;
+ using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
@@ -12,75 +37,92 @@
using slskd.Common.Cryptography;
using slskd.Configuration;
using slskd.Validation;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Reflection;
- using System.Security.Cryptography.X509Certificates;
+ using Utility.CommandLine;
+ using Utility.EnvironmentVariables;
- public static class ProgramExtensions
- {
- public static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile)
- {
- configurationFile = Path.GetFullPath(configurationFile);
-
- return builder
- .AddDefaultValues(
- map: Options.Map.Select(o => o.ToDefaultValue()))
- .AddEnvironmentVariables(
- prefix: environmentVariablePrefix,
- map: Options.Map.Select(o => o.ToEnvironmentVariable()))
- .AddYamlFile(
- path: Path.GetFileName(configurationFile),
- optional: true,
- reloadOnChange: false,
- provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None))
- .AddCommandLine(
- commandLine: Environment.CommandLine,
- map: Options.Map.Select(o => o.ToCommandLineArgument()));
- }
- }
-
- public class Program
+ /// <summary>
+ /// Bootstraps configuration and handles primitive command-line instructions.
+ /// </summary>
+ public static class Program
{
+ /// <summary>
+ /// The name of the application.
+ /// </summary>
public static readonly string AppName = "slskd";
+
+ /// <summary>
+ /// The default configuration filename.
+ /// </summary>
public static readonly string DefaultConfigurationFile = $"{AppName}.yml";
+
+ /// <summary>
+ /// The global prefix for environment variables.
+ /// </summary>
public static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_";
-
- public static Guid InvocationId { get; } = Guid.NewGuid();
- public static int ProcessId { get; } = Environment.ProcessId;
+
+ /// <summary>
+ /// Gets the assembly version of the application.
+ /// </summary>
+ /// <remarks>
+ /// Inaccurate when running locally.
+ /// </remarks>
public static Version AssemblyVersion { get; } = Assembly.GetExecutingAssembly().GetName().Version;
+
+ /// <summary>
+ /// Gets the informational version of the application, including the git sha at the latest commit.
+ /// </summary>
+ /// <remarks>
+ /// Inaccurate when running locally.
+ /// </remarks>
public static string InformationalVersion { get; } = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
+
+ /// <summary>
+ /// Gets the unique Id of this application invocation.
+ /// </summary>
+ public static Guid InvocationId { get; } = Guid.NewGuid();
+
+ /// <summary>
+ /// Gets the Id of the current application process.
+ /// </summary>
+ public static int ProcessId { get; } = Environment.ProcessId;
+
+ /// <summary>
+ /// Gets the full application version, including both assembly and informational versions.
+ /// </summary>
public static string Version { get; } = $"{AssemblyVersion} ({InformationalVersion})";
- [CommandLineArgument('n', "no-logo", "suppress logo on startup")]
+ private static IConfigurationRoot Configuration { get; set; }
+ private static Options Options { get; } = new Options();
+
+ [EnvironmentVariable("CONFIG")]
+ [Argument('c', "config", "path to configuration file")]
+ private static string ConfigurationFile { get; set; } = DefaultConfigurationFile;
+
+ [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
+ private static bool GenerateCertificate { get; set; }
+
+ [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")]
- private static bool GenerateCertificate { get; set; }
-
- [EnvironmentVariable("CONFIG")]
- [CommandLineArgument('c', "config", "path to configuration file")]
- private static string ConfigurationFile { get; set; } = DefaultConfigurationFile;
-
- private static Options Options { get; } = new Options();
- private static IConfigurationRoot Configuration { get; set; }
-
+ /// <summary>
+ /// Entrypoint.
+ /// </summary>
+ /// <param name="args">Command line arguments.</param>
public static void Main(string[] args)
{
+ // populate the properties above so that we can override the default config file if needed, and to
+ // check if the application is being run in command mode (run task and quit).
EnvironmentVariables.Populate(prefix: EnvironmentVariablePrefix);
- CommandLineArguments.Populate(clearExistingValues: false);
+ Arguments.Populate(clearExistingValues: false);
if (ShowVersion)
{
@@ -90,9 +132,21 @@
if (ShowHelp || ShowEnvironmentVariables)
{
- if (!NoLogo) PrintLogo(Version);
- if (ShowHelp) PrintCommandLineArguments(Options.Map);
- if (ShowEnvironmentVariables) PrintEnvironmentVariables(Options.Map, EnvironmentVariablePrefix);
+ if (!NoLogo)
+ {
+ PrintLogo(Version);
+ }
+
+ if (ShowHelp)
+ {
+ PrintCommandLineArguments(typeof(Options));
+ }
+
+ if (ShowEnvironmentVariables)
+ {
+ PrintEnvironmentVariables(typeof(Options), EnvironmentVariablePrefix);
+ }
+
return;
}
@@ -102,13 +156,15 @@
return;
}
+ // the application isn't bein run in command mode. load all configuration values and proceed
+ // with bootstrapping.
try
{
Configuration = new ConfigurationBuilder()
.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile)
.Build();
- Configuration.GetSection("slskd")
+ Configuration.GetSection(AppName)
.Bind(Options, (o) => { o.BindNonPublicProperties = true; });
if (!Options.TryValidate(out var result))
@@ -127,7 +183,7 @@
}
catch (Exception ex)
{
- Console.WriteLine($"Invalid configuration: {(Options.Debug ? ex : ex.Message)}");
+ Console.WriteLine($"Invalid configuration: {(!Options.Debug ? ex : ex.Message)}");
return;
}
@@ -153,7 +209,7 @@
outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.Async(config =>
config.File(
- "logs/slskd-.log",
+ $"logs/{AppName}-.log",
outputTemplate: "[{SourceContext}] [{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day))
.WriteTo.Conditional(
@@ -178,7 +234,7 @@
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.Async(config =>
config.File(
- "logs/slskd-.log",
+ $"logs/{AppName}-.log",
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day))
.WriteTo.Conditional(
@@ -189,7 +245,7 @@
.CreateLogger();
}
- var logger = Log.ForContext<Program>();
+ var logger = Log.ForContext(typeof(Program));
if (ConfigurationFile != DefaultConfigurationFile && !File.Exists(ConfigurationFile))
{
@@ -258,7 +314,27 @@
}
}
- public static void GenerateX509Certificate(string password, string filename)
+ private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile)
+ {
+ configurationFile = Path.GetFullPath(configurationFile);
+
+ return builder
+ .AddDefaultValues(
+ targetType: typeof(Options))
+ .AddEnvironmentVariables(
+ targetType: typeof(Options),
+ prefix: environmentVariablePrefix)
+ .AddYamlFile(
+ path: Path.GetFileName(configurationFile),
+ optional: true,
+ reloadOnChange: false,
+ provider: new PhysicalFileProvider(Path.GetDirectoryName(configurationFile), ExclusionFilters.None)) // required for locations outside of the app directory
+ .AddCommandLine(
+ targetType: typeof(Options),
+ commandLine: Environment.CommandLine);
+ }
+
+ private static void GenerateX509Certificate(string password, string filename)
{
Console.WriteLine("Generating X509 certificate...");
filename = Path.Combine(AppContext.BaseDirectory, filename);
@@ -270,51 +346,96 @@
Console.WriteLine($"Certificate exported to {filename}");
}
- public static void PrintCommandLineArguments(IEnumerable<Option> map)
+ private static void PrintCommandLineArguments(Type targetType)
{
static string GetLongName(string longName, Type type)
=> type == typeof(bool) ? longName : $"{longName} <{type.Name.ToLowerInvariant()}>";
- var longestName = map.Where(a => !string.IsNullOrEmpty(a.LongName)).Select(a => GetLongName(a.LongName, a.Type)).Max(n => n.Length);
+ var lines = new List<(string Item, string Description)>();
- Console.WriteLine("\nusage: slskd [arguments]\n");
- Console.WriteLine("arguments:\n");
-
- foreach (Option item in map)
+ void Map(Type type)
{
- var (shortName, longName, _, key, type, defaultValue, description) = item;
+ var defaults = Activator.CreateInstance(type);
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (shortName == default && string.IsNullOrEmpty(longName))
+ foreach (PropertyInfo property in props)
{
- continue;
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(ArgumentAttribute));
+ var descriptionAttribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(DescriptionAttribute));
+
+ if (attribute != default)
+ {
+ var shortName = (char)attribute.ConstructorArguments[0].Value;
+ var longName = (string)attribute.ConstructorArguments[1].Value;
+ var description = descriptionAttribute?.ConstructorArguments[0].Value;
+
+ var suffix = property.PropertyType == typeof(bool) ? string.Empty : $" (default: {property.GetValue(defaults) ?? "<null>"})";
+ var item = $"{shortName}{(shortName == default ? " " : "|")}--{GetLongName(longName, property.PropertyType)}";
+ var desc = $"{description}{suffix}";
+ lines.Add(new(item, desc));
+ }
+ else
+ {
+ Map(property.PropertyType);
+ }
}
+ }
+
+ Map(targetType);
+
+ var longestItem = lines.Max(l => l.Item.Length);
+
+ Console.WriteLine("\nusage: slskd [arguments]\n");
+ Console.WriteLine("arguments:\n");
- 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);
+ foreach (var line in lines)
+ {
+ Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}");
}
}
- public static void PrintEnvironmentVariables(IEnumerable<Option> map, string prefix)
+ private static void PrintEnvironmentVariables(Type targetType, string prefix)
{
static string GetName(string name, Type type) => $"{name} <{type.Name.ToLowerInvariant()}>";
- var longestName = map.Select(a => GetName(a.EnvironmentVariable, a.Type)).Max(n => n.Length);
-
- Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n");
+ var lines = new List<(string Item, string Description)>();
- foreach (Option item in map)
+ void Map(Type type)
{
- var (_, _, environmentVariable, key, type, defaultValue, description) = item;
+ var defaults = Activator.CreateInstance(type);
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- if (string.IsNullOrEmpty(environmentVariable))
+ foreach (PropertyInfo property in props)
{
- continue;
+ var attribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(EnvironmentVariableAttribute));
+ var descriptionAttribute = property.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(DescriptionAttribute));
+
+ if (attribute != default)
+ {
+ var name = (string)attribute.ConstructorArguments[0].Value;
+ var description = descriptionAttribute?.ConstructorArguments[0].Value;
+
+ var suffix = type == typeof(bool) ? string.Empty : $" (default: {property.GetValue(defaults) ?? "<null>"})";
+ var item = $"{prefix}{GetName(name, property.PropertyType)}";
+ var desc = $"{description}{suffix}";
+ lines.Add(new(item, desc));
+ }
+ else
+ {
+ Map(property.PropertyType);
+ }
}
+ }
+
+ Map(targetType);
+
+ var longestItem = lines.Max(l => l.Item.Length);
- var suffix = type == typeof(bool) ? string.Empty : $" (default: {defaultValue ?? "<null>"})";
- var result = $" {prefix}{GetName(environmentVariable, type).PadRight(longestName + 3)}{description}{suffix}";
- Console.WriteLine(result);
+ Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n");
+
+ foreach (var line in lines)
+ {
+ Console.WriteLine($" {line.Item.PadRight(longestItem)} {line.Description}");
}
}
diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset
new file mode 100644
index 00000000..6605f525
--- /dev/null
+++ b/src/slskd/Properties/analysis.ruleset
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RuleSet Name="Soulseek.NET Ruleset" Description="Global code analysis rules for Soulseek.NET projects up for consumption" ToolsVersion="16.0">
+ <Include Path="allrules.ruleset" Action="Hidden" />
+ <Rules AnalyzerId="Microsoft.CodeQuality.Analyzers" RuleNamespace="Microsoft.CodeQuality.Analyzers">
+ <Rule Id="CA1016" Action="Warning" />
+ <Rule Id="CA1028" Action="None" />
+ <Rule Id="CA1031" Action="None" />
+ <Rule Id="CA1033" Action="Warning" />
+ <Rule Id="CA1060" Action="Warning" />
+ <Rule Id="CA1061" Action="Warning" />
+ <Rule Id="CA1063" Action="Warning" />
+ <Rule Id="CA1065" Action="Warning" />
+ <Rule Id="CA1303" Action="None" />
+ <Rule Id="CA1711" Action="None" />
+ <Rule Id="CA1714" Action="Warning" />
+ <Rule Id="CA1717" Action="Warning" />
+ <Rule Id="CA1725" Action="Warning" />
+ <Rule Id="CA1805" Action="None" />
+ <Rule Id="CA1819" Action="None" />
+ <Rule Id="CA1822" Action="None" />
+ <Rule Id="CA2007" Action="Warning" />
+ <Rule Id="CA2200" Action="Warning" />
+ <Rule Id="CA2214" Action="Warning" />
+ <Rule Id="CA2231" Action="Warning" />
+ </Rules>
+ <Rules AnalyzerId="Microsoft.CodeQuality.CSharp.Analyzers" RuleNamespace="Microsoft.CodeQuality.CSharp.Analyzers">
+ <Rule Id="CA1001" Action="Warning" />
+ <Rule Id="CA1821" Action="Warning" />
+ </Rules>
+ <Rules AnalyzerId="Microsoft.NetCore.Analyzers" RuleNamespace="Microsoft.NetCore.Analyzers">
+ <Rule Id="CA2008" Action="None" />
+ </Rules>
+ <Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp">
+ <Rule Id="S2589" Action="None" />
+ <Rule Id="S3427" Action="Info" />
+ </Rules>
+ <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
+ <Rule Id="SA1008" Action="None" />
+ <Rule Id="SA1009" Action="None" />
+ <Rule Id="SA1101" Action="None" />
+ <Rule Id="SA1124" Action="None" />
+ <Rule Id="SA1300" Action="None" />
+ <Rule Id="SA1402" Action="None" />
+ <Rule Id="SA1516" Action="None" />
+ <Rule Id="SA1600" Action="Info" />
+ <Rule Id="SA1649" Action="None" />
+ </Rules>
+</RuleSet> \ No newline at end of file
diff --git a/src/slskd/Properties/launchSettings.json b/src/slskd/Properties/launchSettings.json
index f5409d71..b151b2f4 100644
--- a/src/slskd/Properties/launchSettings.json
+++ b/src/slskd/Properties/launchSettings.json
@@ -1,12 +1,4 @@
{
- "iisSettings": {
- "windowsAuthentication": false,
- "anonymousAuthentication": true,
- "iisExpress": {
- "applicationUrl": "http://localhost:57117/",
- "sslPort": 44332
- }
- },
"profiles": {
"slskd": {
"commandName": "Project",
diff --git a/src/slskd/slskd.yml b/src/slskd/Properties/slskd.yml
index d5519b65..d5519b65 100644
--- a/src/slskd/slskd.yml
+++ b/src/slskd/Properties/slskd.yml
diff --git a/src/slskd/Properties/stylecop.json b/src/slskd/Properties/stylecop.json
new file mode 100644
index 00000000..7d848f1a
--- /dev/null
+++ b/src/slskd/Properties/stylecop.json
@@ -0,0 +1,27 @@
+{
+ "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
+ "settings": {
+ "orderingRules": {
+ "systemUsingDirectivesFirst": true,
+ "usingDirectivesPlacement": "insideNamespace"
+ },
+ "maintainabilityRules": {
+ "topLevelTypes": [
+ "class",
+ "delegate",
+ "enum",
+ "interface"
+ ]
+ },
+ "documentationRules": {
+ "documentPrivateElements": false,
+ "documentPrivateFields": false,
+ "companyName": "slskd Team",
+ "copyrightText": " Copyright (c) {companyName}. All rights reserved.\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see https://www.gnu.org/licenses/.",
+ "variables": {
+ "licenseName": "AGPLv3",
+ "licenseFile": "LICENSE"
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Security/PassthroughAuthentication.cs b/src/slskd/Security/PassthroughAuthentication.cs
deleted file mode 100644
index 69b94df5..00000000
--- a/src/slskd/Security/PassthroughAuthentication.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-namespace slskd.Security
-{
- using Microsoft.AspNetCore.Authentication;
- using Microsoft.Extensions.Logging;
- using Microsoft.Extensions.Options;
- using System.Security.Principal;
- using System.Text.Encodings.Web;
- using System.Threading.Tasks;
-
- public class PassthroughAuthentication
- {
- public static string AuthenticationScheme { get; } = "Passthrough";
- }
-
- public class PassthroughAuthenticationHandler : AuthenticationHandler<PassthroughAuthenticationOptions>
- {
- public PassthroughAuthenticationHandler(IOptionsMonitor<PassthroughAuthenticationOptions> optionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock)
- : base(optionsMonitor, logger, urlEncoder, systemClock)
- {
- }
-
- protected override Task<AuthenticateResult> HandleAuthenticateAsync()
- {
- var identity = new GenericIdentity(Options.Username);
- var principal = new GenericPrincipal(identity, new[] { "User" });
- var ticket = new AuthenticationTicket(principal , new AuthenticationProperties(), PassthroughAuthentication.AuthenticationScheme);
-
- return Task.FromResult(AuthenticateResult.Success(ticket));
- }
- }
-
- public class PassthroughAuthenticationOptions : AuthenticationSchemeOptions
- {
- public PassthroughAuthenticationOptions()
- {
- }
-
- public string Username { get; set; }
- }
-}
diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs
index f093fa67..7c71a7ec 100644
--- a/src/slskd/Startup.cs
+++ b/src/slskd/Startup.cs
@@ -1,54 +1,71 @@
-namespace slskd
+// <copyright file="Startup.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
{
using System;
+ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
- using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
- using Microsoft.OpenApi.Models;
- using Soulseek;
- using Soulseek.Diagnostics;
- using slskd.Trackers;
- using System.Collections.Concurrent;
+ using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
- using slskd.Security;
- using Microsoft.AspNetCore.Authentication.JwtBearer;
+ using Microsoft.OpenApi.Models;
+ using Prometheus;
using Prometheus.SystemMetrics;
using Serilog;
- using Prometheus;
- using Microsoft.Extensions.FileProviders;
using Serilog.Events;
+ using slskd.API.Authentication;
using slskd.Entities;
- using slskd.Configuration;
+ using slskd.Security;
+ using slskd.Trackers;
+ using Soulseek;
+ using Soulseek.Diagnostics;
+ /// <summary>
+ /// ASP.NET Startup.
+ /// </summary>
public class Startup
{
- private readonly int MaxReconnectAttempts = 3;
- private int CurrentReconnectAttempts = 0;
- private static readonly string XmlDocFile = Path.Combine(AppContext.BaseDirectory, typeof(Startup).GetTypeInfo().Assembly.GetName().Name + ".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 string XmlDocFile = Path.Combine(AppContext.BaseDirectory, Program.AppName + ".xml");
+ private static readonly int MaxReconnectAttempts = 3;
+ private static int currentReconnectAttempts = 0;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Startup"/> class.
+ /// </summary>
+ /// <param name="configuration">The application configuration.</param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Options = new Options();
- Configuration.GetSection("slskd").Bind(Options, (o) =>
+ Configuration.GetSection(Program.AppName).Bind(Options, (o) =>
{
o.BindNonPublicProperties = true;
});
@@ -60,19 +77,28 @@
ContentPath = Path.GetFullPath(Options.Web.ContentPath);
- JwtSigningKey = new SymmetricSecurityKey(PBKDF2.GetKey(Options.Web.Authentication.Jwt.Key));
+ 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<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>();
+ private Options Options { get; }
+ private ISharedFileCache SharedFileCache { get; set; }
+ private string UrlBase { get; set; }
+ /// <summary>
+ /// Configure services.
+ /// </summary>
+ /// <param name="services">The service collection.</param>
public void ConfigureServices(IServiceCollection services)
{
var logger = Log.ForContext<Startup>();
services.AddOptions<Options>()
- .Bind(Configuration.GetSection("slskd"), o => { o.BindNonPublicProperties = true; });
+ .Bind(Configuration.GetSection(Program.AppName), o => { o.BindNonPublicProperties = true; });
services.AddCors(options => options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
@@ -89,7 +115,7 @@
RequireSignedTokens = true,
RequireExpirationTime = true,
ValidateLifetime = true,
- ValidIssuer = "slskd",
+ ValidIssuer = Program.AppName,
ValidateIssuer = true,
ValidateAudience = false,
IssuerSigningKey = JwtSigningKey,
@@ -100,11 +126,12 @@
else
{
logger.Warning("Authentication of web requests is DISABLED");
-
+
services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme)
.AddScheme<PassthroughAuthenticationOptions, PassthroughAuthenticationHandler>(PassthroughAuthentication.AuthenticationScheme, options =>
{
- options.Username = "n/a";
+ options.Username = "Anonymous";
+ options.Role = Role.Administrator;
});
}
@@ -125,22 +152,29 @@
options.SubstituteApiVersionInUrl = true;
});
- services.AddSwaggerGen(options =>
+ if (Options.Feature.Swagger)
{
- options.DescribeAllParametersInCamelCase();
- options.SwaggerDoc("v0",
- new OpenApiInfo
+ services.AddSwaggerGen(options =>
+ {
+ options.DescribeAllParametersInCamelCase();
+ options.SwaggerDoc(
+ "v0",
+ new OpenApiInfo
+ {
+ Title = Program.AppName,
+ Version = "v0",
+ });
+
+ if (System.IO.File.Exists(XmlDocFile))
{
- Title = "slskd",
- Version = "v0"
+ options.IncludeXmlComments(XmlDocFile);
}
- );
-
- 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)
{
@@ -155,11 +189,20 @@
services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250));
}
+ /// <summary>
+ /// Configure middleware.
+ /// </summary>
+ /// <param name="app">The application builder.</param>
+ /// <param name="provider">The api version description provider.</param>
+ /// <param name="tracker">The transfer tracker.</param>
+ /// <param name="browseTracker">The browse tracker.</param>
+ /// <param name="conversationTracker">The conversation tracker.</param>
+ /// <param name="roomTracker">The room tracker.</param>
public void Configure(
- IApplicationBuilder app,
- IApiVersionDescriptionProvider provider,
- ITransferTracker tracker,
- IBrowseTracker browseTracker,
+ IApplicationBuilder app,
+ IApiVersionDescriptionProvider provider,
+ ITransferTracker tracker,
+ IBrowseTracker browseTracker,
IConversationTracker conversationTracker,
IRoomTracker roomTracker)
{
@@ -175,11 +218,11 @@
logger.Information($"Forcing HTTP requests to HTTPS");
}
+ // allow users to specify a custom path base, for use behind a reverse proxy
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 manipulating the path base
app.Use(async (context, next) =>
{
var path = context.Request.Path.ToString();
@@ -203,9 +246,9 @@
fileServerOptions = new FileServerOptions
{
FileProvider = new PhysicalFileProvider(ContentPath),
- RequestPath = "",
+ RequestPath = string.Empty,
EnableDirectoryBrowsing = false,
- EnableDefaultFiles = true
+ EnableDefaultFiles = true,
};
app.UseFileServer(fileServerOptions);
@@ -244,8 +287,8 @@
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
@@ -257,8 +300,8 @@
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);
@@ -275,11 +318,10 @@
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,
+ listenPort: Options.Soulseek.ListenPort,
+ enableListener: true,
userEndPointCache: new UserEndPointCache(),
distributedChildLimit: Options.Soulseek.DistributedNetwork.ChildLimit,
enableDistributedNetwork: !Options.Soulseek.DistributedNetwork.Disabled,
@@ -305,8 +347,8 @@
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
@@ -323,7 +365,7 @@
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();
@@ -339,12 +381,13 @@
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);
@@ -394,16 +437,16 @@
{
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);
+ Interlocked.Increment(ref currentReconnectAttempts);
- if (CurrentReconnectAttempts <= MaxReconnectAttempts)
+ if (currentReconnectAttempts <= MaxReconnectAttempts)
{
- var wait = CurrentReconnectAttempts ^ 3;
+ var wait = currentReconnectAttempts ^ 3;
Console.WriteLine($"Waiting {wait} second(s) before reconnect...");
await Task.Delay(wait);
@@ -412,7 +455,7 @@
}
else
{
- Console.WriteLine($"Unable to reconnect after {CurrentReconnectAttempts} tries.");
+ Console.WriteLine($"Unable to reconnect after {currentReconnectAttempts} tries.");
}
}
};
@@ -426,24 +469,6 @@
}
/// <summary>
- /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request.
- /// </summary>
- /// <param name="username">The username of the requesting user.</param>
- /// <param name="endpoint">The IP endpoint of the requesting user.</param>
- /// <returns>A Task resolving the UserInfo instance.</returns>
- private Task<UserInfo> 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);
- }
-
- /// <summary>
/// Creates and returns an <see cref="IEnumerable{T}"/> of <see cref="Soulseek.Directory"/> in response to a remote request.
/// </summary>
/// <param name="username">The username of the requesting user.</param>
@@ -476,15 +501,20 @@
}
/// <summary>
- /// Invoked upon a remote request to download a file.
+ /// Invoked upon a remote request to download a file.
/// </summary>
/// <param name="username">The username of the requesting user.</param>
/// <param name="endpoint">The IP endpoint of the requesting user.</param>
/// <param name="filename">The filename of the requested file.</param>
/// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
- /// <exception cref="DownloadEnqueueException">Thrown when the download is rejected. The Exception message will be passed to the remote user.</exception>
- /// <exception cref="Exception">Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for security reasons.</exception>
+ /// <exception cref="DownloadEnqueueException">
+ /// Thrown when the download is rejected. The Exception message will be passed to the remote user.
+ /// </exception>
+ /// <exception cref="Exception">
+ /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for
+ /// security reasons.
+ /// </exception>
private Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
{
_ = endpoint;
@@ -499,8 +529,7 @@
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;
}
@@ -509,8 +538,8 @@
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);
@@ -535,14 +564,14 @@
{
var defaultResponse = Task.FromResult<SearchResponse>(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;
@@ -563,21 +592,39 @@
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<SearchResponse>(null);
}
- class IPAddressConverter : JsonConverter<IPAddress>
+ /// <summary>
+ /// Creates and returns a <see cref="UserInfo"/> object in response to a remote request.
+ /// </summary>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="endpoint">The IP endpoint of the requesting user.</param>
+ /// <returns>A Task resolving the UserInfo instance.</returns>
+ private Task<UserInfo> 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<IPAddress>
{
- public override bool CanConvert(Type objectType) => (objectType == typeof(IPAddress));
+ public override bool CanConvert(Type objectType) => objectType == typeof(IPAddress);
public override IPAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => IPAddress.Parse(reader.GetString());
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/Trackers/ITransferTracker.cs b/src/slskd/Trackers/ITransferTracker.cs
index f55a23ac..b16311f8 100644
--- a/src/slskd/Trackers/ITransferTracker.cs
+++ b/src/slskd/Trackers/ITransferTracker.cs
@@ -1,8 +1,25 @@
-namespace slskd.Trackers
+// <copyright file="ITransferTracker.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Trackers
{
- using Soulseek;
using System.Collections.Concurrent;
using System.Threading;
+ using Soulseek;
/// <summary>
/// Tracks transfers.
@@ -12,7 +29,7 @@
/// <summary>
/// Tracked transfers.
/// </summary>
- ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; }
+ ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; }
/// <summary>
/// Adds or updates a tracked transfer.
@@ -35,6 +52,6 @@
/// <param name="id"></param>
/// <param name="transfer"></param>
/// <returns></returns>
- bool TryGet(TransferDirection direction, string username, string id, out (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer);
+ bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer);
}
} \ No newline at end of file
diff --git a/src/slskd/Trackers/TransferTracker.cs b/src/slskd/Trackers/TransferTracker.cs
index 8739b7ca..6efa7345 100644
--- a/src/slskd/Trackers/TransferTracker.cs
+++ b/src/slskd/Trackers/TransferTracker.cs
@@ -1,8 +1,25 @@
-namespace slskd.Trackers
+// <copyright file="TransferTracker.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Trackers
{
using System.Collections.Concurrent;
- using System.Threading;
using System.Linq;
+ using System.Threading;
using Soulseek;
/// <summary>
@@ -16,12 +33,12 @@
/// <param name="allTransfers"></param>
/// <param name="direction"></param>
/// <returns></returns>
- public static ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection(
- this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers,
+ public static ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection(
+ this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers,
TransferDirection direction)
{
allTransfers.TryGetValue(direction, out var transfers);
- return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>();
+ return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>();
}
/// <summary>
@@ -30,7 +47,7 @@
/// <param name="directedTransfers"></param>
/// <returns></returns>
public static object ToMap(
- this ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers)
+ this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers)
{
return directedTransfers.Select(u => new
{
@@ -47,12 +64,12 @@
/// <param name="directedTransfers"></param>
/// <param name="username"></param>
/// <returns></returns>
- public static ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser(
- this ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers,
+ public static ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser(
+ this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers,
string username)
{
directedTransfers.TryGetValue(username, out var transfers);
- return transfers ?? new ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
+ return transfers ?? new ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
}
/// <summary>
@@ -60,7 +77,7 @@
/// </summary>
/// <param name="userTransfers"></param>
public static object ToMap(
- this ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers)
+ this ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers)
{
return userTransfers.Values
.GroupBy(f => f.Transfer.Filename.DirectoryName())
@@ -73,8 +90,8 @@
/// <param name="userTransfers"></param>
/// <param name="id"></param>
/// <returns></returns>
- public static (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId(
- this ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers,
+ public static (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId(
+ this ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers,
string id)
{
userTransfers.TryGetValue(id, out var transfer);
@@ -90,16 +107,16 @@
/// <summary>
/// Tracked transfers.
/// </summary>
- public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } =
- new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer, CancellationTokenSource)>>>();
+ public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } =
+ new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer, CancellationTokenSource)>>>();
/// <summary>
/// Initializes a new instance of the <see cref="TransferTracker"/> class.
/// </summary>
public TransferTracker()
{
- Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
- Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
+ Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
+ Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
}
/// <summary>
@@ -113,7 +130,7 @@
direction.AddOrUpdate(args.Transfer.Username, GetNewDictionaryForUser(args, cancellationTokenSource), (user, dict) =>
{
- var transfer = DTO.Transfer.FromSoulseekTransfer(args.Transfer);
+ var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer);
dict.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, cancellationTokenSource));
return dict;
});
@@ -151,7 +168,7 @@
/// <param name="id"></param>
/// <param name="transfer"></param>
/// <returns></returns>
- public bool TryGet(TransferDirection direction, string username, string id, out (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer)
+ public bool TryGet(TransferDirection direction, string username, string id, out (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer)
{
transfer = default;
@@ -169,10 +186,10 @@
return false;
}
- private ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource)
+ private ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource)
{
- var r = new ConcurrentDictionary<string, (DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
- var transfer = DTO.Transfer.FromSoulseekTransfer(args.Transfer);
+ var r = new ConcurrentDictionary<string, (API.DTO.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
+ var transfer = API.DTO.Transfer.FromSoulseekTransfer(args.Transfer);
r.AddOrUpdate(transfer.Id, (transfer, cancellationTokenSource), (id, record) => (transfer, record.CancellationTokenSource));
return r;
}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index c177f6f7..7a80b5f6 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -1,18 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
-
<PropertyGroup>
- <TargetFramework>net5.0</TargetFramework>
- <LangVersion>9.0</LangVersion>
- </PropertyGroup>
-
- <PropertyGroup>
- <ServerGarbageCollection>false</ServerGarbageCollection>
<RepositoryUrl>https://github.com/slskd/slskd</RepositoryUrl>
<PackageProjectUrl>https://slskd.org</PackageProjectUrl>
<Authors>slskd Team</Authors>
<Copyright>Copyright (c) slskd Team</Copyright>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <TargetFramework>net5.0</TargetFramework>
+ <LangVersion>9.0</LangVersion>
+ <CodeAnalysisRuleSet>Properties\analysis.ruleset</CodeAnalysisRuleSet>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <ServerGarbageCollection>false</ServerGarbageCollection>
+ <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -23,15 +24,29 @@
</PropertyGroup>
<ItemGroup>
- <Content Include="slskd.yml">
- <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+ <AdditionalFiles Include="Properties\stylecop.json" />
+ <Content Update="wwwroot\**\*.*">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
+ <Target Name="CopyAfterBuild" AfterTargets="AfterBuild">
+ <Copy SourceFiles="..\..\LICENSE" DestinationFolder="$(OutDir)" />
+ <Copy SourceFiles="Properties\slskd.yml" DestinationFolder="$(OutDir)" />
+ </Target>
+ <Target Name="CopyOnPublish" AfterTargets="Publish">
+ <Copy SourceFiles="..\..\LICENSE" DestinationFolder="$(PublishDir)" />
+ <Copy SourceFiles="Properties\slskd.yml" DestinationFolder="$(PublishDir)" />
+ </Target>
+
<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" />
+ <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.3" />
+ <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" />
+ <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="5.0.3">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ <PackageReference Include="Microsoft.Data.Sqlite" Version="5.0.3" />
<PackageReference Include="prometheus-net" Version="4.1.1" />
<PackageReference Include="prometheus-net.AspNetCore" Version="4.1.1" />
<PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="4.1.1" />
@@ -44,24 +59,19 @@
<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="SonarAnalyzer.CSharp" Version="8.18.0.27296">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
<PackageReference Include="Soulseek" Version="2.0.0" />
- <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.321">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ <PackageReference Include="Swashbuckle.AspNetCore" Version="6.0.4" />
<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.5" />
<PackageReference Include="YamlDotNet" Version="9.1.4" />
</ItemGroup>
-
- <ItemGroup>
- <Content Update="wwwroot\**\*.*">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- </ItemGroup>
-
- <ItemGroup>
- <None Include="..\..\LICENSE">
- <Pack>True</Pack>
- <PackagePath></PackagePath>
- <CopyToOutputDirectory>Always</CopyToOutputDirectory>
- </None>
- </ItemGroup>
-
</Project>