michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/file_util.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "base/files/file_path.h" michael@0: #include "base/logging.h" michael@0: #include "base/metrics/histogram.h" michael@0: #include "base/process/process_handle.h" michael@0: #include "base/rand_util.h" michael@0: #include "base/strings/string_number_conversions.h" michael@0: #include "base/strings/string_util.h" michael@0: #include "base/strings/utf_string_conversions.h" michael@0: #include "base/threading/thread_restrictions.h" michael@0: #include "base/time/time.h" michael@0: #include "base/win/scoped_handle.h" michael@0: #include "base/win/windows_version.h" michael@0: michael@0: namespace base { michael@0: michael@0: namespace { michael@0: michael@0: const DWORD kFileShareAll = michael@0: FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; michael@0: michael@0: bool ShellCopy(const FilePath& from_path, michael@0: const FilePath& to_path, michael@0: bool recursive) { michael@0: // WinXP SHFileOperation doesn't like trailing separators. michael@0: FilePath stripped_from = from_path.StripTrailingSeparators(); michael@0: FilePath stripped_to = to_path.StripTrailingSeparators(); michael@0: michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: // NOTE: I suspect we could support longer paths, but that would involve michael@0: // analyzing all our usage of files. michael@0: if (stripped_from.value().length() >= MAX_PATH || michael@0: stripped_to.value().length() >= MAX_PATH) { michael@0: return false; michael@0: } michael@0: michael@0: // SHFILEOPSTRUCT wants the path to be terminated with two NULLs, michael@0: // so we have to use wcscpy because wcscpy_s writes non-NULLs michael@0: // into the rest of the buffer. michael@0: wchar_t double_terminated_path_from[MAX_PATH + 1] = {0}; michael@0: wchar_t double_terminated_path_to[MAX_PATH + 1] = {0}; michael@0: #pragma warning(suppress:4996) // don't complain about wcscpy deprecation michael@0: wcscpy(double_terminated_path_from, stripped_from.value().c_str()); michael@0: #pragma warning(suppress:4996) // don't complain about wcscpy deprecation michael@0: wcscpy(double_terminated_path_to, stripped_to.value().c_str()); michael@0: michael@0: SHFILEOPSTRUCT file_operation = {0}; michael@0: file_operation.wFunc = FO_COPY; michael@0: file_operation.pFrom = double_terminated_path_from; michael@0: file_operation.pTo = double_terminated_path_to; michael@0: file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION | michael@0: FOF_NOCONFIRMMKDIR; michael@0: if (!recursive) michael@0: file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY; michael@0: michael@0: return (SHFileOperation(&file_operation) == 0); michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: FilePath MakeAbsoluteFilePath(const FilePath& input) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: wchar_t file_path[MAX_PATH]; michael@0: if (!_wfullpath(file_path, input.value().c_str(), MAX_PATH)) michael@0: return FilePath(); michael@0: return FilePath(file_path); michael@0: } michael@0: michael@0: bool DeleteFile(const FilePath& path, bool recursive) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: if (path.value().length() >= MAX_PATH) michael@0: return false; michael@0: michael@0: if (!recursive) { michael@0: // If not recursing, then first check to see if |path| is a directory. michael@0: // If it is, then remove it with RemoveDirectory. michael@0: PlatformFileInfo file_info; michael@0: if (file_util::GetFileInfo(path, &file_info) && file_info.is_directory) michael@0: return RemoveDirectory(path.value().c_str()) != 0; michael@0: michael@0: // Otherwise, it's a file, wildcard or non-existant. Try DeleteFile first michael@0: // because it should be faster. If DeleteFile fails, then we fall through michael@0: // to SHFileOperation, which will do the right thing. michael@0: if (::DeleteFile(path.value().c_str()) != 0) michael@0: return true; michael@0: } michael@0: michael@0: // SHFILEOPSTRUCT wants the path to be terminated with two NULLs, michael@0: // so we have to use wcscpy because wcscpy_s writes non-NULLs michael@0: // into the rest of the buffer. michael@0: wchar_t double_terminated_path[MAX_PATH + 1] = {0}; michael@0: #pragma warning(suppress:4996) // don't complain about wcscpy deprecation michael@0: if (g_bug108724_debug) michael@0: LOG(WARNING) << "copying "; michael@0: wcscpy(double_terminated_path, path.value().c_str()); michael@0: michael@0: SHFILEOPSTRUCT file_operation = {0}; michael@0: file_operation.wFunc = FO_DELETE; michael@0: file_operation.pFrom = double_terminated_path; michael@0: file_operation.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION; michael@0: if (!recursive) michael@0: file_operation.fFlags |= FOF_NORECURSION | FOF_FILESONLY; michael@0: if (g_bug108724_debug) michael@0: LOG(WARNING) << "Performing shell operation"; michael@0: int err = SHFileOperation(&file_operation); michael@0: if (g_bug108724_debug) michael@0: LOG(WARNING) << "Done: " << err; michael@0: michael@0: // Since we're passing flags to the operation telling it to be silent, michael@0: // it's possible for the operation to be aborted/cancelled without err michael@0: // being set (although MSDN doesn't give any scenarios for how this can michael@0: // happen). See MSDN for SHFileOperation and SHFILEOPTSTRUCT. michael@0: if (file_operation.fAnyOperationsAborted) michael@0: return false; michael@0: michael@0: // Some versions of Windows return ERROR_FILE_NOT_FOUND (0x2) when deleting michael@0: // an empty directory and some return 0x402 when they should be returning michael@0: // ERROR_FILE_NOT_FOUND. MSDN says Vista and up won't return 0x402. michael@0: return (err == 0 || err == ERROR_FILE_NOT_FOUND || err == 0x402); michael@0: } michael@0: michael@0: bool DeleteFileAfterReboot(const FilePath& path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: if (path.value().length() >= MAX_PATH) michael@0: return false; michael@0: michael@0: return MoveFileEx(path.value().c_str(), NULL, michael@0: MOVEFILE_DELAY_UNTIL_REBOOT | michael@0: MOVEFILE_REPLACE_EXISTING) != FALSE; michael@0: } michael@0: michael@0: bool ReplaceFile(const FilePath& from_path, michael@0: const FilePath& to_path, michael@0: PlatformFileError* error) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: // Try a simple move first. It will only succeed when |to_path| doesn't michael@0: // already exist. michael@0: if (::MoveFile(from_path.value().c_str(), to_path.value().c_str())) michael@0: return true; michael@0: // Try the full-blown replace if the move fails, as ReplaceFile will only michael@0: // succeed when |to_path| does exist. When writing to a network share, we may michael@0: // not be able to change the ACLs. Ignore ACL errors then michael@0: // (REPLACEFILE_IGNORE_MERGE_ERRORS). michael@0: if (::ReplaceFile(to_path.value().c_str(), from_path.value().c_str(), NULL, michael@0: REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL)) { michael@0: return true; michael@0: } michael@0: if (error) michael@0: *error = LastErrorToPlatformFileError(GetLastError()); michael@0: return false; michael@0: } michael@0: michael@0: bool CopyDirectory(const FilePath& from_path, const FilePath& to_path, michael@0: bool recursive) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: if (recursive) michael@0: return ShellCopy(from_path, to_path, true); michael@0: michael@0: // The following code assumes that from path is a directory. michael@0: DCHECK(DirectoryExists(from_path)); michael@0: michael@0: // Instead of creating a new directory, we copy the old one to include the michael@0: // security information of the folder as part of the copy. michael@0: if (!PathExists(to_path)) { michael@0: // Except that Vista fails to do that, and instead do a recursive copy if michael@0: // the target directory doesn't exist. michael@0: if (base::win::GetVersion() >= base::win::VERSION_VISTA) michael@0: file_util::CreateDirectory(to_path); michael@0: else michael@0: ShellCopy(from_path, to_path, false); michael@0: } michael@0: michael@0: FilePath directory = from_path.Append(L"*.*"); michael@0: return ShellCopy(directory, to_path, false); michael@0: } michael@0: michael@0: bool PathExists(const FilePath& path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES); michael@0: } michael@0: michael@0: bool PathIsWritable(const FilePath& path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: HANDLE dir = michael@0: CreateFile(path.value().c_str(), FILE_ADD_FILE, kFileShareAll, michael@0: NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); michael@0: michael@0: if (dir == INVALID_HANDLE_VALUE) michael@0: return false; michael@0: michael@0: CloseHandle(dir); michael@0: return true; michael@0: } michael@0: michael@0: bool DirectoryExists(const FilePath& path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: DWORD fileattr = GetFileAttributes(path.value().c_str()); michael@0: if (fileattr != INVALID_FILE_ATTRIBUTES) michael@0: return (fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0; michael@0: return false; michael@0: } michael@0: michael@0: } // namespace base michael@0: michael@0: // ----------------------------------------------------------------------------- michael@0: michael@0: namespace file_util { michael@0: michael@0: using base::DirectoryExists; michael@0: using base::FilePath; michael@0: using base::kFileShareAll; michael@0: michael@0: bool GetTempDir(FilePath* path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: wchar_t temp_path[MAX_PATH + 1]; michael@0: DWORD path_len = ::GetTempPath(MAX_PATH, temp_path); michael@0: if (path_len >= MAX_PATH || path_len <= 0) michael@0: return false; michael@0: // TODO(evanm): the old behavior of this function was to always strip the michael@0: // trailing slash. We duplicate this here, but it shouldn't be necessary michael@0: // when everyone is using the appropriate FilePath APIs. michael@0: *path = FilePath(temp_path).StripTrailingSeparators(); michael@0: return true; michael@0: } michael@0: michael@0: bool GetShmemTempDir(FilePath* path, bool executable) { michael@0: return GetTempDir(path); michael@0: } michael@0: michael@0: bool CreateTemporaryFile(FilePath* path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: FilePath temp_file; michael@0: michael@0: if (!GetTempDir(path)) michael@0: return false; michael@0: michael@0: if (CreateTemporaryFileInDir(*path, &temp_file)) { michael@0: *path = temp_file; michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: return CreateAndOpenTemporaryFile(path); michael@0: } michael@0: michael@0: // On POSIX we have semantics to create and open a temporary file michael@0: // atomically. michael@0: // TODO(jrg): is there equivalent call to use on Windows instead of michael@0: // going 2-step? michael@0: FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: if (!CreateTemporaryFileInDir(dir, path)) { michael@0: return NULL; michael@0: } michael@0: // Open file in binary mode, to avoid problems with fwrite. On Windows michael@0: // it replaces \n's with \r\n's, which may surprise you. michael@0: // Reference: http://msdn.microsoft.com/en-us/library/h9t88zwz(VS.71).aspx michael@0: return OpenFile(*path, "wb+"); michael@0: } michael@0: michael@0: bool CreateTemporaryFileInDir(const FilePath& dir, michael@0: FilePath* temp_file) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: wchar_t temp_name[MAX_PATH + 1]; michael@0: michael@0: if (!GetTempFileName(dir.value().c_str(), L"", 0, temp_name)) { michael@0: DPLOG(WARNING) << "Failed to get temporary file name in " << dir.value(); michael@0: return false; michael@0: } michael@0: michael@0: wchar_t long_temp_name[MAX_PATH + 1]; michael@0: DWORD long_name_len = GetLongPathName(temp_name, long_temp_name, MAX_PATH); michael@0: if (long_name_len > MAX_PATH || long_name_len == 0) { michael@0: // GetLongPathName() failed, but we still have a temporary file. michael@0: *temp_file = FilePath(temp_name); michael@0: return true; michael@0: } michael@0: michael@0: FilePath::StringType long_temp_name_str; michael@0: long_temp_name_str.assign(long_temp_name, long_name_len); michael@0: *temp_file = FilePath(long_temp_name_str); michael@0: return true; michael@0: } michael@0: michael@0: bool CreateTemporaryDirInDir(const FilePath& base_dir, michael@0: const FilePath::StringType& prefix, michael@0: FilePath* new_dir) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: FilePath path_to_create; michael@0: michael@0: for (int count = 0; count < 50; ++count) { michael@0: // Try create a new temporary directory with random generated name. If michael@0: // the one exists, keep trying another path name until we reach some limit. michael@0: string16 new_dir_name; michael@0: new_dir_name.assign(prefix); michael@0: new_dir_name.append(base::IntToString16(::base::GetCurrentProcId())); michael@0: new_dir_name.push_back('_'); michael@0: new_dir_name.append(base::IntToString16(base::RandInt(0, kint16max))); michael@0: michael@0: path_to_create = base_dir.Append(new_dir_name); michael@0: if (::CreateDirectory(path_to_create.value().c_str(), NULL)) { michael@0: *new_dir = path_to_create; michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: bool CreateNewTempDirectory(const FilePath::StringType& prefix, michael@0: FilePath* new_temp_path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: FilePath system_temp_dir; michael@0: if (!GetTempDir(&system_temp_dir)) michael@0: return false; michael@0: michael@0: return CreateTemporaryDirInDir(system_temp_dir, prefix, new_temp_path); michael@0: } michael@0: michael@0: bool CreateDirectoryAndGetError(const FilePath& full_path, michael@0: base::PlatformFileError* error) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: // If the path exists, we've succeeded if it's a directory, failed otherwise. michael@0: const wchar_t* full_path_str = full_path.value().c_str(); michael@0: DWORD fileattr = ::GetFileAttributes(full_path_str); michael@0: if (fileattr != INVALID_FILE_ATTRIBUTES) { michael@0: if ((fileattr & FILE_ATTRIBUTE_DIRECTORY) != 0) { michael@0: DVLOG(1) << "CreateDirectory(" << full_path_str << "), " michael@0: << "directory already exists."; michael@0: return true; michael@0: } michael@0: DLOG(WARNING) << "CreateDirectory(" << full_path_str << "), " michael@0: << "conflicts with existing file."; michael@0: if (error) { michael@0: *error = base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: // Invariant: Path does not exist as file or directory. michael@0: michael@0: // Attempt to create the parent recursively. This will immediately return michael@0: // true if it already exists, otherwise will create all required parent michael@0: // directories starting with the highest-level missing parent. michael@0: FilePath parent_path(full_path.DirName()); michael@0: if (parent_path.value() == full_path.value()) { michael@0: if (error) { michael@0: *error = base::PLATFORM_FILE_ERROR_NOT_FOUND; michael@0: } michael@0: return false; michael@0: } michael@0: if (!CreateDirectoryAndGetError(parent_path, error)) { michael@0: DLOG(WARNING) << "Failed to create one of the parent directories."; michael@0: if (error) { michael@0: DCHECK(*error != base::PLATFORM_FILE_OK); michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: if (!::CreateDirectory(full_path_str, NULL)) { michael@0: DWORD error_code = ::GetLastError(); michael@0: if (error_code == ERROR_ALREADY_EXISTS && DirectoryExists(full_path)) { michael@0: // This error code ERROR_ALREADY_EXISTS doesn't indicate whether we michael@0: // were racing with someone creating the same directory, or a file michael@0: // with the same path. If DirectoryExists() returns true, we lost the michael@0: // race to create the same directory. michael@0: return true; michael@0: } else { michael@0: if (error) michael@0: *error = base::LastErrorToPlatformFileError(error_code); michael@0: DLOG(WARNING) << "Failed to create directory " << full_path_str michael@0: << ", last error is " << error_code << "."; michael@0: return false; michael@0: } michael@0: } else { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: // TODO(rkc): Work out if we want to handle NTFS junctions here or not, handle michael@0: // them if we do decide to. michael@0: bool IsLink(const FilePath& file_path) { michael@0: return false; michael@0: } michael@0: michael@0: bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: WIN32_FILE_ATTRIBUTE_DATA attr; michael@0: if (!GetFileAttributesEx(file_path.value().c_str(), michael@0: GetFileExInfoStandard, &attr)) { michael@0: return false; michael@0: } michael@0: michael@0: ULARGE_INTEGER size; michael@0: size.HighPart = attr.nFileSizeHigh; michael@0: size.LowPart = attr.nFileSizeLow; michael@0: results->size = size.QuadPart; michael@0: michael@0: results->is_directory = michael@0: (attr.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; michael@0: results->last_modified = base::Time::FromFileTime(attr.ftLastWriteTime); michael@0: results->last_accessed = base::Time::FromFileTime(attr.ftLastAccessTime); michael@0: results->creation_time = base::Time::FromFileTime(attr.ftCreationTime); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: FILE* OpenFile(const FilePath& filename, const char* mode) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: std::wstring w_mode = ASCIIToWide(std::string(mode)); michael@0: return _wfsopen(filename.value().c_str(), w_mode.c_str(), _SH_DENYNO); michael@0: } michael@0: michael@0: FILE* OpenFile(const std::string& filename, const char* mode) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: return _fsopen(filename.c_str(), mode, _SH_DENYNO); michael@0: } michael@0: michael@0: int ReadFile(const FilePath& filename, char* data, int size) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: base::win::ScopedHandle file(CreateFile(filename.value().c_str(), michael@0: GENERIC_READ, michael@0: FILE_SHARE_READ | FILE_SHARE_WRITE, michael@0: NULL, michael@0: OPEN_EXISTING, michael@0: FILE_FLAG_SEQUENTIAL_SCAN, michael@0: NULL)); michael@0: if (!file) michael@0: return -1; michael@0: michael@0: DWORD read; michael@0: if (::ReadFile(file, data, size, &read, NULL) && michael@0: static_cast(read) == size) michael@0: return read; michael@0: return -1; michael@0: } michael@0: michael@0: int WriteFile(const FilePath& filename, const char* data, int size) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: base::win::ScopedHandle file(CreateFile(filename.value().c_str(), michael@0: GENERIC_WRITE, michael@0: 0, michael@0: NULL, michael@0: CREATE_ALWAYS, michael@0: 0, michael@0: NULL)); michael@0: if (!file) { michael@0: DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path " michael@0: << filename.value(); michael@0: return -1; michael@0: } michael@0: michael@0: DWORD written; michael@0: BOOL result = ::WriteFile(file, data, size, &written, NULL); michael@0: if (result && static_cast(written) == size) michael@0: return written; michael@0: michael@0: if (!result) { michael@0: // WriteFile failed. michael@0: DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value() michael@0: << " failed"; michael@0: } else { michael@0: // Didn't write all the bytes. michael@0: DLOG(WARNING) << "wrote" << written << " bytes to " michael@0: << filename.value() << " expected " << size; michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: int AppendToFile(const FilePath& filename, const char* data, int size) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: base::win::ScopedHandle file(CreateFile(filename.value().c_str(), michael@0: FILE_APPEND_DATA, michael@0: 0, michael@0: NULL, michael@0: OPEN_EXISTING, michael@0: 0, michael@0: NULL)); michael@0: if (!file) { michael@0: DLOG_GETLASTERROR(WARNING) << "CreateFile failed for path " michael@0: << filename.value(); michael@0: return -1; michael@0: } michael@0: michael@0: DWORD written; michael@0: BOOL result = ::WriteFile(file, data, size, &written, NULL); michael@0: if (result && static_cast(written) == size) michael@0: return written; michael@0: michael@0: if (!result) { michael@0: // WriteFile failed. michael@0: DLOG_GETLASTERROR(WARNING) << "writing file " << filename.value() michael@0: << " failed"; michael@0: } else { michael@0: // Didn't write all the bytes. michael@0: DLOG(WARNING) << "wrote" << written << " bytes to " michael@0: << filename.value() << " expected " << size; michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: // Gets the current working directory for the process. michael@0: bool GetCurrentDirectory(FilePath* dir) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: wchar_t system_buffer[MAX_PATH]; michael@0: system_buffer[0] = 0; michael@0: DWORD len = ::GetCurrentDirectory(MAX_PATH, system_buffer); michael@0: if (len == 0 || len > MAX_PATH) michael@0: return false; michael@0: // TODO(evanm): the old behavior of this function was to always strip the michael@0: // trailing slash. We duplicate this here, but it shouldn't be necessary michael@0: // when everyone is using the appropriate FilePath APIs. michael@0: std::wstring dir_str(system_buffer); michael@0: *dir = FilePath(dir_str).StripTrailingSeparators(); michael@0: return true; michael@0: } michael@0: michael@0: // Sets the current working directory for the process. michael@0: bool SetCurrentDirectory(const FilePath& directory) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: BOOL ret = ::SetCurrentDirectory(directory.value().c_str()); michael@0: return ret != 0; michael@0: } michael@0: michael@0: bool NormalizeFilePath(const FilePath& path, FilePath* real_path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: FilePath mapped_file; michael@0: if (!NormalizeToNativeFilePath(path, &mapped_file)) michael@0: return false; michael@0: // NormalizeToNativeFilePath() will return a path that starts with michael@0: // "\Device\Harddisk...". Helper DevicePathToDriveLetterPath() michael@0: // will find a drive letter which maps to the path's device, so michael@0: // that we return a path starting with a drive letter. michael@0: return DevicePathToDriveLetterPath(mapped_file, real_path); michael@0: } michael@0: michael@0: bool DevicePathToDriveLetterPath(const FilePath& nt_device_path, michael@0: FilePath* out_drive_letter_path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: // Get the mapping of drive letters to device paths. michael@0: const int kDriveMappingSize = 1024; michael@0: wchar_t drive_mapping[kDriveMappingSize] = {'\0'}; michael@0: if (!::GetLogicalDriveStrings(kDriveMappingSize - 1, drive_mapping)) { michael@0: DLOG(ERROR) << "Failed to get drive mapping."; michael@0: return false; michael@0: } michael@0: michael@0: // The drive mapping is a sequence of null terminated strings. michael@0: // The last string is empty. michael@0: wchar_t* drive_map_ptr = drive_mapping; michael@0: wchar_t device_path_as_string[MAX_PATH]; michael@0: wchar_t drive[] = L" :"; michael@0: michael@0: // For each string in the drive mapping, get the junction that links michael@0: // to it. If that junction is a prefix of |device_path|, then we michael@0: // know that |drive| is the real path prefix. michael@0: while (*drive_map_ptr) { michael@0: drive[0] = drive_map_ptr[0]; // Copy the drive letter. michael@0: michael@0: if (QueryDosDevice(drive, device_path_as_string, MAX_PATH)) { michael@0: FilePath device_path(device_path_as_string); michael@0: if (device_path == nt_device_path || michael@0: device_path.IsParent(nt_device_path)) { michael@0: *out_drive_letter_path = FilePath(drive + michael@0: nt_device_path.value().substr(wcslen(device_path_as_string))); michael@0: return true; michael@0: } michael@0: } michael@0: // Move to the next drive letter string, which starts one michael@0: // increment after the '\0' that terminates the current string. michael@0: while (*drive_map_ptr++); michael@0: } michael@0: michael@0: // No drive matched. The path does not start with a device junction michael@0: // that is mounted as a drive letter. This means there is no drive michael@0: // letter path to the volume that holds |device_path|, so fail. michael@0: return false; michael@0: } michael@0: michael@0: bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: // In Vista, GetFinalPathNameByHandle() would give us the real path michael@0: // from a file handle. If we ever deprecate XP, consider changing the michael@0: // code below to a call to GetFinalPathNameByHandle(). The method this michael@0: // function uses is explained in the following msdn article: michael@0: // http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx michael@0: base::win::ScopedHandle file_handle( michael@0: ::CreateFile(path.value().c_str(), michael@0: GENERIC_READ, michael@0: kFileShareAll, michael@0: NULL, michael@0: OPEN_EXISTING, michael@0: FILE_ATTRIBUTE_NORMAL, michael@0: NULL)); michael@0: if (!file_handle) michael@0: return false; michael@0: michael@0: // Create a file mapping object. Can't easily use MemoryMappedFile, because michael@0: // we only map the first byte, and need direct access to the handle. You can michael@0: // not map an empty file, this call fails in that case. michael@0: base::win::ScopedHandle file_map_handle( michael@0: ::CreateFileMapping(file_handle.Get(), michael@0: NULL, michael@0: PAGE_READONLY, michael@0: 0, michael@0: 1, // Just one byte. No need to look at the data. michael@0: NULL)); michael@0: if (!file_map_handle) michael@0: return false; michael@0: michael@0: // Use a view of the file to get the path to the file. michael@0: void* file_view = MapViewOfFile(file_map_handle.Get(), michael@0: FILE_MAP_READ, 0, 0, 1); michael@0: if (!file_view) michael@0: return false; michael@0: michael@0: // The expansion of |path| into a full path may make it longer. michael@0: // GetMappedFileName() will fail if the result is longer than MAX_PATH. michael@0: // Pad a bit to be safe. If kMaxPathLength is ever changed to be less michael@0: // than MAX_PATH, it would be nessisary to test that GetMappedFileName() michael@0: // not return kMaxPathLength. This would mean that only part of the michael@0: // path fit in |mapped_file_path|. michael@0: const int kMaxPathLength = MAX_PATH + 10; michael@0: wchar_t mapped_file_path[kMaxPathLength]; michael@0: bool success = false; michael@0: HANDLE cp = GetCurrentProcess(); michael@0: if (::GetMappedFileNameW(cp, file_view, mapped_file_path, kMaxPathLength)) { michael@0: *nt_path = FilePath(mapped_file_path); michael@0: success = true; michael@0: } michael@0: ::UnmapViewOfFile(file_view); michael@0: return success; michael@0: } michael@0: michael@0: int GetMaximumPathComponentLength(const FilePath& path) { michael@0: base::ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: wchar_t volume_path[MAX_PATH]; michael@0: if (!GetVolumePathNameW(path.NormalizePathSeparators().value().c_str(), michael@0: volume_path, michael@0: arraysize(volume_path))) { michael@0: return -1; michael@0: } michael@0: michael@0: DWORD max_length = 0; michael@0: if (!GetVolumeInformationW(volume_path, NULL, 0, NULL, &max_length, NULL, michael@0: NULL, 0)) { michael@0: return -1; michael@0: } michael@0: michael@0: // Length of |path| with path separator appended. michael@0: size_t prefix = path.StripTrailingSeparators().value().size() + 1; michael@0: // The whole path string must be shorter than MAX_PATH. That is, it must be michael@0: // prefix + component_length < MAX_PATH (or equivalently, <= MAX_PATH - 1). michael@0: int whole_path_limit = std::max(0, MAX_PATH - 1 - static_cast(prefix)); michael@0: return std::min(whole_path_limit, static_cast(max_length)); michael@0: } michael@0: michael@0: } // namespace file_util michael@0: michael@0: namespace base { michael@0: namespace internal { michael@0: michael@0: bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: // NOTE: I suspect we could support longer paths, but that would involve michael@0: // analyzing all our usage of files. michael@0: if (from_path.value().length() >= MAX_PATH || michael@0: to_path.value().length() >= MAX_PATH) { michael@0: return false; michael@0: } michael@0: if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(), michael@0: MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0) michael@0: return true; michael@0: michael@0: // Keep the last error value from MoveFileEx around in case the below michael@0: // fails. michael@0: bool ret = false; michael@0: DWORD last_error = ::GetLastError(); michael@0: michael@0: if (DirectoryExists(from_path)) { michael@0: // MoveFileEx fails if moving directory across volumes. We will simulate michael@0: // the move by using Copy and Delete. Ideally we could check whether michael@0: // from_path and to_path are indeed in different volumes. michael@0: ret = internal::CopyAndDeleteDirectory(from_path, to_path); michael@0: } michael@0: michael@0: if (!ret) { michael@0: // Leave a clue about what went wrong so that it can be (at least) picked michael@0: // up by a PLOG entry. michael@0: ::SetLastError(last_error); michael@0: } michael@0: michael@0: return ret; michael@0: } michael@0: michael@0: bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: michael@0: // NOTE: I suspect we could support longer paths, but that would involve michael@0: // analyzing all our usage of files. michael@0: if (from_path.value().length() >= MAX_PATH || michael@0: to_path.value().length() >= MAX_PATH) { michael@0: return false; michael@0: } michael@0: return (::CopyFile(from_path.value().c_str(), to_path.value().c_str(), michael@0: false) != 0); michael@0: } michael@0: michael@0: bool CopyAndDeleteDirectory(const FilePath& from_path, michael@0: const FilePath& to_path) { michael@0: ThreadRestrictions::AssertIOAllowed(); michael@0: if (CopyDirectory(from_path, to_path, true)) { michael@0: if (DeleteFile(from_path, true)) michael@0: return true; michael@0: michael@0: // Like Move, this function is not transactional, so we just michael@0: // leave the copied bits behind if deleting from_path fails. michael@0: // If to_path exists previously then we have already overwritten michael@0: // it by now, we don't get better off by deleting the new bits. michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: } // namespace internal michael@0: } // namespace base