blob: 721f858a33ab6b3d8391718ce3e0cd83c9b79cf5 [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
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900339} // namespace base
340
341// -----------------------------------------------------------------------------
342
343namespace file_util {
344
345using base::stat_wrapper_t;
346using base::CallStat;
347using base::CallLstat;
brettw@chromium.org5a112e72013-07-16 05:18:09 +0900348using base::DirectoryExists;
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900349using base::FileEnumerator;
350using base::FilePath;
351using base::MakeAbsoluteFilePath;
352using base::RealPath;
353using base::VerifySpecificPathControlledByUser;
354
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900355bool ReadFromFD(int fd, char* buffer, size_t bytes) {
356 size_t total_read = 0;
357 while (total_read < bytes) {
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900358 ssize_t bytes_read =
359 HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read));
360 if (bytes_read <= 0)
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900361 break;
agl@chromium.orgd263ad72009-05-02 06:37:31 +0900362 total_read += bytes_read;
phajdan.jr@chromium.org23725932009-04-23 21:38:08 +0900363 }
364 return total_read == bytes;
365}
366
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900367bool CreateSymbolicLink(const FilePath& target_path,
368 const FilePath& symlink_path) {
369 DCHECK(!symlink_path.empty());
370 DCHECK(!target_path.empty());
371 return ::symlink(target_path.value().c_str(),
372 symlink_path.value().c_str()) != -1;
373}
374
375bool ReadSymbolicLink(const FilePath& symlink_path,
376 FilePath* target_path) {
377 DCHECK(!symlink_path.empty());
378 DCHECK(target_path);
379 char buf[PATH_MAX];
380 ssize_t count = ::readlink(symlink_path.value().c_str(), buf, arraysize(buf));
381
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900382 if (count <= 0) {
383 target_path->clear();
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900384 return false;
gspencer@chromium.org3c6690c2010-12-04 02:37:54 +0900385 }
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900386
387 *target_path = FilePath(FilePath::StringType(buf, count));
gspencer@chromium.org4dcc02c2010-11-30 09:43:37 +0900388 return true;
389}
390
yoshiki@chromium.org670a38f2012-07-11 10:24:02 +0900391bool GetPosixFilePermissions(const FilePath& path, int* mode) {
392 base::ThreadRestrictions::AssertIOAllowed();
393 DCHECK(mode);
394
395 stat_wrapper_t file_info;
396 // Uses stat(), because on symbolic link, lstat() does not return valid
397 // permission bits in st_mode
398 if (CallStat(path.value().c_str(), &file_info) != 0)
399 return false;
400
401 *mode = file_info.st_mode & FILE_PERMISSION_MASK;
402 return true;
403}
404
405bool SetPosixFilePermissions(const FilePath& path,
406 int mode) {
407 base::ThreadRestrictions::AssertIOAllowed();
408 DCHECK((mode & ~FILE_PERMISSION_MASK) == 0);
409
410 // Calls stat() so that we can preserve the higher bits like S_ISGID.
411 stat_wrapper_t stat_buf;
412 if (CallStat(path.value().c_str(), &stat_buf) != 0)
413 return false;
414
415 // Clears the existing permission bits, and adds the new ones.
416 mode_t updated_mode_bits = stat_buf.st_mode & ~FILE_PERMISSION_MASK;
417 updated_mode_bits |= mode & FILE_PERMISSION_MASK;
418
419 if (HANDLE_EINTR(chmod(path.value().c_str(), updated_mode_bits)) != 0)
420 return false;
421
422 return true;
423}
424
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900425// Creates and opens a temporary file in |directory|, returning the
erikkay@chromium.org3a9a6422009-09-12 02:33:50 +0900426// file descriptor. |path| is set to the temporary file path.
427// This function does NOT unlink() the file.
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900428int CreateAndOpenFdForTemporaryFile(FilePath directory, FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900429 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkstemp().
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900430 *path = directory.Append(base::TempFileName());
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900431 const std::string& tmpdir_string = path->value();
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900432 // this should be OK since mkstemp just replaces characters in place
433 char* buffer = const_cast<char*>(tmpdir_string.c_str());
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900434
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900435 return HANDLE_EINTR(mkstemp(buffer));
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900436}
437
erikkay@chromium.org18f0dde2009-08-19 01:07:55 +0900438bool CreateTemporaryFile(FilePath* path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900439 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900440 FilePath directory;
441 if (!GetTempDir(&directory))
442 return false;
443 int fd = CreateAndOpenFdForTemporaryFile(directory, path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900444 if (fd < 0)
445 return false;
phajdan.jr@chromium.orgcad925c2011-04-12 15:51:22 +0900446 ignore_result(HANDLE_EINTR(close(fd)));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900447 return true;
448}
449
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900450FILE* CreateAndOpenTemporaryShmemFile(FilePath* path, bool executable) {
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900451 FilePath directory;
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900452 if (!GetShmemTempDir(&directory, executable))
evan@chromium.org2abe0b42010-06-11 07:56:23 +0900453 return NULL;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900454
phajdan.jr@chromium.org8139fe12009-04-28 15:50:36 +0900455 return CreateAndOpenTemporaryFileInDir(directory, path);
456}
457
458FILE* CreateAndOpenTemporaryFileInDir(const FilePath& dir, FilePath* path) {
459 int fd = CreateAndOpenFdForTemporaryFile(dir, path);
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900460 if (fd < 0)
461 return NULL;
462
phajdan.jr@chromium.orgae25ba22011-04-19 04:05:53 +0900463 FILE* file = fdopen(fd, "a+");
464 if (!file)
465 ignore_result(HANDLE_EINTR(close(fd)));
466 return file;
jrg@chromium.orgd505c3a2009-02-04 09:58:39 +0900467}
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900468
469bool CreateTemporaryFileInDir(const FilePath& dir, FilePath* temp_file) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900470 base::ThreadRestrictions::AssertIOAllowed(); // For call to close().
dumi@chromium.org13e715d2009-09-12 05:06:27 +0900471 int fd = CreateAndOpenFdForTemporaryFile(dir, temp_file);
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900472 return ((fd >= 0) && !HANDLE_EINTR(close(fd)));
jcampan@chromium.orgbf29e602008-10-11 03:50:32 +0900473}
474
skerner@chromium.orge4432392010-05-01 02:00:09 +0900475static bool CreateTemporaryDirInDirImpl(const FilePath& base_dir,
476 const FilePath::StringType& name_tmpl,
477 FilePath* new_dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900478 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdtemp().
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900479 DCHECK(name_tmpl.find("XXXXXX") != FilePath::StringType::npos)
480 << "Directory name template must contain \"XXXXXX\".";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900481
482 FilePath sub_dir = base_dir.Append(name_tmpl);
483 std::string sub_dir_string = sub_dir.value();
484
485 // this should be OK since mkdtemp just replaces characters in place
486 char* buffer = const_cast<char*>(sub_dir_string.c_str());
487 char* dtemp = mkdtemp(buffer);
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900488 if (!dtemp) {
489 DPLOG(ERROR) << "mkdtemp";
skerner@chromium.orge4432392010-05-01 02:00:09 +0900490 return false;
evan@chromium.org01ec22c2010-07-29 06:00:51 +0900491 }
skerner@chromium.orge4432392010-05-01 02:00:09 +0900492 *new_dir = FilePath(dtemp);
493 return true;
494}
495
496bool CreateTemporaryDirInDir(const FilePath& base_dir,
497 const FilePath::StringType& prefix,
skerner@chromium.orgbd112ab2010-06-30 16:19:11 +0900498 FilePath* new_dir) {
skerner@chromium.orge4432392010-05-01 02:00:09 +0900499 FilePath::StringType mkdtemp_template = prefix;
500 mkdtemp_template.append(FILE_PATH_LITERAL("XXXXXX"));
501 return CreateTemporaryDirInDirImpl(base_dir, mkdtemp_template, new_dir);
502}
503
erikkay@google.comcce83822008-12-24 05:20:10 +0900504bool CreateNewTempDirectory(const FilePath::StringType& prefix,
505 FilePath* new_temp_path) {
estade@chromium.orgf474a1b2008-11-11 09:01:38 +0900506 FilePath tmpdir;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900507 if (!GetTempDir(&tmpdir))
508 return false;
skerner@chromium.orge4432392010-05-01 02:00:09 +0900509
brettw@chromium.org0878fea2013-07-02 08:07:36 +0900510 return CreateTemporaryDirInDirImpl(tmpdir, base::TempFileName(),
511 new_temp_path);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900512}
513
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900514bool CreateDirectoryAndGetError(const FilePath& full_path,
515 base::PlatformFileError* error) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900516 base::ThreadRestrictions::AssertIOAllowed(); // For call to mkdir().
evanm@google.com874d1672008-10-31 08:54:04 +0900517 std::vector<FilePath> subpaths;
518
519 // Collect a list of all parent directories.
520 FilePath last_path = full_path;
521 subpaths.push_back(full_path);
522 for (FilePath path = full_path.DirName();
523 path.value() != last_path.value(); path = path.DirName()) {
524 subpaths.push_back(path);
525 last_path = path;
526 }
527
528 // Iterate through the parents and create the missing ones.
529 for (std::vector<FilePath>::reverse_iterator i = subpaths.rbegin();
530 i != subpaths.rend(); ++i) {
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900531 if (DirectoryExists(*i))
532 continue;
533 if (mkdir(i->value().c_str(), 0700) == 0)
534 continue;
535 // Mkdir failed, but it might have failed with EEXIST, or some other error
536 // due to the the directory appearing out of thin air. This can occur if
537 // two processes are trying to create the same file system tree at the same
538 // time. Check to see if it exists and make sure it is a directory.
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900539 int saved_errno = errno;
540 if (!DirectoryExists(*i)) {
541 if (error)
542 *error = base::ErrnoToPlatformFileError(saved_errno);
thestig@chromium.org2e7eebc2010-03-18 06:39:42 +0900543 return false;
dgrogan@chromium.orgf7728132013-06-11 12:50:25 +0900544 }
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900545 }
546 return true;
547}
548
jeremya@chromium.org05609662013-04-04 18:05:21 +0900549base::FilePath MakeUniqueDirectory(const base::FilePath& path) {
550 const int kMaxAttempts = 20;
551 for (int attempts = 0; attempts < kMaxAttempts; attempts++) {
dcheng@chromium.org8164c2c2013-04-09 17:46:45 +0900552 int uniquifier =
553 GetUniquePathNumber(path, base::FilePath::StringType());
jeremya@chromium.org05609662013-04-04 18:05:21 +0900554 if (uniquifier < 0)
555 break;
556 base::FilePath test_path = (uniquifier == 0) ? path :
557 path.InsertBeforeExtensionASCII(
558 base::StringPrintf(" (%d)", uniquifier));
559 if (mkdir(test_path.value().c_str(), 0777) == 0)
560 return test_path;
561 else if (errno != EEXIST)
562 break;
563 }
564 return base::FilePath();
565}
566
rkc@chromium.orga40af282011-06-01 08:10:06 +0900567// TODO(rkc): Refactor GetFileInfo and FileEnumerator to handle symlinks
568// correctly. http://code.google.com/p/chromium-os/issues/detail?id=15948
569bool IsLink(const FilePath& file_path) {
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900570 stat_wrapper_t st;
rkc@chromium.orga40af282011-06-01 08:10:06 +0900571 // If we can't lstat the file, it's safe to assume that the file won't at
572 // least be a 'followable' link.
yoshiki@chromium.org45cbd632012-06-30 14:26:59 +0900573 if (CallLstat(file_path.value().c_str(), &st) != 0)
rkc@chromium.orga40af282011-06-01 08:10:06 +0900574 return false;
575
576 if (S_ISLNK(st.st_mode))
577 return true;
578 else
579 return false;
580}
581
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900582bool GetFileInfo(const FilePath& file_path, base::PlatformFileInfo* results) {
benl@chromium.org6b6b2162009-09-08 01:39:46 +0900583 stat_wrapper_t file_info;
qinmin@chromium.org8abcc0c2013-11-20 16:04:55 +0900584#if defined(OS_ANDROID)
585 if (file_path.IsContentUri()) {
586 int fd = OpenContentUriForRead(file_path);
587 if (fd < 0)
588 return false;
589 ScopedFD scoped_fd(&fd);
590 if (base::CallFstat(fd, &file_info) != 0)
591 return false;
592 } else {
593#endif // defined(OS_ANDROID)
594 if (CallStat(file_path.value().c_str(), &file_info) != 0)
595 return false;
596#if defined(OS_ANDROID)
597 }
598#endif // defined(OS_ANDROID)
darin@google.com7f479f22008-09-26 10:04:08 +0900599 results->is_directory = S_ISDIR(file_info.st_mode);
600 results->size = file_info.st_size;
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900601#if defined(OS_MACOSX)
602 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtimespec);
603 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atimespec);
604 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctimespec);
605#elif defined(OS_ANDROID)
brettw@chromium.orgdbc9b5a2009-07-25 01:13:53 +0900606 results->last_modified = base::Time::FromTimeT(file_info.st_mtime);
dumi@chromium.org97ae2612010-09-03 11:28:37 +0900607 results->last_accessed = base::Time::FromTimeT(file_info.st_atime);
608 results->creation_time = base::Time::FromTimeT(file_info.st_ctime);
apavlov@chromium.org118a9012013-06-10 18:41:35 +0900609#else
610 results->last_modified = base::Time::FromTimeSpec(file_info.st_mtim);
611 results->last_accessed = base::Time::FromTimeSpec(file_info.st_atim);
612 results->creation_time = base::Time::FromTimeSpec(file_info.st_ctim);
613#endif
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900614 return true;
615}
616
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900617bool GetInode(const FilePath& path, ino_t* inode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900618 base::ThreadRestrictions::AssertIOAllowed(); // For call to stat().
phajdan.jr@chromium.org99aec932009-05-15 02:49:23 +0900619 struct stat buffer;
620 int result = stat(path.value().c_str(), &buffer);
621 if (result < 0)
622 return false;
623
624 *inode = buffer.st_ino;
625 return true;
626}
627
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900628FILE* OpenFile(const std::string& filename, const char* mode) {
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900629 return OpenFile(FilePath(filename), mode);
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900630}
631
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900632FILE* OpenFile(const FilePath& filename, const char* mode) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900633 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900634 FILE* result = NULL;
635 do {
636 result = fopen(filename.value().c_str(), mode);
637 } while (!result && errno == EINTR);
638 return result;
mark@chromium.orgd1bafc62008-10-02 02:40:13 +0900639}
640
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900641int ReadFile(const FilePath& filename, char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900642 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900643 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_RDONLY));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900644 if (fd < 0)
645 return -1;
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900646
evan@chromium.org36699862010-02-02 11:28:16 +0900647 ssize_t bytes_read = HANDLE_EINTR(read(fd, data, size));
648 if (int ret = HANDLE_EINTR(close(fd)) < 0)
649 return ret;
650 return bytes_read;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900651}
652
estade@chromium.org9d32ed82009-01-28 14:47:15 +0900653int WriteFile(const FilePath& filename, const char* data, int size) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900654 base::ThreadRestrictions::AssertIOAllowed();
phajdan.jr@chromium.orgad504532011-04-12 15:07:25 +0900655 int fd = HANDLE_EINTR(creat(filename.value().c_str(), 0666));
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900656 if (fd < 0)
657 return -1;
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900658
evan@chromium.org36699862010-02-02 11:28:16 +0900659 int bytes_written = WriteFileDescriptor(fd, data, size);
660 if (int ret = HANDLE_EINTR(close(fd)) < 0)
661 return ret;
662 return bytes_written;
estade@chromium.org557da512009-09-16 09:29:22 +0900663}
664
665int WriteFileDescriptor(const int fd, const char* data, int size) {
666 // Allow for partial writes.
667 ssize_t bytes_written_total = 0;
668 for (ssize_t bytes_written_partial = 0; bytes_written_total < size;
669 bytes_written_total += bytes_written_partial) {
670 bytes_written_partial =
671 HANDLE_EINTR(write(fd, data + bytes_written_total,
672 size - bytes_written_total));
673 if (bytes_written_partial < 0)
674 return -1;
675 }
676
mark@chromium.org8ca0d272008-09-12 02:36:23 +0900677 return bytes_written_total;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900678}
679
loislo@chromium.orgeae0dcb2012-04-29 21:57:10 +0900680int AppendToFile(const FilePath& filename, const char* data, int size) {
681 base::ThreadRestrictions::AssertIOAllowed();
682 int fd = HANDLE_EINTR(open(filename.value().c_str(), O_WRONLY | O_APPEND));
683 if (fd < 0)
684 return -1;
685
686 int bytes_written = WriteFileDescriptor(fd, data, size);
687 if (int ret = HANDLE_EINTR(close(fd)) < 0)
688 return ret;
689 return bytes_written;
690}
691
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900692// Gets the current working directory for the process.
evanm@google.com874d1672008-10-31 08:54:04 +0900693bool GetCurrentDirectory(FilePath* dir) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900694 // getcwd can return ENOENT, which implies it checks against the disk.
695 base::ThreadRestrictions::AssertIOAllowed();
696
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900697 char system_buffer[PATH_MAX] = "";
evanm@google.com874d1672008-10-31 08:54:04 +0900698 if (!getcwd(system_buffer, sizeof(system_buffer))) {
699 NOTREACHED();
700 return false;
701 }
702 *dir = FilePath(system_buffer);
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900703 return true;
704}
705
706// Sets the current working directory for the process.
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900707bool SetCurrentDirectory(const FilePath& path) {
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900708 base::ThreadRestrictions::AssertIOAllowed();
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900709 int ret = chdir(path.value().c_str());
710 return !ret;
mmentovai@google.comaa13be62008-09-03 03:20:34 +0900711}
estade@chromium.orgb1d358a2008-11-18 06:01:19 +0900712
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900713bool NormalizeFilePath(const FilePath& path, FilePath* normalized_path) {
714 FilePath real_path_result;
715 if (!RealPath(path, &real_path_result))
skerner@chromium.org559baa92010-05-13 00:13:57 +0900716 return false;
717
skerner@chromium.org8bbe5be2010-06-10 07:56:48 +0900718 // To be consistant with windows, fail if |real_path_result| is a
719 // directory.
720 stat_wrapper_t file_info;
721 if (CallStat(real_path_result.value().c_str(), &file_info) != 0 ||
722 S_ISDIR(file_info.st_mode))
723 return false;
724
725 *normalized_path = real_path_result;
skerner@chromium.org559baa92010-05-13 00:13:57 +0900726 return true;
727}
728
evan@chromium.orgb9575332010-04-22 06:11:36 +0900729#if !defined(OS_MACOSX)
730bool GetTempDir(FilePath* path) {
731 const char* tmp = getenv("TMPDIR");
732 if (tmp)
733 *path = FilePath(tmp);
734 else
michaelbai@google.com2251c622011-06-22 07:34:50 +0900735#if defined(OS_ANDROID)
nileshagrawal@chromium.org62001b92012-05-18 05:09:06 +0900736 return PathService::Get(base::DIR_CACHE, path);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900737#else
evan@chromium.orgb9575332010-04-22 06:11:36 +0900738 *path = FilePath("/tmp");
michaelbai@google.com2251c622011-06-22 07:34:50 +0900739#endif
evan@chromium.orgb9575332010-04-22 06:11:36 +0900740 return true;
741}
742
michaelbai@google.com2251c622011-06-22 07:34:50 +0900743#if !defined(OS_ANDROID)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900744
robert.nagy@gmail.comea54e462011-10-25 07:05:27 +0900745#if defined(OS_LINUX)
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900746// Determine if /dev/shm files can be mapped and then mprotect'd PROT_EXEC.
747// This depends on the mount options used for /dev/shm, which vary among
748// different Linux distributions and possibly local configuration. It also
749// depends on details of kernel--ChromeOS uses the noexec option for /dev/shm
750// but its kernel allows mprotect with PROT_EXEC anyway.
751
752namespace {
753
754bool DetermineDevShmExecutable() {
755 bool result = false;
756 FilePath path;
757 int fd = CreateAndOpenFdForTemporaryFile(FilePath("/dev/shm"), &path);
758 if (fd >= 0) {
759 ScopedFD shm_fd_closer(&fd);
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900760 DeleteFile(path, false);
scr@chromium.orge7506992011-12-23 07:31:44 +0900761 long sysconf_result = sysconf(_SC_PAGESIZE);
762 CHECK_GE(sysconf_result, 0);
763 size_t pagesize = static_cast<size_t>(sysconf_result);
764 CHECK_GE(sizeof(pagesize), sizeof(sysconf_result));
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900765 void *mapping = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, 0);
766 if (mapping != MAP_FAILED) {
767 if (mprotect(mapping, pagesize, PROT_READ | PROT_EXEC) == 0)
768 result = true;
769 munmap(mapping, pagesize);
770 }
771 }
772 return result;
evan@chromium.orgb9575332010-04-22 06:11:36 +0900773}
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900774
775}; // namespace
776#endif // defined(OS_LINUX)
777
778bool GetShmemTempDir(FilePath* path, bool executable) {
779#if defined(OS_LINUX)
780 bool use_dev_shm = true;
781 if (executable) {
782 static const bool s_dev_shm_executable = DetermineDevShmExecutable();
783 use_dev_shm = s_dev_shm_executable;
784 }
785 if (use_dev_shm) {
786 *path = FilePath("/dev/shm");
787 return true;
788 }
michaelbai@google.com2251c622011-06-22 07:34:50 +0900789#endif
mcgrathr@chromium.org569a4232011-12-07 03:07:05 +0900790 return GetTempDir(path);
791}
792#endif // !defined(OS_ANDROID)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900793
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900794FilePath GetHomeDir() {
haruki@chromium.org712ff262012-08-06 18:14:44 +0900795#if defined(OS_CHROMEOS)
stevenjb@chromium.org861313b2013-09-28 04:28:24 +0900796 if (base::SysInfo::IsRunningOnChromeOS())
haruki@chromium.org712ff262012-08-06 18:14:44 +0900797 return FilePath("/home/chronos/user");
798#endif
799
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900800 const char* home_dir = getenv("HOME");
801 if (home_dir && home_dir[0])
802 return FilePath(home_dir);
803
michaelbai@google.com2251c622011-06-22 07:34:50 +0900804#if defined(OS_ANDROID)
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900805 DLOG(WARNING) << "OS_ANDROID: Home directory lookup not yet implemented.";
spang@chromium.org8d0fa9a2013-11-20 14:33:46 +0900806#elif defined(USE_GLIB) && !defined(OS_CHROMEOS)
evan@chromium.org7c9cd8b2010-10-23 14:19:20 +0900807 // g_get_home_dir calls getpwent, which can fall through to LDAP calls.
808 base::ThreadRestrictions::AssertIOAllowed();
809
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900810 home_dir = g_get_home_dir();
811 if (home_dir && home_dir[0])
812 return FilePath(home_dir);
michaelbai@google.com2251c622011-06-22 07:34:50 +0900813#endif
evan@chromium.org73aec0e2010-04-23 08:28:05 +0900814
815 FilePath rv;
816 if (file_util::GetTempDir(&rv))
817 return rv;
818
819 // Last resort.
820 return FilePath("/tmp");
821}
thorogood@chromium.orge77009d2012-07-23 17:22:44 +0900822#endif // !defined(OS_MACOSX)
evan@chromium.orgb9575332010-04-22 06:11:36 +0900823
skerner@google.com93449ef2011-09-22 23:47:18 +0900824bool VerifyPathControlledByUser(const FilePath& base,
825 const FilePath& path,
826 uid_t owner_uid,
skerner@chromium.org80784142011-10-18 06:30:29 +0900827 const std::set<gid_t>& group_gids) {
skerner@google.com93449ef2011-09-22 23:47:18 +0900828 if (base != path && !base.IsParent(path)) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900829 DLOG(ERROR) << "|base| must be a subdirectory of |path|. base = \""
830 << base.value() << "\", path = \"" << path.value() << "\"";
skerner@google.com93449ef2011-09-22 23:47:18 +0900831 return false;
832 }
833
834 std::vector<FilePath::StringType> base_components;
835 std::vector<FilePath::StringType> path_components;
836
837 base.GetComponents(&base_components);
838 path.GetComponents(&path_components);
839
840 std::vector<FilePath::StringType>::const_iterator ib, ip;
841 for (ib = base_components.begin(), ip = path_components.begin();
842 ib != base_components.end(); ++ib, ++ip) {
843 // |base| must be a subpath of |path|, so all components should match.
844 // If these CHECKs fail, look at the test that base is a parent of
845 // path at the top of this function.
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900846 DCHECK(ip != path_components.end());
847 DCHECK(*ip == *ib);
skerner@google.com93449ef2011-09-22 23:47:18 +0900848 }
849
850 FilePath current_path = base;
skerner@chromium.org80784142011-10-18 06:30:29 +0900851 if (!VerifySpecificPathControlledByUser(current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900852 return false;
853
854 for (; ip != path_components.end(); ++ip) {
855 current_path = current_path.Append(*ip);
skerner@chromium.org80784142011-10-18 06:30:29 +0900856 if (!VerifySpecificPathControlledByUser(
857 current_path, owner_uid, group_gids))
skerner@google.com93449ef2011-09-22 23:47:18 +0900858 return false;
859 }
860 return true;
861}
862
qsr@chromium.org4ab5de92012-07-09 23:40:39 +0900863#if defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900864bool VerifyPathControlledByAdmin(const FilePath& path) {
865 const unsigned kRootUid = 0;
866 const FilePath kFileSystemRoot("/");
867
868 // The name of the administrator group on mac os.
skerner@chromium.org80784142011-10-18 06:30:29 +0900869 const char* const kAdminGroupNames[] = {
870 "admin",
871 "wheel"
872 };
skerner@google.com93449ef2011-09-22 23:47:18 +0900873
874 // Reading the groups database may touch the file system.
875 base::ThreadRestrictions::AssertIOAllowed();
876
skerner@chromium.org80784142011-10-18 06:30:29 +0900877 std::set<gid_t> allowed_group_ids;
878 for (int i = 0, ie = arraysize(kAdminGroupNames); i < ie; ++i) {
879 struct group *group_record = getgrnam(kAdminGroupNames[i]);
880 if (!group_record) {
brettw@chromium.org5faed3c2011-10-27 06:48:00 +0900881 DPLOG(ERROR) << "Could not get the group ID of group \""
882 << kAdminGroupNames[i] << "\".";
skerner@chromium.org80784142011-10-18 06:30:29 +0900883 continue;
884 }
885
886 allowed_group_ids.insert(group_record->gr_gid);
skerner@google.com93449ef2011-09-22 23:47:18 +0900887 }
888
889 return VerifyPathControlledByUser(
skerner@chromium.org80784142011-10-18 06:30:29 +0900890 kFileSystemRoot, path, kRootUid, allowed_group_ids);
skerner@google.com93449ef2011-09-22 23:47:18 +0900891}
stuartmorgan@chromium.org925e0b72012-07-24 20:23:32 +0900892#endif // defined(OS_MACOSX) && !defined(OS_IOS)
skerner@google.com93449ef2011-09-22 23:47:18 +0900893
kinaba@chromium.orgbbe80ba2013-02-21 12:24:08 +0900894int GetMaximumPathComponentLength(const FilePath& path) {
895 base::ThreadRestrictions::AssertIOAllowed();
896 return pathconf(path.value().c_str(), _PC_NAME_MAX);
897}
898
thestig@chromium.org7ecbbc12010-11-20 12:38:15 +0900899} // namespace file_util
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900900
901namespace base {
902namespace internal {
903
904bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) {
905 ThreadRestrictions::AssertIOAllowed();
906 // Windows compatibility: if to_path exists, from_path and to_path
907 // must be the same type, either both files, or both directories.
908 stat_wrapper_t to_file_info;
909 if (CallStat(to_path.value().c_str(), &to_file_info) == 0) {
910 stat_wrapper_t from_file_info;
911 if (CallStat(from_path.value().c_str(), &from_file_info) == 0) {
912 if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode))
913 return false;
914 } else {
915 return false;
916 }
917 }
918
919 if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0)
920 return true;
921
922 if (!CopyDirectory(from_path, to_path, true))
923 return false;
924
brettw@chromium.org220b8de2013-07-17 04:10:23 +0900925 DeleteFile(from_path, true);
brettw@chromium.orgaecf7a32013-07-10 02:42:26 +0900926 return true;
927}
928
929#if !defined(OS_MACOSX)
930// Mac has its own implementation, this is for all other Posix systems.
931bool CopyFileUnsafe(const FilePath& from_path, const FilePath& to_path) {
932 ThreadRestrictions::AssertIOAllowed();
933 int infile = HANDLE_EINTR(open(from_path.value().c_str(), O_RDONLY));
934 if (infile < 0)
935 return false;
936
937 int outfile = HANDLE_EINTR(creat(to_path.value().c_str(), 0666));
938 if (outfile < 0) {
939 ignore_result(HANDLE_EINTR(close(infile)));
940 return false;
941 }
942
943 const size_t kBufferSize = 32768;
944 std::vector<char> buffer(kBufferSize);
945 bool result = true;
946
947 while (result) {
948 ssize_t bytes_read = HANDLE_EINTR(read(infile, &buffer[0], buffer.size()));
949 if (bytes_read < 0) {
950 result = false;
951 break;
952 }
953 if (bytes_read == 0)
954 break;
955 // Allow for partial writes
956 ssize_t bytes_written_per_read = 0;
957 do {
958 ssize_t bytes_written_partial = HANDLE_EINTR(write(
959 outfile,
960 &buffer[bytes_written_per_read],
961 bytes_read - bytes_written_per_read));
962 if (bytes_written_partial < 0) {
963 result = false;
964 break;
965 }
966 bytes_written_per_read += bytes_written_partial;
967 } while (bytes_written_per_read < bytes_read);
968 }
969
970 if (HANDLE_EINTR(close(infile)) < 0)
971 result = false;
972 if (HANDLE_EINTR(close(outfile)) < 0)
973 result = false;
974
975 return result;
976}
977#endif // !defined(OS_MACOSX)
978
979} // namespace internal
980} // namespace base