file_util_win.cc revision c407dc5cd9bdc5668497f21b26b09d988ab439de
1// Copyright (c) 2010 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/file_util.h"
6
7#include <windows.h>
8#include <propvarutil.h>
9#include <psapi.h>
10#include <shellapi.h>
11#include <shlobj.h>
12#include <time.h>
13#include <string>
14
15#include "base/file_path.h"
16#include "base/logging.h"
17#include "base/pe_image.h"
18#include "base/scoped_comptr_win.h"
19#include "base/scoped_handle.h"
20#include "base/string_util.h"
21#include "base/time.h"
22#include "base/win_util.h"
23
24namespace file_util {
25
26namespace {
27
28// Helper for NormalizeFilePath(), defined below.
29bool DevicePathToDriveLetterPath(const FilePath& device_path,
30                                 FilePath* drive_letter_path) {
31  // Get the mapping of drive letters to device paths.
32  const int kDriveMappingSize = 1024;
33  wchar_t drive_mapping[kDriveMappingSize] = {'\0'};
34  if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) {
35    LOG(ERROR) << "Failed to get drive mapping.";
36    return false;
37  }
38
39  // The drive mapping is a sequence of null terminated strings.
40  // The last string is empty.
41  wchar_t* drive_map_ptr = drive_mapping;
42  wchar_t device_name[MAX_PATH];
43  wchar_t drive[] = L" :";
44
45  // For each string in the drive mapping, get the junction that links
46  // to it.  If that junction is a prefix of |device_path|, then we
47  // know that |drive| is the real path prefix.
48  while(*drive_map_ptr) {
49    drive[0] = drive_map_ptr[0];  // Copy the drive letter.
50
51    if (QueryDosDevice(drive, device_name, MAX_PATH) &&
52        StartsWith(device_path.value(), device_name, true)) {
53      *drive_letter_path = FilePath(drive +
54          device_path.value().substr(wcslen(device_name)));
55      return true;
56    }
57    // Move to the next drive letter string, which starts one
58    // increment after the '\0' that terminates the current string.
59    while(*drive_map_ptr++);
60  }
61
62  // No drive matched.  The path does not start with a device junction.
63  *drive_letter_path = device_path;
64  return true;
65}
66
67// Build a security descriptor with the weakest possible file permissions.
68bool InitLooseSecurityDescriptor(SECURITY_ATTRIBUTES *sa,
69                                 SECURITY_DESCRIPTOR *sd) {
70  DWORD last_error;
71
72  if (!InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION)) {
73    last_error = GetLastError();
74    LOG(ERROR) << "InitializeSecurityDescriptor failed: GetLastError() = "
75               << last_error;
76    return false;
77  }
78
79  if (!SetSecurityDescriptorDacl(sd,
80                                 TRUE,  // bDaclPresent: Add one to |sd|.
81                                 NULL,  // pDacl: NULL means allow all access.
82                                 FALSE  // bDaclDefaulted: Not defaulted.
83                                 )) {
84    last_error = GetLastError();
85    LOG(ERROR) << "SetSecurityDescriptorDacl() failed: GetLastError() = "
86               << last_error;
87    return false;
88  }
89
90  if (!SetSecurityDescriptorGroup(sd,
91                                  NULL,  // pGroup: No no primary group.
92                                  FALSE  // bGroupDefaulted: Not defaulted.
93                                  )) {
94    last_error = GetLastError();
95    LOG(ERROR) << "SetSecurityDescriptorGroup() failed: GetLastError() = "
96               << last_error;
97    return false;
98  }
99
100  if (!SetSecurityDescriptorSacl(sd,
101                                 FALSE,  // bSaclPresent: No SACL.
102                                 NULL,
103                                 FALSE
104                                 )) {
105    last_error = GetLastError();
106    LOG(ERROR) << "SetSecurityDescriptorSacl() failed: GetLastError() = "
107               << last_error;
108    return false;
109  }
110
111  sa->nLength = sizeof(SECURITY_ATTRIBUTES);
112  sa->lpSecurityDescriptor = sd;
113  sa->bInheritHandle = TRUE;
114  return true;
115}
116
117}  // namespace
118
119std::wstring GetDirectoryFromPath(const std::wstring& path) {
120  wchar_t path_buffer[MAX_PATH];
121  wchar_t* file_ptr = NULL;
122  if (GetFullPathName(path.c_str(), MAX_PATH, path_buffer, &file_ptr) == 0)
123    return L"";
124
125  std::wstring::size_type length =
126      file_ptr ? file_ptr - path_buffer : path.length();
127  std::wstring directory(path, 0, length);
128  return FilePath(directory).StripTrailingSeparators().value();
129}
130
131bool AbsolutePath(FilePath* path) {
132  wchar_t file_path_buf[MAX_PATH];
133  if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH))
134    return false;
135  *path = FilePath(file_path_buf);
136  return true;
137}
138
139int CountFilesCreatedAfter(const FilePath& path,
140                           const base::Time& comparison_time) {
141  int file_count = 0;
142  FILETIME comparison_filetime(comparison_time.ToFileTime());
143
144  WIN32_FIND_DATA find_file_data;
145  // All files in given dir
146  std::wstring filename_spec = path.Append(L"*").value();
147  HANDLE find_handle = FindFirstFile(filename_spec.c_str(), &find_file_data);
148  if (find_handle != INVALID_HANDLE_VALUE) {
149    do {
150      // Don't count current or parent directories.
151      if ((wcscmp(find_file_data.cFileName, L"..") == 0) ||
152          (wcscmp(find_file_data.cFileName, L".") == 0))
153        continue;
154
155      long result = CompareFileTime(&find_file_data.ftCreationTime,
156                                    &comparison_filetime);
157      // File was created after or on comparison time
158      if ((result == 1) || (result == 0))
159        ++file_count;
160    } while (FindNextFile(find_handle,  &find_file_data));
161    FindClose(find_handle);
162  }
163
164  return file_count;
165}
166
167bool Delete(const FilePath& path, bool recursive) {
168  if (path.value().length() >= MAX_PATH)
169    return false;
170
171  if (!recursive) {
172    // If not recursing, then first check to see if |path| is a directory.
173    // If it is, then remove it with RemoveDirectory.
174    FileInfo file_info;
175    if (GetFileInfo(path, &file_info) && file_info.is_directory)
176      return RemoveDirectory(path.value().c_str()) != 0;
177
178    // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first
179    // because it should be faster. If DeleteFile fails, then we fall through
180    // to SHFileOperation, which will do the right thing.
181    if (DeleteFile(path.value().c_str()) != 0)
182      return true;
183  }
184
185  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
186  // so we have to use wcscpy because wcscpy_s writes non-NULLs
187  // into the rest of the buffer.
188  wchar_t double_terminated_path[MAX_PATH + 1] = {0};
189#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
190  wcscpy(double_terminated_path, path.value().c_str());
191
192  SHFILEOPSTRUCT file_operation = {0};
193  file_operation.wFunc = FO_DELETE;
194  file_operation.pFrom = double_terminated_path;
195  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION;
196  if (!recursive)
197    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
198  int err = SHFileOperation(&file_operation);
199  // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting
200  // an empty directory and some return 0x402 when they should be returning
201  // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402.
202  return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402);
203}
204
205bool DeleteAfterReboot(const FilePath& path) {
206  if (path.value().length() >= MAX_PATH)
207    return false;
208
209  return MoveFileEx(path.value().c_str(), NULL,
210                    MOVEFILE_DELAY_UNTIL_REBOOT |
211                        MOVEFILE_REPLACE_EXISTING) != FALSE;
212}
213
214bool Move(const FilePath& from_path, const FilePath& to_path) {
215  // NOTE: I suspect we could support longer paths, but that would involve
216  // analyzing all our usage of files.
217  if (from_path.value().length() >= MAX_PATH ||
218      to_path.value().length() >= MAX_PATH) {
219    return false;
220  }
221  if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(),
222                 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0)
223    return true;
224  if (DirectoryExists(from_path)) {
225    // MoveFileEx fails if moving directory across volumes. We will simulate
226    // the move by using Copy and Delete. Ideally we could check whether
227    // from_path and to_path are indeed in different volumes.
228    return CopyAndDeleteDirectory(from_path, to_path);
229  }
230  return false;
231}
232
233bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
234  // Make sure that the target file exists.
235  HANDLE target_file = ::CreateFile(
236      to_path.value().c_str(),
237      0,
238      FILE_SHARE_READ | FILE_SHARE_WRITE,
239      NULL,
240      CREATE_NEW,
241      FILE_ATTRIBUTE_NORMAL,
242      NULL);
243  if (target_file != INVALID_HANDLE_VALUE)
244    ::CloseHandle(target_file);
245  // When writing to a network share, we may not be able to change the ACLs.
246  // Ignore ACL errors then (REPLACEFILE_IGNORE_MERGE_ERRORS).
247  return ::ReplaceFile(to_path.value().c_str(),
248      from_path.value().c_str(), NULL,
249      REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL) ? true : false;
250}
251
252bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
253  // NOTE: I suspect we could support longer paths, but that would involve
254  // analyzing all our usage of files.
255  if (from_path.value().length() >= MAX_PATH ||
256      to_path.value().length() >= MAX_PATH) {
257    return false;
258  }
259  return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(),
260                     false) != 0);
261}
262
263bool ShellCopy(const FilePath& from_path, const FilePath& to_path,
264               bool recursive) {
265  // NOTE: I suspect we could support longer paths, but that would involve
266  // analyzing all our usage of files.
267  if (from_path.value().length() >= MAX_PATH ||
268      to_path.value().length() >= MAX_PATH) {
269    return false;
270  }
271
272  // SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
273  // so we have to use wcscpy because wcscpy_s writes non-NULLs
274  // into the rest of the buffer.
275  wchar_t double_terminated_path_from[MAX_PATH + 1] = {0};
276  wchar_t double_terminated_path_to[MAX_PATH + 1] = {0};
277#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
278  wcscpy(double_terminated_path_from, from_path.value().c_str());
279#pragma warning(suppress:4996)  // don't complain about wcscpy deprecation
280  wcscpy(double_terminated_path_to, to_path.value().c_str());
281
282  SHFILEOPSTRUCT file_operation = {0};
283  file_operation.wFunc = FO_COPY;
284  file_operation.pFrom = double_terminated_path_from;
285  file_operation.pTo = double_terminated_path_to;
286  file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION |
287                          FOF_NOCONFIRMMKDIR;
288  if (!recursive)
289    file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY;
290
291  return (SHFileOperation(&file_operation) == 0);
292}
293
294bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
295                   bool recursive) {
296  if (recursive)
297    return ShellCopy(from_path, to_path, true);
298
299  // The following code assumes that from path is a directory.
300  DCHECK(DirectoryExists(from_path));
301
302  // Instead of creating a new directory, we copy the old one to include the
303  // security information of the folder as part of the copy.
304  if (!PathExists(to_path)) {
305    // Except that Vista fails to do that, and instead do a recursive copy if
306    // the target directory doesn't exist.
307    if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
308      CreateDirectory(to_path);
309    else
310      ShellCopy(from_path, to_path, false);
311  }
312
313  FilePath directory = from_path.Append(L"*.*");
314  return ShellCopy(directory, to_path, false);
315}
316
317bool CopyAndDeleteDirectory(const FilePath& from_path,
318                            const FilePath& to_path) {
319  if (CopyDirectory(from_path, to_path, true)) {
320    if (Delete(from_path, true)) {
321      return true;
322    }
323    // Like Move, this function is not transactional, so we just
324    // leave the copied bits behind if deleting from_path fails.
325    // If to_path exists previously then we have already overwritten
326    // it by now, we don't get better off by deleting the new bits.
327  }
328  return false;
329}
330
331
332bool PathExists(const FilePath& path) {
333  return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES);
334}
335
336bool PathIsWritable(const FilePath& path) {
337  HANDLE dir =
338      CreateFile(path.value().c_str(), FILE_ADD_FILE,
339                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
340                 NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
341
342  if (dir == INVALID_HANDLE_VALUE)
343    return false;
344
345  CloseHandle(dir);
346  return true;
347}
348
349bool DirectoryExists(const FilePath& path) {
350  DWORD fileattr = GetFileAttributes(path.value().c_str());
351  if (fileattr != INVALID_FILE_ATTRIBUTES)
352    return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0;
353  return false;
354}
355
356bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
357                                        LPSYSTEMTIME creation_time) {
358  if (!file_handle)
359    return false;
360
361  FILETIME utc_filetime;
362  if (!GetFileTime(file_handle, &utc_filetime, NULL, NULL))
363    return false;
364
365  FILETIME local_filetime;
366  if (!FileTimeToLocalFileTime(&utc_filetime, &local_filetime))
367    return false;
368
369  return !!FileTimeToSystemTime(&local_filetime, creation_time);
370}
371
372bool GetFileCreationLocalTime(const std::wstring& filename,
373                              LPSYSTEMTIME creation_time) {
374  ScopedHandle file_handle(
375      CreateFile(filename.c_str(), GENERIC_READ,
376                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
377                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
378  return GetFileCreationLocalTimeFromHandle(file_handle.Get(), creation_time);
379}
380
381bool ResolveShortcut(FilePath* path) {
382  HRESULT result;
383  ScopedComPtr<IShellLink> i_shell_link;
384  bool is_resolved = false;
385
386  // Get pointer to the IShellLink interface
387  result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
388                                       CLSCTX_INPROC_SERVER);
389  if (SUCCEEDED(result)) {
390    ScopedComPtr<IPersistFile> persist;
391    // Query IShellLink for the IPersistFile interface
392    result = persist.QueryFrom(i_shell_link);
393    if (SUCCEEDED(result)) {
394      WCHAR temp_path[MAX_PATH];
395      // Load the shell link
396      result = persist->Load(path->value().c_str(), STGM_READ);
397      if (SUCCEEDED(result)) {
398        // Try to find the target of a shortcut
399        result = i_shell_link->Resolve(0, SLR_NO_UI);
400        if (SUCCEEDED(result)) {
401          result = i_shell_link->GetPath(temp_path, MAX_PATH,
402                                  NULL, SLGP_UNCPRIORITY);
403          *path = FilePath(temp_path);
404          is_resolved = true;
405        }
406      }
407    }
408  }
409
410  return is_resolved;
411}
412
413bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination,
414                        const wchar_t *working_dir, const wchar_t *arguments,
415                        const wchar_t *description, const wchar_t *icon,
416                        int icon_index, const wchar_t* app_id) {
417  // Length of arguments and description must be less than MAX_PATH.
418  DCHECK(lstrlen(arguments) < MAX_PATH);
419  DCHECK(lstrlen(description) < MAX_PATH);
420
421  ScopedComPtr<IShellLink> i_shell_link;
422  ScopedComPtr<IPersistFile> i_persist_file;
423
424  // Get pointer to the IShellLink interface
425  HRESULT result = i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
426                                               CLSCTX_INPROC_SERVER);
427  if (FAILED(result))
428    return false;
429
430  // Query IShellLink for the IPersistFile interface
431  result = i_persist_file.QueryFrom(i_shell_link);
432  if (FAILED(result))
433    return false;
434
435  if (FAILED(i_shell_link->SetPath(source)))
436    return false;
437
438  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
439    return false;
440
441  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
442    return false;
443
444  if (description && FAILED(i_shell_link->SetDescription(description)))
445    return false;
446
447  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
448    return false;
449
450  if (app_id && (win_util::GetWinVersion() >= win_util::WINVERSION_WIN7)) {
451    ScopedComPtr<IPropertyStore> property_store;
452    if (FAILED(property_store.QueryFrom(i_shell_link)))
453      return false;
454
455    if (!win_util::SetAppIdForPropertyStore(property_store, app_id))
456      return false;
457  }
458
459  result = i_persist_file->Save(destination, TRUE);
460  return SUCCEEDED(result);
461}
462
463
464bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination,
465                        const wchar_t *working_dir, const wchar_t *arguments,
466                        const wchar_t *description, const wchar_t *icon,
467                        int icon_index, const wchar_t* app_id) {
468  // Length of arguments and description must be less than MAX_PATH.
469  DCHECK(lstrlen(arguments) < MAX_PATH);
470  DCHECK(lstrlen(description) < MAX_PATH);
471
472  // Get pointer to the IPersistFile interface and load existing link
473  ScopedComPtr<IShellLink> i_shell_link;
474  if (FAILED(i_shell_link.CreateInstance(CLSID_ShellLink, NULL,
475                                         CLSCTX_INPROC_SERVER)))
476    return false;
477
478  ScopedComPtr<IPersistFile> i_persist_file;
479  if (FAILED(i_persist_file.QueryFrom(i_shell_link)))
480    return false;
481
482  if (FAILED(i_persist_file->Load(destination, STGM_READWRITE)))
483    return false;
484
485  if (source && FAILED(i_shell_link->SetPath(source)))
486    return false;
487
488  if (working_dir && FAILED(i_shell_link->SetWorkingDirectory(working_dir)))
489    return false;
490
491  if (arguments && FAILED(i_shell_link->SetArguments(arguments)))
492    return false;
493
494  if (description && FAILED(i_shell_link->SetDescription(description)))
495    return false;
496
497  if (icon && FAILED(i_shell_link->SetIconLocation(icon, icon_index)))
498    return false;
499
500  if (app_id && win_util::GetWinVersion() >= win_util::WINVERSION_WIN7) {
501    ScopedComPtr<IPropertyStore> property_store;
502    if (FAILED(property_store.QueryFrom(i_shell_link)))
503      return false;
504
505    if (!win_util::SetAppIdForPropertyStore(property_store, app_id))
506      return false;
507  }
508
509  HRESULT result = i_persist_file->Save(destination, TRUE);
510  return SUCCEEDED(result);
511}
512
513bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
514  // "Pin to taskbar" is only supported after Win7.
515  if (win_util::GetWinVersion() < win_util::WINVERSION_WIN7)
516    return false;
517
518  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
519      NULL, NULL, 0));
520  return result > 32;
521}
522
523bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
524  // "Unpin from taskbar" is only supported after Win7.
525  if (win_util::GetWinVersion() < win_util::WINVERSION_WIN7)
526    return false;
527
528  int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
529      shortcut, NULL, NULL, 0));
530  return result > 32;
531}
532
533bool GetTempDir(FilePath* path) {
534  wchar_t temp_path[MAX_PATH + 1];
535  DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
536  if (path_len >= MAX_PATH || path_len <= 0)
537    return false;
538  // TODO(evanm): the old behavior of this function was to always strip the
539  // trailing slash.  We duplicate this here, but it shouldn't be necessary
540  // when everyone is using the appropriate FilePath APIs.
541  *path = FilePath(temp_path).StripTrailingSeparators();
542  return true;
543}
544
545bool GetShmemTempDir(FilePath* path) {
546  return GetTempDir(path);
547}
548
549bool CreateTemporaryFile(FilePath* path) {
550  FilePath temp_file;
551
552  if (!GetTempDir(path))
553    return false;
554
555  if (CreateTemporaryFileInDir(*path, &temp_file)) {
556    *path = temp_file;
557    return true;
558  }
559
560  return false;
561}
562
563FILE* CreateAndOpenTemporaryShmemFile(FilePath* path) {
564  return CreateAndOpenTemporaryFile(path);
565}
566
567// On POSIX we have semantics to create and open a temporary file
568// atomically.
569// TODO(jrg): is there equivalent call to use on Windows instead of
570// going 2-step?
571FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
572  if (!CreateTemporaryFileInDir(dir, path)) {
573    return NULL;
574  }
575  // Open file in binary mode, to avoid problems with fwrite. On Windows
576  // it replaces \n's with \r\n's, which may surprise you.
577  // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx
578  return OpenFile(*path, "wb+");
579}
580
581bool CreateTemporaryFileInDir(const FilePath& dir,
582                              FilePath* temp_file) {
583  wchar_t temp_name[MAX_PATH + 1];
584
585  if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) {
586    PLOG(WARNING) << "Failed to get temporary file name in " << dir.value();
587    return false;
588  }
589
590  DWORD path_len = GetLongPathName(temp_name, temp_name, MAX_PATH);
591  if (path_len > MAX_PATH + 1 || path_len == 0) {
592    PLOG(WARNING) << "Failed to get long path name for " << temp_name;
593    return false;
594  }
595
596  std::wstring temp_file_str;
597  temp_file_str.assign(temp_name, path_len);
598  *temp_file = FilePath(temp_file_str);
599  return true;
600}
601
602bool CreateTemporaryDirInDir(const FilePath& base_dir,
603                             const FilePath::StringType& prefix,
604                             bool loosen_permissions,
605                             FilePath* new_dir) {
606  SECURITY_ATTRIBUTES sa;
607  SECURITY_DESCRIPTOR sd;
608
609  LPSECURITY_ATTRIBUTES directory_security_attributes = NULL;
610  if (loosen_permissions) {
611    if (InitLooseSecurityDescriptor(&sa, &sd))
612      directory_security_attributes = &sa;
613    else
614      LOG(ERROR) << "Failed to init security attributes, fall back to NULL.";
615  }
616
617  FilePath path_to_create;
618  srand(static_cast<uint32>(time(NULL)));
619
620  int count = 0;
621  while (count < 50) {
622    // Try create a new temporary directory with random generated name. If
623    // the one exists, keep trying another path name until we reach some limit.
624    path_to_create = base_dir;
625
626    std::wstring new_dir_name;
627    new_dir_name.assign(prefix);
628    new_dir_name.append(IntToWString(rand() % kint16max));
629
630    path_to_create = path_to_create.Append(new_dir_name);
631    if (::CreateDirectory(path_to_create.value().c_str(),
632                          directory_security_attributes))
633      break;
634    count++;
635  }
636
637  if (count == 50) {
638    return false;
639  }
640
641  *new_dir = path_to_create;
642
643  return true;
644}
645
646bool CreateNewTempDirectory(const FilePath::StringType& prefix,
647                            FilePath* new_temp_path) {
648  FilePath system_temp_dir;
649  if (!GetTempDir(&system_temp_dir))
650    return false;
651
652  return CreateTemporaryDirInDir(system_temp_dir,
653                                 prefix,
654                                 false,
655                                 new_temp_path);
656}
657
658bool CreateDirectory(const FilePath& full_path) {
659  return file_util::CreateDirectoryExtraLogging(full_path, LOG(INFO));
660}
661
662// TODO(skerner): Extra logging has been added to understand crbug/35198 .
663// Remove it once we get a log from a user who can reproduce the issue.
664bool CreateDirectoryExtraLogging(const FilePath& full_path,
665                                 std::ostream& log) {
666  log << "Enter CreateDirectory: full_path = " << full_path.value()
667      << std::endl;
668  // If the path exists, we've succeeded if it's a directory, failed otherwise.
669  const wchar_t* full_path_str = full_path.value().c_str();
670  DWORD fileattr = ::GetFileAttributes(full_path_str);
671  log << "::GetFileAttributes() returned " << fileattr << std::endl;
672  if (fileattr == INVALID_FILE_ATTRIBUTES) {
673    DWORD fileattr_error = GetLastError();
674    log << "::GetFileAttributes() failed.  GetLastError() = "
675        << fileattr_error << std::endl;
676  } else {
677    if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
678      log << "CreateDirectory(" << full_path_str << "), "
679          << "directory already exists." << std::endl;
680      return true;
681    } else {
682      log << "CreateDirectory(" << full_path_str << "), "
683          << "conflicts with existing file." << std::endl;
684    }
685  }
686
687  // Invariant:  Path does not exist as file or directory.
688
689  // Attempt to create the parent recursively.  This will immediately return
690  // true if it already exists, otherwise will create all required parent
691  // directories starting with the highest-level missing parent.
692  FilePath parent_path(full_path.DirName());
693  if (parent_path.value() == full_path.value()) {
694    log << "Can't create directory: parent_path " << parent_path.value()
695        << " should not equal full_path " << full_path.value()
696        << std::endl;
697    return false;
698  }
699  if (!CreateDirectory(parent_path)) {
700    log << "Failed to create one of the parent directories: "
701        << parent_path.value() << std::endl;
702    return false;
703  }
704
705  log << "About to call ::CreateDirectory() with full_path_str = "
706      << full_path_str << std::endl;
707  if (!::CreateDirectory(full_path_str, NULL)) {
708    DWORD error_code = ::GetLastError();
709    log << "CreateDirectory() gave last error " << error_code << std::endl;
710
711    DWORD fileattr = GetFileAttributes(full_path.value().c_str());
712    if (fileattr == INVALID_FILE_ATTRIBUTES) {
713      DWORD fileattr_error = ::GetLastError();
714      log << "GetFileAttributes() failed, GetLastError() = "
715          << fileattr_error << std::endl;
716    } else {
717      log << "GetFileAttributes() returned " << fileattr << std::endl;
718      log << "Is the path a directory: "
719          << ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) << std::endl;
720    }
721    if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) {
722      // This error code doesn't indicate whether we were racing with someone
723      // creating the same directory, or a file with the same path, therefore
724      // we check.
725      log << "Race condition? Directory already exists: "
726          << full_path.value() << std::endl;
727      return true;
728    } else {
729      DWORD dir_exists_error = ::GetLastError();
730      log << "Failed to create directory " << full_path_str << std::endl;
731      log << "GetLastError() for DirectoryExists() is "
732          << dir_exists_error << std::endl;
733      return false;
734    }
735  } else {
736    log << "::CreateDirectory() succeeded." << std::endl;
737    return true;
738  }
739}
740
741bool GetFileInfo(const FilePath& file_path, FileInfo* results) {
742  WIN32_FILE_ATTRIBUTE_DATA attr;
743  if (!GetFileAttributesEx(file_path.value().c_str(),
744                           GetFileExInfoStandard, &attr)) {
745    return false;
746  }
747
748  ULARGE_INTEGER size;
749  size.HighPart = attr.nFileSizeHigh;
750  size.LowPart = attr.nFileSizeLow;
751  results->size = size.QuadPart;
752
753  results->is_directory =
754      (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
755  results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime);
756
757  return true;
758}
759
760bool SetLastModifiedTime(const FilePath& file_path, base::Time last_modified) {
761  FILETIME timestamp(last_modified.ToFileTime());
762  ScopedHandle file_handle(
763      CreateFile(file_path.value().c_str(), FILE_WRITE_ATTRIBUTES,
764                 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
765                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
766  BOOL ret = SetFileTime(file_handle.Get(), NULL, &timestamp, &timestamp);
767  return ret != 0;
768}
769
770FILE* OpenFile(const FilePath& filename, const char* mode) {
771  std::wstring w_mode = ASCIIToWide(std::string(mode));
772  return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO);
773}
774
775FILE* OpenFile(const std::string& filename, const char* mode) {
776  return _fsopen(filename.c_str(), mode, _SH_DENYNO);
777}
778
779int ReadFile(const FilePath& filename, char* data, int size) {
780  ScopedHandle file(CreateFile(filename.value().c_str(),
781                               GENERIC_READ,
782                               FILE_SHARE_READ | FILE_SHARE_WRITE,
783                               NULL,
784                               OPEN_EXISTING,
785                               FILE_FLAG_SEQUENTIAL_SCAN,
786                               NULL));
787  if (file == INVALID_HANDLE_VALUE)
788    return -1;
789
790  DWORD read;
791  if (::ReadFile(file, data, size, &read, NULL) &&
792      static_cast<int>(read) == size)
793    return read;
794  return -1;
795}
796
797int WriteFile(const FilePath& filename, const char* data, int size) {
798  ScopedHandle file(CreateFile(filename.value().c_str(),
799                               GENERIC_WRITE,
800                               0,
801                               NULL,
802                               CREATE_ALWAYS,
803                               0,
804                               NULL));
805  if (file == INVALID_HANDLE_VALUE) {
806    LOG(WARNING) << "CreateFile failed for path " << filename.value() <<
807        " error code=" << GetLastError() <<
808        " error text=" << win_util::FormatLastWin32Error();
809    return -1;
810  }
811
812  DWORD written;
813  BOOL result = ::WriteFile(file, data, size, &written, NULL);
814  if (result && static_cast<int>(written) == size)
815    return written;
816
817  if (!result) {
818    // WriteFile failed.
819    LOG(WARNING) << "writing file " << filename.value() <<
820        " failed, error code=" << GetLastError() <<
821        " description=" << win_util::FormatLastWin32Error();
822  } else {
823    // Didn't write all the bytes.
824    LOG(WARNING) << "wrote" << written << " bytes to " <<
825        filename.value() << " expected " << size;
826  }
827  return -1;
828}
829
830bool RenameFileAndResetSecurityDescriptor(const FilePath& source_file_path,
831                                          const FilePath& target_file_path) {
832  // The parameters to SHFileOperation must be terminated with 2 NULL chars.
833  std::wstring source = source_file_path.value();
834  std::wstring target = target_file_path.value();
835
836  source.append(1, L'\0');
837  target.append(1, L'\0');
838
839  SHFILEOPSTRUCT move_info = {0};
840  move_info.wFunc = FO_MOVE;
841  move_info.pFrom = source.c_str();
842  move_info.pTo = target.c_str();
843  move_info.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI |
844                     FOF_NOCONFIRMMKDIR | FOF_NOCOPYSECURITYATTRIBS;
845
846  if (0 != SHFileOperation(&move_info))
847    return false;
848
849  return true;
850}
851
852// Gets the current working directory for the process.
853bool GetCurrentDirectory(FilePath* dir) {
854  wchar_t system_buffer[MAX_PATH];
855  system_buffer[0] = 0;
856  DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer);
857  if (len == 0 || len > MAX_PATH)
858    return false;
859  // TODO(evanm): the old behavior of this function was to always strip the
860  // trailing slash.  We duplicate this here, but it shouldn't be necessary
861  // when everyone is using the appropriate FilePath APIs.
862  std::wstring dir_str(system_buffer);
863  *dir = FilePath(dir_str).StripTrailingSeparators();
864  return true;
865}
866
867// Sets the current working directory for the process.
868bool SetCurrentDirectory(const FilePath& directory) {
869  BOOL ret = ::SetCurrentDirectory(directory.value().c_str());
870  return ret != 0;
871}
872
873///////////////////////////////////////////////
874// FileEnumerator
875
876FileEnumerator::FileEnumerator(const FilePath& root_path,
877                               bool recursive,
878                               FileEnumerator::FILE_TYPE file_type)
879    : recursive_(recursive),
880      file_type_(file_type),
881      is_in_find_op_(false),
882      find_handle_(INVALID_HANDLE_VALUE) {
883  // INCLUDE_DOT_DOT must not be specified if recursive.
884  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
885  pending_paths_.push(root_path);
886}
887
888FileEnumerator::FileEnumerator(const FilePath& root_path,
889                               bool recursive,
890                               FileEnumerator::FILE_TYPE file_type,
891                               const FilePath::StringType& pattern)
892    : recursive_(recursive),
893      file_type_(file_type),
894      is_in_find_op_(false),
895      pattern_(pattern),
896      find_handle_(INVALID_HANDLE_VALUE) {
897  // INCLUDE_DOT_DOT must not be specified if recursive.
898  DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
899  pending_paths_.push(root_path);
900}
901
902FileEnumerator::~FileEnumerator() {
903  if (find_handle_ != INVALID_HANDLE_VALUE)
904    FindClose(find_handle_);
905}
906
907void FileEnumerator::GetFindInfo(FindInfo* info) {
908  DCHECK(info);
909
910  if (!is_in_find_op_)
911    return;
912
913  memcpy(info, &find_data_, sizeof(*info));
914}
915
916bool FileEnumerator::IsDirectory(const FindInfo& info) {
917  return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
918}
919
920// static
921FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
922  return FilePath(find_info.cFileName);
923}
924
925FilePath FileEnumerator::Next() {
926  if (!is_in_find_op_) {
927    if (pending_paths_.empty())
928      return FilePath();
929
930    // The last find FindFirstFile operation is done, prepare a new one.
931    root_path_ = pending_paths_.top();
932    pending_paths_.pop();
933
934    // Start a new find operation.
935    FilePath src = root_path_;
936
937    if (pattern_.empty())
938      src = src.Append(L"*");  // No pattern = match everything.
939    else
940      src = src.Append(pattern_);
941
942    find_handle_ = FindFirstFile(src.value().c_str(), &find_data_);
943    is_in_find_op_ = true;
944
945  } else {
946    // Search for the next file/directory.
947    if (!FindNextFile(find_handle_, &find_data_)) {
948      FindClose(find_handle_);
949      find_handle_ = INVALID_HANDLE_VALUE;
950    }
951  }
952
953  if (INVALID_HANDLE_VALUE == find_handle_) {
954    is_in_find_op_ = false;
955
956    // This is reached when we have finished a directory and are advancing to
957    // the next one in the queue. We applied the pattern (if any) to the files
958    // in the root search directory, but for those directories which were
959    // matched, we want to enumerate all files inside them. This will happen
960    // when the handle is empty.
961    pattern_ = FilePath::StringType();
962
963    return Next();
964  }
965
966  FilePath cur_file(find_data_.cFileName);
967  if (ShouldSkip(cur_file))
968    return Next();
969
970  // Construct the absolute filename.
971  cur_file = root_path_.Append(cur_file);
972
973  if (find_data_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
974    if (recursive_) {
975      // If |cur_file| is a directory, and we are doing recursive searching, add
976      // it to pending_paths_ so we scan it after we finish scanning this
977      // directory.
978      pending_paths_.push(cur_file);
979    }
980    return (file_type_ & FileEnumerator::DIRECTORIES) ? cur_file : Next();
981  }
982  return (file_type_ & FileEnumerator::FILES) ? cur_file : Next();
983}
984
985///////////////////////////////////////////////
986// MemoryMappedFile
987
988MemoryMappedFile::MemoryMappedFile()
989    : file_(INVALID_HANDLE_VALUE),
990      file_mapping_(INVALID_HANDLE_VALUE),
991      data_(NULL),
992      length_(INVALID_FILE_SIZE) {
993}
994
995bool MemoryMappedFile::MapFileToMemoryInternal() {
996  if (file_ == INVALID_HANDLE_VALUE)
997    return false;
998
999  length_ = ::GetFileSize(file_, NULL);
1000  if (length_ == INVALID_FILE_SIZE)
1001    return false;
1002
1003  // length_ value comes from GetFileSize() above. GetFileSize() returns DWORD,
1004  // therefore the cast here is safe.
1005  file_mapping_ = ::CreateFileMapping(file_, NULL, PAGE_READONLY,
1006                                      0, static_cast<DWORD>(length_), NULL);
1007  if (file_mapping_ == INVALID_HANDLE_VALUE)
1008    return false;
1009
1010  data_ = static_cast<uint8*>(
1011      ::MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, length_));
1012  return data_ != NULL;
1013}
1014
1015void MemoryMappedFile::CloseHandles() {
1016  if (data_)
1017    ::UnmapViewOfFile(data_);
1018  if (file_mapping_ != INVALID_HANDLE_VALUE)
1019    ::CloseHandle(file_mapping_);
1020  if (file_ != INVALID_HANDLE_VALUE)
1021    ::CloseHandle(file_);
1022
1023  data_ = NULL;
1024  file_mapping_ = file_ = INVALID_HANDLE_VALUE;
1025  length_ = INVALID_FILE_SIZE;
1026}
1027
1028bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
1029                              const base::Time& cutoff_time) {
1030  long result = CompareFileTime(&find_info.ftLastWriteTime,
1031                                &cutoff_time.ToFileTime());
1032  return result == 1 || result == 0;
1033}
1034
1035bool NormalizeFilePath(const FilePath& path, FilePath* real_path) {
1036  ScopedHandle path_handle(
1037      ::CreateFile(path.value().c_str(),
1038                   GENERIC_READ,
1039                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1040                   NULL,
1041                   OPEN_EXISTING,
1042                   FILE_ATTRIBUTE_NORMAL,
1043                   NULL));
1044  if (path_handle == INVALID_HANDLE_VALUE)
1045    return false;
1046
1047  // In Vista, GetFinalPathNameByHandle() would give us the real path
1048  // from a file handle.  If we ever deprecate XP, consider changing the
1049  // code below to a call to GetFinalPathNameByHandle().  The method this
1050  // function uses is explained in the following msdn article:
1051  // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx
1052  DWORD file_size_high = 0;
1053  DWORD file_size_low = ::GetFileSize(path_handle.Get(), &file_size_high);
1054  if (file_size_low == 0 && file_size_high == 0) {
1055    // It is not possible to map an empty file.
1056    LOG(ERROR) << "NormalizeFilePath failed: Empty file.";
1057    return false;
1058  }
1059
1060  // Create a file mapping object.  Can't easily use MemoryMappedFile, because
1061  // we only map the first byte, and need direct access to the handle.
1062  ScopedHandle file_map_handle(
1063      ::CreateFileMapping(path_handle.Get(),
1064                          NULL,
1065                          PAGE_READONLY,
1066                          0,
1067                          1, // Just one byte.  No need to look at the data.
1068                          NULL));
1069
1070  if (file_map_handle == INVALID_HANDLE_VALUE)
1071    return false;
1072
1073  // Use a view of the file to get the path to the file.
1074  void* file_view = MapViewOfFile(
1075      file_map_handle.Get(), FILE_MAP_READ, 0, 0, 1);
1076  if (!file_view)
1077    return false;
1078
1079  bool success = false;
1080
1081  // The expansion of |path| into a full path may make it longer.
1082  // GetMappedFileName() will fail if the result is longer than MAX_PATH.
1083  // Pad a bit to be safe.  If kMaxPathLength is ever changed to be less
1084  // than MAX_PATH, it would be nessisary to test that GetMappedFileName()
1085  // not return kMaxPathLength.  This would mean that only part of the
1086  // path fit in |mapped_file_path|.
1087  const int kMaxPathLength = MAX_PATH + 10;
1088  wchar_t mapped_file_path[kMaxPathLength];
1089  if (::GetMappedFileName(GetCurrentProcess(),
1090                          file_view,
1091                          mapped_file_path,
1092                          kMaxPathLength)) {
1093    // GetMappedFileName() will return a path that starts with
1094    // "\Device\Harddisk...".  Helper DevicePathToDriveLetterPath()
1095    // will find a drive letter which maps to the path's device, so
1096    // that we return a path starting with a drive letter.
1097    FilePath mapped_file(mapped_file_path);
1098    success = DevicePathToDriveLetterPath(mapped_file, real_path);
1099  }
1100  UnmapViewOfFile(file_view);
1101  return success;
1102}
1103
1104bool PreReadImage(const wchar_t* file_path, size_t size_to_read,
1105                  size_t step_size) {
1106  HMODULE dll_module = LoadLibraryExW(
1107      file_path,
1108      NULL,
1109      LOAD_WITH_ALTERED_SEARCH_PATH | DONT_RESOLVE_DLL_REFERENCES);
1110
1111  if (!dll_module)
1112    return false;
1113
1114  PEImage pe_image(dll_module);
1115  PIMAGE_NT_HEADERS nt_headers = pe_image.GetNTHeaders();
1116  size_t actual_size_to_read = size_to_read ? size_to_read :
1117                               nt_headers->OptionalHeader.SizeOfImage;
1118  volatile uint8* touch = reinterpret_cast<uint8*>(dll_module);
1119  size_t offset = 0;
1120  while (offset < actual_size_to_read) {
1121    uint8 unused = *(touch + offset);
1122    offset += step_size;
1123  }
1124  FreeLibrary(dll_module);
1125  return true;
1126}
1127
1128}  // namespace file_util
1129