xref: /aosp_15_r20/external/cronet/base/files/file_util_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #include "base/files/file_util.h"
6 
7 #include <windows.h>
8 #include <winsock2.h>
9 
10 #include <io.h>
11 #include <psapi.h>
12 #include <shellapi.h>
13 #include <shlobj.h>
14 #include <stddef.h>
15 #include <stdint.h>
16 #include <time.h>
17 
18 #include <algorithm>
19 #include <limits>
20 #include <string>
21 #include <utility>
22 #include <vector>
23 
24 #include "base/check.h"
25 #include "base/clang_profiling_buildflags.h"
26 #include "base/debug/alias.h"
27 #include "base/feature_list.h"
28 #include "base/features.h"
29 #include "base/files/file_enumerator.h"
30 #include "base/files/file_path.h"
31 #include "base/files/memory_mapped_file.h"
32 #include "base/functional/bind.h"
33 #include "base/functional/callback.h"
34 #include "base/location.h"
35 #include "base/logging.h"
36 #include "base/numerics/safe_conversions.h"
37 #include "base/path_service.h"
38 #include "base/process/process_handle.h"
39 #include "base/rand_util.h"
40 #include "base/strings/strcat.h"
41 #include "base/strings/string_number_conversions.h"
42 #include "base/strings/string_piece.h"
43 #include "base/strings/string_util.h"
44 #include "base/strings/string_util_win.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/task/bind_post_task.h"
47 #include "base/task/sequenced_task_runner.h"
48 #include "base/task/thread_pool.h"
49 #include "base/threading/scoped_blocking_call.h"
50 #include "base/threading/scoped_thread_priority.h"
51 #include "base/time/time.h"
52 #include "base/uuid.h"
53 #include "base/win/scoped_handle.h"
54 #include "base/win/security_util.h"
55 #include "base/win/sid.h"
56 #include "base/win/windows_types.h"
57 #include "base/win/windows_version.h"
58 
59 namespace base {
60 
61 namespace {
62 
63 int g_extra_allowed_path_for_no_execute = 0;
64 
65 bool g_disable_secure_system_temp_for_testing = false;
66 
67 const DWORD kFileShareAll =
68     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
69 const wchar_t kDefaultTempDirPrefix[] = L"ChromiumTemp";
70 
71 // Returns the Win32 last error code or ERROR_SUCCESS if the last error code is
72 // ERROR_FILE_NOT_FOUND or ERROR_PATH_NOT_FOUND. This is useful in cases where
73 // the absence of a file or path is a success condition (e.g., when attempting
74 // to delete an item in the filesystem).
ReturnLastErrorOrSuccessOnNotFound()75 DWORD ReturnLastErrorOrSuccessOnNotFound() {
76   const DWORD error_code = ::GetLastError();
77   return (error_code == ERROR_FILE_NOT_FOUND ||
78           error_code == ERROR_PATH_NOT_FOUND)
79              ? ERROR_SUCCESS
80              : error_code;
81 }
82 
83 // Deletes all files and directories in a path.
84 // Returns ERROR_SUCCESS on success or the Windows error code corresponding to
85 // the first error encountered. ERROR_FILE_NOT_FOUND and ERROR_PATH_NOT_FOUND
86 // are considered success conditions, and are therefore never returned.
DeleteFileRecursive(const FilePath & path,const FilePath::StringType & pattern,bool recursive)87 DWORD DeleteFileRecursive(const FilePath& path,
88                           const FilePath::StringType& pattern,
89                           bool recursive) {
90   FileEnumerator traversal(path, false,
91                            FileEnumerator::FILES | FileEnumerator::DIRECTORIES,
92                            pattern);
93   DWORD result = ERROR_SUCCESS;
94   for (FilePath current = traversal.Next(); !current.empty();
95        current = traversal.Next()) {
96     // Try to clear the read-only bit if we find it.
97     FileEnumerator::FileInfo info = traversal.GetInfo();
98     if ((info.find_data().dwFileAttributes & FILE_ATTRIBUTE_READONLY) &&
99         (recursive || !info.IsDirectory())) {
100       ::SetFileAttributes(
101           current.value().c_str(),
102           info.find_data().dwFileAttributes & ~DWORD{FILE_ATTRIBUTE_READONLY});
103     }
104 
105     DWORD this_result = ERROR_SUCCESS;
106     if (info.IsDirectory()) {
107       if (recursive) {
108         this_result = DeleteFileRecursive(current, pattern, true);
109         DCHECK_NE(static_cast<LONG>(this_result), ERROR_FILE_NOT_FOUND);
110         DCHECK_NE(static_cast<LONG>(this_result), ERROR_PATH_NOT_FOUND);
111         if (this_result == ERROR_SUCCESS &&
112             !::RemoveDirectory(current.value().c_str())) {
113           this_result = ReturnLastErrorOrSuccessOnNotFound();
114         }
115       }
116     } else if (!::DeleteFile(current.value().c_str())) {
117       this_result = ReturnLastErrorOrSuccessOnNotFound();
118     }
119     if (result == ERROR_SUCCESS)
120       result = this_result;
121   }
122   return result;
123 }
124 
125 // Appends |mode_char| to |mode| before the optional character set encoding; see
126 // https://msdn.microsoft.com/library/yeby3zcb.aspx for details.
AppendModeCharacter(wchar_t mode_char,std::wstring * mode)127 void AppendModeCharacter(wchar_t mode_char, std::wstring* mode) {
128   size_t comma_pos = mode->find(L',');
129   mode->insert(comma_pos == std::wstring::npos ? mode->length() : comma_pos, 1,
130                mode_char);
131 }
132 
DoCopyFile(const FilePath & from_path,const FilePath & to_path,bool fail_if_exists)133 bool DoCopyFile(const FilePath& from_path,
134                 const FilePath& to_path,
135                 bool fail_if_exists) {
136   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
137   if (from_path.ReferencesParent() || to_path.ReferencesParent())
138     return false;
139 
140   // NOTE: I suspect we could support longer paths, but that would involve
141   // analyzing all our usage of files.
142   if (from_path.value().length() >= MAX_PATH ||
143       to_path.value().length() >= MAX_PATH) {
144     return false;
145   }
146 
147   // Mitigate the issues caused by loading DLLs on a background thread
148   // (http://crbug/973868).
149   SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();
150 
151   // Unlike the posix implementation that copies the file manually and discards
152   // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access
153   // bits, which is usually not what we want. We can't do much about the
154   // SECURITY_DESCRIPTOR but at least remove the read only bit.
155   const wchar_t* dest = to_path.value().c_str();
156   if (!::CopyFile(from_path.value().c_str(), dest, fail_if_exists)) {
157     // Copy failed.
158     return false;
159   }
160   DWORD attrs = GetFileAttributes(dest);
161   if (attrs == INVALID_FILE_ATTRIBUTES) {
162     return false;
163   }
164   if (attrs & FILE_ATTRIBUTE_READONLY) {
165     SetFileAttributes(dest, attrs & ~DWORD{FILE_ATTRIBUTE_READONLY});
166   }
167   return true;
168 }
169 
DoCopyDirectory(const FilePath & from_path,const FilePath & to_path,bool recursive,bool fail_if_exists)170 bool DoCopyDirectory(const FilePath& from_path,
171                      const FilePath& to_path,
172                      bool recursive,
173                      bool fail_if_exists) {
174   // NOTE(maruel): Previous version of this function used to call
175   // SHFileOperation().  This used to copy the file attributes and extended
176   // attributes, OLE structured storage, NTFS file system alternate data
177   // streams, SECURITY_DESCRIPTOR. In practice, this is not what we want, we
178   // want the containing directory to propagate its SECURITY_DESCRIPTOR.
179   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
180 
181   // NOTE: I suspect we could support longer paths, but that would involve
182   // analyzing all our usage of files.
183   if (from_path.value().length() >= MAX_PATH ||
184       to_path.value().length() >= MAX_PATH) {
185     return false;
186   }
187 
188   // This function does not properly handle destinations within the source.
189   FilePath real_to_path = to_path;
190   if (PathExists(real_to_path)) {
191     real_to_path = MakeAbsoluteFilePath(real_to_path);
192     if (real_to_path.empty())
193       return false;
194   } else {
195     real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
196     if (real_to_path.empty())
197       return false;
198   }
199   FilePath real_from_path = MakeAbsoluteFilePath(from_path);
200   if (real_from_path.empty())
201     return false;
202   if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path))
203     return false;
204 
205   int traverse_type = FileEnumerator::FILES;
206   if (recursive)
207     traverse_type |= FileEnumerator::DIRECTORIES;
208   FileEnumerator traversal(from_path, recursive, traverse_type);
209 
210   if (!PathExists(from_path)) {
211     DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
212                 << from_path.value().c_str();
213     return false;
214   }
215   // TODO(maruel): This is not necessary anymore.
216   DCHECK(recursive || DirectoryExists(from_path));
217 
218   FilePath current = from_path;
219   bool from_is_dir = DirectoryExists(from_path);
220   bool success = true;
221   FilePath from_path_base = from_path;
222   if (recursive && DirectoryExists(to_path)) {
223     // If the destination already exists and is a directory, then the
224     // top level of source needs to be copied.
225     from_path_base = from_path.DirName();
226   }
227 
228   while (success && !current.empty()) {
229     // current is the source path, including from_path, so append
230     // the suffix after from_path to to_path to create the target_path.
231     FilePath target_path(to_path);
232     if (from_path_base != current) {
233       if (!from_path_base.AppendRelativePath(current, &target_path)) {
234         success = false;
235         break;
236       }
237     }
238 
239     if (from_is_dir) {
240       if (!DirectoryExists(target_path) &&
241           !::CreateDirectory(target_path.value().c_str(), NULL)) {
242         DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
243                     << target_path.value().c_str();
244         success = false;
245       }
246     } else if (!DoCopyFile(current, target_path, fail_if_exists)) {
247       DLOG(ERROR) << "CopyDirectory() couldn't create file: "
248                   << target_path.value().c_str();
249       success = false;
250     }
251 
252     current = traversal.Next();
253     if (!current.empty())
254       from_is_dir = traversal.GetInfo().IsDirectory();
255   }
256 
257   return success;
258 }
259 
260 // Returns ERROR_SUCCESS on success, or a Windows error code on failure.
DoDeleteFile(const FilePath & path,bool recursive)261 DWORD DoDeleteFile(const FilePath& path, bool recursive) {
262   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
263 
264   if (path.empty())
265     return ERROR_SUCCESS;
266 
267   if (path.value().length() >= MAX_PATH)
268     return ERROR_BAD_PATHNAME;
269 
270   // Handle any path with wildcards.
271   if (path.BaseName().value().find_first_of(FILE_PATH_LITERAL("*?")) !=
272       FilePath::StringType::npos) {
273     const DWORD error_code =
274         DeleteFileRecursive(path.DirName(), path.BaseName().value(), recursive);
275     DCHECK_NE(static_cast<LONG>(error_code), ERROR_FILE_NOT_FOUND);
276     DCHECK_NE(static_cast<LONG>(error_code), ERROR_PATH_NOT_FOUND);
277     return error_code;
278   }
279 
280   // Report success if the file or path does not exist.
281   const DWORD attr = ::GetFileAttributes(path.value().c_str());
282   if (attr == INVALID_FILE_ATTRIBUTES)
283     return ReturnLastErrorOrSuccessOnNotFound();
284 
285   // Clear the read-only bit if it is set.
286   if ((attr & FILE_ATTRIBUTE_READONLY) &&
287       !::SetFileAttributes(path.value().c_str(),
288                            attr & ~DWORD{FILE_ATTRIBUTE_READONLY})) {
289     // It's possible for |path| to be gone now under a race with other deleters.
290     return ReturnLastErrorOrSuccessOnNotFound();
291   }
292 
293   // Perform a simple delete on anything that isn't a directory.
294   if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
295     return ::DeleteFile(path.value().c_str())
296                ? ERROR_SUCCESS
297                : ReturnLastErrorOrSuccessOnNotFound();
298   }
299 
300   if (recursive) {
301     const DWORD error_code =
302         DeleteFileRecursive(path, FILE_PATH_LITERAL("*"), true);
303     DCHECK_NE(static_cast<LONG>(error_code), ERROR_FILE_NOT_FOUND);
304     DCHECK_NE(static_cast<LONG>(error_code), ERROR_PATH_NOT_FOUND);
305     if (error_code != ERROR_SUCCESS)
306       return error_code;
307   }
308   return ::RemoveDirectory(path.value().c_str())
309              ? ERROR_SUCCESS
310              : ReturnLastErrorOrSuccessOnNotFound();
311 }
312 
313 // Deletes the file/directory at |path| (recursively if |recursive| and |path|
314 // names a directory), returning true on success. Sets the Windows last-error
315 // code and returns false on failure.
DeleteFileOrSetLastError(const FilePath & path,bool recursive)316 bool DeleteFileOrSetLastError(const FilePath& path, bool recursive) {
317   const DWORD error = DoDeleteFile(path, recursive);
318   if (error == ERROR_SUCCESS)
319     return true;
320 
321   ::SetLastError(error);
322   return false;
323 }
324 
325 constexpr int kMaxDeleteAttempts = 9;
326 
DeleteFileWithRetry(const FilePath & path,bool recursive,int attempt,OnceCallback<void (bool)> reply_callback)327 void DeleteFileWithRetry(const FilePath& path,
328                          bool recursive,
329                          int attempt,
330                          OnceCallback<void(bool)> reply_callback) {
331   // Retry every 250ms for up to two seconds. These values were pulled out of
332   // thin air, and may be adjusted in the future based on the metrics collected.
333   static constexpr TimeDelta kDeleteFileRetryDelay = Milliseconds(250);
334 
335   if (DeleteFileOrSetLastError(path, recursive)) {
336     // Consider introducing further retries until the item has been removed from
337     // the filesystem and its name is ready for reuse; see the comments in
338     // chrome/installer/mini_installer/delete_with_retry.cc for details.
339     if (!reply_callback.is_null())
340       std::move(reply_callback).Run(true);
341     return;
342   }
343 
344   ++attempt;
345   DCHECK_LE(attempt, kMaxDeleteAttempts);
346   if (attempt == kMaxDeleteAttempts) {
347     if (!reply_callback.is_null())
348       std::move(reply_callback).Run(false);
349     return;
350   }
351 
352   ThreadPool::PostDelayedTask(FROM_HERE,
353                               {TaskPriority::BEST_EFFORT, MayBlock()},
354                               BindOnce(&DeleteFileWithRetry, path, recursive,
355                                        attempt, std::move(reply_callback)),
356                               kDeleteFileRetryDelay);
357 }
358 
GetDeleteFileCallbackInternal(const FilePath & path,bool recursive,OnceCallback<void (bool)> reply_callback)359 OnceClosure GetDeleteFileCallbackInternal(
360     const FilePath& path,
361     bool recursive,
362     OnceCallback<void(bool)> reply_callback) {
363   OnceCallback<void(bool)> bound_callback;
364   if (!reply_callback.is_null()) {
365     bound_callback = BindPostTask(SequencedTaskRunner::GetCurrentDefault(),
366                                   std::move(reply_callback));
367   }
368   return BindOnce(&DeleteFileWithRetry, path, recursive, /*attempt=*/0,
369                   std::move(bound_callback));
370 }
371 
372 // This function verifies that no code is attempting to set an ACL on a file
373 // that is outside of 'safe' paths. A 'safe' path is defined as one that is
374 // within the user data dir, or the temporary directory. This is explicitly to
375 // prevent code from trying to pass a writeable handle to a file outside of
376 // these directories to an untrusted process. E.g. if some future code created a
377 // writeable handle to a file in c:\users\user\sensitive.dat, this DCHECK would
378 // hit. Setting an ACL on a file outside of these chrome-controlled directories
379 // might cause the browser or operating system to fail in unexpected ways.
IsPathSafeToSetAclOn(const FilePath & path)380 bool IsPathSafeToSetAclOn(const FilePath& path) {
381 #if BUILDFLAG(CLANG_PROFILING)
382   // TODO(crbug.com/329482479) Use PreventExecuteMappingUnchecked for .profraw.
383   // Ignore .profraw profiling files, as they can occur anywhere, and only occur
384   // during testing.
385   if (path.Extension() == FILE_PATH_LITERAL(".profraw")) {
386     return true;
387   }
388 #endif  // BUILDFLAG(CLANG_PROFILING)
389   std::vector<int> valid_path_keys({DIR_TEMP});
390   if (g_extra_allowed_path_for_no_execute) {
391     valid_path_keys.push_back(g_extra_allowed_path_for_no_execute);
392   }
393 
394   // MakeLongFilePath is needed here because temp files can have an 8.3 path
395   // under certain conditions. See comments in base::MakeLongFilePath.
396   FilePath long_path = MakeLongFilePath(path);
397   DCHECK(!long_path.empty()) << "Cannot get long path for " << path;
398 
399   std::vector<FilePath> valid_paths;
400   for (const auto path_key : valid_path_keys) {
401     FilePath valid_path;
402     if (!PathService::Get(path_key, &valid_path)) {
403       DLOG(FATAL) << "Cannot get path for pathservice key " << path_key;
404       continue;
405     }
406     valid_paths.push_back(valid_path);
407   }
408 
409   // Admin users create temporary files in `GetSecureSystemTemp`, see
410   // `CreateNewTempDirectory` below.
411   FilePath secure_system_temp;
412   if (::IsUserAnAdmin() && GetSecureSystemTemp(&secure_system_temp)) {
413     valid_paths.push_back(secure_system_temp);
414   }
415 
416   for (const auto& valid_path : valid_paths) {
417     // Temp files can sometimes have an 8.3 path. See comments in
418     // `MakeLongFilePath`.
419     FilePath full_path = MakeLongFilePath(valid_path);
420     DCHECK(!full_path.empty()) << "Cannot get long path for " << valid_path;
421     if (full_path.IsParent(long_path)) {
422       return true;
423     }
424   }
425 
426   return false;
427 }
428 
429 }  // namespace
430 
GetDeleteFileCallback(const FilePath & path,OnceCallback<void (bool)> reply_callback)431 OnceClosure GetDeleteFileCallback(const FilePath& path,
432                                   OnceCallback<void(bool)> reply_callback) {
433   return GetDeleteFileCallbackInternal(path, /*recursive=*/false,
434                                        std::move(reply_callback));
435 }
436 
GetDeletePathRecursivelyCallback(const FilePath & path,OnceCallback<void (bool)> reply_callback)437 OnceClosure GetDeletePathRecursivelyCallback(
438     const FilePath& path,
439     OnceCallback<void(bool)> reply_callback) {
440   return GetDeleteFileCallbackInternal(path, /*recursive=*/true,
441                                        std::move(reply_callback));
442 }
443 
MakeAbsoluteFilePath(const FilePath & input)444 FilePath MakeAbsoluteFilePath(const FilePath& input) {
445   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
446   wchar_t file_path[MAX_PATH];
447   if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
448     return FilePath();
449   return FilePath(file_path);
450 }
451 
DeleteFile(const FilePath & path)452 bool DeleteFile(const FilePath& path) {
453   return DeleteFileOrSetLastError(path, /*recursive=*/false);
454 }
455 
DeletePathRecursively(const FilePath & path)456 bool DeletePathRecursively(const FilePath& path) {
457   return DeleteFileOrSetLastError(path, /*recursive=*/true);
458 }
459 
DeleteFileAfterReboot(const FilePath & path)460 bool DeleteFileAfterReboot(const FilePath& path) {
461   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
462 
463   if (path.value().length() >= MAX_PATH)
464     return false;
465 
466   return ::MoveFileEx(path.value().c_str(), nullptr,
467                       MOVEFILE_DELAY_UNTIL_REBOOT);
468 }
469 
ReplaceFile(const FilePath & from_path,const FilePath & to_path,File::Error * error)470 bool ReplaceFile(const FilePath& from_path,
471                  const FilePath& to_path,
472                  File::Error* error) {
473   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
474 
475   // Alias paths for investigation of shutdown hangs. crbug.com/1054164
476   FilePath::CharType from_path_str[MAX_PATH];
477   base::wcslcpy(from_path_str, from_path.value().c_str(),
478                 std::size(from_path_str));
479   base::debug::Alias(from_path_str);
480   FilePath::CharType to_path_str[MAX_PATH];
481   base::wcslcpy(to_path_str, to_path.value().c_str(), std::size(to_path_str));
482   base::debug::Alias(to_path_str);
483 
484   // Assume that |to_path| already exists and try the normal replace. This will
485   // fail with ERROR_FILE_NOT_FOUND if |to_path| does not exist. When writing to
486   // a network share, we may not be able to change the ACLs. Ignore ACL errors
487   // then (REPLACEFILE_IGNORE_MERGE_ERRORS).
488   if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
489                     REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
490     return true;
491   }
492 
493   File::Error replace_error = File::OSErrorToFileError(GetLastError());
494 
495   // Try a simple move next. It will only succeed when |to_path| doesn't already
496   // exist.
497   if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
498     return true;
499 
500   // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely that
501   // |to_path| does not exist. In this case, the more relevant error comes
502   // from the call to MoveFile.
503   if (error) {
504     *error = replace_error == File::FILE_ERROR_NOT_FOUND
505                  ? File::GetLastFileError()
506                  : replace_error;
507   }
508   return false;
509 }
510 
CopyDirectory(const FilePath & from_path,const FilePath & to_path,bool recursive)511 bool CopyDirectory(const FilePath& from_path,
512                    const FilePath& to_path,
513                    bool recursive) {
514   return DoCopyDirectory(from_path, to_path, recursive, false);
515 }
516 
CopyDirectoryExcl(const FilePath & from_path,const FilePath & to_path,bool recursive)517 bool CopyDirectoryExcl(const FilePath& from_path,
518                        const FilePath& to_path,
519                        bool recursive) {
520   return DoCopyDirectory(from_path, to_path, recursive, true);
521 }
522 
PathExists(const FilePath & path)523 bool PathExists(const FilePath& path) {
524   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
525   return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
526 }
527 
528 namespace {
529 
PathHasAccess(const FilePath & path,DWORD dir_desired_access,DWORD file_desired_access)530 bool PathHasAccess(const FilePath& path,
531                    DWORD dir_desired_access,
532                    DWORD file_desired_access) {
533   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
534 
535   const wchar_t* const path_str = path.value().c_str();
536   DWORD fileattr = GetFileAttributes(path_str);
537   if (fileattr == INVALID_FILE_ATTRIBUTES)
538     return false;
539 
540   bool is_directory = fileattr & FILE_ATTRIBUTE_DIRECTORY;
541   DWORD desired_access =
542       is_directory ? dir_desired_access : file_desired_access;
543   DWORD flags_and_attrs =
544       is_directory ? FILE_FLAG_BACKUP_SEMANTICS : FILE_ATTRIBUTE_NORMAL;
545 
546   win::ScopedHandle file(CreateFile(path_str, desired_access, kFileShareAll,
547                                     nullptr, OPEN_EXISTING, flags_and_attrs,
548                                     nullptr));
549 
550   return file.is_valid();
551 }
552 
553 }  // namespace
554 
PathIsReadable(const FilePath & path)555 bool PathIsReadable(const FilePath& path) {
556   return PathHasAccess(path, FILE_LIST_DIRECTORY, GENERIC_READ);
557 }
558 
PathIsWritable(const FilePath & path)559 bool PathIsWritable(const FilePath& path) {
560   return PathHasAccess(path, FILE_ADD_FILE, GENERIC_WRITE);
561 }
562 
DirectoryExists(const FilePath & path)563 bool DirectoryExists(const FilePath& path) {
564   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
565   DWORD fileattr = GetFileAttributes(path.value().c_str());
566   if (fileattr != INVALID_FILE_ATTRIBUTES)
567     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
568   return false;
569 }
570 
GetTempDir(FilePath * path)571 bool GetTempDir(FilePath* path) {
572   wchar_t temp_path[MAX_PATH + 1];
573   DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
574   if (path_len >= MAX_PATH || path_len <= 0)
575     return false;
576   // TODO(evanm): the old behavior of this function was to always strip the
577   // trailing slash.  We duplicate this here, but it shouldn't be necessary
578   // when everyone is using the appropriate FilePath APIs.
579   *path = FilePath(temp_path).StripTrailingSeparators();
580   return true;
581 }
582 
GetHomeDir()583 FilePath GetHomeDir() {
584   wchar_t result[MAX_PATH];
585   if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT,
586                                 result)) &&
587       result[0]) {
588     return FilePath(result);
589   }
590 
591   // Fall back to the temporary directory on failure.
592   FilePath temp;
593   if (GetTempDir(&temp))
594     return temp;
595 
596   // Last resort.
597   return FilePath(FILE_PATH_LITERAL("C:\\"));
598 }
599 
CreateAndOpenTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)600 File CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
601   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
602 
603   // Open the file with exclusive r/w/d access, and allow the caller to decide
604   // to mark it for deletion upon close after the fact.
605   constexpr uint32_t kFlags = File::FLAG_CREATE | File::FLAG_READ |
606                               File::FLAG_WRITE | File::FLAG_WIN_EXCLUSIVE_READ |
607                               File::FLAG_WIN_EXCLUSIVE_WRITE |
608                               File::FLAG_CAN_DELETE_ON_CLOSE;
609 
610   // Use GUID instead of ::GetTempFileName() to generate unique file names.
611   // "Due to the algorithm used to generate file names, GetTempFileName can
612   // perform poorly when creating a large number of files with the same prefix.
613   // In such cases, it is recommended that you construct unique file names based
614   // on GUIDs."
615   // https://msdn.microsoft.com/library/windows/desktop/aa364991.aspx
616 
617   FilePath temp_name;
618   File file;
619 
620   // Although it is nearly impossible to get a duplicate name with GUID, we
621   // still use a loop here in case it happens.
622   for (int i = 0; i < 100; ++i) {
623     temp_name = dir.Append(FormatTemporaryFileName(
624         UTF8ToWide(Uuid::GenerateRandomV4().AsLowercaseString())));
625     file.Initialize(temp_name, kFlags);
626     if (file.IsValid())
627       break;
628   }
629 
630   if (!file.IsValid()) {
631     DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
632     return file;
633   }
634 
635   wchar_t long_temp_name[MAX_PATH + 1];
636   const DWORD long_name_len =
637       GetLongPathName(temp_name.value().c_str(), long_temp_name, MAX_PATH);
638   if (long_name_len != 0 && long_name_len <= MAX_PATH) {
639     *temp_file =
640         FilePath(FilePath::StringPieceType(long_temp_name, long_name_len));
641   } else {
642     // GetLongPathName() failed, but we still have a temporary file.
643     *temp_file = std::move(temp_name);
644   }
645 
646   return file;
647 }
648 
CreateTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)649 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
650   return CreateAndOpenTemporaryFileInDir(dir, temp_file).IsValid();
651 }
652 
FormatTemporaryFileName(FilePath::StringPieceType identifier)653 FilePath FormatTemporaryFileName(FilePath::StringPieceType identifier) {
654   return FilePath(StrCat({identifier, FILE_PATH_LITERAL(".tmp")}));
655 }
656 
CreateAndOpenTemporaryStreamInDir(const FilePath & dir,FilePath * path)657 ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
658                                              FilePath* path) {
659   // Open file in binary mode, to avoid problems with fwrite. On Windows
660   // it replaces \n's with \r\n's, which may surprise you.
661   // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
662   return ScopedFILE(
663       FileToFILE(CreateAndOpenTemporaryFileInDir(dir, path), "wb+"));
664 }
665 
CreateTemporaryDirInDir(const FilePath & base_dir,const FilePath::StringType & prefix,FilePath * new_dir)666 bool CreateTemporaryDirInDir(const FilePath& base_dir,
667                              const FilePath::StringType& prefix,
668                              FilePath* new_dir) {
669   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
670 
671   FilePath path_to_create;
672 
673   for (int count = 0; count < 50; ++count) {
674     // Try create a new temporary directory with random generated name. If
675     // the one exists, keep trying another path name until we reach some limit.
676     std::wstring new_dir_name;
677     new_dir_name.assign(prefix);
678     new_dir_name.append(AsWString(NumberToString16(GetCurrentProcId())));
679     new_dir_name.push_back('_');
680     new_dir_name.append(AsWString(
681         NumberToString16(RandInt(0, std::numeric_limits<int32_t>::max()))));
682 
683     path_to_create = base_dir.Append(new_dir_name);
684     if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
685       *new_dir = path_to_create;
686       return true;
687     }
688   }
689 
690   return false;
691 }
692 
GetSecureSystemTemp(FilePath * temp)693 bool GetSecureSystemTemp(FilePath* temp) {
694   if (g_disable_secure_system_temp_for_testing) {
695     return false;
696   }
697 
698   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
699 
700   CHECK(temp);
701 
702   for (const auto key : {DIR_WINDOWS, DIR_PROGRAM_FILES}) {
703     FilePath secure_system_temp;
704     if (!PathService::Get(key, &secure_system_temp)) {
705       continue;
706     }
707 
708     if (key == DIR_WINDOWS) {
709       secure_system_temp = secure_system_temp.AppendASCII("SystemTemp");
710     }
711 
712     if (PathExists(secure_system_temp) && PathIsWritable(secure_system_temp)) {
713       *temp = secure_system_temp;
714       return true;
715     }
716   }
717 
718   return false;
719 }
720 
SetDisableSecureSystemTempForTesting(bool disabled)721 void SetDisableSecureSystemTempForTesting(bool disabled) {
722   g_disable_secure_system_temp_for_testing = disabled;
723 }
724 
725 // The directory is created under `GetSecureSystemTemp` for security reasons if
726 // the caller is admin to avoid attacks from lower privilege processes.
727 //
728 // If unable to create a dir under `GetSecureSystemTemp`, the dir is created
729 // under %TEMP%. The reasons for not being able to create a dir under
730 // `GetSecureSystemTemp` could be because `%systemroot%\SystemTemp` does not
731 // exist, or unable to resolve `DIR_WINDOWS` or `DIR_PROGRAM_FILES`, say due to
732 // registry redirection, or unable to create a directory due to
733 // `GetSecureSystemTemp` being read-only or having atypical ACLs. Tests can also
734 // disable this behavior resulting in false being returned.
CreateNewTempDirectory(const FilePath::StringType & prefix,FilePath * new_temp_path)735 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
736                             FilePath* new_temp_path) {
737   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
738 
739   DCHECK(new_temp_path);
740 
741   FilePath parent_dir;
742   if (::IsUserAnAdmin() && GetSecureSystemTemp(&parent_dir) &&
743       CreateTemporaryDirInDir(parent_dir,
744                               prefix.empty() ? kDefaultTempDirPrefix : prefix,
745                               new_temp_path)) {
746     return true;
747   }
748 
749   if (!GetTempDir(&parent_dir))
750     return false;
751 
752   return CreateTemporaryDirInDir(parent_dir, prefix, new_temp_path);
753 }
754 
CreateDirectoryAndGetError(const FilePath & full_path,File::Error * error)755 bool CreateDirectoryAndGetError(const FilePath& full_path,
756                                 File::Error* error) {
757   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
758 
759   // If the path exists, we've succeeded if it's a directory, failed otherwise.
760   const wchar_t* const full_path_str = full_path.value().c_str();
761   const DWORD fileattr = ::GetFileAttributes(full_path_str);
762   if (fileattr != INVALID_FILE_ATTRIBUTES) {
763     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
764       return true;
765     }
766     DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
767                   << "conflicts with existing file.";
768     if (error)
769       *error = File::FILE_ERROR_NOT_A_DIRECTORY;
770     ::SetLastError(ERROR_FILE_EXISTS);
771     return false;
772   }
773 
774   // Invariant:  Path does not exist as file or directory.
775 
776   // Attempt to create the parent recursively.  This will immediately return
777   // true if it already exists, otherwise will create all required parent
778   // directories starting with the highest-level missing parent.
779   FilePath parent_path(full_path.DirName());
780   if (parent_path.value() == full_path.value()) {
781     if (error)
782       *error = File::FILE_ERROR_NOT_FOUND;
783     ::SetLastError(ERROR_FILE_NOT_FOUND);
784     return false;
785   }
786   if (!CreateDirectoryAndGetError(parent_path, error)) {
787     DLOG(WARNING) << "Failed to create one of the parent directories.";
788     DCHECK(!error || *error != File::FILE_OK);
789     return false;
790   }
791 
792   if (::CreateDirectory(full_path_str, NULL))
793     return true;
794 
795   const DWORD error_code = ::GetLastError();
796   if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
797     // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we were
798     // racing with someone creating the same directory, or a file with the same
799     // path.  If DirectoryExists() returns true, we lost the race to create the
800     // same directory.
801     return true;
802   }
803   if (error)
804     *error = File::OSErrorToFileError(error_code);
805   ::SetLastError(error_code);
806   DPLOG(WARNING) << "Failed to create directory " << full_path_str;
807   return false;
808 }
809 
NormalizeFilePath(const FilePath & path,FilePath * real_path)810 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
811   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
812   File file(path,
813             File::FLAG_OPEN | File::FLAG_READ | File::FLAG_WIN_SHARE_DELETE);
814   if (!file.IsValid())
815     return false;
816 
817   // The expansion of |path| into a full path may make it longer.
818   constexpr int kMaxPathLength = MAX_PATH + 10;
819   wchar_t native_file_path[kMaxPathLength];
820   // On success, `used_wchars` returns the number of written characters, not
821   // include the trailing '\0'. Thus, failure is indicated by returning 0 or >=
822   // kMaxPathLength.
823   DWORD used_wchars = ::GetFinalPathNameByHandle(
824       file.GetPlatformFile(), native_file_path, kMaxPathLength,
825       FILE_NAME_NORMALIZED | VOLUME_NAME_NT);
826 
827   if (used_wchars >= kMaxPathLength || used_wchars == 0)
828     return false;
829 
830   // GetFinalPathNameByHandle() returns the \\?\ syntax for file names and
831   // existing code expects we return a path starting 'X:\' so we call
832   // DevicePathToDriveLetterPath rather than using VOLUME_NAME_DOS above.
833   return DevicePathToDriveLetterPath(
834       FilePath(FilePath::StringPieceType(native_file_path, used_wchars)),
835       real_path);
836 }
837 
DevicePathToDriveLetterPath(const FilePath & nt_device_path,FilePath * out_drive_letter_path)838 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
839                                  FilePath* out_drive_letter_path) {
840   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
841 
842   // Get the mapping of drive letters to device paths.
843   const int kDriveMappingSize = 1024;
844   wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
845   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
846     DLOG(ERROR) << "Failed to get drive mapping.";
847     return false;
848   }
849 
850   // The drive mapping is a sequence of null terminated strings.
851   // The last string is empty.
852   wchar_t* drive_map_ptr = drive_mapping;
853   wchar_t device_path_as_string[MAX_PATH];
854   wchar_t drive[] = FILE_PATH_LITERAL(" :");
855 
856   // For each string in the drive mapping, get the junction that links
857   // to it.  If that junction is a prefix of |device_path|, then we
858   // know that |drive| is the real path prefix.
859   while (*drive_map_ptr) {
860     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
861 
862     if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
863       FilePath device_path(device_path_as_string);
864       if (device_path == nt_device_path ||
865           device_path.IsParent(nt_device_path)) {
866         *out_drive_letter_path =
867             FilePath(drive + nt_device_path.value().substr(
868                                  wcslen(device_path_as_string)));
869         return true;
870       }
871     }
872     // Move to the next drive letter string, which starts one
873     // increment after the '\0' that terminates the current string.
874     while (*drive_map_ptr++) {}
875   }
876 
877   // No drive matched.  The path does not start with a device junction
878   // that is mounted as a drive letter.  This means there is no drive
879   // letter path to the volume that holds |device_path|, so fail.
880   return false;
881 }
882 
MakeLongFilePath(const FilePath & input)883 FilePath MakeLongFilePath(const FilePath& input) {
884   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
885 
886   DWORD path_long_len = ::GetLongPathName(input.value().c_str(), nullptr, 0);
887   if (path_long_len == 0UL)
888     return FilePath();
889 
890   std::wstring path_long_str;
891   path_long_len = ::GetLongPathName(input.value().c_str(),
892                                     WriteInto(&path_long_str, path_long_len),
893                                     path_long_len);
894   if (path_long_len == 0UL)
895     return FilePath();
896 
897   return FilePath(path_long_str);
898 }
899 
CreateWinHardLink(const FilePath & to_file,const FilePath & from_file)900 bool CreateWinHardLink(const FilePath& to_file, const FilePath& from_file) {
901   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
902   return ::CreateHardLink(to_file.value().c_str(), from_file.value().c_str(),
903                           nullptr);
904 }
905 
IsLink(const FilePath & file_path)906 bool IsLink(const FilePath& file_path) {
907   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
908 
909   // Opens the file or directory specified by file_path for querying attributes.
910   // No access rights are requested (FILE_READ_ATTRIBUTES), as we're only
911   // interested in the attributes. The file share mode allows other processes to
912   // read, write, and delete the file while we have it open. The flags
913   // FILE_FLAG_BACKUP_SEMANTICS and FILE_FLAG_OPEN_REPARSE_POINT are used to
914   // ensure we can open directories and work with reparse points, respectively.
915   //
916   // NOTE: In future, we can consider using GetFileInformationByName(...)
917   // instead.
918   win::ScopedHandle file(
919       ::CreateFile(file_path.value().c_str(), FILE_READ_ATTRIBUTES,
920                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
921                    /*lpSecurityAttributes=*/nullptr, OPEN_EXISTING,
922                    FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
923                    /*hTemplateFile=*/nullptr));
924 
925   if (!file.is_valid()) {
926     return false;
927   }
928 
929   FILE_ATTRIBUTE_TAG_INFO attr_taginfo;
930   if (!::GetFileInformationByHandleEx(file.get(), FileAttributeTagInfo,
931                                       &attr_taginfo, sizeof(attr_taginfo))) {
932     return false;
933   }
934 
935   return (attr_taginfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
936          (attr_taginfo.ReparseTag == IO_REPARSE_TAG_SYMLINK);
937 }
938 
GetFileInfo(const FilePath & file_path,File::Info * results)939 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
940   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
941 
942   WIN32_FILE_ATTRIBUTE_DATA attr;
943   if (!GetFileAttributesEx(file_path.value().c_str(), GetFileExInfoStandard,
944                            &attr)) {
945     return false;
946   }
947 
948   ULARGE_INTEGER size;
949   size.HighPart = attr.nFileSizeHigh;
950   size.LowPart = attr.nFileSizeLow;
951   // TODO(crbug.com/1333521): Change Info::size to uint64_t and eliminate this
952   // cast.
953   results->size = checked_cast<int64_t>(size.QuadPart);
954 
955   results->is_directory =
956       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
957   results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
958   results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
959   results->creation_time = Time::FromFileTime(attr.ftCreationTime);
960 
961   return true;
962 }
963 
OpenFile(const FilePath & filename,const char * mode)964 FILE* OpenFile(const FilePath& filename, const char* mode) {
965   // 'N' is unconditionally added below, so be sure there is not one already
966   // present before a comma in |mode|.
967   DCHECK(
968       strchr(mode, 'N') == nullptr ||
969       (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ',')));
970   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
971   std::wstring w_mode = UTF8ToWide(mode);
972   AppendModeCharacter(L'N', &w_mode);
973   return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
974 }
975 
FileToFILE(File file,const char * mode)976 FILE* FileToFILE(File file, const char* mode) {
977   DCHECK(!file.async());
978   if (!file.IsValid())
979     return NULL;
980   int fd =
981       _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
982   if (fd < 0)
983     return NULL;
984   file.TakePlatformFile();
985   FILE* stream = _fdopen(fd, mode);
986   if (!stream)
987     _close(fd);
988   return stream;
989 }
990 
FILEToFile(FILE * file_stream)991 File FILEToFile(FILE* file_stream) {
992   if (!file_stream)
993     return File();
994 
995   int fd = _fileno(file_stream);
996   DCHECK_GE(fd, 0);
997   intptr_t file_handle = _get_osfhandle(fd);
998   DCHECK_NE(file_handle, reinterpret_cast<intptr_t>(INVALID_HANDLE_VALUE));
999 
1000   HANDLE other_handle = nullptr;
1001   if (!::DuplicateHandle(
1002           /*hSourceProcessHandle=*/GetCurrentProcess(),
1003           reinterpret_cast<HANDLE>(file_handle),
1004           /*hTargetProcessHandle=*/GetCurrentProcess(), &other_handle,
1005           /*dwDesiredAccess=*/0,
1006           /*bInheritHandle=*/FALSE,
1007           /*dwOptions=*/DUPLICATE_SAME_ACCESS)) {
1008     return File(File::GetLastFileError());
1009   }
1010 
1011   return File(ScopedPlatformFile(other_handle));
1012 }
1013 
ReadFile(const FilePath & filename,span<char> buffer)1014 std::optional<uint64_t> ReadFile(const FilePath& filename, span<char> buffer) {
1015   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1016   win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_READ,
1017                                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1018                                     OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
1019                                     NULL));
1020   if (!file.is_valid()) {
1021     return std::nullopt;
1022   }
1023 
1024   // TODO(crbug.com/1333521): Consider supporting reading more than INT_MAX
1025   // bytes.
1026   DWORD bytes_to_read = static_cast<DWORD>(checked_cast<int>(buffer.size()));
1027 
1028   DWORD bytes_read;
1029   if (!::ReadFile(file.get(), buffer.data(), bytes_to_read, &bytes_read,
1030                   nullptr)) {
1031     return std::nullopt;
1032   }
1033   return bytes_read;
1034 }
1035 
WriteFile(const FilePath & filename,const char * data,int size)1036 int WriteFile(const FilePath& filename, const char* data, int size) {
1037   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1038   win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_WRITE, 0,
1039                                     NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
1040                                     NULL));
1041   if (!file.is_valid() || size < 0) {
1042     DPLOG(WARNING) << "WriteFile failed for path " << filename.value();
1043     return -1;
1044   }
1045 
1046   DWORD written;
1047   BOOL result =
1048       ::WriteFile(file.get(), data, static_cast<DWORD>(size), &written, NULL);
1049   if (result && static_cast<int>(written) == size)
1050     return static_cast<int>(written);
1051 
1052   if (!result) {
1053     // WriteFile failed.
1054     DPLOG(WARNING) << "writing file " << filename.value() << " failed";
1055   } else {
1056     // Didn't write all the bytes.
1057     DLOG(WARNING) << "wrote" << written << " bytes to " << filename.value()
1058                   << " expected " << size;
1059   }
1060   return -1;
1061 }
1062 
AppendToFile(const FilePath & filename,span<const uint8_t> data)1063 bool AppendToFile(const FilePath& filename, span<const uint8_t> data) {
1064   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1065   win::ScopedHandle file(CreateFile(filename.value().c_str(), FILE_APPEND_DATA,
1066                                     0, nullptr, OPEN_EXISTING, 0, nullptr));
1067   if (!file.is_valid()) {
1068     VPLOG(1) << "CreateFile failed for path " << filename.value();
1069     return false;
1070   }
1071 
1072   DWORD written;
1073   DWORD size = checked_cast<DWORD>(data.size());
1074   BOOL result = ::WriteFile(file.get(), data.data(), size, &written, nullptr);
1075   if (result && written == size)
1076     return true;
1077 
1078   if (!result) {
1079     // WriteFile failed.
1080     VPLOG(1) << "Writing file " << filename.value() << " failed";
1081   } else {
1082     // Didn't write all the bytes.
1083     VPLOG(1) << "Only wrote " << written << " out of " << size << " byte(s) to "
1084              << filename.value();
1085   }
1086   return false;
1087 }
1088 
AppendToFile(const FilePath & filename,StringPiece data)1089 bool AppendToFile(const FilePath& filename, StringPiece data) {
1090   return AppendToFile(filename, as_bytes(make_span(data)));
1091 }
1092 
GetCurrentDirectory(FilePath * dir)1093 bool GetCurrentDirectory(FilePath* dir) {
1094   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1095 
1096   wchar_t system_buffer[MAX_PATH];
1097   system_buffer[0] = 0;
1098   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
1099   if (len == 0 || len > MAX_PATH)
1100     return false;
1101   // TODO(evanm): the old behavior of this function was to always strip the
1102   // trailing slash.  We duplicate this here, but it shouldn't be necessary
1103   // when everyone is using the appropriate FilePath APIs.
1104   *dir = FilePath(FilePath::StringPieceType(system_buffer))
1105              .StripTrailingSeparators();
1106   return true;
1107 }
1108 
SetCurrentDirectory(const FilePath & directory)1109 bool SetCurrentDirectory(const FilePath& directory) {
1110   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1111   return ::SetCurrentDirectory(directory.value().c_str()) != 0;
1112 }
1113 
GetMaximumPathComponentLength(const FilePath & path)1114 int GetMaximumPathComponentLength(const FilePath& path) {
1115   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1116 
1117   wchar_t volume_path[MAX_PATH];
1118   if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
1119                           volume_path, std::size(volume_path))) {
1120     return -1;
1121   }
1122 
1123   DWORD max_length = 0;
1124   if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
1125                              NULL, 0)) {
1126     return -1;
1127   }
1128 
1129   // Length of |path| with path separator appended.
1130   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
1131   // The whole path string must be shorter than MAX_PATH. That is, it must be
1132   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
1133   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
1134   return std::min(whole_path_limit, static_cast<int>(max_length));
1135 }
1136 
CopyFile(const FilePath & from_path,const FilePath & to_path)1137 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
1138   return DoCopyFile(from_path, to_path, false);
1139 }
1140 
SetNonBlocking(int fd)1141 bool SetNonBlocking(int fd) {
1142   unsigned long nonblocking = 1;
1143   if (ioctlsocket(static_cast<SOCKET>(fd), static_cast<long>(FIONBIO),
1144                   &nonblocking) == 0)
1145     return true;
1146   return false;
1147 }
1148 
PreReadFile(const FilePath & file_path,bool is_executable,bool sequential,int64_t max_bytes)1149 bool PreReadFile(const FilePath& file_path,
1150                  bool is_executable,
1151                  bool sequential,
1152                  int64_t max_bytes) {
1153   DCHECK_GE(max_bytes, 0);
1154 
1155   if (max_bytes == 0) {
1156     // ::PrefetchVirtualMemory() fails when asked to read zero bytes.
1157     // base::MemoryMappedFile::Initialize() fails on an empty file.
1158     return true;
1159   }
1160 
1161   // ::PrefetchVirtualMemory() fails if the file is opened with write access.
1162   MemoryMappedFile::Access access = is_executable
1163                                         ? MemoryMappedFile::READ_CODE_IMAGE
1164                                         : MemoryMappedFile::READ_ONLY;
1165   MemoryMappedFile mapped_file;
1166   if (!mapped_file.Initialize(file_path, access)) {
1167     return false;
1168   }
1169 
1170   const ::SIZE_T length =
1171       std::min(base::saturated_cast<::SIZE_T>(max_bytes),
1172                base::saturated_cast<::SIZE_T>(mapped_file.length()));
1173   ::_WIN32_MEMORY_RANGE_ENTRY address_range = {mapped_file.data(), length};
1174   // Use ::PrefetchVirtualMemory(). This is better than a
1175   // simple data file read, more from a RAM perspective than CPU. This is
1176   // because reading the file as data results in double mapping to
1177   // Image/executable pages for all pages of code executed.
1178   return ::PrefetchVirtualMemory(::GetCurrentProcess(),
1179                                  /*NumberOfEntries=*/1, &address_range,
1180                                  /*Flags=*/0);
1181 }
1182 
PreventExecuteMappingInternal(const FilePath & path,bool skip_path_check)1183 bool PreventExecuteMappingInternal(const FilePath& path, bool skip_path_check) {
1184   if (!base::FeatureList::IsEnabled(
1185           features::kEnforceNoExecutableFileHandles)) {
1186     return true;
1187   }
1188 
1189   bool is_path_safe = skip_path_check || IsPathSafeToSetAclOn(path);
1190 
1191   if (!is_path_safe) {
1192     // To mitigate the effect of past OS bugs where attackers are able to use
1193     // writeable handles to create malicious executable images which can be
1194     // later mapped into unsandboxed processes, file handles that permit writing
1195     // that are passed to untrusted processes, e.g. renderers, should be marked
1196     // with a deny execute ACE. This prevents re-opening the file for execute
1197     // later on.
1198     //
1199     // To accomplish this, code that needs to pass writable file handles to a
1200     // renderer should open the file with the flags added by
1201     // `AddFlagsForPassingToUntrustedProcess()` (explicitly
1202     // FLAG_WIN_NO_EXECUTE). This results in this PreventExecuteMapping being
1203     // called by base::File.
1204     //
1205     // However, simply using this universally on all files that are opened
1206     // writeable is also undesirable: things can and will randomly break if they
1207     // are marked no-exec (e.g. marking an exe that the user downloads as
1208     // no-exec will prevent the user from running it). There are also
1209     // performance implications of doing this for all files unnecessarily.
1210     //
1211     // Code that passes writable files to the renderer is also expected to
1212     // reference files in places like the user data dir (e.g. for the filesystem
1213     // API) or temp files. Any attempt to pass a writeable handle to a path
1214     // outside these areas is likely its own security issue as an untrusted
1215     // renderer process should never have write access to e.g. system files or
1216     // downloads.
1217     //
1218     // This check aims to catch misuse of
1219     // `AddFlagsForPassingToUntrustedProcess()` on paths outside these
1220     // locations. Any time it hits it is also likely that a handle to a
1221     // dangerous path is being passed to a renderer, which is inherently unsafe.
1222     //
1223     // If this check hits, please do not ignore it but consult security team.
1224     DLOG(FATAL) << "Unsafe to deny execute access to path : " << path;
1225 
1226     return false;
1227   }
1228 
1229   static constexpr wchar_t kEveryoneSid[] = L"WD";
1230   auto sids = win::Sid::FromSddlStringVector({kEveryoneSid});
1231 
1232   // Remove executable access from the file. The API does not add a duplicate
1233   // ACE if it already exists.
1234   return win::DenyAccessToPath(path, *sids, FILE_EXECUTE, /*NO_INHERITANCE=*/0,
1235                                /*recursive=*/false);
1236 }
1237 
PreventExecuteMapping(const FilePath & path)1238 bool PreventExecuteMapping(const FilePath& path) {
1239   return PreventExecuteMappingInternal(path, false);
1240 }
1241 
PreventExecuteMappingUnchecked(const FilePath & path,base::PassKey<PreventExecuteMappingClasses> passkey)1242 bool PreventExecuteMappingUnchecked(
1243     const FilePath& path,
1244     base::PassKey<PreventExecuteMappingClasses> passkey) {
1245   return PreventExecuteMappingInternal(path, true);
1246 }
1247 
SetExtraNoExecuteAllowedPath(int path_key)1248 void SetExtraNoExecuteAllowedPath(int path_key) {
1249   DCHECK(!g_extra_allowed_path_for_no_execute ||
1250          g_extra_allowed_path_for_no_execute == path_key);
1251   g_extra_allowed_path_for_no_execute = path_key;
1252   base::FilePath valid_path;
1253   DCHECK(
1254       base::PathService::Get(g_extra_allowed_path_for_no_execute, &valid_path));
1255 }
1256 
1257 // -----------------------------------------------------------------------------
1258 
1259 namespace internal {
1260 
MoveUnsafe(const FilePath & from_path,const FilePath & to_path)1261 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
1262   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1263 
1264   // NOTE: I suspect we could support longer paths, but that would involve
1265   // analyzing all our usage of files.
1266   if (from_path.value().length() >= MAX_PATH ||
1267       to_path.value().length() >= MAX_PATH) {
1268     return false;
1269   }
1270   if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
1271                  MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
1272     return true;
1273 
1274   // Keep the last error value from MoveFileEx around in case the below
1275   // fails.
1276   bool ret = false;
1277   DWORD last_error = ::GetLastError();
1278 
1279   if (DirectoryExists(from_path)) {
1280     // MoveFileEx fails if moving directory across volumes. We will simulate
1281     // the move by using Copy and Delete. Ideally we could check whether
1282     // from_path and to_path are indeed in different volumes.
1283     ret = internal::CopyAndDeleteDirectory(from_path, to_path);
1284   }
1285 
1286   if (!ret) {
1287     // Leave a clue about what went wrong so that it can be (at least) picked
1288     // up by a PLOG entry.
1289     ::SetLastError(last_error);
1290   }
1291 
1292   return ret;
1293 }
1294 
CopyAndDeleteDirectory(const FilePath & from_path,const FilePath & to_path)1295 bool CopyAndDeleteDirectory(const FilePath& from_path,
1296                             const FilePath& to_path) {
1297   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1298   if (CopyDirectory(from_path, to_path, true)) {
1299     if (DeletePathRecursively(from_path))
1300       return true;
1301 
1302     // Like Move, this function is not transactional, so we just
1303     // leave the copied bits behind if deleting from_path fails.
1304     // If to_path exists previously then we have already overwritten
1305     // it by now, we don't get better off by deleting the new bits.
1306   }
1307   return false;
1308 }
1309 
1310 }  // namespace internal
1311 }  // namespace base
1312