1 // Copyright 2012 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_FILES_FILE_H_ 6 #define BASE_FILES_FILE_H_ 7 8 #include <stdint.h> 9 10 #include <optional> 11 #include <string> 12 13 #include "base/base_export.h" 14 #include "base/compiler_specific.h" 15 #include "base/containers/span.h" 16 #include "base/files/file_path.h" 17 #include "base/files/file_tracing.h" 18 #include "base/files/platform_file.h" 19 #include "base/time/time.h" 20 #include "base/trace_event/base_tracing_forward.h" 21 #include "build/build_config.h" 22 23 struct stat; 24 25 namespace base { 26 27 using stat_wrapper_t = struct stat; 28 29 // Thin wrapper around an OS-level file. 30 // Note that this class does not provide any support for asynchronous IO, other 31 // than the ability to create asynchronous handles on Windows. 32 // 33 // Note about const: this class does not attempt to determine if the underlying 34 // file system object is affected by a particular method in order to consider 35 // that method const or not. Only methods that deal with member variables in an 36 // obvious non-modifying way are marked as const. Any method that forward calls 37 // to the OS is not considered const, even if there is no apparent change to 38 // member variables. 39 // 40 // On POSIX, if the given file is a symbolic link, most of the methods apply to 41 // the file that the symbolic link resolves to. 42 class BASE_EXPORT File { 43 public: 44 // FLAG_(OPEN|CREATE).* are mutually exclusive. You should specify exactly one 45 // of the five (possibly combining with other flags) when opening or creating 46 // a file. 47 // FLAG_(WRITE|APPEND) are mutually exclusive. This is so that APPEND behavior 48 // will be consistent with O_APPEND on POSIX. 49 enum Flags : uint32_t { 50 FLAG_OPEN = 1 << 0, // Opens a file, only if it exists. 51 FLAG_CREATE = 1 << 1, // Creates a new file, only if it does not 52 // already exist. 53 FLAG_OPEN_ALWAYS = 1 << 2, // May create a new file. 54 FLAG_CREATE_ALWAYS = 1 << 3, // May overwrite an old file. 55 FLAG_OPEN_TRUNCATED = 1 << 4, // Opens a file and truncates it, only if it 56 // exists. 57 FLAG_READ = 1 << 5, 58 FLAG_WRITE = 1 << 6, 59 FLAG_APPEND = 1 << 7, 60 FLAG_WIN_EXCLUSIVE_READ = 1 << 8, // Windows only. Opposite of SHARE. 61 FLAG_WIN_EXCLUSIVE_WRITE = 1 << 9, // Windows only. Opposite of SHARE. 62 FLAG_ASYNC = 1 << 10, 63 FLAG_WIN_TEMPORARY = 1 << 11, // Windows only. 64 FLAG_WIN_HIDDEN = 1 << 12, // Windows only. 65 FLAG_DELETE_ON_CLOSE = 1 << 13, 66 FLAG_WRITE_ATTRIBUTES = 1 << 14, // File opened in a mode allowing writing 67 // attributes, such as with SetTimes(). 68 FLAG_WIN_SHARE_DELETE = 1 << 15, // Windows only. 69 FLAG_TERMINAL_DEVICE = 1 << 16, // Serial port flags. 70 FLAG_WIN_BACKUP_SEMANTICS = 1 << 17, // Windows only. 71 FLAG_WIN_EXECUTE = 1 << 18, // Windows only. 72 FLAG_WIN_SEQUENTIAL_SCAN = 1 << 19, // Windows only. 73 FLAG_CAN_DELETE_ON_CLOSE = 1 << 20, // Requests permission to delete a file 74 // via DeleteOnClose() (Windows only). 75 // See DeleteOnClose() for details. 76 FLAG_WIN_NO_EXECUTE = 77 1 << 21, // Windows only. Marks the file with a deny ACE that prevents 78 // opening the file with EXECUTE access. Cannot be used with 79 // FILE_WIN_EXECUTE flag. See also PreventExecuteMapping. 80 }; 81 82 // This enum has been recorded in multiple histograms using PlatformFileError 83 // enum. If the order of the fields needs to change, please ensure that those 84 // histograms are obsolete or have been moved to a different enum. 85 // 86 // FILE_ERROR_ACCESS_DENIED is returned when a call fails because of a 87 // filesystem restriction. FILE_ERROR_SECURITY is returned when a browser 88 // policy doesn't allow the operation to be executed. 89 enum Error { 90 FILE_OK = 0, 91 FILE_ERROR_FAILED = -1, 92 FILE_ERROR_IN_USE = -2, 93 FILE_ERROR_EXISTS = -3, 94 FILE_ERROR_NOT_FOUND = -4, 95 FILE_ERROR_ACCESS_DENIED = -5, 96 FILE_ERROR_TOO_MANY_OPENED = -6, 97 FILE_ERROR_NO_MEMORY = -7, 98 FILE_ERROR_NO_SPACE = -8, 99 FILE_ERROR_NOT_A_DIRECTORY = -9, 100 FILE_ERROR_INVALID_OPERATION = -10, 101 FILE_ERROR_SECURITY = -11, 102 FILE_ERROR_ABORT = -12, 103 FILE_ERROR_NOT_A_FILE = -13, 104 FILE_ERROR_NOT_EMPTY = -14, 105 FILE_ERROR_INVALID_URL = -15, 106 FILE_ERROR_IO = -16, 107 // Put new entries here and increment FILE_ERROR_MAX. 108 FILE_ERROR_MAX = -17 109 }; 110 111 // This explicit mapping matches both FILE_ on Windows and SEEK_ on Linux. 112 enum Whence { 113 FROM_BEGIN = 0, 114 FROM_CURRENT = 1, 115 FROM_END = 2 116 }; 117 118 // Used to hold information about a given file. 119 // If you add more fields to this structure (platform-specific fields are OK), 120 // make sure to update all functions that use it in file_util_{win|posix}.cc, 121 // too, and the ParamTraits<base::File::Info> implementation in 122 // ipc/ipc_message_utils.cc. 123 struct BASE_EXPORT Info { 124 Info(); 125 ~Info(); 126 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) 127 // Fills this struct with values from |stat_info|. 128 void FromStat(const stat_wrapper_t& stat_info); 129 #endif 130 131 // The size of the file in bytes. Undefined when is_directory is true. 132 int64_t size = 0; 133 134 // True if the file corresponds to a directory. 135 bool is_directory = false; 136 137 // True if the file corresponds to a symbolic link. For Windows currently 138 // not supported and thus always false. 139 bool is_symbolic_link = false; 140 141 // The last modified time of a file. 142 Time last_modified; 143 144 // The last accessed time of a file. 145 Time last_accessed; 146 147 // The creation time of a file. 148 Time creation_time; 149 }; 150 151 File(); 152 153 // Creates or opens the given file. This will fail with 'access denied' if the 154 // |path| contains path traversal ('..') components. 155 File(const FilePath& path, uint32_t flags); 156 157 // Takes ownership of |platform_file| and sets async to false. 158 explicit File(ScopedPlatformFile platform_file); 159 explicit File(PlatformFile platform_file); 160 161 // Takes ownership of |platform_file| and sets async to the given value. 162 // This constructor exists because on Windows you can't check if platform_file 163 // is async or not. 164 File(ScopedPlatformFile platform_file, bool async); 165 File(PlatformFile platform_file, bool async); 166 167 // Creates an object with a specific error_details code. 168 explicit File(Error error_details); 169 170 File(File&& other); 171 172 File(const File&) = delete; 173 File& operator=(const File&) = delete; 174 175 ~File(); 176 177 File& operator=(File&& other); 178 179 // Creates or opens the given file. 180 void Initialize(const FilePath& path, uint32_t flags); 181 182 // Returns |true| if the handle / fd wrapped by this object is valid. This 183 // method doesn't interact with the file system and is thus safe to be called 184 // from threads that disallow blocking. 185 bool IsValid() const; 186 187 // Returns true if a new file was created (or an old one truncated to zero 188 // length to simulate a new file, which can happen with 189 // FLAG_CREATE_ALWAYS), and false otherwise. created()190 bool created() const { return created_; } 191 192 // Returns the OS result of opening this file. Note that the way to verify 193 // the success of the operation is to use IsValid(), not this method: 194 // File file(path, flags); 195 // if (!file.IsValid()) 196 // return; error_details()197 Error error_details() const { return error_details_; } 198 199 PlatformFile GetPlatformFile() const; 200 PlatformFile TakePlatformFile(); 201 202 // Destroying this object closes the file automatically. 203 void Close(); 204 205 // Changes current position in the file to an |offset| relative to an origin 206 // defined by |whence|. Returns the resultant current position in the file 207 // (relative to the start) or -1 in case of error. 208 int64_t Seek(Whence whence, int64_t offset); 209 210 // Simplified versions of Read() and friends (see below) that check the 211 // return value and just return a boolean. They return true if and only if 212 // the function read in exactly |data.size()| bytes of data. 213 bool ReadAndCheck(int64_t offset, span<uint8_t> data); 214 bool ReadAtCurrentPosAndCheck(span<uint8_t> data); 215 216 // Reads the given number of bytes (or until EOF is reached) starting with the 217 // given offset. Returns the number of bytes read, or -1 on error. Note that 218 // this function makes a best effort to read all data on all platforms, so it 219 // is not intended for stream oriented files but instead for cases when the 220 // normal expectation is that actually |size| bytes are read unless there is 221 // an error. 222 UNSAFE_BUFFER_USAGE int Read(int64_t offset, char* data, int size); 223 std::optional<size_t> Read(int64_t offset, base::span<uint8_t> data); 224 225 // Same as above but without seek. 226 UNSAFE_BUFFER_USAGE int ReadAtCurrentPos(char* data, int size); 227 std::optional<size_t> ReadAtCurrentPos(base::span<uint8_t> data); 228 229 // Reads the given number of bytes (or until EOF is reached) starting with the 230 // given offset, but does not make any effort to read all data on all 231 // platforms. Returns the number of bytes read, or -1/std::nullopt on error. 232 UNSAFE_BUFFER_USAGE int ReadNoBestEffort(int64_t offset, 233 char* data, 234 int size); 235 std::optional<size_t> ReadNoBestEffort(int64_t offset, 236 base::span<uint8_t> data); 237 238 // Same as above but without seek. 239 UNSAFE_BUFFER_USAGE int ReadAtCurrentPosNoBestEffort(char* data, int size); 240 std::optional<size_t> ReadAtCurrentPosNoBestEffort(base::span<uint8_t> data); 241 242 // Simplified versions of Write() and friends (see below) that check the 243 // return value and just return a boolean. They return true if and only if 244 // the function wrote out exactly |data.size()| bytes of data. 245 bool WriteAndCheck(int64_t offset, span<const uint8_t> data); 246 bool WriteAtCurrentPosAndCheck(span<const uint8_t> data); 247 248 // Writes the given buffer into the file at the given offset, overwritting any 249 // data that was previously there. Returns the number of bytes written, or -1 250 // on error. Note that this function makes a best effort to write all data on 251 // all platforms. |data| can be nullptr when |size| is 0. 252 // Ignores the offset and writes to the end of the file if the file was opened 253 // with FLAG_APPEND. 254 UNSAFE_BUFFER_USAGE int Write(int64_t offset, const char* data, int size); 255 std::optional<size_t> Write(int64_t offset, base::span<const uint8_t> data); 256 257 // Save as above but without seek. 258 UNSAFE_BUFFER_USAGE int WriteAtCurrentPos(const char* data, int size); 259 std::optional<size_t> WriteAtCurrentPos(base::span<const uint8_t> data); 260 261 // Save as above but does not make any effort to write all data on all 262 // platforms. Returns the number of bytes written, or -1/std::nullopt 263 // on error. 264 UNSAFE_BUFFER_USAGE int WriteAtCurrentPosNoBestEffort(const char* data, 265 int size); 266 std::optional<size_t> WriteAtCurrentPosNoBestEffort( 267 base::span<const uint8_t> data); 268 269 // Returns the current size of this file, or a negative number on failure. 270 int64_t GetLength() const; 271 272 // Truncates the file to the given length. If |length| is greater than the 273 // current size of the file, the file is extended with zeros. If the file 274 // doesn't exist, |false| is returned. 275 bool SetLength(int64_t length); 276 277 // Instructs the filesystem to flush the file to disk. (POSIX: fsync, Windows: 278 // FlushFileBuffers). 279 // Calling Flush() does not guarantee file integrity and thus is not a valid 280 // substitute for file integrity checks and recovery codepaths for malformed 281 // files. It can also be *really* slow, so avoid blocking on Flush(), 282 // especially please don't block shutdown on Flush(). 283 // Latency percentiles of Flush() across all platforms as of July 2016: 284 // 50 % > 5 ms 285 // 10 % > 58 ms 286 // 1 % > 357 ms 287 // 0.1 % > 1.8 seconds 288 // 0.01 % > 7.6 seconds 289 bool Flush(); 290 291 // Updates the file times. 292 bool SetTimes(Time last_access_time, Time last_modified_time); 293 294 // Returns some basic information for the given file. 295 bool GetInfo(Info* info) const; 296 297 #if !BUILDFLAG( \ 298 IS_FUCHSIA) // Fuchsia's POSIX API does not support file locking. 299 enum class LockMode { 300 kShared, 301 kExclusive, 302 }; 303 304 // Attempts to take an exclusive write lock on the file. Returns immediately 305 // (i.e. does not wait for another process to unlock the file). If the lock 306 // was obtained, the result will be FILE_OK. A lock only guarantees 307 // that other processes may not also take a lock on the same file with the 308 // same API - it may still be opened, renamed, unlinked, etc. 309 // 310 // Common semantics: 311 // * Locks are held by processes, but not inherited by child processes. 312 // * Locks are released by the OS on file close or process termination. 313 // * Locks are reliable only on local filesystems. 314 // * Duplicated file handles may also write to locked files. 315 // Windows-specific semantics: 316 // * Locks are mandatory for read/write APIs, advisory for mapping APIs. 317 // * Within a process, locking the same file (by the same or new handle) 318 // will fail. 319 // POSIX-specific semantics: 320 // * Locks are advisory only. 321 // * Within a process, locking the same file (by the same or new handle) 322 // will succeed. The new lock replaces the old lock. 323 // * Closing any descriptor on a given file releases the lock. 324 Error Lock(LockMode mode); 325 326 // Unlock a file previously locked. 327 Error Unlock(); 328 329 #endif // !BUILDFLAG(IS_FUCHSIA) 330 331 // Returns a new object referencing this file for use within the current 332 // process. Handling of FLAG_DELETE_ON_CLOSE varies by OS. On POSIX, the File 333 // object that was created or initialized with this flag will have unlinked 334 // the underlying file when it was created or opened. On Windows, the 335 // underlying file is deleted when the last handle to it is closed. 336 File Duplicate() const; 337 async()338 bool async() const { return async_; } 339 340 // Serialise this object into a trace. 341 void WriteIntoTrace(perfetto::TracedValue context) const; 342 343 #if BUILDFLAG(IS_APPLE) 344 // Initializes experiments. Must be invoked early in process startup, but 345 // after `FeatureList` initialization. 346 static void InitializeFeatures(); 347 #endif // BUILDFLAG(IS_APPLE) 348 349 #if BUILDFLAG(IS_WIN) 350 // Sets or clears the DeleteFile disposition on the file. Returns true if 351 // the disposition was set or cleared, as indicated by |delete_on_close|. 352 // 353 // Microsoft Windows deletes a file only when the DeleteFile disposition is 354 // set on a file when the last handle to the last underlying kernel File 355 // object is closed. This disposition is be set by: 356 // - Calling the Win32 DeleteFile function with the path to a file. 357 // - Opening/creating a file with FLAG_DELETE_ON_CLOSE and then closing all 358 // handles to that File object. 359 // - Opening/creating a file with FLAG_CAN_DELETE_ON_CLOSE and subsequently 360 // calling DeleteOnClose(true). 361 // 362 // In all cases, all pre-existing handles to the file must have been opened 363 // with FLAG_WIN_SHARE_DELETE. Once the disposition has been set by any of the 364 // above means, no new File objects can be created for the file. 365 // 366 // So: 367 // - Use FLAG_WIN_SHARE_DELETE when creating/opening a file to allow another 368 // entity on the system to cause it to be deleted when it is closed. (Note: 369 // another entity can delete the file the moment after it is closed, so not 370 // using this permission doesn't provide any protections.) 371 // - Use FLAG_DELETE_ON_CLOSE for any file that is to be deleted after use. 372 // The OS will ensure it is deleted even in the face of process termination. 373 // Note that it's possible for deletion to be cancelled via another File 374 // object referencing the same file using DeleteOnClose(false) to clear the 375 // DeleteFile disposition after the original File is closed. 376 // - Use FLAG_CAN_DELETE_ON_CLOSE in conjunction with DeleteOnClose() to alter 377 // the DeleteFile disposition on an open handle. This fine-grained control 378 // allows for marking a file for deletion during processing so that it is 379 // deleted in the event of untimely process termination, and then clearing 380 // this state once the file is suitable for persistence. 381 bool DeleteOnClose(bool delete_on_close); 382 383 // Precondition: last_error is not 0, also known as ERROR_SUCCESS. 384 static Error OSErrorToFileError(DWORD last_error); 385 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) 386 // Precondition: saved_errno is not 0. 387 static Error OSErrorToFileError(int saved_errno); 388 #endif 389 390 // Gets the last global error (errno or GetLastError()) and converts it to the 391 // closest base::File::Error equivalent via OSErrorToFileError(). It should 392 // therefore only be called immediately after another base::File method fails. 393 // base::File never resets the global error to zero. 394 static Error GetLastFileError(); 395 396 // Converts an error value to a human-readable form. Used for logging. 397 static std::string ErrorToString(Error error); 398 399 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) 400 // Wrapper for stat(). 401 static int Stat(const FilePath& path, stat_wrapper_t* sb); 402 // Wrapper for fstat(). 403 static int Fstat(int fd, stat_wrapper_t* sb); 404 // Wrapper for lstat(). 405 static int Lstat(const FilePath& path, stat_wrapper_t* sb); 406 #endif 407 408 // This function can be used to augment `flags` with the correct flags 409 // required to create a File that can be safely passed to an untrusted 410 // process. It must be called if the File is intended to be transferred to an 411 // untrusted process, but can still be safely called even if the File is not 412 // intended to be transferred. AddFlagsForPassingToUntrustedProcess(uint32_t flags)413 static constexpr uint32_t AddFlagsForPassingToUntrustedProcess( 414 uint32_t flags) { 415 if (flags & File::FLAG_WRITE || flags & File::FLAG_APPEND || 416 flags & File::FLAG_WRITE_ATTRIBUTES) { 417 flags |= File::FLAG_WIN_NO_EXECUTE; 418 } 419 return flags; 420 } 421 422 private: 423 friend class FileTracing::ScopedTrace; 424 425 // Creates or opens the given file. Only called if |path| has no 426 // traversal ('..') components. 427 void DoInitialize(const FilePath& path, uint32_t flags); 428 429 void SetPlatformFile(PlatformFile file); 430 431 ScopedPlatformFile file_; 432 433 // Platform path to `file_`. Set if `this` wraps a file from an Android 434 // content provider (i.e. a content URI) or if tracing is enabled in 435 // `Initialize()`. 436 FilePath path_; 437 438 // Object tied to the lifetime of |this| that enables/disables tracing. 439 FileTracing::ScopedEnabler trace_enabler_; 440 441 Error error_details_ = FILE_ERROR_FAILED; 442 bool created_ = false; 443 bool async_ = false; 444 }; 445 446 } // namespace base 447 448 #endif // BASE_FILES_FILE_H_ 449