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/file_path.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/platform_file.h"
32 #include "base/string16.h"
35 #include "base/eintr_wrapper.h"
36 #include "base/file_descriptor_posix.h"
37 #include "base/logging.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 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(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(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 FilePath
& parent
, const FilePath
& child
);
66 //-----------------------------------------------------------------------------
67 // Functions that involve filesystem access or modification:
69 // Returns the number of files matching the current path that were
70 // created on or after the given |file_time|. Doesn't count ".." or ".".
72 // Note for POSIX environments: a file created before |file_time|
73 // can be mis-detected as a newer file due to low precision of
74 // timestmap of file creation time. If you need to avoid such
75 // mis-detection perfectly, you should wait one second before
76 // obtaining |file_time|.
77 BASE_EXPORT
int CountFilesCreatedAfter(const FilePath
& path
,
78 const base::Time
& file_time
);
80 // Returns the total number of bytes used by all the files under |root_path|.
81 // If the path does not exist the function returns 0.
83 // This function is implemented using the FileEnumerator class so it is not
84 // particularly speedy in any platform.
85 BASE_EXPORT int64
ComputeDirectorySize(const FilePath
& root_path
);
87 // Returns the total number of bytes used by all files matching the provided
88 // |pattern|, on this |directory| (without recursion). If the path does not
89 // exist the function returns 0.
91 // This function is implemented using the FileEnumerator class so it is not
92 // particularly speedy in any platform.
93 BASE_EXPORT int64
ComputeFilesSize(const FilePath
& directory
,
94 const FilePath::StringType
& pattern
);
96 // Deletes the given path, whether it's a file or a directory.
97 // If it's a directory, it's perfectly happy to delete all of the
98 // directory's contents. Passing true to recursive deletes
99 // subdirectories and their contents as well.
100 // Returns true if successful, false otherwise.
102 // In posix environment and if |path| is a symbolic link, this deletes only
103 // the symlink. (even if the symlink points to a non-existent file)
105 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
106 // TO "rm -rf", SO USE WITH CAUTION.
107 BASE_EXPORT
bool Delete(const FilePath
& path
, bool recursive
);
110 // Schedules to delete the given path, whether it's a file or a directory, until
111 // the operating system is restarted.
113 // 1) The file/directory to be deleted should exist in a temp folder.
114 // 2) The directory to be deleted must be empty.
115 BASE_EXPORT
bool DeleteAfterReboot(const FilePath
& path
);
118 // Moves the given path, whether it's a file or a directory.
119 // If a simple rename is not possible, such as in the case where the paths are
120 // on different volumes, this will attempt to copy and delete. Returns
122 BASE_EXPORT
bool Move(const FilePath
& from_path
, const FilePath
& to_path
);
124 // Renames file |from_path| to |to_path|. Both paths must be on the same
125 // volume, or the function will fail. Destination file will be created
126 // if it doesn't exist. Prefer this function over Move when dealing with
127 // temporary files. On Windows it preserves attributes of the target file.
128 // Returns true on success.
129 BASE_EXPORT
bool ReplaceFile(const FilePath
& from_path
,
130 const FilePath
& to_path
);
132 // Copies a single file. Use CopyDirectory to copy directories.
133 BASE_EXPORT
bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
);
135 // Copies the given path, and optionally all subdirectories and their contents
137 // If there are files existing under to_path, always overwrite.
138 // Returns true if successful, false otherwise.
139 // Don't use wildcards on the names, it may stop working without notice.
141 // If you only need to copy a file use CopyFile, it's faster.
142 BASE_EXPORT
bool CopyDirectory(const FilePath
& from_path
,
143 const FilePath
& to_path
,
146 // Returns true if the given path exists on the local filesystem,
148 BASE_EXPORT
bool PathExists(const FilePath
& path
);
150 // Returns true if the given path is writable by the user, false otherwise.
151 BASE_EXPORT
bool PathIsWritable(const FilePath
& path
);
153 // Returns true if the given path exists and is a directory, false otherwise.
154 BASE_EXPORT
bool DirectoryExists(const FilePath
& path
);
157 // Gets the creation time of the given file (expressed in the local timezone),
158 // and returns it via the creation_time parameter. Returns true if successful,
160 BASE_EXPORT
bool GetFileCreationLocalTime(const std::wstring
& filename
,
161 LPSYSTEMTIME creation_time
);
163 // Same as above, but takes a previously-opened file handle instead of a name.
164 BASE_EXPORT
bool GetFileCreationLocalTimeFromHandle(HANDLE file_handle
,
165 LPSYSTEMTIME creation_time
);
166 #endif // defined(OS_WIN)
168 // Returns true if the contents of the two files given are equal, false
169 // otherwise. If either file can't be read, returns false.
170 BASE_EXPORT
bool ContentsEqual(const FilePath
& filename1
,
171 const FilePath
& filename2
);
173 // Returns true if the contents of the two text files given are equal, false
174 // otherwise. This routine treats "\r\n" and "\n" as equivalent.
175 BASE_EXPORT
bool TextContentsEqual(const FilePath
& filename1
,
176 const FilePath
& filename2
);
178 // Read the file at |path| into |contents|, returning true on success.
179 // |contents| may be NULL, in which case this function is useful for its
180 // side effect of priming the disk cache.
181 // Useful for unit tests.
182 BASE_EXPORT
bool ReadFileToString(const FilePath
& path
, std::string
* contents
);
184 #if defined(OS_POSIX)
185 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
186 // in |buffer|. This function is protected against EINTR and partial reads.
187 // Returns true iff |bytes| bytes have been successfuly read from |fd|.
188 BASE_EXPORT
bool ReadFromFD(int fd
, char* buffer
, size_t bytes
);
190 // Creates a symbolic link at |symlink| pointing to |target|. Returns
192 BASE_EXPORT
bool CreateSymbolicLink(const FilePath
& target
,
193 const FilePath
& symlink
);
195 // Reads the given |symlink| and returns where it points to in |target|.
196 // Returns false upon failure.
197 BASE_EXPORT
bool ReadSymbolicLink(const FilePath
& symlink
, FilePath
* target
);
199 // Bits ans masks of the file permission.
200 enum FilePermissionBits
{
201 FILE_PERMISSION_MASK
= S_IRWXU
| S_IRWXG
| S_IRWXO
,
202 FILE_PERMISSION_USER_MASK
= S_IRWXU
,
203 FILE_PERMISSION_GROUP_MASK
= S_IRWXG
,
204 FILE_PERMISSION_OTHERS_MASK
= S_IRWXO
,
206 FILE_PERMISSION_READ_BY_USER
= S_IRUSR
,
207 FILE_PERMISSION_WRITE_BY_USER
= S_IWUSR
,
208 FILE_PERMISSION_EXECUTE_BY_USER
= S_IXUSR
,
209 FILE_PERMISSION_READ_BY_GROUP
= S_IRGRP
,
210 FILE_PERMISSION_WRITE_BY_GROUP
= S_IWGRP
,
211 FILE_PERMISSION_EXECUTE_BY_GROUP
= S_IXGRP
,
212 FILE_PERMISSION_READ_BY_OTHERS
= S_IROTH
,
213 FILE_PERMISSION_WRITE_BY_OTHERS
= S_IWOTH
,
214 FILE_PERMISSION_EXECUTE_BY_OTHERS
= S_IXOTH
,
217 // Reads the permission of the given |path|, storing the file permission
218 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
219 // a file which the symlink points to.
220 BASE_EXPORT
bool GetPosixFilePermissions(const FilePath
& path
,
222 // Sets the permission of the given |path|. If |path| is symbolic link, sets
223 // the permission of a file which the symlink points to.
224 BASE_EXPORT
bool SetPosixFilePermissions(const FilePath
& path
,
226 #endif // defined(OS_POSIX)
229 // Copy from_path to to_path recursively and then delete from_path recursively.
230 // Returns true if all operations succeed.
231 // This function simulates Move(), but unlike Move() it works across volumes.
232 // This fuction is not transactional.
233 BASE_EXPORT
bool CopyAndDeleteDirectory(const FilePath
& from_path
,
234 const FilePath
& to_path
);
235 #endif // defined(OS_WIN)
237 // Return true if the given directory is empty
238 BASE_EXPORT
bool IsDirectoryEmpty(const FilePath
& dir_path
);
240 // Get the temporary directory provided by the system.
241 // WARNING: DON'T USE THIS. If you want to create a temporary file, use one of
242 // the functions below.
243 BASE_EXPORT
bool GetTempDir(FilePath
* path
);
244 // Get a temporary directory for shared memory files.
245 // Only useful on POSIX; redirects to GetTempDir() on Windows.
246 BASE_EXPORT
bool GetShmemTempDir(FilePath
* path
, bool executable
);
248 // Get the home directory. This is more complicated than just getenv("HOME")
249 // as it knows to fall back on getpwent() etc.
250 BASE_EXPORT FilePath
GetHomeDir();
252 // Creates a temporary file. The full path is placed in |path|, and the
253 // function returns true if was successful in creating the file. The file will
254 // be empty and all handles closed after this function returns.
255 BASE_EXPORT
bool CreateTemporaryFile(FilePath
* path
);
257 // Same as CreateTemporaryFile but the file is created in |dir|.
258 BASE_EXPORT
bool CreateTemporaryFileInDir(const FilePath
& dir
,
259 FilePath
* temp_file
);
261 // Create and open a temporary file. File is opened for read/write.
262 // The full path is placed in |path|.
263 // Returns a handle to the opened file or NULL if an error occured.
264 BASE_EXPORT
FILE* CreateAndOpenTemporaryFile(FilePath
* path
);
265 // Like above but for shmem files. Only useful for POSIX.
266 // The executable flag says the file needs to support using
267 // mprotect with PROT_EXEC after mapping.
268 BASE_EXPORT
FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
,
270 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
271 BASE_EXPORT
FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
,
274 // Create a new directory. If prefix is provided, the new directory name is in
275 // the format of prefixyyyy.
276 // NOTE: prefix is ignored in the POSIX implementation.
277 // If success, return true and output the full path of the directory created.
278 BASE_EXPORT
bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
279 FilePath
* new_temp_path
);
281 // Create a directory within another directory.
282 // Extra characters will be appended to |prefix| to ensure that the
283 // new directory does not have the same name as an existing directory.
284 BASE_EXPORT
bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
285 const FilePath::StringType
& prefix
,
288 // Creates a directory, as well as creating any parent directories, if they
289 // don't exist. Returns 'true' on successful creation, or if the directory
290 // already exists. The directory is only readable by the current user.
291 BASE_EXPORT
bool CreateDirectory(const FilePath
& full_path
);
293 // Returns the file size. Returns true on success.
294 BASE_EXPORT
bool GetFileSize(const FilePath
& file_path
, int64
* file_size
);
296 // Returns true if the given path's base name is ".".
297 BASE_EXPORT
bool IsDot(const FilePath
& path
);
299 // Returns true if the given path's base name is "..".
300 BASE_EXPORT
bool IsDotDot(const FilePath
& path
);
302 // Sets |real_path| to |path| with symbolic links and junctions expanded.
303 // On windows, make sure the path starts with a lettered drive.
304 // |path| must reference a file. Function will fail if |path| points to
305 // a directory or to a nonexistent path. On windows, this function will
306 // fail if |path| is a junction or symlink that points to an empty file,
307 // or if |real_path| would be longer than MAX_PATH characters.
308 BASE_EXPORT
bool NormalizeFilePath(const FilePath
& path
, FilePath
* real_path
);
312 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
313 // return in |drive_letter_path| the equivalent path that starts with
314 // a drive letter ("C:\..."). Return false if no such path exists.
315 BASE_EXPORT
bool DevicePathToDriveLetterPath(const FilePath
& device_path
,
316 FilePath
* drive_letter_path
);
318 // Given an existing file in |path|, set |real_path| to the path
319 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
320 // Returns false if the path can not be found. Empty files cannot
321 // be resolved with this function.
322 BASE_EXPORT
bool NormalizeToNativeFilePath(const FilePath
& path
,
326 // This function will return if the given file is a symlink or not.
327 BASE_EXPORT
bool IsLink(const FilePath
& file_path
);
329 // Returns information about the given file path.
330 BASE_EXPORT
bool GetFileInfo(const FilePath
& file_path
,
331 base::PlatformFileInfo
* info
);
333 // Sets the time of the last access and the time of the last modification.
334 BASE_EXPORT
bool TouchFile(const FilePath
& path
,
335 const base::Time
& last_accessed
,
336 const base::Time
& last_modified
);
338 // Set the time of the last modification. Useful for unit tests.
339 BASE_EXPORT
bool SetLastModifiedTime(const FilePath
& path
,
340 const base::Time
& last_modified
);
342 #if defined(OS_POSIX)
343 // Store inode number of |path| in |inode|. Return true on success.
344 BASE_EXPORT
bool GetInode(const FilePath
& path
, ino_t
* inode
);
347 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
348 BASE_EXPORT
FILE* OpenFile(const FilePath
& filename
, const char* mode
);
350 // Closes file opened by OpenFile. Returns true on success.
351 BASE_EXPORT
bool CloseFile(FILE* file
);
353 // Truncates an open file to end at the location of the current file pointer.
354 // This is a cross-platform analog to Windows' SetEndOfFile() function.
355 BASE_EXPORT
bool TruncateFile(FILE* file
);
357 // Reads the given number of bytes from the file into the buffer. Returns
358 // the number of read bytes, or -1 on error.
359 BASE_EXPORT
int ReadFile(const FilePath
& filename
, char* data
, int size
);
361 // Writes the given buffer into the file, overwriting any data that was
362 // previously there. Returns the number of bytes written, or -1 on error.
363 BASE_EXPORT
int WriteFile(const FilePath
& filename
, const char* data
, int size
);
364 #if defined(OS_POSIX)
365 // Append the data to |fd|. Does not close |fd| when done.
366 BASE_EXPORT
int WriteFileDescriptor(const int fd
, const char* data
, int size
);
368 // Append the given buffer into the file. Returns the number of bytes written,
370 BASE_EXPORT
int AppendToFile(const FilePath
& filename
,
371 const char* data
, int size
);
373 // Gets the current working directory for the process.
374 BASE_EXPORT
bool GetCurrentDirectory(FilePath
* path
);
376 // Sets the current working directory for the process.
377 BASE_EXPORT
bool SetCurrentDirectory(const FilePath
& path
);
379 // Attempts to find a number that can be appended to the |path| to make it
380 // unique. If |path| does not exist, 0 is returned. If it fails to find such
381 // a number, -1 is returned. If |suffix| is not empty, also checks the
382 // existence of it with the given suffix.
383 BASE_EXPORT
int GetUniquePathNumber(const FilePath
& path
,
384 const FilePath::StringType
& suffix
);
386 #if defined(OS_POSIX)
387 // Test that |path| can only be changed by a given user and members of
388 // a given set of groups.
389 // Specifically, test that all parts of |path| under (and including) |base|:
391 // * Are owned by a specific user.
392 // * Are not writable by all users.
393 // * Are owned by a memeber of a given set of groups, or are not writable by
395 // * Are not symbolic links.
396 // This is useful for checking that a config file is administrator-controlled.
397 // |base| must contain |path|.
398 BASE_EXPORT
bool VerifyPathControlledByUser(const FilePath
& base
,
399 const FilePath
& path
,
401 const std::set
<gid_t
>& group_gids
);
402 #endif // defined(OS_POSIX)
404 #if defined(OS_MACOSX) && !defined(OS_IOS)
405 // Is |path| writable only by a user with administrator privileges?
406 // This function uses Mac OS conventions. The super user is assumed to have
407 // uid 0, and the administrator group is assumed to be named "admin".
408 // Testing that |path|, and every parent directory including the root of
409 // the filesystem, are owned by the superuser, controlled by the group
410 // "admin", are not writable by all users, and contain no symbolic links.
411 // Will return false if |path| does not exist.
412 BASE_EXPORT
bool VerifyPathControlledByAdmin(const FilePath
& path
);
413 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
415 // A class to handle auto-closing of FILE*'s.
416 class ScopedFILEClose
{
418 inline void operator()(FILE* x
) const {
425 typedef scoped_ptr_malloc
<FILE, ScopedFILEClose
> ScopedFILE
;
427 #if defined(OS_POSIX)
428 // A class to handle auto-closing of FDs.
429 class ScopedFDClose
{
431 inline void operator()(int* x
) const {
433 if (HANDLE_EINTR(close(*x
)) < 0)
434 DPLOG(ERROR
) << "close";
439 typedef scoped_ptr_malloc
<int, ScopedFDClose
> ScopedFD
;
442 // A class for enumerating the files in a provided path. The order of the
443 // results is not guaranteed.
445 // DO NOT USE FROM THE MAIN THREAD of your application unless it is a test
446 // program where latency does not matter. This class is blocking.
447 class BASE_EXPORT FileEnumerator
{
450 typedef WIN32_FIND_DATA FindInfo
;
451 #elif defined(OS_POSIX)
454 std::string filename
;
460 DIRECTORIES
= 1 << 1,
461 INCLUDE_DOT_DOT
= 1 << 2,
462 #if defined(OS_POSIX)
463 SHOW_SYM_LINKS
= 1 << 4,
467 // |root_path| is the starting directory to search for. It may or may not end
470 // If |recursive| is true, this will enumerate all matches in any
471 // subdirectories matched as well. It does a breadth-first search, so all
472 // files in one directory will be returned before any files in a
475 // |file_type|, a bit mask of FileType, specifies whether the enumerator
476 // should match files, directories, or both.
478 // |pattern| is an optional pattern for which files to match. This
479 // works like shell globbing. For example, "*.txt" or "Foo???.doc".
480 // However, be careful in specifying patterns that aren't cross platform
481 // since the underlying code uses OS-specific matching routines. In general,
482 // Windows matching is less featureful than others, so test there first.
483 // If unspecified, this will match all files.
484 // NOTE: the pattern only matches the contents of root_path, not files in
485 // recursive subdirectories.
486 // TODO(erikkay): Fix the pattern matching to work at all levels.
487 FileEnumerator(const FilePath
& root_path
,
490 FileEnumerator(const FilePath
& root_path
,
493 const FilePath::StringType
& pattern
);
496 // Returns an empty string if there are no more results.
499 // Write the file info into |info|.
500 void GetFindInfo(FindInfo
* info
);
502 // Looks inside a FindInfo and determines if it's a directory.
503 static bool IsDirectory(const FindInfo
& info
);
505 static FilePath
GetFilename(const FindInfo
& find_info
);
506 static int64
GetFilesize(const FindInfo
& find_info
);
507 static base::Time
GetLastModifiedTime(const FindInfo
& find_info
);
510 // Returns true if the given path should be skipped in enumeration.
511 bool ShouldSkip(const FilePath
& path
);
515 // True when find_data_ is valid.
517 WIN32_FIND_DATA find_data_
;
519 #elif defined(OS_POSIX)
520 struct DirectoryEntryInfo
{
525 // Read the filenames in source into the vector of DirectoryEntryInfo's
526 static bool ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
527 const FilePath
& source
, bool show_links
);
529 // The files in the current directory
530 std::vector
<DirectoryEntryInfo
> directory_entries_
;
532 // The next entry to use from the directory_entries_ vector
533 size_t current_directory_entry_
;
539 FilePath::StringType pattern_
; // Empty when we want to find everything.
541 // A stack that keeps track of which subdirectories we still need to
542 // enumerate in the breadth-first search.
543 std::stack
<FilePath
> pending_paths_
;
545 DISALLOW_COPY_AND_ASSIGN(FileEnumerator
);
548 class BASE_EXPORT MemoryMappedFile
{
550 // The default constructor sets all members to invalid/null values.
554 // Opens an existing file and maps it into memory. Access is restricted to
555 // read only. If this object already points to a valid memory mapped file
556 // then this method will fail and return false. If it cannot open the file,
557 // the file does not exist, or the memory mapping fails, it will return false.
558 // Later we may want to allow the user to specify access.
559 bool Initialize(const FilePath
& file_name
);
560 // As above, but works with an already-opened file. MemoryMappedFile will take
561 // ownership of |file| and close it when done.
562 bool Initialize(base::PlatformFile file
);
565 // Opens an existing file and maps it as an image section. Please refer to
566 // the Initialize function above for additional information.
567 bool InitializeAsImageSection(const FilePath
& file_name
);
570 const uint8
* data() const { return data_
; }
571 size_t length() const { return length_
; }
573 // Is file_ a valid file handle that points to an open, memory mapped file?
574 bool IsValid() const;
577 // Open the given file and pass it to MapFileToMemoryInternal().
578 bool MapFileToMemory(const FilePath
& file_name
);
580 // Map the file to memory, set data_ to that memory address. Return true on
581 // success, false on any kind of failure. This is a helper for Initialize().
582 bool MapFileToMemoryInternal();
584 // Closes all open handles. Later we may want to make this public.
588 // MapFileToMemoryInternal calls this function. It provides the ability to
589 // pass in flags which control the mapped section.
590 bool MapFileToMemoryInternalEx(int flags
);
592 HANDLE file_mapping_
;
594 base::PlatformFile file_
;
598 DISALLOW_COPY_AND_ASSIGN(MemoryMappedFile
);
601 // Returns whether the file has been modified since a particular date.
602 BASE_EXPORT
bool HasFileBeenModifiedSince(
603 const FileEnumerator::FindInfo
& find_info
,
604 const base::Time
& cutoff_time
);
606 #if defined(OS_LINUX)
607 // Broad categories of file systems as returned by statfs() on Linux.
608 enum FileSystemType
{
609 FILE_SYSTEM_UNKNOWN
, // statfs failed.
610 FILE_SYSTEM_0
, // statfs.f_type == 0 means unknown, may indicate AFS.
611 FILE_SYSTEM_ORDINARY
, // on-disk filesystem like ext2
615 FILE_SYSTEM_MEMORY
, // in-memory file system
616 FILE_SYSTEM_CGROUP
, // cgroup control.
617 FILE_SYSTEM_OTHER
, // any other value.
618 FILE_SYSTEM_TYPE_COUNT
621 // Attempts determine the FileSystemType for |path|.
622 // Returns false if |path| doesn't exist.
623 BASE_EXPORT
bool GetFileSystemType(const FilePath
& path
, FileSystemType
* type
);
626 } // namespace file_util
628 #endif // BASE_FILE_UTIL_H_