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.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"
61 using base::FileEnumerator
;
63 using base::MakeAbsoluteFilePath
;
67 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
68 base::ThreadRestrictions::AssertIOAllowed();
69 char full_path
[PATH_MAX
];
70 if (realpath(input
.value().c_str(), full_path
) == NULL
)
72 return FilePath(full_path
);
81 #if defined(OS_BSD) || defined(OS_MACOSX)
82 typedef struct stat stat_wrapper_t
;
83 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
84 base::ThreadRestrictions::AssertIOAllowed();
85 return stat(path
, sb
);
87 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
88 base::ThreadRestrictions::AssertIOAllowed();
89 return lstat(path
, sb
);
92 typedef struct stat64 stat_wrapper_t
;
93 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
94 base::ThreadRestrictions::AssertIOAllowed();
95 return stat64(path
, sb
);
97 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
98 base::ThreadRestrictions::AssertIOAllowed();
99 return lstat64(path
, sb
);
103 // Helper for NormalizeFilePath(), defined below.
104 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
105 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
106 FilePath::CharType buf
[PATH_MAX
];
107 if (!realpath(path
.value().c_str(), buf
))
110 *real_path
= FilePath(buf
);
114 // Helper for VerifyPathControlledByUser.
115 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
117 const std::set
<gid_t
>& group_gids
) {
118 stat_wrapper_t stat_info
;
119 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
120 DPLOG(ERROR
) << "Failed to get information on path "
125 if (S_ISLNK(stat_info
.st_mode
)) {
126 DLOG(ERROR
) << "Path " << path
.value()
127 << " is a symbolic link.";
131 if (stat_info
.st_uid
!= owner_uid
) {
132 DLOG(ERROR
) << "Path " << path
.value()
133 << " is owned by the wrong user.";
137 if ((stat_info
.st_mode
& S_IWGRP
) &&
138 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
139 DLOG(ERROR
) << "Path " << path
.value()
140 << " is writable by an unprivileged group.";
144 if (stat_info
.st_mode
& S_IWOTH
) {
145 DLOG(ERROR
) << "Path " << path
.value()
146 << " is writable by any user.";
155 static std::string
TempFileName() {
156 #if defined(OS_MACOSX)
157 return base::StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
160 #if defined(GOOGLE_CHROME_BUILD)
161 return std::string(".com.google.Chrome.XXXXXX");
163 return std::string(".org.chromium.Chromium.XXXXXX");
167 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
168 // which works both with and without the recursive flag. I'm not sure we need
169 // that functionality. If not, remove from file_util_win.cc, otherwise add it
171 bool Delete(const FilePath
& path
, bool recursive
) {
172 base::ThreadRestrictions::AssertIOAllowed();
173 const char* path_str
= path
.value().c_str();
174 stat_wrapper_t file_info
;
175 int test
= CallLstat(path_str
, &file_info
);
177 // The Windows version defines this condition as success.
178 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
181 if (!S_ISDIR(file_info
.st_mode
))
182 return (unlink(path_str
) == 0);
184 return (rmdir(path_str
) == 0);
187 std::stack
<std::string
> directories
;
188 directories
.push(path
.value());
189 FileEnumerator
traversal(path
, true,
190 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
191 FileEnumerator::SHOW_SYM_LINKS
);
192 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
193 current
= traversal
.Next()) {
194 if (traversal
.GetInfo().IsDirectory())
195 directories
.push(current
.value());
197 success
= (unlink(current
.value().c_str()) == 0);
200 while (success
&& !directories
.empty()) {
201 FilePath dir
= FilePath(directories
.top());
203 success
= (rmdir(dir
.value().c_str()) == 0);
208 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
209 base::ThreadRestrictions::AssertIOAllowed();
210 // Windows compatibility: if to_path exists, from_path and to_path
211 // must be the same type, either both files, or both directories.
212 stat_wrapper_t to_file_info
;
213 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
214 stat_wrapper_t from_file_info
;
215 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
216 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
223 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
226 if (!CopyDirectory(from_path
, to_path
, true))
229 Delete(from_path
, true);
233 bool ReplaceFileAndGetError(const FilePath
& from_path
,
234 const FilePath
& to_path
,
235 base::PlatformFileError
* error
) {
236 base::ThreadRestrictions::AssertIOAllowed();
237 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
240 *error
= base::ErrnoToPlatformFileError(errno
);
244 bool CopyDirectory(const FilePath
& from_path
,
245 const FilePath
& to_path
,
247 base::ThreadRestrictions::AssertIOAllowed();
248 // Some old callers of CopyDirectory want it to support wildcards.
249 // After some discussion, we decided to fix those callers.
250 // Break loudly here if anyone tries to do this.
251 // TODO(evanm): remove this once we're sure it's ok.
252 DCHECK(to_path
.value().find('*') == std::string::npos
);
253 DCHECK(from_path
.value().find('*') == std::string::npos
);
255 char top_dir
[PATH_MAX
];
256 if (base::strlcpy(top_dir
, from_path
.value().c_str(),
257 arraysize(top_dir
)) >= arraysize(top_dir
)) {
261 // This function does not properly handle destinations within the source
262 FilePath real_to_path
= to_path
;
263 if (PathExists(real_to_path
)) {
264 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
265 if (real_to_path
.empty())
268 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
269 if (real_to_path
.empty())
272 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
273 if (real_from_path
.empty())
275 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
276 real_to_path
.value().compare(0, real_from_path
.value().size(),
277 real_from_path
.value()) == 0)
281 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
283 traverse_type
|= FileEnumerator::DIRECTORIES
;
284 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
286 // We have to mimic windows behavior here. |to_path| may not exist yet,
287 // start the loop with |to_path|.
288 struct stat from_stat
;
289 FilePath current
= from_path
;
290 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
291 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
292 << from_path
.value() << " errno = " << errno
;
295 struct stat to_path_stat
;
296 FilePath from_path_base
= from_path
;
297 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
298 S_ISDIR(to_path_stat
.st_mode
)) {
299 // If the destination already exists and is a directory, then the
300 // top level of source needs to be copied.
301 from_path_base
= from_path
.DirName();
304 // The Windows version of this function assumes that non-recursive calls
305 // will always have a directory for from_path.
306 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
308 while (success
&& !current
.empty()) {
309 // current is the source path, including from_path, so append
310 // the suffix after from_path to to_path to create the target_path.
311 FilePath
target_path(to_path
);
312 if (from_path_base
!= current
) {
313 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
319 if (S_ISDIR(from_stat
.st_mode
)) {
320 if (mkdir(target_path
.value().c_str(), from_stat
.st_mode
& 01777) != 0 &&
322 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
323 << target_path
.value() << " errno = " << errno
;
326 } else if (S_ISREG(from_stat
.st_mode
)) {
327 if (!CopyFile(current
, target_path
)) {
328 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
329 << target_path
.value();
333 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
337 current
= traversal
.Next();
338 if (!current
.empty())
339 from_stat
= traversal
.GetInfo().stat();
345 bool PathExists(const FilePath
& path
) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 return access(path
.value().c_str(), F_OK
) == 0;
350 bool PathIsWritable(const FilePath
& path
) {
351 base::ThreadRestrictions::AssertIOAllowed();
352 return access(path
.value().c_str(), W_OK
) == 0;
355 bool DirectoryExists(const FilePath
& path
) {
356 base::ThreadRestrictions::AssertIOAllowed();
357 stat_wrapper_t file_info
;
358 if (CallStat(path
.value().c_str(), &file_info
) == 0)
359 return S_ISDIR(file_info
.st_mode
);
363 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
364 size_t total_read
= 0;
365 while (total_read
< bytes
) {
367 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
370 total_read
+= bytes_read
;
372 return total_read
== bytes
;
375 bool CreateSymbolicLink(const FilePath
& target_path
,
376 const FilePath
& symlink_path
) {
377 DCHECK(!symlink_path
.empty());
378 DCHECK(!target_path
.empty());
379 return ::symlink(target_path
.value().c_str(),
380 symlink_path
.value().c_str()) != -1;
383 bool ReadSymbolicLink(const FilePath
& symlink_path
,
384 FilePath
* target_path
) {
385 DCHECK(!symlink_path
.empty());
388 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
391 target_path
->clear();
395 *target_path
= FilePath(FilePath::StringType(buf
, count
));
399 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
400 base::ThreadRestrictions::AssertIOAllowed();
403 stat_wrapper_t file_info
;
404 // Uses stat(), because on symbolic link, lstat() does not return valid
405 // permission bits in st_mode
406 if (CallStat(path
.value().c_str(), &file_info
) != 0)
409 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
413 bool SetPosixFilePermissions(const FilePath
& path
,
415 base::ThreadRestrictions::AssertIOAllowed();
416 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
418 // Calls stat() so that we can preserve the higher bits like S_ISGID.
419 stat_wrapper_t stat_buf
;
420 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
423 // Clears the existing permission bits, and adds the new ones.
424 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
425 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
427 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
433 // Creates and opens a temporary file in |directory|, returning the
434 // file descriptor. |path| is set to the temporary file path.
435 // This function does NOT unlink() the file.
436 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
437 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
438 *path
= directory
.Append(TempFileName());
439 const std::string
& tmpdir_string
= path
->value();
440 // this should be OK since mkstemp just replaces characters in place
441 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
443 return HANDLE_EINTR(mkstemp(buffer
));
446 bool CreateTemporaryFile(FilePath
* path
) {
447 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
449 if (!GetTempDir(&directory
))
451 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
454 ignore_result(HANDLE_EINTR(close(fd
)));
458 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
460 if (!GetShmemTempDir(&directory
, executable
))
463 return CreateAndOpenTemporaryFileInDir(directory
, path
);
466 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
467 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
471 FILE* file
= fdopen(fd
, "a+");
473 ignore_result(HANDLE_EINTR(close(fd
)));
477 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
478 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
479 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
480 return ((fd
>= 0) && !HANDLE_EINTR(close(fd
)));
483 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
484 const FilePath::StringType
& name_tmpl
,
486 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
487 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
488 << "Directory name template must contain \"XXXXXX\".";
490 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
491 std::string sub_dir_string
= sub_dir
.value();
493 // this should be OK since mkdtemp just replaces characters in place
494 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
495 char* dtemp
= mkdtemp(buffer
);
497 DPLOG(ERROR
) << "mkdtemp";
500 *new_dir
= FilePath(dtemp
);
504 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
505 const FilePath::StringType
& prefix
,
507 FilePath::StringType mkdtemp_template
= prefix
;
508 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
509 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
512 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
513 FilePath
* new_temp_path
) {
515 if (!GetTempDir(&tmpdir
))
518 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
521 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
522 base::PlatformFileError
* error
) {
523 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
524 std::vector
<FilePath
> subpaths
;
526 // Collect a list of all parent directories.
527 FilePath last_path
= full_path
;
528 subpaths
.push_back(full_path
);
529 for (FilePath path
= full_path
.DirName();
530 path
.value() != last_path
.value(); path
= path
.DirName()) {
531 subpaths
.push_back(path
);
535 // Iterate through the parents and create the missing ones.
536 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
537 i
!= subpaths
.rend(); ++i
) {
538 if (DirectoryExists(*i
))
540 if (mkdir(i
->value().c_str(), 0700) == 0)
542 // Mkdir failed, but it might have failed with EEXIST, or some other error
543 // due to the the directory appearing out of thin air. This can occur if
544 // two processes are trying to create the same file system tree at the same
545 // time. Check to see if it exists and make sure it is a directory.
546 int saved_errno
= errno
;
547 if (!DirectoryExists(*i
)) {
549 *error
= base::ErrnoToPlatformFileError(saved_errno
);
556 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
557 const int kMaxAttempts
= 20;
558 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
560 GetUniquePathNumber(path
, base::FilePath::StringType());
563 base::FilePath test_path
= (uniquifier
== 0) ? path
:
564 path
.InsertBeforeExtensionASCII(
565 base::StringPrintf(" (%d)", uniquifier
));
566 if (mkdir(test_path
.value().c_str(), 0777) == 0)
568 else if (errno
!= EEXIST
)
571 return base::FilePath();
574 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
575 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
576 bool IsLink(const FilePath
& file_path
) {
578 // If we can't lstat the file, it's safe to assume that the file won't at
579 // least be a 'followable' link.
580 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
583 if (S_ISLNK(st
.st_mode
))
589 bool GetFileInfo(const FilePath
& file_path
, base::PlatformFileInfo
* results
) {
590 stat_wrapper_t file_info
;
591 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
593 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
594 results
->size
= file_info
.st_size
;
595 #if defined(OS_MACOSX)
596 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtimespec
);
597 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atimespec
);
598 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctimespec
);
599 #elif defined(OS_ANDROID)
600 results
->last_modified
= base::Time::FromTimeT(file_info
.st_mtime
);
601 results
->last_accessed
= base::Time::FromTimeT(file_info
.st_atime
);
602 results
->creation_time
= base::Time::FromTimeT(file_info
.st_ctime
);
604 results
->last_modified
= base::Time::FromTimeSpec(file_info
.st_mtim
);
605 results
->last_accessed
= base::Time::FromTimeSpec(file_info
.st_atim
);
606 results
->creation_time
= base::Time::FromTimeSpec(file_info
.st_ctim
);
611 bool GetInode(const FilePath
& path
, ino_t
* inode
) {
612 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
614 int result
= stat(path
.value().c_str(), &buffer
);
618 *inode
= buffer
.st_ino
;
622 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
623 return OpenFile(FilePath(filename
), mode
);
626 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
627 base::ThreadRestrictions::AssertIOAllowed();
630 result
= fopen(filename
.value().c_str(), mode
);
631 } while (!result
&& errno
== EINTR
);
635 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
636 base::ThreadRestrictions::AssertIOAllowed();
637 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
641 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
642 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
647 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
648 base::ThreadRestrictions::AssertIOAllowed();
649 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
653 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
654 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
656 return bytes_written
;
659 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
660 // Allow for partial writes.
661 ssize_t bytes_written_total
= 0;
662 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
663 bytes_written_total
+= bytes_written_partial
) {
664 bytes_written_partial
=
665 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
666 size
- bytes_written_total
));
667 if (bytes_written_partial
< 0)
671 return bytes_written_total
;
674 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
675 base::ThreadRestrictions::AssertIOAllowed();
676 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
680 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
681 if (int ret
= HANDLE_EINTR(close(fd
)) < 0)
683 return bytes_written
;
686 // Gets the current working directory for the process.
687 bool GetCurrentDirectory(FilePath
* dir
) {
688 // getcwd can return ENOENT, which implies it checks against the disk.
689 base::ThreadRestrictions::AssertIOAllowed();
691 char system_buffer
[PATH_MAX
] = "";
692 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
696 *dir
= FilePath(system_buffer
);
700 // Sets the current working directory for the process.
701 bool SetCurrentDirectory(const FilePath
& path
) {
702 base::ThreadRestrictions::AssertIOAllowed();
703 int ret
= chdir(path
.value().c_str());
707 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
708 FilePath real_path_result
;
709 if (!RealPath(path
, &real_path_result
))
712 // To be consistant with windows, fail if |real_path_result| is a
714 stat_wrapper_t file_info
;
715 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
716 S_ISDIR(file_info
.st_mode
))
719 *normalized_path
= real_path_result
;
723 #if !defined(OS_MACOSX)
724 bool GetTempDir(FilePath
* path
) {
725 const char* tmp
= getenv("TMPDIR");
727 *path
= FilePath(tmp
);
729 #if defined(OS_ANDROID)
730 return PathService::Get(base::DIR_CACHE
, path
);
732 *path
= FilePath("/tmp");
737 #if !defined(OS_ANDROID)
739 #if defined(OS_LINUX)
740 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
741 // This depends on the mount options used for /dev/shm, which vary among
742 // different Linux distributions and possibly local configuration. It also
743 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
744 // but its kernel allows mprotect with PROT_EXEC anyway.
748 bool DetermineDevShmExecutable() {
751 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
753 ScopedFD
shm_fd_closer(&fd
);
755 long sysconf_result
= sysconf(_SC_PAGESIZE
);
756 CHECK_GE(sysconf_result
, 0);
757 size_t pagesize
= static_cast<size_t>(sysconf_result
);
758 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
759 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
760 if (mapping
!= MAP_FAILED
) {
761 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
763 munmap(mapping
, pagesize
);
770 #endif // defined(OS_LINUX)
772 bool GetShmemTempDir(FilePath
* path
, bool executable
) {
773 #if defined(OS_LINUX)
774 bool use_dev_shm
= true;
776 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
777 use_dev_shm
= s_dev_shm_executable
;
780 *path
= FilePath("/dev/shm");
784 return GetTempDir(path
);
786 #endif // !defined(OS_ANDROID)
788 FilePath
GetHomeDir() {
789 #if defined(OS_CHROMEOS)
790 if (base::chromeos::IsRunningOnChromeOS())
791 return FilePath("/home/chronos/user");
794 const char* home_dir
= getenv("HOME");
795 if (home_dir
&& home_dir
[0])
796 return FilePath(home_dir
);
798 #if defined(OS_ANDROID)
799 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
801 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
802 base::ThreadRestrictions::AssertIOAllowed();
804 home_dir
= g_get_home_dir();
805 if (home_dir
&& home_dir
[0])
806 return FilePath(home_dir
);
810 if (file_util::GetTempDir(&rv
))
814 return FilePath("/tmp");
817 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
818 base::ThreadRestrictions::AssertIOAllowed();
819 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
823 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
825 ignore_result(HANDLE_EINTR(close(infile
)));
829 const size_t kBufferSize
= 32768;
830 std::vector
<char> buffer(kBufferSize
);
834 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
835 if (bytes_read
< 0) {
841 // Allow for partial writes
842 ssize_t bytes_written_per_read
= 0;
844 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
846 &buffer
[bytes_written_per_read
],
847 bytes_read
- bytes_written_per_read
));
848 if (bytes_written_partial
< 0) {
852 bytes_written_per_read
+= bytes_written_partial
;
853 } while (bytes_written_per_read
< bytes_read
);
856 if (HANDLE_EINTR(close(infile
)) < 0)
858 if (HANDLE_EINTR(close(outfile
)) < 0)
863 #endif // !defined(OS_MACOSX)
865 bool VerifyPathControlledByUser(const FilePath
& base
,
866 const FilePath
& path
,
868 const std::set
<gid_t
>& group_gids
) {
869 if (base
!= path
&& !base
.IsParent(path
)) {
870 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
871 << base
.value() << "\", path = \"" << path
.value() << "\"";
875 std::vector
<FilePath::StringType
> base_components
;
876 std::vector
<FilePath::StringType
> path_components
;
878 base
.GetComponents(&base_components
);
879 path
.GetComponents(&path_components
);
881 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
882 for (ib
= base_components
.begin(), ip
= path_components
.begin();
883 ib
!= base_components
.end(); ++ib
, ++ip
) {
884 // |base| must be a subpath of |path|, so all components should match.
885 // If these CHECKs fail, look at the test that base is a parent of
886 // path at the top of this function.
887 DCHECK(ip
!= path_components
.end());
891 FilePath current_path
= base
;
892 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
895 for (; ip
!= path_components
.end(); ++ip
) {
896 current_path
= current_path
.Append(*ip
);
897 if (!VerifySpecificPathControlledByUser(
898 current_path
, owner_uid
, group_gids
))
904 #if defined(OS_MACOSX) && !defined(OS_IOS)
905 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
906 const unsigned kRootUid
= 0;
907 const FilePath
kFileSystemRoot("/");
909 // The name of the administrator group on mac os.
910 const char* const kAdminGroupNames
[] = {
915 // Reading the groups database may touch the file system.
916 base::ThreadRestrictions::AssertIOAllowed();
918 std::set
<gid_t
> allowed_group_ids
;
919 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
920 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
922 DPLOG(ERROR
) << "Could not get the group ID of group \""
923 << kAdminGroupNames
[i
] << "\".";
927 allowed_group_ids
.insert(group_record
->gr_gid
);
930 return VerifyPathControlledByUser(
931 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
933 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
935 int GetMaximumPathComponentLength(const FilePath
& path
) {
936 base::ThreadRestrictions::AssertIOAllowed();
937 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
940 } // namespace file_util