Revert 236008 "Revert 236006 "Revert 236005 "Fixing Chromeos bui..."
[chromium-blink-merge.git] / base / file_util_posix.cc
bloba2dd19b97c439bd9a406af09526b6b1947b4e726
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"
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 #elif !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
28 #include <glib.h> // for g_get_home_dir()
29 #endif
31 #include <fstream>
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/os_compat_android.h"
52 #endif
54 #if !defined(OS_IOS)
55 #include <grp.h>
56 #endif
58 namespace base {
60 namespace {
62 #if defined(OS_BSD) || defined(OS_MACOSX)
63 typedef struct stat stat_wrapper_t;
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
73 typedef struct stat64 stat_wrapper_t;
74 static int CallStat(const char *path, stat_wrapper_t *sb) {
75 ThreadRestrictions::AssertIOAllowed();
76 return stat64(path, sb);
78 static int CallLstat(const char *path, stat_wrapper_t *sb) {
79 ThreadRestrictions::AssertIOAllowed();
80 return lstat64(path, sb);
82 #endif
84 // Helper for NormalizeFilePath(), defined below.
85 bool RealPath(const FilePath& path, FilePath* real_path) {
86 ThreadRestrictions::AssertIOAllowed(); // For realpath().
87 FilePath::CharType buf[PATH_MAX];
88 if (!realpath(path.value().c_str(), buf))
89 return false;
91 *real_path = FilePath(buf);
92 return true;
95 // Helper for VerifyPathControlledByUser.
96 bool VerifySpecificPathControlledByUser(const FilePath& path,
97 uid_t owner_uid,
98 const std::set<gid_t>& group_gids) {
99 stat_wrapper_t stat_info;
100 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
101 DPLOG(ERROR) << "Failed to get information on path "
102 << path.value();
103 return false;
106 if (S_ISLNK(stat_info.st_mode)) {
107 DLOG(ERROR) << "Path " << path.value()
108 << " is a symbolic link.";
109 return false;
112 if (stat_info.st_uid != owner_uid) {
113 DLOG(ERROR) << "Path " << path.value()
114 << " is owned by the wrong user.";
115 return false;
118 if ((stat_info.st_mode & S_IWGRP) &&
119 !ContainsKey(group_gids, stat_info.st_gid)) {
120 DLOG(ERROR) << "Path " << path.value()
121 << " is writable by an unprivileged group.";
122 return false;
125 if (stat_info.st_mode & S_IWOTH) {
126 DLOG(ERROR) << "Path " << path.value()
127 << " is writable by any user.";
128 return false;
131 return true;
134 std::string TempFileName() {
135 #if defined(OS_MACOSX)
136 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
137 #endif
139 #if defined(GOOGLE_CHROME_BUILD)
140 return std::string(".com.google.Chrome.XXXXXX");
141 #else
142 return std::string(".org.chromium.Chromium.XXXXXX");
143 #endif
146 } // namespace
148 FilePath MakeAbsoluteFilePath(const FilePath& input) {
149 ThreadRestrictions::AssertIOAllowed();
150 char full_path[PATH_MAX];
151 if (realpath(input.value().c_str(), full_path) == NULL)
152 return FilePath();
153 return FilePath(full_path);
156 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
157 // which works both with and without the recursive flag. I'm not sure we need
158 // that functionality. If not, remove from file_util_win.cc, otherwise add it
159 // here.
160 bool DeleteFile(const FilePath& path, bool recursive) {
161 ThreadRestrictions::AssertIOAllowed();
162 const char* path_str = path.value().c_str();
163 stat_wrapper_t file_info;
164 int test = CallLstat(path_str, &file_info);
165 if (test != 0) {
166 // The Windows version defines this condition as success.
167 bool ret = (errno == ENOENT || errno == ENOTDIR);
168 return ret;
170 if (!S_ISDIR(file_info.st_mode))
171 return (unlink(path_str) == 0);
172 if (!recursive)
173 return (rmdir(path_str) == 0);
175 bool success = true;
176 std::stack<std::string> directories;
177 directories.push(path.value());
178 FileEnumerator traversal(path, true,
179 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
180 FileEnumerator::SHOW_SYM_LINKS);
181 for (FilePath current = traversal.Next(); success && !current.empty();
182 current = traversal.Next()) {
183 if (traversal.GetInfo().IsDirectory())
184 directories.push(current.value());
185 else
186 success = (unlink(current.value().c_str()) == 0);
189 while (success && !directories.empty()) {
190 FilePath dir = FilePath(directories.top());
191 directories.pop();
192 success = (rmdir(dir.value().c_str()) == 0);
194 return success;
197 bool ReplaceFile(const FilePath& from_path,
198 const FilePath& to_path,
199 PlatformFileError* error) {
200 ThreadRestrictions::AssertIOAllowed();
201 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
202 return true;
203 if (error)
204 *error = ErrnoToPlatformFileError(errno);
205 return false;
208 bool CopyDirectory(const FilePath& from_path,
209 const FilePath& to_path,
210 bool recursive) {
211 ThreadRestrictions::AssertIOAllowed();
212 // Some old callers of CopyDirectory want it to support wildcards.
213 // After some discussion, we decided to fix those callers.
214 // Break loudly here if anyone tries to do this.
215 // TODO(evanm): remove this once we're sure it's ok.
216 DCHECK(to_path.value().find('*') == std::string::npos);
217 DCHECK(from_path.value().find('*') == std::string::npos);
219 char top_dir[PATH_MAX];
220 if (strlcpy(top_dir, from_path.value().c_str(),
221 arraysize(top_dir)) >= arraysize(top_dir)) {
222 return false;
225 // This function does not properly handle destinations within the source
226 FilePath real_to_path = to_path;
227 if (PathExists(real_to_path)) {
228 real_to_path = MakeAbsoluteFilePath(real_to_path);
229 if (real_to_path.empty())
230 return false;
231 } else {
232 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
233 if (real_to_path.empty())
234 return false;
236 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
237 if (real_from_path.empty())
238 return false;
239 if (real_to_path.value().size() >= real_from_path.value().size() &&
240 real_to_path.value().compare(0, real_from_path.value().size(),
241 real_from_path.value()) == 0)
242 return false;
244 bool success = true;
245 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
246 if (recursive)
247 traverse_type |= FileEnumerator::DIRECTORIES;
248 FileEnumerator traversal(from_path, recursive, traverse_type);
250 // We have to mimic windows behavior here. |to_path| may not exist yet,
251 // start the loop with |to_path|.
252 struct stat from_stat;
253 FilePath current = from_path;
254 if (stat(from_path.value().c_str(), &from_stat) < 0) {
255 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
256 << from_path.value() << " errno = " << errno;
257 success = false;
259 struct stat to_path_stat;
260 FilePath from_path_base = from_path;
261 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
262 S_ISDIR(to_path_stat.st_mode)) {
263 // If the destination already exists and is a directory, then the
264 // top level of source needs to be copied.
265 from_path_base = from_path.DirName();
268 // The Windows version of this function assumes that non-recursive calls
269 // will always have a directory for from_path.
270 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
272 while (success && !current.empty()) {
273 // current is the source path, including from_path, so append
274 // the suffix after from_path to to_path to create the target_path.
275 FilePath target_path(to_path);
276 if (from_path_base != current) {
277 if (!from_path_base.AppendRelativePath(current, &target_path)) {
278 success = false;
279 break;
283 if (S_ISDIR(from_stat.st_mode)) {
284 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
285 errno != EEXIST) {
286 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
287 << target_path.value() << " errno = " << errno;
288 success = false;
290 } else if (S_ISREG(from_stat.st_mode)) {
291 if (!CopyFile(current, target_path)) {
292 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
293 << target_path.value();
294 success = false;
296 } else {
297 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
298 << current.value();
301 current = traversal.Next();
302 if (!current.empty())
303 from_stat = traversal.GetInfo().stat();
306 return success;
309 bool PathExists(const FilePath& path) {
310 ThreadRestrictions::AssertIOAllowed();
311 return access(path.value().c_str(), F_OK) == 0;
314 bool PathIsWritable(const FilePath& path) {
315 ThreadRestrictions::AssertIOAllowed();
316 return access(path.value().c_str(), W_OK) == 0;
319 bool DirectoryExists(const FilePath& path) {
320 ThreadRestrictions::AssertIOAllowed();
321 stat_wrapper_t file_info;
322 if (CallStat(path.value().c_str(), &file_info) == 0)
323 return S_ISDIR(file_info.st_mode);
324 return false;
327 } // namespace base
329 // -----------------------------------------------------------------------------
331 namespace file_util {
333 using base::stat_wrapper_t;
334 using base::CallStat;
335 using base::CallLstat;
336 using base::DirectoryExists;
337 using base::FileEnumerator;
338 using base::FilePath;
339 using base::MakeAbsoluteFilePath;
340 using base::RealPath;
341 using base::VerifySpecificPathControlledByUser;
343 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
344 size_t total_read = 0;
345 while (total_read < bytes) {
346 ssize_t bytes_read =
347 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
348 if (bytes_read <= 0)
349 break;
350 total_read += bytes_read;
352 return total_read == bytes;
355 bool CreateSymbolicLink(const FilePath& target_path,
356 const FilePath& symlink_path) {
357 DCHECK(!symlink_path.empty());
358 DCHECK(!target_path.empty());
359 return ::symlink(target_path.value().c_str(),
360 symlink_path.value().c_str()) != -1;
363 bool ReadSymbolicLink(const FilePath& symlink_path,
364 FilePath* target_path) {
365 DCHECK(!symlink_path.empty());
366 DCHECK(target_path);
367 char buf[PATH_MAX];
368 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
370 if (count <= 0) {
371 target_path->clear();
372 return false;
375 *target_path = FilePath(FilePath::StringType(buf, count));
376 return true;
379 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
380 base::ThreadRestrictions::AssertIOAllowed();
381 DCHECK(mode);
383 stat_wrapper_t file_info;
384 // Uses stat(), because on symbolic link, lstat() does not return valid
385 // permission bits in st_mode
386 if (CallStat(path.value().c_str(), &file_info) != 0)
387 return false;
389 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
390 return true;
393 bool SetPosixFilePermissions(const FilePath& path,
394 int mode) {
395 base::ThreadRestrictions::AssertIOAllowed();
396 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
398 // Calls stat() so that we can preserve the higher bits like S_ISGID.
399 stat_wrapper_t stat_buf;
400 if (CallStat(path.value().c_str(), &stat_buf) != 0)
401 return false;
403 // Clears the existing permission bits, and adds the new ones.
404 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
405 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
407 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
408 return false;
410 return true;
413 // Creates and opens a temporary file in |directory|, returning the
414 // file descriptor. |path| is set to the temporary file path.
415 // This function does NOT unlink() the file.
416 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
417 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
418 *path = directory.Append(base::TempFileName());
419 const std::string& tmpdir_string = path->value();
420 // this should be OK since mkstemp just replaces characters in place
421 char* buffer = const_cast<char*>(tmpdir_string.c_str());
423 return HANDLE_EINTR(mkstemp(buffer));
426 bool CreateTemporaryFile(FilePath* path) {
427 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
428 FilePath directory;
429 if (!GetTempDir(&directory))
430 return false;
431 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
432 if (fd < 0)
433 return false;
434 ignore_result(HANDLE_EINTR(close(fd)));
435 return true;
438 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
439 FilePath directory;
440 if (!GetShmemTempDir(&directory, executable))
441 return NULL;
443 return CreateAndOpenTemporaryFileInDir(directory, path);
446 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
447 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
448 if (fd < 0)
449 return NULL;
451 FILE* file = fdopen(fd, "a+");
452 if (!file)
453 ignore_result(HANDLE_EINTR(close(fd)));
454 return file;
457 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
458 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
459 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
460 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
463 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
464 const FilePath::StringType& name_tmpl,
465 FilePath* new_dir) {
466 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
467 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
468 << "Directory name template must contain \"XXXXXX\".";
470 FilePath sub_dir = base_dir.Append(name_tmpl);
471 std::string sub_dir_string = sub_dir.value();
473 // this should be OK since mkdtemp just replaces characters in place
474 char* buffer = const_cast<char*>(sub_dir_string.c_str());
475 char* dtemp = mkdtemp(buffer);
476 if (!dtemp) {
477 DPLOG(ERROR) << "mkdtemp";
478 return false;
480 *new_dir = FilePath(dtemp);
481 return true;
484 bool CreateTemporaryDirInDir(const FilePath& base_dir,
485 const FilePath::StringType& prefix,
486 FilePath* new_dir) {
487 FilePath::StringType mkdtemp_template = prefix;
488 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
489 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
492 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
493 FilePath* new_temp_path) {
494 FilePath tmpdir;
495 if (!GetTempDir(&tmpdir))
496 return false;
498 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
499 new_temp_path);
502 bool CreateDirectoryAndGetError(const FilePath& full_path,
503 base::PlatformFileError* error) {
504 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
505 std::vector<FilePath> subpaths;
507 // Collect a list of all parent directories.
508 FilePath last_path = full_path;
509 subpaths.push_back(full_path);
510 for (FilePath path = full_path.DirName();
511 path.value() != last_path.value(); path = path.DirName()) {
512 subpaths.push_back(path);
513 last_path = path;
516 // Iterate through the parents and create the missing ones.
517 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
518 i != subpaths.rend(); ++i) {
519 if (DirectoryExists(*i))
520 continue;
521 if (mkdir(i->value().c_str(), 0700) == 0)
522 continue;
523 // Mkdir failed, but it might have failed with EEXIST, or some other error
524 // due to the the directory appearing out of thin air. This can occur if
525 // two processes are trying to create the same file system tree at the same
526 // time. Check to see if it exists and make sure it is a directory.
527 int saved_errno = errno;
528 if (!DirectoryExists(*i)) {
529 if (error)
530 *error = base::ErrnoToPlatformFileError(saved_errno);
531 return false;
534 return true;
537 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
538 const int kMaxAttempts = 20;
539 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
540 int uniquifier =
541 GetUniquePathNumber(path, base::FilePath::StringType());
542 if (uniquifier < 0)
543 break;
544 base::FilePath test_path = (uniquifier == 0) ? path :
545 path.InsertBeforeExtensionASCII(
546 base::StringPrintf(" (%d)", uniquifier));
547 if (mkdir(test_path.value().c_str(), 0777) == 0)
548 return test_path;
549 else if (errno != EEXIST)
550 break;
552 return base::FilePath();
555 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
556 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
557 bool IsLink(const FilePath& file_path) {
558 stat_wrapper_t st;
559 // If we can't lstat the file, it's safe to assume that the file won't at
560 // least be a 'followable' link.
561 if (CallLstat(file_path.value().c_str(), &st) != 0)
562 return false;
564 if (S_ISLNK(st.st_mode))
565 return true;
566 else
567 return false;
570 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
571 stat_wrapper_t file_info;
572 if (CallStat(file_path.value().c_str(), &file_info) != 0)
573 return false;
574 results->is_directory = S_ISDIR(file_info.st_mode);
575 results->size = file_info.st_size;
576 #if defined(OS_MACOSX)
577 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
578 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
579 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
580 #elif defined(OS_ANDROID)
581 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
582 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
583 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
584 #else
585 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
586 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
587 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
588 #endif
589 return true;
592 bool GetInode(const FilePath& path, ino_t* inode) {
593 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
594 struct stat buffer;
595 int result = stat(path.value().c_str(), &buffer);
596 if (result < 0)
597 return false;
599 *inode = buffer.st_ino;
600 return true;
603 FILE* OpenFile(const std::string& filename, const char* mode) {
604 return OpenFile(FilePath(filename), mode);
607 FILE* OpenFile(const FilePath& filename, const char* mode) {
608 base::ThreadRestrictions::AssertIOAllowed();
609 FILE* result = NULL;
610 do {
611 result = fopen(filename.value().c_str(), mode);
612 } while (!result && errno == EINTR);
613 return result;
616 int ReadFile(const FilePath& filename, char* data, int size) {
617 base::ThreadRestrictions::AssertIOAllowed();
618 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
619 if (fd < 0)
620 return -1;
622 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
623 if (int ret = HANDLE_EINTR(close(fd)) < 0)
624 return ret;
625 return bytes_read;
628 int WriteFile(const FilePath& filename, const char* data, int size) {
629 base::ThreadRestrictions::AssertIOAllowed();
630 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
631 if (fd < 0)
632 return -1;
634 int bytes_written = WriteFileDescriptor(fd, data, size);
635 if (int ret = HANDLE_EINTR(close(fd)) < 0)
636 return ret;
637 return bytes_written;
640 int WriteFileDescriptor(const int fd, const char* data, int size) {
641 // Allow for partial writes.
642 ssize_t bytes_written_total = 0;
643 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
644 bytes_written_total += bytes_written_partial) {
645 bytes_written_partial =
646 HANDLE_EINTR(write(fd, data + bytes_written_total,
647 size - bytes_written_total));
648 if (bytes_written_partial < 0)
649 return -1;
652 return bytes_written_total;
655 int AppendToFile(const FilePath& filename, const char* data, int size) {
656 base::ThreadRestrictions::AssertIOAllowed();
657 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
658 if (fd < 0)
659 return -1;
661 int bytes_written = WriteFileDescriptor(fd, data, size);
662 if (int ret = HANDLE_EINTR(close(fd)) < 0)
663 return ret;
664 return bytes_written;
667 // Gets the current working directory for the process.
668 bool GetCurrentDirectory(FilePath* dir) {
669 // getcwd can return ENOENT, which implies it checks against the disk.
670 base::ThreadRestrictions::AssertIOAllowed();
672 char system_buffer[PATH_MAX] = "";
673 if (!getcwd(system_buffer, sizeof(system_buffer))) {
674 NOTREACHED();
675 return false;
677 *dir = FilePath(system_buffer);
678 return true;
681 // Sets the current working directory for the process.
682 bool SetCurrentDirectory(const FilePath& path) {
683 base::ThreadRestrictions::AssertIOAllowed();
684 int ret = chdir(path.value().c_str());
685 return !ret;
688 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
689 FilePath real_path_result;
690 if (!RealPath(path, &real_path_result))
691 return false;
693 // To be consistant with windows, fail if |real_path_result| is a
694 // directory.
695 stat_wrapper_t file_info;
696 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
697 S_ISDIR(file_info.st_mode))
698 return false;
700 *normalized_path = real_path_result;
701 return true;
704 #if !defined(OS_MACOSX)
705 bool GetTempDir(FilePath* path) {
706 const char* tmp = getenv("TMPDIR");
707 if (tmp)
708 *path = FilePath(tmp);
709 else
710 #if defined(OS_ANDROID)
711 return PathService::Get(base::DIR_CACHE, path);
712 #else
713 *path = FilePath("/tmp");
714 #endif
715 return true;
718 #if !defined(OS_ANDROID)
720 #if defined(OS_LINUX)
721 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
722 // This depends on the mount options used for /dev/shm, which vary among
723 // different Linux distributions and possibly local configuration. It also
724 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
725 // but its kernel allows mprotect with PROT_EXEC anyway.
727 namespace {
729 bool DetermineDevShmExecutable() {
730 bool result = false;
731 FilePath path;
732 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
733 if (fd >= 0) {
734 ScopedFD shm_fd_closer(&fd);
735 DeleteFile(path, false);
736 long sysconf_result = sysconf(_SC_PAGESIZE);
737 CHECK_GE(sysconf_result, 0);
738 size_t pagesize = static_cast<size_t>(sysconf_result);
739 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
740 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
741 if (mapping != MAP_FAILED) {
742 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
743 result = true;
744 munmap(mapping, pagesize);
747 return result;
750 }; // namespace
751 #endif // defined(OS_LINUX)
753 bool GetShmemTempDir(FilePath* path, bool executable) {
754 #if defined(OS_LINUX)
755 bool use_dev_shm = true;
756 if (executable) {
757 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
758 use_dev_shm = s_dev_shm_executable;
760 if (use_dev_shm) {
761 *path = FilePath("/dev/shm");
762 return true;
764 #endif
765 return GetTempDir(path);
767 #endif // !defined(OS_ANDROID)
769 FilePath GetHomeDir() {
770 #if defined(OS_CHROMEOS)
771 if (base::SysInfo::IsRunningOnChromeOS())
772 return FilePath("/home/chronos/user");
773 #endif
775 const char* home_dir = getenv("HOME");
776 if (home_dir && home_dir[0])
777 return FilePath(home_dir);
779 #if defined(OS_ANDROID)
780 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
781 #elif !defined(OS_CHROMEOS)
782 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
783 base::ThreadRestrictions::AssertIOAllowed();
785 home_dir = g_get_home_dir();
786 if (home_dir && home_dir[0])
787 return FilePath(home_dir);
788 #endif
790 FilePath rv;
791 if (file_util::GetTempDir(&rv))
792 return rv;
794 // Last resort.
795 return FilePath("/tmp");
797 #endif // !defined(OS_MACOSX)
799 bool VerifyPathControlledByUser(const FilePath& base,
800 const FilePath& path,
801 uid_t owner_uid,
802 const std::set<gid_t>& group_gids) {
803 if (base != path && !base.IsParent(path)) {
804 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
805 << base.value() << "\", path = \"" << path.value() << "\"";
806 return false;
809 std::vector<FilePath::StringType> base_components;
810 std::vector<FilePath::StringType> path_components;
812 base.GetComponents(&base_components);
813 path.GetComponents(&path_components);
815 std::vector<FilePath::StringType>::const_iterator ib, ip;
816 for (ib = base_components.begin(), ip = path_components.begin();
817 ib != base_components.end(); ++ib, ++ip) {
818 // |base| must be a subpath of |path|, so all components should match.
819 // If these CHECKs fail, look at the test that base is a parent of
820 // path at the top of this function.
821 DCHECK(ip != path_components.end());
822 DCHECK(*ip == *ib);
825 FilePath current_path = base;
826 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
827 return false;
829 for (; ip != path_components.end(); ++ip) {
830 current_path = current_path.Append(*ip);
831 if (!VerifySpecificPathControlledByUser(
832 current_path, owner_uid, group_gids))
833 return false;
835 return true;
838 #if defined(OS_MACOSX) && !defined(OS_IOS)
839 bool VerifyPathControlledByAdmin(const FilePath& path) {
840 const unsigned kRootUid = 0;
841 const FilePath kFileSystemRoot("/");
843 // The name of the administrator group on mac os.
844 const char* const kAdminGroupNames[] = {
845 "admin",
846 "wheel"
849 // Reading the groups database may touch the file system.
850 base::ThreadRestrictions::AssertIOAllowed();
852 std::set<gid_t> allowed_group_ids;
853 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
854 struct group *group_record = getgrnam(kAdminGroupNames[i]);
855 if (!group_record) {
856 DPLOG(ERROR) << "Could not get the group ID of group \""
857 << kAdminGroupNames[i] << "\".";
858 continue;
861 allowed_group_ids.insert(group_record->gr_gid);
864 return VerifyPathControlledByUser(
865 kFileSystemRoot, path, kRootUid, allowed_group_ids);
867 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
869 int GetMaximumPathComponentLength(const FilePath& path) {
870 base::ThreadRestrictions::AssertIOAllowed();
871 return pathconf(path.value().c_str(), _PC_NAME_MAX);
874 } // namespace file_util
876 namespace base {
877 namespace internal {
879 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
880 ThreadRestrictions::AssertIOAllowed();
881 // Windows compatibility: if to_path exists, from_path and to_path
882 // must be the same type, either both files, or both directories.
883 stat_wrapper_t to_file_info;
884 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
885 stat_wrapper_t from_file_info;
886 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
887 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
888 return false;
889 } else {
890 return false;
894 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
895 return true;
897 if (!CopyDirectory(from_path, to_path, true))
898 return false;
900 DeleteFile(from_path, true);
901 return true;
904 #if !defined(OS_MACOSX)
905 // Mac has its own implementation, this is for all other Posix systems.
906 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
907 ThreadRestrictions::AssertIOAllowed();
908 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
909 if (infile < 0)
910 return false;
912 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
913 if (outfile < 0) {
914 ignore_result(HANDLE_EINTR(close(infile)));
915 return false;
918 const size_t kBufferSize = 32768;
919 std::vector<char> buffer(kBufferSize);
920 bool result = true;
922 while (result) {
923 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
924 if (bytes_read < 0) {
925 result = false;
926 break;
928 if (bytes_read == 0)
929 break;
930 // Allow for partial writes
931 ssize_t bytes_written_per_read = 0;
932 do {
933 ssize_t bytes_written_partial = HANDLE_EINTR(write(
934 outfile,
935 &buffer[bytes_written_per_read],
936 bytes_read - bytes_written_per_read));
937 if (bytes_written_partial < 0) {
938 result = false;
939 break;
941 bytes_written_per_read += bytes_written_partial;
942 } while (bytes_written_per_read < bytes_read);
945 if (HANDLE_EINTR(close(infile)) < 0)
946 result = false;
947 if (HANDLE_EINTR(close(outfile)) < 0)
948 result = false;
950 return result;
952 #endif // !defined(OS_MACOSX)
954 } // namespace internal
955 } // namespace base