diff options
| author | Artur <5359825+sethidden@users.noreply.github.com> | 2024-05-30 09:27:41 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-30 09:27:41 +0000 |
| commit | a783e181982dd8c435bb51345a8528a65a4304ac (patch) | |
| tree | 236c9b7bc40ca09cf3f40878a9beb1dea292a20d /src/slskd/Files | |
| parent | 02bf77158d3bf3dcb6919a9bd0637bf040644c26 (diff) | |
| parent | b33449b0282d7f466be22570c26e9e3c982b888a (diff) | |
| download | slskd-a783e181982dd8c435bb51345a8528a65a4304ac.tar.gz | |
Merge branch 'slskd:master' into master
Diffstat (limited to 'src/slskd/Files')
| -rw-r--r-- | src/slskd/Files/API/FilesController.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Files/FileExtensions.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 152 | ||||
| -rw-r--r-- | src/slskd/Files/IFileService.cs | 74 | ||||
| -rw-r--r-- | src/slskd/Files/Types/CreateFileOptions.cs | 31 |
5 files changed, 237 insertions, 86 deletions
diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index b99af658..1ced3e63 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -39,14 +39,14 @@ namespace slskd.Files.API public class FilesController : ControllerBase { public FilesController( - IFileService fileService, + FileService fileService, IOptionsSnapshot<Options> optionsSnapshot) { Files = fileService; OptionsSnapshot = optionsSnapshot; } - private IFileService Files { get; } + private FileService Files { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext<FilesController>(); diff --git a/src/slskd/Files/FileExtensions.cs b/src/slskd/Files/FileExtensions.cs new file mode 100644 index 00000000..4aa7a648 --- /dev/null +++ b/src/slskd/Files/FileExtensions.cs @@ -0,0 +1,62 @@ +// <copyright file="FileExtensions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Files; + +using System; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +/// <summary> +/// Extension methods related to <see cref="Files"/>. +/// </summary> +public static class FileExtensions +{ + /// <summary> + /// Converts the specified <paramref name="permissions"/> string into an instance of <see cref="UnixFileMode"/>. + /// </summary> + /// <param name="permissions">A 3 or 4 character string consisting of only 0-7, matching a Unix file permission (e.g. one used with 'chmod').</param> + /// <returns>The converted UnixFileMode.</returns> + /// <exception cref="ArgumentException">Thrown if the specified <paramref name="permissions"/> string is null or consists of only whitespace.</exception> + /// <exception cref="ArgumentOutOfRangeException">Thrown if the specified <paramref name="permissions"/> are not a 3 or 4 character string consisting of only 0-7.</exception> + public static UnixFileMode ToUnixFileMode(this string permissions) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(permissions, nameof(permissions)); + + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(permissions)) + { + throw new ArgumentOutOfRangeException($"The provided permissions are not a valid, expected 0-7 repeated 3 or 4 times (provided: {permissions})"); + } + + var opts = permissions + .Select(x => int.Parse(x.ToString())) + .Reverse() + .ToArray(); + + int mode = 0; + + for (var i = 0; i < opts.Length; i++) + { + mode |= opts[i] << (i * 3); + } + + return (UnixFileMode)mode; + } +}
\ No newline at end of file diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c820220f..0d193d73 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -23,7 +23,6 @@ namespace slskd.Files using System.Collections.Generic; using System.IO; using System.Linq; - using System.Security; using System.Threading.Tasks; using OneOf; using Serilog; @@ -31,25 +30,25 @@ namespace slskd.Files /// <summary> /// Manages files on disk. /// </summary> - public class FileService : IFileService + public class FileService { /// <summary> /// Initializes a new instance of the <see cref="FileService"/> class. /// </summary> public FileService( - IOptionsSnapshot<Options> optionsSnapshot) + IOptionsMonitor<Options> optionsMonitor) { - OptionsSnapshot = optionsSnapshot; + OptionsMonitor = optionsMonitor; } private IEnumerable<string> AllowedDirectories => new[] { - Path.GetFullPath(OptionsSnapshot.Value.Directories.Downloads), - Path.GetFullPath(OptionsSnapshot.Value.Directories.Incomplete), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), + Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), }; private ILogger Log { get; } = Serilog.Log.ForContext<FileService>(); - private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } /// <summary> /// Deletes the specified <paramref name="directories"/>. @@ -66,7 +65,7 @@ namespace slskd.Files /// </exception> /// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> - public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories) + public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories) { if (directories.Any(directory => Path.GetFullPath(directory) != directory)) { @@ -129,7 +128,7 @@ namespace slskd.Files /// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception> /// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> - public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files) + public virtual async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files) { if (files.Any(file => Path.GetFullPath(file) != file)) { @@ -182,7 +181,7 @@ namespace slskd.Files /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> - public async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { if (Path.GetFullPath(directory) != directory) { @@ -237,5 +236,138 @@ namespace slskd.Files } }); } + + /// <summary> + /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>, + /// returning a <see cref="Stream"/> with which the contents of the file can be written. + /// </summary> + /// <remarks> + /// Reasonable defaults, including the Unix permissions from app configuration, have been applied. Be sure to review the defaults + /// for each new use case and ensure they are appropriate. + /// </remarks> + /// <param name="filename">The fully qualified filename.</param> + /// <param name="options">An optional patch for the underlying <see cref="FileStreamOptions"/>.</param> + /// <returns>A Stream with which the contents of the file can be written.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="IOException">Thrown if the underlying file or Stream can't be created for some reason.</exception> + public virtual Stream CreateFile(string filename, CreateFileOptions options = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + var path = Path.GetDirectoryName(filename); + + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + var streamOptions = new FileStreamOptions + { + Access = options?.Access ?? FileAccess.Write, + BufferSize = options?.BufferSize ?? 4096, // framework default + Mode = options?.Mode ?? FileMode.Create, // overwrite + Options = options?.Options ?? FileOptions.None, // synchronous I/O + PreallocationSize = options?.PreallocationSize ?? 0, + Share = options?.Share ?? FileShare.None, // exclusive access + }; + + // attempting to use UnixCreateMode on Windows raises an Exception + // we *MUST* check the OS and skip this on Windows + if (!OperatingSystem.IsWindows()) + { + var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode; + + // if options haven't been passed in and none have been set in app config, omit this + // so that the application's umask will be applied, saving users the hassle of setting it twice. + if (options?.UnixCreateMode != null || !string.IsNullOrWhiteSpace(appOption)) + { + streamOptions.UnixCreateMode = options?.UnixCreateMode ?? appOption?.ToUnixFileMode(); + Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); + } + } + + try + { + return new FileStream(filename, streamOptions); + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to create file {Path.GetFileName(filename)}: {ex.Message}", ex); + } + } + + /// <summary> + /// Moves the specified fully qualified, localized, <paramref name="sourceFilename"/> to the specified fully qualified, localized, + /// <paramref name="destinationDirectory"/>. + /// </summary> + /// <remarks> + /// If the destination file already exists and the <paramref name="overwrite"/> option is not set, the destination filename will + /// be modified to include the current time to avoid the collision while preserving both files. + /// </remarks> + /// <param name="sourceFilename">The fully qualified filename of the file to move.</param> + /// <param name="destinationDirectory">The fully qualified directory to which to move the source file.</param> + /// <param name="overwrite">An optional value indicating whether the destination file should be overwritten if it already exists.</param> + /// <param name="deleteSourceDirectoryIfEmptyAfterMove"> + /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. + /// </param> + /// <returns>The fully qualified filename of the resulting file.</returns> + /// <exception cref="ArgumentNullException">Thrown if either of the specified file or directories are null or contain only whitespace.</exception> + /// <exception cref="FileNotFoundException">Thrown if the specified <paramref name="sourceFilename"/> does not exist.</exception> + /// <exception cref="IOException">Thrown if the file can't be moved, or the <paramref name="deleteSourceDirectoryIfEmptyAfterMove"/> option is set and the operation fails.</exception> + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); + ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + + if (!File.Exists(sourceFilename)) + { + throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); + } + + if (!Directory.Exists(destinationDirectory)) + { + Directory.CreateDirectory(destinationDirectory); + } + + var destinationFilename = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilename)); + + Log.Debug("Attempting to move {Source} to {Destination}", sourceFilename, destinationFilename); + + if (!overwrite && File.Exists(destinationFilename)) + { + Log.Debug("Destination file {Destination} exists, and overwite option is not set; attempting to generate new filename", destinationFilename); + + string extensionlessFilename = Path.Combine(Path.GetDirectoryName(destinationFilename), Path.GetFileNameWithoutExtension(sourceFilename)); + string extension = Path.GetExtension(sourceFilename); + + while (File.Exists(destinationFilename)) + { + destinationFilename = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; + } + } + + try + { + File.Move(sourceFilename, destinationFilename, overwrite: overwrite); + + Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename); + + // if the parent directory is empty after the move, delete it + if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + + return destinationFilename; + } + catch (Exception ex) + { + // the operation above can throw quite a few exceptions, all granular variations of + // IOException. to make handling downstream easier, wrap them all up and re-throw. + throw new IOException($"Failed to move file {Path.GetFileName(sourceFilename)}: {ex.Message}", ex); + } + } } }
\ No newline at end of file diff --git a/src/slskd/Files/IFileService.cs b/src/slskd/Files/IFileService.cs deleted file mode 100644 index 89d4ce76..00000000 --- a/src/slskd/Files/IFileService.cs +++ /dev/null @@ -1,74 +0,0 @@ -// <copyright file="IFileService.cs" company="slskd Team"> -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// </copyright> - -namespace slskd.Files -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Security; - using System.Threading.Tasks; - using OneOf; - - /// <summary> - /// Manages files on disk. - /// </summary> - public interface IFileService - { - /// <summary> - /// Deletes the specified <paramref name="directories"/>. - /// </summary> - /// <remarks> - /// 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. - /// </remarks> - /// <param name="directories">The directories to delete.</param> - /// <returns>The operation context.</returns> - /// <exception cref="ArgumentException">Thrown if any of the specified directories have a relative path.</exception> - /// <exception cref="ArgumentException"> - /// Thrown if any of the directories is an exact match for an application-controlled directory. - /// </exception> - /// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception> - /// <exception cref="UnauthorizedException">Thrown if a specified directory is restricted.</exception> - Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories); - - /// <summary> - /// Deletes the specified <paramref name="files"/>. - /// </summary> - /// <remarks> - /// 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. - /// </remarks> - /// <param name="files">The list of files to delete.</param> - /// <returns>The operation context.</returns> - /// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception> - /// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception> - /// <exception cref="UnauthorizedException">Thrown if a specified file is restricted.</exception> - Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files); - - /// <summary> - /// Lists the contents in the specified <paramref name="directory"/>, optionally applying the specified <paramref name="enumerationOptions"/>. - /// </summary> - /// <param name="directory">The directory from which to start the listing.</param> - /// <param name="enumerationOptions">Optional enumeration options to apply.</param> - /// <returns>The list of found contents.</returns> - /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> - /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> - /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> - Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null); - } -}
\ No newline at end of file diff --git a/src/slskd/Files/Types/CreateFileOptions.cs b/src/slskd/Files/Types/CreateFileOptions.cs new file mode 100644 index 00000000..26d6e7d4 --- /dev/null +++ b/src/slskd/Files/Types/CreateFileOptions.cs @@ -0,0 +1,31 @@ +// <copyright file="CreateFileOptions.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +namespace slskd.Files; + +using System.IO; + +public record CreateFileOptions +{ + public FileAccess? Access { get; init; } + public int? BufferSize { get; init; } + public FileMode? Mode { get; init; } + public FileOptions? Options { get; init; } + public long? PreallocationSize { get; init; } + public FileShare? Share { get; init; } + public UnixFileMode? UnixCreateMode { get; init; } +}
\ No newline at end of file |
