file_util.h 29 KB

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