1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 // File utilities that use the ICU library go in this file.
11
12 #include "base/i18n/file_util_icu.h"
13
14 #include <stdint.h>
15
16 #include "base/check.h"
17 #include "base/files/file_path.h"
18 #include "base/i18n/icu_string_conversions.h"
19 #include "base/i18n/string_compare.h"
20 #include "base/memory/singleton.h"
21 #include "base/numerics/safe_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/sys_string_conversions.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "build/build_config.h"
26 #include "build/chromeos_buildflags.h"
27 #include "third_party/icu/source/common/unicode/uniset.h"
28 #include "third_party/icu/source/i18n/unicode/coll.h"
29
30 namespace base {
31 namespace i18n {
32
33 namespace {
34
35 class IllegalCharacters {
36 public:
37 IllegalCharacters(const IllegalCharacters&) = delete;
38 IllegalCharacters& operator=(const IllegalCharacters&) = delete;
39
GetInstance()40 static IllegalCharacters* GetInstance() {
41 return Singleton<IllegalCharacters>::get();
42 }
43
IsDisallowedEverywhere(UChar32 ucs4) const44 bool IsDisallowedEverywhere(UChar32 ucs4) const {
45 return !!illegal_anywhere_.contains(ucs4);
46 }
47
IsDisallowedLeadingOrTrailing(UChar32 ucs4) const48 bool IsDisallowedLeadingOrTrailing(UChar32 ucs4) const {
49 return !!illegal_at_ends_.contains(ucs4);
50 }
51
52 #if BUILDFLAG(IS_WIN)
IsDisallowedShortNameCharacter(UChar32 ucs4) const53 bool IsDisallowedShortNameCharacter(UChar32 ucs4) const {
54 return !!illegal_in_short_filenames_.contains(ucs4);
55 }
56
IsDisallowedIfMayBeShortName(UChar32 ucs4) const57 bool IsDisallowedIfMayBeShortName(UChar32 ucs4) const {
58 return !!required_to_be_a_short_filename_.contains(ucs4);
59 }
60
61 template <typename StringT>
HasValidDotPositionForShortName(const StringT & s) const62 bool HasValidDotPositionForShortName(const StringT& s) const {
63 auto first_dot = s.find_first_of('.');
64 // Short names are not required to have a "." period character...
65 if (first_dot == std::string::npos) {
66 return s.size() <= 8;
67 }
68 // ...but they must not contain more than one "." period character...
69 if (first_dot != s.find_last_of('.')) {
70 return false;
71 }
72 // ... and must contain a basename of 1-8 characters, optionally with one
73 // "." period character followed by an extension no more than 3 characters
74 // in length.
75 return first_dot > 0 && first_dot <= 8 && first_dot + 4 >= s.size();
76 }
77
78 // Returns whether `s` could possibly be in the 8.3 name format AND contains a
79 // '~' character, which may interact poorly with short filenames on VFAT. See
80 // https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/09c2ccc8-4aaf-439f-9b4e-13b3fe85a4cf.
CouldBeInvalidShortName(const std::u16string & s) const81 bool CouldBeInvalidShortName(const std::u16string& s) const {
82 if (s.size() > 12 ||
83 !required_to_be_a_short_filename_.containsSome(icu::UnicodeString(
84 /*isTerminated=*/false, s.c_str(), s.size())) ||
85 !illegal_in_short_filenames_.containsNone(
86 icu::UnicodeString(/*isTerminated=*/false, s.c_str(), s.size()))) {
87 return false;
88 }
89 return HasValidDotPositionForShortName<std::u16string>(s);
90 }
91 #endif
92
IsAllowedName(const std::u16string & s) const93 bool IsAllowedName(const std::u16string& s) const {
94 return s.empty() || (!!illegal_anywhere_.containsNone(icu::UnicodeString(
95 /*isTerminated=*/false, s.c_str(), s.size())) &&
96 !illegal_at_ends_.contains(*s.begin()) &&
97 !illegal_at_ends_.contains(*s.rbegin())
98 #if BUILDFLAG(IS_WIN)
99 && !CouldBeInvalidShortName(s)
100 #endif
101 );
102 }
103
104 private:
105 friend struct DefaultSingletonTraits<IllegalCharacters>;
106
107 IllegalCharacters();
108 ~IllegalCharacters() = default;
109
110 // Set of characters considered invalid anywhere inside a filename.
111 icu::UnicodeSet illegal_anywhere_;
112
113 // Set of characters considered invalid at either end of a filename.
114 icu::UnicodeSet illegal_at_ends_;
115
116 // #if BUILDFLAG(IS_WIN)
117 // Set of characters which are guaranteed to exist if the filename is to be of
118 // the problematic VFAT 8.3 short filename format.
119 icu::UnicodeSet required_to_be_a_short_filename_;
120 // Set of characters which are not allowed in VFAT 8.3 short filenames. If
121 // any of these characters are present, the file cannot be a short filename.
122 icu::UnicodeSet illegal_in_short_filenames_;
123 // #endif
124 };
125
IllegalCharacters()126 IllegalCharacters::IllegalCharacters() {
127 UErrorCode status = U_ZERO_ERROR;
128 // Control characters, formatting characters, non-characters, path separators,
129 // and some printable ASCII characters regarded as dangerous ('"*/:<>?\\').
130 // See http://blogs.msdn.com/michkap/archive/2006/11/03/941420.aspx
131 // and http://msdn2.microsoft.com/en-us/library/Aa365247.aspx
132 // Note that code points in the "Other, Format" (Cf) category are ignored on
133 // HFS+ despite the ZERO_WIDTH_JOINER and ZERO_WIDTH_NON-JOINER being
134 // legitimate in Arabic and some S/SE Asian scripts. In addition tilde (~) is
135 // also excluded in some circumstances due to the possibility of interacting
136 // poorly with short filenames on VFAT. (Related to CVE-2014-9390)
137 illegal_anywhere_ = icu::UnicodeSet(
138 UNICODE_STRING_SIMPLE("[[\"*/:<>?\\\\|][:Cc:][:Cf:]]"), status);
139 DCHECK(U_SUCCESS(status));
140 // Add non-characters. If this becomes a performance bottleneck by
141 // any chance, do not add these to |set| and change IsFilenameLegal()
142 // to check |ucs4 & 0xFFFEu == 0xFFFEu|, in addition to calling
143 // IsAllowedName().
144 illegal_anywhere_.add(0xFDD0, 0xFDEF);
145 for (int i = 0; i <= 0x10; ++i) {
146 int plane_base = 0x10000 * i;
147 illegal_anywhere_.add(plane_base + 0xFFFE, plane_base + 0xFFFF);
148 }
149 illegal_anywhere_.freeze();
150
151 illegal_at_ends_ =
152 icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:WSpace:][.~]]"), status);
153 DCHECK(U_SUCCESS(status));
154 illegal_at_ends_.freeze();
155
156 #if BUILDFLAG(IS_WIN)
157 required_to_be_a_short_filename_ =
158 icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[~]]"), status);
159 DCHECK(U_SUCCESS(status));
160 required_to_be_a_short_filename_.freeze();
161
162 illegal_in_short_filenames_ = icu::UnicodeSet(
163 UNICODE_STRING_SIMPLE("[[:WSpace:][\"\\/[]:+|<>=;?,*]]"), status);
164 DCHECK(U_SUCCESS(status));
165 illegal_in_short_filenames_.freeze();
166 #endif
167 }
168
169 // Returns the code point at position |cursor| in |file_name|, and increments
170 // |cursor| to the next position.
GetNextCodePoint(const FilePath::StringType * const file_name,int & cursor)171 UChar32 GetNextCodePoint(const FilePath::StringType* const file_name,
172 int& cursor) {
173 UChar32 code_point;
174 #if BUILDFLAG(IS_WIN)
175 // Windows uses UTF-16 encoding for filenames.
176 U16_NEXT(file_name->data(), cursor, static_cast<int>(file_name->length()),
177 code_point);
178 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
179 // Mac and Chrome OS use UTF-8 encoding for filenames.
180 // Linux doesn't actually define file system encoding. Try to parse as
181 // UTF-8.
182 U8_NEXT(file_name->data(), cursor, static_cast<int>(file_name->length()),
183 code_point);
184 #else
185 #error Unsupported platform
186 #endif
187 return code_point;
188 }
189
190 } // namespace
191
IsFilenameLegal(const std::u16string & file_name)192 bool IsFilenameLegal(const std::u16string& file_name) {
193 return IllegalCharacters::GetInstance()->IsAllowedName(file_name);
194 }
195
ReplaceIllegalCharactersInPath(FilePath::StringType * file_name,char replace_char)196 void ReplaceIllegalCharactersInPath(FilePath::StringType* file_name,
197 char replace_char) {
198 IllegalCharacters* illegal = IllegalCharacters::GetInstance();
199
200 DCHECK(!(illegal->IsDisallowedEverywhere(replace_char)));
201 const bool is_replace_char_illegal_at_ends =
202 illegal->IsDisallowedLeadingOrTrailing(replace_char);
203 #if BUILDFLAG(IS_WIN)
204 bool could_be_short_name =
205 file_name->size() <= 12 &&
206 illegal->HasValidDotPositionForShortName<FilePath::StringType>(
207 *file_name);
208 #endif
209 // Keep track of the earliest and latest legal begin/end characters and file-
210 // extension separator encountered, -1 if none yet.
211 int unreplaced_legal_range_begin = -1;
212 int unreplaced_legal_range_end = -1;
213 int last_extension_separator = -1;
214 static const UChar32 kExtensionSeparator =
215 checked_cast<UChar32>(FilePath::kExtensionSeparator);
216
217 int cursor = 0; // The ICU macros expect an int.
218
219 #if BUILDFLAG(IS_WIN)
220 // Loop through the file name, looking for any characters which are invalid in
221 // an 8.3 short file name. If any of these characters exist, it's not an 8.3
222 // file name and we don't need to replace the '~' character.
223 while (could_be_short_name && cursor < static_cast<int>(file_name->size())) {
224 const UChar32 code_point = GetNextCodePoint(file_name, cursor);
225 could_be_short_name = !illegal->IsDisallowedShortNameCharacter(code_point);
226 }
227 #endif
228
229 cursor = 0;
230 while (cursor < static_cast<int>(file_name->size())) {
231 int char_begin = cursor;
232 const UChar32 code_point = GetNextCodePoint(file_name, cursor);
233
234 const bool is_illegal_at_ends =
235 illegal->IsDisallowedLeadingOrTrailing(code_point);
236
237 if (illegal->IsDisallowedEverywhere(code_point) ||
238 #if BUILDFLAG(IS_WIN)
239 (could_be_short_name &&
240 illegal->IsDisallowedIfMayBeShortName(code_point)) ||
241 #endif
242 ((char_begin == 0 || cursor == static_cast<int>(file_name->length())) &&
243 is_illegal_at_ends && !is_replace_char_illegal_at_ends)) {
244 file_name->replace(char_begin, cursor - char_begin, 1, replace_char);
245 // We just made the potentially multi-byte/word char into one that only
246 // takes one byte/word, so need to adjust the cursor to point to the next
247 // character again.
248 cursor = char_begin + 1;
249 } else if (!is_illegal_at_ends) {
250 if (unreplaced_legal_range_begin == -1)
251 unreplaced_legal_range_begin = char_begin;
252 unreplaced_legal_range_end = cursor;
253 }
254
255 if (code_point == kExtensionSeparator)
256 last_extension_separator = char_begin;
257 }
258
259 // If |replace_char| is not a legal starting/ending character, ensure that
260 // |replace_char| is not the first nor last character in |file_name|.
261 if (is_replace_char_illegal_at_ends) {
262 if (unreplaced_legal_range_begin == -1) {
263 // |file_name| has no characters that are legal at ends; enclose in '_'s.
264 file_name->insert(file_name->begin(), FILE_PATH_LITERAL('_'));
265 file_name->append(FILE_PATH_LITERAL("_"));
266 } else {
267 // Trim trailing instances of |replace_char| and other characters that are
268 // illegal at ends.
269 file_name->erase(unreplaced_legal_range_end, FilePath::StringType::npos);
270
271 // Trim leading instances of |replace_char| and other characters that are
272 // illegal at ends, while ensuring that the file-extension separator is
273 // not removed if present. The file-extension separator is considered the
274 // last '.' in |file_name| followed by a legal character.
275 if (last_extension_separator != -1 &&
276 last_extension_separator == unreplaced_legal_range_begin - 1) {
277 // If the file-extension separator is at the start of the resulting
278 // |file_name|, prepend '_' instead of trimming it, e.g.,
279 // "***.txt" -> "_.txt".
280 file_name->erase(0, last_extension_separator);
281 file_name->insert(file_name->begin(), FILE_PATH_LITERAL('_'));
282 } else {
283 file_name->erase(0, unreplaced_legal_range_begin);
284 }
285 }
286 DCHECK(!file_name->empty());
287 }
288 }
289
LocaleAwareCompareFilenames(const FilePath & a,const FilePath & b)290 bool LocaleAwareCompareFilenames(const FilePath& a, const FilePath& b) {
291 UErrorCode error_code = U_ZERO_ERROR;
292 // Use the default collator. The default locale should have been properly
293 // set by the time this constructor is called.
294 std::unique_ptr<icu::Collator> collator(
295 icu::Collator::createInstance(error_code));
296 DCHECK(U_SUCCESS(error_code));
297 // Make it case-sensitive.
298 collator->setStrength(icu::Collator::TERTIARY);
299
300 #if BUILDFLAG(IS_WIN)
301 return CompareString16WithCollator(*collator, AsStringPiece16(a.value()),
302 AsStringPiece16(b.value())) == UCOL_LESS;
303
304 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
305 // On linux, the file system encoding is not defined. We assume
306 // SysNativeMBToWide takes care of it.
307 return CompareString16WithCollator(
308 *collator, WideToUTF16(SysNativeMBToWide(a.value())),
309 WideToUTF16(SysNativeMBToWide(b.value()))) == UCOL_LESS;
310 #endif
311 }
312
NormalizeFileNameEncoding(FilePath * file_name)313 void NormalizeFileNameEncoding(FilePath* file_name) {
314 #if BUILDFLAG(IS_CHROMEOS_ASH)
315 std::string normalized_str;
316 if (ConvertToUtf8AndNormalize(file_name->BaseName().value(), kCodepageUTF8,
317 &normalized_str) &&
318 !normalized_str.empty()) {
319 *file_name = file_name->DirName().Append(FilePath(normalized_str));
320 }
321 #endif
322 }
323
324 } // namespace i18n
325 } // namespace base
326