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