Exclude one flaky test from Valgrind runs
[chromium-blink-merge.git] / base / file_util.h
blobbd339980494e924d524f7a65619c70d3681ecbe9
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
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 #elif defined(OS_POSIX)
16 #include <sys/stat.h>
17 #include <unistd.h>
18 #endif
20 #include <stdio.h>
22 #include <set>
23 #include <string>
24 #include <vector>
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"
33 #if defined(OS_POSIX)
34 #include "base/file_descriptor_posix.h"
35 #include "base/logging.h"
36 #include "base/posix/eintr_wrapper.h"
37 #endif
39 namespace base {
41 class Time;
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);
72 #if defined(OS_WIN)
73 // Schedules to delete the given path, whether it's a file or a directory, until
74 // the operating system is restarted.
75 // Note:
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);
79 #endif
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
84 // true for success.
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,
96 File::Error* error);
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
102 // not kept.
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
106 // as well.
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
112 // applies.
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,
117 bool recursive);
119 // Returns true if the given path exists on the local filesystem,
120 // false otherwise.
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.
140 // |contents| may be NULL, in which case this function is useful for its
141 // side effect of priming the disk cache (could be used for unit tests).
142 // The function returns false and the string pointed to by |contents| is
143 // cleared when |path| does not exist or if it contains path traversal
144 // components ('..').
145 BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
147 // Reads the file at |path| into |contents| and returns true on success.
148 // |contents| may be NULL, in which case this function is useful for its
149 // side effect of priming the disk cache (could be used for unit tests).
150 // The function returns false and the string pointed to by |contents| is
151 // cleared when |path| does not exist or if it contains path traversal
152 // components ('..').
153 // When the file size exceeds |max_size|, the function returns false
154 // with |contents| holding the file truncated to |max_size|.
155 BASE_EXPORT bool ReadFileToString(const FilePath& path,
156 std::string* contents,
157 size_t max_size);
159 #if defined(OS_POSIX)
161 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
162 // in |buffer|. This function is protected against EINTR and partial reads.
163 // Returns true iff |bytes| bytes have been successfully read from |fd|.
164 BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
166 // Creates a symbolic link at |symlink| pointing to |target|. Returns
167 // false on failure.
168 BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
169 const FilePath& symlink);
171 // Reads the given |symlink| and returns where it points to in |target|.
172 // Returns false upon failure.
173 BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
175 // Bits ans masks of the file permission.
176 enum FilePermissionBits {
177 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
178 FILE_PERMISSION_USER_MASK = S_IRWXU,
179 FILE_PERMISSION_GROUP_MASK = S_IRWXG,
180 FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
182 FILE_PERMISSION_READ_BY_USER = S_IRUSR,
183 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
184 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
185 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
186 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
187 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
188 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
189 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
190 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
193 // Reads the permission of the given |path|, storing the file permission
194 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
195 // a file which the symlink points to.
196 BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
197 // Sets the permission of the given |path|. If |path| is symbolic link, sets
198 // the permission of a file which the symlink points to.
199 BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
201 #endif // OS_POSIX
203 // Returns true if the given directory is empty
204 BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
206 // Get the temporary directory provided by the system.
208 // WARNING: In general, you should use CreateTemporaryFile variants below
209 // instead of this function. Those variants will ensure that the proper
210 // permissions are set so that other users on the system can't edit them while
211 // they're open (which can lead to security issues).
212 BASE_EXPORT bool GetTempDir(FilePath* path);
214 // Get a temporary directory for shared memory files. The directory may depend
215 // on whether the destination is intended for executable files, which in turn
216 // depends on how /dev/shmem was mounted. As a result, you must supply whether
217 // you intend to create executable shmem segments so this function can find
218 // an appropriate location.
220 // Only useful on POSIX; redirects to GetTempDir() on Windows.
221 BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
223 // Get the home directory. This is more complicated than just getenv("HOME")
224 // as it knows to fall back on getpwent() etc.
226 // You should not generally call this directly. Instead use DIR_HOME with the
227 // path service which will use this function but cache the value.
228 BASE_EXPORT FilePath GetHomeDir();
230 // Creates a temporary file. The full path is placed in |path|, and the
231 // function returns true if was successful in creating the file. The file will
232 // be empty and all handles closed after this function returns.
233 BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
235 // Same as CreateTemporaryFile but the file is created in |dir|.
236 BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
237 FilePath* temp_file);
239 // Create and open a temporary file. File is opened for read/write.
240 // The full path is placed in |path|.
241 // Returns a handle to the opened file or NULL if an error occurred.
242 BASE_EXPORT FILE* CreateAndOpenTemporaryFile(FilePath* path);
244 // Like above but for shmem files. Only useful for POSIX.
245 // The executable flag says the file needs to support using
246 // mprotect with PROT_EXEC after mapping.
247 BASE_EXPORT FILE* CreateAndOpenTemporaryShmemFile(FilePath* path,
248 bool executable);
250 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
251 BASE_EXPORT FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir,
252 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(const FilePath::StringType& prefix,
259 FilePath* new_temp_path);
261 // Create a directory within another directory.
262 // Extra characters will be appended to |prefix| to ensure that the
263 // new directory does not have the same name as an existing directory.
264 BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
265 const FilePath::StringType& prefix,
266 FilePath* new_dir);
268 // Creates a directory, as well as creating any parent directories, if they
269 // don't exist. Returns 'true' on successful creation, or if the directory
270 // already exists. The directory is only readable by the current user.
271 // Returns true on success, leaving *error unchanged.
272 // Returns false on failure and sets *error appropriately, if it is non-NULL.
273 BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
274 File::Error* error);
276 // Backward-compatible convenience method for the above.
277 BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
279 // Returns the file size. Returns true on success.
280 BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64* file_size);
282 // Sets |real_path| to |path| with symbolic links and junctions expanded.
283 // On windows, make sure the path starts with a lettered drive.
284 // |path| must reference a file. Function will fail if |path| points to
285 // a directory or to a nonexistent path. On windows, this function will
286 // fail if |path| is a junction or symlink that points to an empty file,
287 // or if |real_path| would be longer than MAX_PATH characters.
288 BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
290 #if defined(OS_WIN)
292 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
293 // return in |drive_letter_path| the equivalent path that starts with
294 // a drive letter ("C:\..."). Return false if no such path exists.
295 BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
296 FilePath* drive_letter_path);
298 // Given an existing file in |path|, set |real_path| to the path
299 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
300 // Returns false if the path can not be found. Empty files cannot
301 // be resolved with this function.
302 BASE_EXPORT bool NormalizeToNativeFilePath(const FilePath& path,
303 FilePath* nt_path);
304 #endif
306 // This function will return if the given file is a symlink or not.
307 BASE_EXPORT bool IsLink(const FilePath& file_path);
309 // Returns information about the given file path.
310 BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
312 // Sets the time of the last access and the time of the last modification.
313 BASE_EXPORT bool TouchFile(const FilePath& path,
314 const Time& last_accessed,
315 const Time& last_modified);
317 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
318 BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
320 // Closes file opened by OpenFile. Returns true on success.
321 BASE_EXPORT bool CloseFile(FILE* file);
323 // Truncates an open file to end at the location of the current file pointer.
324 // This is a cross-platform analog to Windows' SetEndOfFile() function.
325 BASE_EXPORT bool TruncateFile(FILE* file);
327 // Reads the given number of bytes from the file into the buffer. Returns
328 // the number of read bytes, or -1 on error.
329 BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int size);
331 } // namespace base
333 // -----------------------------------------------------------------------------
335 namespace file_util {
337 // Writes the given buffer into the file, overwriting any data that was
338 // previously there. Returns the number of bytes written, or -1 on error.
339 BASE_EXPORT int WriteFile(const base::FilePath& filename, const char* data,
340 int size);
341 #if defined(OS_POSIX)
342 // Append the data to |fd|. Does not close |fd| when done.
343 BASE_EXPORT int WriteFileDescriptor(const int fd, const char* data, int size);
344 #endif
345 // Append the given buffer into the file. Returns the number of bytes written,
346 // or -1 on error.
347 BASE_EXPORT int AppendToFile(const base::FilePath& filename,
348 const char* data, int size);
350 // Gets the current working directory for the process.
351 BASE_EXPORT bool GetCurrentDirectory(base::FilePath* path);
353 // Sets the current working directory for the process.
354 BASE_EXPORT bool SetCurrentDirectory(const base::FilePath& path);
356 // Attempts to find a number that can be appended to the |path| to make it
357 // unique. If |path| does not exist, 0 is returned. If it fails to find such
358 // a number, -1 is returned. If |suffix| is not empty, also checks the
359 // existence of it with the given suffix.
360 BASE_EXPORT int GetUniquePathNumber(const base::FilePath& path,
361 const base::FilePath::StringType& suffix);
363 #if defined(OS_POSIX)
364 // Creates a directory with a guaranteed unique name based on |path|, returning
365 // the pathname if successful, or an empty path if there was an error creating
366 // the directory. Does not create parent directories.
367 BASE_EXPORT base::FilePath MakeUniqueDirectory(const base::FilePath& path);
368 #endif
370 #if defined(OS_POSIX)
371 // Test that |path| can only be changed by a given user and members of
372 // a given set of groups.
373 // Specifically, test that all parts of |path| under (and including) |base|:
374 // * Exist.
375 // * Are owned by a specific user.
376 // * Are not writable by all users.
377 // * Are owned by a member of a given set of groups, or are not writable by
378 // their group.
379 // * Are not symbolic links.
380 // This is useful for checking that a config file is administrator-controlled.
381 // |base| must contain |path|.
382 BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
383 const base::FilePath& path,
384 uid_t owner_uid,
385 const std::set<gid_t>& group_gids);
386 #endif // defined(OS_POSIX)
388 #if defined(OS_MACOSX) && !defined(OS_IOS)
389 // Is |path| writable only by a user with administrator privileges?
390 // This function uses Mac OS conventions. The super user is assumed to have
391 // uid 0, and the administrator group is assumed to be named "admin".
392 // Testing that |path|, and every parent directory including the root of
393 // the filesystem, are owned by the superuser, controlled by the group
394 // "admin", are not writable by all users, and contain no symbolic links.
395 // Will return false if |path| does not exist.
396 BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
397 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
399 // Returns the maximum length of path component on the volume containing
400 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
401 BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
403 // Functor for |ScopedFILE| (below).
404 struct ScopedFILEClose {
405 inline void operator()(FILE* x) const {
406 if (x)
407 fclose(x);
411 // Automatically closes |FILE*|s.
412 typedef scoped_ptr<FILE, ScopedFILEClose> ScopedFILE;
414 #if defined(OS_POSIX)
415 // Functor for |ScopedFD| (below).
416 struct ScopedFDClose {
417 inline void operator()(int* x) const {
418 if (x && *x >= 0) {
419 // It's important to crash here.
420 // There are security implications to not closing a file descriptor
421 // properly. As file descriptors are "capabilities", keeping them open
422 // would make the current process keep access to a resource. Much of
423 // Chrome relies on being able to "drop" such access.
424 // It's especially problematic on Linux with the setuid sandbox, where
425 // a single open directory would bypass the entire security model.
426 PCHECK(0 == IGNORE_EINTR(close(*x)));
431 // Automatically closes FDs (note: doesn't store the FD).
432 // TODO(viettrungluu): This is a very odd API, since (unlike |FILE*|s, you'll
433 // need to store the FD separately and keep its memory alive). This should
434 // probably be called |ScopedFDCloser| or something like that.
435 typedef scoped_ptr<int, ScopedFDClose> ScopedFD;
436 // Let new users use ScopedFDCloser already, while ScopedFD is replaced.
437 typedef ScopedFD ScopedFDCloser;
438 #endif // OS_POSIX
440 #if defined(OS_LINUX)
441 // Broad categories of file systems as returned by statfs() on Linux.
442 enum FileSystemType {
443 FILE_SYSTEM_UNKNOWN, // statfs failed.
444 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
445 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
446 FILE_SYSTEM_NFS,
447 FILE_SYSTEM_SMB,
448 FILE_SYSTEM_CODA,
449 FILE_SYSTEM_MEMORY, // in-memory file system
450 FILE_SYSTEM_CGROUP, // cgroup control.
451 FILE_SYSTEM_OTHER, // any other value.
452 FILE_SYSTEM_TYPE_COUNT
455 // Attempts determine the FileSystemType for |path|.
456 // Returns false if |path| doesn't exist.
457 BASE_EXPORT bool GetFileSystemType(const base::FilePath& path,
458 FileSystemType* type);
459 #endif
461 } // namespace file_util
463 // Internal --------------------------------------------------------------------
465 namespace base {
466 namespace internal {
468 // Same as Move but allows paths with traversal components.
469 // Use only with extreme care.
470 BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
471 const FilePath& to_path);
473 // Same as CopyFile but allows paths with traversal components.
474 // Use only with extreme care.
475 BASE_EXPORT bool CopyFileUnsafe(const FilePath& from_path,
476 const FilePath& to_path);
478 #if defined(OS_WIN)
479 // Copy from_path to to_path recursively and then delete from_path recursively.
480 // Returns true if all operations succeed.
481 // This function simulates Move(), but unlike Move() it works across volumes.
482 // This function is not transactional.
483 BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
484 const FilePath& to_path);
485 #endif // defined(OS_WIN)
487 } // namespace internal
488 } // namespace base
490 #endif // BASE_FILE_UTIL_H_