Add ability to change display settings to chrome.systemInfo.display
[chromium-blink-merge.git] / base / file_util_posix.cc
blob340a42fa26963b74de48b7281fe9b6e3d3b9cf46
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)
28 #include <glib.h>
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/threading/thread_restrictions.h"
47 #include "base/time.h"
49 #if defined(OS_ANDROID)
50 #include "base/os_compat_android.h"
51 #endif
53 #if !defined(OS_IOS)
54 #include <grp.h>
55 #endif
57 #if defined(OS_CHROMEOS)
58 #include "base/chromeos/chromeos_version.h"
59 #endif
61 using base::FileEnumerator;
62 using base::FilePath;
63 using base::MakeAbsoluteFilePath;
65 namespace base {
67 FilePath MakeAbsoluteFilePath(const FilePath& input) {
68 base::ThreadRestrictions::AssertIOAllowed();
69 char full_path[PATH_MAX];
70 if (realpath(input.value().c_str(), full_path) == NULL)
71 return FilePath();
72 return FilePath(full_path);
75 } // namespace base
77 namespace file_util {
79 namespace {
81 #if defined(OS_BSD) || defined(OS_MACOSX)
82 typedef struct stat stat_wrapper_t;
83 static int CallStat(const char *path, stat_wrapper_t *sb) {
84 base::ThreadRestrictions::AssertIOAllowed();
85 return stat(path, sb);
87 static int CallLstat(const char *path, stat_wrapper_t *sb) {
88 base::ThreadRestrictions::AssertIOAllowed();
89 return lstat(path, sb);
91 #else
92 typedef struct stat64 stat_wrapper_t;
93 static int CallStat(const char *path, stat_wrapper_t *sb) {
94 base::ThreadRestrictions::AssertIOAllowed();
95 return stat64(path, sb);
97 static int CallLstat(const char *path, stat_wrapper_t *sb) {
98 base::ThreadRestrictions::AssertIOAllowed();
99 return lstat64(path, sb);
101 #endif
103 // Helper for NormalizeFilePath(), defined below.
104 bool RealPath(const FilePath& path, FilePath* real_path) {
105 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
106 FilePath::CharType buf[PATH_MAX];
107 if (!realpath(path.value().c_str(), buf))
108 return false;
110 *real_path = FilePath(buf);
111 return true;
114 // Helper for VerifyPathControlledByUser.
115 bool VerifySpecificPathControlledByUser(const FilePath& path,
116 uid_t owner_uid,
117 const std::set<gid_t>& group_gids) {
118 stat_wrapper_t stat_info;
119 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
120 DPLOG(ERROR) << "Failed to get information on path "
121 << path.value();
122 return false;
125 if (S_ISLNK(stat_info.st_mode)) {
126 DLOG(ERROR) << "Path " << path.value()
127 << " is a symbolic link.";
128 return false;
131 if (stat_info.st_uid != owner_uid) {
132 DLOG(ERROR) << "Path " << path.value()
133 << " is owned by the wrong user.";
134 return false;
137 if ((stat_info.st_mode & S_IWGRP) &&
138 !ContainsKey(group_gids, stat_info.st_gid)) {
139 DLOG(ERROR) << "Path " << path.value()
140 << " is writable by an unprivileged group.";
141 return false;
144 if (stat_info.st_mode & S_IWOTH) {
145 DLOG(ERROR) << "Path " << path.value()
146 << " is writable by any user.";
147 return false;
150 return true;
153 } // namespace
155 static std::string TempFileName() {
156 #if defined(OS_MACOSX)
157 return base::StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
158 #endif
160 #if defined(GOOGLE_CHROME_BUILD)
161 return std::string(".com.google.Chrome.XXXXXX");
162 #else
163 return std::string(".org.chromium.Chromium.XXXXXX");
164 #endif
167 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
168 // which works both with and without the recursive flag. I'm not sure we need
169 // that functionality. If not, remove from file_util_win.cc, otherwise add it
170 // here.
171 bool Delete(const FilePath& path, bool recursive) {
172 base::ThreadRestrictions::AssertIOAllowed();
173 const char* path_str = path.value().c_str();
174 stat_wrapper_t file_info;
175 int test = CallLstat(path_str, &file_info);
176 if (test != 0) {
177 // The Windows version defines this condition as success.
178 bool ret = (errno == ENOENT || errno == ENOTDIR);
179 return ret;
181 if (!S_ISDIR(file_info.st_mode))
182 return (unlink(path_str) == 0);
183 if (!recursive)
184 return (rmdir(path_str) == 0);
186 bool success = true;
187 std::stack<std::string> directories;
188 directories.push(path.value());
189 FileEnumerator traversal(path, true,
190 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
191 FileEnumerator::SHOW_SYM_LINKS);
192 for (FilePath current = traversal.Next(); success && !current.empty();
193 current = traversal.Next()) {
194 if (traversal.GetInfo().IsDirectory())
195 directories.push(current.value());
196 else
197 success = (unlink(current.value().c_str()) == 0);
200 while (success && !directories.empty()) {
201 FilePath dir = FilePath(directories.top());
202 directories.pop();
203 success = (rmdir(dir.value().c_str()) == 0);
205 return success;
208 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
209 base::ThreadRestrictions::AssertIOAllowed();
210 // Windows compatibility: if to_path exists, from_path and to_path
211 // must be the same type, either both files, or both directories.
212 stat_wrapper_t to_file_info;
213 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
214 stat_wrapper_t from_file_info;
215 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
216 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
217 return false;
218 } else {
219 return false;
223 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
224 return true;
226 if (!CopyDirectory(from_path, to_path, true))
227 return false;
229 Delete(from_path, true);
230 return true;
233 bool ReplaceFileAndGetError(const FilePath& from_path,
234 const FilePath& to_path,
235 base::PlatformFileError* error) {
236 base::ThreadRestrictions::AssertIOAllowed();
237 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
238 return true;
239 if (error)
240 *error = base::ErrnoToPlatformFileError(errno);
241 return false;
244 bool CopyDirectory(const FilePath& from_path,
245 const FilePath& to_path,
246 bool recursive) {
247 base::ThreadRestrictions::AssertIOAllowed();
248 // Some old callers of CopyDirectory want it to support wildcards.
249 // After some discussion, we decided to fix those callers.
250 // Break loudly here if anyone tries to do this.
251 // TODO(evanm): remove this once we're sure it's ok.
252 DCHECK(to_path.value().find('*') == std::string::npos);
253 DCHECK(from_path.value().find('*') == std::string::npos);
255 char top_dir[PATH_MAX];
256 if (base::strlcpy(top_dir, from_path.value().c_str(),
257 arraysize(top_dir)) >= arraysize(top_dir)) {
258 return false;
261 // This function does not properly handle destinations within the source
262 FilePath real_to_path = to_path;
263 if (PathExists(real_to_path)) {
264 real_to_path = MakeAbsoluteFilePath(real_to_path);
265 if (real_to_path.empty())
266 return false;
267 } else {
268 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
269 if (real_to_path.empty())
270 return false;
272 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
273 if (real_from_path.empty())
274 return false;
275 if (real_to_path.value().size() >= real_from_path.value().size() &&
276 real_to_path.value().compare(0, real_from_path.value().size(),
277 real_from_path.value()) == 0)
278 return false;
280 bool success = true;
281 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
282 if (recursive)
283 traverse_type |= FileEnumerator::DIRECTORIES;
284 FileEnumerator traversal(from_path, recursive, traverse_type);
286 // We have to mimic windows behavior here. |to_path| may not exist yet,
287 // start the loop with |to_path|.
288 struct stat from_stat;
289 FilePath current = from_path;
290 if (stat(from_path.value().c_str(), &from_stat) < 0) {
291 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
292 << from_path.value() << " errno = " << errno;
293 success = false;
295 struct stat to_path_stat;
296 FilePath from_path_base = from_path;
297 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
298 S_ISDIR(to_path_stat.st_mode)) {
299 // If the destination already exists and is a directory, then the
300 // top level of source needs to be copied.
301 from_path_base = from_path.DirName();
304 // The Windows version of this function assumes that non-recursive calls
305 // will always have a directory for from_path.
306 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
308 while (success && !current.empty()) {
309 // current is the source path, including from_path, so append
310 // the suffix after from_path to to_path to create the target_path.
311 FilePath target_path(to_path);
312 if (from_path_base != current) {
313 if (!from_path_base.AppendRelativePath(current, &target_path)) {
314 success = false;
315 break;
319 if (S_ISDIR(from_stat.st_mode)) {
320 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
321 errno != EEXIST) {
322 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
323 << target_path.value() << " errno = " << errno;
324 success = false;
326 } else if (S_ISREG(from_stat.st_mode)) {
327 if (!CopyFile(current, target_path)) {
328 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
329 << target_path.value();
330 success = false;
332 } else {
333 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
334 << current.value();
337 current = traversal.Next();
338 if (!current.empty())
339 from_stat = traversal.GetInfo().stat();
342 return success;
345 bool PathExists(const FilePath& path) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 return access(path.value().c_str(), F_OK) == 0;
350 bool PathIsWritable(const FilePath& path) {
351 base::ThreadRestrictions::AssertIOAllowed();
352 return access(path.value().c_str(), W_OK) == 0;
355 bool DirectoryExists(const FilePath& path) {
356 base::ThreadRestrictions::AssertIOAllowed();
357 stat_wrapper_t file_info;
358 if (CallStat(path.value().c_str(), &file_info) == 0)
359 return S_ISDIR(file_info.st_mode);
360 return false;
363 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
364 size_t total_read = 0;
365 while (total_read < bytes) {
366 ssize_t bytes_read =
367 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
368 if (bytes_read <= 0)
369 break;
370 total_read += bytes_read;
372 return total_read == bytes;
375 bool CreateSymbolicLink(const FilePath& target_path,
376 const FilePath& symlink_path) {
377 DCHECK(!symlink_path.empty());
378 DCHECK(!target_path.empty());
379 return ::symlink(target_path.value().c_str(),
380 symlink_path.value().c_str()) != -1;
383 bool ReadSymbolicLink(const FilePath& symlink_path,
384 FilePath* target_path) {
385 DCHECK(!symlink_path.empty());
386 DCHECK(target_path);
387 char buf[PATH_MAX];
388 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
390 if (count <= 0) {
391 target_path->clear();
392 return false;
395 *target_path = FilePath(FilePath::StringType(buf, count));
396 return true;
399 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
400 base::ThreadRestrictions::AssertIOAllowed();
401 DCHECK(mode);
403 stat_wrapper_t file_info;
404 // Uses stat(), because on symbolic link, lstat() does not return valid
405 // permission bits in st_mode
406 if (CallStat(path.value().c_str(), &file_info) != 0)
407 return false;
409 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
410 return true;
413 bool SetPosixFilePermissions(const FilePath& path,
414 int mode) {
415 base::ThreadRestrictions::AssertIOAllowed();
416 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
418 // Calls stat() so that we can preserve the higher bits like S_ISGID.
419 stat_wrapper_t stat_buf;
420 if (CallStat(path.value().c_str(), &stat_buf) != 0)
421 return false;
423 // Clears the existing permission bits, and adds the new ones.
424 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
425 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
427 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
428 return false;
430 return true;
433 // Creates and opens a temporary file in |directory|, returning the
434 // file descriptor. |path| is set to the temporary file path.
435 // This function does NOT unlink() the file.
436 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
437 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
438 *path = directory.Append(TempFileName());
439 const std::string& tmpdir_string = path->value();
440 // this should be OK since mkstemp just replaces characters in place
441 char* buffer = const_cast<char*>(tmpdir_string.c_str());
443 return HANDLE_EINTR(mkstemp(buffer));
446 bool CreateTemporaryFile(FilePath* path) {
447 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
448 FilePath directory;
449 if (!GetTempDir(&directory))
450 return false;
451 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
452 if (fd < 0)
453 return false;
454 ignore_result(HANDLE_EINTR(close(fd)));
455 return true;
458 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
459 FilePath directory;
460 if (!GetShmemTempDir(&directory, executable))
461 return NULL;
463 return CreateAndOpenTemporaryFileInDir(directory, path);
466 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
467 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
468 if (fd < 0)
469 return NULL;
471 FILE* file = fdopen(fd, "a+");
472 if (!file)
473 ignore_result(HANDLE_EINTR(close(fd)));
474 return file;
477 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
478 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
479 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
480 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
483 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
484 const FilePath::StringType& name_tmpl,
485 FilePath* new_dir) {
486 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
487 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
488 << "Directory name template must contain \"XXXXXX\".";
490 FilePath sub_dir = base_dir.Append(name_tmpl);
491 std::string sub_dir_string = sub_dir.value();
493 // this should be OK since mkdtemp just replaces characters in place
494 char* buffer = const_cast<char*>(sub_dir_string.c_str());
495 char* dtemp = mkdtemp(buffer);
496 if (!dtemp) {
497 DPLOG(ERROR) << "mkdtemp";
498 return false;
500 *new_dir = FilePath(dtemp);
501 return true;
504 bool CreateTemporaryDirInDir(const FilePath& base_dir,
505 const FilePath::StringType& prefix,
506 FilePath* new_dir) {
507 FilePath::StringType mkdtemp_template = prefix;
508 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
509 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
512 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
513 FilePath* new_temp_path) {
514 FilePath tmpdir;
515 if (!GetTempDir(&tmpdir))
516 return false;
518 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
521 bool CreateDirectoryAndGetError(const FilePath& full_path,
522 base::PlatformFileError* error) {
523 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
524 std::vector<FilePath> subpaths;
526 // Collect a list of all parent directories.
527 FilePath last_path = full_path;
528 subpaths.push_back(full_path);
529 for (FilePath path = full_path.DirName();
530 path.value() != last_path.value(); path = path.DirName()) {
531 subpaths.push_back(path);
532 last_path = path;
535 // Iterate through the parents and create the missing ones.
536 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
537 i != subpaths.rend(); ++i) {
538 if (DirectoryExists(*i))
539 continue;
540 if (mkdir(i->value().c_str(), 0700) == 0)
541 continue;
542 // Mkdir failed, but it might have failed with EEXIST, or some other error
543 // due to the the directory appearing out of thin air. This can occur if
544 // two processes are trying to create the same file system tree at the same
545 // time. Check to see if it exists and make sure it is a directory.
546 int saved_errno = errno;
547 if (!DirectoryExists(*i)) {
548 if (error)
549 *error = base::ErrnoToPlatformFileError(saved_errno);
550 return false;
553 return true;
556 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
557 const int kMaxAttempts = 20;
558 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
559 int uniquifier =
560 GetUniquePathNumber(path, base::FilePath::StringType());
561 if (uniquifier < 0)
562 break;
563 base::FilePath test_path = (uniquifier == 0) ? path :
564 path.InsertBeforeExtensionASCII(
565 base::StringPrintf(" (%d)", uniquifier));
566 if (mkdir(test_path.value().c_str(), 0777) == 0)
567 return test_path;
568 else if (errno != EEXIST)
569 break;
571 return base::FilePath();
574 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
575 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
576 bool IsLink(const FilePath& file_path) {
577 stat_wrapper_t st;
578 // If we can't lstat the file, it's safe to assume that the file won't at
579 // least be a 'followable' link.
580 if (CallLstat(file_path.value().c_str(), &st) != 0)
581 return false;
583 if (S_ISLNK(st.st_mode))
584 return true;
585 else
586 return false;
589 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
590 stat_wrapper_t file_info;
591 if (CallStat(file_path.value().c_str(), &file_info) != 0)
592 return false;
593 results->is_directory = S_ISDIR(file_info.st_mode);
594 results->size = file_info.st_size;
595 #if defined(OS_MACOSX)
596 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
597 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
598 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
599 #elif defined(OS_ANDROID)
600 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
601 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
602 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
603 #else
604 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
605 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
606 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
607 #endif
608 return true;
611 bool GetInode(const FilePath& path, ino_t* inode) {
612 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
613 struct stat buffer;
614 int result = stat(path.value().c_str(), &buffer);
615 if (result < 0)
616 return false;
618 *inode = buffer.st_ino;
619 return true;
622 FILE* OpenFile(const std::string& filename, const char* mode) {
623 return OpenFile(FilePath(filename), mode);
626 FILE* OpenFile(const FilePath& filename, const char* mode) {
627 base::ThreadRestrictions::AssertIOAllowed();
628 FILE* result = NULL;
629 do {
630 result = fopen(filename.value().c_str(), mode);
631 } while (!result && errno == EINTR);
632 return result;
635 int ReadFile(const FilePath& filename, char* data, int size) {
636 base::ThreadRestrictions::AssertIOAllowed();
637 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
638 if (fd < 0)
639 return -1;
641 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
642 if (int ret = HANDLE_EINTR(close(fd)) < 0)
643 return ret;
644 return bytes_read;
647 int WriteFile(const FilePath& filename, const char* data, int size) {
648 base::ThreadRestrictions::AssertIOAllowed();
649 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
650 if (fd < 0)
651 return -1;
653 int bytes_written = WriteFileDescriptor(fd, data, size);
654 if (int ret = HANDLE_EINTR(close(fd)) < 0)
655 return ret;
656 return bytes_written;
659 int WriteFileDescriptor(const int fd, const char* data, int size) {
660 // Allow for partial writes.
661 ssize_t bytes_written_total = 0;
662 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
663 bytes_written_total += bytes_written_partial) {
664 bytes_written_partial =
665 HANDLE_EINTR(write(fd, data + bytes_written_total,
666 size - bytes_written_total));
667 if (bytes_written_partial < 0)
668 return -1;
671 return bytes_written_total;
674 int AppendToFile(const FilePath& filename, const char* data, int size) {
675 base::ThreadRestrictions::AssertIOAllowed();
676 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
677 if (fd < 0)
678 return -1;
680 int bytes_written = WriteFileDescriptor(fd, data, size);
681 if (int ret = HANDLE_EINTR(close(fd)) < 0)
682 return ret;
683 return bytes_written;
686 // Gets the current working directory for the process.
687 bool GetCurrentDirectory(FilePath* dir) {
688 // getcwd can return ENOENT, which implies it checks against the disk.
689 base::ThreadRestrictions::AssertIOAllowed();
691 char system_buffer[PATH_MAX] = "";
692 if (!getcwd(system_buffer, sizeof(system_buffer))) {
693 NOTREACHED();
694 return false;
696 *dir = FilePath(system_buffer);
697 return true;
700 // Sets the current working directory for the process.
701 bool SetCurrentDirectory(const FilePath& path) {
702 base::ThreadRestrictions::AssertIOAllowed();
703 int ret = chdir(path.value().c_str());
704 return !ret;
707 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
708 FilePath real_path_result;
709 if (!RealPath(path, &real_path_result))
710 return false;
712 // To be consistant with windows, fail if |real_path_result| is a
713 // directory.
714 stat_wrapper_t file_info;
715 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
716 S_ISDIR(file_info.st_mode))
717 return false;
719 *normalized_path = real_path_result;
720 return true;
723 #if !defined(OS_MACOSX)
724 bool GetTempDir(FilePath* path) {
725 const char* tmp = getenv("TMPDIR");
726 if (tmp)
727 *path = FilePath(tmp);
728 else
729 #if defined(OS_ANDROID)
730 return PathService::Get(base::DIR_CACHE, path);
731 #else
732 *path = FilePath("/tmp");
733 #endif
734 return true;
737 #if !defined(OS_ANDROID)
739 #if defined(OS_LINUX)
740 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
741 // This depends on the mount options used for /dev/shm, which vary among
742 // different Linux distributions and possibly local configuration. It also
743 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
744 // but its kernel allows mprotect with PROT_EXEC anyway.
746 namespace {
748 bool DetermineDevShmExecutable() {
749 bool result = false;
750 FilePath path;
751 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
752 if (fd >= 0) {
753 ScopedFD shm_fd_closer(&fd);
754 Delete(path, false);
755 long sysconf_result = sysconf(_SC_PAGESIZE);
756 CHECK_GE(sysconf_result, 0);
757 size_t pagesize = static_cast<size_t>(sysconf_result);
758 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
759 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
760 if (mapping != MAP_FAILED) {
761 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
762 result = true;
763 munmap(mapping, pagesize);
766 return result;
769 }; // namespace
770 #endif // defined(OS_LINUX)
772 bool GetShmemTempDir(FilePath* path, bool executable) {
773 #if defined(OS_LINUX)
774 bool use_dev_shm = true;
775 if (executable) {
776 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
777 use_dev_shm = s_dev_shm_executable;
779 if (use_dev_shm) {
780 *path = FilePath("/dev/shm");
781 return true;
783 #endif
784 return GetTempDir(path);
786 #endif // !defined(OS_ANDROID)
788 FilePath GetHomeDir() {
789 #if defined(OS_CHROMEOS)
790 if (base::chromeos::IsRunningOnChromeOS())
791 return FilePath("/home/chronos/user");
792 #endif
794 const char* home_dir = getenv("HOME");
795 if (home_dir && home_dir[0])
796 return FilePath(home_dir);
798 #if defined(OS_ANDROID)
799 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
800 #else
801 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
802 base::ThreadRestrictions::AssertIOAllowed();
804 home_dir = g_get_home_dir();
805 if (home_dir && home_dir[0])
806 return FilePath(home_dir);
807 #endif
809 FilePath rv;
810 if (file_util::GetTempDir(&rv))
811 return rv;
813 // Last resort.
814 return FilePath("/tmp");
817 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
818 base::ThreadRestrictions::AssertIOAllowed();
819 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
820 if (infile < 0)
821 return false;
823 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
824 if (outfile < 0) {
825 ignore_result(HANDLE_EINTR(close(infile)));
826 return false;
829 const size_t kBufferSize = 32768;
830 std::vector<char> buffer(kBufferSize);
831 bool result = true;
833 while (result) {
834 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
835 if (bytes_read < 0) {
836 result = false;
837 break;
839 if (bytes_read == 0)
840 break;
841 // Allow for partial writes
842 ssize_t bytes_written_per_read = 0;
843 do {
844 ssize_t bytes_written_partial = HANDLE_EINTR(write(
845 outfile,
846 &buffer[bytes_written_per_read],
847 bytes_read - bytes_written_per_read));
848 if (bytes_written_partial < 0) {
849 result = false;
850 break;
852 bytes_written_per_read += bytes_written_partial;
853 } while (bytes_written_per_read < bytes_read);
856 if (HANDLE_EINTR(close(infile)) < 0)
857 result = false;
858 if (HANDLE_EINTR(close(outfile)) < 0)
859 result = false;
861 return result;
863 #endif // !defined(OS_MACOSX)
865 bool VerifyPathControlledByUser(const FilePath& base,
866 const FilePath& path,
867 uid_t owner_uid,
868 const std::set<gid_t>& group_gids) {
869 if (base != path && !base.IsParent(path)) {
870 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
871 << base.value() << "\", path = \"" << path.value() << "\"";
872 return false;
875 std::vector<FilePath::StringType> base_components;
876 std::vector<FilePath::StringType> path_components;
878 base.GetComponents(&base_components);
879 path.GetComponents(&path_components);
881 std::vector<FilePath::StringType>::const_iterator ib, ip;
882 for (ib = base_components.begin(), ip = path_components.begin();
883 ib != base_components.end(); ++ib, ++ip) {
884 // |base| must be a subpath of |path|, so all components should match.
885 // If these CHECKs fail, look at the test that base is a parent of
886 // path at the top of this function.
887 DCHECK(ip != path_components.end());
888 DCHECK(*ip == *ib);
891 FilePath current_path = base;
892 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
893 return false;
895 for (; ip != path_components.end(); ++ip) {
896 current_path = current_path.Append(*ip);
897 if (!VerifySpecificPathControlledByUser(
898 current_path, owner_uid, group_gids))
899 return false;
901 return true;
904 #if defined(OS_MACOSX) && !defined(OS_IOS)
905 bool VerifyPathControlledByAdmin(const FilePath& path) {
906 const unsigned kRootUid = 0;
907 const FilePath kFileSystemRoot("/");
909 // The name of the administrator group on mac os.
910 const char* const kAdminGroupNames[] = {
911 "admin",
912 "wheel"
915 // Reading the groups database may touch the file system.
916 base::ThreadRestrictions::AssertIOAllowed();
918 std::set<gid_t> allowed_group_ids;
919 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
920 struct group *group_record = getgrnam(kAdminGroupNames[i]);
921 if (!group_record) {
922 DPLOG(ERROR) << "Could not get the group ID of group \""
923 << kAdminGroupNames[i] << "\".";
924 continue;
927 allowed_group_ids.insert(group_record->gr_gid);
930 return VerifyPathControlledByUser(
931 kFileSystemRoot, path, kRootUid, allowed_group_ids);
933 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
935 int GetMaximumPathComponentLength(const FilePath& path) {
936 base::ThreadRestrictions::AssertIOAllowed();
937 return pathconf(path.value().c_str(), _PC_NAME_MAX);
940 } // namespace file_util