From 37032356080e05b23e54db48d58c62fc0159754a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jun 2023 22:27:06 -0500 Subject: stub IFileService --- src/slskd/Files/FileService.cs | 68 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/slskd/Files/FileService.cs (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs new file mode 100644 index 00000000..c38e6ff4 --- /dev/null +++ b/src/slskd/Files/FileService.cs @@ -0,0 +1,68 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Files +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Linq.Expressions; + using System.Threading.Tasks; + + /// + /// Manages files on disk. + /// + public class FileService : IFileService + { + /// + /// Initializes a new instance of the class. + /// + /// + public FileService( + IOptionsSnapshot optionsSnapshot) + { + OptionsSnapshot = optionsSnapshot; + } + + private IOptionsSnapshot OptionsSnapshot { get; } + + public async Task> ListDownloadedFiles() + { + var dir = new DirectoryInfo(OptionsSnapshot.Value.Directories.Downloads); + + var files = await Task.Run(() => + { + return dir.GetFiles("*", new EnumerationOptions + { + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + IgnoreInaccessible = false, + RecurseSubdirectories = true, + }); + }); + + return files.AsEnumerable(); + } + + public Task> ListIncompleteFiles(Expression> expression = null) + { + throw new NotImplementedException(); + } + } +} -- cgit v1.2.3 From f42aeae2f9db1d10e0804c6d798abb608eebe585 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jun 2023 22:32:09 -0500 Subject: just pass EnumerationOptions --- src/slskd/Files/IFileService.cs | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/slskd/Files/IFileService.cs (limited to 'src') diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs new file mode 100644 index 00000000..a02f7a79 --- /dev/null +++ b/src/slskd/Files/IFileService.cs @@ -0,0 +1,47 @@ +// +// 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.Files +{ + using System.Collections.Generic; + using System.IO; + using System.Threading.Tasks; + + /// + /// Manages files on disk. + /// + public interface IFileService + { + /// + /// Recursively lists all of the files in the downloads directory, starting from the optional , and + /// optionally applying the specified . + /// + /// An optional parent directory from which to begin searching. + /// Optional enumeration options to apply. + /// The list of found files. + Task> ListDownloadedFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null); + + /// + /// Recursively lists all of the files in the incomplete directory, starting from the optional , and + /// optionally applying the specified . + /// + /// An optional parent directory from which to begin searching. + /// Optional enumeration options to apply. + /// The list of found files. + Task> ListIncompleteFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null); + } +} -- cgit v1.2.3 From e2451a8c1207566851c0baad99a78093441445ae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jun 2023 22:32:52 -0500 Subject: rough in download listing --- src/slskd/Files/FileService.cs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c38e6ff4..c03183d5 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -43,18 +43,24 @@ namespace slskd.Files private IOptionsSnapshot OptionsSnapshot { get; } - public async Task> ListDownloadedFiles() + /// + /// Recursively lists all of the files in the downloads directory, starting from the optional , and + /// optionally applying the specified . + /// + /// An optional parent directory from which to begin searching. + /// Optional enumeration options to apply. + /// The list of found files. + public async Task> ListDownloadedFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null) { - var dir = new DirectoryInfo(OptionsSnapshot.Value.Directories.Downloads); + var root = OptionsSnapshot.Value.Directories.Downloads; + parentDirectory = Path.Combine(root, parentDirectory) ?? root; + var dir = new DirectoryInfo(parentDirectory); + + enumerationOptions ??= new EnumerationOptions(); var files = await Task.Run(() => { - return dir.GetFiles("*", new EnumerationOptions - { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, - IgnoreInaccessible = false, - RecurseSubdirectories = true, - }); + return dir.GetFiles("*", enumerationOptions); }); return files.AsEnumerable(); -- cgit v1.2.3 From 5e9c7f4a4ba0f20ded6133b763cf0d0132fb7caa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 20 Jun 2023 09:12:42 -0500 Subject: implement file service --- .../Common/Exceptions/InvalidDirectoryException.cs | 72 ++++++++++++++++++++++ src/slskd/Files/FileService.cs | 51 +++++++++------ src/slskd/Files/IFileService.cs | 23 ++++--- 3 files changed, 119 insertions(+), 27 deletions(-) create mode 100644 src/slskd/Common/Exceptions/InvalidDirectoryException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/InvalidDirectoryException.cs b/src/slskd/Common/Exceptions/InvalidDirectoryException.cs new file mode 100644 index 00000000..1bfdfda8 --- /dev/null +++ b/src/slskd/Common/Exceptions/InvalidDirectoryException.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 errors that originate when a searched resource can't be located. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class InvalidDirectoryException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public InvalidDirectoryException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public InvalidDirectoryException(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 InvalidDirectoryException(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 InvalidDirectoryException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c03183d5..a579bc79 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -19,11 +19,9 @@ using Microsoft.Extensions.Options; namespace slskd.Files { - using System; using System.Collections.Generic; using System.IO; using System.Linq; - using System.Linq.Expressions; using System.Threading.Tasks; /// @@ -44,31 +42,48 @@ namespace slskd.Files private IOptionsSnapshot OptionsSnapshot { get; } /// - /// Recursively lists all of the files in the downloads directory, starting from the optional , and - /// optionally applying the specified . + /// Lists all of the directories in the specified , optionally applying the + /// specified . /// - /// An optional parent directory from which to begin searching. + /// The directory from which to start the listing. /// Optional enumeration options to apply. - /// The list of found files. - public async Task> ListDownloadedFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null) + /// The list of found directories. + /// + /// Thrown if the specified directory is not rooted in an allowed directory. + /// + public async Task> ListDirectoriesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) { - var root = OptionsSnapshot.Value.Directories.Downloads; - parentDirectory = Path.Combine(root, parentDirectory) ?? root; - var dir = new DirectoryInfo(parentDirectory); + if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) + { + throw new InvalidDirectoryException($"The directory '{parentDirectory}' is not rooted in any of the allowed directories"); + } - enumerationOptions ??= new EnumerationOptions(); + return await Task.Run(() => new DirectoryInfo(parentDirectory).GetDirectories("*", enumerationOptions)); + } - var files = await Task.Run(() => + /// + /// Lists all of the files in the specified , optionally applying the specified . + /// + /// An optional parent directory from which to begin searching. + /// Optional enumeration options to apply. + /// The list of found files. + /// + /// Thrown if the specified directory is not rooted in an allowed directory. + /// + public async Task> ListFilesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) + { + if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) { - return dir.GetFiles("*", enumerationOptions); - }); + throw new InvalidDirectoryException($"The directory '{parentDirectory}' is not rooted in any of the applowed directories"); + } - return files.AsEnumerable(); + return await Task.Run(() => new DirectoryInfo(parentDirectory).GetFiles("*", enumerationOptions)); } - public Task> ListIncompleteFiles(Expression> expression = null) + private bool IsPermissibleDirectory(string dir, Options.DirectoriesOptions options) { - throw new NotImplementedException(); + var allowedRoots = new[] { options.Downloads, options.Incomplete }; + return allowedRoots.Any(r => dir.StartsWith(r)); } } -} +} \ No newline at end of file diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index a02f7a79..d8174d88 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -27,21 +27,26 @@ namespace slskd.Files public interface IFileService { /// - /// Recursively lists all of the files in the downloads directory, starting from the optional , and - /// optionally applying the specified . + /// Lists all of the directories in the specified , optionally applying the + /// specified . /// - /// An optional parent directory from which to begin searching. + /// The directory from which to start the listing. /// Optional enumeration options to apply. - /// The list of found files. - Task> ListDownloadedFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null); + /// The list of found directories. + /// + /// Thrown if the specified directory is not rooted in an allowed directory. + /// + Task> ListDirectoriesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); /// - /// Recursively lists all of the files in the incomplete directory, starting from the optional , and - /// optionally applying the specified . + /// Lists all of the files in the specified , optionally applying the specified . /// /// An optional parent directory from which to begin searching. /// Optional enumeration options to apply. /// The list of found files. - Task> ListIncompleteFiles(string parentDirectory = null, EnumerationOptions enumerationOptions = null); + /// + /// Thrown if the specified directory is not rooted in an allowed directory. + /// + Task> ListFilesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); } -} +} \ No newline at end of file -- cgit v1.2.3 From 05bc0e09d54ff4a9e3924668c312610c221bd2b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 08:54:04 -0500 Subject: simplify contents listing --- src/slskd/Files/FileService.cs | 27 +++++++-------------------- src/slskd/Files/IFileService.cs | 18 ++++-------------- 2 files changed, 11 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a579bc79..c7c0105c 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -42,42 +42,29 @@ namespace slskd.Files private IOptionsSnapshot OptionsSnapshot { get; } /// - /// Lists all of the directories in the specified , optionally applying the + /// Lists all of the contents of the specified , optionally applying the /// specified . /// /// The directory from which to start the listing. /// Optional enumeration options to apply. - /// The list of found directories. + /// The list of found contents. /// /// Thrown if the specified directory is not rooted in an allowed directory. /// - public async Task> ListDirectoriesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) + /// Thrown if the specified directory does not exist. + public async Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) { if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) { throw new InvalidDirectoryException($"The directory '{parentDirectory}' is not rooted in any of the allowed directories"); } - return await Task.Run(() => new DirectoryInfo(parentDirectory).GetDirectories("*", enumerationOptions)); - } - - /// - /// Lists all of the files in the specified , optionally applying the specified . - /// - /// An optional parent directory from which to begin searching. - /// Optional enumeration options to apply. - /// The list of found files. - /// - /// Thrown if the specified directory is not rooted in an allowed directory. - /// - public async Task> ListFilesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) - { - if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) + if (!Directory.Exists(parentDirectory)) { - throw new InvalidDirectoryException($"The directory '{parentDirectory}' is not rooted in any of the applowed directories"); + throw new NotFoundException($"The directory '{parentDirectory}' does not exist"); } - return await Task.Run(() => new DirectoryInfo(parentDirectory).GetFiles("*", enumerationOptions)); + return await Task.Run(() => new DirectoryInfo(parentDirectory).GetFileSystemInfos("*", enumerationOptions)); } private bool IsPermissibleDirectory(string dir, Options.DirectoriesOptions options) diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index d8174d88..0b393e64 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -27,26 +27,16 @@ namespace slskd.Files public interface IFileService { /// - /// Lists all of the directories in the specified , optionally applying the + /// Lists all of the contents of the specified , optionally applying the /// specified . /// /// The directory from which to start the listing. /// Optional enumeration options to apply. - /// The list of found directories. + /// The list of found contents. /// /// Thrown if the specified directory is not rooted in an allowed directory. /// - Task> ListDirectoriesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); - - /// - /// Lists all of the files in the specified , optionally applying the specified . - /// - /// An optional parent directory from which to begin searching. - /// Optional enumeration options to apply. - /// The list of found files. - /// - /// Thrown if the specified directory is not rooted in an allowed directory. - /// - Task> ListFilesAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); + /// Thrown if the specified directory does not exist. + Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); } } \ No newline at end of file -- cgit v1.2.3 From a2ed01bf2610a8f615ef725322496cf910c39fe9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 08:54:12 -0500 Subject: add initial endpoints --- src/slskd/Files/API/FilesController.cs | 154 +++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 src/slskd/Files/API/FilesController.cs (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs new file mode 100644 index 00000000..4a15aa49 --- /dev/null +++ b/src/slskd/Files/API/FilesController.cs @@ -0,0 +1,154 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Files.API +{ + using System.Collections.Generic; + using System.IO; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + + /// + /// Files. + /// + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + public class FilesController : ControllerBase + { + public FilesController( + IFileService fileService, + IOptionsSnapshot optionsSnapshot) + { + Files = fileService; + OptionsSnapshot = optionsSnapshot; + } + + private IFileService Files { get; } + private IOptionsSnapshot OptionsSnapshot { get; } + + [HttpGet("downloads")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public IActionResult GetAllDownloadContentsAsync([FromQuery]bool recursive = false) + { + try + { + var dirs = Files.ListContentsAsync(OptionsSnapshot.Value.Directories.Downloads, new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(dirs); + } + catch (InvalidDirectoryException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("downloads/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public IActionResult GetSpecificDownloadContentsAsync([FromRoute]string base64SubdirectoryName, [FromQuery]bool recursive = false) + { + var decodedDir = base64SubdirectoryName.FromBase64(); + var fullDir = Path.Combine(OptionsSnapshot.Value.Directories.Downloads, decodedDir); + + try + { + var dirs = Files.ListContentsAsync(fullDir, new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(dirs); + } + catch (InvalidDirectoryException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("incomplete")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public IActionResult GetAllIncompleteDirectoriesAsync([FromQuery] bool recursive = false) + { + try + { + var dirs = Files.ListContentsAsync(OptionsSnapshot.Value.Directories.Incomplete, new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(dirs); + } + catch (InvalidDirectoryException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("incomplete/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public IActionResult GetSpecificIncompleteDirectoriesAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) + { + var decodedDir = base64SubdirectoryName.FromBase64(); + var fullDir = Path.Combine(OptionsSnapshot.Value.Directories.Incomplete, decodedDir); + + try + { + var dirs = Files.ListContentsAsync(fullDir, new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(dirs); + } + catch (InvalidDirectoryException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + } +} -- cgit v1.2.3 From 6a79a80932860b9c3ec78fcdd0d169d2efa09005 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 10:55:04 -0500 Subject: add types to represent files and dirs --- src/slskd/Files/Types/FilesystemDirectory.cs | 47 ++++++++++++++++++++++++++++ src/slskd/Files/Types/FilesystemFile.cs | 47 ++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 src/slskd/Files/Types/FilesystemDirectory.cs create mode 100644 src/slskd/Files/Types/FilesystemFile.cs (limited to 'src') diff --git a/src/slskd/Files/Types/FilesystemDirectory.cs b/src/slskd/Files/Types/FilesystemDirectory.cs new file mode 100644 index 00000000..020b688c --- /dev/null +++ b/src/slskd/Files/Types/FilesystemDirectory.cs @@ -0,0 +1,47 @@ +// +// 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.Files +{ + using System; + using System.Collections.Generic; + using System.IO; + + public record FilesystemDirectory + { + public string Parent { get; init; } + public string Name { get; init; } + public string FullName { get; init; } + public FileAttributes Attributes { get; init; } + public DateTime CreatedAt { get; init; } + public DateTime ModifiedAt { get; init; } + public IEnumerable Files { get; init; } + + public static FilesystemDirectory FromDirectoryInfo(DirectoryInfo i) + { + return new FilesystemDirectory + { + Parent = Path.GetDirectoryName(i.FullName), + Name = i.Name, + FullName = i.FullName, + Attributes = i.Attributes, + CreatedAt = i.CreationTimeUtc, + ModifiedAt = i.LastWriteTimeUtc, + }; + } + } +} diff --git a/src/slskd/Files/Types/FilesystemFile.cs b/src/slskd/Files/Types/FilesystemFile.cs new file mode 100644 index 00000000..44242582 --- /dev/null +++ b/src/slskd/Files/Types/FilesystemFile.cs @@ -0,0 +1,47 @@ +// +// 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.Files +{ + using System; + using System.IO; + + public record FilesystemFile + { + public string Parent { get; init; } + public string Name { get; init; } + public string FullName { get; init; } + public long Length { get; init; } + public FileAttributes Attributes { get; init; } + public DateTime CreatedAt { get; init; } + public DateTime ModifiedAt { get; init; } + + public static FilesystemFile FromFileInfo(FileInfo i) + { + return new FilesystemFile + { + Parent = Path.GetDirectoryName(i.FullName), + Name = i.Name, + FullName = i.FullName, + Length = i.Length, + Attributes = i.Attributes, + CreatedAt = i.CreationTimeUtc, + ModifiedAt = i.LastWriteTimeUtc, + }; + } + } +} -- cgit v1.2.3 From bf1a9b9effecf8fc18528da672990bc1ed85d6eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 10:57:02 -0500 Subject: return files + dirs together --- src/slskd/Files/FileService.cs | 22 +++++++++++++++++++--- src/slskd/Files/IFileService.cs | 4 ++-- 2 files changed, 21 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c7c0105c..dfb5ad7b 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -42,7 +42,7 @@ namespace slskd.Files private IOptionsSnapshot OptionsSnapshot { get; } /// - /// Lists all of the contents of the specified , optionally applying the + /// Lists the contents in the specified , optionally applying the /// specified . /// /// The directory from which to start the listing. @@ -52,7 +52,7 @@ namespace slskd.Files /// Thrown if the specified directory is not rooted in an allowed directory. /// /// Thrown if the specified directory does not exist. - public async Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) + public async Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) { if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) { @@ -64,7 +64,23 @@ namespace slskd.Files throw new NotFoundException($"The directory '{parentDirectory}' does not exist"); } - return await Task.Run(() => new DirectoryInfo(parentDirectory).GetFileSystemInfos("*", enumerationOptions)); + return await Task.Run(() => + { + var dir = new DirectoryInfo(parentDirectory); + + var contents = dir.GetFileSystemInfos("*", enumerationOptions); + + var files = contents + .OfType() + .Select(f => FilesystemFile.FromFileInfo(f)); + + var dirs = contents + .OfType() + .Prepend(dir) + .Select(d => FilesystemDirectory.FromDirectoryInfo(d) with { Files = files.Where(f => f.Parent == d.FullName) }); + + return dirs; + }); } private bool IsPermissibleDirectory(string dir, Options.DirectoriesOptions options) diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index 0b393e64..0a750b59 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -27,7 +27,7 @@ namespace slskd.Files public interface IFileService { /// - /// Lists all of the contents of the specified , optionally applying the + /// Lists the contents in the specified , optionally applying the /// specified . /// /// The directory from which to start the listing. @@ -37,6 +37,6 @@ namespace slskd.Files /// Thrown if the specified directory is not rooted in an allowed directory. /// /// Thrown if the specified directory does not exist. - Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); + Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); } } \ No newline at end of file -- cgit v1.2.3 From 1e6ff9e218aa381f12fedd04d8055cead1e37b6d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 10:57:09 -0500 Subject: wire up DI --- src/slskd/Program.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1236865f..060284d8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -55,6 +55,7 @@ namespace slskd using slskd.Configuration; using slskd.Core.API; using slskd.Cryptography; + using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -556,6 +557,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddTransient(); services.AddSingleton(); -- cgit v1.2.3 From efccdff7b30d55fc63e195a8f6d865f19fd1a919 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 21 Jun 2023 10:57:29 -0500 Subject: implement download fetch --- src/slskd/Files/API/FilesController.cs | 90 ++++------------------------------ 1 file changed, 9 insertions(+), 81 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 4a15aa49..6ee2e7ac 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -21,6 +21,7 @@ namespace slskd.Files.API { using System.Collections.Generic; using System.IO; + using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -45,101 +46,28 @@ namespace slskd.Files.API private IFileService Files { get; } private IOptionsSnapshot OptionsSnapshot { get; } - [HttpGet("downloads")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult GetAllDownloadContentsAsync([FromQuery]bool recursive = false) - { - try - { - var dirs = Files.ListContentsAsync(OptionsSnapshot.Value.Directories.Downloads, new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); - - return Ok(dirs); - } - catch (InvalidDirectoryException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } - [HttpGet("downloads/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult GetSpecificDownloadContentsAsync([FromRoute]string base64SubdirectoryName, [FromQuery]bool recursive = false) - { - var decodedDir = base64SubdirectoryName.FromBase64(); - var fullDir = Path.Combine(OptionsSnapshot.Value.Directories.Downloads, decodedDir); - - try - { - var dirs = Files.ListContentsAsync(fullDir, new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); - - return Ok(dirs); - } - catch (InvalidDirectoryException) - { - return Forbid(); - } - catch (NotFoundException) - { - return NotFound(); - } - } - - [HttpGet("incomplete")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult GetAllIncompleteDirectoriesAsync([FromQuery] bool recursive = false) + [ProducesResponseType(typeof(IEnumerable), 200)] + public async Task GetDownloadContentsAsync([FromRoute]string base64SubdirectoryName = null, [FromQuery]bool recursive = false) { - try - { - var dirs = Files.ListContentsAsync(OptionsSnapshot.Value.Directories.Incomplete, new EnumerationOptions - { - AttributesToSkip = FileAttributes.System, - RecurseSubdirectories = recursive, - }); + var dir = OptionsSnapshot.Value.Directories.Downloads; - return Ok(dirs); - } - catch (InvalidDirectoryException) - { - return Forbid(); - } - catch (NotFoundException) + if (!string.IsNullOrEmpty(base64SubdirectoryName)) { - return NotFound(); + var decodedDir = base64SubdirectoryName.FromBase64(); + dir = Path.Combine(dir, decodedDir); } - } - - [HttpGet("incomplete/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(IEnumerable), 200)] - public IActionResult GetSpecificIncompleteDirectoriesAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) - { - var decodedDir = base64SubdirectoryName.FromBase64(); - var fullDir = Path.Combine(OptionsSnapshot.Value.Directories.Incomplete, decodedDir); try { - var dirs = Files.ListContentsAsync(fullDir, new EnumerationOptions + var response = await Files.ListContentsAsync(dir, new EnumerationOptions { AttributesToSkip = FileAttributes.System, RecurseSubdirectories = recursive, }); - return Ok(dirs); + return Ok(response); } catch (InvalidDirectoryException) { -- cgit v1.2.3 From 6a722d1fdecd10eb5bcdd8206e1c4da93ea36496 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jun 2023 09:56:37 -0500 Subject: swap exceptions --- src/slskd/Common/Exceptions/ForbiddenException.cs | 72 ++++++++++++++++++++++ .../Common/Exceptions/InvalidDirectoryException.cs | 72 ---------------------- 2 files changed, 72 insertions(+), 72 deletions(-) create mode 100644 src/slskd/Common/Exceptions/ForbiddenException.cs delete mode 100644 src/slskd/Common/Exceptions/InvalidDirectoryException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/ForbiddenException.cs b/src/slskd/Common/Exceptions/ForbiddenException.cs new file mode 100644 index 00000000..814b8cfc --- /dev/null +++ b/src/slskd/Common/Exceptions/ForbiddenException.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 errors that originate when an attempt is made to access a restricted resource. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ForbiddenException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ForbiddenException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ForbiddenException(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 ForbiddenException(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 ForbiddenException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Exceptions/InvalidDirectoryException.cs b/src/slskd/Common/Exceptions/InvalidDirectoryException.cs deleted file mode 100644 index 1bfdfda8..00000000 --- a/src/slskd/Common/Exceptions/InvalidDirectoryException.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.Serialization; - - /// - /// Represents errors that originate when a searched resource can't be located. - /// - [ExcludeFromCodeCoverage] - [Serializable] - public class InvalidDirectoryException : SlskdException - { - /// - /// Initializes a new instance of the class. - /// - public InvalidDirectoryException() - : base() - { - } - - /// - /// Initializes a new instance of the class with a specified error message. - /// - /// The message that describes the error. - public InvalidDirectoryException(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 InvalidDirectoryException(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 InvalidDirectoryException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - } -} \ No newline at end of file -- cgit v1.2.3 From 95b420e10dd6d217317f28d491d2d82b863ac5c4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jun 2023 09:56:57 -0500 Subject: remove parent prop --- src/slskd/Files/Types/FilesystemDirectory.cs | 2 -- src/slskd/Files/Types/FilesystemFile.cs | 2 -- 2 files changed, 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/Types/FilesystemDirectory.cs b/src/slskd/Files/Types/FilesystemDirectory.cs index 020b688c..4183c724 100644 --- a/src/slskd/Files/Types/FilesystemDirectory.cs +++ b/src/slskd/Files/Types/FilesystemDirectory.cs @@ -23,7 +23,6 @@ namespace slskd.Files public record FilesystemDirectory { - public string Parent { get; init; } public string Name { get; init; } public string FullName { get; init; } public FileAttributes Attributes { get; init; } @@ -35,7 +34,6 @@ namespace slskd.Files { return new FilesystemDirectory { - Parent = Path.GetDirectoryName(i.FullName), Name = i.Name, FullName = i.FullName, Attributes = i.Attributes, diff --git a/src/slskd/Files/Types/FilesystemFile.cs b/src/slskd/Files/Types/FilesystemFile.cs index 44242582..fc36fff0 100644 --- a/src/slskd/Files/Types/FilesystemFile.cs +++ b/src/slskd/Files/Types/FilesystemFile.cs @@ -22,7 +22,6 @@ namespace slskd.Files public record FilesystemFile { - public string Parent { get; init; } public string Name { get; init; } public string FullName { get; init; } public long Length { get; init; } @@ -34,7 +33,6 @@ namespace slskd.Files { return new FilesystemFile { - Parent = Path.GetDirectoryName(i.FullName), Name = i.Name, FullName = i.FullName, Length = i.Length, -- cgit v1.2.3 From c76f272f380833ad01e98f7946a7e114a1635a6c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jun 2023 09:57:28 -0500 Subject: obscure full path of files, throw ForbiddenException if root is not whitelisted --- src/slskd/Files/FileService.cs | 39 +++++++++++++++++++++------------------ src/slskd/Files/IFileService.cs | 9 ++++----- 2 files changed, 25 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index dfb5ad7b..7194cc04 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -32,7 +32,6 @@ namespace slskd.Files /// /// Initializes a new instance of the class. /// - /// public FileService( IOptionsSnapshot optionsSnapshot) { @@ -45,28 +44,32 @@ namespace slskd.Files /// Lists the contents in the specified , optionally applying the /// specified . /// - /// The directory from which to start the listing. + /// The root directory. + /// An optional subdirectory from which to start the listing. /// Optional enumeration options to apply. /// The list of found contents. - /// - /// Thrown if the specified directory is not rooted in an allowed directory. - /// /// Thrown if the specified directory does not exist. - public async Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null) + /// Thrown if the specified directory is restricted. + public async Task> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null) { - if (!IsPermissibleDirectory(parentDirectory, OptionsSnapshot.Value.Directories)) + var configuredDirectories = OptionsSnapshot.Value.Directories; + var allowedDirectories = new[] { configuredDirectories.Incomplete, configuredDirectories.Downloads }; + + if (!allowedDirectories.Any(d => rootDirectory == d)) { - throw new InvalidDirectoryException($"The directory '{parentDirectory}' is not rooted in any of the allowed directories"); + throw new ForbiddenException($"For security reasons, only the configured Downloads and Incomplete directories can be listed"); } - if (!Directory.Exists(parentDirectory)) + var fullDirectory = Path.Combine(rootDirectory, parentDirectory); + + if (!Directory.Exists(fullDirectory)) { - throw new NotFoundException($"The directory '{parentDirectory}' does not exist"); + throw new NotFoundException($"The directory '{fullDirectory}' does not exist"); } return await Task.Run(() => { - var dir = new DirectoryInfo(parentDirectory); + var dir = new DirectoryInfo(fullDirectory); var contents = dir.GetFileSystemInfos("*", enumerationOptions); @@ -77,16 +80,16 @@ namespace slskd.Files var dirs = contents .OfType() .Prepend(dir) - .Select(d => FilesystemDirectory.FromDirectoryInfo(d) with { Files = files.Where(f => f.Parent == d.FullName) }); + .Select(d => FilesystemDirectory.FromDirectoryInfo(d) with + { + FullName = d.FullName.ReplaceFirst(rootDirectory, string.Empty).TrimStart('\\', '/'), + Files = files + .Where(f => Path.GetDirectoryName(f.FullName) == d.FullName) + .Select(f => f with { FullName = f.FullName.ReplaceFirst(rootDirectory, string.Empty).TrimStart('\\', '/') }), + }); return dirs; }); } - - private bool IsPermissibleDirectory(string dir, Options.DirectoriesOptions options) - { - var allowedRoots = new[] { options.Downloads, options.Incomplete }; - return allowedRoots.Any(r => dir.StartsWith(r)); - } } } \ No newline at end of file diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index 0a750b59..8e7c780a 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -30,13 +30,12 @@ namespace slskd.Files /// Lists the contents in the specified , optionally applying the /// specified . /// - /// The directory from which to start the listing. + /// The root directory. + /// An optional subdirectory from which to start the listing. /// Optional enumeration options to apply. /// The list of found contents. - /// - /// Thrown if the specified directory is not rooted in an allowed directory. - /// /// Thrown if the specified directory does not exist. - Task> ListContentsAsync(string parentDirectory, EnumerationOptions enumerationOptions = null); + /// Thrown if the specified directory is restricted. + Task> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null); } } \ No newline at end of file -- cgit v1.2.3 From e2767eb91ed0e87a4e7d0b60b00226707cfefdfb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 22 Jun 2023 10:00:17 -0500 Subject: tweak endpoints --- src/slskd/Files/API/FilesController.cs | 96 +++++++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 6ee2e7ac..f2f7284d 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Options; namespace slskd.Files.API { using System.Collections.Generic; + using System.ComponentModel.DataAnnotations; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; @@ -46,22 +47,103 @@ namespace slskd.Files.API private IFileService Files { get; } private IOptionsSnapshot OptionsSnapshot { get; } + [HttpGet("downloads")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public async Task GetDownloadContentsAsync([FromQuery] bool recursive = false) + { + try + { + var response = await Files.ListContentsAsync( + rootDirectory: OptionsSnapshot.Value.Directories.Downloads, + enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(response); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + [HttpGet("downloads/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] - public async Task GetDownloadContentsAsync([FromRoute]string base64SubdirectoryName = null, [FromQuery]bool recursive = false) + public async Task GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery]bool recursive = false) { - var dir = OptionsSnapshot.Value.Directories.Downloads; + var decodedDir = base64SubdirectoryName.FromBase64(); - if (!string.IsNullOrEmpty(base64SubdirectoryName)) + try { - var decodedDir = base64SubdirectoryName.FromBase64(); - dir = Path.Combine(dir, decodedDir); + var response = await Files.ListContentsAsync( + rootDirectory: OptionsSnapshot.Value.Directories.Downloads, + parentDirectory: decodedDir, + enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(response); } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("incomplete")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public async Task GetIncompleteContentsAsync([FromQuery] bool recursive = false) + { + try + { + var response = await Files.ListContentsAsync( + rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, + enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = recursive, + }); + + return Ok(response); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("incomplete/{base64SubdirectoryName}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(IEnumerable), 200)] + public async Task GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + { + var decodedDir = base64SubdirectoryName.FromBase64(); try { - var response = await Files.ListContentsAsync(dir, new EnumerationOptions + var response = await Files.ListContentsAsync( + rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, + parentDirectory: decodedDir, + enumerationOptions: new EnumerationOptions { AttributesToSkip = FileAttributes.System, RecurseSubdirectories = recursive, @@ -69,7 +151,7 @@ namespace slskd.Files.API return Ok(response); } - catch (InvalidDirectoryException) + catch (ForbiddenException) { return Forbid(); } -- cgit v1.2.3 From f66c1275239640bac523675f927a5c2d2beeb9ae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jun 2023 12:50:45 -0500 Subject: add OneOf package --- src/slskd/slskd.csproj | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 74fad760..0bc82fda 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -54,6 +54,7 @@ + -- cgit v1.2.3 From 1b0154aa8add61d0cfb072747e97b770e3c57603 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jun 2023 12:51:06 -0500 Subject: make delete operations variadic, return OneOf --- src/slskd/Files/FileService.cs | 109 +++++++++++++++++++++++++++++++++++++--- src/slskd/Files/IFileService.cs | 35 +++++++++++-- 2 files changed, 133 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 7194cc04..f37c861b 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -19,10 +19,12 @@ using Microsoft.Extensions.Options; namespace slskd.Files { + using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; + using OneOf; /// /// Manages files on disk. @@ -38,11 +40,105 @@ namespace slskd.Files OptionsSnapshot = optionsSnapshot; } + private IEnumerable AllowedDirectories => new[] { OptionsSnapshot.Value.Directories.Downloads, OptionsSnapshot.Value.Directories.Incomplete }; private IOptionsSnapshot OptionsSnapshot { get; } /// - /// Lists the contents in the specified , optionally applying the - /// specified . + /// Deletes the specified . + /// + /// + /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are + /// contained in the result, and are not thrown. + /// + /// The root directory. + /// The directories to delete. + /// The operation context. + /// Thrown if a specified directory does not exist. + /// Thrown if a specified directory is restricted. + public async Task>> DeleteDirectoriesAsync(string rootDirectory, params string[] directories) + { + if (!AllowedDirectories.Any(d => rootDirectory == d)) + { + throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); + } + + await Task.Yield(); + + Dictionary> results = new(); + + foreach (var directory in directories) + { + try + { + Directory.Delete(Path.Combine(rootDirectory, directory), recursive: true); + results.Add(directory, true); + } + catch (FileNotFoundException) + { + results.Add(directory, new NotFoundException($"The directory '{directory}' does not exist")); + } + catch (UnauthorizedAccessException) + { + results.Add(directory, new ForbiddenException()); + } + catch (Exception ex) + { + results.Add(directory, ex); + } + } + + return results; + } + + /// + /// Deletes the specified . + /// + /// + /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are + /// contained in the result, and are not thrown. + /// + /// The root directory. + /// The list of files to delete. + /// The operation context. + /// Thrown if a specified file does not exist. + /// Thrown if a specified file is restricted. + public async Task>> DeleteFilesAsync(string rootDirectory, params string[] files) + { + if (!AllowedDirectories.Any(d => rootDirectory == d)) + { + throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); + } + + await Task.Yield(); + + Dictionary> results = new(); + + foreach (var file in files) + { + try + { + File.Delete(Path.Combine(rootDirectory, file)); + results.Add(file, true); + } + catch (FileNotFoundException) + { + results.Add(file, new NotFoundException($"The file '{file}' does not exist")); + } + catch (UnauthorizedAccessException) + { + results.Add(file, new ForbiddenException()); + } + catch (Exception ex) + { + results.Add(file, ex); + } + } + + return results; + } + + /// + /// Lists the contents in the specified , optionally applying the specified . /// /// The root directory. /// An optional subdirectory from which to start the listing. @@ -52,15 +148,12 @@ namespace slskd.Files /// Thrown if the specified directory is restricted. public async Task> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null) { - var configuredDirectories = OptionsSnapshot.Value.Directories; - var allowedDirectories = new[] { configuredDirectories.Incomplete, configuredDirectories.Downloads }; - - if (!allowedDirectories.Any(d => rootDirectory == d)) + if (!AllowedDirectories.Any(d => rootDirectory == d)) { - throw new ForbiddenException($"For security reasons, only the configured Downloads and Incomplete directories can be listed"); + throw new ForbiddenException($"For security reasons, only application-controlled directories can be deleted"); } - var fullDirectory = Path.Combine(rootDirectory, parentDirectory); + var fullDirectory = parentDirectory is not null ? Path.Combine(rootDirectory, parentDirectory) : rootDirectory; if (!Directory.Exists(fullDirectory)) { diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs index 8e7c780a..8e3ddcb7 100644 --- a/src/slskd/Files/IFileService.cs +++ b/src/slskd/Files/IFileService.cs @@ -17,9 +17,11 @@ namespace slskd.Files { + using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; + using OneOf; /// /// Manages files on disk. @@ -27,15 +29,42 @@ namespace slskd.Files public interface IFileService { /// - /// Lists the contents in the specified , optionally applying the - /// specified . + /// Deletes the specified . + /// + /// + /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are + /// contained in the result, and are not thrown. + /// + /// The root directory. + /// The directories to delete. + /// The operation context. + /// Thrown if a specified directory does not exist. + /// Thrown if a specified directory is restricted. + Task>> DeleteDirectoriesAsync(string rootDirectory, params string[] directories); + + /// + /// Deletes the specified . + /// + /// + /// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are + /// contained in the result, and are not thrown. + /// + /// The root directory. + /// The list of files to delete. + /// The operation context. + /// Thrown if a specified file does not exist. + /// Thrown if a specified file is restricted. + Task>> DeleteFilesAsync(string rootDirectory, params string[] files); + + /// + /// Lists the contents in the specified , optionally applying the specified . /// /// The root directory. /// An optional subdirectory from which to start the listing. /// Optional enumeration options to apply. /// The list of found contents. /// Thrown if the specified directory does not exist. - /// Thrown if the specified directory is restricted. + /// Thrown if the specified root directory is restricted. Task> ListContentsAsync(string rootDirectory, string parentDirectory = null, EnumerationOptions enumerationOptions = null); } } \ No newline at end of file -- cgit v1.2.3 From 1017eeee702535bb2c6dd3ea09e5574627a9a7d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Jun 2023 12:55:43 -0500 Subject: implement controller methods --- src/slskd/Files/API/FilesController.cs | 109 +++++++++++++++++++++++++++++++-- 1 file changed, 105 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index f2f7284d..ff8a1707 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -25,6 +25,7 @@ namespace slskd.Files.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using OneOf; /// /// Files. @@ -47,7 +48,7 @@ namespace slskd.Files.API private IFileService Files { get; } private IOptionsSnapshot OptionsSnapshot { get; } - [HttpGet("downloads")] + [HttpGet("downloads/directories")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task GetDownloadContentsAsync([FromQuery] bool recursive = false) @@ -74,7 +75,7 @@ namespace slskd.Files.API } } - [HttpGet("downloads/{base64SubdirectoryName}")] + [HttpGet("downloads/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery]bool recursive = false) @@ -104,7 +105,57 @@ namespace slskd.Files.API } } - [HttpGet("incomplete")] + [HttpDelete("downloads/directories/{base64SubdirectoryName")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 204)] + public async Task DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + { + var decodedDir = base64SubdirectoryName.FromBase64(); + + try + { + var results = await Files.DeleteDirectoriesAsync(OptionsSnapshot.Value.Directories.Downloads, decodedDir); + + return results[decodedDir].Match( + success => NoContent(), + failure => throw failure); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpDelete("downloads/files/{base64Filename}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 204)] + public async Task DeleteDownloadFileAsync([FromRoute] string base64filename) + { + var decodedFilename = base64filename.FromBase64(); + + try + { + var results = await Files.DeleteFilesAsync(OptionsSnapshot.Value.Directories.Downloads, base64filename); + + return results[decodedFilename].Match( + success => NoContent(), + failure => throw failure); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpGet("incomplete/directories")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task GetIncompleteContentsAsync([FromQuery] bool recursive = false) @@ -131,7 +182,7 @@ namespace slskd.Files.API } } - [HttpGet("incomplete/{base64SubdirectoryName}")] + [HttpGet("incomplete/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] public async Task GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) @@ -160,5 +211,55 @@ namespace slskd.Files.API return NotFound(); } } + + [HttpDelete("incomplete/directories/{base64SubdirectoryName")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 204)] + public async Task DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + { + var decodedDir = base64SubdirectoryName.FromBase64(); + + try + { + var results = await Files.DeleteDirectoriesAsync(OptionsSnapshot.Value.Directories.Incomplete, decodedDir); + + return results[decodedDir].Match( + success => NoContent(), + failure => throw failure); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } + + [HttpDelete("incomplete/files/{base64Filename}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(Dictionary>), 204)] + public async Task DeleteIncompleteFileAsync([FromRoute] string base64filename) + { + var decodedFilename = base64filename.FromBase64(); + + try + { + var results = await Files.DeleteFilesAsync(OptionsSnapshot.Value.Directories.Incomplete, base64filename); + + return results[decodedFilename].Match( + success => NoContent(), + failure => throw failure); + } + catch (ForbiddenException) + { + return Forbid(); + } + catch (NotFoundException) + { + return NotFound(); + } + } } } -- cgit v1.2.3 From 0300a0692f6d388f5a1b3d3c23d2a2ee0cf1d18b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Jun 2023 09:20:25 -0500 Subject: add option to enable remote file management --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index cbf59dab..6a36161e 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -1,5 +1,6 @@ # debug: false # remote_configuration: false +# remote_file_management: false # instance_name: default # flags: # no_logo: false diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1d9f814c..c438c03c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -31,7 +31,6 @@ namespace slskd using NetTools; using slskd.Authentication; using slskd.Configuration; - using slskd.Cryptography; using slskd.Relay; using slskd.Shares; using slskd.Validation; @@ -158,6 +157,14 @@ namespace slskd [Description("allow remote configuration")] public bool RemoteConfiguration { get; init; } = false; + /// + /// Gets a value indicating whether remote file management is allowed. + /// + [Argument(default, "remote-file-management")] + [EnvironmentVariable("REMOTE_FILE_MANAGEMENT")] + [Description("allow remote file management")] + public bool RemoteFileManagement { get; init; } = false; + /// /// Gets the unique name for this instance. /// -- cgit v1.2.3 From 197865c54b2eb50c43d71b89f4587955969a0924 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Jun 2023 09:21:01 -0500 Subject: disallow deletes if option isn't enabled --- src/slskd/Files/API/FilesController.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'src') diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index ff8a1707..d39cffbd 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -110,6 +110,11 @@ namespace slskd.Files.API [ProducesResponseType(typeof(Dictionary>), 204)] public async Task DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) { + if (!OptionsSnapshot.Value.RemoteFileManagement) + { + return Forbid(); + } + var decodedDir = base64SubdirectoryName.FromBase64(); try @@ -135,6 +140,11 @@ namespace slskd.Files.API [ProducesResponseType(typeof(Dictionary>), 204)] public async Task DeleteDownloadFileAsync([FromRoute] string base64filename) { + if (!OptionsSnapshot.Value.RemoteFileManagement) + { + return Forbid(); + } + var decodedFilename = base64filename.FromBase64(); try @@ -217,6 +227,11 @@ namespace slskd.Files.API [ProducesResponseType(typeof(Dictionary>), 204)] public async Task DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) { + if (!OptionsSnapshot.Value.RemoteFileManagement) + { + return Forbid(); + } + var decodedDir = base64SubdirectoryName.FromBase64(); try @@ -242,6 +257,11 @@ namespace slskd.Files.API [ProducesResponseType(typeof(Dictionary>), 204)] public async Task DeleteIncompleteFileAsync([FromRoute] string base64filename) { + if (!OptionsSnapshot.Value.RemoteFileManagement) + { + return Forbid(); + } + var decodedFilename = base64filename.FromBase64(); try -- cgit v1.2.3