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"
60 #if !defined(OS_NACL_NONSFI)
63 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
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
);
72 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
73 static int CallStat(const char *path
, stat_wrapper_t
*sb
) {
74 ThreadRestrictions::AssertIOAllowed();
75 return stat64(path
, sb
);
77 static int CallLstat(const char *path
, stat_wrapper_t
*sb
) {
78 ThreadRestrictions::AssertIOAllowed();
79 return lstat64(path
, sb
);
81 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
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)
188 FilePath
MakeAbsoluteFilePath(const FilePath
& input
) {
189 ThreadRestrictions::AssertIOAllowed();
190 char full_path
[PATH_MAX
];
191 if (realpath(input
.value().c_str(), full_path
) == NULL
)
193 return FilePath(full_path
);
196 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
197 // which works both with and without the recursive flag. I'm not sure we need
198 // that functionality. If not, remove from file_util_win.cc, otherwise add it
200 bool DeleteFile(const FilePath
& path
, bool recursive
) {
201 ThreadRestrictions::AssertIOAllowed();
202 const char* path_str
= path
.value().c_str();
203 stat_wrapper_t file_info
;
204 int test
= CallLstat(path_str
, &file_info
);
206 // The Windows version defines this condition as success.
207 bool ret
= (errno
== ENOENT
|| errno
== ENOTDIR
);
210 if (!S_ISDIR(file_info
.st_mode
))
211 return (unlink(path_str
) == 0);
213 return (rmdir(path_str
) == 0);
216 std::stack
<std::string
> directories
;
217 directories
.push(path
.value());
218 FileEnumerator
traversal(path
, true,
219 FileEnumerator::FILES
| FileEnumerator::DIRECTORIES
|
220 FileEnumerator::SHOW_SYM_LINKS
);
221 for (FilePath current
= traversal
.Next(); success
&& !current
.empty();
222 current
= traversal
.Next()) {
223 if (traversal
.GetInfo().IsDirectory())
224 directories
.push(current
.value());
226 success
= (unlink(current
.value().c_str()) == 0);
229 while (success
&& !directories
.empty()) {
230 FilePath dir
= FilePath(directories
.top());
232 success
= (rmdir(dir
.value().c_str()) == 0);
237 bool ReplaceFile(const FilePath
& from_path
,
238 const FilePath
& to_path
,
239 File::Error
* error
) {
240 ThreadRestrictions::AssertIOAllowed();
241 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
244 *error
= File::OSErrorToFileError(errno
);
248 bool CopyDirectory(const FilePath
& from_path
,
249 const FilePath
& to_path
,
251 ThreadRestrictions::AssertIOAllowed();
252 // Some old callers of CopyDirectory want it to support wildcards.
253 // After some discussion, we decided to fix those callers.
254 // Break loudly here if anyone tries to do this.
255 DCHECK(to_path
.value().find('*') == std::string::npos
);
256 DCHECK(from_path
.value().find('*') == std::string::npos
);
258 if (from_path
.value().size() >= PATH_MAX
) {
262 // This function does not properly handle destinations within the source
263 FilePath real_to_path
= to_path
;
264 if (PathExists(real_to_path
)) {
265 real_to_path
= MakeAbsoluteFilePath(real_to_path
);
266 if (real_to_path
.empty())
269 real_to_path
= MakeAbsoluteFilePath(real_to_path
.DirName());
270 if (real_to_path
.empty())
273 FilePath real_from_path
= MakeAbsoluteFilePath(from_path
);
274 if (real_from_path
.empty())
276 if (real_to_path
.value().size() >= real_from_path
.value().size() &&
277 real_to_path
.value().compare(0, real_from_path
.value().size(),
278 real_from_path
.value()) == 0) {
282 int traverse_type
= FileEnumerator::FILES
| FileEnumerator::SHOW_SYM_LINKS
;
284 traverse_type
|= FileEnumerator::DIRECTORIES
;
285 FileEnumerator
traversal(from_path
, recursive
, traverse_type
);
287 // We have to mimic windows behavior here. |to_path| may not exist yet,
288 // start the loop with |to_path|.
289 struct stat from_stat
;
290 FilePath current
= from_path
;
291 if (stat(from_path
.value().c_str(), &from_stat
) < 0) {
292 DLOG(ERROR
) << "CopyDirectory() couldn't stat source directory: "
293 << from_path
.value() << " errno = " << errno
;
296 struct stat to_path_stat
;
297 FilePath from_path_base
= from_path
;
298 if (recursive
&& stat(to_path
.value().c_str(), &to_path_stat
) == 0 &&
299 S_ISDIR(to_path_stat
.st_mode
)) {
300 // If the destination already exists and is a directory, then the
301 // top level of source needs to be copied.
302 from_path_base
= from_path
.DirName();
305 // The Windows version of this function assumes that non-recursive calls
306 // will always have a directory for from_path.
307 // TODO(maruel): This is not necessary anymore.
308 DCHECK(recursive
|| S_ISDIR(from_stat
.st_mode
));
311 while (success
&& !current
.empty()) {
312 // current is the source path, including from_path, so append
313 // the suffix after from_path to to_path to create the target_path.
314 FilePath
target_path(to_path
);
315 if (from_path_base
!= current
) {
316 if (!from_path_base
.AppendRelativePath(current
, &target_path
)) {
322 if (S_ISDIR(from_stat
.st_mode
)) {
323 if (mkdir(target_path
.value().c_str(),
324 (from_stat
.st_mode
& 01777) | S_IRUSR
| S_IXUSR
| S_IWUSR
) !=
327 DLOG(ERROR
) << "CopyDirectory() couldn't create directory: "
328 << target_path
.value() << " errno = " << errno
;
331 } else if (S_ISREG(from_stat
.st_mode
)) {
332 if (!CopyFile(current
, target_path
)) {
333 DLOG(ERROR
) << "CopyDirectory() couldn't create file: "
334 << target_path
.value();
338 DLOG(WARNING
) << "CopyDirectory() skipping non-regular file: "
342 current
= traversal
.Next();
343 if (!current
.empty())
344 from_stat
= traversal
.GetInfo().stat();
349 #endif // !defined(OS_NACL_NONSFI)
351 bool PathExists(const FilePath
& path
) {
352 ThreadRestrictions::AssertIOAllowed();
353 #if defined(OS_ANDROID)
354 if (path
.IsContentUri()) {
355 return ContentUriExists(path
);
358 return access(path
.value().c_str(), F_OK
) == 0;
361 #if !defined(OS_NACL_NONSFI)
362 bool PathIsWritable(const FilePath
& path
) {
363 ThreadRestrictions::AssertIOAllowed();
364 return access(path
.value().c_str(), W_OK
) == 0;
367 bool DirectoryExists(const FilePath
& path
) {
368 ThreadRestrictions::AssertIOAllowed();
369 stat_wrapper_t file_info
;
370 if (CallStat(path
.value().c_str(), &file_info
) == 0)
371 return S_ISDIR(file_info
.st_mode
);
374 #endif // !defined(OS_NACL_NONSFI)
376 bool ReadFromFD(int fd
, char* buffer
, size_t bytes
) {
377 size_t total_read
= 0;
378 while (total_read
< bytes
) {
380 HANDLE_EINTR(read(fd
, buffer
+ total_read
, bytes
- total_read
));
383 total_read
+= bytes_read
;
385 return total_read
== bytes
;
388 #if !defined(OS_NACL_NONSFI)
389 bool CreateSymbolicLink(const FilePath
& target_path
,
390 const FilePath
& symlink_path
) {
391 DCHECK(!symlink_path
.empty());
392 DCHECK(!target_path
.empty());
393 return ::symlink(target_path
.value().c_str(),
394 symlink_path
.value().c_str()) != -1;
397 bool ReadSymbolicLink(const FilePath
& symlink_path
, FilePath
* target_path
) {
398 DCHECK(!symlink_path
.empty());
401 ssize_t count
= ::readlink(symlink_path
.value().c_str(), buf
, arraysize(buf
));
404 target_path
->clear();
408 *target_path
= FilePath(FilePath::StringType(buf
, count
));
412 bool GetPosixFilePermissions(const FilePath
& path
, int* mode
) {
413 ThreadRestrictions::AssertIOAllowed();
416 stat_wrapper_t file_info
;
417 // Uses stat(), because on symbolic link, lstat() does not return valid
418 // permission bits in st_mode
419 if (CallStat(path
.value().c_str(), &file_info
) != 0)
422 *mode
= file_info
.st_mode
& FILE_PERMISSION_MASK
;
426 bool SetPosixFilePermissions(const FilePath
& path
,
428 ThreadRestrictions::AssertIOAllowed();
429 DCHECK_EQ(mode
& ~FILE_PERMISSION_MASK
, 0);
431 // Calls stat() so that we can preserve the higher bits like S_ISGID.
432 stat_wrapper_t stat_buf
;
433 if (CallStat(path
.value().c_str(), &stat_buf
) != 0)
436 // Clears the existing permission bits, and adds the new ones.
437 mode_t updated_mode_bits
= stat_buf
.st_mode
& ~FILE_PERMISSION_MASK
;
438 updated_mode_bits
|= mode
& FILE_PERMISSION_MASK
;
440 if (HANDLE_EINTR(chmod(path
.value().c_str(), updated_mode_bits
)) != 0)
446 #if !defined(OS_MACOSX)
447 // This is implemented in file_util_mac.mm for Mac.
448 bool GetTempDir(FilePath
* path
) {
449 const char* tmp
= getenv("TMPDIR");
451 *path
= FilePath(tmp
);
453 #if defined(OS_ANDROID)
454 return PathService::Get(base::DIR_CACHE
, path
);
456 *path
= FilePath("/tmp");
461 #endif // !defined(OS_MACOSX)
463 #if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
464 FilePath
GetHomeDir() {
465 #if defined(OS_CHROMEOS)
466 if (SysInfo::IsRunningOnChromeOS()) {
467 // On Chrome OS chrome::DIR_USER_DATA is overridden with a primary user
468 // homedir once it becomes available. Return / as the safe option.
469 return FilePath("/");
473 const char* home_dir
= getenv("HOME");
474 if (home_dir
&& home_dir
[0])
475 return FilePath(home_dir
);
477 #if defined(OS_ANDROID)
478 DLOG(WARNING
) << "OS_ANDROID: Home directory lookup not yet implemented.";
479 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
480 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
481 // this may do I/O. However, it should be rare that $HOME is not defined and
482 // this is typically called from the path service which has no threading
483 // restrictions. The path service will cache the result which limits the
484 // badness of blocking on I/O. As a result, we don't have a thread
486 home_dir
= g_get_home_dir();
487 if (home_dir
&& home_dir
[0])
488 return FilePath(home_dir
);
496 return FilePath("/tmp");
498 #endif // !defined(OS_MACOSX)
500 bool CreateTemporaryFile(FilePath
* path
) {
501 ThreadRestrictions::AssertIOAllowed(); // For call to close().
503 if (!GetTempDir(&directory
))
505 int fd
= CreateAndOpenFdForTemporaryFile(directory
, path
);
512 FILE* CreateAndOpenTemporaryFileInDir(const FilePath
& dir
, FilePath
* path
) {
513 int fd
= CreateAndOpenFdForTemporaryFile(dir
, path
);
517 FILE* file
= fdopen(fd
, "a+");
523 bool CreateTemporaryFileInDir(const FilePath
& dir
, FilePath
* temp_file
) {
524 ThreadRestrictions::AssertIOAllowed(); // For call to close().
525 int fd
= CreateAndOpenFdForTemporaryFile(dir
, temp_file
);
526 return ((fd
>= 0) && !IGNORE_EINTR(close(fd
)));
529 static bool CreateTemporaryDirInDirImpl(const FilePath
& base_dir
,
530 const FilePath::StringType
& name_tmpl
,
532 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
533 DCHECK(name_tmpl
.find("XXXXXX") != FilePath::StringType::npos
)
534 << "Directory name template must contain \"XXXXXX\".";
536 FilePath sub_dir
= base_dir
.Append(name_tmpl
);
537 std::string sub_dir_string
= sub_dir
.value();
539 // this should be OK since mkdtemp just replaces characters in place
540 char* buffer
= const_cast<char*>(sub_dir_string
.c_str());
541 char* dtemp
= mkdtemp(buffer
);
543 DPLOG(ERROR
) << "mkdtemp";
546 *new_dir
= FilePath(dtemp
);
550 bool CreateTemporaryDirInDir(const FilePath
& base_dir
,
551 const FilePath::StringType
& prefix
,
553 FilePath::StringType mkdtemp_template
= prefix
;
554 mkdtemp_template
.append(FILE_PATH_LITERAL("XXXXXX"));
555 return CreateTemporaryDirInDirImpl(base_dir
, mkdtemp_template
, new_dir
);
558 bool CreateNewTempDirectory(const FilePath::StringType
& prefix
,
559 FilePath
* new_temp_path
) {
561 if (!GetTempDir(&tmpdir
))
564 return CreateTemporaryDirInDirImpl(tmpdir
, TempFileName(), new_temp_path
);
567 bool CreateDirectoryAndGetError(const FilePath
& full_path
,
568 File::Error
* error
) {
569 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
570 std::vector
<FilePath
> subpaths
;
572 // Collect a list of all parent directories.
573 FilePath last_path
= full_path
;
574 subpaths
.push_back(full_path
);
575 for (FilePath path
= full_path
.DirName();
576 path
.value() != last_path
.value(); path
= path
.DirName()) {
577 subpaths
.push_back(path
);
581 // Iterate through the parents and create the missing ones.
582 for (std::vector
<FilePath
>::reverse_iterator i
= subpaths
.rbegin();
583 i
!= subpaths
.rend(); ++i
) {
584 if (DirectoryExists(*i
))
586 if (mkdir(i
->value().c_str(), 0700) == 0)
588 // Mkdir failed, but it might have failed with EEXIST, or some other error
589 // due to the the directory appearing out of thin air. This can occur if
590 // two processes are trying to create the same file system tree at the same
591 // time. Check to see if it exists and make sure it is a directory.
592 int saved_errno
= errno
;
593 if (!DirectoryExists(*i
)) {
595 *error
= File::OSErrorToFileError(saved_errno
);
602 bool NormalizeFilePath(const FilePath
& path
, FilePath
* normalized_path
) {
603 FilePath real_path_result
;
604 if (!RealPath(path
, &real_path_result
))
607 // To be consistant with windows, fail if |real_path_result| is a
609 stat_wrapper_t file_info
;
610 if (CallStat(real_path_result
.value().c_str(), &file_info
) != 0 ||
611 S_ISDIR(file_info
.st_mode
))
614 *normalized_path
= real_path_result
;
618 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
619 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
620 bool IsLink(const FilePath
& file_path
) {
622 // If we can't lstat the file, it's safe to assume that the file won't at
623 // least be a 'followable' link.
624 if (CallLstat(file_path
.value().c_str(), &st
) != 0)
627 if (S_ISLNK(st
.st_mode
))
633 bool GetFileInfo(const FilePath
& file_path
, File::Info
* results
) {
634 stat_wrapper_t file_info
;
635 #if defined(OS_ANDROID)
636 if (file_path
.IsContentUri()) {
637 File file
= OpenContentUriForRead(file_path
);
640 return file
.GetInfo(results
);
642 #endif // defined(OS_ANDROID)
643 if (CallStat(file_path
.value().c_str(), &file_info
) != 0)
645 #if defined(OS_ANDROID)
647 #endif // defined(OS_ANDROID)
649 results
->FromStat(file_info
);
653 FILE* OpenFile(const FilePath
& filename
, const char* mode
) {
654 ThreadRestrictions::AssertIOAllowed();
657 result
= fopen(filename
.value().c_str(), mode
);
658 } while (!result
&& errno
== EINTR
);
662 // NaCl doesn't implement system calls to open files directly.
663 #if !defined(OS_NACL)
664 FILE* FileToFILE(File file
, const char* mode
) {
665 FILE* stream
= fdopen(file
.GetPlatformFile(), mode
);
667 file
.TakePlatformFile();
670 #endif // !defined(OS_NACL)
672 int ReadFile(const FilePath
& filename
, char* data
, int max_size
) {
673 ThreadRestrictions::AssertIOAllowed();
674 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_RDONLY
));
678 ssize_t bytes_read
= HANDLE_EINTR(read(fd
, data
, max_size
));
679 if (IGNORE_EINTR(close(fd
)) < 0)
684 int WriteFile(const FilePath
& filename
, const char* data
, int size
) {
685 ThreadRestrictions::AssertIOAllowed();
686 int fd
= HANDLE_EINTR(creat(filename
.value().c_str(), 0640));
690 int bytes_written
= WriteFileDescriptor(fd
, data
, size
) ? size
: -1;
691 if (IGNORE_EINTR(close(fd
)) < 0)
693 return bytes_written
;
696 bool WriteFileDescriptor(const int fd
, const char* data
, int size
) {
697 // Allow for partial writes.
698 ssize_t bytes_written_total
= 0;
699 for (ssize_t bytes_written_partial
= 0; bytes_written_total
< size
;
700 bytes_written_total
+= bytes_written_partial
) {
701 bytes_written_partial
=
702 HANDLE_EINTR(write(fd
, data
+ bytes_written_total
,
703 size
- bytes_written_total
));
704 if (bytes_written_partial
< 0)
711 bool AppendToFile(const FilePath
& filename
, const char* data
, int size
) {
712 ThreadRestrictions::AssertIOAllowed();
714 int fd
= HANDLE_EINTR(open(filename
.value().c_str(), O_WRONLY
| O_APPEND
));
716 VPLOG(1) << "Unable to create file " << filename
.value();
720 // This call will either write all of the data or return false.
721 if (!WriteFileDescriptor(fd
, data
, size
)) {
722 VPLOG(1) << "Error while writing to file " << filename
.value();
726 if (IGNORE_EINTR(close(fd
)) < 0) {
727 VPLOG(1) << "Error while closing file " << filename
.value();
734 // Gets the current working directory for the process.
735 bool GetCurrentDirectory(FilePath
* dir
) {
736 // getcwd can return ENOENT, which implies it checks against the disk.
737 ThreadRestrictions::AssertIOAllowed();
739 char system_buffer
[PATH_MAX
] = "";
740 if (!getcwd(system_buffer
, sizeof(system_buffer
))) {
744 *dir
= FilePath(system_buffer
);
748 // Sets the current working directory for the process.
749 bool SetCurrentDirectory(const FilePath
& path
) {
750 ThreadRestrictions::AssertIOAllowed();
751 int ret
= chdir(path
.value().c_str());
755 bool VerifyPathControlledByUser(const FilePath
& base
,
756 const FilePath
& path
,
758 const std::set
<gid_t
>& group_gids
) {
759 if (base
!= path
&& !base
.IsParent(path
)) {
760 DLOG(ERROR
) << "|base| must be a subdirectory of |path|. base = \""
761 << base
.value() << "\", path = \"" << path
.value() << "\"";
765 std::vector
<FilePath::StringType
> base_components
;
766 std::vector
<FilePath::StringType
> path_components
;
768 base
.GetComponents(&base_components
);
769 path
.GetComponents(&path_components
);
771 std::vector
<FilePath::StringType
>::const_iterator ib
, ip
;
772 for (ib
= base_components
.begin(), ip
= path_components
.begin();
773 ib
!= base_components
.end(); ++ib
, ++ip
) {
774 // |base| must be a subpath of |path|, so all components should match.
775 // If these CHECKs fail, look at the test that base is a parent of
776 // path at the top of this function.
777 DCHECK(ip
!= path_components
.end());
781 FilePath current_path
= base
;
782 if (!VerifySpecificPathControlledByUser(current_path
, owner_uid
, group_gids
))
785 for (; ip
!= path_components
.end(); ++ip
) {
786 current_path
= current_path
.Append(*ip
);
787 if (!VerifySpecificPathControlledByUser(
788 current_path
, owner_uid
, group_gids
))
794 #if defined(OS_MACOSX) && !defined(OS_IOS)
795 bool VerifyPathControlledByAdmin(const FilePath
& path
) {
796 const unsigned kRootUid
= 0;
797 const FilePath
kFileSystemRoot("/");
799 // The name of the administrator group on mac os.
800 const char* const kAdminGroupNames
[] = {
805 // Reading the groups database may touch the file system.
806 ThreadRestrictions::AssertIOAllowed();
808 std::set
<gid_t
> allowed_group_ids
;
809 for (int i
= 0, ie
= arraysize(kAdminGroupNames
); i
< ie
; ++i
) {
810 struct group
*group_record
= getgrnam(kAdminGroupNames
[i
]);
812 DPLOG(ERROR
) << "Could not get the group ID of group \""
813 << kAdminGroupNames
[i
] << "\".";
817 allowed_group_ids
.insert(group_record
->gr_gid
);
820 return VerifyPathControlledByUser(
821 kFileSystemRoot
, path
, kRootUid
, allowed_group_ids
);
823 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
825 int GetMaximumPathComponentLength(const FilePath
& path
) {
826 ThreadRestrictions::AssertIOAllowed();
827 return pathconf(path
.value().c_str(), _PC_NAME_MAX
);
830 #if !defined(OS_ANDROID)
831 // This is implemented in file_util_android.cc for that platform.
832 bool GetShmemTempDir(bool executable
, FilePath
* path
) {
833 #if defined(OS_LINUX)
834 bool use_dev_shm
= true;
836 static const bool s_dev_shm_executable
= DetermineDevShmExecutable();
837 use_dev_shm
= s_dev_shm_executable
;
840 *path
= FilePath("/dev/shm");
844 return GetTempDir(path
);
846 #endif // !defined(OS_ANDROID)
848 #if !defined(OS_MACOSX)
849 // Mac has its own implementation, this is for all other Posix systems.
850 bool CopyFile(const FilePath
& from_path
, const FilePath
& to_path
) {
851 ThreadRestrictions::AssertIOAllowed();
853 #if defined(OS_ANDROID)
854 if (from_path
.IsContentUri()) {
855 infile
= OpenContentUriForRead(from_path
);
857 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
860 infile
= File(from_path
, File::FLAG_OPEN
| File::FLAG_READ
);
862 if (!infile
.IsValid())
865 File
outfile(to_path
, File::FLAG_WRITE
| File::FLAG_CREATE_ALWAYS
);
866 if (!outfile
.IsValid())
869 const size_t kBufferSize
= 32768;
870 std::vector
<char> buffer(kBufferSize
);
874 ssize_t bytes_read
= infile
.ReadAtCurrentPos(&buffer
[0], buffer
.size());
875 if (bytes_read
< 0) {
881 // Allow for partial writes
882 ssize_t bytes_written_per_read
= 0;
884 ssize_t bytes_written_partial
= outfile
.WriteAtCurrentPos(
885 &buffer
[bytes_written_per_read
], bytes_read
- bytes_written_per_read
);
886 if (bytes_written_partial
< 0) {
890 bytes_written_per_read
+= bytes_written_partial
;
891 } while (bytes_written_per_read
< bytes_read
);
896 #endif // !defined(OS_MACOSX)
898 // -----------------------------------------------------------------------------
902 bool MoveUnsafe(const FilePath
& from_path
, const FilePath
& to_path
) {
903 ThreadRestrictions::AssertIOAllowed();
904 // Windows compatibility: if to_path exists, from_path and to_path
905 // must be the same type, either both files, or both directories.
906 stat_wrapper_t to_file_info
;
907 if (CallStat(to_path
.value().c_str(), &to_file_info
) == 0) {
908 stat_wrapper_t from_file_info
;
909 if (CallStat(from_path
.value().c_str(), &from_file_info
) == 0) {
910 if (S_ISDIR(to_file_info
.st_mode
) != S_ISDIR(from_file_info
.st_mode
))
917 if (rename(from_path
.value().c_str(), to_path
.value().c_str()) == 0)
920 if (!CopyDirectory(from_path
, to_path
, true))
923 DeleteFile(from_path
, true);
927 } // namespace internal
929 #endif // !defined(OS_NACL_NONSFI)