1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 // windows.h includes winsock.h which isn't compatible with winsock2.h. To use
8 // winsock2.h you have to include it first.
9 // clang-format off
10 #include <winsock2.h>
11 #include <windows.h>
12 // clang-format on
13 
14 #include <io.h>
15 #include <psapi.h>
16 #include <share.h>
17 #include <shellapi.h>
18 #include <shlobj.h>
19 #include <stddef.h>
20 #include <stdint.h>
21 #include <time.h>
22 
23 #include <algorithm>
24 #include <iterator>
25 #include <limits>
26 #include <string>
27 #include <string_view>
28 
29 #include "base/files/file_enumerator.h"
30 #include "base/files/file_path.h"
31 #include "base/logging.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_util.h"
34 #include "base/strings/stringprintf.h"
35 #include "base/strings/utf_string_conversions.h"
36 #include "base/win/scoped_handle.h"
37 #include "base/win/win_util.h"
38 
39 // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036.  See the
40 // "Community Additions" comment on MSDN here:
41 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
42 #define SystemFunction036 NTAPI SystemFunction036
43 #include <ntsecapi.h>
44 #undef SystemFunction036
45 
46 namespace base {
47 
48 namespace {
49 
50 const DWORD kFileShareAll =
51     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
52 
53 // Deletes all files and directories in a path.
54 // Returns ERROR_SUCCESS on success or the Windows error code corresponding to
55 // the first error encountered.
DeleteFileRecursive(const FilePath& path, const FilePath::StringType& pattern, bool recursive)56 DWORD DeleteFileRecursive(const FilePath& path,
57                           const FilePath::StringType& pattern,
58                           bool recursive) {
59   FileEnumerator traversal(path, false,
60                            FileEnumerator::FILES | FileEnumerator::DIRECTORIES,
61                            pattern);
62   DWORD result = ERROR_SUCCESS;
63   for (FilePath current = traversal.Next(); !current.empty();
64        current = traversal.Next()) {
65     // Try to clear the read-only bit if we find it.
66     FileEnumerator::FileInfo info = traversal.GetInfo();
67     if ((info.find_data().dwFileAttributes & FILE_ATTRIBUTE_READONLY) &&
68         (recursive || !info.IsDirectory())) {
69       ::SetFileAttributes(
70           ToWCharT(&current.value()),
71           info.find_data().dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
72     }
73 
74     DWORD this_result = ERROR_SUCCESS;
75     if (info.IsDirectory()) {
76       if (recursive) {
77         this_result = DeleteFileRecursive(current, pattern, true);
78         if (this_result == ERROR_SUCCESS &&
79             !::RemoveDirectory(ToWCharT(&current.value()))) {
80           this_result = ::GetLastError();
81         }
82       }
83     } else if (!::DeleteFile(ToWCharT(&current.value()))) {
84       this_result = ::GetLastError();
85     }
86     if (result == ERROR_SUCCESS)
87       result = this_result;
88   }
89   return result;
90 }
91 
92 // Appends |mode_char| to |mode| before the optional character set encoding; see
93 // https://msdn.microsoft.com/library/yeby3zcb.aspx for details.
AppendModeCharacter(char16_t mode_char, std::u16string* mode)94 void AppendModeCharacter(char16_t mode_char, std::u16string* mode) {
95   size_t comma_pos = mode->find(L',');
96   mode->insert(comma_pos == std::u16string::npos ? mode->length() : comma_pos,
97                1, mode_char);
98 }
99 
100 // Returns ERROR_SUCCESS on success, or a Windows error code on failure.
DoDeleteFile(const FilePath& path, bool recursive)101 DWORD DoDeleteFile(const FilePath& path, bool recursive) {
102   if (path.empty())
103     return ERROR_SUCCESS;
104 
105   if (path.value().length() >= MAX_PATH)
106     return ERROR_BAD_PATHNAME;
107 
108   // Handle any path with wildcards.
109   if (path.BaseName().value().find_first_of(u"*?") !=
110       FilePath::StringType::npos) {
111     return DeleteFileRecursive(path.DirName(), path.BaseName().value(),
112                                recursive);
113   }
114 
115   // Report success if the file or path does not exist.
116   const DWORD attr = ::GetFileAttributes(ToWCharT(&path.value()));
117   if (attr == INVALID_FILE_ATTRIBUTES) {
118     const DWORD error_code = ::GetLastError();
119     return (error_code == ERROR_FILE_NOT_FOUND ||
120             error_code == ERROR_PATH_NOT_FOUND)
121                ? ERROR_SUCCESS
122                : error_code;
123   }
124 
125   // Clear the read-only bit if it is set.
126   if ((attr & FILE_ATTRIBUTE_READONLY) &&
127       !::SetFileAttributes(ToWCharT(&path.value()),
128                            attr & ~FILE_ATTRIBUTE_READONLY)) {
129     return ::GetLastError();
130   }
131 
132   // Perform a simple delete on anything that isn't a directory.
133   if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
134     return ::DeleteFile(ToWCharT(&path.value())) ? ERROR_SUCCESS
135                                                  : ::GetLastError();
136   }
137 
138   if (recursive) {
139     const DWORD error_code = DeleteFileRecursive(path, u"*", true);
140     if (error_code != ERROR_SUCCESS)
141       return error_code;
142   }
143   return ::RemoveDirectory(ToWCharT(&path.value())) ? ERROR_SUCCESS
144                                                     : ::GetLastError();
145 }
146 
RandomDataToGUIDString(const uint64_t bytes[2])147 std::string RandomDataToGUIDString(const uint64_t bytes[2]) {
148   return base::StringPrintf(
149       "%08x-%04x-%04x-%04x-%012llx", static_cast<unsigned int>(bytes[0] >> 32),
150       static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
151       static_cast<unsigned int>(bytes[0] & 0x0000ffff),
152       static_cast<unsigned int>(bytes[1] >> 48),
153       bytes[1] & 0x0000ffff'ffffffffULL);
154 }
155 
156 void RandBytes(void* output, size_t output_length) {
157   char* output_ptr = static_cast<char*>(output);
158   while (output_length > 0) {
159     const ULONG output_bytes_this_pass = static_cast<ULONG>(std::min(
160         output_length, static_cast<size_t>(std::numeric_limits<ULONG>::max())));
161     const bool success =
162         RtlGenRandom(output_ptr, output_bytes_this_pass) != FALSE;
163     CHECK(success);
164     output_length -= output_bytes_this_pass;
165     output_ptr += output_bytes_this_pass;
166   }
167 }
168 
169 std::string GenerateGUID() {
170   uint64_t sixteen_bytes[2];
171   // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
172   // base version directly, and to prevent the dependency from base/ to crypto/.
173   RandBytes(&sixteen_bytes, sizeof(sixteen_bytes));
174 
175   // Set the GUID to version 4 as described in RFC 4122, section 4.4.
176   // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
177   // where y is one of [8, 9, A, B].
178 
179   // Clear the version bits and set the version to 4:
180   sixteen_bytes[0] &= 0xffffffff'ffff0fffULL;
181   sixteen_bytes[0] |= 0x00000000'00004000ULL;
182 
183   // Set the two most significant bits (bits 6 and 7) of the
184   // clock_seq_hi_and_reserved to zero and one, respectively:
185   sixteen_bytes[1] &= 0x3fffffff'ffffffffULL;
186   sixteen_bytes[1] |= 0x80000000'00000000ULL;
187 
188   return RandomDataToGUIDString(sixteen_bytes);
189 }
190 
191 }  // namespace
192 
193 FilePath MakeAbsoluteFilePath(const FilePath& input) {
194   char16_t file_path[MAX_PATH];
195   if (!_wfullpath(ToWCharT(file_path), ToWCharT(&input.value()), MAX_PATH))
196     return FilePath();
197   return FilePath(file_path);
198 }
199 
200 bool DeleteFile(const FilePath& path, bool recursive) {
201   static constexpr char kRecursive[] = "DeleteFile.Recursive";
202   static constexpr char kNonRecursive[] = "DeleteFile.NonRecursive";
203   const std::string_view operation(recursive ? kRecursive : kNonRecursive);
204 
205   // Metrics for delete failures tracked in https://crbug.com/599084. Delete may
206   // fail for a number of reasons. Log some metrics relating to failures in the
207   // current code so that any improvements or regressions resulting from
208   // subsequent code changes can be detected.
209   const DWORD error = DoDeleteFile(path, recursive);
210   return error == ERROR_SUCCESS;
211 }
212 
213 bool DeleteFileAfterReboot(const FilePath& path) {
214   if (path.value().length() >= MAX_PATH)
215     return false;
216 
217   return MoveFileEx(ToWCharT(&path.value()), NULL,
218                     MOVEFILE_DELAY_UNTIL_REBOOT | MOVEFILE_REPLACE_EXISTING) !=
219          FALSE;
220 }
221 
222 bool ReplaceFile(const FilePath& from_path,
223                  const FilePath& to_path,
224                  File::Error* error) {
225   // Try a simple move first.  It will only succeed when |to_path| doesn't
226   // already exist.
227   if (::MoveFile(ToWCharT(&from_path.value()), ToWCharT(&to_path.value())))
228     return true;
229   File::Error move_error = File::OSErrorToFileError(GetLastError());
230 
231   // Try the full-blown replace if the move fails, as ReplaceFile will only
232   // succeed when |to_path| does exist. When writing to a network share, we may
233   // not be able to change the ACLs. Ignore ACL errors then
234   // (REPLACEFILE_IGNORE_MERGE_ERRORS).
235   if (::ReplaceFile(ToWCharT(&to_path.value()), ToWCharT(&from_path.value()),
236                     NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) {
237     return true;
238   }
239   // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely that
240   // |to_path| does not exist. In this case, the more relevant error comes
241   // from the call to MoveFile.
242   if (error) {
243     File::Error replace_error = File::OSErrorToFileError(GetLastError());
244     *error = replace_error == File::FILE_ERROR_NOT_FOUND ? move_error
245                                                          : replace_error;
246   }
247   return false;
248 }
249 
PathExists(const FilePath& path)250 bool PathExists(const FilePath& path) {
251   return (GetFileAttributes(ToWCharT(&path.value())) !=
252           INVALID_FILE_ATTRIBUTES);
253 }
254 
PathIsWritable(const FilePath& path)255 bool PathIsWritable(const FilePath& path) {
256   HANDLE dir =
257       CreateFile(ToWCharT(&path.value()), FILE_ADD_FILE, kFileShareAll, NULL,
258                  OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
259 
260   if (dir == INVALID_HANDLE_VALUE)
261     return false;
262 
263   CloseHandle(dir);
264   return true;
265 }
266 
DirectoryExists(const FilePath& path)267 bool DirectoryExists(const FilePath& path) {
268   DWORD fileattr = GetFileAttributes(ToWCharT(&path.value()));
269   if (fileattr != INVALID_FILE_ATTRIBUTES)
270     return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
271   return false;
272 }
273 
GetTempDir(FilePath* path)274 bool GetTempDir(FilePath* path) {
275   char16_t temp_path[MAX_PATH + 1];
276   DWORD path_len = ::GetTempPath(MAX_PATH, ToWCharT(temp_path));
277   if (path_len >= MAX_PATH || path_len <= 0)
278     return false;
279   // TODO(evanm): the old behavior of this function was to always strip the
280   // trailing slash.  We duplicate this here, but it shouldn't be necessary
281   // when everyone is using the appropriate FilePath APIs.
282   *path = FilePath(temp_path).StripTrailingSeparators();
283   return true;
284 }
285 
CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file)286 File CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
287   constexpr uint32_t kFlags =
288       File::FLAG_CREATE | File::FLAG_READ | File::FLAG_WRITE;
289 
290   // Use GUID instead of ::GetTempFileName() to generate unique file names.
291   // "Due to the algorithm used to generate file names, GetTempFileName can
292   // perform poorly when creating a large number of files with the same prefix.
293   // In such cases, it is recommended that you construct unique file names based
294   // on GUIDs."
295   // https://msdn.microsoft.com/library/windows/desktop/aa364991.aspx
296 
297   FilePath temp_name;
298   File file;
299 
300   // Although it is nearly impossible to get a duplicate name with GUID, we
301   // still use a loop here in case it happens.
302   for (int i = 0; i < 100; ++i) {
303     temp_name = dir.Append(
304         FilePath(UTF8ToUTF16(GenerateGUID()) + FILE_PATH_LITERAL(".tmp")));
305     file.Initialize(temp_name, kFlags);
306     if (file.IsValid())
307       break;
308   }
309 
310   if (!file.IsValid()) {
311     DPLOG(WARNING) << "Failed to get temporary file name in "
312                    << UTF16ToUTF8(dir.value());
313     return file;
314   }
315 
316   char16_t long_temp_name[MAX_PATH + 1];
317   const DWORD long_name_len = GetLongPathName(
318       ToWCharT(temp_name.value().c_str()), ToWCharT(long_temp_name), MAX_PATH);
319   if (long_name_len != 0 && long_name_len <= MAX_PATH) {
320     *temp_file =
321         FilePath(FilePath::StringViewType(long_temp_name, long_name_len));
322   } else {
323     // GetLongPathName() failed, but we still have a temporary file.
324     *temp_file = std::move(temp_name);
325   }
326 
327   return file;
328 }
329 
CreateTemporaryDirInDir(const FilePath& base_dir, const FilePath::StringType& prefix, FilePath* new_dir)330 bool CreateTemporaryDirInDir(const FilePath& base_dir,
331                              const FilePath::StringType& prefix,
332                              FilePath* new_dir) {
333   FilePath path_to_create;
334 
335   for (int count = 0; count < 50; ++count) {
336     // Try create a new temporary directory with random generated name. If
337     // the one exists, keep trying another path name until we reach some limit.
338     std::u16string new_dir_name;
339     new_dir_name.assign(prefix);
340     new_dir_name.append(IntToString16(::GetCurrentProcessId()));
341     new_dir_name.push_back('_');
342     new_dir_name.append(UTF8ToUTF16(GenerateGUID()));
343 
344     path_to_create = base_dir.Append(new_dir_name);
345     if (::CreateDirectory(ToWCharT(&path_to_create.value()), NULL)) {
346       *new_dir = path_to_create;
347       return true;
348     }
349   }
350 
351   return false;
352 }
353 
CreateNewTempDirectory(const FilePath::StringType& prefix, FilePath* new_temp_path)354 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
355                             FilePath* new_temp_path) {
356   FilePath system_temp_dir;
357   if (!GetTempDir(&system_temp_dir))
358     return false;
359 
360   return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path);
361 }
362 
CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error)363 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error) {
364   // If the path exists, we've succeeded if it's a directory, failed otherwise.
365   DWORD fileattr = ::GetFileAttributes(ToWCharT(&full_path.value()));
366   if (fileattr != INVALID_FILE_ATTRIBUTES) {
367     if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
368       return true;
369     }
370     DLOG(WARNING) << "CreateDirectory(" << UTF16ToUTF8(full_path.value())
371                   << "), " << "conflicts with existing file.";
372     if (error) {
373       *error = File::FILE_ERROR_NOT_A_DIRECTORY;
374     }
375     return false;
376   }
377 
378   // Invariant:  Path does not exist as file or directory.
379 
380   // Attempt to create the parent recursively.  This will immediately return
381   // true if it already exists, otherwise will create all required parent
382   // directories starting with the highest-level missing parent.
383   FilePath parent_path(full_path.DirName());
384   if (parent_path.value() == full_path.value()) {
385     if (error) {
386       *error = File::FILE_ERROR_NOT_FOUND;
387     }
388     return false;
389   }
390   if (!CreateDirectoryAndGetError(parent_path, error)) {
391     DLOG(WARNING) << "Failed to create one of the parent directories.";
392     if (error) {
393       DCHECK(*error != File::FILE_OK);
394     }
395     return false;
396   }
397 
398   if (!::CreateDirectory(ToWCharT(&full_path.value()), NULL)) {
399     DWORD error_code = ::GetLastError();
400     if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
401       // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we
402       // were racing with someone creating the same directory, or a file
403       // with the same path.  If DirectoryExists() returns true, we lost the
404       // race to create the same directory.
405       return true;
406     } else {
407       if (error)
408         *error = File::OSErrorToFileError(error_code);
409       DLOG(WARNING) << "Failed to create directory "
410                     << UTF16ToUTF8(full_path.value()) << ", last error is "
411                     << error_code << ".";
412       return false;
413     }
414   } else {
415     return true;
416   }
417 }
418 
NormalizeFilePath(const FilePath& path, FilePath* real_path)419 bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
420   FilePath mapped_file;
421   if (!NormalizeToNativeFilePath(path, &mapped_file))
422     return false;
423   // NormalizeToNativeFilePath() will return a path that starts with
424   // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
425   // will find a drive letter which maps to the path's device, so
426   // that we return a path starting with a drive letter.
427   return DevicePathToDriveLetterPath(mapped_file, real_path);
428 }
429 
DevicePathToDriveLetterPath(const FilePath& nt_device_path, FilePath* out_drive_letter_path)430 bool DevicePathToDriveLetterPath(const FilePath& nt_device_path,
431                                  FilePath* out_drive_letter_path) {
432   // Get the mapping of drive letters to device paths.
433   const int kDriveMappingSize = 1024;
434   char16_t drive_mapping[kDriveMappingSize] = {'\0'};
435   if (!::GetLogicalDriveStrings(kDriveMappingSize - 1,
436                                 ToWCharT(drive_mapping))) {
437     DLOG(ERROR) << "Failed to get drive mapping.";
438     return false;
439   }
440 
441   // The drive mapping is a sequence of null terminated strings.
442   // The last string is empty.
443   char16_t* drive_map_ptr = drive_mapping;
444   char16_t device_path_as_string[MAX_PATH];
445   char16_t drive[] = u" :";
446 
447   // For each string in the drive mapping, get the junction that links
448   // to it.  If that junction is a prefix of |device_path|, then we
449   // know that |drive| is the real path prefix.
450   while (*drive_map_ptr) {
451     drive[0] = drive_map_ptr[0];  // Copy the drive letter.
452 
453     if (QueryDosDevice(ToWCharT(drive), ToWCharT(device_path_as_string),
454                        MAX_PATH)) {
455       FilePath device_path(device_path_as_string);
456       if (device_path == nt_device_path ||
457           device_path.IsParent(nt_device_path)) {
458         *out_drive_letter_path =
459             FilePath(drive + nt_device_path.value().substr(
460                                  wcslen(ToWCharT(device_path_as_string))));
461         return true;
462       }
463     }
464     // Move to the next drive letter string, which starts one
465     // increment after the '\0' that terminates the current string.
466     while (*drive_map_ptr++) {
467     }
468   }
469 
470   // No drive matched.  The path does not start with a device junction
471   // that is mounted as a drive letter.  This means there is no drive
472   // letter path to the volume that holds |device_path|, so fail.
473   return false;
474 }
475 
NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path)476 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) {
477   // In Vista, GetFinalPathNameByHandle() would give us the real path
478   // from a file handle.  If we ever deprecate XP, consider changing the
479   // code below to a call to GetFinalPathNameByHandle().  The method this
480   // function uses is explained in the following msdn article:
481   // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
482   win::ScopedHandle file_handle(
483       ::CreateFile(ToWCharT(&path.value()), GENERIC_READ, kFileShareAll, NULL,
484                    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
485   if (!file_handle.IsValid())
486     return false;
487 
488   // Create a file mapping object.  Can't easily use MemoryMappedFile, because
489   // we only map the first byte, and need direct access to the handle. You can
490   // not map an empty file, this call fails in that case.
491   win::ScopedHandle file_map_handle(
492       ::CreateFileMapping(file_handle.Get(), NULL, PAGE_READONLY, 0,
493                           1,  // Just one byte.  No need to look at the data.
494                           NULL));
495   if (!file_map_handle.IsValid())
496     return false;
497 
498   // Use a view of the file to get the path to the file.
499   void* file_view =
500       MapViewOfFile(file_map_handle.Get(), FILE_MAP_READ, 0, 0, 1);
501   if (!file_view)
502     return false;
503 
504   // The expansion of |path| into a full path may make it longer.
505   // GetMappedFileName() will fail if the result is longer than MAX_PATH.
506   // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
507   // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
508   // not return kMaxPathLength.  This would mean that only part of the
509   // path fit in |mapped_file_path|.
510   const int kMaxPathLength = MAX_PATH + 10;
511   char16_t mapped_file_path[kMaxPathLength];
512   bool success = false;
513   HANDLE cp = GetCurrentProcess();
514   if (::GetMappedFileNameW(cp, file_view, ToWCharT(mapped_file_path),
515                            kMaxPathLength)) {
516     *nt_path = FilePath(mapped_file_path);
517     success = true;
518   }
519   ::UnmapViewOfFile(file_view);
520   return success;
521 }
522 
523 // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle
524 // them if we do decide to.
IsLink(const FilePath& file_path)525 bool IsLink(const FilePath& file_path) {
526   return false;
527 }
528 
GetFileInfo(const FilePath& file_path, File::Info* results)529 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
530   WIN32_FILE_ATTRIBUTE_DATA attr;
531   if (!GetFileAttributesEx(ToWCharT(&file_path.value()), GetFileExInfoStandard,
532                            &attr)) {
533     return false;
534   }
535 
536   ULARGE_INTEGER size;
537   size.HighPart = attr.nFileSizeHigh;
538   size.LowPart = attr.nFileSizeLow;
539   results->size = size.QuadPart;
540 
541   results->is_directory =
542       (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
543   results->last_modified = *reinterpret_cast<uint64_t*>(&attr.ftLastWriteTime);
544   results->last_accessed = *reinterpret_cast<uint64_t*>(&attr.ftLastAccessTime);
545   results->creation_time = *reinterpret_cast<uint64_t*>(&attr.ftCreationTime);
546 
547   return true;
548 }
549 
OpenFile(const FilePath& filename, const char* mode)550 FILE* OpenFile(const FilePath& filename, const char* mode) {
551   // 'N' is unconditionally added below, so be sure there is not one already
552   // present before a comma in |mode|.
553   DCHECK(
554       strchr(mode, 'N') == nullptr ||
555       (strchr(mode, ',') != nullptr && strchr(mode, 'N') > strchr(mode, ',')));
556   std::u16string w_mode = ASCIIToUTF16(mode);
557   AppendModeCharacter(L'N', &w_mode);
558   return _wfsopen(ToWCharT(&filename.value()), ToWCharT(&w_mode), _SH_DENYNO);
559 }
560 
FileToFILE(File file, const char* mode)561 FILE* FileToFILE(File file, const char* mode) {
562   if (!file.IsValid())
563     return NULL;
564   int fd =
565       _open_osfhandle(reinterpret_cast<intptr_t>(file.GetPlatformFile()), 0);
566   if (fd < 0)
567     return NULL;
568   file.TakePlatformFile();
569   FILE* stream = _fdopen(fd, mode);
570   if (!stream)
571     _close(fd);
572   return stream;
573 }
574 
ReadFile(const FilePath& filename, char* data, int max_size)575 int ReadFile(const FilePath& filename, char* data, int max_size) {
576   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()), GENERIC_READ,
577                                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
578                                     OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
579                                     NULL));
580   if (!file.IsValid())
581     return -1;
582 
583   DWORD read;
584   if (::ReadFile(file.Get(), data, max_size, &read, NULL))
585     return read;
586 
587   return -1;
588 }
589 
WriteFile(const FilePath& filename, const char* data, int size)590 int WriteFile(const FilePath& filename, const char* data, int size) {
591   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()), GENERIC_WRITE,
592                                     0, NULL, CREATE_ALWAYS,
593                                     FILE_ATTRIBUTE_NORMAL, NULL));
594   if (!file.IsValid()) {
595     DPLOG(WARNING) << "CreateFile failed for path "
596                    << UTF16ToUTF8(filename.value());
597     return -1;
598   }
599 
600   DWORD written;
601   BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
602   if (result && static_cast<int>(written) == size)
603     return written;
604 
605   if (!result) {
606     // WriteFile failed.
607     DPLOG(WARNING) << "writing file " << UTF16ToUTF8(filename.value())
608                    << " failed";
609   } else {
610     // Didn't write all the bytes.
611     DLOG(WARNING) << "wrote" << written << " bytes to "
612                   << UTF16ToUTF8(filename.value()) << " expected " << size;
613   }
614   return -1;
615 }
616 
AppendToFile(const FilePath& filename, const char* data, int size)617 bool AppendToFile(const FilePath& filename, const char* data, int size) {
618   win::ScopedHandle file(CreateFile(ToWCharT(&filename.value()),
619                                     FILE_APPEND_DATA, 0, NULL, OPEN_EXISTING, 0,
620                                     NULL));
621   if (!file.IsValid()) {
622     return false;
623   }
624 
625   DWORD written;
626   BOOL result = ::WriteFile(file.Get(), data, size, &written, NULL);
627   if (result && static_cast<int>(written) == size)
628     return true;
629 
630   return false;
631 }
632 
GetCurrentDirectory(FilePath* dir)633 bool GetCurrentDirectory(FilePath* dir) {
634   char16_t system_buffer[MAX_PATH];
635   system_buffer[0] = 0;
636   DWORD len = ::GetCurrentDirectory(MAX_PATH, ToWCharT(system_buffer));
637   if (len == 0 || len > MAX_PATH)
638     return false;
639   // TODO(evanm): the old behavior of this function was to always strip the
640   // trailing slash.  We duplicate this here, but it shouldn't be necessary
641   // when everyone is using the appropriate FilePath APIs.
642   std::u16string dir_str(system_buffer);
643   *dir = FilePath(dir_str).StripTrailingSeparators();
644   return true;
645 }
646 
SetCurrentDirectory(const FilePath& directory)647 bool SetCurrentDirectory(const FilePath& directory) {
648   return ::SetCurrentDirectory(ToWCharT(&directory.value())) != 0;
649 }
650 
GetMaximumPathComponentLength(const FilePath& path)651 int GetMaximumPathComponentLength(const FilePath& path) {
652   char16_t volume_path[MAX_PATH];
653   if (!GetVolumePathNameW(ToWCharT(&path.NormalizePathSeparators().value()),
654                           ToWCharT(volume_path), std::size(volume_path))) {
655     return -1;
656   }
657 
658   DWORD max_length = 0;
659   if (!GetVolumeInformationW(ToWCharT(volume_path), NULL, 0, NULL, &max_length,
660                              NULL, NULL, 0)) {
661     return -1;
662   }
663 
664   // Length of |path| with path separator appended.
665   size_t prefix = path.StripTrailingSeparators().value().size() + 1;
666   // The whole path string must be shorter than MAX_PATH. That is, it must be
667   // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1).
668   int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast<int>(prefix));
669   return std::min(whole_path_limit, static_cast<int>(max_length));
670 }
671 
SetNonBlocking(int fd)672 bool SetNonBlocking(int fd) {
673   unsigned long nonblocking = 1;
674   if (ioctlsocket(fd, FIONBIO, &nonblocking) == 0)
675     return true;
676   return false;
677 }
678 
679 }  // namespace base
680