Add test_runner support for new accessibility event
[chromium-blink-merge.git] / base / files / file_util_posix.cc
blobdad8eddb170a8731639f1530874a651d770f3b84
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 #elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
28 #include <glib.h> // for g_get_home_dir()
29 #endif
31 #include "base/basictypes.h"
32 #include "base/files/file_enumerator.h"
33 #include "base/files/file_path.h"
34 #include "base/files/scoped_file.h"
35 #include "base/logging.h"
36 #include "base/memory/scoped_ptr.h"
37 #include "base/memory/singleton.h"
38 #include "base/path_service.h"
39 #include "base/posix/eintr_wrapper.h"
40 #include "base/stl_util.h"
41 #include "base/strings/string_util.h"
42 #include "base/strings/stringprintf.h"
43 #include "base/strings/sys_string_conversions.h"
44 #include "base/strings/utf_string_conversions.h"
45 #include "base/sys_info.h"
46 #include "base/threading/thread_restrictions.h"
47 #include "base/time/time.h"
49 #if defined(OS_ANDROID)
50 #include "base/android/content_uri_utils.h"
51 #include "base/os_compat_android.h"
52 #endif
54 #if !defined(OS_IOS)
55 #include <grp.h>
56 #endif
58 namespace base {
60 #if !defined(OS_NACL_NONSFI)
61 namespace {
63 #if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
64 static int CallStat(const char *path, stat_wrapper_t *sb) {
65 ThreadRestrictions::AssertIOAllowed();
66 return stat(path, sb);
68 static int CallLstat(const char *path, stat_wrapper_t *sb) {
69 ThreadRestrictions::AssertIOAllowed();
70 return lstat(path, sb);
72 #else // defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
73 static int CallStat(const char *path, stat_wrapper_t *sb) {
74 ThreadRestrictions::AssertIOAllowed();
75 return stat64(path, sb);
77 static int CallLstat(const char *path, stat_wrapper_t *sb) {
78 ThreadRestrictions::AssertIOAllowed();
79 return lstat64(path, sb);
81 #endif // !(defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL))
83 // Helper for NormalizeFilePath(), defined below.
84 bool RealPath(const FilePath& path, FilePath* real_path) {
85 ThreadRestrictions::AssertIOAllowed(); // For realpath().
86 FilePath::CharType buf[PATH_MAX];
87 if (!realpath(path.value().c_str(), buf))
88 return false;
90 *real_path = FilePath(buf);
91 return true;
94 // Helper for VerifyPathControlledByUser.
95 bool VerifySpecificPathControlledByUser(const FilePath& path,
96 uid_t owner_uid,
97 const std::set<gid_t>& group_gids) {
98 stat_wrapper_t stat_info;
99 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
100 DPLOG(ERROR) << "Failed to get information on path "
101 << path.value();
102 return false;
105 if (S_ISLNK(stat_info.st_mode)) {
106 DLOG(ERROR) << "Path " << path.value()
107 << " is a symbolic link.";
108 return false;
111 if (stat_info.st_uid != owner_uid) {
112 DLOG(ERROR) << "Path " << path.value()
113 << " is owned by the wrong user.";
114 return false;
117 if ((stat_info.st_mode & S_IWGRP) &&
118 !ContainsKey(group_gids, stat_info.st_gid)) {
119 DLOG(ERROR) << "Path " << path.value()
120 << " is writable by an unprivileged group.";
121 return false;
124 if (stat_info.st_mode & S_IWOTH) {
125 DLOG(ERROR) << "Path " << path.value()
126 << " is writable by any user.";
127 return false;
130 return true;
133 std::string TempFileName() {
134 #if defined(OS_MACOSX)
135 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
136 #endif
138 #if defined(GOOGLE_CHROME_BUILD)
139 return std::string(".com.google.Chrome.XXXXXX");
140 #else
141 return std::string(".org.chromium.Chromium.XXXXXX");
142 #endif
145 // Creates and opens a temporary file in |directory|, returning the
146 // file descriptor. |path| is set to the temporary file path.
147 // This function does NOT unlink() the file.
148 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
149 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
150 *path = directory.Append(base::TempFileName());
151 const std::string& tmpdir_string = path->value();
152 // this should be OK since mkstemp just replaces characters in place
153 char* buffer = const_cast<char*>(tmpdir_string.c_str());
155 return HANDLE_EINTR(mkstemp(buffer));
158 #if defined(OS_LINUX)
159 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
160 // This depends on the mount options used for /dev/shm, which vary among
161 // different Linux distributions and possibly local configuration. It also
162 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
163 // but its kernel allows mprotect with PROT_EXEC anyway.
164 bool DetermineDevShmExecutable() {
165 bool result = false;
166 FilePath path;
168 ScopedFD fd(CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path));
169 if (fd.is_valid()) {
170 DeleteFile(path, false);
171 long sysconf_result = sysconf(_SC_PAGESIZE);
172 CHECK_GE(sysconf_result, 0);
173 size_t pagesize = static_cast<size_t>(sysconf_result);
174 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
175 void* mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd.get(), 0);
176 if (mapping != MAP_FAILED) {
177 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
178 result = true;
179 munmap(mapping, pagesize);
182 return result;
184 #endif // defined(OS_LINUX)
186 } // namespace
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;
367 bool DirectoryExists(const FilePath& path) {
368 ThreadRestrictions::AssertIOAllowed();
369 stat_wrapper_t file_info;
370 if (CallStat(path.value().c_str(), &file_info) == 0)
371 return S_ISDIR(file_info.st_mode);
372 return false;
374 #endif // !defined(OS_NACL_NONSFI)
376 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
377 size_t total_read = 0;
378 while (total_read < bytes) {
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 #elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
480 // g_get_home_dir calls getpwent, which can fall through to LDAP calls so
481 // this may do I/O. However, it should be rare that $HOME is not defined and
482 // this is typically called from the path service which has no threading
483 // restrictions. The path service will cache the result which limits the
484 // badness of blocking on I/O. As a result, we don't have a thread
485 // restriction here.
486 home_dir = g_get_home_dir();
487 if (home_dir && home_dir[0])
488 return FilePath(home_dir);
489 #endif
491 FilePath rv;
492 if (GetTempDir(&rv))
493 return rv;
495 // Last resort.
496 return FilePath("/tmp");
498 #endif // !defined(OS_MACOSX)
500 bool CreateTemporaryFile(FilePath* path) {
501 ThreadRestrictions::AssertIOAllowed(); // For call to close().
502 FilePath directory;
503 if (!GetTempDir(&directory))
504 return false;
505 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
506 if (fd < 0)
507 return false;
508 close(fd);
509 return true;
512 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
513 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
514 if (fd < 0)
515 return NULL;
517 FILE* file = fdopen(fd, "a+");
518 if (!file)
519 close(fd);
520 return file;
523 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
524 ThreadRestrictions::AssertIOAllowed(); // For call to close().
525 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
526 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
529 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
530 const FilePath::StringType& name_tmpl,
531 FilePath* new_dir) {
532 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
533 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
534 << "Directory name template must contain \"XXXXXX\".";
536 FilePath sub_dir = base_dir.Append(name_tmpl);
537 std::string sub_dir_string = sub_dir.value();
539 // this should be OK since mkdtemp just replaces characters in place
540 char* buffer = const_cast<char*>(sub_dir_string.c_str());
541 char* dtemp = mkdtemp(buffer);
542 if (!dtemp) {
543 DPLOG(ERROR) << "mkdtemp";
544 return false;
546 *new_dir = FilePath(dtemp);
547 return true;
550 bool CreateTemporaryDirInDir(const FilePath& base_dir,
551 const FilePath::StringType& prefix,
552 FilePath* new_dir) {
553 FilePath::StringType mkdtemp_template = prefix;
554 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
555 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
558 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
559 FilePath* new_temp_path) {
560 FilePath tmpdir;
561 if (!GetTempDir(&tmpdir))
562 return false;
564 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
567 bool CreateDirectoryAndGetError(const FilePath& full_path,
568 File::Error* error) {
569 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
570 std::vector<FilePath> subpaths;
572 // Collect a list of all parent directories.
573 FilePath last_path = full_path;
574 subpaths.push_back(full_path);
575 for (FilePath path = full_path.DirName();
576 path.value() != last_path.value(); path = path.DirName()) {
577 subpaths.push_back(path);
578 last_path = path;
581 // Iterate through the parents and create the missing ones.
582 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
583 i != subpaths.rend(); ++i) {
584 if (DirectoryExists(*i))
585 continue;
586 if (mkdir(i->value().c_str(), 0700) == 0)
587 continue;
588 // Mkdir failed, but it might have failed with EEXIST, or some other error
589 // due to the the directory appearing out of thin air. This can occur if
590 // two processes are trying to create the same file system tree at the same
591 // time. Check to see if it exists and make sure it is a directory.
592 int saved_errno = errno;
593 if (!DirectoryExists(*i)) {
594 if (error)
595 *error = File::OSErrorToFileError(saved_errno);
596 return false;
599 return true;
602 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
603 FilePath real_path_result;
604 if (!RealPath(path, &real_path_result))
605 return false;
607 // To be consistant with windows, fail if |real_path_result| is a
608 // directory.
609 stat_wrapper_t file_info;
610 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
611 S_ISDIR(file_info.st_mode))
612 return false;
614 *normalized_path = real_path_result;
615 return true;
618 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
619 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
620 bool IsLink(const FilePath& file_path) {
621 stat_wrapper_t st;
622 // If we can't lstat the file, it's safe to assume that the file won't at
623 // least be a 'followable' link.
624 if (CallLstat(file_path.value().c_str(), &st) != 0)
625 return false;
627 if (S_ISLNK(st.st_mode))
628 return true;
629 else
630 return false;
633 bool GetFileInfo(const FilePath& file_path, File::Info* results) {
634 stat_wrapper_t file_info;
635 #if defined(OS_ANDROID)
636 if (file_path.IsContentUri()) {
637 File file = OpenContentUriForRead(file_path);
638 if (!file.IsValid())
639 return false;
640 return file.GetInfo(results);
641 } else {
642 #endif // defined(OS_ANDROID)
643 if (CallStat(file_path.value().c_str(), &file_info) != 0)
644 return false;
645 #if defined(OS_ANDROID)
647 #endif // defined(OS_ANDROID)
649 results->FromStat(file_info);
650 return true;
653 FILE* OpenFile(const FilePath& filename, const char* mode) {
654 ThreadRestrictions::AssertIOAllowed();
655 FILE* result = NULL;
656 do {
657 result = fopen(filename.value().c_str(), mode);
658 } while (!result && errno == EINTR);
659 return result;
662 // NaCl doesn't implement system calls to open files directly.
663 #if !defined(OS_NACL)
664 FILE* FileToFILE(File file, const char* mode) {
665 FILE* stream = fdopen(file.GetPlatformFile(), mode);
666 if (stream)
667 file.TakePlatformFile();
668 return stream;
670 #endif // !defined(OS_NACL)
672 int ReadFile(const FilePath& filename, char* data, int max_size) {
673 ThreadRestrictions::AssertIOAllowed();
674 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
675 if (fd < 0)
676 return -1;
678 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, max_size));
679 if (IGNORE_EINTR(close(fd)) < 0)
680 return -1;
681 return bytes_read;
684 int WriteFile(const FilePath& filename, const char* data, int size) {
685 ThreadRestrictions::AssertIOAllowed();
686 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0640));
687 if (fd < 0)
688 return -1;
690 int bytes_written = WriteFileDescriptor(fd, data, size) ? size : -1;
691 if (IGNORE_EINTR(close(fd)) < 0)
692 return -1;
693 return bytes_written;
696 bool WriteFileDescriptor(const int fd, const char* data, int size) {
697 // Allow for partial writes.
698 ssize_t bytes_written_total = 0;
699 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
700 bytes_written_total += bytes_written_partial) {
701 bytes_written_partial =
702 HANDLE_EINTR(write(fd, data + bytes_written_total,
703 size - bytes_written_total));
704 if (bytes_written_partial < 0)
705 return false;
708 return true;
711 bool AppendToFile(const FilePath& filename, const char* data, int size) {
712 ThreadRestrictions::AssertIOAllowed();
713 bool ret = true;
714 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
715 if (fd < 0) {
716 VPLOG(1) << "Unable to create file " << filename.value();
717 return false;
720 // This call will either write all of the data or return false.
721 if (!WriteFileDescriptor(fd, data, size)) {
722 VPLOG(1) << "Error while writing to file " << filename.value();
723 ret = false;
726 if (IGNORE_EINTR(close(fd)) < 0) {
727 VPLOG(1) << "Error while closing file " << filename.value();
728 return false;
731 return ret;
734 // Gets the current working directory for the process.
735 bool GetCurrentDirectory(FilePath* dir) {
736 // getcwd can return ENOENT, which implies it checks against the disk.
737 ThreadRestrictions::AssertIOAllowed();
739 char system_buffer[PATH_MAX] = "";
740 if (!getcwd(system_buffer, sizeof(system_buffer))) {
741 NOTREACHED();
742 return false;
744 *dir = FilePath(system_buffer);
745 return true;
748 // Sets the current working directory for the process.
749 bool SetCurrentDirectory(const FilePath& path) {
750 ThreadRestrictions::AssertIOAllowed();
751 int ret = chdir(path.value().c_str());
752 return !ret;
755 bool VerifyPathControlledByUser(const FilePath& base,
756 const FilePath& path,
757 uid_t owner_uid,
758 const std::set<gid_t>& group_gids) {
759 if (base != path && !base.IsParent(path)) {
760 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
761 << base.value() << "\", path = \"" << path.value() << "\"";
762 return false;
765 std::vector<FilePath::StringType> base_components;
766 std::vector<FilePath::StringType> path_components;
768 base.GetComponents(&base_components);
769 path.GetComponents(&path_components);
771 std::vector<FilePath::StringType>::const_iterator ib, ip;
772 for (ib = base_components.begin(), ip = path_components.begin();
773 ib != base_components.end(); ++ib, ++ip) {
774 // |base| must be a subpath of |path|, so all components should match.
775 // If these CHECKs fail, look at the test that base is a parent of
776 // path at the top of this function.
777 DCHECK(ip != path_components.end());
778 DCHECK(*ip == *ib);
781 FilePath current_path = base;
782 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
783 return false;
785 for (; ip != path_components.end(); ++ip) {
786 current_path = current_path.Append(*ip);
787 if (!VerifySpecificPathControlledByUser(
788 current_path, owner_uid, group_gids))
789 return false;
791 return true;
794 #if defined(OS_MACOSX) && !defined(OS_IOS)
795 bool VerifyPathControlledByAdmin(const FilePath& path) {
796 const unsigned kRootUid = 0;
797 const FilePath kFileSystemRoot("/");
799 // The name of the administrator group on mac os.
800 const char* const kAdminGroupNames[] = {
801 "admin",
802 "wheel"
805 // Reading the groups database may touch the file system.
806 ThreadRestrictions::AssertIOAllowed();
808 std::set<gid_t> allowed_group_ids;
809 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
810 struct group *group_record = getgrnam(kAdminGroupNames[i]);
811 if (!group_record) {
812 DPLOG(ERROR) << "Could not get the group ID of group \""
813 << kAdminGroupNames[i] << "\".";
814 continue;
817 allowed_group_ids.insert(group_record->gr_gid);
820 return VerifyPathControlledByUser(
821 kFileSystemRoot, path, kRootUid, allowed_group_ids);
823 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
825 int GetMaximumPathComponentLength(const FilePath& path) {
826 ThreadRestrictions::AssertIOAllowed();
827 return pathconf(path.value().c_str(), _PC_NAME_MAX);
830 #if !defined(OS_ANDROID)
831 // This is implemented in file_util_android.cc for that platform.
832 bool GetShmemTempDir(bool executable, FilePath* path) {
833 #if defined(OS_LINUX)
834 bool use_dev_shm = true;
835 if (executable) {
836 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
837 use_dev_shm = s_dev_shm_executable;
839 if (use_dev_shm) {
840 *path = FilePath("/dev/shm");
841 return true;
843 #endif
844 return GetTempDir(path);
846 #endif // !defined(OS_ANDROID)
848 #if !defined(OS_MACOSX)
849 // Mac has its own implementation, this is for all other Posix systems.
850 bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
851 ThreadRestrictions::AssertIOAllowed();
852 File infile;
853 #if defined(OS_ANDROID)
854 if (from_path.IsContentUri()) {
855 infile = OpenContentUriForRead(from_path);
856 } else {
857 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
859 #else
860 infile = File(from_path, File::FLAG_OPEN | File::FLAG_READ);
861 #endif
862 if (!infile.IsValid())
863 return false;
865 File outfile(to_path, File::FLAG_WRITE | File::FLAG_CREATE_ALWAYS);
866 if (!outfile.IsValid())
867 return false;
869 const size_t kBufferSize = 32768;
870 std::vector<char> buffer(kBufferSize);
871 bool result = true;
873 while (result) {
874 ssize_t bytes_read = infile.ReadAtCurrentPos(&buffer[0], buffer.size());
875 if (bytes_read < 0) {
876 result = false;
877 break;
879 if (bytes_read == 0)
880 break;
881 // Allow for partial writes
882 ssize_t bytes_written_per_read = 0;
883 do {
884 ssize_t bytes_written_partial = outfile.WriteAtCurrentPos(
885 &buffer[bytes_written_per_read], bytes_read - bytes_written_per_read);
886 if (bytes_written_partial < 0) {
887 result = false;
888 break;
890 bytes_written_per_read += bytes_written_partial;
891 } while (bytes_written_per_read < bytes_read);
894 return result;
896 #endif // !defined(OS_MACOSX)
898 // -----------------------------------------------------------------------------
900 namespace internal {
902 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
903 ThreadRestrictions::AssertIOAllowed();
904 // Windows compatibility: if to_path exists, from_path and to_path
905 // must be the same type, either both files, or both directories.
906 stat_wrapper_t to_file_info;
907 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
908 stat_wrapper_t from_file_info;
909 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
910 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
911 return false;
912 } else {
913 return false;
917 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
918 return true;
920 if (!CopyDirectory(from_path, to_path, true))
921 return false;
923 DeleteFile(from_path, true);
924 return true;
927 } // namespace internal
929 #endif // !defined(OS_NACL_NONSFI)
930 } // namespace base