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"
67 #if defined(OS_BSD) || defined(OS_MACOSX)
68 typedef struct stat stat_wrapper_t
;
69 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
70 base::ThreadRestrictions::AssertIOAllowed();
71 return stat(path
, sb
);
73 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
74 base::ThreadRestrictions::AssertIOAllowed();
75 return lstat(path
, sb
);
78 typedef struct stat64 stat_wrapper_t
;
79 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
80 base::ThreadRestrictions::AssertIOAllowed();
81 return stat64(path
, sb
);
83 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
84 base::ThreadRestrictions::AssertIOAllowed();
85 return lstat64(path
, sb
);
89 // Helper for NormalizeFilePath(), defined below.
90 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
91 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
92 FilePath::CharType buf
[PATH_MAX
];
93 if (!realpath(path
.value().c_str(), buf
))
96 *real_path
= FilePath(buf
);
100 // Helper for VerifyPathControlledByUser.
101 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
103 const std::set
<gid_t
>& group_gids
) {
104 stat_wrapper_t stat_info
;
105 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
106 DPLOG(ERROR
) << "Failed to get information on path "
111 if (S_ISLNK(stat_info
.st_mode
)) {
112 DLOG(ERROR
) << "Path " << path
.value()
113 << " is a symbolic link.";
117 if (stat_info
.st_uid
!= owner_uid
) {
118 DLOG(ERROR
) << "Path " << path
.value()
119 << " is owned by the wrong user.";
123 if ((stat_info
.st_mode
& S_IWGRP
) &&
124 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
125 DLOG(ERROR
) << "Path " << path
.value()
126 << " is writable by an unprivileged group.";
130 if (stat_info
.st_mode
& S_IWOTH
) {
131 DLOG(ERROR
) << "Path " << path
.value()
132 << " is writable by any user.";
141 static std::string
TempFileName() {
142 #if defined(OS_MACOSX)
143 return base::StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
146 #if defined(GOOGLE_CHROME_BUILD)
147 return std::string(".com.google.Chrome.XXXXXX");
149 return std::string(".org.chromium.Chromium.XXXXXX");
153 bool AbsolutePath(FilePath
* path
) {
154 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
155 char full_path
[PATH_MAX
];
156 if (realpath(path
->value().c_str(), full_path
) == NULL
)
158 *path
= FilePath(full_path
);
162 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
163 // which works both with and without the recursive flag. I'm not sure we need
164 // that functionality. If not, remove from file_util_win.cc, otherwise add it
166 bool Delete(const FilePath
& path
, bool recursive
) {
167 base::ThreadRestrictions::AssertIOAllowed();
168 const char* path_str
= path
.value().c_str();
169 stat_wrapper_t file_info
;
170 int test
= CallLstat(path_str
, &file_info
);
172 // The Windows version defines this condition as success.
173 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
176 if (!S_ISDIR(file_info
.st_mode
))
177 return (unlink(path_str
) == 0);
179 return (rmdir(path_str
) == 0);
182 std::stack
<std::string
> directories
;
183 directories
.push(path
.value());
184 FileEnumerator
traversal(path
, true,
185 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
186 FileEnumerator::SHOW_SYM_LINKS
);
187 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
188 current
= traversal
.Next()) {
189 FileEnumerator::FindInfo info
;
190 traversal
.GetFindInfo(&info
);
192 if (S_ISDIR(info
.stat
.st_mode
))
193 directories
.push(current
.value());
195 success
= (unlink(current
.value().c_str()) == 0);
198 while (success
&& !directories
.empty()) {
199 FilePath dir
= FilePath(directories
.top());
201 success
= (rmdir(dir
.value().c_str()) == 0);
206 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
207 base::ThreadRestrictions::AssertIOAllowed();
208 // Windows compatibility: if to_path exists, from_path and to_path
209 // must be the same type, either both files, or both directories.
210 stat_wrapper_t to_file_info
;
211 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
212 stat_wrapper_t from_file_info
;
213 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
214 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
221 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
224 if (!CopyDirectory(from_path
, to_path
, true))
227 Delete(from_path
, true);
231 bool ReplaceFile(const FilePath
& from_path
, const FilePath
& to_path
) {
232 base::ThreadRestrictions::AssertIOAllowed();
233 return (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0);
236 bool CopyDirectory(const FilePath
& from_path
,
237 const FilePath
& to_path
,
239 base::ThreadRestrictions::AssertIOAllowed();
240 // Some old callers of CopyDirectory want it to support wildcards.
241 // After some discussion, we decided to fix those callers.
242 // Break loudly here if anyone tries to do this.
243 // TODO(evanm): remove this once we're sure it's ok.
244 DCHECK(to_path
.value().find('*') == std::string::npos
);
245 DCHECK(from_path
.value().find('*') == std::string::npos
);
247 char top_dir
[PATH_MAX
];
248 if (base::strlcpy(top_dir
, from_path
.value().c_str(),
249 arraysize(top_dir
)) >= arraysize(top_dir
)) {
253 // This function does not properly handle destinations within the source
254 FilePath real_to_path
= to_path
;
255 if (PathExists(real_to_path
)) {
256 if (!AbsolutePath(&real_to_path
))
259 real_to_path
= real_to_path
.DirName();
260 if (!AbsolutePath(&real_to_path
))
263 FilePath real_from_path
= from_path
;
264 if (!AbsolutePath(&real_from_path
))
266 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
267 real_to_path
.value().compare(0, real_from_path
.value().size(),
268 real_from_path
.value()) == 0)
272 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
274 traverse_type
|= FileEnumerator::DIRECTORIES
;
275 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
277 // We have to mimic windows behavior here. |to_path| may not exist yet,
278 // start the loop with |to_path|.
279 FileEnumerator::FindInfo info
;
280 FilePath current
= from_path
;
281 if (stat(from_path
.value().c_str(), &info
.stat
) < 0) {
282 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
283 << from_path
.value() << " errno = " << errno
;
286 struct stat to_path_stat
;
287 FilePath from_path_base
= from_path
;
288 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
289 S_ISDIR(to_path_stat
.st_mode
)) {
290 // If the destination already exists and is a directory, then the
291 // top level of source needs to be copied.
292 from_path_base
= from_path
.DirName();
295 // The Windows version of this function assumes that non-recursive calls
296 // will always have a directory for from_path.
297 DCHECK(recursive
|| S_ISDIR(info
.stat
.st_mode
));
299 while (success
&& !current
.empty()) {
300 // current is the source path, including from_path, so append
301 // the suffix after from_path to to_path to create the target_path.
302 FilePath
target_path(to_path
);
303 if (from_path_base
!= current
) {
304 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
310 if (S_ISDIR(info
.stat
.st_mode
)) {
311 if (mkdir(target_path
.value().c_str(), info
.stat
.st_mode
& 01777) != 0 &&
313 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
314 << target_path
.value() << " errno = " << errno
;
317 } else if (S_ISREG(info
.stat
.st_mode
)) {
318 if (!CopyFile(current
, target_path
)) {
319 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
320 << target_path
.value();
324 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
328 current
= traversal
.Next();
329 traversal
.GetFindInfo(&info
);
335 bool PathExists(const FilePath
& path
) {
336 base::ThreadRestrictions::AssertIOAllowed();
337 return access(path
.value().c_str(), F_OK
) == 0;
340 bool PathIsWritable(const FilePath
& path
) {
341 base::ThreadRestrictions::AssertIOAllowed();
342 return access(path
.value().c_str(), W_OK
) == 0;
345 bool DirectoryExists(const FilePath
& path
) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 stat_wrapper_t file_info
;
348 if (CallStat(path
.value().c_str(), &file_info
) == 0)
349 return S_ISDIR(file_info
.st_mode
);
353 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
354 size_t total_read
= 0;
355 while (total_read
< bytes
) {
357 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
360 total_read
+= bytes_read
;
362 return total_read
== bytes
;
365 bool CreateSymbolicLink(const FilePath
& target_path
,
366 const FilePath
& symlink_path
) {
367 DCHECK(!symlink_path
.empty());
368 DCHECK(!target_path
.empty());
369 return ::symlink(target_path
.value().c_str(),
370 symlink_path
.value().c_str()) != -1;
373 bool ReadSymbolicLink(const FilePath
& symlink_path
,
374 FilePath
* target_path
) {
375 DCHECK(!symlink_path
.empty());
378 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
381 target_path
->clear();
385 *target_path
= FilePath(FilePath::StringType(buf
, count
));
389 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
390 base::ThreadRestrictions::AssertIOAllowed();
393 stat_wrapper_t file_info
;
394 // Uses stat(), because on symbolic link, lstat() does not return valid
395 // permission bits in st_mode
396 if (CallStat(path
.value().c_str(), &file_info
) != 0)
399 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
403 bool SetPosixFilePermissions(const FilePath
& path
,
405 base::ThreadRestrictions::AssertIOAllowed();
406 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
408 // Calls stat() so that we can preserve the higher bits like S_ISGID.
409 stat_wrapper_t stat_buf
;
410 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
413 // Clears the existing permission bits, and adds the new ones.
414 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
415 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
417 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
423 // Creates and opens a temporary file in |directory|, returning the
424 // file descriptor. |path| is set to the temporary file path.
425 // This function does NOT unlink() the file.
426 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
427 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
428 *path
= directory
.Append(TempFileName());
429 const std::string
& tmpdir_string
= path
->value();
430 // this should be OK since mkstemp just replaces characters in place
431 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
433 return HANDLE_EINTR(mkstemp(buffer
));
436 bool CreateTemporaryFile(FilePath
* path
) {
437 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
439 if (!GetTempDir(&directory
))
441 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
444 ignore_result(HANDLE_EINTR(close(fd
)));
448 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
450 if (!GetShmemTempDir(&directory
, executable
))
453 return CreateAndOpenTemporaryFileInDir(directory
, path
);
456 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
457 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
461 FILE* file
= fdopen(fd
, "a+");
463 ignore_result(HANDLE_EINTR(close(fd
)));
467 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
468 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
469 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
470 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
473 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
474 const FilePath::StringType
& name_tmpl
,
476 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
477 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
478 << "Directory name template must contain \"XXXXXX\".";
480 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
481 std::string sub_dir_string
= sub_dir
.value();
483 // this should be OK since mkdtemp just replaces characters in place
484 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
485 char* dtemp
= mkdtemp(buffer
);
487 DPLOG(ERROR
) << "mkdtemp";
490 *new_dir
= FilePath(dtemp
);
494 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
495 const FilePath::StringType
& prefix
,
497 FilePath::StringType mkdtemp_template
= prefix
;
498 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
499 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
502 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
503 FilePath
* new_temp_path
) {
505 if (!GetTempDir(&tmpdir
))
508 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
511 bool CreateDirectory(const FilePath
& full_path
) {
512 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
513 std::vector
<FilePath
> subpaths
;
515 // Collect a list of all parent directories.
516 FilePath last_path
= full_path
;
517 subpaths
.push_back(full_path
);
518 for (FilePath path
= full_path
.DirName();
519 path
.value() != last_path
.value(); path
= path
.DirName()) {
520 subpaths
.push_back(path
);
524 // Iterate through the parents and create the missing ones.
525 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
526 i
!= subpaths
.rend(); ++i
) {
527 if (DirectoryExists(*i
))
529 if (mkdir(i
->value().c_str(), 0700) == 0)
531 // Mkdir failed, but it might have failed with EEXIST, or some other error
532 // due to the the directory appearing out of thin air. This can occur if
533 // two processes are trying to create the same file system tree at the same
534 // time. Check to see if it exists and make sure it is a directory.
535 if (!DirectoryExists(*i
))
541 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
542 const int kMaxAttempts
= 20;
543 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
545 GetUniquePathNumber(path
, base::FilePath::StringType());
548 base::FilePath test_path
= (uniquifier
== 0) ? path
:
549 path
.InsertBeforeExtensionASCII(
550 base::StringPrintf(" (%d)", uniquifier
));
551 if (mkdir(test_path
.value().c_str(), 0777) == 0)
553 else if (errno
!= EEXIST
)
556 return base::FilePath();
559 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
560 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
561 bool IsLink(const FilePath
& file_path
) {
563 // If we can't lstat the file, it's safe to assume that the file won't at
564 // least be a 'followable' link.
565 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
568 if (S_ISLNK(st
.st_mode
))
574 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
575 stat_wrapper_t file_info
;
576 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
578 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
579 results
->size
= file_info
.st_size
;
580 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
581 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
582 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
586 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
587 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
589 int result
= stat(path
.value().c_str(), &buffer
);
593 *inode
= buffer
.st_ino
;
597 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
598 return OpenFile(FilePath(filename
), mode
);
601 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
602 base::ThreadRestrictions::AssertIOAllowed();
605 result
= fopen(filename
.value().c_str(), mode
);
606 } while (!result
&& errno
== EINTR
);
610 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
611 base::ThreadRestrictions::AssertIOAllowed();
612 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
616 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
617 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
622 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
623 base::ThreadRestrictions::AssertIOAllowed();
624 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
628 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
629 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
631 return bytes_written
;
634 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
635 // Allow for partial writes.
636 ssize_t bytes_written_total
= 0;
637 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
638 bytes_written_total
+= bytes_written_partial
) {
639 bytes_written_partial
=
640 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
641 size
- bytes_written_total
));
642 if (bytes_written_partial
< 0)
646 return bytes_written_total
;
649 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
650 base::ThreadRestrictions::AssertIOAllowed();
651 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
655 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
656 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
658 return bytes_written
;
661 // Gets the current working directory for the process.
662 bool GetCurrentDirectory(FilePath
* dir
) {
663 // getcwd can return ENOENT, which implies it checks against the disk.
664 base::ThreadRestrictions::AssertIOAllowed();
666 char system_buffer
[PATH_MAX
] = "";
667 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
671 *dir
= FilePath(system_buffer
);
675 // Sets the current working directory for the process.
676 bool SetCurrentDirectory(const FilePath
& path
) {
677 base::ThreadRestrictions::AssertIOAllowed();
678 int ret
= chdir(path
.value().c_str());
682 ///////////////////////////////////////////////
685 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
688 : current_directory_entry_(0),
689 root_path_(root_path
),
690 recursive_(recursive
),
691 file_type_(file_type
) {
692 // INCLUDE_DOT_DOT must not be specified if recursive.
693 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
694 pending_paths_
.push(root_path
);
697 FileEnumerator::FileEnumerator(const FilePath
& root_path
,
700 const FilePath::StringType
& pattern
)
701 : current_directory_entry_(0),
702 root_path_(root_path
),
703 recursive_(recursive
),
704 file_type_(file_type
),
705 pattern_(root_path
.Append(pattern
).value()) {
706 // INCLUDE_DOT_DOT must not be specified if recursive.
707 DCHECK(!(recursive
&& (INCLUDE_DOT_DOT
& file_type_
)));
708 // The Windows version of this code appends the pattern to the root_path,
709 // potentially only matching against items in the top-most directory.
712 pattern_
= FilePath::StringType();
713 pending_paths_
.push(root_path
);
716 FileEnumerator::~FileEnumerator() {
719 FilePath
FileEnumerator::Next() {
720 ++current_directory_entry_
;
722 // While we've exhausted the entries in the current directory, do the next
723 while (current_directory_entry_
>= directory_entries_
.size()) {
724 if (pending_paths_
.empty())
727 root_path_
= pending_paths_
.top();
728 root_path_
= root_path_
.StripTrailingSeparators();
729 pending_paths_
.pop();
731 std::vector
<DirectoryEntryInfo
> entries
;
732 if (!ReadDirectory(&entries
, root_path_
, file_type_
& SHOW_SYM_LINKS
))
735 directory_entries_
.clear();
736 current_directory_entry_
= 0;
737 for (std::vector
<DirectoryEntryInfo
>::const_iterator
738 i
= entries
.begin(); i
!= entries
.end(); ++i
) {
739 FilePath full_path
= root_path_
.Append(i
->filename
);
740 if (ShouldSkip(full_path
))
743 if (pattern_
.size() &&
744 fnmatch(pattern_
.c_str(), full_path
.value().c_str(), FNM_NOESCAPE
))
747 if (recursive_
&& S_ISDIR(i
->stat
.st_mode
))
748 pending_paths_
.push(full_path
);
750 if ((S_ISDIR(i
->stat
.st_mode
) && (file_type_
& DIRECTORIES
)) ||
751 (!S_ISDIR(i
->stat
.st_mode
) && (file_type_
& FILES
)))
752 directory_entries_
.push_back(*i
);
756 return root_path_
.Append(directory_entries_
[current_directory_entry_
760 void FileEnumerator::GetFindInfo(FindInfo
* info
) {
763 if (current_directory_entry_
>= directory_entries_
.size())
766 DirectoryEntryInfo
* cur_entry
= &directory_entries_
[current_directory_entry_
];
767 memcpy(&(info
->stat
), &(cur_entry
->stat
), sizeof(info
->stat
));
768 info
->filename
.assign(cur_entry
->filename
.value());
772 bool FileEnumerator::IsDirectory(const FindInfo
& info
) {
773 return S_ISDIR(info
.stat
.st_mode
);
777 FilePath
FileEnumerator::GetFilename(const FindInfo
& find_info
) {
778 return FilePath(find_info
.filename
);
782 int64
FileEnumerator::GetFilesize(const FindInfo
& find_info
) {
783 return find_info
.stat
.st_size
;
787 base::Time
FileEnumerator::GetLastModifiedTime(const FindInfo
& find_info
) {
788 return base::Time::FromTimeT(find_info
.stat
.st_mtime
);
791 bool FileEnumerator::ReadDirectory(std::vector
<DirectoryEntryInfo
>* entries
,
792 const FilePath
& source
, bool show_links
) {
793 base::ThreadRestrictions::AssertIOAllowed();
794 DIR* dir
= opendir(source
.value().c_str());
798 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
799 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
800 #error Port warning: depending on the definition of struct dirent, \
801 additional space for pathname may be needed
804 struct dirent dent_buf
;
806 while (readdir_r(dir
, &dent_buf
, &dent
) == 0 && dent
) {
807 DirectoryEntryInfo info
;
808 info
.filename
= FilePath(dent
->d_name
);
810 FilePath full_name
= source
.Append(dent
->d_name
);
813 ret
= lstat(full_name
.value().c_str(), &info
.stat
);
815 ret
= stat(full_name
.value().c_str(), &info
.stat
);
817 // Print the stat() error message unless it was ENOENT and we're
818 // following symlinks.
819 if (!(errno
== ENOENT
&& !show_links
)) {
820 DPLOG(ERROR
) << "Couldn't stat "
821 << source
.Append(dent
->d_name
).value();
823 memset(&info
.stat
, 0, sizeof(info
.stat
));
825 entries
->push_back(info
);
832 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
833 FilePath real_path_result
;
834 if (!RealPath(path
, &real_path_result
))
837 // To be consistant with windows, fail if |real_path_result| is a
839 stat_wrapper_t file_info
;
840 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
841 S_ISDIR(file_info
.st_mode
))
844 *normalized_path
= real_path_result
;
848 #if !defined(OS_MACOSX)
849 bool GetTempDir(FilePath
* path
) {
850 const char* tmp
= getenv("TMPDIR");
852 *path
= FilePath(tmp
);
854 #if defined(OS_ANDROID)
855 return PathService::Get(base::DIR_CACHE
, path
);
857 *path
= FilePath("/tmp");
862 #if !defined(OS_ANDROID)
864 #if defined(OS_LINUX)
865 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
866 // This depends on the mount options used for /dev/shm, which vary among
867 // different Linux distributions and possibly local configuration. It also
868 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
869 // but its kernel allows mprotect with PROT_EXEC anyway.
873 bool DetermineDevShmExecutable() {
876 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
878 ScopedFD
shm_fd_closer(&fd
);
880 long sysconf_result
= sysconf(_SC_PAGESIZE
);
881 CHECK_GE(sysconf_result
, 0);
882 size_t pagesize
= static_cast<size_t>(sysconf_result
);
883 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
884 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
885 if (mapping
!= MAP_FAILED
) {
886 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
888 munmap(mapping
, pagesize
);
895 #endif // defined(OS_LINUX)
897 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
898 #if defined(OS_LINUX)
899 bool use_dev_shm
= true;
901 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
902 use_dev_shm
= s_dev_shm_executable
;
905 *path
= FilePath("/dev/shm");
909 return GetTempDir(path
);
911 #endif // !defined(OS_ANDROID)
913 FilePath
GetHomeDir() {
914 #if defined(OS_CHROMEOS)
915 if (base::chromeos::IsRunningOnChromeOS())
916 return FilePath("/home/chronos/user");
919 const char* home_dir
= getenv("HOME");
920 if (home_dir
&& home_dir
[0])
921 return FilePath(home_dir
);
923 #if defined(OS_ANDROID)
924 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
926 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
927 base::ThreadRestrictions::AssertIOAllowed();
929 home_dir
= g_get_home_dir();
930 if (home_dir
&& home_dir
[0])
931 return FilePath(home_dir
);
935 if (file_util::GetTempDir(&rv
))
939 return FilePath("/tmp");
942 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
943 base::ThreadRestrictions::AssertIOAllowed();
944 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
948 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
950 ignore_result(HANDLE_EINTR(close(infile
)));
954 const size_t kBufferSize
= 32768;
955 std::vector
<char> buffer(kBufferSize
);
959 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
960 if (bytes_read
< 0) {
966 // Allow for partial writes
967 ssize_t bytes_written_per_read
= 0;
969 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
971 &buffer
[bytes_written_per_read
],
972 bytes_read
- bytes_written_per_read
));
973 if (bytes_written_partial
< 0) {
977 bytes_written_per_read
+= bytes_written_partial
;
978 } while (bytes_written_per_read
< bytes_read
);
981 if (HANDLE_EINTR(close(infile
)) < 0)
983 if (HANDLE_EINTR(close(outfile
)) < 0)
988 #endif // !defined(OS_MACOSX)
990 bool VerifyPathControlledByUser(const FilePath
& base
,
991 const FilePath
& path
,
993 const std::set
<gid_t
>& group_gids
) {
994 if (base
!= path
&& !base
.IsParent(path
)) {
995 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
996 << base
.value() << "\", path = \"" << path
.value() << "\"";
1000 std::vector
<FilePath::StringType
> base_components
;
1001 std::vector
<FilePath::StringType
> path_components
;
1003 base
.GetComponents(&base_components
);
1004 path
.GetComponents(&path_components
);
1006 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
1007 for (ib
= base_components
.begin(), ip
= path_components
.begin();
1008 ib
!= base_components
.end(); ++ib
, ++ip
) {
1009 // |base| must be a subpath of |path|, so all components should match.
1010 // If these CHECKs fail, look at the test that base is a parent of
1011 // path at the top of this function.
1012 DCHECK(ip
!= path_components
.end());
1016 FilePath current_path
= base
;
1017 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
1020 for (; ip
!= path_components
.end(); ++ip
) {
1021 current_path
= current_path
.Append(*ip
);
1022 if (!VerifySpecificPathControlledByUser(
1023 current_path
, owner_uid
, group_gids
))
1029 #if defined(OS_MACOSX) && !defined(OS_IOS)
1030 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
1031 const unsigned kRootUid
= 0;
1032 const FilePath
kFileSystemRoot("/");
1034 // The name of the administrator group on mac os.
1035 const char* const kAdminGroupNames
[] = {
1040 // Reading the groups database may touch the file system.
1041 base::ThreadRestrictions::AssertIOAllowed();
1043 std::set
<gid_t
> allowed_group_ids
;
1044 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
1045 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
1046 if (!group_record
) {
1047 DPLOG(ERROR
) << "Could not get the group ID of group \""
1048 << kAdminGroupNames
[i
] << "\".";
1052 allowed_group_ids
.insert(group_record
->gr_gid
);
1055 return VerifyPathControlledByUser(
1056 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
1058 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1060 int GetMaximumPathComponentLength(const FilePath
& path
) {
1061 base::ThreadRestrictions::AssertIOAllowed();
1062 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
1065 } // namespace file_util