diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-30 16:00:35 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-05-30 16:00:35 -0500 |
| commit | 012b429f11d6c0247fa90a74c0367a112d45a84c (patch) | |
| tree | 5902f6e96a8a2b8250362680106a3ad6da8938f9 /src/slskd/Common | |
| parent | 062d282403cc03c3fdd4101742647be6a83d0329 (diff) | |
| download | slskd-012b429f11d6c0247fa90a74c0367a112d45a84c.tar.gz | |
add SanitizePathSegment
Diffstat (limited to 'src/slskd/Common')
| -rw-r--r-- | src/slskd/Common/FileSafety.cs | 27 |
1 files changed, 22 insertions, 5 deletions
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 /// <paramref name="replacement"/>. /// </summary> - /// <remarks> - /// This is an overload for <see cref="SanitizeFilename"/> that exists to improve understanding of intent at the - /// call site. - /// </remarks> /// <param name="segment">The path segment.</param> /// <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) => 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; + } /// <summary> /// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system |
