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)
26 #include "base/base_export.h"
27 #include "base/basictypes.h"
28 #include "base/files/file.h"
29 #include "base/files/file_path.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/strings/string16.h"
34 #include "base/file_descriptor_posix.h"
35 #include "base/logging.h"
36 #include "base/posix/eintr_wrapper.h"
43 //-----------------------------------------------------------------------------
44 // Functions that involve filesystem access or modification:
46 // Returns an absolute version of a relative path. Returns an empty path on
47 // error. On POSIX, this function fails if the path does not exist. This
48 // function can result in I/O so it can be slow.
49 BASE_EXPORT FilePath
MakeAbsoluteFilePath(const FilePath
& input
);
51 // Returns the total number of bytes used by all the files under |root_path|.
52 // If the path does not exist the function returns 0.
54 // This function is implemented using the FileEnumerator class so it is not
55 // particularly speedy in any platform.
56 BASE_EXPORT int64
ComputeDirectorySize(const FilePath
& root_path
);
58 // Deletes the given path, whether it's a file or a directory.
59 // If it's a directory, it's perfectly happy to delete all of the
60 // directory's contents. Passing true to recursive deletes
61 // subdirectories and their contents as well.
62 // Returns true if successful, false otherwise. It is considered successful
63 // to attempt to delete a file that does not exist.
65 // In posix environment and if |path| is a symbolic link, this deletes only
66 // the symlink. (even if the symlink points to a non-existent file)
68 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
69 // TO "rm -rf", SO USE WITH CAUTION.
70 BASE_EXPORT
bool DeleteFile(const FilePath
& path
, bool recursive
);
73 // Schedules to delete the given path, whether it's a file or a directory, until
74 // the operating system is restarted.
76 // 1) The file/directory to be deleted should exist in a temp folder.
77 // 2) The directory to be deleted must be empty.
78 BASE_EXPORT
bool DeleteFileAfterReboot(const FilePath
& path
);
81 // Moves the given path, whether it's a file or a directory.
82 // If a simple rename is not possible, such as in the case where the paths are
83 // on different volumes, this will attempt to copy and delete. Returns
85 // This function fails if either path contains traversal components ('..').
86 BASE_EXPORT
bool Move(const FilePath
& from_path
, const FilePath
& to_path
);
88 // Renames file |from_path| to |to_path|. Both paths must be on the same
89 // volume, or the function will fail. Destination file will be created
90 // if it doesn't exist. Prefer this function over Move when dealing with
91 // temporary files. On Windows it preserves attributes of the target file.
92 // Returns true on success, leaving *error unchanged.
93 // Returns false on failure and sets *error appropriately, if it is non-NULL.
94 BASE_EXPORT
bool ReplaceFile(const FilePath
& from_path
,
95 const FilePath
& to_path
,
98 // Copies a single file. Use CopyDirectory to copy directories.
99 // This function fails if either path contains traversal components ('..').
101 // This function keeps the metadata on Windows. The read only bit on Windows is
103 BASE_EXPORT
bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
);
105 // Copies the given path, and optionally all subdirectories and their contents
108 // If there are files existing under to_path, always overwrite. Returns true
109 // if successful, false otherwise. Wildcards on the names are not supported.
111 // This function calls into CopyFile() so the same behavior w.r.t. metadata
114 // If you only need to copy a file use CopyFile, it's faster.
115 BASE_EXPORT
bool CopyDirectory(const FilePath
& from_path
,
116 const FilePath
& to_path
,
119 // Returns true if the given path exists on the local filesystem,
121 BASE_EXPORT
bool PathExists(const FilePath
& path
);
123 // Returns true if the given path is writable by the user, false otherwise.
124 BASE_EXPORT
bool PathIsWritable(const FilePath
& path
);
126 // Returns true if the given path exists and is a directory, false otherwise.
127 BASE_EXPORT
bool DirectoryExists(const FilePath
& path
);
129 // Returns true if the contents of the two files given are equal, false
130 // otherwise. If either file can't be read, returns false.
131 BASE_EXPORT
bool ContentsEqual(const FilePath
& filename1
,
132 const FilePath
& filename2
);
134 // Returns true if the contents of the two text files given are equal, false
135 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
136 BASE_EXPORT
bool TextContentsEqual(const FilePath
& filename1
,
137 const FilePath
& filename2
);
139 // Reads the file at |path| into |contents| and returns true on success and
140 // false on error. For security reasons, a |path| containing path traversal
141 // components ('..') is treated as a read error and |contents| is set to empty.
142 // In case of I/O error, |contents| holds the data that could be read from the
143 // file before the error occurred.
144 // |contents| may be NULL, in which case this function is useful for its side
145 // effect of priming the disk cache (could be used for unit tests).
146 BASE_EXPORT
bool ReadFileToString(const FilePath
& path
, std::string
* contents
);
148 // Reads the file at |path| into |contents| and returns true on success and
149 // false on error. For security reasons, a |path| containing path traversal
150 // components ('..') is treated as a read error and |contents| is set to empty.
151 // In case of I/O error, |contents| holds the data that could be read from the
152 // file before the error occurred. When the file size exceeds |max_size|, the
153 // function returns false with |contents| holding the file truncated to
155 // |contents| may be NULL, in which case this function is useful for its side
156 // effect of priming the disk cache (could be used for unit tests).
157 BASE_EXPORT
bool ReadFileToString(const FilePath
& path
,
158 std::string
* contents
,
161 #if defined(OS_POSIX)
163 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
164 // in |buffer|. This function is protected against EINTR and partial reads.
165 // Returns true iff |bytes| bytes have been successfully read from |fd|.
166 BASE_EXPORT
bool ReadFromFD(int fd
, char* buffer
, size_t bytes
);
168 // Creates a symbolic link at |symlink| pointing to |target|. Returns
170 BASE_EXPORT
bool CreateSymbolicLink(const FilePath
& target
,
171 const FilePath
& symlink
);
173 // Reads the given |symlink| and returns where it points to in |target|.
174 // Returns false upon failure.
175 BASE_EXPORT
bool ReadSymbolicLink(const FilePath
& symlink
, FilePath
* target
);
177 // Bits and masks of the file permission.
178 enum FilePermissionBits
{
179 FILE_PERMISSION_MASK
= S_IRWXU
| S_IRWXG
| S_IRWXO
,
180 FILE_PERMISSION_USER_MASK
= S_IRWXU
,
181 FILE_PERMISSION_GROUP_MASK
= S_IRWXG
,
182 FILE_PERMISSION_OTHERS_MASK
= S_IRWXO
,
184 FILE_PERMISSION_READ_BY_USER
= S_IRUSR
,
185 FILE_PERMISSION_WRITE_BY_USER
= S_IWUSR
,
186 FILE_PERMISSION_EXECUTE_BY_USER
= S_IXUSR
,
187 FILE_PERMISSION_READ_BY_GROUP
= S_IRGRP
,
188 FILE_PERMISSION_WRITE_BY_GROUP
= S_IWGRP
,
189 FILE_PERMISSION_EXECUTE_BY_GROUP
= S_IXGRP
,
190 FILE_PERMISSION_READ_BY_OTHERS
= S_IROTH
,
191 FILE_PERMISSION_WRITE_BY_OTHERS
= S_IWOTH
,
192 FILE_PERMISSION_EXECUTE_BY_OTHERS
= S_IXOTH
,
195 // Reads the permission of the given |path|, storing the file permission
196 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
197 // a file which the symlink points to.
198 BASE_EXPORT
bool GetPosixFilePermissions(const FilePath
& path
, int* mode
);
199 // Sets the permission of the given |path|. If |path| is symbolic link, sets
200 // the permission of a file which the symlink points to.
201 BASE_EXPORT
bool SetPosixFilePermissions(const FilePath
& path
, int mode
);
205 // Returns true if the given directory is empty
206 BASE_EXPORT
bool IsDirectoryEmpty(const FilePath
& dir_path
);
208 // Get the temporary directory provided by the system.
210 // WARNING: In general, you should use CreateTemporaryFile variants below
211 // instead of this function. Those variants will ensure that the proper
212 // permissions are set so that other users on the system can't edit them while
213 // they're open (which can lead to security issues).
214 BASE_EXPORT
bool GetTempDir(FilePath
* path
);
216 // Get the home directory. This is more complicated than just getenv("HOME")
217 // as it knows to fall back on getpwent() etc.
219 // You should not generally call this directly. Instead use DIR_HOME with the
220 // path service which will use this function but cache the value.
221 BASE_EXPORT FilePath
GetHomeDir();
223 // Creates a temporary file. The full path is placed in |path|, and the
224 // function returns true if was successful in creating the file. The file will
225 // be empty and all handles closed after this function returns.
226 BASE_EXPORT
bool CreateTemporaryFile(FilePath
* path
);
228 // Same as CreateTemporaryFile but the file is created in |dir|.
229 BASE_EXPORT
bool CreateTemporaryFileInDir(const FilePath
& dir
,
230 FilePath
* temp_file
);
232 // Create and open a temporary file. File is opened for read/write.
233 // The full path is placed in |path|.
234 // Returns a handle to the opened file or NULL if an error occurred.
235 BASE_EXPORT
FILE* CreateAndOpenTemporaryFile(FilePath
* path
);
237 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
238 BASE_EXPORT
FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
,
241 // Create a new directory. If prefix is provided, the new directory name is in
242 // the format of prefixyyyy.
243 // NOTE: prefix is ignored in the POSIX implementation.
244 // If success, return true and output the full path of the directory created.
245 BASE_EXPORT
bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
246 FilePath
* new_temp_path
);
248 // Create a directory within another directory.
249 // Extra characters will be appended to |prefix| to ensure that the
250 // new directory does not have the same name as an existing directory.
251 BASE_EXPORT
bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
252 const FilePath::StringType
& prefix
,
255 // Creates a directory, as well as creating any parent directories, if they
256 // don't exist. Returns 'true' on successful creation, or if the directory
257 // already exists. The directory is only readable by the current user.
258 // Returns true on success, leaving *error unchanged.
259 // Returns false on failure and sets *error appropriately, if it is non-NULL.
260 BASE_EXPORT
bool CreateDirectoryAndGetError(const FilePath
& full_path
,
263 // Backward-compatible convenience method for the above.
264 BASE_EXPORT
bool CreateDirectory(const FilePath
& full_path
);
266 // Returns the file size. Returns true on success.
267 BASE_EXPORT
bool GetFileSize(const FilePath
& file_path
, int64
* file_size
);
269 // Sets |real_path| to |path| with symbolic links and junctions expanded.
270 // On windows, make sure the path starts with a lettered drive.
271 // |path| must reference a file. Function will fail if |path| points to
272 // a directory or to a nonexistent path. On windows, this function will
273 // fail if |path| is a junction or symlink that points to an empty file,
274 // or if |real_path| would be longer than MAX_PATH characters.
275 BASE_EXPORT
bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
);
279 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
280 // return in |drive_letter_path| the equivalent path that starts with
281 // a drive letter ("C:\..."). Return false if no such path exists.
282 BASE_EXPORT
bool DevicePathToDriveLetterPath(const FilePath
& device_path
,
283 FilePath
* drive_letter_path
);
285 // Given an existing file in |path|, set |real_path| to the path
286 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
287 // Returns false if the path can not be found. Empty files cannot
288 // be resolved with this function.
289 BASE_EXPORT
bool NormalizeToNativeFilePath(const FilePath
& path
,
293 // This function will return if the given file is a symlink or not.
294 BASE_EXPORT
bool IsLink(const FilePath
& file_path
);
296 // Returns information about the given file path.
297 BASE_EXPORT
bool GetFileInfo(const FilePath
& file_path
, File::Info
* info
);
299 // Sets the time of the last access and the time of the last modification.
300 BASE_EXPORT
bool TouchFile(const FilePath
& path
,
301 const Time
& last_accessed
,
302 const Time
& last_modified
);
304 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
305 BASE_EXPORT
FILE* OpenFile(const FilePath
& filename
, const char* mode
);
307 // Closes file opened by OpenFile. Returns true on success.
308 BASE_EXPORT
bool CloseFile(FILE* file
);
310 // Truncates an open file to end at the location of the current file pointer.
311 // This is a cross-platform analog to Windows' SetEndOfFile() function.
312 BASE_EXPORT
bool TruncateFile(FILE* file
);
314 // Reads at most the given number of bytes from the file into the buffer.
315 // Returns the number of read bytes, or -1 on error.
316 BASE_EXPORT
int ReadFile(const FilePath
& filename
, char* data
, int max_size
);
318 // Writes the given buffer into the file, overwriting any data that was
319 // previously there. Returns the number of bytes written, or -1 on error.
320 BASE_EXPORT
int WriteFile(const FilePath
& filename
, const char* data
,
323 #if defined(OS_POSIX)
324 // Append the data to |fd|. Does not close |fd| when done.
325 BASE_EXPORT
int WriteFileDescriptor(const int fd
, const char* data
, int size
);
328 // Append the given buffer into the file. Returns the number of bytes written,
330 BASE_EXPORT
int AppendToFile(const FilePath
& filename
,
331 const char* data
, int size
);
333 // Gets the current working directory for the process.
334 BASE_EXPORT
bool GetCurrentDirectory(FilePath
* path
);
336 // Sets the current working directory for the process.
337 BASE_EXPORT
bool SetCurrentDirectory(const FilePath
& path
);
339 // Attempts to find a number that can be appended to the |path| to make it
340 // unique. If |path| does not exist, 0 is returned. If it fails to find such
341 // a number, -1 is returned. If |suffix| is not empty, also checks the
342 // existence of it with the given suffix.
343 BASE_EXPORT
int GetUniquePathNumber(const FilePath
& path
,
344 const FilePath::StringType
& suffix
);
346 #if defined(OS_POSIX)
347 // Test that |path| can only be changed by a given user and members of
348 // a given set of groups.
349 // Specifically, test that all parts of |path| under (and including) |base|:
351 // * Are owned by a specific user.
352 // * Are not writable by all users.
353 // * Are owned by a member of a given set of groups, or are not writable by
355 // * Are not symbolic links.
356 // This is useful for checking that a config file is administrator-controlled.
357 // |base| must contain |path|.
358 BASE_EXPORT
bool VerifyPathControlledByUser(const base::FilePath
& base
,
359 const base::FilePath
& path
,
361 const std::set
<gid_t
>& group_gids
);
362 #endif // defined(OS_POSIX)
364 #if defined(OS_MACOSX) && !defined(OS_IOS)
365 // Is |path| writable only by a user with administrator privileges?
366 // This function uses Mac OS conventions. The super user is assumed to have
367 // uid 0, and the administrator group is assumed to be named "admin".
368 // Testing that |path|, and every parent directory including the root of
369 // the filesystem, are owned by the superuser, controlled by the group
370 // "admin", are not writable by all users, and contain no symbolic links.
371 // Will return false if |path| does not exist.
372 BASE_EXPORT
bool VerifyPathControlledByAdmin(const base::FilePath
& path
);
373 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
375 // Returns the maximum length of path component on the volume containing
376 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
377 BASE_EXPORT
int GetMaximumPathComponentLength(const base::FilePath
& path
);
379 #if defined(OS_LINUX)
380 // Broad categories of file systems as returned by statfs() on Linux.
381 enum FileSystemType
{
382 FILE_SYSTEM_UNKNOWN
, // statfs failed.
383 FILE_SYSTEM_0
, // statfs.f_type == 0 means unknown, may indicate AFS.
384 FILE_SYSTEM_ORDINARY
, // on-disk filesystem like ext2
388 FILE_SYSTEM_MEMORY
, // in-memory file system
389 FILE_SYSTEM_CGROUP
, // cgroup control.
390 FILE_SYSTEM_OTHER
, // any other value.
391 FILE_SYSTEM_TYPE_COUNT
394 // Attempts determine the FileSystemType for |path|.
395 // Returns false if |path| doesn't exist.
396 BASE_EXPORT
bool GetFileSystemType(const FilePath
& path
, FileSystemType
* type
);
399 #if defined(OS_POSIX)
400 // Get a temporary directory for shared memory files. The directory may depend
401 // on whether the destination is intended for executable files, which in turn
402 // depends on how /dev/shmem was mounted. As a result, you must supply whether
403 // you intend to create executable shmem segments so this function can find
404 // an appropriate location.
405 BASE_EXPORT
bool GetShmemTempDir(bool executable
, FilePath
* path
);
410 // -----------------------------------------------------------------------------
412 namespace file_util
{
414 // Functor for |ScopedFILE| (below).
415 struct ScopedFILEClose
{
416 inline void operator()(FILE* x
) const {
422 // Automatically closes |FILE*|s.
423 typedef scoped_ptr
<FILE, ScopedFILEClose
> ScopedFILE
;
425 } // namespace file_util
427 // Internal --------------------------------------------------------------------
432 // Same as Move but allows paths with traversal components.
433 // Use only with extreme care.
434 BASE_EXPORT
bool MoveUnsafe(const FilePath
& from_path
,
435 const FilePath
& to_path
);
437 // Same as CopyFile but allows paths with traversal components.
438 // Use only with extreme care.
439 BASE_EXPORT
bool CopyFileUnsafe(const FilePath
& from_path
,
440 const FilePath
& to_path
);
443 // Copy from_path to to_path recursively and then delete from_path recursively.
444 // Returns true if all operations succeed.
445 // This function simulates Move(), but unlike Move() it works across volumes.
446 // This function is not transactional.
447 BASE_EXPORT
bool CopyAndDeleteDirectory(const FilePath
& from_path
,
448 const FilePath
& to_path
);
449 #endif // defined(OS_WIN)
451 } // namespace internal
454 #endif // BASE_FILE_UTIL_H_