file_util.h 31 KB

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