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_CHROMEOS) && defined(USE_GLIB)
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/android/content_uri_utils.h"
52 #include "base/os_compat_android.h"
63 #if defined(OS_BSD) || defined(OS_MACOSX)
64 typedef struct stat stat_wrapper_t
;
65 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
66 ThreadRestrictions::AssertIOAllowed();
67 return stat(path
, sb
);
69 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
70 ThreadRestrictions::AssertIOAllowed();
71 return lstat(path
, sb
);
74 typedef struct stat64 stat_wrapper_t
;
75 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
76 ThreadRestrictions::AssertIOAllowed();
77 return stat64(path
, sb
);
79 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
80 ThreadRestrictions::AssertIOAllowed();
81 return lstat64(path
, sb
);
83 #if defined(OS_ANDROID)
84 static int CallFstat(int fd
, stat_wrapper_t
*sb
) {
85 ThreadRestrictions::AssertIOAllowed();
86 return fstat64(fd
, sb
);
91 // Helper for NormalizeFilePath(), defined below.
92 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
93 ThreadRestrictions::AssertIOAllowed(); // For realpath().
94 FilePath::CharType buf
[PATH_MAX
];
95 if (!realpath(path
.value().c_str(), buf
))
98 *real_path
= FilePath(buf
);
102 // Helper for VerifyPathControlledByUser.
103 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
105 const std::set
<gid_t
>& group_gids
) {
106 stat_wrapper_t stat_info
;
107 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
108 DPLOG(ERROR
) << "Failed to get information on path "
113 if (S_ISLNK(stat_info
.st_mode
)) {
114 DLOG(ERROR
) << "Path " << path
.value()
115 << " is a symbolic link.";
119 if (stat_info
.st_uid
!= owner_uid
) {
120 DLOG(ERROR
) << "Path " << path
.value()
121 << " is owned by the wrong user.";
125 if ((stat_info
.st_mode
& S_IWGRP
) &&
126 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
127 DLOG(ERROR
) << "Path " << path
.value()
128 << " is writable by an unprivileged group.";
132 if (stat_info
.st_mode
& S_IWOTH
) {
133 DLOG(ERROR
) << "Path " << path
.value()
134 << " is writable by any user.";
141 std::string
TempFileName() {
142 #if defined(OS_MACOSX)
143 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
146 #if defined(GOOGLE_CHROME_BUILD)
147 return std::string(".com.google.Chrome.XXXXXX");
149 return std::string(".org.chromium.Chromium.XXXXXX");
153 // Creates and opens a temporary file in |directory|, returning the
154 // file descriptor. |path| is set to the temporary file path.
155 // This function does NOT unlink() the file.
156 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
157 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
158 *path
= directory
.Append(base::TempFileName());
159 const std::string
& tmpdir_string
= path
->value();
160 // this should be OK since mkstemp just replaces characters in place
161 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
163 return HANDLE_EINTR(mkstemp(buffer
));
166 #if defined(OS_LINUX)
167 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
168 // This depends on the mount options used for /dev/shm, which vary among
169 // different Linux distributions and possibly local configuration. It also
170 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
171 // but its kernel allows mprotect with PROT_EXEC anyway.
172 bool DetermineDevShmExecutable() {
175 int fd
= CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
);
177 file_util::ScopedFD
shm_fd_closer(&fd
);
178 DeleteFile(path
, false);
179 long sysconf_result
= sysconf(_SC_PAGESIZE
);
180 CHECK_GE(sysconf_result
, 0);
181 size_t pagesize
= static_cast<size_t>(sysconf_result
);
182 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
183 void *mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
, 0);
184 if (mapping
!= MAP_FAILED
) {
185 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
187 munmap(mapping
, pagesize
);
192 #endif // defined(OS_LINUX)
196 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
197 ThreadRestrictions::AssertIOAllowed();
198 char full_path
[PATH_MAX
];
199 if (realpath(input
.value().c_str(), full_path
) == NULL
)
201 return FilePath(full_path
);
204 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
205 // which works both with and without the recursive flag. I'm not sure we need
206 // that functionality. If not, remove from file_util_win.cc, otherwise add it
208 bool DeleteFile(const FilePath
& path
, bool recursive
) {
209 ThreadRestrictions::AssertIOAllowed();
210 const char* path_str
= path
.value().c_str();
211 stat_wrapper_t file_info
;
212 int test
= CallLstat(path_str
, &file_info
);
214 // The Windows version defines this condition as success.
215 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
218 if (!S_ISDIR(file_info
.st_mode
))
219 return (unlink(path_str
) == 0);
221 return (rmdir(path_str
) == 0);
224 std::stack
<std::string
> directories
;
225 directories
.push(path
.value());
226 FileEnumerator
traversal(path
, true,
227 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
228 FileEnumerator::SHOW_SYM_LINKS
);
229 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
230 current
= traversal
.Next()) {
231 if (traversal
.GetInfo().IsDirectory())
232 directories
.push(current
.value());
234 success
= (unlink(current
.value().c_str()) == 0);
237 while (success
&& !directories
.empty()) {
238 FilePath dir
= FilePath(directories
.top());
240 success
= (rmdir(dir
.value().c_str()) == 0);
245 bool ReplaceFile(const FilePath
& from_path
,
246 const FilePath
& to_path
,
247 File::Error
* error
) {
248 ThreadRestrictions::AssertIOAllowed();
249 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
252 *error
= File::OSErrorToFileError(errno
);
256 bool CopyDirectory(const FilePath
& from_path
,
257 const FilePath
& to_path
,
259 ThreadRestrictions::AssertIOAllowed();
260 // Some old callers of CopyDirectory want it to support wildcards.
261 // After some discussion, we decided to fix those callers.
262 // Break loudly here if anyone tries to do this.
263 DCHECK(to_path
.value().find('*') == std::string::npos
);
264 DCHECK(from_path
.value().find('*') == std::string::npos
);
266 if (from_path
.value().size() >= PATH_MAX
) {
270 // This function does not properly handle destinations within the source
271 FilePath real_to_path
= to_path
;
272 if (PathExists(real_to_path
)) {
273 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
274 if (real_to_path
.empty())
277 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
278 if (real_to_path
.empty())
281 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
282 if (real_from_path
.empty())
284 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
285 real_to_path
.value().compare(0, real_from_path
.value().size(),
286 real_from_path
.value()) == 0) {
290 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
292 traverse_type
|= FileEnumerator::DIRECTORIES
;
293 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
295 // We have to mimic windows behavior here. |to_path| may not exist yet,
296 // start the loop with |to_path|.
297 struct stat from_stat
;
298 FilePath current
= from_path
;
299 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
300 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
301 << from_path
.value() << " errno = " << errno
;
304 struct stat to_path_stat
;
305 FilePath from_path_base
= from_path
;
306 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
307 S_ISDIR(to_path_stat
.st_mode
)) {
308 // If the destination already exists and is a directory, then the
309 // top level of source needs to be copied.
310 from_path_base
= from_path
.DirName();
313 // The Windows version of this function assumes that non-recursive calls
314 // will always have a directory for from_path.
315 // TODO(maruel): This is not necessary anymore.
316 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
319 while (success
&& !current
.empty()) {
320 // current is the source path, including from_path, so append
321 // the suffix after from_path to to_path to create the target_path.
322 FilePath
target_path(to_path
);
323 if (from_path_base
!= current
) {
324 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
330 if (S_ISDIR(from_stat
.st_mode
)) {
331 if (mkdir(target_path
.value().c_str(), from_stat
.st_mode
& 01777) != 0 &&
333 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
334 << target_path
.value() << " errno = " << errno
;
337 } else if (S_ISREG(from_stat
.st_mode
)) {
338 if (!CopyFile(current
, target_path
)) {
339 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
340 << target_path
.value();
344 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
348 current
= traversal
.Next();
349 if (!current
.empty())
350 from_stat
= traversal
.GetInfo().stat();
356 bool PathExists(const FilePath
& path
) {
357 ThreadRestrictions::AssertIOAllowed();
358 #if defined(OS_ANDROID)
359 if (path
.IsContentUri()) {
360 return ContentUriExists(path
);
363 return access(path
.value().c_str(), F_OK
) == 0;
366 bool PathIsWritable(const FilePath
& path
) {
367 ThreadRestrictions::AssertIOAllowed();
368 return access(path
.value().c_str(), W_OK
) == 0;
371 bool DirectoryExists(const FilePath
& path
) {
372 ThreadRestrictions::AssertIOAllowed();
373 stat_wrapper_t file_info
;
374 if (CallStat(path
.value().c_str(), &file_info
) == 0)
375 return S_ISDIR(file_info
.st_mode
);
379 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
380 size_t total_read
= 0;
381 while (total_read
< bytes
) {
383 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
386 total_read
+= bytes_read
;
388 return total_read
== bytes
;
391 bool CreateSymbolicLink(const FilePath
& target_path
,
392 const FilePath
& symlink_path
) {
393 DCHECK(!symlink_path
.empty());
394 DCHECK(!target_path
.empty());
395 return ::symlink(target_path
.value().c_str(),
396 symlink_path
.value().c_str()) != -1;
399 bool ReadSymbolicLink(const FilePath
& symlink_path
, FilePath
* target_path
) {
400 DCHECK(!symlink_path
.empty());
403 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
406 target_path
->clear();
410 *target_path
= FilePath(FilePath::StringType(buf
, count
));
414 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
415 ThreadRestrictions::AssertIOAllowed();
418 stat_wrapper_t file_info
;
419 // Uses stat(), because on symbolic link, lstat() does not return valid
420 // permission bits in st_mode
421 if (CallStat(path
.value().c_str(), &file_info
) != 0)
424 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
428 bool SetPosixFilePermissions(const FilePath
& path
,
430 ThreadRestrictions::AssertIOAllowed();
431 DCHECK((mode
& ~FILE_PERMISSION_MASK
) == 0);
433 // Calls stat() so that we can preserve the higher bits like S_ISGID.
434 stat_wrapper_t stat_buf
;
435 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
438 // Clears the existing permission bits, and adds the new ones.
439 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
440 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
442 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
448 #if !defined(OS_MACOSX)
449 // This is implemented in file_util_mac.mm for Mac.
450 bool GetTempDir(FilePath
* path
) {
451 const char* tmp
= getenv("TMPDIR");
453 *path
= FilePath(tmp
);
455 #if defined(OS_ANDROID)
456 return PathService::Get(base::DIR_CACHE
, path
);
458 *path
= FilePath("/tmp");
463 #endif // !defined(OS_MACOSX)
465 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
466 // This is implemented in file_util_mac.mm and file_util_android.cc for those
468 bool GetShmemTempDir(bool executable
, FilePath
* path
) {
469 #if defined(OS_LINUX)
470 bool use_dev_shm
= true;
472 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
473 use_dev_shm
= s_dev_shm_executable
;
476 *path
= FilePath("/dev/shm");
480 return GetTempDir(path
);
482 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
484 #if !defined(OS_MACOSX)
485 FilePath
GetHomeDir() {
486 #if defined(OS_CHROMEOS)
487 if (SysInfo::IsRunningOnChromeOS())
488 return FilePath("/home/chronos/user");
491 const char* home_dir
= getenv("HOME");
492 if (home_dir
&& home_dir
[0])
493 return FilePath(home_dir
);
495 #if defined(OS_ANDROID)
496 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
497 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
498 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
499 ThreadRestrictions::AssertIOAllowed();
501 home_dir
= g_get_home_dir();
502 if (home_dir
&& home_dir
[0])
503 return FilePath(home_dir
);
511 return FilePath("/tmp");
513 #endif // !defined(OS_MACOSX)
515 bool CreateTemporaryFile(FilePath
* path
) {
516 ThreadRestrictions::AssertIOAllowed(); // For call to close().
518 if (!GetTempDir(&directory
))
520 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
527 FILE* CreateAndOpenTemporaryShmemFile(FilePath
* path
, bool executable
) {
529 if (!GetShmemTempDir(executable
, &directory
))
532 return CreateAndOpenTemporaryFileInDir(directory
, path
);
535 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
536 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
540 FILE* file
= fdopen(fd
, "a+");
546 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
547 ThreadRestrictions::AssertIOAllowed(); // For call to close().
548 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
549 return ((fd
>= 0) && !IGNORE_EINTR(close(fd
)));
552 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
553 const FilePath::StringType
& name_tmpl
,
555 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
556 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
557 << "Directory name template must contain \"XXXXXX\".";
559 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
560 std::string sub_dir_string
= sub_dir
.value();
562 // this should be OK since mkdtemp just replaces characters in place
563 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
564 char* dtemp
= mkdtemp(buffer
);
566 DPLOG(ERROR
) << "mkdtemp";
569 *new_dir
= FilePath(dtemp
);
573 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
574 const FilePath::StringType
& prefix
,
576 FilePath::StringType mkdtemp_template
= prefix
;
577 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
578 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
581 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
582 FilePath
* new_temp_path
) {
584 if (!GetTempDir(&tmpdir
))
587 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
590 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
591 File::Error
* error
) {
592 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
593 std::vector
<FilePath
> subpaths
;
595 // Collect a list of all parent directories.
596 FilePath last_path
= full_path
;
597 subpaths
.push_back(full_path
);
598 for (FilePath path
= full_path
.DirName();
599 path
.value() != last_path
.value(); path
= path
.DirName()) {
600 subpaths
.push_back(path
);
604 // Iterate through the parents and create the missing ones.
605 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
606 i
!= subpaths
.rend(); ++i
) {
607 if (DirectoryExists(*i
))
609 if (mkdir(i
->value().c_str(), 0700) == 0)
611 // Mkdir failed, but it might have failed with EEXIST, or some other error
612 // due to the the directory appearing out of thin air. This can occur if
613 // two processes are trying to create the same file system tree at the same
614 // time. Check to see if it exists and make sure it is a directory.
615 int saved_errno
= errno
;
616 if (!DirectoryExists(*i
)) {
618 *error
= File::OSErrorToFileError(saved_errno
);
625 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
626 FilePath real_path_result
;
627 if (!RealPath(path
, &real_path_result
))
630 // To be consistant with windows, fail if |real_path_result| is a
632 stat_wrapper_t file_info
;
633 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
634 S_ISDIR(file_info
.st_mode
))
637 *normalized_path
= real_path_result
;
641 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
642 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
643 bool IsLink(const FilePath
& file_path
) {
645 // If we can't lstat the file, it's safe to assume that the file won't at
646 // least be a 'followable' link.
647 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
650 if (S_ISLNK(st
.st_mode
))
656 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
657 stat_wrapper_t file_info
;
658 #if defined(OS_ANDROID)
659 if (file_path
.IsContentUri()) {
660 int fd
= OpenContentUriForRead(file_path
);
663 file_util::ScopedFD
scoped_fd(&fd
);
664 if (CallFstat(fd
, &file_info
) != 0)
667 #endif // defined(OS_ANDROID)
668 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
670 #if defined(OS_ANDROID)
672 #endif // defined(OS_ANDROID)
673 results
->is_directory
= S_ISDIR(file_info
.st_mode
);
674 results
->size
= file_info
.st_size
;
675 #if defined(OS_MACOSX)
676 results
->last_modified
= Time::FromTimeSpec(file_info
.st_mtimespec
);
677 results
->last_accessed
= Time::FromTimeSpec(file_info
.st_atimespec
);
678 results
->creation_time
= Time::FromTimeSpec(file_info
.st_ctimespec
);
679 #elif defined(OS_ANDROID)
680 results
->last_modified
= Time::FromTimeT(file_info
.st_mtime
);
681 results
->last_accessed
= Time::FromTimeT(file_info
.st_atime
);
682 results
->creation_time
= Time::FromTimeT(file_info
.st_ctime
);
684 results
->last_modified
= Time::FromTimeSpec(file_info
.st_mtim
);
685 results
->last_accessed
= Time::FromTimeSpec(file_info
.st_atim
);
686 results
->creation_time
= Time::FromTimeSpec(file_info
.st_ctim
);
691 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
692 ThreadRestrictions::AssertIOAllowed();
695 result
= fopen(filename
.value().c_str(), mode
);
696 } while (!result
&& errno
== EINTR
);
700 int ReadFile(const FilePath
& filename
, char* data
, int size
) {
701 ThreadRestrictions::AssertIOAllowed();
702 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
706 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, size
));
707 if (int ret
= IGNORE_EINTR(close(fd
)) < 0)
714 // -----------------------------------------------------------------------------
716 namespace file_util
{
718 using base::stat_wrapper_t
;
719 using base::CallStat
;
720 using base::CallLstat
;
721 using base::CreateAndOpenFdForTemporaryFile
;
722 using base::DirectoryExists
;
723 using base::FileEnumerator
;
724 using base::FilePath
;
725 using base::MakeAbsoluteFilePath
;
726 using base::VerifySpecificPathControlledByUser
;
728 base::FilePath
MakeUniqueDirectory(const base::FilePath
& path
) {
729 const int kMaxAttempts
= 20;
730 for (int attempts
= 0; attempts
< kMaxAttempts
; attempts
++) {
732 GetUniquePathNumber(path
, base::FilePath::StringType());
735 base::FilePath test_path
= (uniquifier
== 0) ? path
:
736 path
.InsertBeforeExtensionASCII(
737 base::StringPrintf(" (%d)", uniquifier
));
738 if (mkdir(test_path
.value().c_str(), 0777) == 0)
740 else if (errno
!= EEXIST
)
743 return base::FilePath();
746 FILE* OpenFile(const std::string
& filename
, const char* mode
) {
747 return OpenFile(FilePath(filename
), mode
);
750 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
751 base::ThreadRestrictions::AssertIOAllowed();
752 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0666));
756 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
757 if (int ret
= IGNORE_EINTR(close(fd
)) < 0)
759 return bytes_written
;
762 int WriteFileDescriptor(const int fd
, const char* data
, int size
) {
763 // Allow for partial writes.
764 ssize_t bytes_written_total
= 0;
765 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
766 bytes_written_total
+= bytes_written_partial
) {
767 bytes_written_partial
=
768 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
769 size
- bytes_written_total
));
770 if (bytes_written_partial
< 0)
774 return bytes_written_total
;
777 int AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
778 base::ThreadRestrictions::AssertIOAllowed();
779 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
783 int bytes_written
= WriteFileDescriptor(fd
, data
, size
);
784 if (int ret
= IGNORE_EINTR(close(fd
)) < 0)
786 return bytes_written
;
789 // Gets the current working directory for the process.
790 bool GetCurrentDirectory(FilePath
* dir
) {
791 // getcwd can return ENOENT, which implies it checks against the disk.
792 base::ThreadRestrictions::AssertIOAllowed();
794 char system_buffer
[PATH_MAX
] = "";
795 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
799 *dir
= FilePath(system_buffer
);
803 // Sets the current working directory for the process.
804 bool SetCurrentDirectory(const FilePath
& path
) {
805 base::ThreadRestrictions::AssertIOAllowed();
806 int ret
= chdir(path
.value().c_str());
810 bool VerifyPathControlledByUser(const FilePath
& base
,
811 const FilePath
& path
,
813 const std::set
<gid_t
>& group_gids
) {
814 if (base
!= path
&& !base
.IsParent(path
)) {
815 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
816 << base
.value() << "\", path = \"" << path
.value() << "\"";
820 std::vector
<FilePath::StringType
> base_components
;
821 std::vector
<FilePath::StringType
> path_components
;
823 base
.GetComponents(&base_components
);
824 path
.GetComponents(&path_components
);
826 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
827 for (ib
= base_components
.begin(), ip
= path_components
.begin();
828 ib
!= base_components
.end(); ++ib
, ++ip
) {
829 // |base| must be a subpath of |path|, so all components should match.
830 // If these CHECKs fail, look at the test that base is a parent of
831 // path at the top of this function.
832 DCHECK(ip
!= path_components
.end());
836 FilePath current_path
= base
;
837 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
840 for (; ip
!= path_components
.end(); ++ip
) {
841 current_path
= current_path
.Append(*ip
);
842 if (!VerifySpecificPathControlledByUser(
843 current_path
, owner_uid
, group_gids
))
849 #if defined(OS_MACOSX) && !defined(OS_IOS)
850 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
851 const unsigned kRootUid
= 0;
852 const FilePath
kFileSystemRoot("/");
854 // The name of the administrator group on mac os.
855 const char* const kAdminGroupNames
[] = {
860 // Reading the groups database may touch the file system.
861 base::ThreadRestrictions::AssertIOAllowed();
863 std::set
<gid_t
> allowed_group_ids
;
864 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
865 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
867 DPLOG(ERROR
) << "Could not get the group ID of group \""
868 << kAdminGroupNames
[i
] << "\".";
872 allowed_group_ids
.insert(group_record
->gr_gid
);
875 return VerifyPathControlledByUser(
876 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
878 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
880 int GetMaximumPathComponentLength(const FilePath
& path
) {
881 base::ThreadRestrictions::AssertIOAllowed();
882 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
885 } // namespace file_util
890 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
891 ThreadRestrictions::AssertIOAllowed();
892 // Windows compatibility: if to_path exists, from_path and to_path
893 // must be the same type, either both files, or both directories.
894 stat_wrapper_t to_file_info
;
895 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
896 stat_wrapper_t from_file_info
;
897 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
898 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
905 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
908 if (!CopyDirectory(from_path
, to_path
, true))
911 DeleteFile(from_path
, true);
915 #if !defined(OS_MACOSX)
916 // Mac has its own implementation, this is for all other Posix systems.
917 bool CopyFileUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
918 ThreadRestrictions::AssertIOAllowed();
919 int infile
= HANDLE_EINTR(open(from_path
.value().c_str(), O_RDONLY
));
923 int outfile
= HANDLE_EINTR(creat(to_path
.value().c_str(), 0666));
929 const size_t kBufferSize
= 32768;
930 std::vector
<char> buffer(kBufferSize
);
934 ssize_t bytes_read
= HANDLE_EINTR(read(infile
, &buffer
[0], buffer
.size()));
935 if (bytes_read
< 0) {
941 // Allow for partial writes
942 ssize_t bytes_written_per_read
= 0;
944 ssize_t bytes_written_partial
= HANDLE_EINTR(write(
946 &buffer
[bytes_written_per_read
],
947 bytes_read
- bytes_written_per_read
));
948 if (bytes_written_partial
< 0) {
952 bytes_written_per_read
+= bytes_written_partial
;
953 } while (bytes_written_per_read
< bytes_read
);
956 if (IGNORE_EINTR(close(infile
)) < 0)
958 if (IGNORE_EINTR(close(outfile
)) < 0)
963 #endif // !defined(OS_MACOSX)
965 } // namespace internal