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 5 // This file contains utility functions for dealing with the local 6 // filesystem. 7 8 #ifndef BASE_FILES_FILE_UTIL_H_ 9 #define BASE_FILES_FILE_UTIL_H_ 10 11 #include <stddef.h> 12 #include <stdint.h> 13 #include <stdio.h> 14 15 #include <set> 16 #include <string> 17 #include <vector> 18 19 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 20 #include <sys/stat.h> 21 #include <unistd.h> 22 #endif 23 24 #include "base/files/file.h" 25 #include "base/files/file_path.h" 26 #include "util/build_config.h" 27 28 #if defined(OS_WIN) 29 #include <windows.h> 30 #elif defined(OS_POSIX) || defined(OS_FUCHSIA) 31 #include "base/logging.h" 32 #include "base/posix/eintr_wrapper.h" 33 #endif 34 35 namespace base { 36 37 class Environment; 38 39 //----------------------------------------------------------------------------- 40 // Functions that involve filesystem access or modification: 41 42 // Returns an absolute version of a relative path. Returns an empty path on 43 // error. On POSIX, this function fails if the path does not exist. This 44 // function can result in I/O so it can be slow. 45 FilePath MakeAbsoluteFilePath(const FilePath& input); 46 47 // Returns the total number of bytes used by all the files under |root_path|. 48 // If the path does not exist the function returns 0. 49 // 50 // This function is implemented using the FileEnumerator class so it is not 51 // particularly speedy in any platform. 52 int64_t ComputeDirectorySize(const FilePath& root_path); 53 54 // Deletes the given path, whether it's a file or a directory. 55 // If it's a directory, it's perfectly happy to delete all of the 56 // directory's contents. Passing true to recursive deletes 57 // subdirectories and their contents as well. 58 // Returns true if successful, false otherwise. It is considered successful 59 // to attempt to delete a file that does not exist. 60 // 61 // In posix environment and if |path| is a symbolic link, this deletes only 62 // the symlink. (even if the symlink points to a non-existent file) 63 // 64 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT 65 // TO "rm -rf", SO USE WITH CAUTION. 66 bool DeleteFile(const FilePath& path, bool recursive); 67 68 #if defined(OS_WIN) 69 // Schedules to delete the given path, whether it's a file or a directory, until 70 // the operating system is restarted. 71 // Note: 72 // 1) The file/directory to be deleted should exist in a temp folder. 73 // 2) The directory to be deleted must be empty. 74 bool DeleteFileAfterReboot(const FilePath& path); 75 #endif 76 77 // Renames file |from_path| to |to_path|. Both paths must be on the same 78 // volume, or the function will fail. Destination file will be created 79 // if it doesn't exist. Prefer this function over Move when dealing with 80 // temporary files. On Windows it preserves attributes of the target file. 81 // Returns true on success, leaving *error unchanged. 82 // Returns false on failure and sets *error appropriately, if it is non-NULL. 83 bool ReplaceFile(const FilePath& from_path, 84 const FilePath& to_path, 85 File::Error* error); 86 87 // Returns true if the given path exists on the local filesystem, 88 // false otherwise. 89 bool PathExists(const FilePath& path); 90 91 // Returns true if the given path is writable by the user, false otherwise. 92 bool PathIsWritable(const FilePath& path); 93 94 // Returns true if the given path exists and is a directory, false otherwise. 95 bool DirectoryExists(const FilePath& path); 96 97 // Returns true if the contents of the two files given are equal, false 98 // otherwise. If either file can't be read, returns false. 99 bool ContentsEqual(const FilePath& filename1, const FilePath& filename2); 100 101 // Returns true if the contents of the two text files given are equal, false 102 // otherwise. This routine treats "\r\n" and "\n" as equivalent. 103 bool TextContentsEqual(const FilePath& filename1, const FilePath& filename2); 104 105 // Reads the file at |path| into |contents| and returns true on success and 106 // false on error. For security reasons, a |path| containing path traversal 107 // components ('..') is treated as a read error and |contents| is set to empty. 108 // In case of I/O error, |contents| holds the data that could be read from the 109 // file before the error occurred. 110 // |contents| may be NULL, in which case this function is useful for its side 111 // effect of priming the disk cache (could be used for unit tests). 112 bool ReadFileToString(const FilePath& path, std::string* contents); 113 114 // Reads the file at |path| into |contents| and returns true on success and 115 // false on error. For security reasons, a |path| containing path traversal 116 // components ('..') is treated as a read error and |contents| is set to empty. 117 // In case of I/O error, |contents| holds the data that could be read from the 118 // file before the error occurred. When the file size exceeds |max_size|, the 119 // function returns false with |contents| holding the file truncated to 120 // |max_size|. 121 // |contents| may be NULL, in which case this function is useful for its side 122 // effect of priming the disk cache (could be used for unit tests). 123 bool ReadFileToStringWithMaxSize(const FilePath& path, 124 std::string* contents, 125 size_t max_size); 126 127 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 128 129 // Performs the same function as CreateAndOpenTemporaryFileInDir(), but 130 // returns the file-descriptor wrapped in a ScopedFD rather than a File. 131 ScopedFD CreateAndOpenFdForTemporaryFileInDir(const FilePath& dir, 132 FilePath* path); 133 134 #endif 135 136 #if defined(OS_POSIX) 137 138 // Creates a symbolic link at |symlink| pointing to |target|. Returns 139 // false on failure. 140 bool CreateSymbolicLink(const FilePath& target, const FilePath& symlink); 141 142 // Reads the given |symlink| and returns where it points to in |target|. 143 // Returns false upon failure. 144 bool ReadSymbolicLink(const FilePath& symlink, FilePath* target); 145 146 // Bits and masks of the file permission. 147 enum FilePermissionBits { 148 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO, 149 FILE_PERMISSION_USER_MASK = S_IRWXU, 150 FILE_PERMISSION_GROUP_MASK = S_IRWXG, 151 FILE_PERMISSION_OTHERS_MASK = S_IRWXO, 152 153 FILE_PERMISSION_READ_BY_USER = S_IRUSR, 154 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR, 155 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR, 156 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP, 157 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP, 158 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP, 159 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH, 160 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH, 161 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH, 162 }; 163 164 // Reads the permission of the given |path|, storing the file permission 165 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of 166 // a file which the symlink points to. 167 bool GetPosixFilePermissions(const FilePath& path, int* mode); 168 // Sets the permission of the given |path|. If |path| is symbolic link, sets 169 // the permission of a file which the symlink points to. 170 bool SetPosixFilePermissions(const FilePath& path, int mode); 171 172 // Returns true iff |executable| can be found in any directory specified by the 173 // environment variable in |env|. 174 bool ExecutableExistsInPath(Environment* env, 175 const FilePath::StringType& executable); 176 177 #endif // OS_POSIX 178 179 // Returns true if the given directory is empty 180 bool IsDirectoryEmpty(const FilePath& dir_path); 181 182 // Get the temporary directory provided by the system. 183 bool GetTempDir(FilePath* path); 184 185 // Returns a new temporary file in |dir| with a unique name. On success, 186 // |temp_file| is populated with the full path to the created file. 187 File CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* temp_file); 188 189 // Create a new directory. If prefix is provided, the new directory name is in 190 // the format of prefixyyyy. 191 // NOTE: prefix is ignored in the POSIX implementation. 192 // If success, return true and output the full path of the directory created. 193 bool CreateNewTempDirectory(const FilePath::StringType& prefix, 194 FilePath* new_temp_path); 195 196 // Create a directory within another directory. 197 // Extra characters will be appended to |prefix| to ensure that the 198 // new directory does not have the same name as an existing directory. 199 bool CreateTemporaryDirInDir(const FilePath& base_dir, 200 const FilePath::StringType& prefix, 201 FilePath* new_dir); 202 203 // Creates a directory, as well as creating any parent directories, if they 204 // don't exist. Returns 'true' on successful creation, or if the directory 205 // already exists. The directory is only readable by the current user. 206 // Returns true on success, leaving *error unchanged. 207 // Returns false on failure and sets *error appropriately, if it is non-NULL. 208 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error); 209 210 // Backward-compatible convenience method for the above. 211 bool CreateDirectory(const FilePath& full_path); 212 213 // Returns the file size. Returns true on success. 214 bool GetFileSize(const FilePath& file_path, int64_t* file_size); 215 216 // Sets |real_path| to |path| with symbolic links and junctions expanded. 217 // On windows, make sure the path starts with a lettered drive. 218 // |path| must reference a file. Function will fail if |path| points to 219 // a directory or to a nonexistent path. On windows, this function will 220 // fail if |path| is a junction or symlink that points to an empty file, 221 // or if |real_path| would be longer than MAX_PATH characters. 222 bool NormalizeFilePath(const FilePath& path, FilePath* real_path); 223 224 #if defined(OS_WIN) 225 226 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."), 227 // return in |drive_letter_path| the equivalent path that starts with 228 // a drive letter ("C:\..."). Return false if no such path exists. 229 bool DevicePathToDriveLetterPath(const FilePath& device_path, 230 FilePath* drive_letter_path); 231 232 // Given an existing file in |path|, set |real_path| to the path 233 // in native NT format, of the form "\Device\HarddiskVolumeXX\..". 234 // Returns false if the path can not be found. Empty files cannot 235 // be resolved with this function. 236 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path); 237 #endif 238 239 // This function will return if the given file is a symlink or not. 240 bool IsLink(const FilePath& file_path); 241 242 // Returns information about the given file path. 243 bool GetFileInfo(const FilePath& file_path, File::Info* info); 244 245 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The 246 // underlying file descriptor (POSIX) or handle (Windows) is unconditionally 247 // configured to not be propagated to child processes. 248 FILE* OpenFile(const FilePath& filename, const char* mode); 249 250 // Closes file opened by OpenFile. Returns true on success. 251 bool CloseFile(FILE* file); 252 253 // Associates a standard FILE stream with an existing File. Note that this 254 // functions take ownership of the existing File. 255 FILE* FileToFILE(File file, const char* mode); 256 257 // Truncates an open file to end at the location of the current file pointer. 258 // This is a cross-platform analog to Windows' SetEndOfFile() function. 259 bool TruncateFile(FILE* file); 260 261 // Reads at most the given number of bytes from the file into the buffer. 262 // Returns the number of read bytes, or -1 on error. 263 int ReadFile(const FilePath& filename, char* data, int max_size); 264 265 // Writes the given buffer into the file, overwriting any data that was 266 // previously there. Returns the number of bytes written, or -1 on error. 267 int WriteFile(const FilePath& filename, const char* data, int size); 268 269 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 270 // Appends |data| to |fd|. Does not close |fd| when done. Returns true iff 271 // |size| bytes of |data| were written to |fd|. 272 bool WriteFileDescriptor(const int fd, const char* data, int size); 273 #endif 274 275 // Appends |data| to |filename|. Returns true iff |size| bytes of |data| were 276 // written to |filename|. 277 bool AppendToFile(const FilePath& filename, const char* data, int size); 278 279 // Gets the current working directory for the process. 280 bool GetCurrentDirectory(FilePath* path); 281 282 // Sets the current working directory for the process. 283 bool SetCurrentDirectory(const FilePath& path); 284 285 // Attempts to find a number that can be appended to the |path| to make it 286 // unique. If |path| does not exist, 0 is returned. If it fails to find such 287 // a number, -1 is returned. If |suffix| is not empty, also checks the 288 // existence of it with the given suffix. 289 int GetUniquePathNumber(const FilePath& path, 290 const FilePath::StringType& suffix); 291 292 // Sets the given |fd| to non-blocking mode. 293 // Returns true if it was able to set it in the non-blocking mode, otherwise 294 // false. 295 bool SetNonBlocking(int fd); 296 297 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 298 // Creates a non-blocking, close-on-exec pipe. 299 // This creates a non-blocking pipe that is not intended to be shared with any 300 // child process. This will be done atomically if the operating system supports 301 // it. Returns true if it was able to create the pipe, otherwise false. 302 bool CreateLocalNonBlockingPipe(int fds[2]); 303 304 // Sets the given |fd| to close-on-exec mode. 305 // Returns true if it was able to set it in the close-on-exec mode, otherwise 306 // false. 307 bool SetCloseOnExec(int fd); 308 309 // Test that |path| can only be changed by a given user and members of 310 // a given set of groups. 311 // Specifically, test that all parts of |path| under (and including) |base|: 312 // * Exist. 313 // * Are owned by a specific user. 314 // * Are not writable by all users. 315 // * Are owned by a member of a given set of groups, or are not writable by 316 // their group. 317 // * Are not symbolic links. 318 // This is useful for checking that a config file is administrator-controlled. 319 // |base| must contain |path|. 320 bool VerifyPathControlledByUser(const base::FilePath& base, 321 const base::FilePath& path, 322 uid_t owner_uid, 323 const std::set<gid_t>& group_gids); 324 #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) 325 326 #if defined(OS_MACOSX) && !defined(OS_IOS) 327 // Is |path| writable only by a user with administrator privileges? 328 // This function uses Mac OS conventions. The super user is assumed to have 329 // uid 0, and the administrator group is assumed to be named "admin". 330 // Testing that |path|, and every parent directory including the root of 331 // the filesystem, are owned by the superuser, controlled by the group 332 // "admin", are not writable by all users, and contain no symbolic links. 333 // Will return false if |path| does not exist. 334 bool VerifyPathControlledByAdmin(const base::FilePath& path); 335 #endif // defined(OS_MACOSX) && !defined(OS_IOS) 336 337 // Returns the maximum length of path component on the volume containing 338 // the directory |path|, in the number of FilePath::CharType, or -1 on failure. 339 int GetMaximumPathComponentLength(const base::FilePath& path); 340 341 #if defined(OS_LINUX) || defined(OS_AIX) || defined(OS_BSD) 342 // Broad categories of file systems as returned by statfs() on Linux. 343 enum FileSystemType { 344 FILE_SYSTEM_UNKNOWN, // statfs failed. 345 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS. 346 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2 347 FILE_SYSTEM_NFS, 348 FILE_SYSTEM_SMB, 349 FILE_SYSTEM_CODA, 350 FILE_SYSTEM_MEMORY, // in-memory file system 351 FILE_SYSTEM_CGROUP, // cgroup control. 352 FILE_SYSTEM_OTHER, // any other value. 353 FILE_SYSTEM_TYPE_COUNT 354 }; 355 356 // Attempts determine the FileSystemType for |path|. 357 // Returns false if |path| doesn't exist. 358 bool GetFileSystemType(const FilePath& path, FileSystemType* type); 359 #endif 360 361 } // namespace base 362 363 #endif // BASE_FILES_FILE_UTIL_H_ 364