security/sandbox/chromium/base/file_util.h

Wed, 31 Dec 2014 07:16:47 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 07:16:47 +0100
branch
TOR_BUG_9701
changeset 3
141e0f1194b1
permissions
-rw-r--r--

Revert simplistic fix pending revisit of Mozilla integration attempt.

     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.
     5 // This file contains utility functions for dealing with the local
     6 // filesystem.
     8 #ifndef BASE_FILE_UTIL_H_
     9 #define BASE_FILE_UTIL_H_
    11 #include "build/build_config.h"
    13 #if defined(OS_WIN)
    14 #include <windows.h>
    15 #elif defined(OS_POSIX)
    16 #include <sys/stat.h>
    17 #include <unistd.h>
    18 #endif
    20 #include <stdio.h>
    22 #include <set>
    23 #include <string>
    24 #include <vector>
    26 #include "base/base_export.h"
    27 #include "base/basictypes.h"
    28 #include "base/files/file_path.h"
    29 #include "base/memory/scoped_ptr.h"
    30 #include "base/platform_file.h"
    31 #include "base/strings/string16.h"
    33 #if defined(OS_POSIX)
    34 #include "base/file_descriptor_posix.h"
    35 #include "base/logging.h"
    36 #include "base/posix/eintr_wrapper.h"
    37 #endif
    39 namespace base {
    41 class Time;
    43 extern bool g_bug108724_debug;
    45 //-----------------------------------------------------------------------------
    46 // Functions that involve filesystem access or modification:
    48 // Returns an absolute version of a relative path. Returns an empty path on
    49 // error. On POSIX, this function fails if the path does not exist. This
    50 // function can result in I/O so it can be slow.
    51 BASE_EXPORT FilePath MakeAbsoluteFilePath(const FilePath& input);
    53 // Returns the total number of bytes used by all the files under |root_path|.
    54 // If the path does not exist the function returns 0.
    55 //
    56 // This function is implemented using the FileEnumerator class so it is not
    57 // particularly speedy in any platform.
    58 BASE_EXPORT int64 ComputeDirectorySize(const FilePath& root_path);
    60 // Deletes the given path, whether it's a file or a directory.
    61 // If it's a directory, it's perfectly happy to delete all of the
    62 // directory's contents.  Passing true to recursive deletes
    63 // subdirectories and their contents as well.
    64 // Returns true if successful, false otherwise. It is considered successful
    65 // to attempt to delete a file that does not exist.
    66 //
    67 // In posix environment and if |path| is a symbolic link, this deletes only
    68 // the symlink. (even if the symlink points to a non-existent file)
    69 //
    70 // WARNING: USING THIS WITH recursive==true IS EQUIVALENT
    71 //          TO "rm -rf", SO USE WITH CAUTION.
    72 BASE_EXPORT bool DeleteFile(const FilePath& path, bool recursive);
    74 #if defined(OS_WIN)
    75 // Schedules to delete the given path, whether it's a file or a directory, until
    76 // the operating system is restarted.
    77 // Note:
    78 // 1) The file/directory to be deleted should exist in a temp folder.
    79 // 2) The directory to be deleted must be empty.
    80 BASE_EXPORT bool DeleteFileAfterReboot(const FilePath& path);
    81 #endif
    83 // Moves the given path, whether it's a file or a directory.
    84 // If a simple rename is not possible, such as in the case where the paths are
    85 // on different volumes, this will attempt to copy and delete. Returns
    86 // true for success.
    87 // This function fails if either path contains traversal components ('..').
    88 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                              PlatformFileError* error);
   100 // Copies a single file. Use CopyDirectory to copy directories.
   101 // This function fails if either path contains traversal components ('..').
   102 BASE_EXPORT bool CopyFile(const FilePath& from_path, const FilePath& to_path);
   104 // Copies the given path, and optionally all subdirectories and their contents
   105 // as well.
   106 //
   107 // If there are files existing under to_path, always overwrite. Returns true
   108 // if successful, false otherwise. Wildcards on the names are not supported.
   109 //
   110 // If you only need to copy a file use CopyFile, it's faster.
   111 BASE_EXPORT bool CopyDirectory(const FilePath& from_path,
   112                                const FilePath& to_path,
   113                                bool recursive);
   115 // Returns true if the given path exists on the local filesystem,
   116 // false otherwise.
   117 BASE_EXPORT bool PathExists(const FilePath& path);
   119 // Returns true if the given path is writable by the user, false otherwise.
   120 BASE_EXPORT bool PathIsWritable(const FilePath& path);
   122 // Returns true if the given path exists and is a directory, false otherwise.
   123 BASE_EXPORT bool DirectoryExists(const FilePath& path);
   125 // Returns true if the contents of the two files given are equal, false
   126 // otherwise.  If either file can't be read, returns false.
   127 BASE_EXPORT bool ContentsEqual(const FilePath& filename1,
   128                                const FilePath& filename2);
   130 // Returns true if the contents of the two text files given are equal, false
   131 // otherwise.  This routine treats "\r\n" and "\n" as equivalent.
   132 BASE_EXPORT bool TextContentsEqual(const FilePath& filename1,
   133                                    const FilePath& filename2);
   135 // Read the file at |path| into |contents|, returning true on success.
   136 // This function fails if the |path| contains path traversal components ('..').
   137 // |contents| may be NULL, in which case this function is useful for its
   138 // side effect of priming the disk cache.
   139 // Useful for unit tests.
   140 BASE_EXPORT bool ReadFileToString(const FilePath& path, std::string* contents);
   142 }  // namespace base
   144 // -----------------------------------------------------------------------------
   146 namespace file_util {
   148 #if defined(OS_POSIX)
   149 // Read exactly |bytes| bytes from file descriptor |fd|, storing the result
   150 // in |buffer|. This function is protected against EINTR and partial reads.
   151 // Returns true iff |bytes| bytes have been successfully read from |fd|.
   152 BASE_EXPORT bool ReadFromFD(int fd, char* buffer, size_t bytes);
   154 // Creates a symbolic link at |symlink| pointing to |target|.  Returns
   155 // false on failure.
   156 BASE_EXPORT bool CreateSymbolicLink(const base::FilePath& target,
   157                                     const base::FilePath& symlink);
   159 // Reads the given |symlink| and returns where it points to in |target|.
   160 // Returns false upon failure.
   161 BASE_EXPORT bool ReadSymbolicLink(const base::FilePath& symlink,
   162                                   base::FilePath* target);
   164 // Bits ans masks of the file permission.
   165 enum FilePermissionBits {
   166   FILE_PERMISSION_MASK              = S_IRWXU | S_IRWXG | S_IRWXO,
   167   FILE_PERMISSION_USER_MASK         = S_IRWXU,
   168   FILE_PERMISSION_GROUP_MASK        = S_IRWXG,
   169   FILE_PERMISSION_OTHERS_MASK       = S_IRWXO,
   171   FILE_PERMISSION_READ_BY_USER      = S_IRUSR,
   172   FILE_PERMISSION_WRITE_BY_USER     = S_IWUSR,
   173   FILE_PERMISSION_EXECUTE_BY_USER   = S_IXUSR,
   174   FILE_PERMISSION_READ_BY_GROUP     = S_IRGRP,
   175   FILE_PERMISSION_WRITE_BY_GROUP    = S_IWGRP,
   176   FILE_PERMISSION_EXECUTE_BY_GROUP  = S_IXGRP,
   177   FILE_PERMISSION_READ_BY_OTHERS    = S_IROTH,
   178   FILE_PERMISSION_WRITE_BY_OTHERS   = S_IWOTH,
   179   FILE_PERMISSION_EXECUTE_BY_OTHERS = S_IXOTH,
   180 };
   182 // Reads the permission of the given |path|, storing the file permission
   183 // bits in |mode|. If |path| is symbolic link, |mode| is the permission of
   184 // a file which the symlink points to.
   185 BASE_EXPORT bool GetPosixFilePermissions(const base::FilePath& path,
   186                                          int* mode);
   187 // Sets the permission of the given |path|. If |path| is symbolic link, sets
   188 // the permission of a file which the symlink points to.
   189 BASE_EXPORT bool SetPosixFilePermissions(const base::FilePath& path,
   190                                          int mode);
   191 #endif  // defined(OS_POSIX)
   193 // Return true if the given directory is empty
   194 BASE_EXPORT bool IsDirectoryEmpty(const base::FilePath& dir_path);
   196 // Get the temporary directory provided by the system.
   197 // WARNING: DON'T USE THIS. If you want to create a temporary file, use one of
   198 // the functions below.
   199 BASE_EXPORT bool GetTempDir(base::FilePath* path);
   200 // Get a temporary directory for shared memory files.
   201 // Only useful on POSIX; redirects to GetTempDir() on Windows.
   202 BASE_EXPORT bool GetShmemTempDir(base::FilePath* path, bool executable);
   204 // Get the home directory.  This is more complicated than just getenv("HOME")
   205 // as it knows to fall back on getpwent() etc.
   206 BASE_EXPORT base::FilePath GetHomeDir();
   208 // Creates a temporary file. The full path is placed in |path|, and the
   209 // function returns true if was successful in creating the file. The file will
   210 // be empty and all handles closed after this function returns.
   211 BASE_EXPORT bool CreateTemporaryFile(base::FilePath* path);
   213 // Same as CreateTemporaryFile but the file is created in |dir|.
   214 BASE_EXPORT bool CreateTemporaryFileInDir(const base::FilePath& dir,
   215                                           base::FilePath* temp_file);
   217 // Create and open a temporary file.  File is opened for read/write.
   218 // The full path is placed in |path|.
   219 // Returns a handle to the opened file or NULL if an error occurred.
   220 BASE_EXPORT FILE* CreateAndOpenTemporaryFile(base::FilePath* path);
   221 // Like above but for shmem files.  Only useful for POSIX.
   222 // The executable flag says the file needs to support using
   223 // mprotect with PROT_EXEC after mapping.
   224 BASE_EXPORT FILE* CreateAndOpenTemporaryShmemFile(base::FilePath* path,
   225                                                   bool executable);
   226 // Similar to CreateAndOpenTemporaryFile, but the file is created in |dir|.
   227 BASE_EXPORT FILE* CreateAndOpenTemporaryFileInDir(const base::FilePath& dir,
   228                                                   base::FilePath* path);
   230 // Create a new directory. If prefix is provided, the new directory name is in
   231 // the format of prefixyyyy.
   232 // NOTE: prefix is ignored in the POSIX implementation.
   233 // If success, return true and output the full path of the directory created.
   234 BASE_EXPORT bool CreateNewTempDirectory(
   235     const base::FilePath::StringType& prefix,
   236     base::FilePath* new_temp_path);
   238 // Create a directory within another directory.
   239 // Extra characters will be appended to |prefix| to ensure that the
   240 // new directory does not have the same name as an existing directory.
   241 BASE_EXPORT bool CreateTemporaryDirInDir(
   242     const base::FilePath& base_dir,
   243     const base::FilePath::StringType& prefix,
   244     base::FilePath* new_dir);
   246 // Creates a directory, as well as creating any parent directories, if they
   247 // don't exist. Returns 'true' on successful creation, or if the directory
   248 // already exists.  The directory is only readable by the current user.
   249 // Returns true on success, leaving *error unchanged.
   250 // Returns false on failure and sets *error appropriately, if it is non-NULL.
   251 BASE_EXPORT bool CreateDirectoryAndGetError(const base::FilePath& full_path,
   252                                             base::PlatformFileError* error);
   254 // Backward-compatible convenience method for the above.
   255 BASE_EXPORT bool CreateDirectory(const base::FilePath& full_path);
   257 // Returns the file size. Returns true on success.
   258 BASE_EXPORT bool GetFileSize(const base::FilePath& file_path, int64* file_size);
   260 // Sets |real_path| to |path| with symbolic links and junctions expanded.
   261 // On windows, make sure the path starts with a lettered drive.
   262 // |path| must reference a file.  Function will fail if |path| points to
   263 // a directory or to a nonexistent path.  On windows, this function will
   264 // fail if |path| is a junction or symlink that points to an empty file,
   265 // or if |real_path| would be longer than MAX_PATH characters.
   266 BASE_EXPORT bool NormalizeFilePath(const base::FilePath& path,
   267                                    base::FilePath* real_path);
   269 #if defined(OS_WIN)
   271 // Given a path in NT native form ("\Device\HarddiskVolumeXX\..."),
   272 // return in |drive_letter_path| the equivalent path that starts with
   273 // a drive letter ("C:\...").  Return false if no such path exists.
   274 BASE_EXPORT bool DevicePathToDriveLetterPath(const base::FilePath& device_path,
   275                                              base::FilePath* drive_letter_path);
   277 // Given an existing file in |path|, set |real_path| to the path
   278 // in native NT format, of the form "\Device\HarddiskVolumeXX\..".
   279 // Returns false if the path can not be found. Empty files cannot
   280 // be resolved with this function.
   281 BASE_EXPORT bool NormalizeToNativeFilePath(const base::FilePath& path,
   282                                            base::FilePath* nt_path);
   283 #endif
   285 // This function will return if the given file is a symlink or not.
   286 BASE_EXPORT bool IsLink(const base::FilePath& file_path);
   288 // Returns information about the given file path.
   289 BASE_EXPORT bool GetFileInfo(const base::FilePath& file_path,
   290                              base::PlatformFileInfo* info);
   292 // Sets the time of the last access and the time of the last modification.
   293 BASE_EXPORT bool TouchFile(const base::FilePath& path,
   294                            const base::Time& last_accessed,
   295                            const base::Time& last_modified);
   297 // Set the time of the last modification. Useful for unit tests.
   298 BASE_EXPORT bool SetLastModifiedTime(const base::FilePath& path,
   299                                      const base::Time& last_modified);
   301 #if defined(OS_POSIX)
   302 // Store inode number of |path| in |inode|. Return true on success.
   303 BASE_EXPORT bool GetInode(const base::FilePath& path, ino_t* inode);
   304 #endif
   306 // Wrapper for fopen-like calls. Returns non-NULL FILE* on success.
   307 BASE_EXPORT FILE* OpenFile(const base::FilePath& filename, const char* mode);
   309 // Closes file opened by OpenFile. Returns true on success.
   310 BASE_EXPORT bool CloseFile(FILE* file);
   312 // Truncates an open file to end at the location of the current file pointer.
   313 // This is a cross-platform analog to Windows' SetEndOfFile() function.
   314 BASE_EXPORT bool TruncateFile(FILE* file);
   316 // Reads the given number of bytes from the file into the buffer.  Returns
   317 // the number of read bytes, or -1 on error.
   318 BASE_EXPORT int ReadFile(const base::FilePath& filename, char* data, int size);
   320 // Writes the given buffer into the file, overwriting any data that was
   321 // previously there.  Returns the number of bytes written, or -1 on error.
   322 BASE_EXPORT int WriteFile(const base::FilePath& filename, const char* data,
   323                           int size);
   324 #if defined(OS_POSIX)
   325 // Append the data to |fd|. Does not close |fd| when done.
   326 BASE_EXPORT int WriteFileDescriptor(const int fd, const char* data, int size);
   327 #endif
   328 // Append the given buffer into the file. Returns the number of bytes written,
   329 // or -1 on error.
   330 BASE_EXPORT int AppendToFile(const base::FilePath& filename,
   331                              const char* data, int size);
   333 // Gets the current working directory for the process.
   334 BASE_EXPORT bool GetCurrentDirectory(base::FilePath* path);
   336 // Sets the current working directory for the process.
   337 BASE_EXPORT bool SetCurrentDirectory(const base::FilePath& path);
   339 // Attempts to find a number that can be appended to the |path| to make it
   340 // unique. If |path| does not exist, 0 is returned.  If it fails to find such
   341 // a number, -1 is returned. If |suffix| is not empty, also checks the
   342 // existence of it with the given suffix.
   343 BASE_EXPORT int GetUniquePathNumber(const base::FilePath& path,
   344                                     const base::FilePath::StringType& suffix);
   346 #if defined(OS_POSIX)
   347 // Creates a directory with a guaranteed unique name based on |path|, returning
   348 // the pathname if successful, or an empty path if there was an error creating
   349 // the directory. Does not create parent directories.
   350 BASE_EXPORT base::FilePath MakeUniqueDirectory(const base::FilePath& path);
   351 #endif
   353 #if defined(OS_POSIX)
   354 // Test that |path| can only be changed by a given user and members of
   355 // a given set of groups.
   356 // Specifically, test that all parts of |path| under (and including) |base|:
   357 // * Exist.
   358 // * Are owned by a specific user.
   359 // * Are not writable by all users.
   360 // * Are owned by a member of a given set of groups, or are not writable by
   361 //   their group.
   362 // * Are not symbolic links.
   363 // This is useful for checking that a config file is administrator-controlled.
   364 // |base| must contain |path|.
   365 BASE_EXPORT bool VerifyPathControlledByUser(const base::FilePath& base,
   366                                             const base::FilePath& path,
   367                                             uid_t owner_uid,
   368                                             const std::set<gid_t>& group_gids);
   369 #endif  // defined(OS_POSIX)
   371 #if defined(OS_MACOSX) && !defined(OS_IOS)
   372 // Is |path| writable only by a user with administrator privileges?
   373 // This function uses Mac OS conventions.  The super user is assumed to have
   374 // uid 0, and the administrator group is assumed to be named "admin".
   375 // Testing that |path|, and every parent directory including the root of
   376 // the filesystem, are owned by the superuser, controlled by the group
   377 // "admin", are not writable by all users, and contain no symbolic links.
   378 // Will return false if |path| does not exist.
   379 BASE_EXPORT bool VerifyPathControlledByAdmin(const base::FilePath& path);
   380 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
   382 // Returns the maximum length of path component on the volume containing
   383 // the directory |path|, in the number of FilePath::CharType, or -1 on failure.
   384 BASE_EXPORT int GetMaximumPathComponentLength(const base::FilePath& path);
   386 // A class to handle auto-closing of FILE*'s.
   387 class ScopedFILEClose {
   388  public:
   389   inline void operator()(FILE* x) const {
   390     if (x) {
   391       fclose(x);
   392     }
   393   }
   394 };
   396 typedef scoped_ptr_malloc<FILE, ScopedFILEClose> ScopedFILE;
   398 #if defined(OS_POSIX)
   399 // A class to handle auto-closing of FDs.
   400 class ScopedFDClose {
   401  public:
   402   inline void operator()(int* x) const {
   403     if (x && *x >= 0) {
   404       if (HANDLE_EINTR(close(*x)) < 0)
   405         DPLOG(ERROR) << "close";
   406     }
   407   }
   408 };
   410 typedef scoped_ptr_malloc<int, ScopedFDClose> ScopedFD;
   411 #endif  // OS_POSIX
   413 #if defined(OS_LINUX)
   414 // Broad categories of file systems as returned by statfs() on Linux.
   415 enum FileSystemType {
   416   FILE_SYSTEM_UNKNOWN,  // statfs failed.
   417   FILE_SYSTEM_0,        // statfs.f_type == 0 means unknown, may indicate AFS.
   418   FILE_SYSTEM_ORDINARY,       // on-disk filesystem like ext2
   419   FILE_SYSTEM_NFS,
   420   FILE_SYSTEM_SMB,
   421   FILE_SYSTEM_CODA,
   422   FILE_SYSTEM_MEMORY,         // in-memory file system
   423   FILE_SYSTEM_CGROUP,         // cgroup control.
   424   FILE_SYSTEM_OTHER,          // any other value.
   425   FILE_SYSTEM_TYPE_COUNT
   426 };
   428 // Attempts determine the FileSystemType for |path|.
   429 // Returns false if |path| doesn't exist.
   430 BASE_EXPORT bool GetFileSystemType(const base::FilePath& path,
   431                                    FileSystemType* type);
   432 #endif
   434 }  // namespace file_util
   436 // Internal --------------------------------------------------------------------
   438 namespace base {
   439 namespace internal {
   441 // Same as Move but allows paths with traversal components.
   442 // Use only with extreme care.
   443 BASE_EXPORT bool MoveUnsafe(const FilePath& from_path,
   444                             const FilePath& to_path);
   446 // Same as CopyFile but allows paths with traversal components.
   447 // Use only with extreme care.
   448 BASE_EXPORT bool CopyFileUnsafe(const FilePath& from_path,
   449                                 const FilePath& to_path);
   451 #if defined(OS_WIN)
   452 // Copy from_path to to_path recursively and then delete from_path recursively.
   453 // Returns true if all operations succeed.
   454 // This function simulates Move(), but unlike Move() it works across volumes.
   455 // This function is not transactional.
   456 BASE_EXPORT bool CopyAndDeleteDirectory(const FilePath& from_path,
   457                                         const FilePath& to_path);
   458 #endif  // defined(OS_WIN)
   460 }  // namespace internal
   461 }  // namespace base
   463 #endif  // BASE_FILE_UTIL_H_

mercurial