1 /*
2 * Copyright (c) 2002-2026 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.util;
16
17 /**
18 * File utility class for functions not covered by third-party libraries.
19 *
20 * @author Ronald Brill
21 */
22 public final class FileUtils {
23
24 /** Characters not allowed in file names on at least one platform (control characters aside). */
25 private static final String INVALID_FILENAME_CHARS = "\\/:*?\"<>|";
26
27 /**
28 * Disallow instantiation of this class.
29 */
30 private FileUtils() {
31 // Empty.
32 }
33
34 /**
35 * Makes the given name usable as the name of a file, the way the browsers do it
36 * for downloaded files.
37 * <ul>
38 * <li>Characters that are not allowed in file names on at least one platform
39 * ({@code \ / : * ? " < > |}), the control characters (U+0000 - U+001F) and DEL (U+007F)
40 * are replaced by an underscore. Because the path separators are replaced, the result is always
41 * a plain file name; e.g. {@code ../../evil.txt} becomes {@code _.._evil.txt}, so the name
42 * can be resolved against a folder without leaving it.</li>
43 * <li>Leading dots and white space (no hidden files) and trailing dots and white space
44 * are removed.</li>
45 * </ul>
46 * <p>The name is not checked any further; e.g. names reserved by Windows (like {@code CON} or
47 * {@code NUL}) and the maximum length of a file name are not taken into account.</p>
48 *
49 * @param name the name to sanitize, can be {@code null}
50 * @return the sanitized name or {@code null} if the name is {@code null} or nothing is left
51 */
52 public static String sanitizeFilename(final String name) {
53 if (name == null) {
54 return null;
55 }
56
57 final StringBuilder sb = new StringBuilder(name.length());
58 for (int i = 0; i < name.length(); i++) {
59 final char c = name.charAt(i);
60 if (c < ' ' || c == 127 || INVALID_FILENAME_CHARS.indexOf(c) >= 0) {
61 sb.append('_');
62 }
63 else {
64 sb.append(c);
65 }
66 }
67
68 int start = 0;
69 int end = sb.length();
70 while (start < end && isTrimmed(sb.charAt(start))) {
71 start++;
72 }
73 while (end > start && isTrimmed(sb.charAt(end - 1))) {
74 end--;
75 }
76 return start == end ? null : sb.substring(start, end);
77 }
78
79 private static boolean isTrimmed(final char c) {
80 return c == '.' || Character.isWhitespace(c);
81 }
82 }