From 25245ca526b436b00b2150c02e0eb946df548e93 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 8 May 2024 22:44:52 -0500 Subject: stub options --- src/slskd/Core/Options.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81dc09f6..3fef8a94 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,6 +209,12 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); + /// + /// Gets file options. + /// + [Validate] + public FilesOptions Files { get; init; } = new FilesOptions(); + /// /// Gets directory options. /// @@ -602,6 +608,33 @@ namespace slskd } } + /// + /// File options. + /// + public class FilesOptions : IValidatableObject + { + public string Permissions { get; init; } + public string Umask { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); + var results = new List(); + + if (!string.IsNullOrEmpty(Permissions) && !regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + } + + if (!string.IsNullOrEmpty(Umask) && !regEx.IsMatch(Umask)) + { + results.Add(new ValidationResult($"Field {nameof(Umask)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + } + + return results; + } + } + /// /// Directory options. /// -- cgit v1.2.3 From 6f652112800cc3de11c1ce0eaca3162b2179d02b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 May 2024 22:30:17 -0500 Subject: docs, remove umask --- src/slskd/Core/Options.cs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3fef8a94..81e73403 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -613,22 +613,30 @@ namespace slskd /// public class FilesOptions : IValidatableObject { - public string Permissions { get; init; } - public string Umask { get; init; } + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [Argument(default, "file-permissions")] + [EnvironmentVariable("FILE_PERMISSIONS")] + [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] + public string Permissions { get; init; } = "644"; + /// + /// Extended validation. + /// + /// + /// public IEnumerable Validate(ValidationContext validationContext) { var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); var results = new List(); - if (!string.IsNullOrEmpty(Permissions) && !regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); - } - - if (!string.IsNullOrEmpty(Umask) && !regEx.IsMatch(Umask)) + if (!regEx.IsMatch(Permissions)) { - results.Add(new ValidationResult($"Field {nameof(Umask)} is invalid. Specify a three-character string consisting of only 0-7 (000-777, inclusive)")); + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (chmod syntax, 000-777, inclusive)")); } return results; -- cgit v1.2.3 From 28c2c7cbe76b215c605e1b510cee34270596cf27 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 13:19:36 -0500 Subject: stub creation logic --- src/slskd/Transfers/Downloads/DownloadService.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 57a78a1f..a8269b49 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -598,7 +598,18 @@ namespace slskd.Transfers.Downloads Directory.CreateDirectory(path); } - return new FileStream(localFilename, FileMode.Create); + var options = new FileStreamOptions + { + Mode = FileMode.Create, + Access = FileAccess.Write, + }; + + if (!OperatingSystem.IsWindows()) + { + options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; + } + + return new FileStream(localFilename, options); } private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) -- cgit v1.2.3 From f54a5ec419bdbcddcaea760c984df7cc47005905 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:11:26 -0500 Subject: rough in create/move --- src/slskd/Files/FileService.cs | 120 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index ee8271b1..67488491 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -236,5 +236,125 @@ namespace slskd.Files } }); } + + /// + /// Creates a new file with the specified fully qualified and the optional , + /// returning a with which the contents of the file can be written. + /// + /// + /// 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. + /// + /// The fully qualified filename. + /// An optional patch for the underlying . + /// A Stream with which the contents of the file can be written. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the underlying file or Stream can't be created for some reason. + 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()) + { + streamOptions.UnixCreateMode = options?.UnixCreateMode ?? UnixFileMode.None; // todo: substitute default from options + } + + 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); + } + } + + /// + /// Moves the specified fully qualified, localized, to the specified fully qualified, localized, + /// . + /// + /// + /// If the destination file already exists and the option is not set, the destination filename will + /// be modified to include the current time to avoid the collision while preserving both files. + /// + /// The fully qualified filename of the file to move. + /// The fully qualified directory to which to move the source file. + /// An optional value indicating whether the destination file should be overwritten if it already exists. + /// + /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. + /// + /// The fully qualified filename of the resulting file. + /// Thrown if either of the specified file or directories are null or contain only whitespace. + /// Thrown if the specified does not exist. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = true) + { + 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 filename = Path.GetFileName(sourceFilename); // without directory + var destinationFilename = Path.Combine(destinationDirectory, filename); + + if (!overwrite && 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); + } + } + + try + { + File.Move(sourceFilename, destinationFilename, overwrite: overwrite); + + // if the parent directory is empty after the move, delete it + if (deleteEmptiedParentDirectory && !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(filename)}: {ex.Message}", ex); + } + } } } \ No newline at end of file -- cgit v1.2.3 From 3ddbba90fbbe67e2ca6f2d58a09c578efefa8f3d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:13:08 -0500 Subject: docs, default delete to false --- src/slskd/Files/FileService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 67488491..c3da7621 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -307,7 +307,8 @@ namespace slskd.Files /// The fully qualified filename of the resulting file. /// Thrown if either of the specified file or directories are null or contain only whitespace. /// Thrown if the specified does not exist. - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = true) + /// Thrown if the file can't be moved, or the option is set and the operation fails. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); -- cgit v1.2.3 From 7fe5b89ad8a211d0e1be1bd10a477ad9f7db51f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:13:18 -0500 Subject: add CreateFileOptions --- src/slskd/Files/Types/CreateFileOptions.cs | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/slskd/Files/Types/CreateFileOptions.cs (limited to 'src') 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 (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.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 -- cgit v1.2.3 From 2c8a0d34b4bc89a0f51cdd0e5667cc4fa8ee5424 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:15:13 -0500 Subject: temporarily comment old create/move --- src/slskd/Transfers/Downloads/DownloadService.cs | 116 +++++++++++------------ 1 file changed, 58 insertions(+), 58 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a8269b49..bf036e48 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -588,62 +588,62 @@ namespace slskd.Transfers.Downloads 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); - } - - var options = new FileStreamOptions - { - Mode = FileMode.Create, - Access = FileAccess.Write, - }; - - if (!OperatingSystem.IsWindows()) - { - options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; - } - - return new FileStream(localFilename, options); - } - - 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; - } + // 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); + // } + + // var options = new FileStreamOptions + // { + // Mode = FileMode.Create, + // Access = FileAccess.Write, + // }; + + // if (!OperatingSystem.IsWindows()) + // { + // options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; + // } + + // return new FileStream(localFilename, options); + // } + + // private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) + // { + // var sourceFilename = filename.ToLocalFilename(baseDirectory: sourceDirectory); + // var destinationFilename = filename.ToLocalFilename(baseDirectory: 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 -- cgit v1.2.3 From e0874640202c2a978685bdc8c19e05ce049b081b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:15:40 -0500 Subject: inject FileService --- src/slskd/Transfers/Downloads/DownloadService.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf036e48..41fb45ee 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -120,12 +120,14 @@ namespace slskd.Transfers.Downloads IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory 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 ContextFactory { get; } private IFTPService FTP { get; } + private FileService Files { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } -- cgit v1.2.3 From 45907e3a8547bdfe59e6e829aec91af934c5367e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:16:09 -0500 Subject: use FileService --- src/slskd/Transfers/Downloads/DownloadService.cs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 41fb45ee..8ec7def2 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -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; @@ -288,7 +288,16 @@ 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 = System.IO.UnixFileMode.None, // todo: replace with options + })), size: file.Size, startOffset: 0, token: null, @@ -307,7 +316,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: OptionsMonitor.CurrentValue.Directories.Downloads, + overwrite: false, + deleteEmptiedParentDirectory: true); Log.Debug("Moved file to {Destination}", finalFilename); -- cgit v1.2.3 From e4c20ae1a67dc6d03db6f3a6f6e8eac1c612d3f3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 May 2024 19:27:45 -0500 Subject: make FileService singleton --- src/slskd/Files/FileService.cs | 10 +++++----- src/slskd/Program.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c3da7621..18bf72d1 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 class. /// public FileService( - IOptionsSnapshot optionsSnapshot) + IOptionsMonitor optionsMonitor) { - OptionsSnapshot = optionsSnapshot; + OptionsMonitor = optionsMonitor; } private IEnumerable 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(); - private IOptionsSnapshot OptionsSnapshot { get; } + private IOptionsMonitor OptionsMonitor { get; } /// /// Deletes the specified . 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(); services.AddSingleton(); services.AddSingleton(); - services.AddTransient(); + services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From dbccaefb3c50ae67f671c91f88d088972d6a7f57 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 15:29:07 -0500 Subject: preserve remote directory --- src/slskd/Files/FileService.cs | 26 ++++++++++++++---------- src/slskd/Transfers/Downloads/DownloadService.cs | 6 +++--- 2 files changed, 18 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 18bf72d1..e5ce63f9 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -301,14 +301,14 @@ namespace slskd.Files /// The fully qualified filename of the file to move. /// The fully qualified directory to which to move the source file. /// An optional value indicating whether the destination file should be overwritten if it already exists. - /// + /// /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. /// /// The fully qualified filename of the resulting file. /// Thrown if either of the specified file or directories are null or contain only whitespace. /// Thrown if the specified does not exist. - /// Thrown if the file can't be moved, or the option is set and the operation fails. - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteEmptiedParentDirectory = false) + /// Thrown if the file can't be moved, or the option is set and the operation fails. + public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); @@ -323,18 +323,20 @@ namespace slskd.Files Directory.CreateDirectory(destinationDirectory); } - var filename = Path.GetFileName(sourceFilename); // without directory - var destinationFilename = Path.Combine(destinationDirectory, filename); + var destinationFilename = Path.Combine(destinationDirectory, Path.GetFileName(sourceFilename)); + + Log.Debug("Attempting to move {Source} to {Destination}", sourceFilename, destinationFilename); if (!overwrite && File.Exists(destinationFilename)) { - string extensionlessFilename = Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename)); - string extension = Path.GetExtension(filename); + 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)) { - string filenameUTC = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; - destinationFilename = filenameUTC.ToLocalFilename(destinationDirectory); + destinationFilename = $"{extensionlessFilename}_{DateTime.UtcNow.Ticks}{extension}"; } } @@ -342,8 +344,10 @@ namespace slskd.Files { 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 (deleteEmptiedParentDirectory && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) { Directory.Delete(Path.GetDirectoryName(sourceFilename)); } @@ -354,7 +358,7 @@ namespace slskd.Files { // 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(filename)}: {ex.Message}", ex); + throw new IOException($"Failed to move file {Path.GetFileName(sourceFilename)}: {ex.Message}", ex); } } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8ec7def2..90d40b22 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -318,9 +318,9 @@ namespace slskd.Transfers.Downloads // argue both ways for that being the correct behavior. revisit this later. var finalFilename = Files.MoveFile( sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: OptionsMonitor.CurrentValue.Directories.Downloads, + destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), overwrite: false, - deleteEmptiedParentDirectory: true); + deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file to {Destination}", finalFilename); -- cgit v1.2.3 From 91133c53779c19590586139231537a2ef3df1da0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 15:29:20 -0500 Subject: remove deprecated code --- src/slskd/Transfers/Downloads/DownloadService.cs | 60 +----------------------- 1 file changed, 1 insertion(+), 59 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 90d40b22..8d06fcec 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -603,63 +603,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); - // } - - // var options = new FileStreamOptions - // { - // Mode = FileMode.Create, - // Access = FileAccess.Write, - // }; - - // if (!OperatingSystem.IsWindows()) - // { - // options.UnixCreateMode = UnixFileMode.GroupExecute | UnixFileMode.GroupRead | UnixFileMode.UserRead | UnixFileMode.UserExecute; - // } - - // return new FileStream(localFilename, options); - // } - - // private static string MoveFile(string filename, string sourceDirectory, string destinationDirectory) - // { - // var sourceFilename = filename.ToLocalFilename(baseDirectory: sourceDirectory); - // var destinationFilename = filename.ToLocalFilename(baseDirectory: 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 -- cgit v1.2.3 From 9db3b39cf1f606f80fb15872aa5a8a7e9ff0baad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 17:58:22 -0500 Subject: allow 4 character perms --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 81e73403..37b333ba 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -631,7 +631,7 @@ namespace slskd /// public IEnumerable Validate(ValidationContext validationContext) { - var regEx = new Regex("[0-7]{3}", RegexOptions.Compiled); + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); var results = new List(); if (!regEx.IsMatch(Permissions)) -- cgit v1.2.3 From cb17718d1e072bd41d014f22f4804ff48f82996e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:06 -0500 Subject: add extension ToUnixFileMode --- src/slskd/Files/FileExtensions.cs | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/slskd/Files/FileExtensions.cs (limited to 'src') 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 (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; +using System.Linq; +using System.Text.RegularExpressions; + +/// +/// Extension methods related to . +/// +public static class FileExtensions +{ + /// + /// Converts the specified string into an instance of . + /// + /// A 3 or 4 character string consisting of only 0-7, matching a Unix file permission (e.g. one used with 'chmod'). + /// The converted UnixFileMode. + /// Thrown if the specified string is null or consists of only whitespace. + /// Thrown if the specified are not a 3 or 4 character string consisting of only 0-7. + 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 -- cgit v1.2.3 From c00096d90e14d391272919c102eda702a0a2b35a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:09:42 -0500 Subject: use configured permissions when creating files --- src/slskd/Files/FileService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index e5ce63f9..af8f4111 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,7 +275,9 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - streamOptions.UnixCreateMode = options?.UnixCreateMode ?? UnixFileMode.None; // todo: substitute default from options + streamOptions.UnixCreateMode = options?.UnixCreateMode + ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() + ?? UnixFileMode.None; } try -- cgit v1.2.3 From ac66a8f6fbe9d49d4ed1f6cc8808ee75f92e62d0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 22:30:59 -0500 Subject: add log --- src/slskd/Files/FileService.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index af8f4111..91dadba6 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -278,6 +278,8 @@ namespace slskd.Files streamOptions.UnixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() ?? UnixFileMode.None; + + Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); } try -- cgit v1.2.3 From ad43047f4f57a26d0ab5225f22b2a78ab491a12c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 22:31:10 -0500 Subject: send correct perms --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8d06fcec..f848928f 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,7 @@ namespace slskd.Transfers.Downloads 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 = System.IO.UnixFileMode.None, // todo: replace with options + UnixCreateMode = OptionsMonitor.CurrentValue.Files.Permissions.ToUnixFileMode(), })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From d221780782481d931daa11b04e14229accceee6d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 May 2024 18:27:32 -0500 Subject: move config under Global --- config/slskd.example.yml | 4 +- src/slskd/Core/Options.cs | 82 ++++++++++++------------ src/slskd/Files/FileService.cs | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 4 files changed, 45 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 3d79f05d..7dedebd6 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,8 +32,6 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: # cidr: 0.0.0.0/0,::/0 -# files: -# permissions: 644 # directories: # incomplete: ~ # downloads: ~ @@ -69,6 +67,8 @@ # download: # slots: 500 # speed_limit: 1000 +# file: +# permissions: 644 # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 37b333ba..e67be138 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,12 +209,6 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); - /// - /// Gets file options. - /// - [Validate] - public FilesOptions Files { get; init; } = new FilesOptions(); - /// /// Gets directory options. /// @@ -608,41 +602,6 @@ namespace slskd } } - /// - /// File options. - /// - public class FilesOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly created files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - [Argument(default, "file-permissions")] - [EnvironmentVariable("FILE_PERMISSIONS")] - [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } = "644"; - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); - var results = new List(); - - if (!regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three-character string consisting of only 0-7 (chmod syntax, 000-777, inclusive)")); - } - - return results; - } - } - /// /// Directory options. /// @@ -894,6 +853,47 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; + + /// + /// Gets downloaded file options. + /// + [Validate] + public GlobalDownloadFileOptions File { get; init; } = new GlobalDownloadFileOptions(); + } + + /// + /// File options. + /// + public class GlobalDownloadFileOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly downloaded files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [Argument(default, "downloaded-file-permissions")] + [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] + [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] + public string Permissions { get; init; } = "644"; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + var results = new List(); + + if (!regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + + return results; + } } } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 91dadba6..3bcdd04f 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -276,7 +276,7 @@ namespace slskd.Files if (!OperatingSystem.IsWindows()) { streamOptions.UnixCreateMode = options?.UnixCreateMode - ?? OptionsMonitor.CurrentValue.Files.Permissions?.ToUnixFileMode() + ?? OptionsMonitor.CurrentValue.Global.Download.File.Permissions?.ToUnixFileMode() ?? UnixFileMode.None; Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f848928f..e6410691 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,7 @@ namespace slskd.Transfers.Downloads 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 = OptionsMonitor.CurrentValue.Files.Permissions.ToUnixFileMode(), + UnixCreateMode = OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode(), })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From 65337c147088318961e58c549a90ab79dfa51b44 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 May 2024 14:18:50 -0500 Subject: default file permissions to nothing (use umask) --- src/slskd/Core/Options.cs | 12 ++++++++---- src/slskd/Files/FileService.cs | 12 ++++++++---- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +++- 3 files changed, 19 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e67be138..e7462848 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -875,7 +875,7 @@ namespace slskd [Argument(default, "downloaded-file-permissions")] [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } = "644"; + public string Permissions { get; init; } /// /// Extended validation. @@ -884,12 +884,16 @@ namespace slskd /// public IEnumerable Validate(ValidationContext validationContext) { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); var results = new List(); - if (!regEx.IsMatch(Permissions)) + if (!string.IsNullOrEmpty(Permissions)) { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Permissions)) + { + results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } } return results; diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 3bcdd04f..d9aa9dc3 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,11 +275,15 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - streamOptions.UnixCreateMode = options?.UnixCreateMode - ?? OptionsMonitor.CurrentValue.Global.Download.File.Permissions?.ToUnixFileMode() - ?? UnixFileMode.None; + var appOption = OptionsMonitor.CurrentValue.Global.Download.File.Permissions; - Log.Debug("Setting Unix file mode to {Mode}", streamOptions.UnixCreateMode); + // 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 diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e6410691..bdd7ebed 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,7 +296,9 @@ namespace slskd.Transfers.Downloads 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 = OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode(), + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Global.Download.File.Permissions) + ? OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode() + : null, })), size: file.Size, startOffset: 0, -- cgit v1.2.3 From 79cd6c0033631b33e9508b7c10e48b9edfafe21d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 May 2024 21:40:47 -0500 Subject: move options once again --- src/slskd/Core/Options.cs | 102 +++++++++++++---------- src/slskd/Files/FileService.cs | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +- 3 files changed, 60 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e7462848..f2419c83 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -209,6 +209,12 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); + /// + /// Gets permission options. + /// + [Validate] + public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + /// /// Gets directory options. /// @@ -602,6 +608,57 @@ namespace slskd } } + /// + /// Permission options. + /// + public class PermissionsOptions + { + /// + /// Gets file permission options. + /// + [Validate] + public FileOptions File { get; init; } = new FileOptions(); + + /// + /// File permission options. + /// + public class FileOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + [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; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } + /// /// Directory options. /// @@ -853,51 +910,6 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; - - /// - /// Gets downloaded file options. - /// - [Validate] - public GlobalDownloadFileOptions File { get; init; } = new GlobalDownloadFileOptions(); - } - - /// - /// File options. - /// - public class GlobalDownloadFileOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly downloaded files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - [Argument(default, "downloaded-file-permissions")] - [EnvironmentVariable("DOWNLOADED_FILE_PERMISSIONS")] - [Description("the permissions to apply to newly downloaded files (chmod syntax, non-Windows only)")] - public string Permissions { get; init; } - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - if (!string.IsNullOrEmpty(Permissions)) - { - var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); - - if (!regEx.IsMatch(Permissions)) - { - results.Add(new ValidationResult($"Field {nameof(Permissions)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); - } - } - - return results; - } } } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index d9aa9dc3..0d193d73 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -275,7 +275,7 @@ namespace slskd.Files // we *MUST* check the OS and skip this on Windows if (!OperatingSystem.IsWindows()) { - var appOption = OptionsMonitor.CurrentValue.Global.Download.File.Permissions; + 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. diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bdd7ebed..32903bf9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -296,8 +296,8 @@ namespace slskd.Transfers.Downloads 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.Global.Download.File.Permissions) - ? OptionsMonitor.CurrentValue.Global.Download.File.Permissions.ToUnixFileMode() + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null, })), size: file.Size, -- cgit v1.2.3