• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 #include <io.h>
10 #include <psapi.h>
11 #include <shellapi.h>
12 #include <shlobj.h>
13 #include <stddef.h>
14 #include <stdint.h>
15 #include <time.h>
16 #include <winsock2.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   // Ignore .profraw profiling files, as they can occur anywhere, and only occur
383   // during testing.
384   if (path.Extension() == FILE_PATH_LITERAL(".profraw")) {
385     return true;
386   }
387 #endif  // BUILDFLAG(CLANG_PROFILING)
388   std::vector<int> valid_path_keys({DIR_TEMP});
389   if (g_extra_allowed_path_for_no_execute) {
390     valid_path_keys.push_back(g_extra_allowed_path_for_no_execute);
391   }
392 
393   // MakeLongFilePath is needed here because temp files can have an 8.3 path
394   // under certain conditions. See comments in base::MakeLongFilePath.
395   FilePath long_path = MakeLongFilePath(path);
396   DCHECK(!long_path.empty()) << "Cannot get long path for " << path;
397 
398   std::vector<FilePath> valid_paths;
399   for (const auto path_key : valid_path_keys) {
400     FilePath valid_path;
401     if (!PathService::Get(path_key, &valid_path)) {
402       DLOG(FATAL) << "Cannot get path for pathservice key " << path_key;
403       continue;
404     }
405     valid_paths.push_back(valid_path);
406   }
407 
408   // Admin users create temporary files in `GetSecureSystemTemp`, see
409   // `CreateNewTempDirectory` below.
410   FilePath secure_system_temp;
411   if (::IsUserAnAdmin() && GetSecureSystemTemp(&secure_system_temp)) {
412     valid_paths.push_back(secure_system_temp);
413   }
414 
415   for (const auto& valid_path : valid_paths) {
416     // Temp files can sometimes have an 8.3 path. See comments in
417     // `MakeLongFilePath`.
418     FilePath full_path = MakeLongFilePath(valid_path);
419     DCHECK(!full_path.empty()) << "Cannot get long path for " << valid_path;
420     if (full_path.IsParent(long_path)) {
421       return true;
422     }
423   }
424 
425   return false;
426 }
427 
428 }  // namespace
429 
GetDeleteFileCallback(const FilePath & path,OnceCallback<void (bool)> reply_callback)430 OnceClosure GetDeleteFileCallback(const FilePath& path,
431                                   OnceCallback<void(bool)> reply_callback) {
432   return GetDeleteFileCallbackInternal(path, /*recursive=*/false,
433                                        std::move(reply_callback));
434 }
435 
GetDeletePathRecursivelyCallback(const FilePath & path,OnceCallback<void (bool)> reply_callback)436 OnceClosure GetDeletePathRecursivelyCallback(
437     const FilePath& path,
438     OnceCallback<void(bool)> reply_callback) {
439   return GetDeleteFileCallbackInternal(path, /*recursive=*/true,
440                                        std::move(reply_callback));
441 }
442 
MakeAbsoluteFilePath(const FilePath & input)443 FilePath MakeAbsoluteFilePath(const FilePath& input) {
444   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
445   wchar_t file_path[MAX_PATH];
446   if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH))
447     return FilePath();
448   return FilePath(file_path);
449 }
450 
DeleteFile(const FilePath & path)451 bool DeleteFile(const FilePath& path) {
452   return DeleteFileOrSetLastError(path, /*recursive=*/false);
453 }
454 
DeletePathRecursively(const FilePath & path)455 bool DeletePathRecursively(const FilePath& path) {
456   return DeleteFileOrSetLastError(path, /*recursive=*/true);
457 }
458 
DeleteFileAfterReboot(const FilePath & path)459 bool DeleteFileAfterReboot(const FilePath& path) {
460   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
461 
462   if (path.value().length() >= MAX_PATH)
463     return false;
464 
465   return ::MoveFileEx(path.value().c_str(), nullptr,
466                       MOVEFILE_DELAY_UNTIL_REBOOT);
467 }
468 
ReplaceFile(const FilePath & from_path,const FilePath & to_path,File::Error * error)469 bool ReplaceFile(const FilePath& from_path,
470                  const FilePath& to_path,
471                  File::Error* error) {
472   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
473 
474   // Alias paths for investigation of shutdown hangs. crbug.com/1054164
475   FilePath::CharType from_path_str[MAX_PATH];
476   base::wcslcpy(from_path_str, from_path.value().c_str(),
477                 std::size(from_path_str));
478   base::debug::Alias(from_path_str);
479   FilePath::CharType to_path_str[MAX_PATH];
480   base::wcslcpy(to_path_str, to_path.value().c_str(), std::size(to_path_str));
481   base::debug::Alias(to_path_str);
482 
483   // Assume that |to_path| already exists and try the normal replace. This will
484   // fail with ERROR_FILE_NOT_FOUND if |to_path| does not exist. When writing to
485   // a network share, we may not be able to change the ACLs. Ignore ACL errors
486   // then (REPLACEFILE_IGNORE_MERGE_ERRORS).
487   if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL,
488                     REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
489     return true;
490   }
491 
492   File::Error replace_error = File::OSErrorToFileError(GetLastError());
493 
494   // Try a simple move next. It will only succeed when |to_path| doesn't already
495   // exist.
496   if (::MoveFile(from_path.value().c_str(), to_path.value().c_str()))
497     return true;
498 
499   // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely that
500   // |to_path| does not exist. In this case, the more relevant error comes
501   // from the call to MoveFile.
502   if (error) {
503     *error = replace_error == File::FILE_ERROR_NOT_FOUND
504                  ? File::GetLastFileError()
505                  : replace_error;
506   }
507   return false;
508 }
509 
CopyDirectory(const FilePath & from_path,const FilePath & to_path,bool recursive)510 bool CopyDirectory(const FilePath& from_path,
511                    const FilePath& to_path,
512                    bool recursive) {
513   return DoCopyDirectory(from_path, to_path, recursive, false);
514 }
515 
CopyDirectoryExcl(const FilePath & from_path,const FilePath & to_path,bool recursive)516 bool CopyDirectoryExcl(const FilePath& from_path,
517                        const FilePath& to_path,
518                        bool recursive) {
519   return DoCopyDirectory(from_path, to_path, recursive, true);
520 }
521 
PathExists(const FilePath & path)522 bool PathExists(const FilePath& path) {
523   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
524   return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
525 }
526 
527 namespace {
528 
PathHasAccess(const FilePath & path,DWORD dir_desired_access,DWORD file_desired_access)529 bool PathHasAccess(const FilePath& path,
530                    DWORD dir_desired_access,
531                    DWORD file_desired_access) {
532   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
533 
534   const wchar_t* const path_str = path.value().c_str();
535   DWORD fileattr = GetFileAttributes(path_str);
536   if (fileattr == INVALID_FILE_ATTRIBUTES)
537     return false;
538 
539   bool is_directory = fileattr & FILE_ATTRIBUTE_DIRECTORY;
540   DWORD desired_access =
541       is_directory ? dir_desired_access : file_desired_access;
542   DWORD flags_and_attrs =
543       is_directory ? FILE_FLAG_BACKUP_SEMANTICS : FILE_ATTRIBUTE_NORMAL;
544 
545   win::ScopedHandle file(CreateFile(path_str, desired_access, kFileShareAll,
546                                     nullptr, OPEN_EXISTING, flags_and_attrs,
547                                     nullptr));
548 
549   return file.is_valid();
550 }
551 
552 }  // namespace
553 
PathIsReadable(const FilePath & path)554 bool PathIsReadable(const FilePath& path) {
555   return PathHasAccess(path, FILE_LIST_DIRECTORY, GENERIC_READ);
556 }
557 
PathIsWritable(const FilePath & path)558 bool PathIsWritable(const FilePath& path) {
559   return PathHasAccess(path, FILE_ADD_FILE, GENERIC_WRITE);
560 }
561 
DirectoryExists(const FilePath & path)562 bool DirectoryExists(const FilePath& path) {
563   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
564   DWORD fileattr = GetFileAttributes(path.value().c_str());
565   if (fileattr != INVALID_FILE_ATTRIBUTES)
566     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
567   return false;
568 }
569 
GetTempDir(FilePath * path)570 bool GetTempDir(FilePath* path) {
571   wchar_t temp_path[MAX_PATH + 1];
572   DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
573   if (path_len >= MAX_PATH || path_len <= 0)
574     return false;
575   // TODO(evanm): the old behavior of this function was to always strip the
576   // trailing slash.  We duplicate this here, but it shouldn't be necessary
577   // when everyone is using the appropriate FilePath APIs.
578   *path = FilePath(temp_path).StripTrailingSeparators();
579   return true;
580 }
581 
GetHomeDir()582 FilePath GetHomeDir() {
583   wchar_t result[MAX_PATH];
584   if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT,
585                                 result)) &&
586       result[0]) {
587     return FilePath(result);
588   }
589 
590   // Fall back to the temporary directory on failure.
591   FilePath temp;
592   if (GetTempDir(&temp))
593     return temp;
594 
595   // Last resort.
596   return FilePath(FILE_PATH_LITERAL("C:\\"));
597 }
598 
CreateAndOpenTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)599 File CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
600   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
601 
602   // Open the file with exclusive r/w/d access, and allow the caller to decide
603   // to mark it for deletion upon close after the fact.
604   constexpr uint32_t kFlags = File::FLAG_CREATE | File::FLAG_READ |
605                               File::FLAG_WRITE | File::FLAG_WIN_EXCLUSIVE_READ |
606                               File::FLAG_WIN_EXCLUSIVE_WRITE |
607                               File::FLAG_CAN_DELETE_ON_CLOSE;
608 
609   // Use GUID instead of ::GetTempFileName() to generate unique file names.
610   // "Due to the algorithm used to generate file names, GetTempFileName can
611   // perform poorly when creating a large number of files with the same prefix.
612   // In such cases, it is recommended that you construct unique file names based
613   // on GUIDs."
614   // https://msdn.microsoft.com/library/windows/desktop/aa364991.aspx
615 
616   FilePath temp_name;
617   File file;
618 
619   // Although it is nearly impossible to get a duplicate name with GUID, we
620   // still use a loop here in case it happens.
621   for (int i = 0; i < 100; ++i) {
622     temp_name = dir.Append(FormatTemporaryFileName(
623         UTF8ToWide(Uuid::GenerateRandomV4().AsLowercaseString())));
624     file.Initialize(temp_name, kFlags);
625     if (file.IsValid())
626       break;
627   }
628 
629   if (!file.IsValid()) {
630     DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
631     return file;
632   }
633 
634   wchar_t long_temp_name[MAX_PATH + 1];
635   const DWORD long_name_len =
636       GetLongPathName(temp_name.value().c_str(), long_temp_name, MAX_PATH);
637   if (long_name_len != 0 && long_name_len <= MAX_PATH) {
638     *temp_file =
639         FilePath(FilePath::StringPieceType(long_temp_name, long_name_len));
640   } else {
641     // GetLongPathName() failed, but we still have a temporary file.
642     *temp_file = std::move(temp_name);
643   }
644 
645   return file;
646 }
647 
CreateTemporaryFileInDir(const FilePath & dir,FilePath * temp_file)648 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
649   return CreateAndOpenTemporaryFileInDir(dir, temp_file).IsValid();
650 }
651 
FormatTemporaryFileName(FilePath::StringPieceType identifier)652 FilePath FormatTemporaryFileName(FilePath::StringPieceType identifier) {
653   return FilePath(StrCat({identifier, FILE_PATH_LITERAL(".tmp")}));
654 }
655 
CreateAndOpenTemporaryStreamInDir(const FilePath & dir,FilePath * path)656 ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
657                                              FilePath* path) {
658   // Open file in binary mode, to avoid problems with fwrite. On Windows
659   // it replaces \n's with \r\n's, which may surprise you.
660   // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
661   return ScopedFILE(
662       FileToFILE(CreateAndOpenTemporaryFileInDir(dir, path), "wb+"));
663 }
664 
CreateTemporaryDirInDir(const FilePath & base_dir,const FilePath::StringType & prefix,FilePath * new_dir)665 bool CreateTemporaryDirInDir(const FilePath& base_dir,
666                              const FilePath::StringType& prefix,
667                              FilePath* new_dir) {
668   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
669 
670   FilePath path_to_create;
671 
672   for (int count = 0; count < 50; ++count) {
673     // Try create a new temporary directory with random generated name. If
674     // the one exists, keep trying another path name until we reach some limit.
675     std::wstring new_dir_name;
676     new_dir_name.assign(prefix);
677     new_dir_name.append(AsWString(NumberToString16(GetCurrentProcId())));
678     new_dir_name.push_back('_');
679     new_dir_name.append(AsWString(
680         NumberToString16(RandInt(0, std::numeric_limits<int32_t>::max()))));
681 
682     path_to_create = base_dir.Append(new_dir_name);
683     if (::CreateDirectory(path_to_create.value().c_str(), NULL)) {
684       *new_dir = path_to_create;
685       return true;
686     }
687   }
688 
689   return false;
690 }
691 
GetSecureSystemTemp(FilePath * temp)692 bool GetSecureSystemTemp(FilePath* temp) {
693   if (g_disable_secure_system_temp_for_testing) {
694     return false;
695   }
696 
697   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
698 
699   CHECK(temp);
700 
701   for (const auto key : {DIR_WINDOWS, DIR_PROGRAM_FILES}) {
702     FilePath secure_system_temp;
703     if (!PathService::Get(key, &secure_system_temp)) {
704       continue;
705     }
706 
707     if (key == DIR_WINDOWS) {
708       secure_system_temp = secure_system_temp.AppendASCII("SystemTemp");
709     }
710 
711     if (PathExists(secure_system_temp) && PathIsWritable(secure_system_temp)) {
712       *temp = secure_system_temp;
713       return true;
714     }
715   }
716 
717   return false;
718 }
719 
SetDisableSecureSystemTempForTesting(bool disabled)720 void SetDisableSecureSystemTempForTesting(bool disabled) {
721   g_disable_secure_system_temp_for_testing = disabled;
722 }
723 
724 // The directory is created under `GetSecureSystemTemp` for security reasons if
725 // the caller is admin to avoid attacks from lower privilege processes.
726 //
727 // If unable to create a dir under `GetSecureSystemTemp`, the dir is created
728 // under %TEMP%. The reasons for not being able to create a dir under
729 // `GetSecureSystemTemp` could be because `%systemroot%\SystemTemp` does not
730 // exist, or unable to resolve `DIR_WINDOWS` or `DIR_PROGRAM_FILES`, say due to
731 // registry redirection, or unable to create a directory due to
732 // `GetSecureSystemTemp` being read-only or having atypical ACLs. Tests can also
733 // disable this behavior resulting in false being returned.
CreateNewTempDirectory(const FilePath::StringType & prefix,FilePath * new_temp_path)734 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
735                             FilePath* new_temp_path) {
736   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
737 
738   DCHECK(new_temp_path);
739 
740   FilePath parent_dir;
741   if (::IsUserAnAdmin() && GetSecureSystemTemp(&parent_dir) &&
742       CreateTemporaryDirInDir(parent_dir,
743                               prefix.empty() ? kDefaultTempDirPrefix : prefix,
744                               new_temp_path)) {
745     return true;
746   }
747 
748   if (!GetTempDir(&parent_dir))
749     return false;
750 
751   return CreateTemporaryDirInDir(parent_dir, prefix, new_temp_path);
752 }
753 
CreateDirectoryAndGetError(const FilePath & full_path,File::Error * error)754 bool CreateDirectoryAndGetError(const FilePath& full_path,
755                                 File::Error* error) {
756   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
757 
758   // If the path exists, we've succeeded if it's a directory, failed otherwise.
759   const wchar_t* const full_path_str = full_path.value().c_str();
760   const DWORD fileattr = ::GetFileAttributes(full_path_str);
761   if (fileattr != INVALID_FILE_ATTRIBUTES) {
762     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
763       return true;
764     }
765     DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), "
766                   << "conflicts with existing file.";
767     if (error)
768       *error = File::FILE_ERROR_NOT_A_DIRECTORY;
769     ::SetLastError(ERROR_FILE_EXISTS);
770     return false;
771   }
772 
773   // Invariant:  Path does not exist as file or directory.
774 
775   // Attempt to create the parent recursively.  This will immediately return
776   // true if it already exists, otherwise will create all required parent
777   // directories starting with the highest-level missing parent.
778   FilePath parent_path(full_path.DirName());
779   if (parent_path.value() == full_path.value()) {
780     if (error)
781       *error = File::FILE_ERROR_NOT_FOUND;
782     ::SetLastError(ERROR_FILE_NOT_FOUND);
783     return false;
784   }
785   if (!CreateDirectoryAndGetError(parent_path, error)) {
786     DLOG(WARNING) << "Failed to create one of the parent directories.";
787     DCHECK(!error || *error != File::FILE_OK);
788     return false;
789   }
790 
791   if (::CreateDirectory(full_path_str, NULL))
792     return true;
793 
794   const DWORD error_code = ::GetLastError();
795   if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
796     // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we were
797     // racing with someone creating the same directory, or a file with the same
798     // path.  If DirectoryExists() returns true, we lost the race to create the
799     // same directory.
800     return true;
801   }
802   if (error)
803     *error = File::OSErrorToFileError(error_code);
804   ::SetLastError(error_code);
805   DPLOG(WARNING) << "Failed to create directory " << full_path_str;
806   return false;
807 }
808 
NormalizeFilePath(const FilePath & path,FilePath * real_path)809 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
810   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
811   File file(path,
812             File::FLAG_OPEN | File::FLAG_READ | File::FLAG_WIN_SHARE_DELETE);
813   if (!file.IsValid())
814     return false;
815 
816   // The expansion of |path| into a full path may make it longer.
817   constexpr int kMaxPathLength = MAX_PATH + 10;
818   wchar_t native_file_path[kMaxPathLength];
819   // kMaxPathLength includes space for trailing '\0' so we subtract 1.
820   // Returned length, used_wchars, does not include trailing '\0'.
821   // Failure is indicated by returning 0 or >= kMaxPathLength.
822   DWORD used_wchars = ::GetFinalPathNameByHandle(
823       file.GetPlatformFile(), native_file_path, kMaxPathLength - 1,
824       FILE_NAME_NORMALIZED | VOLUME_NAME_NT);
825 
826   if (used_wchars >= kMaxPathLength || used_wchars == 0)
827     return false;
828 
829   // GetFinalPathNameByHandle() returns the \\?\ syntax for file names and
830   // existing code expects we return a path starting 'X:\' so we call
831   // DevicePathToDriveLetterPath rather than using VOLUME_NAME_DOS above.
832   return DevicePathToDriveLetterPath(
833       FilePath(FilePath::StringPieceType(native_file_path, used_wchars)),
834       real_path);
835 }
836 
DevicePathToDriveLetterPath(const FilePath & nt_device_path,FilePath * out_drive_letter_path)837 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
838                                  FilePath* out_drive_letter_path) {
839   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
840 
841   // Get the mapping of drive letters to device paths.
842   const int kDriveMappingSize = 1024;
843   wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
844   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
845     DLOG(ERROR) << "Failed to get drive mapping.";
846     return false;
847   }
848 
849   // The drive mapping is a sequence of null terminated strings.
850   // The last string is empty.
851   wchar_t* drive_map_ptr = drive_mapping;
852   wchar_t device_path_as_string[MAX_PATH];
853   wchar_t drive[] = FILE_PATH_LITERAL(" :");
854 
855   // For each string in the drive mapping, get the junction that links
856   // to it.  If that junction is a prefix of |device_path|, then we
857   // know that |drive| is the real path prefix.
858   while (*drive_map_ptr) {
859     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
860 
861     if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) {
862       FilePath device_path(device_path_as_string);
863       if (device_path == nt_device_path ||
864           device_path.IsParent(nt_device_path)) {
865         *out_drive_letter_path =
866             FilePath(drive + nt_device_path.value().substr(
867                                  wcslen(device_path_as_string)));
868         return true;
869       }
870     }
871     // Move to the next drive letter string, which starts one
872     // increment after the '\0' that terminates the current string.
873     while (*drive_map_ptr++) {}
874   }
875 
876   // No drive matched.  The path does not start with a device junction
877   // that is mounted as a drive letter.  This means there is no drive
878   // letter path to the volume that holds |device_path|, so fail.
879   return false;
880 }
881 
MakeLongFilePath(const FilePath & input)882 FilePath MakeLongFilePath(const FilePath& input) {
883   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
884 
885   DWORD path_long_len = ::GetLongPathName(input.value().c_str(), nullptr, 0);
886   if (path_long_len == 0UL)
887     return FilePath();
888 
889   std::wstring path_long_str;
890   path_long_len = ::GetLongPathName(input.value().c_str(),
891                                     WriteInto(&path_long_str, path_long_len),
892                                     path_long_len);
893   if (path_long_len == 0UL)
894     return FilePath();
895 
896   return FilePath(path_long_str);
897 }
898 
CreateWinHardLink(const FilePath & to_file,const FilePath & from_file)899 bool CreateWinHardLink(const FilePath& to_file, const FilePath& from_file) {
900   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
901   return ::CreateHardLink(to_file.value().c_str(), from_file.value().c_str(),
902                           nullptr);
903 }
904 
905 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
906 // them if we do decide to.
IsLink(const FilePath & file_path)907 bool IsLink(const FilePath& file_path) {
908   return false;
909 }
910 
GetFileInfo(const FilePath & file_path,File::Info * results)911 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
912   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
913 
914   WIN32_FILE_ATTRIBUTE_DATA attr;
915   if (!GetFileAttributesEx(file_path.value().c_str(), GetFileExInfoStandard,
916                            &attr)) {
917     return false;
918   }
919 
920   ULARGE_INTEGER size;
921   size.HighPart = attr.nFileSizeHigh;
922   size.LowPart = attr.nFileSizeLow;
923   // TODO(crbug.com/1333521): Change Info::size to uint64_t and eliminate this
924   // cast.
925   results->size = checked_cast<int64_t>(size.QuadPart);
926 
927   results->is_directory =
928       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
929   results->last_modified = Time::FromFileTime(attr.ftLastWriteTime);
930   results->last_accessed = Time::FromFileTime(attr.ftLastAccessTime);
931   results->creation_time = Time::FromFileTime(attr.ftCreationTime);
932 
933   return true;
934 }
935 
OpenFile(const FilePath & filename,const char * mode)936 FILE* OpenFile(const FilePath& filename, const char* mode) {
937   // 'N' is unconditionally added below, so be sure there is not one already
938   // present before a comma in |mode|.
939   DCHECK(
940       strchr(mode, 'N') == nullptr ||
941       (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ',')));
942   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
943   std::wstring w_mode = UTF8ToWide(mode);
944   AppendModeCharacter(L'N', &w_mode);
945   return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
946 }
947 
FileToFILE(File file,const char * mode)948 FILE* FileToFILE(File file, const char* mode) {
949   DCHECK(!file.async());
950   if (!file.IsValid())
951     return NULL;
952   int fd =
953       _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
954   if (fd < 0)
955     return NULL;
956   file.TakePlatformFile();
957   FILE* stream = _fdopen(fd, mode);
958   if (!stream)
959     _close(fd);
960   return stream;
961 }
962 
FILEToFile(FILE * file_stream)963 File FILEToFile(FILE* file_stream) {
964   if (!file_stream)
965     return File();
966 
967   int fd = _fileno(file_stream);
968   DCHECK_GE(fd, 0);
969   intptr_t file_handle = _get_osfhandle(fd);
970   DCHECK_NE(file_handle, reinterpret_cast<intptr_t>(INVALID_HANDLE_VALUE));
971 
972   HANDLE other_handle = nullptr;
973   if (!::DuplicateHandle(
974           /*hSourceProcessHandle=*/GetCurrentProcess(),
975           reinterpret_cast<HANDLE>(file_handle),
976           /*hTargetProcessHandle=*/GetCurrentProcess(), &other_handle,
977           /*dwDesiredAccess=*/0,
978           /*bInheritHandle=*/FALSE,
979           /*dwOptions=*/DUPLICATE_SAME_ACCESS)) {
980     return File(File::GetLastFileError());
981   }
982 
983   return File(ScopedPlatformFile(other_handle));
984 }
985 
ReadFile(const FilePath & filename,char * data,int max_size)986 int ReadFile(const FilePath& filename, char* data, int max_size) {
987   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
988   win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_READ,
989                                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
990                                     OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
991                                     NULL));
992   if (!file.is_valid() || max_size < 0)
993     return -1;
994 
995   DWORD read;
996   if (::ReadFile(file.get(), data, static_cast<DWORD>(max_size), &read, NULL)) {
997     // TODO(crbug.com/1333521): Change to return some type with a uint64_t size
998     // and eliminate this cast.
999     return checked_cast<int>(read);
1000   }
1001 
1002   return -1;
1003 }
1004 
WriteFile(const FilePath & filename,const char * data,int size)1005 int WriteFile(const FilePath& filename, const char* data, int size) {
1006   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1007   win::ScopedHandle file(CreateFile(filename.value().c_str(), GENERIC_WRITE, 0,
1008                                     NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
1009                                     NULL));
1010   if (!file.is_valid() || size < 0) {
1011     DPLOG(WARNING) << "WriteFile failed for path " << filename.value();
1012     return -1;
1013   }
1014 
1015   DWORD written;
1016   BOOL result =
1017       ::WriteFile(file.get(), data, static_cast<DWORD>(size), &written, NULL);
1018   if (result && static_cast<int>(written) == size)
1019     return static_cast<int>(written);
1020 
1021   if (!result) {
1022     // WriteFile failed.
1023     DPLOG(WARNING) << "writing file " << filename.value() << " failed";
1024   } else {
1025     // Didn't write all the bytes.
1026     DLOG(WARNING) << "wrote" << written << " bytes to " << filename.value()
1027                   << " expected " << size;
1028   }
1029   return -1;
1030 }
1031 
AppendToFile(const FilePath & filename,span<const uint8_t> data)1032 bool AppendToFile(const FilePath& filename, span<const uint8_t> data) {
1033   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1034   win::ScopedHandle file(CreateFile(filename.value().c_str(), FILE_APPEND_DATA,
1035                                     0, nullptr, OPEN_EXISTING, 0, nullptr));
1036   if (!file.is_valid()) {
1037     VPLOG(1) << "CreateFile failed for path " << filename.value();
1038     return false;
1039   }
1040 
1041   DWORD written;
1042   DWORD size = checked_cast<DWORD>(data.size());
1043   BOOL result = ::WriteFile(file.get(), data.data(), size, &written, nullptr);
1044   if (result && written == size)
1045     return true;
1046 
1047   if (!result) {
1048     // WriteFile failed.
1049     VPLOG(1) << "Writing file " << filename.value() << " failed";
1050   } else {
1051     // Didn't write all the bytes.
1052     VPLOG(1) << "Only wrote " << written << " out of " << size << " byte(s) to "
1053              << filename.value();
1054   }
1055   return false;
1056 }
1057 
AppendToFile(const FilePath & filename,StringPiece data)1058 bool AppendToFile(const FilePath& filename, StringPiece data) {
1059   return AppendToFile(filename, as_bytes(make_span(data)));
1060 }
1061 
GetCurrentDirectory(FilePath * dir)1062 bool GetCurrentDirectory(FilePath* dir) {
1063   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1064 
1065   wchar_t system_buffer[MAX_PATH];
1066   system_buffer[0] = 0;
1067   DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
1068   if (len == 0 || len > MAX_PATH)
1069     return false;
1070   // TODO(evanm): the old behavior of this function was to always strip the
1071   // trailing slash.  We duplicate this here, but it shouldn't be necessary
1072   // when everyone is using the appropriate FilePath APIs.
1073   *dir = FilePath(FilePath::StringPieceType(system_buffer))
1074              .StripTrailingSeparators();
1075   return true;
1076 }
1077 
SetCurrentDirectory(const FilePath & directory)1078 bool SetCurrentDirectory(const FilePath& directory) {
1079   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1080   return ::SetCurrentDirectory(directory.value().c_str()) != 0;
1081 }
1082 
GetMaximumPathComponentLength(const FilePath & path)1083 int GetMaximumPathComponentLength(const FilePath& path) {
1084   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1085 
1086   wchar_t volume_path[MAX_PATH];
1087   if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(),
1088                           volume_path, std::size(volume_path))) {
1089     return -1;
1090   }
1091 
1092   DWORD max_length = 0;
1093   if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL,
1094                              NULL, 0)) {
1095     return -1;
1096   }
1097 
1098   // Length of |path| with path separator appended.
1099   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
1100   // The whole path string must be shorter than MAX_PATH. That is, it must be
1101   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
1102   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
1103   return std::min(whole_path_limit, static_cast<int>(max_length));
1104 }
1105 
CopyFile(const FilePath & from_path,const FilePath & to_path)1106 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
1107   return DoCopyFile(from_path, to_path, false);
1108 }
1109 
SetNonBlocking(int fd)1110 bool SetNonBlocking(int fd) {
1111   unsigned long nonblocking = 1;
1112   if (ioctlsocket(static_cast<SOCKET>(fd), static_cast<long>(FIONBIO),
1113                   &nonblocking) == 0)
1114     return true;
1115   return false;
1116 }
1117 
PreReadFile(const FilePath & file_path,bool is_executable,int64_t max_bytes)1118 bool PreReadFile(const FilePath& file_path,
1119                  bool is_executable,
1120                  int64_t max_bytes) {
1121   DCHECK_GE(max_bytes, 0);
1122 
1123   if (max_bytes == 0) {
1124     // ::PrefetchVirtualMemory() fails when asked to read zero bytes.
1125     // base::MemoryMappedFile::Initialize() fails on an empty file.
1126     return true;
1127   }
1128 
1129   // ::PrefetchVirtualMemory() fails if the file is opened with write access.
1130   MemoryMappedFile::Access access = is_executable
1131                                         ? MemoryMappedFile::READ_CODE_IMAGE
1132                                         : MemoryMappedFile::READ_ONLY;
1133   MemoryMappedFile mapped_file;
1134   if (!mapped_file.Initialize(file_path, access))
1135     return internal::PreReadFileSlow(file_path, max_bytes);
1136 
1137   const ::SIZE_T length =
1138       std::min(base::saturated_cast<::SIZE_T>(max_bytes),
1139                base::saturated_cast<::SIZE_T>(mapped_file.length()));
1140   ::_WIN32_MEMORY_RANGE_ENTRY address_range = {mapped_file.data(), length};
1141   // Use ::PrefetchVirtualMemory(). This is better than a
1142   // simple data file read, more from a RAM perspective than CPU. This is
1143   // because reading the file as data results in double mapping to
1144   // Image/executable pages for all pages of code executed.
1145   if (!::PrefetchVirtualMemory(::GetCurrentProcess(),
1146                                /*NumberOfEntries=*/1, &address_range,
1147                                /*Flags=*/0)) {
1148     return internal::PreReadFileSlow(file_path, max_bytes);
1149   }
1150   return true;
1151 }
1152 
PreventExecuteMapping(const FilePath & path)1153 bool PreventExecuteMapping(const FilePath& path) {
1154   if (!base::FeatureList::IsEnabled(
1155           features::kEnforceNoExecutableFileHandles)) {
1156     return true;
1157   }
1158 
1159   bool is_path_safe = IsPathSafeToSetAclOn(path);
1160 
1161   if (!is_path_safe) {
1162     // To mitigate the effect of past OS bugs where attackers are able to use
1163     // writeable handles to create malicious executable images which can be
1164     // later mapped into unsandboxed processes, file handles that permit writing
1165     // that are passed to untrusted processes, e.g. renderers, should be marked
1166     // with a deny execute ACE. This prevents re-opening the file for execute
1167     // later on.
1168     //
1169     // To accomplish this, code that needs to pass writable file handles to a
1170     // renderer should open the file with the flags added by
1171     // `AddFlagsForPassingToUntrustedProcess()` (explicitly
1172     // FLAG_WIN_NO_EXECUTE). This results in this PreventExecuteMapping being
1173     // called by base::File.
1174     //
1175     // However, simply using this universally on all files that are opened
1176     // writeable is also undesirable: things can and will randomly break if they
1177     // are marked no-exec (e.g. marking an exe that the user downloads as
1178     // no-exec will prevent the user from running it). There are also
1179     // performance implications of doing this for all files unnecessarily.
1180     //
1181     // Code that passes writable files to the renderer is also expected to
1182     // reference files in places like the user data dir (e.g. for the filesystem
1183     // API) or temp files. Any attempt to pass a writeable handle to a path
1184     // outside these areas is likely its own security issue as an untrusted
1185     // renderer process should never have write access to e.g. system files or
1186     // downloads.
1187     //
1188     // This check aims to catch misuse of
1189     // `AddFlagsForPassingToUntrustedProcess()` on paths outside these
1190     // locations. Any time it hits it is also likely that a handle to a
1191     // dangerous path is being passed to a renderer, which is inherently unsafe.
1192     //
1193     // If this check hits, please do not ignore it but consult security team.
1194     DLOG(FATAL) << "Unsafe to deny execute access to path : " << path;
1195 
1196     return false;
1197   }
1198 
1199   static constexpr wchar_t kEveryoneSid[] = L"WD";
1200   auto sids = win::Sid::FromSddlStringVector({kEveryoneSid});
1201 
1202   // Remove executable access from the file. The API does not add a duplicate
1203   // ACE if it already exists.
1204   return win::DenyAccessToPath(path, *sids, FILE_EXECUTE, /*NO_INHERITANCE=*/0,
1205                                /*recursive=*/false);
1206 }
1207 
SetExtraNoExecuteAllowedPath(int path_key)1208 void SetExtraNoExecuteAllowedPath(int path_key) {
1209   DCHECK(!g_extra_allowed_path_for_no_execute ||
1210          g_extra_allowed_path_for_no_execute == path_key);
1211   g_extra_allowed_path_for_no_execute = path_key;
1212   base::FilePath valid_path;
1213   DCHECK(
1214       base::PathService::Get(g_extra_allowed_path_for_no_execute, &valid_path));
1215 }
1216 
1217 // -----------------------------------------------------------------------------
1218 
1219 namespace internal {
1220 
MoveUnsafe(const FilePath & from_path,const FilePath & to_path)1221 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
1222   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1223 
1224   // NOTE: I suspect we could support longer paths, but that would involve
1225   // analyzing all our usage of files.
1226   if (from_path.value().length() >= MAX_PATH ||
1227       to_path.value().length() >= MAX_PATH) {
1228     return false;
1229   }
1230   if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
1231                  MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
1232     return true;
1233 
1234   // Keep the last error value from MoveFileEx around in case the below
1235   // fails.
1236   bool ret = false;
1237   DWORD last_error = ::GetLastError();
1238 
1239   if (DirectoryExists(from_path)) {
1240     // MoveFileEx fails if moving directory across volumes. We will simulate
1241     // the move by using Copy and Delete. Ideally we could check whether
1242     // from_path and to_path are indeed in different volumes.
1243     ret = internal::CopyAndDeleteDirectory(from_path, to_path);
1244   }
1245 
1246   if (!ret) {
1247     // Leave a clue about what went wrong so that it can be (at least) picked
1248     // up by a PLOG entry.
1249     ::SetLastError(last_error);
1250   }
1251 
1252   return ret;
1253 }
1254 
CopyAndDeleteDirectory(const FilePath & from_path,const FilePath & to_path)1255 bool CopyAndDeleteDirectory(const FilePath& from_path,
1256                             const FilePath& to_path) {
1257   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
1258   if (CopyDirectory(from_path, to_path, true)) {
1259     if (DeletePathRecursively(from_path))
1260       return true;
1261 
1262     // Like Move, this function is not transactional, so we just
1263     // leave the copied bits behind if deleting from_path fails.
1264     // If to_path exists previously then we have already overwritten
1265     // it by now, we don't get better off by deleting the new bits.
1266   }
1267   return false;
1268 }
1269 
1270 }  // namespace internal
1271 }  // namespace base
1272