michael@0: // Copyright (c) 2006-2008 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 "base/file_path.h" michael@0: #include "base/logging.h" michael@0: #include "base/scoped_handle.h" michael@0: #include "base/string_util.h" michael@0: #include "base/time.h" michael@0: #include "base/win_util.h" michael@0: michael@0: namespace file_util { michael@0: michael@0: bool AbsolutePath(FilePath* path) { michael@0: wchar_t file_path_buf[MAX_PATH]; michael@0: if (!_wfullpath(file_path_buf, path->value().c_str(), MAX_PATH)) michael@0: return false; michael@0: *path = FilePath(file_path_buf); michael@0: return true; michael@0: } michael@0: michael@0: bool Delete(const FilePath& path, bool recursive) { michael@0: if (path.value().length() >= MAX_PATH) michael@0: return false; michael@0: michael@0: // If we're not recursing use DeleteFile; it should be faster. DeleteFile michael@0: // fails if passed a directory though, which is why we fall through on michael@0: // failure to the SHFileOperation. michael@0: if (!recursive && DeleteFile(path.value().c_str()) != 0) michael@0: return true; 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: 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: int err = SHFileOperation(&file_operation); michael@0: // Some versions of Windows return ERROR_FILE_NOT_FOUND when michael@0: // deleting an empty directory. michael@0: return (err == 0 || err == ERROR_FILE_NOT_FOUND); michael@0: } michael@0: michael@0: bool CopyFile(const FilePath& from_path, const FilePath& to_path) { 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 ShellCopy(const FilePath& from_path, const FilePath& to_path, michael@0: bool recursive) { 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: 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, from_path.value().c_str()); michael@0: #pragma warning(suppress:4996) // don't complain about wcscpy deprecation michael@0: wcscpy(double_terminated_path_to, to_path.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: bool CopyDirectory(const FilePath& from_path, const FilePath& to_path, michael@0: bool recursive) { michael@0: if (recursive) michael@0: return ShellCopy(from_path, to_path, true); 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 (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) michael@0: 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: return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES); michael@0: } michael@0: michael@0: bool PathIsWritable(const FilePath& path) { michael@0: HANDLE dir = michael@0: CreateFile(path.value().c_str(), FILE_ADD_FILE, michael@0: FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 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: 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: bool GetTempDir(FilePath* path) { 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: std::wstring path_str(temp_path); michael@0: TrimTrailingSeparator(&path_str); michael@0: *path = FilePath(path_str); michael@0: return true; michael@0: } michael@0: michael@0: bool GetShmemTempDir(FilePath* path) { michael@0: return GetTempDir(path); michael@0: } michael@0: michael@0: bool CreateTemporaryFileName(FilePath* path) { michael@0: std::wstring temp_path, temp_file; michael@0: michael@0: if (!GetTempDir(&temp_path)) michael@0: return false; michael@0: michael@0: if (CreateTemporaryFileNameInDir(temp_path, &temp_file)) { michael@0: *path = FilePath(temp_file); michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: FILE* CreateAndOpenTemporaryShmemFile(FilePath* path) { 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: std::wstring wstring_path; michael@0: if (!CreateTemporaryFileNameInDir(dir.value(), &wstring_path)) { michael@0: return NULL; michael@0: } michael@0: *path = FilePath(wstring_path); 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 CreateTemporaryFileNameInDir(const std::wstring& dir, michael@0: std::wstring* temp_file) { michael@0: wchar_t temp_name[MAX_PATH + 1]; michael@0: michael@0: if (!GetTempFileName(dir.c_str(), L"", 0, temp_name)) michael@0: return false; // fail! michael@0: michael@0: DWORD path_len = GetLongPathName(temp_name, temp_name, MAX_PATH); michael@0: if (path_len > MAX_PATH + 1 || path_len == 0) michael@0: return false; // fail! michael@0: michael@0: temp_file->assign(temp_name, path_len); michael@0: return true; michael@0: } michael@0: michael@0: bool CreateNewTempDirectory(const FilePath::StringType& prefix, michael@0: FilePath* new_temp_path) { michael@0: FilePath system_temp_dir; michael@0: if (!GetTempDir(&system_temp_dir)) michael@0: return false; michael@0: michael@0: FilePath path_to_create; michael@0: srand(static_cast(time(NULL))); michael@0: michael@0: int count = 0; michael@0: while (count < 50) { 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: path_to_create = system_temp_dir; michael@0: std::wstring new_dir_name; michael@0: new_dir_name.assign(prefix); michael@0: new_dir_name.append(IntToWString(rand() % kint16max)); michael@0: path_to_create = path_to_create.Append(new_dir_name); michael@0: michael@0: if (::CreateDirectory(path_to_create.value().c_str(), NULL)) michael@0: break; michael@0: count++; michael@0: } michael@0: michael@0: if (count == 50) { michael@0: return false; michael@0: } michael@0: michael@0: *new_temp_path = path_to_create; michael@0: return true; michael@0: } michael@0: michael@0: bool CreateDirectory(const FilePath& full_path) { michael@0: if (DirectoryExists(full_path)) michael@0: return true; michael@0: int err = SHCreateDirectoryEx(NULL, full_path.value().c_str(), NULL); michael@0: return err == ERROR_SUCCESS; michael@0: } michael@0: michael@0: bool GetFileInfo(const FilePath& file_path, FileInfo* results) { michael@0: WIN32_FILE_ATTRIBUTE_DATA attr; michael@0: if (!GetFileAttributesEx(file_path.ToWStringHack().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: return true; michael@0: } michael@0: michael@0: FILE* OpenFile(const FilePath& filename, const char* mode) { michael@0: std::wstring w_mode = ASCIIToWide(std::string(mode)); michael@0: FILE* file; michael@0: if (_wfopen_s(&file, filename.value().c_str(), w_mode.c_str()) != 0) { michael@0: return NULL; michael@0: } michael@0: return file; michael@0: } michael@0: michael@0: FILE* OpenFile(const std::string& filename, const char* mode) { michael@0: FILE* file; michael@0: if (fopen_s(&file, filename.c_str(), mode) != 0) { michael@0: return NULL; michael@0: } michael@0: return file; michael@0: } michael@0: michael@0: int ReadFile(const FilePath& filename, char* data, int size) { michael@0: 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 == INVALID_HANDLE_VALUE) michael@0: return -1; michael@0: michael@0: int ret_value; michael@0: DWORD read; michael@0: if (::ReadFile(file, data, size, &read, NULL) && read == size) { michael@0: ret_value = static_cast(read); michael@0: } else { michael@0: ret_value = -1; michael@0: } michael@0: michael@0: return ret_value; michael@0: } michael@0: michael@0: int WriteFile(const FilePath& filename, const char* data, int size) { michael@0: 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 == INVALID_HANDLE_VALUE) { michael@0: CHROMIUM_LOG(WARNING) << "CreateFile failed for path " << filename.value() << michael@0: " error code=" << GetLastError() << michael@0: " error text=" << win_util::FormatLastWin32Error(); 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 && written == size) michael@0: return static_cast(written); michael@0: michael@0: if (!result) { michael@0: // WriteFile failed. michael@0: CHROMIUM_LOG(WARNING) << "writing file " << filename.value() << michael@0: " failed, error code=" << GetLastError() << michael@0: " description=" << win_util::FormatLastWin32Error(); michael@0: } else { michael@0: // Didn't write all the bytes. michael@0: CHROMIUM_LOG(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: 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: file_util::TrimTrailingSeparator(&dir_str); michael@0: *dir = FilePath(dir_str); 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: BOOL ret = ::SetCurrentDirectory(directory.value().c_str()); michael@0: return ret != 0; michael@0: } michael@0: michael@0: // Deprecated functions ---------------------------------------------------- michael@0: michael@0: void InsertBeforeExtension(std::wstring* path_str, michael@0: const std::wstring& suffix) { michael@0: FilePath path(*path_str); michael@0: InsertBeforeExtension(&path, suffix); michael@0: path_str->assign(path.value()); michael@0: } michael@0: void ReplaceExtension(std::wstring* file_name, const std::wstring& extension) { michael@0: FilePath path(*file_name); michael@0: ReplaceExtension(&path, extension); michael@0: file_name->assign(path.value()); michael@0: } michael@0: } // namespace file_util