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"
46 extern bool g_bug108724_debug
;
48 //-----------------------------------------------------------------------------
49 // Functions that operate purely on a path string w/o touching the filesystem:
51 // Returns true if the given path ends with a path separator character.
52 BASE_EXPORT
bool EndsWithSeparator(const base::FilePath
& path
);
54 // Makes sure that |path| ends with a separator IFF path is a directory that
55 // exists. Returns true if |path| is an existing directory, false otherwise.
56 BASE_EXPORT
bool EnsureEndsWithSeparator(base::FilePath
* path
);
58 // Convert provided relative path into an absolute path. Returns false on
59 // error. On POSIX, this function fails if the path does not exist.
60 BASE_EXPORT
bool AbsolutePath(base::FilePath
* path
);
62 // Returns true if |parent| contains |child|. Both paths are converted to
63 // absolute paths before doing the comparison.
64 BASE_EXPORT
bool ContainsPath(const base::FilePath
& parent
,
65 const base::FilePath
& child
);
67 //-----------------------------------------------------------------------------
68 // Functions that involve filesystem access or modification:
70 // Returns the total number of bytes used by all the files under |root_path|.
71 // If the path does not exist the function returns 0.
73 // This function is implemented using the FileEnumerator class so it is not
74 // particularly speedy in any platform.
75 BASE_EXPORT int64
ComputeDirectorySize(const base::FilePath
& root_path
);
77 // Deletes the given path, whether it's a file or a directory.
78 // If it's a directory, it's perfectly happy to delete all of the
79 // directory's contents. Passing true to recursive deletes
80 // subdirectories and their contents as well.
81 // Returns true if successful, false otherwise.
83 // In posix environment and if |path| is a symbolic link, this deletes only
84 // the symlink. (even if the symlink points to a non-existent file)
86 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
87 // TO "rm -rf", SO USE WITH CAUTION.
88 BASE_EXPORT
bool Delete(const base::FilePath
& path
, bool recursive
);
91 // Schedules to delete the given path, whether it's a file or a directory, until
92 // the operating system is restarted.
94 // 1) The file/directory to be deleted should exist in a temp folder.
95 // 2) The directory to be deleted must be empty.
96 BASE_EXPORT
bool DeleteAfterReboot(const base::FilePath
& path
);
99 // Moves the given path, whether it's a file or a directory.
100 // If a simple rename is not possible, such as in the case where the paths are
101 // on different volumes, this will attempt to copy and delete. Returns
103 // This function fails if either path contains traversal components ('..').
104 BASE_EXPORT
bool Move(const base::FilePath
& from_path
,
105 const base::FilePath
& to_path
);
107 // Same as Move but allows paths with traversal components.
108 // Use only with extreme care.
109 BASE_EXPORT
bool MoveUnsafe(const base::FilePath
& from_path
,
110 const base::FilePath
& to_path
);
112 // Renames file |from_path| to |to_path|. Both paths must be on the same
113 // volume, or the function will fail. Destination file will be created
114 // if it doesn't exist. Prefer this function over Move when dealing with
115 // temporary files. On Windows it preserves attributes of the target file.
116 // Returns true on success.
117 BASE_EXPORT
bool ReplaceFile(const base::FilePath
& from_path
,
118 const base::FilePath
& to_path
);
120 // Copies a single file. Use CopyDirectory to copy directories.
121 // This function fails if either path contains traversal components ('..').
122 BASE_EXPORT
bool CopyFile(const base::FilePath
& from_path
,
123 const base::FilePath
& to_path
);
125 // Same as CopyFile but allows paths with traversal components.
126 // Use only with extreme care.
127 BASE_EXPORT
bool CopyFileUnsafe(const base::FilePath
& from_path
,
128 const base::FilePath
& to_path
);
130 // Copies the given path, and optionally all subdirectories and their contents
132 // If there are files existing under to_path, always overwrite.
133 // Returns true if successful, false otherwise.
134 // Don't use wildcards on the names, it may stop working without notice.
136 // If you only need to copy a file use CopyFile, it's faster.
137 BASE_EXPORT
bool CopyDirectory(const base::FilePath
& from_path
,
138 const base::FilePath
& to_path
,
141 // Returns true if the given path exists on the local filesystem,
143 BASE_EXPORT
bool PathExists(const base::FilePath
& path
);
145 // Returns true if the given path is writable by the user, false otherwise.
146 BASE_EXPORT
bool PathIsWritable(const base::FilePath
& path
);
148 // Returns true if the given path exists and is a directory, false otherwise.
149 BASE_EXPORT
bool DirectoryExists(const base::FilePath
& path
);
151 // Returns true if the contents of the two files given are equal, false
152 // otherwise. If either file can't be read, returns false.
153 BASE_EXPORT
bool ContentsEqual(const base::FilePath
& filename1
,
154 const base::FilePath
& filename2
);
156 // Returns true if the contents of the two text files given are equal, false
157 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
158 BASE_EXPORT
bool TextContentsEqual(const base::FilePath
& filename1
,
159 const base::FilePath
& filename2
);
161 // Read the file at |path| into |contents|, returning true on success.
162 // This function fails if the |path| contains path traversal components ('..').
163 // |contents| may be NULL, in which case this function is useful for its
164 // side effect of priming the disk cache.
165 // Useful for unit tests.
166 BASE_EXPORT
bool ReadFileToString(const base::FilePath
& path
,
167 std::string
* contents
);
169 #if defined(OS_POSIX)
170 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
171 // in |buffer|. This function is protected against EINTR and partial reads.
172 // Returns true iff |bytes| bytes have been successfuly read from |fd|.
173 BASE_EXPORT
bool ReadFromFD(int fd
, char* buffer
, size_t bytes
);
175 // Creates a symbolic link at |symlink| pointing to |target|. Returns
177 BASE_EXPORT
bool CreateSymbolicLink(const base::FilePath
& target
,
178 const base::FilePath
& symlink
);
180 // Reads the given |symlink| and returns where it points to in |target|.
181 // Returns false upon failure.
182 BASE_EXPORT
bool ReadSymbolicLink(const base::FilePath
& symlink
,
183 base::FilePath
* target
);
185 // Bits ans masks of the file permission.
186 enum FilePermissionBits
{
187 FILE_PERMISSION_MASK
= S_IRWXU
| S_IRWXG
| S_IRWXO
,
188 FILE_PERMISSION_USER_MASK
= S_IRWXU
,
189 FILE_PERMISSION_GROUP_MASK
= S_IRWXG
,
190 FILE_PERMISSION_OTHERS_MASK
= S_IRWXO
,
192 FILE_PERMISSION_READ_BY_USER
= S_IRUSR
,
193 FILE_PERMISSION_WRITE_BY_USER
= S_IWUSR
,
194 FILE_PERMISSION_EXECUTE_BY_USER
= S_IXUSR
,
195 FILE_PERMISSION_READ_BY_GROUP
= S_IRGRP
,
196 FILE_PERMISSION_WRITE_BY_GROUP
= S_IWGRP
,
197 FILE_PERMISSION_EXECUTE_BY_GROUP
= S_IXGRP
,
198 FILE_PERMISSION_READ_BY_OTHERS
= S_IROTH
,
199 FILE_PERMISSION_WRITE_BY_OTHERS
= S_IWOTH
,
200 FILE_PERMISSION_EXECUTE_BY_OTHERS
= S_IXOTH
,
203 // Reads the permission of the given |path|, storing the file permission
204 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
205 // a file which the symlink points to.
206 BASE_EXPORT
bool GetPosixFilePermissions(const base::FilePath
& path
,
208 // Sets the permission of the given |path|. If |path| is symbolic link, sets
209 // the permission of a file which the symlink points to.
210 BASE_EXPORT
bool SetPosixFilePermissions(const base::FilePath
& path
,
212 #endif // defined(OS_POSIX)
215 // Copy from_path to to_path recursively and then delete from_path recursively.
216 // Returns true if all operations succeed.
217 // This function simulates Move(), but unlike Move() it works across volumes.
218 // This fuction is not transactional.
219 BASE_EXPORT
bool CopyAndDeleteDirectory(const base::FilePath
& from_path
,
220 const base::FilePath
& to_path
);
221 #endif // defined(OS_WIN)
223 // Return true if the given directory is empty
224 BASE_EXPORT
bool IsDirectoryEmpty(const base::FilePath
& dir_path
);
226 // Get the temporary directory provided by the system.
227 // WARNING: DON'T USE THIS. If you want to create a temporary file, use one of
228 // the functions below.
229 BASE_EXPORT
bool GetTempDir(base::FilePath
* path
);
230 // Get a temporary directory for shared memory files.
231 // Only useful on POSIX; redirects to GetTempDir() on Windows.
232 BASE_EXPORT
bool GetShmemTempDir(base::FilePath
* path
, bool executable
);
234 // Get the home directory. This is more complicated than just getenv("HOME")
235 // as it knows to fall back on getpwent() etc.
236 BASE_EXPORT
base::FilePath
GetHomeDir();
238 // Creates a temporary file. The full path is placed in |path|, and the
239 // function returns true if was successful in creating the file. The file will
240 // be empty and all handles closed after this function returns.
241 BASE_EXPORT
bool CreateTemporaryFile(base::FilePath
* path
);
243 // Same as CreateTemporaryFile but the file is created in |dir|.
244 BASE_EXPORT
bool CreateTemporaryFileInDir(const base::FilePath
& dir
,
245 base::FilePath
* temp_file
);
247 // Create and open a temporary file. File is opened for read/write.
248 // The full path is placed in |path|.
249 // Returns a handle to the opened file or NULL if an error occured.
250 BASE_EXPORT
FILE* CreateAndOpenTemporaryFile(base::FilePath
* path
);
251 // Like above but for shmem files. Only useful for POSIX.
252 // The executable flag says the file needs to support using
253 // mprotect with PROT_EXEC after mapping.
254 BASE_EXPORT
FILE* CreateAndOpenTemporaryShmemFile(base::FilePath
* path
,
256 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
257 BASE_EXPORT
FILE* CreateAndOpenTemporaryFileInDir(const base::FilePath
& dir
,
258 base::FilePath
* path
);
260 // Create a new directory. If prefix is provided, the new directory name is in
261 // the format of prefixyyyy.
262 // NOTE: prefix is ignored in the POSIX implementation.
263 // If success, return true and output the full path of the directory created.
264 BASE_EXPORT
bool CreateNewTempDirectory(
265 const base::FilePath::StringType
& prefix
,
266 base::FilePath
* new_temp_path
);
268 // Create a directory within another directory.
269 // Extra characters will be appended to |prefix| to ensure that the
270 // new directory does not have the same name as an existing directory.
271 BASE_EXPORT
bool CreateTemporaryDirInDir(
272 const base::FilePath
& base_dir
,
273 const base::FilePath::StringType
& prefix
,
274 base::FilePath
* new_dir
);
276 // Creates a directory, as well as creating any parent directories, if they
277 // don't exist. Returns 'true' on successful creation, or if the directory
278 // already exists. The directory is only readable by the current user.
279 BASE_EXPORT
bool CreateDirectory(const base::FilePath
& full_path
);
281 // Returns the file size. Returns true on success.
282 BASE_EXPORT
bool GetFileSize(const base::FilePath
& file_path
, int64
* file_size
);
284 // Returns true if the given path's base name is ".".
285 BASE_EXPORT
bool IsDot(const base::FilePath
& path
);
287 // Returns true if the given path's base name is "..".
288 BASE_EXPORT
bool IsDotDot(const base::FilePath
& path
);
290 // Sets |real_path| to |path| with symbolic links and junctions expanded.
291 // On windows, make sure the path starts with a lettered drive.
292 // |path| must reference a file. Function will fail if |path| points to
293 // a directory or to a nonexistent path. On windows, this function will
294 // fail if |path| is a junction or symlink that points to an empty file,
295 // or if |real_path| would be longer than MAX_PATH characters.
296 BASE_EXPORT
bool NormalizeFilePath(const base::FilePath
& path
,
297 base::FilePath
* real_path
);
301 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
302 // return in |drive_letter_path| the equivalent path that starts with
303 // a drive letter ("C:\..."). Return false if no such path exists.
304 BASE_EXPORT
bool DevicePathToDriveLetterPath(const base::FilePath
& device_path
,
305 base::FilePath
* drive_letter_path
);
307 // Given an existing file in |path|, set |real_path| to the path
308 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
309 // Returns false if the path can not be found. Empty files cannot
310 // be resolved with this function.
311 BASE_EXPORT
bool NormalizeToNativeFilePath(const base::FilePath
& path
,
312 base::FilePath
* nt_path
);
315 // This function will return if the given file is a symlink or not.
316 BASE_EXPORT
bool IsLink(const base::FilePath
& file_path
);
318 // Returns information about the given file path.
319 BASE_EXPORT
bool GetFileInfo(const base::FilePath
& file_path
,
320 base::PlatformFileInfo
* info
);
322 // Sets the time of the last access and the time of the last modification.
323 BASE_EXPORT
bool TouchFile(const base::FilePath
& path
,
324 const base::Time
& last_accessed
,
325 const base::Time
& last_modified
);
327 // Set the time of the last modification. Useful for unit tests.
328 BASE_EXPORT
bool SetLastModifiedTime(const base::FilePath
& path
,
329 const base::Time
& last_modified
);
331 #if defined(OS_POSIX)
332 // Store inode number of |path| in |inode|. Return true on success.
333 BASE_EXPORT
bool GetInode(const base::FilePath
& path
, ino_t
* inode
);
336 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
337 BASE_EXPORT
FILE* OpenFile(const base::FilePath
& filename
, const char* mode
);
339 // Closes file opened by OpenFile. Returns true on success.
340 BASE_EXPORT
bool CloseFile(FILE* file
);
342 // Truncates an open file to end at the location of the current file pointer.
343 // This is a cross-platform analog to Windows' SetEndOfFile() function.
344 BASE_EXPORT
bool TruncateFile(FILE* file
);
346 // Reads the given number of bytes from the file into the buffer. Returns
347 // the number of read bytes, or -1 on error.
348 BASE_EXPORT
int ReadFile(const base::FilePath
& filename
, char* data
, int size
);
350 // Writes the given buffer into the file, overwriting any data that was
351 // previously there. Returns the number of bytes written, or -1 on error.
352 BASE_EXPORT
int WriteFile(const base::FilePath
& filename
, const char* data
,
354 #if defined(OS_POSIX)
355 // Append the data to |fd|. Does not close |fd| when done.
356 BASE_EXPORT
int WriteFileDescriptor(const int fd
, const char* data
, int size
);
358 // Append the given buffer into the file. Returns the number of bytes written,
360 BASE_EXPORT
int AppendToFile(const base::FilePath
& filename
,
361 const char* data
, int size
);
363 // Gets the current working directory for the process.
364 BASE_EXPORT
bool GetCurrentDirectory(base::FilePath
* path
);
366 // Sets the current working directory for the process.
367 BASE_EXPORT
bool SetCurrentDirectory(const base::FilePath
& path
);
369 // Attempts to find a number that can be appended to the |path| to make it
370 // unique. If |path| does not exist, 0 is returned. If it fails to find such
371 // a number, -1 is returned. If |suffix| is not empty, also checks the
372 // existence of it with the given suffix.
373 BASE_EXPORT
int GetUniquePathNumber(const base::FilePath
& path
,
374 const base::FilePath::StringType
& suffix
);
376 #if defined(OS_POSIX)
377 // Creates a directory with a guaranteed unique name based on |path|, returning
378 // the pathname if successful, or an empty path if there was an error creating
379 // the directory. Does not create parent directories.
380 BASE_EXPORT
base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
);
383 #if defined(OS_POSIX)
384 // Test that |path| can only be changed by a given user and members of
385 // a given set of groups.
386 // Specifically, test that all parts of |path| under (and including) |base|:
388 // * Are owned by a specific user.
389 // * Are not writable by all users.
390 // * Are owned by a memeber of a given set of groups, or are not writable by
392 // * Are not symbolic links.
393 // This is useful for checking that a config file is administrator-controlled.
394 // |base| must contain |path|.
395 BASE_EXPORT
bool VerifyPathControlledByUser(const base::FilePath
& base
,
396 const base::FilePath
& path
,
398 const std::set
<gid_t
>& group_gids
);
399 #endif // defined(OS_POSIX)
401 #if defined(OS_MACOSX) && !defined(OS_IOS)
402 // Is |path| writable only by a user with administrator privileges?
403 // This function uses Mac OS conventions. The super user is assumed to have
404 // uid 0, and the administrator group is assumed to be named "admin".
405 // Testing that |path|, and every parent directory including the root of
406 // the filesystem, are owned by the superuser, controlled by the group
407 // "admin", are not writable by all users, and contain no symbolic links.
408 // Will return false if |path| does not exist.
409 BASE_EXPORT
bool VerifyPathControlledByAdmin(const base::FilePath
& path
);
410 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
412 // Returns the maximum length of path component on the volume containing
413 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
414 BASE_EXPORT
int GetMaximumPathComponentLength(const base::FilePath
& path
);
416 // A class to handle auto-closing of FILE*'s.
417 class ScopedFILEClose
{
419 inline void operator()(FILE* x
) const {
426 typedef scoped_ptr_malloc
<FILE, ScopedFILEClose
> ScopedFILE
;
428 #if defined(OS_POSIX)
429 // A class to handle auto-closing of FDs.
430 class ScopedFDClose
{
432 inline void operator()(int* x
) const {
434 if (HANDLE_EINTR(close(*x
)) < 0)
435 DPLOG(ERROR
) << "close";
440 typedef scoped_ptr_malloc
<int, ScopedFDClose
> ScopedFD
;
443 // A class for enumerating the files in a provided path. The order of the
444 // results is not guaranteed.
446 // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
447 // program where latency does not matter. This class is blocking.
448 class BASE_EXPORT FileEnumerator
{
451 typedef WIN32_FIND_DATA FindInfo
;
452 #elif defined(OS_POSIX)
455 std::string filename
;
461 DIRECTORIES
= 1 << 1,
462 INCLUDE_DOT_DOT
= 1 << 2,
463 #if defined(OS_POSIX)
464 SHOW_SYM_LINKS
= 1 << 4,
468 // |root_path| is the starting directory to search for. It may or may not end
471 // If |recursive| is true, this will enumerate all matches in any
472 // subdirectories matched as well. It does a breadth-first search, so all
473 // files in one directory will be returned before any files in a
476 // |file_type|, a bit mask of FileType, specifies whether the enumerator
477 // should match files, directories, or both.
479 // |pattern| is an optional pattern for which files to match. This
480 // works like shell globbing. For example, "*.txt" or "Foo???.doc".
481 // However, be careful in specifying patterns that aren't cross platform
482 // since the underlying code uses OS-specific matching routines. In general,
483 // Windows matching is less featureful than others, so test there first.
484 // If unspecified, this will match all files.
485 // NOTE: the pattern only matches the contents of root_path, not files in
486 // recursive subdirectories.
487 // TODO(erikkay): Fix the pattern matching to work at all levels.
488 FileEnumerator(const base::FilePath
& root_path
,
491 FileEnumerator(const base::FilePath
& root_path
,
494 const base::FilePath::StringType
& pattern
);
497 // Returns an empty string if there are no more results.
498 base::FilePath
Next();
500 // Write the file info into |info|.
501 void GetFindInfo(FindInfo
* info
);
503 // Looks inside a FindInfo and determines if it's a directory.
504 static bool IsDirectory(const FindInfo
& info
);
506 static base::FilePath
GetFilename(const FindInfo
& find_info
);
507 static int64
GetFilesize(const FindInfo
& find_info
);
508 static base::Time
GetLastModifiedTime(const FindInfo
& find_info
);
511 // Returns true if the given path should be skipped in enumeration.
512 bool ShouldSkip(const base::FilePath
& path
);
516 // True when find_data_ is valid.
518 WIN32_FIND_DATA find_data_
;
520 #elif defined(OS_POSIX)
521 struct DirectoryEntryInfo
{
522 base::FilePath filename
;
526 // Read the filenames in source into the vector of DirectoryEntryInfo's
527 static bool ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
528 const base::FilePath
& source
, bool show_links
);
530 // The files in the current directory
531 std::vector
<DirectoryEntryInfo
> directory_entries_
;
533 // The next entry to use from the directory_entries_ vector
534 size_t current_directory_entry_
;
537 base::FilePath root_path_
;
540 base::FilePath::StringType pattern_
; // Empty when we want to find
543 // A stack that keeps track of which subdirectories we still need to
544 // enumerate in the breadth-first search.
545 std::stack
<base::FilePath
> pending_paths_
;
547 DISALLOW_COPY_AND_ASSIGN(FileEnumerator
);
550 #if defined(OS_LINUX)
551 // Broad categories of file systems as returned by statfs() on Linux.
552 enum FileSystemType
{
553 FILE_SYSTEM_UNKNOWN
, // statfs failed.
554 FILE_SYSTEM_0
, // statfs.f_type == 0 means unknown, may indicate AFS.
555 FILE_SYSTEM_ORDINARY
, // on-disk filesystem like ext2
559 FILE_SYSTEM_MEMORY
, // in-memory file system
560 FILE_SYSTEM_CGROUP
, // cgroup control.
561 FILE_SYSTEM_OTHER
, // any other value.
562 FILE_SYSTEM_TYPE_COUNT
565 // Attempts determine the FileSystemType for |path|.
566 // Returns false if |path| doesn't exist.
567 BASE_EXPORT
bool GetFileSystemType(const base::FilePath
& path
,
568 FileSystemType
* type
);
571 } // namespace file_util
573 #endif // BASE_FILE_UTIL_H_