blob: 3f0ee0aef2efd54c583e3102e02e484cd9b9d505 [file] [log] [blame]
tzik@chromium.orgf5864952012-03-10 09:18:31 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
mmentovai@google.comaa13be62008-09-03 03:20:34 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/file_util.h"
6
evan@chromium.org37301322009-04-21 10:50:39 +09007#include <dirent.h>
evanm@google.com5c1d39b2008-09-19 04:15:54 +09008#include <errno.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +09009#include <fcntl.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090010#include <libgen.h>
skerner@chromium.org5f3c4562010-05-13 06:36:39 +090011#include <limits.h>
mark@chromium.orgd1bafc62008-10-02 02:40:13 +090012#include <stdio.h>
evan@chromium.org73aec0e2010-04-23 08:28:05 +090013#include <stdlib.h>
evanm@google.com5c1d39b2008-09-19 04:15:54 +090014#include <string.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090015#include <sys/errno.h>
estade@chromium.org2c233532008-12-13 08:43:03 +090016#include <sys/mman.h>
skerner@chromium.org559baa92010-05-13 00:13:57 +090017#include <sys/param.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090018#include <sys/stat.h>
jochen@chromium.orga6879772010-02-18 19:02:26 +090019#include <sys/time.h>
evan@chromium.org37301322009-04-21 10:50:39 +090020#include <sys/types.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090021#include <time.h>
evan@chromium.org37301322009-04-21 10:50:39 +090022#include <unistd.h>
mmentovai@google.comaa13be62008-09-03 03:20:34 +090023
mark@chromium.org0e56c162009-09-17 02:31:25 +090024#if defined(OS_MACOSX)
25#include <AvailabilityMacros.h>
mark@chromium.org13aa8aa2011-04-22 13:15:13 +090026#include "base/mac/foundation_util.h"
spang@chromium.org8d0fa9a2013-11-20 14:33:46 +090027#elif !defined(OS_CHROMEOS) && defined(USE_GLIB)
satorux@chromium.org0c64e3e2013-11-07 20:38:32 +090028#include <glib.h> // for g_get_home_dir()
mark@chromium.org0e56c162009-09-17 02:31:25 +090029#endif
30
mmentovai@google.comaa13be62008-09-03 03:20:34 +090031#include <fstream>
32
33#include "base/basictypes.h"
brettw@chromium.org56946722013-06-08 13:53:36 +090034#include "base/files/file_enumerator.h"
brettw@chromium.org59eef1f2013-02-24 14:40:52 +090035#include "base/files/file_path.h"
mmentovai@google.comaa13be62008-09-03 03:20:34 +090036#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090037#include "base/memory/scoped_ptr.h"
38#include "base/memory/singleton.h"
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +090039#include "base/path_service.h"
brettw@chromium.orgb1788fb2012-11-15 05:54:35 +090040#include "base/posix/eintr_wrapper.h"
skerner@chromium.org80784142011-10-18 06:30:29 +090041#include "base/stl_util.h"
avi@chromium.org94bd5732013-06-11 22:36:37 +090042#include "base/strings/string_util.h"
43#include "base/strings/stringprintf.h"
brettw@chromium.org1f67a912013-02-08 04:18:03 +090044#include "base/strings/sys_string_conversions.h"
avi@chromium.org17f60622013-06-08 03:37:07 +090045#include "base/strings/utf_string_conversions.h"
stevenjb@chromium.org861313b2013-09-28 04:28:24 +090046#include "base/sys_info.h"
brettw@chromium.org5b5f5e02011-01-01 10:01:06 +090047#include "base/threading/thread_restrictions.h"
avi@chromium.orgb039e8b2013-06-28 09:49:07 +090048#include "base/time/time.h"
estade@chromium.org868ecbc2009-06-24 12:29:26 +090049
michaelbai@google.com2251c622011-06-22 07:34:50 +090050#if defined(OS_ANDROID)
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +090051#include "base/android/content_uri_utils.h"
michaelbai@google.com2251c622011-06-22 07:34:50 +090052#include "base/os_compat_android.h"
53#endif
54
qsr@chromium.org4ab5de92012-07-09 23:40:39 +090055#if !defined(OS_IOS)
56#include <grp.h>
57#endif
58
brettw@chromium.org99b198e2013-04-12 14:17:15 +090059namespace base {
60
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090061namespace {
62
rsesek@chromium.orgdc818ac2012-07-20 07:24:02 +090063#if defined(OS_BSD) || defined(OS_MACOSX)
skerner@google.com93449ef2011-09-22 23:47:18 +090064typedef struct stat stat_wrapper_t;
65static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090066 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090067 return stat(path, sb);
68}
69static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090070 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090071 return lstat(path, sb);
72}
73#else
74typedef struct stat64 stat_wrapper_t;
75static int CallStat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090076 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090077 return stat64(path, sb);
78}
79static int CallLstat(const char *path, stat_wrapper_t *sb) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090080 ThreadRestrictions::AssertIOAllowed();
skerner@google.com93449ef2011-09-22 23:47:18 +090081 return lstat64(path, sb);
82}
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +090083#if defined(OS_ANDROID)
84static int CallFstat(int fd, stat_wrapper_t *sb) {
85 ThreadRestrictions::AssertIOAllowed();
86 return fstat64(fd, sb);
87}
88#endif
skerner@google.com93449ef2011-09-22 23:47:18 +090089#endif
90
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090091// Helper for NormalizeFilePath(), defined below.
92bool RealPath(const FilePath& path, FilePath* real_path) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +090093 ThreadRestrictions::AssertIOAllowed(); // For realpath().
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +090094 FilePath::CharType buf[PATH_MAX];
95 if (!realpath(path.value().c_str(), buf))
96 return false;
97
98 *real_path = FilePath(buf);
99 return true;
100}
101
skerner@google.com93449ef2011-09-22 23:47:18 +0900102// Helper for VerifyPathControlledByUser.
103bool VerifySpecificPathControlledByUser(const FilePath& path,
104 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900105 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900106 stat_wrapper_t stat_info;
107 if (CallLstat(path.value().c_str(), &stat_info) != 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900108 DPLOG(ERROR) << "Failed to get information on path "
109 << path.value();
skerner@google.com93449ef2011-09-22 23:47:18 +0900110 return false;
111 }
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900112
skerner@google.com93449ef2011-09-22 23:47:18 +0900113 if (S_ISLNK(stat_info.st_mode)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900114 DLOG(ERROR) << "Path " << path.value()
skerner@google.com93449ef2011-09-22 23:47:18 +0900115 << " is a symbolic link.";
116 return false;
117 }
118
119 if (stat_info.st_uid != owner_uid) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900120 DLOG(ERROR) << "Path " << path.value()
121 << " is owned by the wrong user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900122 return false;
123 }
124
skerner@chromium.org80784142011-10-18 06:30:29 +0900125 if ((stat_info.st_mode & S_IWGRP) &&
126 !ContainsKey(group_gids, stat_info.st_gid)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900127 DLOG(ERROR) << "Path " << path.value()
128 << " is writable by an unprivileged group.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900129 return false;
130 }
131
132 if (stat_info.st_mode & S_IWOTH) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900133 DLOG(ERROR) << "Path " << path.value()
134 << " is writable by any user.";
skerner@google.com93449ef2011-09-22 23:47:18 +0900135 return false;
136 }
137
138 return true;
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900139}
skerner@google.com93449ef2011-09-22 23:47:18 +0900140
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900141std::string TempFileName() {
142#if defined(OS_MACOSX)
143 return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID());
144#endif
145
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
151}
152
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900153// Creates and opens a temporary file in |directory|, returning the
154// file descriptor. |path| is set to the temporary file path.
155// This function does NOT unlink() the file.
156int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
157 ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
158 *path = directory.Append(base::TempFileName());
159 const std::string& tmpdir_string = path->value();
160 // this should be OK since mkstemp just replaces characters in place
161 char* buffer = const_cast<char*>(tmpdir_string.c_str());
162
163 return HANDLE_EINTR(mkstemp(buffer));
164}
165
166#if defined(OS_LINUX)
167// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
168// This depends on the mount options used for /dev/shm, which vary among
169// different Linux distributions and possibly local configuration. It also
170// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
171// but its kernel allows mprotect with PROT_EXEC anyway.
172bool DetermineDevShmExecutable() {
173 bool result = false;
174 FilePath path;
175 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
176 if (fd >= 0) {
177 file_util::ScopedFD shm_fd_closer(&fd);
178 DeleteFile(path, false);
179 long sysconf_result = sysconf(_SC_PAGESIZE);
180 CHECK_GE(sysconf_result, 0);
181 size_t pagesize = static_cast<size_t>(sysconf_result);
182 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
183 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
184 if (mapping != MAP_FAILED) {
185 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
186 result = true;
187 munmap(mapping, pagesize);
188 }
189 }
190 return result;
191}
192#endif // defined(OS_LINUX)
193
skerner@google.com93449ef2011-09-22 23:47:18 +0900194} // namespace
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900195
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900196FilePath MakeAbsoluteFilePath(const FilePath& input) {
197 ThreadRestrictions::AssertIOAllowed();
198 char full_path[PATH_MAX];
199 if (realpath(input.value().c_str(), full_path) == NULL)
200 return FilePath();
201 return FilePath(full_path);
mark@chromium.org13aa8aa2011-04-22 13:15:13 +0900202}
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900203
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900204// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
205// which works both with and without the recursive flag. I'm not sure we need
206// that functionality. If not, remove from file_util_win.cc, otherwise add it
207// here.
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900208bool DeleteFile(const FilePath& path, bool recursive) {
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900209 ThreadRestrictions::AssertIOAllowed();
evanm@google.com874d1672008-10-31 08:54:04 +0900210 const char* path_str = path.value().c_str();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900211 stat_wrapper_t file_info;
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900212 int test = CallLstat(path_str, &file_info);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900213 if (test != 0) {
214 // The Windows version defines this condition as success.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900215 bool ret = (errno == ENOENT || errno == ENOTDIR);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900216 return ret;
217 }
218 if (!S_ISDIR(file_info.st_mode))
evanm@google.com874d1672008-10-31 08:54:04 +0900219 return (unlink(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900220 if (!recursive)
evanm@google.com874d1672008-10-31 08:54:04 +0900221 return (rmdir(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900222
223 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900224 std::stack<std::string> directories;
225 directories.push(path.value());
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900226 FileEnumerator traversal(path, true,
227 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
228 FileEnumerator::SHOW_SYM_LINKS);
thestig@chromium.org3217c822009-08-07 06:23:07 +0900229 for (FilePath current = traversal.Next(); success && !current.empty();
230 current = traversal.Next()) {
brettw@chromium.org56946722013-06-08 13:53:36 +0900231 if (traversal.GetInfo().IsDirectory())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900232 directories.push(current.value());
233 else
234 success = (unlink(current.value().c_str()) == 0);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900235 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900236
237 while (success && !directories.empty()) {
238 FilePath dir = FilePath(directories.top());
239 directories.pop();
240 success = (rmdir(dir.value().c_str()) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900241 }
242 return success;
243}
244
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900245bool ReplaceFile(const FilePath& from_path,
246 const FilePath& to_path,
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900247 File::Error* error) {
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900248 ThreadRestrictions::AssertIOAllowed();
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900249 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
250 return true;
251 if (error)
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900252 *error = File::OSErrorToFileError(errno);
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900253 return false;
phajdan.jr@chromium.orgd86bea02009-05-20 02:21:07 +0900254}
255
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900256bool CopyDirectory(const FilePath& from_path,
257 const FilePath& to_path,
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900258 bool recursive) {
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900259 ThreadRestrictions::AssertIOAllowed();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900260 // Some old callers of CopyDirectory want it to support wildcards.
261 // After some discussion, we decided to fix those callers.
262 // Break loudly here if anyone tries to do this.
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900263 // TODO(evanm): remove this once we're sure it's ok.
evanm@google.com874d1672008-10-31 08:54:04 +0900264 DCHECK(to_path.value().find('*') == std::string::npos);
265 DCHECK(from_path.value().find('*') == std::string::npos);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900266
267 char top_dir[PATH_MAX];
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900268 if (strlcpy(top_dir, from_path.value().c_str(),
269 arraysize(top_dir)) >= arraysize(top_dir)) {
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900270 return false;
271 }
272
thestig@chromium.org3217c822009-08-07 06:23:07 +0900273 // This function does not properly handle destinations within the source
274 FilePath real_to_path = to_path;
brettw@chromium.org10b64122013-07-12 02:36:07 +0900275 if (PathExists(real_to_path)) {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900276 real_to_path = MakeAbsoluteFilePath(real_to_path);
277 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900278 return false;
279 } else {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900280 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
281 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900282 return false;
283 }
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900284 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
285 if (real_from_path.empty())
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900286 return false;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900287 if (real_to_path.value().size() >= real_from_path.value().size() &&
288 real_to_path.value().compare(0, real_from_path.value().size(),
289 real_from_path.value()) == 0)
290 return false;
291
292 bool success = true;
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900293 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900294 if (recursive)
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900295 traverse_type |= FileEnumerator::DIRECTORIES;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900296 FileEnumerator traversal(from_path, recursive, traverse_type);
297
vandebo@chromium.org70cf3f12009-10-14 02:57:27 +0900298 // We have to mimic windows behavior here. |to_path| may not exist yet,
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900299 // start the loop with |to_path|.
brettw@chromium.org56946722013-06-08 13:53:36 +0900300 struct stat from_stat;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900301 FilePath current = from_path;
brettw@chromium.org56946722013-06-08 13:53:36 +0900302 if (stat(from_path.value().c_str(), &from_stat) < 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900303 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
304 << from_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900305 success = false;
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900306 }
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900307 struct stat to_path_stat;
308 FilePath from_path_base = from_path;
309 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
310 S_ISDIR(to_path_stat.st_mode)) {
311 // If the destination already exists and is a directory, then the
312 // top level of source needs to be copied.
313 from_path_base = from_path.DirName();
314 }
315
316 // The Windows version of this function assumes that non-recursive calls
317 // will always have a directory for from_path.
brettw@chromium.org56946722013-06-08 13:53:36 +0900318 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900319
thestig@chromium.org3217c822009-08-07 06:23:07 +0900320 while (success && !current.empty()) {
aedla@chromium.orgfef1a202013-01-30 20:38:02 +0900321 // current is the source path, including from_path, so append
322 // the suffix after from_path to to_path to create the target_path.
323 FilePath target_path(to_path);
324 if (from_path_base != current) {
325 if (!from_path_base.AppendRelativePath(current, &target_path)) {
326 success = false;
327 break;
328 }
phajdan.jr@chromium.orgecf50752009-01-14 03:57:46 +0900329 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900330
brettw@chromium.org56946722013-06-08 13:53:36 +0900331 if (S_ISDIR(from_stat.st_mode)) {
332 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
thestig@chromium.org3217c822009-08-07 06:23:07 +0900333 errno != EEXIST) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900334 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
335 << target_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900336 success = false;
337 }
brettw@chromium.org56946722013-06-08 13:53:36 +0900338 } else if (S_ISREG(from_stat.st_mode)) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900339 if (!CopyFile(current, target_path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900340 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
341 << target_path.value();
thestig@chromium.org3217c822009-08-07 06:23:07 +0900342 success = false;
343 }
344 } else {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900345 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
346 << current.value();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900347 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900348
thestig@chromium.org3217c822009-08-07 06:23:07 +0900349 current = traversal.Next();
brettw@chromium.org56946722013-06-08 13:53:36 +0900350 if (!current.empty())
351 from_stat = traversal.GetInfo().stat();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900352 }
353
thestig@chromium.org3217c822009-08-07 06:23:07 +0900354 return success;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900355}
356
brettw@chromium.org10b64122013-07-12 02:36:07 +0900357bool PathExists(const FilePath& path) {
358 ThreadRestrictions::AssertIOAllowed();
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +0900359#if defined(OS_ANDROID)
360 if (path.IsContentUri()) {
361 return ContentUriExists(path);
362 }
363#endif
brettw@chromium.org10b64122013-07-12 02:36:07 +0900364 return access(path.value().c_str(), F_OK) == 0;
365}
366
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900367bool PathIsWritable(const FilePath& path) {
368 ThreadRestrictions::AssertIOAllowed();
369 return access(path.value().c_str(), W_OK) == 0;
370}
371
372bool DirectoryExists(const FilePath& path) {
373 ThreadRestrictions::AssertIOAllowed();
374 stat_wrapper_t file_info;
375 if (CallStat(path.value().c_str(), &file_info) == 0)
376 return S_ISDIR(file_info.st_mode);
377 return false;
378}
379
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900380bool ReadFromFD(int fd, char* buffer, size_t bytes) {
381 size_t total_read = 0;
382 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900383 ssize_t bytes_read =
384 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
385 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900386 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900387 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900388 }
389 return total_read == bytes;
390}
391
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900392bool CreateSymbolicLink(const FilePath& target_path,
393 const FilePath& symlink_path) {
394 DCHECK(!symlink_path.empty());
395 DCHECK(!target_path.empty());
396 return ::symlink(target_path.value().c_str(),
397 symlink_path.value().c_str()) != -1;
398}
399
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900400bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900401 DCHECK(!symlink_path.empty());
402 DCHECK(target_path);
403 char buf[PATH_MAX];
404 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
405
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900406 if (count <= 0) {
407 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900408 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900409 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900410
411 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900412 return true;
413}
414
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900415bool GetPosixFilePermissions(const FilePath& path, int* mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900416 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900417 DCHECK(mode);
418
419 stat_wrapper_t file_info;
420 // Uses stat(), because on symbolic link, lstat() does not return valid
421 // permission bits in st_mode
422 if (CallStat(path.value().c_str(), &file_info) != 0)
423 return false;
424
425 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
426 return true;
427}
428
429bool SetPosixFilePermissions(const FilePath& path,
430 int mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900431 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900432 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
433
434 // Calls stat() so that we can preserve the higher bits like S_ISGID.
435 stat_wrapper_t stat_buf;
436 if (CallStat(path.value().c_str(), &stat_buf) != 0)
437 return false;
438
439 // Clears the existing permission bits, and adds the new ones.
440 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
441 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
442
443 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
444 return false;
445
446 return true;
447}
448
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900449#if !defined(OS_MACOSX)
450// This is implemented in file_util_mac.mm for Mac.
451bool GetTempDir(FilePath* path) {
452 const char* tmp = getenv("TMPDIR");
453 if (tmp) {
454 *path = FilePath(tmp);
455 } else {
456#if defined(OS_ANDROID)
457 return PathService::Get(base::DIR_CACHE, path);
458#else
459 *path = FilePath("/tmp");
460#endif
461 }
462 return true;
463}
464#endif // !defined(OS_MACOSX)
465
466#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
467// This is implemented in file_util_mac.mm and file_util_android.cc for those
468// platforms.
469bool GetShmemTempDir(bool executable, FilePath* path) {
470#if defined(OS_LINUX)
471 bool use_dev_shm = true;
472 if (executable) {
473 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
474 use_dev_shm = s_dev_shm_executable;
475 }
476 if (use_dev_shm) {
477 *path = FilePath("/dev/shm");
478 return true;
479 }
480#endif
481 return GetTempDir(path);
482}
483#endif // !defined(OS_MACOSX) && !defined(OS_ANDROID)
484
485#if !defined(OS_MACOSX)
486FilePath GetHomeDir() {
487#if defined(OS_CHROMEOS)
488 if (SysInfo::IsRunningOnChromeOS())
489 return FilePath("/home/chronos/user");
490#endif
491
492 const char* home_dir = getenv("HOME");
493 if (home_dir && home_dir[0])
494 return FilePath(home_dir);
495
496#if defined(OS_ANDROID)
497 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
498#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
499 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
500 ThreadRestrictions::AssertIOAllowed();
501
502 home_dir = g_get_home_dir();
503 if (home_dir && home_dir[0])
504 return FilePath(home_dir);
505#endif
506
507 FilePath rv;
508 if (GetTempDir(&rv))
509 return rv;
510
511 // Last resort.
512 return FilePath("/tmp");
513}
514#endif // !defined(OS_MACOSX)
515
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900516bool CreateTemporaryFile(FilePath* path) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900517 ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900518 FilePath directory;
519 if (!GetTempDir(&directory))
520 return false;
521 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900522 if (fd < 0)
523 return false;
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900524 close(fd);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900525 return true;
526}
527
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900528FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900529 FilePath directory;
brettw@chromium.org83c44c82013-12-03 03:55:49 +0900530 if (!GetShmemTempDir(executable, &directory))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900531 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900532
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900533 return CreateAndOpenTemporaryFileInDir(directory, path);
534}
535
536FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
537 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900538 if (fd < 0)
539 return NULL;
540
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900541 FILE* file = fdopen(fd, "a+");
542 if (!file)
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900543 close(fd);
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900544 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900545}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900546
547bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900548 ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900549 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900550 return ((fd >= 0) && !IGNORE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900551}
552
skerner@chromium.orge4432392010-05-01 02:00:09 +0900553static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
554 const FilePath::StringType& name_tmpl,
555 FilePath* new_dir) {
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900556 ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900557 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
558 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900559
560 FilePath sub_dir = base_dir.Append(name_tmpl);
561 std::string sub_dir_string = sub_dir.value();
562
563 // this should be OK since mkdtemp just replaces characters in place
564 char* buffer = const_cast<char*>(sub_dir_string.c_str());
565 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900566 if (!dtemp) {
567 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900568 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900569 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900570 *new_dir = FilePath(dtemp);
571 return true;
572}
573
574bool CreateTemporaryDirInDir(const FilePath& base_dir,
575 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900576 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900577 FilePath::StringType mkdtemp_template = prefix;
578 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
579 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
580}
581
erikkay@google.comcce83822008-12-24 05:20:10 +0900582bool CreateNewTempDirectory(const FilePath::StringType& prefix,
583 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900584 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900585 if (!GetTempDir(&tmpdir))
586 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900587
brettw@chromium.org735d11d2013-12-04 02:55:52 +0900588 return CreateTemporaryDirInDirImpl(tmpdir, TempFileName(), new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900589}
590
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900591bool CreateDirectoryAndGetError(const FilePath& full_path,
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900592 File::Error* error) {
brettw@chromium.org738669a2013-12-04 05:08:54 +0900593 ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900594 std::vector<FilePath> subpaths;
595
596 // Collect a list of all parent directories.
597 FilePath last_path = full_path;
598 subpaths.push_back(full_path);
599 for (FilePath path = full_path.DirName();
600 path.value() != last_path.value(); path = path.DirName()) {
601 subpaths.push_back(path);
602 last_path = path;
603 }
604
605 // Iterate through the parents and create the missing ones.
606 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
607 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900608 if (DirectoryExists(*i))
609 continue;
610 if (mkdir(i->value().c_str(), 0700) == 0)
611 continue;
612 // Mkdir failed, but it might have failed with EEXIST, or some other error
613 // due to the the directory appearing out of thin air. This can occur if
614 // two processes are trying to create the same file system tree at the same
615 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900616 int saved_errno = errno;
617 if (!DirectoryExists(*i)) {
618 if (error)
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900619 *error = File::OSErrorToFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900620 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900621 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900622 }
623 return true;
624}
625
brettw@chromium.org70684242013-12-05 03:22:49 +0900626bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
627 FilePath real_path_result;
628 if (!RealPath(path, &real_path_result))
629 return false;
630
631 // To be consistant with windows, fail if |real_path_result| is a
632 // directory.
633 stat_wrapper_t file_info;
634 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
635 S_ISDIR(file_info.st_mode))
636 return false;
637
638 *normalized_path = real_path_result;
639 return true;
640}
641
brettw@chromium.orga9154032013-12-05 05:56:49 +0900642// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
643// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
644bool IsLink(const FilePath& file_path) {
645 stat_wrapper_t st;
646 // If we can't lstat the file, it's safe to assume that the file won't at
647 // least be a 'followable' link.
648 if (CallLstat(file_path.value().c_str(), &st) != 0)
649 return false;
650
651 if (S_ISLNK(st.st_mode))
652 return true;
653 else
654 return false;
655}
656
rvargas@chromium.orgb005b382014-01-07 19:06:58 +0900657bool GetFileInfo(const FilePath& file_path, File::Info* results) {
brettw@chromium.orga9154032013-12-05 05:56:49 +0900658 stat_wrapper_t file_info;
659#if defined(OS_ANDROID)
660 if (file_path.IsContentUri()) {
661 int fd = OpenContentUriForRead(file_path);
662 if (fd < 0)
663 return false;
664 file_util::ScopedFD scoped_fd(&fd);
665 if (CallFstat(fd, &file_info) != 0)
666 return false;
667 } else {
668#endif // defined(OS_ANDROID)
669 if (CallStat(file_path.value().c_str(), &file_info) != 0)
670 return false;
671#if defined(OS_ANDROID)
672 }
673#endif // defined(OS_ANDROID)
674 results->is_directory = S_ISDIR(file_info.st_mode);
675 results->size = file_info.st_size;
676#if defined(OS_MACOSX)
677 results->last_modified = Time::FromTimeSpec(file_info.st_mtimespec);
678 results->last_accessed = Time::FromTimeSpec(file_info.st_atimespec);
679 results->creation_time = Time::FromTimeSpec(file_info.st_ctimespec);
680#elif defined(OS_ANDROID)
681 results->last_modified = Time::FromTimeT(file_info.st_mtime);
682 results->last_accessed = Time::FromTimeT(file_info.st_atime);
683 results->creation_time = Time::FromTimeT(file_info.st_ctime);
684#else
685 results->last_modified = Time::FromTimeSpec(file_info.st_mtim);
686 results->last_accessed = Time::FromTimeSpec(file_info.st_atim);
687 results->creation_time = Time::FromTimeSpec(file_info.st_ctim);
688#endif
689 return true;
690}
691
thakis@chromium.orgf01de7e2013-12-09 06:43:30 +0900692FILE* OpenFile(const FilePath& filename, const char* mode) {
693 ThreadRestrictions::AssertIOAllowed();
694 FILE* result = NULL;
695 do {
696 result = fopen(filename.value().c_str(), mode);
697 } while (!result && errno == EINTR);
698 return result;
699}
700
701int ReadFile(const FilePath& filename, char* data, int size) {
702 ThreadRestrictions::AssertIOAllowed();
703 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
704 if (fd < 0)
705 return -1;
706
707 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
708 if (int ret = IGNORE_EINTR(close(fd)) < 0)
709 return ret;
710 return bytes_read;
711}
712
brettw@chromium.org738669a2013-12-04 05:08:54 +0900713} // namespace base
714
715// -----------------------------------------------------------------------------
716
717namespace file_util {
718
719using base::stat_wrapper_t;
720using base::CallStat;
721using base::CallLstat;
722using base::CreateAndOpenFdForTemporaryFile;
723using base::DirectoryExists;
724using base::FileEnumerator;
725using base::FilePath;
726using base::MakeAbsoluteFilePath;
brettw@chromium.org738669a2013-12-04 05:08:54 +0900727using base::VerifySpecificPathControlledByUser;
728
jeremya@chromium.org05609662013-04-04 18:05:21 +0900729base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
730 const int kMaxAttempts = 20;
731 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900732 int uniquifier =
733 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900734 if (uniquifier < 0)
735 break;
736 base::FilePath test_path = (uniquifier == 0) ? path :
737 path.InsertBeforeExtensionASCII(
738 base::StringPrintf(" (%d)", uniquifier));
739 if (mkdir(test_path.value().c_str(), 0777) == 0)
740 return test_path;
741 else if (errno != EEXIST)
742 break;
743 }
744 return base::FilePath();
745}
746
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900747FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900748 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900749}
750
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900751int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900752 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900753 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900754 if (fd < 0)
755 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900756
evan@chromium.org36699862010-02-02 11:28:16 +0900757 int bytes_written = WriteFileDescriptor(fd, data, size);
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900758 if (int ret = IGNORE_EINTR(close(fd)) < 0)
evan@chromium.org36699862010-02-02 11:28:16 +0900759 return ret;
760 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900761}
762
763int WriteFileDescriptor(const int fd, const char* data, int size) {
764 // Allow for partial writes.
765 ssize_t bytes_written_total = 0;
766 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
767 bytes_written_total += bytes_written_partial) {
768 bytes_written_partial =
769 HANDLE_EINTR(write(fd, data + bytes_written_total,
770 size - bytes_written_total));
771 if (bytes_written_partial < 0)
772 return -1;
773 }
774
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900775 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900776}
777
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900778int AppendToFile(const FilePath& filename, const char* data, int size) {
779 base::ThreadRestrictions::AssertIOAllowed();
780 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
781 if (fd < 0)
782 return -1;
783
784 int bytes_written = WriteFileDescriptor(fd, data, size);
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900785 if (int ret = IGNORE_EINTR(close(fd)) < 0)
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900786 return ret;
787 return bytes_written;
788}
789
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900790// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900791bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900792 // getcwd can return ENOENT, which implies it checks against the disk.
793 base::ThreadRestrictions::AssertIOAllowed();
794
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900795 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900796 if (!getcwd(system_buffer, sizeof(system_buffer))) {
797 NOTREACHED();
798 return false;
799 }
800 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900801 return true;
802}
803
804// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900805bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900806 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900807 int ret = chdir(path.value().c_str());
808 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900809}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900810
skerner@google.com93449ef2011-09-22 23:47:18 +0900811bool VerifyPathControlledByUser(const FilePath& base,
812 const FilePath& path,
813 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900814 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900815 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900816 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
817 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900818 return false;
819 }
820
821 std::vector<FilePath::StringType> base_components;
822 std::vector<FilePath::StringType> path_components;
823
824 base.GetComponents(&base_components);
825 path.GetComponents(&path_components);
826
827 std::vector<FilePath::StringType>::const_iterator ib, ip;
828 for (ib = base_components.begin(), ip = path_components.begin();
829 ib != base_components.end(); ++ib, ++ip) {
830 // |base| must be a subpath of |path|, so all components should match.
831 // If these CHECKs fail, look at the test that base is a parent of
832 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900833 DCHECK(ip != path_components.end());
834 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900835 }
836
837 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900838 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900839 return false;
840
841 for (; ip != path_components.end(); ++ip) {
842 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900843 if (!VerifySpecificPathControlledByUser(
844 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900845 return false;
846 }
847 return true;
848}
849
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900850#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900851bool VerifyPathControlledByAdmin(const FilePath& path) {
852 const unsigned kRootUid = 0;
853 const FilePath kFileSystemRoot("/");
854
855 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900856 const char* const kAdminGroupNames[] = {
857 "admin",
858 "wheel"
859 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900860
861 // Reading the groups database may touch the file system.
862 base::ThreadRestrictions::AssertIOAllowed();
863
skerner@chromium.org80784142011-10-18 06:30:29 +0900864 std::set<gid_t> allowed_group_ids;
865 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
866 struct group *group_record = getgrnam(kAdminGroupNames[i]);
867 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900868 DPLOG(ERROR) << "Could not get the group ID of group \""
869 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900870 continue;
871 }
872
873 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900874 }
875
876 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900877 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900878}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900879#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900880
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900881int GetMaximumPathComponentLength(const FilePath& path) {
882 base::ThreadRestrictions::AssertIOAllowed();
883 return pathconf(path.value().c_str(), _PC_NAME_MAX);
884}
885
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900886} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900887
888namespace base {
889namespace internal {
890
891bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
892 ThreadRestrictions::AssertIOAllowed();
893 // Windows compatibility: if to_path exists, from_path and to_path
894 // must be the same type, either both files, or both directories.
895 stat_wrapper_t to_file_info;
896 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
897 stat_wrapper_t from_file_info;
898 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
899 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
900 return false;
901 } else {
902 return false;
903 }
904 }
905
906 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
907 return true;
908
909 if (!CopyDirectory(from_path, to_path, true))
910 return false;
911
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900912 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900913 return true;
914}
915
916#if !defined(OS_MACOSX)
917// Mac has its own implementation, this is for all other Posix systems.
918bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
919 ThreadRestrictions::AssertIOAllowed();
920 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
921 if (infile < 0)
922 return false;
923
924 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
925 if (outfile < 0) {
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900926 close(infile);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900927 return false;
928 }
929
930 const size_t kBufferSize = 32768;
931 std::vector<char> buffer(kBufferSize);
932 bool result = true;
933
934 while (result) {
935 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
936 if (bytes_read < 0) {
937 result = false;
938 break;
939 }
940 if (bytes_read == 0)
941 break;
942 // Allow for partial writes
943 ssize_t bytes_written_per_read = 0;
944 do {
945 ssize_t bytes_written_partial = HANDLE_EINTR(write(
946 outfile,
947 &buffer[bytes_written_per_read],
948 bytes_read - bytes_written_per_read));
949 if (bytes_written_partial < 0) {
950 result = false;
951 break;
952 }
953 bytes_written_per_read += bytes_written_partial;
954 } while (bytes_written_per_read < bytes_read);
955 }
956
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900957 if (IGNORE_EINTR(close(infile)) < 0)
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900958 result = false;
mark@chromium.orgfa5a0f92013-12-03 23:10:59 +0900959 if (IGNORE_EINTR(close(outfile)) < 0)
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900960 result = false;
961
962 return result;
963}
964#endif // !defined(OS_MACOSX)
965
966} // namespace internal
967} // namespace base