Revert "Revert "Revert 198403 "Move WrappedTexImage functionality to ui/gl"""
[chromium-blink-merge.git] / base / file_util_posix.cc
blob8b368127410e091eb392cf440f2bd9c50a417acd
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 ReplaceFile(const FilePath& from_path, const FilePath& to_path) {
236 base::ThreadRestrictions::AssertIOAllowed();
237 return (rename(from_path.value().c_str(), to_path.value().c_str()) == 0);
240 bool CopyDirectory(const FilePath& from_path,
241 const FilePath& to_path,
242 bool recursive) {
243 base::ThreadRestrictions::AssertIOAllowed();
244 // Some old callers of CopyDirectory want it to support wildcards.
245 // After some discussion, we decided to fix those callers.
246 // Break loudly here if anyone tries to do this.
247 // TODO(evanm): remove this once we're sure it's ok.
248 DCHECK(to_path.value().find('*') == std::string::npos);
249 DCHECK(from_path.value().find('*') == std::string::npos);
251 char top_dir[PATH_MAX];
252 if (base::strlcpy(top_dir, from_path.value().c_str(),
253 arraysize(top_dir)) >= arraysize(top_dir)) {
254 return false;
257 // This function does not properly handle destinations within the source
258 FilePath real_to_path = to_path;
259 if (PathExists(real_to_path)) {
260 real_to_path = MakeAbsoluteFilePath(real_to_path);
261 if (real_to_path.empty())
262 return false;
263 } else {
264 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
265 if (real_to_path.empty())
266 return false;
268 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
269 if (real_from_path.empty())
270 return false;
271 if (real_to_path.value().size() >= real_from_path.value().size() &&
272 real_to_path.value().compare(0, real_from_path.value().size(),
273 real_from_path.value()) == 0)
274 return false;
276 bool success = true;
277 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
278 if (recursive)
279 traverse_type |= FileEnumerator::DIRECTORIES;
280 FileEnumerator traversal(from_path, recursive, traverse_type);
282 // We have to mimic windows behavior here. |to_path| may not exist yet,
283 // start the loop with |to_path|.
284 FileEnumerator::FindInfo info;
285 FilePath current = from_path;
286 if (stat(from_path.value().c_str(), &info.stat) < 0) {
287 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
288 << from_path.value() << " errno = " << errno;
289 success = false;
291 struct stat to_path_stat;
292 FilePath from_path_base = from_path;
293 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
294 S_ISDIR(to_path_stat.st_mode)) {
295 // If the destination already exists and is a directory, then the
296 // top level of source needs to be copied.
297 from_path_base = from_path.DirName();
300 // The Windows version of this function assumes that non-recursive calls
301 // will always have a directory for from_path.
302 DCHECK(recursive || S_ISDIR(info.stat.st_mode));
304 while (success && !current.empty()) {
305 // current is the source path, including from_path, so append
306 // the suffix after from_path to to_path to create the target_path.
307 FilePath target_path(to_path);
308 if (from_path_base != current) {
309 if (!from_path_base.AppendRelativePath(current, &target_path)) {
310 success = false;
311 break;
315 if (S_ISDIR(info.stat.st_mode)) {
316 if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
317 errno != EEXIST) {
318 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
319 << target_path.value() << " errno = " << errno;
320 success = false;
322 } else if (S_ISREG(info.stat.st_mode)) {
323 if (!CopyFile(current, target_path)) {
324 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
325 << target_path.value();
326 success = false;
328 } else {
329 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
330 << current.value();
333 current = traversal.Next();
334 traversal.GetFindInfo(&info);
337 return success;
340 bool PathExists(const FilePath& path) {
341 base::ThreadRestrictions::AssertIOAllowed();
342 return access(path.value().c_str(), F_OK) == 0;
345 bool PathIsWritable(const FilePath& path) {
346 base::ThreadRestrictions::AssertIOAllowed();
347 return access(path.value().c_str(), W_OK) == 0;
350 bool DirectoryExists(const FilePath& path) {
351 base::ThreadRestrictions::AssertIOAllowed();
352 stat_wrapper_t file_info;
353 if (CallStat(path.value().c_str(), &file_info) == 0)
354 return S_ISDIR(file_info.st_mode);
355 return false;
358 bool ReadFromFD(int fd, char* buffer, size_t bytes) {
359 size_t total_read = 0;
360 while (total_read < bytes) {
361 ssize_t bytes_read =
362 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
363 if (bytes_read <= 0)
364 break;
365 total_read += bytes_read;
367 return total_read == bytes;
370 bool CreateSymbolicLink(const FilePath& target_path,
371 const FilePath& symlink_path) {
372 DCHECK(!symlink_path.empty());
373 DCHECK(!target_path.empty());
374 return ::symlink(target_path.value().c_str(),
375 symlink_path.value().c_str()) != -1;
378 bool ReadSymbolicLink(const FilePath& symlink_path,
379 FilePath* target_path) {
380 DCHECK(!symlink_path.empty());
381 DCHECK(target_path);
382 char buf[PATH_MAX];
383 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
385 if (count <= 0) {
386 target_path->clear();
387 return false;
390 *target_path = FilePath(FilePath::StringType(buf, count));
391 return true;
394 bool GetPosixFilePermissions(const FilePath& path, int* mode) {
395 base::ThreadRestrictions::AssertIOAllowed();
396 DCHECK(mode);
398 stat_wrapper_t file_info;
399 // Uses stat(), because on symbolic link, lstat() does not return valid
400 // permission bits in st_mode
401 if (CallStat(path.value().c_str(), &file_info) != 0)
402 return false;
404 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
405 return true;
408 bool SetPosixFilePermissions(const FilePath& path,
409 int mode) {
410 base::ThreadRestrictions::AssertIOAllowed();
411 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
413 // Calls stat() so that we can preserve the higher bits like S_ISGID.
414 stat_wrapper_t stat_buf;
415 if (CallStat(path.value().c_str(), &stat_buf) != 0)
416 return false;
418 // Clears the existing permission bits, and adds the new ones.
419 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
420 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
422 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
423 return false;
425 return true;
428 // Creates and opens a temporary file in |directory|, returning the
429 // file descriptor. |path| is set to the temporary file path.
430 // This function does NOT unlink() the file.
431 int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
432 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
433 *path = directory.Append(TempFileName());
434 const std::string& tmpdir_string = path->value();
435 // this should be OK since mkstemp just replaces characters in place
436 char* buffer = const_cast<char*>(tmpdir_string.c_str());
438 return HANDLE_EINTR(mkstemp(buffer));
441 bool CreateTemporaryFile(FilePath* path) {
442 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
443 FilePath directory;
444 if (!GetTempDir(&directory))
445 return false;
446 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
447 if (fd < 0)
448 return false;
449 ignore_result(HANDLE_EINTR(close(fd)));
450 return true;
453 FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
454 FilePath directory;
455 if (!GetShmemTempDir(&directory, executable))
456 return NULL;
458 return CreateAndOpenTemporaryFileInDir(directory, path);
461 FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
462 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
463 if (fd < 0)
464 return NULL;
466 FILE* file = fdopen(fd, "a+");
467 if (!file)
468 ignore_result(HANDLE_EINTR(close(fd)));
469 return file;
472 bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
473 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
474 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
475 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
478 static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
479 const FilePath::StringType& name_tmpl,
480 FilePath* new_dir) {
481 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
482 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
483 << "Directory name template must contain \"XXXXXX\".";
485 FilePath sub_dir = base_dir.Append(name_tmpl);
486 std::string sub_dir_string = sub_dir.value();
488 // this should be OK since mkdtemp just replaces characters in place
489 char* buffer = const_cast<char*>(sub_dir_string.c_str());
490 char* dtemp = mkdtemp(buffer);
491 if (!dtemp) {
492 DPLOG(ERROR) << "mkdtemp";
493 return false;
495 *new_dir = FilePath(dtemp);
496 return true;
499 bool CreateTemporaryDirInDir(const FilePath& base_dir,
500 const FilePath::StringType& prefix,
501 FilePath* new_dir) {
502 FilePath::StringType mkdtemp_template = prefix;
503 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
504 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
507 bool CreateNewTempDirectory(const FilePath::StringType& prefix,
508 FilePath* new_temp_path) {
509 FilePath tmpdir;
510 if (!GetTempDir(&tmpdir))
511 return false;
513 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
516 bool CreateDirectory(const FilePath& full_path) {
517 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
518 std::vector<FilePath> subpaths;
520 // Collect a list of all parent directories.
521 FilePath last_path = full_path;
522 subpaths.push_back(full_path);
523 for (FilePath path = full_path.DirName();
524 path.value() != last_path.value(); path = path.DirName()) {
525 subpaths.push_back(path);
526 last_path = path;
529 // Iterate through the parents and create the missing ones.
530 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
531 i != subpaths.rend(); ++i) {
532 if (DirectoryExists(*i))
533 continue;
534 if (mkdir(i->value().c_str(), 0700) == 0)
535 continue;
536 // Mkdir failed, but it might have failed with EEXIST, or some other error
537 // due to the the directory appearing out of thin air. This can occur if
538 // two processes are trying to create the same file system tree at the same
539 // time. Check to see if it exists and make sure it is a directory.
540 if (!DirectoryExists(*i))
541 return false;
543 return true;
546 base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
547 const int kMaxAttempts = 20;
548 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
549 int uniquifier =
550 GetUniquePathNumber(path, base::FilePath::StringType());
551 if (uniquifier < 0)
552 break;
553 base::FilePath test_path = (uniquifier == 0) ? path :
554 path.InsertBeforeExtensionASCII(
555 base::StringPrintf(" (%d)", uniquifier));
556 if (mkdir(test_path.value().c_str(), 0777) == 0)
557 return test_path;
558 else if (errno != EEXIST)
559 break;
561 return base::FilePath();
564 // TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
565 // correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
566 bool IsLink(const FilePath& file_path) {
567 stat_wrapper_t st;
568 // If we can't lstat the file, it's safe to assume that the file won't at
569 // least be a 'followable' link.
570 if (CallLstat(file_path.value().c_str(), &st) != 0)
571 return false;
573 if (S_ISLNK(st.st_mode))
574 return true;
575 else
576 return false;
579 bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
580 stat_wrapper_t file_info;
581 if (CallStat(file_path.value().c_str(), &file_info) != 0)
582 return false;
583 results->is_directory = S_ISDIR(file_info.st_mode);
584 results->size = file_info.st_size;
585 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
586 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
587 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
588 return true;
591 bool GetInode(const FilePath& path, ino_t* inode) {
592 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
593 struct stat buffer;
594 int result = stat(path.value().c_str(), &buffer);
595 if (result < 0)
596 return false;
598 *inode = buffer.st_ino;
599 return true;
602 FILE* OpenFile(const std::string& filename, const char* mode) {
603 return OpenFile(FilePath(filename), mode);
606 FILE* OpenFile(const FilePath& filename, const char* mode) {
607 base::ThreadRestrictions::AssertIOAllowed();
608 FILE* result = NULL;
609 do {
610 result = fopen(filename.value().c_str(), mode);
611 } while (!result && errno == EINTR);
612 return result;
615 int ReadFile(const FilePath& filename, char* data, int size) {
616 base::ThreadRestrictions::AssertIOAllowed();
617 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
618 if (fd < 0)
619 return -1;
621 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
622 if (int ret = HANDLE_EINTR(close(fd)) < 0)
623 return ret;
624 return bytes_read;
627 int WriteFile(const FilePath& filename, const char* data, int size) {
628 base::ThreadRestrictions::AssertIOAllowed();
629 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
630 if (fd < 0)
631 return -1;
633 int bytes_written = WriteFileDescriptor(fd, data, size);
634 if (int ret = HANDLE_EINTR(close(fd)) < 0)
635 return ret;
636 return bytes_written;
639 int WriteFileDescriptor(const int fd, const char* data, int size) {
640 // Allow for partial writes.
641 ssize_t bytes_written_total = 0;
642 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
643 bytes_written_total += bytes_written_partial) {
644 bytes_written_partial =
645 HANDLE_EINTR(write(fd, data + bytes_written_total,
646 size - bytes_written_total));
647 if (bytes_written_partial < 0)
648 return -1;
651 return bytes_written_total;
654 int AppendToFile(const FilePath& filename, const char* data, int size) {
655 base::ThreadRestrictions::AssertIOAllowed();
656 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
657 if (fd < 0)
658 return -1;
660 int bytes_written = WriteFileDescriptor(fd, data, size);
661 if (int ret = HANDLE_EINTR(close(fd)) < 0)
662 return ret;
663 return bytes_written;
666 // Gets the current working directory for the process.
667 bool GetCurrentDirectory(FilePath* dir) {
668 // getcwd can return ENOENT, which implies it checks against the disk.
669 base::ThreadRestrictions::AssertIOAllowed();
671 char system_buffer[PATH_MAX] = "";
672 if (!getcwd(system_buffer, sizeof(system_buffer))) {
673 NOTREACHED();
674 return false;
676 *dir = FilePath(system_buffer);
677 return true;
680 // Sets the current working directory for the process.
681 bool SetCurrentDirectory(const FilePath& path) {
682 base::ThreadRestrictions::AssertIOAllowed();
683 int ret = chdir(path.value().c_str());
684 return !ret;
687 ///////////////////////////////////////////////
688 // FileEnumerator
690 FileEnumerator::FileEnumerator(const FilePath& root_path,
691 bool recursive,
692 int file_type)
693 : current_directory_entry_(0),
694 root_path_(root_path),
695 recursive_(recursive),
696 file_type_(file_type) {
697 // INCLUDE_DOT_DOT must not be specified if recursive.
698 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
699 pending_paths_.push(root_path);
702 FileEnumerator::FileEnumerator(const FilePath& root_path,
703 bool recursive,
704 int file_type,
705 const FilePath::StringType& pattern)
706 : current_directory_entry_(0),
707 root_path_(root_path),
708 recursive_(recursive),
709 file_type_(file_type),
710 pattern_(root_path.Append(pattern).value()) {
711 // INCLUDE_DOT_DOT must not be specified if recursive.
712 DCHECK(!(recursive && (INCLUDE_DOT_DOT & file_type_)));
713 // The Windows version of this code appends the pattern to the root_path,
714 // potentially only matching against items in the top-most directory.
715 // Do the same here.
716 if (pattern.empty())
717 pattern_ = FilePath::StringType();
718 pending_paths_.push(root_path);
721 FileEnumerator::~FileEnumerator() {
724 FilePath FileEnumerator::Next() {
725 ++current_directory_entry_;
727 // While we've exhausted the entries in the current directory, do the next
728 while (current_directory_entry_ >= directory_entries_.size()) {
729 if (pending_paths_.empty())
730 return FilePath();
732 root_path_ = pending_paths_.top();
733 root_path_ = root_path_.StripTrailingSeparators();
734 pending_paths_.pop();
736 std::vector<DirectoryEntryInfo> entries;
737 if (!ReadDirectory(&entries, root_path_, file_type_ & SHOW_SYM_LINKS))
738 continue;
740 directory_entries_.clear();
741 current_directory_entry_ = 0;
742 for (std::vector<DirectoryEntryInfo>::const_iterator
743 i = entries.begin(); i != entries.end(); ++i) {
744 FilePath full_path = root_path_.Append(i->filename);
745 if (ShouldSkip(full_path))
746 continue;
748 if (pattern_.size() &&
749 fnmatch(pattern_.c_str(), full_path.value().c_str(), FNM_NOESCAPE))
750 continue;
752 if (recursive_ && S_ISDIR(i->stat.st_mode))
753 pending_paths_.push(full_path);
755 if ((S_ISDIR(i->stat.st_mode) && (file_type_ & DIRECTORIES)) ||
756 (!S_ISDIR(i->stat.st_mode) && (file_type_ & FILES)))
757 directory_entries_.push_back(*i);
761 return root_path_.Append(directory_entries_[current_directory_entry_
762 ].filename);
765 void FileEnumerator::GetFindInfo(FindInfo* info) {
766 DCHECK(info);
768 if (current_directory_entry_ >= directory_entries_.size())
769 return;
771 DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
772 memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
773 info->filename.assign(cur_entry->filename.value());
776 // static
777 bool FileEnumerator::IsDirectory(const FindInfo& info) {
778 return S_ISDIR(info.stat.st_mode);
781 // static
782 FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
783 return FilePath(find_info.filename);
786 // static
787 int64 FileEnumerator::GetFilesize(const FindInfo& find_info) {
788 return find_info.stat.st_size;
791 // static
792 base::Time FileEnumerator::GetLastModifiedTime(const FindInfo& find_info) {
793 return base::Time::FromTimeT(find_info.stat.st_mtime);
796 bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
797 const FilePath& source, bool show_links) {
798 base::ThreadRestrictions::AssertIOAllowed();
799 DIR* dir = opendir(source.value().c_str());
800 if (!dir)
801 return false;
803 #if !defined(OS_LINUX) && !defined(OS_MACOSX) && !defined(OS_BSD) && \
804 !defined(OS_SOLARIS) && !defined(OS_ANDROID)
805 #error Port warning: depending on the definition of struct dirent, \
806 additional space for pathname may be needed
807 #endif
809 struct dirent dent_buf;
810 struct dirent* dent;
811 while (readdir_r(dir, &dent_buf, &dent) == 0 && dent) {
812 DirectoryEntryInfo info;
813 info.filename = FilePath(dent->d_name);
815 FilePath full_name = source.Append(dent->d_name);
816 int ret;
817 if (show_links)
818 ret = lstat(full_name.value().c_str(), &info.stat);
819 else
820 ret = stat(full_name.value().c_str(), &info.stat);
821 if (ret < 0) {
822 // Print the stat() error message unless it was ENOENT and we're
823 // following symlinks.
824 if (!(errno == ENOENT && !show_links)) {
825 DPLOG(ERROR) << "Couldn't stat "
826 << source.Append(dent->d_name).value();
828 memset(&info.stat, 0, sizeof(info.stat));
830 entries->push_back(info);
833 closedir(dir);
834 return true;
837 bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
838 FilePath real_path_result;
839 if (!RealPath(path, &real_path_result))
840 return false;
842 // To be consistant with windows, fail if |real_path_result| is a
843 // directory.
844 stat_wrapper_t file_info;
845 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
846 S_ISDIR(file_info.st_mode))
847 return false;
849 *normalized_path = real_path_result;
850 return true;
853 #if !defined(OS_MACOSX)
854 bool GetTempDir(FilePath* path) {
855 const char* tmp = getenv("TMPDIR");
856 if (tmp)
857 *path = FilePath(tmp);
858 else
859 #if defined(OS_ANDROID)
860 return PathService::Get(base::DIR_CACHE, path);
861 #else
862 *path = FilePath("/tmp");
863 #endif
864 return true;
867 #if !defined(OS_ANDROID)
869 #if defined(OS_LINUX)
870 // Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
871 // This depends on the mount options used for /dev/shm, which vary among
872 // different Linux distributions and possibly local configuration. It also
873 // depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
874 // but its kernel allows mprotect with PROT_EXEC anyway.
876 namespace {
878 bool DetermineDevShmExecutable() {
879 bool result = false;
880 FilePath path;
881 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
882 if (fd >= 0) {
883 ScopedFD shm_fd_closer(&fd);
884 Delete(path, false);
885 long sysconf_result = sysconf(_SC_PAGESIZE);
886 CHECK_GE(sysconf_result, 0);
887 size_t pagesize = static_cast<size_t>(sysconf_result);
888 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
889 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
890 if (mapping != MAP_FAILED) {
891 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
892 result = true;
893 munmap(mapping, pagesize);
896 return result;
899 }; // namespace
900 #endif // defined(OS_LINUX)
902 bool GetShmemTempDir(FilePath* path, bool executable) {
903 #if defined(OS_LINUX)
904 bool use_dev_shm = true;
905 if (executable) {
906 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
907 use_dev_shm = s_dev_shm_executable;
909 if (use_dev_shm) {
910 *path = FilePath("/dev/shm");
911 return true;
913 #endif
914 return GetTempDir(path);
916 #endif // !defined(OS_ANDROID)
918 FilePath GetHomeDir() {
919 #if defined(OS_CHROMEOS)
920 if (base::chromeos::IsRunningOnChromeOS())
921 return FilePath("/home/chronos/user");
922 #endif
924 const char* home_dir = getenv("HOME");
925 if (home_dir && home_dir[0])
926 return FilePath(home_dir);
928 #if defined(OS_ANDROID)
929 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
930 #else
931 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
932 base::ThreadRestrictions::AssertIOAllowed();
934 home_dir = g_get_home_dir();
935 if (home_dir && home_dir[0])
936 return FilePath(home_dir);
937 #endif
939 FilePath rv;
940 if (file_util::GetTempDir(&rv))
941 return rv;
943 // Last resort.
944 return FilePath("/tmp");
947 bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
948 base::ThreadRestrictions::AssertIOAllowed();
949 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
950 if (infile < 0)
951 return false;
953 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
954 if (outfile < 0) {
955 ignore_result(HANDLE_EINTR(close(infile)));
956 return false;
959 const size_t kBufferSize = 32768;
960 std::vector<char> buffer(kBufferSize);
961 bool result = true;
963 while (result) {
964 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
965 if (bytes_read < 0) {
966 result = false;
967 break;
969 if (bytes_read == 0)
970 break;
971 // Allow for partial writes
972 ssize_t bytes_written_per_read = 0;
973 do {
974 ssize_t bytes_written_partial = HANDLE_EINTR(write(
975 outfile,
976 &buffer[bytes_written_per_read],
977 bytes_read - bytes_written_per_read));
978 if (bytes_written_partial < 0) {
979 result = false;
980 break;
982 bytes_written_per_read += bytes_written_partial;
983 } while (bytes_written_per_read < bytes_read);
986 if (HANDLE_EINTR(close(infile)) < 0)
987 result = false;
988 if (HANDLE_EINTR(close(outfile)) < 0)
989 result = false;
991 return result;
993 #endif // !defined(OS_MACOSX)
995 bool VerifyPathControlledByUser(const FilePath& base,
996 const FilePath& path,
997 uid_t owner_uid,
998 const std::set<gid_t>& group_gids) {
999 if (base != path && !base.IsParent(path)) {
1000 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
1001 << base.value() << "\", path = \"" << path.value() << "\"";
1002 return false;
1005 std::vector<FilePath::StringType> base_components;
1006 std::vector<FilePath::StringType> path_components;
1008 base.GetComponents(&base_components);
1009 path.GetComponents(&path_components);
1011 std::vector<FilePath::StringType>::const_iterator ib, ip;
1012 for (ib = base_components.begin(), ip = path_components.begin();
1013 ib != base_components.end(); ++ib, ++ip) {
1014 // |base| must be a subpath of |path|, so all components should match.
1015 // If these CHECKs fail, look at the test that base is a parent of
1016 // path at the top of this function.
1017 DCHECK(ip != path_components.end());
1018 DCHECK(*ip == *ib);
1021 FilePath current_path = base;
1022 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
1023 return false;
1025 for (; ip != path_components.end(); ++ip) {
1026 current_path = current_path.Append(*ip);
1027 if (!VerifySpecificPathControlledByUser(
1028 current_path, owner_uid, group_gids))
1029 return false;
1031 return true;
1034 #if defined(OS_MACOSX) && !defined(OS_IOS)
1035 bool VerifyPathControlledByAdmin(const FilePath& path) {
1036 const unsigned kRootUid = 0;
1037 const FilePath kFileSystemRoot("/");
1039 // The name of the administrator group on mac os.
1040 const char* const kAdminGroupNames[] = {
1041 "admin",
1042 "wheel"
1045 // Reading the groups database may touch the file system.
1046 base::ThreadRestrictions::AssertIOAllowed();
1048 std::set<gid_t> allowed_group_ids;
1049 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
1050 struct group *group_record = getgrnam(kAdminGroupNames[i]);
1051 if (!group_record) {
1052 DPLOG(ERROR) << "Could not get the group ID of group \""
1053 << kAdminGroupNames[i] << "\".";
1054 continue;
1057 allowed_group_ids.insert(group_record->gr_gid);
1060 return VerifyPathControlledByUser(
1061 kFileSystemRoot, path, kRootUid, allowed_group_ids);
1063 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
1065 int GetMaximumPathComponentLength(const FilePath& path) {
1066 base::ThreadRestrictions::AssertIOAllowed();
1067 return pathconf(path.value().c_str(), _PC_NAME_MAX);
1070 } // namespace file_util