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.
4
5// This file contains utility functions for dealing with the local
6// filesystem.
7
8#ifndef BASE_FILES_FILE_UTIL_H_
9#define BASE_FILES_FILE_UTIL_H_
10
11#include <stddef.h>
12#include <stdint.h>
13#include <stdio.h>
14
15#include <set>
16#include <string>
17#include <vector>
18
19#include "base/base_export.h"
20#include "base/files/file.h"
21#include "base/files/file_path.h"
22#include "base/strings/string16.h"
23#include "build/build_config.h"
24
25#if defined(OS_WIN)
26#include <windows.h>
27#elif defined(OS_POSIX)
28#include <sys/stat.h>
29#include <unistd.h>
30#endif
31
32#if defined(OS_POSIX)
33#include "base/file_descriptor_posix.h"
34#include "base/logging.h"
35#include "base/posix/eintr_wrapper.h"
36#endif
37
38namespace base {
39
40class Environment;
41class Time;
42
43//-----------------------------------------------------------------------------
44// Functions that involve filesystem access or modification:
45
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.
49BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
50
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.
53//
54// This function is implemented using the FileEnumerator class so it is not
55// particularly speedy in any platform.
56BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
57
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.
64//
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)
67//
68// WARNING: USING THIS WITH recursive==true IS EQUIVALENT
69//          TO "rm -rf", SO USE WITH CAUTION.
70BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
71
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.
78BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
79#endif
80
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 ('..').
86BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
87
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.
94BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
95                             const FilePath& to_path,
96                             File::Error* error);
97
98// Copies a single file. Use CopyDirectory to copy directories.
99// This function fails if either path contains traversal components ('..').
100//
101// This function keeps the metadata on Windows. The read only bit on Windows is
102// not kept.
103BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
104
105// Copies the given path, and optionally all subdirectories and their contents
106// as well.
107//
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.
110//
111// This function calls into CopyFile() so the same behavior w.r.t. metadata
112// applies.
113//
114// If you only need to copy a file use CopyFile, it's faster.
115BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
116                               const FilePath& to_path,
117                               bool recursive);
118
119// Returns true if the given path exists on the local filesystem,
120// false otherwise.
121BASE_EXPORT bool PathExists(const FilePath& path);
122
123// Returns true if the given path is writable by the user, false otherwise.
124BASE_EXPORT bool PathIsWritable(const FilePath& path);
125
126// Returns true if the given path exists and is a directory, false otherwise.
127BASE_EXPORT bool DirectoryExists(const FilePath& path);
128
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.
131BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
132                               const FilePath& filename2);
133
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.
136BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
137                                   const FilePath& filename2);
138
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).
146BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
147
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
154// |max_size|.
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).
157BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
158                                             std::string* contents,
159                                             size_t max_size);
160
161#if defined(OS_POSIX)
162
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|.
166BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
167
168// Creates a symbolic link at |symlink| pointing to |target|.  Returns
169// false on failure.
170BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
171                                    const FilePath& symlink);
172
173// Reads the given |symlink| and returns where it points to in |target|.
174// Returns false upon failure.
175BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
176
177// Bits and masks of the file permission.
178enum 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,
183
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,
193};
194
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.
198BASE_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.
201BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
202
203// Returns true iff |executable| can be found in any directory specified by the
204// environment variable in |env|.
205BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
206                                        const FilePath::StringType& executable);
207
208#endif  // OS_POSIX
209
210// Returns true if the given directory is empty
211BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
212
213// Get the temporary directory provided by the system.
214//
215// WARNING: In general, you should use CreateTemporaryFile variants below
216// instead of this function. Those variants will ensure that the proper
217// permissions are set so that other users on the system can't edit them while
218// they're open (which can lead to security issues).
219BASE_EXPORT bool GetTempDir(FilePath* path);
220
221// Get the home directory. This is more complicated than just getenv("HOME")
222// as it knows to fall back on getpwent() etc.
223//
224// You should not generally call this directly. Instead use DIR_HOME with the
225// path service which will use this function but cache the value.
226// Path service may also override DIR_HOME.
227BASE_EXPORT FilePath GetHomeDir();
228
229// Creates a temporary file. The full path is placed in |path|, and the
230// function returns true if was successful in creating the file. The file will
231// be empty and all handles closed after this function returns.
232BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
233
234// Same as CreateTemporaryFile but the file is created in |dir|.
235BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
236                                          FilePath* temp_file);
237
238// Create and open a temporary file.  File is opened for read/write.
239// The full path is placed in |path|.
240// Returns a handle to the opened file or NULL if an error occurred.
241BASE_EXPORT FILE* CreateAndOpenTemporaryFile(FilePath* path);
242
243// Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
244BASE_EXPORT FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir,
245                                                  FilePath* path);
246
247// Create a new directory. If prefix is provided, the new directory name is in
248// the format of prefixyyyy.
249// NOTE: prefix is ignored in the POSIX implementation.
250// If success, return true and output the full path of the directory created.
251BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
252                                        FilePath* new_temp_path);
253
254// Create a directory within another directory.
255// Extra characters will be appended to |prefix| to ensure that the
256// new directory does not have the same name as an existing directory.
257BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
258                                         const FilePath::StringType& prefix,
259                                         FilePath* new_dir);
260
261// Creates a directory, as well as creating any parent directories, if they
262// don't exist. Returns 'true' on successful creation, or if the directory
263// already exists.  The directory is only readable by the current user.
264// Returns true on success, leaving *error unchanged.
265// Returns false on failure and sets *error appropriately, if it is non-NULL.
266BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
267                                            File::Error* error);
268
269// Backward-compatible convenience method for the above.
270BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
271
272// Returns the file size. Returns true on success.
273BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
274
275// Sets |real_path| to |path| with symbolic links and junctions expanded.
276// On windows, make sure the path starts with a lettered drive.
277// |path| must reference a file.  Function will fail if |path| points to
278// a directory or to a nonexistent path.  On windows, this function will
279// fail if |path| is a junction or symlink that points to an empty file,
280// or if |real_path| would be longer than MAX_PATH characters.
281BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
282
283#if defined(OS_WIN)
284
285// Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
286// return in |drive_letter_path| the equivalent path that starts with
287// a drive letter ("C:\...").  Return false if no such path exists.
288BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
289                                             FilePath* drive_letter_path);
290
291// Given an existing file in |path|, set |real_path| to the path
292// in native NT format, of the form "\Device\HarddiskVolumeXX\..".
293// Returns false if the path can not be found. Empty files cannot
294// be resolved with this function.
295BASE_EXPORT bool NormalizeToNativeFilePath(const FilePath& path,
296                                           FilePath* nt_path);
297
298// Given an existing file in |path|, returns whether this file is on a network
299// drive or not. If |path| does not exist, this function returns false.
300BASE_EXPORT bool IsOnNetworkDrive(const base::FilePath& path);
301#endif
302
303// This function will return if the given file is a symlink or not.
304BASE_EXPORT bool IsLink(const FilePath& file_path);
305
306// Returns information about the given file path.
307BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
308
309// Sets the time of the last access and the time of the last modification.
310BASE_EXPORT bool TouchFile(const FilePath& path,
311                           const Time& last_accessed,
312                           const Time& last_modified);
313
314// Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
315BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
316
317// Closes file opened by OpenFile. Returns true on success.
318BASE_EXPORT bool CloseFile(FILE* file);
319
320// Associates a standard FILE stream with an existing File. Note that this
321// functions take ownership of the existing File.
322BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
323
324// Truncates an open file to end at the location of the current file pointer.
325// This is a cross-platform analog to Windows' SetEndOfFile() function.
326BASE_EXPORT bool TruncateFile(FILE* file);
327
328// Reads at most the given number of bytes from the file into the buffer.
329// Returns the number of read bytes, or -1 on error.
330BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
331
332// Writes the given buffer into the file, overwriting any data that was
333// previously there.  Returns the number of bytes written, or -1 on error.
334BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
335                          int size);
336
337#if defined(OS_POSIX)
338// Appends |data| to |fd|. Does not close |fd| when done.  Returns true iff
339// |size| bytes of |data| were written to |fd|.
340BASE_EXPORT bool WriteFileDescriptor(const int fd, const char* data, int size);
341#endif
342
343// Appends |data| to |filename|.  Returns true iff |size| bytes of |data| were
344// written to |filename|.
345BASE_EXPORT bool AppendToFile(const FilePath& filename,
346                              const char* data,
347                              int size);
348
349// Gets the current working directory for the process.
350BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
351
352// Sets the current working directory for the process.
353BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
354
355// Attempts to find a number that can be appended to the |path| to make it
356// unique. If |path| does not exist, 0 is returned.  If it fails to find such
357// a number, -1 is returned. If |suffix| is not empty, also checks the
358// existence of it with the given suffix.
359BASE_EXPORT int GetUniquePathNumber(const FilePath& path,
360                                    const FilePath::StringType& suffix);
361
362// Sets the given |fd| to non-blocking mode.
363// Returns true if it was able to set it in the non-blocking mode, otherwise
364// false.
365BASE_EXPORT bool SetNonBlocking(int fd);
366
367#if defined(OS_POSIX)
368// Test that |path| can only be changed by a given user and members of
369// a given set of groups.
370// Specifically, test that all parts of |path| under (and including) |base|:
371// * Exist.
372// * Are owned by a specific user.
373// * Are not writable by all users.
374// * Are owned by a member of a given set of groups, or are not writable by
375//   their group.
376// * Are not symbolic links.
377// This is useful for checking that a config file is administrator-controlled.
378// |base| must contain |path|.
379BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
380                                            const base::FilePath& path,
381                                            uid_t owner_uid,
382                                            const std::set<gid_t>& group_gids);
383#endif  // defined(OS_POSIX)
384
385#if defined(OS_MACOSX) && !defined(OS_IOS)
386// Is |path| writable only by a user with administrator privileges?
387// This function uses Mac OS conventions.  The super user is assumed to have
388// uid 0, and the administrator group is assumed to be named "admin".
389// Testing that |path|, and every parent directory including the root of
390// the filesystem, are owned by the superuser, controlled by the group
391// "admin", are not writable by all users, and contain no symbolic links.
392// Will return false if |path| does not exist.
393BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
394#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
395
396// Returns the maximum length of path component on the volume containing
397// the directory |path|, in the number of FilePath::CharType, or -1 on failure.
398BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
399
400#if defined(OS_LINUX)
401// Broad categories of file systems as returned by statfs() on Linux.
402enum FileSystemType {
403  FILE_SYSTEM_UNKNOWN,  // statfs failed.
404  FILE_SYSTEM_0,        // statfs.f_type == 0 means unknown, may indicate AFS.
405  FILE_SYSTEM_ORDINARY,       // on-disk filesystem like ext2
406  FILE_SYSTEM_NFS,
407  FILE_SYSTEM_SMB,
408  FILE_SYSTEM_CODA,
409  FILE_SYSTEM_MEMORY,         // in-memory file system
410  FILE_SYSTEM_CGROUP,         // cgroup control.
411  FILE_SYSTEM_OTHER,          // any other value.
412  FILE_SYSTEM_TYPE_COUNT
413};
414
415// Attempts determine the FileSystemType for |path|.
416// Returns false if |path| doesn't exist.
417BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
418#endif
419
420#if defined(OS_POSIX)
421// Get a temporary directory for shared memory files. The directory may depend
422// on whether the destination is intended for executable files, which in turn
423// depends on how /dev/shmem was mounted. As a result, you must supply whether
424// you intend to create executable shmem segments so this function can find
425// an appropriate location.
426BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
427#endif
428
429// Internal --------------------------------------------------------------------
430
431namespace internal {
432
433// Same as Move but allows paths with traversal components.
434// Use only with extreme care.
435BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
436                            const FilePath& to_path);
437
438#if defined(OS_WIN)
439// Copy from_path to to_path recursively and then delete from_path recursively.
440// Returns true if all operations succeed.
441// This function simulates Move(), but unlike Move() it works across volumes.
442// This function is not transactional.
443BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
444                                        const FilePath& to_path);
445#endif  // defined(OS_WIN)
446
447}  // namespace internal
448}  // namespace base
449
450#endif  // BASE_FILES_FILE_UTIL_H_
451