Protect WebURLLoaderImpl::Context while receiving responses.
[chromium-blink-merge.git] / base / file_util_posix.cc
blob7ef09a200de29c96c1f3f49e7002e50798488ec0
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 <fnmatch.h>
11 #include <libgen.h>
12 #include <limits.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/errno.h>
17 #include <sys/mman.h>
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <time.h>
23 #include <unistd.h>
25 #if defined(OS_MACOSX)
26 #include <AvailabilityMacros.h>
27 #include "base/mac/foundation_util.h"
28 #elif !defined(OS_ANDROID)
29 #include <glib.h>
30 #endif
32 #include <fstream>
34 #include "base/basictypes.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/string_util.h"
43 #include "base/stringprintf.h"
44 #include "base/strings/sys_string_conversions.h"
45 #include "base/threading/thread_restrictions.h"
46 #include "base/time.h"
47 #include "base/utf_string_conversions.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::FilePath;
62 using base::MakeAbsoluteFilePath;
64 namespace base {
66 FilePath MakeAbsoluteFilePath(const FilePath& input) {
67 base::ThreadRestrictions::AssertIOAllowed();
68 char full_path[PATH_MAX];
69 if (realpath(input.value().c_str(), full_path) == NULL)
70 return FilePath();
71 return FilePath(full_path);
74 } // namespace base
76 namespace file_util {
78 namespace {
80 #if defined(OS_BSD) || defined(OS_MACOSX)
81 typedef struct stat stat_wrapper_t;
82 static int CallStat(const char *path, stat_wrapper_t *sb) {
83 base::ThreadRestrictions::AssertIOAllowed();
84 return stat(path, sb);
86 static int CallLstat(const char *path, stat_wrapper_t *sb) {
87 base::ThreadRestrictions::AssertIOAllowed();
88 return lstat(path, sb);
90 #else
91 typedef struct stat64 stat_wrapper_t;
92 static int CallStat(const char *path, stat_wrapper_t *sb) {
93 base::ThreadRestrictions::AssertIOAllowed();
94 return stat64(path, sb);
96 static int CallLstat(const char *path, stat_wrapper_t *sb) {
97 base::ThreadRestrictions::AssertIOAllowed();
98 return lstat64(path, sb);
100 #endif
102 // Helper for NormalizeFilePath(), defined below.
103 bool RealPath(const FilePath& path, FilePath* real_path) {
104 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
105 FilePath::CharType buf[PATH_MAX];
106 if (!realpath(path.value().c_str(), buf))
107 return false;
109 *real_path = FilePath(buf);
110 return true;
113 // Helper for VerifyPathControlledByUser.
114 bool VerifySpecificPathControlledByUser(const FilePath& path,
115 uid_t owner_uid,
116 const std::set<gid_t>& group_gids) {
117 stat_wrapper_t stat_info;
118 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
119 DPLOG(ERROR) << "Failed to get information on path "
120 << path.value();
121 return false;
124 if (S_ISLNK(stat_info.st_mode)) {
125 DLOG(ERROR) << "Path " << path.value()
126 << " is a symbolic link.";
127 return false;
130 if (stat_info.st_uid != owner_uid) {
131 DLOG(ERROR) << "Path " << path.value()
132 << " is owned by the wrong user.";
133 return false;
136 if ((stat_info.st_mode & S_IWGRP) &&
137 !ContainsKey(group_gids, stat_info.st_gid)) {
138 DLOG(ERROR) << "Path " << path.value()
139 << " is writable by an unprivileged group.";
140 return false;
143 if (stat_info.st_mode & S_IWOTH) {
144 DLOG(ERROR) << "Path " << path.value()
145 << " is writable by any user.";
146 return false;
149 return true;
152 } // namespace
154 static std::string TempFileName() {
155 #if defined(OS_MACOSX)
156 return base::StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
157 #endif
159 #if defined(GOOGLE_CHROME_BUILD)
160 return std::string(".com.google.Chrome.XXXXXX");
161 #else
162 return std::string(".org.chromium.Chromium.XXXXXX");
163 #endif
166 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
167 // which works both with and without the recursive flag. I'm not sure we need
168 // that functionality. If not, remove from file_util_win.cc, otherwise add it
169 // here.
170 bool Delete(const FilePath& path, bool recursive) {
171 base::ThreadRestrictions::AssertIOAllowed();
172 const char* path_str = path.value().c_str();
173 stat_wrapper_t file_info;
174 int test = CallLstat(path_str, &file_info);
175 if (test != 0) {
176 // The Windows version defines this condition as success.
177 bool ret = (errno == ENOENT || errno == ENOTDIR);
178 return ret;
180 if (!S_ISDIR(file_info.st_mode))
181 return (unlink(path_str) == 0);
182 if (!recursive)
183 return (rmdir(path_str) == 0);
185 bool success = true;
186 std::stack<std::string> directories;
187 directories.push(path.value());
188 FileEnumerator traversal(path, true,
189 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
190 FileEnumerator::SHOW_SYM_LINKS);
191 for (FilePath current = traversal.Next(); success && !current.empty();
192 current = traversal.Next()) {
193 FileEnumerator::FindInfo info;
194 traversal.GetFindInfo(&info);
196 if (S_ISDIR(info.stat.st_mode))
197 directories.push(current.value());
198 else
199 success = (unlink(current.value().c_str()) == 0);
202 while (success && !directories.empty()) {
203 FilePath dir = FilePath(directories.top());
204 directories.pop();
205 success = (rmdir(dir.value().c_str()) == 0);
207 return success;
210 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
211 base::ThreadRestrictions::AssertIOAllowed();
212 // Windows compatibility: if to_path exists, from_path and to_path
213 // must be the same type, either both files, or both directories.
214 stat_wrapper_t to_file_info;
215 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
216 stat_wrapper_t from_file_info;
217 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
218 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
219 return false;
220 } else {
221 return false;
225 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
226 return true;
228 if (!CopyDirectory(from_path, to_path, true))
229 return false;
231 Delete(from_path, true);
232 return true;
235 bool ReplaceFileAndGetError(const FilePath& from_path,
236 const FilePath& to_path,
237 base::PlatformFileError* error) {
238 base::ThreadRestrictions::AssertIOAllowed();
239 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
240 return true;
241 if (error)
242 *error = base::ErrnoToPlatformFileError(errno);
243 return false;
246 bool CopyDirectory(const FilePath& from_path,
247 const FilePath& to_path,
248 bool recursive) {
249 base::ThreadRestrictions::AssertIOAllowed();
250 // Some old callers of CopyDirectory want it to support wildcards.
251 // After some discussion, we decided to fix those callers.
252 // Break loudly here if anyone tries to do this.
253 // TODO(evanm): remove this once we're sure it's ok.
254 DCHECK(to_path.value().find('*') == std::string::npos);
255 DCHECK(from_path.value().find('*') == std::string::npos);
257 char top_dir[PATH_MAX];
258 if (base::strlcpy(top_dir, from_path.value().c_str(),
259 arraysize(top_dir)) >= arraysize(top_dir)) {
260 return false;
263 // This function does not properly handle destinations within the source
264 FilePath real_to_path = to_path;
265 if (PathExists(real_to_path)) {
266 real_to_path = MakeAbsoluteFilePath(real_to_path);
267 if (real_to_path.empty())
268 return false;
269 } else {
270 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
271 if (real_to_path.empty())
272 return false;
274 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
275 if (real_from_path.empty())
276 return false;
277 if (real_to_path.value().size() >= real_from_path.value().size() &&
278 real_to_path.value().compare(0, real_from_path.value().size(),
279 real_from_path.value()) == 0)
280 return false;
282 bool success = true;
283 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
284 if (recursive)
285 traverse_type |= FileEnumerator::DIRECTORIES;
286 FileEnumerator traversal(from_path, recursive, traverse_type);
288 // We have to mimic windows behavior here. |to_path| may not exist yet,
289 // start the loop with |to_path|.
290 FileEnumerator::FindInfo info;
291 FilePath current = from_path;
292 if (stat(from_path.value().c_str(), &info.stat) < 0) {
293 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
294 << from_path.value() << " errno = " << errno;
295 success = false;
297 struct stat to_path_stat;
298 FilePath from_path_base = from_path;
299 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
300 S_ISDIR(to_path_stat.st_mode)) {
301 // If the destination already exists and is a directory, then the
302 // top level of source needs to be copied.
303 from_path_base = from_path.DirName();
306 // The Windows version of this function assumes that non-recursive calls
307 // will always have a directory for from_path.
308 DCHECK(recursive || S_ISDIR(info.stat.st_mode));
310 while (success && !current.empty()) {
311 // current is the source path, including from_path, so append
312 // the suffix after from_path to to_path to create the target_path.
313 FilePath target_path(to_path);
314 if (from_path_base != current) {
315 if (!from_path_base.AppendRelativePath(current, &target_path)) {
316 success = false;
317 break;
321 if (S_ISDIR(info.stat.st_mode)) {
322 if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
323 errno != EEXIST) {
324 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
325 << target_path.value() << " errno = " << errno;
326 success = false;
328 } else if (S_ISREG(info.stat.st_mode)) {
329 if (!CopyFile(current, target_path)) {
330 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
331 << target_path.value();
332 success = false;
334 } else {
335 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
336 << current.value();
339 current = traversal.Next();
340 traversal.GetFindInfo(&info);
343 return success;
346 bool PathExists(const FilePath& path) {
347 base::ThreadRestrictions::AssertIOAllowed();
348 return access(path.value().c_str(), F_OK) == 0;
351 bool PathIsWritable(const FilePath& path) {
352 base::ThreadRestrictions::AssertIOAllowed();
353 return access(path.value().c_str(), W_OK) == 0;
356 bool DirectoryExists(const FilePath& path) {
357 base::ThreadRestrictions::AssertIOAllowed();
358 stat_wrapper_t file_info;
359 if (CallStat(path.value().c_str(), &file_info) == 0)
360 return S_ISDIR(file_info.st_mode);
361 return false;
364 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
365 size_t total_read = 0;
366 while (total_read < bytes) {
367 ssize_t bytes_read =
368 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
369 if (bytes_read <= 0)
370 break;
371 total_read += bytes_read;
373 return total_read == bytes;
376 bool CreateSymbolicLink(const FilePath& target_path,
377 const FilePath& symlink_path) {
378 DCHECK(!symlink_path.empty());
379 DCHECK(!target_path.empty());
380 return ::symlink(target_path.value().c_str(),
381 symlink_path.value().c_str()) != -1;
384 bool ReadSymbolicLink(const FilePath& symlink_path,
385 FilePath* target_path) {
386 DCHECK(!symlink_path.empty());
387 DCHECK(target_path);
388 char buf[PATH_MAX];
389 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
391 if (count <= 0) {
392 target_path->clear();
393 return false;
396 *target_path = FilePath(FilePath::StringType(buf, count));
397 return true;
400 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
401 base::ThreadRestrictions::AssertIOAllowed();
402 DCHECK(mode);
404 stat_wrapper_t file_info;
405 // Uses stat(), because on symbolic link, lstat() does not return valid
406 // permission bits in st_mode
407 if (CallStat(path.value().c_str(), &file_info) != 0)
408 return false;
410 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
411 return true;
414 bool SetPosixFilePermissions(const FilePath& path,
415 int mode) {
416 base::ThreadRestrictions::AssertIOAllowed();
417 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
419 // Calls stat() so that we can preserve the higher bits like S_ISGID.
420 stat_wrapper_t stat_buf;
421 if (CallStat(path.value().c_str(), &stat_buf) != 0)
422 return false;
424 // Clears the existing permission bits, and adds the new ones.
425 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
426 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
428 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
429 return false;
431 return true;
434 // Creates and opens a temporary file in |directory|, returning the
435 // file descriptor. |path| is set to the temporary file path.
436 // This function does NOT unlink() the file.
437 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
438 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
439 *path = directory.Append(TempFileName());
440 const std::string& tmpdir_string = path->value();
441 // this should be OK since mkstemp just replaces characters in place
442 char* buffer = const_cast<char*>(tmpdir_string.c_str());
444 return HANDLE_EINTR(mkstemp(buffer));
447 bool CreateTemporaryFile(FilePath* path) {
448 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
449 FilePath directory;
450 if (!GetTempDir(&directory))
451 return false;
452 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
453 if (fd < 0)
454 return false;
455 ignore_result(HANDLE_EINTR(close(fd)));
456 return true;
459 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
460 FilePath directory;
461 if (!GetShmemTempDir(&directory, executable))
462 return NULL;
464 return CreateAndOpenTemporaryFileInDir(directory, path);
467 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
468 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
469 if (fd < 0)
470 return NULL;
472 FILE* file = fdopen(fd, "a+");
473 if (!file)
474 ignore_result(HANDLE_EINTR(close(fd)));
475 return file;
478 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
479 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
480 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
481 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
484 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
485 const FilePath::StringType& name_tmpl,
486 FilePath* new_dir) {
487 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
488 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
489 << "Directory name template must contain \"XXXXXX\".";
491 FilePath sub_dir = base_dir.Append(name_tmpl);
492 std::string sub_dir_string = sub_dir.value();
494 // this should be OK since mkdtemp just replaces characters in place
495 char* buffer = const_cast<char*>(sub_dir_string.c_str());
496 char* dtemp = mkdtemp(buffer);
497 if (!dtemp) {
498 DPLOG(ERROR) << "mkdtemp";
499 return false;
501 *new_dir = FilePath(dtemp);
502 return true;
505 bool CreateTemporaryDirInDir(const FilePath& base_dir,
506 const FilePath::StringType& prefix,
507 FilePath* new_dir) {
508 FilePath::StringType mkdtemp_template = prefix;
509 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
510 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
513 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
514 FilePath* new_temp_path) {
515 FilePath tmpdir;
516 if (!GetTempDir(&tmpdir))
517 return false;
519 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
522 bool CreateDirectory(const FilePath& full_path) {
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 if (!DirectoryExists(*i))
547 return false;
549 return true;
552 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
553 const int kMaxAttempts = 20;
554 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
555 int uniquifier =
556 GetUniquePathNumber(path, base::FilePath::StringType());
557 if (uniquifier < 0)
558 break;
559 base::FilePath test_path = (uniquifier == 0) ? path :
560 path.InsertBeforeExtensionASCII(
561 base::StringPrintf(" (%d)", uniquifier));
562 if (mkdir(test_path.value().c_str(), 0777) == 0)
563 return test_path;
564 else if (errno != EEXIST)
565 break;
567 return base::FilePath();
570 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
571 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
572 bool IsLink(const FilePath& file_path) {
573 stat_wrapper_t st;
574 // If we can't lstat the file, it's safe to assume that the file won't at
575 // least be a 'followable' link.
576 if (CallLstat(file_path.value().c_str(), &st) != 0)
577 return false;
579 if (S_ISLNK(st.st_mode))
580 return true;
581 else
582 return false;
585 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
586 stat_wrapper_t file_info;
587 if (CallStat(file_path.value().c_str(), &file_info) != 0)
588 return false;
589 results->is_directory = S_ISDIR(file_info.st_mode);
590 results->size = file_info.st_size;
591 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
592 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
593 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
594 return true;
597 bool GetInode(const FilePath& path, ino_t* inode) {
598 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
599 struct stat buffer;
600 int result = stat(path.value().c_str(), &buffer);
601 if (result < 0)
602 return false;
604 *inode = buffer.st_ino;
605 return true;
608 FILE* OpenFile(const std::string& filename, const char* mode) {
609 return OpenFile(FilePath(filename), mode);
612 FILE* OpenFile(const FilePath& filename, const char* mode) {
613 base::ThreadRestrictions::AssertIOAllowed();
614 FILE* result = NULL;
615 do {
616 result = fopen(filename.value().c_str(), mode);
617 } while (!result && errno == EINTR);
618 return result;
621 int ReadFile(const FilePath& filename, char* data, int size) {
622 base::ThreadRestrictions::AssertIOAllowed();
623 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
624 if (fd < 0)
625 return -1;
627 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
628 if (int ret = HANDLE_EINTR(close(fd)) < 0)
629 return ret;
630 return bytes_read;
633 int WriteFile(const FilePath& filename, const char* data, int size) {
634 base::ThreadRestrictions::AssertIOAllowed();
635 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
636 if (fd < 0)
637 return -1;
639 int bytes_written = WriteFileDescriptor(fd, data, size);
640 if (int ret = HANDLE_EINTR(close(fd)) < 0)
641 return ret;
642 return bytes_written;
645 int WriteFileDescriptor(const int fd, const char* data, int size) {
646 // Allow for partial writes.
647 ssize_t bytes_written_total = 0;
648 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
649 bytes_written_total += bytes_written_partial) {
650 bytes_written_partial =
651 HANDLE_EINTR(write(fd, data + bytes_written_total,
652 size - bytes_written_total));
653 if (bytes_written_partial < 0)
654 return -1;
657 return bytes_written_total;
660 int AppendToFile(const FilePath& filename, const char* data, int size) {
661 base::ThreadRestrictions::AssertIOAllowed();
662 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
663 if (fd < 0)
664 return -1;
666 int bytes_written = WriteFileDescriptor(fd, data, size);
667 if (int ret = HANDLE_EINTR(close(fd)) < 0)
668 return ret;
669 return bytes_written;
672 // Gets the current working directory for the process.
673 bool GetCurrentDirectory(FilePath* dir) {
674 // getcwd can return ENOENT, which implies it checks against the disk.
675 base::ThreadRestrictions::AssertIOAllowed();
677 char system_buffer[PATH_MAX] = "";
678 if (!getcwd(system_buffer, sizeof(system_buffer))) {
679 NOTREACHED();
680 return false;
682 *dir = FilePath(system_buffer);
683 return true;
686 // Sets the current working directory for the process.
687 bool SetCurrentDirectory(const FilePath& path) {
688 base::ThreadRestrictions::AssertIOAllowed();
689 int ret = chdir(path.value().c_str());
690 return !ret;
693 ///////////////////////////////////////////////
694 // FileEnumerator
696 FileEnumerator::FileEnumerator(const FilePath& root_path,
697 bool recursive,
698 int file_type)
699 : current_directory_entry_(0),
700 root_path_(root_path),
701 recursive_(recursive),
702 file_type_(file_type) {
703 // INCLUDE_DOT_DOT must not be specified if recursive.
704 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
705 pending_paths_.push(root_path);
708 FileEnumerator::FileEnumerator(const FilePath& root_path,
709 bool recursive,
710 int file_type,
711 const FilePath::StringType& pattern)
712 : current_directory_entry_(0),
713 root_path_(root_path),
714 recursive_(recursive),
715 file_type_(file_type),
716 pattern_(root_path.Append(pattern).value()) {
717 // INCLUDE_DOT_DOT must not be specified if recursive.
718 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
719 // The Windows version of this code appends the pattern to the root_path,
720 // potentially only matching against items in the top-most directory.
721 // Do the same here.
722 if (pattern.empty())
723 pattern_ = FilePath::StringType();
724 pending_paths_.push(root_path);
727 FileEnumerator::~FileEnumerator() {
730 FilePath FileEnumerator::Next() {
731 ++current_directory_entry_;
733 // While we've exhausted the entries in the current directory, do the next
734 while (current_directory_entry_ >= directory_entries_.size()) {
735 if (pending_paths_.empty())
736 return FilePath();
738 root_path_ = pending_paths_.top();
739 root_path_ = root_path_.StripTrailingSeparators();
740 pending_paths_.pop();
742 std::vector<DirectoryEntryInfo> entries;
743 if (!ReadDirectory(&entries, root_path_, file_type_ & SHOW_SYM_LINKS))
744 continue;
746 directory_entries_.clear();
747 current_directory_entry_ = 0;
748 for (std::vector<DirectoryEntryInfo>::const_iterator
749 i = entries.begin(); i != entries.end(); ++i) {
750 FilePath full_path = root_path_.Append(i->filename);
751 if (ShouldSkip(full_path))
752 continue;
754 if (pattern_.size() &&
755 fnmatch(pattern_.c_str(), full_path.value().c_str(), FNM_NOESCAPE))
756 continue;
758 if (recursive_ && S_ISDIR(i->stat.st_mode))
759 pending_paths_.push(full_path);
761 if ((S_ISDIR(i->stat.st_mode) && (file_type_ & DIRECTORIES)) ||
762 (!S_ISDIR(i->stat.st_mode) && (file_type_ & FILES)))
763 directory_entries_.push_back(*i);
767 return root_path_.Append(directory_entries_[current_directory_entry_
768 ].filename);
771 void FileEnumerator::GetFindInfo(FindInfo* info) {
772 DCHECK(info);
774 if (current_directory_entry_ >= directory_entries_.size())
775 return;
777 DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
778 memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
779 info->filename.assign(cur_entry->filename.value());
782 // static
783 bool FileEnumerator::IsDirectory(const FindInfo& info) {
784 return S_ISDIR(info.stat.st_mode);
787 // static
788 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
789 return FilePath(find_info.filename);
792 // static
793 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
794 return find_info.stat.st_size;
797 // static
798 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
799 return base::Time::FromTimeT(find_info.stat.st_mtime);
802 bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
803 const FilePath& source, bool show_links) {
804 base::ThreadRestrictions::AssertIOAllowed();
805 DIR* dir = opendir(source.value().c_str());
806 if (!dir)
807 return false;
809 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
810 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
811 #error Port warning: depending on the definition of struct dirent, \
812 additional space for pathname may be needed
813 #endif
815 struct dirent dent_buf;
816 struct dirent* dent;
817 while (readdir_r(dir, &dent_buf, &dent) == 0 && dent) {
818 DirectoryEntryInfo info;
819 info.filename = FilePath(dent->d_name);
821 FilePath full_name = source.Append(dent->d_name);
822 int ret;
823 if (show_links)
824 ret = lstat(full_name.value().c_str(), &info.stat);
825 else
826 ret = stat(full_name.value().c_str(), &info.stat);
827 if (ret < 0) {
828 // Print the stat() error message unless it was ENOENT and we're
829 // following symlinks.
830 if (!(errno == ENOENT && !show_links)) {
831 DPLOG(ERROR) << "Couldn't stat "
832 << source.Append(dent->d_name).value();
834 memset(&info.stat, 0, sizeof(info.stat));
836 entries->push_back(info);
839 closedir(dir);
840 return true;
843 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
844 FilePath real_path_result;
845 if (!RealPath(path, &real_path_result))
846 return false;
848 // To be consistant with windows, fail if |real_path_result| is a
849 // directory.
850 stat_wrapper_t file_info;
851 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
852 S_ISDIR(file_info.st_mode))
853 return false;
855 *normalized_path = real_path_result;
856 return true;
859 #if !defined(OS_MACOSX)
860 bool GetTempDir(FilePath* path) {
861 const char* tmp = getenv("TMPDIR");
862 if (tmp)
863 *path = FilePath(tmp);
864 else
865 #if defined(OS_ANDROID)
866 return PathService::Get(base::DIR_CACHE, path);
867 #else
868 *path = FilePath("/tmp");
869 #endif
870 return true;
873 #if !defined(OS_ANDROID)
875 #if defined(OS_LINUX)
876 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
877 // This depends on the mount options used for /dev/shm, which vary among
878 // different Linux distributions and possibly local configuration. It also
879 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
880 // but its kernel allows mprotect with PROT_EXEC anyway.
882 namespace {
884 bool DetermineDevShmExecutable() {
885 bool result = false;
886 FilePath path;
887 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
888 if (fd >= 0) {
889 ScopedFD shm_fd_closer(&fd);
890 Delete(path, false);
891 long sysconf_result = sysconf(_SC_PAGESIZE);
892 CHECK_GE(sysconf_result, 0);
893 size_t pagesize = static_cast<size_t>(sysconf_result);
894 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
895 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
896 if (mapping != MAP_FAILED) {
897 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
898 result = true;
899 munmap(mapping, pagesize);
902 return result;
905 }; // namespace
906 #endif // defined(OS_LINUX)
908 bool GetShmemTempDir(FilePath* path, bool executable) {
909 #if defined(OS_LINUX)
910 bool use_dev_shm = true;
911 if (executable) {
912 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
913 use_dev_shm = s_dev_shm_executable;
915 if (use_dev_shm) {
916 *path = FilePath("/dev/shm");
917 return true;
919 #endif
920 return GetTempDir(path);
922 #endif // !defined(OS_ANDROID)
924 FilePath GetHomeDir() {
925 #if defined(OS_CHROMEOS)
926 if (base::chromeos::IsRunningOnChromeOS())
927 return FilePath("/home/chronos/user");
928 #endif
930 const char* home_dir = getenv("HOME");
931 if (home_dir && home_dir[0])
932 return FilePath(home_dir);
934 #if defined(OS_ANDROID)
935 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
936 #else
937 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
938 base::ThreadRestrictions::AssertIOAllowed();
940 home_dir = g_get_home_dir();
941 if (home_dir && home_dir[0])
942 return FilePath(home_dir);
943 #endif
945 FilePath rv;
946 if (file_util::GetTempDir(&rv))
947 return rv;
949 // Last resort.
950 return FilePath("/tmp");
953 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
954 base::ThreadRestrictions::AssertIOAllowed();
955 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
956 if (infile < 0)
957 return false;
959 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
960 if (outfile < 0) {
961 ignore_result(HANDLE_EINTR(close(infile)));
962 return false;
965 const size_t kBufferSize = 32768;
966 std::vector<char> buffer(kBufferSize);
967 bool result = true;
969 while (result) {
970 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
971 if (bytes_read < 0) {
972 result = false;
973 break;
975 if (bytes_read == 0)
976 break;
977 // Allow for partial writes
978 ssize_t bytes_written_per_read = 0;
979 do {
980 ssize_t bytes_written_partial = HANDLE_EINTR(write(
981 outfile,
982 &buffer[bytes_written_per_read],
983 bytes_read - bytes_written_per_read));
984 if (bytes_written_partial < 0) {
985 result = false;
986 break;
988 bytes_written_per_read += bytes_written_partial;
989 } while (bytes_written_per_read < bytes_read);
992 if (HANDLE_EINTR(close(infile)) < 0)
993 result = false;
994 if (HANDLE_EINTR(close(outfile)) < 0)
995 result = false;
997 return result;
999 #endif // !defined(OS_MACOSX)
1001 bool VerifyPathControlledByUser(const FilePath& base,
1002 const FilePath& path,
1003 uid_t owner_uid,
1004 const std::set<gid_t>& group_gids) {
1005 if (base != path && !base.IsParent(path)) {
1006 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
1007 << base.value() << "\", path = \"" << path.value() << "\"";
1008 return false;
1011 std::vector<FilePath::StringType> base_components;
1012 std::vector<FilePath::StringType> path_components;
1014 base.GetComponents(&base_components);
1015 path.GetComponents(&path_components);
1017 std::vector<FilePath::StringType>::const_iterator ib, ip;
1018 for (ib = base_components.begin(), ip = path_components.begin();
1019 ib != base_components.end(); ++ib, ++ip) {
1020 // |base| must be a subpath of |path|, so all components should match.
1021 // If these CHECKs fail, look at the test that base is a parent of
1022 // path at the top of this function.
1023 DCHECK(ip != path_components.end());
1024 DCHECK(*ip == *ib);
1027 FilePath current_path = base;
1028 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
1029 return false;
1031 for (; ip != path_components.end(); ++ip) {
1032 current_path = current_path.Append(*ip);
1033 if (!VerifySpecificPathControlledByUser(
1034 current_path, owner_uid, group_gids))
1035 return false;
1037 return true;
1040 #if defined(OS_MACOSX) && !defined(OS_IOS)
1041 bool VerifyPathControlledByAdmin(const FilePath& path) {
1042 const unsigned kRootUid = 0;
1043 const FilePath kFileSystemRoot("/");
1045 // The name of the administrator group on mac os.
1046 const char* const kAdminGroupNames[] = {
1047 "admin",
1048 "wheel"
1051 // Reading the groups database may touch the file system.
1052 base::ThreadRestrictions::AssertIOAllowed();
1054 std::set<gid_t> allowed_group_ids;
1055 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
1056 struct group *group_record = getgrnam(kAdminGroupNames[i]);
1057 if (!group_record) {
1058 DPLOG(ERROR) << "Could not get the group ID of group \""
1059 << kAdminGroupNames[i] << "\".";
1060 continue;
1063 allowed_group_ids.insert(group_record->gr_gid);
1066 return VerifyPathControlledByUser(
1067 kFileSystemRoot, path, kRootUid, allowed_group_ids);
1069 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1071 int GetMaximumPathComponentLength(const FilePath& path) {
1072 base::ThreadRestrictions::AssertIOAllowed();
1073 return pathconf(path.value().c_str(), _PC_NAME_MAX);
1076 } // namespace file_util