diff options
117 files changed, 6584 insertions, 1215 deletions
diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 00000000..79556b83 --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "dotnet-outdated-tool": { + "version": "4.8.1", + "commands": [ + "dotnet-outdated" + ], + "rollForward": false + }, + "dotnet-affected": { + "version": "7.0.1", + "commands": [ + "dotnet-affected" + ], + "rollForward": false + } + } +}
\ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 8bec6cd6..5d63b709 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: false contact_links: - name: Support via Discord - url: https://discord.gg/GjDW5r8u + url: https://discord.gg/ZptUkTWXbh about: Chat with users and devs on support and setup related topics.
\ No newline at end of file @@ -4,14 +4,13 @@ # build static web content # note: pin this to amd64 to speed it up, it is prohibitively slow under QEMU FROM --platform=$BUILDPLATFORM node:22-alpine AS web -ARG VERSION=0.0.1.65534-local WORKDIR /slskd COPY bin bin/. COPY src/web src/web/. -RUN sh ./bin/build --web-only --version $VERSION +RUN sh ./bin/build --web-only --version 0.0.1.65534-local # build, test, and publish application binaries # note: this needs to be pinned to an amd64 image in order to publish armv7 binaries @@ -37,10 +36,6 @@ RUN bash ./bin/publish --no-prebuild --platform $TARGETPLATFORM --version $VERSI # application FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-noble AS slskd ARG TARGETPLATFORM -ARG TAG=0.0.1 -ARG VERSION=0.0.1.65534-local -ARG REVISION=0 -ARG BUILD_DATE RUN apt-get update && apt-get install --no-install-recommends -y \ jq \ @@ -62,6 +57,11 @@ RUN bash -c 'mkdir -p /.net \ HEALTHCHECK --interval=60s --timeout=3s --start-period=60m --retries=3 CMD wget -q -O - http://localhost:${SLSKD_HTTP_PORT}/health +ARG TAG=0.0.1 +ARG VERSION=0.0.1.65534-local +ARG REVISION=0 +ARG BUILD_DATE + ENV SHELL=/usr/bin/bash \ DOTNET_EnableDiagnostics=0 \ DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \ @@ -81,9 +81,9 @@ ENV SHELL=/usr/bin/bash \ LABEL org.opencontainers.image.title=slskd \ org.opencontainers.image.description="A modern client-server application for the Soulseek file sharing network" \ - org.opencontainers.image.authors="JP Dillingham, slskd Contributors" \ + org.opencontainers.image.authors="JP Dillingham" \ org.opencontainers.image.vendor="slskd Project" \ - org.opencontainers.image.licenses=AGPL-3.0 \ + org.opencontainers.image.licenses=AGPL-3.0-only \ org.opencontainers.image.url=https://slskd.org \ org.opencontainers.image.source=https://github.com/slskd/slskd \ org.opencontainers.image.documentation=https://github.com/slskd/slskd \ diff --git a/bin/benchmark b/bin/benchmark new file mode 100755 index 00000000..33e11f33 --- /dev/null +++ b/bin/benchmark @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -e +set -o pipefail + +test_name="" + +while test $# -gt 0; do + case "$1" in + -h|--help) + echo '' + echo 'usage: benchmark --test <name>' + echo '' + echo 'options:' + echo '-h, --help show help' + echo '--test NAME name (or substring, case-insensitive) of the benchmark test class to run' + echo '' + echo 'examples:' + echo ' benchmark --test helloworld' + echo '' + exit 0 + ;; + --test) + shift + test_name=$1 + shift + ;; + *) + break + ;; + esac +done + +if [ -z "$test_name" ]; then + echo 'error: --test is required' + exit 1 +fi + +dotnet test tests/slskd.Tests.Benchmarks -c Release -v q --nologo --filter "FullyQualifiedName~$test_name" --logger "console;verbosity=detailed" \ + | sed -n '/BenchmarkRunner: Start/,/BenchmarkRunner: End/p' @@ -39,7 +39,12 @@ while test $# -gt 0; do esac done -if [ -z "$version" ]; then +if [ -z "$version" ]; then + if ! command -v git >/dev/null 2>&1; then + echo "💥 error: git is required to compose the version, but the executable couldn't be found" + exit 1 + fi + tag=$(git describe --tags --abbrev=0) sha=$(git rev-parse --short HEAD) version=$tag+$sha @@ -28,3 +28,11 @@ else echo $'\n🛠️ dotnet format --verbosity normal\n' dotnet format --verbosity normal fi + +if [ "$fix" == false ]; then + echo $'\n🛠️ npm run lint\n' + (cd src/web && npm run lint) +else + echo $'\n🛠️ npm run lint:fix\n' + (cd src/web && npm run lint:fix) +fi diff --git a/bin/test b/bin/test new file mode 100644 index 00000000..1c4ccb6d --- /dev/null +++ b/bin/test @@ -0,0 +1,121 @@ +#!/usr/bin/env bash +set -e +set -o pipefail + +affected=false +from="" +unit=false +integration=false +web=false + +while test $# -gt 0; do + case "$1" in + -h|--help) + echo '' + echo 'usage: test [options]' + echo '' + echo 'options:' + echo '-h, --help show help' + echo '--unit run only unit tests' + echo '--integration run only integration tests' + echo '--dotnet run only unit and integration tests' + echo '--web run only frontend tests' + echo '--all run unit, integration, and frontend tests' + echo '--affected run only tests for projects affected by changes (uses dotnet-affected)' + echo '--from REF branch or commit to compare against when using --affected. defaults to HEAD' + echo '' + echo 'with no options, only unit tests are run.' + echo '' + echo 'examples:' + echo ' test' + echo ' test --all' + echo ' test --web' + echo ' test --affected --from master' + echo '' + exit 0 + ;; + --unit) + unit=true + shift + ;; + --integration) + integration=true + shift + ;; + --dotnet) + unit=true + integration=true + shift + ;; + --web) + web=true + shift + ;; + --all) + unit=true + integration=true + web=true + shift + ;; + --affected) + affected=true + shift + ;; + --from) + shift + from=$1 + shift + ;; + *) + echo "error: unknown option '$1'" + exit 1 + ;; + esac +done + +if [ "$unit" == false ] && [ "$integration" == false ] && [ "$web" == false ]; then + unit=true +fi + +if [ "$unit" == true ] || [ "$integration" == true ]; then + pattern="" + + if [ "$unit" == true ]; then + pattern="Tests\.Unit\.csproj$" + fi + + if [ "$integration" == true ]; then + pattern="${pattern:+$pattern|}Tests\.Integration\.csproj$" + fi + + if [ "$affected" == true ]; then + args=(--format text --dry-run) + + if [ -n "$from" ]; then + args+=(--from "$from") + fi + + echo $'\n🔍 dotnet tool run dotnet-affected --' "${args[@]}" $'\n' + + dotnet tool restore > /dev/null + projects=$(dotnet tool run dotnet-affected -- "${args[@]}" | tr -d '\r' | grep -E '\.csproj$' | grep -E "$pattern" || true) + else + projects=$(find tests -name '*.csproj' | grep -E "$pattern" || true) + fi + + if [ -z "$projects" ]; then + echo $'\n🤷 no test projects to run\n' + else + while IFS= read -r project; do + echo $'\n\t🧪 dotnet test' "$project" $'\n' + dotnet test "$project" + done <<< "$projects" + fi +fi + +if [ "$web" == true ]; then + echo $'\n\t🧪 npm run test-unattended\n' + (cd src/web && npm run test-unattended) +fi + +echo $'\n\t🎉 tests passed!\n' diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 99bfebfb..a30813c4 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -37,9 +37,6 @@ # instance_name: my_agent # make sure the top-level instance_name of the agent matches! # secret: <a 16-255 character string unique to this agent> # cidr: 0.0.0.0/0,::/0 -# permissions: -# file: -# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # directories: # incomplete: ~ # downloads: ~ @@ -202,7 +199,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 +# no_disk: false # no_color: false # loki: ~ # metrics: @@ -240,6 +237,7 @@ # write: 16384 # transfer: 262144 # write_queue: 250 +# mtu: 1500 # proxy: # enabled: false # address: ~ diff --git a/docs/config.md b/docs/config.md index c8a8fca2..d864458b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -834,6 +834,21 @@ soulseek: password: ~ ``` +### MTU + +If needed, the MTU advertised to the server can be set. + +| Command-Line | Environment Variable | Description | +| ------------------- | ----------------------- | ---------------------------------------------------------------------------------- | +| `--slsk-server-mtu` | `SLSKD_SLSK_SERVER_MTU` | The maximum TCP transmission unit size advertised to the server (0 for OS default) | + +#### **YAML** +```yaml +soulseek: + connection: + mtu: 1500 +``` + ## Diagnostic Level The diagnostic level option is passed to the Soulseek.NET configuration and determines the level of detail the library produces diagnostic messages. This option should generally be left to `Info` or `Warning` but can be set to `Debug` if more verbose logging is desired. @@ -1299,8 +1314,8 @@ Notification API calls are made up to the maximum configured retry count and the | Command-Line | Environment Variable | Description | | ------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `--pushbullet` | `SLSKD_PUSHBULLET` | Determines whether Pushbullet integration is enabled | -| `--pushbullet-token` | `SLSKD_PUSHBULLET_TOKEN` | The Pushbullet API access token | -| `--pushbullet-prefix` | `SLSKD_PUSHBULLET_PREFIX` | The prefix for notification titles | +| `--pushbullet-token` | `SLSKD_PUSHBULLET_ACCESS_TOKEN` | The Pushbullet API access token | +| `--pushbullet-prefix` | `PUSHBULLET_NOTIFICATION_PREFIX` | The prefix for notification titles | | `--pushbullet-notify-on-pm` | `SLSKD_PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE` | Determines whether to send a notification when a private message is received | | `--pushbullet-notify-on-room-mention` | `SLSKD_PUSHBULLET_NOTIFY_ON_ROOM_MENTION` | Determines whether to send a notification when the current user's name is mentioned in a chat room | | `--pushbullet-retry-attempts` | `SLSKD_PUSHBULLET_RETRY_ATTEMPTS` | The number of times failing API calls will be retried | @@ -1336,13 +1351,13 @@ instance_name: default ## Logging Options and Configurable Loggers -By default, the application logs to console with colors enabled. Logging to disk is optional, and if enabled, logs will be written to `/logs` in the application directory. +By default, the application logs to console with colors enabled, and to files in the `/logs` subdirectory of the application directory with extended timestamps and colors disabled. Console colors can be disabled via typical application configuration described below, or by setting the environment variable `NO_COLOR` in accordance with https://no-color.org/. | Command Line | Environment Variable | Description | | ------------------ | ------------------------------ | ---------------------------------- | -| `--disk-logger` | `SLSKD_DISK_LOGGER` | Enable logging to disk | +| `--no-disk-logger` | `SLSKD_NO_DISK_LOGGER` | Disable logging to disk | | `--no-color` | `SLSKD_NO_COLOR` or `NO_COLOR` | Disable console log colors | Logs can optionally be forwarded to external services, and the targets can be expanded to any service supported by a [Serilog Sink](https://github.com/serilog/serilog/wiki/Provided-Sinks). Support for targets is added on an as-needed basis and within reason. @@ -1357,7 +1372,7 @@ The current list of available targets is: ```yaml logger: loki: ~ - disk: false + no_disk: false no_color: false ``` diff --git a/docs/system_requirements.md b/docs/system_requirements.md index e3a7e69b..bebc7217 100644 --- a/docs/system_requirements.md +++ b/docs/system_requirements.md @@ -6,4 +6,35 @@ Designed to run on a minimum of a Raspberry Pi 2 (or equivalent), or any system * at least 512mb RAM * at least 150mb disk space -Users concerned about optimal performance should consider something faster.
\ No newline at end of file +Users concerned about optimal performance should consider something faster. + +# Storage Hardware + +* SSD/NVMe: Ideal +* HDD: Shouldn't notice any issues +* Flash: It should work but you're probably going to kill the card + +# Filesystems + +## Supported + +* ext4 +* NTFS +* XFS +* APFS +* HFS+ + +## Might Work but Complaints Will Be Ignored + +* ZFS +* Btrfs +* FAT32 +* exFAT + +## Not Supported + +* NFS +* SMB/CIFS +* APF +* Distributed databases (Ceph, GlusterFS, Lustre, HDFS) +* Anything that puts a network between slskd and `/app` @@ -46,21 +46,55 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "docs", "docs", "{53D80066-A docs\docker.md = docs\docker.md EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "slskd.Tests.Benchmarks", "tests\slskd.Tests.Benchmarks\slskd.Tests.Benchmarks.csproj", "{25F150B1-48F8-46B6-9B17-1E10D7004E6E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|x64.ActiveCfg = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|x64.Build.0 = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|x86.ActiveCfg = Debug|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Debug|x86.Build.0 = Debug|Any CPU {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|Any CPU.Build.0 = Release|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|x64.ActiveCfg = Release|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|x64.Build.0 = Release|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|x86.ActiveCfg = Release|Any CPU + {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC}.Release|x86.Build.0 = Release|Any CPU {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|x64.ActiveCfg = Debug|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|x64.Build.0 = Debug|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|x86.ActiveCfg = Debug|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Debug|x86.Build.0 = Debug|Any CPU {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|Any CPU.ActiveCfg = Release|Any CPU {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|Any CPU.Build.0 = Release|Any CPU -EndGlobalSection + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|x64.ActiveCfg = Release|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|x64.Build.0 = Release|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|x86.ActiveCfg = Release|Any CPU + {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A}.Release|x86.Build.0 = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|x64.ActiveCfg = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|x64.Build.0 = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|x86.ActiveCfg = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Debug|x86.Build.0 = Debug|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|Any CPU.Build.0 = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|x64.ActiveCfg = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|x64.Build.0 = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|x86.ActiveCfg = Release|Any CPU + {25F150B1-48F8-46B6-9B17-1E10D7004E6E}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection @@ -68,6 +102,7 @@ EndGlobalSection {E9EA3F80-07F4-4BEF-A233-5D87EF7D9ABC} = {5478DBA0-A595-4273-9F9D-3D5E11A8ECE8} {ED2A1CCD-9C47-4AB5-AF00-84EF507E2402} = {6186A99C-FE43-4C97-8A6A-F27432F44282} {2777623C-3DBE-4EB4-A092-DFEA7BD8EA3A} = {137724E1-1613-4EFC-BD67-399A620AEABF} + {25F150B1-48F8-46B6-9B17-1E10D7004E6E} = {137724E1-1613-4EFC-BD67-399A620AEABF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A793ED59-76F4-4874-846B-2A199C92A48E} diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 475e4288..208de9e1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -128,19 +128,19 @@ namespace slskd Console.CancelKeyPress += (_, args) => { ShuttingDown = true; - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Log.Warning("Received SIGINT"); }; 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(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); 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; } @@ -418,7 +419,15 @@ namespace slskd // os-specific keepalive is configured for long-lived connections for the server and distributed parent/children var serverOptions = connectionOptions.With( inactivityTimeout: -1, // don't disconnect due to inactivity - configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection)); + configureSocket: socket => + { + ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection); + + if (OptionsAtStartup.Soulseek.Connection.Mtu.HasValue) + { + ConfigureSocketMtu(socket, OptionsAtStartup.Soulseek.Connection.Mtu.Value); + } + }); var distributedOptions = connectionOptions.With( writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance @@ -568,6 +577,35 @@ namespace slskd } } + private void ConfigureSocketMtu(Socket socket, int mtu) + { + /* + limits the size of the packets sent and received on this connection to the given MTU. there's no per-socket MTU setting, + so this is done by setting TCP_MAXSEG to the MTU minus the IPv4 and TCP headers (20 bytes each) + + Windows is skipped because it only supports reading TCP_MAXSEG, not setting it + see: https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options + and: https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-getsockopt + */ + if (!(System.OperatingSystem.IsLinux() || System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD())) + { + return; + } + + try + { + const int IPPROTO_TCP = 6; + const int TCP_MAXSEG = 2; + const int IPV4_AND_TCP_HEADER_SIZE = 40; + + socket.SetRawSocketOption(IPPROTO_TCP, TCP_MAXSEG, BitConverter.GetBytes(mtu - IPV4_AND_TCP_HEADER_SIZE)); + } + catch (SocketException ex) + { + Log.Warning("Failed to set the MTU of the server connection to {MTU}: {Message}", mtu, ex.Message); + } + } + private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { Metrics.Enqueue.RequestsReceived.Inc(1); @@ -704,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. @@ -1257,28 +1295,39 @@ namespace slskd RecurseSubdirectories = true, }; - var files = System.IO.Directory.GetFiles(directory, "*", options) - .Select(filename => Files.ResolveFileInfo(filename)) - .Where(file => file.LastAccessTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value)); - - Log.Debug("Found {Count} files of need of pruning", files.Count()); + var fileInfo = new DirectoryInfo(directory) + .EnumerateFiles("*", options) + .Where(file => + { + try + { + return file.LastWriteTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to access file {File} during pruning: {Message}", file.Name, ex.Message); + return false; + } + }); - int errors = 0; + int errorCount = 0; + int fileCount = 0; - foreach (var file in files) + foreach (var file in fileInfo) { try { file.Delete(); + fileCount++; } catch (Exception ex) { - errors++; + errorCount++; Log.Warning(ex, "Failed to prune file {File}: {Message}", file, ex.Message); } } - Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", files.Count() - errors, errors); + Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", fileCount, errorCount); } catch (Exception ex) { @@ -1391,16 +1440,30 @@ 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); } try { - var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); + var upload = Transfers.Uploads.Query(q => + q + .Where(t => t.Username == username && t.Filename == filename && t.EnqueuedAt != null) + .OrderByDescending(t => t.EnqueuedAt) + .Take(1), + includeRemoved: false) + .FirstOrDefault(); + + // transfer might not be in the queue, or might not exist at all + if (upload is null) + { + return Task.FromResult<int?>(null); + } + + var place = Transfers.Uploads.Queue.EstimatePosition(upload); return Task.FromResult((int?)place); } - catch (NotFoundException) + catch (NotFoundException) // transfer is not in the queue { return Task.FromResult<int?>(null); } @@ -1503,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(); @@ -1567,7 +1637,15 @@ namespace slskd serverPatch = connectionPatch.With( inactivityTimeout: -1, // don't disconnect due to inactivity - configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, options: connection)); + configureSocket: socket => + { + ConfigureSocketKeepaliveOptions(socket, options: connection); + + if (connection.Mtu.HasValue) + { + ConfigureSocketMtu(socket, connection.Mtu.Value); + } + }); distributedPatch = connectionPatch.With( writeQueueSize: connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance @@ -1738,7 +1816,7 @@ namespace slskd // note: the following uses cached user data to determine group, so if the user's data // isn't cached they may get a forecast based on the wrong group. this is a hot path though, // and we don't want to incur the massive penalties that would caching data for each request. - var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); + var (groupName, totalSlots, freeSlots, forecastedPosition) = Transfers.Uploads.Queue.ForecastPosition(username); Log.Debug("Sending search response with {Count} files to {Username} for query '{Query}'", results.Count(), username, query.SearchText); @@ -1746,7 +1824,7 @@ namespace slskd Client.Username, token, uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - hasFreeUploadSlot: forecastedPosition == 0, + hasFreeUploadSlot: freeSlots > 0, queueLength: forecastedPosition, fileList: results); } @@ -1946,12 +2024,11 @@ namespace slskd // we are deliberately skipping it here; if the username is watched // leech detection works and they get accurate info, if not, they won't var groupName = await Users.GetOrFetchGroupAsync(username); - var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); // forecast the position at which this user would enter the queue if they were to request // a file at this moment. this will be zero if a slot is available and the transfer would // begin immediately - var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); + var (group, totalSlots, freeSlots, forecastedPosition) = Transfers.Uploads.Queue.ForecastPosition(username); // if i get a user's info to determine whether i want to download files from them, // i want to know how many slots they have, which gives me an idea of how fast their @@ -1960,9 +2037,9 @@ namespace slskd // revisited 3 years later: why was it important to leave this comment?? var info = new UserInfo( description: Options.Soulseek.Description, - uploadSlots: group.Slots, + uploadSlots: totalSlots, queueLength: forecastedPosition, - hasFreeUploadSlot: forecastedPosition == 0, + hasFreeUploadSlot: freeSlots > 0, picture: pictureBytes); return info; diff --git a/src/slskd/Common/Authentication/AuthRole.cs b/src/slskd/Common/Authentication/AuthRole.cs index 958cc143..e9cd38aa 100644 --- a/src/slskd/Common/Authentication/AuthRole.cs +++ b/src/slskd/Common/Authentication/AuthRole.cs @@ -32,6 +32,8 @@ namespace slskd { + using slskd.Authentication; + /// <summary> /// Authentication roles. /// </summary> @@ -40,9 +42,8 @@ namespace slskd /// </remarks> public static class AuthRole { - public const string AdministratorOnly = "Administrator"; - public const string ReadWriteOrAdministrator = "ReadWrite,Administrator"; - public const string GuestOrAdministrator = "Guest,Administrator"; - public const string Any = "ReadOnly,ReadWrite,Guest,Administrator"; + public const string AdministratorOnly = $"{nameof(Role.Administrator)}"; + public const string ReadWriteOrAdministrator = $"{nameof(Role.ReadWrite)},{nameof(Role.Administrator)}"; + public const string Any = $"{nameof(Role.ReadOnly)},{nameof(Role.ReadWrite)},{nameof(Role.Administrator)}"; } } diff --git a/src/slskd/Common/Authentication/Role.cs b/src/slskd/Common/Authentication/Role.cs index d081c198..42314c2d 100644 --- a/src/slskd/Common/Authentication/Role.cs +++ b/src/slskd/Common/Authentication/Role.cs @@ -36,7 +36,6 @@ namespace slskd.Authentication { ReadOnly = 0, ReadWrite = 1, - Guest = 2, Administrator = 3, } } diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 95721163..5affdf5c 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> @@ -229,6 +231,25 @@ namespace slskd } /// <summary> + /// Safely cancels this <see cref="CancellationTokenSource"/> without throwing if it is disposed. + /// </summary> + /// <param name="cts">The CancellationTokenSource instance.</param> + /// <param name="swallowObjectDisposedException">A value indicating whether to swallow ObjectDisposedException, if it occurs.</param> + /// <returns>A value indicating whether the cancellation completed successfully.</returns> + public static bool Cancel(this CancellationTokenSource cts, bool swallowObjectDisposedException) + { + try + { + cts.Cancel(); + return true; + } + catch (ObjectDisposedException) when (swallowObjectDisposedException) + { + return false; + } + } + + /// <summary> /// Recursively retrieves all properties. /// </summary> /// <param name="type">The type from which to retrieve properties.</param> @@ -358,7 +379,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 +502,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/Dumper.cs b/src/slskd/Common/Dumper.cs deleted file mode 100644 index 27304873..00000000 --- a/src/slskd/Common/Dumper.cs +++ /dev/null @@ -1,176 +0,0 @@ -// <copyright file="Dumper.cs" company="JP Dillingham"> -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ This program is free software: you can redistribute it and/or modify -// │ it under the terms of the GNU Affero General Public License as published -// │ by the Free Software Foundation, version 3. -// │ -// │ This program is distributed in the hope that it will be useful, -// │ but WITHOUT ANY WARRANTY; without even the implied warranty of -// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// │ GNU Affero General Public License for more details. -// │ -// │ You should have received a copy of the GNU Affero General Public License -// │ along with this program. If not, see https://www.gnu.org/licenses/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// </copyright> - -namespace slskd -{ - using System; - using System.Diagnostics; - using System.IO; - using System.Net.Http; - using System.Runtime.InteropServices; - using System.Threading.Tasks; - - /// <summary> - /// Dumps the contents of the application's memory to a .dmp file using dotnet-dump. - /// </summary> - /// <remarks> - /// <para> - /// Monitor https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump for tool updates. Currently supported - /// runtime IDs: - /// </para> - /// <list type="bullet"> - /// <listheader>Currently supported runtime IDs:</listheader> - /// <item>https://aka.ms/dotnet-dump/win-x86</item> - /// <item>https://aka.ms/dotnet-dump/win-x64</item> - /// <item>https://aka.ms/dotnet-dump/win-arm</item> - /// <item>https://aka.ms/dotnet-dump/win-arm64</item> - /// <item>https://aka.ms/dotnet-dump/osx-x64</item> - /// <item>https://aka.ms/dotnet-dump/linux-x64</item> - /// <item>https://aka.ms/dotnet-dump/linux-arm</item> - /// <item>https://aka.ms/dotnet-dump/linux-arm64</item> - /// <item>https://aka.ms/dotnet-dump/linux-musl-x64</item> - /// <item>https://aka.ms/dotnet-dump/linux-musl-arm64</item> - /// <item></item> - /// </list> - /// </remarks> - public class Dumper : IDisposable - { - private static readonly string URLTemplate = "https://aka.ms/dotnet-dump/$RID"; - - private string BinFile { get; set; } - private bool Disposed { get; set; } - - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - public async Task<string> DumpAsync() - { - BinFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - var outputFile = Path.Combine(Path.GetTempPath(), $"slskd_{Path.GetRandomFileName()}.dmp"); - - var url = URLTemplate.Replace("$RID", GetRID()); - - await Download(url, BinFile); - - if (!System.OperatingSystem.IsWindows()) - { - await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\""); - } - - await ExecAsync(BinFile, $"collect --process-id {Environment.ProcessId} --type full --output {outputFile}"); - - return outputFile; - } - - protected virtual void Dispose(bool disposing) - { - if (!Disposed) - { - if (disposing) - { - TryDelete(BinFile); - } - - Disposed = true; - } - } - - private async Task Download(string url, string destination) - { - using var http = new HttpClient(); - - using var localStream = new FileStream(destination, FileMode.OpenOrCreate); - using var remoteStream = await http.GetStreamAsync(url); - - await remoteStream.CopyToAsync(localStream); - } - - private async Task ExecAsync(string bin, string args) - { - using var process = new Process(); - process.StartInfo.FileName = bin; - process.StartInfo.Arguments = args; - process.Start(); - await process.WaitForExitAsync(); - } - - private string GetRID() - { - // one of: x86, x64, arm, arm64, wasm, s390x - var arch = RuntimeInformation.ProcessArchitecture.ToString().ToLower(); - - // .RuntimeIdentifier returns a very specific (e.g. win10-x64) RID, and we need a generic one (e.g. win-x64). rather - // than trying to hack this up to derive a generic RID, only inspect this to see if this build targeted musl libc (we - // can't get this any other way) - var isMusl = RuntimeInformation.RuntimeIdentifier.ToLower().Contains("musl"); - - string os = default; - - // seems like there should be a way to just retrieve this, but there is not as of .NET 6 - if (System.OperatingSystem.IsLinux()) - { - os = "linux"; - } - else if (System.OperatingSystem.IsWindows()) - { - os = "win"; - } - else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD()) - { - os = "osx"; - } - - if (os == default) - { - throw new PlatformNotSupportedException($"Unable to determine operating system. RID is {RuntimeInformation.RuntimeIdentifier}; did someone forget to update Dumper.cs to reflect .NET targeting changes?"); - } - - return $"{os}-{(isMusl ? "musl-" : string.Empty)}{arch}"; - } - - private bool TryDelete(string file) - { - try - { - File.Delete(file); - return true; - } - catch (FileNotFoundException) - { - return false; - } - } - } -}
\ No newline at end of file diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 6a6dea22..cb7991d2 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -233,6 +233,61 @@ public static class FileSafety public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// <summary> + /// Indicates whether the specified <paramref name="subDirectory"/> is a subdirectory within (or is) the <paramref name="root"/>. + /// </summary> + /// <param name="root">The potential root path.</param> + /// <param name="subDirectory">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>A value indicating whether the specified path is a subdirectory of (or is) the root.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified root is null, empty, or consists of only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified root or subdirectories are not absolute or contain traversal segments.</exception> + public static bool IsRootDirectoryOf(string root, string subDirectory, OperatingSystem? os = null) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(root); + + if (!IsPathAbsolute(root, os)) + { + throw new ArgumentException("Specified root path must be absolute"); + } + + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root path contains traversal segments"); + } + + if (!IsPathAbsolute(subDirectory, os)) + { + throw new ArgumentException("Specified subdirectory path must be absolute"); + } + + if (ContainsTraversalSegments(subDirectory)) + { + throw new ArgumentException("Specified subdirectory path contains traversal segments"); + } + + var stringComparison = StringComparison.Ordinal; + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) + { + stringComparison = StringComparison.OrdinalIgnoreCase; + } + + return subDirectory.TrimEnd('/', '\\').Equals(root.TrimEnd('/', '\\'), stringComparison) || + subDirectory.StartsWith(root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar, stringComparison); + } + + /// <summary> + /// Indicates whether the specified <paramref name="root"/> is the parent path of (or is) the <paramref name="subDirectory"/>. + /// </summary> + /// <param name="subDirectory">The potential subdirectory.</param> + /// <param name="root">The path to check.</param> + /// <param name="os">An optional operating system override, for testing.</param> + /// <returns>A value indicating whether the specified path is the parent of (or is) the subdirectory.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified root is null, empty, or consists of only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified root or subdirectories are not absolute or contain traversal segments.</exception> + public static bool IsSubDirectoryOf(string subDirectory, string root, OperatingSystem? os = null) => IsRootDirectoryOf(root, subDirectory, os); + + /// <summary> /// Returns the filename from the specified <paramref name="path"/>, properly /// handling both forward and backslashes and removing invalid characters. /// </summary> 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/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs index 11d64b88..440f25ae 100644 --- a/src/slskd/Common/TokenBucket.cs +++ b/src/slskd/Common/TokenBucket.cs @@ -92,7 +92,7 @@ namespace slskd /// </summary> public class TokenBucket : ITokenBucket, IDisposable { - private TaskCompletionSource<bool> waitForReset = new(); + private TaskCompletionSource<bool> waitForReset = new(TaskCreationOptions.RunContinuationsAsynchronously); /// <summary> /// Initializes a new instance of the <see cref="TokenBucket"/> class. @@ -243,6 +243,6 @@ namespace slskd } private void Reset() - => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource<bool>()).SetResult(true); + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously)).SetResult(true); } } 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/FileDoesNotExistAttribute.cs b/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs index 9336b064..03f72d76 100644 --- a/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs +++ b/src/slskd/Common/Validation/FileDoesNotExistAttribute.cs @@ -42,7 +42,7 @@ namespace slskd.Validation { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value is not null && !string.IsNullOrEmpty(value.ToString())) { var file = Path.GetFullPath(value?.ToString()); diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs index c4d97a7c..bd7f1530 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; @@ -53,7 +54,7 @@ namespace slskd.Validation protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value is not null && !string.IsNullOrEmpty(value.ToString())) { var file = Path.GetFullPath(value?.ToString()); @@ -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/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index b55fc865..09d9eda2 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -42,6 +42,7 @@ namespace slskd.Core.API using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using Serilog; + using slskd.Authentication; /// <summary> /// Application. @@ -57,17 +58,20 @@ namespace slskd.Core.API IHostApplicationLifetime lifetime, IApplication application, IOptionsMonitor<Options> optionsMonitor, + OptionsAtStartup optionsAtStartup, IStateMonitor<State> applicationStateMonitor) { Lifetime = lifetime; Application = application; OptionsMonitor = optionsMonitor; + OptionsAtStartup = optionsAtStartup; ApplicationStateMonitor = applicationStateMonitor; } private IApplication Application { get; } private IStateMonitor<State> ApplicationStateMonitor { get; } private IOptionsMonitor<Options> OptionsMonitor { get; } + private OptionsAtStartup OptionsAtStartup { get; } private IHostApplicationLifetime Lifetime { get; } private ILogger Log { get; } = Serilog.Log.ForContext<ApplicationController>(); @@ -90,7 +94,7 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public IActionResult Shutdown() { - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Lifetime.StopApplication(); Task.Run(async () => @@ -110,7 +114,7 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public IActionResult Restart() { - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); Lifetime.StopApplication(); @@ -133,11 +137,16 @@ namespace slskd.Core.API /// </summary> /// <returns></returns> [HttpGet("version/latest")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.Any)] public async Task<IActionResult> CheckVersion([FromQuery] bool forceCheck = false) { if (forceCheck) { + if (!User.IsInRole(nameof(Role.ReadWrite)) && !User.IsInRole(nameof(Role.Administrator))) + { + return Forbid(); + } + await Application.CheckVersionAsync(); } @@ -148,8 +157,9 @@ namespace slskd.Core.API /// Forces garbage collection. /// </summary> /// <returns></returns> + [ApiExplorerSettings(IgnoreApi = true)] [HttpPost("gc")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult CollectGarbage() { Application.CollectGarbage(); @@ -157,18 +167,9 @@ namespace slskd.Core.API return Ok(); } - [HttpGet("dump")] - [Authorize(Policy = AuthPolicy.Any)] - public async Task<IActionResult> DumpMemory() - { - using var dumper = new Dumper(); - var file = await dumper.DumpAsync(); - - return PhysicalFile(file, "application/octet-stream", "slskd.dmp"); - } - + [ApiExplorerSettings(IgnoreApi = true)] [HttpPost("loopback")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] public IActionResult Loopback([FromBody] object body) { Log.Information("Loopback POST: {Body}", body); diff --git a/src/slskd/Core/API/Controllers/DebugController.cs b/src/slskd/Core/API/Controllers/DebugController.cs new file mode 100644 index 00000000..7f4dcafc --- /dev/null +++ b/src/slskd/Core/API/Controllers/DebugController.cs @@ -0,0 +1,74 @@ +// <copyright file="DebugController.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Core.API +{ + using Asp.Versioning; + using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Mvc; + using Soulseek; + + /// <summary> + /// Debug. + /// </summary> + [ApiExplorerSettings(IgnoreApi = true)] + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + [Produces("application/json")] + [Consumes("application/json")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public class DebugController : ControllerBase + { + public DebugController(ISoulseekClient soulseekClient) + { + Client = soulseekClient; + } + + private ISoulseekClient Client { get; } + + [HttpGet("transfers")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + [ProducesResponseType(typeof(Transfer), 200)] + public IActionResult Transfers() + { + return Ok(new + { + Soulseek = new + { + Client.Uploads, + Client.Downloads, + }, + }); + } + } +} diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..c11d8ff3 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,16 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Linq; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// <summary> /// Logs. @@ -44,17 +51,101 @@ namespace slskd.Core.API [ApiController] [Produces("application/json")] [Consumes("application/json")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public class LogsController : ControllerBase { + public LogsController(FileService fileService) + { + Files = fileService; + } + + private FileService Files { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<LogsController>(); + /// <summary> /// Gets the last few application logs. /// </summary> /// <returns></returns> - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + /// <summary> + /// Lists the log files currently on disk. + /// </summary> + /// <returns></returns> + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public async Task<IActionResult> List() + { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, + RecurseSubdirectories = false, + }); + + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); + } + + /// <summary> + /// Retrieves the requested log file from disk as plain text. + /// </summary> + /// <param name="filename">The name of the log file.</param> + /// <returns></returns> + [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] + public IActionResult Get([FromRoute] string filename) + { + if (string.IsNullOrWhiteSpace(filename)) + { + return BadRequest("Filename is required"); + } + + if (filename.ContainsAny('/', '\\')) + { + return BadRequest("Filename must not contain a path"); + } + + var sanitizedFilename = FileSafety.GetFileNameSafely(filename, sanitize: true); + + if (!sanitizedFilename.Equals(filename, StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Input filename {Filename} sanitized to {Sanitized}", filename, sanitizedFilename); + return BadRequest("Filename contains one or more invalid characters"); + } + + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); + } + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + return File(stream, "text/plain; charset=utf-8", enableRangeProcessing: true); + } + catch (NotFoundException) + { + return NotFound(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to retrieve log file {Filename}: {Message}", filename, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); + } + } } } diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs index 2d314b5f..e8769ca9 100644 --- a/src/slskd/Core/API/Controllers/OptionsController.cs +++ b/src/slskd/Core/API/Controllers/OptionsController.cs @@ -127,7 +127,7 @@ namespace slskd.Core.API /// <returns></returns> [HttpGet] [Route("startup")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] [ProducesResponseType(typeof(Options), 200)] public IActionResult Startup() { @@ -221,7 +221,7 @@ namespace slskd.Core.API } [HttpPost] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] [Route("yaml/validate")] public IActionResult ValidateYamlFile([FromBody] string yaml) { diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index dd9c37d2..41c1f1b1 100644 --- a/src/slskd/Core/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -73,7 +73,7 @@ namespace slskd.Core.API /// <returns></returns> [HttpPut] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(StatusCodes.Status205ResetContent)] [ProducesResponseType(403)] @@ -109,7 +109,7 @@ namespace slskd.Core.API /// <returns></returns> [HttpDelete] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(403)] public IActionResult Disconnect([FromBody] string message) diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index b26dfe6e..1115f46c 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -34,8 +34,11 @@ using Microsoft.Extensions.Options; namespace slskd.Core.API { + using System.Security.Cryptography; + using System.Text; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Authentication; @@ -115,13 +118,15 @@ namespace slskd.Core.API { if (OptionsAtStartup.Headless) { - Log.Warning("Login from {User} rejected; web UI is DISABLED when running in headless mode", login.Username); + // if running headless, reject all login attempts and provide no feedback about inputs; there is nothing + // a caller can do to change the outcome, so a 400 is misleading + Log.Warning("Login from {User} rejected; web UI is DISABLED when running in headless mode", login?.Username ?? "<unspecified>"); return Forbid(); } if (login == default) { - return BadRequest(); + return BadRequest("No credentials provided"); } if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password)) @@ -129,8 +134,24 @@ namespace slskd.Core.API return BadRequest("Username and/or Password missing or invalid"); } + Options.WebOptions.WebAuthenticationOptions options = OptionsSnapshot.Value.Web.Authentication; + + if (string.IsNullOrEmpty(options.Username) || string.IsNullOrEmpty(options.Password)) + { + // validation within the Options class should prevent this, but confirm in case of regression + Log.Error("Authentication is misconfigured; when enabled, username and password must be at least one character. Login is disabled."); + return StatusCode(StatusCodes.Status500InternalServerError, "Login disabled, check application logs for details"); + } + + // compare in constant time to avoid timing attacks + static bool ParanoidEquals(string left, string right) + => CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(left), Encoding.UTF8.GetBytes(right)); + // only admin login for now - if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) + var usernameMatches = ParanoidEquals(options.Username, login.Username); + var passwordMatches = ParanoidEquals(options.Password, login.Password); + + if (usernameMatches & passwordMatches) { return Ok(new TokenResponse(Security.GenerateJwt(login.Username, Role.Administrator))); } diff --git a/src/slskd/Core/API/Hubs/LogsHub.cs b/src/slskd/Core/API/Hubs/LogsHub.cs index bec12d6a..0697f5ef 100644 --- a/src/slskd/Core/API/Hubs/LogsHub.cs +++ b/src/slskd/Core/API/Hubs/LogsHub.cs @@ -62,7 +62,7 @@ namespace slskd.Core.API /// <summary> /// The logs SignalR hub. /// </summary> - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public class LogsHub : Hub { public override async Task OnConnectedAsync() diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs index 517b5e4b..6f25b93c 100644 --- a/src/slskd/Core/Blacklist.cs +++ b/src/slskd/Core/Blacklist.cs @@ -39,6 +39,7 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Net; +using System.Net.Sockets; using System.Threading.Tasks; using NetTools; using Serilog; @@ -315,6 +316,18 @@ public class Blacklist /// <returns>A value indicating whether the specified IP is contained within the blacklist.</returns> public virtual bool Contains(IPAddress ip) { + // looks like '::ffff:1.2.3.4'; convert it back to IPv4 so the lookup below works + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + // only IPv4 ranges are supported + if (ip.AddressFamily != AddressFamily.InterNetwork) + { + return false; + } + // grab the first octet int first = ip.GetAddressBytes()[0]; diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index d53d7c8c..332077a9 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -133,7 +133,7 @@ public class Migrator */ Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsToApply.Count()); - var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); + var migrationId = DateTime.UtcNow.ToString("MMddyy_HHmmss"); Log.Warning("--> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <--", migrationId); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index dce97f4e..e8af8c0b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1453,16 +1453,17 @@ namespace slskd [EnvironmentVariable("LOKI")] [Description("optional; url to a Grafana Loki instance to which to log")] [RequiresRestart] + [Secret] public string Loki { get; init; } = null; /// <summary> /// Gets a value indicating whether to write logs to disk. /// </summary> - [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 NoDisk { get; init; } = false; /// <summary> /// Gets a value indicating whether to suppress colorization of console logs. @@ -1500,8 +1501,8 @@ namespace slskd /// <summary> /// Gets the time to retain logs, in days. /// </summary> - [Range(1, maximum: int.MaxValue)] - public int Logs { get; init; } = 180; + [Range(2, maximum: int.MaxValue)] + public int Logs { get; init; } = 14; /// <summary> /// Transfer retention options. @@ -1815,6 +1816,16 @@ namespace slskd public ProxyOptions Proxy { get; init; } = new ProxyOptions(); /// <summary> + /// Gets the MTU to use for the server connection, or null to use the OS default. + /// </summary> + [Argument(default, "slsk-server-mtu")] + [EnvironmentVariable("SLSK_SERVER_MTU")] + [Description("MTU to use for the server connection")] + [Range(576, 65535)] + [RequiresReconnect] + public int? Mtu { get; init; } = null; + + /// <summary> /// Connection buffer options. /// </summary> public class BufferOptions @@ -2182,9 +2193,12 @@ namespace slskd { var role = tuple.Split('=').LastOrDefault(); - if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _)) + var roleResult = new EnumAttribute(typeof(Role), ignoreCase: true) + .GetValidationResult(role, new ValidationContext(this) { MemberName = nameof(ApiKey), DisplayName = "API key role" }); + + if (roleResult != ValidationResult.Success) { - results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}")); + results.Add(new ValidationResult(roleResult.ErrorMessage)); } } else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) @@ -2239,7 +2253,7 @@ namespace slskd [Argument(default, "jwt-ttl")] [EnvironmentVariable("JWT_TTL")] [Description("TTL for JWTs")] - [Range(3600, int.MaxValue)] + [Range(3600000, int.MaxValue)] [RequiresRestart] public int Ttl { get; init; } = 604800000; } @@ -2622,6 +2636,7 @@ namespace slskd /// Gets the fully qualified URL for the webhook. /// </summary> [NotNullOrWhiteSpace] + [Secret] public string Url { get; init; } /// <summary> @@ -2658,6 +2673,7 @@ namespace slskd /// <summary> /// Gets the header's value. /// </summary> + [Secret] public string Value { get; init; } } @@ -2698,6 +2714,7 @@ namespace slskd /// <summary> /// Gets the shell command to run. /// </summary> + [Secret] public string Command { get; init; } /// <summary> @@ -2711,6 +2728,7 @@ namespace slskd /// <remarks> /// Mutually exclusive with <see cref="Arglist"/>. /// </remarks> + [Secret] public string Args { get; init; } /// <summary> diff --git a/src/slskd/Core/Security/DataProtectionKeyRepository.cs b/src/slskd/Core/Security/DataProtectionKeyRepository.cs new file mode 100644 index 00000000..4d962190 --- /dev/null +++ b/src/slskd/Core/Security/DataProtectionKeyRepository.cs @@ -0,0 +1,63 @@ +// <copyright file="DataProtectionKeyRepository.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd +{ + using System.Collections.Generic; + using System.Xml.Linq; + using Microsoft.AspNetCore.DataProtection.Repositories; + + /// <summary> + /// An <see cref="IXmlRepository"/> that keeps data protection keys in memory, so that they are never written to disk. + /// </summary> + public class DataProtectionKeyRepository : IXmlRepository + { + private List<XElement> Elements { get; } = new(); + private object SyncRoot { get; } = new(); + + public IReadOnlyCollection<XElement> GetAllElements() + { + lock (SyncRoot) + { + return Elements.ConvertAll(element => new XElement(element)); + } + } + + public void StoreElement(XElement element, string friendlyName) + { + lock (SyncRoot) + { + Elements.Add(new XElement(element)); + } + } + } +} diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 790f5806..26ed49d2 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -40,6 +40,8 @@ using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net; using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; using Microsoft.IdentityModel.Tokens; using NetTools; using Serilog; @@ -121,11 +123,12 @@ public class SecurityService keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey)); } - var record = keys.FirstOrDefault(k => k.Value.Key == key); + var keyBytes = Encoding.UTF8.GetBytes(key ?? string.Empty); + var record = keys.FirstOrDefault(k => k.Value.Key is not null && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(k.Value.Key), keyBytes)); if (record.Key == null) { - throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); + throw new NotFoundException("Unknown API key"); } // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4 diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index e031498c..2f3f3573 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -123,7 +123,7 @@ public class EventsController : ControllerBase /// <response code="500">An unexpected error is encountered.</response> /// <response code="201">The request completed successfully.</response> [HttpPost("{type}", Name = nameof(RaiseEvent))] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(401)] [ProducesResponseType(403)] @@ -131,7 +131,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(Event), 201)] public IActionResult RaiseEvent([FromRoute] string type, [FromBody] string disambiguator) { - if (!Enum.TryParse<EventType>(type, ignoreCase: true, out var eventType)) + if (!Enum.TryParse<EventType>(type, ignoreCase: true, out var eventType) || !Enum.IsDefined(eventType)) { var names = Enum.GetNames(typeof(EventType)) .Where(n => n != EventType.Any.ToString() && n != EventType.None.ToString()); @@ -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/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 8a96d83f..8954c1ac 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -34,9 +34,9 @@ using Microsoft.Extensions.Options; namespace slskd.Files.API { + using System; using System.ComponentModel.DataAnnotations; using System.IO; - using System.Security; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -95,7 +95,7 @@ namespace slskd.Files.API [ProducesResponseType(401)] [ProducesResponseType(403)] [ProducesResponseType(404)] - public Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) + public Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute, UrlEncoded] string base64SubdirectoryName, [FromQuery] bool recursive = false) => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName, recursive); /// <summary> @@ -108,9 +108,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("downloads/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + public Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute, UrlEncoded] string base64SubdirectoryName) => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName); /// <summary> @@ -123,9 +123,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("downloads/files/{base64FileName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteDownloadFileAsync([FromRoute] string base64FileName) + public Task<IActionResult> DeleteDownloadFileAsync([FromRoute, UrlEncoded] string base64FileName) => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64FileName); /// <summary> @@ -154,7 +154,7 @@ namespace slskd.Files.API [HttpGet("incomplete/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + public Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, UrlEncoded, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName, recursive); /// <summary> @@ -167,9 +167,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("incomplete/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + public Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute, UrlEncoded] string base64SubdirectoryName) => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName); /// <summary> @@ -182,9 +182,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("incomplete/files/{base64FileName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteIncompleteFileAsync([FromRoute] string base64FileName) + public Task<IActionResult> DeleteIncompleteFileAsync([FromRoute, UrlEncoded] string base64FileName) => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64FileName); private async Task<IActionResult> ListDirectoryAsync(string rootDirectory, string base64SubdirectoryName = null, bool recursive = false) @@ -192,7 +192,13 @@ namespace slskd.Files.API var requestedDir = (base64SubdirectoryName ?? string.Empty) .FromBase64() .Replace('\\', Path.DirectorySeparatorChar) - .Replace('/', Path.DirectorySeparatorChar); + .Replace('/', Path.DirectorySeparatorChar) + .TrimStart(Path.DirectorySeparatorChar); + + if (!FileSafety.IsPathRelative(requestedDir)) + { + return BadRequest("Path must be relative"); + } requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); @@ -200,7 +206,7 @@ namespace slskd.Files.API try { - var response = await Files.ListContentsAsync( + var response = await Files.ListDirectoryContentsAsync( directory: requestedDir, enumerationOptions: new EnumerationOptions { @@ -210,11 +216,16 @@ namespace slskd.Files.API return Ok(response); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("Directory listing of '{Directory}' forbidden", requestedDir); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Debug("Directory '{Directory}' not found", requestedDir); @@ -235,6 +246,11 @@ namespace slskd.Files.API .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar); + if (!FileSafety.IsPathRelative(requestedDir)) + { + return BadRequest("Path must be relative"); + } + requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); Log.Information("Deleting directory '{Directory}'", requestedDir); @@ -247,11 +263,16 @@ namespace slskd.Files.API success => NoContent(), failure => throw failure); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("Directory deletion of '{Directory}' forbidden", requestedDir); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Information("Directory '{Directory}' not found", requestedDir); @@ -272,6 +293,11 @@ namespace slskd.Files.API .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar); + if (!FileSafety.IsPathRelative(requestedFilename)) + { + return BadRequest("Path must be relative"); + } + requestedFilename = Path.GetFullPath(Path.Combine(rootDirectory, requestedFilename)); Log.Information("Deleting file '{File}'", requestedFilename); @@ -284,11 +310,16 @@ namespace slskd.Files.API success => NoContent(), failure => throw failure); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("File deletion of '{File}' forbidden", requestedFilename); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Information("File '{File}' not found", requestedFilename); diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..7cce5198 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,50 +59,29 @@ namespace slskd.Files private IEnumerable<string> AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - }; + OptionsMonitor.CurrentValue.Directories.Downloads, + OptionsMonitor.CurrentValue.Directories.Incomplete, + Program.LogDirectory, + }.Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => Path.GetFullPath(x)); private ILogger Log { get; } = Serilog.Log.ForContext<FileService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } /// <summary> - /// Resolves an instance of <see cref="FileInfo"/> for the specified <paramref name="filename"/>, following + /// Resolves an instance of <see cref="FileInfo"/> for the specified <paramref name="info"/>, following /// any symlinks that may be present to their final target. A non-null return value is guaranteed. /// </summary> - /// <param name="filename">The fully qualified filename for which to resolve the FileInfo instance.</param> + /// <param name="info">The FileInfo instance for which to follow symlinks.</param> /// <returns>The resolved FileInfo instance.</returns> - /// <exception cref="ArgumentException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified FileInfo is null.</exception> /// <exception cref="UnauthorizedException">Thrown if the specified or linked file is restricted.</exception> /// <exception cref="IOException">Thrown if the specified or linked file can't be resolved for some reason.</exception> - public virtual FileInfo ResolveFileInfo(string filename) + public virtual FileInfo ResolveFileInfo(FileInfo info) { - ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); - - if (Path.GetFullPath(filename) != filename) - { - throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); - } - - if (FileSafety.ContainsTraversalSegments(filename)) - { - Log.Warning("Suspicious attempt to resolve file info for 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", nameof(filename)); - } - - FileInfo info; - - try - { - info = new FileInfo(filename); - } - catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) - { - throw new UnauthorizedException($"Access to the file '{filename}' was denied: {ex.Message}", ex); - } - catch (Exception ex) + if (info is null) { - throw new IOException($"Failed to access file '{filename}': {ex.Message}", ex); + throw new ArgumentException("The specified FileInfo is null", nameof(info)); } // if the above didn't throw we are guaranteed a valid instance of FileInfo regardless of whether @@ -124,27 +103,71 @@ 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) { - throw new UnauthorizedException($"Access to the linked file '{filename}->{info.LinkTarget}' was denied: {ex.Message}", ex); + throw new UnauthorizedException($"Access to the linked file '{info.Name}->{info.LinkTarget}' was denied: {ex.Message}", ex); } catch (Exception ex) { - Log.Error(ex, "Failed to resolve FileInfo for linked file '{File}->{Link}': {Message}", filename, info.LinkTarget, ex.Message); - throw new IOException($"Failed to resolve FileInfo for linked file '{filename}->{info.LinkTarget}': {ex.Message}", ex); + Log.Error(ex, "Failed to resolve FileInfo for linked file '{File}->{Link}': {Message}", info.Name, info.LinkTarget, ex.Message); + 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 resolved; + } + + /// <summary> + /// Resolves an instance of <see cref="FileInfo"/> for the specified <paramref name="filename"/>, following + /// any symlinks that may be present to their final target. A non-null return value is guaranteed. + /// </summary> + /// <param name="filename">The fully qualified filename for which to resolve the FileInfo instance.</param> + /// <returns>The resolved FileInfo instance.</returns> + /// <exception cref="ArgumentException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="UnauthorizedException">Thrown if the specified or linked file is restricted.</exception> + /// <exception cref="IOException">Thrown if the specified or linked file can't be resolved for some reason.</exception> + public virtual FileInfo ResolveFileInfo(string filename) + { + ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + if (Path.GetFullPath(filename) != filename) { - Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", filename, info.LinkTarget); - throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{filename}->{info.LinkTarget}'"); + throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); + } + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to resolve file info for 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", nameof(filename)); + } + + FileInfo info; + + try + { + info = new FileInfo(filename); + } + catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException) + { + throw new UnauthorizedException($"Access to the file '{filename}' was denied: {ex.Message}", ex); + } + catch (Exception ex) + { + throw new IOException($"Failed to access file '{filename}': {ex.Message}", ex); } - return info; + return ResolveFileInfo(info); } /// <summary> @@ -300,7 +323,7 @@ namespace slskd.Files /// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception> /// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception> /// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception> - public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task<FilesystemDirectory> ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -332,7 +355,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType<FileInfo>() @@ -365,6 +388,49 @@ namespace slskd.Files } /// <summary> + /// Retrieves the contents of the specified <paramref name="filename"/> as a stream. + /// </summary> + /// <param name="filename">The file for which contents are to be retrieved.</param> + /// <returns>A Stream containing the contents of the file.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception> + /// <exception cref="ArgumentException">Thrown if the specified filename contains path traversal segments.</exception> + /// <exception cref="UnauthorizedException">Thrown if the specified file is not within an allowed directory.</exception> + /// <exception cref="NotFoundException">Thrown if the specified file does not exist.</exception> + /// <exception cref="IOException">Thrown if the file can't be opened for some reason.</exception> + public virtual Stream GetFileContents(string filename) + { + ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to read a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' + if (!AllowedDirectories.Any(allowed => filename.StartsWith(allowed + Path.DirectorySeparatorChar))) + { + throw new UnauthorizedException($"Only application-controlled directories can be listed"); + } + + var info = ResolveFileInfo(filename); + + if (!info.Exists) + { + throw new NotFoundException(); + } + + try + { + return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + + /// <summary> /// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>, /// returning a <see cref="Stream"/> with which the contents of the file can be written. /// </summary> diff --git a/src/slskd/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/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 7ed0a92c..a1c6038f 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -87,7 +87,7 @@ namespace slskd.Messaging.API /// A conversation with the specified username, or a message matching the specified id could not be found. /// </response> [HttpPut("{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task<IActionResult> Acknowledge([FromRoute, UrlEncoded] string username, [FromRoute] int id) @@ -97,7 +97,7 @@ namespace slskd.Messaging.API return Forbid(); } - var message = Messages.Conversations.FindMessageAsync(username, id); + var message = await Messages.Conversations.FindMessageAsync(username, id); if (message == default) { @@ -117,7 +117,7 @@ namespace slskd.Messaging.API /// <response code="200">The request completed successfully.</response> /// <response code="404">A conversation with the specified username could not be found.</response> [HttpPut("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task<IActionResult> AcknowledgeAll([FromRoute, UrlEncoded] string username) @@ -127,7 +127,7 @@ namespace slskd.Messaging.API return Forbid(); } - var conversation = Messages.Conversations.FindAsync(username); + var conversation = await Messages.Conversations.FindAsync(username); if (conversation == default) { @@ -146,7 +146,7 @@ namespace slskd.Messaging.API /// <response code="204">The request completed successfully.</response> /// <response code="404">A conversation with the specified username could not be found.</response> [HttpDelete("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(404)] [ProducesResponseType(204)] public async Task<IActionResult> Close([FromRoute, UrlEncoded] string username) @@ -156,7 +156,7 @@ namespace slskd.Messaging.API return Forbid(); } - var conversation = Messages.Conversations.FindAsync(username, includeInactive: false); + var conversation = await Messages.Conversations.FindAsync(username, includeInactive: false); if (conversation == default) { @@ -259,7 +259,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="400">The specified message is null or empty.</response> [HttpPost("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(400)] public async Task<IActionResult> Send([FromRoute, UrlEncoded] string username, [FromBody] string message) diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 3b2fe568..57d3b742 100644 --- a/src/slskd/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -127,7 +127,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/messages")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> SendMessage([FromRoute, UrlEncoded] string roomName, [FromBody] string message) @@ -155,7 +155,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/ticker")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> SetTicker([FromRoute, UrlEncoded] string roomName, [FromBody] string message) @@ -183,7 +183,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/members")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> AddRoomMember([FromRoute, UrlEncoded] string roomName, [FromBody] string username) @@ -298,7 +298,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="304">The room has already been joined.</response> [HttpPost("joined")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Room), 201)] [ProducesResponseType(304)] public async Task<IActionResult> JoinRoom([FromBody] string roomName) @@ -339,7 +339,7 @@ namespace slskd.Messaging.API /// <response code="204">The request completed successfully.</response> /// <response code="404">The room has not been joined.</response> [HttpDelete("joined/{roomName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task<IActionResult> LeaveRoom([FromRoute, UrlEncoded] string roomName) diff --git a/src/slskd/Messaging/ConversationService.cs b/src/slskd/Messaging/ConversationService.cs index a744dcca..9873b88b 100644 --- a/src/slskd/Messaging/ConversationService.cs +++ b/src/slskd/Messaging/ConversationService.cs @@ -398,20 +398,23 @@ namespace slskd.Messaging private void ActivateConversation(string username) { - using var context = ContextFactory.CreateDbContext(); + try + { + using var context = ContextFactory.CreateDbContext(); - var conversation = context.Conversations.FirstOrDefault(c => c.Username == username); + context.Database.ExecuteSql($@" + INSERT INTO Conversations (Username, IsActive) + VALUES ({username}, 1) + ON CONFLICT(Username) DO UPDATE SET IsActive = excluded.IsActive; + "); - if (conversation != default) - { - conversation.IsActive = true; + Log.Debug("Successfully activated Conversation for {Username}", username); } - else + catch (Exception ex) { - context.Conversations.Add(new Conversation { Username = username, IsActive = true }); + Log.Warning(ex, "Failed to activate Conversation for {Username}: {Message}", username, ex.Message); + throw; } - - context.SaveChanges(); } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index df20270d..8677c7ff 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -52,11 +52,12 @@ namespace slskd using Asp.Versioning.ApiExplorer; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.DataProtection; + using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; + using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -278,6 +279,7 @@ namespace slskd private static Mutex Mutex { get; set; } private static IDisposable DotNetRuntimeStats { get; set; } private static VolatileOverlayConfigurationSource<OptionsOverlay> VolatileOverlayConfigurationSource { get; set; } = new VolatileOverlayConfigurationSource<OptionsOverlay>(); + private static List<SqliteConnection> VolatileDatabaseKeepaliveConnections { get; } = []; [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -382,7 +384,11 @@ namespace slskd // only one long-running instance. try { - Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out bool created); + Mutex = new Mutex( + initiallyOwned: true, + name: Compute.Sha256Hash(AppName), + options: new NamedWaitHandleOptions { CurrentUserOnly = false, CurrentSessionOnly = true }, + out bool created); if (!created) { @@ -450,7 +456,17 @@ namespace slskd if (OptionsAtStartup.Debug) { - Log.Information($"Configuration:\n{Configuration.GetDebugView()}"); + // redact values for any key matching the name of a property marked [Secret]. keys from YAML may be + // snake or kebab case, so normalize before comparing. this over-redacts, which is fine here + var secretNames = typeof(Options).Assembly.GetTypes() + .Where(t => t == typeof(Options) || (t.FullName?.StartsWith($"{typeof(Options).FullName}+") ?? false)) + .SelectMany(t => t.GetProperties()) + .Where(p => p.GetCustomAttributes(typeof(SecretAttribute), inherit: false).Length > 0) + .Select(p => p.Name.ToLowerInvariant()) + .ToHashSet(); + + Log.Information($"Configuration:\n{Configuration.GetDebugView(context => + secretNames.Contains(context.Key.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant()) ? "*****" : context.Value)}"); } if (!OptionsAtStartup.TryValidate(out var result)) @@ -461,7 +477,7 @@ namespace slskd } catch (Exception ex) { - Log.Information($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); + Log.Information($"Invalid configuration: {(OptionsAtStartup.Debug ? ex : ex.Message)}"); return; } @@ -512,7 +528,7 @@ namespace slskd Log.Information("Storing application data in {DataDirectory}", DataDirectory); - if (OptionsAtStartup.Logger.Disk) + if (!OptionsAtStartup.Logger.NoDisk) { Log.Information("Saving application logs to {LogDirectory}", LogDirectory); } @@ -521,7 +537,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 @@ -733,7 +749,7 @@ namespace slskd var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing var connStr = OptionsAtStartup.Flags.Volatile - ? $"Data Source=file:{database}?mode=memory;Pooling={pooling};" + ? $"Data Source=file:{database}?mode=memory&cache=shared;Pooling={pooling};" : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Pooling={pooling}"; return new KeyValuePair<Database, ConnectionString>(database, connStr); @@ -857,8 +873,15 @@ namespace slskd services.ConfigureTelemetry(); - services.AddDataProtection() - .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); + /* + by default, adding authentication of any kind adds data protection, and the default configuration for + data protection drops .DataProtection-Keys on the filesystem. we're not using data protection, but this + can't be suppressed. + + instead, we must fake the key manager into using a dummy repository to stop it from using the filesystem + */ + services.AddDataProtection(); + services.Configure<KeyManagementOptions>(options => options.XmlRepository = new DataProtectionKeyRepository()); var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); @@ -930,7 +953,7 @@ namespace slskd try { // check to see if the provided value is a valid API key - var service = services.BuildServiceProvider().GetRequiredService<SecurityService>(); + var service = context.HttpContext.RequestServices.GetRequiredService<SecurityService>(); var (name, role) = service.AuthenticateWithApiKey(token, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress); // the API key is valid. create a new, short lived jwt for the key name and role @@ -1045,7 +1068,7 @@ namespace slskd }, License = new OpenApiLicense { - Name = "AGPL-3.0 license", + Name = "AGPL-3.0-only", Url = new Uri("https://github.com/slskd/slskd/blob/master/LICENSE"), }, }); @@ -1089,12 +1112,17 @@ namespace slskd var urlBase = OptionsAtStartup.Web.UrlBase; urlBase = urlBase.StartsWith("/") ? urlBase : "/" + urlBase; - // use urlBase. this effectively just removes urlBase from the path. - // inject urlBase into any html files we serve, and rewrite links to ./static or /static to - // prepend the url base. + // use urlBase. this effectively just removes urlBase from the path before sending it to the next middleware app.UsePathBase(urlBase); + + // rewrite relative html links to ./static or ./favicon.ico to absolute links that include urlBase + // this is necessary because SPA routers (like React Router) mess with the browser's current address app.UseHTMLRewrite("((\\.)?\\/static)", $"{(urlBase == "/" ? string.Empty : urlBase)}/static"); + app.UseHTMLRewrite("((\\.)?\\/favicon\\.ico)", $"{(urlBase == "/" ? string.Empty : urlBase)}/favicon.ico"); + + // inject urlBase and port into any html files we serve as a window-scoped javascript variable app.UseHTMLInjection($"<script>window.urlBase=\"{urlBase}\";window.port={OptionsAtStartup.Web.Port}</script>", excludedRoutes: new[] { "/api", "/swagger" }); + Log.Information("Using base url {UrlBase}", urlBase); // serve static content from the configured path @@ -1174,12 +1202,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; @@ -1264,10 +1294,10 @@ namespace slskd outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") .WriteTo.Async(config => config.Conditional( - e => OptionsAtStartup.Logger.Disk, + e => !OptionsAtStartup.Logger.NoDisk, config => config.File( Path.Combine(LogDirectory, $"{AppName}-.log"), - outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}", + outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:yyyy-MM-ddTHH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day, retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) .WriteTo.Conditional( @@ -1295,7 +1325,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('"'), @@ -1327,11 +1357,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); } }; } @@ -1520,6 +1550,17 @@ namespace slskd } }); + // in-memory databases are destroyed when the last connection to them closes. hold one open for the + // lifetime of the application so the data (and schema) survive between operations. this must be + // opened before EnsureCreated(), otherwise the schema is created in a database that is destroyed + // as soon as EnsureCreated() closes its connection + if (OptionsAtStartup.Flags.Volatile) + { + var keepalive = new SqliteConnection(connectionString); + keepalive.Open(); + VolatileDatabaseKeepaliveConnections.Add(keepalive); + } + /* instantiate the DbContext and make sure it is created */ diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index ddb8d0b0..ba1c4982 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -322,6 +322,12 @@ namespace slskd.Relay return Unauthorized(); } + if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) + { + Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); + return Unauthorized(); + } + IEnumerable<Share> shares; IFormFile database; @@ -338,12 +344,6 @@ namespace slskd.Relay Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName); - if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) - { - Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); - return Unauthorized(); - } - Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db"); @@ -354,14 +354,16 @@ namespace slskd.Relay var sw = new Stopwatch(); sw.Start(); - using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = database.OpenReadStream(); - - await inputStream.CopyToAsync(outputStream); + // the streams must be closed (and the output flushed) before the file is handed off to be opened as a database + using (var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write)) + using (var inputStream = database.OpenReadStream()) + { + await inputStream.CopyToAsync(outputStream); + } sw.Stop(); - Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); + Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)database.Length).SizeSuffix(), sw.ElapsedMilliseconds); await Relay.HandleShareUploadAsync(agentName, id: guid, shares, temp); diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 8430164c..4e044bdb 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -85,7 +85,7 @@ namespace slskd.Relay /// <summary> /// The relay SignalR hub. /// </summary> - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public class RelayHub : Hub<IRelayHub> { /// <summary> @@ -120,6 +120,7 @@ namespace slskd.Relay { Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress()); Context.Abort(); + return; } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); @@ -222,9 +223,9 @@ namespace slskd.Relay /// Executed by the agent to notify the controller that the agent was unable to upload the file requested by a call to <see cref="IRelayHub.RequestFileUpload"/>. /// </summary> /// <param name="id">The unique identifier of the request.</param> - /// <param name="exception">The Exception that caused the failure.</param> + /// <param name="message">A message describing the failure.</param> /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> - public void NotifyFileUploadFailed(Guid id, Exception exception) + public void NotifyFileUploadFailed(Guid id, string message) { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { @@ -232,9 +233,9 @@ namespace slskd.Relay throw new UnauthorizedAccessException(); } - Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, GetRemoteIPAddress(), id, exception.Message); + Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress(), id, message); - Relay.NotifyFileStreamException(record.Agent.Name, id, exception); + Relay.NotifyFileStreamException(record.Agent.Name, id, new RelayException(message)); } /// <summary> diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index fef16573..4f1e2924 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -148,7 +148,15 @@ namespace slskd.Relay // the controller will send an authentication challenge immediately after connection // wait for the auth handler to log in before proceeding with the initial share upload - await LoggedInTaskCompletionSource.Task; + try + { + await LoggedInTaskCompletionSource.Task; + } + catch (Exception) + { + await StopAsync(cancellationToken); + throw; + } Log.Information("Uploading shares..."); @@ -271,7 +279,7 @@ namespace slskd.Relay // if the client is attempting a connection, cancel it it's going to be dropped when we create a new instance, but // we need the retry loop around connection to stop. - StartCancellationTokenSource?.Cancel(); + StartCancellationTokenSource?.Cancel(swallowObjectDisposedException: true); HubConnection = new HubConnectionBuilder() .WithUrl($"{options.Relay.Controller.Address.TrimEnd('/')}/hub/relay", builder => @@ -366,6 +374,7 @@ namespace slskd.Relay catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + LoggedInTaskCompletionSource.TrySetException(ex); } } @@ -375,6 +384,7 @@ namespace slskd.Relay { Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); + return; } Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); @@ -399,7 +409,8 @@ namespace slskd.Relay if (FileSafety.ContainsTraversalSegments(filename)) { Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); - await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token, "Requested filename contains unsafe path segments"); + return; } _ = Task.Run(async () => @@ -436,7 +447,9 @@ namespace slskd.Relay request.Content = content; Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); - var response = await CreateHttpClient().SendAsync(request); + + using var client = CreateHttpClient(); + using var response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { @@ -452,7 +465,7 @@ namespace slskd.Relay Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token, ex.Message); } }); } @@ -647,7 +660,9 @@ namespace slskd.Relay Log.Information("Beginning upload of shares ({Size})", size); Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson()); - var response = await CreateHttpClient().SendAsync(request, cancellationToken); + + using var client = CreateHttpClient(); + using var response = await client.SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) { diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 26a635a1..c6c1f5d0 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -366,8 +366,8 @@ namespace slskd.Relay { var token = Cryptography.Random.GetBytes(32).ToBase62(); - // this token is only valid for this connection id for a short time this is important to prevent replay-type attacks. - MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromSeconds(10)); + // this token is only valid for this connection id for a short time; this is important to prevent replay-type attacks. + MemoryCache.Set(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromMinutes(1)); Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); return token; } @@ -765,6 +765,9 @@ namespace slskd.Relay return false; } + // challenge tokens can be used exactly once, pass or fail + MemoryCache.Remove(GetAuthTokenCacheKey(connectionId)); + var agentOptions = OptionsMonitor.CurrentValue.Relay.Agents.Values.SingleOrDefault(a => a.InstanceName == agentName); if (agentOptions == default) @@ -777,7 +780,9 @@ namespace slskd.Relay var tokenBytes = System.Text.Encoding.UTF8.GetBytes((string)challengeToken); var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62(); - if (expectedCredential != credential) + if (!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( + left: System.Text.Encoding.UTF8.GetBytes(expectedCredential), + right: System.Text.Encoding.UTF8.GetBytes(credential ?? string.Empty))) { Log.Debug("Validation failed: Supplied credential {Credential} does not match expected credential {Expected}", credential, expectedCredential); return false; @@ -853,6 +858,8 @@ namespace slskd.Relay else { // the controller changed. disconnect and throw away the client and create a new one + var oldClient = Client; + Client = new RelayClient( shareService: Shares, fileService: Files, @@ -862,6 +869,8 @@ namespace slskd.Relay Client.StateMonitor.OnChange(clientState => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); + oldClient.TryDispose(); + State.SetValue(state => state with { Mode = mode, @@ -925,7 +934,9 @@ namespace slskd.Relay var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62(); - if (expectedCredential != credential) + if (!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( + left: System.Text.Encoding.UTF8.GetBytes(expectedCredential), + right: System.Text.Encoding.UTF8.GetBytes(credential ?? string.Empty))) { Log.Debug("Validation failed: Supplied credential {Credential} does not match expected credential {Expected}", credential, expectedCredential); return false; diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 99214410..a573c1e0 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -78,7 +78,7 @@ namespace slskd.Search.API /// <response code="400">The specified <paramref name="request"/> was malformed.</response> /// <response code="500">The search terminated abnormally.</response> [HttpPost("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] public async Task<IActionResult> Post([FromBody] SearchRequest request) { if (Program.IsRelayAgent) @@ -207,7 +207,7 @@ namespace slskd.Search.API /// <response code="304">The search was not in progress.</response> /// <returns></returns> [HttpPut("{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(304)] public async Task<IActionResult> Cancel([FromRoute] Guid id) @@ -236,7 +236,7 @@ namespace slskd.Search.API /// <response code="404">A search with the specified id could not be found.</response> /// <returns></returns> [HttpDelete("{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task<IActionResult> Delete([FromRoute] Guid id) diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 208e8f9d..ec45bb5c 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); @@ -415,7 +416,7 @@ namespace slskd.Search { if (CancellationTokens.TryGetValue(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 76ec4643..4e328717 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -148,20 +148,18 @@ namespace slskd.Shares.API /// <response code="409">A share scan is already in progress.</response> [HttpPut] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(409)] public IActionResult RescanSharesAsync() { - try - { - _ = Shares.ScanAsync(); - } - catch (ShareScanInProgressException) + if (Shares.StateMonitor.CurrentValue.Scanning) { - return Conflict("A share scan is already in progress."); + return Conflict("A share scan is already in progress"); } + _ = Shares.ScanAsync(); + return Ok(); } @@ -173,7 +171,7 @@ namespace slskd.Shares.API /// <response code="409">A share scan was not in progress.</response> [HttpDelete] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelShareScan() diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 3b57c16f..e9799663 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -53,6 +53,11 @@ namespace slskd.Shares void BackupTo(IShareRepository repository); /// <summary> + /// Checkpoints the current database, flushing the contents of the WAL (write ahead log) into the table(s). + /// </summary> + void Checkpoint(); + + /// <summary> /// Counts the number of directories in the database. /// </summary> /// <param name="parentDirectory">The optional directory prefix used for counting subdirectories.</param> diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 7c93d437..7ae1aa4e 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -199,46 +199,91 @@ namespace slskd.Shares Log.Information("Enumerating shared directories"); swSnapshot = sw.ElapsedMilliseconds; - // derive a list of all directories from all shares. skip hidden and system directories, as well as anything that - // can't be accessed due to security restrictions. it's necessary to enumerate these directories up front so we - // can deduplicate directories and apply exclusions - var unmaskedDirectories = Shares - .SelectMany(share => + // note: there's a safer version of this in the FileSafety class that checks for traversal and navigates + // case sensitivity for different operating systems. this version is stripped down for speed, and because + // we're not dealing with untrusted data + static bool IsSubDirectoryOf(string subDirectory, string root, StringComparison stringComparison = StringComparison.OrdinalIgnoreCase) + { + return subDirectory.TrimEnd('/', '\\').Equals(root.TrimEnd('/', '\\'), stringComparison) || // subdirectory literally is the root + subDirectory.StartsWith(root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar, stringComparison); + } + + /* + derive a list of all subdirectories to scan by enumerating the subdirectories within each configured + share recursively, omitting any directory that matches a filter or that exists within an excluded share + + we don't enumerate excluded shares because 1) the exclusion is a subdirectory of another share and it + will be enumerated once already or 2) the exclusion is not a subdirectory of another share and we don't + want to enumerate its directories just to remove them all. this is probably obvious and kind of a worthless comment + */ + var unmaskedDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + var excludedDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + + var excludedPaths = Shares.Where(s => s.IsExcluded).Select(s => s.LocalPath).ToHashSet(); + + foreach (var share in Shares) + { + if (share.IsExcluded) { - try + continue; + } + + try + { + var directories = Directory.EnumerateDirectories(share.LocalPath, "*", new EnumerationOptions() { - var directories = System.IO.Directory.GetDirectories(share.LocalPath, "*", new EnumerationOptions() - { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, - IgnoreInaccessible = true, - RecurseSubdirectories = true, - }); + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, + IgnoreInaccessible = true, + RecurseSubdirectories = true, + }); - return directories.Where(directory => !filters.Any(filter => filter.IsMatch(directory))); - } - catch (Exception ex) + unmaskedDirectories.Add(share.LocalPath); + + foreach (var directory in directories) { - Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); - return Array.Empty<string>(); - } - }) - .Concat(Shares.Select(share => share.LocalPath)) // include the shares themselves (GetDirectories returns only subdirectories) - .Where(share => System.IO.Directory.Exists(share)) // discard any directories that don't exist. we already warned about them. - .ToHashSet(); // remove duplicates (in case shares overlap) + if (excludedPaths.Any(excludedPath => IsSubDirectoryOf(subDirectory: directory, root: excludedPath))) + { + excludedDirectories.Add(directory); + Log.Debug("Excluding directory {Directory} because it is a subdirectory of an excluded share", directory); + continue; + } - var excludedDirectories = unmaskedDirectories - .Where(share => Shares.Where(share => share.IsExcluded).Any(exclusion => share.StartsWith(exclusion.LocalPath))); + if (filters.Any(f => f.IsMatch(directory))) + { + excludedDirectories.Add(directory); + Log.Debug("Excluding directory {Directory} because it matches one or more share filters", directory); + continue; + } - unmaskedDirectories = unmaskedDirectories.Except(excludedDirectories).ToHashSet(); + unmaskedDirectories.Add(directory); + } + } + catch (Exception ex) + { + Log.Warning("Failed to scan share {Directory}: {Message}", share.LocalPath, ex.Message); + } + } - State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count() }); - Log.Information("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count(), sw.ElapsedMilliseconds - swSnapshot); + State.SetValue(state => state with { Directories = unmaskedDirectories.Count, ExcludedDirectories = excludedDirectories.Count }); + Log.Information("Found {Directories} shared directories (and {Excluded} were excluded) in {Elapsed}ms. Starting file scan.", unmaskedDirectories.Count, excludedDirectories.Count, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; var current = 0; var cached = 0; var filtered = 0; + // set up a function to reliably resolve the Share given a directory; users can define nested shares, + // so we need to sort to ensure the deepest-nested share is selected first + var sortedShares = Shares + .Where(s => !s.IsExcluded) + .OrderByDescending(s => s.LocalPath.Length) + .ToList(); + + Share ResolveShareFromDirectory(string directory) + { + return sortedShares.First(share => IsSubDirectoryOf(subDirectory: directory, root: share.LocalPath)); + } + // set up a channel to fan out for directory scanning var channel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000) { @@ -263,7 +308,7 @@ namespace slskd.Shares var addedFiles = 0; var filteredFiles = 0; - var share = Shares.First(share => directory.StartsWith(share.LocalPath)); + var share = ResolveShareFromDirectory(directory); repository.InsertDirectory(directory.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek(), timestamp); @@ -273,29 +318,29 @@ namespace slskd.Shares { // enumerate files in this directory only (no subdirectories) exclude hidden and system files and anything // that can't be accessed due to security restrictions - var newFiles = System.IO.Directory.GetFiles(directory, "*", new EnumerationOptions() + var newFileInfos = new DirectoryInfo(directory).EnumerateFiles("*", new EnumerationOptions() { - AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint, IgnoreInaccessible = true, RecurseSubdirectories = false, }); - addedFiles = newFiles.Length; - // merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully // qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another. - foreach (var originalFilename in newFiles) + foreach (var info in newFileInfos) { - var info = Files.ResolveFileInfo(originalFilename); - var file = SoulseekFileFactory.Create(originalFilename, maskedFilename: originalFilename.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek()); - - if (filters.Any(filter => filter.IsMatch(originalFilename))) + if (filters.Any(filter => filter.IsMatch(info.FullName))) { filteredFiles++; continue; } - repository.InsertFile(maskedFilename: file.Filename, originalFilename, touchedAt: info.LastWriteTimeUtc, file, timestamp); + var file = SoulseekFileFactory.Create( + filename: info.FullName, + maskedFilename: info.FullName.ReplaceFirst(share.LocalPath, share.RemotePath).NormalizePathForSoulseek()); + + repository.InsertFile(maskedFilename: file.Filename, originalFilename: info.FullName, touchedAt: info.LastWriteTimeUtc, file, timestamp); + addedFiles++; } } catch (Exception ex) @@ -343,7 +388,7 @@ namespace slskd.Shares await Task.WhenAll(workers.Select(w => w.Completed)); Log.Debug("All workers finished"); - Log.Information("Scan found {Files} files (and {Filtered} were filtered) in {Elapsed}ms", cached, filtered, sw.ElapsedMilliseconds - swSnapshot); + Log.Information("Scan found {Files} files, cached {Cached}, and filtered {Filtered} in {Elapsed}ms", cached + filtered, cached, filtered, sw.ElapsedMilliseconds - swSnapshot); swSnapshot = sw.ElapsedMilliseconds; var deletedFiles = repository.PruneFiles(olderThanTimestamp: timestamp); @@ -358,6 +403,10 @@ namespace slskd.Shares Log.Debug("Vacuuming..."); repository.Vacuum(); Log.Debug("Vacuumed successfully"); + + Log.Debug("Checkpointing..."); + repository.Checkpoint(); + Log.Debug("Checkpointed successfully"); } catch (OperationCanceledException) { @@ -408,7 +457,7 @@ namespace slskd.Shares { if (CancellationTokenSource != null) { - CancellationTokenSource.Cancel(); + CancellationTokenSource.Cancel(swallowObjectDisposedException: true); return true; } 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/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index ed594209..75d3064e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -84,14 +84,58 @@ namespace slskd.Shares /// <param name="repository">The destination repository.</param> public void BackupTo(IShareRepository repository) { - using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(repository.ConnectionString); - sourceConn.BackupDatabase(backupConn); + using (var sourceConn = GetConnection(ConnectionString)) + using (var backupConn = GetConnection(repository.ConnectionString)) + { + sourceConn.BackupDatabase(backupConn); + } + + using var backupRepository = new SqliteShareRepository(repository.ConnectionString); Log.Debug("Vacuuming backup"); - using var cmd = new SqliteCommand("VACUUM", backupConn); - cmd.ExecuteNonQuery(); + backupRepository.Vacuum(); Log.Debug("Backup vacuumed successfully"); + + Log.Debug("Checkpointing backup"); + backupRepository.Checkpoint(); + Log.Debug("Backup checkpointed successfully"); + } + + /// <summary> + /// Checkpoints the current database, flushing the contents of the WAL (write ahead log) into the table(s). + /// </summary> + public void Checkpoint() + { + const int maxAttempts = 3; + + using var conn = GetConnection(); + + for (var attempt = 1; attempt <= maxAttempts; attempt++) + { + using var cmd = new SqliteCommand("PRAGMA wal_checkpoint(TRUNCATE);", conn); + using var reader = cmd.ExecuteReader(); + + reader.Read(); + + var busy = reader.GetInt32(0); // another operation prevented the checkpoint (true/false) + var log = reader.GetInt32(1); // number of frames in the WAL at the start + var checkpointed = reader.GetInt32(2); // number of frames moved from the WAL to the db + + if (busy == 0 && checkpointed == log) + { + Log.Debug("WAL checkpoint complete; {Log} frames in log, {Checkpointed} checkpointed", log, checkpointed); + return; + } + + Log.Warning("WAL checkpoint attempt {Attempt} of {MaxAttempts} did not fully complete; {Log} frames in log, {Checkpointed} checkpointed", attempt, maxAttempts, log, checkpointed); + + if (attempt < maxAttempts) + { + System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); + } + } + + throw new TimeoutException($"Failed to fully checkpoint the shares database after {maxAttempts} attempts"); } /// <summary> @@ -113,8 +157,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%' ESCAPE '^'", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -146,8 +190,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%' ESCAPE '^'", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -370,8 +414,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ORDER BY name ASC;", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ESCAPE '^' ORDER BY name ASC;", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -410,8 +454,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); - cmd.Parameters.AddWithValue("match", parentDirectory + '%'); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ESCAPE '^' ORDER BY maskedFilename ASC;", conn); + cmd.Parameters.AddWithValue("match", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_") + '%'); } var reader = cmd.ExecuteReader(); @@ -547,7 +591,7 @@ namespace slskd.Shares var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + - $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + + "WHERE filenames MATCH @match " + $"ORDER BY filenames.maskedFilename ASC {(limit.HasValue ? $"LIMIT {limit.Value}" : string.Empty)};"; var results = new List<Soulseek.File>(); @@ -556,6 +600,7 @@ namespace slskd.Shares { using var conn = GetConnection(); using var cmd = new SqliteCommand(sql, conn); + cmd.Parameters.AddWithValue("match", $"({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}"); using var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -709,6 +754,7 @@ namespace slskd.Shares { if (disposing) { + KeepaliveTimer.Dispose(); KeepaliveConnection.Dispose(); } diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs index eef8989d..5b16ccf0 100644 --- a/src/slskd/Shares/Types/Share.cs +++ b/src/slskd/Shares/Types/Share.cs @@ -71,6 +71,7 @@ namespace slskd.Shares /// <param name="share"></param> public Share(string share) { + share = share.TrimEnd('/', '\\'); Raw = share; IsExcluded = share.StartsWith('-') || share.StartsWith('!'); 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/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 83eb04ef..b3453530 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -89,7 +89,7 @@ namespace slskd.Transfers.API /// <response code="204">The download was cancelled successfully.</response> /// <response code="404">The specified download was not found.</response> [HttpDelete("downloads/{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelDownloadAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) @@ -127,7 +127,7 @@ namespace slskd.Transfers.API /// <returns></returns> /// <response code="204">The downloads were removed successfully.</response> [HttpDelete("downloads/all/completed")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] public IActionResult ClearCompletedDownloads() { @@ -158,7 +158,7 @@ namespace slskd.Transfers.API /// <response code="204">The upload was cancelled successfully.</response> /// <response code="404">The specified upload was not found.</response> [HttpDelete("uploads/{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelUpload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) @@ -196,7 +196,7 @@ namespace slskd.Transfers.API /// <returns></returns> /// <response code="204">The uploads were removed successfully.</response> [HttpDelete("uploads/all/completed")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] public IActionResult ClearCompletedUploads() { @@ -228,7 +228,7 @@ namespace slskd.Transfers.API /// <response code="500">An unexpected error was encountered.</response> [Obsolete("Will be phased out in future versions; use batches")] [HttpPost("downloads/{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] @@ -302,7 +302,7 @@ namespace slskd.Transfers.API /// <response code="429">Request throttled.</response> /// <response code="500">An unexpected error was encountered.</response> [HttpPost("downloads/batches")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status201Created)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] @@ -582,7 +582,7 @@ namespace slskd.Transfers.API /// <response code="200">The request completed successfully.</response> /// <response code="404">The specified download was not found.</response> [HttpGet("downloads/{username}/{id}/position")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) @@ -709,7 +709,7 @@ namespace slskd.Transfers.API return BadRequest(); } - var upload = Transfers.Uploads.Find(t => t.Id == guid); + var upload = Transfers.Uploads.Find(guid); if (upload == default) { diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index 7af36fcb..3e2c138f 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -1,4 +1,4 @@ -// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs index 3d066fe9..924611eb 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs @@ -1,4 +1,4 @@ -// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham"> +// <copyright file="EnqueueDownloadBatchResponse.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a4d48279..707221ac 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -195,7 +195,8 @@ namespace slskd.Transfers.Downloads FileService fileService, IRelayService relayService, IFTPService ftpClient, - EventBus eventBus) + EventBus eventBus, + TimeProvider timeProvider = null) { Batches = batchService; Searches = searchService; @@ -207,6 +208,8 @@ namespace slskd.Transfers.Downloads Relay = relayService; EventBus = eventBus; + TimeProvider = timeProvider ?? TimeProvider.System; + Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } @@ -245,6 +248,7 @@ namespace slskd.Transfers.Downloads private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus EventBus { get; } private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private TimeProvider TimeProvider { get; } /// <summary> /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -320,7 +324,7 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files)); } - if (fileList.Count != fileList.Distinct().Count()) + if (fileList.Count != fileList.Select(f => f.Filename).Distinct().Count()) { throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); } @@ -505,11 +509,12 @@ namespace slskd.Transfers.Downloads 2. the transfer enters a state containing Completed 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled 4. the 'max wait time' CancellationTokenSource is cancelled + 5. the DownloadAsync() method throws add this to the dictionary before inserting the record, so we are guaranteed to have it in the right place once the transfer hits the UI */ - var enqueuedTcs = new TaskCompletionSource<Transfer>(); + var enqueuedTcs = new TaskCompletionSource<Transfer>(TaskCreationOptions.RunContinuationsAsynchronously); // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call) var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -545,11 +550,16 @@ namespace slskd.Transfers.Downloads TransferStates state = TransferStates.None; // satisfies condition #4; remote user doesn't respond after a really long time - using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForEnqueueRequestAck); + using var timeoutCts = new CancellationTokenSource(delay: maxTimeToWaitForEnqueueRequestAck, timeProvider: TimeProvider); timeoutCts.Token.Register(() => { + // note: disposed once we leave the try block, so registration doesn't fire unless it actually times out Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions)); enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs")); + + // cancel the download attempt so that it doesn't keep running (within Soulseek.NET) and cause the internal + // state of slskd to diverge from the internal state of Soulseek.NET. + cts.Cancel(swallowObjectDisposedException: true); }); // satisfies conditions #1 and #2 @@ -593,6 +603,10 @@ namespace slskd.Transfers.Downloads Log.Error(ex, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message); + // trip the TCS if DownloadAsync() throws before any of the other conditions trip it + // this is harmless if it has already been tripped + enqueuedTcs.TrySetException(ex); + if (!TryFail(transferId, exception: ex)) { Log.Error(ex, "Failed to clean up transfer {Id} after failed download", transferId); @@ -610,6 +624,7 @@ namespace slskd.Transfers.Downloads 2. the transfer enters a state containing Completed 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled 4. the 'max wait time' CancellationTokenSource is cancelled + 5. the DownloadAsync() method throws */ await enqueuedTcs.Task; @@ -716,9 +731,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); @@ -1002,7 +1017,7 @@ namespace slskd.Transfers.Downloads // of the transfer to Cancelled. _should_! if (CancellationTokens.TryRemove(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } @@ -1053,6 +1068,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; @@ -1064,6 +1085,7 @@ namespace slskd.Transfers.Downloads { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, + TransferRejectedException => TransferStates.Rejected, _ => TransferStates.Errored, }; } @@ -1078,6 +1100,11 @@ namespace slskd.Transfers.Downloads Log.Error(ex, "Failed to update database: {Message}", ex.Message); return false; } + finally + { + CancellationTokens.TryRemove(id, out var cts); + cts?.TryDispose(); + } } /// <summary> @@ -1215,20 +1242,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)) @@ -1248,6 +1261,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); } @@ -1547,11 +1572,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); @@ -1563,11 +1587,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/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs index 2e9dc8ef..ab209cff 100644 --- a/src/slskd/Transfers/Types/Upload.cs +++ b/src/slskd/Transfers/Types/Upload.cs @@ -37,12 +37,13 @@ namespace slskd.Transfers public sealed class Upload { - public DateTime Enqueued { get; set; } = DateTime.UtcNow; - public string Filename { get; set; } + public required Guid Id { get; init; } + public required DateTime Enqueued { get; init; } + public required string Filename { get; init; } public string Group { get; set; } public DateTime? Ready { get; set; } = null; public DateTime? Started { get; set; } = null; - public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); - public string Username { get; set; } + public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public required string Username { get; init; } } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index fa307b53..0a142c9f 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -32,13 +32,16 @@ namespace slskd.Transfers { + using System; + using System.Collections.Generic; + public sealed record UploadGroup { public string Name { get; init; } public int Priority { get; set; } - public bool SlotAvailable => UsedSlots < Slots; + public bool HasAvailableSlot => UsedSlots.Count < Slots; public int Slots { get; set; } public QueueStrategy Strategy { get; set; } - public int UsedSlots { get; set; } + public HashSet<Guid> UsedSlots { get; set; } } } diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2dca0d9e..3ad27e63 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -50,61 +50,66 @@ namespace slskd.Transfers.Uploads public interface IUploadQueue { /// <summary> - /// Awaits the start of an upload. + /// Awaits the start of an upload by returning a <see cref="Task"/> that is completed when the queue initiates it. /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The filename for which to await the start.</param> + /// <param name="transfer">The Transfer to await.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The operation context.</returns> - Task AwaitStartAsync(string username, string filename); + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + Task AwaitStartAsync(Transfer transfer, CancellationToken cancellationToken = default); /// <summary> /// Signals the completion of an upload. /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The completed filename.</param> - void Complete(string username, string filename); + /// <param name="transfer">The Transfer to complete.</param> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + void Complete(Transfer transfer); /// <summary> /// Gracefully attempts to signal the completion of an upload, returning false if a problem is encountered /// (such as the upload not being tracked currently). /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The completed filename.</param> + /// <param name="transfer">The Transfer to complete.</param> /// <returns>A value indicating whether a problem was encountered.</returns> - bool TryComplete(string username, string filename); + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + bool TryComplete(Transfer transfer); /// <summary> /// Enqueues an upload. /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The filename to enqueue.</param> - void Enqueue(string username, string filename); + /// <param name="transfer">The Transfer to enqueue.</param> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + void Enqueue(Transfer transfer); /// <summary> - /// Gets information about the specified <paramref name="groupName"/>. + /// Computes the estimated queue position of the specified <paramref name="transfer"/>. /// </summary> - /// <param name="groupName">The name of the group.</param> - /// <returns>The group information.</returns> - UploadGroup GetGroupInfo(string groupName); - - /// <summary> - /// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>. - /// </summary> - /// <param name="username">The username associated with the file.</param> - /// <param name="filename">The filename of the file for which the position is to be estimated.</param> + /// <remarks> + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// </remarks> + /// <param name="transfer">The Tranfer for which to estimate the position.</param> /// <returns>The estimated queue position of the file.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="NotFoundException">Thrown if the specified filename is not enqueued.</exception> - int EstimatePosition(string username, string filename); + int EstimatePosition(Transfer transfer); /// <summary> /// Computes the estimated queue position of the specified <paramref name="username"/> if they were to enqueue a file, - /// or zero if the transfer could start immediately. + /// along with the slot counts for the user's group. /// </summary> + /// <remarks> + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// </remarks> /// <param name="username">The username for which to estimate.</param> /// <returns> - /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. + /// The user's group, the group's total and free slots, and the estimated position if the user were to enqueue a file. /// </returns> - int ForecastPosition(string username); + /// <exception cref="ArgumentException">Thrown if the specified username is null or consists only of whitespace.</exception> + (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username); } /// <summary> @@ -140,37 +145,34 @@ namespace slskd.Transfers.Uploads private IUserService Users { get; } /// <summary> - /// Returns a <see cref="Task"/> that, when complete, signals the underlying Soulseek.NET logic that - /// the 'wait for a free slot' permissive has been obtained. When the <see cref="Process"/> method is - /// ready, it will complete the Task and the upload will start. + /// Awaits the start of an upload by returning a <see cref="Task"/> that is completed when the queue initiates it. /// </summary> - /// <remarks> - /// This is the mechanism we use to control the queue; the Task we return here is completed in the - /// <see cref="Process"/> method once we have determined that this transfer is next to go. - /// </remarks> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The filename for which to await the start.</param> + /// <param name="transfer">The Transfer to await.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The operation context.</returns> - public Task AwaitStartAsync(string username, string filename) + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + public Task AwaitStartAsync(Transfer transfer, CancellationToken cancellationToken = default) { - SyncRoot.Wait(); + ArgumentNullException.ThrowIfNull(transfer); + + SyncRoot.Wait(cancellationToken); try { - if (!UploadDictionary.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(transfer.Username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {username}"); + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var upload = list.FirstOrDefault(e => e.Filename == filename); + var upload = list.FirstOrDefault(e => e.Id == transfer.Id); if (upload == default) { - throw new SlskdException($"File {filename} is not enqueued for user {username}"); + throw new SlskdException($"Transfer {transfer.Id} is not enqueued for user {transfer.Username}"); } upload.Ready = DateTime.UtcNow; - Log.Debug("Ready: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + Log.Debug("Ready: {File} for {User} at {Time} (id: {Id})", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued, upload.Id); return upload.TaskCompletionSource.Task; } @@ -185,14 +187,16 @@ namespace slskd.Transfers.Uploads /// Gracefully attempts to signal the completion of an upload, returning false if a problem is encountered /// (such as the upload not being tracked currently). /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The completed filename.</param> + /// <param name="transfer">The Transfer to complete.</param> /// <returns>A value indicating whether a problem was encountered.</returns> - public bool TryComplete(string username, string filename) + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + public bool TryComplete(Transfer transfer) { + ArgumentNullException.ThrowIfNull(transfer); + try { - Complete(username, filename); + Complete(transfer); return true; } catch (SlskdException) @@ -204,30 +208,37 @@ namespace slskd.Transfers.Uploads /// <summary> /// Signals the completion of an upload. /// </summary> - /// <remarks> - /// Will not throw on repeated attempts. - /// </remarks> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The completed filename.</param> - public void Complete(string username, string filename) + /// <param name="transfer">The Transfer to complete.</param> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + public void Complete(Transfer transfer) { + ArgumentNullException.ThrowIfNull(transfer); + SyncRoot.Wait(); try { - if (!UploadDictionary.TryGetValue(username, out var list)) + if (!UploadDictionary.TryGetValue(transfer.Username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {username}"); + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var upload = list.FirstOrDefault(e => e.Filename == filename); + var upload = list.FirstOrDefault(e => e.Id == transfer.Id); if (upload == default) { - throw new SlskdException($"File {filename} is not enqueued for user {username}"); + throw new SlskdException($"Transfer {transfer.Id} is not enqueued for user {transfer.Username}"); } list.Remove(upload); + + // 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), upload.Username); + upload.TaskCompletionSource.TrySetCanceled(); + } + Log.Debug("Complete: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); // ensure the slot is returned to the group from which it was acquired the group may have been removed during the @@ -236,13 +247,13 @@ namespace slskd.Transfers.Uploads { var group = Groups[upload.Group]; - group.UsedSlots = Math.Max(0, group.UsedSlots - 1); - Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + group.UsedSlots.Remove(transfer.Id); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots.Count, group.Slots); } - if (list.Count == 0 && UploadDictionary.TryRemove(username, out _)) + if (list.Count == 0 && UploadDictionary.TryRemove(transfer.Username, out _)) { - Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", username); + Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", transfer.Username); } EmitMetrics(); @@ -257,19 +268,27 @@ namespace slskd.Transfers.Uploads /// <summary> /// Enqueues an upload. /// </summary> - /// <param name="username">The username of the remote user.</param> - /// <param name="filename">The filename to enqueue.</param> - public void Enqueue(string username, string filename) + /// <param name="transfer">The Transfer to enqueue.</param> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + public void Enqueue(Transfer transfer) { + ArgumentNullException.ThrowIfNull(transfer); + SyncRoot.Wait(); try { - var upload = new Upload() { Username = username, Filename = filename }; + var upload = new Upload() + { + Id = transfer.Id, + Username = transfer.Username, + Filename = transfer.Filename, + Enqueued = DateTime.UtcNow, + }; UploadDictionary.AddOrUpdate( - key: username, - addValue: new List<Upload>(new[] { upload }), + key: transfer.Username, + addValue: [upload], updateValueFactory: (key, list) => { list.Add(upload); @@ -277,7 +296,7 @@ namespace slskd.Transfers.Uploads }); EmitMetrics(); - Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + Log.Debug("Enqueued: {File} for {User} at {Time} (id: {Id})", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued, upload.Id); } finally { @@ -287,141 +306,162 @@ namespace slskd.Transfers.Uploads } /// <summary> - /// Gets information about the specified <paramref name="groupName"/>. - /// </summary> - /// <param name="groupName">The name of the group.</param> - /// <returns>The group information.</returns> - public UploadGroup GetGroupInfo(string groupName) - { - if (Groups.TryGetValue(groupName, out var group)) - { - return group; - } - - throw new NotFoundException($"A group with the name {groupName} could not be found"); - } - - /// <summary> - /// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>. + /// Computes the estimated queue position of the specified <paramref name="transfer"/>. /// </summary> - /// <param name="username">The username associated with the file.</param> - /// <param name="filename">The filename of the file for which the position is to be estimated.</param> + /// <remarks> + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// </remarks> + /// <param name="transfer">The Tranfer for which to estimate the position.</param> /// <returns>The estimated queue position of the file.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="NotFoundException">Thrown if the specified filename is not enqueued.</exception> - public int EstimatePosition(string username, string filename) + public int EstimatePosition(Transfer transfer) { - var groupName = Users.GetGroup(username); - var groupRecord = Groups.GetValueOrDefault(groupName); + ArgumentNullException.ThrowIfNull(transfer); + + var groupName = Users.GetGroup(transfer.Username); + + if (!Groups.TryGetValue(groupName, out var groupRecord)) + { + throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); + } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user + // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); - // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates - // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the - // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files - // are of equal length. - if (groupRecord.Strategy == QueueStrategy.RoundRobin) + SyncRoot.Wait(); + + try { // find this user's uploads - if (!UploadDictionary.TryGetValue(username, out var uploadsForUser)) + if (!UploadDictionary.TryGetValue(transfer.Username, out var uploadsForUser)) { - throw new NotFoundException($"File {filename} is not enqueued for user {username}"); + throw new NotFoundException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); } - // find the position of the requested file in the user's queue - var localPosition = uploadsForUser - .OrderBy(upload => upload.Enqueued) - .ToList() - .FindIndex(upload => upload.Username == username && upload.Filename == filename); - - if (localPosition < 0) + // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates + // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the + // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files + // are of equal length. + if (groupRecord.Strategy == QueueStrategy.RoundRobin) { - throw new NotFoundException($"File {filename} is not enqueued for user {username}"); - } + // find the position of the requested file in the user's queue + // note: backed by List<T>, which is stable and already ordered by enqueue time ASC + var localPosition = uploadsForUser + .FindIndex(u => u.Id == transfer.Id); - // start the position to the local position within this user's queue; the user's own files must be completed - // before this one can start. - var position = localPosition; - - // for each other user, add either localPosition or the count of that user's uploads, whichever is less - // example: - // - // aaaaa - // bb - // cccccccccccc - // ddddddd - // ^ - // - // if we want the position of the file over the carat above, first find the position of it - // within its own queue (= 5). assume uploads will process top down, left to right until reaching - // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over - // the carat at position 16. the actual number will vary due to many factors, including where in the - // round-robin ordering d is actually positioned (so +/- number of users downloading). - foreach (var group in uploadsForGroup.Where(group => group.Key != username)) - { - position += Math.Min(localPosition, group.Value.Count); + if (localPosition < 0) + { + throw new NotFoundException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + // start the position to the local position within this user's queue; the user's own files must be completed + // before this one can start. + var position = localPosition; + + // for each other user, add either localPosition or the count of that user's uploads, whichever is less + // example: + // + // aaaaa + // bb + // cccccccccccc + // ddddddd + // ^ + // + // if we want the position of the file over the carat above, first find the position of it + // within its own queue (= 4). assume uploads will process top down, left to right until reaching + // this one. that's the 4 ahead of it from d, plus 4 from a, 2 from b, and 4 from c in earlier rounds (= 14). + foreach (var group in uploadsForGroup.Where(group => group.Key != transfer.Username)) + { + position += Math.Min(localPosition, group.Value.Count); + } + + // be pessimistic and assume d is last in the rotation; every other user with a file in the same round + // goes first. in the example, a and c have a 5th file and b doesn't, putting the file over the carat + // at position 16. + var usersWithAtLeastAsManyFiles = uploadsForGroup + .Count(g => g.Key != transfer.Username && g.Value.Count() >= localPosition + 1); // localPosition is zero-based + + return position + usersWithAtLeastAsManyFiles; } - return position; - } + // find the upload + var upload = uploadsForUser.SingleOrDefault(u => u.Id == transfer.Id); - // for FIFO queues, files are uploaded in the order they are enqueued, so the position should be pretty good estimate. - // List ordering is guaranteed, so we are getting an accurate portrayal of where this file is in the queue by order of - // time enqueued. this includes uploads that are in progress. - var flattenedSortedUploadsForGroup = uploadsForGroup - .SelectMany(group => group.Value) - .OrderBy(upload => upload.Enqueued) - .ToList(); + if (upload is null) + { + throw new NotFoundException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } - var globalPosition = flattenedSortedUploadsForGroup.FindIndex(upload => upload.Username == username && upload.Filename == filename); + // the place in queue is simply the sum of all uploads across all other users in the group that were + // enqueued before this upload. + var globalPosition = uploadsForGroup.Sum(kvp => kvp.Value.Count(c => c.Enqueued < upload.Enqueued)); - if (globalPosition < 0) + return globalPosition; + } + finally { - throw new NotFoundException($"File {filename} is not enqueued for user {username}"); + SyncRoot.Release(); } - - return globalPosition; } /// <summary> /// Computes the estimated queue position of the specified <paramref name="username"/> if they were to enqueue a file, - /// or zero if the transfer could start immediately. + /// along with the slot counts for the user's group. /// </summary> + /// <remarks> + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// </remarks> /// <param name="username">The username for which to estimate.</param> /// <returns> - /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. + /// The user's group, the group's total and free slots, and the estimated position if the user were to enqueue a file. /// </returns> - public int ForecastPosition(string username) + /// <exception cref="ArgumentException">Thrown if the specified username is null or consists only of whitespace.</exception> + public (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username) { + ArgumentException.ThrowIfNullOrWhiteSpace(username); + var groupName = Users.GetGroup(username); + if (!Groups.TryGetValue(groupName, out var groupRecord)) + { + throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); + } + + var totalSlots = Math.Min(GlobalSlots, groupRecord.Slots); + var freeSlots = Math.Max(0, totalSlots - groupRecord.UsedSlots.Count); + // if there's a slot available, the user will enter the queue at position 0 (will start immediately) - if (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.SlotAvailable) + if (freeSlots > 0) { - return 0; + return (groupName, totalSlots, freeSlots, 0); } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user + // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the - // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. + // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting. if (groupRecord.Strategy == QueueStrategy.RoundRobin) { - return uploadsForGroup.Count() + 1; + return (groupName, totalSlots, freeSlots, uploadsForGroup.Count()); } // for FIFO queues, the user will enter the queue at the very back. return the total number of uploads in progress and - // enqueued, + 1. - return uploadsForGroup - .SelectMany(group => group.Value) - .Count() + 1; + // enqueued. + return (groupName, totalSlots, freeSlots, uploadsForGroup.Sum(kvp => kvp.Value.Count)); } private void Configure(Options options) { - int GetExistingUsedSlotsOrDefault(string group) - => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0; + HashSet<Guid> GetExistingUsedSlotsOrDefault(string group) + => Groups.ContainsKey(group) ? Groups[group].UsedSlots : []; SyncRoot.Wait(); @@ -502,7 +542,7 @@ namespace slskd.Transfers.Uploads // number of global slots, just exit. we *could* proceed, but uploads would stack up behind the // global semaphore in Soulseek.NET and we wouldn't be able to control the order in which those // were processed, so don't do that. - if (Groups.Values.Sum(g => g.UsedSlots) >= GlobalSlots) + if (Groups.Values.Sum(g => g.UsedSlots.Count) >= GlobalSlots) { return null; } @@ -536,7 +576,7 @@ namespace slskd.Transfers.Uploads // process each group in ascending order of priority, and stop after the first ready upload is released. foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name)) { - if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) + if (group.UsedSlots.Count >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) { continue; } @@ -549,7 +589,7 @@ namespace slskd.Transfers.Uploads // returned to the proper place upon completion upload.Started = DateTime.UtcNow; upload.Group = group.Name; - group.UsedSlots++; + group.UsedSlots.Add(upload.Id); // release the upload upload.TaskCompletionSource.SetResult(); @@ -557,7 +597,7 @@ namespace slskd.Transfers.Uploads EmitMetrics(); Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); - Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots.Count, group.Slots); return upload; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..246f4b31 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -45,6 +45,7 @@ namespace slskd.Transfers.Uploads using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; + using Microsoft.EntityFrameworkCore.Query; using Serilog; using slskd.Events; using slskd.Relay; @@ -96,11 +97,11 @@ namespace slskd.Transfers.Uploads Task<Transfer> UploadAsync(Transfer transfer, CancellationToken cancellationToken = default); /// <summary> - /// Finds a single upload matching the specified <paramref name="expression"/>. + /// Finds a single upload matching the specified <paramref name="id"/>. /// </summary> - /// <param name="expression">The expression to use to match uploads.</param> + /// <param name="id">The unique identifier of the upload.</param> /// <returns>The found transfer, or default if not found.</returns> - Transfer Find(Expression<Func<Transfer, bool>> expression); + Transfer Find(Guid id); /// <summary> /// Gets upload statistics for the specified <paramref name="username"/>. @@ -111,9 +112,9 @@ namespace slskd.Transfers.Uploads UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null); /// <summary> - /// Returns a list of all uploads matching the optional <paramref name="expression"/>. + /// Returns a list of all uploads matching the specified <paramref name="expression"/>. /// </summary> - /// <param name="expression">An optional expression used to match uploads.</param> + /// <param name="expression">An expression used to match uploads.</param> /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param> /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns> List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved); @@ -127,6 +128,15 @@ namespace slskd.Transfers.Uploads int Prune(int age, params TransferStates[] states); /// <summary> + /// Returns a list of all uploads matching the specified <paramref name="query"/>, projected to type <typeparamref name="TResult"/>. + /// </summary> + /// <typeparam name="TResult">The Type of the returned projection.</typeparam> + /// <param name="query">The query expression.</param> + /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param> + /// <returns>The list of uploads matching the specified query.</returns> + List<TResult> Query<TResult>(Func<IQueryable<Transfer>, IQueryable<TResult>> query, bool includeRemoved = false); + + /// <summary> /// Removes the completed upload matching the specified <paramref name="id"/>. /// </summary> /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks> @@ -297,7 +307,7 @@ namespace slskd.Transfers.Uploads we're not using DbContext and tracked changes here because we don't want to hold a connection open for the duration of the upload */ - transfer = Find(t => t.Id == transfer.Id) + transfer = Find(transfer.Id) ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) @@ -413,7 +423,6 @@ namespace slskd.Transfers.Uploads lastReportedAverageSpeed = now; } - } finally { @@ -430,14 +439,14 @@ namespace slskd.Transfers.Uploads disposeInputStreamOnCompletion: true, // note: don't set this to false! governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), - slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), - slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(transfer, ct), + slotReleased: (tx) => Queue.Complete(transfer)); // register the cancellation token CancellationTokens.TryAdd(transfer.Id, cts); // add the transfer to the UploadQueue so that it can become eligible for selection - Queue.Enqueue(transfer.Username, transfer.Filename); + Queue.Enqueue(transfer); transfer.EnqueuedAt = DateTime.UtcNow; SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); @@ -507,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); @@ -523,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); @@ -539,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); @@ -599,7 +605,7 @@ namespace slskd.Transfers.Uploads // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious // and ensure it gets removed - Queue.TryComplete(username: transfer.Username, filename: transfer.Filename); + Queue.TryComplete(transfer); } catch (Exception ex) { @@ -796,21 +802,15 @@ namespace slskd.Transfers.Uploads } /// <summary> - /// Finds a single upload matching the specified <paramref name="expression"/>. + /// Finds a single upload matching the specified <paramref name="id"/>. /// </summary> - /// <param name="expression">The expression to use to match uploads.</param> + /// <param name="id">The unique identifier of the upload.</param> /// <returns>The found transfer, or default if not found.</returns> - public Transfer Find(Expression<Func<Transfer, bool>> expression) + public Transfer Find(Guid id) { try { - using var context = ContextFactory.CreateDbContext(); - - return context.Transfers - .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression) - .SingleOrDefault(); + return Query(q => q.Where(t => t.Id == id), includeRemoved: true).SingleOrDefault(); } catch (Exception ex) { @@ -820,9 +820,9 @@ namespace slskd.Transfers.Uploads } /// <summary> - /// Returns a list of all uploads matching the optional <paramref name="expression"/>. + /// Returns a list of all uploads matching the specified <paramref name="expression"/>. /// </summary> - /// <param name="expression">An optional expression used to match uploads.</param> + /// <param name="expression">An expression used to match uploads.</param> /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param> /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns> public List<Transfer> List(Expression<Func<Transfer, bool>> expression, bool includeRemoved) @@ -831,18 +831,51 @@ namespace slskd.Transfers.Uploads try { + return Query(q => q.Where(expression), includeRemoved); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + throw; + } + } + + /// <summary> + /// Returns a list of all uploads matching the specified <paramref name="query"/>, projected to type <typeparamref name="TResult"/>. + /// </summary> + /// <typeparam name="TResult">The Type of the returned projection.</typeparam> + /// <param name="query">The query expression.</param> + /// <param name="includeRemoved">A value indicating whether to include uploads that have been removed previously.</param> + /// <returns>The list of uploads matching the specified query.</returns> + public List<TResult> Query<TResult>(Func<IQueryable<Transfer>, IQueryable<TResult>> query, bool includeRemoved = false) + { + ArgumentNullException.ThrowIfNull(query); + + try + { using var context = ContextFactory.CreateDbContext(); - return context.Transfers + var transfers = context.Transfers .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Upload) - .Where(t => !t.Removed || includeRemoved) - .Where(expression) - .ToList(); + .Where(t => t.Direction == TransferDirection.Upload); + + if (!includeRemoved) + { + transfers = transfers.Where(t => !t.Removed); + } + + var result = query(transfers); + + if (result.Provider is not IAsyncQueryProvider) + { + throw new InvalidOperationException("Query must be fully translatable to SQL; in-memory evaluation is not allowed (remove any AsEnumerable() present in the query)"); + } + + return result.ToList(); } catch (Exception ex) { - Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + Log.Error(ex, "Failed to execute upload queury: {Message}", ex.Message); throw; } } @@ -937,7 +970,7 @@ namespace slskd.Transfers.Uploads { if (CancellationTokens.TryRemove(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } @@ -1082,7 +1115,7 @@ namespace slskd.Transfers.Uploads private bool TryFail(Guid id, string exception, TransferStates state) { - var t = Find(t => t.Id == id); + var t = Find(id); if (t is null) { diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 8029b5e0..41d2db6a 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -42,7 +42,6 @@ namespace slskd.Users.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; - using Soulseek; /// <summary> @@ -83,7 +82,7 @@ namespace slskd.Users.API /// <returns></returns> /// <response code="200">The request completed successfully.</response> [HttpGet("{username}/endpoint")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IPEndPoint), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Endpoint([FromRoute, UrlEncoded, Required] string username) @@ -115,7 +114,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/browse")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Browse([FromRoute, UrlEncoded, Required] string username) @@ -179,7 +178,7 @@ namespace slskd.Users.API /// <param name="request">The directory contents request.</param> /// <returns></returns> [HttpPost("{username}/directory")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Directory([FromRoute, UrlEncoded, Required] string username, [FromBody, Required] DirectoryContentsRequest request) @@ -219,7 +218,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/info")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Info), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Info([FromRoute, UrlEncoded, Required] string username) @@ -251,7 +250,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/status")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Status), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Status([FromRoute, UrlEncoded, Required] string username) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 3ce827c8..046a87e5 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -325,7 +325,15 @@ namespace slskd.Users { ArgumentNullException.ThrowIfNull(username); - if (BlacklistDecisionCache.TryGetValue<bool>(username, out var cached)) + // looks like '::ffff:1.2.3.4'; convert it back to IPv4 so CIDR checks work + if (ipAddress is not null && ipAddress.IsIPv4MappedToIPv6) + { + ipAddress = ipAddress.MapToIPv4(); + } + + var cacheKey = ipAddress is null ? username : $"{username}@{ipAddress}"; + + if (BlacklistDecisionCache.TryGetValue<bool>(cacheKey, out var cached)) { return cached; } @@ -343,7 +351,7 @@ namespace slskd.Users var blacklisted = IsBlacklistedInternal(username, ipAddress); BlacklistDecisionCache.Set( - key: username, + key: cacheKey, value: blacklisted, options: new MemoryCacheEntryOptions { @@ -444,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 } }); } } @@ -564,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 }); } @@ -572,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 }); } } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 03fc4af4..f17e6046 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -14,6 +14,7 @@ <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled> <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion> <_SkipUpgradeNetAnalyzersNuGetWarning>true</_SkipUpgradeNetAnalyzersNuGetWarning> + <StaticWebAssetsEnabled>false</StaticWebAssetsEnabled> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> @@ -43,38 +44,38 @@ </Target> <ItemGroup> - <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" /> - <PackageReference Include="Dapper" Version="2.1.79" /> + <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" /> + <PackageReference Include="Dapper" Version="2.1.89" /> <PackageReference Include="FluentFTP" Version="49.0.2" /> <PackageReference Include="IPAddressRange" Version="6.3.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" /> - <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.9" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.301"> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.13" /> + <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.402"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.9" /> - <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.9" /> + <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.13" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.13" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.13" /> <PackageReference Include="OneOf" Version="3.0.271" /> <PackageReference Include="prometheus-net" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="8.2.1" /> <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.1" /> <PackageReference Include="prometheus-net.SystemMetrics" Version="3.1.0" /> - <PackageReference Include="Serilog" Version="4.3.1" /> + <PackageReference Include="Serilog" Version="4.4.0" /> <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> <PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" /> <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> - <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="9.0.1" /> + <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="9.0.2" /> <PackageReference Include="Serilog.Sinks.Http" Version="9.2.1" /> <PackageReference Include="Soulseek" Version="10.0.2" /> - <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"> + <PackageReference Include="StyleCop.Analyzers" Version="1.3.151-beta"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" /> + <PackageReference Include="Swashbuckle.AspNetCore" Version="10.3.1" /> <PackageReference Include="TagLibSharp" Version="2.3.0" /> <PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" /> <PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" /> diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 6e096188..0be1b6d6 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3429,9 +3429,9 @@ } }, "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.15.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", - "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -6392,13 +6392,16 @@ "dev": true }, "node_modules/baseline-browser-mapping": { - "version": "2.9.19", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.19.tgz", - "integrity": "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==", + "version": "2.11.20", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.20.tgz", + "integrity": "sha512-H0ulySigv6icDJ1F7SjtdCD6PrhTpdYCmP0CactWy1+ekh0AFd0o1Wn5T8b+hnTmdBx19u9yhL6wvCylXMY7zw==", "dev": true, "license": "Apache-2.0", "bin": { - "baseline-browser-mapping": "dist/cli.js" + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" } }, "node_modules/batch": { @@ -6447,23 +6450,24 @@ "dev": true }, "node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "version": "1.20.9", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz", + "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==", "dev": true, + "license": "MIT", "dependencies": { - "bytes": "3.1.2", + "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.16.0", + "raw-body": "~2.5.3", "type-is": "~1.6.18", - "unpipe": "1.0.0" + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8", @@ -6475,15 +6479,38 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, + "license": "MIT", "dependencies": { "ms": "2.0.0" } }, + "node_modules/body-parser/node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/body-parser/node_modules/iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, + "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -6495,7 +6522,18 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "dev": true + "dev": true, + "license": "MIT" + }, + "node_modules/body-parser/node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } }, "node_modules/bonjour-service": { "version": "1.1.1", @@ -6522,10 +6560,11 @@ "dev": true }, "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -6550,9 +6589,9 @@ "dev": true }, "node_modules/browserslist": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", - "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "version": "4.28.8", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.8.tgz", + "integrity": "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==", "dev": true, "funding": [ { @@ -6570,11 +6609,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.9.0", - "caniuse-lite": "^1.0.30001759", - "electron-to-chromium": "^1.5.263", - "node-releases": "^2.0.27", - "update-browserslist-db": "^1.2.0" + "baseline-browser-mapping": "^2.11.12", + "caniuse-lite": "^1.0.30001809", + "electron-to-chromium": "^1.5.402", + "node-releases": "^2.0.53", + "update-browserslist-db": "^1.3.0" }, "bin": { "browserslist": "cli.js" @@ -6743,9 +6782,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001768", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001768.tgz", - "integrity": "sha512-qY3aDRZC5nWPgHUgIB84WL+nySuo19wk0VJpp/XI9T34lrvkyhRvNVOFJOp2kxClQhiFBu+TaUSudf6oa3vkSA==", + "version": "1.0.30001810", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001810.tgz", + "integrity": "sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==", "dev": true, "funding": [ { @@ -7149,15 +7188,16 @@ } }, "node_modules/compression": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", - "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz", + "integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==", "dev": true, "license": "MIT", "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", + "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", @@ -7165,6 +7205,10 @@ }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/compression/node_modules/debug": { @@ -7230,6 +7274,7 @@ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8412,9 +8457,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.286", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.286.tgz", - "integrity": "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==", + "version": "1.5.420", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.420.tgz", + "integrity": "sha512-2yD6XreGusOfNV+dUcvipJEXc3n/n7fgr7996aszTG+YY5E4mqM4tOq/3uhP129cazL9YHbVWSpc79ePotWtPA==", "dev": true, "license": "ISC" }, @@ -9156,9 +9201,9 @@ } }, "node_modules/eslint-config-canonical/node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { @@ -9531,10 +9576,11 @@ } }, "node_modules/eslint-plugin-canonical/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } @@ -10277,10 +10323,11 @@ } }, "node_modules/eslint-plugin-vitest/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } @@ -10696,15 +10743,15 @@ } }, "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "version": "4.22.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", + "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==", "dev": true, "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "~1.20.3", + "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", @@ -10721,9 +10768,9 @@ "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "~0.1.12", + "path-to-regexp": "~0.1.13", "proxy-addr": "~2.0.7", - "qs": "~6.14.0", + "qs": "~6.16.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", @@ -10764,28 +10811,12 @@ "dev": true }, "node_modules/express/node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", "dev": true, "license": "MIT" }, - "node_modules/express/node_modules/qs": { - "version": "6.14.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", - "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/extract-files": { "version": "11.0.0", "resolved": "https://registry.npmjs.org/extract-files/-/extract-files-11.0.0.tgz", @@ -10887,9 +10918,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { @@ -10999,10 +11030,11 @@ } }, "node_modules/filelist/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } @@ -11152,9 +11184,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", "funding": [ { "type": "individual", @@ -14306,9 +14338,9 @@ } }, "node_modules/js-yaml": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", - "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { @@ -14569,14 +14601,14 @@ } }, "node_modules/launch-editor": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", - "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", + "version": "2.14.2", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.2.tgz", + "integrity": "sha512-NHJEb30MGBCkmZXLZwz25t37QR4aY03ZzPYUJXOJaOa92uWwExI9SBQUuIznBYc1xkD7cJNGX7oc3Nl3sq2kQQ==", "dev": true, "license": "MIT", "dependencies": { "picocolors": "^1.1.1", - "shell-quote": "^1.8.4" + "shell-quote": "^1.10.0" } }, "node_modules/less": { @@ -14972,6 +15004,7 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -15249,9 +15282,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", - "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==", + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", "dev": true, "funding": [ { @@ -15259,6 +15292,7 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -15351,9 +15385,9 @@ } }, "node_modules/node-forge": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.2.tgz", - "integrity": "sha512-6xKiQ+cph9KImrRh0VsjH2d8/GXA4FIMlgU4B757iI1ApvcyA9VlouP0yZJha01V+huImO+kKMU7ih+2+E14fw==", + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", "dev": true, "license": "(BSD-3-Clause OR GPL-2.0)", "engines": { @@ -15367,11 +15401,14 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.27", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", - "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "version": "2.0.54", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.54.tgz", + "integrity": "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -17225,10 +17262,11 @@ } }, "node_modules/postcss-selector-parser": { - "version": "6.0.13", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz", - "integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==", + "version": "6.1.5", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.5.tgz", + "integrity": "sha512-TEHFzb5KRDKaOgJ4TYE+0jyJtFbjLvkdVOu0fZ2b6MTWzoqZd4Le+61aEppWkvTlYePgOX4ATL1wsAIPMLTw6Q==", "dev": true, + "license": "MIT", "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -17477,16 +17515,21 @@ } }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "dev": true, + "license": "MIT", "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-addr/node_modules/ipaddr.js": { @@ -17556,12 +17599,14 @@ } }, "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz", + "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.6" + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" @@ -17639,18 +17684,40 @@ } }, "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", "dev": true, + "license": "MIT", "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" }, "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/raw-body/node_modules/iconv-lite": { @@ -17658,6 +17725,7 @@ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, + "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -17665,6 +17733,16 @@ "node": ">=0.10.0" } }, + "node_modules/raw-body/node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/react": { "version": "16.14.0", "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz", @@ -19185,9 +19263,9 @@ } }, "node_modules/shell-quote": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz", - "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", "dev": true, "license": "MIT", "engines": { @@ -19198,15 +19276,15 @@ } }, "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -19218,14 +19296,14 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -19329,10 +19407,11 @@ } }, "node_modules/source-map-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", - "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } @@ -19956,9 +20035,9 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.15.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz", - "integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -20570,6 +20649,7 @@ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", "dev": true, + "license": "MIT", "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -20792,9 +20872,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.2.tgz", + "integrity": "sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==", "dev": true, "funding": [ { diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 3fbaa468..091cc2f8 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -127,7 +127,7 @@ const ModeSpecificConnectButton = ({ color = 'yellow'; } - if (server?.isConnecting || server?.IsLoggingIn) { + if (server?.isConnecting || server?.isLoggingIn) { icon = 'sync alternate loading'; color = 'green'; } @@ -499,8 +499,8 @@ class App extends Component { <Modal.Content> <p> You are currently running version{' '} - <strong>{current}</strong> - while version <strong>{latest}</strong> is available. + <strong>{current}</strong> while version{' '} + <strong>{latest}</strong> is available. </p> </Modal.Content> <Modal.Actions> diff --git a/src/web/src/components/AppFooter.jsx b/src/web/src/components/AppFooter.jsx index 9a295eb5..b07af7a2 100644 --- a/src/web/src/components/AppFooter.jsx +++ b/src/web/src/components/AppFooter.jsx @@ -1,3 +1,4 @@ +import { urlBase } from '../config'; import { formatBytes } from '../lib/util'; import React from 'react'; import { Icon, Menu } from 'semantic-ui-react'; @@ -69,7 +70,7 @@ const AppFooter = ({ <img alt="" className="footer-logo" - src="/favicon.ico" + src={`${urlBase}/favicon.ico`} /> slskd {current && <span className="footer-version">{current}</span>} diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx index 44e6b2dd..c6107bd5 100644 --- a/src/web/src/components/Browse/Browse.jsx +++ b/src/web/src/components/Browse/Browse.jsx @@ -251,8 +251,13 @@ class Browse extends Component { return; } - const response = await users.getBrowseStatus({ username }); - this.setState({ browseStatus: response.data }); + try { + const response = await users.getBrowseStatus({ username }); + this.setState({ browseStatus: response.data }); + } catch { + // status is not available until the first progress update, and is removed shortly after completion; + // this runs on an interval, so just try again next time + } }; getDirectoryTree = ({ directories, separator }) => { diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 9224fb30..4fcb44ed 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -60,7 +60,13 @@ class Chat extends Component { this.setState( { active: sessionStorage.getItem(activeChatKey) || '', - interval: window.setInterval(this.fetchConversations, 5_000), + interval: window.setInterval(async () => { + try { + await this.fetchConversations(); + } catch (error) { + console.error(error); + } + }, 5_000), }, async () => { await this.fetchConversations(); @@ -113,7 +119,6 @@ class Chat extends Component { // check to see if the active chat is still active // this will happen whenever a chat is closed/removed if (activeConversation) { - console.log('active?', activeConversation); // *before* fetching messages, ack any unacked messages // for the active chat if (activeConversation.hasUnAcknowledgedMessages === true) { diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx index 5a6cf0c2..dd3c7178 100644 --- a/src/web/src/components/Rooms/RoomJoinModal.jsx +++ b/src/web/src/components/Rooms/RoomJoinModal.jsx @@ -25,7 +25,7 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { const getAvailableRooms = async () => { setLoading(true); const availableResult = await rooms.getAvailable(); - setAvailable(availableResult); + setAvailable(availableResult ?? []); setLoading(false); }; diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index f6bdb685..87fe51be 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -1,4 +1,4 @@ -import { activeRoomKey } from '../../config'; +import { activeRoomKey, urlBase } from '../../config'; import * as rooms from '../../lib/rooms'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; import RoomMenu from './RoomMenu'; @@ -81,8 +81,20 @@ class Rooms extends Component { { active: sessionStorage.getItem(activeRoomKey) || '', intervals: { - messages: window.setInterval(this.fetchActiveRoom, 1_000), - rooms: window.setInterval(this.fetchJoinedRooms, 500), + messages: window.setInterval(async () => { + try { + await this.fetchActiveRoom(); + } catch (error) { + console.error(error); + } + }, 1_000), + rooms: window.setInterval(async () => { + try { + await this.fetchJoinedRooms(); + } catch (error) { + console.error(error); + } + }, 500), }, }, async () => { @@ -248,13 +260,13 @@ class Rooms extends Component { }; handleUserProfile = () => { - this.props.history.push('/users', { + this.props.history.push(`${urlBase}/users`, { user: this.state.contextMenu.message.username, }); }; handleBrowseShares = () => { - this.props.history.push('/browse', { + this.props.history.push(`${urlBase}/browse`, { user: this.state.contextMenu.message.username, }); }; diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx index 567b80a3..a17df823 100644 --- a/src/web/src/components/Search/Response.jsx +++ b/src/web/src/components/Search/Response.jsx @@ -254,8 +254,9 @@ class Response extends Component { size="large" /> <Label> - {downloadError.data + - ` (HTTP ${downloadError.status} ${downloadError.statusText})`} + {downloadError?.data + ? `${downloadError.data} (HTTP ${downloadError.status} ${downloadError.statusText})` + : 'Download failed'} </Label> </span> )} diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx index d50462ba..9306867c 100644 --- a/src/web/src/components/Search/Searches.jsx +++ b/src/web/src/components/Search/Searches.jsx @@ -145,9 +145,11 @@ const Searches = ({ server } = {}) => { }); setRemoving(false); - } catch (error_) { - console.error(error_); - toast.error(error?.response?.data ?? error?.message ?? error); + } catch (removeError) { + console.error(removeError); + toast.error( + removeError?.response?.data ?? removeError?.message ?? removeError, + ); setRemoving(false); } }; @@ -218,24 +220,24 @@ const Searches = ({ server } = {}) => { action={ <> <Button - disabled={creating || !server.isConnected} + disabled={creating || !server?.isConnected} icon="plus" onClick={create} /> <Button - disabled={creating || !server.isConnected} + disabled={creating || !server?.isConnected} icon="search" onClick={() => create({ navigate: true })} /> </> } className="search-input" - disabled={creating || !server.isConnected} + disabled={creating || !server?.isConnected} input={ <input data-lpignore="true" placeholder={ - server.isConnected + server?.isConnected ? 'Search phrase' : 'Connect to server to perform a search' } diff --git a/src/web/src/components/Shared/CodeEditor.jsx b/src/web/src/components/Shared/CodeEditor.jsx index 8780bc31..b82683de 100644 --- a/src/web/src/components/Shared/CodeEditor.jsx +++ b/src/web/src/components/Shared/CodeEditor.jsx @@ -8,8 +8,6 @@ import CodeMirror from '@uiw/react-codemirror'; import React from 'react'; const CodeEditor = ({ onChange = () => {}, theme, value, ...rest }) => { - console.log(defaultHighlightStyle); - return ( <CodeMirror extensions={[ diff --git a/src/web/src/components/System/Data/index.jsx b/src/web/src/components/System/Data/index.jsx index 8b6a99eb..2424ea87 100644 --- a/src/web/src/components/System/Data/index.jsx +++ b/src/web/src/components/System/Data/index.jsx @@ -5,9 +5,15 @@ import { Button, Divider, Header, Icon } from 'semantic-ui-react'; const clear = async ({ direction, setState }) => { setState(true); - await clearCompleted({ direction }); - setState(false); - toast.success(`Completed ${direction}s cleared!`); + + try { + await clearCompleted({ direction }); + toast.success(`Completed ${direction}s cleared!`); + } catch (error) { + toast.error(error?.response?.data ?? error?.message ?? error); + } finally { + setState(false); + } }; const Data = () => { diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx index 7f708908..b0549259 100644 --- a/src/web/src/components/System/Events/index.jsx +++ b/src/web/src/components/System/Events/index.jsx @@ -17,18 +17,27 @@ const Events = () => { const fetch = async () => { setLoading(true); - const { events: items, totalCount } = await list({ - limit: PER_PAGE, - offset: (page - 1) * PER_PAGE, - }); + try { + const { events: items, totalCount } = await list({ + limit: PER_PAGE, + offset: (page - 1) * PER_PAGE, + }); - const tp = Math.ceil(totalCount / PER_PAGE); + const tp = Math.ceil(totalCount / PER_PAGE); - setEvents(items); - setTotalPages(Number.isNaN(tp) ? 0 : tp); - setLoading(false); + setEvents(items); + setTotalPages(Number.isNaN(tp) ? 0 : tp); - return items; + return items; + } catch (error) { + console.error(error); + setEvents([]); + setTotalPages(0); + + return []; + } finally { + setLoading(false); + } }; const paginationChanged = ({ activePage }) => { diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx index ca0bdba1..a4f0bbbe 100644 --- a/src/web/src/components/System/Files/Explorer.jsx +++ b/src/web/src/components/System/Files/Explorer.jsx @@ -9,6 +9,7 @@ const FileRow = ({ length, modifiedAt, name, + onDeleted, remoteFileManagement, root, subdirectory, @@ -34,7 +35,7 @@ const FileRow = ({ path: `${subdirectory.join('/')}/${fullName}`, root, }); - fetch(); + onDeleted(); }, }, ]} @@ -66,6 +67,7 @@ const DirectoryRow = ({ modifiedAt, name, onClick = () => {}, + onDeleted, remoteFileManagement, root, subdirectory, @@ -94,7 +96,7 @@ const DirectoryRow = ({ path: `${subdirectory.join('/')}/${fullName}`, root, }); - fetch(); + onDeleted(); }, }, ]} @@ -131,12 +133,19 @@ const Explorer = ({ remoteFileManagement, root }) => { const fetch = async () => { setLoading(true); - const directoryResult = await list({ - root, - subdirectory: subdirectory.join('/'), - }); - setDirectory(directoryResult); - setLoading(false); + + try { + const directoryResult = await list({ + root, + subdirectory: subdirectory.join('/'), + }); + setDirectory(directoryResult); + } catch (error) { + console.error(error); + setDirectory({ directories: [], files: [] }); + } finally { + setLoading(false); + } }; useEffect(() => { @@ -281,6 +290,7 @@ const Explorer = ({ remoteFileManagement, root }) => { <DirectoryRow key={d.name} onClick={() => select({ path: d.name })} + onDeleted={fetch} remoteFileManagement={remoteFileManagement} root={root} subdirectory={subdirectory} @@ -290,6 +300,7 @@ const Explorer = ({ remoteFileManagement, root }) => { {sortedFiles?.map((f) => ( <FileRow key={f.name} + onDeleted={fetch} remoteFileManagement={remoteFileManagement} root={root} subdirectory={subdirectory} diff --git a/src/web/src/components/System/Info/index.jsx b/src/web/src/components/System/Info/index.jsx index 8672b5df..016b683f 100644 --- a/src/web/src/components/System/Info/index.jsx +++ b/src/web/src/components/System/Info/index.jsx @@ -42,8 +42,9 @@ const Info = ({ state, theme }) => { mediaQuery="(max-width: 686px)" onClick={() => window.open( - `http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`, + `http://www.slsknet.org/qtlogin.php?username=${encodeURIComponent(state?.user?.username ?? '')}`, '_blank', + 'noopener,noreferrer', ) } > diff --git a/src/web/src/components/System/Logs/Explorer.jsx b/src/web/src/components/System/Logs/Explorer.jsx new file mode 100644 index 00000000..b1391da2 --- /dev/null +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -0,0 +1,216 @@ +import '../Files/Files.css'; +import { getFileBlob, list } from '../../../lib/logs'; +import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; +import { + ErrorSegment, + LoaderSegment, + PlaceholderSegment, + Switch, +} from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { toast } from 'react-toastify'; +import { Header, Icon, Table } from 'semantic-ui-react'; + +const view = async (filename) => { + const tab = window.open('', '_blank'); + + if (!tab) { + toast.error( + 'Unable to open a new window; allow pop-ups for this site to view logs', + ); + return; + } + + try { + const blob = await getFileBlob({ filename }); + + // hack: we can't pass a JWT in a plain link, so we have to fetch the blob + // and then shove it into the window rather than just displaying it + tab.location.href = window.URL.createObjectURL( + new Blob([blob], { type: 'text/plain; charset=utf-8' }), + ); + } catch (error) { + tab.close(); + toast.error(error?.message ?? error); + } +}; + +const download = async (filename) => { + try { + const blob = await getFileBlob({ filename }); + + downloadFile(blob, filename, 'text/plain'); + } catch (error) { + toast.error(error?.message ?? error); + } +}; + +const FileRow = ({ length, modifiedAt, name }) => ( + <Table.Row key={name}> + <Table.Cell> + <Icon name="file alternate outline" /> + {name} + </Table.Cell> + <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> + <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell> + <Table.Cell style={{ whiteSpace: 'nowrap' }}> + <Icon + name="external alternate" + onClick={() => view(name)} + style={{ cursor: 'pointer', marginRight: '0.5em' }} + title={`View ${name} in a new window`} + /> + <Icon + name="download" + onClick={() => download(name)} + style={{ cursor: 'pointer' }} + title={`Download ${name}`} + /> + </Table.Cell> + </Table.Row> +); + +const Explorer = () => { + const [files, setFiles] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(undefined); + const [sortColumn, setSortColumn] = useState('date'); + const [sortDirection, setSortDirection] = useState('descending'); + + const fetch = async () => { + setLoading(true); + setError(undefined); + + try { + setFiles(await list()); + } catch (fetchError) { + if (fetchError?.response?.status === 404) { + setFiles([]); + } else { + setError(fetchError?.message ?? fetchError); + } + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetch(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + const handleSort = (column) => { + if (sortColumn === column) { + setSortDirection( + sortDirection === 'ascending' ? 'descending' : 'ascending', + ); + } else { + setSortColumn(column); + setSortDirection('ascending'); + } + }; + + const sortItems = (items) => { + if (!items || items.length === 0) return items; + + return [...items].sort((a, b) => { + let compareValue = 0; + + if (sortColumn === 'name') { + compareValue = a.name.localeCompare(b.name, undefined, { + numeric: true, + sensitivity: 'base', + }); + } else if (sortColumn === 'date') { + const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); + const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); + compareValue = dateA - dateB; + } + + return sortDirection === 'ascending' ? compareValue : -compareValue; + }); + }; + + const sortedFiles = sortItems(files); + + return ( + <> + <Header + className="explorer-working-directory" + size="small" + > + <Icon name="folder open" /> + /logs + </Header> + <Switch + empty={ + !loading && + !error && + files.length === 0 && ( + <PlaceholderSegment + caption="No log files" + icon="file alternate outline" + /> + ) + } + error={error && <ErrorSegment caption={error} />} + loading={loading && <LoaderSegment />} + > + <Table + className="unstackable" + size="large" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell + className="explorer-list-name" + onClick={() => handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + <Icon + name={ + sortDirection === 'ascending' + ? 'chevron up' + : 'chevron down' + } + /> + )} + </Table.HeaderCell> + <Table.HeaderCell + className="explorer-list-date" + onClick={() => handleSort('date')} + style={{ cursor: 'pointer' }} + > + Date Modified + {sortColumn === 'date' && ( + <Icon + name={ + sortDirection === 'ascending' + ? 'chevron up' + : 'chevron down' + } + /> + )} + </Table.HeaderCell> + <Table.HeaderCell className="explorer-list-size"> + Size + </Table.HeaderCell> + <Table.HeaderCell className="explorer-list-action" /> + </Table.Row> + </Table.Header> + <Table.Body> + {sortedFiles.map((f) => ( + <FileRow + key={f.name} + {...f} + /> + ))} + </Table.Body> + </Table> + </Switch> + </> + ); +}; + +export default Explorer; 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..c572b2f9 --- /dev/null +++ b/src/web/src/components/System/Logs/Live.jsx @@ -0,0 +1,68 @@ +import '../System.css'; +import { createLogsHubConnection } from '../../../lib/hubFactory'; +import { LoaderSegment } from '../../Shared'; +import LogTable from './LogTable'; +import { Component } from 'react'; + +const initialState = { + connected: false, + logs: [], +}; + +const maxLogs = 500; + +class Live extends Component { + constructor(props) { + super(props); + + this.state = initialState; + } + + componentDidMount() { + const logsHub = createLogsHubConnection(); + this.logsHub = logsHub; + + logsHub.on('buffer', (buffer) => { + this.setState({ + connected: true, + logs: buffer.reverse().slice(0, maxLogs).map(this.withId), + }); + }); + + logsHub.on('log', (log) => { + const record = this.withId(log); + + this.setState((previousState) => ({ + connected: true, + logs: [record].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(); + } + + componentWillUnmount() { + this.logsHub?.stop(); + } + + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); + + render() { + const { connected, logs } = this.state; + + return ( + <div className="logs"> + {!connected && <LoaderSegment />} + {connected && <LogTable logs={logs} />} + </div> + ); + } +} + +export default Live; diff --git a/src/web/src/components/System/Logs/LogTable.jsx b/src/web/src/components/System/Logs/LogTable.jsx new file mode 100644 index 00000000..68bf6244 --- /dev/null +++ b/src/web/src/components/System/Logs/LogTable.jsx @@ -0,0 +1,64 @@ +import '../System.css'; +import { Table } from 'semantic-ui-react'; + +const abbreviations = { + Debug: 'DBG', + Error: 'ERR', + Fatal: 'FTL', + Information: 'INF', + Verbose: 'VRB', + Warning: 'WRN', +}; + +export const 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 +}; + +const LogTable = ({ emptyMessage = 'No logs', logs }) => ( + <Table + className="logs-table" + compact="very" + > + <Table.Header> + <Table.Row> + <Table.HeaderCell>Timestamp</Table.HeaderCell> + <Table.HeaderCell>Level</Table.HeaderCell> + <Table.HeaderCell>Message</Table.HeaderCell> + </Table.Row> + </Table.Header> + <Table.Body className="logs-table-body"> + {logs?.length === 0 ? ( + <Table.Row> + <Table.Cell + colSpan={99} + style={{ + opacity: 0.5, + padding: '10px !important', + textAlign: 'center', + }} + > + {emptyMessage} + </Table.Cell> + </Table.Row> + ) : ( + logs.map((log) => ( + <Table.Row + disabled={log.level === 'Debug' || log.level === 'Verbose'} + key={log.id} + negative={log.level === 'Error' || log.level === 'Fatal'} + warning={log.level === 'Warning'} + > + <Table.Cell>{formatTimestamp(log.timestamp)}</Table.Cell> + <Table.Cell>{abbreviations[log.level] || log.level}</Table.Cell> + <Table.Cell className="logs-table-message"> + {log.message} + </Table.Cell> + </Table.Row> + )) + )} + </Table.Body> + </Table> +); + +export default LogTable; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx index f36258ec..f0fa4a58 100644 --- a/src/web/src/components/System/Logs/index.jsx +++ b/src/web/src/components/System/Logs/index.jsx @@ -1,98 +1,35 @@ -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', +import Explorer from './Explorer'; +import Live from './Live'; +import React from 'react'; +import { Tab } from 'semantic-ui-react'; + +const Logs = () => { + const panes = [ + { + menuItem: 'Live', + render: () => ( + <Tab.Pane> + <Live /> + </Tab.Pane> + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + <Tab.Pane> + <Explorer /> + </Tab.Pane> + ), + route: 'history', + }, + ]; + + return ( + <div> + <Tab panes={panes} /> + </div> + ); }; -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 ( - <div className="logs"> - {!connected && <LoaderSegment />} - {connected && ( - <Table - className="logs-table" - compact="very" - > - <Table.Header> - <Table.Row> - <Table.HeaderCell>Timestamp</Table.HeaderCell> - <Table.HeaderCell>Level</Table.HeaderCell> - <Table.HeaderCell>Message</Table.HeaderCell> - </Table.Row> - </Table.Header> - <Table.Body className="logs-table-body"> - {logs.map((log) => ( - <Table.Row - disabled={log.level === 'Debug'} - key={log.timestamp} - negative={log.level === 'Error'} - warning={log.level === 'Warning'} - > - <Table.Cell>{this.formatTimestamp(log.timestamp)}</Table.Cell> - <Table.Cell>{levels[log.level] || log.level}</Table.Cell> - <Table.Cell className="logs-table-message"> - {log.message} - </Table.Cell> - </Table.Row> - ))} - </Table.Body> - </Table> - )} - </div> - ); - } -} - export default Logs; diff --git a/src/web/src/components/System/Options/EditModal.jsx b/src/web/src/components/System/Options/EditModal.jsx index 6fc2af69..0727b83e 100644 --- a/src/web/src/components/System/Options/EditModal.jsx +++ b/src/web/src/components/System/Options/EditModal.jsx @@ -43,6 +43,7 @@ const EditModal = ({ onClose, open, theme }) => { const validate = async (newYaml) => { const response = await validateYaml({ yaml: newYaml }); setYamlError(response); + return response; }; const update = async (newYaml) => { @@ -51,14 +52,16 @@ const EditModal = ({ onClose, open, theme }) => { }; const save = async (newYaml) => { - await validate(newYaml); + const validationError = await validate(newYaml); - if (!yamlError) { + if (!validationError) { try { await updateYaml({ yaml: newYaml }); onClose(); } catch (nextUpdateError) { - setUpdateError(nextUpdateError.response.data); + setUpdateError( + nextUpdateError?.response?.data ?? nextUpdateError?.message, + ); } } }; diff --git a/src/web/src/components/System/Shares/ContentsModal.jsx b/src/web/src/components/System/Shares/ContentsModal.jsx index 5399bcf2..36d1d79d 100644 --- a/src/web/src/components/System/Shares/ContentsModal.jsx +++ b/src/web/src/components/System/Shares/ContentsModal.jsx @@ -13,7 +13,16 @@ const ContentsModal = ({ onClose, share, theme }) => { const fetch = async () => { setLoading(true); - const result = await browse({ id }); + let result; + + try { + result = await browse({ id }); + } catch (error) { + console.error(error); + setContents(error?.response?.data ?? error?.message ?? String(error)); + setLoading(false); + return; + } const directories = result.map((directory) => { const lines = [directory.name.replace(remotePath, localPath)]; diff --git a/src/web/src/components/Transfers/TransferGroup.jsx b/src/web/src/components/Transfers/TransferGroup.jsx index bdab5504..f150459a 100644 --- a/src/web/src/components/Transfers/TransferGroup.jsx +++ b/src/web/src/components/Transfers/TransferGroup.jsx @@ -42,7 +42,7 @@ class TransferGroup extends Component { .map((s) => user.directories .find((d) => d.directory === s.directory) - .files.find((f) => f.filename === s.filename), + ?.files?.find((f) => f.filename === s.filename), ) .filter((s) => s !== undefined); }; @@ -65,21 +65,29 @@ class TransferGroup extends Component { }; cancelAll = async (direction, username, selected) => { - await Promise.all( - selected.map((file) => - transfers.cancel({ direction, id: file.id, username }), - ), - ); + try { + await Promise.all( + selected.map((file) => + transfers.cancel({ direction, id: file.id, username }), + ), + ); + } catch (error) { + console.error(error); + } }; removeAll = async (direction, username, selected) => { - await Promise.all( - selected.map((file) => - transfers - .cancel({ direction, id: file.id, remove: true, username }) - .then(() => this.removeFileSelection(file)), - ), - ); + try { + await Promise.all( + selected.map((file) => + transfers + .cancel({ direction, id: file.id, remove: true, username }) + .then(() => this.removeFileSelection(file)), + ), + ); + } catch (error) { + console.error(error); + } }; handleRetry = async (file) => { @@ -114,8 +122,9 @@ class TransferGroup extends Component { const all = selected.length > 1 ? ' Selected' : ''; const allRetryable = + direction === 'download' && selected.filter((f) => transfers.isStateRetryable(f.state)).length === - selected.length; + selected.length; const anyCancellable = selected.some((f) => transfers.isStateCancellable(f.state), ); diff --git a/src/web/src/components/Transfers/Transfers.jsx b/src/web/src/components/Transfers/Transfers.jsx index f43ed1ae..025de9e2 100644 --- a/src/web/src/components/Transfers/Transfers.jsx +++ b/src/web/src/components/Transfers/Transfers.jsx @@ -17,7 +17,7 @@ const Transfers = ({ direction, server }) => { const fetch = async () => { try { const response = await transfersLibrary.getAll({ direction }); - setTransfers(response); + setTransfers(response ?? []); } catch (error) { console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); diff --git a/src/web/src/components/Users/User.jsx b/src/web/src/components/Users/User.jsx index 0e392122..457c095b 100644 --- a/src/web/src/components/Users/User.jsx +++ b/src/web/src/components/Users/User.jsx @@ -33,6 +33,7 @@ const FreeUploadSlot = ({ hasFreeUploadSlot }) => ( const User = ({ address, description, + hasFreeUploadSlot, hasPicture, picture, port, @@ -57,7 +58,8 @@ const User = ({ {username} </Item.Header> <Item.Meta> - Free Upload Slot: <FreeUploadSlot hasFreeUploadSlot />, Total Upload + Free Upload Slot:{' '} + <FreeUploadSlot hasFreeUploadSlot={hasFreeUploadSlot} />, Total Upload Slots: {uploadSlots}, Queue Length: {queueLength}, IP Address: {address} , Port: {port} </Item.Meta> diff --git a/src/web/src/components/Users/Users.jsx b/src/web/src/components/Users/Users.jsx index 55dc1047..fd9c3c6c 100644 --- a/src/web/src/components/Users/Users.jsx +++ b/src/web/src/components/Users/Users.jsx @@ -3,7 +3,7 @@ import { activeUserInfoKey } from '../../config'; import * as users from '../../lib/users'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; import User from './User'; -import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { Icon, Input, Item, Loader, Segment } from 'semantic-ui-react'; @@ -37,20 +37,20 @@ const Users = () => { const keyUp = (event) => (event.key === 'Escape' ? clear() : ''); - useLayoutEffect(() => { - document.removeEventListener('keyup', keyUp, false); - }, []); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { document.addEventListener('keyup', keyUp, false); const storedUsername = location.state?.user || localStorage.getItem(activeUserInfoKey); - if (storedUsername !== undefined) { + if (storedUsername) { setSelectedUsername(storedUsername); setInputText(storedUsername); } + + return () => { + document.removeEventListener('keyup', keyUp, false); + }; }, []); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js index 9506a0da..74602d63 100644 --- a/src/web/src/lib/api.js +++ b/src/web/src/lib/api.js @@ -26,7 +26,7 @@ api.interceptors.response.use( }, (error) => { if ( - error.response.status === 401 && + error.response?.status === 401 && !['/session', '/server', '/application'].includes( error.response.config.url, ) diff --git a/src/web/src/lib/files.js b/src/web/src/lib/files.js index 99a82b2c..cbd0bd3c 100644 --- a/src/web/src/lib/files.js +++ b/src/web/src/lib/files.js @@ -1,21 +1,30 @@ import api from './api'; +// paths may contain any unicode character, so they are encoded as UTF-8 before base64 (btoa only accepts Latin-1), +// and the result is URL-encoded because base64 may contain '/', which would otherwise split the route + export const list = async ({ root, subdirectory = '' }) => { const response = ( - await api.get(`/files/${root}/directories/${btoa(subdirectory)}`) + await api.get( + `/files/${root}/directories/${encodeURIComponent(btoa(String.fromCodePoint(...new TextEncoder().encode(subdirectory))))}`, + ) ).data; return response; }; export const deleteDirectory = async ({ root, path }) => { - const response = await api.delete(`/files/${root}/directories/${btoa(path)}`); + const response = await api.delete( + `/files/${root}/directories/${encodeURIComponent(btoa(String.fromCodePoint(...new TextEncoder().encode(path))))}`, + ); return response; }; export const deleteFile = async ({ root, path }) => { - const response = await api.delete(`/files/${root}/files/${btoa(path)}`); + const response = await api.delete( + `/files/${root}/files/${encodeURIComponent(btoa(String.fromCodePoint(...new TextEncoder().encode(path))))}`, + ); return response; }; diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js new file mode 100644 index 00000000..35ae5d84 --- /dev/null +++ b/src/web/src/lib/logs.js @@ -0,0 +1,27 @@ +import api from './api'; + +export const list = async () => { + const response = (await api.get('/logs/files')).data; + + return response; +}; + +export const getFileText = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + responseType: 'text', + }) + ).data; + + return response; +}; + +export const getFileBlob = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + responseType: 'blob', + }) + ).data; + + return response; +}; diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js index 1c3c55c5..891d0ee2 100644 --- a/src/web/src/lib/options.js +++ b/src/web/src/lib/options.js @@ -17,9 +17,9 @@ export const getYamlLocation = async () => { }; export const validateYaml = async ({ yaml }) => { - return (await api.post('/options/yaml/validate', yaml)).data; + return (await api.post('/options/yaml/validate', JSON.stringify(yaml))).data; }; export const updateYaml = async ({ yaml }) => { - return (await api.put('/options/yaml', yaml)).data; + return (await api.put('/options/yaml', JSON.stringify(yaml))).data; }; diff --git a/src/web/src/lib/relay.js b/src/web/src/lib/relay.js index 35149f02..956a8073 100644 --- a/src/web/src/lib/relay.js +++ b/src/web/src/lib/relay.js @@ -1,9 +1,9 @@ import api from './api'; export const connect = () => { - return api.put('/relay'); + return api.put('/relay/agent'); }; export const disconnect = () => { - return api.delete('/relay'); + return api.delete('/relay/agent'); }; diff --git a/src/web/src/lib/rooms.js b/src/web/src/lib/rooms.js index 35da6701..3c6c22cb 100644 --- a/src/web/src/lib/rooms.js +++ b/src/web/src/lib/rooms.js @@ -49,7 +49,7 @@ export const getUsers = async ({ roomName }) => { }; export const join = async ({ roomName }) => { - return api.post('/rooms/joined', roomName); + return api.post('/rooms/joined', JSON.stringify(roomName)); }; export const leave = async ({ roomName }) => { diff --git a/src/web/src/lib/session.js b/src/web/src/lib/session.js index 014b131c..cf6966c6 100644 --- a/src/web/src/lib/session.js +++ b/src/web/src/lib/session.js @@ -36,7 +36,7 @@ export const check = async () => { await api.get('/session'); return true; } catch (error) { - if (error.response.status === 401) { + if (error.response?.status === 401) { console.error('session error; not logged in or session has expired'); logout(); return false; diff --git a/tests/slskd.Tests.Benchmarks/.gitignore b/tests/slskd.Tests.Benchmarks/.gitignore new file mode 100644 index 00000000..3eabeee4 --- /dev/null +++ b/tests/slskd.Tests.Benchmarks/.gitignore @@ -0,0 +1,352 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +wwwroot
\ No newline at end of file diff --git a/tests/slskd.Tests.Benchmarks/HelloWorld.cs b/tests/slskd.Tests.Benchmarks/HelloWorld.cs new file mode 100644 index 00000000..21b93d57 --- /dev/null +++ b/tests/slskd.Tests.Benchmarks/HelloWorld.cs @@ -0,0 +1,29 @@ +namespace slskd.Tests.Benchmarks +{ + using BenchmarkDotNet.Attributes; + using BenchmarkDotNet.Running; + using Xunit; + + public class HelloWorldBenchmarks + { + [Benchmark] + public void LoopOneHundredTimes() + { + for (var i = 0; i < 100; i++) + { + _ = i; + } + } + } + + public class HelloWorld + { + [Fact] + public void RunHelloWorldBenchmark() + { + var summary = BenchmarkRunner.Run<HelloWorldBenchmarks>(); + + Assert.NotNull(summary); + } + } +} diff --git a/tests/slskd.Tests.Benchmarks/slskd.Tests.Benchmarks.csproj b/tests/slskd.Tests.Benchmarks/slskd.Tests.Benchmarks.csproj new file mode 100644 index 00000000..3d022d41 --- /dev/null +++ b/tests/slskd.Tests.Benchmarks/slskd.Tests.Benchmarks.csproj @@ -0,0 +1,35 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <TargetFramework>net10.0</TargetFramework> + <IsPackable>false</IsPackable> + </PropertyGroup> + + <Target Name="EnforceMoqVersion" BeforeTargets="ResolvePackageAssets"> + <ItemGroup> + <_MoqRef Include="@(PackageReference)" Condition="'%(Identity)' == 'Moq'" /> + </ItemGroup> + <Error Condition="'%(_MoqRef.Version)' != '4.16.1'" Text="Moq is locked to 4.16.1 and must not be upgraded. See https://github.com/moq/moq/issues/1372 for context." /> + </Target> + + <ItemGroup> + <PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" /> + <PackageReference Include="BenchmarkDotNet" Version="0.15.8" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" /> + <PackageReference Include="Moq" Version="4.16.1" /> + <PackageReference Include="xunit" Version="2.9.3" /> + <PackageReference Include="xunit.runner.visualstudio" Version="4.0.1"> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="coverlet.msbuild" Version="10.1.0"> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\..\src\slskd\slskd.csproj" /> + </ItemGroup> + +</Project> diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs new file mode 100644 index 00000000..f035f703 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsRootDirectoryOfTests.cs @@ -0,0 +1,245 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class IsRootDirectoryOfTests + { + [Fact] + public void Root_Null_Throws_ArgumentNullException() + { + string root = null; + + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo")); + + Assert.NotNull(ex); + Assert.IsType<ArgumentNullException>(ex); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Root_Empty_Or_Whitespace_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo")); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + public class Windows + { + [Theory] + [InlineData("foo")] + [InlineData("foo\\bar")] + [InlineData("foo/bar")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + [InlineData("C:\\..")] + [InlineData("\\\\foo\\..")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo\\bar")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foo")] + [InlineData("C:\\FOO", "C:\\foo")] + [InlineData("C:\\foo", "C:\\FOO")] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar")] + [InlineData("\\\\FOO\\bar", "\\\\foo\\BAR")] + public void Equal_Paths_Are_A_Case_Insensitive_Match(string root, string subdirectory) + { + Assert.True(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + // the character joining root and subdirectory is always the runtime OS separator + // (Path.DirectorySeparatorChar) regardless of the `os` override passed to force + // Windows-style absolute-path and case-sensitivity rules, so the expected result + // is computed from the actual runtime separator rather than hardcoded - this keeps + // the case correct on whichever OS the suite runs on, while still exercising both + // slash styles, mixed styles, drive letters, and UNC-style roots via inline data. + [Theory] + [InlineData("C:\\foo", "C:\\foo\\bar", '\\')] + [InlineData("C:\\foo", "C:\\foo/bar", '/')] + [InlineData("C:/foo", "C:/foo/bar", '/')] + [InlineData("C:/foo", "C:/foo\\bar", '\\')] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar\\baz", '\\')] + [InlineData("\\\\foo\\bar", "\\\\foo\\bar/baz", '/')] + [InlineData("C:\\foo\\", "C:\\foo\\bar", '\\')] + [InlineData("C:\\foo/", "C:\\foo\\bar", '\\')] + public void Subdirectory_Match_Depends_On_Native_Separator_At_The_Boundary(string root, string subdirectory, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foobar")] + [InlineData("C:\\foo\\bar", "C:\\foo")] + [InlineData("C:\\foo", "C:\\bar")] + [InlineData("C:\\foo\\bar", "C:\\foo\\baz")] + [InlineData("C:\\foo", "D:\\foo\\bar")] + [InlineData("\\\\foo\\bar", "\\\\foo\\barbaz")] + public void Non_Subdirectory_Returns_False(string root, string subdirectory) + { + Assert.False(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Windows)); + } + + [Fact] + public void StartsWith_Check_Is_Case_Insensitive() + { + var subdirectory = "C:\\FOO" + Path.DirectorySeparatorChar + "bar"; + + Assert.True(FileSafety.IsRootDirectoryOf("C:\\foo", subdirectory, OperatingSystem.Windows)); + } + } + + public class Linux + { + [Theory] + [InlineData("foo")] + [InlineData("foo/bar")] + [InlineData("foo\\bar")] + [InlineData("C:\\foo")] + [InlineData("\\\\foo\\bar")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("/foo/..")] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + [InlineData("/..")] + [InlineData("//foo/..")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf(root, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo/bar")] + [InlineData("C:\\foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("/foo/..")] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("/foo", "/foo")] + [InlineData("//foo/bar", "//foo/bar")] + public void Equal_Paths_Match(string root, string subdirectory) + { + Assert.True(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Fact] + public void Equal_Paths_Different_Case_Do_Not_Match() + { + Assert.False(FileSafety.IsRootDirectoryOf("/FOO", "/foo", OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo", "/foo/bar", '/')] + [InlineData("/foo", "/foo\\bar", '\\')] + [InlineData("//foo/bar", "//foo/bar/baz", '/')] + [InlineData("//foo/bar", "//foo/bar\\baz", '\\')] + [InlineData("/foo/", "/foo/bar", '/')] + [InlineData("/foo\\", "/foo/bar", '/')] + public void Subdirectory_Match_Depends_On_Native_Separator_At_The_Boundary(string root, string subdirectory, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo", "/foobar")] + [InlineData("/foo/bar", "/foo")] + [InlineData("/foo", "/bar")] + [InlineData("/foo/bar", "/foo/baz")] + public void Non_Subdirectory_Returns_False(string root, string subdirectory) + { + Assert.False(FileSafety.IsRootDirectoryOf(root, subdirectory, OperatingSystem.Linux)); + } + + [Fact] + public void StartsWith_Check_Is_Case_Sensitive() + { + var subdirectory = "/FOO" + Path.DirectorySeparatorChar + "bar"; + + Assert.False(FileSafety.IsRootDirectoryOf("/foo", subdirectory, OperatingSystem.Linux)); + } + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs new file mode 100644 index 00000000..2f5fe8ee --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsSubDirectoryOfTests.cs @@ -0,0 +1,215 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class IsSubDirectoryOfTests + { + // IsSubDirectoryOf(subdirectory, root) forwards to IsRootDirectoryOf(root, subdirectory), + // so `root` (the second parameter here) lands on IsRootDirectoryOf's first parameter and + // is the one validated with ArgumentNullException.ThrowIfNullOrWhiteSpace. + [Fact] + public void Root_Null_Throws_ArgumentNullException() + { + string root = null; + + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo", root)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentNullException>(ex); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void Root_Empty_Or_Whitespace_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo", root)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + // subdirectory (the first parameter here) is never null-checked directly; it only fails + // the "must be absolute" check, so null/empty/whitespace all throw plain ArgumentException. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void Subdirectory_Null_Empty_Or_Whitespace_Throws_ArgumentException_Not_ArgumentNullException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + public class Windows + { + [Theory] + [InlineData("foo")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo\\bar", root, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("\\foo")] + [InlineData("C:")] + [InlineData("C:foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo\\..")] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("C:\\foo\\bar", root, OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo\\..\\bar")] + [InlineData("C:\\foo\\.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "C:\\foo", OperatingSystem.Windows)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("C:\\foo", "C:\\foo")] + [InlineData("C:\\FOO", "C:\\foo")] + [InlineData("C:\\foo", "C:\\FOO")] + public void Equal_Paths_Are_A_Case_Insensitive_Match(string subdirectory, string root) + { + Assert.True(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foo\\bar", "C:\\foo", '\\')] + [InlineData("C:\\foo/bar", "C:\\foo", '/')] + [InlineData("\\\\foo\\bar\\baz", "\\\\foo\\bar", '\\')] + [InlineData("\\\\foo\\bar/baz", "\\\\foo\\bar", '/')] + [InlineData("C:\\foo\\bar", "C:\\foo\\", '\\')] + public void Match_Depends_On_Native_Separator_At_The_Boundary(string subdirectory, string root, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + + [Theory] + [InlineData("C:\\foobar", "C:\\foo")] + [InlineData("C:\\foo", "C:\\foo\\bar")] + [InlineData("C:\\bar", "C:\\foo")] + [InlineData("C:\\foo\\baz", "C:\\foo\\bar")] + public void Not_A_Child_Of_Root_Returns_False(string subdirectory, string root) + { + Assert.False(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Windows)); + } + } + + public class Linux + { + [Theory] + [InlineData("foo")] + [InlineData("C:\\foo")] + public void Relative_Root_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("/foo/bar", root, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("foo")] + [InlineData("C:\\foo")] + public void Relative_Subdirectory_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Root_With_Traversal_Segments_Throws_ArgumentException(string root) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf("/foo/bar", root, OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Theory] + [InlineData("/foo/../bar")] + [InlineData("/foo/.")] + public void Subdirectory_With_Traversal_Segments_Throws_ArgumentException(string subdirectory) + { + var ex = Record.Exception(() => FileSafety.IsSubDirectoryOf(subdirectory, "/foo", OperatingSystem.Linux)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); + } + + [Fact] + public void Equal_Paths_Match() + { + Assert.True(FileSafety.IsSubDirectoryOf("/foo", "/foo", OperatingSystem.Linux)); + } + + [Fact] + public void Equal_Paths_Different_Case_Do_Not_Match() + { + Assert.False(FileSafety.IsSubDirectoryOf("/FOO", "/foo", OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foo/bar", "/foo", '/')] + [InlineData("/foo\\bar", "/foo", '\\')] + [InlineData("//foo/bar/baz", "//foo/bar", '/')] + [InlineData("//foo/bar\\baz", "//foo/bar", '\\')] + public void Match_Depends_On_Native_Separator_At_The_Boundary(string subdirectory, string root, char boundarySeparator) + { + var expected = boundarySeparator == Path.DirectorySeparatorChar; + + Assert.Equal(expected, FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Linux)); + } + + [Theory] + [InlineData("/foobar", "/foo")] + [InlineData("/foo", "/foo/bar")] + [InlineData("/bar", "/foo")] + [InlineData("/foo/baz", "/foo/bar")] + public void Not_A_Child_Of_Root_Returns_False(string subdirectory, string root) + { + Assert.False(FileSafety.IsSubDirectoryOf(subdirectory, root, OperatingSystem.Linux)); + } + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs b/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs new file mode 100644 index 00000000..640bca0e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Middleware/HTMLInjectionMiddlewareTests.cs @@ -0,0 +1,204 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace slskd.Tests.Unit.Common.Middleware; + +public class HTMLInjectionMiddlewareTests +{ + private const string Html = "<html><body>hello</body></html>"; + private const string Injection = "<script>window.urlBase=\"/slskd\"</script>"; + private static readonly string[] ExcludedRoutes = ["/api", "/swagger"]; + + [Theory] + [InlineData("text/html")] + [InlineData("TEXT/HTML")] + [InlineData("application/xhtml+xml")] + [InlineData("application/xml")] + [InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")] + [InlineData("application/xml;q=0.9")] + [InlineData("application/json, text/html")] + public async Task InvokeAsync_Injects_When_Accept_Is_Injectable(string accept) + { + var (context, body) = CreateContext(path: "/", accept: accept); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html + Injection, Read(body)); + } + + [Theory] + [InlineData("application/json")] + [InlineData("*/*")] + [InlineData("")] + public async Task InvokeAsync_Does_Not_Inject_When_Accept_Is_Not_Injectable(string accept) + { + var (context, body) = CreateContext(path: "/", accept: accept); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData("text/html")] + [InlineData("text/html; charset=utf-8")] + [InlineData("TEXT/HTML;charset=UTF-8")] + [InlineData("application/xhtml+xml")] + public async Task InvokeAsync_Injects_When_Response_Content_Type_Is_Injectable(string contentType) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, contentType)); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html + Injection, Read(body)); + } + + [Theory] + [InlineData("application/json")] + [InlineData("text/plain; charset=utf-8")] + [InlineData(null)] + public async Task InvokeAsync_Does_Not_Inject_When_Response_Content_Type_Is_Not_Injectable(string contentType) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond("{\"foo\":\"bar\"}", contentType)); + + await middleware.InvokeAsync(context); + + Assert.Equal("{\"foo\":\"bar\"}", Read(body)); + } + + [Theory] + [InlineData("/api")] + [InlineData("/api/v0/application")] + [InlineData("/swagger")] + [InlineData("/swagger/index.html")] + public async Task InvokeAsync_Does_Not_Inject_Excluded_Routes(string path) + { + var (context, body) = CreateContext(path: path, accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData("/")] + [InlineData("/searches")] + [InlineData("/system/info")] + public async Task InvokeAsync_Injects_Non_Excluded_Routes(string path) + { + var (context, body) = CreateContext(path: path, accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html + Injection, Read(body)); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("HEAD")] + public async Task InvokeAsync_Does_Not_Inject_Non_GET_Requests(string method) + { + var (context, body) = CreateContext(path: "/", accept: "text/html", method: method); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData(404)] + [InlineData(500)] + public async Task InvokeAsync_Does_Not_Inject_Non_200_Responses(int statusCode) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html", statusCode)); + + await middleware.InvokeAsync(context); + + Assert.Equal(statusCode, context.Response.StatusCode); + Assert.Equal(Html, Read(body)); + } + + [Fact] + public async Task InvokeAsync_Removes_Content_Length_And_Retains_Other_Headers() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(async ctx => + { + ctx.Response.Headers["X-Test"] = "value"; + ctx.Response.ContentLength = Html.Length; + await Respond(Html, "text/html")(ctx); + }); + + await middleware.InvokeAsync(context); + + Assert.Null(context.Response.ContentLength); + Assert.Equal("value", context.Response.Headers["X-Test"]); + Assert.Equal("text/html", context.Response.ContentType); + Assert.Equal(Html + Injection, Read(body)); + } + + [Fact] + public async Task InvokeAsync_Restores_Original_Body_Stream_When_Downstream_Throws() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(_ => throw new InvalidOperationException("boom")); + + var ex = await Record.ExceptionAsync(() => middleware.InvokeAsync(context)); + + Assert.IsType<InvalidOperationException>(ex); + Assert.Same(body, context.Response.Body); + } + + [Fact] + public async Task InvokeAsync_Restores_Original_Body_Stream_When_Successful() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Same(body, context.Response.Body); + } + + private static HTMLInjectionMiddleware CreateMiddleware(RequestDelegate next) + => new(next, Injection, ExcludedRoutes); + + private static RequestDelegate Respond(string content, string contentType, int statusCode = 200) + => async ctx => + { + ctx.Response.StatusCode = statusCode; + ctx.Response.ContentType = contentType; + await ctx.Response.WriteAsync(content); + }; + + private static (HttpContext Context, MemoryStream Body) CreateContext(string path, string accept, string method = "GET") + { + var body = new MemoryStream(); + var context = new DefaultHttpContext(); + + context.Request.Method = method; + context.Request.Path = path; + context.Request.Headers.Accept = accept; + context.Response.Body = body; + + return (context, body); + } + + private static string Read(MemoryStream stream) + { + stream.Seek(0, SeekOrigin.Begin); + return new StreamReader(stream).ReadToEnd(); + } +} diff --git a/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs b/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs new file mode 100644 index 00000000..203b9e0e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Middleware/HTMLRewriteMiddlewareTests.cs @@ -0,0 +1,190 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace slskd.Tests.Unit.Common.Middleware; + +public class HTMLRewriteMiddlewareTests +{ + // the same patterns and replacements used in Program.cs, with a url base of /slskd + private const string StaticPattern = "((\\.)?\\/static)"; + private const string StaticReplacement = "/slskd/static"; + private const string Html = "<html><script src=\"./static/js/main.js\"></script><link href=\"/static/css/main.css\"></html>"; + private const string RewrittenHtml = "<html><script src=\"/slskd/static/js/main.js\"></script><link href=\"/slskd/static/css/main.css\"></html>"; + + [Theory] + [InlineData("text/html")] + [InlineData("TEXT/HTML")] + [InlineData("application/xhtml+xml")] + [InlineData("application/xml")] + [InlineData("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")] + [InlineData("application/xml;q=0.9")] + [InlineData("application/json, text/html")] + public async Task InvokeAsync_Rewrites_When_Accept_Is_Rewriteable(string accept) + { + var (context, body) = CreateContext(path: "/", accept: accept); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(RewrittenHtml, Read(body)); + } + + [Theory] + [InlineData("application/json")] + [InlineData("*/*")] + [InlineData("")] + public async Task InvokeAsync_Does_Not_Rewrite_When_Accept_Is_Not_Rewriteable(string accept) + { + var (context, body) = CreateContext(path: "/", accept: accept); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData("text/html")] + [InlineData("text/html; charset=utf-8")] + [InlineData("TEXT/HTML;charset=UTF-8")] + [InlineData("application/xhtml+xml")] + public async Task InvokeAsync_Rewrites_When_Response_Content_Type_Is_Rewriteable(string contentType) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, contentType)); + + await middleware.InvokeAsync(context); + + Assert.Equal(RewrittenHtml, Read(body)); + } + + [Theory] + [InlineData("application/javascript")] + [InlineData("text/css; charset=utf-8")] + [InlineData(null)] + public async Task InvokeAsync_Does_Not_Rewrite_When_Response_Content_Type_Is_Not_Rewriteable(string contentType) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, contentType)); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData("/api")] + [InlineData("/api/v0/application")] + public async Task InvokeAsync_Does_Not_Rewrite_API_Routes(string path) + { + var (context, body) = CreateContext(path: path, accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("HEAD")] + public async Task InvokeAsync_Does_Not_Rewrite_Non_GET_Requests(string method) + { + var (context, body) = CreateContext(path: "/", accept: "text/html", method: method); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Equal(Html, Read(body)); + } + + [Theory] + [InlineData(404)] + [InlineData(500)] + public async Task InvokeAsync_Does_Not_Rewrite_Non_200_Responses(int statusCode) + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html", statusCode)); + + await middleware.InvokeAsync(context); + + Assert.Equal(statusCode, context.Response.StatusCode); + Assert.Equal(Html, Read(body)); + } + + [Fact] + public async Task InvokeAsync_Removes_Content_Length_And_Retains_Other_Headers() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(async ctx => + { + ctx.Response.Headers["X-Test"] = "value"; + ctx.Response.ContentLength = Html.Length; + await Respond(Html, "text/html")(ctx); + }); + + await middleware.InvokeAsync(context); + + Assert.Null(context.Response.ContentLength); + Assert.Equal("value", context.Response.Headers["X-Test"]); + Assert.Equal("text/html", context.Response.ContentType); + Assert.Equal(RewrittenHtml, Read(body)); + } + + [Fact] + public async Task InvokeAsync_Restores_Original_Body_Stream_When_Downstream_Throws() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(_ => throw new InvalidOperationException("boom")); + + var ex = await Record.ExceptionAsync(() => middleware.InvokeAsync(context)); + + Assert.IsType<InvalidOperationException>(ex); + Assert.Same(body, context.Response.Body); + } + + [Fact] + public async Task InvokeAsync_Restores_Original_Body_Stream_When_Successful() + { + var (context, body) = CreateContext(path: "/", accept: "text/html"); + var middleware = CreateMiddleware(Respond(Html, "text/html")); + + await middleware.InvokeAsync(context); + + Assert.Same(body, context.Response.Body); + } + + private static HTMLRewriteMiddleware CreateMiddleware(RequestDelegate next) + => new(next, StaticPattern, StaticReplacement); + + private static RequestDelegate Respond(string content, string contentType, int statusCode = 200) + => async ctx => + { + ctx.Response.StatusCode = statusCode; + ctx.Response.ContentType = contentType; + await ctx.Response.WriteAsync(content); + }; + + private static (HttpContext Context, MemoryStream Body) CreateContext(string path, string accept, string method = "GET") + { + var body = new MemoryStream(); + var context = new DefaultHttpContext(); + + context.Request.Method = method; + context.Request.Path = path; + context.Request.Headers.Accept = accept; + context.Response.Body = body; + + return (context, body); + } + + private static string Read(MemoryStream stream) + { + stream.Seek(0, SeekOrigin.Begin); + return new StreamReader(stream).ReadToEnd(); + } +} diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index d6c30316..05f967da 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -34,7 +34,7 @@ namespace slskd.Tests.Unit.Files [Fact] public async Task ListContentsAsync_Throws_ArgumentException_Given_Relative_Path() { - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: "../")); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: "../")); Assert.NotNull(ex); Assert.IsType<ArgumentException>(ex); @@ -53,7 +53,7 @@ namespace slskd.Tests.Unit.Files } }); - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "foo"))); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "foo"))); Assert.NotNull(ex); Assert.IsType<UnauthorizedException>(ex); @@ -71,7 +71,7 @@ namespace slskd.Tests.Unit.Files } }); - var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "downloads", "foo"))); + var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "downloads", "foo"))); Assert.NotNull(ex); Assert.IsType<NotFoundException>(ex); diff --git a/tests/slskd.Tests.Unit/Shares/SqliteShareRepositoryTests.cs b/tests/slskd.Tests.Unit/Shares/SqliteShareRepositoryTests.cs new file mode 100644 index 00000000..2624582c --- /dev/null +++ b/tests/slskd.Tests.Unit/Shares/SqliteShareRepositoryTests.cs @@ -0,0 +1,368 @@ +namespace slskd.Tests.Unit.Shares +{ + using System; + using System.Collections.Generic; + using System.Linq; + using slskd.Shares; + using Soulseek; + using Xunit; + + public class SqliteShareRepositoryTests + { + public class Search + { + [Fact] + public void Returns_Only_Files_Matching_All_Terms() + { + var (a, b, c, d, e) = (Random(), Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}.dat", + $@"@@share\{a}\{c}\{b}.dat", + $@"@@share\{c}\{b} {a}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{a}\{c}.dat", + $@"@@share\{d}\{b}.dat", + $@"@@share\{a}{b}.dat", + $@"@@share\{c}\{a}{e}\{b}{e}.dat", + $@"@@share\{e}\{d}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [a, b], exclusions: [])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Fact] + public void Returns_Nothing_When_No_File_Matches_All_Terms() + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + + using var repository = GetRepository( + [ + $@"@@share\{a}\{c}.dat", + $@"@@share\{a}\{d}.dat", + $@"@@share\{b}\{c}.dat", + $@"@@share\{b}\{d}.dat", + $@"@@share\{a}{b}.dat", + $@"@@share\{c}\{d}.dat", + ]); + + // make sure the files are searchable, so an empty result below means something + Assert.Equal(2, repository.Search(new SearchQuery(terms: [a], exclusions: [])).Count()); + + var results = repository.Search(new SearchQuery(terms: [a, b], exclusions: [])); + + Assert.Empty(results); + } + + [Fact] + public void Excludes_Files_Matching_Exclusion() + { + var (a, b, c, x, y) = (Random(), Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}.dat", + $@"@@share\{a}\{c}.dat", + $@"@@share\{a}\{b}\{c}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{a}\{x}.dat", + $@"@@share\{a}\{x}\{b}.dat", + $@"@@share\{a}\{c}{x}.dat", + $@"@@share\{y}\{b}.dat", + $@"@@share\{y}\{x}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [a], exclusions: [x])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Fact] + public void Excludes_Files_Matching_Any_Of_Several_Exclusions() + { + var (a, b, c, x, y, z) = (Random(), Random(), Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}.dat", + $@"@@share\{a}\{c}.dat", + $@"@@share\{a}\{b}\{c}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{a}\{x}.dat", + $@"@@share\{a}\{y}.dat", + $@"@@share\{a}\{x}\{y}.dat", + $@"@@share\{a}\{b}{y}.dat", + $@"@@share\{a}\{z}\{x}.dat", + $@"@@share\{z}\{b}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [a], exclusions: [x, y])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Fact] + public void Matches_Term_Containing_Single_Quote() + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}'{c}.dat", + $@"@@share\{d}\{b}'{c} {a}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{a}\{b}.dat", + $@"@@share\{a}\{c}.dat", + $@"@@share\{a}\{c}'{b}.dat", + $@"@@share\{a}\{b}\{d}\{c}.dat", + $@"@@share\{d}\{a}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [$"{b}'{c}"], exclusions: [])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Fact] + public void Excludes_Files_Matching_Exclusion_Containing_Single_Quote() + { + var (a, b, c, d, e) = (Random(), Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}.dat", + $@"@@share\{a}\{c}.dat", + $@"@@share\{a}\{c}'{b}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{a}\{b}'{c}.dat", + $@"@@share\{a}\{d}\{b}'{c}.dat", + $@"@@share\{a}\{d}{b}'{c}{e}.dat", + $@"@@share\{e}\{b}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [a], exclusions: [$"{b}'{c}"])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Theory] + [InlineData("\"{0} {1}\"")] + [InlineData("{0}\"{1}")] + [InlineData("\"{0}\"{1}\"")] + [InlineData("{0} \"{1}")] + public void Matches_Term_Containing_Double_Quotes(string template) + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + var term = string.Format(template, a, b); + + // a double quote in a term must be treated as a separator. if it were left in place it would end the + // phrase early, either breaking the query or splitting the term into separate words that match the + // decoys below. if it were removed instead, '{0}"{1}' would become a single word and match nothing + string[] expected = + [ + $@"@@share\{c}\{a}\{b}.dat", + $@"@@share\{a} {b}\{d}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{b}\{a}.dat", + $@"@@share\{a}\{c}\{b}.dat", + $@"@@share\{a}{b}.dat", + $@"@@share\{a}\{d}.dat", + $@"@@share\{c}\{b}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [term], exclusions: [])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Theory] + [InlineData("\\")] + [InlineData("/")] + [InlineData(":")] + public void Matches_Term_Containing_Separator(string separator) + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{a}\{b}.dat", + $@"@@share\{c}\{a}\{b}\{d}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{b}\{a}.dat", + $@"@@share\{a}\{c}\{b}.dat", + $@"@@share\{a}\{d}.dat", + $@"@@share\{c}\{b}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [$"{a}{separator}{b}"], exclusions: [])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Theory] + [InlineData("{0}') OR 1=1 --{1}")] + [InlineData("{0}' UNION SELECT maskedFilename, code, size, extension, attributeJson FROM files --{1}")] + [InlineData("{0}\" OR \"{1}")] + [InlineData("{0} OR {1}")] + [InlineData("{0} AND {1}")] + [InlineData("{0} NOT {1}")] + [InlineData("NEAR({0} {1})")] + [InlineData("maskedFilename:{0} {1}")] + public void Treats_Query_Syntax_In_Term_As_Text(string template) + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + var term = string.Format(template, a, b); + + // only the file containing the literal term should match. if the term were interpreted as SQL or FTS + // syntax, either the query would fail and nothing would match, or some of the other files would match + string[] expected = + [ + $@"@@share\{c}\{term}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{c}\{a}.dat", + $@"@@share\{c}\{b}.dat", + $@"@@share\{c}\{a} {b}.dat", + $@"@@share\{c}\{b} {a}.dat", + $@"@@share\{c}\{a}\{d}.dat", + $@"@@share\{d}\{c}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [term], exclusions: [])); + + Assert.Equal(expected, results.Select(f => f.Filename)); + } + + [Fact] + public void Does_Not_Treat_Asterisk_As_Prefix_Wildcard() + { + var (a, b, c, d) = (Random(), Random(), Random(), Random()); + + string[] expected = + [ + $@"@@share\{c}\{a}.dat", + $@"@@share\{d}\{a}\{b}.dat", + ]; + + using var repository = GetRepository( + [ + .. expected, + $@"@@share\{c}\{a}{b}.dat", + $@"@@share\{c}\{a}{d}\{b}.dat", + $@"@@share\{c}\{b}.dat", + $@"@@share\{d}\{c}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [$"{a}*"], exclusions: [])); + + Assert.Equal(expected.Order(StringComparer.Ordinal), results.Select(f => f.Filename)); + } + + [Fact] + public void Returns_First_Matches_Up_To_Limit() + { + var (a, b, c) = (Random(), Random(), Random()); + + string[] matching = + [ + $@"@@share\{a}\{Random()}.dat", + $@"@@share\{a}\{Random()}.dat", + $@"@@share\{a}\{Random()}.dat", + $@"@@share\{a}\{Random()}.dat", + $@"@@share\{a}\{Random()}.dat", + ]; + + using var repository = GetRepository( + [ + .. matching, + $@"@@share\{b}\{Random()}.dat", + $@"@@share\{b}\{Random()}.dat", + $@"@@share\{c}\{Random()}.dat", + ]); + + var results = repository.Search(new SearchQuery(terms: [a], exclusions: []), limit: 3); + + Assert.Equal(matching.Order(StringComparer.Ordinal).Take(3), results.Select(f => f.Filename)); + } + + [Fact] + public void Returns_Details_Of_Matching_File() + { + var (a, b, c) = (Random(), Random(), Random()); + var filename = $@"@@share\{a}\{b}.dat"; + + using var repository = GetRepository( + [ + $@"@@share\{a}\{c}.dat", + $@"@@share\{c}\{b}.dat", + $@"@@share\{c}\{a}.dat", + ]); + + var attributes = new List<FileAttribute>() { new(FileAttributeType.BitRate, 320), new(FileAttributeType.Length, 180) }; + repository.InsertFile(filename, originalFilename: filename, touchedAt: DateTime.UtcNow, new File(1, filename, 12345, "dat", attributes), timestamp: 1); + repository.RebuildFilenameIndex(); + + var result = Assert.Single(repository.Search(new SearchQuery(terms: [a, b], exclusions: []))); + + Assert.Equal(filename, result.Filename); + Assert.Equal(1, result.Code); + Assert.Equal(12345, result.Size); + Assert.Equal("dat", result.Extension); + Assert.Equal(320, result.BitRate); + Assert.Equal(180, result.Length); + } + } + + private static string Random() => Guid.NewGuid().ToString("N"); + + private static SqliteShareRepository GetRepository(string[] maskedFilenames) + { + var repository = new SqliteShareRepository($"Data Source=file:shares.test_{Guid.NewGuid():N}?mode=memory;Cache=shared"); + repository.Create(); + + foreach (var maskedFilename in maskedFilenames) + { + var file = new File(1, maskedFilename, 42, "dat", new List<FileAttribute>()); + repository.InsertFile(maskedFilename, originalFilename: maskedFilename, touchedAt: DateTime.UtcNow, file, timestamp: 1); + } + + repository.RebuildFilenameIndex(); + + return repository; + } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/EnqueueAsyncTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/EnqueueAsyncTests.cs new file mode 100644 index 00000000..6c1cb963 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/EnqueueAsyncTests.cs @@ -0,0 +1,1157 @@ +namespace slskd.Tests.Unit.Transfers.Downloads; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Moq; +using slskd.Files; +using slskd.Transfers; +using slskd.Transfers.Downloads; +using Soulseek; +using Xunit; + +public partial class DownloadServiceTests +{ + /* + EnqueueAsync() waits for one of five conditions before releasing the per-file enqueue semaphore: + + 1. the transfer enters the Queued | Remotely state + 2. the transfer enters a state containing Completed + 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled + 4. the 'max wait time' CancellationTokenSource is cancelled + 5. the DownloadAsync() method throws + + the 'max wait time' timer is created through the injected TimeProvider; disposal of that timer is how + these tests observe that the wait ended, and invoking its callback is how they simulate the timeout. + */ + public class EnqueueAsync + { + private const string Username = "alice"; + private const string Filename = "@alice\\Music\\track.flac"; + private const long Size = 12345; + + private static readonly TimeSpan WaitLimit = TimeSpan.FromSeconds(10); + + [Fact] + public async Task Condition_1_Queued_Remotely_Ends_Wait_Without_Failing_Or_Cancelling_Download() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(TransferStates.Queued | TransferStates.Remotely); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = fixture.Service.Find(t => t.Id == transfer.Id); + Assert.Equal(TransferStates.Queued | TransferStates.Remotely, record.State); + Assert.Null(record.Exception); + Assert.False(download.CancellationToken.IsCancellationRequested); + Assert.False(fixture.TimerFired); + } + + [Fact] + public async Task Condition_2_Completed_Succeeded_Ends_Wait_Without_Failing() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(TransferStates.Completed | TransferStates.Succeeded); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = fixture.Service.Find(t => t.Id == transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Succeeded, record.State); + Assert.Null(record.Exception); + Assert.False(fixture.TimerFired); + } + + [Fact] + public async Task Condition_2_Completed_Without_Success_Ends_Wait_And_Fails_Transfer() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(TransferStates.Completed | TransferStates.Rejected); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Rejected, record.State); + Assert.False(fixture.TimerFired); + } + + [Fact] + public async Task Condition_3_User_Cancellation_Ends_Wait_And_Cancels_Transfer() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + Assert.True(fixture.Service.TryCancel(transfer.Id)); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Cancelled, record.State); + Assert.True(download.CancellationToken.IsCancellationRequested); + Assert.False(fixture.TimerFired); + } + + [Fact] + public async Task Condition_4_Timeout_Ends_Wait_Times_Out_Transfer_And_Cancels_Download() + { + // the download ignores cancellation so that the enqueue timeout is the only thing that fails the transfer + using var fixture = new Fixture(honorCancellation: false); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + fixture.FireTimer(); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.TimedOut, record.State); + Assert.Contains("hard time limit", record.Exception); + + // the download is cancelled so that slskd and Soulseek.NET don't diverge (#1827) + Assert.True(download.CancellationToken.IsCancellationRequested); + } + + [Fact] + public async Task Condition_4_Timeout_Does_Not_Throw_When_Transfer_CancellationTokenSource_Is_Already_Disposed() + { + // regression test for #1891; DownloadAsync() disposes the transfer's CancellationTokenSource in its finally block, + // and if the timeout fires after that, Cancel() threw ObjectDisposedException on a timer thread and crashed the process + using var fixture = new Fixture(honorCancellation: false); + var transfer = await fixture.EnqueueAsync(); + await fixture.Download.Task.WaitAsync(WaitLimit); + + fixture.GetTransferCancellationTokenSource(transfer.Id).Dispose(); + + var ex = Record.Exception(() => fixture.FireTimer()); + + Assert.Null(ex); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.TimedOut, record.State); + } + + [Fact] + public async Task Condition_5_DownloadAsync_Throwing_Ends_Wait_And_Fails_Transfer() + { + // the download fails without ever reporting a Completed state, which previously left the wait hanging until the timeout + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.Fail(new Exception("boom")); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Errored, record.State); + Assert.Equal("boom", record.Exception); + Assert.False(fixture.TimerFired); + } + + /* + everything below exists to cover the remainder of EnqueueAsync(); statements, branches, and each operand of + every compound condition (each operand is shown to independently change the outcome). + */ + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task Throws_ArgumentException_When_Username_Is_Null_Or_Empty(string username) + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(username, [(Filename, Size)])); + + Assert.Equal("username", Assert.IsType<ArgumentException>(ex).ParamName); + fixture.Client.Verify(c => c.GetUserEndPointAsync(It.IsAny<string>(), It.IsAny<CancellationToken?>()), Times.Never); + } + + [Fact] + public async Task Throws_ArgumentException_When_Files_Is_Null() + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, null)); + + Assert.Equal("files", Assert.IsType<ArgumentException>(ex).ParamName); + } + + [Fact] + public async Task Throws_ArgumentException_When_Files_Is_Empty() + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [])); + + Assert.Equal("files", Assert.IsType<ArgumentException>(ex).ParamName); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task Throws_ArgumentException_When_Any_Filename_Is_Null_Or_Empty(string filename) + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (filename, Size)])); + + Assert.Contains("null or empty", Assert.IsType<ArgumentException>(ex).Message); + Assert.Empty(fixture.Records()); + } + + [Theory] + [InlineData("..\\track.flac")] + [InlineData("@alice\\..\\track.flac")] + [InlineData("@alice/../track.flac")] + public async Task Throws_ArgumentException_When_Any_Filename_Contains_Traversal(string filename) + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (filename, Size)])); + + Assert.Contains("traversal", Assert.IsType<ArgumentException>(ex).Message); + Assert.Empty(fixture.Records()); + } + + [Fact] + public async Task Throws_ArgumentException_When_Files_Are_Duplicated() + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (Filename, Size)])); + + Assert.Contains("duplicated", Assert.IsType<ArgumentException>(ex).Message); + Assert.Empty(fixture.Records()); + } + + [Fact] + public async Task Throws_ArgumentException_When_Filenames_Are_Duplicated_With_Different_Sizes() + { + using var fixture = new Fixture(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (Filename, Size + 1)])); + + Assert.Contains("duplicated", Assert.IsType<ArgumentException>(ex).Message); + Assert.Empty(fixture.Records()); + } + + [Fact] + public async Task Rethrows_When_User_Endpoint_Lookup_Fails() + { + using var fixture = new Fixture(); + var expected = new UserOfflineException("offline"); + fixture.Client.Setup(c => c.GetUserEndPointAsync(It.IsAny<string>(), It.IsAny<CancellationToken?>())) + .ThrowsAsync(expected); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + + Assert.Same(expected, ex); + fixture.Client.Verify(c => c.ConnectToUserAsync(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken?>()), Times.Never); + Assert.Empty(fixture.Records()); + } + + [Fact] + public async Task Rethrows_When_Connecting_To_User_Fails() + { + using var fixture = new Fixture(); + var expected = new ConnectionException("unreachable"); + fixture.Client.Setup(c => c.ConnectToUserAsync(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken?>())) + .ThrowsAsync(expected); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + + Assert.Same(expected, ex); + Assert.Empty(fixture.Records()); + } + + [Fact] + public async Task Throws_When_Cancelled_Before_Acquiring_Semaphores_And_Leaves_User_Semaphore_Usable() + { + using var fixture = new Fixture(); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)], cancellationToken: cts.Token)); + + Assert.IsAssignableFrom<OperationCanceledException>(ex); + Assert.Empty(fixture.Records()); + + // a subsequent enqueue for the same user must not be blocked + await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]).WaitAsync(WaitLimit); + } + + [Fact] + public async Task Concurrent_Enqueues_For_Same_User_Are_Serialized_And_Second_Sees_First_As_In_Progress() + { + using var fixture = new Fixture(); + var (entered, gate) = fixture.BlockFirstDbContext(); + + var first = Task.Run(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + await entered.Task.WaitAsync(WaitLimit); + + var second = Task.Run(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + await Task.Delay(100); + + Assert.False(second.IsCompleted); + + gate.Set(); + + var (firstEnqueued, firstFailed) = await first.WaitAsync(WaitLimit); + var (secondEnqueued, secondFailed) = await second.WaitAsync(WaitLimit); + + Assert.Single(firstEnqueued); + Assert.Empty(firstFailed); + Assert.Empty(secondEnqueued); + Assert.Equal((Filename, "Skipped: Already in progress"), Assert.Single(secondFailed)); + Assert.Single(fixture.Records()); + } + + [Fact] + public async Task Cancelling_While_Waiting_For_User_Semaphore_Throws_And_Does_Not_Release_It() + { + using var fixture = new Fixture(); + var (entered, gate) = fixture.BlockFirstDbContext(); + + var first = Task.Run(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + await entered.Task.WaitAsync(WaitLimit); + + using var cts = new CancellationTokenSource(); + var second = Task.Run(() => fixture.Service.EnqueueAsync(Username, [(OtherFilename, Size)], cancellationToken: cts.Token)); + await Task.Delay(100); + + cts.Cancel(); + + Assert.IsAssignableFrom<OperationCanceledException>(await Record.ExceptionAsync(() => second.WaitAsync(WaitLimit))); + + gate.Set(); + + // if the cancelled waiter had released the semaphore, the first enqueue would throw SemaphoreFullException here + var (firstEnqueued, _) = await first.WaitAsync(WaitLimit); + Assert.Single(firstEnqueued); + + var (thirdEnqueued, _) = await fixture.Service.EnqueueAsync(Username, [(OtherFilename, Size)]).WaitAsync(WaitLimit); + Assert.Single(thirdEnqueued); + } + + [Fact] + public async Task Cancelling_Mid_Batch_Throws_And_Already_Inserted_Records_End_Up_Cancelled() + { + using var fixture = new Fixture(); + using var cts = new CancellationTokenSource(); + var inCriticalSection = false; + + fixture.OnCreateDbContext = () => inCriticalSection = true; + fixture.ClientDownloads = () => + { + // cancel while the first file is being processed; the second iteration of the loop should throw + if (inCriticalSection) + { + cts.Cancel(); + } + + return []; + }; + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (OtherFilename, Size)], cancellationToken: cts.Token)); + + Assert.IsAssignableFrom<OperationCanceledException>(ex); + + var record = Assert.Single(fixture.Records()); + Assert.Equal(Filename, record.Filename); + + record = await fixture.WaitForCompletedAsync(record.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Cancelled, record.State); + Assert.Empty(fixture.Downloads); + + // the user semaphore was released + fixture.OnCreateDbContext = null; + fixture.ClientDownloads = () => []; + + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, [(OtherFilename, Size)]).WaitAsync(WaitLimit); + Assert.Single(enqueued); + } + + [Fact] + public async Task Rethrows_And_Releases_User_Semaphore_When_Reading_Existing_Records_Fails() + { + using var fixture = new Fixture(); + var expected = new Exception("database unavailable"); + fixture.OnCreateDbContext = () => throw expected; + + var ex = await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size)])); + + Assert.Same(expected, ex); + + fixture.OnCreateDbContext = null; + + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]).WaitAsync(WaitLimit); + Assert.Single(enqueued); + } + + [Fact] + public async Task Returns_Locally_Queued_Transfer_With_Requested_Properties() + { + using var fixture = new Fixture(); + var batchId = fixture.InsertBatch(Username).Id; + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)], batchId: batchId); + + Assert.Empty(failed); + var transfer = Assert.Single(enqueued); + Assert.NotEqual(Guid.Empty, transfer.Id); + Assert.Equal(batchId, transfer.BatchId); + Assert.Equal(Username, transfer.Username); + Assert.Equal(Filename, transfer.Filename); + Assert.Equal(Size, transfer.Size); + Assert.Equal(TransferDirection.Download, transfer.Direction); + Assert.Equal(TransferStates.Queued | TransferStates.Locally, transfer.State); + Assert.NotEqual(default, transfer.RequestedAt); + + var record = Assert.Single(fixture.Records()); + Assert.Equal(transfer.Id, record.Id); + Assert.Equal(batchId, record.BatchId); + Assert.False(record.Removed); + } + + [Theory] + [InlineData(false, TransferStates.Queued | TransferStates.Remotely, true)] // not ended, not completed + [InlineData(false, TransferStates.Completed | TransferStates.Succeeded, true)] // not ended, completed + [InlineData(true, TransferStates.InProgress, true)] // ended, not completed + [InlineData(true, TransferStates.Completed | TransferStates.Succeeded, false)] // ended and completed + public async Task Existing_Record_Is_In_Progress_Unless_Both_Ended_And_Completed(bool ended, TransferStates state, bool expectSkipped) + { + using var fixture = new Fixture(); + var existing = fixture.Insert(Username, Filename, state, endedAt: ended ? DateTime.UtcNow : null); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + if (expectSkipped) + { + Assert.Empty(enqueued); + Assert.Equal((Filename, "Skipped: Already in progress"), Assert.Single(failed)); + Assert.False(Assert.Single(fixture.Records()).Removed); + Assert.Empty(fixture.Downloads); + } + else + { + // the existing record is superseded by the new one + var transfer = Assert.Single(enqueued); + Assert.Empty(failed); + Assert.True(fixture.Records().Single(r => r.Id == existing.Id).Removed); + Assert.False(fixture.Records().Single(r => r.Id == transfer.Id).Removed); + } + } + + [Fact] + public async Task Existing_Removed_And_Completed_Record_Is_Ignored() + { + using var fixture = new Fixture(); + var existing = fixture.Insert(Username, Filename, TransferStates.Completed | TransferStates.Errored, endedAt: DateTime.UtcNow, removed: true); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Single(enqueued); + Assert.Empty(failed); + Assert.Equal(2, fixture.Records().Count); + Assert.True(fixture.Records().Single(r => r.Id == existing.Id).Removed); + } + + [Fact] + public async Task Existing_Removed_But_Not_Completed_Record_Is_In_Progress() + { + using var fixture = new Fixture(); + fixture.Insert(Username, Filename, TransferStates.InProgress, endedAt: null, removed: true); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Empty(enqueued); + Assert.Equal((Filename, "Skipped: Already in progress"), Assert.Single(failed)); + } + + [Fact] + public async Task Existing_Records_For_Other_Files_Users_And_Directions_Are_Unaffected() + { + using var fixture = new Fixture(); + var otherFileInProgress = fixture.Insert(Username, OtherFilename, TransferStates.Queued | TransferStates.Remotely); + var otherFileCompleted = fixture.Insert(Username, "@alice\\Music\\other.flac", TransferStates.Completed | TransferStates.Succeeded, endedAt: DateTime.UtcNow); + var otherUser = fixture.Insert("bob", Filename, TransferStates.Queued | TransferStates.Remotely); + var upload = fixture.Insert(Username, Filename, TransferStates.Queued | TransferStates.Locally, direction: TransferDirection.Upload); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Single(enqueued); + Assert.Empty(failed); + + var records = fixture.Records(); + Assert.All(new[] { otherFileInProgress, otherFileCompleted, otherUser, upload }, existing => Assert.False(records.Single(r => r.Id == existing.Id).Removed)); + } + + [Fact] + public async Task Only_Completed_Records_Matching_Each_File_Are_Superseded() + { + using var fixture = new Fixture(); + var completed = fixture.Insert(Username, Filename, TransferStates.Completed | TransferStates.Errored, endedAt: DateTime.UtcNow); + var otherCompleted = fixture.Insert(Username, "@alice\\Music\\other.flac", TransferStates.Completed | TransferStates.Errored, endedAt: DateTime.UtcNow); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size), (OtherFilename, Size)]); + + Assert.Equal(2, enqueued.Count); + Assert.Empty(failed); + + var records = fixture.Records(); + Assert.True(records.Single(r => r.Id == completed.Id).Removed); + Assert.False(records.Single(r => r.Id == otherCompleted.Id).Removed); + } + + [Fact] + public async Task Proceeds_When_Client_Downloads_Is_Null() + { + using var fixture = new Fixture(); + fixture.ClientDownloads = () => null; + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Single(enqueued); + Assert.Empty(failed); + } + + [Theory] + [InlineData(Username, Filename, true)] // same user, same file + [InlineData(Username, OtherFilename, false)] // same user, other file + [InlineData("bob", Filename, false)] // other user, same file + public async Task Skips_File_Already_Tracked_By_Soulseek_Client_For_Same_User(string trackedUsername, string trackedFilename, bool expectSkipped) + { + using var fixture = new Fixture(); + var tracked = SoulseekTransfer(trackedUsername, trackedFilename, TransferStates.Queued | TransferStates.Remotely); + fixture.ClientDownloads = () => [tracked]; + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + if (expectSkipped) + { + Assert.Empty(enqueued); + Assert.Equal((Filename, "Skipped: Already in progress"), Assert.Single(failed)); + Assert.Empty(fixture.Records()); + } + else + { + Assert.Single(enqueued); + Assert.Empty(failed); + } + } + + [Fact] + public async Task Fails_File_When_Exception_Is_Thrown_Before_Cancellation_Token_Is_Tracked() + { + using var fixture = new Fixture(); + fixture.ClientDownloads = () => throw new Exception("client exploded"); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Empty(enqueued); + Assert.Equal((Filename, "Error: client exploded"), Assert.Single(failed)); + Assert.Empty(fixture.Records()); + Assert.Empty(fixture.CancellationTokens); + } + + [Fact] + public async Task Fails_File_And_Disposes_Cancellation_Token_When_Saving_Record_Fails() + { + using var fixture = new Fixture(); + fixture.Execute($"CREATE TRIGGER fail_insert BEFORE INSERT ON Transfers WHEN NEW.Filename = '{Filename}' BEGIN SELECT RAISE(ABORT, 'insert failed'); END;"); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Empty(enqueued); + var (failedFilename, message) = Assert.Single(failed); + Assert.Equal(Filename, failedFilename); + Assert.StartsWith("Error: ", message); + Assert.Empty(fixture.Records()); + Assert.Empty(fixture.CancellationTokens); + Assert.Empty(fixture.Downloads); + } + + [Fact] + public async Task Sends_All_Enqueue_Requests_Concurrently_When_Batch_Has_30_Files() + { + using var fixture = new Fixture(); + + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, Files(30)); + + Assert.Equal(30, enqueued.Count); + await fixture.WaitUntilAsync(() => fixture.Downloads.Count == 30); + } + + [Fact] + public async Task Sends_At_Most_5_Enqueue_Requests_Concurrently_When_Batch_Has_More_Than_30_Files() + { + using var fixture = new Fixture(); + + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, Files(31)); + + Assert.Equal(31, enqueued.Count); + await fixture.WaitUntilAsync(() => fixture.Downloads.Count == 5); + await Task.Delay(250); + Assert.Equal(5, fixture.Downloads.Count); + + // once one is queued remotely, its slot is released to the next waiting file + fixture.Downloads.Values.First().RaiseStateChanged(TransferStates.Queued | TransferStates.Remotely); + + await fixture.WaitUntilAsync(() => fixture.Downloads.Count == 6); + await Task.Delay(250); + Assert.Equal(6, fixture.Downloads.Count); + } + + [Fact] + public async Task Cancelling_File_Waiting_For_Enqueue_Slot_Cancels_Transfer_Without_Starting_Download() + { + using var fixture = new Fixture(); + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, Files(31)); + await fixture.WaitUntilAsync(() => fixture.Downloads.Count == 5); + + var waiting = enqueued.First(t => !fixture.Downloads.ContainsKey(t.Filename)); + + Assert.True(fixture.Service.TryCancel(waiting.Id)); + + var record = await fixture.WaitForCompletedAsync(waiting.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Cancelled, record.State); + + await Task.Delay(250); + Assert.False(fixture.Downloads.ContainsKey(waiting.Filename)); + Assert.Equal(5, fixture.Downloads.Count); + } + + [Fact] + public async Task Cancelling_File_Waiting_For_Enqueue_Slot_Tolerates_Missing_Record() + { + using var fixture = new Fixture(); + var (enqueued, _) = await fixture.Service.EnqueueAsync(Username, Files(31)); + await fixture.WaitUntilAsync(() => fixture.Downloads.Count == 5); + + var waiting = enqueued.First(t => !fixture.Downloads.ContainsKey(t.Filename)); + fixture.Delete(waiting.Id); + + Assert.True(fixture.Service.TryCancel(waiting.Id)); + + await Task.Delay(250); + Assert.Null(fixture.Service.Find(t => t.Id == waiting.Id)); + Assert.Equal(5, fixture.Downloads.Count); + } + + [Theory] + [InlineData(TransferStates.Queued | TransferStates.Locally)] // queued, but not remotely + [InlineData(TransferStates.Remotely)] // remotely, but not queued + [InlineData(TransferStates.Initializing)] + [InlineData(TransferStates.InProgress)] + public async Task Non_Terminal_States_Other_Than_Queued_Remotely_Do_Not_End_Wait(TransferStates state) + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(state); + await Task.Delay(100); + + Assert.False(fixture.TimerDisposed.Task.IsCompleted); + Assert.False(fixture.Service.Find(t => t.Id == transfer.Id).State.HasFlag(TransferStates.Completed)); + + download.RaiseStateChanged(TransferStates.Queued | TransferStates.Remotely); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + } + + [Fact] + public async Task Completed_Without_Success_Preserves_Remote_Exception_Message() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(TransferStates.Completed | TransferStates.Errored, new Exception("remote said no")); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Errored, record.State); + Assert.Equal("remote said no", record.Exception); + } + + [Fact] + public async Task Successful_Download_Completes_Transfer_And_Releases_Cancellation_Token() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + download.RaiseStateChanged(TransferStates.Queued | TransferStates.Remotely); + download.Complete(); + + await fixture.WaitUntilAsync(() => !fixture.CancellationTokens.ContainsKey(transfer.Id)); + + var record = fixture.Service.Find(t => t.Id == transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Succeeded, record.State); + Assert.Null(record.Exception); + fixture.Files.Verify(f => f.MoveFile(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UnixFileMode?>(), It.IsAny<bool>(), true), Times.Once); + } + + [Fact] + public async Task Download_Cancelled_Before_Transfer_Starts_Cancels_Transfer() + { + using var fixture = new Fixture(); + var cancelled = 0; + + fixture.ClientDownloads = () => + { + // the first call is EnqueueAsync() checking for duplicates (no record yet); the next is DownloadAsync() + // doing the same, at which point we cancel so that DownloadAsync() throws OperationCanceledException + var record = fixture.Service.Find(t => t.Filename == Filename); + + if (record is not null && Interlocked.Exchange(ref cancelled, 1) == 0) + { + fixture.Service.TryCancel(record.Id); + } + + return []; + }; + + var transfer = await fixture.EnqueueAsync(); + + var result = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Cancelled, result.State); + Assert.Empty(fixture.Downloads); + } + + [Fact] + public async Task Download_Failure_Tolerates_Missing_Record() + { + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + fixture.Delete(transfer.Id); + download.Fail(new Exception("boom")); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + await fixture.WaitUntilAsync(() => !fixture.CancellationTokens.ContainsKey(transfer.Id)); + await Task.Delay(100); + + Assert.Null(fixture.Service.Find(t => t.Id == transfer.Id)); + } + + [Fact] + public async Task Removed_Record_With_Uncategorized_Completed_State_Is_Loaded_But_Not_Superseded_Again() + { + // Completed | Locally isn't in TransferStateCategories.Completed, so the query loads this removed record, but it + // isn't in progress (ended and has the Completed flag), so it reaches the supersede step where !Removed excludes it + using var fixture = new Fixture(); + var existing = fixture.Insert(Username, Filename, TransferStates.Completed | TransferStates.Locally, endedAt: DateTime.UtcNow, removed: true); + + var (enqueued, failed) = await fixture.Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Single(enqueued); + Assert.Empty(failed); + + var record = fixture.Records().Single(r => r.Id == existing.Id); + Assert.True(record.Removed); + Assert.Equal(TransferStates.Completed | TransferStates.Locally, record.State); + } + + [Fact] + public async Task Database_Failure_While_Failing_Transfer_Does_Not_Escape() + { + // TryFail() rethrows when it can't read the record; when that happens inside the enqueue catch block, + // the enqueue Task faults and its continuation tries (and fails) again. none of this may escape. + using var fixture = new Fixture(); + var transfer = await fixture.EnqueueAsync(); + var download = await fixture.Download.Task.WaitAsync(WaitLimit); + + fixture.OnCreateDbContext = () => throw new Exception("database unavailable"); + download.Fail(new Exception("boom")); + + await fixture.TimerDisposed.Task.WaitAsync(WaitLimit); + await fixture.WaitUntilAsync(() => !fixture.CancellationTokens.ContainsKey(transfer.Id)); + await Task.Delay(100); + } + + [Fact] + public async Task Cancellation_Token_Is_Released_When_DownloadAsync_Throws_Before_Starting() + { + using var fixture = new Fixture(); + + fixture.ClientDownloads = () => + { + // the first call is EnqueueAsync() checking for duplicates (no record yet); once the record exists, DownloadAsync() + // makes the same check, and reporting a duplicate makes it throw DuplicateTransferException before its try block + var record = fixture.Service.Find(t => t.Filename == Filename); + return record is null ? [] : [SoulseekTransfer(Username, Filename, TransferStates.Queued | TransferStates.Remotely)]; + }; + + var transfer = await fixture.EnqueueAsync(); + + var record = await fixture.WaitForCompletedAsync(transfer.Id); + Assert.Equal(TransferStates.Completed | TransferStates.Errored, record.State); + Assert.Empty(fixture.Downloads); + + await Task.Delay(100); + Assert.False(fixture.CancellationTokens.ContainsKey(transfer.Id)); + } + + [Fact] + public async Task Cancellation_Token_Is_Released_When_Batch_Is_Cancelled_Mid_Loop() + { + using var fixture = new Fixture(); + using var cts = new CancellationTokenSource(); + var inCriticalSection = false; + + fixture.OnCreateDbContext = () => inCriticalSection = true; + fixture.ClientDownloads = () => + { + if (inCriticalSection) + { + cts.Cancel(); + } + + return []; + }; + + await Record.ExceptionAsync(() => fixture.Service.EnqueueAsync(Username, [(Filename, Size), (OtherFilename, Size)], cancellationToken: cts.Token)); + + var record = await fixture.WaitForCompletedAsync(Assert.Single(fixture.Records()).Id); + Assert.Equal(TransferStates.Completed | TransferStates.Cancelled, record.State); + + await Task.Delay(100); + Assert.False(fixture.CancellationTokens.ContainsKey(record.Id)); + } + + private const string OtherFilename = "@alice\\Music\\track2.flac"; + + private static List<(string Filename, long Size)> Files(int count) + => Enumerable.Range(0, count).Select(i => ($"@alice\\Music\\track{i:00}.flac", Size)).ToList(); + + private static Soulseek.Transfer SoulseekTransfer(string username, string filename, TransferStates state, Exception exception = null) + => new( + Soulseek.TransferDirection.Download, + username, + filename, + 1, + state, + Size, + 0, + state.HasFlag(TransferStates.Succeeded) ? Size : 0, + 0, + state.HasFlag(TransferStates.Completed) ? DateTime.UtcNow : null, + state.HasFlag(TransferStates.Completed) ? DateTime.UtcNow : null, + null, + null, + exception); + + private sealed class Fixture : IDisposable + { + private readonly SqliteConnection _anchor; + private readonly DbContextOptions<TransfersDbContext> _dbContextOptions; + private TimerCallback _timerCallback; + private object _timerState; + + public Fixture(bool honorCancellation = true) + { + var connectionString = $"Data Source=enqueue_{Guid.NewGuid():N};Mode=Memory;Cache=Shared"; + + // keep the shared-cache in-memory database alive for the life of this fixture + _anchor = new SqliteConnection(connectionString); + _anchor.Open(); + + _dbContextOptions = new DbContextOptionsBuilder<TransfersDbContext>() + .UseSqlite(connectionString) + .Options; + + using (var context = new TransfersDbContext(_dbContextOptions)) + { + context.Database.EnsureCreated(); + } + + var contextFactory = new Mock<IDbContextFactory<TransfersDbContext>>(); + contextFactory.Setup(f => f.CreateDbContext()).Returns(() => + { + OnCreateDbContext?.Invoke(); + return new TransfersDbContext(_dbContextOptions); + }); + + var options = new Options + { + Directories = new Options.DirectoriesOptions { Incomplete = Path.GetTempPath(), Downloads = Path.GetTempPath() }, + Transfers = new Options.TransfersOptions + { + Download = new Options.TransfersOptions.GlobalDownloadOptions + { + // one attempt, so that failures are terminal and no retry delays are introduced + Retry = new Options.TransfersOptions.GlobalDownloadOptions.RetryOptions { Attempts = 1 }, + }, + }, + }; + + var optionsMonitor = new TestOptionsMonitor<Options>(options); + + Client.Setup(c => c.GetUserEndPointAsync(It.IsAny<string>(), It.IsAny<CancellationToken?>())) + .ReturnsAsync(new IPEndPoint(IPAddress.Loopback, 2234)); + Client.Setup(c => c.ConnectToUserAsync(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken?>())) + .Returns(Task.CompletedTask); + Client.Setup(c => c.Downloads) + .Returns(() => ClientDownloads()?.ToList()); + Client.Setup(c => c.DownloadAsync( + It.IsAny<string>(), + It.IsAny<string>(), + It.IsAny<Func<Task<Stream>>>(), + It.IsAny<long?>(), + It.IsAny<long>(), + It.IsAny<int?>(), + It.IsAny<TransferOptions>(), + It.IsAny<CancellationToken?>())) + .Returns<string, string, Func<Task<Stream>>, long?, long, int?, TransferOptions, CancellationToken?>((username, filename, _, _, _, _, transferOptions, cancellationToken) => + { + var download = new FakeDownload(username, filename, transferOptions, cancellationToken ?? CancellationToken.None, honorCancellation); + Downloads.TryAdd(filename, download); + Download.TrySetResult(download); + return download.Task; + }); + + Files = new Mock<FileService>(optionsMonitor); + Files.Setup(f => f.ResolveFileInfo(It.IsAny<string>())) + .Returns(new FileInfo(Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.incomplete"))); + + var timer = new Mock<ITimer>(); + timer.Setup(t => t.Dispose()).Callback(() => TimerDisposed.TrySetResult()); + + var timeProvider = new Mock<TimeProvider>(); + timeProvider.Setup(p => p.CreateTimer(It.IsAny<TimerCallback>(), It.IsAny<object>(), It.IsAny<TimeSpan>(), It.IsAny<TimeSpan>())) + .Callback<TimerCallback, object, TimeSpan, TimeSpan>((callback, state, _, _) => + { + _timerCallback = callback; + _timerState = state; + }) + .Returns(timer.Object); + + Service = new DownloadService( + new Mock<IBatchService>().Object, + new Mock<slskd.Search.ISearchService>().Object, + optionsMonitor, + Client.Object, + contextFactory.Object, + Files.Object, + null, + null, + null, + timeProvider.Object); + } + + public DownloadService Service { get; } + public Mock<ISoulseekClient> Client { get; } = new(); + public Mock<FileService> Files { get; } + public Func<IEnumerable<Soulseek.Transfer>> ClientDownloads { get; set; } = () => []; + public Action OnCreateDbContext { get; set; } + public ConcurrentDictionary<string, FakeDownload> Downloads { get; } = new(); + public TaskCompletionSource<FakeDownload> Download { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource TimerDisposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public bool TimerFired { get; private set; } + public ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens + => Service.GetProperty<ConcurrentDictionary<Guid, CancellationTokenSource>>("CancellationTokens"); + + public async Task<slskd.Transfers.Transfer> EnqueueAsync() + { + var (enqueued, failed) = await Service.EnqueueAsync(Username, [(Filename, Size)]); + + Assert.Empty(failed); + return Assert.Single(enqueued); + } + + public void FireTimer() + { + TimerFired = true; + _timerCallback(_timerState); + } + + public CancellationTokenSource GetTransferCancellationTokenSource(Guid id) + { + return CancellationTokens[id]; + } + + /// <summary> + /// Blocks the first DbContext creation (made from within the per-user critical section of EnqueueAsync()) until + /// the returned gate is set; the returned TaskCompletionSource completes once the block is entered. + /// </summary> + public (TaskCompletionSource Entered, ManualResetEventSlim Gate) BlockFirstDbContext() + { + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var gate = new ManualResetEventSlim(false); + var first = 1; + + OnCreateDbContext = () => + { + if (Interlocked.Exchange(ref first, 0) == 1) + { + entered.TrySetResult(); + gate.Wait(WaitLimit); + } + }; + + return (entered, gate); + } + + public slskd.Transfers.Transfer Insert( + string username, + string filename, + TransferStates state, + DateTime? endedAt = null, + bool removed = false, + TransferDirection direction = TransferDirection.Download) + { + var transfer = new slskd.Transfers.Transfer + { + Id = Guid.NewGuid(), + Username = username, + Direction = direction, + Filename = filename, + Size = Size, + State = state, + RequestedAt = DateTime.UtcNow, + EndedAt = endedAt, + Removed = removed, + }; + + using var context = new TransfersDbContext(_dbContextOptions); + context.Transfers.Add(transfer); + context.SaveChanges(); + + return transfer; + } + + public Batch InsertBatch(string username) + { + var batch = new Batch { Id = Guid.NewGuid(), Username = username }; + + using var context = new TransfersDbContext(_dbContextOptions); + context.Batches.Add(batch); + context.SaveChanges(); + + return batch; + } + + public void Delete(Guid id) + { + using var context = new TransfersDbContext(_dbContextOptions); + context.Transfers.Where(t => t.Id == id).ExecuteDelete(); + } + + public void Execute(string sql) + { + using var command = _anchor.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); + } + + public List<slskd.Transfers.Transfer> Records() + { + using var context = new TransfersDbContext(_dbContextOptions); + return context.Transfers.AsNoTracking().ToList(); + } + + public async Task WaitUntilAsync(Func<bool> condition) + { + var deadline = DateTime.UtcNow + WaitLimit; + + while (!condition()) + { + if (DateTime.UtcNow > deadline) + { + throw new TimeoutException("Condition was not met before the wait limit"); + } + + await Task.Delay(25); + } + } + + public async Task<slskd.Transfers.Transfer> WaitForCompletedAsync(Guid id) + { + var deadline = DateTime.UtcNow + WaitLimit; + + while (true) + { + var record = Service.Find(t => t.Id == id); + + if (record.State.HasFlag(TransferStates.Completed) || DateTime.UtcNow > deadline) + { + return record; + } + + await Task.Delay(25); + } + } + + public void Dispose() + { + _anchor.Dispose(); + } + } + + private sealed class FakeDownload + { + private readonly string _username; + private readonly string _filename; + private readonly TransferOptions _options; + private readonly TaskCompletionSource<Soulseek.Transfer> _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); + private TransferStates _state = TransferStates.Queued | TransferStates.Locally; + + public FakeDownload(string username, string filename, TransferOptions options, CancellationToken cancellationToken, bool honorCancellation) + { + _username = username; + _filename = filename; + _options = options; + CancellationToken = cancellationToken; + + if (honorCancellation) + { + cancellationToken.Register(() => _tcs.TrySetCanceled(cancellationToken)); + } + } + + public CancellationToken CancellationToken { get; } + public Task<Soulseek.Transfer> Task => _tcs.Task; + + public void RaiseStateChanged(TransferStates state, Exception exception = null) + { + var previous = _state; + _state = state; + + _options.StateChanged((previous, SoulseekTransfer(_username, _filename, state, exception))); + } + + public void Complete() + { + RaiseStateChanged(TransferStates.Completed | TransferStates.Succeeded); + _tcs.TrySetResult(SoulseekTransfer(_username, _filename, TransferStates.Completed | TransferStates.Succeeded)); + } + + public void Fail(Exception exception) + { + _tcs.TrySetException(exception); + } + } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index b1da3a77..19920a3d 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -3,6 +3,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; + using System.Threading; using System.Threading.Tasks; using AutoFixture.Xunit2; using Moq; @@ -39,7 +40,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(Application.PrivilegedGroup, p.Name); Assert.Equal(0, p.Priority); Assert.Equal(new Options().Transfers.Upload.Slots, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(QueueStrategy.FirstInFirstOut, p.Strategy); } @@ -76,7 +77,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(Application.DefaultGroup, p.Name); Assert.Equal(priority, p.Priority); Assert.Equal(slots, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy, p.Strategy); } @@ -114,7 +115,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(Application.LeecherGroup, p.Name); Assert.Equal(priority, p.Priority); Assert.Equal(slots, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy, p.Strategy); } @@ -169,7 +170,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(group1, p.Name); Assert.Equal(priority1, p.Priority); Assert.Equal(slots1, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy1, p.Strategy); p = groups[group2]; @@ -177,7 +178,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(group2, p.Name); Assert.Equal(priority2, p.Priority); Assert.Equal(slots2, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy2, p.Strategy); } @@ -236,7 +237,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(group, p.Name); Assert.Equal(priority, p.Priority); Assert.Equal(slots, p.Slots); - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy, p.Strategy); } @@ -293,12 +294,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(group, p.Name); Assert.Equal(priority, p.Priority); Assert.Equal(42, p.Slots); // clamped to global value - Assert.Equal(0, p.UsedSlots); + Assert.Empty(p.UsedSlots); Assert.Equal(strategy, p.Strategy); } [Theory, AutoData] - public void Retains_Used_Slot_Count_When_Options_Change(string group, int newPriority, int usedSlots) + public void Retains_Used_Slots_When_Options_Change(string group, int newPriority, Guid id1, Guid id2) { var options = new Options() { @@ -328,7 +329,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads var (queue, mocks) = GetFixture(options); var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); - groups[group].UsedSlots = usedSlots; + groups[group].UsedSlots.Add(id1); + groups[group].UsedSlots.Add(id2); // reconfigure with different options to bypass the hash check options = new Options() @@ -363,11 +365,139 @@ namespace slskd.Tests.Unit.Transfers.Uploads var p = groups[group]; - Assert.Equal(usedSlots, p.UsedSlots); + Assert.Equal(2, p.UsedSlots.Count); + Assert.Contains(id1, p.UsedSlots); + Assert.Contains(id2, p.UsedSlots); Assert.Equal(newPriority, p.Priority); } } + public class Guards + { + [Fact] + public void Enqueue_Throws_ArgumentNullException_If_Transfer_Is_Null() + { + var (queue, _) = GetFixture(); + + var ex = Record.Exception(() => queue.Enqueue(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("transfer", ((ArgumentNullException)ex).ParamName); + } + + [Fact] + public async Task AwaitStartAsync_Throws_ArgumentNullException_If_Transfer_Is_Null() + { + var (queue, _) = GetFixture(); + + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("transfer", ((ArgumentNullException)ex).ParamName); + } + + [Fact] + public void Complete_Throws_ArgumentNullException_If_Transfer_Is_Null() + { + var (queue, _) = GetFixture(); + + var ex = Record.Exception(() => queue.Complete(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("transfer", ((ArgumentNullException)ex).ParamName); + } + + [Fact] + public void TryComplete_Throws_ArgumentNullException_If_Transfer_Is_Null() + { + var (queue, _) = GetFixture(); + + // a null transfer is a programming error, not a "problem completing"; it is not swallowed + var ex = Record.Exception(() => queue.TryComplete(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("transfer", ((ArgumentNullException)ex).ParamName); + } + + [Fact] + public void EstimatePosition_Throws_ArgumentNullException_If_Transfer_Is_Null() + { + var (queue, _) = GetFixture(); + + var ex = Record.Exception(() => queue.EstimatePosition(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("transfer", ((ArgumentNullException)ex).ParamName); + } + + [Fact] + public void ForecastPosition_Throws_ArgumentNullException_If_Username_Is_Null() + { + var (queue, _) = GetFixture(); + + var ex = Record.Exception(() => queue.ForecastPosition(null)); + + Assert.IsType<ArgumentNullException>(ex); + Assert.Equal("username", ((ArgumentNullException)ex).ParamName); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("\t")] + public void ForecastPosition_Throws_ArgumentException_If_Username_Is_Empty_Or_Whitespace(string username) + { + var (queue, _) = GetFixture(); + + var ex = Record.Exception(() => queue.ForecastPosition(username)); + + Assert.IsType<ArgumentException>(ex); + Assert.Equal("username", ((ArgumentException)ex).ParamName); + } + + [Theory, AutoData] + public void Guard_Failures_Do_Not_Hold_The_Lock(string username, string filename) + { + var (queue, _) = GetFixture(); + + Record.Exception(() => queue.Enqueue(null)); + Record.Exception(() => queue.Complete(null)); + Record.Exception(() => queue.EstimatePosition(null)); + + var syncRoot = queue.GetProperty<SemaphoreSlim>("SyncRoot"); + + Assert.Equal(1, syncRoot.CurrentCount); + + // and the queue still works + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + Assert.True(queue.AwaitStartAsync(transfer).IsCompletedSuccessfully); + } + + [Theory, AutoData] + public async Task AwaitStartAsync_Throws_OperationCanceledException_If_Token_Is_Already_Cancelled(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(transfer, cts.Token)); + + Assert.IsAssignableFrom<OperationCanceledException>(ex); + + // the upload was not marked ready, and the lock was never taken + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + Assert.Null(uploads[username][0].Ready); + Assert.Equal(1, queue.GetProperty<SemaphoreSlim>("SyncRoot").CurrentCount); + } + } + public class Enqueue { [Theory, AutoData] @@ -377,7 +507,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Empty(queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary")); - queue.Enqueue(username, filename); + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); @@ -392,8 +523,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); - queue.Enqueue(username, filename2); + queue.Enqueue(CreateTransfer(username, filename)); + queue.Enqueue(CreateTransfer(username, filename2)); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); @@ -411,8 +542,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Empty(queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary")); - queue.Enqueue(username, filename); - queue.Enqueue(username2, filename2); + queue.Enqueue(CreateTransfer(username, filename)); + queue.Enqueue(CreateTransfer(username2, filename2)); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); @@ -428,6 +559,38 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Single(uploads.GetValueOrDefault(username2)); Assert.Equal(filename2, uploads.GetValueOrDefault(username2).First().Filename); } + + [Theory, AutoData] + public void Enqueue_Copies_Transfer_Id_To_Upload(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + Assert.Equal(transfer.Id, uploads[username][0].Id); + Assert.Equal(username, uploads[username][0].Username); + } + + [Theory, AutoData] + public void Enqueue_Tracks_Same_File_Separately_For_Each_Transfer(string username, string filename) + { + var (queue, _) = GetFixture(); + + var first = CreateTransfer(username, filename); + var second = CreateTransfer(username, filename); + + queue.Enqueue(first); + queue.Enqueue(second); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + Assert.Equal(2, uploads[username].Count); + Assert.Equal(first.Id, uploads[username][0].Id); + Assert.Equal(second.Id, uploads[username][1].Id); + } } public class Complete @@ -437,7 +600,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - var ex = Record.Exception(() => queue.Complete(username, filename)); + var ex = Record.Exception(() => queue.Complete(CreateTransfer(username, filename))); Assert.NotNull(ex); Assert.IsType<SlskdException>(ex); @@ -445,13 +608,14 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] - public void Throws_If_No_Such_Filename(string username, string filename) + public void Throws_If_No_Such_Transfer(string username, string filename) { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); + queue.Enqueue(CreateTransfer(username, filename)); - var ex = Record.Exception(() => queue.Complete(username, "foo")); + // same user and file, but a different transfer + var ex = Record.Exception(() => queue.Complete(CreateTransfer(username, filename))); Assert.NotNull(ex); Assert.IsType<SlskdException>(ex); @@ -459,16 +623,41 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] + public void TryComplete_Returns_False_If_No_Such_Transfer(string username, string filename) + { + var (queue, _) = GetFixture(); + + queue.Enqueue(CreateTransfer(username, filename)); + + Assert.False(queue.TryComplete(CreateTransfer(username, filename))); + } + + [Theory, AutoData] + public void TryComplete_Returns_True_And_Removes_Transfer(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + Assert.True(queue.TryComplete(transfer)); + Assert.Empty(queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary")); + } + + [Theory, AutoData] public async Task Removes_Filename(string username, string filename, string filename2) { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); - await queue.AwaitStartAsync(username, filename); - queue.Enqueue(username, filename2); - await queue.AwaitStartAsync(username, filename2); + var transfer = CreateTransfer(username, filename); + var transfer2 = CreateTransfer(username, filename2); - queue.Complete(username, filename); + queue.Enqueue(transfer); + await queue.AwaitStartAsync(transfer); + queue.Enqueue(transfer2); + await queue.AwaitStartAsync(transfer2); + + queue.Complete(transfer); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); @@ -479,25 +668,232 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] - public async Task Decrements_UsedSlots_For_Group(string username, string filename, string filename2) + public void Removes_Only_The_Matching_Transfer_When_Same_File_Is_Enqueued_Twice(string username, string filename) + { + var (queue, _) = GetFixture(); + + var first = CreateTransfer(username, filename); + var second = CreateTransfer(username, filename); + + queue.Enqueue(first); + queue.Enqueue(second); + + // completing the second must not remove the first, which comes first in the list + queue.Complete(second); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + Assert.Single(uploads[username]); + Assert.Equal(first.Id, uploads[username][0].Id); + Assert.False(uploads[username][0].TaskCompletionSource.Task.IsCompleted); + } + + [Theory, AutoData] + public void Stale_TryComplete_Does_Not_Remove_New_Request_For_Same_File(string username, string filename) { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); - await queue.AwaitStartAsync(username, filename); + // the original transfer finishes and is removed + var stale = CreateTransfer(username, filename); + queue.Enqueue(stale); + queue.Complete(stale); + + // the user requests the same file again before the original transfer's cleanup runs + var fresh = CreateTransfer(username, filename); + queue.Enqueue(fresh); - queue.Enqueue(username, filename2); - await queue.AwaitStartAsync(username, filename2); + // the original transfer's cleanup must not touch the new request + Assert.False(queue.TryComplete(stale)); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + Assert.Single(uploads[username]); + Assert.Equal(fresh.Id, uploads[username][0].Id); + Assert.False(uploads[username][0].TaskCompletionSource.Task.IsCompleted); + } + + [Theory, AutoData] + public async Task Releases_Slot_Held_By_Completed_Upload(string username, string filename, string filename2) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + var transfer2 = CreateTransfer(username, filename2); + + queue.Enqueue(transfer); + await queue.AwaitStartAsync(transfer); + + queue.Enqueue(transfer2); + await queue.AwaitStartAsync(transfer2); var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); - Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots); + Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots.Count); + Assert.Contains(transfer.Id, groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(transfer2.Id, groups[Application.DefaultGroup].UsedSlots); - queue.Complete(username, filename); + queue.Complete(transfer); groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); - Assert.Equal(1, groups[Application.DefaultGroup].UsedSlots); + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(transfer2.Id, groups[Application.DefaultGroup].UsedSlots); + } + + [Theory, AutoData] + public async Task Releases_Only_The_Matching_Slot_When_Same_File_Holds_Two_Slots(string username, string filename) + { + var (queue, _) = GetFixture(); + + var first = CreateTransfer(username, filename); + var second = CreateTransfer(username, filename); + + queue.Enqueue(first); + await queue.AwaitStartAsync(first); + + queue.Enqueue(second); + await queue.AwaitStartAsync(second); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + + // keyed by transfer id, so the same file counts as two slots + Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots.Count); + + queue.Complete(first); + + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(second.Id, groups[Application.DefaultGroup].UsedSlots); + } + + [Theory, AutoData] + public async Task Releases_Slot_To_Pinned_Group_If_Users_Group_Changed(string username, string filename) + { + var (queue, mocks) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + + queue.Enqueue(transfer); + await queue.AwaitStartAsync(transfer); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + + Assert.Contains(transfer.Id, groups[Application.DefaultGroup].UsedSlots); + + // the user moves to a different group mid-transfer + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(Application.LeecherGroup); + + queue.Complete(transfer); + + Assert.Empty(groups[Application.DefaultGroup].UsedSlots); + Assert.Empty(groups[Application.LeecherGroup].UsedSlots); + } + + [Theory, AutoData] + public async Task Does_Not_Release_Slots_Held_By_Other_Uploads_When_Completing_Upload_That_Never_Started(string username, string filename, string other, string otherFilename) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + + var otherTransfer = CreateTransfer(other, otherFilename); + queue.Enqueue(otherTransfer); + await queue.AwaitStartAsync(otherTransfer); + + // no slot available; this upload is queued but never started + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + var task = queue.AwaitStartAsync(transfer); + + Assert.False(task.IsCompleted); + + queue.Complete(transfer); + + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(otherTransfer.Id, groups[Application.DefaultGroup].UsedSlots); + } + + [Theory, AutoData] + public async Task Cancels_Task_Of_Upload_That_Is_Waiting_For_A_Slot(string username, string filename, string other, string otherFilename) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + + var otherTransfer = CreateTransfer(other, otherFilename); + queue.Enqueue(otherTransfer); + await queue.AwaitStartAsync(otherTransfer); + + // no slot available; the caller is left waiting on this task + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + var task = queue.AwaitStartAsync(transfer); + + Assert.False(task.IsCompleted); + + queue.Complete(transfer); + + // continuations run asynchronously, but the task's status is set synchronously + Assert.True(task.IsCanceled); + } + + [Theory, AutoData] + public void Cancels_Task_Of_Upload_That_Was_Never_Ready(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + var task = uploads[username][0].TaskCompletionSource.Task; + + Assert.False(task.IsCompleted); + + queue.Complete(transfer); + + Assert.True(task.IsCanceled); + } + + [Theory, AutoData] + public async Task Does_Not_Cancel_Task_Of_Upload_That_Started(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + var task = queue.AwaitStartAsync(transfer); + await task; + + queue.Complete(transfer); + + Assert.True(task.IsCompletedSuccessfully); + } + + [Theory, AutoData] + public async Task Releasing_A_Slot_Starts_The_Next_Ready_Upload(string username, string filename, string other, string otherFilename) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + + var otherTransfer = CreateTransfer(other, otherFilename); + queue.Enqueue(otherTransfer); + await queue.AwaitStartAsync(otherTransfer); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + var task = queue.AwaitStartAsync(transfer); + + Assert.False(task.IsCompleted); + + queue.Complete(otherTransfer); + + Assert.True(task.IsCompletedSuccessfully); + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(transfer.Id, groups[Application.DefaultGroup].UsedSlots); } [Theory, AutoData] @@ -505,15 +901,18 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); - queue.Enqueue(username, filename2); + var transfer = CreateTransfer(username, filename); + var transfer2 = CreateTransfer(username, filename2); + + queue.Enqueue(transfer); + queue.Enqueue(transfer2); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); Assert.Single(uploads); - queue.Complete(username, filename); - queue.Complete(username, filename2); + queue.Complete(transfer); + queue.Complete(transfer2); uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); @@ -528,7 +927,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(username, filename)); + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(CreateTransfer(username, filename))); Assert.NotNull(ex); Assert.IsType<SlskdException>(ex); @@ -536,13 +935,14 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] - public async Task Throws_If_No_Such_Filename(string username, string filename) + public async Task Throws_If_No_Such_Transfer(string username, string filename) { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); + queue.Enqueue(CreateTransfer(username, filename)); - var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(username, "foo")); + // same user and file, but a different transfer + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(CreateTransfer(username, filename))); Assert.NotNull(ex); Assert.IsType<SlskdException>(ex); @@ -554,14 +954,601 @@ namespace slskd.Tests.Unit.Transfers.Uploads { var (queue, _) = GetFixture(); - queue.Enqueue(username, filename); + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); - var task = queue.AwaitStartAsync(username, filename); + var task = queue.AwaitStartAsync(transfer); Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task); } + + [Theory, AutoData] + public void Returns_Task_Of_Matching_Transfer_When_Same_File_Is_Enqueued_Twice(string username, string filename) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 0; + + var first = CreateTransfer(username, filename); + var second = CreateTransfer(username, filename); + + queue.Enqueue(first); + queue.Enqueue(second); + + var task = queue.AwaitStartAsync(second); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary"); + + // only the second transfer is marked ready, and its own task is returned + Assert.Equal(uploads[username][1].TaskCompletionSource.Task, task); + Assert.Null(uploads[username][0].Ready); + Assert.NotNull(uploads[username][1].Ready); + } + + [Theory, AutoData] + public void Occupies_Slot_When_Upload_Is_Released(string username, string filename) + { + var (queue, _) = GetFixture(); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + + // enqueueing alone does not consume a slot; the upload must be ready first + Assert.Empty(groups[Application.DefaultGroup].UsedSlots); + + var task = queue.AwaitStartAsync(transfer); + + Assert.True(task.IsCompletedSuccessfully); + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.Contains(transfer.Id, groups[Application.DefaultGroup].UsedSlots); + } + + [Theory, AutoData] + public void Does_Not_Occupy_Slot_When_No_Slot_Is_Available(string username, string filename, Guid otherId) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + groups[Application.DefaultGroup].UsedSlots.Add(otherId); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + var task = queue.AwaitStartAsync(transfer); + + Assert.False(task.IsCompleted); + Assert.Single(groups[Application.DefaultGroup].UsedSlots); + Assert.DoesNotContain(transfer.Id, groups[Application.DefaultGroup].UsedSlots); + } + } + + public class EstimatePosition + { + private static readonly DateTime Now = DateTime.UtcNow; + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Throws_NotFoundException_If_User_Has_No_Uploads(QueueStrategy strategy, string username, string filename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var ex = Record.Exception(() => queue.EstimatePosition(CreateTransfer(username, filename))); + + Assert.IsType<NotFoundException>(ex); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Throws_NotFoundException_If_Transfer_Is_Not_Enqueued(QueueStrategy strategy, string username, string filename, string otherFilename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + + uploads.TryAdd(username, new List<Upload>() + { + new Upload() { Id = Guid.NewGuid(), Username = username, Filename = otherFilename, Enqueued = Now }, + }); + + queue.SetProperty("UploadDictionary", uploads); + + var ex = Record.Exception(() => queue.EstimatePosition(CreateTransfer(username, filename))); + + Assert.IsType<NotFoundException>(ex); + } + + [Theory, AutoData] + public void Throws_SlskdException_If_Group_Does_Not_Exist(string username, string filename, string groupName) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(groupName); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + var ex = Record.Exception(() => queue.EstimatePosition(TransferFor(uploads[username][0]))); + + Assert.IsType<SlskdException>(ex); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Throws_NotFoundException_If_Same_File_Is_Enqueued_Under_A_Different_Transfer(QueueStrategy strategy, string username, string filename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var transfer = CreateTransfer(username, filename); + queue.Enqueue(transfer); + + // same user and file, but a different transfer + var ex = Record.Exception(() => queue.EstimatePosition(CreateTransfer(username, filename))); + + Assert.IsType<NotFoundException>(ex); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_Position_Of_Matching_Transfer_When_Same_File_Is_Enqueued_Twice(QueueStrategy strategy, string username, string filename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, new List<Upload>() + { + new Upload() { Id = Guid.NewGuid(), Enqueued = Now, Username = username, Filename = filename }, + new Upload() { Id = Guid.NewGuid(), Enqueued = Now.AddSeconds(1), Username = username, Filename = filename }, + }); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(TransferFor(uploads[username][0]))); + Assert.Equal(1, queue.EstimatePosition(TransferFor(uploads[username][1]))); + } + + [Theory, AutoData] + public void RoundRobin_Returns_Local_Position_If_User_Is_Alone_In_Group(string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(TransferFor(uploads[username][0]))); + Assert.Equal(1, queue.EstimatePosition(TransferFor(uploads[username][1]))); + Assert.Equal(2, queue.EstimatePosition(TransferFor(uploads[username][2]))); + } + + [Theory, AutoData] + public void RoundRobin_First_File_Is_Behind_Every_Other_User_With_Queued_Files(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 10, offset: -100)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1, offset: -100)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + // pessimistic; both other users have a file in round 0, and are assumed to go first + Assert.Equal(2, queue.EstimatePosition(TransferFor(uploads[username][0]))); + } + + [Theory, AutoData] + public void RoundRobin_Adds_Lesser_Of_Local_Position_And_Upload_Count_For_Each_Other_User(string a, string b, string c, string d) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + // aaaaa + // bb + // cccccccccccc + // ddddddd + // ^ (local position 4) + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(a, CreateUploads(a, count: 5)); + uploads.TryAdd(b, CreateUploads(b, count: 2)); + uploads.TryAdd(c, CreateUploads(c, count: 12)); + uploads.TryAdd(d, CreateUploads(d, count: 7)); + + queue.SetProperty("UploadDictionary", uploads); + + // 4 (local) + min(4, 5) + min(4, 2) + min(4, 12), + 1 each for a and c, which have a file in round 4 + Assert.Equal(4 + 4 + 2 + 4 + 2, queue.EstimatePosition(TransferFor(uploads[d][4]))); + } + + [Theory] + [InlineAutoData(1, 3)] + [InlineAutoData(2, 4)] + [InlineAutoData(3, 5)] + [InlineAutoData(10, 5)] + public void RoundRobin_Counts_Other_User_As_Ahead_Only_If_They_Have_A_File_In_The_Same_Round(int otherCount, int expected, string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + // the requested file is at local position 2 (round 2). the other user contends for round 2 only if they + // have more than 2 files: 2 (local) + min(2, otherCount) + (otherCount > 2 ? 1 : 0) + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + uploads.TryAdd(other, CreateUploads(other, count: otherCount)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(expected, queue.EstimatePosition(TransferFor(uploads[username][2]))); + } + + [Theory, AutoData] + public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other, CreateUploads(other, count: 10)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(TransferFor(uploads[username][2]))); + } + + [Theory, AutoData] + public void FirstInFirstOut_Returns_Zero_If_Upload_Is_Earliest_In_Group(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 1)); + uploads.TryAdd(other, CreateUploads(other, count: 5, offset: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(TransferFor(uploads[username][0]))); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_All_Uploads_In_Group_Enqueued_Earlier(string a, string b, string c) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + // enqueued at: + // a: 0, 3, 6 + // b: 1, 4, 7 + // c: 2, 5, 8 + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(a, CreateUploads(a, count: 3, offset: 0, step: 3)); + uploads.TryAdd(b, CreateUploads(b, count: 3, offset: 1, step: 3)); + uploads.TryAdd(c, CreateUploads(c, count: 3, offset: 2, step: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(TransferFor(uploads[a][0]))); + Assert.Equal(4, queue.EstimatePosition(TransferFor(uploads[b][1]))); + Assert.Equal(8, queue.EstimatePosition(TransferFor(uploads[c][2]))); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + var started = CreateUploads(other, count: 2); + started.ForEach(u => u.Started = Now); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other, started); + uploads.TryAdd(username, CreateUploads(username, count: 1, offset: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(TransferFor(uploads[username][0]))); + } + + [Theory, AutoData] + public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other, CreateUploads(other, count: 10, offset: -100)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(TransferFor(uploads[username][2]))); + } + } + + public class ForecastPosition + { + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_Zero_If_Slot_Is_Available_Regardless_Of_Queue(QueueStrategy strategy, string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, true); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other, CreateUploads(other, count: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.ForecastPosition(username).Position); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_Zero_Without_Free_Slot_If_No_Slot_Is_Available_And_Queue_Is_Empty(QueueStrategy strategy, string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, false); + + var (_, _, freeSlots, position) = queue.ForecastPosition(username); + + // nothing is ahead, but the transfer can't start immediately; callers use FreeSlots to tell the difference + Assert.Equal(0, position); + Assert.Equal(0, freeSlots); + } + + [Theory, AutoData] + public void RoundRobin_Returns_Number_Of_Users_In_Group(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 10)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + // worst case; the new file is last in the rotation. file counts don't matter + Assert.Equal(2, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void RoundRobin_Counts_Requesting_User_Once_Regardless_Of_Their_Queued_Files(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 10)); + uploads.TryAdd(other, CreateUploads(other, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other1, string other2) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 1)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(1, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(username, CreateUploads(username, count: 2)); + uploads.TryAdd(other1, CreateUploads(other1, count: 3)); + uploads.TryAdd(other2, CreateUploads(other2, count: 4)); + + queue.SetProperty("UploadDictionary", uploads); + + // the new file goes to the back of the queue, behind every upload in the group, including the user's own + Assert.Equal(2 + 3 + 4, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + var started = CreateUploads(other, count: 2); + started.ForEach(u => u.Started = Now); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other, started); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other1, string other2) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 3)); + uploads.TryAdd(other2, CreateUploads(other2, count: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(3, queue.ForecastPosition(username).Position); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_Group_And_Slot_Counts_If_No_Slot_Is_Available(QueueStrategy strategy, string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, false); + + var (group, totalSlots, freeSlots, _) = queue.ForecastPosition(username); + + Assert.Equal(Application.DefaultGroup, group); + Assert.Equal(1, totalSlots); + Assert.Equal(0, freeSlots); + } + + [Theory, AutoData] + public void Returns_Group_And_Slot_Counts_If_Slot_Is_Available(string username) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 3; + FillSlots(groups[Application.DefaultGroup], 1); + + var (group, totalSlots, freeSlots, position) = queue.ForecastPosition(username); + + Assert.Equal(Application.DefaultGroup, group); + Assert.Equal(3, totalSlots); + Assert.Equal(2, freeSlots); + Assert.Equal(0, position); + } + + [Theory, AutoData] + public void Ignores_Slots_Used_By_Other_Groups(string username) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + var globalSlots = queue.GetProperty<int>("GlobalSlots"); + + // every global slot is held by the privileged group, but the default group's own slots are free + FillSlots(groups[Application.PrivilegedGroup], globalSlots); + groups[Application.DefaultGroup].Slots = 2; + + var (group, totalSlots, freeSlots, position) = queue.ForecastPosition(username); + + Assert.Equal(Application.DefaultGroup, group); + Assert.Equal(2, totalSlots); + Assert.Equal(2, freeSlots); + Assert.Equal(0, position); + } + + [Theory, AutoData] + public void Limits_Total_Slots_To_Global_Slots(string username) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + var globalSlots = queue.GetProperty<int>("GlobalSlots"); + + groups[Application.DefaultGroup].Slots = globalSlots + 10; + + var (_, totalSlots, freeSlots, _) = queue.ForecastPosition(username); + + Assert.Equal(globalSlots, totalSlots); + Assert.Equal(globalSlots, freeSlots); + } + + [Theory, AutoData] + public void Free_Slots_Is_Never_Negative(QueueStrategy strategy, string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + // the group holds more slots than it is allowed, for instance after its slot count was reduced at run time + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + FillSlots(groups[Application.DefaultGroup], 3); + + var (_, totalSlots, freeSlots, position) = queue.ForecastPosition(username); + + Assert.Equal(1, totalSlots); + Assert.Equal(0, freeSlots); + Assert.Equal(0, position); + } + + [Theory, AutoData] + public void Throws_SlskdException_If_Group_Does_Not_Exist(string username, string groupName) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(groupName); + + var ex = Record.Exception(() => queue.ForecastPosition(username)); + + Assert.IsType<SlskdException>(ex); + } } public class Process @@ -573,13 +1560,36 @@ namespace slskd.Tests.Unit.Transfers.Uploads var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); - groups[Application.DefaultGroup].UsedSlots = int.MaxValue; + FillSlots(groups[Application.DefaultGroup], queue.GetProperty<int>("GlobalSlots")); var result = queue.InvokeMethod<UploadGroup>("Process"); Assert.Null(result); } + [Theory, AutoData] + public void Does_Not_Release_Upload_If_Global_Slots_Are_Consumed_Across_Groups(string user1, string file1) + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + var globalSlots = queue.GetProperty<int>("GlobalSlots"); + + // split the global slots between two groups; neither group is full on its own + FillSlots(groups[Application.PrivilegedGroup], globalSlots - 1); + FillSlots(groups[Application.LeecherGroup], 1); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(user1, new List<Upload>() { new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); + + queue.SetProperty("UploadDictionary", uploads); + + var result = queue.InvokeMethod<Upload>("Process"); + + Assert.Null(result); + Assert.Empty(groups[Application.DefaultGroup].UsedSlots); + } + [Fact] public void Does_Nothing_If_No_Uploads() { @@ -601,7 +1611,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); queue.SetProperty("UploadDictionary", uploads); @@ -615,7 +1625,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] - public void Increments_UsedSlots_Of_Group(string user1, string file1) + public void Occupies_Slot_In_Group_Of_Released_Upload(string user1, string file1) { var (queue, mocks) = GetFixture(); @@ -625,7 +1635,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); queue.SetProperty("UploadDictionary", uploads); @@ -634,7 +1644,33 @@ namespace slskd.Tests.Unit.Transfers.Uploads var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); - Assert.Equal(1, groups[Application.PrivilegedGroup].UsedSlots); + Assert.Single(groups[Application.PrivilegedGroup].UsedSlots); + Assert.Contains(uploads[user1][0].Id, groups[Application.PrivilegedGroup].UsedSlots); + + // no other group is charged for the slot + Assert.All(groups.Values.Where(g => g.Name != Application.PrivilegedGroup), g => Assert.Empty(g.UsedSlots)); + } + + [Theory, AutoData] + public void Does_Not_Release_Upload_That_Already_Started(string user1, string file1) + { + var (queue, _) = GetFixture(); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow, Started = DateTime.UtcNow, Group = Application.DefaultGroup }, + }); + + queue.SetProperty("UploadDictionary", uploads); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].UsedSlots.Add(uploads[user1][0].Id); + + var result = queue.InvokeMethod<Upload>("Process"); + + Assert.Null(result); + Assert.Single(groups[Application.DefaultGroup].UsedSlots); } [Theory, AutoData] @@ -649,12 +1685,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); uploads.TryAdd(user2, new List<Upload>() { - new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user2, Filename = file2, Ready = DateTime.UtcNow } }); queue.SetProperty("UploadDictionary", uploads); @@ -663,6 +1699,11 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(user1, result.Username); Assert.Equal(file1, result.Filename); + + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + + Assert.Contains(uploads[user1][0].Id, groups[Application.PrivilegedGroup].UsedSlots); + Assert.Empty(groups[Application.DefaultGroup].UsedSlots); } [Theory, AutoData] @@ -678,12 +1719,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user1, Filename = file1, Ready = DateTime.UtcNow } }); uploads.TryAdd(user2, new List<Upload>() { - new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } + new Upload() { Id = Guid.NewGuid(), Enqueued = DateTime.UtcNow, Username = user2, Filename = file2, Ready = DateTime.UtcNow } }); queue.SetProperty("UploadDictionary", uploads); @@ -691,13 +1732,16 @@ namespace slskd.Tests.Unit.Transfers.Uploads // all default group slots consumed var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); groups[Application.DefaultGroup].Slots = 1; - groups[Application.DefaultGroup].UsedSlots = 1; + FillSlots(groups[Application.DefaultGroup], 1); var result = queue.InvokeMethod<Upload>("Process"); // leecher group upload released Assert.Equal(user2, result.Username); Assert.Equal(file2, result.Filename); + + Assert.Contains(uploads[user2][0].Id, groups[Application.LeecherGroup].UsedSlots); + Assert.DoesNotContain(uploads[user1][0].Id, groups[Application.DefaultGroup].UsedSlots); } [Theory, AutoData] @@ -713,12 +1757,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Enqueued = enqueued.AddHours(-1), Ready = ready } + new Upload() { Id = Guid.NewGuid(), Username = user1, Filename = file1, Enqueued = enqueued.AddHours(-1), Ready = ready } }); uploads.TryAdd(user2, new List<Upload>() { - new Upload() { Username = user2, Filename = file2, Enqueued = enqueued.AddHours(-2), Ready = ready } + new Upload() { Id = Guid.NewGuid(), Username = user2, Filename = file2, Enqueued = enqueued.AddHours(-2), Ready = ready } }); queue.SetProperty("UploadDictionary", uploads); @@ -745,12 +1789,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads uploads.TryAdd(user1, new List<Upload>() { - new Upload() { Username = user1, Filename = file1, Enqueued = enqueued, Ready = ready } + new Upload() { Id = Guid.NewGuid(), Username = user1, Filename = file1, Enqueued = enqueued, Ready = ready } }); uploads.TryAdd(user2, new List<Upload>() { - new Upload() { Username = user2, Filename = file2, Enqueued = enqueued, Ready = ready.AddMinutes(-1) } + new Upload() { Id = Guid.NewGuid(), Username = user2, Filename = file2, Enqueued = enqueued, Ready = ready.AddMinutes(-1) } }); queue.SetProperty("UploadDictionary", uploads); @@ -765,6 +1809,64 @@ namespace slskd.Tests.Unit.Transfers.Uploads } } + private static readonly DateTime Now = DateTime.UtcNow; + + private static void SetStrategy(UploadQueue queue, QueueStrategy strategy) + { + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Strategy = strategy; + } + + private static void SetSlotAvailable(UploadQueue queue, bool available) + { + var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + groups[Application.DefaultGroup].UsedSlots.Clear(); + FillSlots(groups[Application.DefaultGroup], available ? 0 : 1); + } + + // creates a transfer that matches an upload already in the queue + private static Transfer TransferFor(Upload upload) + => new() + { + Id = upload.Id, + Username = upload.Username, + Filename = upload.Filename, + Direction = Soulseek.TransferDirection.Upload, + }; + + private static Transfer CreateTransfer(string username, string filename) + => new() + { + Id = Guid.NewGuid(), + Username = username, + Filename = filename, + Direction = Soulseek.TransferDirection.Upload, + }; + + // occupies the specified number of slots in the group with placeholder uploads + private static void FillSlots(UploadGroup group, int count) + { + for (int i = 0; i < count; i++) + { + group.UsedSlots.Add(Guid.NewGuid()); + } + } + + // creates uploads named file0..fileN, enqueued at Now + offset + (i * step) seconds, in ascending order + private static List<Upload> CreateUploads(string username, int count, int offset = 0, int step = 1) + { + return Enumerable.Range(0, count) + .Select(i => new Upload() + { + Id = Guid.NewGuid(), + Username = username, + Filename = $"file{i}", + Enqueued = Now.AddSeconds(offset + (i * step)), + }) + .ToList(); + } + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj index caf8e3c3..f6e4909a 100644 --- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj +++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj @@ -14,14 +14,14 @@ <ItemGroup>
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.7.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="xunit" Version="2.9.3" />
- <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
+ <PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="coverlet.msbuild" Version="10.0.1">
+ <PackageReference Include="coverlet.msbuild" Version="10.1.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
|
