From fae0729152ff1db8c4fd25c0c7a667bb3b76962e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 5 Oct 2022 08:28:03 -0500 Subject: disable API key auth --- src/slskd/Program.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index fd80d649..c9417ed8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -612,13 +612,13 @@ namespace slskd }; }); - services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) - .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => - { - options.EnableSignalRSupport = true; - options.SignalRRoutePrefix = "/hub"; - options.Role = Role.Administrator; - }); + //services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) + // .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => + // { + // options.EnableSignalRSupport = true; + // options.SignalRRoutePrefix = "/hub"; + // options.Role = Role.Administrator; + // }); } else { -- cgit v1.2.3 From 6785b5533e1495ee597e5cf83a99aa8beefd7c1c Mon Sep 17 00:00:00 2001 From: Exouxas Date: Wed, 5 Oct 2022 16:59:58 +0200 Subject: Change version delimiter for hash to plus --- bin/build | 2 +- src/slskd/Program.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/bin/build b/bin/build index a8f1dd7e..04fd0805 100755 --- a/bin/build +++ b/bin/build @@ -42,7 +42,7 @@ done if [ -z "$version" ]; then tag=$(git describe --tags --abbrev=0) sha=$(git rev-parse --short HEAD) - version=$tag-$sha + version=$tag+$sha fi if [ "$dotnet_only" == true ]; then diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c9417ed8..f01dcbe4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -131,7 +131,7 @@ namespace slskd /// /// Gets the semantic application version. /// - public static string SemanticVersion { get; } = InformationalVersion.Split('-').First(); + public static string SemanticVersion { get; } = InformationalVersion.Split('+').First(); /// /// Gets the full application version, including both assembly and informational versions. -- cgit v1.2.3 From cd6874b3dd54c6b3e501439d308d591e4b2aada5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 5 Oct 2022 18:30:31 -0500 Subject: add auth policies --- src/slskd/Common/Authentication/AuthPolicy.cs | 28 ++++++++++++++++ .../Core/API/Controllers/ApplicationController.cs | 14 ++++---- src/slskd/Core/API/Controllers/LogsController.cs | 2 +- .../Core/API/Controllers/MetricsController.cs | 2 +- .../Core/API/Controllers/OptionsController.cs | 14 ++++---- src/slskd/Core/API/Controllers/ServerController.cs | 6 ++-- .../Core/API/Controllers/SessionController.cs | 2 +- src/slskd/Core/API/Hubs/ApplicationHub.cs | 2 +- src/slskd/Core/API/Hubs/LogsHub.cs | 2 +- .../API/Controllers/ConversationsController.cs | 12 +++---- .../API/Controllers/PublicChatController.cs | 4 +-- .../Messaging/API/Controllers/RoomsController.cs | 20 +++++------ src/slskd/Program.cs | 39 +++++++++++++++++----- .../Search/API/Controllers/SearchesController.cs | 12 +++---- src/slskd/Search/API/Hubs/SearchHub.cs | 2 +- .../Shares/API/Controllers/SharesController.cs | 12 +++---- .../API/Controllers/TransfersController.cs | 20 +++++------ src/slskd/Users/API/Controllers/UsersController.cs | 10 +++--- 18 files changed, 127 insertions(+), 76 deletions(-) create mode 100644 src/slskd/Common/Authentication/AuthPolicy.cs (limited to 'src') diff --git a/src/slskd/Common/Authentication/AuthPolicy.cs b/src/slskd/Common/Authentication/AuthPolicy.cs new file mode 100644 index 00000000..e355b2e6 --- /dev/null +++ b/src/slskd/Common/Authentication/AuthPolicy.cs @@ -0,0 +1,28 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + /// + /// Authentication policies. + /// + public static class AuthPolicy + { + public const string JwtOnly = "Jwt"; + public const string Any = "Any"; + } +} diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 7fb914e9..c09b5513 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -58,7 +58,7 @@ namespace slskd.Core.API /// /// [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public IActionResult State() { return Ok(ApplicationStateMonitor.CurrentValue); @@ -69,7 +69,7 @@ namespace slskd.Core.API /// /// [HttpDelete] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] public IActionResult Shutdown() { Program.MasterCancellationTokenSource.Cancel(); @@ -89,7 +89,7 @@ namespace slskd.Core.API /// /// [HttpPut] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] public IActionResult Restart() { Program.MasterCancellationTokenSource.Cancel(); @@ -104,7 +104,7 @@ namespace slskd.Core.API /// /// [HttpGet("version")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public IActionResult GetVersion() { return Ok(Program.SemanticVersion); @@ -115,7 +115,7 @@ namespace slskd.Core.API /// /// [HttpGet("version/latest")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task CheckVersion([FromQuery] bool forceCheck = false) { if (forceCheck) @@ -131,7 +131,7 @@ namespace slskd.Core.API /// /// [HttpPost("gc")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public IActionResult CollectGarbage() { Application.CollectGarbage(); @@ -140,7 +140,7 @@ namespace slskd.Core.API } [HttpGet("dump")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task DumpMemory() { using var dumper = new Dumper(); diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 57366867..2beaf279 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,7 +35,7 @@ namespace slskd.Core.API /// /// [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public IActionResult Logs() { return Ok(Program.LogBuffer); diff --git a/src/slskd/Core/API/Controllers/MetricsController.cs b/src/slskd/Core/API/Controllers/MetricsController.cs index da2707c1..886f1f05 100644 --- a/src/slskd/Core/API/Controllers/MetricsController.cs +++ b/src/slskd/Core/API/Controllers/MetricsController.cs @@ -36,7 +36,7 @@ namespace slskd.Core.API /// /// [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task Get() { var response = await Metrics.BuildAsync(); diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs index b0856ed3..f621b37a 100644 --- a/src/slskd/Core/API/Controllers/OptionsController.cs +++ b/src/slskd/Core/API/Controllers/OptionsController.cs @@ -56,7 +56,7 @@ namespace slskd.Core.API /// /// [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Options), 200)] public IActionResult Current() { @@ -69,7 +69,7 @@ namespace slskd.Core.API /// [HttpGet] [Route("startup")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Options), 200)] public IActionResult Startup() { @@ -82,7 +82,7 @@ namespace slskd.Core.API /// [HttpGet] [Route("debug")] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] [ProducesResponseType(typeof(string), 200)] public IActionResult Debug() { @@ -95,7 +95,7 @@ namespace slskd.Core.API } [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] [Route("yaml/location")] public IActionResult GetYamlFileLocation() { @@ -103,7 +103,7 @@ namespace slskd.Core.API } [HttpGet] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] [Route("yaml")] public IActionResult GetYamlFile() { @@ -117,7 +117,7 @@ namespace slskd.Core.API } [HttpPost] - [Authorize] + [Authorize(Policy = AuthPolicy.JwtOnly)] [Route("yaml")] public IActionResult UpdateYamlFile([FromBody] string yaml) { @@ -144,7 +144,7 @@ namespace slskd.Core.API } [HttpPost] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [Route("yaml/validate")] public IActionResult ValidateYamlFile([FromBody] string yaml) { diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index 172333ec..a725c978 100644 --- a/src/slskd/Core/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -54,7 +54,7 @@ namespace slskd.Core.API /// [HttpPut] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(403)] public async Task Connect() @@ -74,7 +74,7 @@ namespace slskd.Core.API /// [HttpDelete] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) @@ -94,7 +94,7 @@ namespace slskd.Core.API /// [HttpGet] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(ServerState), 200)] [ProducesResponseType(403)] public IActionResult Get() diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index 5f20aa9f..65a43e72 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -61,7 +61,7 @@ namespace slskd.Core.API /// The authentication is is invalid. [HttpGet] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(401)] public IActionResult Check() diff --git a/src/slskd/Core/API/Hubs/ApplicationHub.cs b/src/slskd/Core/API/Hubs/ApplicationHub.cs index 9861d0f9..063dfd2b 100644 --- a/src/slskd/Core/API/Hubs/ApplicationHub.cs +++ b/src/slskd/Core/API/Hubs/ApplicationHub.cs @@ -60,7 +60,7 @@ namespace slskd.Core.API /// /// The application SignalR hub. /// - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public class ApplicationHub : Hub { public ApplicationHub( diff --git a/src/slskd/Core/API/Hubs/LogsHub.cs b/src/slskd/Core/API/Hubs/LogsHub.cs index 7c14cc17..2bd30192 100644 --- a/src/slskd/Core/API/Hubs/LogsHub.cs +++ b/src/slskd/Core/API/Hubs/LogsHub.cs @@ -47,7 +47,7 @@ namespace slskd.Core.API /// /// The logs SignalR hub. /// - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public class LogsHub : Hub { public override async Task OnConnectedAsync() diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 492340f0..17c55a10 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -66,7 +66,7 @@ namespace slskd.Messaging.API /// A conversation with the specified username, or a message matching the specified id could not be found. /// [HttpPut("{username}/{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task Acknowledge([FromRoute]string username, [FromRoute]int id) @@ -90,7 +90,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// A conversation with the specified username could not be found. [HttpPut("{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task AcknowledgeAll([FromRoute]string username) @@ -124,7 +124,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// A conversation with the specified username could not be found. [HttpDelete("{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(404)] [ProducesResponseType(204)] public IActionResult Delete([FromRoute]string username) @@ -145,7 +145,7 @@ namespace slskd.Messaging.API /// /// The request completed successfully. [HttpGet("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Dictionary>), 200)] public IActionResult GetAll() { @@ -166,7 +166,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// A matching search was not found. [HttpGet("{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(404)] public IActionResult GetByUsername([FromRoute]string username) @@ -192,7 +192,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified message is null or empty. [HttpPost("{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(400)] public async Task Send([FromRoute]string username, [FromBody]string message) diff --git a/src/slskd/Messaging/API/Controllers/PublicChatController.cs b/src/slskd/Messaging/API/Controllers/PublicChatController.cs index c30e08a8..83f7ede7 100644 --- a/src/slskd/Messaging/API/Controllers/PublicChatController.cs +++ b/src/slskd/Messaging/API/Controllers/PublicChatController.cs @@ -45,7 +45,7 @@ namespace slskd.Messaging.API /// /// [HttpPost] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task Start() { await Client.StartPublicChatAsync(); @@ -57,7 +57,7 @@ namespace slskd.Messaging.API /// /// [HttpDelete] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task Stop() { await Client.StopPublicChatAsync(); diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 8a3e5f3f..66993630 100644 --- a/src/slskd/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -59,7 +59,7 @@ namespace slskd.Messaging.API /// /// The request completed successfully. [HttpGet("joined")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Dictionary>), 200)] public IActionResult GetAll() { @@ -74,7 +74,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpGet("joined/{roomName}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Room), 200)] [ProducesResponseType(404)] public IActionResult GetByRoomName([FromRoute]string roomName) @@ -96,7 +96,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpPost("joined/{roomName}/messages")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task SendMessage([FromRoute]string roomName, [FromBody]string message) @@ -119,7 +119,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpPost("joined/{roomName}/ticker")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) @@ -142,7 +142,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpPost("joined/{roomName}/members")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task AddRoomMember([FromRoute]string roomName, [FromBody]string username) @@ -164,7 +164,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpGet("joined/{roomName}/users")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IList), 200)] [ProducesResponseType(404)] public IActionResult GetUsersByRoomName([FromRoute]string roomName) @@ -188,7 +188,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The specified roomName could not be found. [HttpGet("joined/{roomName}/messages")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IList), 200)] [ProducesResponseType(404)] public IActionResult GetMessagesByRoomName([FromRoute]string roomName) @@ -209,7 +209,7 @@ namespace slskd.Messaging.API /// /// [HttpGet("available")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] public async Task GetRooms() { @@ -237,7 +237,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The room has already been joined. [HttpPost("joined")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Room), 201)] [ProducesResponseType(304)] public async Task JoinRoom([FromBody]string roomName) @@ -273,7 +273,7 @@ namespace slskd.Messaging.API /// The request completed successfully. /// The room has not been joined. [HttpDelete("joined/{roomName}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task LeaveRoom([FromRoute]string roomName) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c9417ed8..43d802b1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -579,6 +579,22 @@ namespace slskd if (!OptionsAtStartup.Web.Authentication.Disabled) { + services.AddAuthorization(options => + { + options.AddPolicy(AuthPolicy.JwtOnly, policy => + { + policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + policy.RequireAuthenticatedUser(); + }); + + options.AddPolicy(AuthPolicy.Any, policy => + { + policy.AuthenticationSchemes.Add(ApiKeyAuthentication.AuthenticationScheme); + policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); + policy.RequireAuthenticatedUser(); + }); + }); + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { @@ -610,20 +626,27 @@ namespace slskd return Task.CompletedTask; }, }; + }) + .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => + { + options.EnableSignalRSupport = true; + options.SignalRRoutePrefix = "/hub"; + options.Role = Role.Administrator; }); - - //services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) - // .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => - // { - // options.EnableSignalRSupport = true; - // options.SignalRRoutePrefix = "/hub"; - // options.Role = Role.Administrator; - // }); } else { Log.Warning("Authentication of web requests is DISABLED"); + services.AddAuthorization(options => + { + options.AddPolicy(AuthPolicy.Any, policy => + { + policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme); + policy.RequireAuthenticatedUser(); + }); + }); + services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) .AddScheme(PassthroughAuthentication.AuthenticationScheme, options => { diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index acae18e0..aadf01b2 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -54,7 +54,7 @@ namespace slskd.Search.API /// The specified was malformed. /// The search terminated abnormally. [HttpPost("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task Post([FromBody] SearchRequest request) { if (string.IsNullOrWhiteSpace(request.SearchText)) @@ -91,7 +91,7 @@ namespace slskd.Search.API /// The request completed successfully. /// A matching search was not found. [HttpGet("{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task GetById([FromRoute] Guid id, [FromQuery] bool includeResponses = false) { var search = await Searches.FindAsync(search => search.Id == id, includeResponses); @@ -112,7 +112,7 @@ namespace slskd.Search.API /// The request completed successfully. /// A matching search was not found. [HttpGet("{id}/responses")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task GetResponsesById([FromRoute] Guid id) { var search = await Searches.FindAsync(search => search.Id == id, includeResponses: true); @@ -130,7 +130,7 @@ namespace slskd.Search.API /// /// [HttpGet("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task GetAll() { var searches = await Searches.ListAsync(); @@ -145,7 +145,7 @@ namespace slskd.Search.API /// The search was not in progress. /// [HttpPut("{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(304)] public async Task Cancel([FromRoute] Guid id) @@ -173,7 +173,7 @@ namespace slskd.Search.API /// A search with the specified id could not be found. /// [HttpDelete("{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task Delete([FromRoute] Guid id) diff --git a/src/slskd/Search/API/Hubs/SearchHub.cs b/src/slskd/Search/API/Hubs/SearchHub.cs index aaf9a287..b1fbf725 100644 --- a/src/slskd/Search/API/Hubs/SearchHub.cs +++ b/src/slskd/Search/API/Hubs/SearchHub.cs @@ -73,7 +73,7 @@ namespace slskd.Search.API /// /// The search SignalR hub. /// - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public class SearchHub : Hub { public SearchHub( diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 5f87f900..d07e8eed 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -32,7 +32,6 @@ namespace slskd.Shares.API [Produces("application/json")] [Consumes("application/json")] [Route("api/v{version:apiVersion}/[controller]")] - [Authorize] public class SharesController : ControllerBase { /// @@ -53,7 +52,7 @@ namespace slskd.Shares.API /// The request completed successfully. /// [HttpGet("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task List() { @@ -87,7 +86,7 @@ namespace slskd.Shares.API /// The requested share could not be found. /// [HttpGet("{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(SummarizedShare), 200)] [ProducesResponseType(404)] public async Task Get(string id) @@ -122,7 +121,7 @@ namespace slskd.Shares.API /// /// The request completed successfully. [HttpGet("contents")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task BrowseAll() { @@ -137,6 +136,7 @@ namespace slskd.Shares.API /// The request completed successfully. /// The requested share could not be found. [HttpGet("{id}/contents")] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] public async Task BrowseShare(string id) @@ -161,7 +161,7 @@ namespace slskd.Shares.API /// A share scan is already in progress. [HttpPut] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(409)] public IActionResult RescanSharesAsync() @@ -186,7 +186,7 @@ namespace slskd.Shares.API /// A share scan was not in progress. [HttpDelete] [Route("")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelShareScan() diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index bdab6582..45896c2e 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -57,7 +57,7 @@ namespace slskd.Transfers.API /// The download was cancelled successfully. /// The specified download was not found. [HttpDelete("downloads/{username}/{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task CancelDownloadAsync([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) @@ -94,7 +94,7 @@ namespace slskd.Transfers.API /// The upload was cancelled successfully. /// The specified upload was not found. [HttpDelete("uploads/{username}/{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) @@ -131,7 +131,7 @@ namespace slskd.Transfers.API /// The download was rejected. /// An unexpected error was encountered. [HttpPost("downloads/{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] @@ -154,7 +154,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. [HttpGet("downloads")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] public async Task GetDownloadsAsync([FromQuery]bool includeRemoved = false) { @@ -181,7 +181,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. [HttpGet("downloads/{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] public async Task GetDownloadsAsync([FromRoute, Required] string username) { @@ -207,7 +207,7 @@ namespace slskd.Transfers.API } [HttpGet("downloads/{username}/{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] public async Task GetDownload([FromRoute, Required] string username, [FromRoute, Required] string id) @@ -237,7 +237,7 @@ namespace slskd.Transfers.API /// The request completed successfully. /// The specified download was not found. [HttpGet("downloads/{username}/{id}/position")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] public async Task GetPlaceInQueueAsync([FromRoute, Required] string username, [FromRoute, Required] string id) @@ -268,7 +268,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. [HttpGet("uploads")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] public async Task GetUploads([FromQuery] bool includeRemoved = false) { @@ -295,7 +295,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. [HttpGet("uploads/{username}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] public async Task GetUploads([FromRoute, Required] string username) { @@ -328,7 +328,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. [HttpGet("uploads/{username}/{id}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] public async Task GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 2439785e..0f06a677 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -59,7 +59,7 @@ namespace slskd.Users.API /// /// The request completed successfully. [HttpGet("{username}/endpoint")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IPEndPoint), 200)] [ProducesResponseType(404)] public async Task Endpoint([FromRoute, Required] string username) @@ -81,7 +81,7 @@ namespace slskd.Users.API /// The username of the user. /// [HttpGet("{username}/browse")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] public async Task Browse([FromRoute, Required] string username) @@ -110,7 +110,7 @@ namespace slskd.Users.API /// The username of the user. /// [HttpGet("{username}/browse/status")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(decimal), 200)] [ProducesResponseType(404)] public IActionResult BrowseStatus([FromRoute, Required] string username) @@ -129,7 +129,7 @@ namespace slskd.Users.API /// The username of the user. /// [HttpGet("{username}/info")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Info), 200)] [ProducesResponseType(404)] public async Task Info([FromRoute, Required] string username) @@ -151,7 +151,7 @@ namespace slskd.Users.API /// The username of the user. /// [HttpGet("{username}/status")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Status), 200)] [ProducesResponseType(404)] public async Task Status([FromRoute, Required] string username) -- cgit v1.2.3 From 486d0a9768525c6f5d94ebc5b3c02cc9f7376b17 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 6 Oct 2022 08:12:49 -0500 Subject: add policies for passthrough --- src/slskd/Program.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 43d802b1..f4d25630 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -645,6 +645,12 @@ namespace slskd policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme); policy.RequireAuthenticatedUser(); }); + + options.AddPolicy(AuthPolicy.JwtOnly, policy => + { + policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme); + policy.RequireAuthenticatedUser(); + }); }); services.AddAuthentication(PassthroughAuthentication.AuthenticationScheme) -- cgit v1.2.3 From 00ddee0a99d6435613adc4451994b7018acc5f99 Mon Sep 17 00:00:00 2001 From: Exouxas Date: Sun, 9 Oct 2022 10:37:55 +0200 Subject: Add logic for duplicate filenames --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9b4d14fc..4e037f38 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -493,6 +493,18 @@ namespace slskd.Transfers.Downloads Directory.CreateDirectory(destinationPath); } + if (File.Exists(destinationFilename)) + { + string extensionlessFilename = Path.GetFileNameWithoutExtension(filename); + string extension = Path.GetExtension(filename); + + while (File.Exists(destinationFilename)) + { + string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}.{extension}"; + destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); + } + } + File.Move(sourceFilename, destinationFilename, overwrite: true); if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) -- cgit v1.2.3 From 3345653b6b5293215b5eda2516e9c96bced83ab2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 18:02:11 -0500 Subject: implement more explicit schema checks, add scans table --- .../Exceptions/ShareInitializationException.cs | 72 ++++++++++++++++++++++ src/slskd/Shares/ShareRepository.cs | 61 +++++++++++++++++- src/slskd/Shares/ShareScanner.cs | 16 +++-- src/slskd/Shares/ShareService.cs | 59 ++++++++++++------ 4 files changed, 181 insertions(+), 27 deletions(-) create mode 100644 src/slskd/Common/Exceptions/ShareInitializationException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/ShareInitializationException.cs b/src/slskd/Common/Exceptions/ShareInitializationException.cs new file mode 100644 index 00000000..31e45b91 --- /dev/null +++ b/src/slskd/Common/Exceptions/ShareInitializationException.cs @@ -0,0 +1,72 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareInitializationException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ShareInitializationException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ShareInitializationException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ShareInitializationException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ShareInitializationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Shares/ShareRepository.cs b/src/slskd/Shares/ShareRepository.cs index b8ecd2be..7b723ac6 100644 --- a/src/slskd/Shares/ShareRepository.cs +++ b/src/slskd/Shares/ShareRepository.cs @@ -23,7 +23,6 @@ namespace slskd.Shares using System.Linq; using Microsoft.Data.Sqlite; using Serilog; - using slskd.Transfers.Uploads; using Soulseek; /// @@ -85,6 +84,13 @@ namespace slskd.Shares /// The timestamp to assign to the record. void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, Soulseek.File file, long timestamp); + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + void InsertScan(long timestamp, Options.SharesOptions options); + /// /// Lists all directories. /// @@ -126,6 +132,13 @@ namespace slskd.Shares /// The search query. /// The list of matching files. IEnumerable Search(SearchQuery query); + + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + void UpdateScan(long timestamp, long end); } /// @@ -160,10 +173,18 @@ namespace slskd.Shares var log = Serilog.Log.ForContext(); + // to update this schema map, run the following query against a valid, up-to-date database and paste the output below: + // select '{ "' || name || '", "' || sql || '" },' from sqlite_master where type = 'table' var schema = new Dictionary() { + { "scans", "CREATE TABLE scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL)" }, { "directories", "CREATE TABLE directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL)" }, { "filenames", "CREATE VIRTUAL TABLE filenames USING fts5(maskedFilename)" }, + { "filenames_data", "CREATE TABLE 'filenames_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { "filenames_idx", "CREATE TABLE 'filenames_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID" }, + { "filenames_content", "CREATE TABLE 'filenames_content'(id INTEGER PRIMARY KEY, c0)" }, + { "filenames_docsize", "CREATE TABLE 'filenames_docsize'(id INTEGER PRIMARY KEY, sz BLOB)" }, + { "filenames_config", "CREATE TABLE 'filenames_config'(k PRIMARY KEY, v) WITHOUT ROWID" }, { "files", "CREATE TABLE files (maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL)" }, }; @@ -174,7 +195,7 @@ namespace slskd.Shares using var conn = new SqliteConnection(connectionString); conn.Open(); - using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table' AND name IN ('directories', 'filenames', 'files');", conn); + using var cmd = new SqliteCommand("SELECT name, sql from sqlite_master WHERE type = 'table';", conn); var reader = cmd.ExecuteReader(); var rows = 0; @@ -306,9 +327,11 @@ namespace slskd.Shares if (discardExisting) { - conn.ExecuteNonQuery("DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); + conn.ExecuteNonQuery("DROP TABLE IF EXISTS scans; DROP TABLE IF EXISTS directories; DROP TABLE IF EXISTS filenames; DROP TABLE IF EXISTS files;"); } + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS scans (timestamp INTEGER PRIMARY KEY, options TEXT NOT NULL, end INTEGER DEFAULT NULL);"); + conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS directories (name TEXT PRIMARY KEY, timestamp INTEGER NOT NULL);"); conn.ExecuteNonQuery("CREATE VIRTUAL TABLE IF NOT EXISTS filenames USING fts5(maskedFilename);"); @@ -391,6 +414,22 @@ namespace slskd.Shares }); } + /// + /// Inserts a scan record at the specified . + /// + /// The timestamp associated with the scan. + /// The options snapshot at the start of the scan. + public void InsertScan(long timestamp, Options.SharesOptions options) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("INSERT INTO scans (timestamp, options) VALUES(@timestamp, @options)", cmd => + { + cmd.Parameters.AddWithValue("timestamp", timestamp); + cmd.Parameters.AddWithValue("options", options.ToJson()); + }); + } + /// /// Lists all directories. /// @@ -583,6 +622,22 @@ namespace slskd.Shares } } + /// + /// Updates the scan started at the specified to set the . + /// + /// The timestamp associated with the scan. + /// The timestamp at the conclusion of the scan. + public void UpdateScan(long timestamp, long end) + { + using var conn = GetConnection(); + + conn.ExecuteNonQuery("UPDATE scans SET end = @end WHERE timestamp = @timestamp;", cmd => + { + cmd.Parameters.AddWithValue("end", end); + cmd.Parameters.AddWithValue("timestamp", timestamp); + }); + } + private SqliteConnection GetConnection(string connectionString = null) { connectionString ??= ConnectionString; diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 369e4981..74f0d131 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -44,9 +44,9 @@ namespace slskd.Shares /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. - /// The list of regular expressions used to exclude files or paths from scanning. + /// The current options snapshot. /// The operation context. - Task ScanAsync(IEnumerable shares, IEnumerable filters); + Task ScanAsync(IEnumerable shares, Options.SharesOptions options); /// /// Cancels the currently running fill operation, if one is running. @@ -90,9 +90,9 @@ namespace slskd.Shares /// Scans the configured shares and fills the cache. /// /// The list of shares from which to fill the cache. - /// The list of regular expressions used to exclude files or paths from scanning. + /// The current options snapshot. /// The operation context. - public async Task ScanAsync(IEnumerable shares, IEnumerable filters) + public async Task ScanAsync(IEnumerable shares, Options.SharesOptions options) { // obtain the semaphore, or fail if it can't be obtained immediately, indicating that a scan is running. if (!await SyncRoot.WaitAsync(millisecondsTimeout: 0)) @@ -130,10 +130,16 @@ namespace slskd.Shares Log.Information("Shared file cache re-created and ready for scan."); } + var filters = options.Filters + .Select(filter => new Regex(filter, RegexOptions.Compiled)) + .ToList(); + Log.Information("Starting shared file scan"); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Repository.InsertScan(timestamp, options); + var sw = new Stopwatch(); var swSnapshot = 0L; sw.Start(); @@ -316,6 +322,8 @@ namespace slskd.Shares State.SetValue(state => state with { Cancelled = true }); } + Repository.UpdateScan(timestamp, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + Log.Debug("Backing up shared file cache database..."); Repository.BackupTo(Program.ConnectionStrings.SharesBackup); Log.Debug("Shared file cache database backup complete"); diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 09085b72..a9c8c629 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -94,7 +94,6 @@ namespace slskd.Shares private List SharesList { get; set; } = new List(); private IManagedState State { get; } = new ManagedState(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private List FilterRegexes { get; set; } = new List(); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -218,7 +217,7 @@ namespace slskd.Shares /// Thrown when a scan is already in progress. public Task ScanAsync() { - return Scanner.ScanAsync(Shares, FilterRegexes); + return Scanner.ScanAsync(Shares, OptionsMonitor.CurrentValue.Shares); } /// @@ -251,6 +250,8 @@ namespace slskd.Shares /// The operation context. public async Task InitializeAsync(bool forceRescan = false) { + Log.Information("Initializing shares"); + try { if (forceRescan) @@ -258,31 +259,54 @@ namespace slskd.Shares Log.Warning("Performing a forced re-scan of shares"); await ScanAsync(); } - else if (CacheStorageMode == StorageMode.Memory || (CacheStorageMode == StorageMode.Disk && !ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares))) + else if (CacheStorageMode == StorageMode.Memory) { - Log.Debug($"Share cache {(CacheStorageMode == StorageMode.Memory ? "StorageMode is 'Memory'" : "database is missing from disk")}. Attempting to load from backup..."); + Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - // the backup is missing; we can't do anything but recreate it from scratch - if (!ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) { - Log.Warning("Share cache couldn't be loaded from backup"); - await InitializeAsync(forceRescan: true); - } - else - { - Log.Debug("Share cache backup located. Attempting to restore..."); + Log.Information("Share cache backup validated. Attempting to restore..."); Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); Log.Information("Share cache successfully restored from backup"); } + else + { + Log.Warning("Share cache backup is missing, corrupt, or is out of date"); + throw new ShareInitializationException("Share cache backup is missing, corrupt, or is out of date"); + } } - else + else if (CacheStorageMode == StorageMode.Disk) { - // the cache mode is disk and the existing db is valid. nothing to do. + Log.Information("Share cache StorageMode is 'Disk'. Attempting to validate..."); + + if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.Shares)) + { + // no-op + } + else + { + Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); + + if (ShareRepository.TryValidateDatabase(Program.ConnectionStrings.SharesBackup)) + { + Log.Information("Share cache backup validated. Attempting to restore..."); + + Repository.RestoreFrom(connectionString: Program.ConnectionStrings.SharesBackup); + + Log.Information("Share cache successfully restored from backup"); + } + else + { + Log.Warning("Share cache and backup are both missing, corrupt, or is out of date"); + throw new ShareInitializationException("Share cache and backup are both missing, corrupt, or is out of date"); + } + } } // one of several thigns happened above before we got here: + // this method was called with forceRescan = true // the storage mode is memory, and we loaded the in-memory db from a valid backup // the storage mode is disk, and the file is there and valid // the storage mode is disk but either missing or invalid, and we restored from a valid backup @@ -335,13 +359,8 @@ namespace slskd.Shares .OrderByDescending(share => share.LocalPath.Length) // process subdirectories first. this allows them to be aliased separately from their parent .ToList(); - var regexes = options.Shares.Filters - .Select(filter => new Regex(filter, RegexOptions.Compiled)) - .ToList(); - SharesList = shares; - FilterRegexes = regexes; - + State.SetValue(state => state with { ScanPending = true }); LastOptionsHash = optionsHash; -- cgit v1.2.3