1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file contains utility functions for dealing with the local
8 #ifndef BASE_FILE_UTIL_H_
9 #define BASE_FILE_UTIL_H_
11 #include "build/build_config.h"
15 #elif defined(OS_POSIX)
27 #include "base/base_export.h"
28 #include "base/basictypes.h"
29 #include "base/files/file_path.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/platform_file.h"
32 #include "base/string16.h"
35 #include "base/file_descriptor_posix.h"
36 #include "base/logging.h"
37 #include "base/posix/eintr_wrapper.h"
43 // Returns an absolute version of a relative path. Returns an empty path on
44 // error. On POSIX, this function fails if the path does not exist. This
45 // function can result in I/O so it can be slow.
46 BASE_EXPORT FilePath
MakeAbsoluteFilePath(const FilePath
& input
);
52 extern bool g_bug108724_debug
;
54 //-----------------------------------------------------------------------------
55 // Functions that involve filesystem access or modification:
57 // Returns the total number of bytes used by all the files under |root_path|.
58 // If the path does not exist the function returns 0.
60 // This function is implemented using the FileEnumerator class so it is not
61 // particularly speedy in any platform.
62 BASE_EXPORT int64
ComputeDirectorySize(const base::FilePath
& root_path
);
64 // Deletes the given path, whether it's a file or a directory.
65 // If it's a directory, it's perfectly happy to delete all of the
66 // directory's contents. Passing true to recursive deletes
67 // subdirectories and their contents as well.
68 // Returns true if successful, false otherwise. It is considered successful
69 // to attempt to delete a file that does not exist.
71 // In posix environment and if |path| is a symbolic link, this deletes only
72 // the symlink. (even if the symlink points to a non-existent file)
74 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
75 // TO "rm -rf", SO USE WITH CAUTION.
76 BASE_EXPORT
bool Delete(const base::FilePath
& path
, bool recursive
);
79 // Schedules to delete the given path, whether it's a file or a directory, until
80 // the operating system is restarted.
82 // 1) The file/directory to be deleted should exist in a temp folder.
83 // 2) The directory to be deleted must be empty.
84 BASE_EXPORT
bool DeleteAfterReboot(const base::FilePath
& path
);
87 // Moves the given path, whether it's a file or a directory.
88 // If a simple rename is not possible, such as in the case where the paths are
89 // on different volumes, this will attempt to copy and delete. Returns
91 // This function fails if either path contains traversal components ('..').
92 BASE_EXPORT
bool Move(const base::FilePath
& from_path
,
93 const base::FilePath
& to_path
);
95 // Same as Move but allows paths with traversal components.
96 // Use only with extreme care.
97 BASE_EXPORT
bool MoveUnsafe(const base::FilePath
& from_path
,
98 const base::FilePath
& to_path
);
100 // Renames file |from_path| to |to_path|. Both paths must be on the same
101 // volume, or the function will fail. Destination file will be created
102 // if it doesn't exist. Prefer this function over Move when dealing with
103 // temporary files. On Windows it preserves attributes of the target file.
104 // Returns true on success, leaving *error unchanged.
105 // Returns false on failure and sets *error appropriately, if it is non-NULL.
106 BASE_EXPORT
bool ReplaceFileAndGetError(const base::FilePath
& from_path
,
107 const base::FilePath
& to_path
,
108 base::PlatformFileError
* error
);
110 // Backward-compatible convenience method for the above.
111 BASE_EXPORT
bool ReplaceFile(const base::FilePath
& from_path
,
112 const base::FilePath
& to_path
);
114 // Copies a single file. Use CopyDirectory to copy directories.
115 // This function fails if either path contains traversal components ('..').
116 BASE_EXPORT
bool CopyFile(const base::FilePath
& from_path
,
117 const base::FilePath
& to_path
);
119 // Same as CopyFile but allows paths with traversal components.
120 // Use only with extreme care.
121 BASE_EXPORT
bool CopyFileUnsafe(const base::FilePath
& from_path
,
122 const base::FilePath
& to_path
);
124 // Copies the given path, and optionally all subdirectories and their contents
126 // If there are files existing under to_path, always overwrite.
127 // Returns true if successful, false otherwise.
128 // Don't use wildcards on the names, it may stop working without notice.
130 // If you only need to copy a file use CopyFile, it's faster.
131 BASE_EXPORT
bool CopyDirectory(const base::FilePath
& from_path
,
132 const base::FilePath
& to_path
,
135 // Returns true if the given path exists on the local filesystem,
137 BASE_EXPORT
bool PathExists(const base::FilePath
& path
);
139 // Returns true if the given path is writable by the user, false otherwise.
140 BASE_EXPORT
bool PathIsWritable(const base::FilePath
& path
);
142 // Returns true if the given path exists and is a directory, false otherwise.
143 BASE_EXPORT
bool DirectoryExists(const base::FilePath
& path
);
145 // Returns true if the contents of the two files given are equal, false
146 // otherwise. If either file can't be read, returns false.
147 BASE_EXPORT
bool ContentsEqual(const base::FilePath
& filename1
,
148 const base::FilePath
& filename2
);
150 // Returns true if the contents of the two text files given are equal, false
151 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
152 BASE_EXPORT
bool TextContentsEqual(const base::FilePath
& filename1
,
153 const base::FilePath
& filename2
);
155 // Read the file at |path| into |contents|, returning true on success.
156 // This function fails if the |path| contains path traversal components ('..').
157 // |contents| may be NULL, in which case this function is useful for its
158 // side effect of priming the disk cache.
159 // Useful for unit tests.
160 BASE_EXPORT
bool ReadFileToString(const base::FilePath
& path
,
161 std::string
* contents
);
163 #if defined(OS_POSIX)
164 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
165 // in |buffer|. This function is protected against EINTR and partial reads.
166 // Returns true iff |bytes| bytes have been successfuly read from |fd|.
167 BASE_EXPORT
bool ReadFromFD(int fd
, char* buffer
, size_t bytes
);
169 // Creates a symbolic link at |symlink| pointing to |target|. Returns
171 BASE_EXPORT
bool CreateSymbolicLink(const base::FilePath
& target
,
172 const base::FilePath
& symlink
);
174 // Reads the given |symlink| and returns where it points to in |target|.
175 // Returns false upon failure.
176 BASE_EXPORT
bool ReadSymbolicLink(const base::FilePath
& symlink
,
177 base::FilePath
* target
);
179 // Bits ans masks of the file permission.
180 enum FilePermissionBits
{
181 FILE_PERMISSION_MASK
= S_IRWXU
| S_IRWXG
| S_IRWXO
,
182 FILE_PERMISSION_USER_MASK
= S_IRWXU
,
183 FILE_PERMISSION_GROUP_MASK
= S_IRWXG
,
184 FILE_PERMISSION_OTHERS_MASK
= S_IRWXO
,
186 FILE_PERMISSION_READ_BY_USER
= S_IRUSR
,
187 FILE_PERMISSION_WRITE_BY_USER
= S_IWUSR
,
188 FILE_PERMISSION_EXECUTE_BY_USER
= S_IXUSR
,
189 FILE_PERMISSION_READ_BY_GROUP
= S_IRGRP
,
190 FILE_PERMISSION_WRITE_BY_GROUP
= S_IWGRP
,
191 FILE_PERMISSION_EXECUTE_BY_GROUP
= S_IXGRP
,
192 FILE_PERMISSION_READ_BY_OTHERS
= S_IROTH
,
193 FILE_PERMISSION_WRITE_BY_OTHERS
= S_IWOTH
,
194 FILE_PERMISSION_EXECUTE_BY_OTHERS
= S_IXOTH
,
197 // Reads the permission of the given |path|, storing the file permission
198 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
199 // a file which the symlink points to.
200 BASE_EXPORT
bool GetPosixFilePermissions(const base::FilePath
& path
,
202 // Sets the permission of the given |path|. If |path| is symbolic link, sets
203 // the permission of a file which the symlink points to.
204 BASE_EXPORT
bool SetPosixFilePermissions(const base::FilePath
& path
,
206 #endif // defined(OS_POSIX)
209 // Copy from_path to to_path recursively and then delete from_path recursively.
210 // Returns true if all operations succeed.
211 // This function simulates Move(), but unlike Move() it works across volumes.
212 // This fuction is not transactional.
213 BASE_EXPORT
bool CopyAndDeleteDirectory(const base::FilePath
& from_path
,
214 const base::FilePath
& to_path
);
215 #endif // defined(OS_WIN)
217 // Return true if the given directory is empty
218 BASE_EXPORT
bool IsDirectoryEmpty(const base::FilePath
& dir_path
);
220 // Get the temporary directory provided by the system.
221 // WARNING: DON'T USE THIS. If you want to create a temporary file, use one of
222 // the functions below.
223 BASE_EXPORT
bool GetTempDir(base::FilePath
* path
);
224 // Get a temporary directory for shared memory files.
225 // Only useful on POSIX; redirects to GetTempDir() on Windows.
226 BASE_EXPORT
bool GetShmemTempDir(base::FilePath
* path
, bool executable
);
228 // Get the home directory. This is more complicated than just getenv("HOME")
229 // as it knows to fall back on getpwent() etc.
230 BASE_EXPORT
base::FilePath
GetHomeDir();
232 // Creates a temporary file. The full path is placed in |path|, and the
233 // function returns true if was successful in creating the file. The file will
234 // be empty and all handles closed after this function returns.
235 BASE_EXPORT
bool CreateTemporaryFile(base::FilePath
* path
);
237 // Same as CreateTemporaryFile but the file is created in |dir|.
238 BASE_EXPORT
bool CreateTemporaryFileInDir(const base::FilePath
& dir
,
239 base::FilePath
* temp_file
);
241 // Create and open a temporary file. File is opened for read/write.
242 // The full path is placed in |path|.
243 // Returns a handle to the opened file or NULL if an error occured.
244 BASE_EXPORT
FILE* CreateAndOpenTemporaryFile(base::FilePath
* path
);
245 // Like above but for shmem files. Only useful for POSIX.
246 // The executable flag says the file needs to support using
247 // mprotect with PROT_EXEC after mapping.
248 BASE_EXPORT
FILE* CreateAndOpenTemporaryShmemFile(base::FilePath
* path
,
250 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
251 BASE_EXPORT
FILE* CreateAndOpenTemporaryFileInDir(const base::FilePath
& dir
,
252 base::FilePath
* path
);
254 // Create a new directory. If prefix is provided, the new directory name is in
255 // the format of prefixyyyy.
256 // NOTE: prefix is ignored in the POSIX implementation.
257 // If success, return true and output the full path of the directory created.
258 BASE_EXPORT
bool CreateNewTempDirectory(
259 const base::FilePath::StringType
& prefix
,
260 base::FilePath
* new_temp_path
);
262 // Create a directory within another directory.
263 // Extra characters will be appended to |prefix| to ensure that the
264 // new directory does not have the same name as an existing directory.
265 BASE_EXPORT
bool CreateTemporaryDirInDir(
266 const base::FilePath
& base_dir
,
267 const base::FilePath::StringType
& prefix
,
268 base::FilePath
* new_dir
);
270 // Creates a directory, as well as creating any parent directories, if they
271 // don't exist. Returns 'true' on successful creation, or if the directory
272 // already exists. The directory is only readable by the current user.
273 BASE_EXPORT
bool CreateDirectory(const base::FilePath
& full_path
);
275 // Returns the file size. Returns true on success.
276 BASE_EXPORT
bool GetFileSize(const base::FilePath
& file_path
, int64
* file_size
);
278 // Sets |real_path| to |path| with symbolic links and junctions expanded.
279 // On windows, make sure the path starts with a lettered drive.
280 // |path| must reference a file. Function will fail if |path| points to
281 // a directory or to a nonexistent path. On windows, this function will
282 // fail if |path| is a junction or symlink that points to an empty file,
283 // or if |real_path| would be longer than MAX_PATH characters.
284 BASE_EXPORT
bool NormalizeFilePath(const base::FilePath
& path
,
285 base::FilePath
* real_path
);
289 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
290 // return in |drive_letter_path| the equivalent path that starts with
291 // a drive letter ("C:\..."). Return false if no such path exists.
292 BASE_EXPORT
bool DevicePathToDriveLetterPath(const base::FilePath
& device_path
,
293 base::FilePath
* drive_letter_path
);
295 // Given an existing file in |path|, set |real_path| to the path
296 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
297 // Returns false if the path can not be found. Empty files cannot
298 // be resolved with this function.
299 BASE_EXPORT
bool NormalizeToNativeFilePath(const base::FilePath
& path
,
300 base::FilePath
* nt_path
);
303 // This function will return if the given file is a symlink or not.
304 BASE_EXPORT
bool IsLink(const base::FilePath
& file_path
);
306 // Returns information about the given file path.
307 BASE_EXPORT
bool GetFileInfo(const base::FilePath
& file_path
,
308 base::PlatformFileInfo
* info
);
310 // Sets the time of the last access and the time of the last modification.
311 BASE_EXPORT
bool TouchFile(const base::FilePath
& path
,
312 const base::Time
& last_accessed
,
313 const base::Time
& last_modified
);
315 // Set the time of the last modification. Useful for unit tests.
316 BASE_EXPORT
bool SetLastModifiedTime(const base::FilePath
& path
,
317 const base::Time
& last_modified
);
319 #if defined(OS_POSIX)
320 // Store inode number of |path| in |inode|. Return true on success.
321 BASE_EXPORT
bool GetInode(const base::FilePath
& path
, ino_t
* inode
);
324 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
325 BASE_EXPORT
FILE* OpenFile(const base::FilePath
& filename
, const char* mode
);
327 // Closes file opened by OpenFile. Returns true on success.
328 BASE_EXPORT
bool CloseFile(FILE* file
);
330 // Truncates an open file to end at the location of the current file pointer.
331 // This is a cross-platform analog to Windows' SetEndOfFile() function.
332 BASE_EXPORT
bool TruncateFile(FILE* file
);
334 // Reads the given number of bytes from the file into the buffer. Returns
335 // the number of read bytes, or -1 on error.
336 BASE_EXPORT
int ReadFile(const base::FilePath
& filename
, char* data
, int size
);
338 // Writes the given buffer into the file, overwriting any data that was
339 // previously there. Returns the number of bytes written, or -1 on error.
340 BASE_EXPORT
int WriteFile(const base::FilePath
& filename
, const char* data
,
342 #if defined(OS_POSIX)
343 // Append the data to |fd|. Does not close |fd| when done.
344 BASE_EXPORT
int WriteFileDescriptor(const int fd
, const char* data
, int size
);
346 // Append the given buffer into the file. Returns the number of bytes written,
348 BASE_EXPORT
int AppendToFile(const base::FilePath
& filename
,
349 const char* data
, int size
);
351 // Gets the current working directory for the process.
352 BASE_EXPORT
bool GetCurrentDirectory(base::FilePath
* path
);
354 // Sets the current working directory for the process.
355 BASE_EXPORT
bool SetCurrentDirectory(const base::FilePath
& path
);
357 // Attempts to find a number that can be appended to the |path| to make it
358 // unique. If |path| does not exist, 0 is returned. If it fails to find such
359 // a number, -1 is returned. If |suffix| is not empty, also checks the
360 // existence of it with the given suffix.
361 BASE_EXPORT
int GetUniquePathNumber(const base::FilePath
& path
,
362 const base::FilePath::StringType
& suffix
);
364 #if defined(OS_POSIX)
365 // Creates a directory with a guaranteed unique name based on |path|, returning
366 // the pathname if successful, or an empty path if there was an error creating
367 // the directory. Does not create parent directories.
368 BASE_EXPORT
base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
);
371 #if defined(OS_POSIX)
372 // Test that |path| can only be changed by a given user and members of
373 // a given set of groups.
374 // Specifically, test that all parts of |path| under (and including) |base|:
376 // * Are owned by a specific user.
377 // * Are not writable by all users.
378 // * Are owned by a memeber of a given set of groups, or are not writable by
380 // * Are not symbolic links.
381 // This is useful for checking that a config file is administrator-controlled.
382 // |base| must contain |path|.
383 BASE_EXPORT
bool VerifyPathControlledByUser(const base::FilePath
& base
,
384 const base::FilePath
& path
,
386 const std::set
<gid_t
>& group_gids
);
387 #endif // defined(OS_POSIX)
389 #if defined(OS_MACOSX) && !defined(OS_IOS)
390 // Is |path| writable only by a user with administrator privileges?
391 // This function uses Mac OS conventions. The super user is assumed to have
392 // uid 0, and the administrator group is assumed to be named "admin".
393 // Testing that |path|, and every parent directory including the root of
394 // the filesystem, are owned by the superuser, controlled by the group
395 // "admin", are not writable by all users, and contain no symbolic links.
396 // Will return false if |path| does not exist.
397 BASE_EXPORT
bool VerifyPathControlledByAdmin(const base::FilePath
& path
);
398 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
400 // Returns the maximum length of path component on the volume containing
401 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
402 BASE_EXPORT
int GetMaximumPathComponentLength(const base::FilePath
& path
);
404 // A class to handle auto-closing of FILE*'s.
405 class ScopedFILEClose
{
407 inline void operator()(FILE* x
) const {
414 typedef scoped_ptr_malloc
<FILE, ScopedFILEClose
> ScopedFILE
;
416 #if defined(OS_POSIX)
417 // A class to handle auto-closing of FDs.
418 class ScopedFDClose
{
420 inline void operator()(int* x
) const {
422 if (HANDLE_EINTR(close(*x
)) < 0)
423 DPLOG(ERROR
) << "close";
428 typedef scoped_ptr_malloc
<int, ScopedFDClose
> ScopedFD
;
431 // A class for enumerating the files in a provided path. The order of the
432 // results is not guaranteed.
434 // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
435 // program where latency does not matter. This class is blocking.
436 class BASE_EXPORT FileEnumerator
{
439 typedef WIN32_FIND_DATA FindInfo
;
440 #elif defined(OS_POSIX)
443 std::string filename
;
449 DIRECTORIES
= 1 << 1,
450 INCLUDE_DOT_DOT
= 1 << 2,
451 #if defined(OS_POSIX)
452 SHOW_SYM_LINKS
= 1 << 4,
456 // |root_path| is the starting directory to search for. It may or may not end
459 // If |recursive| is true, this will enumerate all matches in any
460 // subdirectories matched as well. It does a breadth-first search, so all
461 // files in one directory will be returned before any files in a
464 // |file_type|, a bit mask of FileType, specifies whether the enumerator
465 // should match files, directories, or both.
467 // |pattern| is an optional pattern for which files to match. This
468 // works like shell globbing. For example, "*.txt" or "Foo???.doc".
469 // However, be careful in specifying patterns that aren't cross platform
470 // since the underlying code uses OS-specific matching routines. In general,
471 // Windows matching is less featureful than others, so test there first.
472 // If unspecified, this will match all files.
473 // NOTE: the pattern only matches the contents of root_path, not files in
474 // recursive subdirectories.
475 // TODO(erikkay): Fix the pattern matching to work at all levels.
476 FileEnumerator(const base::FilePath
& root_path
,
479 FileEnumerator(const base::FilePath
& root_path
,
482 const base::FilePath::StringType
& pattern
);
485 // Returns an empty string if there are no more results.
486 base::FilePath
Next();
488 // Write the file info into |info|.
489 void GetFindInfo(FindInfo
* info
);
491 // Looks inside a FindInfo and determines if it's a directory.
492 static bool IsDirectory(const FindInfo
& info
);
494 static base::FilePath
GetFilename(const FindInfo
& find_info
);
495 static int64
GetFilesize(const FindInfo
& find_info
);
496 static base::Time
GetLastModifiedTime(const FindInfo
& find_info
);
499 // Returns true if the given path should be skipped in enumeration.
500 bool ShouldSkip(const base::FilePath
& path
);
504 // True when find_data_ is valid.
506 WIN32_FIND_DATA find_data_
;
508 #elif defined(OS_POSIX)
509 struct DirectoryEntryInfo
{
510 base::FilePath filename
;
514 // Read the filenames in source into the vector of DirectoryEntryInfo's
515 static bool ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
516 const base::FilePath
& source
, bool show_links
);
518 // The files in the current directory
519 std::vector
<DirectoryEntryInfo
> directory_entries_
;
521 // The next entry to use from the directory_entries_ vector
522 size_t current_directory_entry_
;
525 base::FilePath root_path_
;
528 base::FilePath::StringType pattern_
; // Empty when we want to find
531 // A stack that keeps track of which subdirectories we still need to
532 // enumerate in the breadth-first search.
533 std::stack
<base::FilePath
> pending_paths_
;
535 DISALLOW_COPY_AND_ASSIGN(FileEnumerator
);
538 #if defined(OS_LINUX)
539 // Broad categories of file systems as returned by statfs() on Linux.
540 enum FileSystemType
{
541 FILE_SYSTEM_UNKNOWN
, // statfs failed.
542 FILE_SYSTEM_0
, // statfs.f_type == 0 means unknown, may indicate AFS.
543 FILE_SYSTEM_ORDINARY
, // on-disk filesystem like ext2
547 FILE_SYSTEM_MEMORY
, // in-memory file system
548 FILE_SYSTEM_CGROUP
, // cgroup control.
549 FILE_SYSTEM_OTHER
, // any other value.
550 FILE_SYSTEM_TYPE_COUNT
553 // Attempts determine the FileSystemType for |path|.
554 // Returns false if |path| doesn't exist.
555 BASE_EXPORT
bool GetFileSystemType(const base::FilePath
& path
,
556 FileSystemType
* type
);
559 } // namespace file_util
561 #endif // BASE_FILE_UTIL_H_