diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-11-07 23:16:26 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-07 23:16:26 -0600 |
| commit | cefdcd02e28b1f02f546002fdd475de4fa03e839 (patch) | |
| tree | 95bb26f4ed7b60e3739bcd884966a19be1e9ee07 /src/slskd | |
| parent | 2b827344d11e7490b323defa898264cadbdb6089 (diff) | |
| parent | dbc308d5e408a2e194a0c70a8fc7592f776aaf11 (diff) | |
| download | slskd-cefdcd02e28b1f02f546002fdd475de4fa03e839.tar.gz | |
Merge pull request #1913 from slskd/bugs
Fix a random assortment of bugs
Diffstat (limited to 'src/slskd')
25 files changed, 268 insertions, 169 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e055fcd8..461a5fef 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -134,13 +134,13 @@ namespace slskd foreach (var signal in new[] { PosixSignal.SIGINT, PosixSignal.SIGQUIT, PosixSignal.SIGTERM }) { - PosixSignalRegistration.Create(signal, context => + PosixSignals.Add(PosixSignalRegistration.Create(signal, context => { ShuttingDown = true; Program.MasterCancellationTokenSource.Cancel(); Log.Fatal("Received {Signal}", signal); Environment.Exit(1); - }); + })); } OptionsAtStartup = optionsAtStartup; @@ -237,6 +237,7 @@ namespace slskd public static bool IsShuttingDown => Environment.HasShutdownStarted || ShuttingDown; private static bool ShuttingDown { get; set; } = false; + private static List<PosixSignalRegistration> PosixSignals { get; } = []; private ISoulseekClient Client { get; set; } private FileService Files { get; } @@ -741,7 +742,7 @@ namespace slskd } bool IsNull(Options.TransfersOptions.LimitsOptions.Limits lim, Options.TransfersOptions.LimitsOptions.Limits global) - => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); + => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim?.Failures ?? global?.Failures) is null); /* * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. @@ -1439,7 +1440,7 @@ namespace slskd { if (Users.IsBlacklisted(username, endpoint.Address)) { - Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); + Log.Information("Returned no place in queue for blacklisted user {Username} ({IP})", username, endpoint.Address); return Task.FromResult<int?>(null); } @@ -1565,8 +1566,15 @@ namespace slskd if (PreviousOptions.Filters.Search.Request.Except(newOptions.Filters.Search.Request).Any() || newOptions.Filters.Search.Request.Except(PreviousOptions.Filters.Search.Request).Any()) { + var regexOptions = RegexOptions.Compiled; + + if (!Flags.CaseSensitiveRegEx) + { + regexOptions |= RegexOptions.IgnoreCase; + } + CompiledSearchRequestFilters = newOptions.Filters.Search.Request - .Select(f => new Regex(f, RegexOptions.Compiled)) + .Select(f => new Regex(f, regexOptions)) .ToList() .AsReadOnly(); diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 95721163..47e4aee1 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -53,6 +53,8 @@ namespace slskd /// </summary> public static class CommonExtensions { + private static readonly JsonSerializerOptions DefaultJsonSerializerOptions = GetJsonSerializerOptions(); + /// <summary> /// Times this Task out after the specified TimeSpan. /// </summary> @@ -358,7 +360,7 @@ namespace slskd /// </summary> /// <param name="obj">The object to serialize.</param> /// <returns>A string containing the serialized object.</returns> - public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, GetJsonSerializerOptions()); + public static string ToJson(this object obj) => JsonSerializer.Serialize(obj, DefaultJsonSerializerOptions); /// <summary> /// Serializes this object to yaml. @@ -481,7 +483,7 @@ namespace slskd /// <typeparam name="T">The type to which to deserialize the string.</typeparam> /// <param name="str">The string to deserialize.</param> /// <returns>The new object deserialized from the string.</returns> - public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, GetJsonSerializerOptions()); + public static T FromJson<T>(this string str) => JsonSerializer.Deserialize<T>(str, DefaultJsonSerializerOptions); /// <summary> /// Applies the standard json serializer options to the specified instance. diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index 68900267..18851c0d 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -54,7 +54,7 @@ namespace slskd /// <returns></returns> public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html, IEnumerable<string> excludedRoutes) { - return builder.UseMiddleware<HTMLInjectionMiddleware>(html); + return builder.UseMiddleware<HTMLInjectionMiddleware>(html, excludedRoutes); } } @@ -87,9 +87,13 @@ namespace slskd /// <returns></returns> public async Task InvokeAsync(HttpContext context) { + // accept types can have some metadata after the type, separated by a semicolon. example: + // text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 context.Request.Headers.TryGetValue("accept", out var accept); - var requestedTypes = accept.ToString().Split(','); - var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + // split by comma, then drop the semicolon and everything after it (if present) for that type + var requestedTypes = accept.ToString().Split(',').Select(type => type.Split(';')[0].Trim()); + var injectableTypes = new[] { "text/html", "application/xhtml+xml", "application/xml" }; var isInjectableType = requestedTypes .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) .Any(); @@ -106,46 +110,55 @@ namespace slskd var stream = new MemoryStream(); context.Response.Body = stream; - await Next.Invoke(context); - - if (context.Response.StatusCode == 200) + try { - // something downstream responded with a 200, meaning there's data in the body - // we need to read it, so we can reset then play it back with the modified HTML - context.Response.Body.Seek(0, SeekOrigin.Begin); - var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); - - var headers = context.Response.Headers - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) - .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); + await Next.Invoke(context); - context.Response.Clear(); - - foreach (var header in headers) + if (context.Response.StatusCode == 200) { - context.Response.Headers.Add(header); + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the modified HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + var headers = context.Response.Headers + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); + + context.Response.Clear(); + + foreach (var header in headers) + { + context.Response.Headers.Add(header); + } + + // check the response content type to make sure it's still injectable. the server might return something other + // than what was requested. if it's no longer injectable, don't inject. + // drop the semicolon and everything after it (e.g. '; charset=utf-8') before comparing + var responseType = context.Response.ContentType?.Split(';')[0].Trim(); + var isInjectableResponseType = injectableTypes.Contains(responseType, StringComparer.InvariantCultureIgnoreCase); + + if (!isInjectableResponseType) + { + await context.Response.WriteAsync(body); + } + else + { + await context.Response.WriteAsync(body + HTML); + } } - // check the response content type to make sure it's still injectable. the server might return something other - // than what was requested. if it's no longer injectable, don't inject. - var isInjectableResponseType = injectableTypes.Any(injectableType => context.Response.Headers.ContentType.Contains(injectableType)); - if (!isInjectableResponseType) - { - await context.Response.WriteAsync(body); - } - else - { - await context.Response.WriteAsync(body + HTML); - } + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + } + finally + { + // swap the original stream back in, even if something downstream threw, so that + // upstream middleware (e.g. the exception handler) can write to the response + context.Response.Body = originalStream; } - - // rewind the stream we injected to the beginning, then replay the data to the - // original stream - stream.Seek(0, SeekOrigin.Begin); - await stream.CopyToAsync(originalStream); - - // swap the original stream back in - context.Response.Body = originalStream; } else { diff --git a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs index e91a2352..0c8a8fb2 100644 --- a/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLRewriteMiddleware.cs @@ -87,9 +87,13 @@ namespace slskd /// <returns></returns> public async Task InvokeAsync(HttpContext context) { + // accept types can have some metadata after the type, separated by a semicolon. example: + // text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 context.Request.Headers.TryGetValue("accept", out var accept); - var requestedTypes = accept.ToString().Split(','); - var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" }; + + // split by comma, then drop the semicolon and everything after it (if present) for that type + var requestedTypes = accept.ToString().Split(',').Select(type => type.Split(';')[0].Trim()); + var injectableTypes = new[] { "text/html", "application/xhtml+xml", "application/xml" }; var isRewriteableType = requestedTypes .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase) .Any(); @@ -106,36 +110,54 @@ namespace slskd var stream = new MemoryStream(); context.Response.Body = stream; - await Next.Invoke(context); - - if (context.Response.StatusCode == 200) + try { - // something downstream responded with a 200, meaning there's data in the body - // we need to read it, so we can reset then play it back with the modified HTML - context.Response.Body.Seek(0, SeekOrigin.Begin); - var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); - - var headers = context.Response.Headers - .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) - .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); - - context.Response.Clear(); + await Next.Invoke(context); - foreach (var header in headers) + if (context.Response.StatusCode == 200) { - context.Response.Headers.Add(header); + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the modified HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + var headers = context.Response.Headers + .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) + .Where(kvp => !string.Equals(kvp.Key, "Content-Length", StringComparison.InvariantCultureIgnoreCase)); + + context.Response.Clear(); + + foreach (var header in headers) + { + context.Response.Headers.Add(header); + } + + // check the response content type to make sure it's still rewriteable. the server might return something other + // than what was requested. if it's no longer rewriteable, don't rewrite. + // drop the semicolon and everything after it (e.g. '; charset=utf-8') before comparing + var responseType = context.Response.ContentType?.Split(';')[0].Trim(); + var isRewriteableResponseType = injectableTypes.Contains(responseType, StringComparer.InvariantCultureIgnoreCase); + if (!isRewriteableResponseType) + { + await context.Response.WriteAsync(body); + } + else + { + await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + } } - await context.Response.WriteAsync(Regex.Replace(body, Pattern, Replacement)); + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + } + finally + { + // swap the original stream back in, even if something downstream threw, so that + // upstream middleware (e.g. the exception handler) can write to the response + context.Response.Body = originalStream; } - - // rewind the stream we injected to the beginning, then replay the data to the - // original stream - stream.Seek(0, SeekOrigin.Begin); - await stream.CopyToAsync(originalStream); - - // swap the original stream back in - context.Response.Body = originalStream; } else { diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs index ac34ed5d..7229441f 100644 --- a/src/slskd/Common/RateLimiter.cs +++ b/src/slskd/Common/RateLimiter.cs @@ -97,6 +97,7 @@ namespace slskd return; } + // previously staged action is lost, intentionally Staged = action; } @@ -131,8 +132,11 @@ namespace slskd { try { - Staged?.Invoke(); + // capture the staged action before nulling it to avoid + // a race where another action might slip in between the invoke and null + var staged = Staged; Staged = null; + staged?.Invoke(); } finally { diff --git a/src/slskd/Common/Validation/EnumAttribute.cs b/src/slskd/Common/Validation/EnumAttribute.cs index fc077bb6..cdbaccda 100644 --- a/src/slskd/Common/Validation/EnumAttribute.cs +++ b/src/slskd/Common/Validation/EnumAttribute.cs @@ -60,14 +60,14 @@ namespace slskd.Validation return new ValidationResult($"The {validationContext.DisplayName} field contains one or more null or empty values"); } - if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out _))) + if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out var parsed) || !Enum.IsDefined(TargetType, parsed))) { return new ValidationResult($"The elements in the {validationContext.DisplayName} field must all be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); } } else { - if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + if (value != null && (!Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out var parsed) || !Enum.IsDefined(TargetType, parsed))) { return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); } diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index c4d97a7c..6fc50f63 100644 --- a/src/slskd/Common/Validation/FileExistsAttribute.cs +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -32,6 +32,7 @@ namespace slskd.Validation { + using System; using System.ComponentModel.DataAnnotations; using System.IO; @@ -71,7 +72,7 @@ namespace slskd.Validation using var fs = File.Open(file, FileMode.Open, FileAccess.Value); fs.Close(); } - catch (IOException) + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { return new ValidationResult($"The {validationContext.DisplayName} field specifies a file '{file}' that cannot be opened for required access '{FileAccess}'"); } diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs index bb323ba2..d656a047 100644 --- a/src/slskd/Common/Validation/StringAttribute.cs +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -90,7 +90,7 @@ namespace slskd.Validation if (Pattern is not null && Pattern.IsMatch(val)) { - return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + return new ValidationResult($"The {validationContext.DisplayName} field must not match the regular expression {Pattern.ToJson()}"); } return ValidationResult.Success; diff --git a/src/slskd/Common/WaitKey.cs b/src/slskd/Common/WaitKey.cs index af71af7a..3306103d 100644 --- a/src/slskd/Common/WaitKey.cs +++ b/src/slskd/Common/WaitKey.cs @@ -61,12 +61,12 @@ namespace slskd public static bool operator !=(WaitKey lhs, WaitKey rhs) { - return !lhs.Equals(rhs); + return !(lhs == rhs); } public static bool operator ==(WaitKey lhs, WaitKey rhs) { - return lhs.Equals(rhs); + return lhs is null ? rhs is null : lhs.Equals(rhs); } /// <summary> @@ -93,7 +93,7 @@ namespace slskd /// <returns>A value indicating whether the specified WaitKey is equal to this instance.</returns> public bool Equals(WaitKey other) { - return Token == other.Token; + return other is not null && Token == other.Token; } /// <summary> diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index 5381f513..2f3f3573 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -148,18 +148,45 @@ public class EventsController : ControllerBase { var d = disambiguator; - Event @event = eventType switch + Event @event; + + // each event must be raised using its concrete type so that the correct subscribers are invoked + switch (eventType) { - EventType.DownloadFileComplete => new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, - EventType.DownloadDirectoryComplete => new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" }, - EventType.UploadFileComplete => new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }, - EventType.PrivateMessageReceived => new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } }, - EventType.RoomMessageReceived => new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } }, - EventType.Noop => new NoopEvent(), - _ => throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."), - }; - - EventBus.Raise(@event); + case EventType.DownloadFileComplete: + var downloadFileComplete = new DownloadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }; + EventBus.Raise(downloadFileComplete); + @event = downloadFileComplete; + break; + case EventType.DownloadDirectoryComplete: + var downloadDirectoryComplete = new DownloadDirectoryCompleteEvent { LocalDirectoryName = $"{d}local.directory", RemoteDirectoryName = $"{d}remote.directory", Username = $"{d}username" }; + EventBus.Raise(downloadDirectoryComplete); + @event = downloadDirectoryComplete; + break; + case EventType.UploadFileComplete: + var uploadFileComplete = new UploadFileCompleteEvent { LocalFilename = $"{d}local.file", RemoteFilename = $"{d}remote.file", Transfer = new Transfer() }; + EventBus.Raise(uploadFileComplete); + @event = uploadFileComplete; + break; + case EventType.PrivateMessageReceived: + var privateMessageReceived = new PrivateMessageReceivedEvent { Message = new PrivateMessage { Id = 42, Timestamp = DateTime.UtcNow, Username = $"{d}username", Message = $"{d}message" } }; + EventBus.Raise(privateMessageReceived); + @event = privateMessageReceived; + break; + case EventType.RoomMessageReceived: + var roomMessageReceived = new RoomMessageReceivedEvent { Message = new RoomMessage { RoomName = $"{d}room", Username = $"{d}username", Message = $"{d}message" } }; + EventBus.Raise(roomMessageReceived); + @event = roomMessageReceived; + break; + case EventType.Noop: + var noop = new NoopEvent(); + EventBus.Raise(noop); + @event = noop; + break; + default: + throw new SlskdException($"Event type {eventType} is an enum member but is not handled. Please submit an issue on GitHub."); + } + return StatusCode(201, @event); } catch (Exception ex) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 0c9b8e57..72f797ff 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -88,6 +88,15 @@ public class EventBus public virtual void Raise<T>(T data) where T : Event { + // we look up the list of subscribers using T, and then cast the callback to Func<T, Task>, and this breaks when + // T is Event rather than the derived type. the fix for this involves wrapping the callbacks with another delegate + // that performs the proper cast (or just rethinking this approach entirely), so we're just going to throw + // at run-time instead, which the smallest amount of functional testing will surface + if (typeof(T) == typeof(Event)) + { + throw new ArgumentException($"Raise can not be called with a type argument of type Event because the bus can't properly source the list of subscribers. Supply the derived Event Type when calling"); + } + Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 70bfc293..7cce5198 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -103,9 +103,11 @@ namespace slskd.Files // we should only get this far if: // 1) the given file exists and // 2) it is a symlink, meaning this line _SHOULD_ be guaranteed to return an instance of FileInfo. + FileInfo resolved; + try { - info = (FileInfo)info.ResolveLinkTarget(returnFinalTarget: true); + resolved = (FileInfo)info.ResolveLinkTarget(returnFinalTarget: true); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) { @@ -117,13 +119,13 @@ namespace slskd.Files throw new IOException($"Failed to resolve FileInfo for linked file '{info.Name}->{info.LinkTarget}': {ex.Message}", ex); } - if (info is null) + if (resolved is null) { Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", info.Name, info.LinkTarget); throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{info.Name}->{info.LinkTarget}'"); } - return info; + return resolved; } /// <summary> diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 33ef0b9b..f3f0efde 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -108,7 +108,7 @@ public class ScriptService foreach (var script in scriptsTriggeredByThisEventType) { - _ = Task.Run(() => + _ = Task.Run(async () => { Process process = default; var processId = Guid.NewGuid(); @@ -123,7 +123,7 @@ public class ScriptService if (string.IsNullOrEmpty(executable)) { - Log.Warning("Script '{Script}' will not be run: unable to determine script executable. Update the script configuration, or set your operating system's SHELL envar."); + Log.Warning("Script '{Script}' will not be run: unable to determine script executable. Update the script configuration, or set your operating system's SHELL envar.", script.Key); return; } @@ -202,17 +202,20 @@ public class ScriptService process.Start(); - process.WaitForExit(); + var errorTask = process.StandardError.ReadToEndAsync(); + var outputTask = process.StandardOutput.ReadToEndAsync(); + + await process.WaitForExitAsync(); sw.Stop(); - var error = process.StandardError.ReadToEnd(); + var error = await errorTask; if (!string.IsNullOrEmpty(error)) { throw new Exception($"STDERR: {Regex.Replace(error, @"\r\n?|\n", " ", RegexOptions.Compiled)}"); } - var result = process.StandardOutput.ReadToEnd(); + var result = await outputTask; var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output} (id: {ProcessId})", script.Key, sw.ElapsedMilliseconds, resultAsLines, processId); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 372dc998..879f76b7 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -535,7 +535,7 @@ namespace slskd if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - Log.Information("Forwarding logs to Grafana Loki instance at {LoggerLokiUrl}", OptionsAtStartup.Logger.Loki); + Log.Information("Forwarding logs to Grafana Loki"); } // bootstrap the ASP.NET application @@ -1178,12 +1178,14 @@ namespace slskd if (!options.Authentication.Disabled) { var auth = context.Request.Headers["Authorization"].FirstOrDefault(); - var providedCreds = auth?.Split(' ').Last(); + var providedCreds = auth?.Split(' ').Last() ?? string.Empty; var validCreds = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{options.Authentication.Username}:{options.Authentication.Password}")); + // use paranoid FixedTimeEquals to protect against time attacks if (string.IsNullOrEmpty(auth) || - !auth.StartsWith("Basic", StringComparison.InvariantCultureIgnoreCase) || - !string.Equals(providedCreds, validCreds, StringComparison.InvariantCultureIgnoreCase)) + !auth.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase) || + string.IsNullOrEmpty(providedCreds) || + !System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(providedCreds), Encoding.UTF8.GetBytes(validCreds))) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return; @@ -1299,7 +1301,7 @@ namespace slskd var record = new LogRecord() { Timestamp = logEvent.Timestamp.LocalDateTime, - Context = logEvent.Properties["SourceContext"].ToString().TrimStart('"').TrimEnd('"'), + Context = logEvent.Properties.TryGetValue("SourceContext", out var sourceContext) ? sourceContext.ToString().TrimStart('"').TrimEnd('"') : null, SubContext = logEvent.Properties.ContainsKey("SubContext") ? logEvent.Properties["SubContext"].ToString().TrimStart('"').TrimEnd('"') : null, Level = logEvent.Level.ToString(), Message = message.TrimStart('"').TrimEnd('"'), @@ -1331,11 +1333,11 @@ namespace slskd if (e.IsTerminating) { - Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", exception?.Message); } else { - Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception?.Message); } }; } diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 208e8f9d..8b107084 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -271,7 +271,8 @@ namespace slskd.Search // initialize the list of responses that we'll use to accumulate them // populated by the responseHandler we pass to SearchAsync - List<SearchResponse> responses = new(); + // responses arrive concurrently from many connections, so this must be thread safe + ConcurrentQueue<SearchResponse> responses = new(); options ??= new SearchOptions(); options = options.WithActions( @@ -308,7 +309,7 @@ namespace slskd.Search // the client state (e.g. disconnected) or a problem with the search (e.g. no terms) var soulseekSearchTask = Client.SearchAsync( query, - responseHandler: (response) => responses.Add(response), + responseHandler: (response) => responses.Enqueue(response), scope, token, options, @@ -377,7 +378,7 @@ namespace slskd.Search rateLimiter.Dispose(); CancellationTokens.TryRemove(id, out _); } - }, cancellationToken: cancellationTokenSource.Token); + }); // broadcast and return the _newly created_ search; it will continue to be updated in the background await SearchHub.BroadcastUpdateAsync(search); diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 64d703bd..4e328717 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -153,15 +153,13 @@ namespace slskd.Shares.API [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - try + if (Shares.StateMonitor.CurrentValue.Scanning) { - _ = Shares.ScanAsync(); - } - catch (ShareScanInProgressException) - { - return Conflict("A share scan is already in progress."); + return Conflict("A share scan is already in progress"); } + _ = Shares.ScanAsync(); + return Ok(); } diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 054561bf..40603892 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -391,7 +391,11 @@ namespace slskd.Shares await Scanner.ScanAsync(Local.Host.Shares, OptionsMonitor.CurrentValue.Shares, Local.Repository); Log.Debug("Backing up shared file cache database..."); - Local.Repository.BackupTo(ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)); + using (var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name)) + { + Local.Repository.BackupTo(backupRepository); + } + Log.Debug("Shared file cache database backup complete"); Log.Debug("Recomputing share statistics..."); @@ -443,7 +447,7 @@ namespace slskd.Shares { Log.Information("Share cache StorageMode is 'Memory'. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); + using var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { @@ -471,7 +475,7 @@ namespace slskd.Shares { Log.Warning("Share cache is missing, corrupt, or is out of date. Attempting to load from backup..."); - var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); + using var backupRepository = ShareRepositoryFactory.CreateFromHostBackup(Local.Host.Name); if (backupRepository.TryValidate(out _)) { diff --git a/src/slskd/Telemetry/API/MetricsController.cs b/src/slskd/Telemetry/API/MetricsController.cs index 1f0efee1..7954bd22 100644 --- a/src/slskd/Telemetry/API/MetricsController.cs +++ b/src/slskd/Telemetry/API/MetricsController.cs @@ -79,13 +79,13 @@ public class MetricsController : ControllerBase /// </summary> private List<Regex> KpiRegexes { get; } = [ - new Regex("slskd_.*", RegexOptions.Compiled), - new Regex("node_(?!cpu)", RegexOptions.Compiled), - new Regex("process_.*", RegexOptions.Compiled), - new Regex("dotnet_total_memory_bytes", RegexOptions.Compiled), - new Regex("system_runtime_[cpu_usage|working_set|alloc_total]", RegexOptions.Compiled), - new Regex("system_net_sockets.*", RegexOptions.Compiled), - new Regex("microsoft_aspnetcore_server_kestrel_[current|total]_connections", RegexOptions.Compiled), + new Regex("^slskd_.*", RegexOptions.Compiled), + new Regex("^node_(?!cpu)", RegexOptions.Compiled), + new Regex("^process_.*", RegexOptions.Compiled), + new Regex("^dotnet_total_memory_bytes", RegexOptions.Compiled), + new Regex("^system_runtime_(cpu_usage|working_set|alloc_total)", RegexOptions.Compiled), + new Regex("^system_net_sockets.*", RegexOptions.Compiled), + new Regex("^microsoft_aspnetcore_server_kestrel_(current|total)_connections", RegexOptions.Compiled), ]; /// <summary> diff --git a/src/slskd/Telemetry/API/MetricsHub.cs b/src/slskd/Telemetry/API/MetricsHub.cs index 5dcd4ecc..b6920ef0 100644 --- a/src/slskd/Telemetry/API/MetricsHub.cs +++ b/src/slskd/Telemetry/API/MetricsHub.cs @@ -42,7 +42,7 @@ public interface IMetricsHub Task Update(object metrics); } -[Authorize] +[Authorize(Policy = AuthPolicy.Any)] public class MetricsHub : Hub<IMetricsHub> { public MetricsHub(MetricsService metricsService) diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index ccb45daf..02b962e1 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -104,7 +104,7 @@ public class ReportsController : ControllerBase if (!string.IsNullOrWhiteSpace(direction)) { - if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -205,7 +205,7 @@ public class ReportsController : ControllerBase if (!string.IsNullOrWhiteSpace(direction)) { - if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -263,7 +263,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -276,12 +276,12 @@ public class ReportsController : ControllerBase return BadRequest("End time must be later than start time"); } - if (!Enum.TryParse<LeaderboardSortBy>(sortBy, out var parsedSortBy)) + if (!Enum.TryParse<LeaderboardSortBy>(sortBy, out var parsedSortBy) || !Enum.IsDefined(parsedSortBy)) { return BadRequest($"Invalid sortBy; expected one of: {string.Join(", ", Enum.GetNames(typeof(LeaderboardSortBy)))}"); } - if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder)) + if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder) || !Enum.IsDefined(parsedSortOrder)) { return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}"); } @@ -425,7 +425,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } @@ -438,7 +438,7 @@ public class ReportsController : ControllerBase return BadRequest("End time must be later than start time"); } - if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder)) + if (!Enum.TryParse<SortOrder>(sortOrder, out var parsedSortOrder) || !Enum.IsDefined(parsedSortOrder)) { return BadRequest($"Invalid sortOrder; expected one of: {string.Join(", ", Enum.GetNames(typeof(SortOrder)))}"); } @@ -502,7 +502,7 @@ public class ReportsController : ControllerBase return BadRequest("Direction is required"); } - if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection)) + if (!Enum.TryParse<TransferDirection>(direction, ignoreCase: true, out var parsedDirection) || !Enum.IsDefined(parsedDirection)) { return BadRequest($"Invalid direction; expected one of: {string.Join(", ", Enum.GetNames(typeof(TransferDirection)))}"); } diff --git a/src/slskd/Telemetry/PrometheusService.cs b/src/slskd/Telemetry/PrometheusService.cs index 9c1e46c5..a26c8283 100644 --- a/src/slskd/Telemetry/PrometheusService.cs +++ b/src/slskd/Telemetry/PrometheusService.cs @@ -34,6 +34,7 @@ namespace slskd.Telemetry; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -137,7 +138,9 @@ public class PrometheusService var groups = match.Groups; var sampleName = groups[1].Value; var sampleLabels = groups[2].Value; - var sampleValue = double.Parse(groups[3].Value); + + // the exposition format is culture invariant, and uses '+Inf'/'-Inf' which .NET doesn't recognize + var sampleValue = double.Parse(groups[3].Value.Replace("Inf", "Infinity"), NumberStyles.Float, CultureInfo.InvariantCulture); var labels = ParseLabels(sampleLabels); if (type.Equals("counter") || type.Equals("gauge")) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index cb9423bc..5a5fe699 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -722,9 +722,9 @@ namespace slskd.Transfers.Downloads var transfer = context.Transfers.Find(id); - if (transfer == default) + if (transfer == default || transfer.Direction != TransferDirection.Download) { - throw new NotFoundException($"No download matching id ${id}"); + throw new NotFoundException($"No download matching id {id}"); } var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); @@ -1059,6 +1059,12 @@ namespace slskd.Transfers.Downloads t.EndedAt ??= DateTime.UtcNow; + // Retry.Do() wraps failures in an AggregateException; use the most recent so that the state reflects what happened + if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count > 0) + { + exception = aggregate.InnerExceptions.Last(); + } + // Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking // exceptions in a database. when we encounter one of these, drop the first segment. var m = exception.Message; @@ -1070,6 +1076,7 @@ namespace slskd.Transfers.Downloads { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, + TransferRejectedException => TransferStates.Rejected, _ => TransferStates.Errored, }; } @@ -1221,20 +1228,6 @@ namespace slskd.Transfers.Downloads transfer.EnqueuedAt ??= DateTime.UtcNow; } - // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer - // *might* still have remaining retry attempts. leave this non-committal for now, and allow - // the final update after all retry attempts have been exhausted to add it. - // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all - // retries is to look for this flag - if (args.Transfer.State.HasFlag(TransferStates.Completed) - && !args.Transfer.State.HasFlag(TransferStates.Succeeded) - && transfer.Attempts < retryOptions.Attempts) - { - transfer.State = TransferStates.Queued | TransferStates.Locally; - } - - transfer = transfer.WithSoulseekTransfer(args.Transfer); - Telemetry.Metrics.Update(() => { if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) @@ -1254,6 +1247,18 @@ namespace slskd.Transfers.Downloads stateHistory.Add(transfer.State); + // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer + // *might* still have remaining retry attempts. leave this non-committal for now, and allow + // the final update after all retry attempts have been exhausted to add it. + // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all + // retries is to look for this flag + if (args.Transfer.State.HasFlag(TransferStates.Completed) + && !args.Transfer.State.HasFlag(TransferStates.Succeeded) + && transfer.Attempts < retryOptions.Attempts) + { + transfer.State = TransferStates.Queued | TransferStates.Locally; + } + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } @@ -1553,11 +1558,10 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); @@ -1569,11 +1573,10 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1); diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 9aff5195..3ad27e63 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -70,7 +70,7 @@ namespace slskd.Transfers.Uploads /// (such as the upload not being tracked currently). /// </summary> /// <param name="transfer">The Transfer to complete.</param> - /// <returns>A value indicating whether a problem was encountered.</return> + /// <returns>A value indicating whether a problem was encountered.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> bool TryComplete(Transfer transfer); @@ -235,7 +235,7 @@ namespace slskd.Transfers.Uploads // todo: deprecate this with improved cancellation handling; it shouldn't be needed if (!upload.TaskCompletionSource.Task.IsCompleted) { - Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename)); + Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename), upload.Username); upload.TaskCompletionSource.TrySetCanceled(); } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 35bb9468..05251ecf 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -516,11 +516,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); @@ -532,11 +531,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); @@ -548,11 +546,10 @@ namespace slskd.Transfers.Uploads { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - TryFail(transfer.Id, exception: ex); - - // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + TryFail(transfer.Id, exception: ex); + // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 51b47d5b..046a87e5 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -452,7 +452,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Status = new Status { IsPrivileged = true } }, + addValue: new User() { Username = username, Status = new Status { IsPrivileged = true } }, updateValueFactory: (key, user) => user with { Username = username, Status = user.Status with { IsPrivileged = true } }); } } @@ -572,7 +572,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Statistics = statistics }, + addValue: new User() { Username = username, Statistics = statistics }, updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); } @@ -580,7 +580,7 @@ namespace slskd.Users { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Status = status }, + addValue: new User() { Username = username, Status = status }, updateValueFactory: (key, user) => user with { Username = username, Status = status }); } } |
