WebKit Roll 61390:61491.
[chromium-blink-merge.git] / base / file_util.h
bloba16c5c72bc3b7fb2d666c6febece2d4bacd67240
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.
5 // This file contains utility functions for dealing with the local
6 // filesystem.
8 #ifndef BASE_FILE_UTIL_H_
9 #define BASE_FILE_UTIL_H_
11 #include "build/build_config.h"
13 #if defined(OS_WIN)
14 #include <windows.h>
15 #if defined(UNIT_TEST)
16 #include <aclapi.h>
17 #endif
18 #elif defined(OS_POSIX)
19 #include <sys/stat.h>
20 #endif
22 #include <stdio.h>
24 #include <stack>
25 #include <string>
26 #include <vector>
28 #include "base/basictypes.h"
29 #include "base/file_path.h"
30 #include "base/platform_file.h"
31 #include "base/scoped_ptr.h"
32 #include "base/string16.h"
33 #include "base/time.h"
35 #if defined(OS_POSIX)
36 #include "base/eintr_wrapper.h"
37 #include "base/file_descriptor_posix.h"
38 #endif
40 namespace base {
41 class Time;
44 namespace file_util {
46 //-----------------------------------------------------------------------------
47 // Functions that operate purely on a path string w/o touching the filesystem:
49 // Returns true if the given path ends with a path separator character.
50 bool EndsWithSeparator(const FilePath& path);
52 // Makes sure that |path| ends with a separator IFF path is a directory that
53 // exists. Returns true if |path| is an existing directory, false otherwise.
54 bool EnsureEndsWithSeparator(FilePath* path);
56 // Convert provided relative path into an absolute path. Returns false on
57 // error. On POSIX, this function fails if the path does not exist.
58 bool AbsolutePath(FilePath* path);
60 // Returns true if |parent| contains |child|. Both paths are converted to
61 // absolute paths before doing the comparison.
62 bool ContainsPath(const FilePath& parent, const FilePath& child);
64 //-----------------------------------------------------------------------------
65 // Functions that involve filesystem access or modification:
67 // Returns the number of files matching the current path that were
68 // created on or after the given |file_time|. Doesn't count ".." or ".".
70 // Note for POSIX environments: a file created before |file_time|
71 // can be mis-detected as a newer file due to low precision of
72 // timestmap of file creation time. If you need to avoid such
73 // mis-detection perfectly, you should wait one second before
74 // obtaining |file_time|.
75 int CountFilesCreatedAfter(const FilePath& path,
76 const base::Time& file_time);
78 // Returns the total number of bytes used by all the files under |root_path|.
79 // If the path does not exist the function returns 0.
81 // This function is implemented using the FileEnumerator class so it is not
82 // particularly speedy in any platform.
83 int64 ComputeDirectorySize(const FilePath& root_path);
85 // Returns the total number of bytes used by all files matching the provided
86 // |pattern|, on this |directory| (without recursion). If the path does not
87 // exist the function returns 0.
89 // This function is implemented using the FileEnumerator class so it is not
90 // particularly speedy in any platform.
91 int64 ComputeFilesSize(const FilePath& directory,
92 const FilePath::StringType& pattern);
94 // Deletes the given path, whether it's a file or a directory.
95 // If it's a directory, it's perfectly happy to delete all of the
96 // directory's contents. Passing true to recursive deletes
97 // subdirectories and their contents as well.
98 // Returns true if successful, false otherwise.
100 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
101 // TO "rm -rf", SO USE WITH CAUTION.
102 bool Delete(const FilePath& path, bool recursive);
104 #if defined(OS_WIN)
105 // Schedules to delete the given path, whether it's a file or a directory, until
106 // the operating system is restarted.
107 // Note:
108 // 1) The file/directory to be deleted should exist in a temp folder.
109 // 2) The directory to be deleted must be empty.
110 bool DeleteAfterReboot(const FilePath& path);
111 #endif
113 // Moves the given path, whether it's a file or a directory.
114 // If a simple rename is not possible, such as in the case where the paths are
115 // on different volumes, this will attempt to copy and delete. Returns
116 // true for success.
117 bool Move(const FilePath& from_path, const FilePath& to_path);
119 // Renames file |from_path| to |to_path|. Both paths must be on the same
120 // volume, or the function will fail. Destination file will be created
121 // if it doesn't exist. Prefer this function over Move when dealing with
122 // temporary files. On Windows it preserves attributes of the target file.
123 // Returns true on success.
124 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path);
126 // Copies a single file. Use CopyDirectory to copy directories.
127 bool CopyFile(const FilePath& from_path, const FilePath& to_path);
129 // Copies the given path, and optionally all subdirectories and their contents
130 // as well.
131 // If there are files existing under to_path, always overwrite.
132 // Returns true if successful, false otherwise.
133 // Don't use wildcards on the names, it may stop working without notice.
135 // If you only need to copy a file use CopyFile, it's faster.
136 bool CopyDirectory(const FilePath& from_path, const FilePath& to_path,
137 bool recursive);
139 // Returns true if the given path exists on the local filesystem,
140 // false otherwise.
141 bool PathExists(const FilePath& path);
143 // Returns true if the given path is writable by the user, false otherwise.
144 bool PathIsWritable(const FilePath& path);
146 // Returns true if the given path exists and is a directory, false otherwise.
147 bool DirectoryExists(const FilePath& path);
149 #if defined(OS_WIN)
150 // Gets the creation time of the given file (expressed in the local timezone),
151 // and returns it via the creation_time parameter. Returns true if successful,
152 // false otherwise.
153 bool GetFileCreationLocalTime(const std::wstring& filename,
154 LPSYSTEMTIME creation_time);
156 // Same as above, but takes a previously-opened file handle instead of a name.
157 bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle,
158 LPSYSTEMTIME creation_time);
159 #endif // defined(OS_WIN)
161 // Returns true if the contents of the two files given are equal, false
162 // otherwise. If either file can't be read, returns false.
163 bool ContentsEqual(const FilePath& filename1,
164 const FilePath& filename2);
166 // Returns true if the contents of the two text files given are equal, false
167 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
168 bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2);
170 // Read the file at |path| into |contents|, returning true on success.
171 // |contents| may be NULL, in which case this function is useful for its
172 // side effect of priming the disk cache.
173 // Useful for unit tests.
174 bool ReadFileToString(const FilePath& path, std::string* contents);
176 #if defined(OS_POSIX)
177 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
178 // in |buffer|. This function is protected against EINTR and partial reads.
179 // Returns true iff |bytes| bytes have been successfuly read from |fd|.
180 bool ReadFromFD(int fd, char* buffer, size_t bytes);
181 #endif // defined(OS_POSIX)
183 #if defined(OS_WIN)
184 // Resolve Windows shortcut (.LNK file)
185 // This methods tries to resolve a shortcut .LNK file. If the |path| is valid
186 // returns true and puts the target into the |path|, otherwise returns
187 // false leaving the path as it is.
188 bool ResolveShortcut(FilePath* path);
190 // Create a Windows shortcut (.LNK file)
191 // This method creates a shortcut link using the information given. Ensure
192 // you have initialized COM before calling into this function. 'source'
193 // and 'destination' parameters are required, everything else can be NULL.
194 // 'source' is the existing file, 'destination' is the new link file to be
195 // created; for best results pass the filename with the .lnk extension.
196 // The 'icon' can specify a dll or exe in which case the icon index is the
197 // resource id. 'app_id' is the app model id for the shortcut on Win7.
198 // Note that if the shortcut exists it will overwrite it.
199 bool CreateShortcutLink(const wchar_t *source, const wchar_t *destination,
200 const wchar_t *working_dir, const wchar_t *arguments,
201 const wchar_t *description, const wchar_t *icon,
202 int icon_index, const wchar_t* app_id);
204 // Update a Windows shortcut (.LNK file). This method assumes the shortcut
205 // link already exists (otherwise false is returned). Ensure you have
206 // initialized COM before calling into this function. Only 'destination'
207 // parameter is required, everything else can be NULL (but if everything else
208 // is NULL no changes are made to the shortcut). 'destination' is the link
209 // file to be updated. 'app_id' is the app model id for the shortcut on Win7.
210 // For best results pass the filename with the .lnk extension.
211 bool UpdateShortcutLink(const wchar_t *source, const wchar_t *destination,
212 const wchar_t *working_dir, const wchar_t *arguments,
213 const wchar_t *description, const wchar_t *icon,
214 int icon_index, const wchar_t* app_id);
216 // Pins a shortcut to the Windows 7 taskbar. The shortcut file must already
217 // exist and be a shortcut that points to an executable.
218 bool TaskbarPinShortcutLink(const wchar_t* shortcut);
220 // Unpins a shortcut from the Windows 7 taskbar. The shortcut must exist and
221 // already be pinned to the taskbar.
222 bool TaskbarUnpinShortcutLink(const wchar_t* shortcut);
224 // Copy from_path to to_path recursively and then delete from_path recursively.
225 // Returns true if all operations succeed.
226 // This function simulates Move(), but unlike Move() it works across volumes.
227 // This fuction is not transactional.
228 bool CopyAndDeleteDirectory(const FilePath& from_path,
229 const FilePath& to_path);
230 #endif // defined(OS_WIN)
232 // Return true if the given directory is empty
233 bool IsDirectoryEmpty(const FilePath& dir_path);
235 // Get the temporary directory provided by the system.
236 bool GetTempDir(FilePath* path);
237 // Get a temporary directory for shared memory files.
238 // Only useful on POSIX; redirects to GetTempDir() on Windows.
239 bool GetShmemTempDir(FilePath* path);
241 // Get the home directory. This is more complicated than just getenv("HOME")
242 // as it knows to fall back on getpwent() etc.
243 FilePath GetHomeDir();
245 // Creates a temporary file. The full path is placed in |path|, and the
246 // function returns true if was successful in creating the file. The file will
247 // be empty and all handles closed after this function returns.
248 bool CreateTemporaryFile(FilePath* path);
250 // Create and open a temporary file. File is opened for read/write.
251 // The full path is placed in |path|.
252 // Returns a handle to the opened file or NULL if an error occured.
253 FILE* CreateAndOpenTemporaryFile(FilePath* path);
254 // Like above but for shmem files. Only useful for POSIX.
255 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path);
257 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
258 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path);
260 // Same as CreateTemporaryFile but the file is created in |dir|.
261 bool CreateTemporaryFileInDir(const FilePath& dir,
262 FilePath* temp_file);
264 // Create a directory within another directory.
265 // Extra characters will be appended to |name_tmpl| to ensure that the
266 // new directory does not have the same name as an existing directory.
267 bool CreateTemporaryDirInDir(const FilePath& base_dir,
268 const FilePath::StringType& prefix,
269 FilePath* new_dir);
271 // Create a new directory under TempPath. If prefix is provided, the new
272 // directory name is in the format of prefixyyyy.
273 // NOTE: prefix is ignored in the POSIX implementation.
274 // TODO(erikkay): is this OK?
275 // If success, return true and output the full path of the directory created.
276 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
277 FilePath* new_temp_path);
279 // Creates a directory, as well as creating any parent directories, if they
280 // don't exist. Returns 'true' on successful creation, or if the directory
281 // already exists. The directory is only readable by the current user.
282 bool CreateDirectory(const FilePath& full_path);
284 #if defined(OS_WIN)
285 // Added for debugging an issue where CreateDirectory() fails. LOG(*) does
286 // not work, because the failure happens in a sandboxed process.
287 // TODO(skerner): Remove once crbug/35198 is resolved.
288 bool CreateDirectoryExtraLogging(const FilePath& full_path,
289 std::ostream& error);
290 #endif // defined (OS_WIN)
292 // Returns the file size. Returns true on success.
293 bool GetFileSize(const FilePath& file_path, int64* file_size);
295 // Returns true if the given path's base name is ".".
296 bool IsDot(const FilePath& path);
298 // Returns true if the given path's base name is "..".
299 bool IsDotDot(const FilePath& path);
301 // Sets |real_path| to |path| with symbolic links and junctions expanded.
302 // On windows, make sure the path starts with a lettered drive.
303 // |path| must reference a file. Function will fail if |path| points to
304 // a directory or to a nonexistent path. On windows, this function will
305 // fail if |path| is a junction or symlink that points to an empty file,
306 // or if |real_path| would be longer than MAX_PATH characters.
307 bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
309 // Used to hold information about a given file path. See GetFileInfo below.
310 struct FileInfo {
311 // The size of the file in bytes. Undefined when is_directory is true.
312 int64 size;
314 // True if the file corresponds to a directory.
315 bool is_directory;
317 // The last modified time of a file.
318 base::Time last_modified;
320 // Add additional fields here as needed.
323 // Returns information about the given file path.
324 bool GetFileInfo(const FilePath& file_path, FileInfo* info);
326 // Set the time of the last modification. Useful for unit tests.
327 bool SetLastModifiedTime(const FilePath& file_path, base::Time last_modified);
329 #if defined(OS_POSIX)
330 // Store inode number of |path| in |inode|. Return true on success.
331 bool GetInode(const FilePath& path, ino_t* inode);
332 #endif
334 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
335 FILE* OpenFile(const FilePath& filename, const char* mode);
337 // Closes file opened by OpenFile. Returns true on success.
338 bool CloseFile(FILE* file);
340 // Truncates an open file to end at the location of the current file pointer.
341 // This is a cross-platform analog to Windows' SetEndOfFile() function.
342 bool TruncateFile(FILE* file);
344 // Reads the given number of bytes from the file into the buffer. Returns
345 // the number of read bytes, or -1 on error.
346 int ReadFile(const FilePath& filename, char* data, int size);
348 // Writes the given buffer into the file, overwriting any data that was
349 // previously there. Returns the number of bytes written, or -1 on error.
350 int WriteFile(const FilePath& filename, const char* data, int size);
351 #if defined(OS_POSIX)
352 // Append the data to |fd|. Does not close |fd| when done.
353 int WriteFileDescriptor(const int fd, const char* data, int size);
354 #endif
356 // Gets the current working directory for the process.
357 bool GetCurrentDirectory(FilePath* path);
359 // Sets the current working directory for the process.
360 bool SetCurrentDirectory(const FilePath& path);
362 // A class to handle auto-closing of FILE*'s.
363 class ScopedFILEClose {
364 public:
365 inline void operator()(FILE* x) const {
366 if (x) {
367 fclose(x);
372 typedef scoped_ptr_malloc<FILE, ScopedFILEClose> ScopedFILE;
374 #if defined(OS_POSIX)
375 // A class to handle auto-closing of FDs.
376 class ScopedFDClose {
377 public:
378 inline void operator()(int* x) const {
379 if (x && *x >= 0) {
380 HANDLE_EINTR(close(*x));
385 typedef scoped_ptr_malloc<int, ScopedFDClose> ScopedFD;
386 #endif // OS_POSIX
388 // A class for enumerating the files in a provided path. The order of the
389 // results is not guaranteed.
391 // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
392 // program where latency does not matter. This class is blocking.
393 class FileEnumerator {
394 public:
395 #if defined(OS_WIN)
396 typedef WIN32_FIND_DATA FindInfo;
397 #elif defined(OS_POSIX)
398 typedef struct {
399 struct stat stat;
400 std::string filename;
401 } FindInfo;
402 #endif
404 enum FILE_TYPE {
405 FILES = 1 << 0,
406 DIRECTORIES = 1 << 1,
407 INCLUDE_DOT_DOT = 1 << 2,
408 #if defined(OS_POSIX)
409 SHOW_SYM_LINKS = 1 << 4,
410 #endif
413 // |root_path| is the starting directory to search for. It may or may not end
414 // in a slash.
416 // If |recursive| is true, this will enumerate all matches in any
417 // subdirectories matched as well. It does a breadth-first search, so all
418 // files in one directory will be returned before any files in a
419 // subdirectory.
421 // |file_type| specifies whether the enumerator should match files,
422 // directories, or both.
424 // |pattern| is an optional pattern for which files to match. This
425 // works like shell globbing. For example, "*.txt" or "Foo???.doc".
426 // However, be careful in specifying patterns that aren't cross platform
427 // since the underlying code uses OS-specific matching routines. In general,
428 // Windows matching is less featureful than others, so test there first.
429 // If unspecified, this will match all files.
430 // NOTE: the pattern only matches the contents of root_path, not files in
431 // recursive subdirectories.
432 // TODO(erikkay): Fix the pattern matching to work at all levels.
433 FileEnumerator(const FilePath& root_path,
434 bool recursive,
435 FileEnumerator::FILE_TYPE file_type);
436 FileEnumerator(const FilePath& root_path,
437 bool recursive,
438 FileEnumerator::FILE_TYPE file_type,
439 const FilePath::StringType& pattern);
440 ~FileEnumerator();
442 // Returns an empty string if there are no more results.
443 FilePath Next();
445 // Write the file info into |info|.
446 void GetFindInfo(FindInfo* info);
448 // Looks inside a FindInfo and determines if it's a directory.
449 static bool IsDirectory(const FindInfo& info);
451 static FilePath GetFilename(const FindInfo& find_info);
453 private:
454 // Returns true if the given path should be skipped in enumeration.
455 bool ShouldSkip(const FilePath& path);
458 #if defined(OS_WIN)
459 WIN32_FIND_DATA find_data_;
460 HANDLE find_handle_;
461 #elif defined(OS_POSIX)
462 typedef struct {
463 FilePath filename;
464 struct stat stat;
465 } DirectoryEntryInfo;
467 // Read the filenames in source into the vector of DirectoryEntryInfo's
468 static bool ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
469 const FilePath& source, bool show_links);
471 // The files in the current directory
472 std::vector<DirectoryEntryInfo> directory_entries_;
474 // The next entry to use from the directory_entries_ vector
475 size_t current_directory_entry_;
476 #endif
478 FilePath root_path_;
479 bool recursive_;
480 FILE_TYPE file_type_;
481 FilePath::StringType pattern_; // Empty when we want to find everything.
483 // Set to true when there is a find operation open. This way, we can lazily
484 // start the operations when the caller calls Next().
485 bool is_in_find_op_;
487 // A stack that keeps track of which subdirectories we still need to
488 // enumerate in the breadth-first search.
489 std::stack<FilePath> pending_paths_;
491 DISALLOW_COPY_AND_ASSIGN(FileEnumerator);
494 class MemoryMappedFile {
495 public:
496 // The default constructor sets all members to invalid/null values.
497 MemoryMappedFile();
498 ~MemoryMappedFile();
500 // Opens an existing file and maps it into memory. Access is restricted to
501 // read only. If this object already points to a valid memory mapped file
502 // then this method will fail and return false. If it cannot open the file,
503 // the file does not exist, or the memory mapping fails, it will return false.
504 // Later we may want to allow the user to specify access.
505 bool Initialize(const FilePath& file_name);
506 // As above, but works with an already-opened file. MemoryMappedFile will take
507 // ownership of |file| and close it when done.
508 bool Initialize(base::PlatformFile file);
510 const uint8* data() const { return data_; }
511 size_t length() const { return length_; }
513 // Is file_ a valid file handle that points to an open, memory mapped file?
514 bool IsValid();
516 private:
517 // Open the given file and pass it to MapFileToMemoryInternal().
518 bool MapFileToMemory(const FilePath& file_name);
520 // Map the file to memory, set data_ to that memory address. Return true on
521 // success, false on any kind of failure. This is a helper for Initialize().
522 bool MapFileToMemoryInternal();
524 // Closes all open handles. Later we may want to make this public.
525 void CloseHandles();
527 base::PlatformFile file_;
528 #if defined(OS_WIN)
529 HANDLE file_mapping_;
530 #endif
531 uint8* data_;
532 size_t length_;
534 DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile);
537 // Renames a file using the SHFileOperation API to ensure that the target file
538 // gets the correct default security descriptor in the new path.
539 bool RenameFileAndResetSecurityDescriptor(
540 const FilePath& source_file_path,
541 const FilePath& target_file_path);
543 // Returns whether the file has been modified since a particular date.
544 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo& find_info,
545 const base::Time& cutoff_time);
547 #ifdef UNIT_TEST
549 inline bool MakeFileUnreadable(const FilePath& path) {
550 #if defined(OS_POSIX)
551 struct stat stat_buf;
552 if (stat(path.value().c_str(), &stat_buf) != 0)
553 return false;
554 stat_buf.st_mode &= ~(S_IRUSR | S_IRGRP | S_IROTH);
556 return chmod(path.value().c_str(), stat_buf.st_mode) == 0;
558 #elif defined(OS_WIN)
559 PACL old_dacl;
560 PSECURITY_DESCRIPTOR security_descriptor;
561 if (GetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()),
562 SE_FILE_OBJECT,
563 DACL_SECURITY_INFORMATION, NULL, NULL, &old_dacl,
564 NULL, &security_descriptor) != ERROR_SUCCESS)
565 return false;
567 // Deny Read access for the current user.
568 EXPLICIT_ACCESS change;
569 change.grfAccessPermissions = GENERIC_READ;
570 change.grfAccessMode = DENY_ACCESS;
571 change.grfInheritance = 0;
572 change.Trustee.pMultipleTrustee = NULL;
573 change.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
574 change.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
575 change.Trustee.TrusteeType = TRUSTEE_IS_USER;
576 change.Trustee.ptstrName = L"CURRENT_USER";
578 PACL new_dacl;
579 if (SetEntriesInAcl(1, &change, old_dacl, &new_dacl) != ERROR_SUCCESS) {
580 LocalFree(security_descriptor);
581 return false;
584 DWORD rc = SetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()),
585 SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
586 NULL, NULL, new_dacl, NULL);
587 LocalFree(security_descriptor);
588 LocalFree(new_dacl);
590 return rc == ERROR_SUCCESS;
591 #else
592 NOTIMPLEMENTED();
593 return false;
594 #endif
597 #endif // UNIT_TEST
599 } // namespace file_util
601 // Deprecated functions have been moved to this separate header file,
602 // which must be included last after all the above definitions.
603 #include "base/file_util_deprecated.h"
605 #endif // BASE_FILE_UTIL_H_