From 0da8e151297fd2ea123e0e59b7928171b2006d9e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 8 May 2024 22:00:54 -0500 Subject: add example file perm config --- config/slskd.example.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f4839e6d..f3871b5a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -35,6 +35,8 @@ # directories: # incomplete: ~ # downloads: ~ +# files: +# permissions: 655 # shares: # directories: # - ~ -- cgit v1.2.3 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(+) 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 a30d5fb6d9fb3ce582f62b58af0d36dccb906869 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 May 2024 22:30:01 -0500 Subject: tweak example --- config/slskd.example.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f3871b5a..3d79f05d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,11 +32,11 @@ # 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: ~ -# files: -# permissions: 655 # shares: # directories: # - ~ -- 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(-) 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(-) 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(+) 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(-) 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 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(-) 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(+) 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(-) 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(-) 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(-) 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(-) 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(-) 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 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 ce69e9b95349d71c05ff53eebcd92ad01ab431a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:36 -0500 Subject: add ToUnixFileMode tests --- .../slskd.Tests.Unit/Files/FileExtensionsTests.cs | 71 ++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs diff --git a/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs new file mode 100644 index 00000000..c270bb31 --- /dev/null +++ b/tests/slskd.Tests.Unit/Files/FileExtensionsTests.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using slskd.Files; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class FileExtensionsTests +{ + [Theory] + [InlineData("0000", UnixFileMode.None)] + [InlineData("0100", UnixFileMode.UserExecute)] + [InlineData("0200", UnixFileMode.UserWrite)] + [InlineData("0300", UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0400", UnixFileMode.UserRead)] + [InlineData("0500", UnixFileMode.UserRead | UnixFileMode.UserExecute)] + [InlineData("0600", UnixFileMode.UserRead | UnixFileMode.UserWrite)] + [InlineData("0700", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute)] + [InlineData("0010", UnixFileMode.GroupExecute)] + [InlineData("0020", UnixFileMode.GroupWrite)] + [InlineData("0030", UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0040", UnixFileMode.GroupRead)] + [InlineData("0050", UnixFileMode.GroupRead | UnixFileMode.GroupExecute)] + [InlineData("0060", UnixFileMode.GroupRead | UnixFileMode.GroupWrite)] + [InlineData("0070", UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute)] + [InlineData("0001", UnixFileMode.OtherExecute)] + [InlineData("0002", UnixFileMode.OtherWrite)] + [InlineData("0003", UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0004", UnixFileMode.OtherRead)] + [InlineData("0005", UnixFileMode.OtherRead | UnixFileMode.OtherExecute)] + [InlineData("0006", UnixFileMode.OtherRead | UnixFileMode.OtherWrite)] + [InlineData("0007", UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)] + [InlineData("0644", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead)] + [InlineData("0777", UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + [InlineData("1000", UnixFileMode.StickyBit)] + [InlineData("2000", UnixFileMode.SetGroup)] + [InlineData("3000", UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("4000", UnixFileMode.SetUser)] + [InlineData("5000", UnixFileMode.SetUser | UnixFileMode.StickyBit)] + [InlineData("6000", UnixFileMode.SetUser | UnixFileMode.SetGroup)] + [InlineData("7000", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit)] + [InlineData("7777", UnixFileMode.SetUser | UnixFileMode.SetGroup | UnixFileMode.StickyBit | UnixFileMode.UserExecute | UnixFileMode.UserWrite | UnixFileMode.UserRead | UnixFileMode.GroupExecute | UnixFileMode.GroupWrite | UnixFileMode.GroupRead | UnixFileMode.OtherExecute | UnixFileMode.OtherWrite | UnixFileMode.OtherRead)] + public void ToUnixFileMode_Works_As_Expected(string permissions, UnixFileMode expected) + { + var result = permissions.ToUnixFileMode(); + + Assert.Equal(expected, result); + } + + [Fact] + public void ToUinixFileMode_Throws_ArgumentException_Given_Empty() + { + var ex = Record.Exception(() => "".ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("0")] + [InlineData("00")] + [InlineData("00000")] + [InlineData("foo bar baz")] + public void ToUinixFileMode_Throws_ArgumentOutOfRangeException_Given_Bad_String(string str) + { + var ex = Record.Exception(() => str.ToUnixFileMode()); + + Assert.NotNull(ex); + Assert.IsType(ex); + } +} \ No newline at end of file -- cgit v1.2.3 From 4f17a9558688d172c2c01400cadeed855a536778 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 May 2024 18:02:42 -0500 Subject: fix FileServiceTests --- tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index 917d1a43..6c3d1d73 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -13,13 +13,13 @@ namespace slskd.Tests.Unit.Files { public FileServiceTests() { - OptionsSnapshotMock = new Mock>(); + OptionsMonitorMock = new Mock>(); Temp = Path.Combine(Path.GetTempPath(), $"slskd.test.{Guid.NewGuid()}"); Directory.CreateDirectory(Temp); FileService = new FileService( - optionsSnapshot: OptionsSnapshotMock.Object); + optionsMonitor: OptionsMonitorMock.Object); } public void Dispose() @@ -27,7 +27,7 @@ namespace slskd.Tests.Unit.Files Directory.Delete(Temp, recursive: true); } - private Mock> OptionsSnapshotMock { get; init; } + private Mock> OptionsMonitorMock { get; init; } private string Temp { get; init; } private FileService FileService { get; init; } @@ -44,7 +44,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_UnauthorizedException_Given_Disallowed_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -62,7 +62,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_NotFoundException_Given_NonExistent_Directory() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -90,7 +90,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteDirectoriesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { @@ -118,7 +118,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task DeleteFilesAsync_Throws_ArgumentException_Given_Disallowed_Path() { - OptionsSnapshotMock.Setup(o => o.Value).Returns(new Options + OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { Directories = new Options.DirectoriesOptions { -- 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(-) 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(+) 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(-) 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(-) 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 2e278a5f0651ac70324557c12e0388fd1de3159d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 May 2024 18:53:04 -0500 Subject: add permissions to docs --- docs/config.md | 53 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/docs/config.md b/docs/config.md index f81fe8c0..9e08e8c4 100644 --- a/docs/config.md +++ b/docs/config.md @@ -272,11 +272,39 @@ relay: downloads: false ``` -# Limits and User Groups +# Upload/Download Configuration, Limits and User Groups -## Global Slot and Speed Limits +## Downloads -Global slot and speed behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. +A hard limit for download slots can be set to limit the number of concurrent downloads. Upon reaching the limit, additional downloads will be queued locally (and thus a remote queue position will not be obtained). There is no slot limit by default. + +A download speed limit can be set to limit the total amount of network bandwidth consumed by downloads. When configured, this bandwidth is split among all active downloads. There is no speed limit by default. + +A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. + +Unix file permissions can be configured and applied to newly downloaded files. The permission syntax is the same as the syntax used by the [chmod](https://en.wikipedia.org/wiki/Chmod) utility, accepting a numeric string of 3 or 4 numbers, each from 0 to 7. Unix file permissions are only applied when the application is running on a unix-like operating system (effectively, everything except Windows). The default permissions are 644, translating to read/write permissions for the owner (the user under which the application runs), read only for the owner's group, and read only for all other users. + +| Command-Line | Environment Variable | Description | +| ------------------------------- | ------------------------------------| ----------------------------------------------------------- | +| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | +| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | +| `--downloaded-file-permissions` | `SLSKD_DOWNLOADED_FILE_PERMISSIONS` | The Unix file permissions to be applied to downloaded files | + +#### **YAML** +```yaml +global: + download: + slots: 500 + speed_limit: 1000 # kibibytes + file: + permissions: 644 +``` + +## Uploads + +### Global Slot and Speed Limits + +Global upload slot and speed limits behave as hard limits, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. @@ -284,8 +312,6 @@ A change to slot limits requires an application restart to take effect, while sp | ------------------------ | ---------------------------- | ------------------------------------------------ | | `--upload-slots` | `SLSKD_UPLOAD_SLOTS` | The limit for the total number of upload slots | | `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit, in kibibytes | -| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | -| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | #### **YAML** ```yaml @@ -293,12 +319,9 @@ global: upload: slots: 20 speed_limit: 1000 # kibibytes - download: - slots: 500 - speed_limit: 1000 ``` -## Global Upload Limits +### Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. @@ -327,7 +350,7 @@ global: failures: 1000 ``` -## Groups +### Groups User groups are used to control upload slots, speed limits, and queue behavior on a per-user basis. @@ -362,7 +385,7 @@ limits: failures: 1000 ``` -## Built-In Groups +### Built-In Groups The `default` built-in group contains all users who have not been explicitly added to a user-defined group, are not privileged, and haven't been identified as leechers. @@ -415,7 +438,7 @@ groups: failures: 30 ``` -## User Blacklist +### User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -441,7 +464,7 @@ groups: - ``` -## User Defined Groups +### User Defined Groups In the group configuration, any number of user-defined groups can be added under the `user_defined` key. @@ -467,7 +490,7 @@ groups: - alice ``` -## Example +### Example In the following example: @@ -506,7 +529,7 @@ groups: - bob ``` -## Managed Blacklist +# Managed Blacklist A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. -- cgit v1.2.3 From 57b0a10b294d89659fba11ba616b1afdefd82d5e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 May 2024 14:07:41 -0500 Subject: add SLSKD_UMASK --- Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 9ffcc2a1..07278892 100644 --- a/Dockerfile +++ b/Dockerfile @@ -63,6 +63,7 @@ ENV DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \ DOTNET_gcConcurrent=1 \ DOTNET_GCHeapHardLimit=1F400000 \ DOTNET_GCConserveMemory=9 \ + SLSKD_UMASK=0022 \ SLSKD_HTTP_PORT=5030 \ SLSKD_HTTPS_PORT=5031 \ SLSKD_SLSK_LISTEN_PORT=50300 \ @@ -87,4 +88,7 @@ LABEL org.opencontainers.image.title=slskd \ WORKDIR /slskd COPY --from=publish /slskd/dist/${TARGETPLATFORM} . -ENTRYPOINT ["/usr/bin/tini", "--", "./slskd"] +RUN echo "umask \$SLSKD_UMASK && ./slskd" > start.sh \ + && chmod +x start.sh + +ENTRYPOINT ["/usr/bin/tini", "--", "./start.sh"] -- 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(-) 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(-) 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 From 4f50d184c8923d975e5930a66a6385683823ef77 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 May 2024 20:32:46 -0500 Subject: update example --- config/slskd.example.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7dedebd6..f1e1b4ab 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -32,6 +32,9 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: # cidr: 0.0.0.0/0,::/0 +# permissions: +# file: +# mode: ~ # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask # directories: # incomplete: ~ # downloads: ~ @@ -67,8 +70,6 @@ # download: # slots: 500 # speed_limit: 1000 -# file: -# permissions: 644 # groups: # default: # upload: -- cgit v1.2.3 From 29faa7d07a11862fd4fb51a84df98c9a53d70625 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 May 2024 20:38:18 -0500 Subject: revert docs --- docs/config.md | 55 ++++++++++++++++--------------------------------------- 1 file changed, 16 insertions(+), 39 deletions(-) diff --git a/docs/config.md b/docs/config.md index 9e08e8c4..bed6d2d6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -272,39 +272,11 @@ relay: downloads: false ``` -# Upload/Download Configuration, Limits and User Groups +# Limits and User Groups -## Downloads +## Global Slot and Speed Limits -A hard limit for download slots can be set to limit the number of concurrent downloads. Upon reaching the limit, additional downloads will be queued locally (and thus a remote queue position will not be obtained). There is no slot limit by default. - -A download speed limit can be set to limit the total amount of network bandwidth consumed by downloads. When configured, this bandwidth is split among all active downloads. There is no speed limit by default. - -A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. - -Unix file permissions can be configured and applied to newly downloaded files. The permission syntax is the same as the syntax used by the [chmod](https://en.wikipedia.org/wiki/Chmod) utility, accepting a numeric string of 3 or 4 numbers, each from 0 to 7. Unix file permissions are only applied when the application is running on a unix-like operating system (effectively, everything except Windows). The default permissions are 644, translating to read/write permissions for the owner (the user under which the application runs), read only for the owner's group, and read only for all other users. - -| Command-Line | Environment Variable | Description | -| ------------------------------- | ------------------------------------| ----------------------------------------------------------- | -| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | -| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | -| `--downloaded-file-permissions` | `SLSKD_DOWNLOADED_FILE_PERMISSIONS` | The Unix file permissions to be applied to downloaded files | - -#### **YAML** -```yaml -global: - download: - slots: 500 - speed_limit: 1000 # kibibytes - file: - permissions: 644 -``` - -## Uploads - -### Global Slot and Speed Limits - -Global upload slot and speed limits behave as hard limits, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. +Global slot and speed behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. @@ -312,6 +284,8 @@ A change to slot limits requires an application restart to take effect, while sp | ------------------------ | ---------------------------- | ------------------------------------------------ | | `--upload-slots` | `SLSKD_UPLOAD_SLOTS` | The limit for the total number of upload slots | | `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit, in kibibytes | +| `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | +| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | #### **YAML** ```yaml @@ -319,9 +293,12 @@ global: upload: slots: 20 speed_limit: 1000 # kibibytes + download: + slots: 500 + speed_limit: 1000 ``` -### Global Upload Limits +## Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. @@ -350,7 +327,7 @@ global: failures: 1000 ``` -### Groups +## Groups User groups are used to control upload slots, speed limits, and queue behavior on a per-user basis. @@ -385,7 +362,7 @@ limits: failures: 1000 ``` -### Built-In Groups +## Built-In Groups The `default` built-in group contains all users who have not been explicitly added to a user-defined group, are not privileged, and haven't been identified as leechers. @@ -438,7 +415,7 @@ groups: failures: 30 ``` -### User Blacklist +## User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -464,7 +441,7 @@ groups: - ``` -### User Defined Groups +## User Defined Groups In the group configuration, any number of user-defined groups can be added under the `user_defined` key. @@ -490,7 +467,7 @@ groups: - alice ``` -### Example +## Example In the following example: @@ -529,7 +506,7 @@ groups: - bob ``` -# Managed Blacklist +## Managed Blacklist A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. @@ -1113,4 +1090,4 @@ The application can be run in "command mode", causing it to execute a command an | `-h\|--help` | Display available command-line arguments | | `-e\|--envars` | Display available environment variables | | `-g\|--generate-cert` | Generate an X509 certificate and password for HTTPS | -| `-k\|--generate-secret ` | Generate a random secret of the specified length | +| `-k\|--generate-secret ` | Generate a random secret of the specified length | \ No newline at end of file -- cgit v1.2.3 From f7fefd065aec5ba3a9b4e679e36a5997924ec591 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 May 2024 22:49:41 -0500 Subject: docs --- docs/config.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index bed6d2d6..5c4eb2bb 100644 --- a/docs/config.md +++ b/docs/config.md @@ -73,6 +73,30 @@ If an attacker were to gain access to the application and retrieve the YAML file remote_configuration: false ``` +# Permissions + +On [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems, slskd creates downloaded files with permissions dictated by the [umask](https://en.wikipedia.org/wiki/Umask) of the process, usually 022, which translates to a file mode of 644; read/write for the owner and read for the group and all others. + +Users wishing to create files with different permissions can change the umask value before launching the application (e.g. `umask 000 & ./slskd`), and the file mode will be changed accordingly. + +When running within a docker container the environment variable `SLSKD_UMASK` can be used to change the umask for the process within the container, and this will in turn change the resulting file mode on a mounted volume. + +Users can optionally configure alternative permissions for files by setting the file permission mode option. It's not possible to supersede the configured umask value; setting a mode of 777, for example, will have no effect with a umask of 022. + +These options have no effect on Windows. + +| Command-Line | Environment Variable | Description | +| ------------------------ | -----------------------------| -------------------------------------------------------------------------------- | +| n/a | `SLSKD_UMASK` | When running within the slskd Docker container, the umask for the process | +| `--file-permission-mode` | `SLSKD_FILE_PERMISSION_MODE` | The permissions to apply to newly created files (chmod syntax, non-Windows only) | + +#### **YAML** +```yaml +permissions: + file: + mode: 644 # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask +``` + # Application Directory Configuration The application directory configuration option determines the location of the YAML file, the default locations of the download and incomplete directories, and the location of application working data, such as logs and SQLite databases. @@ -1090,4 +1114,4 @@ The application can be run in "command mode", causing it to execute a command an | `-h\|--help` | Display available command-line arguments | | `-e\|--envars` | Display available environment variables | | `-g\|--generate-cert` | Generate an X509 certificate and password for HTTPS | -| `-k\|--generate-secret ` | Generate a random secret of the specified length | \ No newline at end of file +| `-k\|--generate-secret ` | Generate a random secret of the specified length | -- cgit v1.2.3