1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/files/file_util.h"
15 #include <sys/errno.h>
17 #include <sys/param.h>
20 #include <sys/types.h>
24 #if defined(OS_MACOSX)
25 #include <AvailabilityMacros.h>
26 #include "base/mac/foundation_util.h"
27 #elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
28 #include <glib.h> // for g_get_home_dir()
31 #include "base/basictypes.h"
32 #include "base/files/file_enumerator.h"
33 #include "base/files/file_path.h"
34 #include "base/files/scoped_file.h"
35 #include "base/logging.h"
36 #include "base/memory/scoped_ptr.h"
37 #include "base/memory/singleton.h"
38 #include "base/path_service.h"
39 #include "base/posix/eintr_wrapper.h"
40 #include "base/stl_util.h"
41 #include "base/strings/string_util.h"
42 #include "base/strings/stringprintf.h"
43 #include "base/strings/sys_string_conversions.h"
44 #include "base/strings/utf_string_conversions.h"
45 #include "base/sys_info.h"
46 #include "base/threading/thread_restrictions.h"
47 #include "base/time/time.h"
49 #if defined(OS_ANDROID)
50 #include "base/android/content_uri_utils.h"
51 #include "base/os_compat_android.h"
62 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
63 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
64 ThreadRestrictions::AssertIOAllowed();
65 return stat(path
, sb
);
67 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
68 ThreadRestrictions::AssertIOAllowed();
69 return lstat(path
, sb
);
71 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
72 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
73 ThreadRestrictions::AssertIOAllowed();
74 return stat64(path
, sb
);
76 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
77 ThreadRestrictions::AssertIOAllowed();
78 return lstat64(path
, sb
);
80 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
82 #if !defined(OS_NACL_NONSFI)
83 // Helper for NormalizeFilePath(), defined below.
84 bool RealPath(const FilePath
& path
, FilePath
* real_path
) {
85 ThreadRestrictions::AssertIOAllowed(); // For realpath().
86 FilePath::CharType buf
[PATH_MAX
];
87 if (!realpath(path
.value().c_str(), buf
))
90 *real_path
= FilePath(buf
);
94 // Helper for VerifyPathControlledByUser.
95 bool VerifySpecificPathControlledByUser(const FilePath
& path
,
97 const std::set
<gid_t
>& group_gids
) {
98 stat_wrapper_t stat_info
;
99 if (CallLstat(path
.value().c_str(), &stat_info
) != 0) {
100 DPLOG(ERROR
) << "Failed to get information on path "
105 if (S_ISLNK(stat_info
.st_mode
)) {
106 DLOG(ERROR
) << "Path " << path
.value()
107 << " is a symbolic link.";
111 if (stat_info
.st_uid
!= owner_uid
) {
112 DLOG(ERROR
) << "Path " << path
.value()
113 << " is owned by the wrong user.";
117 if ((stat_info
.st_mode
& S_IWGRP
) &&
118 !ContainsKey(group_gids
, stat_info
.st_gid
)) {
119 DLOG(ERROR
) << "Path " << path
.value()
120 << " is writable by an unprivileged group.";
124 if (stat_info
.st_mode
& S_IWOTH
) {
125 DLOG(ERROR
) << "Path " << path
.value()
126 << " is writable by any user.";
133 std::string
TempFileName() {
134 #if defined(OS_MACOSX)
135 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
138 #if defined(GOOGLE_CHROME_BUILD)
139 return std::string(".com.google.Chrome.XXXXXX");
141 return std::string(".org.chromium.Chromium.XXXXXX");
145 // Creates and opens a temporary file in |directory|, returning the
146 // file descriptor. |path| is set to the temporary file path.
147 // This function does NOT unlink() the file.
148 int CreateAndOpenFdForTemporaryFile(FilePath directory
, FilePath
* path
) {
149 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
150 *path
= directory
.Append(base::TempFileName());
151 const std::string
& tmpdir_string
= path
->value();
152 // this should be OK since mkstemp just replaces characters in place
153 char* buffer
= const_cast<char*>(tmpdir_string
.c_str());
155 return HANDLE_EINTR(mkstemp(buffer
));
158 #if defined(OS_LINUX)
159 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
160 // This depends on the mount options used for /dev/shm, which vary among
161 // different Linux distributions and possibly local configuration. It also
162 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
163 // but its kernel allows mprotect with PROT_EXEC anyway.
164 bool DetermineDevShmExecutable() {
168 ScopedFD
fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path
));
170 DeleteFile(path
, false);
171 long sysconf_result
= sysconf(_SC_PAGESIZE
);
172 CHECK_GE(sysconf_result
, 0);
173 size_t pagesize
= static_cast<size_t>(sysconf_result
);
174 CHECK_GE(sizeof(pagesize
), sizeof(sysconf_result
));
175 void* mapping
= mmap(NULL
, pagesize
, PROT_READ
, MAP_SHARED
, fd
.get(), 0);
176 if (mapping
!= MAP_FAILED
) {
177 if (mprotect(mapping
, pagesize
, PROT_READ
| PROT_EXEC
) == 0)
179 munmap(mapping
, pagesize
);
184 #endif // defined(OS_LINUX)
185 #endif // !defined(OS_NACL_NONSFI)
189 #if !defined(OS_NACL_NONSFI)
190 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
191 ThreadRestrictions::AssertIOAllowed();
192 char full_path
[PATH_MAX
];
193 if (realpath(input
.value().c_str(), full_path
) == NULL
)
195 return FilePath(full_path
);
198 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
199 // which works both with and without the recursive flag. I'm not sure we need
200 // that functionality. If not, remove from file_util_win.cc, otherwise add it
202 bool DeleteFile(const FilePath
& path
, bool recursive
) {
203 ThreadRestrictions::AssertIOAllowed();
204 const char* path_str
= path
.value().c_str();
205 stat_wrapper_t file_info
;
206 int test
= CallLstat(path_str
, &file_info
);
208 // The Windows version defines this condition as success.
209 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
212 if (!S_ISDIR(file_info
.st_mode
))
213 return (unlink(path_str
) == 0);
215 return (rmdir(path_str
) == 0);
218 std::stack
<std::string
> directories
;
219 directories
.push(path
.value());
220 FileEnumerator
traversal(path
, true,
221 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
222 FileEnumerator::SHOW_SYM_LINKS
);
223 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
224 current
= traversal
.Next()) {
225 if (traversal
.GetInfo().IsDirectory())
226 directories
.push(current
.value());
228 success
= (unlink(current
.value().c_str()) == 0);
231 while (success
&& !directories
.empty()) {
232 FilePath dir
= FilePath(directories
.top());
234 success
= (rmdir(dir
.value().c_str()) == 0);
239 bool ReplaceFile(const FilePath
& from_path
,
240 const FilePath
& to_path
,
241 File::Error
* error
) {
242 ThreadRestrictions::AssertIOAllowed();
243 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
246 *error
= File::OSErrorToFileError(errno
);
250 bool CopyDirectory(const FilePath
& from_path
,
251 const FilePath
& to_path
,
253 ThreadRestrictions::AssertIOAllowed();
254 // Some old callers of CopyDirectory want it to support wildcards.
255 // After some discussion, we decided to fix those callers.
256 // Break loudly here if anyone tries to do this.
257 DCHECK(to_path
.value().find('*') == std::string::npos
);
258 DCHECK(from_path
.value().find('*') == std::string::npos
);
260 if (from_path
.value().size() >= PATH_MAX
) {
264 // This function does not properly handle destinations within the source
265 FilePath real_to_path
= to_path
;
266 if (PathExists(real_to_path
)) {
267 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
268 if (real_to_path
.empty())
271 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
272 if (real_to_path
.empty())
275 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
276 if (real_from_path
.empty())
278 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
279 real_to_path
.value().compare(0, real_from_path
.value().size(),
280 real_from_path
.value()) == 0) {
284 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
286 traverse_type
|= FileEnumerator::DIRECTORIES
;
287 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
289 // We have to mimic windows behavior here. |to_path| may not exist yet,
290 // start the loop with |to_path|.
291 struct stat from_stat
;
292 FilePath current
= from_path
;
293 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
294 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
295 << from_path
.value() << " errno = " << errno
;
298 struct stat to_path_stat
;
299 FilePath from_path_base
= from_path
;
300 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
301 S_ISDIR(to_path_stat
.st_mode
)) {
302 // If the destination already exists and is a directory, then the
303 // top level of source needs to be copied.
304 from_path_base
= from_path
.DirName();
307 // The Windows version of this function assumes that non-recursive calls
308 // will always have a directory for from_path.
309 // TODO(maruel): This is not necessary anymore.
310 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
313 while (success
&& !current
.empty()) {
314 // current is the source path, including from_path, so append
315 // the suffix after from_path to to_path to create the target_path.
316 FilePath
target_path(to_path
);
317 if (from_path_base
!= current
) {
318 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
324 if (S_ISDIR(from_stat
.st_mode
)) {
325 if (mkdir(target_path
.value().c_str(),
326 (from_stat
.st_mode
& 01777) | S_IRUSR
| S_IXUSR
| S_IWUSR
) !=
329 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
330 << target_path
.value() << " errno = " << errno
;
333 } else if (S_ISREG(from_stat
.st_mode
)) {
334 if (!CopyFile(current
, target_path
)) {
335 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
336 << target_path
.value();
340 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
344 current
= traversal
.Next();
345 if (!current
.empty())
346 from_stat
= traversal
.GetInfo().stat();
351 #endif // !defined(OS_NACL_NONSFI)
353 bool PathExists(const FilePath
& path
) {
354 ThreadRestrictions::AssertIOAllowed();
355 #if defined(OS_ANDROID)
356 if (path
.IsContentUri()) {
357 return ContentUriExists(path
);
360 return access(path
.value().c_str(), F_OK
) == 0;
363 #if !defined(OS_NACL_NONSFI)
364 bool PathIsWritable(const FilePath
& path
) {
365 ThreadRestrictions::AssertIOAllowed();
366 return access(path
.value().c_str(), W_OK
) == 0;
368 #endif // !defined(OS_NACL_NONSFI)
370 bool DirectoryExists(const FilePath
& path
) {
371 ThreadRestrictions::AssertIOAllowed();
372 stat_wrapper_t file_info
;
373 if (CallStat(path
.value().c_str(), &file_info
) == 0)
374 return S_ISDIR(file_info
.st_mode
);
378 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
379 size_t total_read
= 0;
380 while (total_read
< bytes
) {
382 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
385 total_read
+= bytes_read
;
387 return total_read
== bytes
;
390 #if !defined(OS_NACL_NONSFI)
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_EQ(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) // Mac implementation is in file_util_mac.mm.
466 FilePath
GetHomeDir() {
467 #if defined(OS_CHROMEOS)
468 if (SysInfo::IsRunningOnChromeOS()) {
469 // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
470 // homedir once it becomes available. Return / as the safe option.
471 return FilePath("/");
475 const char* home_dir
= getenv("HOME");
476 if (home_dir
&& home_dir
[0])
477 return FilePath(home_dir
);
479 #if defined(OS_ANDROID)
480 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
481 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
482 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
483 // this may do I/O. However, it should be rare that $HOME is not defined and
484 // this is typically called from the path service which has no threading
485 // restrictions. The path service will cache the result which limits the
486 // badness of blocking on I/O. As a result, we don't have a thread
488 home_dir
= g_get_home_dir();
489 if (home_dir
&& home_dir
[0])
490 return FilePath(home_dir
);
498 return FilePath("/tmp");
500 #endif // !defined(OS_MACOSX)
502 bool CreateTemporaryFile(FilePath
* path
) {
503 ThreadRestrictions::AssertIOAllowed(); // For call to close().
505 if (!GetTempDir(&directory
))
507 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
514 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
515 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
519 FILE* file
= fdopen(fd
, "a+");
525 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
526 ThreadRestrictions::AssertIOAllowed(); // For call to close().
527 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
528 return ((fd
>= 0) && !IGNORE_EINTR(close(fd
)));
531 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
532 const FilePath::StringType
& name_tmpl
,
534 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
535 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
536 << "Directory name template must contain \"XXXXXX\".";
538 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
539 std::string sub_dir_string
= sub_dir
.value();
541 // this should be OK since mkdtemp just replaces characters in place
542 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
543 char* dtemp
= mkdtemp(buffer
);
545 DPLOG(ERROR
) << "mkdtemp";
548 *new_dir
= FilePath(dtemp
);
552 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
553 const FilePath::StringType
& prefix
,
555 FilePath::StringType mkdtemp_template
= prefix
;
556 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
557 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
560 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
561 FilePath
* new_temp_path
) {
563 if (!GetTempDir(&tmpdir
))
566 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
569 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
570 File::Error
* error
) {
571 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
572 std::vector
<FilePath
> subpaths
;
574 // Collect a list of all parent directories.
575 FilePath last_path
= full_path
;
576 subpaths
.push_back(full_path
);
577 for (FilePath path
= full_path
.DirName();
578 path
.value() != last_path
.value(); path
= path
.DirName()) {
579 subpaths
.push_back(path
);
583 // Iterate through the parents and create the missing ones.
584 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
585 i
!= subpaths
.rend(); ++i
) {
586 if (DirectoryExists(*i
))
588 if (mkdir(i
->value().c_str(), 0700) == 0)
590 // Mkdir failed, but it might have failed with EEXIST, or some other error
591 // due to the the directory appearing out of thin air. This can occur if
592 // two processes are trying to create the same file system tree at the same
593 // time. Check to see if it exists and make sure it is a directory.
594 int saved_errno
= errno
;
595 if (!DirectoryExists(*i
)) {
597 *error
= File::OSErrorToFileError(saved_errno
);
604 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
605 FilePath real_path_result
;
606 if (!RealPath(path
, &real_path_result
))
609 // To be consistant with windows, fail if |real_path_result| is a
611 stat_wrapper_t file_info
;
612 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
613 S_ISDIR(file_info
.st_mode
))
616 *normalized_path
= real_path_result
;
620 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
621 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
622 bool IsLink(const FilePath
& file_path
) {
624 // If we can't lstat the file, it's safe to assume that the file won't at
625 // least be a 'followable' link.
626 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
629 if (S_ISLNK(st
.st_mode
))
635 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
636 stat_wrapper_t file_info
;
637 #if defined(OS_ANDROID)
638 if (file_path
.IsContentUri()) {
639 File file
= OpenContentUriForRead(file_path
);
642 return file
.GetInfo(results
);
644 #endif // defined(OS_ANDROID)
645 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
647 #if defined(OS_ANDROID)
649 #endif // defined(OS_ANDROID)
651 results
->FromStat(file_info
);
654 #endif // !defined(OS_NACL_NONSFI)
656 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
657 ThreadRestrictions::AssertIOAllowed();
660 result
= fopen(filename
.value().c_str(), mode
);
661 } while (!result
&& errno
== EINTR
);
665 // NaCl doesn't implement system calls to open files directly.
666 #if !defined(OS_NACL)
667 FILE* FileToFILE(File file
, const char* mode
) {
668 FILE* stream
= fdopen(file
.GetPlatformFile(), mode
);
670 file
.TakePlatformFile();
673 #endif // !defined(OS_NACL)
675 int ReadFile(const FilePath
& filename
, char* data
, int max_size
) {
676 ThreadRestrictions::AssertIOAllowed();
677 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
681 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, max_size
));
682 if (IGNORE_EINTR(close(fd
)) < 0)
687 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
688 ThreadRestrictions::AssertIOAllowed();
689 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0640));
693 int bytes_written
= WriteFileDescriptor(fd
, data
, size
) ? size
: -1;
694 if (IGNORE_EINTR(close(fd
)) < 0)
696 return bytes_written
;
699 bool WriteFileDescriptor(const int fd
, const char* data
, int size
) {
700 // Allow for partial writes.
701 ssize_t bytes_written_total
= 0;
702 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
703 bytes_written_total
+= bytes_written_partial
) {
704 bytes_written_partial
=
705 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
706 size
- bytes_written_total
));
707 if (bytes_written_partial
< 0)
714 #if !defined(OS_NACL_NONSFI)
716 bool AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
717 ThreadRestrictions::AssertIOAllowed();
719 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
721 VPLOG(1) << "Unable to create file " << filename
.value();
725 // This call will either write all of the data or return false.
726 if (!WriteFileDescriptor(fd
, data
, size
)) {
727 VPLOG(1) << "Error while writing to file " << filename
.value();
731 if (IGNORE_EINTR(close(fd
)) < 0) {
732 VPLOG(1) << "Error while closing file " << filename
.value();
739 // Gets the current working directory for the process.
740 bool GetCurrentDirectory(FilePath
* dir
) {
741 // getcwd can return ENOENT, which implies it checks against the disk.
742 ThreadRestrictions::AssertIOAllowed();
744 char system_buffer
[PATH_MAX
] = "";
745 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
749 *dir
= FilePath(system_buffer
);
753 // Sets the current working directory for the process.
754 bool SetCurrentDirectory(const FilePath
& path
) {
755 ThreadRestrictions::AssertIOAllowed();
756 int ret
= chdir(path
.value().c_str());
760 bool VerifyPathControlledByUser(const FilePath
& base
,
761 const FilePath
& path
,
763 const std::set
<gid_t
>& group_gids
) {
764 if (base
!= path
&& !base
.IsParent(path
)) {
765 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
766 << base
.value() << "\", path = \"" << path
.value() << "\"";
770 std::vector
<FilePath::StringType
> base_components
;
771 std::vector
<FilePath::StringType
> path_components
;
773 base
.GetComponents(&base_components
);
774 path
.GetComponents(&path_components
);
776 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
777 for (ib
= base_components
.begin(), ip
= path_components
.begin();
778 ib
!= base_components
.end(); ++ib
, ++ip
) {
779 // |base| must be a subpath of |path|, so all components should match.
780 // If these CHECKs fail, look at the test that base is a parent of
781 // path at the top of this function.
782 DCHECK(ip
!= path_components
.end());
786 FilePath current_path
= base
;
787 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
790 for (; ip
!= path_components
.end(); ++ip
) {
791 current_path
= current_path
.Append(*ip
);
792 if (!VerifySpecificPathControlledByUser(
793 current_path
, owner_uid
, group_gids
))
799 #if defined(OS_MACOSX) && !defined(OS_IOS)
800 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
801 const unsigned kRootUid
= 0;
802 const FilePath
kFileSystemRoot("/");
804 // The name of the administrator group on mac os.
805 const char* const kAdminGroupNames
[] = {
810 // Reading the groups database may touch the file system.
811 ThreadRestrictions::AssertIOAllowed();
813 std::set
<gid_t
> allowed_group_ids
;
814 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
815 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
817 DPLOG(ERROR
) << "Could not get the group ID of group \""
818 << kAdminGroupNames
[i
] << "\".";
822 allowed_group_ids
.insert(group_record
->gr_gid
);
825 return VerifyPathControlledByUser(
826 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
828 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
830 int GetMaximumPathComponentLength(const FilePath
& path
) {
831 ThreadRestrictions::AssertIOAllowed();
832 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
835 #if !defined(OS_ANDROID)
836 // This is implemented in file_util_android.cc for that platform.
837 bool GetShmemTempDir(bool executable
, FilePath
* path
) {
838 #if defined(OS_LINUX)
839 bool use_dev_shm
= true;
841 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
842 use_dev_shm
= s_dev_shm_executable
;
845 *path
= FilePath("/dev/shm");
849 return GetTempDir(path
);
851 #endif // !defined(OS_ANDROID)
853 #if !defined(OS_MACOSX)
854 // Mac has its own implementation, this is for all other Posix systems.
855 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
856 ThreadRestrictions::AssertIOAllowed();
858 #if defined(OS_ANDROID)
859 if (from_path
.IsContentUri()) {
860 infile
= OpenContentUriForRead(from_path
);
862 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
865 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
867 if (!infile
.IsValid())
870 File
outfile(to_path
, File::FLAG_WRITE
| File::FLAG_CREATE_ALWAYS
);
871 if (!outfile
.IsValid())
874 const size_t kBufferSize
= 32768;
875 std::vector
<char> buffer(kBufferSize
);
879 ssize_t bytes_read
= infile
.ReadAtCurrentPos(&buffer
[0], buffer
.size());
880 if (bytes_read
< 0) {
886 // Allow for partial writes
887 ssize_t bytes_written_per_read
= 0;
889 ssize_t bytes_written_partial
= outfile
.WriteAtCurrentPos(
890 &buffer
[bytes_written_per_read
], bytes_read
- bytes_written_per_read
);
891 if (bytes_written_partial
< 0) {
895 bytes_written_per_read
+= bytes_written_partial
;
896 } while (bytes_written_per_read
< bytes_read
);
901 #endif // !defined(OS_MACOSX)
903 // -----------------------------------------------------------------------------
907 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
908 ThreadRestrictions::AssertIOAllowed();
909 // Windows compatibility: if to_path exists, from_path and to_path
910 // must be the same type, either both files, or both directories.
911 stat_wrapper_t to_file_info
;
912 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
913 stat_wrapper_t from_file_info
;
914 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
915 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
922 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
925 if (!CopyDirectory(from_path
, to_path
, true))
928 DeleteFile(from_path
, true);
932 } // namespace internal
934 #endif // !defined(OS_NACL_NONSFI)