From aa3401f33bb0a6e55324f1f0b67c9946a2df86db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:11 -0500 Subject: whitelist log directory --- src/slskd/Files/FileService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..6ab2328a 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -61,6 +61,7 @@ namespace slskd.Files { Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), + Path.GetFullPath(Program.LogDirectory), }; private ILogger Log { get; } = Serilog.Log.ForContext(); -- cgit v1.2.3 From 96420adbda382a91406c71ecfdddd5878bfb8f9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:43 -0500 Subject: rename method for clarity --- src/slskd/Files/API/FilesController.cs | 2 +- src/slskd/Files/FileService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd') 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 6ab2328a..f348e658 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -301,7 +301,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); -- cgit v1.2.3 From 514911ad65d3bdad6c05eedeef1d0aa3213803ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:57 -0500 Subject: warnings --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 2 +- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) (limited to 'src/slskd') 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 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ 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 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..1c2b85b5 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 { -- cgit v1.2.3 From 1f6c6b1bf962dd03c66f55098704530bb5c4620a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:09 -0500 Subject: stub function to return file contents --- src/slskd/Files/FileService.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index f348e658..a78d4dd4 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,39 @@ namespace slskd.Files }); } + 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); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + /// /// Creates a new file with the specified fully qualified and the optional , /// returning a with which the contents of the file can be written. -- cgit v1.2.3 From 91ad4826bbd0d89f69276ea0789e1498f2a92801 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:36 -0500 Subject: stub endpoints to list and read log files --- src/slskd/Core/API/Controllers/LogsController.cs | 59 +++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a12d9187 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,14 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// /// Logs. @@ -46,15 +51,67 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController( + FileService fileService, + OptionsAtStartup optionsAtStartup) + { + Files = fileService; + OptionsAtStartup = optionsAtStartup; + } + + private FileService Files { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + /// /// Gets the last few application logs. /// /// - [HttpGet] + [HttpGet("buffer")] [Authorize(Policy = AuthPolicy.Any)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + [HttpGet] + [Authorize(Policy = AuthPolicy.Any)] + public async Task List() + { + var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = false, + }); + + return Ok(directory.Files); + } + + [HttpGet("{filename}")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task Get(string filename, [FromQuery] bool download = false) + { + filename = FileSafety.GetFileNameSafely(filename); + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + + if (download) + { + return File(stream, "text/plain", filename); + } + + return File(stream, "text/plain"); + } + catch (UnauthorizedException) + { + return NotFound(); + } + catch (NotFoundException) + { + return NotFound(); + } + } } } -- cgit v1.2.3 From 8133ee872bfe07e859fc09bf6ea7062c08249ecb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:08:06 -0500 Subject: docs for GetFileContents --- src/slskd/Files/FileService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a78d4dd4..c100c7e9 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,16 @@ namespace slskd.Files }); } + /// + /// Retrieves the contents of the specified as a stream. + /// + /// The file for which contents are to be retrieved. + /// A Stream containing the contents of the file. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified filename contains path traversal segments. + /// Thrown if the specified file is not within an allowed directory. + /// Thrown if the specified file does not exist. + /// Thrown if the file can't be opened for some reason. public virtual Stream GetFileContents(string filename) { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); -- cgit v1.2.3 From 2c719dd8f5f330de61caf850c9087b5b989c1611 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:10:29 -0500 Subject: docs, change routes, lock endpoints down to administrators only --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a12d9187..465993c1 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -67,15 +67,19 @@ namespace slskd.Core.API /// Gets the last few application logs. /// /// - [HttpGet("buffer")] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Lists the log files currently on disk. + /// + /// + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions @@ -87,8 +91,14 @@ namespace slskd.Core.API return Ok(directory.Files); } - [HttpGet("{filename}")] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Retrieves the requested log file from disk. + /// + /// + /// + /// + [HttpGet("files/{filename}")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { filename = FileSafety.GetFileNameSafely(filename); -- cgit v1.2.3 From f76b210689cf1d0bc8b3f0d971194263eb66b3d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:25:11 -0500 Subject: remove uneccessary import --- src/slskd/Core/API/Controllers/LogsController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 465993c1..590ee6b7 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -52,15 +52,12 @@ namespace slskd.Core.API public class LogsController : ControllerBase { public LogsController( - FileService fileService, - OptionsAtStartup optionsAtStartup) + FileService fileService) { Files = fileService; - OptionsAtStartup = optionsAtStartup; } private FileService Files { get; } - private OptionsAtStartup OptionsAtStartup { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// -- cgit v1.2.3 From bb25e7accb1e47bfea4ddbb998106ad7365a88a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:08:47 -0500 Subject: add log file fetch and download --- src/slskd/Core/API/Controllers/LogsController.cs | 92 ++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 4 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 590ee6b7..43300e63 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -98,27 +98,111 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { - filename = FileSafety.GetFileNameSafely(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"); + } try { - var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); if (download) { return File(stream, "text/plain", filename); } - return File(stream, "text/plain"); + var logs = await ParseLogEntriesAsync(stream); + + return Ok(logs); } catch (UnauthorizedException) { - return NotFound(); + return Unauthorized(); } catch (NotFoundException) { return NotFound(); } } + + private async Task> ParseLogEntriesAsync(Stream stream) + { + Dictionary levels = new() + { + ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), + ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), + ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), + ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), + ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), + ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), + }; + + var list = new List(); + + var reader = new StreamReader(stream); + string line; + + while ((line = await reader.ReadLineAsync()) is not null) + { + if (line.Length == 0) + { + continue; + } + + try + { + // if the line isn't a log, append it to the previous message + if (!line.StartsWith('[')) + { + var lastIndex = list.Count - 1; + + if (lastIndex >= 0) + { + var old = list[lastIndex]; + + list[lastIndex] = new LogRecord + { + Timestamp = old.Timestamp, + Level = old.Level, + Message = old.Message + '\n' + line, + }; + } + + continue; + } + + var parts = line.TrimStart('[').Split(']', count: 2); + var meta = parts[0].Split(' '); + + list.Add(new LogRecord + { + Timestamp = DateTime.Parse(meta[0]), + Level = levels[meta[1]], + Message = parts[1].TrimStart(), + }); + } + catch (Exception ex) + { + Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); + continue; + } + } + + return list; + } } } -- cgit v1.2.3 From 3b2d0c62f410a4db800055b831bf37c1e512c1b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:10:36 -0500 Subject: wip of log zip --- src/slskd/Core/API/Controllers/LogsController.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 43300e63..569848b2 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,7 +33,10 @@ namespace slskd.Core.API { using System; + using System.Collections.Generic; using System.IO; + using System.IO.Compression; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -77,7 +80,7 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List() + public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { @@ -85,6 +88,16 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); + if (download) + { + var stream = new MemoryStream(); + await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); + + var now = DateTime.UtcNow; + + return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); + } + return Ok(directory.Files); } -- cgit v1.2.3 From e5a8ae30b640212386cbb4e1fffd2ae937234793 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 08:55:24 -0500 Subject: forget about downloading a zip --- src/slskd/Core/API/Controllers/LogsController.cs | 11 ----------- 1 file changed, 11 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 569848b2..a35c6097 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,7 +35,6 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; - using System.IO.Compression; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -88,16 +87,6 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); - if (download) - { - var stream = new MemoryStream(); - await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); - - var now = DateTime.UtcNow; - - return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); - } - return Ok(directory.Files); } -- cgit v1.2.3 From e427bc851f09fbda5768ef427de83286ee1b4822 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 17:56:57 -0500 Subject: use r/w fileshare --- src/slskd/Files/FileService.cs | 2 +- src/web/src/components/System/Logs/Live.jsx | 98 ++++++++++++++++++++++++++++ src/web/src/components/System/Logs/index.jsx | 98 ---------------------------- 3 files changed, 99 insertions(+), 99 deletions(-) create mode 100644 src/web/src/components/System/Logs/Live.jsx delete mode 100644 src/web/src/components/System/Logs/index.jsx (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c100c7e9..e3479210 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -400,7 +400,7 @@ namespace slskd.Files try { - return new FileStream(filename, FileMode.Open, FileAccess.Read); + return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx new file mode 100644 index 00000000..f36258ec --- /dev/null +++ b/src/web/src/components/System/Logs/Live.jsx @@ -0,0 +1,98 @@ +import '../System.css'; +import { createLogsHubConnection } from '../../../lib/hubFactory'; +import { LoaderSegment } from '../../Shared'; +import React, { Component } from 'react'; +import { Table } from 'semantic-ui-react'; + +const initialState = { + connected: false, + logs: [], +}; + +const levels = { + Debug: 'DBG', + Error: 'ERR', + Information: 'INF', + Warning: 'WRN', +}; + +const maxLogs = 500; + +class Logs extends Component { + constructor(props) { + super(props); + + this.state = initialState; + } + + componentDidMount() { + const logsHub = createLogsHubConnection(); + + logsHub.on('buffer', (buffer) => { + this.setState({ + connected: true, + logs: buffer.reverse().slice(0, maxLogs), + }); + }); + + logsHub.on('log', (log) => { + this.setState((previousState) => ({ + connected: true, + logs: [log].concat(previousState.logs).slice(0, maxLogs), + })); + }); + + logsHub.onreconnecting(() => this.setState({ connected: false })); + logsHub.onclose(() => this.setState({ connected: false })); + logsHub.onreconnected(() => this.setState({ connected: true })); + + logsHub.start(); + } + + formatTimestamp = (timestamp) => { + const date = new Date(timestamp); + return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len + }; + + render() { + const { connected, logs } = this.state; + + return ( +
+ {!connected && } + {connected && ( + + + + Timestamp + Level + Message + + + + {logs.map((log) => ( + + {this.formatTimestamp(log.timestamp)} + {levels[log.level] || log.level} + + {log.message} + + + ))} + +
+ )} +
+ ); + } +} + +export default Logs; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx deleted file mode 100644 index f36258ec..00000000 --- a/src/web/src/components/System/Logs/index.jsx +++ /dev/null @@ -1,98 +0,0 @@ -import '../System.css'; -import { createLogsHubConnection } from '../../../lib/hubFactory'; -import { LoaderSegment } from '../../Shared'; -import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; - -const initialState = { - connected: false, - logs: [], -}; - -const levels = { - Debug: 'DBG', - Error: 'ERR', - Information: 'INF', - Warning: 'WRN', -}; - -const maxLogs = 500; - -class Logs extends Component { - constructor(props) { - super(props); - - this.state = initialState; - } - - componentDidMount() { - const logsHub = createLogsHubConnection(); - - logsHub.on('buffer', (buffer) => { - this.setState({ - connected: true, - logs: buffer.reverse().slice(0, maxLogs), - }); - }); - - logsHub.on('log', (log) => { - this.setState((previousState) => ({ - connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), - })); - }); - - logsHub.onreconnecting(() => this.setState({ connected: false })); - logsHub.onclose(() => this.setState({ connected: false })); - logsHub.onreconnected(() => this.setState({ connected: true })); - - logsHub.start(); - } - - formatTimestamp = (timestamp) => { - const date = new Date(timestamp); - return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len - }; - - render() { - const { connected, logs } = this.state; - - return ( -
- {!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} -
- ); - } -} - -export default Logs; -- cgit v1.2.3 From f3dca154f98a9f37c9323b2e276e4f6d5540850c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:01:56 -0500 Subject: share logs --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5260760f..778502a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1247,7 +1247,8 @@ namespace slskd Path.Combine(LogDirectory, $"{AppName}-.log"), outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {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 => -- cgit v1.2.3 From 556b588197f31ed98c0e3dec7a9ceeddf8eb10e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:04:46 -0500 Subject: enable disk logging by default --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/slskd') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index af2871e2..442d0ce3 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -195,7 +195,7 @@ # circuit_breaker: 500 # maximum number of pending search requests # response_file_limit: 500 # maximum number of files to return in a single search response # logger: -# disk: false +# disk: true # no_color: false # loki: ~ # metrics: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d1062a2c..84dafe29 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1458,11 +1458,11 @@ namespace slskd /// /// Gets a value indicating whether to write logs to disk. /// - [Argument(default, "disk-logger")] - [EnvironmentVariable("DISK_LOGGER")] - [Description("enable logging to disk")] + [Argument(default, "no-disk-logger")] + [EnvironmentVariable("NO_DISK_LOGGER")] + [Description("disable logging to disk")] [RequiresRestart] - public bool Disk { get; init; } = false; + public bool Disk { get; init; } = true; /// /// Gets a value indicating whether to suppress colorization of console logs. -- cgit v1.2.3 From 42e69540d07af2819b74735c1aea194eb344ac46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:05:56 -0500 Subject: reduce default log retention to 30 days, increase minimum to 7 --- src/slskd/Core/Options.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 84dafe29..3499e564 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1500,8 +1500,8 @@ namespace slskd /// /// Gets the time to retain logs, in days. /// - [Range(1, maximum: int.MaxValue)] - public int Logs { get; init; } = 180; + [Range(7, maximum: int.MaxValue)] + public int Logs { get; init; } = 30; /// /// Transfer retention options. -- cgit v1.2.3 From 216c8ab2bcf84c2e11b8fa6fa640a9fdaa37f472 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:14 -0500 Subject: add date and milliseconds to disk logs --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 778502a2..def4c2aa 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1245,7 +1245,7 @@ namespace slskd e => OptionsAtStartup.Logger.Disk, 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), shared: true))) // allow log file to be read concurrently -- cgit v1.2.3 From ec02691a206451e9e9c11a2f305ab928c6f9676b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:38 -0500 Subject: add regex for parsing log lines --- src/slskd/Core/API/Controllers/LogsController.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a35c6097..fff5e843 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,6 +35,7 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -61,6 +62,7 @@ namespace slskd.Core.API private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. -- cgit v1.2.3 From 5b063c478b5d5f8e694a5cdea76af0d8eada3150 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:53 -0500 Subject: leave note about streaming optimization --- src/slskd/Core/API/Controllers/LogsController.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index fff5e843..13f8ab95 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -129,6 +129,10 @@ namespace slskd.Core.API return File(stream, "text/plain", filename); } + // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up + // memory to build a list. save each log in memory and then emit it when the next log + // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer + // that is flushed when the next log is read, or the file is complete var logs = await ParseLogEntriesAsync(stream); return Ok(logs); -- cgit v1.2.3 From ea4ca200cd6dda759917dcd76d47d2bddfa5d2f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:23 -0500 Subject: break if the file is being appended to avoid an endless loop --- src/slskd/Core/API/Controllers/LogsController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 13f8ab95..d7e011eb 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -161,6 +161,8 @@ namespace slskd.Core.API var list = new List(); + var currentLength = stream.Length; + var reader = new StreamReader(stream); string line; @@ -171,6 +173,15 @@ namespace slskd.Core.API continue; } + if (stream.Position > currentLength) + { + // if we're reading the latest file, Serilog can append it while we're inside of this loop, + // or worse, a problem inside this loop appends lines. if this happens the position will grow + // beyond the length at the start + Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); + break; + } + try { // if the line isn't a log, append it to the previous message -- cgit v1.2.3 From e2bc14a1572c4a3d035ac7a4ffe47cff35fd2e16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:39 -0500 Subject: parse logs with the regex --- src/slskd/Core/API/Controllers/LogsController.cs | 48 +++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index d7e011eb..1c1f057b 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -204,14 +204,52 @@ namespace slskd.Core.API continue; } - var parts = line.TrimStart('[').Split(']', count: 2); - var meta = parts[0].Split(' '); + /* + there should be 3 possible line types: + + debug: + [Some.Context] [2000-1-1T11:11:11 WRN] foo bar + + info: + [2000-1-1T11:11:11 WRN] foo bar + + line wrap/newline: + foo bar + + additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle + cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date + + the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) + using the debug log as an example, the groups are: + + 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar + 1. [Some.Context] + 2. Some.Context + 3. [2000-01-01T11:11:11 WRN] + 4. 2000-01-01T + 5. 2000-01-01 + 6. 11:11:11 + 7. WRN + 8. foo bar + + the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line + */ + match = LogLineParseRegex.Match(line); + + var grp = match.Groups; + + var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); + var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); + var dateTime = date.ToDateTime(time); + + var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; list.Add(new LogRecord { - Timestamp = DateTime.Parse(meta[0]), - Level = levels[meta[1]], - Message = parts[1].TrimStart(), + Context = grp[2].Value, + Timestamp = dateTime, + Level = level, + Message = grp[8].Value, }); } catch (Exception ex) -- cgit v1.2.3 From 0ef9cd71e115642cce876372c76fd3a1d8de6a4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:13:02 -0500 Subject: wip --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1c1f057b..1a3e027f 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -165,6 +165,7 @@ namespace slskd.Core.API var reader = new StreamReader(stream); string line; + Match match = default; while ((line = await reader.ReadLineAsync()) is not null) { @@ -251,14 +252,31 @@ namespace slskd.Core.API Level = level, Message = grp[8].Value, }); + + Log.Information("Added: {Text}", grp[8].Value); } catch (Exception ex) { - Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); - continue; + Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); + + Log.Warning("Got {GroupCount} groups", match.Groups.Count); + + foreach (var key in match.Groups.Keys) + { + Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); + } + + break; + + list.Add(new LogRecord + { + Message = line, + }); } } + Log.Information("Returned {Lines}", list.Count); + return list; } } -- cgit v1.2.3 From 58a289bcdcf4d649d94ee6058c40ee7197d95209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 25 Sep 2026 09:29:34 -0500 Subject: strip out complicated parsing --- src/slskd/Core/API/Controllers/LogsController.cs | 176 +++-------------------- 1 file changed, 21 insertions(+), 155 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1a3e027f..6ef4a7b6 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,10 +33,8 @@ namespace slskd.Core.API { using System; - using System.Collections.Generic; using System.IO; - using System.Text.RegularExpressions; - using System.Threading; + using System.Linq; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -54,15 +52,13 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { - public LogsController( - FileService fileService) + public LogsController(FileService fileService) { Files = fileService; } private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. @@ -81,26 +77,29 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) + public async Task List() { - var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { - AttributesToSkip = FileAttributes.System, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, RecurseSubdirectories = false, }); - return Ok(directory.Files); + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); } /// - /// Retrieves the requested log file from disk. + /// Retrieves the requested log file from disk as plain text. /// - /// - /// + /// The name of the log file. + /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task Get(string filename, [FromQuery] bool download = false) + public IActionResult Get(string filename, [FromQuery] bool download = false) { if (string.IsNullOrWhiteSpace(filename)) { @@ -120,22 +119,22 @@ namespace slskd.Core.API return BadRequest("Filename contains one or more invalid characters"); } + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return BadRequest("Only .log files may be retrieved"); + } + try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + const string contentType = "text/plain; charset=utf-8"; if (download) { - return File(stream, "text/plain", filename); + return File(stream, contentType, filename); } - // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up - // memory to build a list. save each log in memory and then emit it when the next log - // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer - // that is flushed when the next log is read, or the file is complete - var logs = await ParseLogEntriesAsync(stream); - - return Ok(logs); + return File(stream, contentType); } catch (UnauthorizedException) { @@ -146,138 +145,5 @@ namespace slskd.Core.API return NotFound(); } } - - private async Task> ParseLogEntriesAsync(Stream stream) - { - Dictionary levels = new() - { - ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), - ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), - ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), - ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), - ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), - ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), - }; - - var list = new List(); - - var currentLength = stream.Length; - - var reader = new StreamReader(stream); - string line; - Match match = default; - - while ((line = await reader.ReadLineAsync()) is not null) - { - if (line.Length == 0) - { - continue; - } - - if (stream.Position > currentLength) - { - // if we're reading the latest file, Serilog can append it while we're inside of this loop, - // or worse, a problem inside this loop appends lines. if this happens the position will grow - // beyond the length at the start - Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); - break; - } - - try - { - // if the line isn't a log, append it to the previous message - if (!line.StartsWith('[')) - { - var lastIndex = list.Count - 1; - - if (lastIndex >= 0) - { - var old = list[lastIndex]; - - list[lastIndex] = new LogRecord - { - Timestamp = old.Timestamp, - Level = old.Level, - Message = old.Message + '\n' + line, - }; - } - - continue; - } - - /* - there should be 3 possible line types: - - debug: - [Some.Context] [2000-1-1T11:11:11 WRN] foo bar - - info: - [2000-1-1T11:11:11 WRN] foo bar - - line wrap/newline: - foo bar - - additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle - cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date - - the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) - using the debug log as an example, the groups are: - - 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar - 1. [Some.Context] - 2. Some.Context - 3. [2000-01-01T11:11:11 WRN] - 4. 2000-01-01T - 5. 2000-01-01 - 6. 11:11:11 - 7. WRN - 8. foo bar - - the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line - */ - match = LogLineParseRegex.Match(line); - - var grp = match.Groups; - - var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); - var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); - var dateTime = date.ToDateTime(time); - - var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; - - list.Add(new LogRecord - { - Context = grp[2].Value, - Timestamp = dateTime, - Level = level, - Message = grp[8].Value, - }); - - Log.Information("Added: {Text}", grp[8].Value); - } - catch (Exception ex) - { - Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); - - Log.Warning("Got {GroupCount} groups", match.Groups.Count); - - foreach (var key in match.Groups.Keys) - { - Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); - } - - break; - - list.Add(new LogRecord - { - Message = line, - }); - } - } - - Log.Information("Returned {Lines}", list.Count); - - return list; - } } } -- cgit v1.2.3 From f32f73b402e9bfd5aca47cb94a245fccbd21482f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:40:32 -0500 Subject: tweak controller --- src/slskd/Core/API/Controllers/LogsController.cs | 33 ++++++++++++------------ 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 6ef4a7b6..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -38,6 +38,7 @@ namespace slskd.Core.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Files; @@ -58,7 +59,7 @@ namespace slskd.Core.API } private FileService Files { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Gets the last few application logs. @@ -79,6 +80,11 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { IgnoreInaccessible = true, @@ -95,11 +101,12 @@ namespace slskd.Core.API /// Retrieves the requested log file from disk as plain text. /// /// The name of the log file. - /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public IActionResult Get(string filename, [FromQuery] bool download = false) + public IActionResult Get([FromRoute] string filename) { if (string.IsNullOrWhiteSpace(filename)) { @@ -121,29 +128,23 @@ namespace slskd.Core.API if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) { - return BadRequest("Only .log files may be retrieved"); + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); } try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); - const string contentType = "text/plain; charset=utf-8"; - - if (download) - { - return File(stream, contentType, filename); - } - - return File(stream, contentType); - } - catch (UnauthorizedException) - { - return Unauthorized(); + 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); + } } } } -- cgit v1.2.3 From 400108c9a4a88edb6738309e0b83c9299ca36072 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 19:04:22 -0500 Subject: make enumeration options default as intended --- src/slskd/Files/FileService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 665fe919..584aab08 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -320,7 +320,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -352,7 +352,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType() -- cgit v1.2.3 From c2a9302741e79165978fa91da040b6f7e689cc48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 13:51:32 -0500 Subject: compensate for late-populated LogDirectory --- src/slskd/Files/FileService.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src/slskd') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 584aab08..70bfc293 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,10 +59,11 @@ namespace slskd.Files private IEnumerable AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - Path.GetFullPath(Program.LogDirectory), - }; + 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(); private IOptionsMonitor OptionsMonitor { get; } -- cgit v1.2.3