rAc - revert invalid suggestions to edit mode
[chromium-blink-merge.git] / base / file_util_posix.cc
blobf17b34161ca94312eaa153da27df038af23b0701
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_CHROMEOS) && defined(USE_GLIB)
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/android/content_uri_utils.h"
52 #include "base/os_compat_android.h"
53 #endif
55 #if !defined(OS_IOS)
56 #include <grp.h>
57 #endif
59 namespace base {
61 namespace {
63 #if defined(OS_BSD) || defined(OS_MACOSX)
64 typedef struct stat stat_wrapper_t;
65 static int CallStat(const char *path, stat_wrapper_t *sb) {
66 ThreadRestrictions::AssertIOAllowed();
67 return stat(path, sb);
69 static int CallLstat(const char *path, stat_wrapper_t *sb) {
70 ThreadRestrictions::AssertIOAllowed();
71 return lstat(path, sb);
73 #else
74 typedef struct stat64 stat_wrapper_t;
75 static int CallStat(const char *path, stat_wrapper_t *sb) {
76 ThreadRestrictions::AssertIOAllowed();
77 return stat64(path, sb);
79 static int CallLstat(const char *path, stat_wrapper_t *sb) {
80 ThreadRestrictions::AssertIOAllowed();
81 return lstat64(path, sb);
83 #if defined(OS_ANDROID)
84 static int CallFstat(int fd, stat_wrapper_t *sb) {
85 ThreadRestrictions::AssertIOAllowed();
86 return fstat64(fd, sb);
88 #endif
89 #endif
91 // Helper for NormalizeFilePath(), defined below.
92 bool RealPath(const FilePath& path, FilePath* real_path) {
93 ThreadRestrictions::AssertIOAllowed(); // For realpath().
94 FilePath::CharType buf[PATH_MAX];
95 if (!realpath(path.value().c_str(), buf))
96 return false;
98 *real_path = FilePath(buf);
99 return true;
102 // Helper for VerifyPathControlledByUser.
103 bool VerifySpecificPathControlledByUser(const FilePath& path,
104 uid_t owner_uid,
105 const std::set<gid_t>& group_gids) {
106 stat_wrapper_t stat_info;
107 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
108 DPLOG(ERROR) << "Failed to get information on path "
109 << path.value();
110 return false;
113 if (S_ISLNK(stat_info.st_mode)) {
114 DLOG(ERROR) << "Path " << path.value()
115 << " is a symbolic link.";
116 return false;
119 if (stat_info.st_uid != owner_uid) {
120 DLOG(ERROR) << "Path " << path.value()
121 << " is owned by the wrong user.";
122 return false;
125 if ((stat_info.st_mode & S_IWGRP) &&
126 !ContainsKey(group_gids, stat_info.st_gid)) {
127 DLOG(ERROR) << "Path " << path.value()
128 << " is writable by an unprivileged group.";
129 return false;
132 if (stat_info.st_mode & S_IWOTH) {
133 DLOG(ERROR) << "Path " << path.value()
134 << " is writable by any user.";
135 return false;
138 return true;
141 std::string TempFileName() {
142 #if defined(OS_MACOSX)
143 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
144 #endif
146 #if defined(GOOGLE_CHROME_BUILD)
147 return std::string(".com.google.Chrome.XXXXXX");
148 #else
149 return std::string(".org.chromium.Chromium.XXXXXX");
150 #endif
153 // Creates and opens a temporary file in |directory|, returning the
154 // file descriptor. |path| is set to the temporary file path.
155 // This function does NOT unlink() the file.
156 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
157 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
158 *path = directory.Append(base::TempFileName());
159 const std::string& tmpdir_string = path->value();
160 // this should be OK since mkstemp just replaces characters in place
161 char* buffer = const_cast<char*>(tmpdir_string.c_str());
163 return HANDLE_EINTR(mkstemp(buffer));
166 #if defined(OS_LINUX)
167 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
168 // This depends on the mount options used for /dev/shm, which vary among
169 // different Linux distributions and possibly local configuration. It also
170 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
171 // but its kernel allows mprotect with PROT_EXEC anyway.
172 bool DetermineDevShmExecutable() {
173 bool result = false;
174 FilePath path;
175 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
176 if (fd >= 0) {
177 file_util::ScopedFD shm_fd_closer(&fd);
178 DeleteFile(path, false);
179 long sysconf_result = sysconf(_SC_PAGESIZE);
180 CHECK_GE(sysconf_result, 0);
181 size_t pagesize = static_cast<size_t>(sysconf_result);
182 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
183 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
184 if (mapping != MAP_FAILED) {
185 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
186 result = true;
187 munmap(mapping, pagesize);
190 return result;
192 #endif // defined(OS_LINUX)
194 } // namespace
196 FilePath MakeAbsoluteFilePath(const FilePath& input) {
197 ThreadRestrictions::AssertIOAllowed();
198 char full_path[PATH_MAX];
199 if (realpath(input.value().c_str(), full_path) == NULL)
200 return FilePath();
201 return FilePath(full_path);
204 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
205 // which works both with and without the recursive flag. I'm not sure we need
206 // that functionality. If not, remove from file_util_win.cc, otherwise add it
207 // here.
208 bool DeleteFile(const FilePath& path, bool recursive) {
209 ThreadRestrictions::AssertIOAllowed();
210 const char* path_str = path.value().c_str();
211 stat_wrapper_t file_info;
212 int test = CallLstat(path_str, &file_info);
213 if (test != 0) {
214 // The Windows version defines this condition as success.
215 bool ret = (errno == ENOENT || errno == ENOTDIR);
216 return ret;
218 if (!S_ISDIR(file_info.st_mode))
219 return (unlink(path_str) == 0);
220 if (!recursive)
221 return (rmdir(path_str) == 0);
223 bool success = true;
224 std::stack<std::string> directories;
225 directories.push(path.value());
226 FileEnumerator traversal(path, true,
227 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
228 FileEnumerator::SHOW_SYM_LINKS);
229 for (FilePath current = traversal.Next(); success && !current.empty();
230 current = traversal.Next()) {
231 if (traversal.GetInfo().IsDirectory())
232 directories.push(current.value());
233 else
234 success = (unlink(current.value().c_str()) == 0);
237 while (success && !directories.empty()) {
238 FilePath dir = FilePath(directories.top());
239 directories.pop();
240 success = (rmdir(dir.value().c_str()) == 0);
242 return success;
245 bool ReplaceFile(const FilePath& from_path,
246 const FilePath& to_path,
247 File::Error* error) {
248 ThreadRestrictions::AssertIOAllowed();
249 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
250 return true;
251 if (error)
252 *error = File::OSErrorToFileError(errno);
253 return false;
256 bool CopyDirectory(const FilePath& from_path,
257 const FilePath& to_path,
258 bool recursive) {
259 ThreadRestrictions::AssertIOAllowed();
260 // Some old callers of CopyDirectory want it to support wildcards.
261 // After some discussion, we decided to fix those callers.
262 // Break loudly here if anyone tries to do this.
263 DCHECK(to_path.value().find('*') == std::string::npos);
264 DCHECK(from_path.value().find('*') == std::string::npos);
266 if (from_path.value().size() >= PATH_MAX) {
267 return false;
270 // This function does not properly handle destinations within the source
271 FilePath real_to_path = to_path;
272 if (PathExists(real_to_path)) {
273 real_to_path = MakeAbsoluteFilePath(real_to_path);
274 if (real_to_path.empty())
275 return false;
276 } else {
277 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
278 if (real_to_path.empty())
279 return false;
281 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
282 if (real_from_path.empty())
283 return false;
284 if (real_to_path.value().size() >= real_from_path.value().size() &&
285 real_to_path.value().compare(0, real_from_path.value().size(),
286 real_from_path.value()) == 0) {
287 return false;
290 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
291 if (recursive)
292 traverse_type |= FileEnumerator::DIRECTORIES;
293 FileEnumerator traversal(from_path, recursive, traverse_type);
295 // We have to mimic windows behavior here. |to_path| may not exist yet,
296 // start the loop with |to_path|.
297 struct stat from_stat;
298 FilePath current = from_path;
299 if (stat(from_path.value().c_str(), &from_stat) < 0) {
300 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
301 << from_path.value() << " errno = " << errno;
302 return false;
304 struct stat to_path_stat;
305 FilePath from_path_base = from_path;
306 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
307 S_ISDIR(to_path_stat.st_mode)) {
308 // If the destination already exists and is a directory, then the
309 // top level of source needs to be copied.
310 from_path_base = from_path.DirName();
313 // The Windows version of this function assumes that non-recursive calls
314 // will always have a directory for from_path.
315 // TODO(maruel): This is not necessary anymore.
316 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
318 bool success = true;
319 while (success && !current.empty()) {
320 // current is the source path, including from_path, so append
321 // the suffix after from_path to to_path to create the target_path.
322 FilePath target_path(to_path);
323 if (from_path_base != current) {
324 if (!from_path_base.AppendRelativePath(current, &target_path)) {
325 success = false;
326 break;
330 if (S_ISDIR(from_stat.st_mode)) {
331 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
332 errno != EEXIST) {
333 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
334 << target_path.value() << " errno = " << errno;
335 success = false;
337 } else if (S_ISREG(from_stat.st_mode)) {
338 if (!CopyFile(current, target_path)) {
339 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
340 << target_path.value();
341 success = false;
343 } else {
344 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
345 << current.value();
348 current = traversal.Next();
349 if (!current.empty())
350 from_stat = traversal.GetInfo().stat();
353 return success;
356 bool PathExists(const FilePath& path) {
357 ThreadRestrictions::AssertIOAllowed();
358 #if defined(OS_ANDROID)
359 if (path.IsContentUri()) {
360 return ContentUriExists(path);
362 #endif
363 return access(path.value().c_str(), F_OK) == 0;
366 bool PathIsWritable(const FilePath& path) {
367 ThreadRestrictions::AssertIOAllowed();
368 return access(path.value().c_str(), W_OK) == 0;
371 bool DirectoryExists(const FilePath& path) {
372 ThreadRestrictions::AssertIOAllowed();
373 stat_wrapper_t file_info;
374 if (CallStat(path.value().c_str(), &file_info) == 0)
375 return S_ISDIR(file_info.st_mode);
376 return false;
379 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
380 size_t total_read = 0;
381 while (total_read < bytes) {
382 ssize_t bytes_read =
383 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
384 if (bytes_read <= 0)
385 break;
386 total_read += bytes_read;
388 return total_read == bytes;
391 bool CreateSymbolicLink(const FilePath& target_path,
392 const FilePath& symlink_path) {
393 DCHECK(!symlink_path.empty());
394 DCHECK(!target_path.empty());
395 return ::symlink(target_path.value().c_str(),
396 symlink_path.value().c_str()) != -1;
399 bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
400 DCHECK(!symlink_path.empty());
401 DCHECK(target_path);
402 char buf[PATH_MAX];
403 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
405 if (count <= 0) {
406 target_path->clear();
407 return false;
410 *target_path = FilePath(FilePath::StringType(buf, count));
411 return true;
414 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
415 ThreadRestrictions::AssertIOAllowed();
416 DCHECK(mode);
418 stat_wrapper_t file_info;
419 // Uses stat(), because on symbolic link, lstat() does not return valid
420 // permission bits in st_mode
421 if (CallStat(path.value().c_str(), &file_info) != 0)
422 return false;
424 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
425 return true;
428 bool SetPosixFilePermissions(const FilePath& path,
429 int mode) {
430 ThreadRestrictions::AssertIOAllowed();
431 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
433 // Calls stat() so that we can preserve the higher bits like S_ISGID.
434 stat_wrapper_t stat_buf;
435 if (CallStat(path.value().c_str(), &stat_buf) != 0)
436 return false;
438 // Clears the existing permission bits, and adds the new ones.
439 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
440 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
442 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
443 return false;
445 return true;
448 #if !defined(OS_MACOSX)
449 // This is implemented in file_util_mac.mm for Mac.
450 bool GetTempDir(FilePath* path) {
451 const char* tmp = getenv("TMPDIR");
452 if (tmp) {
453 *path = FilePath(tmp);
454 } else {
455 #if defined(OS_ANDROID)
456 return PathService::Get(base::DIR_CACHE, path);
457 #else
458 *path = FilePath("/tmp");
459 #endif
461 return true;
463 #endif // !defined(OS_MACOSX)
465 #if !defined(OS_MACOSX) && !defined(OS_ANDROID)
466 // This is implemented in file_util_mac.mm and file_util_android.cc for those
467 // platforms.
468 bool GetShmemTempDir(bool executable, FilePath* path) {
469 #if defined(OS_LINUX)
470 bool use_dev_shm = true;
471 if (executable) {
472 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
473 use_dev_shm = s_dev_shm_executable;
475 if (use_dev_shm) {
476 *path = FilePath("/dev/shm");
477 return true;
479 #endif
480 return GetTempDir(path);
482 #endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
484 #if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm.
485 FilePath GetHomeDir() {
486 #if defined(OS_CHROMEOS)
487 if (SysInfo::IsRunningOnChromeOS())
488 return FilePath("/home/chronos/user");
489 #endif
491 const char* home_dir = getenv("HOME");
492 if (home_dir && home_dir[0])
493 return FilePath(home_dir);
495 #if defined(OS_ANDROID)
496 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
497 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
498 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
499 // this may do I/O. However, it should be rare that $HOME is not defined and
500 // this is typically called from the path service which has no threading
501 // restrictions. The path service will cache the result which limits the
502 // badness of blocking on I/O. As a result, we don't have a thread
503 // restriction here.
504 home_dir = g_get_home_dir();
505 if (home_dir && home_dir[0])
506 return FilePath(home_dir);
507 #endif
509 FilePath rv;
510 if (GetTempDir(&rv))
511 return rv;
513 // Last resort.
514 return FilePath("/tmp");
516 #endif // !defined(OS_MACOSX)
518 bool CreateTemporaryFile(FilePath* path) {
519 ThreadRestrictions::AssertIOAllowed(); // For call to close().
520 FilePath directory;
521 if (!GetTempDir(&directory))
522 return false;
523 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
524 if (fd < 0)
525 return false;
526 close(fd);
527 return true;
530 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
531 FilePath directory;
532 if (!GetShmemTempDir(executable, &directory))
533 return NULL;
535 return CreateAndOpenTemporaryFileInDir(directory, path);
538 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
539 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
540 if (fd < 0)
541 return NULL;
543 FILE* file = fdopen(fd, "a+");
544 if (!file)
545 close(fd);
546 return file;
549 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
550 ThreadRestrictions::AssertIOAllowed(); // For call to close().
551 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
552 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
555 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
556 const FilePath::StringType& name_tmpl,
557 FilePath* new_dir) {
558 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
559 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
560 << "Directory name template must contain \"XXXXXX\".";
562 FilePath sub_dir = base_dir.Append(name_tmpl);
563 std::string sub_dir_string = sub_dir.value();
565 // this should be OK since mkdtemp just replaces characters in place
566 char* buffer = const_cast<char*>(sub_dir_string.c_str());
567 char* dtemp = mkdtemp(buffer);
568 if (!dtemp) {
569 DPLOG(ERROR) << "mkdtemp";
570 return false;
572 *new_dir = FilePath(dtemp);
573 return true;
576 bool CreateTemporaryDirInDir(const FilePath& base_dir,
577 const FilePath::StringType& prefix,
578 FilePath* new_dir) {
579 FilePath::StringType mkdtemp_template = prefix;
580 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
581 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
584 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
585 FilePath* new_temp_path) {
586 FilePath tmpdir;
587 if (!GetTempDir(&tmpdir))
588 return false;
590 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
593 bool CreateDirectoryAndGetError(const FilePath& full_path,
594 File::Error* error) {
595 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
596 std::vector<FilePath> subpaths;
598 // Collect a list of all parent directories.
599 FilePath last_path = full_path;
600 subpaths.push_back(full_path);
601 for (FilePath path = full_path.DirName();
602 path.value() != last_path.value(); path = path.DirName()) {
603 subpaths.push_back(path);
604 last_path = path;
607 // Iterate through the parents and create the missing ones.
608 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
609 i != subpaths.rend(); ++i) {
610 if (DirectoryExists(*i))
611 continue;
612 if (mkdir(i->value().c_str(), 0700) == 0)
613 continue;
614 // Mkdir failed, but it might have failed with EEXIST, or some other error
615 // due to the the directory appearing out of thin air. This can occur if
616 // two processes are trying to create the same file system tree at the same
617 // time. Check to see if it exists and make sure it is a directory.
618 int saved_errno = errno;
619 if (!DirectoryExists(*i)) {
620 if (error)
621 *error = File::OSErrorToFileError(saved_errno);
622 return false;
625 return true;
628 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
629 FilePath real_path_result;
630 if (!RealPath(path, &real_path_result))
631 return false;
633 // To be consistant with windows, fail if |real_path_result| is a
634 // directory.
635 stat_wrapper_t file_info;
636 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
637 S_ISDIR(file_info.st_mode))
638 return false;
640 *normalized_path = real_path_result;
641 return true;
644 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
645 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
646 bool IsLink(const FilePath& file_path) {
647 stat_wrapper_t st;
648 // If we can't lstat the file, it's safe to assume that the file won't at
649 // least be a 'followable' link.
650 if (CallLstat(file_path.value().c_str(), &st) != 0)
651 return false;
653 if (S_ISLNK(st.st_mode))
654 return true;
655 else
656 return false;
659 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
660 stat_wrapper_t file_info;
661 #if defined(OS_ANDROID)
662 if (file_path.IsContentUri()) {
663 int fd = OpenContentUriForRead(file_path);
664 if (fd < 0)
665 return false;
666 file_util::ScopedFD scoped_fd(&fd);
667 if (CallFstat(fd, &file_info) != 0)
668 return false;
669 } else {
670 #endif // defined(OS_ANDROID)
671 if (CallStat(file_path.value().c_str(), &file_info) != 0)
672 return false;
673 #if defined(OS_ANDROID)
675 #endif // defined(OS_ANDROID)
676 results->is_directory = S_ISDIR(file_info.st_mode);
677 results->size = file_info.st_size;
678 #if defined(OS_MACOSX)
679 results->last_modified = Time::FromTimeSpec(file_info.st_mtimespec);
680 results->last_accessed = Time::FromTimeSpec(file_info.st_atimespec);
681 results->creation_time = Time::FromTimeSpec(file_info.st_ctimespec);
682 #elif defined(OS_ANDROID)
683 results->last_modified = Time::FromTimeT(file_info.st_mtime);
684 results->last_accessed = Time::FromTimeT(file_info.st_atime);
685 results->creation_time = Time::FromTimeT(file_info.st_ctime);
686 #else
687 results->last_modified = Time::FromTimeSpec(file_info.st_mtim);
688 results->last_accessed = Time::FromTimeSpec(file_info.st_atim);
689 results->creation_time = Time::FromTimeSpec(file_info.st_ctim);
690 #endif
691 return true;
694 FILE* OpenFile(const FilePath& filename, const char* mode) {
695 ThreadRestrictions::AssertIOAllowed();
696 FILE* result = NULL;
697 do {
698 result = fopen(filename.value().c_str(), mode);
699 } while (!result && errno == EINTR);
700 return result;
703 int ReadFile(const FilePath& filename, char* data, int size) {
704 ThreadRestrictions::AssertIOAllowed();
705 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
706 if (fd < 0)
707 return -1;
709 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
710 if (int ret = IGNORE_EINTR(close(fd)) < 0)
711 return ret;
712 return bytes_read;
715 } // namespace base
717 // -----------------------------------------------------------------------------
719 namespace file_util {
721 using base::stat_wrapper_t;
722 using base::CallStat;
723 using base::CallLstat;
724 using base::CreateAndOpenFdForTemporaryFile;
725 using base::DirectoryExists;
726 using base::FileEnumerator;
727 using base::FilePath;
728 using base::MakeAbsoluteFilePath;
729 using base::VerifySpecificPathControlledByUser;
731 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
732 const int kMaxAttempts = 20;
733 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
734 int uniquifier =
735 GetUniquePathNumber(path, base::FilePath::StringType());
736 if (uniquifier < 0)
737 break;
738 base::FilePath test_path = (uniquifier == 0) ? path :
739 path.InsertBeforeExtensionASCII(
740 base::StringPrintf(" (%d)", uniquifier));
741 if (mkdir(test_path.value().c_str(), 0777) == 0)
742 return test_path;
743 else if (errno != EEXIST)
744 break;
746 return base::FilePath();
749 FILE* OpenFile(const std::string& filename, const char* mode) {
750 return OpenFile(FilePath(filename), mode);
753 int WriteFile(const FilePath& filename, const char* data, int size) {
754 base::ThreadRestrictions::AssertIOAllowed();
755 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
756 if (fd < 0)
757 return -1;
759 int bytes_written = WriteFileDescriptor(fd, data, size);
760 if (int ret = IGNORE_EINTR(close(fd)) < 0)
761 return ret;
762 return bytes_written;
765 int WriteFileDescriptor(const int fd, const char* data, int size) {
766 // Allow for partial writes.
767 ssize_t bytes_written_total = 0;
768 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
769 bytes_written_total += bytes_written_partial) {
770 bytes_written_partial =
771 HANDLE_EINTR(write(fd, data + bytes_written_total,
772 size - bytes_written_total));
773 if (bytes_written_partial < 0)
774 return -1;
777 return bytes_written_total;
780 int AppendToFile(const FilePath& filename, const char* data, int size) {
781 base::ThreadRestrictions::AssertIOAllowed();
782 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
783 if (fd < 0)
784 return -1;
786 int bytes_written = WriteFileDescriptor(fd, data, size);
787 if (int ret = IGNORE_EINTR(close(fd)) < 0)
788 return ret;
789 return bytes_written;
792 // Gets the current working directory for the process.
793 bool GetCurrentDirectory(FilePath* dir) {
794 // getcwd can return ENOENT, which implies it checks against the disk.
795 base::ThreadRestrictions::AssertIOAllowed();
797 char system_buffer[PATH_MAX] = "";
798 if (!getcwd(system_buffer, sizeof(system_buffer))) {
799 NOTREACHED();
800 return false;
802 *dir = FilePath(system_buffer);
803 return true;
806 // Sets the current working directory for the process.
807 bool SetCurrentDirectory(const FilePath& path) {
808 base::ThreadRestrictions::AssertIOAllowed();
809 int ret = chdir(path.value().c_str());
810 return !ret;
813 bool VerifyPathControlledByUser(const FilePath& base,
814 const FilePath& path,
815 uid_t owner_uid,
816 const std::set<gid_t>& group_gids) {
817 if (base != path && !base.IsParent(path)) {
818 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
819 << base.value() << "\", path = \"" << path.value() << "\"";
820 return false;
823 std::vector<FilePath::StringType> base_components;
824 std::vector<FilePath::StringType> path_components;
826 base.GetComponents(&base_components);
827 path.GetComponents(&path_components);
829 std::vector<FilePath::StringType>::const_iterator ib, ip;
830 for (ib = base_components.begin(), ip = path_components.begin();
831 ib != base_components.end(); ++ib, ++ip) {
832 // |base| must be a subpath of |path|, so all components should match.
833 // If these CHECKs fail, look at the test that base is a parent of
834 // path at the top of this function.
835 DCHECK(ip != path_components.end());
836 DCHECK(*ip == *ib);
839 FilePath current_path = base;
840 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
841 return false;
843 for (; ip != path_components.end(); ++ip) {
844 current_path = current_path.Append(*ip);
845 if (!VerifySpecificPathControlledByUser(
846 current_path, owner_uid, group_gids))
847 return false;
849 return true;
852 #if defined(OS_MACOSX) && !defined(OS_IOS)
853 bool VerifyPathControlledByAdmin(const FilePath& path) {
854 const unsigned kRootUid = 0;
855 const FilePath kFileSystemRoot("/");
857 // The name of the administrator group on mac os.
858 const char* const kAdminGroupNames[] = {
859 "admin",
860 "wheel"
863 // Reading the groups database may touch the file system.
864 base::ThreadRestrictions::AssertIOAllowed();
866 std::set<gid_t> allowed_group_ids;
867 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
868 struct group *group_record = getgrnam(kAdminGroupNames[i]);
869 if (!group_record) {
870 DPLOG(ERROR) << "Could not get the group ID of group \""
871 << kAdminGroupNames[i] << "\".";
872 continue;
875 allowed_group_ids.insert(group_record->gr_gid);
878 return VerifyPathControlledByUser(
879 kFileSystemRoot, path, kRootUid, allowed_group_ids);
881 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
883 int GetMaximumPathComponentLength(const FilePath& path) {
884 base::ThreadRestrictions::AssertIOAllowed();
885 return pathconf(path.value().c_str(), _PC_NAME_MAX);
888 } // namespace file_util
890 namespace base {
891 namespace internal {
893 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
894 ThreadRestrictions::AssertIOAllowed();
895 // Windows compatibility: if to_path exists, from_path and to_path
896 // must be the same type, either both files, or both directories.
897 stat_wrapper_t to_file_info;
898 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
899 stat_wrapper_t from_file_info;
900 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
901 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
902 return false;
903 } else {
904 return false;
908 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
909 return true;
911 if (!CopyDirectory(from_path, to_path, true))
912 return false;
914 DeleteFile(from_path, true);
915 return true;
918 #if !defined(OS_MACOSX)
919 // Mac has its own implementation, this is for all other Posix systems.
920 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
921 ThreadRestrictions::AssertIOAllowed();
922 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
923 if (infile < 0)
924 return false;
926 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
927 if (outfile < 0) {
928 close(infile);
929 return false;
932 const size_t kBufferSize = 32768;
933 std::vector<char> buffer(kBufferSize);
934 bool result = true;
936 while (result) {
937 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
938 if (bytes_read < 0) {
939 result = false;
940 break;
942 if (bytes_read == 0)
943 break;
944 // Allow for partial writes
945 ssize_t bytes_written_per_read = 0;
946 do {
947 ssize_t bytes_written_partial = HANDLE_EINTR(write(
948 outfile,
949 &buffer[bytes_written_per_read],
950 bytes_read - bytes_written_per_read));
951 if (bytes_written_partial < 0) {
952 result = false;
953 break;
955 bytes_written_per_read += bytes_written_partial;
956 } while (bytes_written_per_read < bytes_read);
959 if (IGNORE_EINTR(close(infile)) < 0)
960 result = false;
961 if (IGNORE_EINTR(close(outfile)) < 0)
962 result = false;
964 return result;
966 #endif // !defined(OS_MACOSX)
968 } // namespace internal
969 } // namespace base