Skip to content

Commit c97a895

Browse files
committed
Add support for double backslashes to StringUtils#cleanPath
Closes gh-32962
1 parent 3b13f2e commit c97a895

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

spring-core/src/main/java/org/springframework/util/StringUtils.java

+13-2
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
* @author Arjen Poutsma
5959
* @author Sam Brannen
6060
* @author Brian Clozel
61+
* @author Sebastien Deleuze
6162
* @since 16 April 2001
6263
*/
6364
public abstract class StringUtils {
@@ -70,6 +71,8 @@ public abstract class StringUtils {
7071

7172
private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
7273

74+
private static final String DOUBLE_BACKLASHES = "\\\\";
75+
7376
private static final String TOP_PATH = "..";
7477

7578
private static final String CURRENT_PATH = ".";
@@ -690,7 +693,7 @@ public static String applyRelativePath(String path, String relativePath) {
690693
* Normalize the path by suppressing sequences like "path/.." and
691694
* inner simple dots.
692695
* <p>The result is convenient for path comparison. For other uses,
693-
* notice that Windows separators ("\") are replaced by simple slashes.
696+
* notice that Windows separators ("\" and "\\") are replaced by simple slashes.
694697
* <p><strong>NOTE</strong> that {@code cleanPath} should not be depended
695698
* upon in a security context. Other mechanisms should be used to prevent
696699
* path-traversal issues.
@@ -702,7 +705,15 @@ public static String cleanPath(String path) {
702705
return path;
703706
}
704707

705-
String normalizedPath = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
708+
String normalizedPath;
709+
// Optimize when there is no backslash
710+
if (path.indexOf('\\') != -1) {
711+
normalizedPath = replace(path, DOUBLE_BACKLASHES, FOLDER_SEPARATOR);
712+
normalizedPath = replace(normalizedPath, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
713+
}
714+
else {
715+
normalizedPath = path;
716+
}
706717
String pathToUse = normalizedPath;
707718

708719
// Shortcut if there is no work to do

spring-core/src/test/java/org/springframework/util/StringUtilsTests.java

+1
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@ void cleanPath() {
419419
assertThat(StringUtils.cleanPath("file:///c:/some/../path/the%20file.txt")).isEqualTo("file:///c:/path/the%20file.txt");
420420
assertThat(StringUtils.cleanPath("jar:file:///c:\\some\\..\\path\\.\\the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt");
421421
assertThat(StringUtils.cleanPath("jar:file:///c:/some/../path/./the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt");
422+
assertThat(StringUtils.cleanPath("jar:file:///c:\\\\some\\\\..\\\\path\\\\.\\\\the%20file.txt")).isEqualTo("jar:file:///c:/path/the%20file.txt");
422423
}
423424

424425
@Test

0 commit comments

Comments
 (0)