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) 128 129 // Creates a symbolic link at |symlink| pointing to |target|. Returns 130 // false on failure. 131 bool CreateSymbolicLink(const FilePath& target, const FilePath& symlink); 132 133 // Reads the given |symlink| and returns where it points to in |target|. 134 // Returns false upon failure. 135 bool ReadSymbolicLink(const FilePath& symlink, FilePath* target); 136 137 // Bits and masks of the file permission. 138 enum FilePermissionBits { 139 FILE_PERMISSION_MASK = S_IRWXU | S_IRWXG | S_IRWXO, 140 FILE_PERMISSION_USER_MASK = S_IRWXU, 141 FILE_PERMISSION_GROUP_MASK = S_IRWXG, 142 FILE_PERMISSION_OTHERS_MASK = S_IRWXO, 143 144 FILE_PERMISSION_READ_BY_USER = S_IRUSR, 145 FILE_PERMISSION_WRITE_BY_USER = S_IWUSR, 146 FILE_PERMISSION_EXECUTE_BY_USER = S_IXUSR, 147 FILE_PERMISSION_READ_BY_GROUP = S_IRGRP, 148 FILE_PERMISSION_WRITE_BY_GROUP = S_IWGRP, 149 FILE_PERMISSION_EXECUTE_BY_GROUP = S_IXGRP, 150 FILE_PERMISSION_READ_BY_OTHERS = S_IROTH, 151 FILE_PERMISSION_WRITE_BY_OTHERS = S_IWOTH, 152 FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH, 153 }; 154 155 // Reads the permission of the given |path|, storing the file permission 156 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of 157 // a file which the symlink points to. 158 bool GetPosixFilePermissions(const FilePath& path, int* mode); 159 // Sets the permission of the given |path|. If |path| is symbolic link, sets 160 // the permission of a file which the symlink points to. 161 bool SetPosixFilePermissions(const FilePath& path, int mode); 162 163 // Returns true iff |executable| can be found in any directory specified by the 164 // environment variable in |env|. 165 bool ExecutableExistsInPath(Environment* env, 166 const FilePath::StringType& executable); 167 168 #endif // OS_POSIX 169 170 // Returns true if the given directory is empty 171 bool IsDirectoryEmpty(const FilePath& dir_path); 172 173 // Get the temporary directory provided by the system. 174 bool GetTempDir(FilePath* path); 175 176 // Create a new directory. If prefix is provided, the new directory name is in 177 // the format of prefixyyyy. 178 // NOTE: prefix is ignored in the POSIX implementation. 179 // If success, return true and output the full path of the directory created. 180 bool CreateNewTempDirectory(const FilePath::StringType& prefix, 181 FilePath* new_temp_path); 182 183 // Create a directory within another directory. 184 // Extra characters will be appended to |prefix| to ensure that the 185 // new directory does not have the same name as an existing directory. 186 bool CreateTemporaryDirInDir(const FilePath& base_dir, 187 const FilePath::StringType& prefix, 188 FilePath* new_dir); 189 190 // Creates a directory, as well as creating any parent directories, if they 191 // don't exist. Returns 'true' on successful creation, or if the directory 192 // already exists. The directory is only readable by the current user. 193 // Returns true on success, leaving *error unchanged. 194 // Returns false on failure and sets *error appropriately, if it is non-NULL. 195 bool CreateDirectoryAndGetError(const FilePath& full_path, File::Error* error); 196 197 // Backward-compatible convenience method for the above. 198 bool CreateDirectory(const FilePath& full_path); 199 200 // Returns the file size. Returns true on success. 201 bool GetFileSize(const FilePath& file_path, int64_t* file_size); 202 203 // Sets |real_path| to |path| with symbolic links and junctions expanded. 204 // On windows, make sure the path starts with a lettered drive. 205 // |path| must reference a file. Function will fail if |path| points to 206 // a directory or to a nonexistent path. On windows, this function will 207 // fail if |path| is a junction or symlink that points to an empty file, 208 // or if |real_path| would be longer than MAX_PATH characters. 209 bool NormalizeFilePath(const FilePath& path, FilePath* real_path); 210 211 #if defined(OS_WIN) 212 213 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."), 214 // return in |drive_letter_path| the equivalent path that starts with 215 // a drive letter ("C:\..."). Return false if no such path exists. 216 bool DevicePathToDriveLetterPath(const FilePath& device_path, 217 FilePath* drive_letter_path); 218 219 // Given an existing file in |path|, set |real_path| to the path 220 // in native NT format, of the form "\Device\HarddiskVolumeXX\..". 221 // Returns false if the path can not be found. Empty files cannot 222 // be resolved with this function. 223 bool NormalizeToNativeFilePath(const FilePath& path, FilePath* nt_path); 224 #endif 225 226 // This function will return if the given file is a symlink or not. 227 bool IsLink(const FilePath& file_path); 228 229 // Returns information about the given file path. 230 bool GetFileInfo(const FilePath& file_path, File::Info* info); 231 232 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success. The 233 // underlying file descriptor (POSIX) or handle (Windows) is unconditionally 234 // configured to not be propagated to child processes. 235 FILE* OpenFile(const FilePath& filename, const char* mode); 236 237 // Closes file opened by OpenFile. Returns true on success. 238 bool CloseFile(FILE* file); 239 240 // Associates a standard FILE stream with an existing File. Note that this 241 // functions take ownership of the existing File. 242 FILE* FileToFILE(File file, const char* mode); 243 244 // Truncates an open file to end at the location of the current file pointer. 245 // This is a cross-platform analog to Windows' SetEndOfFile() function. 246 bool TruncateFile(FILE* file); 247 248 // Reads at most the given number of bytes from the file into the buffer. 249 // Returns the number of read bytes, or -1 on error. 250 int ReadFile(const FilePath& filename, char* data, int max_size); 251 252 // Writes the given buffer into the file, overwriting any data that was 253 // previously there. Returns the number of bytes written, or -1 on error. 254 int WriteFile(const FilePath& filename, const char* data, int size); 255 256 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 257 // Appends |data| to |fd|. Does not close |fd| when done. Returns true iff 258 // |size| bytes of |data| were written to |fd|. 259 bool WriteFileDescriptor(const int fd, const char* data, int size); 260 #endif 261 262 // Appends |data| to |filename|. Returns true iff |size| bytes of |data| were 263 // written to |filename|. 264 bool AppendToFile(const FilePath& filename, const char* data, int size); 265 266 // Gets the current working directory for the process. 267 bool GetCurrentDirectory(FilePath* path); 268 269 // Sets the current working directory for the process. 270 bool SetCurrentDirectory(const FilePath& path); 271 272 // Attempts to find a number that can be appended to the |path| to make it 273 // unique. If |path| does not exist, 0 is returned. If it fails to find such 274 // a number, -1 is returned. If |suffix| is not empty, also checks the 275 // existence of it with the given suffix. 276 int GetUniquePathNumber(const FilePath& path, 277 const FilePath::StringType& suffix); 278 279 // Sets the given |fd| to non-blocking mode. 280 // Returns true if it was able to set it in the non-blocking mode, otherwise 281 // false. 282 bool SetNonBlocking(int fd); 283 284 #if defined(OS_POSIX) || defined(OS_FUCHSIA) 285 // Creates a non-blocking, close-on-exec pipe. 286 // This creates a non-blocking pipe that is not intended to be shared with any 287 // child process. This will be done atomically if the operating system supports 288 // it. Returns true if it was able to create the pipe, otherwise false. 289 bool CreateLocalNonBlockingPipe(int fds[2]); 290 291 // Sets the given |fd| to close-on-exec mode. 292 // Returns true if it was able to set it in the close-on-exec mode, otherwise 293 // false. 294 bool SetCloseOnExec(int fd); 295 296 // Test that |path| can only be changed by a given user and members of 297 // a given set of groups. 298 // Specifically, test that all parts of |path| under (and including) |base|: 299 // * Exist. 300 // * Are owned by a specific user. 301 // * Are not writable by all users. 302 // * Are owned by a member of a given set of groups, or are not writable by 303 // their group. 304 // * Are not symbolic links. 305 // This is useful for checking that a config file is administrator-controlled. 306 // |base| must contain |path|. 307 bool VerifyPathControlledByUser(const base::FilePath& base, 308 const base::FilePath& path, 309 uid_t owner_uid, 310 const std::set<gid_t>& group_gids); 311 #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) 312 313 #if defined(OS_MACOSX) && !defined(OS_IOS) 314 // Is |path| writable only by a user with administrator privileges? 315 // This function uses Mac OS conventions. The super user is assumed to have 316 // uid 0, and the administrator group is assumed to be named "admin". 317 // Testing that |path|, and every parent directory including the root of 318 // the filesystem, are owned by the superuser, controlled by the group 319 // "admin", are not writable by all users, and contain no symbolic links. 320 // Will return false if |path| does not exist. 321 bool VerifyPathControlledByAdmin(const base::FilePath& path); 322 #endif // defined(OS_MACOSX) && !defined(OS_IOS) 323 324 // Returns the maximum length of path component on the volume containing 325 // the directory |path|, in the number of FilePath::CharType, or -1 on failure. 326 int GetMaximumPathComponentLength(const base::FilePath& path); 327 328 #if defined(OS_LINUX) || defined(OS_AIX) || defined(OS_BSD) 329 // Broad categories of file systems as returned by statfs() on Linux. 330 enum FileSystemType { 331 FILE_SYSTEM_UNKNOWN, // statfs failed. 332 FILE_SYSTEM_0, // statfs.f_type == 0 means unknown, may indicate AFS. 333 FILE_SYSTEM_ORDINARY, // on-disk filesystem like ext2 334 FILE_SYSTEM_NFS, 335 FILE_SYSTEM_SMB, 336 FILE_SYSTEM_CODA, 337 FILE_SYSTEM_MEMORY, // in-memory file system 338 FILE_SYSTEM_CGROUP, // cgroup control. 339 FILE_SYSTEM_OTHER, // any other value. 340 FILE_SYSTEM_TYPE_COUNT 341 }; 342 343 // Attempts determine the FileSystemType for |path|. 344 // Returns false if |path| doesn't exist. 345 bool GetFileSystemType(const FilePath& path, FileSystemType* type); 346 #endif 347 348 } // namespace base 349 350 #endif // BASE_FILES_FILE_UTIL_H_ 351