blob: 027337f32c6f90e217bc5e4cc62e2aefca5b7a49 [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
skerner@google.com93449ef2011-09-22 23:47:18 +0900153} // namespace
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900154
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900155FilePath MakeAbsoluteFilePath(const FilePath& input) {
156 ThreadRestrictions::AssertIOAllowed();
157 char full_path[PATH_MAX];
158 if (realpath(input.value().c_str(), full_path) == NULL)
159 return FilePath();
160 return FilePath(full_path);
mark@chromium.org13aa8aa2011-04-22 13:15:13 +0900161}
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900162
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900163// TODO(erikkay): The Windows version of this accepts paths like "foo/bar/*"
164// which works both with and without the recursive flag. I'm not sure we need
165// that functionality. If not, remove from file_util_win.cc, otherwise add it
166// here.
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900167bool DeleteFile(const FilePath& path, bool recursive) {
brettw@chromium.orge9f99482013-07-02 04:41:02 +0900168 ThreadRestrictions::AssertIOAllowed();
evanm@google.com874d1672008-10-31 08:54:04 +0900169 const char* path_str = path.value().c_str();
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900170 stat_wrapper_t file_info;
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900171 int test = CallLstat(path_str, &file_info);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900172 if (test != 0) {
173 // The Windows version defines this condition as success.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900174 bool ret = (errno == ENOENT || errno == ENOTDIR);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900175 return ret;
176 }
177 if (!S_ISDIR(file_info.st_mode))
evanm@google.com874d1672008-10-31 08:54:04 +0900178 return (unlink(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900179 if (!recursive)
evanm@google.com874d1672008-10-31 08:54:04 +0900180 return (rmdir(path_str) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900181
182 bool success = true;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900183 std::stack<std::string> directories;
184 directories.push(path.value());
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900185 FileEnumerator traversal(path, true,
186 FileEnumerator::FILES | FileEnumerator::DIRECTORIES |
187 FileEnumerator::SHOW_SYM_LINKS);
thestig@chromium.org3217c822009-08-07 06:23:07 +0900188 for (FilePath current = traversal.Next(); success && !current.empty();
189 current = traversal.Next()) {
brettw@chromium.org56946722013-06-08 13:53:36 +0900190 if (traversal.GetInfo().IsDirectory())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900191 directories.push(current.value());
192 else
193 success = (unlink(current.value().c_str()) == 0);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900194 }
thestig@chromium.org3217c822009-08-07 06:23:07 +0900195
196 while (success && !directories.empty()) {
197 FilePath dir = FilePath(directories.top());
198 directories.pop();
199 success = (rmdir(dir.value().c_str()) == 0);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900200 }
201 return success;
202}
203
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900204bool ReplaceFile(const FilePath& from_path,
205 const FilePath& to_path,
206 PlatformFileError* error) {
207 ThreadRestrictions::AssertIOAllowed();
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900208 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
209 return true;
210 if (error)
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900211 *error = ErrnoToPlatformFileError(errno);
dgrogan@chromium.org38fc56d2013-05-09 07:02:36 +0900212 return false;
phajdan.jr@chromium.orgd86bea02009-05-20 02:21:07 +0900213}
214
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900215bool CopyDirectory(const FilePath& from_path,
216 const FilePath& to_path,
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900217 bool recursive) {
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900218 ThreadRestrictions::AssertIOAllowed();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900219 // Some old callers of CopyDirectory want it to support wildcards.
220 // After some discussion, we decided to fix those callers.
221 // Break loudly here if anyone tries to do this.
dbeam@chromium.org85aa52a2013-05-08 14:46:20 +0900222 // TODO(evanm): remove this once we're sure it's ok.
evanm@google.com874d1672008-10-31 08:54:04 +0900223 DCHECK(to_path.value().find('*') == std::string::npos);
224 DCHECK(from_path.value().find('*') == std::string::npos);
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900225
226 char top_dir[PATH_MAX];
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900227 if (strlcpy(top_dir, from_path.value().c_str(),
228 arraysize(top_dir)) >= arraysize(top_dir)) {
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900229 return false;
230 }
231
thestig@chromium.org3217c822009-08-07 06:23:07 +0900232 // This function does not properly handle destinations within the source
233 FilePath real_to_path = to_path;
brettw@chromium.org10b64122013-07-12 02:36:07 +0900234 if (PathExists(real_to_path)) {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900235 real_to_path = MakeAbsoluteFilePath(real_to_path);
236 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900237 return false;
238 } else {
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900239 real_to_path = MakeAbsoluteFilePath(real_to_path.DirName());
240 if (real_to_path.empty())
thestig@chromium.org3217c822009-08-07 06:23:07 +0900241 return false;
242 }
brettw@chromium.org99b198e2013-04-12 14:17:15 +0900243 FilePath real_from_path = MakeAbsoluteFilePath(from_path);
244 if (real_from_path.empty())
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900245 return false;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900246 if (real_to_path.value().size() >= real_from_path.value().size() &&
247 real_to_path.value().compare(0, real_from_path.value().size(),
248 real_from_path.value()) == 0)
249 return false;
250
251 bool success = true;
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900252 int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900253 if (recursive)
haruki@chromium.org0e1a70b2012-08-12 10:57:23 +0900254 traverse_type |= FileEnumerator::DIRECTORIES;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900255 FileEnumerator traversal(from_path, recursive, traverse_type);
256
vandebo@chromium.org70cf3f12009-10-14 02:57:27 +0900257 // We have to mimic windows behavior here. |to_path| may not exist yet,
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900258 // start the loop with |to_path|.
brettw@chromium.org56946722013-06-08 13:53:36 +0900259 struct stat from_stat;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900260 FilePath current = from_path;
brettw@chromium.org56946722013-06-08 13:53:36 +0900261 if (stat(from_path.value().c_str(), &from_stat) < 0) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900262 DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
263 << from_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900264 success = false;
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900265 }
vandebo@chromium.orgc0cf77e2009-10-15 10:11:44 +0900266 struct stat to_path_stat;
267 FilePath from_path_base = from_path;
268 if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
269 S_ISDIR(to_path_stat.st_mode)) {
270 // If the destination already exists and is a directory, then the
271 // top level of source needs to be copied.
272 from_path_base = from_path.DirName();
273 }
274
275 // The Windows version of this function assumes that non-recursive calls
276 // will always have a directory for from_path.
brettw@chromium.org56946722013-06-08 13:53:36 +0900277 DCHECK(recursive || S_ISDIR(from_stat.st_mode));
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900278
thestig@chromium.org3217c822009-08-07 06:23:07 +0900279 while (success && !current.empty()) {
aedla@chromium.orgfef1a202013-01-30 20:38:02 +0900280 // current is the source path, including from_path, so append
281 // the suffix after from_path to to_path to create the target_path.
282 FilePath target_path(to_path);
283 if (from_path_base != current) {
284 if (!from_path_base.AppendRelativePath(current, &target_path)) {
285 success = false;
286 break;
287 }
phajdan.jr@chromium.orgecf50752009-01-14 03:57:46 +0900288 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900289
brettw@chromium.org56946722013-06-08 13:53:36 +0900290 if (S_ISDIR(from_stat.st_mode)) {
291 if (mkdir(target_path.value().c_str(), from_stat.st_mode & 01777) != 0 &&
thestig@chromium.org3217c822009-08-07 06:23:07 +0900292 errno != EEXIST) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900293 DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
294 << target_path.value() << " errno = " << errno;
thestig@chromium.org3217c822009-08-07 06:23:07 +0900295 success = false;
296 }
brettw@chromium.org56946722013-06-08 13:53:36 +0900297 } else if (S_ISREG(from_stat.st_mode)) {
thestig@chromium.org3217c822009-08-07 06:23:07 +0900298 if (!CopyFile(current, target_path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900299 DLOG(ERROR) << "CopyDirectory() couldn't create file: "
300 << target_path.value();
thestig@chromium.org3217c822009-08-07 06:23:07 +0900301 success = false;
302 }
303 } else {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900304 DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
305 << current.value();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900306 }
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900307
thestig@chromium.org3217c822009-08-07 06:23:07 +0900308 current = traversal.Next();
brettw@chromium.org56946722013-06-08 13:53:36 +0900309 if (!current.empty())
310 from_stat = traversal.GetInfo().stat();
evanm@google.com5c1d39b2008-09-19 04:15:54 +0900311 }
312
thestig@chromium.org3217c822009-08-07 06:23:07 +0900313 return success;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900314}
315
brettw@chromium.org10b64122013-07-12 02:36:07 +0900316bool PathExists(const FilePath& path) {
317 ThreadRestrictions::AssertIOAllowed();
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +0900318#if defined(OS_ANDROID)
319 if (path.IsContentUri()) {
320 return ContentUriExists(path);
321 }
322#endif
brettw@chromium.org10b64122013-07-12 02:36:07 +0900323 return access(path.value().c_str(), F_OK) == 0;
324}
325
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900326bool PathIsWritable(const FilePath& path) {
327 ThreadRestrictions::AssertIOAllowed();
328 return access(path.value().c_str(), W_OK) == 0;
329}
330
331bool DirectoryExists(const FilePath& path) {
332 ThreadRestrictions::AssertIOAllowed();
333 stat_wrapper_t file_info;
334 if (CallStat(path.value().c_str(), &file_info) == 0)
335 return S_ISDIR(file_info.st_mode);
336 return false;
337}
338
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900339bool ReadFromFD(int fd, char* buffer, size_t bytes) {
340 size_t total_read = 0;
341 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900342 ssize_t bytes_read =
343 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
344 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900345 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900346 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900347 }
348 return total_read == bytes;
349}
350
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900351bool CreateSymbolicLink(const FilePath& target_path,
352 const FilePath& symlink_path) {
353 DCHECK(!symlink_path.empty());
354 DCHECK(!target_path.empty());
355 return ::symlink(target_path.value().c_str(),
356 symlink_path.value().c_str()) != -1;
357}
358
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900359bool ReadSymbolicLink(const FilePath& symlink_path, FilePath* target_path) {
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900360 DCHECK(!symlink_path.empty());
361 DCHECK(target_path);
362 char buf[PATH_MAX];
363 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
364
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900365 if (count <= 0) {
366 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900367 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900368 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900369
370 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900371 return true;
372}
373
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900374bool GetPosixFilePermissions(const FilePath& path, int* mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900375 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900376 DCHECK(mode);
377
378 stat_wrapper_t file_info;
379 // Uses stat(), because on symbolic link, lstat() does not return valid
380 // permission bits in st_mode
381 if (CallStat(path.value().c_str(), &file_info) != 0)
382 return false;
383
384 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
385 return true;
386}
387
388bool SetPosixFilePermissions(const FilePath& path,
389 int mode) {
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900390 ThreadRestrictions::AssertIOAllowed();
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900391 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
392
393 // Calls stat() so that we can preserve the higher bits like S_ISGID.
394 stat_wrapper_t stat_buf;
395 if (CallStat(path.value().c_str(), &stat_buf) != 0)
396 return false;
397
398 // Clears the existing permission bits, and adds the new ones.
399 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
400 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
401
402 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
403 return false;
404
405 return true;
406}
407
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900408} // namespace base
409
410// -----------------------------------------------------------------------------
411
412namespace file_util {
413
414using base::stat_wrapper_t;
415using base::CallStat;
416using base::CallLstat;
417using base::DirectoryExists;
418using base::FileEnumerator;
419using base::FilePath;
420using base::MakeAbsoluteFilePath;
421using base::RealPath;
422using base::VerifySpecificPathControlledByUser;
423
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900424// Creates and opens a temporary file in |directory|, returning the
erikkay@chromium.org3a9a6422009-09-12 02:33:50 +0900425// file descriptor. |path| is set to the temporary file path.
426// This function does NOT unlink() the file.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900427int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900428 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900429 *path = directory.Append(base::TempFileName());
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900430 const std::string& tmpdir_string = path->value();
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900431 // this should be OK since mkstemp just replaces characters in place
432 char* buffer = const_cast<char*>(tmpdir_string.c_str());
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900433
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900434 return HANDLE_EINTR(mkstemp(buffer));
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900435}
436
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900437bool CreateTemporaryFile(FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900438 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900439 FilePath directory;
440 if (!GetTempDir(&directory))
441 return false;
442 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900443 if (fd < 0)
444 return false;
phajdan.jr@chromium.orgcad925c2011-04-12 15:51:22 +0900445 ignore_result(HANDLE_EINTR(close(fd)));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900446 return true;
447}
448
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900449FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900450 FilePath directory;
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900451 if (!GetShmemTempDir(&directory, executable))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900452 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900453
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900454 return CreateAndOpenTemporaryFileInDir(directory, path);
455}
456
457FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
458 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900459 if (fd < 0)
460 return NULL;
461
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900462 FILE* file = fdopen(fd, "a+");
463 if (!file)
464 ignore_result(HANDLE_EINTR(close(fd)));
465 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900466}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900467
468bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900469 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900470 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900471 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900472}
473
skerner@chromium.orge4432392010-05-01 02:00:09 +0900474static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
475 const FilePath::StringType& name_tmpl,
476 FilePath* new_dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900477 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900478 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
479 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900480
481 FilePath sub_dir = base_dir.Append(name_tmpl);
482 std::string sub_dir_string = sub_dir.value();
483
484 // this should be OK since mkdtemp just replaces characters in place
485 char* buffer = const_cast<char*>(sub_dir_string.c_str());
486 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900487 if (!dtemp) {
488 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900489 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900490 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900491 *new_dir = FilePath(dtemp);
492 return true;
493}
494
495bool CreateTemporaryDirInDir(const FilePath& base_dir,
496 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900497 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900498 FilePath::StringType mkdtemp_template = prefix;
499 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
500 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
501}
502
erikkay@google.comcce83822008-12-24 05:20:10 +0900503bool CreateNewTempDirectory(const FilePath::StringType& prefix,
504 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900505 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900506 if (!GetTempDir(&tmpdir))
507 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900508
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900509 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
510 new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900511}
512
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900513bool CreateDirectoryAndGetError(const FilePath& full_path,
514 base::PlatformFileError* error) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900515 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900516 std::vector<FilePath> subpaths;
517
518 // Collect a list of all parent directories.
519 FilePath last_path = full_path;
520 subpaths.push_back(full_path);
521 for (FilePath path = full_path.DirName();
522 path.value() != last_path.value(); path = path.DirName()) {
523 subpaths.push_back(path);
524 last_path = path;
525 }
526
527 // Iterate through the parents and create the missing ones.
528 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
529 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900530 if (DirectoryExists(*i))
531 continue;
532 if (mkdir(i->value().c_str(), 0700) == 0)
533 continue;
534 // Mkdir failed, but it might have failed with EEXIST, or some other error
535 // due to the the directory appearing out of thin air. This can occur if
536 // two processes are trying to create the same file system tree at the same
537 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900538 int saved_errno = errno;
539 if (!DirectoryExists(*i)) {
540 if (error)
541 *error = base::ErrnoToPlatformFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900542 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900543 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900544 }
545 return true;
546}
547
jeremya@chromium.org05609662013-04-04 18:05:21 +0900548base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
549 const int kMaxAttempts = 20;
550 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900551 int uniquifier =
552 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900553 if (uniquifier < 0)
554 break;
555 base::FilePath test_path = (uniquifier == 0) ? path :
556 path.InsertBeforeExtensionASCII(
557 base::StringPrintf(" (%d)", uniquifier));
558 if (mkdir(test_path.value().c_str(), 0777) == 0)
559 return test_path;
560 else if (errno != EEXIST)
561 break;
562 }
563 return base::FilePath();
564}
565
rkc@chromium.orga40af282011-06-01 08:10:06 +0900566// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
567// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
568bool IsLink(const FilePath& file_path) {
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900569 stat_wrapper_t st;
rkc@chromium.orga40af282011-06-01 08:10:06 +0900570 // If we can't lstat the file, it's safe to assume that the file won't at
571 // least be a 'followable' link.
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900572 if (CallLstat(file_path.value().c_str(), &st) != 0)
rkc@chromium.orga40af282011-06-01 08:10:06 +0900573 return false;
574
575 if (S_ISLNK(st.st_mode))
576 return true;
577 else
578 return false;
579}
580
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900581bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900582 stat_wrapper_t file_info;
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +0900583#if defined(OS_ANDROID)
584 if (file_path.IsContentUri()) {
585 int fd = OpenContentUriForRead(file_path);
586 if (fd < 0)
587 return false;
588 ScopedFD scoped_fd(&fd);
589 if (base::CallFstat(fd, &file_info) != 0)
590 return false;
591 } else {
592#endif // defined(OS_ANDROID)
593 if (CallStat(file_path.value().c_str(), &file_info) != 0)
594 return false;
595#if defined(OS_ANDROID)
596 }
597#endif // defined(OS_ANDROID)
darin@google.com7f479f22008-09-26 10:04:08 +0900598 results->is_directory = S_ISDIR(file_info.st_mode);
599 results->size = file_info.st_size;
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900600#if defined(OS_MACOSX)
601 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
602 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
603 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
604#elif defined(OS_ANDROID)
brettw@chromium.orgdbc9b5a2009-07-25 01:13:53 +0900605 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900606 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
607 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900608#else
609 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
610 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
611 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
612#endif
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900613 return true;
614}
615
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900616bool GetInode(const FilePath& path, ino_t* inode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900617 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900618 struct stat buffer;
619 int result = stat(path.value().c_str(), &buffer);
620 if (result < 0)
621 return false;
622
623 *inode = buffer.st_ino;
624 return true;
625}
626
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900627FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900628 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900629}
630
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900631FILE* OpenFile(const FilePath& filename, const char* mode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900632 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900633 FILE* result = NULL;
634 do {
635 result = fopen(filename.value().c_str(), mode);
636 } while (!result && errno == EINTR);
637 return result;
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900638}
639
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900640int ReadFile(const FilePath& filename, char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900641 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900642 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900643 if (fd < 0)
644 return -1;
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900645
evan@chromium.org36699862010-02-02 11:28:16 +0900646 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
647 if (int ret = HANDLE_EINTR(close(fd)) < 0)
648 return ret;
649 return bytes_read;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900650}
651
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900652int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900653 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900654 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900655 if (fd < 0)
656 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900657
evan@chromium.org36699862010-02-02 11:28:16 +0900658 int bytes_written = WriteFileDescriptor(fd, data, size);
659 if (int ret = HANDLE_EINTR(close(fd)) < 0)
660 return ret;
661 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900662}
663
664int WriteFileDescriptor(const int fd, const char* data, int size) {
665 // Allow for partial writes.
666 ssize_t bytes_written_total = 0;
667 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
668 bytes_written_total += bytes_written_partial) {
669 bytes_written_partial =
670 HANDLE_EINTR(write(fd, data + bytes_written_total,
671 size - bytes_written_total));
672 if (bytes_written_partial < 0)
673 return -1;
674 }
675
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900676 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900677}
678
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900679int AppendToFile(const FilePath& filename, const char* data, int size) {
680 base::ThreadRestrictions::AssertIOAllowed();
681 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
682 if (fd < 0)
683 return -1;
684
685 int bytes_written = WriteFileDescriptor(fd, data, size);
686 if (int ret = HANDLE_EINTR(close(fd)) < 0)
687 return ret;
688 return bytes_written;
689}
690
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900691// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900692bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900693 // getcwd can return ENOENT, which implies it checks against the disk.
694 base::ThreadRestrictions::AssertIOAllowed();
695
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900696 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900697 if (!getcwd(system_buffer, sizeof(system_buffer))) {
698 NOTREACHED();
699 return false;
700 }
701 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900702 return true;
703}
704
705// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900706bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900707 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900708 int ret = chdir(path.value().c_str());
709 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900710}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900711
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900712bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
713 FilePath real_path_result;
714 if (!RealPath(path, &real_path_result))
skerner@chromium.org559baa92010-05-13 00:13:57 +0900715 return false;
716
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900717 // To be consistant with windows, fail if |real_path_result| is a
718 // directory.
719 stat_wrapper_t file_info;
720 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
721 S_ISDIR(file_info.st_mode))
722 return false;
723
724 *normalized_path = real_path_result;
skerner@chromium.org559baa92010-05-13 00:13:57 +0900725 return true;
726}
727
evan@chromium.orgb9575332010-04-22 06:11:36 +0900728#if !defined(OS_MACOSX)
729bool GetTempDir(FilePath* path) {
730 const char* tmp = getenv("TMPDIR");
731 if (tmp)
732 *path = FilePath(tmp);
733 else
michaelbai@google.com2251c622011-06-22 07:34:50 +0900734#if defined(OS_ANDROID)
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +0900735 return PathService::Get(base::DIR_CACHE, path);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900736#else
evan@chromium.orgb9575332010-04-22 06:11:36 +0900737 *path = FilePath("/tmp");
michaelbai@google.com2251c622011-06-22 07:34:50 +0900738#endif
evan@chromium.orgb9575332010-04-22 06:11:36 +0900739 return true;
740}
741
michaelbai@google.com2251c622011-06-22 07:34:50 +0900742#if !defined(OS_ANDROID)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900743
robert.nagy@gmail.comea54e462011-10-25 07:05:27 +0900744#if defined(OS_LINUX)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900745// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
746// This depends on the mount options used for /dev/shm, which vary among
747// different Linux distributions and possibly local configuration. It also
748// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
749// but its kernel allows mprotect with PROT_EXEC anyway.
750
751namespace {
752
753bool DetermineDevShmExecutable() {
754 bool result = false;
755 FilePath path;
756 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
757 if (fd >= 0) {
758 ScopedFD shm_fd_closer(&fd);
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900759 DeleteFile(path, false);
scr@chromium.orge7506992011-12-23 07:31:44 +0900760 long sysconf_result = sysconf(_SC_PAGESIZE);
761 CHECK_GE(sysconf_result, 0);
762 size_t pagesize = static_cast<size_t>(sysconf_result);
763 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900764 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
765 if (mapping != MAP_FAILED) {
766 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
767 result = true;
768 munmap(mapping, pagesize);
769 }
770 }
771 return result;
evan@chromium.orgb9575332010-04-22 06:11:36 +0900772}
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900773
774}; // namespace
775#endif // defined(OS_LINUX)
776
777bool GetShmemTempDir(FilePath* path, bool executable) {
778#if defined(OS_LINUX)
779 bool use_dev_shm = true;
780 if (executable) {
781 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
782 use_dev_shm = s_dev_shm_executable;
783 }
784 if (use_dev_shm) {
785 *path = FilePath("/dev/shm");
786 return true;
787 }
michaelbai@google.com2251c622011-06-22 07:34:50 +0900788#endif
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900789 return GetTempDir(path);
790}
791#endif // !defined(OS_ANDROID)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900792
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900793FilePath GetHomeDir() {
haruki@chromium.org712ff262012-08-06 18:14:44 +0900794#if defined(OS_CHROMEOS)
stevenjb@chromium.org861313b2013-09-28 04:28:24 +0900795 if (base::SysInfo::IsRunningOnChromeOS())
haruki@chromium.org712ff262012-08-06 18:14:44 +0900796 return FilePath("/home/chronos/user");
797#endif
798
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900799 const char* home_dir = getenv("HOME");
800 if (home_dir && home_dir[0])
801 return FilePath(home_dir);
802
michaelbai@google.com2251c622011-06-22 07:34:50 +0900803#if defined(OS_ANDROID)
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900804 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
spang@chromium.org8d0fa9a2013-11-20 14:33:46 +0900805#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900806 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
807 base::ThreadRestrictions::AssertIOAllowed();
808
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900809 home_dir = g_get_home_dir();
810 if (home_dir && home_dir[0])
811 return FilePath(home_dir);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900812#endif
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900813
814 FilePath rv;
815 if (file_util::GetTempDir(&rv))
816 return rv;
817
818 // Last resort.
819 return FilePath("/tmp");
820}
thorogood@chromium.orge77009d2012-07-23 17:22:44 +0900821#endif // !defined(OS_MACOSX)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900822
skerner@google.com93449ef2011-09-22 23:47:18 +0900823bool VerifyPathControlledByUser(const FilePath& base,
824 const FilePath& path,
825 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900826 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900827 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900828 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
829 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900830 return false;
831 }
832
833 std::vector<FilePath::StringType> base_components;
834 std::vector<FilePath::StringType> path_components;
835
836 base.GetComponents(&base_components);
837 path.GetComponents(&path_components);
838
839 std::vector<FilePath::StringType>::const_iterator ib, ip;
840 for (ib = base_components.begin(), ip = path_components.begin();
841 ib != base_components.end(); ++ib, ++ip) {
842 // |base| must be a subpath of |path|, so all components should match.
843 // If these CHECKs fail, look at the test that base is a parent of
844 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900845 DCHECK(ip != path_components.end());
846 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900847 }
848
849 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900850 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900851 return false;
852
853 for (; ip != path_components.end(); ++ip) {
854 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900855 if (!VerifySpecificPathControlledByUser(
856 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900857 return false;
858 }
859 return true;
860}
861
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900862#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900863bool VerifyPathControlledByAdmin(const FilePath& path) {
864 const unsigned kRootUid = 0;
865 const FilePath kFileSystemRoot("/");
866
867 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900868 const char* const kAdminGroupNames[] = {
869 "admin",
870 "wheel"
871 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900872
873 // Reading the groups database may touch the file system.
874 base::ThreadRestrictions::AssertIOAllowed();
875
skerner@chromium.org80784142011-10-18 06:30:29 +0900876 std::set<gid_t> allowed_group_ids;
877 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
878 struct group *group_record = getgrnam(kAdminGroupNames[i]);
879 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900880 DPLOG(ERROR) << "Could not get the group ID of group \""
881 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900882 continue;
883 }
884
885 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900886 }
887
888 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900889 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900890}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900891#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900892
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900893int GetMaximumPathComponentLength(const FilePath& path) {
894 base::ThreadRestrictions::AssertIOAllowed();
895 return pathconf(path.value().c_str(), _PC_NAME_MAX);
896}
897
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900898} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900899
900namespace base {
901namespace internal {
902
903bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
904 ThreadRestrictions::AssertIOAllowed();
905 // Windows compatibility: if to_path exists, from_path and to_path
906 // must be the same type, either both files, or both directories.
907 stat_wrapper_t to_file_info;
908 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
909 stat_wrapper_t from_file_info;
910 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
911 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
912 return false;
913 } else {
914 return false;
915 }
916 }
917
918 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
919 return true;
920
921 if (!CopyDirectory(from_path, to_path, true))
922 return false;
923
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900924 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900925 return true;
926}
927
928#if !defined(OS_MACOSX)
929// Mac has its own implementation, this is for all other Posix systems.
930bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
931 ThreadRestrictions::AssertIOAllowed();
932 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
933 if (infile < 0)
934 return false;
935
936 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
937 if (outfile < 0) {
938 ignore_result(HANDLE_EINTR(close(infile)));
939 return false;
940 }
941
942 const size_t kBufferSize = 32768;
943 std::vector<char> buffer(kBufferSize);
944 bool result = true;
945
946 while (result) {
947 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
948 if (bytes_read < 0) {
949 result = false;
950 break;
951 }
952 if (bytes_read == 0)
953 break;
954 // Allow for partial writes
955 ssize_t bytes_written_per_read = 0;
956 do {
957 ssize_t bytes_written_partial = HANDLE_EINTR(write(
958 outfile,
959 &buffer[bytes_written_per_read],
960 bytes_read - bytes_written_per_read));
961 if (bytes_written_partial < 0) {
962 result = false;
963 break;
964 }
965 bytes_written_per_read += bytes_written_partial;
966 } while (bytes_written_per_read < bytes_read);
967 }
968
969 if (HANDLE_EINTR(close(infile)) < 0)
970 result = false;
971 if (HANDLE_EINTR(close(outfile)) < 0)
972 result = false;
973
974 return result;
975}
976#endif // !defined(OS_MACOSX)
977
978} // namespace internal
979} // namespace base