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 #include "base/file_util.h"
16 #include <sys/errno.h>
18 #include <sys/param.h>
21 #include <sys/types.h>
25 #if defined(OS_MACOSX)
26 #include <AvailabilityMacros.h>
27 #include "base/mac/foundation_util.h"
28 #elif !defined(OS_ANDROID)
34 #include "base/basictypes.h"
35 #include "base/eintr_wrapper.h"
36 #include "base/file_path.h"
37 #include "base/logging.h"
38 #include "base/memory/scoped_ptr.h"
39 #include "base/memory/singleton.h"
40 #include "base/path_service.h"
41 #include "base/stl_util.h"
42 #include "base/string_util.h"
43 #include "base/stringprintf.h"
44 #include "base/sys_string_conversions.h"
45 #include "base/threading/thread_restrictions.h"
46 #include "base/time.h"
47 #include "base/utf_string_conversions.h"
49 #if defined(OS_ANDROID)
50 #include "base/os_compat_android.h"
57 #if defined(OS_CHROMEOS)
58 #include "base/chromeos/chromeos_version.h"
65 #if defined(OS_BSD) || defined(OS_MACOSX)
66 typedef struct stat stat_wrapper_t
;
67 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
68 base::ThreadRestrictions::AssertIOAllowed();
69 return stat(path
, sb
);
71 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
72 base::ThreadRestrictions::AssertIOAllowed();
73 return lstat(path
, sb
);
76 typedef struct stat64 stat_wrapper_t
;
77 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
78 base::ThreadRestrictions::AssertIOAllowed();
79 return stat64(path
, sb
);
81 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
82 base::ThreadRestrictions::AssertIOAllowed();
83 return lstat64(path
, sb
);
87 // Helper for NormalizeFilePath(), defined below.
88 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
89 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
90 FilePath::CharType buf
[PATH_MAX
];
91 if (!realpath(path
.value().c_str(), buf
))
94 *real_path
= FilePath(buf
);
98 // Helper for VerifyPathControlledByUser.
99 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
101 const std::set
<gid_t
>& group_gids
) {
102 stat_wrapper_t stat_info
;
103 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
104 DPLOG(ERROR
) << "Failed to get information on path "
109 if (S_ISLNK(stat_info
.st_mode
)) {
110 DLOG(ERROR
) << "Path " << path
.value()
111 << " is a symbolic link.";
115 if (stat_info
.st_uid
!= owner_uid
) {
116 DLOG(ERROR
) << "Path " << path
.value()
117 << " is owned by the wrong user.";
121 if ((stat_info
.st_mode
& S_IWGRP
) &&
122 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
123 DLOG(ERROR
) << "Path " << path
.value()
124 << " is writable by an unprivileged group.";
128 if (stat_info
.st_mode
& S_IWOTH
) {
129 DLOG(ERROR
) << "Path " << path
.value()
130 << " is writable by any user.";
139 static std::string
TempFileName() {
140 #if defined(OS_MACOSX)
141 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
144 #if defined(GOOGLE_CHROME_BUILD)
145 return std::string(".com.google.Chrome.XXXXXX");
147 return std::string(".org.chromium.Chromium.XXXXXX");
151 bool AbsolutePath(FilePath
* path
) {
152 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
153 char full_path
[PATH_MAX
];
154 if (realpath(path
->value().c_str(), full_path
) == NULL
)
156 *path
= FilePath(full_path
);
160 int CountFilesCreatedAfter(const FilePath
& path
,
161 const base::Time
& comparison_time
) {
162 base::ThreadRestrictions::AssertIOAllowed();
165 DIR* dir
= opendir(path
.value().c_str());
167 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
168 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
169 #error Port warning: depending on the definition of struct dirent, \
170 additional space for pathname may be needed
172 struct dirent ent_buf
;
174 while (readdir_r(dir
, &ent_buf
, &ent
) == 0 && ent
) {
175 if ((strcmp(ent
->d_name
, ".") == 0) ||
176 (strcmp(ent
->d_name
, "..") == 0))
180 int test
= CallStat(path
.Append(ent
->d_name
).value().c_str(), &st
);
182 DPLOG(ERROR
) << "stat64 failed";
185 // Here, we use Time::TimeT(), which discards microseconds. This
186 // means that files which are newer than |comparison_time| may
187 // be considered older. If we don't discard microseconds, it
188 // introduces another issue. Suppose the following case:
190 // 1. Get |comparison_time| by Time::Now() and the value is 10.1 (secs).
191 // 2. Create a file and the current time is 10.3 (secs).
193 // As POSIX doesn't have microsecond precision for |st_ctime|,
194 // the creation time of the file created in the step 2 is 10 and
195 // the file is considered older than |comparison_time|. After
196 // all, we may have to accept either of the two issues: 1. files
197 // which are older than |comparison_time| are considered newer
198 // (current implementation) 2. files newer than
199 // |comparison_time| are considered older.
200 if (static_cast<time_t>(st
.st_ctime
) >= comparison_time
.ToTimeT())
208 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
209 // which works both with and without the recursive flag. I'm not sure we need
210 // that functionality. If not, remove from file_util_win.cc, otherwise add it
212 bool Delete(const FilePath
& path
, bool recursive
) {
213 base::ThreadRestrictions::AssertIOAllowed();
214 const char* path_str
= path
.value().c_str();
215 stat_wrapper_t file_info
;
216 int test
= CallLstat(path_str
, &file_info
);
218 // The Windows version defines this condition as success.
219 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
222 if (!S_ISDIR(file_info
.st_mode
))
223 return (unlink(path_str
) == 0);
225 return (rmdir(path_str
) == 0);
228 std::stack
<std::string
> directories
;
229 directories
.push(path
.value());
230 FileEnumerator
traversal(path
, true,
231 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
232 FileEnumerator::SHOW_SYM_LINKS
);
233 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
234 current
= traversal
.Next()) {
235 FileEnumerator::FindInfo info
;
236 traversal
.GetFindInfo(&info
);
238 if (S_ISDIR(info
.stat
.st_mode
))
239 directories
.push(current
.value());
241 success
= (unlink(current
.value().c_str()) == 0);
244 while (success
&& !directories
.empty()) {
245 FilePath dir
= FilePath(directories
.top());
247 success
= (rmdir(dir
.value().c_str()) == 0);
252 bool Move(const FilePath
& from_path
, const FilePath
& to_path
) {
253 base::ThreadRestrictions::AssertIOAllowed();
254 // Windows compatibility: if to_path exists, from_path and to_path
255 // must be the same type, either both files, or both directories.
256 stat_wrapper_t to_file_info
;
257 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
258 stat_wrapper_t from_file_info
;
259 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
260 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
267 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
270 if (!CopyDirectory(from_path
, to_path
, true))
273 Delete(from_path
, true);
277 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
278 base::ThreadRestrictions::AssertIOAllowed();
279 return (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0);
282 bool CopyDirectory(const FilePath
& from_path
,
283 const FilePath
& to_path
,
285 base::ThreadRestrictions::AssertIOAllowed();
286 // Some old callers of CopyDirectory want it to support wildcards.
287 // After some discussion, we decided to fix those callers.
288 // Break loudly here if anyone tries to do this.
289 // TODO(evanm): remove this once we're sure it's ok.
290 DCHECK(to_path
.value().find('*') == std::string::npos
);
291 DCHECK(from_path
.value().find('*') == std::string::npos
);
293 char top_dir
[PATH_MAX
];
294 if (base::strlcpy(top_dir
, from_path
.value().c_str(),
295 arraysize(top_dir
)) >= arraysize(top_dir
)) {
299 // This function does not properly handle destinations within the source
300 FilePath real_to_path
= to_path
;
301 if (PathExists(real_to_path
)) {
302 if (!AbsolutePath(&real_to_path
))
305 real_to_path
= real_to_path
.DirName();
306 if (!AbsolutePath(&real_to_path
))
309 FilePath real_from_path
= from_path
;
310 if (!AbsolutePath(&real_from_path
))
312 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
313 real_to_path
.value().compare(0, real_from_path
.value().size(),
314 real_from_path
.value()) == 0)
318 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
320 traverse_type
|= FileEnumerator::DIRECTORIES
;
321 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
323 // We have to mimic windows behavior here. |to_path| may not exist yet,
324 // start the loop with |to_path|.
325 FileEnumerator::FindInfo info
;
326 FilePath current
= from_path
;
327 if (stat(from_path
.value().c_str(), &info
.stat
) < 0) {
328 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
329 << from_path
.value() << " errno = " << errno
;
332 struct stat to_path_stat
;
333 FilePath from_path_base
= from_path
;
334 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
335 S_ISDIR(to_path_stat
.st_mode
)) {
336 // If the destination already exists and is a directory, then the
337 // top level of source needs to be copied.
338 from_path_base
= from_path
.DirName();
341 // The Windows version of this function assumes that non-recursive calls
342 // will always have a directory for from_path.
343 DCHECK(recursive
|| S_ISDIR(info
.stat
.st_mode
));
345 while (success
&& !current
.empty()) {
346 // current is the source path, including from_path, so paste
347 // the suffix after from_path onto to_path to create the target_path.
348 std::string
suffix(¤t
.value().c_str()[from_path_base
.value().size()]);
349 // Strip the leading '/' (if any).
350 if (!suffix
.empty()) {
351 DCHECK_EQ('/', suffix
[0]);
354 const FilePath target_path
= to_path
.Append(suffix
);
356 if (S_ISDIR(info
.stat
.st_mode
)) {
357 if (mkdir(target_path
.value().c_str(), info
.stat
.st_mode
& 01777) != 0 &&
359 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
360 << target_path
.value() << " errno = " << errno
;
363 } else if (S_ISREG(info
.stat
.st_mode
)) {
364 if (!CopyFile(current
, target_path
)) {
365 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
366 << target_path
.value();
370 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
374 current
= traversal
.Next();
375 traversal
.GetFindInfo(&info
);
381 bool PathExists(const FilePath
& path
) {
382 base::ThreadRestrictions::AssertIOAllowed();
383 return access(path
.value().c_str(), F_OK
) == 0;
386 bool PathIsWritable(const FilePath
& path
) {
387 base::ThreadRestrictions::AssertIOAllowed();
388 return access(path
.value().c_str(), W_OK
) == 0;
391 bool DirectoryExists(const FilePath
& path
) {
392 base::ThreadRestrictions::AssertIOAllowed();
393 stat_wrapper_t file_info
;
394 if (CallStat(path
.value().c_str(), &file_info
) == 0)
395 return S_ISDIR(file_info
.st_mode
);
399 // TODO(erikkay): implement
401 bool GetFileCreationLocalTimeFromHandle(int fd
,
402 LPSYSTEMTIME creation_time
) {
406 FILETIME utc_filetime
;
407 if (!GetFileTime(file_handle
, &utc_filetime
, NULL
, NULL
))
410 FILETIME local_filetime
;
411 if (!FileTimeToLocalFileTime(&utc_filetime
, &local_filetime
))
414 return !!FileTimeToSystemTime(&local_filetime
, creation_time
);
417 bool GetFileCreationLocalTime(const std::string
& filename
,
418 LPSYSTEMTIME creation_time
) {
419 ScopedHandle
file_handle(
420 CreateFile(filename
.c_str(), GENERIC_READ
,
421 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
, NULL
,
422 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
));
423 return GetFileCreationLocalTimeFromHandle(file_handle
.Get(), creation_time
);
427 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
428 size_t total_read
= 0;
429 while (total_read
< bytes
) {
431 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
434 total_read
+= bytes_read
;
436 return total_read
== bytes
;
439 bool CreateSymbolicLink(const FilePath
& target_path
,
440 const FilePath
& symlink_path
) {
441 DCHECK(!symlink_path
.empty());
442 DCHECK(!target_path
.empty());
443 return ::symlink(target_path
.value().c_str(),
444 symlink_path
.value().c_str()) != -1;
447 bool ReadSymbolicLink(const FilePath
& symlink_path
,
448 FilePath
* target_path
) {
449 DCHECK(!symlink_path
.empty());
452 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
455 target_path
->clear();
459 *target_path
= FilePath(FilePath::StringType(buf
, count
));
463 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
464 base::ThreadRestrictions::AssertIOAllowed();
467 stat_wrapper_t file_info
;
468 // Uses stat(), because on symbolic link, lstat() does not return valid
469 // permission bits in st_mode
470 if (CallStat(path
.value().c_str(), &file_info
) != 0)
473 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
477 bool SetPosixFilePermissions(const FilePath
& path
,
479 base::ThreadRestrictions::AssertIOAllowed();
480 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
482 // Calls stat() so that we can preserve the higher bits like S_ISGID.
483 stat_wrapper_t stat_buf
;
484 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
487 // Clears the existing permission bits, and adds the new ones.
488 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
489 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
491 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
497 // Creates and opens a temporary file in |directory|, returning the
498 // file descriptor. |path| is set to the temporary file path.
499 // This function does NOT unlink() the file.
500 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
501 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
502 *path
= directory
.Append(TempFileName());
503 const std::string
& tmpdir_string
= path
->value();
504 // this should be OK since mkstemp just replaces characters in place
505 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
507 return HANDLE_EINTR(mkstemp(buffer
));
510 bool CreateTemporaryFile(FilePath
* path
) {
511 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
513 if (!GetTempDir(&directory
))
515 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
518 ignore_result(HANDLE_EINTR(close(fd
)));
522 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
524 if (!GetShmemTempDir(&directory
, executable
))
527 return CreateAndOpenTemporaryFileInDir(directory
, path
);
530 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
531 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
535 FILE* file
= fdopen(fd
, "a+");
537 ignore_result(HANDLE_EINTR(close(fd
)));
541 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
542 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
543 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
544 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
547 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
548 const FilePath::StringType
& name_tmpl
,
550 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
551 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
552 << "Directory name template must contain \"XXXXXX\".";
554 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
555 std::string sub_dir_string
= sub_dir
.value();
557 // this should be OK since mkdtemp just replaces characters in place
558 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
559 char* dtemp
= mkdtemp(buffer
);
561 DPLOG(ERROR
) << "mkdtemp";
564 *new_dir
= FilePath(dtemp
);
568 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
569 const FilePath::StringType
& prefix
,
571 FilePath::StringType mkdtemp_template
= prefix
;
572 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
573 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
576 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
577 FilePath
* new_temp_path
) {
579 if (!GetTempDir(&tmpdir
))
582 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
585 bool CreateDirectory(const FilePath
& full_path
) {
586 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
587 std::vector
<FilePath
> subpaths
;
589 // Collect a list of all parent directories.
590 FilePath last_path
= full_path
;
591 subpaths
.push_back(full_path
);
592 for (FilePath path
= full_path
.DirName();
593 path
.value() != last_path
.value(); path
= path
.DirName()) {
594 subpaths
.push_back(path
);
598 // Iterate through the parents and create the missing ones.
599 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
600 i
!= subpaths
.rend(); ++i
) {
601 if (DirectoryExists(*i
))
603 if (mkdir(i
->value().c_str(), 0700) == 0)
605 // Mkdir failed, but it might have failed with EEXIST, or some other error
606 // due to the the directory appearing out of thin air. This can occur if
607 // two processes are trying to create the same file system tree at the same
608 // time. Check to see if it exists and make sure it is a directory.
609 if (!DirectoryExists(*i
))
615 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
616 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
617 bool IsLink(const FilePath
& file_path
) {
619 // If we can't lstat the file, it's safe to assume that the file won't at
620 // least be a 'followable' link.
621 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
624 if (S_ISLNK(st
.st_mode
))
630 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
631 stat_wrapper_t file_info
;
632 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
634 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
635 results
->size
= file_info
.st_size
;
636 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
637 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
638 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
642 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
643 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
645 int result
= stat(path
.value().c_str(), &buffer
);
649 *inode
= buffer
.st_ino
;
653 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
654 return OpenFile(FilePath(filename
), mode
);
657 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
658 base::ThreadRestrictions::AssertIOAllowed();
661 result
= fopen(filename
.value().c_str(), mode
);
662 } while (!result
&& errno
== EINTR
);
666 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
667 base::ThreadRestrictions::AssertIOAllowed();
668 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
672 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
673 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
678 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
679 base::ThreadRestrictions::AssertIOAllowed();
680 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
684 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
685 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
687 return bytes_written
;
690 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
691 // Allow for partial writes.
692 ssize_t bytes_written_total
= 0;
693 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
694 bytes_written_total
+= bytes_written_partial
) {
695 bytes_written_partial
=
696 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
697 size
- bytes_written_total
));
698 if (bytes_written_partial
< 0)
702 return bytes_written_total
;
705 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
706 base::ThreadRestrictions::AssertIOAllowed();
707 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
711 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
712 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
714 return bytes_written
;
717 // Gets the current working directory for the process.
718 bool GetCurrentDirectory(FilePath
* dir
) {
719 // getcwd can return ENOENT, which implies it checks against the disk.
720 base::ThreadRestrictions::AssertIOAllowed();
722 char system_buffer
[PATH_MAX
] = "";
723 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
727 *dir
= FilePath(system_buffer
);
731 // Sets the current working directory for the process.
732 bool SetCurrentDirectory(const FilePath
& path
) {
733 base::ThreadRestrictions::AssertIOAllowed();
734 int ret
= chdir(path
.value().c_str());
738 ///////////////////////////////////////////////
741 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
744 : current_directory_entry_(0),
745 root_path_(root_path
),
746 recursive_(recursive
),
747 file_type_(file_type
) {
748 // INCLUDE_DOT_DOT must not be specified if recursive.
749 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
750 pending_paths_
.push(root_path
);
753 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
756 const FilePath::StringType
& pattern
)
757 : current_directory_entry_(0),
758 root_path_(root_path
),
759 recursive_(recursive
),
760 file_type_(file_type
),
761 pattern_(root_path
.Append(pattern
).value()) {
762 // INCLUDE_DOT_DOT must not be specified if recursive.
763 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
764 // The Windows version of this code appends the pattern to the root_path,
765 // potentially only matching against items in the top-most directory.
768 pattern_
= FilePath::StringType();
769 pending_paths_
.push(root_path
);
772 FileEnumerator::~FileEnumerator() {
775 FilePath
FileEnumerator::Next() {
776 ++current_directory_entry_
;
778 // While we've exhausted the entries in the current directory, do the next
779 while (current_directory_entry_
>= directory_entries_
.size()) {
780 if (pending_paths_
.empty())
783 root_path_
= pending_paths_
.top();
784 root_path_
= root_path_
.StripTrailingSeparators();
785 pending_paths_
.pop();
787 std::vector
<DirectoryEntryInfo
> entries
;
788 if (!ReadDirectory(&entries
, root_path_
, file_type_
& SHOW_SYM_LINKS
))
791 directory_entries_
.clear();
792 current_directory_entry_
= 0;
793 for (std::vector
<DirectoryEntryInfo
>::const_iterator
794 i
= entries
.begin(); i
!= entries
.end(); ++i
) {
795 FilePath full_path
= root_path_
.Append(i
->filename
);
796 if (ShouldSkip(full_path
))
799 if (pattern_
.size() &&
800 fnmatch(pattern_
.c_str(), full_path
.value().c_str(), FNM_NOESCAPE
))
803 if (recursive_
&& S_ISDIR(i
->stat
.st_mode
))
804 pending_paths_
.push(full_path
);
806 if ((S_ISDIR(i
->stat
.st_mode
) && (file_type_
& DIRECTORIES
)) ||
807 (!S_ISDIR(i
->stat
.st_mode
) && (file_type_
& FILES
)))
808 directory_entries_
.push_back(*i
);
812 return root_path_
.Append(directory_entries_
[current_directory_entry_
816 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
819 if (current_directory_entry_
>= directory_entries_
.size())
822 DirectoryEntryInfo
* cur_entry
= &directory_entries_
[current_directory_entry_
];
823 memcpy(&(info
->stat
), &(cur_entry
->stat
), sizeof(info
->stat
));
824 info
->filename
.assign(cur_entry
->filename
.value());
828 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
829 return S_ISDIR(info
.stat
.st_mode
);
833 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
834 return FilePath(find_info
.filename
);
838 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
839 return find_info
.stat
.st_size
;
843 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
844 return base::Time::FromTimeT(find_info
.stat
.st_mtime
);
847 bool FileEnumerator::ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
848 const FilePath
& source
, bool show_links
) {
849 base::ThreadRestrictions::AssertIOAllowed();
850 DIR* dir
= opendir(source
.value().c_str());
854 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
855 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
856 #error Port warning: depending on the definition of struct dirent, \
857 additional space for pathname may be needed
860 struct dirent dent_buf
;
862 while (readdir_r(dir
, &dent_buf
, &dent
) == 0 && dent
) {
863 DirectoryEntryInfo info
;
864 info
.filename
= FilePath(dent
->d_name
);
866 FilePath full_name
= source
.Append(dent
->d_name
);
869 ret
= lstat(full_name
.value().c_str(), &info
.stat
);
871 ret
= stat(full_name
.value().c_str(), &info
.stat
);
873 // Print the stat() error message unless it was ENOENT and we're
874 // following symlinks.
875 if (!(errno
== ENOENT
&& !show_links
)) {
876 DPLOG(ERROR
) << "Couldn't stat "
877 << source
.Append(dent
->d_name
).value();
879 memset(&info
.stat
, 0, sizeof(info
.stat
));
881 entries
->push_back(info
);
888 ///////////////////////////////////////////////
891 MemoryMappedFile::MemoryMappedFile()
892 : file_(base::kInvalidPlatformFileValue
),
897 bool MemoryMappedFile::MapFileToMemoryInternal() {
898 base::ThreadRestrictions::AssertIOAllowed();
900 struct stat file_stat
;
901 if (fstat(file_
, &file_stat
) == base::kInvalidPlatformFileValue
) {
902 DLOG(ERROR
) << "Couldn't fstat " << file_
<< ", errno " << errno
;
905 length_
= file_stat
.st_size
;
907 data_
= static_cast<uint8
*>(
908 mmap(NULL
, length_
, PROT_READ
, MAP_SHARED
, file_
, 0));
909 if (data_
== MAP_FAILED
)
910 DLOG(ERROR
) << "Couldn't mmap " << file_
<< ", errno " << errno
;
912 return data_
!= MAP_FAILED
;
915 void MemoryMappedFile::CloseHandles() {
916 base::ThreadRestrictions::AssertIOAllowed();
919 munmap(data_
, length_
);
920 if (file_
!= base::kInvalidPlatformFileValue
)
921 ignore_result(HANDLE_EINTR(close(file_
)));
925 file_
= base::kInvalidPlatformFileValue
;
928 bool HasFileBeenModifiedSince(const FileEnumerator::FindInfo
& find_info
,
929 const base::Time
& cutoff_time
) {
930 return static_cast<time_t>(find_info
.stat
.st_mtime
) >= cutoff_time
.ToTimeT();
933 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
934 FilePath real_path_result
;
935 if (!RealPath(path
, &real_path_result
))
938 // To be consistant with windows, fail if |real_path_result| is a
940 stat_wrapper_t file_info
;
941 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
942 S_ISDIR(file_info
.st_mode
))
945 *normalized_path
= real_path_result
;
949 #if !defined(OS_MACOSX)
950 bool GetTempDir(FilePath
* path
) {
951 const char* tmp
= getenv("TMPDIR");
953 *path
= FilePath(tmp
);
955 #if defined(OS_ANDROID)
956 return PathService::Get(base::DIR_CACHE
, path
);
958 *path
= FilePath("/tmp");
963 #if !defined(OS_ANDROID)
965 #if defined(OS_LINUX)
966 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
967 // This depends on the mount options used for /dev/shm, which vary among
968 // different Linux distributions and possibly local configuration. It also
969 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
970 // but its kernel allows mprotect with PROT_EXEC anyway.
974 bool DetermineDevShmExecutable() {
977 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
979 ScopedFD
shm_fd_closer(&fd
);
981 long sysconf_result
= sysconf(_SC_PAGESIZE
);
982 CHECK_GE(sysconf_result
, 0);
983 size_t pagesize
= static_cast<size_t>(sysconf_result
);
984 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
985 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
986 if (mapping
!= MAP_FAILED
) {
987 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
989 munmap(mapping
, pagesize
);
996 #endif // defined(OS_LINUX)
998 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
999 #if defined(OS_LINUX)
1000 bool use_dev_shm
= true;
1002 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
1003 use_dev_shm
= s_dev_shm_executable
;
1006 *path
= FilePath("/dev/shm");
1010 return GetTempDir(path
);
1012 #endif // !defined(OS_ANDROID)
1014 FilePath
GetHomeDir() {
1015 #if defined(OS_CHROMEOS)
1016 if (base::chromeos::IsRunningOnChromeOS())
1017 return FilePath("/home/chronos/user");
1020 const char* home_dir
= getenv("HOME");
1021 if (home_dir
&& home_dir
[0])
1022 return FilePath(home_dir
);
1024 #if defined(OS_ANDROID)
1025 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
1027 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
1028 base::ThreadRestrictions::AssertIOAllowed();
1030 home_dir
= g_get_home_dir();
1031 if (home_dir
&& home_dir
[0])
1032 return FilePath(home_dir
);
1036 if (file_util::GetTempDir(&rv
))
1040 return FilePath("/tmp");
1043 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
1044 base::ThreadRestrictions::AssertIOAllowed();
1045 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
1049 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
1051 ignore_result(HANDLE_EINTR(close(infile
)));
1055 const size_t kBufferSize
= 32768;
1056 std::vector
<char> buffer(kBufferSize
);
1060 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
1061 if (bytes_read
< 0) {
1065 if (bytes_read
== 0)
1067 // Allow for partial writes
1068 ssize_t bytes_written_per_read
= 0;
1070 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
1072 &buffer
[bytes_written_per_read
],
1073 bytes_read
- bytes_written_per_read
));
1074 if (bytes_written_partial
< 0) {
1078 bytes_written_per_read
+= bytes_written_partial
;
1079 } while (bytes_written_per_read
< bytes_read
);
1082 if (HANDLE_EINTR(close(infile
)) < 0)
1084 if (HANDLE_EINTR(close(outfile
)) < 0)
1089 #endif // !defined(OS_MACOSX)
1091 bool VerifyPathControlledByUser(const FilePath
& base
,
1092 const FilePath
& path
,
1094 const std::set
<gid_t
>& group_gids
) {
1095 if (base
!= path
&& !base
.IsParent(path
)) {
1096 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
1097 << base
.value() << "\", path = \"" << path
.value() << "\"";
1101 std::vector
<FilePath::StringType
> base_components
;
1102 std::vector
<FilePath::StringType
> path_components
;
1104 base
.GetComponents(&base_components
);
1105 path
.GetComponents(&path_components
);
1107 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
1108 for (ib
= base_components
.begin(), ip
= path_components
.begin();
1109 ib
!= base_components
.end(); ++ib
, ++ip
) {
1110 // |base| must be a subpath of |path|, so all components should match.
1111 // If these CHECKs fail, look at the test that base is a parent of
1112 // path at the top of this function.
1113 DCHECK(ip
!= path_components
.end());
1117 FilePath current_path
= base
;
1118 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
1121 for (; ip
!= path_components
.end(); ++ip
) {
1122 current_path
= current_path
.Append(*ip
);
1123 if (!VerifySpecificPathControlledByUser(
1124 current_path
, owner_uid
, group_gids
))
1130 #if defined(OS_MACOSX) && !defined(OS_IOS)
1131 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
1132 const unsigned kRootUid
= 0;
1133 const FilePath
kFileSystemRoot("/");
1135 // The name of the administrator group on mac os.
1136 const char* const kAdminGroupNames
[] = {
1141 // Reading the groups database may touch the file system.
1142 base::ThreadRestrictions::AssertIOAllowed();
1144 std::set
<gid_t
> allowed_group_ids
;
1145 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
1146 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
1147 if (!group_record
) {
1148 DPLOG(ERROR
) << "Could not get the group ID of group \""
1149 << kAdminGroupNames
[i
] << "\".";
1153 allowed_group_ids
.insert(group_record
->gr_gid
);
1156 return VerifyPathControlledByUser(
1157 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
1159 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1161 } // namespace file_util