From 012b429f11d6c0247fa90a74c0367a112d45a84c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:00:35 -0500 Subject: add SanitizePathSegment --- src/slskd/Common/FileSafety.cs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a175ebbd..7e8c3516 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,15 +323,32 @@ public static class FileSafety /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified /// . /// - /// - /// This is an overload for that exists to improve understanding of intent at the - /// call site. - /// /// The path segment. /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) => SanitizeFilename(segment, replacement, os); + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } /// /// Sanitizes the specified to make it suitable and safe on the local operating system -- cgit v1.2.3