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