[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 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 | |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 11 | #include <stddef.h> |
| 12 | #include <stdint.h> |
| 13 | #include <stdio.h> |
| 14 | |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 15 | #include <limits> |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 16 | #include <set> |
| 17 | #include <string> |
| 18 | #include <vector> |
| 19 | |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 20 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 21 | #include <sys/stat.h> |
| 22 | #include <unistd.h> |
| 23 | #endif |
| 24 | |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 25 | #include "base/base_export.h" |
Lei Zhang | e3aa0b9a | 2020-06-11 08:59:23 | [diff] [blame] | 26 | #include "base/callback_forward.h" |
Lei Zhang | eebbef6 | 2020-05-05 20:16:05 | [diff] [blame] | 27 | #include "base/containers/span.h" |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 28 | #include "base/files/file.h" |
| 29 | #include "base/files/file_path.h" |
Greg Thompson | f75f5fb | 2020-04-30 08:13:25 | [diff] [blame] | 30 | #include "base/files/scoped_file.h" |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 31 | #include "base/strings/string16.h" |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 32 | #include "build/build_config.h" |
| 33 | |
| 34 | #if defined(OS_WIN) |
Bruce Dawson | bfdc3fd | 2018-01-03 20:32:36 | [diff] [blame] | 35 | #include "base/win/windows_types.h" |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 36 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 37 | #include "base/file_descriptor_posix.h" |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 38 | #include "base/posix/eintr_wrapper.h" |
| 39 | #endif |
| 40 | |
| 41 | namespace base { |
| 42 | |
thomasanderson | 1929bb2 | 2016-06-24 02:01:00 | [diff] [blame] | 43 | class Environment; |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 44 | class Time; |
| 45 | |
| 46 | //----------------------------------------------------------------------------- |
| 47 | // Functions that involve filesystem access or modification: |
| 48 | |
| 49 | // Returns an absolute version of a relative path. Returns an empty path on |
| 50 | // error. On POSIX, this function fails if the path does not exist. This |
| 51 | // function can result in I/O so it can be slow. |
| 52 | BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input); |
| 53 | |
| 54 | // Returns the total number of bytes used by all the files under |root_path|. |
| 55 | // If the path does not exist the function returns 0. |
| 56 | // |
| 57 | // This function is implemented using the FileEnumerator class so it is not |
| 58 | // particularly speedy in any platform. |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 59 | BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 60 | |
| 61 | // Deletes the given path, whether it's a file or a directory. |
Lei Zhang | f9696375 | 2020-06-18 20:34:10 | [diff] [blame] | 62 | // If it's a directory, it's perfectly happy to delete all of the directory's |
| 63 | // contents, but it will not recursively delete subdirectories and their |
| 64 | // contents. |
| 65 | // Returns true if successful, false otherwise. It is considered successful to |
| 66 | // attempt to delete a file that does not exist. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 67 | // |
Lei Zhang | aeb72b5 | 2019-10-14 22:39:40 | [diff] [blame] | 68 | // In POSIX environment and if |path| is a symbolic link, this deletes only |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 69 | // the symlink. (even if the symlink points to a non-existent file) |
Lei Zhang | f9696375 | 2020-06-18 20:34:10 | [diff] [blame] | 70 | BASE_EXPORT bool DeleteFile(const FilePath& path); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 71 | |
Lei Zhang | aeb72b5 | 2019-10-14 22:39:40 | [diff] [blame] | 72 | // Deletes the given path, whether it's a file or a directory. |
| 73 | // If it's a directory, it's perfectly happy to delete all of the |
| 74 | // directory's contents, including subdirectories and their contents. |
| 75 | // Returns true if successful, false otherwise. It is considered successful |
| 76 | // to attempt to delete a file that does not exist. |
| 77 | // |
| 78 | // In POSIX environment and if |path| is a symbolic link, this deletes only |
| 79 | // the symlink. (even if the symlink points to a non-existent file) |
| 80 | // |
| 81 | // WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION. |
Lei Zhang | 746ce47 | 2020-07-01 04:39:45 | [diff] [blame] | 82 | BASE_EXPORT bool DeletePathRecursively(const FilePath& path); |
Lei Zhang | aeb72b5 | 2019-10-14 22:39:40 | [diff] [blame] | 83 | |
Lei Zhang | f9696375 | 2020-06-18 20:34:10 | [diff] [blame] | 84 | // Simplified way to get a callback to do DeleteFile(path) and ignore the |
Lei Zhang | e3aa0b9a | 2020-06-11 08:59:23 | [diff] [blame] | 85 | // DeleteFile() result. |
| 86 | BASE_EXPORT OnceCallback<void(const FilePath&)> GetDeleteFileCallback(); |
| 87 | |
Lei Zhang | 746ce47 | 2020-07-01 04:39:45 | [diff] [blame] | 88 | // Simplified way to get a callback to do DeletePathRecursively(path) and ignore |
| 89 | // the DeletePathRecursively() result. |
Lei Zhang | 3190449f7 | 2020-06-12 05:14:04 | [diff] [blame] | 90 | BASE_EXPORT OnceCallback<void(const FilePath&)> |
| 91 | GetDeletePathRecursivelyCallback(); |
| 92 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 93 | #if defined(OS_WIN) |
| 94 | // Schedules to delete the given path, whether it's a file or a directory, until |
| 95 | // the operating system is restarted. |
| 96 | // Note: |
| 97 | // 1) The file/directory to be deleted should exist in a temp folder. |
| 98 | // 2) The directory to be deleted must be empty. |
| 99 | BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path); |
| 100 | #endif |
| 101 | |
| 102 | // Moves the given path, whether it's a file or a directory. |
| 103 | // If a simple rename is not possible, such as in the case where the paths are |
| 104 | // on different volumes, this will attempt to copy and delete. Returns |
| 105 | // true for success. |
| 106 | // This function fails if either path contains traversal components ('..'). |
| 107 | BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path); |
| 108 | |
| 109 | // Renames file |from_path| to |to_path|. Both paths must be on the same |
| 110 | // volume, or the function will fail. Destination file will be created |
| 111 | // if it doesn't exist. Prefer this function over Move when dealing with |
| 112 | // temporary files. On Windows it preserves attributes of the target file. |
| 113 | // Returns true on success, leaving *error unchanged. |
| 114 | // Returns false on failure and sets *error appropriately, if it is non-NULL. |
| 115 | BASE_EXPORT bool ReplaceFile(const FilePath& from_path, |
| 116 | const FilePath& to_path, |
| 117 | File::Error* error); |
| 118 | |
Lei Zhang | 6a0e47ca | 2017-10-02 23:02:16 | [diff] [blame] | 119 | // Copies a single file. Use CopyDirectory() to copy directories. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 120 | // This function fails if either path contains traversal components ('..'). |
Lei Zhang | 6a0e47ca | 2017-10-02 23:02:16 | [diff] [blame] | 121 | // This function also fails if |to_path| is a directory. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 122 | // |
Lei Zhang | 6a0e47ca | 2017-10-02 23:02:16 | [diff] [blame] | 123 | // On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This |
| 124 | // may have security implications. Use with care. |
| 125 | // |
| 126 | // If |to_path| already exists and is a regular file, it will be overwritten, |
| 127 | // though its permissions will stay the same. |
| 128 | // |
| 129 | // If |to_path| does not exist, it will be created. The new file's permissions |
| 130 | // varies per platform: |
| 131 | // |
| 132 | // - This function keeps the metadata on Windows. The read only bit is not kept. |
| 133 | // - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user |
| 134 | // read/write permissions are always set. |
| 135 | // - On Linux and Android, |to_path| has user read/write permissions only. i.e. |
| 136 | // Always 0600. |
| 137 | // - On ChromeOS, |to_path| has user read/write permissions and group/others |
| 138 | // read permissions. i.e. Always 0644. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 139 | BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path); |
| 140 | |
Alexander Bolodurin | 53bfc89c2 | 2020-11-25 22:43:29 | [diff] [blame] | 141 | // Copies the contents of one file into another. |
| 142 | // The files are taken as is: the copy is done starting from the current offset |
| 143 | // of |infile| until the end of |infile| is reached, into the current offset of |
| 144 | // |outfile|. |
| 145 | BASE_EXPORT bool CopyFileContents(File& infile, File& outfile); |
| 146 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 147 | // Copies the given path, and optionally all subdirectories and their contents |
| 148 | // as well. |
| 149 | // |
| 150 | // If there are files existing under to_path, always overwrite. Returns true |
| 151 | // if successful, false otherwise. Wildcards on the names are not supported. |
| 152 | // |
Eric Caruso | bca21fc58 | 2017-09-28 00:34:34 | [diff] [blame] | 153 | // This function has the same metadata behavior as CopyFile(). |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 154 | // |
| 155 | // If you only need to copy a file use CopyFile, it's faster. |
| 156 | BASE_EXPORT bool CopyDirectory(const FilePath& from_path, |
| 157 | const FilePath& to_path, |
| 158 | bool recursive); |
| 159 | |
Eric Caruso | 128f0dd | 2017-12-16 01:32:49 | [diff] [blame] | 160 | // Like CopyDirectory() except trying to overwrite an existing file will not |
| 161 | // work and will return false. |
| 162 | BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path, |
| 163 | const FilePath& to_path, |
| 164 | bool recursive); |
| 165 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 166 | // Returns true if the given path exists on the local filesystem, |
| 167 | // false otherwise. |
| 168 | BASE_EXPORT bool PathExists(const FilePath& path); |
| 169 | |
Avi Drissman | b2a8ac9a | 2020-09-11 18:41:32 | [diff] [blame] | 170 | // Returns true if the given path is readable by the user, false otherwise. |
| 171 | BASE_EXPORT bool PathIsReadable(const FilePath& path); |
| 172 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 173 | // Returns true if the given path is writable by the user, false otherwise. |
| 174 | BASE_EXPORT bool PathIsWritable(const FilePath& path); |
| 175 | |
| 176 | // Returns true if the given path exists and is a directory, false otherwise. |
| 177 | BASE_EXPORT bool DirectoryExists(const FilePath& path); |
| 178 | |
| 179 | // Returns true if the contents of the two files given are equal, false |
| 180 | // otherwise. If either file can't be read, returns false. |
| 181 | BASE_EXPORT bool ContentsEqual(const FilePath& filename1, |
| 182 | const FilePath& filename2); |
| 183 | |
| 184 | // Returns true if the contents of the two text files given are equal, false |
| 185 | // otherwise. This routine treats "\r\n" and "\n" as equivalent. |
| 186 | BASE_EXPORT bool TextContentsEqual(const FilePath& filename1, |
| 187 | const FilePath& filename2); |
| 188 | |
| 189 | // Reads the file at |path| into |contents| and returns true on success and |
| 190 | // false on error. For security reasons, a |path| containing path traversal |
| 191 | // components ('..') is treated as a read error and |contents| is set to empty. |
| 192 | // In case of I/O error, |contents| holds the data that could be read from the |
| 193 | // file before the error occurred. |
| 194 | // |contents| may be NULL, in which case this function is useful for its side |
| 195 | // effect of priming the disk cache (could be used for unit tests). |
| 196 | BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents); |
| 197 | |
| 198 | // Reads the file at |path| into |contents| and returns true on success and |
| 199 | // false on error. For security reasons, a |path| containing path traversal |
| 200 | // components ('..') is treated as a read error and |contents| is set to empty. |
| 201 | // In case of I/O error, |contents| holds the data that could be read from the |
| 202 | // file before the error occurred. When the file size exceeds |max_size|, the |
| 203 | // function returns false with |contents| holding the file truncated to |
| 204 | // |max_size|. |
| 205 | // |contents| may be NULL, in which case this function is useful for its side |
| 206 | // effect of priming the disk cache (could be used for unit tests). |
hashimoto | 6da2fef | 2016-02-24 03:39:58 | [diff] [blame] | 207 | BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path, |
| 208 | std::string* contents, |
| 209 | size_t max_size); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 210 | |
Greg Thompson | 3f7e20f4 | 2020-05-02 19:01:11 | [diff] [blame] | 211 | // As ReadFileToString, but reading from an open stream after seeking to its |
| 212 | // start (if supported by the stream). |
| 213 | BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents); |
| 214 | |
| 215 | // As ReadFileToStringWithMaxSize, but reading from an open stream after seeking |
| 216 | // to its start (if supported by the stream). |
| 217 | BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream, |
| 218 | size_t max_size, |
| 219 | std::string* contents); |
| 220 | |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 221 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 222 | |
| 223 | // Read exactly |bytes| bytes from file descriptor |fd|, storing the result |
| 224 | // in |buffer|. This function is protected against EINTR and partial reads. |
| 225 | // Returns true iff |bytes| bytes have been successfully read from |fd|. |
| 226 | BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes); |
| 227 | |
Greg Thompson | f75f5fb | 2020-04-30 08:13:25 | [diff] [blame] | 228 | // Performs the same function as CreateAndOpenTemporaryStreamInDir(), but |
| 229 | // returns the file-descriptor wrapped in a ScopedFD, rather than the stream |
| 230 | // wrapped in a ScopedFILE. |
Lei Zhang | d22c973 | 2019-08-02 16:31:38 | [diff] [blame] | 231 | BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir, |
| 232 | FilePath* path); |
Wez | 45a7b30 | 2018-02-22 22:42:39 | [diff] [blame] | 233 | |
Lei Zhang | d22c973 | 2019-08-02 16:31:38 | [diff] [blame] | 234 | #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 235 | |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 236 | #if defined(OS_POSIX) |
Kevin Marshall | a9f05ec | 2017-07-14 02:10:05 | [diff] [blame] | 237 | |
Brian Geffon | 49ddbf0 | 2020-06-19 22:57:56 | [diff] [blame] | 238 | // ReadFileToStringNonBlocking is identical to ReadFileToString except it |
| 239 | // guarantees that it will not block. This guarantee is provided on POSIX by |
| 240 | // opening the file as O_NONBLOCK. This variant should only be used on files |
| 241 | // which are guaranteed not to block (such as kernel files). Or in situations |
| 242 | // where a partial read would be acceptable because the backing store returned |
| 243 | // EWOULDBLOCK. |
| 244 | BASE_EXPORT bool ReadFileToStringNonBlocking(const base::FilePath& file, |
| 245 | std::string* ret); |
| 246 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 247 | // Creates a symbolic link at |symlink| pointing to |target|. Returns |
| 248 | // false on failure. |
| 249 | BASE_EXPORT bool CreateSymbolicLink(const FilePath& target, |
| 250 | const FilePath& symlink); |
| 251 | |
| 252 | // Reads the given |symlink| and returns where it points to in |target|. |
| 253 | // Returns false upon failure. |
| 254 | BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target); |
| 255 | |
| 256 | // Bits and masks of the file permission. |
| 257 | enum FilePermissionBits { |
| 258 | FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO, |
| 259 | FILE_PERMISSION_USER_MASK = S_IRWXU, |
| 260 | FILE_PERMISSION_GROUP_MASK = S_IRWXG, |
| 261 | FILE_PERMISSION_OTHERS_MASK = S_IRWXO, |
| 262 | |
| 263 | FILE_PERMISSION_READ_BY_USER = S_IRUSR, |
| 264 | FILE_PERMISSION_WRITE_BY_USER = S_IWUSR, |
| 265 | FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR, |
| 266 | FILE_PERMISSION_READ_BY_GROUP = S_IRGRP, |
| 267 | FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP, |
| 268 | FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP, |
| 269 | FILE_PERMISSION_READ_BY_OTHERS = S_IROTH, |
| 270 | FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH, |
| 271 | FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH, |
| 272 | }; |
| 273 | |
| 274 | // Reads the permission of the given |path|, storing the file permission |
| 275 | // bits in |mode|. If |path| is symbolic link, |mode| is the permission of |
| 276 | // a file which the symlink points to. |
| 277 | BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode); |
| 278 | // Sets the permission of the given |path|. If |path| is symbolic link, sets |
| 279 | // the permission of a file which the symlink points to. |
| 280 | BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode); |
| 281 | |
thomasanderson | 1929bb2 | 2016-06-24 02:01:00 | [diff] [blame] | 282 | // Returns true iff |executable| can be found in any directory specified by the |
| 283 | // environment variable in |env|. |
| 284 | BASE_EXPORT bool ExecutableExistsInPath(Environment* env, |
| 285 | const FilePath::StringType& executable); |
| 286 | |
Sean McAllister | 39b8d34 | 2020-08-25 09:08:32 | [diff] [blame] | 287 | #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX) |
Sergey Volk | 76166f5b | 2018-06-15 17:38:02 | [diff] [blame] | 288 | // Determine if files under a given |path| can be mapped and then mprotect'd |
| 289 | // PROT_EXEC. This depends on the mount options used for |path|, which vary |
| 290 | // among different Linux distributions and possibly local configuration. It also |
| 291 | // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm |
| 292 | // but its kernel allows mprotect with PROT_EXEC anyway. |
| 293 | BASE_EXPORT bool IsPathExecutable(const FilePath& path); |
Sean McAllister | 39b8d34 | 2020-08-25 09:08:32 | [diff] [blame] | 294 | #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX) |
Sergey Volk | 76166f5b | 2018-06-15 17:38:02 | [diff] [blame] | 295 | |
Fabrice de Gans-Riberi | 65421f6 | 2018-05-22 23:16:18 | [diff] [blame] | 296 | #endif // OS_POSIX |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 297 | |
| 298 | // Returns true if the given directory is empty |
| 299 | BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path); |
| 300 | |
| 301 | // Get the temporary directory provided by the system. |
| 302 | // |
| 303 | // WARNING: In general, you should use CreateTemporaryFile variants below |
| 304 | // instead of this function. Those variants will ensure that the proper |
| 305 | // permissions are set so that other users on the system can't edit them while |
| 306 | // they're open (which can lead to security issues). |
| 307 | BASE_EXPORT bool GetTempDir(FilePath* path); |
| 308 | |
| 309 | // Get the home directory. This is more complicated than just getenv("HOME") |
| 310 | // as it knows to fall back on getpwent() etc. |
| 311 | // |
| 312 | // You should not generally call this directly. Instead use DIR_HOME with the |
| 313 | // path service which will use this function but cache the value. |
| 314 | // Path service may also override DIR_HOME. |
| 315 | BASE_EXPORT FilePath GetHomeDir(); |
| 316 | |
Greg Thompson | 3f7e20f4 | 2020-05-02 19:01:11 | [diff] [blame] | 317 | // Returns a new temporary file in |dir| with a unique name. The file is opened |
| 318 | // for exclusive read, write, and delete access (note: exclusivity is unique to |
| 319 | // Windows). On Windows, the returned file supports File::DeleteOnClose. |
| 320 | // On success, |temp_file| is populated with the full path to the created file. |
| 321 | BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir, |
| 322 | FilePath* temp_file); |
| 323 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 324 | // Creates a temporary file. The full path is placed in |path|, and the |
| 325 | // function returns true if was successful in creating the file. The file will |
| 326 | // be empty and all handles closed after this function returns. |
| 327 | BASE_EXPORT bool CreateTemporaryFile(FilePath* path); |
| 328 | |
| 329 | // Same as CreateTemporaryFile but the file is created in |dir|. |
| 330 | BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir, |
| 331 | FilePath* temp_file); |
| 332 | |
Aidan Wolter | 3fab2a2 | 2020-12-02 20:24:35 | [diff] [blame^] | 333 | // Returns the file name for a temporary file by using a platform-specific |
| 334 | // naming scheme that incorporates |identifier|. |
| 335 | BASE_EXPORT FilePath |
| 336 | FormatTemporaryFileName(FilePath::StringPieceType identifier); |
| 337 | |
Greg Thompson | 3f7e20f4 | 2020-05-02 19:01:11 | [diff] [blame] | 338 | // Create and open a temporary file stream for exclusive read, write, and delete |
| 339 | // access (note: exclusivity is unique to Windows). The full path is placed in |
| 340 | // |path|. Returns the opened file stream, or null in case of error. |
Greg Thompson | f75f5fb | 2020-04-30 08:13:25 | [diff] [blame] | 341 | BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 342 | |
Greg Thompson | f75f5fb | 2020-04-30 08:13:25 | [diff] [blame] | 343 | // Similar to CreateAndOpenTemporaryStream, but the file is created in |dir|. |
| 344 | BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir, |
| 345 | FilePath* path); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 346 | |
| 347 | // Create a new directory. If prefix is provided, the new directory name is in |
| 348 | // the format of prefixyyyy. |
| 349 | // NOTE: prefix is ignored in the POSIX implementation. |
| 350 | // If success, return true and output the full path of the directory created. |
| 351 | BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix, |
| 352 | FilePath* new_temp_path); |
| 353 | |
| 354 | // Create a directory within another directory. |
| 355 | // Extra characters will be appended to |prefix| to ensure that the |
| 356 | // new directory does not have the same name as an existing directory. |
| 357 | BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir, |
| 358 | const FilePath::StringType& prefix, |
| 359 | FilePath* new_dir); |
| 360 | |
| 361 | // Creates a directory, as well as creating any parent directories, if they |
| 362 | // don't exist. Returns 'true' on successful creation, or if the directory |
| 363 | // already exists. The directory is only readable by the current user. |
| 364 | // Returns true on success, leaving *error unchanged. |
| 365 | // Returns false on failure and sets *error appropriately, if it is non-NULL. |
| 366 | BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path, |
| 367 | File::Error* error); |
| 368 | |
| 369 | // Backward-compatible convenience method for the above. |
| 370 | BASE_EXPORT bool CreateDirectory(const FilePath& full_path); |
| 371 | |
| 372 | // Returns the file size. Returns true on success. |
avi | 543540e | 2015-12-24 05:15:32 | [diff] [blame] | 373 | BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 374 | |
| 375 | // Sets |real_path| to |path| with symbolic links and junctions expanded. |
| 376 | // On windows, make sure the path starts with a lettered drive. |
| 377 | // |path| must reference a file. Function will fail if |path| points to |
| 378 | // a directory or to a nonexistent path. On windows, this function will |
Alex Gough | 84ee78c | 2019-06-06 22:46:23 | [diff] [blame] | 379 | // fail if |real_path| would be longer than MAX_PATH characters. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 380 | BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path); |
| 381 | |
| 382 | #if defined(OS_WIN) |
| 383 | |
| 384 | // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."), |
| 385 | // return in |drive_letter_path| the equivalent path that starts with |
| 386 | // a drive letter ("C:\..."). Return false if no such path exists. |
| 387 | BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path, |
| 388 | FilePath* drive_letter_path); |
| 389 | |
Bruce Long | c343f7e | 2019-05-11 02:20:12 | [diff] [blame] | 390 | // Method that wraps the win32 GetLongPathName API, normalizing the specified |
| 391 | // path to its long form. An example where this is needed is when comparing |
| 392 | // temp file paths. If a username isn't a valid 8.3 short file name (even just a |
| 393 | // lengthy name like "user with long name"), Windows will set the TMP and TEMP |
| 394 | // environment variables to be 8.3 paths. ::GetTempPath (called in |
| 395 | // base::GetTempDir) just uses the value specified by TMP or TEMP, and so can |
| 396 | // return a short path. Returns an empty path on error. |
| 397 | BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input); |
David Bienvenu | f863412f | 2019-12-10 21:55:16 | [diff] [blame] | 398 | |
| 399 | // Creates a hard link named |to_file| to the file |from_file|. Both paths |
| 400 | // must be on the same volume, and |from_file| may not name a directory. |
| 401 | // Returns true if the hard link is created, false if it fails. |
| 402 | BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file, |
| 403 | const FilePath& from_file); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 404 | #endif |
| 405 | |
| 406 | // This function will return if the given file is a symlink or not. |
| 407 | BASE_EXPORT bool IsLink(const FilePath& file_path); |
| 408 | |
| 409 | // Returns information about the given file path. |
| 410 | BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info); |
| 411 | |
| 412 | // Sets the time of the last access and the time of the last modification. |
| 413 | BASE_EXPORT bool TouchFile(const FilePath& path, |
| 414 | const Time& last_accessed, |
| 415 | const Time& last_modified); |
| 416 | |
grt | d0bc44f | 2017-02-13 17:52:17 | [diff] [blame] | 417 | // Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The |
| 418 | // underlying file descriptor (POSIX) or handle (Windows) is unconditionally |
| 419 | // configured to not be propagated to child processes. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 420 | BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode); |
| 421 | |
| 422 | // Closes file opened by OpenFile. Returns true on success. |
| 423 | BASE_EXPORT bool CloseFile(FILE* file); |
| 424 | |
| 425 | // Associates a standard FILE stream with an existing File. Note that this |
| 426 | // functions take ownership of the existing File. |
| 427 | BASE_EXPORT FILE* FileToFILE(File file, const char* mode); |
| 428 | |
Greg Thompson | 3f7e20f4 | 2020-05-02 19:01:11 | [diff] [blame] | 429 | // Returns a new handle to the file underlying |file_stream|. |
| 430 | BASE_EXPORT File FILEToFile(FILE* file_stream); |
| 431 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 432 | // Truncates an open file to end at the location of the current file pointer. |
| 433 | // This is a cross-platform analog to Windows' SetEndOfFile() function. |
| 434 | BASE_EXPORT bool TruncateFile(FILE* file); |
| 435 | |
| 436 | // Reads at most the given number of bytes from the file into the buffer. |
| 437 | // Returns the number of read bytes, or -1 on error. |
| 438 | BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size); |
| 439 | |
| 440 | // Writes the given buffer into the file, overwriting any data that was |
| 441 | // previously there. Returns the number of bytes written, or -1 on error. |
Andrew | 091a47b1 | 2019-12-12 00:24:00 | [diff] [blame] | 442 | // If file doesn't exist, it gets created with read/write permissions for all. |
Lei Zhang | eebbef6 | 2020-05-05 20:16:05 | [diff] [blame] | 443 | // Note that the other variants of WriteFile() below may be easier to use. |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 444 | BASE_EXPORT int WriteFile(const FilePath& filename, const char* data, |
| 445 | int size); |
| 446 | |
Lei Zhang | eebbef6 | 2020-05-05 20:16:05 | [diff] [blame] | 447 | // Writes |data| into the file, overwriting any data that was previously there. |
| 448 | // Returns true if and only if all of |data| was written. If the file does not |
| 449 | // exist, it gets created with read/write permissions for all. |
| 450 | BASE_EXPORT bool WriteFile(const FilePath& filename, span<const uint8_t> data); |
| 451 | |
| 452 | // Another WriteFile() variant that takes a StringPiece so callers don't have to |
| 453 | // do manual conversions from a char span to a uint8_t span. |
| 454 | BASE_EXPORT bool WriteFile(const FilePath& filename, StringPiece data); |
| 455 | |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 456 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
chirantan | 75ea2fd | 2014-10-07 23:15:30 | [diff] [blame] | 457 | // Appends |data| to |fd|. Does not close |fd| when done. Returns true iff |
| 458 | // |size| bytes of |data| were written to |fd|. |
| 459 | BASE_EXPORT bool WriteFileDescriptor(const int fd, const char* data, int size); |
Alex Ilin | 925adf0 | 2019-04-26 11:03:25 | [diff] [blame] | 460 | |
| 461 | // Allocates disk space for the file referred to by |fd| for the byte range |
| 462 | // starting at |offset| and continuing for |size| bytes. The file size will be |
| 463 | // changed if |offset|+|len| is greater than the file size. Zeros will fill the |
| 464 | // new space. |
| 465 | // After a successful call, subsequent writes into the specified range are |
| 466 | // guaranteed not to fail because of lack of disk space. |
| 467 | BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 468 | #endif |
| 469 | |
chirantan | 75ea2fd | 2014-10-07 23:15:30 | [diff] [blame] | 470 | // Appends |data| to |filename|. Returns true iff |size| bytes of |data| were |
| 471 | // written to |filename|. |
| 472 | BASE_EXPORT bool AppendToFile(const FilePath& filename, |
| 473 | const char* data, |
| 474 | int size); |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 475 | |
| 476 | // Gets the current working directory for the process. |
| 477 | BASE_EXPORT bool GetCurrentDirectory(FilePath* path); |
| 478 | |
| 479 | // Sets the current working directory for the process. |
| 480 | BASE_EXPORT bool SetCurrentDirectory(const FilePath& path); |
| 481 | |
Greg Thompson | b4abcb4 | 2019-08-23 01:42:56 | [diff] [blame] | 482 | // The largest value attempted by GetUniquePath{Number,}. |
| 483 | enum { kMaxUniqueFiles = 100 }; |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 484 | |
Greg Thompson | b4abcb4 | 2019-08-23 01:42:56 | [diff] [blame] | 485 | // Returns the number N that makes |path| unique when formatted as " (N)" in a |
| 486 | // suffix to its basename before any file extension, where N is a number between |
| 487 | // 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is |
| 488 | // unique as-is), or -1 if no such number can be found. |
| 489 | BASE_EXPORT int GetUniquePathNumber(const FilePath& path); |
| 490 | |
| 491 | // Returns |path| if it does not exist. Otherwise, returns |path| with the |
| 492 | // suffix " (N)" appended to its basename before any file extension, where N is |
| 493 | // a number between 1 and 100 (inclusive). Returns an empty path if no such |
| 494 | // number can be found. |
Bruce Long | d096e489 | 2019-02-28 17:50:00 | [diff] [blame] | 495 | BASE_EXPORT FilePath GetUniquePath(const FilePath& path); |
| 496 | |
tfarina | 060df7e | 2015-12-16 05:15:32 | [diff] [blame] | 497 | // Sets the given |fd| to non-blocking mode. |
| 498 | // Returns true if it was able to set it in the non-blocking mode, otherwise |
| 499 | // false. |
| 500 | BASE_EXPORT bool SetNonBlocking(int fd); |
| 501 | |
Jesse McKenna | 768f3be | 2020-06-26 02:30:26 | [diff] [blame] | 502 | // Possible results of PreReadFile(). |
| 503 | // These values are persisted to logs. Entries should not be renumbered and |
| 504 | // numeric values should never be reused. |
| 505 | enum class PrefetchResultCode { |
| 506 | kSuccess = 0, |
| 507 | kInvalidFile = 1, |
| 508 | kSlowSuccess = 2, |
| 509 | kSlowFailed = 3, |
| 510 | kMemoryMapFailedSlowUsed = 4, |
| 511 | kMemoryMapFailedSlowFailed = 5, |
| 512 | kFastFailed = 6, |
| 513 | kFastFailedSlowUsed = 7, |
| 514 | kFastFailedSlowFailed = 8, |
| 515 | kMaxValue = kFastFailedSlowFailed |
| 516 | }; |
| 517 | |
| 518 | struct PrefetchResult { |
| 519 | bool succeeded() const { |
| 520 | return code_ == PrefetchResultCode::kSuccess || |
| 521 | code_ == PrefetchResultCode::kSlowSuccess; |
| 522 | } |
| 523 | const PrefetchResultCode code_; |
| 524 | }; |
| 525 | |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 526 | // Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache. |
| 527 | // |
| 528 | // If called at the appropriate time, this can reduce the latency incurred by |
| 529 | // feature code that needs to read the file. |
| 530 | // |
| 531 | // |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the |
| 532 | // file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient |
| 533 | // way to get the entire file pre-fetched. |
| 534 | // |
| 535 | // |is_executable| specifies whether the file is to be prefetched as |
| 536 | // executable code or as data. Windows treats the file backed pages in RAM |
| 537 | // differently, and specifying the wrong value results in two copies in RAM. |
| 538 | // |
Jesse McKenna | 768f3be | 2020-06-26 02:30:26 | [diff] [blame] | 539 | // Returns a PrefetchResult indicating whether prefetch succeeded, and the type |
| 540 | // of failure if it did not. A return value of kSuccess does not guarantee that |
| 541 | // the entire desired range was prefetched. |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 542 | // |
| 543 | // Calling this before using ::LoadLibrary() on Windows is more efficient memory |
| 544 | // wise, but we must be sure no other threads try to LoadLibrary() the file |
| 545 | // while we are doing the mapping and prefetching, or the process will get a |
| 546 | // private copy of the DLL via COW. |
Jesse McKenna | 768f3be | 2020-06-26 02:30:26 | [diff] [blame] | 547 | BASE_EXPORT PrefetchResult |
| 548 | PreReadFile(const FilePath& file_path, |
| 549 | bool is_executable, |
| 550 | int64_t max_bytes = std::numeric_limits<int64_t>::max()); |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 551 | |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 552 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
Nick Diego Yamane | 61bf28ba | 2019-03-19 14:56:37 | [diff] [blame] | 553 | |
| 554 | // Creates a pipe. Returns true on success, otherwise false. |
| 555 | // On success, |read_fd| will be set to the fd of the read side, and |
| 556 | // |write_fd| will be set to the one of write side. If |non_blocking| |
| 557 | // is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set |
| 558 | // otherwise flag is set to zero (default). |
| 559 | BASE_EXPORT bool CreatePipe(ScopedFD* read_fd, |
| 560 | ScopedFD* write_fd, |
| 561 | bool non_blocking = false); |
| 562 | |
lhchavez | 80c77bfd | 2016-10-08 00:50:53 | [diff] [blame] | 563 | // Creates a non-blocking, close-on-exec pipe. |
| 564 | // This creates a non-blocking pipe that is not intended to be shared with any |
| 565 | // child process. This will be done atomically if the operating system supports |
| 566 | // it. Returns true if it was able to create the pipe, otherwise false. |
| 567 | BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]); |
| 568 | |
| 569 | // Sets the given |fd| to close-on-exec mode. |
| 570 | // Returns true if it was able to set it in the close-on-exec mode, otherwise |
| 571 | // false. |
| 572 | BASE_EXPORT bool SetCloseOnExec(int fd); |
| 573 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 574 | // Test that |path| can only be changed by a given user and members of |
| 575 | // a given set of groups. |
| 576 | // Specifically, test that all parts of |path| under (and including) |base|: |
| 577 | // * Exist. |
| 578 | // * Are owned by a specific user. |
| 579 | // * Are not writable by all users. |
| 580 | // * Are owned by a member of a given set of groups, or are not writable by |
| 581 | // their group. |
| 582 | // * Are not symbolic links. |
| 583 | // This is useful for checking that a config file is administrator-controlled. |
| 584 | // |base| must contain |path|. |
| 585 | BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base, |
| 586 | const base::FilePath& path, |
| 587 | uid_t owner_uid, |
| 588 | const std::set<gid_t>& group_gids); |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 589 | #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 590 | |
Avi Drissman | 5b28637 | 2020-07-28 21:59:38 | [diff] [blame] | 591 | #if defined(OS_MAC) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 592 | // Is |path| writable only by a user with administrator privileges? |
| 593 | // This function uses Mac OS conventions. The super user is assumed to have |
| 594 | // uid 0, and the administrator group is assumed to be named "admin". |
| 595 | // Testing that |path|, and every parent directory including the root of |
| 596 | // the filesystem, are owned by the superuser, controlled by the group |
| 597 | // "admin", are not writable by all users, and contain no symbolic links. |
| 598 | // Will return false if |path| does not exist. |
| 599 | BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path); |
Avi Drissman | 5b28637 | 2020-07-28 21:59:38 | [diff] [blame] | 600 | #endif // defined(OS_MAC) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 601 | |
| 602 | // Returns the maximum length of path component on the volume containing |
| 603 | // the directory |path|, in the number of FilePath::CharType, or -1 on failure. |
| 604 | BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path); |
| 605 | |
Sean McAllister | 39b8d34 | 2020-08-25 09:08:32 | [diff] [blame] | 606 | #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_AIX) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 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 |
| 612 | FILE_SYSTEM_NFS, |
| 613 | FILE_SYSTEM_SMB, |
| 614 | FILE_SYSTEM_CODA, |
| 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 |
| 619 | }; |
| 620 | |
| 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); |
| 624 | #endif |
| 625 | |
Fabrice de Gans-Riberi | 306871de | 2018-05-16 19:38:39 | [diff] [blame] | 626 | #if defined(OS_POSIX) || defined(OS_FUCHSIA) |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 627 | // Get a temporary directory for shared memory files. The directory may depend |
| 628 | // on whether the destination is intended for executable files, which in turn |
| 629 | // depends on how /dev/shmem was mounted. As a result, you must supply whether |
| 630 | // you intend to create executable shmem segments so this function can find |
| 631 | // an appropriate location. |
| 632 | BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path); |
| 633 | #endif |
| 634 | |
| 635 | // Internal -------------------------------------------------------------------- |
| 636 | |
| 637 | namespace internal { |
| 638 | |
| 639 | // Same as Move but allows paths with traversal components. |
| 640 | // Use only with extreme care. |
| 641 | BASE_EXPORT bool MoveUnsafe(const FilePath& from_path, |
| 642 | const FilePath& to_path); |
| 643 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 644 | #if defined(OS_WIN) |
| 645 | // Copy from_path to to_path recursively and then delete from_path recursively. |
| 646 | // Returns true if all operations succeed. |
| 647 | // This function simulates Move(), but unlike Move() it works across volumes. |
| 648 | // This function is not transactional. |
| 649 | BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path, |
| 650 | const FilePath& to_path); |
| 651 | #endif // defined(OS_WIN) |
| 652 | |
Victor Costan | b5a0a9700 | 2019-09-08 04:55:15 | [diff] [blame] | 653 | // Used by PreReadFile() when no kernel support for prefetching is available. |
| 654 | bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes); |
| 655 | |
[email protected] | e3177dd5 | 2014-08-13 20:22:14 | [diff] [blame] | 656 | } // namespace internal |
| 657 | } // namespace base |
| 658 | |
| 659 | #endif // BASE_FILES_FILE_UTIL_H_ |