diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-05-26 20:59:00 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-26 20:59:00 -0500 |
| commit | e2e8fb86f74fdbd1c39820a7ac3adc91d4a5c2a8 (patch) | |
| tree | a6d1ec0e9c8bcef57951924073a905329392ebdd /src | |
| parent | ff841bc6411be74e99b0b71754d23614a59c7187 (diff) | |
| parent | f7fefd065aec5ba3a9b4e679e36a5997924ec591 (diff) | |
| download | slskd-e2e8fb86f74fdbd1c39820a7ac3adc91d4a5c2a8.tar.gz | |
Merge pull request #1128 from slskd/file-perms
Add the ability to configure Unix file permissions to be applied to newly downloaded files
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Core/Options.cs | 57 | ||||
| -rw-r--r-- | src/slskd/Files/FileExtensions.cs | 62 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 143 | ||||
| -rw-r--r-- | src/slskd/Files/Types/CreateFileOptions.cs | 31 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 71 |
6 files changed, 310 insertions, 56 deletions
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81dc09f6..f2419c83 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -210,6 +210,12 @@ namespace slskd public RelayOptions Relay { get; init; } = new RelayOptions(); /// <summary> + /// Gets permission options. + /// </summary> + [Validate] + public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + + /// <summary> /// Gets directory options. /// </summary> [Validate] @@ -603,6 +609,57 @@ namespace slskd } /// <summary> + /// Permission options. + /// </summary> + public class PermissionsOptions + { + /// <summary> + /// Gets file permission options. + /// </summary> + [Validate] + public FileOptions File { get; init; } = new FileOptions(); + + /// <summary> + /// File permission options. + /// </summary> + public class FileOptions : IValidatableObject + { + /// <summary> + /// Gets the permissions to apply to newly created files. + /// </summary> + /// <remarks> + /// Applicable to non-Windows operating systems, only. + /// </remarks> + [Argument(default, "file-permission-mode")] + [EnvironmentVariable("FILE_PERMISSION_MODE")] + [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] + public string Mode { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (!string.IsNullOrEmpty(Mode)) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Mode)) + { + results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + } + + return results; + } + } + } + + /// <summary> /// Directory options. /// </summary> public class DirectoriesOptions 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 ee8271b1..0d193d73 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -36,19 +36,19 @@ namespace slskd.Files /// 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"/>. @@ -236,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/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 diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 545a80ab..27cbfc6f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -590,7 +590,7 @@ namespace slskd services.AddSingleton<ITransferService, TransferService>(); services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); - services.AddTransient<FileService>(); + services.AddSingleton<FileService>(); services.AddSingleton<IRelayService, RelayService>(); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 57a78a1f..32903bf9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -23,13 +23,13 @@ namespace slskd.Transfers.Downloads using System; using System.Collections.Concurrent; using System.Collections.Generic; - using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; @@ -120,12 +120,14 @@ namespace slskd.Transfers.Downloads IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, + FileService fileService, IRelayService relayService, IFTPService ftpClient) { Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; + Files = fileService; FTP = ftpClient; Relay = relayService; } @@ -134,6 +136,7 @@ namespace slskd.Transfers.Downloads private ISoulseekClient Client { get; } private IDbContextFactory<TransfersDbContext> ContextFactory { get; } private IFTPService FTP { get; } + private FileService Files { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -285,7 +288,18 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Client.DownloadAsync( username: username, remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult(GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete)), + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null, + })), size: file.Size, startOffset: 0, token: null, @@ -304,7 +318,11 @@ namespace slskd.Transfers.Downloads // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could // argue both ways for that being the correct behavior. revisit this later. - var finalFilename = MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + var finalFilename = Files.MoveFile( + sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file to {Destination}", finalFilename); @@ -587,52 +605,5 @@ namespace slskd.Transfers.Downloads context.Update(transfer); context.SaveChanges(); } - - private static Stream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - return new FileStream(localFilename, FileMode.Create); - } - - private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!Directory.Exists(destinationPath)) - { - Directory.CreateDirectory(destinationPath); - } - - if (File.Exists(destinationFilename)) - { - string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), 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()) - { - Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - - return destinationFilename; - } } }
\ No newline at end of file |
