New: Improve path validation when handling paths from different OSes

(cherry picked from commit 0321368cc392d7a0a488409bf6bd586ba45497af)

Closes #2309
This commit is contained in:
Mark McDowall
2023-03-23 17:34:19 -07:00
committed by Bogdan
parent a4930474a5
commit b3cf903a3b
16 changed files with 94 additions and 72 deletions
@@ -31,7 +31,7 @@ namespace NzbDrone.Common.Extensions
public static string CleanFilePath(this string path)
{
Ensure.That(path, () => path).IsNotNullOrWhiteSpace();
Ensure.That(path, () => path).IsValidPath();
Ensure.That(path, () => path).IsValidPath(PathValidationType.AnyOs);
var info = new FileInfo(path.Trim());
return info.FullName.CleanFilePathBasic();
@@ -40,7 +40,7 @@ namespace NzbDrone.Common.Extensions
public static string CleanFilePathBasic(this string path)
{
//UNC
if (OsInfo.IsWindows && path.StartsWith(@"\\"))
if (!path.Contains('/') && path.StartsWith(@"\\"))
{
return path.TrimEnd('/', '\\', ' ');
}
@@ -138,24 +138,24 @@ namespace NzbDrone.Common.Extensions
private static readonly Regex WindowsPathWithDriveRegex = new Regex(@"^[a-zA-Z]:\\", RegexOptions.Compiled);
public static bool IsPathValid(this string path)
public static bool IsPathValid(this string path, PathValidationType validationType)
{
if (path.ContainsInvalidPathChars() || string.IsNullOrWhiteSpace(path))
{
return false;
}
if (validationType == PathValidationType.AnyOs)
{
return IsPathValidForWindows(path) || IsPathValidForNonWindows(path);
}
if (OsInfo.IsNotWindows)
{
return path.StartsWith(Path.DirectorySeparatorChar.ToString());
return IsPathValidForNonWindows(path);
}
if (path.StartsWith("\\") || WindowsPathWithDriveRegex.IsMatch(path))
{
return true;
}
return false;
return IsPathValidForWindows(path);
}
public static bool ContainsInvalidPathChars(this string text)
@@ -371,5 +371,15 @@ namespace NzbDrone.Common.Extensions
{
return Path.Combine(appFolderInfo.StartUpFolder, NLOG_CONFIG_FILE);
}
private static bool IsPathValidForWindows(string path)
{
return path.StartsWith("\\") || WindowsPathWithDriveRegex.IsMatch(path);
}
private static bool IsPathValidForNonWindows(string path)
{
return path.StartsWith("/");
}
}
}