aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-06-07 14:45:04 -0500
committerGitHub <noreply@github.com>2026-06-07 14:45:04 -0500
commitb747b68ba0ba777be578e73bd1328fbde940e436 (patch)
tree160d23aeb8707dc04f81bb52e81913c1b77bb2a4 /src/slskd/Common
parente06999e5eec1616d93b34ffbab0eade617d1aaf6 (diff)
parent2d069bbf1f71f38e1286e27d45c24b478feb11ac (diff)
downloadslskd-b747b68ba0ba777be578e73bd1328fbde940e436.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/launch-editor-2.14.1
Diffstat (limited to 'src/slskd/Common')
-rw-r--r--src/slskd/Common/CommonExtensions.cs74
-rw-r--r--src/slskd/Common/Compute.cs18
-rw-r--r--src/slskd/Common/Dumper.cs8
-rw-r--r--src/slskd/Common/FileSafety.cs93
-rw-r--r--src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs2
-rw-r--r--src/slskd/Common/OperatingSystem.cs43
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs28
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs32
8 files changed, 143 insertions, 155 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 5ff3e519..95721163 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -382,21 +382,6 @@ namespace slskd
.Deserialize<T>(str);
/// <summary>
- /// Converts a fully qualified remote filename to a local filename based in the provided
- /// <paramref name="baseDirectory"/>, swapping directory characters for those specific to the local OS, removing any
- /// characters that are invalid for the local OS, and making the path relative to the remote store (including the
- /// filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <param name="baseDirectory">The base directory for the local filename.</param>
- /// <returns>The converted filename.</returns>
- [Obsolete("Find something more intelligent to do instead of this")]
- public static string ToLocalFilename(this string remoteFilename, string baseDirectory)
- {
- return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename());
- }
-
- /// <summary>
/// Converts the given path to the normalized format (normalizes path separators to backslashes).
/// </summary>
/// <remarks>
@@ -410,16 +395,6 @@ namespace slskd
}
/// <summary>
- /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar).
- /// </summary>
- /// <param name="path">The path to convert.</param>
- /// <returns>The converted path.</returns>
- public static string LocalizePath(this string path)
- {
- return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
- }
-
- /// <summary>
/// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
@@ -440,55 +415,6 @@ namespace slskd
}
/// <summary>
- /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific
- /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the
- /// remote store (including the filename and the parent folder).
- /// </summary>
- /// <param name="remoteFilename">The fully qualified remote filename to convert.</param>
- /// <returns>The converted filename.</returns>
- [Obsolete("Find something more intelligent to do instead of this")]
- public static string ToLocalRelativeFilename(this string remoteFilename)
- {
- if (string.IsNullOrWhiteSpace(remoteFilename))
- {
- throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename));
- }
-
- // normalize path separators
- var localizedRemoteFilename = remoteFilename.LocalizePath();
-
- var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar);
-
- if (parts.Length == 1)
- {
- return parts.First().ReplaceInvalidFileNameCharacters();
- }
-
- var file = parts.Last().ReplaceInvalidFileNameCharacters();
- var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters();
-
- return FileSafety.CombineSafely(directory, file);
- }
-
- /// <summary>
- /// Replaces any occurrence of an invalid filename character with the specified <see paramref="replacement"/>.
- /// </summary>
- /// <param name="path">The path to sanitize.</param>
- /// <param name="replacement">The character with which to replace invalid characters.</param>
- /// <returns>The sanitized path.</returns>
- public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_')
- {
- var sanitized = path;
-
- foreach (var c in Path.GetInvalidFileNameChars())
- {
- sanitized = sanitized.Replace(c, replacement);
- }
-
- return sanitized;
- }
-
- /// <summary>
/// Converts a ModelStateDictionary into a human-readable format.
/// </summary>
/// <param name="dictionary">The ModelStateDictionary to format.</param>
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
index dc565806..d235a87c 100644
--- a/src/slskd/Common/Compute.cs
+++ b/src/slskd/Common/Compute.cs
@@ -66,24 +66,14 @@ namespace slskd
return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
}
- public static OSPlatform OSPlatform()
+ public static OperatingSystem OperatingSystem()
{
- if (OperatingSystem.IsWindows())
+ if (System.OperatingSystem.IsWindows())
{
- return System.Runtime.InteropServices.OSPlatform.Windows;
+ return slskd.OperatingSystem.Windows;
}
- if (OperatingSystem.IsMacOS())
- {
- return System.Runtime.InteropServices.OSPlatform.OSX;
- }
-
- if (OperatingSystem.IsFreeBSD())
- {
- return System.Runtime.InteropServices.OSPlatform.FreeBSD;
- }
-
- return System.Runtime.InteropServices.OSPlatform.Linux;
+ return slskd.OperatingSystem.Linux;
}
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs
index f4367e61..27304873 100644
--- a/src/slskd/Common/Dumper.cs
+++ b/src/slskd/Common/Dumper.cs
@@ -84,7 +84,7 @@ namespace slskd
await Download(url, BinFile);
- if (!OperatingSystem.IsWindows())
+ if (!System.OperatingSystem.IsWindows())
{
await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\"");
}
@@ -139,15 +139,15 @@ namespace slskd
string os = default;
// seems like there should be a way to just retrieve this, but there is not as of .NET 6
- if (OperatingSystem.IsLinux())
+ if (System.OperatingSystem.IsLinux())
{
os = "linux";
}
- else if (OperatingSystem.IsWindows())
+ else if (System.OperatingSystem.IsWindows())
{
os = "win";
}
- else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
+ else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD())
{
os = "osx";
}
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
index 5a5d964e..6a6dea22 100644
--- a/src/slskd/Common/FileSafety.cs
+++ b/src/slskd/Common/FileSafety.cs
@@ -35,7 +35,6 @@ namespace slskd;
using System;
using System.IO;
using System.Linq;
-using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
/// <summary>
@@ -85,7 +84,7 @@ public static class FileSafety
/// <returns>The combined path.</returns>
/// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception>
/// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception>
- public static string CombineSafely(string root, OSPlatform? os, params string[] segments)
+ public static string CombineSafely(string root, OperatingSystem? os, params string[] segments)
{
// ensure no inputs are null. matches the behavior of Path.Combine()
if (string.IsNullOrWhiteSpace(root))
@@ -103,13 +102,21 @@ public static class FileSafety
throw new ArgumentNullException(nameof(segments), $"One or more segments is null");
}
- var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows();
+ root = root.TrimEnd('/', '\\');
+
+ if (segments.Length == 0)
+ {
+ return root;
+ }
+
+ var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows();
+ var sep = isWindows ? '\\' : '/';
foreach (var segment in segments)
{
- // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment
- // and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc"
- // not what we want!
+ // disallow any segments that:
+ // windows: are drive letter (C:\) or UNC path (\\)
+ // linux: begin with a forward slash (any number, covering both local and UNC paths)
if (IsPathAbsolute(segment, os))
{
throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'");
@@ -134,17 +141,26 @@ public static class FileSafety
// ensure the segments we're combining don't contain traversal segments "." or ".."
// untrusted input could use this to "break out" of the root directory and access sensitive areas
+ // this covers cases where the entire segment is . or .., or foo\..\bar, or \.. or ..\ or \..\
if (parts.Any(s => s is "." or ".."))
{
throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'");
}
}
- var combined = Path.Combine(root, Path.Combine(segments));
+ segments = [.. segments
+ .Where(s => !string.IsNullOrEmpty(s))];
+
+ var combined = string.Join(sep, [root, .. segments]);
+
+ if (combined.TrimEnd('/', '\\') == root.TrimEnd('/', '\\'))
+ {
+ return combined;
+ }
// this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting
// path is actually rooted in the root we provided; if not the input was successful in traversal
- if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root)))
+ if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\"))
{
throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed");
}
@@ -170,14 +186,14 @@ public static class FileSafety
/// <param name="path">The path to check.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>True if the path is absolute, false otherwise.</returns>
- public static bool IsPathAbsolute(string path, OSPlatform? os = null)
+ public static bool IsPathAbsolute(string path, OperatingSystem? os = null)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
- if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows())
+ if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows())
{
// Windows drive-letter path: X:\ or X:/
// X:foo is relative on windows
@@ -214,7 +230,7 @@ public static class FileSafety
/// <param name="path">The path to check.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>True if the path is relative, false otherwise.</returns>
- public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os);
+ public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os);
/// <summary>
/// Returns the filename from the specified <paramref name="path"/>, properly
@@ -224,7 +240,7 @@ public static class FileSafety
/// <param name="sanitize">An optional value indicating that invalid characters should not be replaced.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The extracted filename.</returns>
- public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null)
+ public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null)
{
if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\'))
{
@@ -256,7 +272,7 @@ public static class FileSafety
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The directory name.</returns>
/// <exception cref="ArgumentNullException">Thrown if the specified path is null.</exception>
- public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null)
+ public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null)
{
if (path is null or "")
{
@@ -271,8 +287,8 @@ public static class FileSafety
var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count();
- os ??= Compute.OSPlatform();
- var sep = os.Value == OSPlatform.Windows ? '\\' : '/';
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
var local = LocalizePath(path, os)
.TrimEnd('/', '\\'); // treat file-less paths the same as files
@@ -322,15 +338,15 @@ public static class FileSafety
/// <param name="path">The path to convert.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The converted path.</returns>
- public static string LocalizePath(string path, OSPlatform? os = null)
+ public static string LocalizePath(string path, OperatingSystem? os = null)
{
if (path is null)
{
return null;
}
- os ??= Compute.OSPlatform();
- var sep = os.Value == OSPlatform.Windows ? '\\' : '/';
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
return path.Replace('\\', sep).Replace('/', sep);
}
@@ -344,7 +360,7 @@ public static class FileSafety
/// <param name="replacement">The character to substitute for invalid characters.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The sanitized filename.</returns>
- public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null)
+ public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null)
{
if (filename is null)
{
@@ -356,9 +372,9 @@ public static class FileSafety
throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames");
}
- os ??= Compute.OSPlatform();
+ os ??= Compute.OperatingSystem();
- var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix;
+ var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix;
if (characters.Contains(replacement))
{
@@ -388,7 +404,7 @@ public static class FileSafety
/// <param name="replacement">The character to substitute for invalid characters.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The sanitized path segment.</returns>
- public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null)
+ public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null)
{
var sanitized = SanitizeFilename(segment, replacement, os);
@@ -413,49 +429,36 @@ public static class FileSafety
/// <summary>
/// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system
- /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with
- /// the specified <paramref name="replacement"/>, and by dropping any path traversal segments.
+ /// by converting to the correct slashes, replacing any invalid characters with the specified
+ /// <paramref name="replacement"/>, and by dropping any path traversal segments.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="replacement">The character to substitute for invalid characters.</param>
- /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The sanitized path.</returns>
- public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null)
+ public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null)
{
if (path is null)
{
return null;
}
- var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count();
-
- os ??= Compute.OSPlatform();
- var sep = os.Value == OSPlatform.Windows ? '\\' : '/';
+ os ??= Compute.OperatingSystem();
+ var sep = os.Value == OperatingSystem.Windows ? '\\' : '/';
// flip slashes the correct way
path = LocalizePath(path, os);
- if (!retainRoot)
- {
- // strip C:\ or //server, if present (regardless of slash variant, etc)
- path = StripPathRoot(path, os);
- }
-
- // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings
+ // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings,
+ // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement)
var segments = path
.Split('/', '\\')
.Where(s => s is not "")
- .Select(s => SanitizePathSegment(s, replacement, os));
+ .Select(s => SanitizePathSegment(s, replacement, os))
+ .Where(s => s is not "");
var newPath = string.Join(sep, segments);
- if (retainRoot)
- {
- // leading slashes are stripped of leading slashes by Split() so we must add them back
- return new string(sep, leadingSlashCount) + newPath;
- }
-
return newPath;
}
@@ -467,7 +470,7 @@ public static class FileSafety
/// <param name="path">The path to strip.</param>
/// <param name="os">An optional operating system override, for testing.</param>
/// <returns>The path with the root stripped, if one was present.</returns>
- public static string StripPathRoot(string path, OSPlatform? os = null)
+ public static string StripPathRoot(string path, OperatingSystem? os = null)
{
if (path is null)
{
diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
index a7e7e0dc..760f7ba9 100644
--- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
+++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs
@@ -36,7 +36,7 @@ using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
-using Microsoft.OpenApi.Models;
+using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
/// <summary>
diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs
new file mode 100644
index 00000000..0c3dae2c
--- /dev/null
+++ b/src/slskd/Common/OperatingSystem.cs
@@ -0,0 +1,43 @@
+// <copyright file="OperatingSystem.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;
+
+public enum OperatingSystem
+{
+ None = 0,
+ Linux = 1,
+ Windows = 2,
+ Current = 3,
+ Any = 4,
+ All = 5,
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
index eb1c9069..217a4eea 100644
--- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -33,23 +33,24 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.Runtime.InteropServices;
/// <summary>
/// Validates that the specified path is absolute.
/// </summary>
public class AbsolutePathAttribute : ValidationAttribute
{
- public AbsolutePathAttribute()
+ public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current)
{
- }
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
- public AbsolutePathAttribute(OSPlatform? os = null)
- {
OS = os;
}
- public OSPlatform? OS { get; }
+ public OperatingSystem OS { get; }
+ private OperatingSystem? Injected { get; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
@@ -57,9 +58,20 @@ namespace slskd.Validation
{
var path = value.ToString();
- if (!FileSafety.IsPathAbsolute(path, os: OS))
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any
+ if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems.");
}
}
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
index f465ba98..ea2b627b 100644
--- a/src/slskd/Common/Validation/RelativePathAttribute.cs
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -33,36 +33,50 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.Runtime.InteropServices;
/// <summary>
/// Validates that the specified path is relative.
/// </summary>
public class RelativePathAttribute : ValidationAttribute
{
- public RelativePathAttribute()
+ public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current)
{
- }
+ if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All)
+ {
+ throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os));
+ }
- public RelativePathAttribute(OSPlatform? os = null)
- {
OS = os;
}
- public OSPlatform? OS { get; }
+ public OperatingSystem OS { get; }
+
+ private OperatingSystem? Injected { get; }
+
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null && value is string str && !string.IsNullOrEmpty(str))
{
var path = value.ToString();
- if (!FileSafety.IsPathRelative(path, os: OS))
+ if (OS == OperatingSystem.Current)
+ {
+ if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem()))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system.");
+ }
+
+ return ValidationResult.Success;
+ }
+
+ // OS == OperatingSystem.All or .Any;
+ if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems.");
}
}
return ValidationResult.Success;
}
}
-}
+} \ No newline at end of file