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