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 ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
236 base::ThreadRestrictions::AssertIOAllowed();
237 return (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0);
240 bool CopyDirectory(const FilePath
& from_path
,
241 const FilePath
& to_path
,
243 base::ThreadRestrictions::AssertIOAllowed();
244 // Some old callers of CopyDirectory want it to support wildcards.
245 // After some discussion, we decided to fix those callers.
246 // Break loudly here if anyone tries to do this.
247 // TODO(evanm): remove this once we're sure it's ok.
248 DCHECK(to_path
.value().find('*') == std::string::npos
);
249 DCHECK(from_path
.value().find('*') == std::string::npos
);
251 char top_dir
[PATH_MAX
];
252 if (base::strlcpy(top_dir
, from_path
.value().c_str(),
253 arraysize(top_dir
)) >= arraysize(top_dir
)) {
257 // This function does not properly handle destinations within the source
258 FilePath real_to_path
= to_path
;
259 if (PathExists(real_to_path
)) {
260 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
261 if (real_to_path
.empty())
264 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
265 if (real_to_path
.empty())
268 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
269 if (real_from_path
.empty())
271 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
272 real_to_path
.value().compare(0, real_from_path
.value().size(),
273 real_from_path
.value()) == 0)
277 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
279 traverse_type
|= FileEnumerator::DIRECTORIES
;
280 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
282 // We have to mimic windows behavior here. |to_path| may not exist yet,
283 // start the loop with |to_path|.
284 FileEnumerator::FindInfo info
;
285 FilePath current
= from_path
;
286 if (stat(from_path
.value().c_str(), &info
.stat
) < 0) {
287 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
288 << from_path
.value() << " errno = " << errno
;
291 struct stat to_path_stat
;
292 FilePath from_path_base
= from_path
;
293 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
294 S_ISDIR(to_path_stat
.st_mode
)) {
295 // If the destination already exists and is a directory, then the
296 // top level of source needs to be copied.
297 from_path_base
= from_path
.DirName();
300 // The Windows version of this function assumes that non-recursive calls
301 // will always have a directory for from_path.
302 DCHECK(recursive
|| S_ISDIR(info
.stat
.st_mode
));
304 while (success
&& !current
.empty()) {
305 // current is the source path, including from_path, so append
306 // the suffix after from_path to to_path to create the target_path.
307 FilePath
target_path(to_path
);
308 if (from_path_base
!= current
) {
309 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
315 if (S_ISDIR(info
.stat
.st_mode
)) {
316 if (mkdir(target_path
.value().c_str(), info
.stat
.st_mode
& 01777) != 0 &&
318 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
319 << target_path
.value() << " errno = " << errno
;
322 } else if (S_ISREG(info
.stat
.st_mode
)) {
323 if (!CopyFile(current
, target_path
)) {
324 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
325 << target_path
.value();
329 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
333 current
= traversal
.Next();
334 traversal
.GetFindInfo(&info
);
340 bool PathExists(const FilePath
& path
) {
341 base::ThreadRestrictions::AssertIOAllowed();
342 return access(path
.value().c_str(), F_OK
) == 0;
345 bool PathIsWritable(const FilePath
& path
) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 return access(path
.value().c_str(), W_OK
) == 0;
350 bool DirectoryExists(const FilePath
& path
) {
351 base::ThreadRestrictions::AssertIOAllowed();
352 stat_wrapper_t file_info
;
353 if (CallStat(path
.value().c_str(), &file_info
) == 0)
354 return S_ISDIR(file_info
.st_mode
);
358 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
359 size_t total_read
= 0;
360 while (total_read
< bytes
) {
362 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
365 total_read
+= bytes_read
;
367 return total_read
== bytes
;
370 bool CreateSymbolicLink(const FilePath
& target_path
,
371 const FilePath
& symlink_path
) {
372 DCHECK(!symlink_path
.empty());
373 DCHECK(!target_path
.empty());
374 return ::symlink(target_path
.value().c_str(),
375 symlink_path
.value().c_str()) != -1;
378 bool ReadSymbolicLink(const FilePath
& symlink_path
,
379 FilePath
* target_path
) {
380 DCHECK(!symlink_path
.empty());
383 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
386 target_path
->clear();
390 *target_path
= FilePath(FilePath::StringType(buf
, count
));
394 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
395 base::ThreadRestrictions::AssertIOAllowed();
398 stat_wrapper_t file_info
;
399 // Uses stat(), because on symbolic link, lstat() does not return valid
400 // permission bits in st_mode
401 if (CallStat(path
.value().c_str(), &file_info
) != 0)
404 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
408 bool SetPosixFilePermissions(const FilePath
& path
,
410 base::ThreadRestrictions::AssertIOAllowed();
411 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
413 // Calls stat() so that we can preserve the higher bits like S_ISGID.
414 stat_wrapper_t stat_buf
;
415 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
418 // Clears the existing permission bits, and adds the new ones.
419 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
420 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
422 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
428 // Creates and opens a temporary file in |directory|, returning the
429 // file descriptor. |path| is set to the temporary file path.
430 // This function does NOT unlink() the file.
431 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
432 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
433 *path
= directory
.Append(TempFileName());
434 const std::string
& tmpdir_string
= path
->value();
435 // this should be OK since mkstemp just replaces characters in place
436 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
438 return HANDLE_EINTR(mkstemp(buffer
));
441 bool CreateTemporaryFile(FilePath
* path
) {
442 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
444 if (!GetTempDir(&directory
))
446 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
449 ignore_result(HANDLE_EINTR(close(fd
)));
453 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
455 if (!GetShmemTempDir(&directory
, executable
))
458 return CreateAndOpenTemporaryFileInDir(directory
, path
);
461 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
462 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
466 FILE* file
= fdopen(fd
, "a+");
468 ignore_result(HANDLE_EINTR(close(fd
)));
472 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
473 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
474 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
475 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
478 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
479 const FilePath::StringType
& name_tmpl
,
481 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
482 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
483 << "Directory name template must contain \"XXXXXX\".";
485 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
486 std::string sub_dir_string
= sub_dir
.value();
488 // this should be OK since mkdtemp just replaces characters in place
489 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
490 char* dtemp
= mkdtemp(buffer
);
492 DPLOG(ERROR
) << "mkdtemp";
495 *new_dir
= FilePath(dtemp
);
499 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
500 const FilePath::StringType
& prefix
,
502 FilePath::StringType mkdtemp_template
= prefix
;
503 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
504 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
507 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
508 FilePath
* new_temp_path
) {
510 if (!GetTempDir(&tmpdir
))
513 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
516 bool CreateDirectory(const FilePath
& full_path
) {
517 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
518 std::vector
<FilePath
> subpaths
;
520 // Collect a list of all parent directories.
521 FilePath last_path
= full_path
;
522 subpaths
.push_back(full_path
);
523 for (FilePath path
= full_path
.DirName();
524 path
.value() != last_path
.value(); path
= path
.DirName()) {
525 subpaths
.push_back(path
);
529 // Iterate through the parents and create the missing ones.
530 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
531 i
!= subpaths
.rend(); ++i
) {
532 if (DirectoryExists(*i
))
534 if (mkdir(i
->value().c_str(), 0700) == 0)
536 // Mkdir failed, but it might have failed with EEXIST, or some other error
537 // due to the the directory appearing out of thin air. This can occur if
538 // two processes are trying to create the same file system tree at the same
539 // time. Check to see if it exists and make sure it is a directory.
540 if (!DirectoryExists(*i
))
546 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
547 const int kMaxAttempts
= 20;
548 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
550 GetUniquePathNumber(path
, base::FilePath::StringType());
553 base::FilePath test_path
= (uniquifier
== 0) ? path
:
554 path
.InsertBeforeExtensionASCII(
555 base::StringPrintf(" (%d)", uniquifier
));
556 if (mkdir(test_path
.value().c_str(), 0777) == 0)
558 else if (errno
!= EEXIST
)
561 return base::FilePath();
564 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
565 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
566 bool IsLink(const FilePath
& file_path
) {
568 // If we can't lstat the file, it's safe to assume that the file won't at
569 // least be a 'followable' link.
570 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
573 if (S_ISLNK(st
.st_mode
))
579 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
580 stat_wrapper_t file_info
;
581 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
583 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
584 results
->size
= file_info
.st_size
;
585 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
586 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
587 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
591 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
592 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
594 int result
= stat(path
.value().c_str(), &buffer
);
598 *inode
= buffer
.st_ino
;
602 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
603 return OpenFile(FilePath(filename
), mode
);
606 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
607 base::ThreadRestrictions::AssertIOAllowed();
610 result
= fopen(filename
.value().c_str(), mode
);
611 } while (!result
&& errno
== EINTR
);
615 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
616 base::ThreadRestrictions::AssertIOAllowed();
617 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
621 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
622 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
627 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
628 base::ThreadRestrictions::AssertIOAllowed();
629 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
633 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
634 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
636 return bytes_written
;
639 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
640 // Allow for partial writes.
641 ssize_t bytes_written_total
= 0;
642 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
643 bytes_written_total
+= bytes_written_partial
) {
644 bytes_written_partial
=
645 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
646 size
- bytes_written_total
));
647 if (bytes_written_partial
< 0)
651 return bytes_written_total
;
654 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
655 base::ThreadRestrictions::AssertIOAllowed();
656 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
660 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
661 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
663 return bytes_written
;
666 // Gets the current working directory for the process.
667 bool GetCurrentDirectory(FilePath
* dir
) {
668 // getcwd can return ENOENT, which implies it checks against the disk.
669 base::ThreadRestrictions::AssertIOAllowed();
671 char system_buffer
[PATH_MAX
] = "";
672 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
676 *dir
= FilePath(system_buffer
);
680 // Sets the current working directory for the process.
681 bool SetCurrentDirectory(const FilePath
& path
) {
682 base::ThreadRestrictions::AssertIOAllowed();
683 int ret
= chdir(path
.value().c_str());
687 ///////////////////////////////////////////////
690 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
693 : current_directory_entry_(0),
694 root_path_(root_path
),
695 recursive_(recursive
),
696 file_type_(file_type
) {
697 // INCLUDE_DOT_DOT must not be specified if recursive.
698 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
699 pending_paths_
.push(root_path
);
702 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
705 const FilePath::StringType
& pattern
)
706 : current_directory_entry_(0),
707 root_path_(root_path
),
708 recursive_(recursive
),
709 file_type_(file_type
),
710 pattern_(root_path
.Append(pattern
).value()) {
711 // INCLUDE_DOT_DOT must not be specified if recursive.
712 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
713 // The Windows version of this code appends the pattern to the root_path,
714 // potentially only matching against items in the top-most directory.
717 pattern_
= FilePath::StringType();
718 pending_paths_
.push(root_path
);
721 FileEnumerator::~FileEnumerator() {
724 FilePath
FileEnumerator::Next() {
725 ++current_directory_entry_
;
727 // While we've exhausted the entries in the current directory, do the next
728 while (current_directory_entry_
>= directory_entries_
.size()) {
729 if (pending_paths_
.empty())
732 root_path_
= pending_paths_
.top();
733 root_path_
= root_path_
.StripTrailingSeparators();
734 pending_paths_
.pop();
736 std::vector
<DirectoryEntryInfo
> entries
;
737 if (!ReadDirectory(&entries
, root_path_
, file_type_
& SHOW_SYM_LINKS
))
740 directory_entries_
.clear();
741 current_directory_entry_
= 0;
742 for (std::vector
<DirectoryEntryInfo
>::const_iterator
743 i
= entries
.begin(); i
!= entries
.end(); ++i
) {
744 FilePath full_path
= root_path_
.Append(i
->filename
);
745 if (ShouldSkip(full_path
))
748 if (pattern_
.size() &&
749 fnmatch(pattern_
.c_str(), full_path
.value().c_str(), FNM_NOESCAPE
))
752 if (recursive_
&& S_ISDIR(i
->stat
.st_mode
))
753 pending_paths_
.push(full_path
);
755 if ((S_ISDIR(i
->stat
.st_mode
) && (file_type_
& DIRECTORIES
)) ||
756 (!S_ISDIR(i
->stat
.st_mode
) && (file_type_
& FILES
)))
757 directory_entries_
.push_back(*i
);
761 return root_path_
.Append(directory_entries_
[current_directory_entry_
765 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
768 if (current_directory_entry_
>= directory_entries_
.size())
771 DirectoryEntryInfo
* cur_entry
= &directory_entries_
[current_directory_entry_
];
772 memcpy(&(info
->stat
), &(cur_entry
->stat
), sizeof(info
->stat
));
773 info
->filename
.assign(cur_entry
->filename
.value());
777 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
778 return S_ISDIR(info
.stat
.st_mode
);
782 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
783 return FilePath(find_info
.filename
);
787 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
788 return find_info
.stat
.st_size
;
792 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
793 return base::Time::FromTimeT(find_info
.stat
.st_mtime
);
796 bool FileEnumerator::ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
797 const FilePath
& source
, bool show_links
) {
798 base::ThreadRestrictions::AssertIOAllowed();
799 DIR* dir
= opendir(source
.value().c_str());
803 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
804 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
805 #error Port warning: depending on the definition of struct dirent, \
806 additional space for pathname may be needed
809 struct dirent dent_buf
;
811 while (readdir_r(dir
, &dent_buf
, &dent
) == 0 && dent
) {
812 DirectoryEntryInfo info
;
813 info
.filename
= FilePath(dent
->d_name
);
815 FilePath full_name
= source
.Append(dent
->d_name
);
818 ret
= lstat(full_name
.value().c_str(), &info
.stat
);
820 ret
= stat(full_name
.value().c_str(), &info
.stat
);
822 // Print the stat() error message unless it was ENOENT and we're
823 // following symlinks.
824 if (!(errno
== ENOENT
&& !show_links
)) {
825 DPLOG(ERROR
) << "Couldn't stat "
826 << source
.Append(dent
->d_name
).value();
828 memset(&info
.stat
, 0, sizeof(info
.stat
));
830 entries
->push_back(info
);
837 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
838 FilePath real_path_result
;
839 if (!RealPath(path
, &real_path_result
))
842 // To be consistant with windows, fail if |real_path_result| is a
844 stat_wrapper_t file_info
;
845 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
846 S_ISDIR(file_info
.st_mode
))
849 *normalized_path
= real_path_result
;
853 #if !defined(OS_MACOSX)
854 bool GetTempDir(FilePath
* path
) {
855 const char* tmp
= getenv("TMPDIR");
857 *path
= FilePath(tmp
);
859 #if defined(OS_ANDROID)
860 return PathService::Get(base::DIR_CACHE
, path
);
862 *path
= FilePath("/tmp");
867 #if !defined(OS_ANDROID)
869 #if defined(OS_LINUX)
870 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
871 // This depends on the mount options used for /dev/shm, which vary among
872 // different Linux distributions and possibly local configuration. It also
873 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
874 // but its kernel allows mprotect with PROT_EXEC anyway.
878 bool DetermineDevShmExecutable() {
881 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
883 ScopedFD
shm_fd_closer(&fd
);
885 long sysconf_result
= sysconf(_SC_PAGESIZE
);
886 CHECK_GE(sysconf_result
, 0);
887 size_t pagesize
= static_cast<size_t>(sysconf_result
);
888 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
889 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
890 if (mapping
!= MAP_FAILED
) {
891 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
893 munmap(mapping
, pagesize
);
900 #endif // defined(OS_LINUX)
902 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
903 #if defined(OS_LINUX)
904 bool use_dev_shm
= true;
906 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
907 use_dev_shm
= s_dev_shm_executable
;
910 *path
= FilePath("/dev/shm");
914 return GetTempDir(path
);
916 #endif // !defined(OS_ANDROID)
918 FilePath
GetHomeDir() {
919 #if defined(OS_CHROMEOS)
920 if (base::chromeos::IsRunningOnChromeOS())
921 return FilePath("/home/chronos/user");
924 const char* home_dir
= getenv("HOME");
925 if (home_dir
&& home_dir
[0])
926 return FilePath(home_dir
);
928 #if defined(OS_ANDROID)
929 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
931 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
932 base::ThreadRestrictions::AssertIOAllowed();
934 home_dir
= g_get_home_dir();
935 if (home_dir
&& home_dir
[0])
936 return FilePath(home_dir
);
940 if (file_util::GetTempDir(&rv
))
944 return FilePath("/tmp");
947 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
948 base::ThreadRestrictions::AssertIOAllowed();
949 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
953 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
955 ignore_result(HANDLE_EINTR(close(infile
)));
959 const size_t kBufferSize
= 32768;
960 std::vector
<char> buffer(kBufferSize
);
964 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
965 if (bytes_read
< 0) {
971 // Allow for partial writes
972 ssize_t bytes_written_per_read
= 0;
974 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
976 &buffer
[bytes_written_per_read
],
977 bytes_read
- bytes_written_per_read
));
978 if (bytes_written_partial
< 0) {
982 bytes_written_per_read
+= bytes_written_partial
;
983 } while (bytes_written_per_read
< bytes_read
);
986 if (HANDLE_EINTR(close(infile
)) < 0)
988 if (HANDLE_EINTR(close(outfile
)) < 0)
993 #endif // !defined(OS_MACOSX)
995 bool VerifyPathControlledByUser(const FilePath
& base
,
996 const FilePath
& path
,
998 const std::set
<gid_t
>& group_gids
) {
999 if (base
!= path
&& !base
.IsParent(path
)) {
1000 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
1001 << base
.value() << "\", path = \"" << path
.value() << "\"";
1005 std::vector
<FilePath::StringType
> base_components
;
1006 std::vector
<FilePath::StringType
> path_components
;
1008 base
.GetComponents(&base_components
);
1009 path
.GetComponents(&path_components
);
1011 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
1012 for (ib
= base_components
.begin(), ip
= path_components
.begin();
1013 ib
!= base_components
.end(); ++ib
, ++ip
) {
1014 // |base| must be a subpath of |path|, so all components should match.
1015 // If these CHECKs fail, look at the test that base is a parent of
1016 // path at the top of this function.
1017 DCHECK(ip
!= path_components
.end());
1021 FilePath current_path
= base
;
1022 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
1025 for (; ip
!= path_components
.end(); ++ip
) {
1026 current_path
= current_path
.Append(*ip
);
1027 if (!VerifySpecificPathControlledByUser(
1028 current_path
, owner_uid
, group_gids
))
1034 #if defined(OS_MACOSX) && !defined(OS_IOS)
1035 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
1036 const unsigned kRootUid
= 0;
1037 const FilePath
kFileSystemRoot("/");
1039 // The name of the administrator group on mac os.
1040 const char* const kAdminGroupNames
[] = {
1045 // Reading the groups database may touch the file system.
1046 base::ThreadRestrictions::AssertIOAllowed();
1048 std::set
<gid_t
> allowed_group_ids
;
1049 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
1050 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
1051 if (!group_record
) {
1052 DPLOG(ERROR
) << "Could not get the group ID of group \""
1053 << kAdminGroupNames
[i
] << "\".";
1057 allowed_group_ids
.insert(group_record
->gr_gid
);
1060 return VerifyPathControlledByUser(
1061 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
1063 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1065 int GetMaximumPathComponentLength(const FilePath
& path
) {
1066 base::ThreadRestrictions::AssertIOAllowed();
1067 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
1070 } // namespace file_util