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