diff options
22 files changed, 1333 insertions, 152 deletions
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' diff --git a/config/slskd.example.yml b/config/slskd.example.yml index af2871e2..86b7b17f 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -195,7 +195,7 @@ # circuit_breaker: 500 # maximum number of pending search requests # response_file_limit: 500 # maximum number of files to return in a single search response # logger: -# disk: false +# no_disk: false # no_color: false # loki: ~ # metrics: diff --git a/docs/config.md b/docs/config.md index 0202d89b..2c21d12b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1342,7 +1342,7 @@ Console colors can be disabled via typical application configuration described b | 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. 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..8de4fe53 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1257,28 +1257,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) { 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/Core/Options.cs b/src/slskd/Core/Options.cs index d1062a2c..13a24eed 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1458,11 +1458,11 @@ namespace slskd /// <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 +1500,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(7, maximum: int.MaxValue)] + public int Logs { get; init; } = 30; /// <summary> /// Transfer retention options. diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..8450ba48 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -67,42 +67,19 @@ namespace slskd.Files 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 @@ -130,24 +107,66 @@ namespace slskd.Files } 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) { - 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}'"); + Log.Error("Resolved FileInfo for linked file '{File}->{Link}' was unexpectedly null", info.Name, info.LinkTarget); + throw new IOException($"An unexpected error was encountered while resolving FileInfo for linked file '{info.Name}->{info.LinkTarget}'"); } return info; } /// <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) + { + 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 ResolveFileInfo(info); + } + + /// <summary> /// Deletes the specified <paramref name="directories"/>. /// </summary> /// <remarks> 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 5260760f..b1f57ce4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -512,7 +512,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); } @@ -1067,12 +1067,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 @@ -1242,7 +1247,7 @@ 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}", 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..98a3f092 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) { diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index ed594209..6d84308a 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> 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/web/package-lock.json b/src/web/package-lock.json index f57c0923..11dafd7a 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.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz", - "integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==", + "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": { @@ -6551,9 +6554,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": [ { @@ -6571,11 +6574,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" @@ -6744,9 +6747,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": [ { @@ -8413,9 +8416,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" }, @@ -10890,9 +10893,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", + "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", "dev": true, "funding": [ { @@ -14310,9 +14313,9 @@ } }, "node_modules/js-yaml": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", - "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "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": [ { @@ -15253,9 +15256,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": [ { @@ -15263,6 +15266,7 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -15371,11 +15375,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", @@ -19960,9 +19967,9 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.15.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz", - "integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==", + "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": { @@ -20796,9 +20803,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/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/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..580612e4 --- /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.4" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.7.0" /> + <PackageReference Include="Moq" Version="4.16.1" /> + <PackageReference Include="xunit" Version="2.9.3" /> + <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5"> + <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> + <PrivateAssets>all</PrivateAssets> + </PackageReference> + <PackageReference Include="coverlet.msbuild" Version="10.0.1"> + <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)); + } + } + } +} |
