diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-10-03 23:28:23 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-03 23:28:23 -0500 |
| commit | fc11d5d691ac008e1507f25ebb5ce3ac7a5cfc60 (patch) | |
| tree | 3de54f5e8b4001253db53bd20dc153ebe49b271c /src/slskd | |
| parent | 1915a370c1bd11aee8849574e116b353a0b7153f (diff) | |
| parent | a97a425c7121f19c1613106c0bab7a1dcf616f92 (diff) | |
| download | slskd-fc11d5d691ac008e1507f25ebb5ce3ac7a5cfc60.tar.gz | |
Merge branch 'master' into upload-queue-fixes
Diffstat (limited to 'src/slskd')
| -rw-r--r-- | src/slskd/Core/API/Controllers/LogsController.cs | 94 | ||||
| -rw-r--r-- | src/slskd/Files/API/FilesController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Files/FileService.cs | 55 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 1 |
7 files changed, 148 insertions, 13 deletions
diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,16 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Linq; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// <summary> /// Logs. @@ -46,15 +53,98 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController(FileService fileService) + { + Files = fileService; + } + + private FileService Files { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<LogsController>(); + /// <summary> /// Gets the last few application logs. /// </summary> /// <returns></returns> - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + /// <summary> + /// Lists the log files currently on disk. + /// </summary> + /// <returns></returns> + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public async Task<IActionResult> List() + { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, + RecurseSubdirectories = false, + }); + + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); + } + + /// <summary> + /// Retrieves the requested log file from disk as plain text. + /// </summary> + /// <param name="filename">The name of the log file.</param> + /// <returns></returns> + [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public IActionResult Get([FromRoute] string filename) + { + if (string.IsNullOrWhiteSpace(filename)) + { + return BadRequest("Filename is required"); + } + + if (filename.ContainsAny('/', '\\')) + { + return BadRequest("Filename must not contain a path"); + } + + var sanitizedFilename = FileSafety.GetFileNameSafely(filename, sanitize: true); + + if (!sanitizedFilename.Equals(filename, StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Input filename {Filename} sanitized to {Sanitized}", filename, sanitizedFilename); + return BadRequest("Filename contains one or more invalid characters"); + } + + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); + } + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + return File(stream, "text/plain; charset=utf-8", enableRangeProcessing: true); + } + catch (NotFoundException) + { + return NotFound(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to retrieve log file {Filename}: {Message}", filename, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } } } diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 8a96d83f..5f30f325 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -200,7 +200,7 @@ namespace slskd.Files.API try { - var response = await Files.ListContentsAsync( + var response = await Files.ListDirectoryContentsAsync( directory: requestedDir, enumerationOptions: new EnumerationOptions { diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 8450ba48..70bfc293 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,9 +59,11 @@ namespace slskd.Files private IEnumerable<string> AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - }; + OptionsMonitor.CurrentValue.Directories.Downloads, + OptionsMonitor.CurrentValue.Directories.Incomplete, + Program.LogDirectory, + }.Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => Path.GetFullPath(x)); private ILogger Log { get; } = Serilog.Log.ForContext<FileService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } @@ -319,7 +321,7 @@ namespace slskd.Files /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> - public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task<FilesystemDirectory> ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -351,7 +353,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType<FileInfo>() @@ -384,6 +386,49 @@ namespace slskd.Files } /// <summary> + /// Retrieves the contents of the specified <paramref name="filename"/> as a stream. + /// </summary> + /// <param name="filename">The file for which contents are to be retrieved.</param> + /// <returns>A Stream containing the contents of the file.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified filename contains path traversal segments.</exception> + /// <exception cref="UnauthorizedException">Thrown if the specified file is not within an allowed directory.</exception> + /// <exception cref="NotFoundException">Thrown if the specified file does not exist.</exception> + /// <exception cref="IOException">Thrown if the file can't be opened for some reason.</exception> + public virtual Stream GetFileContents(string filename) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to read a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' + if (!AllowedDirectories.Any(allowed => filename.StartsWith(allowed + Path.DirectorySeparatorChar))) + { + throw new UnauthorizedException($"Only application-controlled directories can be listed"); + } + + var info = ResolveFileInfo(filename); + + if (!info.Exists) + { + throw new NotFoundException(); + } + + try + { + return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + + /// <summary> /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>, /// returning a <see cref="Stream"/> with which the contents of the file can be written. /// </summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b1f57ce4..cfe8bcba 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1250,9 +1250,10 @@ namespace slskd e => !OptionsAtStartup.Logger.NoDisk, config => config.File( Path.Combine(LogDirectory, $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:yyyy-MM-ddTHH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, - retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) + retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs), + shared: true))) // allow log file to be read concurrently .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), config => diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index 7af36fcb..3e2c138f 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -1,4 +1,4 @@ -// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs index 3d066fe9..924611eb 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs @@ -1,4 +1,4 @@ -// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchResponse.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 7bc889ba..b480e764 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -413,7 +413,6 @@ namespace slskd.Transfers.Uploads lastReportedAverageSpeed = now; } - } finally { |
