Separate Simple Backend creation from initialization.
[chromium-blink-merge.git] / base / file_util_posix.cc
blob8bf164ace5c4a175907d416672e0507362808e6c
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;
63 namespace file_util {
65 namespace {
67 #if defined(OS_BSD) || defined(OS_MACOSX)
68 typedef struct stat stat_wrapper_t;
69 static int CallStat(const char *path, stat_wrapper_t *sb) {
70 base::ThreadRestrictions::AssertIOAllowed();
71 return stat(path, sb);
73 static int CallLstat(const char *path, stat_wrapper_t *sb) {
74 base::ThreadRestrictions::AssertIOAllowed();
75 return lstat(path, sb);
77 #else
78 typedef struct stat64 stat_wrapper_t;
79 static int CallStat(const char *path, stat_wrapper_t *sb) {
80 base::ThreadRestrictions::AssertIOAllowed();
81 return stat64(path, sb);
83 static int CallLstat(const char *path, stat_wrapper_t *sb) {
84 base::ThreadRestrictions::AssertIOAllowed();
85 return lstat64(path, sb);
87 #endif
89 // Helper for NormalizeFilePath(), defined below.
90 bool RealPath(const FilePath& path, FilePath* real_path) {
91 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
92 FilePath::CharType buf[PATH_MAX];
93 if (!realpath(path.value().c_str(), buf))
94 return false;
96 *real_path = FilePath(buf);
97 return true;
100 // Helper for VerifyPathControlledByUser.
101 bool VerifySpecificPathControlledByUser(const FilePath& path,
102 uid_t owner_uid,
103 const std::set<gid_t>& group_gids) {
104 stat_wrapper_t stat_info;
105 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
106 DPLOG(ERROR) << "Failed to get information on path "
107 << path.value();
108 return false;
111 if (S_ISLNK(stat_info.st_mode)) {
112 DLOG(ERROR) << "Path " << path.value()
113 << " is a symbolic link.";
114 return false;
117 if (stat_info.st_uid != owner_uid) {
118 DLOG(ERROR) << "Path " << path.value()
119 << " is owned by the wrong user.";
120 return false;
123 if ((stat_info.st_mode & S_IWGRP) &&
124 !ContainsKey(group_gids, stat_info.st_gid)) {
125 DLOG(ERROR) << "Path " << path.value()
126 << " is writable by an unprivileged group.";
127 return false;
130 if (stat_info.st_mode & S_IWOTH) {
131 DLOG(ERROR) << "Path " << path.value()
132 << " is writable by any user.";
133 return false;
136 return true;
139 } // namespace
141 static std::string TempFileName() {
142 #if defined(OS_MACOSX)
143 return base::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 bool AbsolutePath(FilePath* path) {
154 base::ThreadRestrictions::AssertIOAllowed(); // For realpath().
155 char full_path[PATH_MAX];
156 if (realpath(path->value().c_str(), full_path) == NULL)
157 return false;
158 *path = FilePath(full_path);
159 return true;
162 // TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
163 // which works both with and without the recursive flag. I'm not sure we need
164 // that functionality. If not, remove from file_util_win.cc, otherwise add it
165 // here.
166 bool Delete(const FilePath& path, bool recursive) {
167 base::ThreadRestrictions::AssertIOAllowed();
168 const char* path_str = path.value().c_str();
169 stat_wrapper_t file_info;
170 int test = CallLstat(path_str, &file_info);
171 if (test != 0) {
172 // The Windows version defines this condition as success.
173 bool ret = (errno == ENOENT || errno == ENOTDIR);
174 return ret;
176 if (!S_ISDIR(file_info.st_mode))
177 return (unlink(path_str) == 0);
178 if (!recursive)
179 return (rmdir(path_str) == 0);
181 bool success = true;
182 std::stack<std::string> directories;
183 directories.push(path.value());
184 FileEnumerator traversal(path, true,
185 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
186 FileEnumerator::SHOW_SYM_LINKS);
187 for (FilePath current = traversal.Next(); success && !current.empty();
188 current = traversal.Next()) {
189 FileEnumerator::FindInfo info;
190 traversal.GetFindInfo(&info);
192 if (S_ISDIR(info.stat.st_mode))
193 directories.push(current.value());
194 else
195 success = (unlink(current.value().c_str()) == 0);
198 while (success && !directories.empty()) {
199 FilePath dir = FilePath(directories.top());
200 directories.pop();
201 success = (rmdir(dir.value().c_str()) == 0);
203 return success;
206 bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
207 base::ThreadRestrictions::AssertIOAllowed();
208 // Windows compatibility: if to_path exists, from_path and to_path
209 // must be the same type, either both files, or both directories.
210 stat_wrapper_t to_file_info;
211 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
212 stat_wrapper_t from_file_info;
213 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
214 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
215 return false;
216 } else {
217 return false;
221 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
222 return true;
224 if (!CopyDirectory(from_path, to_path, true))
225 return false;
227 Delete(from_path, true);
228 return true;
231 bool ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
232 base::ThreadRestrictions::AssertIOAllowed();
233 return (rename(from_path.value().c_str(), to_path.value().c_str()) == 0);
236 bool CopyDirectory(const FilePath& from_path,
237 const FilePath& to_path,
238 bool recursive) {
239 base::ThreadRestrictions::AssertIOAllowed();
240 // Some old callers of CopyDirectory want it to support wildcards.
241 // After some discussion, we decided to fix those callers.
242 // Break loudly here if anyone tries to do this.
243 // TODO(evanm): remove this once we're sure it's ok.
244 DCHECK(to_path.value().find('*') == std::string::npos);
245 DCHECK(from_path.value().find('*') == std::string::npos);
247 char top_dir[PATH_MAX];
248 if (base::strlcpy(top_dir, from_path.value().c_str(),
249 arraysize(top_dir)) >= arraysize(top_dir)) {
250 return false;
253 // This function does not properly handle destinations within the source
254 FilePath real_to_path = to_path;
255 if (PathExists(real_to_path)) {
256 if (!AbsolutePath(&real_to_path))
257 return false;
258 } else {
259 real_to_path = real_to_path.DirName();
260 if (!AbsolutePath(&real_to_path))
261 return false;
263 FilePath real_from_path = from_path;
264 if (!AbsolutePath(&real_from_path))
265 return false;
266 if (real_to_path.value().size() >= real_from_path.value().size() &&
267 real_to_path.value().compare(0, real_from_path.value().size(),
268 real_from_path.value()) == 0)
269 return false;
271 bool success = true;
272 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
273 if (recursive)
274 traverse_type |= FileEnumerator::DIRECTORIES;
275 FileEnumerator traversal(from_path, recursive, traverse_type);
277 // We have to mimic windows behavior here. |to_path| may not exist yet,
278 // start the loop with |to_path|.
279 FileEnumerator::FindInfo info;
280 FilePath current = from_path;
281 if (stat(from_path.value().c_str(), &info.stat) < 0) {
282 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
283 << from_path.value() << " errno = " << errno;
284 success = false;
286 struct stat to_path_stat;
287 FilePath from_path_base = from_path;
288 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
289 S_ISDIR(to_path_stat.st_mode)) {
290 // If the destination already exists and is a directory, then the
291 // top level of source needs to be copied.
292 from_path_base = from_path.DirName();
295 // The Windows version of this function assumes that non-recursive calls
296 // will always have a directory for from_path.
297 DCHECK(recursive || S_ISDIR(info.stat.st_mode));
299 while (success && !current.empty()) {
300 // current is the source path, including from_path, so append
301 // the suffix after from_path to to_path to create the target_path.
302 FilePath target_path(to_path);
303 if (from_path_base != current) {
304 if (!from_path_base.AppendRelativePath(current, &target_path)) {
305 success = false;
306 break;
310 if (S_ISDIR(info.stat.st_mode)) {
311 if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
312 errno != EEXIST) {
313 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
314 << target_path.value() << " errno = " << errno;
315 success = false;
317 } else if (S_ISREG(info.stat.st_mode)) {
318 if (!CopyFile(current, target_path)) {
319 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
320 << target_path.value();
321 success = false;
323 } else {
324 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
325 << current.value();
328 current = traversal.Next();
329 traversal.GetFindInfo(&info);
332 return success;
335 bool PathExists(const FilePath& path) {
336 base::ThreadRestrictions::AssertIOAllowed();
337 return access(path.value().c_str(), F_OK) == 0;
340 bool PathIsWritable(const FilePath& path) {
341 base::ThreadRestrictions::AssertIOAllowed();
342 return access(path.value().c_str(), W_OK) == 0;
345 bool DirectoryExists(const FilePath& path) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 stat_wrapper_t file_info;
348 if (CallStat(path.value().c_str(), &file_info) == 0)
349 return S_ISDIR(file_info.st_mode);
350 return false;
353 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
354 size_t total_read = 0;
355 while (total_read < bytes) {
356 ssize_t bytes_read =
357 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
358 if (bytes_read <= 0)
359 break;
360 total_read += bytes_read;
362 return total_read == bytes;
365 bool CreateSymbolicLink(const FilePath& target_path,
366 const FilePath& symlink_path) {
367 DCHECK(!symlink_path.empty());
368 DCHECK(!target_path.empty());
369 return ::symlink(target_path.value().c_str(),
370 symlink_path.value().c_str()) != -1;
373 bool ReadSymbolicLink(const FilePath& symlink_path,
374 FilePath* target_path) {
375 DCHECK(!symlink_path.empty());
376 DCHECK(target_path);
377 char buf[PATH_MAX];
378 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
380 if (count <= 0) {
381 target_path->clear();
382 return false;
385 *target_path = FilePath(FilePath::StringType(buf, count));
386 return true;
389 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
390 base::ThreadRestrictions::AssertIOAllowed();
391 DCHECK(mode);
393 stat_wrapper_t file_info;
394 // Uses stat(), because on symbolic link, lstat() does not return valid
395 // permission bits in st_mode
396 if (CallStat(path.value().c_str(), &file_info) != 0)
397 return false;
399 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
400 return true;
403 bool SetPosixFilePermissions(const FilePath& path,
404 int mode) {
405 base::ThreadRestrictions::AssertIOAllowed();
406 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
408 // Calls stat() so that we can preserve the higher bits like S_ISGID.
409 stat_wrapper_t stat_buf;
410 if (CallStat(path.value().c_str(), &stat_buf) != 0)
411 return false;
413 // Clears the existing permission bits, and adds the new ones.
414 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
415 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
417 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
418 return false;
420 return true;
423 // Creates and opens a temporary file in |directory|, returning the
424 // file descriptor. |path| is set to the temporary file path.
425 // This function does NOT unlink() the file.
426 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
427 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
428 *path = directory.Append(TempFileName());
429 const std::string& tmpdir_string = path->value();
430 // this should be OK since mkstemp just replaces characters in place
431 char* buffer = const_cast<char*>(tmpdir_string.c_str());
433 return HANDLE_EINTR(mkstemp(buffer));
436 bool CreateTemporaryFile(FilePath* path) {
437 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
438 FilePath directory;
439 if (!GetTempDir(&directory))
440 return false;
441 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
442 if (fd < 0)
443 return false;
444 ignore_result(HANDLE_EINTR(close(fd)));
445 return true;
448 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
449 FilePath directory;
450 if (!GetShmemTempDir(&directory, executable))
451 return NULL;
453 return CreateAndOpenTemporaryFileInDir(directory, path);
456 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
457 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
458 if (fd < 0)
459 return NULL;
461 FILE* file = fdopen(fd, "a+");
462 if (!file)
463 ignore_result(HANDLE_EINTR(close(fd)));
464 return file;
467 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
468 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
469 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
470 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
473 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
474 const FilePath::StringType& name_tmpl,
475 FilePath* new_dir) {
476 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
477 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
478 << "Directory name template must contain \"XXXXXX\".";
480 FilePath sub_dir = base_dir.Append(name_tmpl);
481 std::string sub_dir_string = sub_dir.value();
483 // this should be OK since mkdtemp just replaces characters in place
484 char* buffer = const_cast<char*>(sub_dir_string.c_str());
485 char* dtemp = mkdtemp(buffer);
486 if (!dtemp) {
487 DPLOG(ERROR) << "mkdtemp";
488 return false;
490 *new_dir = FilePath(dtemp);
491 return true;
494 bool CreateTemporaryDirInDir(const FilePath& base_dir,
495 const FilePath::StringType& prefix,
496 FilePath* new_dir) {
497 FilePath::StringType mkdtemp_template = prefix;
498 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
499 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
502 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
503 FilePath* new_temp_path) {
504 FilePath tmpdir;
505 if (!GetTempDir(&tmpdir))
506 return false;
508 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
511 bool CreateDirectory(const FilePath& full_path) {
512 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
513 std::vector<FilePath> subpaths;
515 // Collect a list of all parent directories.
516 FilePath last_path = full_path;
517 subpaths.push_back(full_path);
518 for (FilePath path = full_path.DirName();
519 path.value() != last_path.value(); path = path.DirName()) {
520 subpaths.push_back(path);
521 last_path = path;
524 // Iterate through the parents and create the missing ones.
525 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
526 i != subpaths.rend(); ++i) {
527 if (DirectoryExists(*i))
528 continue;
529 if (mkdir(i->value().c_str(), 0700) == 0)
530 continue;
531 // Mkdir failed, but it might have failed with EEXIST, or some other error
532 // due to the the directory appearing out of thin air. This can occur if
533 // two processes are trying to create the same file system tree at the same
534 // time. Check to see if it exists and make sure it is a directory.
535 if (!DirectoryExists(*i))
536 return false;
538 return true;
541 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
542 const int kMaxAttempts = 20;
543 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
544 int uniquifier =
545 GetUniquePathNumber(path, base::FilePath::StringType());
546 if (uniquifier < 0)
547 break;
548 base::FilePath test_path = (uniquifier == 0) ? path :
549 path.InsertBeforeExtensionASCII(
550 base::StringPrintf(" (%d)", uniquifier));
551 if (mkdir(test_path.value().c_str(), 0777) == 0)
552 return test_path;
553 else if (errno != EEXIST)
554 break;
556 return base::FilePath();
559 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
560 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
561 bool IsLink(const FilePath& file_path) {
562 stat_wrapper_t st;
563 // If we can't lstat the file, it's safe to assume that the file won't at
564 // least be a 'followable' link.
565 if (CallLstat(file_path.value().c_str(), &st) != 0)
566 return false;
568 if (S_ISLNK(st.st_mode))
569 return true;
570 else
571 return false;
574 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
575 stat_wrapper_t file_info;
576 if (CallStat(file_path.value().c_str(), &file_info) != 0)
577 return false;
578 results->is_directory = S_ISDIR(file_info.st_mode);
579 results->size = file_info.st_size;
580 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
581 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
582 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
583 return true;
586 bool GetInode(const FilePath& path, ino_t* inode) {
587 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
588 struct stat buffer;
589 int result = stat(path.value().c_str(), &buffer);
590 if (result < 0)
591 return false;
593 *inode = buffer.st_ino;
594 return true;
597 FILE* OpenFile(const std::string& filename, const char* mode) {
598 return OpenFile(FilePath(filename), mode);
601 FILE* OpenFile(const FilePath& filename, const char* mode) {
602 base::ThreadRestrictions::AssertIOAllowed();
603 FILE* result = NULL;
604 do {
605 result = fopen(filename.value().c_str(), mode);
606 } while (!result && errno == EINTR);
607 return result;
610 int ReadFile(const FilePath& filename, char* data, int size) {
611 base::ThreadRestrictions::AssertIOAllowed();
612 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
613 if (fd < 0)
614 return -1;
616 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
617 if (int ret = HANDLE_EINTR(close(fd)) < 0)
618 return ret;
619 return bytes_read;
622 int WriteFile(const FilePath& filename, const char* data, int size) {
623 base::ThreadRestrictions::AssertIOAllowed();
624 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
625 if (fd < 0)
626 return -1;
628 int bytes_written = WriteFileDescriptor(fd, data, size);
629 if (int ret = HANDLE_EINTR(close(fd)) < 0)
630 return ret;
631 return bytes_written;
634 int WriteFileDescriptor(const int fd, const char* data, int size) {
635 // Allow for partial writes.
636 ssize_t bytes_written_total = 0;
637 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
638 bytes_written_total += bytes_written_partial) {
639 bytes_written_partial =
640 HANDLE_EINTR(write(fd, data + bytes_written_total,
641 size - bytes_written_total));
642 if (bytes_written_partial < 0)
643 return -1;
646 return bytes_written_total;
649 int AppendToFile(const FilePath& filename, const char* data, int size) {
650 base::ThreadRestrictions::AssertIOAllowed();
651 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
652 if (fd < 0)
653 return -1;
655 int bytes_written = WriteFileDescriptor(fd, data, size);
656 if (int ret = HANDLE_EINTR(close(fd)) < 0)
657 return ret;
658 return bytes_written;
661 // Gets the current working directory for the process.
662 bool GetCurrentDirectory(FilePath* dir) {
663 // getcwd can return ENOENT, which implies it checks against the disk.
664 base::ThreadRestrictions::AssertIOAllowed();
666 char system_buffer[PATH_MAX] = "";
667 if (!getcwd(system_buffer, sizeof(system_buffer))) {
668 NOTREACHED();
669 return false;
671 *dir = FilePath(system_buffer);
672 return true;
675 // Sets the current working directory for the process.
676 bool SetCurrentDirectory(const FilePath& path) {
677 base::ThreadRestrictions::AssertIOAllowed();
678 int ret = chdir(path.value().c_str());
679 return !ret;
682 ///////////////////////////////////////////////
683 // FileEnumerator
685 FileEnumerator::FileEnumerator(const FilePath& root_path,
686 bool recursive,
687 int file_type)
688 : current_directory_entry_(0),
689 root_path_(root_path),
690 recursive_(recursive),
691 file_type_(file_type) {
692 // INCLUDE_DOT_DOT must not be specified if recursive.
693 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
694 pending_paths_.push(root_path);
697 FileEnumerator::FileEnumerator(const FilePath& root_path,
698 bool recursive,
699 int file_type,
700 const FilePath::StringType& pattern)
701 : current_directory_entry_(0),
702 root_path_(root_path),
703 recursive_(recursive),
704 file_type_(file_type),
705 pattern_(root_path.Append(pattern).value()) {
706 // INCLUDE_DOT_DOT must not be specified if recursive.
707 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
708 // The Windows version of this code appends the pattern to the root_path,
709 // potentially only matching against items in the top-most directory.
710 // Do the same here.
711 if (pattern.empty())
712 pattern_ = FilePath::StringType();
713 pending_paths_.push(root_path);
716 FileEnumerator::~FileEnumerator() {
719 FilePath FileEnumerator::Next() {
720 ++current_directory_entry_;
722 // While we've exhausted the entries in the current directory, do the next
723 while (current_directory_entry_ >= directory_entries_.size()) {
724 if (pending_paths_.empty())
725 return FilePath();
727 root_path_ = pending_paths_.top();
728 root_path_ = root_path_.StripTrailingSeparators();
729 pending_paths_.pop();
731 std::vector<DirectoryEntryInfo> entries;
732 if (!ReadDirectory(&entries, root_path_, file_type_ & SHOW_SYM_LINKS))
733 continue;
735 directory_entries_.clear();
736 current_directory_entry_ = 0;
737 for (std::vector<DirectoryEntryInfo>::const_iterator
738 i = entries.begin(); i != entries.end(); ++i) {
739 FilePath full_path = root_path_.Append(i->filename);
740 if (ShouldSkip(full_path))
741 continue;
743 if (pattern_.size() &&
744 fnmatch(pattern_.c_str(), full_path.value().c_str(), FNM_NOESCAPE))
745 continue;
747 if (recursive_ && S_ISDIR(i->stat.st_mode))
748 pending_paths_.push(full_path);
750 if ((S_ISDIR(i->stat.st_mode) && (file_type_ & DIRECTORIES)) ||
751 (!S_ISDIR(i->stat.st_mode) && (file_type_ & FILES)))
752 directory_entries_.push_back(*i);
756 return root_path_.Append(directory_entries_[current_directory_entry_
757 ].filename);
760 void FileEnumerator::GetFindInfo(FindInfo* info) {
761 DCHECK(info);
763 if (current_directory_entry_ >= directory_entries_.size())
764 return;
766 DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
767 memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
768 info->filename.assign(cur_entry->filename.value());
771 // static
772 bool FileEnumerator::IsDirectory(const FindInfo& info) {
773 return S_ISDIR(info.stat.st_mode);
776 // static
777 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
778 return FilePath(find_info.filename);
781 // static
782 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
783 return find_info.stat.st_size;
786 // static
787 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
788 return base::Time::FromTimeT(find_info.stat.st_mtime);
791 bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
792 const FilePath& source, bool show_links) {
793 base::ThreadRestrictions::AssertIOAllowed();
794 DIR* dir = opendir(source.value().c_str());
795 if (!dir)
796 return false;
798 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
799 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
800 #error Port warning: depending on the definition of struct dirent, \
801 additional space for pathname may be needed
802 #endif
804 struct dirent dent_buf;
805 struct dirent* dent;
806 while (readdir_r(dir, &dent_buf, &dent) == 0 && dent) {
807 DirectoryEntryInfo info;
808 info.filename = FilePath(dent->d_name);
810 FilePath full_name = source.Append(dent->d_name);
811 int ret;
812 if (show_links)
813 ret = lstat(full_name.value().c_str(), &info.stat);
814 else
815 ret = stat(full_name.value().c_str(), &info.stat);
816 if (ret < 0) {
817 // Print the stat() error message unless it was ENOENT and we're
818 // following symlinks.
819 if (!(errno == ENOENT && !show_links)) {
820 DPLOG(ERROR) << "Couldn't stat "
821 << source.Append(dent->d_name).value();
823 memset(&info.stat, 0, sizeof(info.stat));
825 entries->push_back(info);
828 closedir(dir);
829 return true;
832 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
833 FilePath real_path_result;
834 if (!RealPath(path, &real_path_result))
835 return false;
837 // To be consistant with windows, fail if |real_path_result| is a
838 // directory.
839 stat_wrapper_t file_info;
840 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
841 S_ISDIR(file_info.st_mode))
842 return false;
844 *normalized_path = real_path_result;
845 return true;
848 #if !defined(OS_MACOSX)
849 bool GetTempDir(FilePath* path) {
850 const char* tmp = getenv("TMPDIR");
851 if (tmp)
852 *path = FilePath(tmp);
853 else
854 #if defined(OS_ANDROID)
855 return PathService::Get(base::DIR_CACHE, path);
856 #else
857 *path = FilePath("/tmp");
858 #endif
859 return true;
862 #if !defined(OS_ANDROID)
864 #if defined(OS_LINUX)
865 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
866 // This depends on the mount options used for /dev/shm, which vary among
867 // different Linux distributions and possibly local configuration. It also
868 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
869 // but its kernel allows mprotect with PROT_EXEC anyway.
871 namespace {
873 bool DetermineDevShmExecutable() {
874 bool result = false;
875 FilePath path;
876 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
877 if (fd >= 0) {
878 ScopedFD shm_fd_closer(&fd);
879 Delete(path, false);
880 long sysconf_result = sysconf(_SC_PAGESIZE);
881 CHECK_GE(sysconf_result, 0);
882 size_t pagesize = static_cast<size_t>(sysconf_result);
883 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
884 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
885 if (mapping != MAP_FAILED) {
886 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
887 result = true;
888 munmap(mapping, pagesize);
891 return result;
894 }; // namespace
895 #endif // defined(OS_LINUX)
897 bool GetShmemTempDir(FilePath* path, bool executable) {
898 #if defined(OS_LINUX)
899 bool use_dev_shm = true;
900 if (executable) {
901 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
902 use_dev_shm = s_dev_shm_executable;
904 if (use_dev_shm) {
905 *path = FilePath("/dev/shm");
906 return true;
908 #endif
909 return GetTempDir(path);
911 #endif // !defined(OS_ANDROID)
913 FilePath GetHomeDir() {
914 #if defined(OS_CHROMEOS)
915 if (base::chromeos::IsRunningOnChromeOS())
916 return FilePath("/home/chronos/user");
917 #endif
919 const char* home_dir = getenv("HOME");
920 if (home_dir && home_dir[0])
921 return FilePath(home_dir);
923 #if defined(OS_ANDROID)
924 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
925 #else
926 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
927 base::ThreadRestrictions::AssertIOAllowed();
929 home_dir = g_get_home_dir();
930 if (home_dir && home_dir[0])
931 return FilePath(home_dir);
932 #endif
934 FilePath rv;
935 if (file_util::GetTempDir(&rv))
936 return rv;
938 // Last resort.
939 return FilePath("/tmp");
942 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
943 base::ThreadRestrictions::AssertIOAllowed();
944 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
945 if (infile < 0)
946 return false;
948 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
949 if (outfile < 0) {
950 ignore_result(HANDLE_EINTR(close(infile)));
951 return false;
954 const size_t kBufferSize = 32768;
955 std::vector<char> buffer(kBufferSize);
956 bool result = true;
958 while (result) {
959 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
960 if (bytes_read < 0) {
961 result = false;
962 break;
964 if (bytes_read == 0)
965 break;
966 // Allow for partial writes
967 ssize_t bytes_written_per_read = 0;
968 do {
969 ssize_t bytes_written_partial = HANDLE_EINTR(write(
970 outfile,
971 &buffer[bytes_written_per_read],
972 bytes_read - bytes_written_per_read));
973 if (bytes_written_partial < 0) {
974 result = false;
975 break;
977 bytes_written_per_read += bytes_written_partial;
978 } while (bytes_written_per_read < bytes_read);
981 if (HANDLE_EINTR(close(infile)) < 0)
982 result = false;
983 if (HANDLE_EINTR(close(outfile)) < 0)
984 result = false;
986 return result;
988 #endif // !defined(OS_MACOSX)
990 bool VerifyPathControlledByUser(const FilePath& base,
991 const FilePath& path,
992 uid_t owner_uid,
993 const std::set<gid_t>& group_gids) {
994 if (base != path && !base.IsParent(path)) {
995 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
996 << base.value() << "\", path = \"" << path.value() << "\"";
997 return false;
1000 std::vector<FilePath::StringType> base_components;
1001 std::vector<FilePath::StringType> path_components;
1003 base.GetComponents(&base_components);
1004 path.GetComponents(&path_components);
1006 std::vector<FilePath::StringType>::const_iterator ib, ip;
1007 for (ib = base_components.begin(), ip = path_components.begin();
1008 ib != base_components.end(); ++ib, ++ip) {
1009 // |base| must be a subpath of |path|, so all components should match.
1010 // If these CHECKs fail, look at the test that base is a parent of
1011 // path at the top of this function.
1012 DCHECK(ip != path_components.end());
1013 DCHECK(*ip == *ib);
1016 FilePath current_path = base;
1017 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
1018 return false;
1020 for (; ip != path_components.end(); ++ip) {
1021 current_path = current_path.Append(*ip);
1022 if (!VerifySpecificPathControlledByUser(
1023 current_path, owner_uid, group_gids))
1024 return false;
1026 return true;
1029 #if defined(OS_MACOSX) && !defined(OS_IOS)
1030 bool VerifyPathControlledByAdmin(const FilePath& path) {
1031 const unsigned kRootUid = 0;
1032 const FilePath kFileSystemRoot("/");
1034 // The name of the administrator group on mac os.
1035 const char* const kAdminGroupNames[] = {
1036 "admin",
1037 "wheel"
1040 // Reading the groups database may touch the file system.
1041 base::ThreadRestrictions::AssertIOAllowed();
1043 std::set<gid_t> allowed_group_ids;
1044 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
1045 struct group *group_record = getgrnam(kAdminGroupNames[i]);
1046 if (!group_record) {
1047 DPLOG(ERROR) << "Could not get the group ID of group \""
1048 << kAdminGroupNames[i] << "\".";
1049 continue;
1052 allowed_group_ids.insert(group_record->gr_gid);
1055 return VerifyPathControlledByUser(
1056 kFileSystemRoot, path, kRootUid, allowed_group_ids);
1058 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1060 int GetMaximumPathComponentLength(const FilePath& path) {
1061 base::ThreadRestrictions::AssertIOAllowed();
1062 return pathconf(path.value().c_str(), _PC_NAME_MAX);
1065 } // namespace file_util