blob: 192a1f764e54ea26a07c51ca1ef75913d9b2ea92 [file] [log] [blame]
[email protected]e3177dd52014-08-13 20:22:141// Copyright (c) 2012 The Chromium Authors. All rights reserved.
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
avi543540e2015-12-24 05:15:3211#include <stddef.h>
12#include <stdint.h>
13#include <stdio.h>
14
Victor Costanb5a0a97002019-09-08 04:55:1515#include <limits>
avi543540e2015-12-24 05:15:3216#include <set>
17#include <string>
18#include <vector>
19
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3920#if defined(OS_POSIX) || defined(OS_FUCHSIA)
21#include <sys/stat.h>
22#include <unistd.h>
23#endif
24
avi543540e2015-12-24 05:15:3225#include "base/base_export.h"
26#include "base/files/file.h"
27#include "base/files/file_path.h"
Greg Thompsonf75f5fb2020-04-30 08:13:2528#include "base/files/scoped_file.h"
avi543540e2015-12-24 05:15:3229#include "base/strings/string16.h"
[email protected]e3177dd52014-08-13 20:22:1430#include "build/build_config.h"
31
32#if defined(OS_WIN)
Bruce Dawsonbfdc3fd2018-01-03 20:32:3633#include "base/win/windows_types.h"
Fabrice de Gans-Riberi306871de2018-05-16 19:38:3934#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:1435#include "base/file_descriptor_posix.h"
36#include "base/logging.h"
37#include "base/posix/eintr_wrapper.h"
38#endif
39
40namespace base {
41
thomasanderson1929bb22016-06-24 02:01:0042class Environment;
[email protected]e3177dd52014-08-13 20:22:1443class Time;
44
45//-----------------------------------------------------------------------------
46// Functions that involve filesystem access or modification:
47
48// Returns an absolute version of a relative path. Returns an empty path on
49// error. On POSIX, this function fails if the path does not exist. This
50// function can result in I/O so it can be slow.
51BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
52
53// Returns the total number of bytes used by all the files under |root_path|.
54// If the path does not exist the function returns 0.
55//
56// This function is implemented using the FileEnumerator class so it is not
57// particularly speedy in any platform.
avi543540e2015-12-24 05:15:3258BASE_EXPORT int64_t ComputeDirectorySize(const FilePath& root_path);
[email protected]e3177dd52014-08-13 20:22:1459
60// Deletes the given path, whether it's a file or a directory.
61// If it's a directory, it's perfectly happy to delete all of the
62// directory's contents. Passing true to recursive deletes
63// subdirectories and their contents as well.
64// Returns true if successful, false otherwise. It is considered successful
65// to attempt to delete a file that does not exist.
66//
Lei Zhangaeb72b52019-10-14 22:39:4067// In POSIX environment and if |path| is a symbolic link, this deletes only
[email protected]e3177dd52014-08-13 20:22:1468// the symlink. (even if the symlink points to a non-existent file)
69//
70// WARNING: USING THIS WITH recursive==true IS EQUIVALENT
71// TO "rm -rf", SO USE WITH CAUTION.
Lei Zhangaeb72b52019-10-14 22:39:4072//
73// Note: The |recursive| parameter is in the process of being removed. Use
74// DeleteFileRecursively() instead. See https://crbug.com/1009837
[email protected]e3177dd52014-08-13 20:22:1475BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
76
Lei Zhangaeb72b52019-10-14 22:39:4077// Deletes the given path, whether it's a file or a directory.
78// If it's a directory, it's perfectly happy to delete all of the
79// directory's contents, including subdirectories and their contents.
80// Returns true if successful, false otherwise. It is considered successful
81// to attempt to delete a file that does not exist.
82//
83// In POSIX environment and if |path| is a symbolic link, this deletes only
84// the symlink. (even if the symlink points to a non-existent file)
85//
86// WARNING: USING THIS EQUIVALENT TO "rm -rf", SO USE WITH CAUTION.
87BASE_EXPORT bool DeleteFileRecursively(const FilePath& path);
88
[email protected]e3177dd52014-08-13 20:22:1489#if defined(OS_WIN)
90// Schedules to delete the given path, whether it's a file or a directory, until
91// the operating system is restarted.
92// Note:
93// 1) The file/directory to be deleted should exist in a temp folder.
94// 2) The directory to be deleted must be empty.
95BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
96#endif
97
98// Moves the given path, whether it's a file or a directory.
99// If a simple rename is not possible, such as in the case where the paths are
100// on different volumes, this will attempt to copy and delete. Returns
101// true for success.
102// This function fails if either path contains traversal components ('..').
103BASE_EXPORT bool Move(const FilePath& from_path, const FilePath& to_path);
104
105// Renames file |from_path| to |to_path|. Both paths must be on the same
106// volume, or the function will fail. Destination file will be created
107// if it doesn't exist. Prefer this function over Move when dealing with
108// temporary files. On Windows it preserves attributes of the target file.
109// Returns true on success, leaving *error unchanged.
110// Returns false on failure and sets *error appropriately, if it is non-NULL.
111BASE_EXPORT bool ReplaceFile(const FilePath& from_path,
112 const FilePath& to_path,
113 File::Error* error);
114
Lei Zhang6a0e47ca2017-10-02 23:02:16115// Copies a single file. Use CopyDirectory() to copy directories.
[email protected]e3177dd52014-08-13 20:22:14116// This function fails if either path contains traversal components ('..').
Lei Zhang6a0e47ca2017-10-02 23:02:16117// This function also fails if |to_path| is a directory.
[email protected]e3177dd52014-08-13 20:22:14118//
Lei Zhang6a0e47ca2017-10-02 23:02:16119// On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This
120// may have security implications. Use with care.
121//
122// If |to_path| already exists and is a regular file, it will be overwritten,
123// though its permissions will stay the same.
124//
125// If |to_path| does not exist, it will be created. The new file's permissions
126// varies per platform:
127//
128// - This function keeps the metadata on Windows. The read only bit is not kept.
129// - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user
130// read/write permissions are always set.
131// - On Linux and Android, |to_path| has user read/write permissions only. i.e.
132// Always 0600.
133// - On ChromeOS, |to_path| has user read/write permissions and group/others
134// read permissions. i.e. Always 0644.
[email protected]e3177dd52014-08-13 20:22:14135BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
136
137// Copies the given path, and optionally all subdirectories and their contents
138// as well.
139//
140// If there are files existing under to_path, always overwrite. Returns true
141// if successful, false otherwise. Wildcards on the names are not supported.
142//
Eric Carusobca21fc582017-09-28 00:34:34143// This function has the same metadata behavior as CopyFile().
[email protected]e3177dd52014-08-13 20:22:14144//
145// If you only need to copy a file use CopyFile, it's faster.
146BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
147 const FilePath& to_path,
148 bool recursive);
149
Eric Caruso128f0dd2017-12-16 01:32:49150// Like CopyDirectory() except trying to overwrite an existing file will not
151// work and will return false.
152BASE_EXPORT bool CopyDirectoryExcl(const FilePath& from_path,
153 const FilePath& to_path,
154 bool recursive);
155
[email protected]e3177dd52014-08-13 20:22:14156// Returns true if the given path exists on the local filesystem,
157// false otherwise.
158BASE_EXPORT bool PathExists(const FilePath& path);
159
160// Returns true if the given path is writable by the user, false otherwise.
161BASE_EXPORT bool PathIsWritable(const FilePath& path);
162
163// Returns true if the given path exists and is a directory, false otherwise.
164BASE_EXPORT bool DirectoryExists(const FilePath& path);
165
166// Returns true if the contents of the two files given are equal, false
167// otherwise. If either file can't be read, returns false.
168BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
169 const FilePath& filename2);
170
171// Returns true if the contents of the two text files given are equal, false
172// otherwise. This routine treats "\r\n" and "\n" as equivalent.
173BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
174 const FilePath& filename2);
175
176// Reads the file at |path| into |contents| and returns true on success and
177// false on error. For security reasons, a |path| containing path traversal
178// components ('..') is treated as a read error and |contents| is set to empty.
179// In case of I/O error, |contents| holds the data that could be read from the
180// file before the error occurred.
181// |contents| may be NULL, in which case this function is useful for its side
182// effect of priming the disk cache (could be used for unit tests).
183BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
184
185// Reads the file at |path| into |contents| and returns true on success and
186// false on error. For security reasons, a |path| containing path traversal
187// components ('..') is treated as a read error and |contents| is set to empty.
188// In case of I/O error, |contents| holds the data that could be read from the
189// file before the error occurred. When the file size exceeds |max_size|, the
190// function returns false with |contents| holding the file truncated to
191// |max_size|.
192// |contents| may be NULL, in which case this function is useful for its side
193// effect of priming the disk cache (could be used for unit tests).
hashimoto6da2fef2016-02-24 03:39:58194BASE_EXPORT bool ReadFileToStringWithMaxSize(const FilePath& path,
195 std::string* contents,
196 size_t max_size);
[email protected]e3177dd52014-08-13 20:22:14197
Greg Thompson3f7e20f42020-05-02 19:01:11198// As ReadFileToString, but reading from an open stream after seeking to its
199// start (if supported by the stream).
200BASE_EXPORT bool ReadStreamToString(FILE* stream, std::string* contents);
201
202// As ReadFileToStringWithMaxSize, but reading from an open stream after seeking
203// to its start (if supported by the stream).
204BASE_EXPORT bool ReadStreamToStringWithMaxSize(FILE* stream,
205 size_t max_size,
206 std::string* contents);
207
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39208#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14209
210// Read exactly |bytes| bytes from file descriptor |fd|, storing the result
211// in |buffer|. This function is protected against EINTR and partial reads.
212// Returns true iff |bytes| bytes have been successfully read from |fd|.
213BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
214
Greg Thompsonf75f5fb2020-04-30 08:13:25215// Performs the same function as CreateAndOpenTemporaryStreamInDir(), but
216// returns the file-descriptor wrapped in a ScopedFD, rather than the stream
217// wrapped in a ScopedFILE.
Lei Zhangd22c9732019-08-02 16:31:38218BASE_EXPORT ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir,
219 FilePath* path);
Wez45a7b302018-02-22 22:42:39220
Lei Zhangd22c9732019-08-02 16:31:38221#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39222
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18223#if defined(OS_POSIX)
Kevin Marshalla9f05ec2017-07-14 02:10:05224
[email protected]e3177dd52014-08-13 20:22:14225// Creates a symbolic link at |symlink| pointing to |target|. Returns
226// false on failure.
227BASE_EXPORT bool CreateSymbolicLink(const FilePath& target,
228 const FilePath& symlink);
229
230// Reads the given |symlink| and returns where it points to in |target|.
231// Returns false upon failure.
232BASE_EXPORT bool ReadSymbolicLink(const FilePath& symlink, FilePath* target);
233
234// Bits and masks of the file permission.
235enum FilePermissionBits {
236 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO,
237 FILE_PERMISSION_USER_MASK = S_IRWXU,
238 FILE_PERMISSION_GROUP_MASK = S_IRWXG,
239 FILE_PERMISSION_OTHERS_MASK = S_IRWXO,
240
241 FILE_PERMISSION_READ_BY_USER = S_IRUSR,
242 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR,
243 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR,
244 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP,
245 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP,
246 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP,
247 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH,
248 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH,
249 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
250};
251
252// Reads the permission of the given |path|, storing the file permission
253// bits in |mode|. If |path| is symbolic link, |mode| is the permission of
254// a file which the symlink points to.
255BASE_EXPORT bool GetPosixFilePermissions(const FilePath& path, int* mode);
256// Sets the permission of the given |path|. If |path| is symbolic link, sets
257// the permission of a file which the symlink points to.
258BASE_EXPORT bool SetPosixFilePermissions(const FilePath& path, int mode);
259
thomasanderson1929bb22016-06-24 02:01:00260// Returns true iff |executable| can be found in any directory specified by the
261// environment variable in |env|.
262BASE_EXPORT bool ExecutableExistsInPath(Environment* env,
263 const FilePath::StringType& executable);
264
Sergey Volk76166f5b2018-06-15 17:38:02265#if defined(OS_LINUX) || defined(OS_AIX)
266// Determine if files under a given |path| can be mapped and then mprotect'd
267// PROT_EXEC. This depends on the mount options used for |path|, which vary
268// among different Linux distributions and possibly local configuration. It also
269// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
270// but its kernel allows mprotect with PROT_EXEC anyway.
271BASE_EXPORT bool IsPathExecutable(const FilePath& path);
272#endif // OS_LINUX || OS_AIX
273
Fabrice de Gans-Riberi65421f62018-05-22 23:16:18274#endif // OS_POSIX
[email protected]e3177dd52014-08-13 20:22:14275
276// Returns true if the given directory is empty
277BASE_EXPORT bool IsDirectoryEmpty(const FilePath& dir_path);
278
279// Get the temporary directory provided by the system.
280//
281// WARNING: In general, you should use CreateTemporaryFile variants below
282// instead of this function. Those variants will ensure that the proper
283// permissions are set so that other users on the system can't edit them while
284// they're open (which can lead to security issues).
285BASE_EXPORT bool GetTempDir(FilePath* path);
286
287// Get the home directory. This is more complicated than just getenv("HOME")
288// as it knows to fall back on getpwent() etc.
289//
290// You should not generally call this directly. Instead use DIR_HOME with the
291// path service which will use this function but cache the value.
292// Path service may also override DIR_HOME.
293BASE_EXPORT FilePath GetHomeDir();
294
Greg Thompson3f7e20f42020-05-02 19:01:11295// Returns a new temporary file in |dir| with a unique name. The file is opened
296// for exclusive read, write, and delete access (note: exclusivity is unique to
297// Windows). On Windows, the returned file supports File::DeleteOnClose.
298// On success, |temp_file| is populated with the full path to the created file.
299BASE_EXPORT File CreateAndOpenTemporaryFileInDir(const FilePath& dir,
300 FilePath* temp_file);
301
[email protected]e3177dd52014-08-13 20:22:14302// Creates a temporary file. The full path is placed in |path|, and the
303// function returns true if was successful in creating the file. The file will
304// be empty and all handles closed after this function returns.
305BASE_EXPORT bool CreateTemporaryFile(FilePath* path);
306
307// Same as CreateTemporaryFile but the file is created in |dir|.
308BASE_EXPORT bool CreateTemporaryFileInDir(const FilePath& dir,
309 FilePath* temp_file);
310
Greg Thompson3f7e20f42020-05-02 19:01:11311// Create and open a temporary file stream for exclusive read, write, and delete
312// access (note: exclusivity is unique to Windows). The full path is placed in
313// |path|. Returns the opened file stream, or null in case of error.
Greg Thompsonf75f5fb2020-04-30 08:13:25314BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStream(FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14315
Greg Thompsonf75f5fb2020-04-30 08:13:25316// Similar to CreateAndOpenTemporaryStream, but the file is created in |dir|.
317BASE_EXPORT ScopedFILE CreateAndOpenTemporaryStreamInDir(const FilePath& dir,
318 FilePath* path);
[email protected]e3177dd52014-08-13 20:22:14319
320// Create a new directory. If prefix is provided, the new directory name is in
321// the format of prefixyyyy.
322// NOTE: prefix is ignored in the POSIX implementation.
323// If success, return true and output the full path of the directory created.
324BASE_EXPORT bool CreateNewTempDirectory(const FilePath::StringType& prefix,
325 FilePath* new_temp_path);
326
327// Create a directory within another directory.
328// Extra characters will be appended to |prefix| to ensure that the
329// new directory does not have the same name as an existing directory.
330BASE_EXPORT bool CreateTemporaryDirInDir(const FilePath& base_dir,
331 const FilePath::StringType& prefix,
332 FilePath* new_dir);
333
334// Creates a directory, as well as creating any parent directories, if they
335// don't exist. Returns 'true' on successful creation, or if the directory
336// already exists. The directory is only readable by the current user.
337// Returns true on success, leaving *error unchanged.
338// Returns false on failure and sets *error appropriately, if it is non-NULL.
339BASE_EXPORT bool CreateDirectoryAndGetError(const FilePath& full_path,
340 File::Error* error);
341
342// Backward-compatible convenience method for the above.
343BASE_EXPORT bool CreateDirectory(const FilePath& full_path);
344
345// Returns the file size. Returns true on success.
avi543540e2015-12-24 05:15:32346BASE_EXPORT bool GetFileSize(const FilePath& file_path, int64_t* file_size);
[email protected]e3177dd52014-08-13 20:22:14347
348// Sets |real_path| to |path| with symbolic links and junctions expanded.
349// On windows, make sure the path starts with a lettered drive.
350// |path| must reference a file. Function will fail if |path| points to
351// a directory or to a nonexistent path. On windows, this function will
Alex Gough84ee78c2019-06-06 22:46:23352// fail if |real_path| would be longer than MAX_PATH characters.
[email protected]e3177dd52014-08-13 20:22:14353BASE_EXPORT bool NormalizeFilePath(const FilePath& path, FilePath* real_path);
354
355#if defined(OS_WIN)
356
357// Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
358// return in |drive_letter_path| the equivalent path that starts with
359// a drive letter ("C:\..."). Return false if no such path exists.
360BASE_EXPORT bool DevicePathToDriveLetterPath(const FilePath& device_path,
361 FilePath* drive_letter_path);
362
Bruce Longc343f7e2019-05-11 02:20:12363// Method that wraps the win32 GetLongPathName API, normalizing the specified
364// path to its long form. An example where this is needed is when comparing
365// temp file paths. If a username isn't a valid 8.3 short file name (even just a
366// lengthy name like "user with long name"), Windows will set the TMP and TEMP
367// environment variables to be 8.3 paths. ::GetTempPath (called in
368// base::GetTempDir) just uses the value specified by TMP or TEMP, and so can
369// return a short path. Returns an empty path on error.
370BASE_EXPORT FilePath MakeLongFilePath(const FilePath& input);
David Bienvenuf863412f2019-12-10 21:55:16371
372// Creates a hard link named |to_file| to the file |from_file|. Both paths
373// must be on the same volume, and |from_file| may not name a directory.
374// Returns true if the hard link is created, false if it fails.
375BASE_EXPORT bool CreateWinHardLink(const FilePath& to_file,
376 const FilePath& from_file);
[email protected]e3177dd52014-08-13 20:22:14377#endif
378
379// This function will return if the given file is a symlink or not.
380BASE_EXPORT bool IsLink(const FilePath& file_path);
381
382// Returns information about the given file path.
383BASE_EXPORT bool GetFileInfo(const FilePath& file_path, File::Info* info);
384
385// Sets the time of the last access and the time of the last modification.
386BASE_EXPORT bool TouchFile(const FilePath& path,
387 const Time& last_accessed,
388 const Time& last_modified);
389
grtd0bc44f2017-02-13 17:52:17390// Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The
391// underlying file descriptor (POSIX) or handle (Windows) is unconditionally
392// configured to not be propagated to child processes.
[email protected]e3177dd52014-08-13 20:22:14393BASE_EXPORT FILE* OpenFile(const FilePath& filename, const char* mode);
394
395// Closes file opened by OpenFile. Returns true on success.
396BASE_EXPORT bool CloseFile(FILE* file);
397
398// Associates a standard FILE stream with an existing File. Note that this
399// functions take ownership of the existing File.
400BASE_EXPORT FILE* FileToFILE(File file, const char* mode);
401
Greg Thompson3f7e20f42020-05-02 19:01:11402// Returns a new handle to the file underlying |file_stream|.
403BASE_EXPORT File FILEToFile(FILE* file_stream);
404
[email protected]e3177dd52014-08-13 20:22:14405// Truncates an open file to end at the location of the current file pointer.
406// This is a cross-platform analog to Windows' SetEndOfFile() function.
407BASE_EXPORT bool TruncateFile(FILE* file);
408
409// Reads at most the given number of bytes from the file into the buffer.
410// Returns the number of read bytes, or -1 on error.
411BASE_EXPORT int ReadFile(const FilePath& filename, char* data, int max_size);
412
413// Writes the given buffer into the file, overwriting any data that was
414// previously there. Returns the number of bytes written, or -1 on error.
Andrew091a47b12019-12-12 00:24:00415// If file doesn't exist, it gets created with read/write permissions for all.
[email protected]e3177dd52014-08-13 20:22:14416BASE_EXPORT int WriteFile(const FilePath& filename, const char* data,
417 int size);
418
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39419#if defined(OS_POSIX) || defined(OS_FUCHSIA)
chirantan75ea2fd2014-10-07 23:15:30420// Appends |data| to |fd|. Does not close |fd| when done. Returns true iff
421// |size| bytes of |data| were written to |fd|.
422BASE_EXPORT bool WriteFileDescriptor(const int fd, const char* data, int size);
Alex Ilin925adf02019-04-26 11:03:25423
424// Allocates disk space for the file referred to by |fd| for the byte range
425// starting at |offset| and continuing for |size| bytes. The file size will be
426// changed if |offset|+|len| is greater than the file size. Zeros will fill the
427// new space.
428// After a successful call, subsequent writes into the specified range are
429// guaranteed not to fail because of lack of disk space.
430BASE_EXPORT bool AllocateFileRegion(File* file, int64_t offset, size_t size);
[email protected]e3177dd52014-08-13 20:22:14431#endif
432
chirantan75ea2fd2014-10-07 23:15:30433// Appends |data| to |filename|. Returns true iff |size| bytes of |data| were
434// written to |filename|.
435BASE_EXPORT bool AppendToFile(const FilePath& filename,
436 const char* data,
437 int size);
[email protected]e3177dd52014-08-13 20:22:14438
439// Gets the current working directory for the process.
440BASE_EXPORT bool GetCurrentDirectory(FilePath* path);
441
442// Sets the current working directory for the process.
443BASE_EXPORT bool SetCurrentDirectory(const FilePath& path);
444
Greg Thompsonb4abcb42019-08-23 01:42:56445// The largest value attempted by GetUniquePath{Number,}.
446enum { kMaxUniqueFiles = 100 };
[email protected]e3177dd52014-08-13 20:22:14447
Greg Thompsonb4abcb42019-08-23 01:42:56448// Returns the number N that makes |path| unique when formatted as " (N)" in a
449// suffix to its basename before any file extension, where N is a number between
450// 1 and 100 (inclusive). Returns 0 if |path| does not exist (meaning that it is
451// unique as-is), or -1 if no such number can be found.
452BASE_EXPORT int GetUniquePathNumber(const FilePath& path);
453
454// Returns |path| if it does not exist. Otherwise, returns |path| with the
455// suffix " (N)" appended to its basename before any file extension, where N is
456// a number between 1 and 100 (inclusive). Returns an empty path if no such
457// number can be found.
Bruce Longd096e4892019-02-28 17:50:00458BASE_EXPORT FilePath GetUniquePath(const FilePath& path);
459
tfarina060df7e2015-12-16 05:15:32460// Sets the given |fd| to non-blocking mode.
461// Returns true if it was able to set it in the non-blocking mode, otherwise
462// false.
463BASE_EXPORT bool SetNonBlocking(int fd);
464
Victor Costanb5a0a97002019-09-08 04:55:15465// Hints the OS to prefetch the first |max_bytes| of |file_path| into its cache.
466//
467// If called at the appropriate time, this can reduce the latency incurred by
468// feature code that needs to read the file.
469//
470// |max_bytes| specifies how many bytes should be pre-fetched. It may exceed the
471// file's size. Passing in std::numeric_limits<int64_t>::max() is a convenient
472// way to get the entire file pre-fetched.
473//
474// |is_executable| specifies whether the file is to be prefetched as
475// executable code or as data. Windows treats the file backed pages in RAM
476// differently, and specifying the wrong value results in two copies in RAM.
477//
478// Returns false if prefetching definitely failed. A return value of true does
479// not guarantee that the entire desired range was prefetched.
480//
481// Calling this before using ::LoadLibrary() on Windows is more efficient memory
482// wise, but we must be sure no other threads try to LoadLibrary() the file
483// while we are doing the mapping and prefetching, or the process will get a
484// private copy of the DLL via COW.
485BASE_EXPORT bool PreReadFile(
486 const FilePath& file_path,
487 bool is_executable,
488 int64_t max_bytes = std::numeric_limits<int64_t>::max());
489
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39490#if defined(OS_POSIX) || defined(OS_FUCHSIA)
Nick Diego Yamane61bf28ba2019-03-19 14:56:37491
492// Creates a pipe. Returns true on success, otherwise false.
493// On success, |read_fd| will be set to the fd of the read side, and
494// |write_fd| will be set to the one of write side. If |non_blocking|
495// is set the pipe will be created with O_NONBLOCK|O_CLOEXEC flags set
496// otherwise flag is set to zero (default).
497BASE_EXPORT bool CreatePipe(ScopedFD* read_fd,
498 ScopedFD* write_fd,
499 bool non_blocking = false);
500
lhchavez80c77bfd2016-10-08 00:50:53501// Creates a non-blocking, close-on-exec pipe.
502// This creates a non-blocking pipe that is not intended to be shared with any
503// child process. This will be done atomically if the operating system supports
504// it. Returns true if it was able to create the pipe, otherwise false.
505BASE_EXPORT bool CreateLocalNonBlockingPipe(int fds[2]);
506
507// Sets the given |fd| to close-on-exec mode.
508// Returns true if it was able to set it in the close-on-exec mode, otherwise
509// false.
510BASE_EXPORT bool SetCloseOnExec(int fd);
511
[email protected]e3177dd52014-08-13 20:22:14512// Test that |path| can only be changed by a given user and members of
513// a given set of groups.
514// Specifically, test that all parts of |path| under (and including) |base|:
515// * Exist.
516// * Are owned by a specific user.
517// * Are not writable by all users.
518// * Are owned by a member of a given set of groups, or are not writable by
519// their group.
520// * Are not symbolic links.
521// This is useful for checking that a config file is administrator-controlled.
522// |base| must contain |path|.
523BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
524 const base::FilePath& path,
525 uid_t owner_uid,
526 const std::set<gid_t>& group_gids);
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39527#endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14528
529#if defined(OS_MACOSX) && !defined(OS_IOS)
530// Is |path| writable only by a user with administrator privileges?
531// This function uses Mac OS conventions. The super user is assumed to have
532// uid 0, and the administrator group is assumed to be named "admin".
533// Testing that |path|, and every parent directory including the root of
534// the filesystem, are owned by the superuser, controlled by the group
535// "admin", are not writable by all users, and contain no symbolic links.
536// Will return false if |path| does not exist.
537BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
538#endif // defined(OS_MACOSX) && !defined(OS_IOS)
539
540// Returns the maximum length of path component on the volume containing
541// the directory |path|, in the number of FilePath::CharType, or -1 on failure.
542BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
543
rayb0088ee52017-04-26 22:35:08544#if defined(OS_LINUX) || defined(OS_AIX)
[email protected]e3177dd52014-08-13 20:22:14545// Broad categories of file systems as returned by statfs() on Linux.
546enum FileSystemType {
547 FILE_SYSTEM_UNKNOWN, // statfs failed.
548 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS.
549 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2
550 FILE_SYSTEM_NFS,
551 FILE_SYSTEM_SMB,
552 FILE_SYSTEM_CODA,
553 FILE_SYSTEM_MEMORY, // in-memory file system
554 FILE_SYSTEM_CGROUP, // cgroup control.
555 FILE_SYSTEM_OTHER, // any other value.
556 FILE_SYSTEM_TYPE_COUNT
557};
558
559// Attempts determine the FileSystemType for |path|.
560// Returns false if |path| doesn't exist.
561BASE_EXPORT bool GetFileSystemType(const FilePath& path, FileSystemType* type);
562#endif
563
Fabrice de Gans-Riberi306871de2018-05-16 19:38:39564#if defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]e3177dd52014-08-13 20:22:14565// Get a temporary directory for shared memory files. The directory may depend
566// on whether the destination is intended for executable files, which in turn
567// depends on how /dev/shmem was mounted. As a result, you must supply whether
568// you intend to create executable shmem segments so this function can find
569// an appropriate location.
570BASE_EXPORT bool GetShmemTempDir(bool executable, FilePath* path);
571#endif
572
573// Internal --------------------------------------------------------------------
574
575namespace internal {
576
577// Same as Move but allows paths with traversal components.
578// Use only with extreme care.
579BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
580 const FilePath& to_path);
581
[email protected]e3177dd52014-08-13 20:22:14582#if defined(OS_WIN)
583// Copy from_path to to_path recursively and then delete from_path recursively.
584// Returns true if all operations succeed.
585// This function simulates Move(), but unlike Move() it works across volumes.
586// This function is not transactional.
587BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
588 const FilePath& to_path);
589#endif // defined(OS_WIN)
590
Victor Costanb5a0a97002019-09-08 04:55:15591// Used by PreReadFile() when no kernel support for prefetching is available.
592bool PreReadFileSlow(const FilePath& file_path, int64_t max_bytes);
593
[email protected]e3177dd52014-08-13 20:22:14594} // namespace internal
595} // namespace base
596
597#endif // BASE_FILES_FILE_UTIL_H_