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/files/file_path.h"
36 #include "base/logging.h"
37 #include "base/memory/scoped_ptr.h"
38 #include "base/memory/singleton.h"
39 #include "base/path_service.h"
40 #include "base/posix/eintr_wrapper.h"
41 #include "base/stl_util.h"
42 #include "base/string_util.h"
43 #include "base/stringprintf.h"
44 #include "base/strings/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"
62 using base::MakeAbsoluteFilePath
;
66 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
67 base::ThreadRestrictions::AssertIOAllowed();
68 char full_path
[PATH_MAX
];
69 if (realpath(input
.value().c_str(), full_path
) == NULL
)
71 return FilePath(full_path
);
80 #if defined(OS_BSD) || defined(OS_MACOSX)
81 typedef struct stat stat_wrapper_t
;
82 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
83 base::ThreadRestrictions::AssertIOAllowed();
84 return stat(path
, sb
);
86 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
87 base::ThreadRestrictions::AssertIOAllowed();
88 return lstat(path
, sb
);
91 typedef struct stat64 stat_wrapper_t
;
92 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
93 base::ThreadRestrictions::AssertIOAllowed();
94 return stat64(path
, sb
);
96 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
97 base::ThreadRestrictions::AssertIOAllowed();
98 return lstat64(path
, sb
);
102 // Helper for NormalizeFilePath(), defined below.
103 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
104 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
105 FilePath::CharType buf
[PATH_MAX
];
106 if (!realpath(path
.value().c_str(), buf
))
109 *real_path
= FilePath(buf
);
113 // Helper for VerifyPathControlledByUser.
114 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
116 const std::set
<gid_t
>& group_gids
) {
117 stat_wrapper_t stat_info
;
118 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
119 DPLOG(ERROR
) << "Failed to get information on path "
124 if (S_ISLNK(stat_info
.st_mode
)) {
125 DLOG(ERROR
) << "Path " << path
.value()
126 << " is a symbolic link.";
130 if (stat_info
.st_uid
!= owner_uid
) {
131 DLOG(ERROR
) << "Path " << path
.value()
132 << " is owned by the wrong user.";
136 if ((stat_info
.st_mode
& S_IWGRP
) &&
137 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
138 DLOG(ERROR
) << "Path " << path
.value()
139 << " is writable by an unprivileged group.";
143 if (stat_info
.st_mode
& S_IWOTH
) {
144 DLOG(ERROR
) << "Path " << path
.value()
145 << " is writable by any user.";
154 static std::string
TempFileName() {
155 #if defined(OS_MACOSX)
156 return base::StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
159 #if defined(GOOGLE_CHROME_BUILD)
160 return std::string(".com.google.Chrome.XXXXXX");
162 return std::string(".org.chromium.Chromium.XXXXXX");
166 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
167 // which works both with and without the recursive flag. I'm not sure we need
168 // that functionality. If not, remove from file_util_win.cc, otherwise add it
170 bool Delete(const FilePath
& path
, bool recursive
) {
171 base::ThreadRestrictions::AssertIOAllowed();
172 const char* path_str
= path
.value().c_str();
173 stat_wrapper_t file_info
;
174 int test
= CallLstat(path_str
, &file_info
);
176 // The Windows version defines this condition as success.
177 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
180 if (!S_ISDIR(file_info
.st_mode
))
181 return (unlink(path_str
) == 0);
183 return (rmdir(path_str
) == 0);
186 std::stack
<std::string
> directories
;
187 directories
.push(path
.value());
188 FileEnumerator
traversal(path
, true,
189 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
190 FileEnumerator::SHOW_SYM_LINKS
);
191 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
192 current
= traversal
.Next()) {
193 FileEnumerator::FindInfo info
;
194 traversal
.GetFindInfo(&info
);
196 if (S_ISDIR(info
.stat
.st_mode
))
197 directories
.push(current
.value());
199 success
= (unlink(current
.value().c_str()) == 0);
202 while (success
&& !directories
.empty()) {
203 FilePath dir
= FilePath(directories
.top());
205 success
= (rmdir(dir
.value().c_str()) == 0);
210 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
211 base::ThreadRestrictions::AssertIOAllowed();
212 // Windows compatibility: if to_path exists, from_path and to_path
213 // must be the same type, either both files, or both directories.
214 stat_wrapper_t to_file_info
;
215 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
216 stat_wrapper_t from_file_info
;
217 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
218 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
225 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
228 if (!CopyDirectory(from_path
, to_path
, true))
231 Delete(from_path
, true);
235 bool ReplaceFileAndGetError(const FilePath
& from_path
,
236 const FilePath
& to_path
,
237 base::PlatformFileError
* error
) {
238 base::ThreadRestrictions::AssertIOAllowed();
239 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
242 *error
= base::ErrnoToPlatformFileError(errno
);
246 bool CopyDirectory(const FilePath
& from_path
,
247 const FilePath
& to_path
,
249 base::ThreadRestrictions::AssertIOAllowed();
250 // Some old callers of CopyDirectory want it to support wildcards.
251 // After some discussion, we decided to fix those callers.
252 // Break loudly here if anyone tries to do this.
253 // TODO(evanm): remove this once we're sure it's ok.
254 DCHECK(to_path
.value().find('*') == std::string::npos
);
255 DCHECK(from_path
.value().find('*') == std::string::npos
);
257 char top_dir
[PATH_MAX
];
258 if (base::strlcpy(top_dir
, from_path
.value().c_str(),
259 arraysize(top_dir
)) >= arraysize(top_dir
)) {
263 // This function does not properly handle destinations within the source
264 FilePath real_to_path
= to_path
;
265 if (PathExists(real_to_path
)) {
266 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
267 if (real_to_path
.empty())
270 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
271 if (real_to_path
.empty())
274 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
275 if (real_from_path
.empty())
277 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
278 real_to_path
.value().compare(0, real_from_path
.value().size(),
279 real_from_path
.value()) == 0)
283 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
285 traverse_type
|= FileEnumerator::DIRECTORIES
;
286 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
288 // We have to mimic windows behavior here. |to_path| may not exist yet,
289 // start the loop with |to_path|.
290 FileEnumerator::FindInfo info
;
291 FilePath current
= from_path
;
292 if (stat(from_path
.value().c_str(), &info
.stat
) < 0) {
293 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
294 << from_path
.value() << " errno = " << errno
;
297 struct stat to_path_stat
;
298 FilePath from_path_base
= from_path
;
299 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
300 S_ISDIR(to_path_stat
.st_mode
)) {
301 // If the destination already exists and is a directory, then the
302 // top level of source needs to be copied.
303 from_path_base
= from_path
.DirName();
306 // The Windows version of this function assumes that non-recursive calls
307 // will always have a directory for from_path.
308 DCHECK(recursive
|| S_ISDIR(info
.stat
.st_mode
));
310 while (success
&& !current
.empty()) {
311 // current is the source path, including from_path, so append
312 // the suffix after from_path to to_path to create the target_path.
313 FilePath
target_path(to_path
);
314 if (from_path_base
!= current
) {
315 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
321 if (S_ISDIR(info
.stat
.st_mode
)) {
322 if (mkdir(target_path
.value().c_str(), info
.stat
.st_mode
& 01777) != 0 &&
324 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
325 << target_path
.value() << " errno = " << errno
;
328 } else if (S_ISREG(info
.stat
.st_mode
)) {
329 if (!CopyFile(current
, target_path
)) {
330 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
331 << target_path
.value();
335 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
339 current
= traversal
.Next();
340 traversal
.GetFindInfo(&info
);
346 bool PathExists(const FilePath
& path
) {
347 base::ThreadRestrictions::AssertIOAllowed();
348 return access(path
.value().c_str(), F_OK
) == 0;
351 bool PathIsWritable(const FilePath
& path
) {
352 base::ThreadRestrictions::AssertIOAllowed();
353 return access(path
.value().c_str(), W_OK
) == 0;
356 bool DirectoryExists(const FilePath
& path
) {
357 base::ThreadRestrictions::AssertIOAllowed();
358 stat_wrapper_t file_info
;
359 if (CallStat(path
.value().c_str(), &file_info
) == 0)
360 return S_ISDIR(file_info
.st_mode
);
364 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
365 size_t total_read
= 0;
366 while (total_read
< bytes
) {
368 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
371 total_read
+= bytes_read
;
373 return total_read
== bytes
;
376 bool CreateSymbolicLink(const FilePath
& target_path
,
377 const FilePath
& symlink_path
) {
378 DCHECK(!symlink_path
.empty());
379 DCHECK(!target_path
.empty());
380 return ::symlink(target_path
.value().c_str(),
381 symlink_path
.value().c_str()) != -1;
384 bool ReadSymbolicLink(const FilePath
& symlink_path
,
385 FilePath
* target_path
) {
386 DCHECK(!symlink_path
.empty());
389 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
392 target_path
->clear();
396 *target_path
= FilePath(FilePath::StringType(buf
, count
));
400 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
401 base::ThreadRestrictions::AssertIOAllowed();
404 stat_wrapper_t file_info
;
405 // Uses stat(), because on symbolic link, lstat() does not return valid
406 // permission bits in st_mode
407 if (CallStat(path
.value().c_str(), &file_info
) != 0)
410 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
414 bool SetPosixFilePermissions(const FilePath
& path
,
416 base::ThreadRestrictions::AssertIOAllowed();
417 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
419 // Calls stat() so that we can preserve the higher bits like S_ISGID.
420 stat_wrapper_t stat_buf
;
421 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
424 // Clears the existing permission bits, and adds the new ones.
425 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
426 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
428 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
434 // Creates and opens a temporary file in |directory|, returning the
435 // file descriptor. |path| is set to the temporary file path.
436 // This function does NOT unlink() the file.
437 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
438 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
439 *path
= directory
.Append(TempFileName());
440 const std::string
& tmpdir_string
= path
->value();
441 // this should be OK since mkstemp just replaces characters in place
442 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
444 return HANDLE_EINTR(mkstemp(buffer
));
447 bool CreateTemporaryFile(FilePath
* path
) {
448 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
450 if (!GetTempDir(&directory
))
452 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
455 ignore_result(HANDLE_EINTR(close(fd
)));
459 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
461 if (!GetShmemTempDir(&directory
, executable
))
464 return CreateAndOpenTemporaryFileInDir(directory
, path
);
467 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
468 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
472 FILE* file
= fdopen(fd
, "a+");
474 ignore_result(HANDLE_EINTR(close(fd
)));
478 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
479 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
480 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
481 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
484 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
485 const FilePath::StringType
& name_tmpl
,
487 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
488 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
489 << "Directory name template must contain \"XXXXXX\".";
491 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
492 std::string sub_dir_string
= sub_dir
.value();
494 // this should be OK since mkdtemp just replaces characters in place
495 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
496 char* dtemp
= mkdtemp(buffer
);
498 DPLOG(ERROR
) << "mkdtemp";
501 *new_dir
= FilePath(dtemp
);
505 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
506 const FilePath::StringType
& prefix
,
508 FilePath::StringType mkdtemp_template
= prefix
;
509 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
510 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
513 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
514 FilePath
* new_temp_path
) {
516 if (!GetTempDir(&tmpdir
))
519 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
522 bool CreateDirectory(const FilePath
& full_path
) {
523 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
524 std::vector
<FilePath
> subpaths
;
526 // Collect a list of all parent directories.
527 FilePath last_path
= full_path
;
528 subpaths
.push_back(full_path
);
529 for (FilePath path
= full_path
.DirName();
530 path
.value() != last_path
.value(); path
= path
.DirName()) {
531 subpaths
.push_back(path
);
535 // Iterate through the parents and create the missing ones.
536 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
537 i
!= subpaths
.rend(); ++i
) {
538 if (DirectoryExists(*i
))
540 if (mkdir(i
->value().c_str(), 0700) == 0)
542 // Mkdir failed, but it might have failed with EEXIST, or some other error
543 // due to the the directory appearing out of thin air. This can occur if
544 // two processes are trying to create the same file system tree at the same
545 // time. Check to see if it exists and make sure it is a directory.
546 if (!DirectoryExists(*i
))
552 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
553 const int kMaxAttempts
= 20;
554 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
556 GetUniquePathNumber(path
, base::FilePath::StringType());
559 base::FilePath test_path
= (uniquifier
== 0) ? path
:
560 path
.InsertBeforeExtensionASCII(
561 base::StringPrintf(" (%d)", uniquifier
));
562 if (mkdir(test_path
.value().c_str(), 0777) == 0)
564 else if (errno
!= EEXIST
)
567 return base::FilePath();
570 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
571 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
572 bool IsLink(const FilePath
& file_path
) {
574 // If we can't lstat the file, it's safe to assume that the file won't at
575 // least be a 'followable' link.
576 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
579 if (S_ISLNK(st
.st_mode
))
585 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
586 stat_wrapper_t file_info
;
587 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
589 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
590 results
->size
= file_info
.st_size
;
591 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
592 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
593 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
597 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
598 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
600 int result
= stat(path
.value().c_str(), &buffer
);
604 *inode
= buffer
.st_ino
;
608 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
609 return OpenFile(FilePath(filename
), mode
);
612 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
613 base::ThreadRestrictions::AssertIOAllowed();
616 result
= fopen(filename
.value().c_str(), mode
);
617 } while (!result
&& errno
== EINTR
);
621 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
622 base::ThreadRestrictions::AssertIOAllowed();
623 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
627 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
628 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
633 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
634 base::ThreadRestrictions::AssertIOAllowed();
635 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
639 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
640 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
642 return bytes_written
;
645 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
646 // Allow for partial writes.
647 ssize_t bytes_written_total
= 0;
648 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
649 bytes_written_total
+= bytes_written_partial
) {
650 bytes_written_partial
=
651 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
652 size
- bytes_written_total
));
653 if (bytes_written_partial
< 0)
657 return bytes_written_total
;
660 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
661 base::ThreadRestrictions::AssertIOAllowed();
662 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
666 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
667 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
669 return bytes_written
;
672 // Gets the current working directory for the process.
673 bool GetCurrentDirectory(FilePath
* dir
) {
674 // getcwd can return ENOENT, which implies it checks against the disk.
675 base::ThreadRestrictions::AssertIOAllowed();
677 char system_buffer
[PATH_MAX
] = "";
678 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
682 *dir
= FilePath(system_buffer
);
686 // Sets the current working directory for the process.
687 bool SetCurrentDirectory(const FilePath
& path
) {
688 base::ThreadRestrictions::AssertIOAllowed();
689 int ret
= chdir(path
.value().c_str());
693 ///////////////////////////////////////////////
696 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
699 : current_directory_entry_(0),
700 root_path_(root_path
),
701 recursive_(recursive
),
702 file_type_(file_type
) {
703 // INCLUDE_DOT_DOT must not be specified if recursive.
704 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
705 pending_paths_
.push(root_path
);
708 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
711 const FilePath::StringType
& pattern
)
712 : current_directory_entry_(0),
713 root_path_(root_path
),
714 recursive_(recursive
),
715 file_type_(file_type
),
716 pattern_(root_path
.Append(pattern
).value()) {
717 // INCLUDE_DOT_DOT must not be specified if recursive.
718 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
719 // The Windows version of this code appends the pattern to the root_path,
720 // potentially only matching against items in the top-most directory.
723 pattern_
= FilePath::StringType();
724 pending_paths_
.push(root_path
);
727 FileEnumerator::~FileEnumerator() {
730 FilePath
FileEnumerator::Next() {
731 ++current_directory_entry_
;
733 // While we've exhausted the entries in the current directory, do the next
734 while (current_directory_entry_
>= directory_entries_
.size()) {
735 if (pending_paths_
.empty())
738 root_path_
= pending_paths_
.top();
739 root_path_
= root_path_
.StripTrailingSeparators();
740 pending_paths_
.pop();
742 std::vector
<DirectoryEntryInfo
> entries
;
743 if (!ReadDirectory(&entries
, root_path_
, file_type_
& SHOW_SYM_LINKS
))
746 directory_entries_
.clear();
747 current_directory_entry_
= 0;
748 for (std::vector
<DirectoryEntryInfo
>::const_iterator
749 i
= entries
.begin(); i
!= entries
.end(); ++i
) {
750 FilePath full_path
= root_path_
.Append(i
->filename
);
751 if (ShouldSkip(full_path
))
754 if (pattern_
.size() &&
755 fnmatch(pattern_
.c_str(), full_path
.value().c_str(), FNM_NOESCAPE
))
758 if (recursive_
&& S_ISDIR(i
->stat
.st_mode
))
759 pending_paths_
.push(full_path
);
761 if ((S_ISDIR(i
->stat
.st_mode
) && (file_type_
& DIRECTORIES
)) ||
762 (!S_ISDIR(i
->stat
.st_mode
) && (file_type_
& FILES
)))
763 directory_entries_
.push_back(*i
);
767 return root_path_
.Append(directory_entries_
[current_directory_entry_
771 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
774 if (current_directory_entry_
>= directory_entries_
.size())
777 DirectoryEntryInfo
* cur_entry
= &directory_entries_
[current_directory_entry_
];
778 memcpy(&(info
->stat
), &(cur_entry
->stat
), sizeof(info
->stat
));
779 info
->filename
.assign(cur_entry
->filename
.value());
783 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
784 return S_ISDIR(info
.stat
.st_mode
);
788 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
789 return FilePath(find_info
.filename
);
793 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
794 return find_info
.stat
.st_size
;
798 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
799 return base::Time::FromTimeT(find_info
.stat
.st_mtime
);
802 bool FileEnumerator::ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
803 const FilePath
& source
, bool show_links
) {
804 base::ThreadRestrictions::AssertIOAllowed();
805 DIR* dir
= opendir(source
.value().c_str());
809 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
810 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
811 #error Port warning: depending on the definition of struct dirent, \
812 additional space for pathname may be needed
815 struct dirent dent_buf
;
817 while (readdir_r(dir
, &dent_buf
, &dent
) == 0 && dent
) {
818 DirectoryEntryInfo info
;
819 info
.filename
= FilePath(dent
->d_name
);
821 FilePath full_name
= source
.Append(dent
->d_name
);
824 ret
= lstat(full_name
.value().c_str(), &info
.stat
);
826 ret
= stat(full_name
.value().c_str(), &info
.stat
);
828 // Print the stat() error message unless it was ENOENT and we're
829 // following symlinks.
830 if (!(errno
== ENOENT
&& !show_links
)) {
831 DPLOG(ERROR
) << "Couldn't stat "
832 << source
.Append(dent
->d_name
).value();
834 memset(&info
.stat
, 0, sizeof(info
.stat
));
836 entries
->push_back(info
);
843 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
844 FilePath real_path_result
;
845 if (!RealPath(path
, &real_path_result
))
848 // To be consistant with windows, fail if |real_path_result| is a
850 stat_wrapper_t file_info
;
851 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
852 S_ISDIR(file_info
.st_mode
))
855 *normalized_path
= real_path_result
;
859 #if !defined(OS_MACOSX)
860 bool GetTempDir(FilePath
* path
) {
861 const char* tmp
= getenv("TMPDIR");
863 *path
= FilePath(tmp
);
865 #if defined(OS_ANDROID)
866 return PathService::Get(base::DIR_CACHE
, path
);
868 *path
= FilePath("/tmp");
873 #if !defined(OS_ANDROID)
875 #if defined(OS_LINUX)
876 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
877 // This depends on the mount options used for /dev/shm, which vary among
878 // different Linux distributions and possibly local configuration. It also
879 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
880 // but its kernel allows mprotect with PROT_EXEC anyway.
884 bool DetermineDevShmExecutable() {
887 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
889 ScopedFD
shm_fd_closer(&fd
);
891 long sysconf_result
= sysconf(_SC_PAGESIZE
);
892 CHECK_GE(sysconf_result
, 0);
893 size_t pagesize
= static_cast<size_t>(sysconf_result
);
894 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
895 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
896 if (mapping
!= MAP_FAILED
) {
897 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
899 munmap(mapping
, pagesize
);
906 #endif // defined(OS_LINUX)
908 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
909 #if defined(OS_LINUX)
910 bool use_dev_shm
= true;
912 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
913 use_dev_shm
= s_dev_shm_executable
;
916 *path
= FilePath("/dev/shm");
920 return GetTempDir(path
);
922 #endif // !defined(OS_ANDROID)
924 FilePath
GetHomeDir() {
925 #if defined(OS_CHROMEOS)
926 if (base::chromeos::IsRunningOnChromeOS())
927 return FilePath("/home/chronos/user");
930 const char* home_dir
= getenv("HOME");
931 if (home_dir
&& home_dir
[0])
932 return FilePath(home_dir
);
934 #if defined(OS_ANDROID)
935 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
937 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
938 base::ThreadRestrictions::AssertIOAllowed();
940 home_dir
= g_get_home_dir();
941 if (home_dir
&& home_dir
[0])
942 return FilePath(home_dir
);
946 if (file_util::GetTempDir(&rv
))
950 return FilePath("/tmp");
953 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
954 base::ThreadRestrictions::AssertIOAllowed();
955 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
959 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
961 ignore_result(HANDLE_EINTR(close(infile
)));
965 const size_t kBufferSize
= 32768;
966 std::vector
<char> buffer(kBufferSize
);
970 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
971 if (bytes_read
< 0) {
977 // Allow for partial writes
978 ssize_t bytes_written_per_read
= 0;
980 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
982 &buffer
[bytes_written_per_read
],
983 bytes_read
- bytes_written_per_read
));
984 if (bytes_written_partial
< 0) {
988 bytes_written_per_read
+= bytes_written_partial
;
989 } while (bytes_written_per_read
< bytes_read
);
992 if (HANDLE_EINTR(close(infile
)) < 0)
994 if (HANDLE_EINTR(close(outfile
)) < 0)
999 #endif // !defined(OS_MACOSX)
1001 bool VerifyPathControlledByUser(const FilePath
& base
,
1002 const FilePath
& path
,
1004 const std::set
<gid_t
>& group_gids
) {
1005 if (base
!= path
&& !base
.IsParent(path
)) {
1006 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
1007 << base
.value() << "\", path = \"" << path
.value() << "\"";
1011 std::vector
<FilePath::StringType
> base_components
;
1012 std::vector
<FilePath::StringType
> path_components
;
1014 base
.GetComponents(&base_components
);
1015 path
.GetComponents(&path_components
);
1017 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
1018 for (ib
= base_components
.begin(), ip
= path_components
.begin();
1019 ib
!= base_components
.end(); ++ib
, ++ip
) {
1020 // |base| must be a subpath of |path|, so all components should match.
1021 // If these CHECKs fail, look at the test that base is a parent of
1022 // path at the top of this function.
1023 DCHECK(ip
!= path_components
.end());
1027 FilePath current_path
= base
;
1028 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
1031 for (; ip
!= path_components
.end(); ++ip
) {
1032 current_path
= current_path
.Append(*ip
);
1033 if (!VerifySpecificPathControlledByUser(
1034 current_path
, owner_uid
, group_gids
))
1040 #if defined(OS_MACOSX) && !defined(OS_IOS)
1041 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
1042 const unsigned kRootUid
= 0;
1043 const FilePath
kFileSystemRoot("/");
1045 // The name of the administrator group on mac os.
1046 const char* const kAdminGroupNames
[] = {
1051 // Reading the groups database may touch the file system.
1052 base::ThreadRestrictions::AssertIOAllowed();
1054 std::set
<gid_t
> allowed_group_ids
;
1055 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
1056 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
1057 if (!group_record
) {
1058 DPLOG(ERROR
) << "Could not get the group ID of group \""
1059 << kAdminGroupNames
[i
] << "\".";
1063 allowed_group_ids
.insert(group_record
->gr_gid
);
1066 return VerifyPathControlledByUser(
1067 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
1069 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1071 int GetMaximumPathComponentLength(const FilePath
& path
) {
1072 base::ThreadRestrictions::AssertIOAllowed();
1073 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
1076 } // namespace file_util