xref: /aosp_15_r20/external/cronet/base/files/file_util.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 // 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 <limits>
16 #include <optional>
17 #include <set>
18 #include <string>
19 
20 #include "base/base_export.h"
21 #include "base/containers/span.h"
22 #include "base/files/file.h"
23 #include "base/files/file_path.h"
24 #include "base/files/scoped_file.h"
25 #include "base/functional/callback.h"
26 #include "base/types/pass_key.h"
27 #include "build/build_config.h"
28 
29 #if BUILDFLAG(IS_WIN)
30 #include "base/win/windows_types.h"
31 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
32 #include <sys/stat.h>
33 #include <unistd.h>
34 #include "base/posix/eintr_wrapper.h"
35 #endif
36 
37 namespace content::internal {
38 class ChildProcessLauncherHelper;
39 }  // namespace content::internal
40 
41 namespace base {
42 
43 class Environment;
44 class Time;
45 
46 #if BUILDFLAG(IS_WIN)
47 class PreventExecuteMappingClasses {
48  public:
49   using PassKey = base::PassKey<PreventExecuteMappingClasses>;
50 
51  private:
GetPassKey()52   static PassKey GetPassKey() { return PassKey(); }
53 
54   // Allowed to open log files in arbitrary locations.
55   friend class content::internal::ChildProcessLauncherHelper;
56 };
57 #endif
58 
59 //-----------------------------------------------------------------------------
60 // Functions that involve filesystem access or modification:
61 
62 // Returns an absolute version of a relative path. Returns an empty path on
63 // error. This function can result in I/O so it can be slow.
64 //
65 // On POSIX, this function calls realpath(), so:
66 // 1) it fails if the path does not exist.
67 // 2) it expands all symlink components of the path.
68 // 3) it removes "." and ".." directory components.
69 BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
70 
71 #if BUILDFLAG(IS_POSIX)
72 // Prepends the current working directory if `input` is not already absolute,
73 // and removes "/./" and "/../" This is similar to MakeAbsoluteFilePath(), but
74 // MakeAbsoluteFilePath() expands all symlinks in the path and this does not.
75 //
76 // This may block if `input` is a relative path, when calling
77 // GetCurrentDirectory().
78 //
79 // This doesn't return std::nullopt unless (1) `input` is empty, or (2)
80 // `input` is a relative path and GetCurrentDirectory() fails.
81 [[nodiscard]] BASE_EXPORT std::optional<FilePath>
82 MakeAbsoluteFilePathNoResolveSymbolicLinks(const FilePath& input);
83 #endif
84 
85 // Returns the total number of bytes used by all the files under |root_path|.
86 // If the path does not exist the function returns 0.
87 //
88 // This function is implemented using the FileEnumerator class so it is not
89 // particularly speedy on any platform.
90 BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
91 
92 // Deletes the given path, whether it's a file or a directory.
93 // If it's a directory, it's perfectly happy to delete all of the directory's
94 // contents, but it will not recursively delete subdirectories and their
95 // contents.
96 // Returns true if successful, false otherwise. It is considered successful to
97 // attempt to delete a file that does not exist.
98 //
99 // In POSIX environment and if |path| is a symbolic link, this deletes only
100 // the symlink. (even if the symlink points to a non-existent file)
101 BASE_EXPORT bool DeleteFile(const FilePath& path);
102 
103 // Deletes the given path, whether it's a file or a directory.
104 // If it's a directory, it's perfectly happy to delete all of the
105 // directory's contents, including subdirectories and their contents.
106 // Returns true if successful, false otherwise. It is considered successful
107 // to attempt to delete a file that does not exist.
108 //
109 // In POSIX environment and if |path| is a symbolic link, this deletes only
110 // the symlink. (even if the symlink points to a non-existent file)
111 //
112 // WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION.
113 BASE_EXPORT bool DeletePathRecursively(const FilePath& path);
114 
115 // Returns a closure that, when run on any sequence that allows blocking calls,
116 // will kick off a potentially asynchronous operation to delete `path`, whose
117 // behavior is similar to `DeleteFile()` and `DeletePathRecursively()`
118 // respectively.
119 //
120 // In contrast to `DeleteFile()` and `DeletePathRecursively()`, the thread pool
121 // may be used in case retries are needed. On Windows, in particular, retries
122 // will be attempted for some time to allow other programs (e.g., anti-virus
123 // scanners or malware) to close any open handles to `path` or its contents. If
124 // `reply_callback` is not null, it will be posted to the caller's sequence with
125 // true if `path` was fully deleted or false otherwise.
126 //
127 // WARNING: It is NOT safe to use `path` until `reply_callback` is run, as the
128 // retry task may still be actively trying to delete it.
129 BASE_EXPORT OnceClosure
130 GetDeleteFileCallback(const FilePath& path,
131                       OnceCallback<void(bool)> reply_callback = {});
132 BASE_EXPORT OnceClosure
133 GetDeletePathRecursivelyCallback(const FilePath& path,
134                                  OnceCallback<void(bool)> reply_callback = {});
135 
136 #if BUILDFLAG(IS_WIN)
137 // Schedules to delete the given path, whether it's a file or a directory, until
138 // the operating system is restarted.
139 // Note:
140 // 1) The file/directory to be deleted should exist in a temp folder.
141 // 2) The directory to be deleted must be empty.
142 BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
143 
144 // Prevents opening the file at `path` with EXECUTE access by adding a deny ACE
145 // on the filesystem. This allows the file handle to be safely passed to an
146 // untrusted process. See also `File::FLAG_WIN_NO_EXECUTE`.
147 BASE_EXPORT bool PreventExecuteMapping(const FilePath& path);
148 
149 // Same as PreventExecuteMapping but DCHECK for known allowed paths is omitted.
150 // Only call this if you know the path you are providing is safe to mark as
151 // non-executable, such as log files.
152 BASE_EXPORT bool PreventExecuteMappingUnchecked(
153     const FilePath& path,
154     base::PassKey<PreventExecuteMappingClasses> passkey);
155 
156 // Set `path_key` to the second of two valid paths that support safely marking a
157 // file as non-execute. The first allowed path is always PATH_TEMP. This is
158 // needed to avoid layering violations, as the user data dir is an embedder
159 // concept and only known later at runtime.
160 BASE_EXPORT void SetExtraNoExecuteAllowedPath(int path_key);
161 #endif  // BUILDFLAG(IS_WIN)
162 
163 // Moves the given path, whether it's a file or a directory.
164 // If a simple rename is not possible, such as in the case where the paths are
165 // on different volumes, this will attempt to copy and delete. Returns
166 // true for success.
167 // This function fails if either path contains traversal components ('..').
168 BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
169 
170 // Renames file |from_path| to |to_path|. Both paths must be on the same
171 // volume, or the function will fail. Destination file will be created
172 // if it doesn't exist. Prefer this function over Move when dealing with
173 // temporary files. On Windows it preserves attributes of the target file.
174 // Returns true on success, leaving *error unchanged.
175 // Returns false on failure and sets *error appropriately, if it is non-NULL.
176 BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
177                              const FilePath& to_path,
178                              File::Error* error);
179 
180 // Copies a single file. Use CopyDirectory() to copy directories.
181 // This function fails if either path contains traversal components ('..').
182 // This function also fails if |to_path| is a directory.
183 //
184 // On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This
185 // may have security implications. Use with care.
186 //
187 // If |to_path| already exists and is a regular file, it will be overwritten,
188 // though its permissions will stay the same.
189 //
190 // If |to_path| does not exist, it will be created. The new file's permissions
191 // varies per platform:
192 //
193 // - This function keeps the metadata on Windows. The read only bit is not kept.
194 // - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user
195 //   read/write permissions are always set.
196 // - On Linux and Android, |to_path| has user read/write permissions only. i.e.
197 //   Always 0600.
198 // - On ChromeOS, |to_path| has user read/write permissions and group/others
199 //   read permissions. i.e. Always 0644.
200 BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
201 
202 // Copies the contents of one file into another.
203 // The files are taken as is: the copy is done starting from the current offset
204 // of |infile| until the end of |infile| is reached, into the current offset of
205 // |outfile|.
206 BASE_EXPORT bool CopyFileContents(File& infile, File& outfile);
207 
208 // Copies the given path, and optionally all subdirectories and their contents
209 // as well.
210 //
211 // If there are files existing under to_path, always overwrite. Returns true
212 // if successful, false otherwise. Wildcards on the names are not supported.
213 //
214 // This function has the same metadata behavior as CopyFile().
215 //
216 // If you only need to copy a file use CopyFile, it's faster.
217 BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
218                                const FilePath& to_path,
219                                bool recursive);
220 
221 // Like CopyDirectory() except trying to overwrite an existing file will not
222 // work and will return false.
223 BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path,
224                                    const FilePath& to_path,
225                                    bool recursive);
226 
227 // Returns true if the given path exists on the local filesystem,
228 // false otherwise.
229 BASE_EXPORT bool PathExists(const FilePath& path);
230 
231 // Returns true if the given path is readable by the user, false otherwise.
232 BASE_EXPORT bool PathIsReadable(const FilePath& path);
233 
234 // Returns true if the given path is writable by the user, false otherwise.
235 BASE_EXPORT bool PathIsWritable(const FilePath& path);
236 
237 // Returns true if the given path exists and is a directory, false otherwise.
238 BASE_EXPORT bool DirectoryExists(const FilePath& path);
239 
240 // Returns true if the contents of the two files given are equal, false
241 // otherwise.  If either file can't be read, returns false.
242 BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
243                                const FilePath& filename2);
244 
245 // Returns true if the contents of the two text files given are equal, false
246 // otherwise.  This routine treats "\r\n" and "\n" as equivalent.
247 BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
248                                    const FilePath& filename2);
249 
250 // Reads the file at |path| and returns a vector of bytes on success, and
251 // nullopt on error. For security reasons, a |path| containing path traversal
252 // components ('..') is treated as a read error, returning nullopt.
253 BASE_EXPORT std::optional<std::vector<uint8_t>> ReadFileToBytes(
254     const FilePath& path);
255 
256 // Reads the file at |path| into |contents| and returns true on success and
257 // false on error.  For security reasons, a |path| containing path traversal
258 // components ('..') is treated as a read error and |contents| is set to empty.
259 // In case of I/O error, |contents| holds the data that could be read from the
260 // file before the error occurred.
261 // |contents| may be NULL, in which case this function is useful for its side
262 // effect of priming the disk cache (could be used for unit tests).
263 BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
264 
265 // Reads the file at |path| into |contents| and returns true on success and
266 // false on error.  For security reasons, a |path| containing path traversal
267 // components ('..') is treated as a read error and |contents| is set to empty.
268 // In case of I/O error, |contents| holds the data that could be read from the
269 // file before the error occurred.  When the file size exceeds |max_size|, the
270 // function returns false with |contents| holding the file truncated to
271 // |max_size|.
272 // |contents| may be NULL, in which case this function is useful for its side
273 // effect of priming the disk cache (could be used for unit tests).
274 BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
275                                              std::string* contents,
276                                              size_t max_size);
277 
278 // As ReadFileToString, but reading from an open stream after seeking to its
279 // start (if supported by the stream). This can also be used to read the whole
280 // file from a file descriptor by converting the file descriptor into a stream
281 // by using base::FileToFILE() before calling this function.
282 BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents);
283 
284 // As ReadFileToStringWithMaxSize, but reading from an open stream after seeking
285 // to its start (if supported by the stream).
286 BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream,
287                                                size_t max_size,
288                                                std::string* contents);
289 
290 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
291 
292 // Reads exactly as many bytes as `buffer` can hold from file descriptor `fd`
293 // into `buffer`. This function is protected against EINTR and partial reads.
294 // Returns true iff `buffer` was successfully filled with bytes read from `fd`.
295 BASE_EXPORT bool ReadFromFD(int fd, span<char> buffer);
296 // TODO(https://crbug.com/1490484): Migrate callers to the span variant.
297 BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
298 
299 // Performs the same function as CreateAndOpenTemporaryStreamInDir(), but
300 // returns the file-descriptor wrapped in a ScopedFD, rather than the stream
301 // wrapped in a ScopedFILE.
302 // The caller is responsible for deleting the file `path` points to, if
303 // appropriate.
304 BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir,
305                                                           FilePath* path);
306 
307 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
308 
309 #if BUILDFLAG(IS_POSIX)
310 
311 // ReadFileToStringNonBlocking is identical to ReadFileToString except it
312 // guarantees that it will not block. This guarantee is provided on POSIX by
313 // opening the file as O_NONBLOCK. This variant should only be used on files
314 // which are guaranteed not to block (such as kernel files). Or in situations
315 // where a partial read would be acceptable because the backing store returned
316 // EWOULDBLOCK.
317 BASE_EXPORT bool ReadFileToStringNonBlocking(const base::FilePath& file,
318                                              std::string* ret);
319 
320 // Creates a symbolic link at |symlink| pointing to |target|.  Returns
321 // false on failure.
322 BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
323                                     const FilePath& symlink);
324 
325 // Reads the given |symlink| and returns the raw string in |target|.
326 // Returns false upon failure.
327 // IMPORTANT NOTE: if the string stored in the symlink is a relative file path,
328 // it should be interpreted relative to the symlink's directory, NOT the current
329 // working directory. ReadSymbolicLinkAbsolute() may be the better choice.
330 BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
331 
332 // Same as ReadSymbolicLink(), but properly converts it into an absolute path if
333 // the link is relative.
334 // Can fail if readlink() fails, or if
335 // MakeAbsoluteFilePathNoResolveSymbolicLinks() fails on the resulting absolute
336 // path.
337 BASE_EXPORT std::optional<FilePath> ReadSymbolicLinkAbsolute(
338     const FilePath& symlink);
339 
340 // Bits and masks of the file permission.
341 enum FilePermissionBits {
342   FILE_PERMISSION_MASK              = S_IRWXU | S_IRWXG | S_IRWXO,
343   FILE_PERMISSION_USER_MASK         = S_IRWXU,
344   FILE_PERMISSION_GROUP_MASK        = S_IRWXG,
345   FILE_PERMISSION_OTHERS_MASK       = S_IRWXO,
346 
347   FILE_PERMISSION_READ_BY_USER      = S_IRUSR,
348   FILE_PERMISSION_WRITE_BY_USER     = S_IWUSR,
349   FILE_PERMISSION_EXECUTE_BY_USER   = S_IXUSR,
350   FILE_PERMISSION_READ_BY_GROUP     = S_IRGRP,
351   FILE_PERMISSION_WRITE_BY_GROUP    = S_IWGRP,
352   FILE_PERMISSION_EXECUTE_BY_GROUP  = S_IXGRP,
353   FILE_PERMISSION_READ_BY_OTHERS    = S_IROTH,
354   FILE_PERMISSION_WRITE_BY_OTHERS   = S_IWOTH,
355   FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
356 };
357 
358 // Reads the permission of the given |path|, storing the file permission
359 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
360 // a file which the symlink points to.
361 BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
362 // Sets the permission of the given |path|. If |path| is symbolic link, sets
363 // the permission of a file which the symlink points to.
364 BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
365 
366 // Returns true iff |executable| can be found in any directory specified by the
367 // environment variable in |env|.
368 BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
369                                         const FilePath::StringType& executable);
370 
371 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
372 // Determine if files under a given |path| can be mapped and then mprotect'd
373 // PROT_EXEC. This depends on the mount options used for |path|, which vary
374 // among different Linux distributions and possibly local configuration. It also
375 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
376 // but its kernel allows mprotect with PROT_EXEC anyway.
377 BASE_EXPORT bool IsPathExecutable(const FilePath& path);
378 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
379 
380 #endif  // BUILDFLAG(IS_POSIX)
381 
382 // Returns true if the given directory is empty
383 BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
384 
385 // Get the temporary directory provided by the system.
386 //
387 // WARNING: In general, you should use CreateTemporaryFile variants below
388 // instead of this function. Those variants will ensure that the proper
389 // permissions are set so that other users on the system can't edit them while
390 // they're open (which can lead to security issues).
391 BASE_EXPORT bool GetTempDir(FilePath* path);
392 
393 // Get the home directory. This is more complicated than just getenv("HOME")
394 // as it knows to fall back on getpwent() etc.
395 //
396 // You should not generally call this directly. Instead use DIR_HOME with the
397 // path service which will use this function but cache the value.
398 // Path service may also override DIR_HOME.
399 BASE_EXPORT FilePath GetHomeDir();
400 
401 // Returns a new temporary file in |dir| with a unique name. The file is opened
402 // for exclusive read, write, and delete access.
403 // On success, |temp_file| is populated with the full path to the created file.
404 //
405 // NOTE: Exclusivity is unique to Windows. On Windows, the returned file
406 // supports File::DeleteOnClose. On other platforms, the caller is responsible
407 // for deleting the file `temp_file` points to, if appropriate.
408 BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir,
409                                                  FilePath* temp_file);
410 
411 // Creates a temporary file. The full path is placed in `path`, and the
412 // function returns true if was successful in creating the file. The file will
413 // be empty and all handles closed after this function returns.
414 // The caller is responsible for deleting the file `path` points to, if
415 // appropriate.
416 BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
417 
418 // Same as CreateTemporaryFile() but the file is created in `dir`.
419 // The caller is responsible for deleting the file `temp_file` points to, if
420 // appropriate.
421 BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
422                                           FilePath* temp_file);
423 
424 // Returns the file name for a temporary file by using a platform-specific
425 // naming scheme that incorporates |identifier|.
426 BASE_EXPORT FilePath
427 FormatTemporaryFileName(FilePath::StringPieceType identifier);
428 
429 // Create and open a temporary file stream for exclusive read, write, and delete
430 // access. The full path is placed in `path`. Returns the opened file stream, or
431 // null in case of error.
432 // NOTE: Exclusivity is unique to Windows. On Windows, the returned file
433 // supports File::DeleteOnClose. On other platforms, the caller is responsible
434 // for deleting the file `path` points to, if appropriate.
435 BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path);
436 
437 // Similar to CreateAndOpenTemporaryStream(), but the file is created in `dir`.
438 BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
439                                                          FilePath* path);
440 
441 #if BUILDFLAG(IS_WIN)
442 // Retrieves the path `%systemroot%\SystemTemp`, if available, else retrieves
443 // `%programfiles%`.
444 // Returns the path in `temp` and `true` if the path is writable by the caller,
445 // which is usually only when the caller is running as admin or system.
446 // Returns `false` otherwise.
447 // Both paths are only accessible to admin and system processes, and are
448 // therefore secure.
449 BASE_EXPORT bool GetSecureSystemTemp(FilePath* temp);
450 
451 // Set whether or not the use of %systemroot%\SystemTemp or %programfiles% is
452 // permitted for testing. This is so tests that run as admin will still continue
453 // to use %TMP% so their files will be correctly cleaned up by the test
454 // launcher.
455 BASE_EXPORT void SetDisableSecureSystemTempForTesting(bool disabled);
456 #endif  // BUILDFLAG(IS_WIN)
457 
458 // Do NOT USE in new code. Use ScopedTempDir instead.
459 // TODO(crbug.com/561597) Remove existing usage and make this an implementation
460 // detail inside ScopedTempDir.
461 //
462 // Create a new directory. If prefix is provided, the new directory name is in
463 // the format of prefixyyyy.
464 // NOTE: prefix is ignored in the POSIX implementation.
465 // If success, return true and output the full path of the directory created.
466 //
467 // For Windows, this directory is usually created in a secure location if the
468 // caller is admin. This is because the default %TEMP% folder for Windows is
469 // insecure, since low privilege users can get the path of folders under %TEMP%
470 // after creation and are able to create subfolders and files within these
471 // folders which can lead to privilege escalation.
472 BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
473                                         FilePath* new_temp_path);
474 
475 // Create a directory within another directory.
476 // Extra characters will be appended to |prefix| to ensure that the
477 // new directory does not have the same name as an existing directory.
478 BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
479                                          const FilePath::StringType& prefix,
480                                          FilePath* new_dir);
481 
482 // Creates a directory, as well as creating any parent directories, if they
483 // don't exist. Returns 'true' on successful creation, or if the directory
484 // already exists.  The directory is only readable by the current user.
485 // Returns true on success, leaving *error unchanged.
486 // Returns false on failure and sets *error appropriately, if it is non-NULL.
487 BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
488                                             File::Error* error);
489 
490 // Backward-compatible convenience method for the above.
491 BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
492 
493 // Returns the file size. Returns true on success.
494 BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
495 
496 // Sets |real_path| to |path| with symbolic links and junctions expanded.
497 // On windows, make sure the path starts with a lettered drive.
498 // |path| must reference a file.  Function will fail if |path| points to
499 // a directory or to a nonexistent path.  On windows, this function will
500 // fail if |real_path| would be longer than MAX_PATH characters.
501 BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
502 
503 #if BUILDFLAG(IS_WIN)
504 
505 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
506 // return in |drive_letter_path| the equivalent path that starts with
507 // a drive letter ("C:\...").  Return false if no such path exists.
508 BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
509                                              FilePath* drive_letter_path);
510 
511 // Method that wraps the win32 GetLongPathName API, normalizing the specified
512 // path to its long form. An example where this is needed is when comparing
513 // temp file paths. If a username isn't a valid 8.3 short file name (even just a
514 // lengthy name like "user with long name"), Windows will set the TMP and TEMP
515 // environment variables to be 8.3 paths. ::GetTempPath (called in
516 // base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
517 // return a short path. Returns an empty path on error.
518 BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input);
519 
520 // Creates a hard link named |to_file| to the file |from_file|. Both paths
521 // must be on the same volume, and |from_file| may not name a directory.
522 // Returns true if the hard link is created, false if it fails.
523 BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file,
524                                    const FilePath& from_file);
525 #endif
526 
527 // This function will return if the given file is a symlink or not.
528 //
529 // IMPORTANT NOTE: This method is subject to race conditions, meaning its
530 // results might not always accurately reflect the current state of the file
531 // system by the time they are used. Specifically, the link target could change
532 // between the time of this check and subsequent operations, leading to
533 // potential inconsistencies. Therefore, this method should only be used by
534 // callers that need to know nothing more than whether or not a given directory
535 // entry is a symlink. When the path to the target is required, callers should
536 // instead use `base::ReadSymbolicLink()` or `base::ReadSymbolicLinkAbsolute()`.
537 BASE_EXPORT bool IsLink(const FilePath& file_path);
538 
539 // Returns information about the given file path. Also see |File::GetInfo|.
540 BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
541 
542 // Sets the time of the last access and the time of the last modification.
543 BASE_EXPORT bool TouchFile(const FilePath& path,
544                            const Time& last_accessed,
545                            const Time& last_modified);
546 
547 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The
548 // underlying file descriptor (POSIX) or handle (Windows) is unconditionally
549 // configured to not be propagated to child processes.
550 BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
551 
552 // Closes file opened by OpenFile. Returns true on success.
553 BASE_EXPORT bool CloseFile(FILE* file);
554 
555 // Associates a standard FILE stream with an existing File. Note that this
556 // functions take ownership of the existing File.
557 BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
558 
559 // Returns a new handle to the file underlying |file_stream|.
560 BASE_EXPORT File FILEToFile(FILE* file_stream);
561 
562 // Truncates an open file to end at the location of the current file pointer.
563 // This is a cross-platform analog to Windows' SetEndOfFile() function.
564 BASE_EXPORT bool TruncateFile(FILE* file);
565 
566 // Reads from the file into `buffer`. This will read at most as many bytes as
567 // `buffer` can hold, but may not always fill `buffer` entirely.
568 // Returns the number of bytes read, or nullopt on error.
569 // TODO(crbug.com/1333521): Despite the 64-bit return value, this only supports
570 // reading at most INT_MAX bytes. The program will crash if a buffer is passed
571 // whose length exceeds INT_MAX.
572 BASE_EXPORT std::optional<uint64_t> ReadFile(const FilePath& filename,
573                                              span<char> buffer);
574 BASE_EXPORT std::optional<uint64_t> ReadFile(const FilePath& filename,
575                                              span<uint8_t> buffer);
576 
577 // Same as above, but returns -1 on error.
578 // TODO(https://crbug.com/1490484): Migrate callers to the span variant.
579 BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
580 
581 // Writes the given buffer into the file, overwriting any data that was
582 // previously there.  Returns the number of bytes written, or -1 on error.
583 // If file doesn't exist, it gets created with read/write permissions for all.
584 // Note that the other variants of WriteFile() below may be easier to use.
585 // TODO(https://crbug.com/1490484): Migrate callers to the span variant.
586 BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
587                           int size);
588 
589 // Writes |data| into the file, overwriting any data that was previously there.
590 // Returns true if and only if all of |data| was written. If the file does not
591 // exist, it gets created with read/write permissions for all.
592 BASE_EXPORT bool WriteFile(const FilePath& filename, span<const uint8_t> data);
593 
594 // Another WriteFile() variant that takes a StringPiece so callers don't have to
595 // do manual conversions from a char span to a uint8_t span.
596 BASE_EXPORT bool WriteFile(const FilePath& filename, StringPiece data);
597 
598 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
599 // Appends |data| to |fd|. Does not close |fd| when done.  Returns true iff all
600 // of |data| were written to |fd|.
601 BASE_EXPORT bool WriteFileDescriptor(int fd, span<const uint8_t> data);
602 
603 // WriteFileDescriptor() variant that takes a StringPiece so callers don't have
604 // to do manual conversions from a char span to a uint8_t span.
605 BASE_EXPORT bool WriteFileDescriptor(int fd, StringPiece data);
606 
607 // Allocates disk space for the file referred to by |fd| for the byte range
608 // starting at |offset| and continuing for |size| bytes. The file size will be
609 // changed if |offset|+|len| is greater than the file size. Zeros will fill the
610 // new space.
611 // After a successful call, subsequent writes into the specified range are
612 // guaranteed not to fail because of lack of disk space.
613 BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size);
614 #endif
615 
616 // Appends |data| to |filename|.  Returns true iff |data| were written to
617 // |filename|.
618 BASE_EXPORT bool AppendToFile(const FilePath& filename,
619                               span<const uint8_t> data);
620 
621 // AppendToFile() variant that takes a StringPiece so callers don't have to do
622 // manual conversions from a char span to a uint8_t span.
623 BASE_EXPORT bool AppendToFile(const FilePath& filename, StringPiece data);
624 
625 // Gets the current working directory for the process.
626 BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
627 
628 // Sets the current working directory for the process.
629 BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
630 
631 // The largest value attempted by GetUniquePath{Number,}.
632 enum { kMaxUniqueFiles = 100 };
633 
634 // Returns the number N that makes |path| unique when formatted as " (N)" in a
635 // suffix to its basename before any file extension, where N is a number between
636 // 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is
637 // unique as-is), or -1 if no such number can be found.
638 BASE_EXPORT int GetUniquePathNumber(const FilePath& path);
639 
640 // Returns |path| if it does not exist. Otherwise, returns |path| with the
641 // suffix " (N)" appended to its basename before any file extension, where N is
642 // a number between 1 and 100 (inclusive). Returns an empty path if no such
643 // number can be found.
644 BASE_EXPORT FilePath GetUniquePath(const FilePath& path);
645 
646 // Sets the given |fd| to non-blocking mode.
647 // Returns true if it was able to set it in the non-blocking mode, otherwise
648 // false.
649 BASE_EXPORT bool SetNonBlocking(int fd);
650 
651 // Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache.
652 //
653 // If called at the appropriate time, this can reduce the latency incurred by
654 // feature code that needs to read the file.
655 //
656 // |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the
657 // file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient
658 // way to get the entire file pre-fetched.
659 //
660 // |is_executable| specifies whether the file is to be prefetched as
661 // executable code or as data. Windows treats the file backed pages in RAM
662 // differently, and specifying the wrong value results in two copies in RAM.
663 //
664 // |sequential| hints that the file will be read sequentially in the future.
665 // This has the affect of using POSIX_FADV_SEQUENTIAL on supported POSIX
666 // systems.
667 //
668 // Returns true if at least part of the requested range was successfully
669 // prefetched.
670 //
671 // Calling this before using ::LoadLibrary() on Windows is more efficient memory
672 // wise, but we must be sure no other threads try to LoadLibrary() the file
673 // while we are doing the mapping and prefetching, or the process will get a
674 // private copy of the DLL via COW.
675 BASE_EXPORT bool PreReadFile(
676     const FilePath& file_path,
677     bool is_executable,
678     bool sequential,
679     int64_t max_bytes = std::numeric_limits<int64_t>::max());
680 
681 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
682 
683 // Creates a pipe. Returns true on success, otherwise false.
684 // On success, |read_fd| will be set to the fd of the read side, and
685 // |write_fd| will be set to the one of write side. If |non_blocking|
686 // is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set
687 // otherwise flag is set to zero (default).
688 BASE_EXPORT bool CreatePipe(ScopedFD* read_fd,
689                             ScopedFD* write_fd,
690                             bool non_blocking = false);
691 
692 // Creates a non-blocking, close-on-exec pipe.
693 // This creates a non-blocking pipe that is not intended to be shared with any
694 // child process. This will be done atomically if the operating system supports
695 // it. Returns true if it was able to create the pipe, otherwise false.
696 BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]);
697 
698 // Sets the given |fd| to close-on-exec mode.
699 // Returns true if it was able to set it in the close-on-exec mode, otherwise
700 // false.
701 BASE_EXPORT bool SetCloseOnExec(int fd);
702 
703 // Removes close-on-exec flag from the given |fd|.
704 // Returns true if it was able to remove the close-on-exec flag, otherwise
705 // false.
706 BASE_EXPORT bool RemoveCloseOnExec(int fd);
707 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
708 
709 #if BUILDFLAG(IS_MAC)
710 // Test that |path| can only be changed by a given user and members of
711 // a given set of groups.
712 // Specifically, test that all parts of |path| under (and including) |base|:
713 // * Exist.
714 // * Are owned by a specific user.
715 // * Are not writable by all users.
716 // * Are owned by a member of a given set of groups, or are not writable by
717 //   their group.
718 // * Are not symbolic links.
719 // This is useful for checking that a config file is administrator-controlled.
720 // |base| must contain |path|.
721 BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
722                                             const base::FilePath& path,
723                                             uid_t owner_uid,
724                                             const std::set<gid_t>& group_gids);
725 
726 // Is |path| writable only by a user with administrator privileges?
727 // This function uses Mac OS conventions.  The super user is assumed to have
728 // uid 0, and the administrator group is assumed to be named "admin".
729 // Testing that |path|, and every parent directory including the root of
730 // the filesystem, are owned by the superuser, controlled by the group
731 // "admin", are not writable by all users, and contain no symbolic links.
732 // Will return false if |path| does not exist.
733 BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
734 #endif  // BUILDFLAG(IS_MAC)
735 
736 // Returns the maximum length of path component on the volume containing
737 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
738 BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
739 
740 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
741 // Get a temporary directory for shared memory files. The directory may depend
742 // on whether the destination is intended for executable files, which in turn
743 // depends on how /dev/shmem was mounted. As a result, you must supply whether
744 // you intend to create executable shmem segments so this function can find
745 // an appropriate location.
746 BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
747 #endif
748 
749 // Internal --------------------------------------------------------------------
750 
751 namespace internal {
752 
753 // Same as Move but allows paths with traversal components.
754 // Use only with extreme care.
755 BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
756                             const FilePath& to_path);
757 
758 #if BUILDFLAG(IS_WIN)
759 // Copy from_path to to_path recursively and then delete from_path recursively.
760 // Returns true if all operations succeed.
761 // This function simulates Move(), but unlike Move() it works across volumes.
762 // This function is not transactional.
763 BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
764                                         const FilePath& to_path);
765 #endif  // BUILDFLAG(IS_WIN)
766 
767 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
768 // CopyFileContentsWithSendfile will use the sendfile(2) syscall to perform a
769 // file copy without moving the data between kernel and userspace. This is much
770 // more efficient than sequences of read(2)/write(2) calls. The |retry_slow|
771 // parameter instructs the caller that it should try to fall back to a normal
772 // sequences of read(2)/write(2) syscalls.
773 //
774 // The input file |infile| must be opened for reading and the output file
775 // |outfile| must be opened for writing.
776 BASE_EXPORT bool CopyFileContentsWithSendfile(File& infile,
777                                               File& outfile,
778                                               bool& retry_slow);
779 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
780         // BUILDFLAG(IS_ANDROID)
781 
782 }  // namespace internal
783 }  // namespace base
784 
785 #endif  // BASE_FILES_FILE_UTIL_H_
786