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/files/file_util.h"
15 #include <sys/errno.h>
17 #include <sys/param.h>
20 #include <sys/types.h>
24 #if defined(OS_MACOSX)
25 #include <AvailabilityMacros.h>
26 #include "base/mac/foundation_util.h"
29 #include "base/basictypes.h"
30 #include "base/files/file_enumerator.h"
31 #include "base/files/file_path.h"
32 #include "base/files/scoped_file.h"
33 #include "base/logging.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/memory/singleton.h"
36 #include "base/path_service.h"
37 #include "base/posix/eintr_wrapper.h"
38 #include "base/stl_util.h"
39 #include "base/strings/string_util.h"
40 #include "base/strings/stringprintf.h"
41 #include "base/strings/sys_string_conversions.h"
42 #include "base/strings/utf_string_conversions.h"
43 #include "base/sys_info.h"
44 #include "base/threading/thread_restrictions.h"
45 #include "base/time/time.h"
47 #if defined(OS_ANDROID)
48 #include "base/android/content_uri_utils.h"
49 #include "base/os_compat_android.h"
60 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
61 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
62 ThreadRestrictions::AssertIOAllowed();
63 return stat(path
, sb
);
65 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
66 ThreadRestrictions::AssertIOAllowed();
67 return lstat(path
, sb
);
69 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
70 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
71 ThreadRestrictions::AssertIOAllowed();
72 return stat64(path
, sb
);
74 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
75 ThreadRestrictions::AssertIOAllowed();
76 return lstat64(path
, sb
);
78 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
80 #if !defined(OS_NACL_NONSFI)
81 // Helper for NormalizeFilePath(), defined below.
82 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
83 ThreadRestrictions::AssertIOAllowed(); // For realpath().
84 FilePath::CharType buf
[PATH_MAX
];
85 if (!realpath(path
.value().c_str(), buf
))
88 *real_path
= FilePath(buf
);
92 // Helper for VerifyPathControlledByUser.
93 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
95 const std::set
<gid_t
>& group_gids
) {
96 stat_wrapper_t stat_info
;
97 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
98 DPLOG(ERROR
) << "Failed to get information on path "
103 if (S_ISLNK(stat_info
.st_mode
)) {
104 DLOG(ERROR
) << "Path " << path
.value()
105 << " is a symbolic link.";
109 if (stat_info
.st_uid
!= owner_uid
) {
110 DLOG(ERROR
) << "Path " << path
.value()
111 << " is owned by the wrong user.";
115 if ((stat_info
.st_mode
& S_IWGRP
) &&
116 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
117 DLOG(ERROR
) << "Path " << path
.value()
118 << " is writable by an unprivileged group.";
122 if (stat_info
.st_mode
& S_IWOTH
) {
123 DLOG(ERROR
) << "Path " << path
.value()
124 << " is writable by any user.";
131 std::string
TempFileName() {
132 #if defined(OS_MACOSX)
133 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
136 #if defined(GOOGLE_CHROME_BUILD)
137 return std::string(".com.google.Chrome.XXXXXX");
139 return std::string(".org.chromium.Chromium.XXXXXX");
143 // Creates and opens a temporary file in |directory|, returning the
144 // file descriptor. |path| is set to the temporary file path.
145 // This function does NOT unlink() the file.
146 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
147 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
148 *path
= directory
.Append(base::TempFileName());
149 const std::string
& tmpdir_string
= path
->value();
150 // this should be OK since mkstemp just replaces characters in place
151 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
153 return HANDLE_EINTR(mkstemp(buffer
));
156 #if defined(OS_LINUX)
157 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
158 // This depends on the mount options used for /dev/shm, which vary among
159 // different Linux distributions and possibly local configuration. It also
160 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
161 // but its kernel allows mprotect with PROT_EXEC anyway.
162 bool DetermineDevShmExecutable() {
166 ScopedFD
fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
));
168 DeleteFile(path
, false);
169 long sysconf_result
= sysconf(_SC_PAGESIZE
);
170 CHECK_GE(sysconf_result
, 0);
171 size_t pagesize
= static_cast<size_t>(sysconf_result
);
172 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
173 void* mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
.get(), 0);
174 if (mapping
!= MAP_FAILED
) {
175 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
177 munmap(mapping
, pagesize
);
182 #endif // defined(OS_LINUX)
183 #endif // !defined(OS_NACL_NONSFI)
187 #if !defined(OS_NACL_NONSFI)
188 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
189 ThreadRestrictions::AssertIOAllowed();
190 char full_path
[PATH_MAX
];
191 if (realpath(input
.value().c_str(), full_path
) == NULL
)
193 return FilePath(full_path
);
196 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
197 // which works both with and without the recursive flag. I'm not sure we need
198 // that functionality. If not, remove from file_util_win.cc, otherwise add it
200 bool DeleteFile(const FilePath
& path
, bool recursive
) {
201 ThreadRestrictions::AssertIOAllowed();
202 const char* path_str
= path
.value().c_str();
203 stat_wrapper_t file_info
;
204 int test
= CallLstat(path_str
, &file_info
);
206 // The Windows version defines this condition as success.
207 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
210 if (!S_ISDIR(file_info
.st_mode
))
211 return (unlink(path_str
) == 0);
213 return (rmdir(path_str
) == 0);
216 std::stack
<std::string
> directories
;
217 directories
.push(path
.value());
218 FileEnumerator
traversal(path
, true,
219 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
220 FileEnumerator::SHOW_SYM_LINKS
);
221 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
222 current
= traversal
.Next()) {
223 if (traversal
.GetInfo().IsDirectory())
224 directories
.push(current
.value());
226 success
= (unlink(current
.value().c_str()) == 0);
229 while (success
&& !directories
.empty()) {
230 FilePath dir
= FilePath(directories
.top());
232 success
= (rmdir(dir
.value().c_str()) == 0);
237 bool ReplaceFile(const FilePath
& from_path
,
238 const FilePath
& to_path
,
239 File::Error
* error
) {
240 ThreadRestrictions::AssertIOAllowed();
241 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
244 *error
= File::OSErrorToFileError(errno
);
248 bool CopyDirectory(const FilePath
& from_path
,
249 const FilePath
& to_path
,
251 ThreadRestrictions::AssertIOAllowed();
252 // Some old callers of CopyDirectory want it to support wildcards.
253 // After some discussion, we decided to fix those callers.
254 // Break loudly here if anyone tries to do this.
255 DCHECK(to_path
.value().find('*') == std::string::npos
);
256 DCHECK(from_path
.value().find('*') == std::string::npos
);
258 if (from_path
.value().size() >= PATH_MAX
) {
262 // This function does not properly handle destinations within the source
263 FilePath real_to_path
= to_path
;
264 if (PathExists(real_to_path
)) {
265 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
266 if (real_to_path
.empty())
269 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
270 if (real_to_path
.empty())
273 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
274 if (real_from_path
.empty())
276 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
277 real_to_path
.value().compare(0, real_from_path
.value().size(),
278 real_from_path
.value()) == 0) {
282 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
284 traverse_type
|= FileEnumerator::DIRECTORIES
;
285 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
287 // We have to mimic windows behavior here. |to_path| may not exist yet,
288 // start the loop with |to_path|.
289 struct stat from_stat
;
290 FilePath current
= from_path
;
291 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
292 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
293 << from_path
.value() << " errno = " << errno
;
296 struct stat to_path_stat
;
297 FilePath from_path_base
= from_path
;
298 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
299 S_ISDIR(to_path_stat
.st_mode
)) {
300 // If the destination already exists and is a directory, then the
301 // top level of source needs to be copied.
302 from_path_base
= from_path
.DirName();
305 // The Windows version of this function assumes that non-recursive calls
306 // will always have a directory for from_path.
307 // TODO(maruel): This is not necessary anymore.
308 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
311 while (success
&& !current
.empty()) {
312 // current is the source path, including from_path, so append
313 // the suffix after from_path to to_path to create the target_path.
314 FilePath
target_path(to_path
);
315 if (from_path_base
!= current
) {
316 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
322 if (S_ISDIR(from_stat
.st_mode
)) {
323 if (mkdir(target_path
.value().c_str(),
324 (from_stat
.st_mode
& 01777) | S_IRUSR
| S_IXUSR
| S_IWUSR
) !=
327 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
328 << target_path
.value() << " errno = " << errno
;
331 } else if (S_ISREG(from_stat
.st_mode
)) {
332 if (!CopyFile(current
, target_path
)) {
333 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
334 << target_path
.value();
338 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
342 current
= traversal
.Next();
343 if (!current
.empty())
344 from_stat
= traversal
.GetInfo().stat();
349 #endif // !defined(OS_NACL_NONSFI)
351 bool PathExists(const FilePath
& path
) {
352 ThreadRestrictions::AssertIOAllowed();
353 #if defined(OS_ANDROID)
354 if (path
.IsContentUri()) {
355 return ContentUriExists(path
);
358 return access(path
.value().c_str(), F_OK
) == 0;
361 #if !defined(OS_NACL_NONSFI)
362 bool PathIsWritable(const FilePath
& path
) {
363 ThreadRestrictions::AssertIOAllowed();
364 return access(path
.value().c_str(), W_OK
) == 0;
366 #endif // !defined(OS_NACL_NONSFI)
368 bool DirectoryExists(const FilePath
& path
) {
369 ThreadRestrictions::AssertIOAllowed();
370 stat_wrapper_t file_info
;
371 if (CallStat(path
.value().c_str(), &file_info
) == 0)
372 return S_ISDIR(file_info
.st_mode
);
376 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
377 size_t total_read
= 0;
378 while (total_read
< bytes
) {
380 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
383 total_read
+= bytes_read
;
385 return total_read
== bytes
;
388 #if !defined(OS_NACL_NONSFI)
389 bool CreateSymbolicLink(const FilePath
& target_path
,
390 const FilePath
& symlink_path
) {
391 DCHECK(!symlink_path
.empty());
392 DCHECK(!target_path
.empty());
393 return ::symlink(target_path
.value().c_str(),
394 symlink_path
.value().c_str()) != -1;
397 bool ReadSymbolicLink(const FilePath
& symlink_path
, FilePath
* target_path
) {
398 DCHECK(!symlink_path
.empty());
401 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
404 target_path
->clear();
408 *target_path
= FilePath(FilePath::StringType(buf
, count
));
412 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
413 ThreadRestrictions::AssertIOAllowed();
416 stat_wrapper_t file_info
;
417 // Uses stat(), because on symbolic link, lstat() does not return valid
418 // permission bits in st_mode
419 if (CallStat(path
.value().c_str(), &file_info
) != 0)
422 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
426 bool SetPosixFilePermissions(const FilePath
& path
,
428 ThreadRestrictions::AssertIOAllowed();
429 DCHECK_EQ(mode
& ~FILE_PERMISSION_MASK
, 0);
431 // Calls stat() so that we can preserve the higher bits like S_ISGID.
432 stat_wrapper_t stat_buf
;
433 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
436 // Clears the existing permission bits, and adds the new ones.
437 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
438 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
440 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
446 #if !defined(OS_MACOSX)
447 // This is implemented in file_util_mac.mm for Mac.
448 bool GetTempDir(FilePath
* path
) {
449 const char* tmp
= getenv("TMPDIR");
451 *path
= FilePath(tmp
);
453 #if defined(OS_ANDROID)
454 return PathService::Get(base::DIR_CACHE
, path
);
456 *path
= FilePath("/tmp");
461 #endif // !defined(OS_MACOSX)
463 #if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
464 FilePath
GetHomeDir() {
465 #if defined(OS_CHROMEOS)
466 if (SysInfo::IsRunningOnChromeOS()) {
467 // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
468 // homedir once it becomes available. Return / as the safe option.
469 return FilePath("/");
473 const char* home_dir
= getenv("HOME");
474 if (home_dir
&& home_dir
[0])
475 return FilePath(home_dir
);
477 #if defined(OS_ANDROID)
478 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
486 return FilePath("/tmp");
488 #endif // !defined(OS_MACOSX)
490 bool CreateTemporaryFile(FilePath
* path
) {
491 ThreadRestrictions::AssertIOAllowed(); // For call to close().
493 if (!GetTempDir(&directory
))
495 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
502 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
503 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
507 FILE* file
= fdopen(fd
, "a+");
513 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
514 ThreadRestrictions::AssertIOAllowed(); // For call to close().
515 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
516 return ((fd
>= 0) && !IGNORE_EINTR(close(fd
)));
519 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
520 const FilePath::StringType
& name_tmpl
,
522 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
523 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
524 << "Directory name template must contain \"XXXXXX\".";
526 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
527 std::string sub_dir_string
= sub_dir
.value();
529 // this should be OK since mkdtemp just replaces characters in place
530 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
531 char* dtemp
= mkdtemp(buffer
);
533 DPLOG(ERROR
) << "mkdtemp";
536 *new_dir
= FilePath(dtemp
);
540 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
541 const FilePath::StringType
& prefix
,
543 FilePath::StringType mkdtemp_template
= prefix
;
544 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
545 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
548 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
549 FilePath
* new_temp_path
) {
551 if (!GetTempDir(&tmpdir
))
554 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
557 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
558 File::Error
* error
) {
559 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
560 std::vector
<FilePath
> subpaths
;
562 // Collect a list of all parent directories.
563 FilePath last_path
= full_path
;
564 subpaths
.push_back(full_path
);
565 for (FilePath path
= full_path
.DirName();
566 path
.value() != last_path
.value(); path
= path
.DirName()) {
567 subpaths
.push_back(path
);
571 // Iterate through the parents and create the missing ones.
572 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
573 i
!= subpaths
.rend(); ++i
) {
574 if (DirectoryExists(*i
))
576 if (mkdir(i
->value().c_str(), 0700) == 0)
578 // Mkdir failed, but it might have failed with EEXIST, or some other error
579 // due to the the directory appearing out of thin air. This can occur if
580 // two processes are trying to create the same file system tree at the same
581 // time. Check to see if it exists and make sure it is a directory.
582 int saved_errno
= errno
;
583 if (!DirectoryExists(*i
)) {
585 *error
= File::OSErrorToFileError(saved_errno
);
592 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
593 FilePath real_path_result
;
594 if (!RealPath(path
, &real_path_result
))
597 // To be consistant with windows, fail if |real_path_result| is a
599 stat_wrapper_t file_info
;
600 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
601 S_ISDIR(file_info
.st_mode
))
604 *normalized_path
= real_path_result
;
608 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
609 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
610 bool IsLink(const FilePath
& file_path
) {
612 // If we can't lstat the file, it's safe to assume that the file won't at
613 // least be a 'followable' link.
614 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
617 if (S_ISLNK(st
.st_mode
))
623 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
624 stat_wrapper_t file_info
;
625 #if defined(OS_ANDROID)
626 if (file_path
.IsContentUri()) {
627 File file
= OpenContentUriForRead(file_path
);
630 return file
.GetInfo(results
);
632 #endif // defined(OS_ANDROID)
633 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
635 #if defined(OS_ANDROID)
637 #endif // defined(OS_ANDROID)
639 results
->FromStat(file_info
);
642 #endif // !defined(OS_NACL_NONSFI)
644 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
645 ThreadRestrictions::AssertIOAllowed();
648 result
= fopen(filename
.value().c_str(), mode
);
649 } while (!result
&& errno
== EINTR
);
653 // NaCl doesn't implement system calls to open files directly.
654 #if !defined(OS_NACL)
655 FILE* FileToFILE(File file
, const char* mode
) {
656 FILE* stream
= fdopen(file
.GetPlatformFile(), mode
);
658 file
.TakePlatformFile();
661 #endif // !defined(OS_NACL)
663 int ReadFile(const FilePath
& filename
, char* data
, int max_size
) {
664 ThreadRestrictions::AssertIOAllowed();
665 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
669 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, max_size
));
670 if (IGNORE_EINTR(close(fd
)) < 0)
675 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
676 ThreadRestrictions::AssertIOAllowed();
677 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0640));
681 int bytes_written
= WriteFileDescriptor(fd
, data
, size
) ? size
: -1;
682 if (IGNORE_EINTR(close(fd
)) < 0)
684 return bytes_written
;
687 bool WriteFileDescriptor(const int fd
, const char* data
, int size
) {
688 // Allow for partial writes.
689 ssize_t bytes_written_total
= 0;
690 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
691 bytes_written_total
+= bytes_written_partial
) {
692 bytes_written_partial
=
693 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
694 size
- bytes_written_total
));
695 if (bytes_written_partial
< 0)
702 #if !defined(OS_NACL_NONSFI)
704 bool AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
705 ThreadRestrictions::AssertIOAllowed();
707 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
709 VPLOG(1) << "Unable to create file " << filename
.value();
713 // This call will either write all of the data or return false.
714 if (!WriteFileDescriptor(fd
, data
, size
)) {
715 VPLOG(1) << "Error while writing to file " << filename
.value();
719 if (IGNORE_EINTR(close(fd
)) < 0) {
720 VPLOG(1) << "Error while closing file " << filename
.value();
727 // Gets the current working directory for the process.
728 bool GetCurrentDirectory(FilePath
* dir
) {
729 // getcwd can return ENOENT, which implies it checks against the disk.
730 ThreadRestrictions::AssertIOAllowed();
732 char system_buffer
[PATH_MAX
] = "";
733 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
737 *dir
= FilePath(system_buffer
);
741 // Sets the current working directory for the process.
742 bool SetCurrentDirectory(const FilePath
& path
) {
743 ThreadRestrictions::AssertIOAllowed();
744 int ret
= chdir(path
.value().c_str());
748 bool VerifyPathControlledByUser(const FilePath
& base
,
749 const FilePath
& path
,
751 const std::set
<gid_t
>& group_gids
) {
752 if (base
!= path
&& !base
.IsParent(path
)) {
753 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
754 << base
.value() << "\", path = \"" << path
.value() << "\"";
758 std::vector
<FilePath::StringType
> base_components
;
759 std::vector
<FilePath::StringType
> path_components
;
761 base
.GetComponents(&base_components
);
762 path
.GetComponents(&path_components
);
764 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
765 for (ib
= base_components
.begin(), ip
= path_components
.begin();
766 ib
!= base_components
.end(); ++ib
, ++ip
) {
767 // |base| must be a subpath of |path|, so all components should match.
768 // If these CHECKs fail, look at the test that base is a parent of
769 // path at the top of this function.
770 DCHECK(ip
!= path_components
.end());
774 FilePath current_path
= base
;
775 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
778 for (; ip
!= path_components
.end(); ++ip
) {
779 current_path
= current_path
.Append(*ip
);
780 if (!VerifySpecificPathControlledByUser(
781 current_path
, owner_uid
, group_gids
))
787 #if defined(OS_MACOSX) && !defined(OS_IOS)
788 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
789 const unsigned kRootUid
= 0;
790 const FilePath
kFileSystemRoot("/");
792 // The name of the administrator group on mac os.
793 const char* const kAdminGroupNames
[] = {
798 // Reading the groups database may touch the file system.
799 ThreadRestrictions::AssertIOAllowed();
801 std::set
<gid_t
> allowed_group_ids
;
802 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
803 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
805 DPLOG(ERROR
) << "Could not get the group ID of group \""
806 << kAdminGroupNames
[i
] << "\".";
810 allowed_group_ids
.insert(group_record
->gr_gid
);
813 return VerifyPathControlledByUser(
814 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
816 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
818 int GetMaximumPathComponentLength(const FilePath
& path
) {
819 ThreadRestrictions::AssertIOAllowed();
820 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
823 #if !defined(OS_ANDROID)
824 // This is implemented in file_util_android.cc for that platform.
825 bool GetShmemTempDir(bool executable
, FilePath
* path
) {
826 #if defined(OS_LINUX)
827 bool use_dev_shm
= true;
829 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
830 use_dev_shm
= s_dev_shm_executable
;
833 *path
= FilePath("/dev/shm");
837 return GetTempDir(path
);
839 #endif // !defined(OS_ANDROID)
841 #if !defined(OS_MACOSX)
842 // Mac has its own implementation, this is for all other Posix systems.
843 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
844 ThreadRestrictions::AssertIOAllowed();
846 #if defined(OS_ANDROID)
847 if (from_path
.IsContentUri()) {
848 infile
= OpenContentUriForRead(from_path
);
850 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
853 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
855 if (!infile
.IsValid())
858 File
outfile(to_path
, File::FLAG_WRITE
| File::FLAG_CREATE_ALWAYS
);
859 if (!outfile
.IsValid())
862 const size_t kBufferSize
= 32768;
863 std::vector
<char> buffer(kBufferSize
);
867 ssize_t bytes_read
= infile
.ReadAtCurrentPos(&buffer
[0], buffer
.size());
868 if (bytes_read
< 0) {
874 // Allow for partial writes
875 ssize_t bytes_written_per_read
= 0;
877 ssize_t bytes_written_partial
= outfile
.WriteAtCurrentPos(
878 &buffer
[bytes_written_per_read
], bytes_read
- bytes_written_per_read
);
879 if (bytes_written_partial
< 0) {
883 bytes_written_per_read
+= bytes_written_partial
;
884 } while (bytes_written_per_read
< bytes_read
);
889 #endif // !defined(OS_MACOSX)
891 // -----------------------------------------------------------------------------
895 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
896 ThreadRestrictions::AssertIOAllowed();
897 // Windows compatibility: if to_path exists, from_path and to_path
898 // must be the same type, either both files, or both directories.
899 stat_wrapper_t to_file_info
;
900 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
901 stat_wrapper_t from_file_info
;
902 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
903 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
910 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
913 if (!CopyDirectory(from_path
, to_path
, true))
916 DeleteFile(from_path
, true);
920 } // namespace internal
922 #endif // !defined(OS_NACL_NONSFI)