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) && !defined(OS_CHROMEOS)
28 #include <glib.h> // for g_get_home_dir()
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/sys_info.h"
47 #include "base/threading/thread_restrictions.h"
48 #include "base/time/time.h"
50 #if defined(OS_ANDROID)
51 #include "base/os_compat_android.h"
62 #if defined(OS_BSD) || defined(OS_MACOSX)
63 typedef struct stat stat_wrapper_t
;
64 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
65 ThreadRestrictions::AssertIOAllowed();
66 return stat(path
, sb
);
68 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
69 ThreadRestrictions::AssertIOAllowed();
70 return lstat(path
, sb
);
73 typedef struct stat64 stat_wrapper_t
;
74 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
75 ThreadRestrictions::AssertIOAllowed();
76 return stat64(path
, sb
);
78 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
79 ThreadRestrictions::AssertIOAllowed();
80 return lstat64(path
, sb
);
84 // Helper for NormalizeFilePath(), defined below.
85 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
86 ThreadRestrictions::AssertIOAllowed(); // For realpath().
87 FilePath::CharType buf
[PATH_MAX
];
88 if (!realpath(path
.value().c_str(), buf
))
91 *real_path
= FilePath(buf
);
95 // Helper for VerifyPathControlledByUser.
96 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
98 const std::set
<gid_t
>& group_gids
) {
99 stat_wrapper_t stat_info
;
100 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
101 DPLOG(ERROR
) << "Failed to get information on path "
106 if (S_ISLNK(stat_info
.st_mode
)) {
107 DLOG(ERROR
) << "Path " << path
.value()
108 << " is a symbolic link.";
112 if (stat_info
.st_uid
!= owner_uid
) {
113 DLOG(ERROR
) << "Path " << path
.value()
114 << " is owned by the wrong user.";
118 if ((stat_info
.st_mode
& S_IWGRP
) &&
119 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
120 DLOG(ERROR
) << "Path " << path
.value()
121 << " is writable by an unprivileged group.";
125 if (stat_info
.st_mode
& S_IWOTH
) {
126 DLOG(ERROR
) << "Path " << path
.value()
127 << " is writable by any user.";
134 std::string
TempFileName() {
135 #if defined(OS_MACOSX)
136 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
139 #if defined(GOOGLE_CHROME_BUILD)
140 return std::string(".com.google.Chrome.XXXXXX");
142 return std::string(".org.chromium.Chromium.XXXXXX");
148 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
149 ThreadRestrictions::AssertIOAllowed();
150 char full_path
[PATH_MAX
];
151 if (realpath(input
.value().c_str(), full_path
) == NULL
)
153 return FilePath(full_path
);
156 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
157 // which works both with and without the recursive flag. I'm not sure we need
158 // that functionality. If not, remove from file_util_win.cc, otherwise add it
160 bool DeleteFile(const FilePath
& path
, bool recursive
) {
161 ThreadRestrictions::AssertIOAllowed();
162 const char* path_str
= path
.value().c_str();
163 stat_wrapper_t file_info
;
164 int test
= CallLstat(path_str
, &file_info
);
166 // The Windows version defines this condition as success.
167 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
170 if (!S_ISDIR(file_info
.st_mode
))
171 return (unlink(path_str
) == 0);
173 return (rmdir(path_str
) == 0);
176 std::stack
<std::string
> directories
;
177 directories
.push(path
.value());
178 FileEnumerator
traversal(path
, true,
179 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
180 FileEnumerator::SHOW_SYM_LINKS
);
181 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
182 current
= traversal
.Next()) {
183 if (traversal
.GetInfo().IsDirectory())
184 directories
.push(current
.value());
186 success
= (unlink(current
.value().c_str()) == 0);
189 while (success
&& !directories
.empty()) {
190 FilePath dir
= FilePath(directories
.top());
192 success
= (rmdir(dir
.value().c_str()) == 0);
197 bool ReplaceFile(const FilePath
& from_path
,
198 const FilePath
& to_path
,
199 PlatformFileError
* error
) {
200 ThreadRestrictions::AssertIOAllowed();
201 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
204 *error
= ErrnoToPlatformFileError(errno
);
208 bool CopyDirectory(const FilePath
& from_path
,
209 const FilePath
& to_path
,
211 ThreadRestrictions::AssertIOAllowed();
212 // Some old callers of CopyDirectory want it to support wildcards.
213 // After some discussion, we decided to fix those callers.
214 // Break loudly here if anyone tries to do this.
215 // TODO(evanm): remove this once we're sure it's ok.
216 DCHECK(to_path
.value().find('*') == std::string::npos
);
217 DCHECK(from_path
.value().find('*') == std::string::npos
);
219 char top_dir
[PATH_MAX
];
220 if (strlcpy(top_dir
, from_path
.value().c_str(),
221 arraysize(top_dir
)) >= arraysize(top_dir
)) {
225 // This function does not properly handle destinations within the source
226 FilePath real_to_path
= to_path
;
227 if (PathExists(real_to_path
)) {
228 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
229 if (real_to_path
.empty())
232 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
233 if (real_to_path
.empty())
236 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
237 if (real_from_path
.empty())
239 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
240 real_to_path
.value().compare(0, real_from_path
.value().size(),
241 real_from_path
.value()) == 0)
245 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
247 traverse_type
|= FileEnumerator::DIRECTORIES
;
248 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
250 // We have to mimic windows behavior here. |to_path| may not exist yet,
251 // start the loop with |to_path|.
252 struct stat from_stat
;
253 FilePath current
= from_path
;
254 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
255 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
256 << from_path
.value() << " errno = " << errno
;
259 struct stat to_path_stat
;
260 FilePath from_path_base
= from_path
;
261 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
262 S_ISDIR(to_path_stat
.st_mode
)) {
263 // If the destination already exists and is a directory, then the
264 // top level of source needs to be copied.
265 from_path_base
= from_path
.DirName();
268 // The Windows version of this function assumes that non-recursive calls
269 // will always have a directory for from_path.
270 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
272 while (success
&& !current
.empty()) {
273 // current is the source path, including from_path, so append
274 // the suffix after from_path to to_path to create the target_path.
275 FilePath
target_path(to_path
);
276 if (from_path_base
!= current
) {
277 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
283 if (S_ISDIR(from_stat
.st_mode
)) {
284 if (mkdir(target_path
.value().c_str(), from_stat
.st_mode
& 01777) != 0 &&
286 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
287 << target_path
.value() << " errno = " << errno
;
290 } else if (S_ISREG(from_stat
.st_mode
)) {
291 if (!CopyFile(current
, target_path
)) {
292 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
293 << target_path
.value();
297 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
301 current
= traversal
.Next();
302 if (!current
.empty())
303 from_stat
= traversal
.GetInfo().stat();
309 bool PathExists(const FilePath
& path
) {
310 ThreadRestrictions::AssertIOAllowed();
311 return access(path
.value().c_str(), F_OK
) == 0;
314 bool PathIsWritable(const FilePath
& path
) {
315 ThreadRestrictions::AssertIOAllowed();
316 return access(path
.value().c_str(), W_OK
) == 0;
319 bool DirectoryExists(const FilePath
& path
) {
320 ThreadRestrictions::AssertIOAllowed();
321 stat_wrapper_t file_info
;
322 if (CallStat(path
.value().c_str(), &file_info
) == 0)
323 return S_ISDIR(file_info
.st_mode
);
329 // -----------------------------------------------------------------------------
331 namespace file_util
{
333 using base::stat_wrapper_t
;
334 using base::CallStat
;
335 using base::CallLstat
;
336 using base::DirectoryExists
;
337 using base::FileEnumerator
;
338 using base::FilePath
;
339 using base::MakeAbsoluteFilePath
;
340 using base::RealPath
;
341 using base::VerifySpecificPathControlledByUser
;
343 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
344 size_t total_read
= 0;
345 while (total_read
< bytes
) {
347 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
350 total_read
+= bytes_read
;
352 return total_read
== bytes
;
355 bool CreateSymbolicLink(const FilePath
& target_path
,
356 const FilePath
& symlink_path
) {
357 DCHECK(!symlink_path
.empty());
358 DCHECK(!target_path
.empty());
359 return ::symlink(target_path
.value().c_str(),
360 symlink_path
.value().c_str()) != -1;
363 bool ReadSymbolicLink(const FilePath
& symlink_path
,
364 FilePath
* target_path
) {
365 DCHECK(!symlink_path
.empty());
368 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
371 target_path
->clear();
375 *target_path
= FilePath(FilePath::StringType(buf
, count
));
379 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
380 base::ThreadRestrictions::AssertIOAllowed();
383 stat_wrapper_t file_info
;
384 // Uses stat(), because on symbolic link, lstat() does not return valid
385 // permission bits in st_mode
386 if (CallStat(path
.value().c_str(), &file_info
) != 0)
389 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
393 bool SetPosixFilePermissions(const FilePath
& path
,
395 base::ThreadRestrictions::AssertIOAllowed();
396 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
398 // Calls stat() so that we can preserve the higher bits like S_ISGID.
399 stat_wrapper_t stat_buf
;
400 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
403 // Clears the existing permission bits, and adds the new ones.
404 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
405 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
407 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
413 // Creates and opens a temporary file in |directory|, returning the
414 // file descriptor. |path| is set to the temporary file path.
415 // This function does NOT unlink() the file.
416 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
417 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
418 *path
= directory
.Append(base::TempFileName());
419 const std::string
& tmpdir_string
= path
->value();
420 // this should be OK since mkstemp just replaces characters in place
421 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
423 return HANDLE_EINTR(mkstemp(buffer
));
426 bool CreateTemporaryFile(FilePath
* path
) {
427 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
429 if (!GetTempDir(&directory
))
431 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
434 ignore_result(HANDLE_EINTR(close(fd
)));
438 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
440 if (!GetShmemTempDir(&directory
, executable
))
443 return CreateAndOpenTemporaryFileInDir(directory
, path
);
446 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
447 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
451 FILE* file
= fdopen(fd
, "a+");
453 ignore_result(HANDLE_EINTR(close(fd
)));
457 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
458 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
459 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
460 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
463 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
464 const FilePath::StringType
& name_tmpl
,
466 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
467 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
468 << "Directory name template must contain \"XXXXXX\".";
470 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
471 std::string sub_dir_string
= sub_dir
.value();
473 // this should be OK since mkdtemp just replaces characters in place
474 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
475 char* dtemp
= mkdtemp(buffer
);
477 DPLOG(ERROR
) << "mkdtemp";
480 *new_dir
= FilePath(dtemp
);
484 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
485 const FilePath::StringType
& prefix
,
487 FilePath::StringType mkdtemp_template
= prefix
;
488 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
489 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
492 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
493 FilePath
* new_temp_path
) {
495 if (!GetTempDir(&tmpdir
))
498 return CreateTemporaryDirInDirImpl(tmpdir
, base::TempFileName(),
502 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
503 base::PlatformFileError
* error
) {
504 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
505 std::vector
<FilePath
> subpaths
;
507 // Collect a list of all parent directories.
508 FilePath last_path
= full_path
;
509 subpaths
.push_back(full_path
);
510 for (FilePath path
= full_path
.DirName();
511 path
.value() != last_path
.value(); path
= path
.DirName()) {
512 subpaths
.push_back(path
);
516 // Iterate through the parents and create the missing ones.
517 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
518 i
!= subpaths
.rend(); ++i
) {
519 if (DirectoryExists(*i
))
521 if (mkdir(i
->value().c_str(), 0700) == 0)
523 // Mkdir failed, but it might have failed with EEXIST, or some other error
524 // due to the the directory appearing out of thin air. This can occur if
525 // two processes are trying to create the same file system tree at the same
526 // time. Check to see if it exists and make sure it is a directory.
527 int saved_errno
= errno
;
528 if (!DirectoryExists(*i
)) {
530 *error
= base::ErrnoToPlatformFileError(saved_errno
);
537 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
538 const int kMaxAttempts
= 20;
539 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
541 GetUniquePathNumber(path
, base::FilePath::StringType());
544 base::FilePath test_path
= (uniquifier
== 0) ? path
:
545 path
.InsertBeforeExtensionASCII(
546 base::StringPrintf(" (%d)", uniquifier
));
547 if (mkdir(test_path
.value().c_str(), 0777) == 0)
549 else if (errno
!= EEXIST
)
552 return base::FilePath();
555 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
556 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
557 bool IsLink(const FilePath
& file_path
) {
559 // If we can't lstat the file, it's safe to assume that the file won't at
560 // least be a 'followable' link.
561 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
564 if (S_ISLNK(st
.st_mode
))
570 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
571 stat_wrapper_t file_info
;
572 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
574 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
575 results
->size
= file_info
.st_size
;
576 #if defined(OS_MACOSX)
577 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtimespec
);
578 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atimespec
);
579 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctimespec
);
580 #elif defined(OS_ANDROID)
581 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
582 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
583 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
585 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtim
);
586 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atim
);
587 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctim
);
592 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
593 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
595 int result
= stat(path
.value().c_str(), &buffer
);
599 *inode
= buffer
.st_ino
;
603 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
604 return OpenFile(FilePath(filename
), mode
);
607 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
608 base::ThreadRestrictions::AssertIOAllowed();
611 result
= fopen(filename
.value().c_str(), mode
);
612 } while (!result
&& errno
== EINTR
);
616 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
617 base::ThreadRestrictions::AssertIOAllowed();
618 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
622 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
623 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
628 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
629 base::ThreadRestrictions::AssertIOAllowed();
630 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
634 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
635 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
637 return bytes_written
;
640 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
641 // Allow for partial writes.
642 ssize_t bytes_written_total
= 0;
643 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
644 bytes_written_total
+= bytes_written_partial
) {
645 bytes_written_partial
=
646 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
647 size
- bytes_written_total
));
648 if (bytes_written_partial
< 0)
652 return bytes_written_total
;
655 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
656 base::ThreadRestrictions::AssertIOAllowed();
657 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
661 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
662 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
664 return bytes_written
;
667 // Gets the current working directory for the process.
668 bool GetCurrentDirectory(FilePath
* dir
) {
669 // getcwd can return ENOENT, which implies it checks against the disk.
670 base::ThreadRestrictions::AssertIOAllowed();
672 char system_buffer
[PATH_MAX
] = "";
673 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
677 *dir
= FilePath(system_buffer
);
681 // Sets the current working directory for the process.
682 bool SetCurrentDirectory(const FilePath
& path
) {
683 base::ThreadRestrictions::AssertIOAllowed();
684 int ret
= chdir(path
.value().c_str());
688 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
689 FilePath real_path_result
;
690 if (!RealPath(path
, &real_path_result
))
693 // To be consistant with windows, fail if |real_path_result| is a
695 stat_wrapper_t file_info
;
696 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
697 S_ISDIR(file_info
.st_mode
))
700 *normalized_path
= real_path_result
;
704 #if !defined(OS_MACOSX)
705 bool GetTempDir(FilePath
* path
) {
706 const char* tmp
= getenv("TMPDIR");
708 *path
= FilePath(tmp
);
710 #if defined(OS_ANDROID)
711 return PathService::Get(base::DIR_CACHE
, path
);
713 *path
= FilePath("/tmp");
718 #if !defined(OS_ANDROID)
720 #if defined(OS_LINUX)
721 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
722 // This depends on the mount options used for /dev/shm, which vary among
723 // different Linux distributions and possibly local configuration. It also
724 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
725 // but its kernel allows mprotect with PROT_EXEC anyway.
729 bool DetermineDevShmExecutable() {
732 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
734 ScopedFD
shm_fd_closer(&fd
);
735 DeleteFile(path
, false);
736 long sysconf_result
= sysconf(_SC_PAGESIZE
);
737 CHECK_GE(sysconf_result
, 0);
738 size_t pagesize
= static_cast<size_t>(sysconf_result
);
739 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
740 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
741 if (mapping
!= MAP_FAILED
) {
742 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
744 munmap(mapping
, pagesize
);
751 #endif // defined(OS_LINUX)
753 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
754 #if defined(OS_LINUX)
755 bool use_dev_shm
= true;
757 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
758 use_dev_shm
= s_dev_shm_executable
;
761 *path
= FilePath("/dev/shm");
765 return GetTempDir(path
);
767 #endif // !defined(OS_ANDROID)
769 FilePath
GetHomeDir() {
770 #if defined(OS_CHROMEOS)
771 if (base::SysInfo::IsRunningOnChromeOS())
772 return FilePath("/home/chronos/user");
775 const char* home_dir
= getenv("HOME");
776 if (home_dir
&& home_dir
[0])
777 return FilePath(home_dir
);
779 #if defined(OS_ANDROID)
780 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
781 #elif !defined(OS_CHROMEOS)
782 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
783 base::ThreadRestrictions::AssertIOAllowed();
785 home_dir
= g_get_home_dir();
786 if (home_dir
&& home_dir
[0])
787 return FilePath(home_dir
);
791 if (file_util::GetTempDir(&rv
))
795 return FilePath("/tmp");
797 #endif // !defined(OS_MACOSX)
799 bool VerifyPathControlledByUser(const FilePath
& base
,
800 const FilePath
& path
,
802 const std::set
<gid_t
>& group_gids
) {
803 if (base
!= path
&& !base
.IsParent(path
)) {
804 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
805 << base
.value() << "\", path = \"" << path
.value() << "\"";
809 std::vector
<FilePath::StringType
> base_components
;
810 std::vector
<FilePath::StringType
> path_components
;
812 base
.GetComponents(&base_components
);
813 path
.GetComponents(&path_components
);
815 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
816 for (ib
= base_components
.begin(), ip
= path_components
.begin();
817 ib
!= base_components
.end(); ++ib
, ++ip
) {
818 // |base| must be a subpath of |path|, so all components should match.
819 // If these CHECKs fail, look at the test that base is a parent of
820 // path at the top of this function.
821 DCHECK(ip
!= path_components
.end());
825 FilePath current_path
= base
;
826 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
829 for (; ip
!= path_components
.end(); ++ip
) {
830 current_path
= current_path
.Append(*ip
);
831 if (!VerifySpecificPathControlledByUser(
832 current_path
, owner_uid
, group_gids
))
838 #if defined(OS_MACOSX) && !defined(OS_IOS)
839 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
840 const unsigned kRootUid
= 0;
841 const FilePath
kFileSystemRoot("/");
843 // The name of the administrator group on mac os.
844 const char* const kAdminGroupNames
[] = {
849 // Reading the groups database may touch the file system.
850 base::ThreadRestrictions::AssertIOAllowed();
852 std::set
<gid_t
> allowed_group_ids
;
853 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
854 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
856 DPLOG(ERROR
) << "Could not get the group ID of group \""
857 << kAdminGroupNames
[i
] << "\".";
861 allowed_group_ids
.insert(group_record
->gr_gid
);
864 return VerifyPathControlledByUser(
865 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
867 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
869 int GetMaximumPathComponentLength(const FilePath
& path
) {
870 base::ThreadRestrictions::AssertIOAllowed();
871 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
874 } // namespace file_util
879 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
880 ThreadRestrictions::AssertIOAllowed();
881 // Windows compatibility: if to_path exists, from_path and to_path
882 // must be the same type, either both files, or both directories.
883 stat_wrapper_t to_file_info
;
884 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
885 stat_wrapper_t from_file_info
;
886 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
887 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
894 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
897 if (!CopyDirectory(from_path
, to_path
, true))
900 DeleteFile(from_path
, true);
904 #if !defined(OS_MACOSX)
905 // Mac has its own implementation, this is for all other Posix systems.
906 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
907 ThreadRestrictions::AssertIOAllowed();
908 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
912 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
914 ignore_result(HANDLE_EINTR(close(infile
)));
918 const size_t kBufferSize
= 32768;
919 std::vector
<char> buffer(kBufferSize
);
923 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
924 if (bytes_read
< 0) {
930 // Allow for partial writes
931 ssize_t bytes_written_per_read
= 0;
933 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
935 &buffer
[bytes_written_per_read
],
936 bytes_read
- bytes_written_per_read
));
937 if (bytes_written_partial
< 0) {
941 bytes_written_per_read
+= bytes_written_partial
;
942 } while (bytes_written_per_read
< bytes_read
);
945 if (HANDLE_EINTR(close(infile
)) < 0)
947 if (HANDLE_EINTR(close(outfile
)) < 0)
952 #endif // !defined(OS_MACOSX)
954 } // namespace internal