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"
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"
27 #elif !defined(OS_ANDROID)
33 #include "base/basictypes.h"
34 #include "base/files/file_enumerator.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/strings/string_util.h"
43 #include "base/strings/stringprintf.h"
44 #include "base/strings/sys_string_conversions.h"
45 #include "base/strings/utf_string_conversions.h"
46 #include "base/threading/thread_restrictions.h"
47 #include "base/time/time.h"
49 #if defined(OS_ANDROID)
50 #include "base/os_compat_android.h"
57 #if defined(OS_CHROMEOS)
58 #include "base/chromeos/chromeos_version.h"
65 #if defined(OS_BSD) || defined(OS_MACOSX)
66 typedef struct stat stat_wrapper_t
;
67 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
68 ThreadRestrictions::AssertIOAllowed();
69 return stat(path
, sb
);
71 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
72 ThreadRestrictions::AssertIOAllowed();
73 return lstat(path
, sb
);
76 typedef struct stat64 stat_wrapper_t
;
77 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
78 ThreadRestrictions::AssertIOAllowed();
79 return stat64(path
, sb
);
81 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
82 ThreadRestrictions::AssertIOAllowed();
83 return lstat64(path
, sb
);
87 // Helper for NormalizeFilePath(), defined below.
88 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
89 ThreadRestrictions::AssertIOAllowed(); // For realpath().
90 FilePath::CharType buf
[PATH_MAX
];
91 if (!realpath(path
.value().c_str(), buf
))
94 *real_path
= FilePath(buf
);
98 // Helper for VerifyPathControlledByUser.
99 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
101 const std::set
<gid_t
>& group_gids
) {
102 stat_wrapper_t stat_info
;
103 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
104 DPLOG(ERROR
) << "Failed to get information on path "
109 if (S_ISLNK(stat_info
.st_mode
)) {
110 DLOG(ERROR
) << "Path " << path
.value()
111 << " is a symbolic link.";
115 if (stat_info
.st_uid
!= owner_uid
) {
116 DLOG(ERROR
) << "Path " << path
.value()
117 << " is owned by the wrong user.";
121 if ((stat_info
.st_mode
& S_IWGRP
) &&
122 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
123 DLOG(ERROR
) << "Path " << path
.value()
124 << " is writable by an unprivileged group.";
128 if (stat_info
.st_mode
& S_IWOTH
) {
129 DLOG(ERROR
) << "Path " << path
.value()
130 << " is writable by any user.";
137 std::string
TempFileName() {
138 #if defined(OS_MACOSX)
139 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
142 #if defined(GOOGLE_CHROME_BUILD)
143 return std::string(".com.google.Chrome.XXXXXX");
145 return std::string(".org.chromium.Chromium.XXXXXX");
151 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
152 ThreadRestrictions::AssertIOAllowed();
153 char full_path
[PATH_MAX
];
154 if (realpath(input
.value().c_str(), full_path
) == NULL
)
156 return FilePath(full_path
);
159 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
160 // which works both with and without the recursive flag. I'm not sure we need
161 // that functionality. If not, remove from file_util_win.cc, otherwise add it
163 bool DeleteFile(const FilePath
& path
, bool recursive
) {
164 ThreadRestrictions::AssertIOAllowed();
165 const char* path_str
= path
.value().c_str();
166 stat_wrapper_t file_info
;
167 int test
= CallLstat(path_str
, &file_info
);
169 // The Windows version defines this condition as success.
170 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
173 if (!S_ISDIR(file_info
.st_mode
))
174 return (unlink(path_str
) == 0);
176 return (rmdir(path_str
) == 0);
179 std::stack
<std::string
> directories
;
180 directories
.push(path
.value());
181 FileEnumerator
traversal(path
, true,
182 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
183 FileEnumerator::SHOW_SYM_LINKS
);
184 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
185 current
= traversal
.Next()) {
186 if (traversal
.GetInfo().IsDirectory())
187 directories
.push(current
.value());
189 success
= (unlink(current
.value().c_str()) == 0);
192 while (success
&& !directories
.empty()) {
193 FilePath dir
= FilePath(directories
.top());
195 success
= (rmdir(dir
.value().c_str()) == 0);
200 bool ReplaceFile(const FilePath
& from_path
,
201 const FilePath
& to_path
,
202 PlatformFileError
* error
) {
203 ThreadRestrictions::AssertIOAllowed();
204 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
207 *error
= ErrnoToPlatformFileError(errno
);
211 bool CopyDirectory(const FilePath
& from_path
,
212 const FilePath
& to_path
,
214 ThreadRestrictions::AssertIOAllowed();
215 // Some old callers of CopyDirectory want it to support wildcards.
216 // After some discussion, we decided to fix those callers.
217 // Break loudly here if anyone tries to do this.
218 // TODO(evanm): remove this once we're sure it's ok.
219 DCHECK(to_path
.value().find('*') == std::string::npos
);
220 DCHECK(from_path
.value().find('*') == std::string::npos
);
222 char top_dir
[PATH_MAX
];
223 if (strlcpy(top_dir
, from_path
.value().c_str(),
224 arraysize(top_dir
)) >= arraysize(top_dir
)) {
228 // This function does not properly handle destinations within the source
229 FilePath real_to_path
= to_path
;
230 if (PathExists(real_to_path
)) {
231 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
232 if (real_to_path
.empty())
235 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
236 if (real_to_path
.empty())
239 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
240 if (real_from_path
.empty())
242 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
243 real_to_path
.value().compare(0, real_from_path
.value().size(),
244 real_from_path
.value()) == 0)
248 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
250 traverse_type
|= FileEnumerator::DIRECTORIES
;
251 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
253 // We have to mimic windows behavior here. |to_path| may not exist yet,
254 // start the loop with |to_path|.
255 struct stat from_stat
;
256 FilePath current
= from_path
;
257 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
258 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
259 << from_path
.value() << " errno = " << errno
;
262 struct stat to_path_stat
;
263 FilePath from_path_base
= from_path
;
264 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
265 S_ISDIR(to_path_stat
.st_mode
)) {
266 // If the destination already exists and is a directory, then the
267 // top level of source needs to be copied.
268 from_path_base
= from_path
.DirName();
271 // The Windows version of this function assumes that non-recursive calls
272 // will always have a directory for from_path.
273 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
275 while (success
&& !current
.empty()) {
276 // current is the source path, including from_path, so append
277 // the suffix after from_path to to_path to create the target_path.
278 FilePath
target_path(to_path
);
279 if (from_path_base
!= current
) {
280 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
286 if (S_ISDIR(from_stat
.st_mode
)) {
287 if (mkdir(target_path
.value().c_str(), from_stat
.st_mode
& 01777) != 0 &&
289 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
290 << target_path
.value() << " errno = " << errno
;
293 } else if (S_ISREG(from_stat
.st_mode
)) {
294 if (!CopyFile(current
, target_path
)) {
295 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
296 << target_path
.value();
300 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
304 current
= traversal
.Next();
305 if (!current
.empty())
306 from_stat
= traversal
.GetInfo().stat();
312 bool PathExists(const FilePath
& path
) {
313 ThreadRestrictions::AssertIOAllowed();
314 return access(path
.value().c_str(), F_OK
) == 0;
317 bool PathIsWritable(const FilePath
& path
) {
318 ThreadRestrictions::AssertIOAllowed();
319 return access(path
.value().c_str(), W_OK
) == 0;
322 bool DirectoryExists(const FilePath
& path
) {
323 ThreadRestrictions::AssertIOAllowed();
324 stat_wrapper_t file_info
;
325 if (CallStat(path
.value().c_str(), &file_info
) == 0)
326 return S_ISDIR(file_info
.st_mode
);
332 // -----------------------------------------------------------------------------
334 namespace file_util
{
336 using base::stat_wrapper_t
;
337 using base::CallStat
;
338 using base::CallLstat
;
339 using base::DirectoryExists
;
340 using base::FileEnumerator
;
341 using base::FilePath
;
342 using base::MakeAbsoluteFilePath
;
343 using base::RealPath
;
344 using base::VerifySpecificPathControlledByUser
;
346 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
347 size_t total_read
= 0;
348 while (total_read
< bytes
) {
350 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
353 total_read
+= bytes_read
;
355 return total_read
== bytes
;
358 bool CreateSymbolicLink(const FilePath
& target_path
,
359 const FilePath
& symlink_path
) {
360 DCHECK(!symlink_path
.empty());
361 DCHECK(!target_path
.empty());
362 return ::symlink(target_path
.value().c_str(),
363 symlink_path
.value().c_str()) != -1;
366 bool ReadSymbolicLink(const FilePath
& symlink_path
,
367 FilePath
* target_path
) {
368 DCHECK(!symlink_path
.empty());
371 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
374 target_path
->clear();
378 *target_path
= FilePath(FilePath::StringType(buf
, count
));
382 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
383 base::ThreadRestrictions::AssertIOAllowed();
386 stat_wrapper_t file_info
;
387 // Uses stat(), because on symbolic link, lstat() does not return valid
388 // permission bits in st_mode
389 if (CallStat(path
.value().c_str(), &file_info
) != 0)
392 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
396 bool SetPosixFilePermissions(const FilePath
& path
,
398 base::ThreadRestrictions::AssertIOAllowed();
399 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
401 // Calls stat() so that we can preserve the higher bits like S_ISGID.
402 stat_wrapper_t stat_buf
;
403 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
406 // Clears the existing permission bits, and adds the new ones.
407 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
408 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
410 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
416 // Creates and opens a temporary file in |directory|, returning the
417 // file descriptor. |path| is set to the temporary file path.
418 // This function does NOT unlink() the file.
419 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
420 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
421 *path
= directory
.Append(base::TempFileName());
422 const std::string
& tmpdir_string
= path
->value();
423 // this should be OK since mkstemp just replaces characters in place
424 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
426 return HANDLE_EINTR(mkstemp(buffer
));
429 bool CreateTemporaryFile(FilePath
* path
) {
430 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
432 if (!GetTempDir(&directory
))
434 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
437 ignore_result(HANDLE_EINTR(close(fd
)));
441 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
443 if (!GetShmemTempDir(&directory
, executable
))
446 return CreateAndOpenTemporaryFileInDir(directory
, path
);
449 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
450 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
454 FILE* file
= fdopen(fd
, "a+");
456 ignore_result(HANDLE_EINTR(close(fd
)));
460 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
461 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
462 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
463 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
466 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
467 const FilePath::StringType
& name_tmpl
,
469 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
470 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
471 << "Directory name template must contain \"XXXXXX\".";
473 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
474 std::string sub_dir_string
= sub_dir
.value();
476 // this should be OK since mkdtemp just replaces characters in place
477 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
478 char* dtemp
= mkdtemp(buffer
);
480 DPLOG(ERROR
) << "mkdtemp";
483 *new_dir
= FilePath(dtemp
);
487 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
488 const FilePath::StringType
& prefix
,
490 FilePath::StringType mkdtemp_template
= prefix
;
491 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
492 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
495 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
496 FilePath
* new_temp_path
) {
498 if (!GetTempDir(&tmpdir
))
501 return CreateTemporaryDirInDirImpl(tmpdir
, base::TempFileName(),
505 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
506 base::PlatformFileError
* error
) {
507 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
508 std::vector
<FilePath
> subpaths
;
510 // Collect a list of all parent directories.
511 FilePath last_path
= full_path
;
512 subpaths
.push_back(full_path
);
513 for (FilePath path
= full_path
.DirName();
514 path
.value() != last_path
.value(); path
= path
.DirName()) {
515 subpaths
.push_back(path
);
519 // Iterate through the parents and create the missing ones.
520 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
521 i
!= subpaths
.rend(); ++i
) {
522 if (DirectoryExists(*i
))
524 if (mkdir(i
->value().c_str(), 0700) == 0)
526 // Mkdir failed, but it might have failed with EEXIST, or some other error
527 // due to the the directory appearing out of thin air. This can occur if
528 // two processes are trying to create the same file system tree at the same
529 // time. Check to see if it exists and make sure it is a directory.
530 int saved_errno
= errno
;
531 if (!DirectoryExists(*i
)) {
533 *error
= base::ErrnoToPlatformFileError(saved_errno
);
540 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
541 const int kMaxAttempts
= 20;
542 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
544 GetUniquePathNumber(path
, base::FilePath::StringType());
547 base::FilePath test_path
= (uniquifier
== 0) ? path
:
548 path
.InsertBeforeExtensionASCII(
549 base::StringPrintf(" (%d)", uniquifier
));
550 if (mkdir(test_path
.value().c_str(), 0777) == 0)
552 else if (errno
!= EEXIST
)
555 return base::FilePath();
558 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
559 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
560 bool IsLink(const FilePath
& file_path
) {
562 // If we can't lstat the file, it's safe to assume that the file won't at
563 // least be a 'followable' link.
564 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
567 if (S_ISLNK(st
.st_mode
))
573 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
574 stat_wrapper_t file_info
;
575 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
577 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
578 results
->size
= file_info
.st_size
;
579 #if defined(OS_MACOSX)
580 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtimespec
);
581 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atimespec
);
582 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctimespec
);
583 #elif defined(OS_ANDROID)
584 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
585 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
586 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
588 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtim
);
589 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atim
);
590 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctim
);
595 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
596 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
598 int result
= stat(path
.value().c_str(), &buffer
);
602 *inode
= buffer
.st_ino
;
606 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
607 return OpenFile(FilePath(filename
), mode
);
610 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
611 base::ThreadRestrictions::AssertIOAllowed();
614 result
= fopen(filename
.value().c_str(), mode
);
615 } while (!result
&& errno
== EINTR
);
619 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
620 base::ThreadRestrictions::AssertIOAllowed();
621 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
625 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
626 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
631 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
632 base::ThreadRestrictions::AssertIOAllowed();
633 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
637 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
638 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
640 return bytes_written
;
643 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
644 // Allow for partial writes.
645 ssize_t bytes_written_total
= 0;
646 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
647 bytes_written_total
+= bytes_written_partial
) {
648 bytes_written_partial
=
649 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
650 size
- bytes_written_total
));
651 if (bytes_written_partial
< 0)
655 return bytes_written_total
;
658 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
659 base::ThreadRestrictions::AssertIOAllowed();
660 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
664 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
665 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
667 return bytes_written
;
670 // Gets the current working directory for the process.
671 bool GetCurrentDirectory(FilePath
* dir
) {
672 // getcwd can return ENOENT, which implies it checks against the disk.
673 base::ThreadRestrictions::AssertIOAllowed();
675 char system_buffer
[PATH_MAX
] = "";
676 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
680 *dir
= FilePath(system_buffer
);
684 // Sets the current working directory for the process.
685 bool SetCurrentDirectory(const FilePath
& path
) {
686 base::ThreadRestrictions::AssertIOAllowed();
687 int ret
= chdir(path
.value().c_str());
691 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
692 FilePath real_path_result
;
693 if (!RealPath(path
, &real_path_result
))
696 // To be consistant with windows, fail if |real_path_result| is a
698 stat_wrapper_t file_info
;
699 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
700 S_ISDIR(file_info
.st_mode
))
703 *normalized_path
= real_path_result
;
707 #if !defined(OS_MACOSX)
708 bool GetTempDir(FilePath
* path
) {
709 const char* tmp
= getenv("TMPDIR");
711 *path
= FilePath(tmp
);
713 #if defined(OS_ANDROID)
714 return PathService::Get(base::DIR_CACHE
, path
);
716 *path
= FilePath("/tmp");
721 #if !defined(OS_ANDROID)
723 #if defined(OS_LINUX)
724 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
725 // This depends on the mount options used for /dev/shm, which vary among
726 // different Linux distributions and possibly local configuration. It also
727 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
728 // but its kernel allows mprotect with PROT_EXEC anyway.
732 bool DetermineDevShmExecutable() {
735 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
737 ScopedFD
shm_fd_closer(&fd
);
738 DeleteFile(path
, false);
739 long sysconf_result
= sysconf(_SC_PAGESIZE
);
740 CHECK_GE(sysconf_result
, 0);
741 size_t pagesize
= static_cast<size_t>(sysconf_result
);
742 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
743 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
744 if (mapping
!= MAP_FAILED
) {
745 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
747 munmap(mapping
, pagesize
);
754 #endif // defined(OS_LINUX)
756 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
757 #if defined(OS_LINUX)
758 bool use_dev_shm
= true;
760 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
761 use_dev_shm
= s_dev_shm_executable
;
764 *path
= FilePath("/dev/shm");
768 return GetTempDir(path
);
770 #endif // !defined(OS_ANDROID)
772 FilePath
GetHomeDir() {
773 #if defined(OS_CHROMEOS)
774 if (base::chromeos::IsRunningOnChromeOS())
775 return FilePath("/home/chronos/user");
778 const char* home_dir
= getenv("HOME");
779 if (home_dir
&& home_dir
[0])
780 return FilePath(home_dir
);
782 #if defined(OS_ANDROID)
783 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
785 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
786 base::ThreadRestrictions::AssertIOAllowed();
788 home_dir
= g_get_home_dir();
789 if (home_dir
&& home_dir
[0])
790 return FilePath(home_dir
);
794 if (file_util::GetTempDir(&rv
))
798 return FilePath("/tmp");
800 #endif // !defined(OS_MACOSX)
802 bool VerifyPathControlledByUser(const FilePath
& base
,
803 const FilePath
& path
,
805 const std::set
<gid_t
>& group_gids
) {
806 if (base
!= path
&& !base
.IsParent(path
)) {
807 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
808 << base
.value() << "\", path = \"" << path
.value() << "\"";
812 std::vector
<FilePath::StringType
> base_components
;
813 std::vector
<FilePath::StringType
> path_components
;
815 base
.GetComponents(&base_components
);
816 path
.GetComponents(&path_components
);
818 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
819 for (ib
= base_components
.begin(), ip
= path_components
.begin();
820 ib
!= base_components
.end(); ++ib
, ++ip
) {
821 // |base| must be a subpath of |path|, so all components should match.
822 // If these CHECKs fail, look at the test that base is a parent of
823 // path at the top of this function.
824 DCHECK(ip
!= path_components
.end());
828 FilePath current_path
= base
;
829 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
832 for (; ip
!= path_components
.end(); ++ip
) {
833 current_path
= current_path
.Append(*ip
);
834 if (!VerifySpecificPathControlledByUser(
835 current_path
, owner_uid
, group_gids
))
841 #if defined(OS_MACOSX) && !defined(OS_IOS)
842 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
843 const unsigned kRootUid
= 0;
844 const FilePath
kFileSystemRoot("/");
846 // The name of the administrator group on mac os.
847 const char* const kAdminGroupNames
[] = {
852 // Reading the groups database may touch the file system.
853 base::ThreadRestrictions::AssertIOAllowed();
855 std::set
<gid_t
> allowed_group_ids
;
856 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
857 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
859 DPLOG(ERROR
) << "Could not get the group ID of group \""
860 << kAdminGroupNames
[i
] << "\".";
864 allowed_group_ids
.insert(group_record
->gr_gid
);
867 return VerifyPathControlledByUser(
868 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
870 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
872 int GetMaximumPathComponentLength(const FilePath
& path
) {
873 base::ThreadRestrictions::AssertIOAllowed();
874 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
877 } // namespace file_util
882 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
883 ThreadRestrictions::AssertIOAllowed();
884 // Windows compatibility: if to_path exists, from_path and to_path
885 // must be the same type, either both files, or both directories.
886 stat_wrapper_t to_file_info
;
887 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
888 stat_wrapper_t from_file_info
;
889 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
890 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
897 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
900 if (!CopyDirectory(from_path
, to_path
, true))
903 DeleteFile(from_path
, true);
907 #if !defined(OS_MACOSX)
908 // Mac has its own implementation, this is for all other Posix systems.
909 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
910 ThreadRestrictions::AssertIOAllowed();
911 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
915 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
917 ignore_result(HANDLE_EINTR(close(infile
)));
921 const size_t kBufferSize
= 32768;
922 std::vector
<char> buffer(kBufferSize
);
926 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
927 if (bytes_read
< 0) {
933 // Allow for partial writes
934 ssize_t bytes_written_per_read
= 0;
936 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
938 &buffer
[bytes_written_per_read
],
939 bytes_read
- bytes_written_per_read
));
940 if (bytes_written_partial
< 0) {
944 bytes_written_per_read
+= bytes_written_partial
;
945 } while (bytes_written_per_read
< bytes_read
);
948 if (HANDLE_EINTR(close(infile
)) < 0)
950 if (HANDLE_EINTR(close(outfile
)) < 0)
955 #endif // !defined(OS_MACOSX)
957 } // namespace internal