Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / base / files / file_util_posix.cc
blobffa79a45f42d64c933801895c918134f3502dc77
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"
7 #include <dirent.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <libgen.h>
11 #include <limits.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/errno.h>
16 #include <sys/mman.h>
17 #include <sys/param.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <time.h>
22 #include <unistd.h>
24 #if defined(OS_MACOSX)
25 #include <AvailabilityMacros.h>
26 #include "base/mac/foundation_util.h"
27 #endif
29 #include "base/basictypes.h"
30 #include "base/files/file_enumerator.h"
31 #include "base/files/file_path.h"
32 #include "base/files/scoped_file.h"
33 #include "base/logging.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/memory/singleton.h"
36 #include "base/path_service.h"
37 #include "base/posix/eintr_wrapper.h"
38 #include "base/stl_util.h"
39 #include "base/strings/string_util.h"
40 #include "base/strings/stringprintf.h"
41 #include "base/strings/sys_string_conversions.h"
42 #include "base/strings/utf_string_conversions.h"
43 #include "base/sys_info.h"
44 #include "base/threading/thread_restrictions.h"
45 #include "base/time/time.h"
47 #if defined(OS_ANDROID)
48 #include "base/android/content_uri_utils.h"
49 #include "base/os_compat_android.h"
50 #endif
52 #if !defined(OS_IOS)
53 #include <grp.h>
54 #endif
56 namespace base {
58 namespace {
60 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
61 static int CallStat(const char *path, stat_wrapper_t *sb) {
62 ThreadRestrictions::AssertIOAllowed();
63 return stat(path, sb);
65 static int CallLstat(const char *path, stat_wrapper_t *sb) {
66 ThreadRestrictions::AssertIOAllowed();
67 return lstat(path, sb);
69 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
70 static int CallStat(const char *path, stat_wrapper_t *sb) {
71 ThreadRestrictions::AssertIOAllowed();
72 return stat64(path, sb);
74 static int CallLstat(const char *path, stat_wrapper_t *sb) {
75 ThreadRestrictions::AssertIOAllowed();
76 return lstat64(path, sb);
78 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
80 #if !defined(OS_NACL_NONSFI)
81 // Helper for NormalizeFilePath(), defined below.
82 bool RealPath(const FilePath& path, FilePath* real_path) {
83 ThreadRestrictions::AssertIOAllowed(); // For realpath().
84 FilePath::CharType buf[PATH_MAX];
85 if (!realpath(path.value().c_str(), buf))
86 return false;
88 *real_path = FilePath(buf);
89 return true;
92 // Helper for VerifyPathControlledByUser.
93 bool VerifySpecificPathControlledByUser(const FilePath& path,
94 uid_t owner_uid,
95 const std::set<gid_t>& group_gids) {
96 stat_wrapper_t stat_info;
97 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
98 DPLOG(ERROR) << "Failed to get information on path "
99 << path.value();
100 return false;
103 if (S_ISLNK(stat_info.st_mode)) {
104 DLOG(ERROR) << "Path " << path.value()
105 << " is a symbolic link.";
106 return false;
109 if (stat_info.st_uid != owner_uid) {
110 DLOG(ERROR) << "Path " << path.value()
111 << " is owned by the wrong user.";
112 return false;
115 if ((stat_info.st_mode & S_IWGRP) &&
116 !ContainsKey(group_gids, stat_info.st_gid)) {
117 DLOG(ERROR) << "Path " << path.value()
118 << " is writable by an unprivileged group.";
119 return false;
122 if (stat_info.st_mode & S_IWOTH) {
123 DLOG(ERROR) << "Path " << path.value()
124 << " is writable by any user.";
125 return false;
128 return true;
131 std::string TempFileName() {
132 #if defined(OS_MACOSX)
133 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
134 #endif
136 #if defined(GOOGLE_CHROME_BUILD)
137 return std::string(".com.google.Chrome.XXXXXX");
138 #else
139 return std::string(".org.chromium.Chromium.XXXXXX");
140 #endif
143 // Creates and opens a temporary file in |directory|, returning the
144 // file descriptor. |path| is set to the temporary file path.
145 // This function does NOT unlink() the file.
146 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
147 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
148 *path = directory.Append(base::TempFileName());
149 const std::string& tmpdir_string = path->value();
150 // this should be OK since mkstemp just replaces characters in place
151 char* buffer = const_cast<char*>(tmpdir_string.c_str());
153 return HANDLE_EINTR(mkstemp(buffer));
156 #if defined(OS_LINUX)
157 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
158 // This depends on the mount options used for /dev/shm, which vary among
159 // different Linux distributions and possibly local configuration. It also
160 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
161 // but its kernel allows mprotect with PROT_EXEC anyway.
162 bool DetermineDevShmExecutable() {
163 bool result = false;
164 FilePath path;
166 ScopedFD fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path));
167 if (fd.is_valid()) {
168 DeleteFile(path, false);
169 long sysconf_result = sysconf(_SC_PAGESIZE);
170 CHECK_GE(sysconf_result, 0);
171 size_t pagesize = static_cast<size_t>(sysconf_result);
172 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
173 void* mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
174 if (mapping != MAP_FAILED) {
175 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
176 result = true;
177 munmap(mapping, pagesize);
180 return result;
182 #endif // defined(OS_LINUX)
183 #endif // !defined(OS_NACL_NONSFI)
185 } // namespace
187 #if !defined(OS_NACL_NONSFI)
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)
192 return FilePath();
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
199 // here.
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);
205 if (test != 0) {
206 // The Windows version defines this condition as success.
207 bool ret = (errno == ENOENT || errno == ENOTDIR);
208 return ret;
210 if (!S_ISDIR(file_info.st_mode))
211 return (unlink(path_str) == 0);
212 if (!recursive)
213 return (rmdir(path_str) == 0);
215 bool success = true;
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());
225 else
226 success = (unlink(current.value().c_str()) == 0);
229 while (success && !directories.empty()) {
230 FilePath dir = FilePath(directories.top());
231 directories.pop();
232 success = (rmdir(dir.value().c_str()) == 0);
234 return success;
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)
242 return true;
243 if (error)
244 *error = File::OSErrorToFileError(errno);
245 return false;
248 bool CopyDirectory(const FilePath& from_path,
249 const FilePath& to_path,
250 bool recursive) {
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) {
259 return false;
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())
267 return false;
268 } else {
269 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
270 if (real_to_path.empty())
271 return false;
273 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
274 if (real_from_path.empty())
275 return false;
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) {
279 return false;
282 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
283 if (recursive)
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;
294 return false;
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));
310 bool success = true;
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)) {
317 success = false;
318 break;
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) !=
325 0 &&
326 errno != EEXIST) {
327 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
328 << target_path.value() << " errno = " << errno;
329 success = false;
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();
335 success = false;
337 } else {
338 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
339 << current.value();
342 current = traversal.Next();
343 if (!current.empty())
344 from_stat = traversal.GetInfo().stat();
347 return success;
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);
357 #endif
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;
366 #endif // !defined(OS_NACL_NONSFI)
368 bool DirectoryExists(const FilePath& path) {
369 ThreadRestrictions::AssertIOAllowed();
370 stat_wrapper_t file_info;
371 if (CallStat(path.value().c_str(), &file_info) == 0)
372 return S_ISDIR(file_info.st_mode);
373 return false;
376 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
377 size_t total_read = 0;
378 while (total_read < bytes) {
379 ssize_t bytes_read =
380 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
381 if (bytes_read <= 0)
382 break;
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());
399 DCHECK(target_path);
400 char buf[PATH_MAX];
401 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
403 if (count <= 0) {
404 target_path->clear();
405 return false;
408 *target_path = FilePath(FilePath::StringType(buf, count));
409 return true;
412 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
413 ThreadRestrictions::AssertIOAllowed();
414 DCHECK(mode);
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)
420 return false;
422 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
423 return true;
426 bool SetPosixFilePermissions(const FilePath& path,
427 int mode) {
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)
434 return false;
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)
441 return false;
443 return true;
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");
450 if (tmp) {
451 *path = FilePath(tmp);
452 } else {
453 #if defined(OS_ANDROID)
454 return PathService::Get(base::DIR_CACHE, path);
455 #else
456 *path = FilePath("/tmp");
457 #endif
459 return true;
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("/");
471 #endif
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 #endif
481 FilePath rv;
482 if (GetTempDir(&rv))
483 return rv;
485 // Last resort.
486 return FilePath("/tmp");
488 #endif // !defined(OS_MACOSX)
490 bool CreateTemporaryFile(FilePath* path) {
491 ThreadRestrictions::AssertIOAllowed(); // For call to close().
492 FilePath directory;
493 if (!GetTempDir(&directory))
494 return false;
495 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
496 if (fd < 0)
497 return false;
498 close(fd);
499 return true;
502 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
503 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
504 if (fd < 0)
505 return NULL;
507 FILE* file = fdopen(fd, "a+");
508 if (!file)
509 close(fd);
510 return file;
513 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
514 ThreadRestrictions::AssertIOAllowed(); // For call to close().
515 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
516 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
519 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
520 const FilePath::StringType& name_tmpl,
521 FilePath* new_dir) {
522 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
523 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
524 << "Directory name template must contain \"XXXXXX\".";
526 FilePath sub_dir = base_dir.Append(name_tmpl);
527 std::string sub_dir_string = sub_dir.value();
529 // this should be OK since mkdtemp just replaces characters in place
530 char* buffer = const_cast<char*>(sub_dir_string.c_str());
531 char* dtemp = mkdtemp(buffer);
532 if (!dtemp) {
533 DPLOG(ERROR) << "mkdtemp";
534 return false;
536 *new_dir = FilePath(dtemp);
537 return true;
540 bool CreateTemporaryDirInDir(const FilePath& base_dir,
541 const FilePath::StringType& prefix,
542 FilePath* new_dir) {
543 FilePath::StringType mkdtemp_template = prefix;
544 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
545 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
548 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
549 FilePath* new_temp_path) {
550 FilePath tmpdir;
551 if (!GetTempDir(&tmpdir))
552 return false;
554 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
557 bool CreateDirectoryAndGetError(const FilePath& full_path,
558 File::Error* error) {
559 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
560 std::vector<FilePath> subpaths;
562 // Collect a list of all parent directories.
563 FilePath last_path = full_path;
564 subpaths.push_back(full_path);
565 for (FilePath path = full_path.DirName();
566 path.value() != last_path.value(); path = path.DirName()) {
567 subpaths.push_back(path);
568 last_path = path;
571 // Iterate through the parents and create the missing ones.
572 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
573 i != subpaths.rend(); ++i) {
574 if (DirectoryExists(*i))
575 continue;
576 if (mkdir(i->value().c_str(), 0700) == 0)
577 continue;
578 // Mkdir failed, but it might have failed with EEXIST, or some other error
579 // due to the the directory appearing out of thin air. This can occur if
580 // two processes are trying to create the same file system tree at the same
581 // time. Check to see if it exists and make sure it is a directory.
582 int saved_errno = errno;
583 if (!DirectoryExists(*i)) {
584 if (error)
585 *error = File::OSErrorToFileError(saved_errno);
586 return false;
589 return true;
592 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
593 FilePath real_path_result;
594 if (!RealPath(path, &real_path_result))
595 return false;
597 // To be consistant with windows, fail if |real_path_result| is a
598 // directory.
599 stat_wrapper_t file_info;
600 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
601 S_ISDIR(file_info.st_mode))
602 return false;
604 *normalized_path = real_path_result;
605 return true;
608 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
609 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
610 bool IsLink(const FilePath& file_path) {
611 stat_wrapper_t st;
612 // If we can't lstat the file, it's safe to assume that the file won't at
613 // least be a 'followable' link.
614 if (CallLstat(file_path.value().c_str(), &st) != 0)
615 return false;
617 if (S_ISLNK(st.st_mode))
618 return true;
619 else
620 return false;
623 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
624 stat_wrapper_t file_info;
625 #if defined(OS_ANDROID)
626 if (file_path.IsContentUri()) {
627 File file = OpenContentUriForRead(file_path);
628 if (!file.IsValid())
629 return false;
630 return file.GetInfo(results);
631 } else {
632 #endif // defined(OS_ANDROID)
633 if (CallStat(file_path.value().c_str(), &file_info) != 0)
634 return false;
635 #if defined(OS_ANDROID)
637 #endif // defined(OS_ANDROID)
639 results->FromStat(file_info);
640 return true;
642 #endif // !defined(OS_NACL_NONSFI)
644 FILE* OpenFile(const FilePath& filename, const char* mode) {
645 ThreadRestrictions::AssertIOAllowed();
646 FILE* result = NULL;
647 do {
648 result = fopen(filename.value().c_str(), mode);
649 } while (!result && errno == EINTR);
650 return result;
653 // NaCl doesn't implement system calls to open files directly.
654 #if !defined(OS_NACL)
655 FILE* FileToFILE(File file, const char* mode) {
656 FILE* stream = fdopen(file.GetPlatformFile(), mode);
657 if (stream)
658 file.TakePlatformFile();
659 return stream;
661 #endif // !defined(OS_NACL)
663 int ReadFile(const FilePath& filename, char* data, int max_size) {
664 ThreadRestrictions::AssertIOAllowed();
665 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
666 if (fd < 0)
667 return -1;
669 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, max_size));
670 if (IGNORE_EINTR(close(fd)) < 0)
671 return -1;
672 return bytes_read;
675 int WriteFile(const FilePath& filename, const char* data, int size) {
676 ThreadRestrictions::AssertIOAllowed();
677 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0640));
678 if (fd < 0)
679 return -1;
681 int bytes_written = WriteFileDescriptor(fd, data, size) ? size : -1;
682 if (IGNORE_EINTR(close(fd)) < 0)
683 return -1;
684 return bytes_written;
687 bool WriteFileDescriptor(const int fd, const char* data, int size) {
688 // Allow for partial writes.
689 ssize_t bytes_written_total = 0;
690 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
691 bytes_written_total += bytes_written_partial) {
692 bytes_written_partial =
693 HANDLE_EINTR(write(fd, data + bytes_written_total,
694 size - bytes_written_total));
695 if (bytes_written_partial < 0)
696 return false;
699 return true;
702 #if !defined(OS_NACL_NONSFI)
704 bool AppendToFile(const FilePath& filename, const char* data, int size) {
705 ThreadRestrictions::AssertIOAllowed();
706 bool ret = true;
707 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
708 if (fd < 0) {
709 VPLOG(1) << "Unable to create file " << filename.value();
710 return false;
713 // This call will either write all of the data or return false.
714 if (!WriteFileDescriptor(fd, data, size)) {
715 VPLOG(1) << "Error while writing to file " << filename.value();
716 ret = false;
719 if (IGNORE_EINTR(close(fd)) < 0) {
720 VPLOG(1) << "Error while closing file " << filename.value();
721 return false;
724 return ret;
727 // Gets the current working directory for the process.
728 bool GetCurrentDirectory(FilePath* dir) {
729 // getcwd can return ENOENT, which implies it checks against the disk.
730 ThreadRestrictions::AssertIOAllowed();
732 char system_buffer[PATH_MAX] = "";
733 if (!getcwd(system_buffer, sizeof(system_buffer))) {
734 NOTREACHED();
735 return false;
737 *dir = FilePath(system_buffer);
738 return true;
741 // Sets the current working directory for the process.
742 bool SetCurrentDirectory(const FilePath& path) {
743 ThreadRestrictions::AssertIOAllowed();
744 int ret = chdir(path.value().c_str());
745 return !ret;
748 bool VerifyPathControlledByUser(const FilePath& base,
749 const FilePath& path,
750 uid_t owner_uid,
751 const std::set<gid_t>& group_gids) {
752 if (base != path && !base.IsParent(path)) {
753 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
754 << base.value() << "\", path = \"" << path.value() << "\"";
755 return false;
758 std::vector<FilePath::StringType> base_components;
759 std::vector<FilePath::StringType> path_components;
761 base.GetComponents(&base_components);
762 path.GetComponents(&path_components);
764 std::vector<FilePath::StringType>::const_iterator ib, ip;
765 for (ib = base_components.begin(), ip = path_components.begin();
766 ib != base_components.end(); ++ib, ++ip) {
767 // |base| must be a subpath of |path|, so all components should match.
768 // If these CHECKs fail, look at the test that base is a parent of
769 // path at the top of this function.
770 DCHECK(ip != path_components.end());
771 DCHECK(*ip == *ib);
774 FilePath current_path = base;
775 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
776 return false;
778 for (; ip != path_components.end(); ++ip) {
779 current_path = current_path.Append(*ip);
780 if (!VerifySpecificPathControlledByUser(
781 current_path, owner_uid, group_gids))
782 return false;
784 return true;
787 #if defined(OS_MACOSX) && !defined(OS_IOS)
788 bool VerifyPathControlledByAdmin(const FilePath& path) {
789 const unsigned kRootUid = 0;
790 const FilePath kFileSystemRoot("/");
792 // The name of the administrator group on mac os.
793 const char* const kAdminGroupNames[] = {
794 "admin",
795 "wheel"
798 // Reading the groups database may touch the file system.
799 ThreadRestrictions::AssertIOAllowed();
801 std::set<gid_t> allowed_group_ids;
802 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
803 struct group *group_record = getgrnam(kAdminGroupNames[i]);
804 if (!group_record) {
805 DPLOG(ERROR) << "Could not get the group ID of group \""
806 << kAdminGroupNames[i] << "\".";
807 continue;
810 allowed_group_ids.insert(group_record->gr_gid);
813 return VerifyPathControlledByUser(
814 kFileSystemRoot, path, kRootUid, allowed_group_ids);
816 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
818 int GetMaximumPathComponentLength(const FilePath& path) {
819 ThreadRestrictions::AssertIOAllowed();
820 return pathconf(path.value().c_str(), _PC_NAME_MAX);
823 #if !defined(OS_ANDROID)
824 // This is implemented in file_util_android.cc for that platform.
825 bool GetShmemTempDir(bool executable, FilePath* path) {
826 #if defined(OS_LINUX)
827 bool use_dev_shm = true;
828 if (executable) {
829 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
830 use_dev_shm = s_dev_shm_executable;
832 if (use_dev_shm) {
833 *path = FilePath("/dev/shm");
834 return true;
836 #endif
837 return GetTempDir(path);
839 #endif // !defined(OS_ANDROID)
841 #if !defined(OS_MACOSX)
842 // Mac has its own implementation, this is for all other Posix systems.
843 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
844 ThreadRestrictions::AssertIOAllowed();
845 File infile;
846 #if defined(OS_ANDROID)
847 if (from_path.IsContentUri()) {
848 infile = OpenContentUriForRead(from_path);
849 } else {
850 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
852 #else
853 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
854 #endif
855 if (!infile.IsValid())
856 return false;
858 File outfile(to_path, File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
859 if (!outfile.IsValid())
860 return false;
862 const size_t kBufferSize = 32768;
863 std::vector<char> buffer(kBufferSize);
864 bool result = true;
866 while (result) {
867 ssize_t bytes_read = infile.ReadAtCurrentPos(&buffer[0], buffer.size());
868 if (bytes_read < 0) {
869 result = false;
870 break;
872 if (bytes_read == 0)
873 break;
874 // Allow for partial writes
875 ssize_t bytes_written_per_read = 0;
876 do {
877 ssize_t bytes_written_partial = outfile.WriteAtCurrentPos(
878 &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read);
879 if (bytes_written_partial < 0) {
880 result = false;
881 break;
883 bytes_written_per_read += bytes_written_partial;
884 } while (bytes_written_per_read < bytes_read);
887 return result;
889 #endif // !defined(OS_MACOSX)
891 // -----------------------------------------------------------------------------
893 namespace internal {
895 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
896 ThreadRestrictions::AssertIOAllowed();
897 // Windows compatibility: if to_path exists, from_path and to_path
898 // must be the same type, either both files, or both directories.
899 stat_wrapper_t to_file_info;
900 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
901 stat_wrapper_t from_file_info;
902 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
903 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
904 return false;
905 } else {
906 return false;
910 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
911 return true;
913 if (!CopyDirectory(from_path, to_path, true))
914 return false;
916 DeleteFile(from_path, true);
917 return true;
920 } // namespace internal
922 #endif // !defined(OS_NACL_NONSFI)
923 } // namespace base